@pix3/cli 1.6.4 → 2.0.0-alpha.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.
Files changed (168) hide show
  1. package/LICENSE +201 -201
  2. package/README.md +722 -788
  3. package/dist/index.js +557 -421
  4. package/dist/runtime-types.json +1 -1
  5. package/dist/smoke/prebuilt/{build-7MIXIMSZ.mjs → build-7REMSA2S.mjs} +52 -52
  6. package/dist/smoke/prebuilt/chunk-4DGG2BKR.mjs +2 -0
  7. package/dist/smoke/prebuilt/chunk-YLBMUJ2H.mjs +238 -0
  8. package/dist/smoke/prebuilt/runtime.mjs +1 -1
  9. package/dist/smoke/prebuilt/smoke-worker.mjs +211 -2
  10. package/dist/smoke/prebuilt/tree-defaults.mjs +1 -1
  11. package/dist/validate/prebuilt/{build-AUGKXER3.js → build-ADF5EEE2.js} +52 -52
  12. package/dist/validate/prebuilt/bundle-main.js +223 -18
  13. package/dist/validate/prebuilt/chunk-VIHIF4G2.js +238 -0
  14. package/dist/validate/prebuilt/runtime.js +1 -1
  15. package/kit/files/.claude/skills/pix3-editor/SKILL.md +200 -0
  16. package/kit/files/.claude/skills/pix3-nodes/SKILL.md +13 -15
  17. package/kit/files/.claude/skills/pix3-nodes/reference.md +77 -71
  18. package/kit/files/.claude/skills/pix3-scene-format/SKILL.md +38 -41
  19. package/kit/files/.claude/skills/pix3-scene-format/pix3anim.md +185 -0
  20. package/kit/files/.claude/skills/pix3-scene-format/project-files.md +244 -0
  21. package/kit/files/.claude/skills/pix3-scene-format/reference.md +28 -16
  22. package/kit/files/.claude/skills/pix3-scripts/SKILL.md +34 -24
  23. package/kit/files/.claude/skills/pix3-scripts/reference.md +68 -141
  24. package/kit/files/.claude/skills/pix3-verify/SKILL.md +65 -326
  25. package/kit/files/.claude/skills/pix3-verify/reference.md +2 -14
  26. package/kit/files/AGENTS.md +76 -84
  27. package/kit/files/design/tests/bots/pix3-test-bot.d.ts +89 -0
  28. package/kit/kit.json +8 -5
  29. package/package.json +62 -54
  30. package/templates/2d/files/scenes/main.pix3scene +31 -0
  31. package/templates/2d/template.yaml +11 -0
  32. package/templates/3d/files/scenes/main.pix3scene +50 -0
  33. package/templates/3d/template.yaml +11 -0
  34. package/templates/base/files/README.md +39 -0
  35. package/templates/base/files/gitignore +11 -0
  36. package/templates/base/files/index.html +23 -0
  37. package/templates/base/files/package.json +28 -0
  38. package/templates/base/files/src/main.ts +3 -0
  39. package/templates/base/files/tsconfig.json +17 -0
  40. package/templates/base/files/vite.config.ts +10 -0
  41. package/dist/smoke/prebuilt/chunk-CBFYKDS7.mjs +0 -2
  42. package/dist/smoke/prebuilt/chunk-VJHJ5BCO.mjs +0 -239
  43. package/dist/validate/prebuilt/chunk-CFQFEI52.js +0 -239
  44. package/templates/empty-2d/files/README.md +0 -20
  45. package/templates/empty-2d/files/scenes/main.pix3scene +0 -68
  46. package/templates/empty-2d/files/sprites/pix3-logo.png +0 -0
  47. package/templates/empty-2d/template.yaml +0 -7
  48. package/templates/empty-3d/files/README.md +0 -20
  49. package/templates/empty-3d/files/scenes/main.pix3scene +0 -108
  50. package/templates/empty-3d/files/sprites/pix3-logo.png +0 -0
  51. package/templates/empty-3d/template.yaml +0 -7
  52. package/templates/idea-blank/files/README.md +0 -22
  53. package/templates/idea-blank/files/scenes/main.pix3scene +0 -37
  54. package/templates/idea-blank/template.yaml +0 -10
  55. package/templates/minigame-2d/files/README.md +0 -44
  56. package/templates/minigame-2d/files/design/tests/reachability.json +0 -1
  57. package/templates/minigame-2d/files/design/tests/routines/mute-music.json +0 -44
  58. package/templates/minigame-2d/files/scenes/main.pix3scene +0 -84
  59. package/templates/minigame-2d/files/scenes/menu.pix3scene +0 -118
  60. package/templates/minigame-2d/files/scenes/ui/settings-window.pix3scene +0 -138
  61. package/templates/minigame-2d/files/scripts/GameFlow.ts +0 -133
  62. package/templates/minigame-2d/files/scripts/MenuFlow.ts +0 -217
  63. package/templates/minigame-2d/files/scripts/SettingsWindow.ts +0 -198
  64. package/templates/minigame-2d/template.yaml +0 -10
  65. package/templates/playable-2d/files/README.md +0 -30
  66. package/templates/playable-2d/files/design/recipe.md +0 -83
  67. package/templates/playable-2d/files/design/tests/reachability.json +0 -4
  68. package/templates/playable-2d/files/design/tests/routines/intro-to-cta.json +0 -32
  69. package/templates/playable-2d/files/scenes/main.pix3scene +0 -111
  70. package/templates/playable-2d/files/scenes/ui/end-screen.pix3scene +0 -91
  71. package/templates/playable-2d/files/scenes/ui/intro.pix3scene +0 -65
  72. package/templates/playable-2d/files/scripts/CtaButton.ts +0 -55
  73. package/templates/playable-2d/files/scripts/GameFlow.ts +0 -256
  74. package/templates/playable-2d/files/sprites/pix3-logo.png +0 -0
  75. package/templates/playable-2d/template.yaml +0 -9
  76. package/templates/playable-3d/files/README.md +0 -32
  77. package/templates/playable-3d/files/design/recipe.md +0 -127
  78. package/templates/playable-3d/files/design/tests/reachability.json +0 -4
  79. package/templates/playable-3d/files/design/tests/routines/intro-to-cta.json +0 -32
  80. package/templates/playable-3d/files/scenes/main.pix3scene +0 -230
  81. package/templates/playable-3d/files/scenes/ui/end-screen.pix3scene +0 -91
  82. package/templates/playable-3d/files/scenes/ui/intro.pix3scene +0 -65
  83. package/templates/playable-3d/files/scripts/CtaButton.ts +0 -55
  84. package/templates/playable-3d/files/scripts/GameFlow.ts +0 -309
  85. package/templates/playable-3d/files/scripts/GameRules.ts +0 -290
  86. package/templates/playable-3d/files/scripts/ScoreHud.ts +0 -113
  87. package/templates/playable-3d/template.yaml +0 -9
  88. package/templates/recipe-arena-2d/files/README.md +0 -48
  89. package/templates/recipe-arena-2d/files/design/recipe.md +0 -127
  90. package/templates/recipe-arena-2d/files/design/tests/reachability.json +0 -4
  91. package/templates/recipe-arena-2d/files/design/tests/routines/terminal-retry.json +0 -23
  92. package/templates/recipe-arena-2d/files/scenes/main.pix3scene +0 -292
  93. package/templates/recipe-arena-2d/files/scenes/menu.pix3scene +0 -100
  94. package/templates/recipe-arena-2d/files/scenes/prefabs/hazard.pix3scene +0 -42
  95. package/templates/recipe-arena-2d/files/scenes/prefabs/pickup.pix3scene +0 -45
  96. package/templates/recipe-arena-2d/files/scenes/ui/result.pix3scene +0 -85
  97. package/templates/recipe-arena-2d/files/scripts/GameRules.ts +0 -368
  98. package/templates/recipe-arena-2d/files/scripts/MenuFlow.ts +0 -106
  99. package/templates/recipe-arena-2d/files/scripts/PlayerController.ts +0 -151
  100. package/templates/recipe-arena-2d/files/scripts/ScoreHud.ts +0 -94
  101. package/templates/recipe-arena-2d/files/scripts/Spawner.ts +0 -214
  102. package/templates/recipe-arena-2d/files/scripts/TouchRules.ts +0 -174
  103. package/templates/recipe-arena-2d/files/sprites/ph-avatar.png +0 -0
  104. package/templates/recipe-arena-2d/files/sprites/ph-hazard.png +0 -0
  105. package/templates/recipe-arena-2d/files/sprites/ph-pickup.png +0 -0
  106. package/templates/recipe-arena-2d/template.yaml +0 -10
  107. package/templates/recipe-blank-2d/files/README.md +0 -61
  108. package/templates/recipe-blank-2d/files/design/recipe.md +0 -148
  109. package/templates/recipe-blank-2d/files/design/tests/reachability.json +0 -4
  110. package/templates/recipe-blank-2d/files/design/tests/routines/restart.json +0 -27
  111. package/templates/recipe-blank-2d/files/design/tests/routines/terminal-retry.json +0 -23
  112. package/templates/recipe-blank-2d/files/scenes/main.pix3scene +0 -224
  113. package/templates/recipe-blank-2d/files/scenes/ui/result.pix3scene +0 -85
  114. package/templates/recipe-blank-2d/files/scripts/GameRules.ts +0 -350
  115. package/templates/recipe-blank-2d/files/scripts/ScoreHud.ts +0 -110
  116. package/templates/recipe-blank-2d/files/sprites/ph-bg.png +0 -0
  117. package/templates/recipe-blank-2d/files/sprites/ph-capsule.png +0 -0
  118. package/templates/recipe-blank-2d/files/sprites/ph-circle.png +0 -0
  119. package/templates/recipe-blank-2d/files/sprites/ph-orb.png +0 -0
  120. package/templates/recipe-blank-2d/files/sprites/ph-ring.png +0 -0
  121. package/templates/recipe-blank-2d/files/sprites/ph-star.png +0 -0
  122. package/templates/recipe-blank-2d/template.yaml +0 -10
  123. package/templates/recipe-bouncer-2d/files/README.md +0 -81
  124. package/templates/recipe-bouncer-2d/files/design/recipe.md +0 -146
  125. package/templates/recipe-bouncer-2d/files/design/tests/reachability.json +0 -4
  126. package/templates/recipe-bouncer-2d/files/design/tests/routines/terminal-retry.json +0 -23
  127. package/templates/recipe-bouncer-2d/files/scenes/main.pix3scene +0 -615
  128. package/templates/recipe-bouncer-2d/files/scenes/menu.pix3scene +0 -191
  129. package/templates/recipe-bouncer-2d/files/scenes/ui/result.pix3scene +0 -87
  130. package/templates/recipe-bouncer-2d/files/scripts/BallBody.ts +0 -298
  131. package/templates/recipe-bouncer-2d/files/scripts/GameRules.ts +0 -377
  132. package/templates/recipe-bouncer-2d/files/scripts/MenuFlow.ts +0 -109
  133. package/templates/recipe-bouncer-2d/files/scripts/PaddleController.ts +0 -112
  134. package/templates/recipe-bouncer-2d/files/scripts/ScoreHud.ts +0 -94
  135. package/templates/recipe-bouncer-2d/files/scripts/TouchRules.ts +0 -263
  136. package/templates/recipe-bouncer-2d/files/scripts/ball-collision.ts +0 -307
  137. package/templates/recipe-bouncer-2d/files/sprites/ph-ball.png +0 -0
  138. package/templates/recipe-bouncer-2d/files/sprites/ph-bg.png +0 -0
  139. package/templates/recipe-bouncer-2d/files/sprites/ph-bumper.png +0 -0
  140. package/templates/recipe-bouncer-2d/files/sprites/ph-paddle.png +0 -0
  141. package/templates/recipe-bouncer-2d/template.yaml +0 -10
  142. package/templates/recipe-grid-3d/files/README.md +0 -22
  143. package/templates/recipe-grid-3d/files/design/recipe.md +0 -110
  144. package/templates/recipe-grid-3d/files/scenes/main.pix3scene +0 -169
  145. package/templates/recipe-grid-3d/files/scenes/menu.pix3scene +0 -100
  146. package/templates/recipe-grid-3d/files/scenes/ui/result.pix3scene +0 -105
  147. package/templates/recipe-grid-3d/files/scripts/GridBoard.ts +0 -319
  148. package/templates/recipe-grid-3d/files/scripts/GridRules.ts +0 -278
  149. package/templates/recipe-grid-3d/files/scripts/MenuFlow.ts +0 -106
  150. package/templates/recipe-grid-3d/files/scripts/ScoreHud.ts +0 -94
  151. package/templates/recipe-grid-3d/template.yaml +0 -10
  152. package/templates/recipe-tapper-2d/files/README.md +0 -39
  153. package/templates/recipe-tapper-2d/files/design/recipe.md +0 -132
  154. package/templates/recipe-tapper-2d/files/design/tests/reachability.json +0 -4
  155. package/templates/recipe-tapper-2d/files/design/tests/routines/terminal-retry.json +0 -23
  156. package/templates/recipe-tapper-2d/files/scenes/main.pix3scene +0 -269
  157. package/templates/recipe-tapper-2d/files/scenes/menu.pix3scene +0 -100
  158. package/templates/recipe-tapper-2d/files/scenes/prefabs/hazard.pix3scene +0 -42
  159. package/templates/recipe-tapper-2d/files/scenes/prefabs/target.pix3scene +0 -45
  160. package/templates/recipe-tapper-2d/files/scenes/ui/result.pix3scene +0 -85
  161. package/templates/recipe-tapper-2d/files/scripts/GameRules.ts +0 -368
  162. package/templates/recipe-tapper-2d/files/scripts/MenuFlow.ts +0 -106
  163. package/templates/recipe-tapper-2d/files/scripts/ScoreHud.ts +0 -94
  164. package/templates/recipe-tapper-2d/files/scripts/Spawner.ts +0 -214
  165. package/templates/recipe-tapper-2d/files/scripts/TouchRules.ts +0 -192
  166. package/templates/recipe-tapper-2d/files/sprites/ph-hazard.png +0 -0
  167. package/templates/recipe-tapper-2d/files/sprites/ph-target.png +0 -0
  168. package/templates/recipe-tapper-2d/template.yaml +0 -10
@@ -0,0 +1,238 @@
1
+ import { createRequire as __pix3CreateRequire } from 'node:module'; const require = __pix3CreateRequire(import.meta.url);
2
+ import{$f as Mm,Aa as Qi,Ad as Fr,Ae as It,Ba as sm,Bd as Zi,Bf as Tm,Bg as Nm,Da as Hl,Dd as L,Ee as rr,Eg as ss,Gd as er,Ge as Kl,He as wm,Id as dm,Ie as xm,Jf as Xl,Kd as ut,Kg as Im,Lb as lm,Lc as oe,Lf as ts,Lg as Rm,Ma as am,Mb as cm,Nf as is,Ob as um,Of as Ql,Pb as ql,Pd as Qo,Rd as pm,Sf as Cm,Td as Q,Tf as Jl,Ud as mm,Vd as ae,Wd as $l,Xb as hm,Xd as Yl,Yb as Xo,Yd as Jo,Zb as _r,Zf as nr,a as Yo,b as M,be as B,bg as ge,c as Ew,ce as O,cg as rs,d as Qp,de as fm,df as z,dg as ns,ee as gm,eg as de,fc as Pe,fg as os,gc as Ge,ge as ym,gf as es,gg as Dm,hd as R,he as je,id as N,ie as tr,if as Pm,jd as F,je as zr,kd as S,lg as or,lh as Bm,m as Jp,md as Gl,ne as Nt,oe as bm,of as km,p as Zp,pd as jl,pe as ir,pg as Em,qe as Zo,qf as hi,r as xe,re as Sm,rf as Ve,sa as Ko,se as vm,t as lt,ta as im,u as ct,ua as rm,v as em,va as Lr,vf as Am,w as tm,wa as nm,xd as se,ya as om,yd as Ji}from"./chunk-6ACT6FNV.js";var G=M(ue=>{"use strict";var Uu=Symbol.for("yaml.alias"),cg=Symbol.for("yaml.document"),Gs=Symbol.for("yaml.map"),ug=Symbol.for("yaml.pair"),Wu=Symbol.for("yaml.scalar"),js=Symbol.for("yaml.seq"),kt=Symbol.for("yaml.node.type"),b0=n=>!!n&&typeof n=="object"&&n[kt]===Uu,S0=n=>!!n&&typeof n=="object"&&n[kt]===cg,v0=n=>!!n&&typeof n=="object"&&n[kt]===Gs,w0=n=>!!n&&typeof n=="object"&&n[kt]===ug,hg=n=>!!n&&typeof n=="object"&&n[kt]===Wu,x0=n=>!!n&&typeof n=="object"&&n[kt]===js;function dg(n){if(n&&typeof n=="object")switch(n[kt]){case Gs:case js:return!0}return!1}function P0(n){if(n&&typeof n=="object")switch(n[kt]){case Uu:case Gs:case Wu:case js:return!0}return!1}var k0=n=>(hg(n)||dg(n))&&!!n.anchor;ue.ALIAS=Uu;ue.DOC=cg;ue.MAP=Gs;ue.NODE_TYPE=kt;ue.PAIR=ug;ue.SCALAR=Wu;ue.SEQ=js;ue.hasAnchor=k0;ue.isAlias=b0;ue.isCollection=dg;ue.isDocument=S0;ue.isMap=v0;ue.isNode=P0;ue.isPair=w0;ue.isScalar=hg;ue.isSeq=x0});var gn=M(Hu=>{"use strict";var ce=G(),be=Symbol("break visit"),pg=Symbol("skip children"),rt=Symbol("remove node");function $s(n,e){let t=mg(e);ce.isDocument(n)?yr(null,n.contents,t,Object.freeze([n]))===rt&&(n.contents=null):yr(null,n,t,Object.freeze([]))}$s.BREAK=be;$s.SKIP=pg;$s.REMOVE=rt;function yr(n,e,t,i){let r=fg(n,e,t,i);if(ce.isNode(r)||ce.isPair(r))return gg(n,i,r),yr(n,r,t,i);if(typeof r!="symbol"){if(ce.isCollection(e)){i=Object.freeze(i.concat(e));for(let o=0;o<e.items.length;++o){let s=yr(o,e.items[o],t,i);if(typeof s=="number")o=s-1;else{if(s===be)return be;s===rt&&(e.items.splice(o,1),o-=1)}}}else if(ce.isPair(e)){i=Object.freeze(i.concat(e));let o=yr("key",e.key,t,i);if(o===be)return be;o===rt&&(e.key=null);let s=yr("value",e.value,t,i);if(s===be)return be;s===rt&&(e.value=null)}}return r}async function Ys(n,e){let t=mg(e);ce.isDocument(n)?await br(null,n.contents,t,Object.freeze([n]))===rt&&(n.contents=null):await br(null,n,t,Object.freeze([]))}Ys.BREAK=be;Ys.SKIP=pg;Ys.REMOVE=rt;async function br(n,e,t,i){let r=await fg(n,e,t,i);if(ce.isNode(r)||ce.isPair(r))return gg(n,i,r),br(n,r,t,i);if(typeof r!="symbol"){if(ce.isCollection(e)){i=Object.freeze(i.concat(e));for(let o=0;o<e.items.length;++o){let s=await br(o,e.items[o],t,i);if(typeof s=="number")o=s-1;else{if(s===be)return be;s===rt&&(e.items.splice(o,1),o-=1)}}}else if(ce.isPair(e)){i=Object.freeze(i.concat(e));let o=await br("key",e.key,t,i);if(o===be)return be;o===rt&&(e.key=null);let s=await br("value",e.value,t,i);if(s===be)return be;s===rt&&(e.value=null)}}return r}function mg(n){return typeof n=="object"&&(n.Collection||n.Node||n.Value)?Object.assign({Alias:n.Node,Map:n.Node,Scalar:n.Node,Seq:n.Node},n.Value&&{Map:n.Value,Scalar:n.Value,Seq:n.Value},n.Collection&&{Map:n.Collection,Seq:n.Collection},n):n}function fg(n,e,t,i){if(typeof t=="function")return t(n,e,i);if(ce.isMap(e))return t.Map?.(n,e,i);if(ce.isSeq(e))return t.Seq?.(n,e,i);if(ce.isPair(e))return t.Pair?.(n,e,i);if(ce.isScalar(e))return t.Scalar?.(n,e,i);if(ce.isAlias(e))return t.Alias?.(n,e,i)}function gg(n,e,t){let i=e[e.length-1];if(ce.isCollection(i))i.items[n]=t;else if(ce.isPair(i))n==="key"?i.key=t:i.value=t;else if(ce.isDocument(i))i.contents=t;else{let r=ce.isAlias(i)?"alias":"scalar";throw new Error(`Cannot replace node with ${r} parent`)}}Hu.visit=$s;Hu.visitAsync=Ys});var qu=M(bg=>{"use strict";var yg=G(),A0=gn(),T0={"!":"%21",",":"%2C","[":"%5B","]":"%5D","{":"%7B","}":"%7D"},C0=n=>n.replace(/[!,[\]{}]/g,e=>T0[e]),yn=class n{constructor(e,t){this.docStart=null,this.docEnd=!1,this.yaml=Object.assign({},n.defaultYaml,e),this.tags=Object.assign({},n.defaultTags,t)}clone(){let e=new n(this.yaml,this.tags);return e.docStart=this.docStart,e}atDocument(){let e=new n(this.yaml,this.tags);switch(this.yaml.version){case"1.1":this.atNextDocument=!0;break;case"1.2":this.atNextDocument=!1,this.yaml={explicit:n.defaultYaml.explicit,version:"1.2"},this.tags=Object.assign({},n.defaultTags);break}return e}add(e,t){this.atNextDocument&&(this.yaml={explicit:n.defaultYaml.explicit,version:"1.1"},this.tags=Object.assign({},n.defaultTags),this.atNextDocument=!1);let i=e.trim().split(/[ \t]+/),r=i.shift();switch(r){case"%TAG":{if(i.length!==2&&(t(0,"%TAG directive should contain exactly two parts"),i.length<2))return!1;let[o,s]=i;return this.tags[o]=s,!0}case"%YAML":{if(this.yaml.explicit=!0,i.length!==1)return t(0,"%YAML directive should contain exactly one part"),!1;let[o]=i;if(o==="1.1"||o==="1.2")return this.yaml.version=o,!0;{let s=/^\d+\.\d+$/.test(o);return t(6,`Unsupported YAML version ${o}`,s),!1}}default:return t(0,`Unknown directive ${r}`,!0),!1}}tagName(e,t){if(e==="!")return"!";if(e[0]!=="!")return t(`Not a valid tag: ${e}`),null;if(e[1]==="<"){let s=e.slice(2,-1);return s==="!"||s==="!!"?(t(`Verbatim tags aren't resolved, so ${e} is invalid.`),null):(e[e.length-1]!==">"&&t("Verbatim tags must end with a >"),s)}let[,i,r]=e.match(/^(.*!)([^!]*)$/s);r||t(`The ${e} tag has no suffix`);let o=this.tags[i];if(o)try{return o+decodeURIComponent(r)}catch(s){return t(String(s)),null}return i==="!"?e:(t(`Could not resolve tag: ${e}`),null)}tagString(e){for(let[t,i]of Object.entries(this.tags))if(e.startsWith(i))return t+C0(e.substring(i.length));return e[0]==="!"?e:`!<${e}>`}toString(e){let t=this.yaml.explicit?[`%YAML ${this.yaml.version||"1.2"}`]:[],i=Object.entries(this.tags),r;if(e&&i.length>0&&yg.isNode(e.contents)){let o={};A0.visit(e.contents,(s,a)=>{yg.isNode(a)&&a.tag&&(o[a.tag]=!0)}),r=Object.keys(o)}else r=[];for(let[o,s]of i)o==="!!"&&s==="tag:yaml.org,2002:"||(!e||r.some(a=>a.startsWith(s)))&&t.push(`%TAG ${o} ${s}`);return t.join(`
3
+ `)}};yn.defaultYaml={explicit:!1,version:"1.2"};yn.defaultTags={"!!":"tag:yaml.org,2002:"};bg.Directives=yn});var Ks=M(bn=>{"use strict";var Sg=G(),M0=gn();function D0(n){if(/[\x00-\x19\s,[\]{}]/.test(n)){let t=`Anchor must not contain whitespace or control characters: ${JSON.stringify(n)}`;throw new Error(t)}return!0}function vg(n){let e=new Set;return M0.visit(n,{Value(t,i){i.anchor&&e.add(i.anchor)}}),e}function wg(n,e){for(let t=1;;++t){let i=`${n}${t}`;if(!e.has(i))return i}}function E0(n,e){let t=[],i=new Map,r=null;return{onAnchor:o=>{t.push(o),r??(r=vg(n));let s=wg(e,r);return r.add(s),s},setAnchors:()=>{for(let o of t){let s=i.get(o);if(typeof s=="object"&&s.anchor&&(Sg.isScalar(s.node)||Sg.isCollection(s.node)))s.node.anchor=s.anchor;else{let a=new Error("Failed to resolve repeated object (this should not happen)");throw a.source=o,a}}},sourceObjects:i}}bn.anchorIsValid=D0;bn.anchorNames=vg;bn.createNodeAnchors=E0;bn.findNewAnchor=wg});var Gu=M(xg=>{"use strict";function Sn(n,e,t,i){if(i&&typeof i=="object")if(Array.isArray(i))for(let r=0,o=i.length;r<o;++r){let s=i[r],a=Sn(n,i,String(r),s);a===void 0?delete i[r]:a!==s&&(i[r]=a)}else if(i instanceof Map)for(let r of Array.from(i.keys())){let o=i.get(r),s=Sn(n,i,r,o);s===void 0?i.delete(r):s!==o&&i.set(r,s)}else if(i instanceof Set)for(let r of Array.from(i)){let o=Sn(n,i,r,r);o===void 0?i.delete(r):o!==r&&(i.delete(r),i.add(o))}else for(let[r,o]of Object.entries(i)){let s=Sn(n,i,r,o);s===void 0?delete i[r]:s!==o&&(i[r]=s)}return n.call(e,t,i)}xg.applyReviver=Sn});var Gt=M(kg=>{"use strict";var N0=G();function Pg(n,e,t){if(Array.isArray(n))return n.map((i,r)=>Pg(i,String(r),t));if(n&&typeof n.toJSON=="function"){if(!t||!N0.hasAnchor(n))return n.toJSON(e,t);let i={aliasCount:0,count:1,res:void 0};t.anchors.set(n,i),t.onCreate=o=>{i.res=o,delete t.onCreate};let r=n.toJSON(e,t);return t.onCreate&&t.onCreate(r),r}return typeof n=="bigint"&&!t?.keep?Number(n):n}kg.toJS=Pg});var Xs=M(Tg=>{"use strict";var I0=Gu(),Ag=G(),R0=Gt(),ju=class{constructor(e){Object.defineProperty(this,Ag.NODE_TYPE,{value:e})}clone(){let e=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return this.range&&(e.range=this.range.slice()),e}toJS(e,{mapAsMap:t,maxAliasCount:i,onAnchor:r,reviver:o}={}){if(!Ag.isDocument(e))throw new TypeError("A document argument is required");let s={anchors:new Map,doc:e,keep:!0,mapAsMap:t===!0,mapKeyWarned:!1,maxAliasCount:typeof i=="number"?i:100},a=R0.toJS(this,"",s);if(typeof r=="function")for(let{count:l,res:c}of s.anchors.values())r(c,l);return typeof o=="function"?I0.applyReviver(o,{"":a},"",a):a}};Tg.NodeBase=ju});var vn=M(Cg=>{"use strict";var B0=Ks(),O0=gn(),Sr=G(),V0=Xs(),L0=Gt(),$u=class extends V0.NodeBase{constructor(e){super(Sr.ALIAS),this.source=e,Object.defineProperty(this,"tag",{set(){throw new Error("Alias nodes cannot have tags")}})}resolve(e,t){if(t?.maxAliasCount===0)throw new ReferenceError("Alias resolution is disabled");let i;t?.aliasResolveCache?i=t.aliasResolveCache:(i=[],O0.visit(e,{Node:(o,s)=>{(Sr.isAlias(s)||Sr.hasAnchor(s))&&i.push(s)}}),t&&(t.aliasResolveCache=i));let r;for(let o of i){if(o===this)break;o.anchor===this.source&&(r=o)}if(r&&t){let{anchors:o,doc:s,maxAliasCount:a}=t,l=o.get(r);if(l||(L0.toJS(r,null,t),l=o.get(r)),l?.res===void 0){let c="This should not happen: Alias anchor was not resolved?";throw new ReferenceError(c)}if(a>=0&&(l.count+=1,l.aliasCount===0&&(l.aliasCount=Qs(s,r,o)),l.count*l.aliasCount>a)){let c="Excessive alias count indicates a resource exhaustion attack";throw new ReferenceError(c)}}return r}toJSON(e,t){if(!t)return{source:this.source};let i=this.resolve(t.doc,t);if(!i){let r=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new ReferenceError(r)}return t.anchors.get(i).res}toString(e,t,i){let r=`*${this.source}`;if(e){if(B0.anchorIsValid(this.source),e.options.verifyAliasOrder&&!e.anchors.has(this.source)){let o=`Unresolved alias (the anchor must be set before the alias): ${this.source}`;throw new Error(o)}if(e.implicitKey)return`${r} `}return r}};function Qs(n,e,t){if(Sr.isAlias(e)){let i=e.resolve(n),r=t&&i&&t.get(i);return r?r.count*r.aliasCount:0}else if(Sr.isCollection(e)){let i=0;for(let r of e.items){let o=Qs(n,r,t);o>i&&(i=o)}return i}else if(Sr.isPair(e)){let i=Qs(n,e.key,t),r=Qs(n,e.value,t);return Math.max(i,r)}return 1}Cg.Alias=$u});var ne=M(Yu=>{"use strict";var _0=G(),F0=Xs(),z0=Gt(),U0=n=>!n||typeof n!="function"&&typeof n!="object",jt=class extends F0.NodeBase{constructor(e){super(_0.SCALAR),this.value=e}toJSON(e,t){return t?.keep?this.value:z0.toJS(this.value,e,t)}toString(){return String(this.value)}};jt.BLOCK_FOLDED="BLOCK_FOLDED";jt.BLOCK_LITERAL="BLOCK_LITERAL";jt.PLAIN="PLAIN";jt.QUOTE_DOUBLE="QUOTE_DOUBLE";jt.QUOTE_SINGLE="QUOTE_SINGLE";Yu.Scalar=jt;Yu.isScalarValue=U0});var wn=M(Dg=>{"use strict";var W0=vn(),Ii=G(),Mg=ne(),H0="tag:yaml.org,2002:";function q0(n,e,t){if(e){let i=t.filter(o=>o.tag===e),r=i.find(o=>!o.format)??i[0];if(!r)throw new Error(`Tag ${e} not found`);return r}return t.find(i=>i.identify?.(n)&&!i.format)}function G0(n,e,t){if(Ii.isDocument(n)&&(n=n.contents),Ii.isNode(n))return n;if(Ii.isPair(n)){let h=t.schema[Ii.MAP].createNode?.(t.schema,null,t);return h.items.push(n),h}(n instanceof String||n instanceof Number||n instanceof Boolean||typeof BigInt<"u"&&n instanceof BigInt)&&(n=n.valueOf());let{aliasDuplicateObjects:i,onAnchor:r,onTagObj:o,schema:s,sourceObjects:a}=t,l;if(i&&n&&typeof n=="object"){if(l=a.get(n),l)return l.anchor??(l.anchor=r(n)),new W0.Alias(l.anchor);l={anchor:null,node:null},a.set(n,l)}e?.startsWith("!!")&&(e=H0+e.slice(2));let c=q0(n,e,s.tags);if(!c){if(n&&typeof n.toJSON=="function"&&(n=n.toJSON()),!n||typeof n!="object"){let h=new Mg.Scalar(n);return l&&(l.node=h),h}c=n instanceof Map?s[Ii.MAP]:Symbol.iterator in Object(n)?s[Ii.SEQ]:s[Ii.MAP]}o&&(o(c),delete t.onTagObj);let u=c?.createNode?c.createNode(t.schema,n,t):typeof c?.nodeClass?.from=="function"?c.nodeClass.from(t.schema,n,t):new Mg.Scalar(n);return e?u.tag=e:c.default||(u.tag=c.tag),l&&(l.node=u),u}Dg.createNode=G0});var Zs=M(Js=>{"use strict";var j0=wn(),nt=G(),$0=Xs();function Ku(n,e,t){let i=t;for(let r=e.length-1;r>=0;--r){let o=e[r];if(typeof o=="number"&&Number.isInteger(o)&&o>=0){let s=[];s[o]=i,i=s}else i=new Map([[o,i]])}return j0.createNode(i,void 0,{aliasDuplicateObjects:!1,keepUndefined:!1,onAnchor:()=>{throw new Error("This should not happen, please report a bug.")},schema:n,sourceObjects:new Map})}var Eg=n=>n==null||typeof n=="object"&&!!n[Symbol.iterator]().next().done,Xu=class extends $0.NodeBase{constructor(e,t){super(e),Object.defineProperty(this,"schema",{value:t,configurable:!0,enumerable:!1,writable:!0})}clone(e){let t=Object.create(Object.getPrototypeOf(this),Object.getOwnPropertyDescriptors(this));return e&&(t.schema=e),t.items=t.items.map(i=>nt.isNode(i)||nt.isPair(i)?i.clone(e):i),this.range&&(t.range=this.range.slice()),t}addIn(e,t){if(Eg(e))this.add(t);else{let[i,...r]=e,o=this.get(i,!0);if(nt.isCollection(o))o.addIn(r,t);else if(o===void 0&&this.schema)this.set(i,Ku(this.schema,r,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}deleteIn(e){let[t,...i]=e;if(i.length===0)return this.delete(t);let r=this.get(t,!0);if(nt.isCollection(r))return r.deleteIn(i);throw new Error(`Expected YAML collection at ${t}. Remaining path: ${i}`)}getIn(e,t){let[i,...r]=e,o=this.get(i,!0);return r.length===0?!t&&nt.isScalar(o)?o.value:o:nt.isCollection(o)?o.getIn(r,t):void 0}hasAllNullValues(e){return this.items.every(t=>{if(!nt.isPair(t))return!1;let i=t.value;return i==null||e&&nt.isScalar(i)&&i.value==null&&!i.commentBefore&&!i.comment&&!i.tag})}hasIn(e){let[t,...i]=e;if(i.length===0)return this.has(t);let r=this.get(t,!0);return nt.isCollection(r)?r.hasIn(i):!1}setIn(e,t){let[i,...r]=e;if(r.length===0)this.set(i,t);else{let o=this.get(i,!0);if(nt.isCollection(o))o.setIn(r,t);else if(o===void 0&&this.schema)this.set(i,Ku(this.schema,r,t));else throw new Error(`Expected YAML collection at ${i}. Remaining path: ${r}`)}}};Js.Collection=Xu;Js.collectionFromPath=Ku;Js.isEmptyPath=Eg});var xn=M(ea=>{"use strict";var Y0=n=>n.replace(/^(?!$)(?: $)?/gm,"#");function Qu(n,e){return/^\n+$/.test(n)?n.substring(1):e?n.replace(/^(?! *$)/gm,e):n}var K0=(n,e,t)=>n.endsWith(`
4
+ `)?Qu(t,e):t.includes(`
5
+ `)?`
6
+ `+Qu(t,e):(n.endsWith(" ")?"":" ")+t;ea.indentComment=Qu;ea.lineComment=K0;ea.stringifyComment=Y0});var Ig=M(Pn=>{"use strict";var X0="flow",Ju="block",ta="quoted";function Q0(n,e,t="flow",{indentAtStart:i,lineWidth:r=80,minContentWidth:o=20,onFold:s,onOverflow:a}={}){if(!r||r<0)return n;r<o&&(o=0);let l=Math.max(1+o,1+r-e.length);if(n.length<=l)return n;let c=[],u={},h=r-e.length;typeof i=="number"&&(i>r-Math.max(2,o)?c.push(0):h=r-i);let d,p,f=!1,m=-1,g=-1,y=-1;t===Ju&&(m=Ng(n,m,e.length),m!==-1&&(h=m+l));for(let v;v=n[m+=1];){if(t===ta&&v==="\\"){switch(g=m,n[m+1]){case"x":m+=3;break;case"u":m+=5;break;case"U":m+=9;break;default:m+=1}y=m}if(v===`
7
+ `)t===Ju&&(m=Ng(n,m,e.length)),h=m+e.length+l,d=void 0;else{if(v===" "&&p&&p!==" "&&p!==`
8
+ `&&p!==" "){let w=n[m+1];w&&w!==" "&&w!==`
9
+ `&&w!==" "&&(d=m)}if(m>=h)if(d)c.push(d),h=d+l,d=void 0;else if(t===ta){for(;p===" "||p===" ";)p=v,v=n[m+=1],f=!0;let w=m>y+1?m-2:g-1;if(u[w])return n;c.push(w),u[w]=!0,h=w+l,d=void 0}else f=!0}p=v}if(f&&a&&a(),c.length===0)return n;s&&s();let b=n.slice(0,c[0]);for(let v=0;v<c.length;++v){let w=c[v],k=c[v+1]||n.length;w===0?b=`
10
+ ${e}${n.slice(0,k)}`:(t===ta&&u[w]&&(b+=`${n[w]}\\`),b+=`
11
+ ${e}${n.slice(w+1,k)}`)}return b}function Ng(n,e,t){let i=e,r=e+1,o=n[r];for(;o===" "||o===" ";)if(e<r+t)o=n[++e];else{do o=n[++e];while(o&&o!==`
12
+ `);i=e,r=e+1,o=n[r]}return i}Pn.FOLD_BLOCK=Ju;Pn.FOLD_FLOW=X0;Pn.FOLD_QUOTED=ta;Pn.foldFlowLines=Q0});var An=M(Rg=>{"use strict";var He=ne(),$t=Ig(),ra=(n,e)=>({indentAtStart:e?n.indent.length:n.indentAtStart,lineWidth:n.options.lineWidth,minContentWidth:n.options.minContentWidth}),na=n=>/^(%|---|\.\.\.)/m.test(n);function J0(n,e,t){if(!e||e<0)return!1;let i=e-t,r=n.length;if(r<=i)return!1;for(let o=0,s=0;o<r;++o)if(n[o]===`
13
+ `){if(o-s>i)return!0;if(s=o+1,r-s<=i)return!1}return!0}function kn(n,e){let t=JSON.stringify(n);if(e.options.doubleQuotedAsJSON)return t;let{implicitKey:i}=e,r=e.options.doubleQuotedMinMultiLineLength,o=e.indent||(na(n)?" ":""),s="",a=0;for(let l=0,c=t[l];c;c=t[++l])if(c===" "&&t[l+1]==="\\"&&t[l+2]==="n"&&(s+=t.slice(a,l)+"\\ ",l+=1,a=l,c="\\"),c==="\\")switch(t[l+1]){case"u":{s+=t.slice(a,l);let u=t.substr(l+2,4);switch(u){case"0000":s+="\\0";break;case"0007":s+="\\a";break;case"000b":s+="\\v";break;case"001b":s+="\\e";break;case"0085":s+="\\N";break;case"00a0":s+="\\_";break;case"2028":s+="\\L";break;case"2029":s+="\\P";break;default:u.substr(0,2)==="00"?s+="\\x"+u.substr(2):s+=t.substr(l,6)}l+=5,a=l+1}break;case"n":if(i||t[l+2]==='"'||t.length<r)l+=1;else{for(s+=t.slice(a,l)+`
14
+
15
+ `;t[l+2]==="\\"&&t[l+3]==="n"&&t[l+4]!=='"';)s+=`
16
+ `,l+=2;s+=o,t[l+2]===" "&&(s+="\\"),l+=1,a=l+1}break;default:l+=1}return s=a?s+t.slice(a):t,i?s:$t.foldFlowLines(s,o,$t.FOLD_QUOTED,ra(e,!1))}function Zu(n,e){if(e.options.singleQuote===!1||e.implicitKey&&n.includes(`
17
+ `)||/[ \t]\n|\n[ \t]/.test(n))return kn(n,e);let t=e.indent||(na(n)?" ":""),i="'"+n.replace(/'/g,"''").replace(/\n+/g,`$&
18
+ ${t}`)+"'";return e.implicitKey?i:$t.foldFlowLines(i,t,$t.FOLD_FLOW,ra(e,!1))}function vr(n,e){let{singleQuote:t}=e.options,i;if(t===!1)i=kn;else{let r=n.includes('"'),o=n.includes("'");r&&!o?i=Zu:o&&!r?i=kn:i=t?Zu:kn}return i(n,e)}var eh;try{eh=new RegExp(`(^|(?<!
19
+ ))
20
+ +(?!
21
+ |$)`,"g")}catch{eh=/\n+(?!\n|$)/g}function ia({comment:n,type:e,value:t},i,r,o){let{blockQuote:s,commentString:a,lineWidth:l}=i.options;if(!s||/\n[\t ]+$/.test(t))return vr(t,i);let c=i.indent||(i.forceBlockIndent||na(t)?" ":""),u=s==="literal"?!0:s==="folded"||e===He.Scalar.BLOCK_FOLDED?!1:e===He.Scalar.BLOCK_LITERAL?!0:!J0(t,l,c.length);if(!t)return u?`|
22
+ `:`>
23
+ `;let h,d;for(d=t.length;d>0;--d){let k=t[d-1];if(k!==`
24
+ `&&k!==" "&&k!==" ")break}let p=t.substring(d),f=p.indexOf(`
25
+ `);f===-1?h="-":t===p||f!==p.length-1?(h="+",o&&o()):h="",p&&(t=t.slice(0,-p.length),p[p.length-1]===`
26
+ `&&(p=p.slice(0,-1)),p=p.replace(eh,`$&${c}`));let m=!1,g,y=-1;for(g=0;g<t.length;++g){let k=t[g];if(k===" ")m=!0;else if(k===`
27
+ `)y=g;else break}let b=t.substring(0,y<g?y+1:g);b&&(t=t.substring(b.length),b=b.replace(/\n+/g,`$&${c}`));let w=(m?c?"2":"1":"")+h;if(n&&(w+=" "+a(n.replace(/ ?[\r\n]+/g," ")),r&&r()),!u){let k=t.replace(/\n+/g,`
28
+ $&`).replace(/(?:^|\n)([\t ].*)(?:([\n\t ]*)\n(?![\n\t ]))?/g,"$1$2").replace(/\n+/g,`$&${c}`),T=!1,E=ra(i,!0);s!=="folded"&&e!==He.Scalar.BLOCK_FOLDED&&(E.onOverflow=()=>{T=!0});let A=$t.foldFlowLines(`${b}${k}${p}`,c,$t.FOLD_BLOCK,E);if(!T)return`>${w}
29
+ ${c}${A}`}return t=t.replace(/\n+/g,`$&${c}`),`|${w}
30
+ ${c}${b}${t}${p}`}function Z0(n,e,t,i){let{type:r,value:o}=n,{actualString:s,implicitKey:a,indent:l,indentStep:c,inFlow:u}=e;if(a&&o.includes(`
31
+ `)||u&&/[[\]{},]/.test(o))return vr(o,e);if(/^[\n\t ,[\]{}#&*!|>'"%@`]|^[?-]$|^[?-][ \t]|[\n:][ \t]|[ \t]\n|[\n\t ]#|[\n\t :]$/.test(o))return a||u||!o.includes(`
32
+ `)?vr(o,e):ia(n,e,t,i);if(!a&&!u&&r!==He.Scalar.PLAIN&&o.includes(`
33
+ `))return ia(n,e,t,i);if(na(o)){if(l==="")return e.forceBlockIndent=!0,ia(n,e,t,i);if(a&&l===c)return vr(o,e)}let h=o.replace(/\n+/g,`$&
34
+ ${l}`);if(s){let d=m=>m.default&&m.tag!=="tag:yaml.org,2002:str"&&m.test?.test(h),{compat:p,tags:f}=e.doc.schema;if(f.some(d)||p?.some(d))return vr(o,e)}return a?h:$t.foldFlowLines(h,l,$t.FOLD_FLOW,ra(e,!1))}function eP(n,e,t,i){let{implicitKey:r,inFlow:o}=e,s=typeof n.value=="string"?n:Object.assign({},n,{value:String(n.value)}),{type:a}=n;a!==He.Scalar.QUOTE_DOUBLE&&/[\x00-\x08\x0b-\x1f\x7f-\x9f\u{D800}-\u{DFFF}]/u.test(s.value)&&(a=He.Scalar.QUOTE_DOUBLE);let l=u=>{switch(u){case He.Scalar.BLOCK_FOLDED:case He.Scalar.BLOCK_LITERAL:return r||o?vr(s.value,e):ia(s,e,t,i);case He.Scalar.QUOTE_DOUBLE:return kn(s.value,e);case He.Scalar.QUOTE_SINGLE:return Zu(s.value,e);case He.Scalar.PLAIN:return Z0(s,e,t,i);default:return null}},c=l(a);if(c===null){let{defaultKeyType:u,defaultStringType:h}=e.options,d=r&&u||h;if(c=l(d),c===null)throw new Error(`Unsupported default string type ${d}`)}return c}Rg.stringifyString=eP});var Tn=M(th=>{"use strict";var tP=Ks(),Yt=G(),iP=xn(),rP=An();function nP(n,e){let t=Object.assign({blockQuote:!0,commentString:iP.stringifyComment,defaultKeyType:null,defaultStringType:"PLAIN",directives:null,doubleQuotedAsJSON:!1,doubleQuotedMinMultiLineLength:40,falseStr:"false",flowCollectionPadding:!0,indentSeq:!0,lineWidth:80,minContentWidth:20,nullStr:"null",simpleKeys:!1,singleQuote:null,trailingComma:!1,trueStr:"true",verifyAliasOrder:!0},n.schema.toStringOptions,e),i;switch(t.collectionStyle){case"block":i=!1;break;case"flow":i=!0;break;default:i=null}return{anchors:new Set,doc:n,flowCollectionPadding:t.flowCollectionPadding?" ":"",indent:"",indentStep:typeof t.indent=="number"?" ".repeat(t.indent):" ",inFlow:i,options:t}}function oP(n,e){if(e.tag){let r=n.filter(o=>o.tag===e.tag);if(r.length>0)return r.find(o=>o.format===e.format)??r[0]}let t,i;if(Yt.isScalar(e)){i=e.value;let r=n.filter(o=>o.identify?.(i));if(r.length>1){let o=r.filter(s=>s.test);o.length>0&&(r=o)}t=r.find(o=>o.format===e.format)??r.find(o=>!o.format)}else i=e,t=n.find(r=>r.nodeClass&&i instanceof r.nodeClass);if(!t){let r=i?.constructor?.name??(i===null?"null":typeof i);throw new Error(`Tag not resolved for ${r} value`)}return t}function sP(n,e,{anchors:t,doc:i}){if(!i.directives)return"";let r=[],o=(Yt.isScalar(n)||Yt.isCollection(n))&&n.anchor;o&&tP.anchorIsValid(o)&&(t.add(o),r.push(`&${o}`));let s=n.tag??(e.default?null:e.tag);return s&&r.push(i.directives.tagString(s)),r.join(" ")}function aP(n,e,t,i){if(Yt.isPair(n))return n.toString(e,t,i);if(Yt.isAlias(n)){if(e.doc.directives)return n.toString(e);if(e.resolvedAliases?.has(n))throw new TypeError("Cannot stringify circular structure without alias nodes");e.resolvedAliases?e.resolvedAliases.add(n):e.resolvedAliases=new Set([n]),n=n.resolve(e.doc)}let r,o=Yt.isNode(n)?n:e.doc.createNode(n,{onTagObj:l=>r=l});r??(r=oP(e.doc.schema.tags,o));let s=sP(o,r,e);s.length>0&&(e.indentAtStart=(e.indentAtStart??0)+s.length+1);let a=typeof r.stringify=="function"?r.stringify(o,e,t,i):Yt.isScalar(o)?rP.stringifyString(o,e,t,i):o.toString(e,t,i);return s?Yt.isScalar(o)||a[0]==="{"||a[0]==="["?`${s} ${a}`:`${s}
35
+ ${e.indent}${a}`:a}th.createStringifyContext=nP;th.stringify=aP});var Lg=M(Vg=>{"use strict";var At=G(),Bg=ne(),Og=Tn(),Cn=xn();function lP({key:n,value:e},t,i,r){let{allNullValues:o,doc:s,indent:a,indentStep:l,options:{commentString:c,indentSeq:u,simpleKeys:h}}=t,d=At.isNode(n)&&n.comment||null;if(h){if(d)throw new Error("With simple keys, key nodes cannot have comments");if(At.isCollection(n)||!At.isNode(n)&&typeof n=="object"){let E="With simple keys, collection cannot be used as a key value";throw new Error(E)}}let p=!h&&(!n||d&&e==null&&!t.inFlow||At.isCollection(n)||(At.isScalar(n)?n.type===Bg.Scalar.BLOCK_FOLDED||n.type===Bg.Scalar.BLOCK_LITERAL:typeof n=="object"));t=Object.assign({},t,{allNullValues:!1,implicitKey:!p&&(h||!o),indent:a+l});let f=!1,m=!1,g=Og.stringify(n,t,()=>f=!0,()=>m=!0);if(!p&&!t.inFlow&&g.length>1024){if(h)throw new Error("With simple keys, single line scalar must not span more than 1024 characters");p=!0}if(t.inFlow){if(o||e==null)return f&&i&&i(),g===""?"?":p?`? ${g}`:g}else if(o&&!h||e==null&&p)return g=`? ${g}`,d&&!f?g+=Cn.lineComment(g,t.indent,c(d)):m&&r&&r(),g;f&&(d=null),p?(d&&(g+=Cn.lineComment(g,t.indent,c(d))),g=`? ${g}
36
+ ${a}:`):(g=`${g}:`,d&&(g+=Cn.lineComment(g,t.indent,c(d))));let y,b,v;At.isNode(e)?(y=!!e.spaceBefore,b=e.commentBefore,v=e.comment):(y=!1,b=null,v=null,e&&typeof e=="object"&&(e=s.createNode(e))),t.implicitKey=!1,!p&&!d&&At.isScalar(e)&&(t.indentAtStart=g.length+1),m=!1,!u&&l.length>=2&&!t.inFlow&&!p&&At.isSeq(e)&&!e.flow&&!e.tag&&!e.anchor&&(t.indent=t.indent.substring(2));let w=!1,k=Og.stringify(e,t,()=>w=!0,()=>m=!0),T=" ";if(d||y||b){if(T=y?`
37
+ `:"",b){let E=c(b);T+=`
38
+ ${Cn.indentComment(E,t.indent)}`}k===""&&!t.inFlow?T===`
39
+ `&&v&&(T=`
40
+
41
+ `):T+=`
42
+ ${t.indent}`}else if(!p&&At.isCollection(e)){let E=k[0],A=k.indexOf(`
43
+ `),_=A!==-1,J=t.inFlow??e.flow??e.items.length===0;if(_||!J){let re=!1;if(_&&(E==="&"||E==="!")){let ee=k.indexOf(" ");E==="&"&&ee!==-1&&ee<A&&k[ee+1]==="!"&&(ee=k.indexOf(" ",ee+1)),(ee===-1||A<ee)&&(re=!0)}re||(T=`
44
+ ${t.indent}`)}}else(k===""||k[0]===`
45
+ `)&&(T="");return g+=T+k,t.inFlow?w&&i&&i():v&&!w?g+=Cn.lineComment(g,t.indent,c(v)):m&&r&&r(),g}Vg.stringifyPair=lP});var rh=M(ih=>{"use strict";var _g=Yo("process");function cP(n,...e){n==="debug"&&console.log(...e)}function uP(n,e){(n==="debug"||n==="warn")&&(typeof _g.emitWarning=="function"?_g.emitWarning(e):console.warn(e))}ih.debug=cP;ih.warn=uP});var ca=M(la=>{"use strict";var aa=G(),Fg=ne(),oa="<<",sa={identify:n=>n===oa||typeof n=="symbol"&&n.description===oa,default:"key",tag:"tag:yaml.org,2002:merge",test:/^<<$/,resolve:()=>Object.assign(new Fg.Scalar(Symbol(oa)),{addToJSMap:zg}),stringify:()=>oa},hP=(n,e)=>(sa.identify(e)||aa.isScalar(e)&&(!e.type||e.type===Fg.Scalar.PLAIN)&&sa.identify(e.value))&&n?.doc.schema.tags.some(t=>t.tag===sa.tag&&t.default);function zg(n,e,t){let i=Ug(n,t);if(aa.isSeq(i))for(let r of i.items)nh(n,e,r);else if(Array.isArray(i))for(let r of i)nh(n,e,r);else nh(n,e,i)}function nh(n,e,t){let i=Ug(n,t);if(!aa.isMap(i))throw new Error("Merge sources must be maps or map aliases");let r=i.toJSON(null,n,Map);for(let[o,s]of r)e instanceof Map?e.has(o)||e.set(o,s):e instanceof Set?e.add(o):Object.prototype.hasOwnProperty.call(e,o)||Object.defineProperty(e,o,{value:s,writable:!0,enumerable:!0,configurable:!0});return e}function Ug(n,e){return n&&aa.isAlias(e)?e.resolve(n.doc,n):e}la.addMergeToJSMap=zg;la.isMergeKey=hP;la.merge=sa});var sh=M(qg=>{"use strict";var dP=rh(),Wg=ca(),pP=Tn(),Hg=G(),oh=Gt();function mP(n,e,{key:t,value:i}){if(Hg.isNode(t)&&t.addToJSMap)t.addToJSMap(n,e,i);else if(Wg.isMergeKey(n,t))Wg.addMergeToJSMap(n,e,i);else{let r=oh.toJS(t,"",n);if(e instanceof Map)e.set(r,oh.toJS(i,r,n));else if(e instanceof Set)e.add(r);else{let o=fP(t,r,n),s=oh.toJS(i,o,n);o in e?Object.defineProperty(e,o,{value:s,writable:!0,enumerable:!0,configurable:!0}):e[o]=s}}return e}function fP(n,e,t){if(e===null)return"";if(typeof e!="object")return String(e);if(Hg.isNode(n)&&t?.doc){let i=pP.createStringifyContext(t.doc,{});i.anchors=new Set;for(let o of t.anchors.keys())i.anchors.add(o.anchor);i.inFlow=!0,i.inStringifyKey=!0;let r=n.toString(i);if(!t.mapKeyWarned){let o=JSON.stringify(r);o.length>40&&(o=o.substring(0,36)+'..."'),dP.warn(t.doc.options.logLevel,`Keys with collection values will be stringified due to JS Object restrictions: ${o}. Set mapAsMap: true to use object keys.`),t.mapKeyWarned=!0}return r}return JSON.stringify(e)}qg.addPairToJSMap=mP});var Kt=M(ah=>{"use strict";var Gg=wn(),gP=Lg(),yP=sh(),ua=G();function bP(n,e,t){let i=Gg.createNode(n,void 0,t),r=Gg.createNode(e,void 0,t);return new ha(i,r)}var ha=class n{constructor(e,t=null){Object.defineProperty(this,ua.NODE_TYPE,{value:ua.PAIR}),this.key=e,this.value=t}clone(e){let{key:t,value:i}=this;return ua.isNode(t)&&(t=t.clone(e)),ua.isNode(i)&&(i=i.clone(e)),new n(t,i)}toJSON(e,t){let i=t?.mapAsMap?new Map:{};return yP.addPairToJSMap(t,i,this)}toString(e,t,i){return e?.doc?gP.stringifyPair(this,e,t,i):JSON.stringify(this)}};ah.Pair=ha;ah.createPair=bP});var lh=M($g=>{"use strict";var Ri=G(),jg=Tn(),da=xn();function SP(n,e,t){return(e.inFlow??n.flow?wP:vP)(n,e,t)}function vP({comment:n,items:e},t,{blockItemPrefix:i,flowChars:r,itemIndent:o,onChompKeep:s,onComment:a}){let{indent:l,options:{commentString:c}}=t,u=Object.assign({},t,{indent:o,type:null}),h=!1,d=[];for(let f=0;f<e.length;++f){let m=e[f],g=null;if(Ri.isNode(m))!h&&m.spaceBefore&&d.push(""),pa(t,d,m.commentBefore,h),m.comment&&(g=m.comment);else if(Ri.isPair(m)){let b=Ri.isNode(m.key)?m.key:null;b&&(!h&&b.spaceBefore&&d.push(""),pa(t,d,b.commentBefore,h))}h=!1;let y=jg.stringify(m,u,()=>g=null,()=>h=!0);g&&(y+=da.lineComment(y,o,c(g))),h&&g&&(h=!1),d.push(i+y)}let p;if(d.length===0)p=r.start+r.end;else{p=d[0];for(let f=1;f<d.length;++f){let m=d[f];p+=m?`
46
+ ${l}${m}`:`
47
+ `}}return n?(p+=`
48
+ `+da.indentComment(c(n),l),a&&a()):h&&s&&s(),p}function wP({items:n},e,{flowChars:t,itemIndent:i}){let{indent:r,indentStep:o,flowCollectionPadding:s,options:{commentString:a}}=e;i+=o;let l=Object.assign({},e,{indent:i,inFlow:!0,type:null}),c=!1,u=0,h=[];for(let f=0;f<n.length;++f){let m=n[f],g=null;if(Ri.isNode(m))m.spaceBefore&&h.push(""),pa(e,h,m.commentBefore,!1),m.comment&&(g=m.comment);else if(Ri.isPair(m)){let b=Ri.isNode(m.key)?m.key:null;b&&(b.spaceBefore&&h.push(""),pa(e,h,b.commentBefore,!1),b.comment&&(c=!0));let v=Ri.isNode(m.value)?m.value:null;v?(v.comment&&(g=v.comment),v.commentBefore&&(c=!0)):m.value==null&&b?.comment&&(g=b.comment)}g&&(c=!0);let y=jg.stringify(m,l,()=>g=null);c||(c=h.length>u||y.includes(`
49
+ `)),f<n.length-1?y+=",":e.options.trailingComma&&(e.options.lineWidth>0&&(c||(c=h.reduce((b,v)=>b+v.length+2,2)+(y.length+2)>e.options.lineWidth)),c&&(y+=",")),g&&(y+=da.lineComment(y,i,a(g))),h.push(y),u=h.length}let{start:d,end:p}=t;if(h.length===0)return d+p;if(!c){let f=h.reduce((m,g)=>m+g.length+2,2);c=e.options.lineWidth>0&&f>e.options.lineWidth}if(c){let f=d;for(let m of h)f+=m?`
50
+ ${o}${r}${m}`:`
51
+ `;return`${f}
52
+ ${r}${p}`}else return`${d}${s}${h.join(" ")}${s}${p}`}function pa({indent:n,options:{commentString:e}},t,i,r){if(i&&r&&(i=i.replace(/^\n+/,"")),i){let o=da.indentComment(e(i),n);t.push(o.trimStart())}}$g.stringifyCollection=SP});var Qt=M(uh=>{"use strict";var xP=lh(),PP=sh(),kP=Zs(),Xt=G(),ma=Kt(),AP=ne();function Mn(n,e){let t=Xt.isScalar(e)?e.value:e;for(let i of n)if(Xt.isPair(i)&&(i.key===e||i.key===t||Xt.isScalar(i.key)&&i.key.value===t))return i}var ch=class extends kP.Collection{static get tagName(){return"tag:yaml.org,2002:map"}constructor(e){super(Xt.MAP,e),this.items=[]}static from(e,t,i){let{keepUndefined:r,replacer:o}=i,s=new this(e),a=(l,c)=>{if(typeof o=="function")c=o.call(t,l,c);else if(Array.isArray(o)&&!o.includes(l))return;(c!==void 0||r)&&s.items.push(ma.createPair(l,c,i))};if(t instanceof Map)for(let[l,c]of t)a(l,c);else if(t&&typeof t=="object")for(let l of Object.keys(t))a(l,t[l]);return typeof e.sortMapEntries=="function"&&s.items.sort(e.sortMapEntries),s}add(e,t){let i;Xt.isPair(e)?i=e:!e||typeof e!="object"||!("key"in e)?i=new ma.Pair(e,e?.value):i=new ma.Pair(e.key,e.value);let r=Mn(this.items,i.key),o=this.schema?.sortMapEntries;if(r){if(!t)throw new Error(`Key ${i.key} already set`);Xt.isScalar(r.value)&&AP.isScalarValue(i.value)?r.value.value=i.value:r.value=i.value}else if(o){let s=this.items.findIndex(a=>o(i,a)<0);s===-1?this.items.push(i):this.items.splice(s,0,i)}else this.items.push(i)}delete(e){let t=Mn(this.items,e);return t?this.items.splice(this.items.indexOf(t),1).length>0:!1}get(e,t){let r=Mn(this.items,e)?.value;return(!t&&Xt.isScalar(r)?r.value:r)??void 0}has(e){return!!Mn(this.items,e)}set(e,t){this.add(new ma.Pair(e,t),!0)}toJSON(e,t,i){let r=i?new i:t?.mapAsMap?new Map:{};t?.onCreate&&t.onCreate(r);for(let o of this.items)PP.addPairToJSMap(t,r,o);return r}toString(e,t,i){if(!e)return JSON.stringify(this);for(let r of this.items)if(!Xt.isPair(r))throw new Error(`Map items must all be pairs; found ${JSON.stringify(r)} instead`);return!e.allNullValues&&this.hasAllNullValues(!1)&&(e=Object.assign({},e,{allNullValues:!0})),xP.stringifyCollection(this,e,{blockItemPrefix:"",flowChars:{start:"{",end:"}"},itemIndent:e.indent||"",onChompKeep:i,onComment:t})}};uh.YAMLMap=ch;uh.findPair=Mn});var wr=M(Kg=>{"use strict";var TP=G(),Yg=Qt(),CP={collection:"map",default:!0,nodeClass:Yg.YAMLMap,tag:"tag:yaml.org,2002:map",resolve(n,e){return TP.isMap(n)||e("Expected a mapping for this tag"),n},createNode:(n,e,t)=>Yg.YAMLMap.from(n,e,t)};Kg.map=CP});var Jt=M(Xg=>{"use strict";var MP=wn(),DP=lh(),EP=Zs(),ga=G(),NP=ne(),IP=Gt(),hh=class extends EP.Collection{static get tagName(){return"tag:yaml.org,2002:seq"}constructor(e){super(ga.SEQ,e),this.items=[]}add(e){this.items.push(e)}delete(e){let t=fa(e);return typeof t!="number"?!1:this.items.splice(t,1).length>0}get(e,t){let i=fa(e);if(typeof i!="number")return;let r=this.items[i];return!t&&ga.isScalar(r)?r.value:r}has(e){let t=fa(e);return typeof t=="number"&&t<this.items.length}set(e,t){let i=fa(e);if(typeof i!="number")throw new Error(`Expected a valid index, not ${e}.`);let r=this.items[i];ga.isScalar(r)&&NP.isScalarValue(t)?r.value=t:this.items[i]=t}toJSON(e,t){let i=[];t?.onCreate&&t.onCreate(i);let r=0;for(let o of this.items)i.push(IP.toJS(o,String(r++),t));return i}toString(e,t,i){return e?DP.stringifyCollection(this,e,{blockItemPrefix:"- ",flowChars:{start:"[",end:"]"},itemIndent:(e.indent||"")+" ",onChompKeep:i,onComment:t}):JSON.stringify(this)}static from(e,t,i){let{replacer:r}=i,o=new this(e);if(t&&Symbol.iterator in Object(t)){let s=0;for(let a of t){if(typeof r=="function"){let l=t instanceof Set?a:String(s++);a=r.call(t,l,a)}o.items.push(MP.createNode(a,void 0,i))}}return o}};function fa(n){let e=ga.isScalar(n)?n.value:n;return e&&typeof e=="string"&&(e=Number(e)),typeof e=="number"&&Number.isInteger(e)&&e>=0?e:null}Xg.YAMLSeq=hh});var xr=M(Jg=>{"use strict";var RP=G(),Qg=Jt(),BP={collection:"seq",default:!0,nodeClass:Qg.YAMLSeq,tag:"tag:yaml.org,2002:seq",resolve(n,e){return RP.isSeq(n)||e("Expected a sequence for this tag"),n},createNode:(n,e,t)=>Qg.YAMLSeq.from(n,e,t)};Jg.seq=BP});var Dn=M(Zg=>{"use strict";var OP=An(),VP={identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify(n,e,t,i){return e=Object.assign({actualString:!0},e),OP.stringifyString(n,e,t,i)}};Zg.string=VP});var ya=M(iy=>{"use strict";var ey=ne(),ty={identify:n=>n==null,createNode:()=>new ey.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^(?:~|[Nn]ull|NULL)?$/,resolve:()=>new ey.Scalar(null),stringify:({source:n},e)=>typeof n=="string"&&ty.test.test(n)?n:e.options.nullStr};iy.nullTag=ty});var dh=M(ny=>{"use strict";var LP=ne(),ry={identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:[Tt]rue|TRUE|[Ff]alse|FALSE)$/,resolve:n=>new LP.Scalar(n[0]==="t"||n[0]==="T"),stringify({source:n,value:e},t){if(n&&ry.test.test(n)){let i=n[0]==="t"||n[0]==="T";if(e===i)return n}return e?t.options.trueStr:t.options.falseStr}};ny.boolTag=ry});var Pr=M(oy=>{"use strict";function _P({format:n,minFractionDigits:e,tag:t,value:i}){if(typeof i=="bigint")return String(i);let r=typeof i=="number"?i:Number(i);if(!isFinite(r))return isNaN(r)?".nan":r<0?"-.inf":".inf";let o=Object.is(i,-0)?"-0":JSON.stringify(i);if(!n&&e&&(!t||t==="tag:yaml.org,2002:float")&&/^-?\d/.test(o)&&!o.includes("e")){let s=o.indexOf(".");s<0&&(s=o.length,o+=".");let a=e-(o.length-s-1);for(;a-- >0;)o+="0"}return o}oy.stringifyNumber=_P});var mh=M(ba=>{"use strict";var FP=ne(),ph=Pr(),zP={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:ph.stringifyNumber},UP={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:\.[0-9]+|[0-9]+(?:\.[0-9]*)?)[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():ph.stringifyNumber(n)}},WP={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:\.[0-9]+|[0-9]+\.[0-9]*)$/,resolve(n){let e=new FP.Scalar(parseFloat(n)),t=n.indexOf(".");return t!==-1&&n[n.length-1]==="0"&&(e.minFractionDigits=n.length-t-1),e},stringify:ph.stringifyNumber};ba.float=WP;ba.floatExp=UP;ba.floatNaN=zP});var gh=M(va=>{"use strict";var sy=Pr(),Sa=n=>typeof n=="bigint"||Number.isInteger(n),fh=(n,e,t,{intAsBigInt:i})=>i?BigInt(n):parseInt(n.substring(e),t);function ay(n,e,t){let{value:i}=n;return Sa(i)&&i>=0?t+i.toString(e):sy.stringifyNumber(n)}var HP={identify:n=>Sa(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^0o[0-7]+$/,resolve:(n,e,t)=>fh(n,2,8,t),stringify:n=>ay(n,8,"0o")},qP={identify:Sa,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9]+$/,resolve:(n,e,t)=>fh(n,0,10,t),stringify:sy.stringifyNumber},GP={identify:n=>Sa(n)&&n>=0,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^0x[0-9a-fA-F]+$/,resolve:(n,e,t)=>fh(n,2,16,t),stringify:n=>ay(n,16,"0x")};va.int=qP;va.intHex=GP;va.intOct=HP});var cy=M(ly=>{"use strict";var jP=wr(),$P=ya(),YP=xr(),KP=Dn(),XP=dh(),yh=mh(),bh=gh(),QP=[jP.map,YP.seq,KP.string,$P.nullTag,XP.boolTag,bh.intOct,bh.int,bh.intHex,yh.floatNaN,yh.floatExp,yh.float];ly.schema=QP});var dy=M(hy=>{"use strict";var JP=ne(),ZP=wr(),ek=xr();function uy(n){return typeof n=="bigint"||Number.isInteger(n)}var wa=({value:n})=>JSON.stringify(n),tk=[{identify:n=>typeof n=="string",default:!0,tag:"tag:yaml.org,2002:str",resolve:n=>n,stringify:wa},{identify:n=>n==null,createNode:()=>new JP.Scalar(null),default:!0,tag:"tag:yaml.org,2002:null",test:/^null$/,resolve:()=>null,stringify:wa},{identify:n=>typeof n=="boolean",default:!0,tag:"tag:yaml.org,2002:bool",test:/^true$|^false$/,resolve:n=>n==="true",stringify:wa},{identify:uy,default:!0,tag:"tag:yaml.org,2002:int",test:/^-?(?:0|[1-9][0-9]*)$/,resolve:(n,e,{intAsBigInt:t})=>t?BigInt(n):parseInt(n,10),stringify:({value:n})=>uy(n)?n.toString():JSON.stringify(n)},{identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^-?(?:0|[1-9][0-9]*)(?:\.[0-9]*)?(?:[eE][-+]?[0-9]+)?$/,resolve:n=>parseFloat(n),stringify:wa}],ik={default:!0,tag:"",test:/^/,resolve(n,e){return e(`Unresolved plain scalar ${JSON.stringify(n)}`),n}},rk=[ZP.map,ek.seq].concat(tk,ik);hy.schema=rk});var vh=M(py=>{"use strict";var En=Yo("buffer"),Sh=ne(),nk=An(),ok={identify:n=>n instanceof Uint8Array,default:!1,tag:"tag:yaml.org,2002:binary",resolve(n,e){if(typeof En.Buffer=="function")return En.Buffer.from(n,"base64");if(typeof atob=="function"){let t=atob(n.replace(/[\n\r]/g,"")),i=new Uint8Array(t.length);for(let r=0;r<t.length;++r)i[r]=t.charCodeAt(r);return i}else return e("This environment does not support reading binary tags; either Buffer or atob is required"),n},stringify({comment:n,type:e,value:t},i,r,o){if(!t)return"";let s=t,a;if(typeof En.Buffer=="function")a=s instanceof En.Buffer?s.toString("base64"):En.Buffer.from(s.buffer).toString("base64");else if(typeof btoa=="function"){let l="";for(let c=0;c<s.length;++c)l+=String.fromCharCode(s[c]);a=btoa(l)}else throw new Error("This environment does not support writing binary tags; either Buffer or btoa is required");if(e??(e=Sh.Scalar.BLOCK_LITERAL),e!==Sh.Scalar.QUOTE_DOUBLE){let l=Math.max(i.options.lineWidth-i.indent.length,i.options.minContentWidth),c=Math.ceil(a.length/l),u=new Array(c);for(let h=0,d=0;h<c;++h,d+=l)u[h]=a.substr(d,l);a=u.join(e===Sh.Scalar.BLOCK_LITERAL?`
53
+ `:" ")}return nk.stringifyString({comment:n,type:e,value:a},i,r,o)}};py.binary=ok});var ka=M(Pa=>{"use strict";var xa=G(),wh=Kt(),sk=ne(),ak=Jt();function my(n,e){if(xa.isSeq(n))for(let t=0;t<n.items.length;++t){let i=n.items[t];if(!xa.isPair(i)){if(xa.isMap(i)){i.items.length>1&&e("Each pair must have its own sequence indicator");let r=i.items[0]||new wh.Pair(new sk.Scalar(null));if(i.commentBefore&&(r.key.commentBefore=r.key.commentBefore?`${i.commentBefore}
54
+ ${r.key.commentBefore}`:i.commentBefore),i.comment){let o=r.value??r.key;o.comment=o.comment?`${i.comment}
55
+ ${o.comment}`:i.comment}i=r}n.items[t]=xa.isPair(i)?i:new wh.Pair(i)}}else e("Expected a sequence for this tag");return n}function fy(n,e,t){let{replacer:i}=t,r=new ak.YAMLSeq(n);r.tag="tag:yaml.org,2002:pairs";let o=0;if(e&&Symbol.iterator in Object(e))for(let s of e){typeof i=="function"&&(s=i.call(e,String(o++),s));let a,l;if(Array.isArray(s))if(s.length===2)a=s[0],l=s[1];else throw new TypeError(`Expected [key, value] tuple: ${s}`);else if(s&&s instanceof Object){let c=Object.keys(s);if(c.length===1)a=c[0],l=s[a];else throw new TypeError(`Expected tuple with one key, not ${c.length} keys`)}else a=s;r.items.push(wh.createPair(a,l,t))}return r}var lk={collection:"seq",default:!1,tag:"tag:yaml.org,2002:pairs",resolve:my,createNode:fy};Pa.createPairs=fy;Pa.pairs=lk;Pa.resolvePairs=my});var kh=M(Ph=>{"use strict";var gy=G(),xh=Gt(),Nn=Qt(),ck=Jt(),yy=ka(),Bi=class n extends ck.YAMLSeq{constructor(){super(),this.add=Nn.YAMLMap.prototype.add.bind(this),this.delete=Nn.YAMLMap.prototype.delete.bind(this),this.get=Nn.YAMLMap.prototype.get.bind(this),this.has=Nn.YAMLMap.prototype.has.bind(this),this.set=Nn.YAMLMap.prototype.set.bind(this),this.tag=n.tag}toJSON(e,t){if(!t)return super.toJSON(e);let i=new Map;t?.onCreate&&t.onCreate(i);for(let r of this.items){let o,s;if(gy.isPair(r)?(o=xh.toJS(r.key,"",t),s=xh.toJS(r.value,o,t)):o=xh.toJS(r,"",t),i.has(o))throw new Error("Ordered maps must not include duplicate keys");i.set(o,s)}return i}static from(e,t,i){let r=yy.createPairs(e,t,i),o=new this;return o.items=r.items,o}};Bi.tag="tag:yaml.org,2002:omap";var uk={collection:"seq",identify:n=>n instanceof Map,nodeClass:Bi,default:!1,tag:"tag:yaml.org,2002:omap",resolve(n,e){let t=yy.resolvePairs(n,e),i=[];for(let{key:r}of t.items)gy.isScalar(r)&&(i.includes(r.value)?e(`Ordered maps must not include duplicate keys: ${r.value}`):i.push(r.value));return Object.assign(new Bi,t)},createNode:(n,e,t)=>Bi.from(n,e,t)};Ph.YAMLOMap=Bi;Ph.omap=uk});var xy=M(Ah=>{"use strict";var by=ne();function Sy({value:n,source:e},t){return e&&(n?vy:wy).test.test(e)?e:n?t.options.trueStr:t.options.falseStr}var vy={identify:n=>n===!0,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:Y|y|[Yy]es|YES|[Tt]rue|TRUE|[Oo]n|ON)$/,resolve:()=>new by.Scalar(!0),stringify:Sy},wy={identify:n=>n===!1,default:!0,tag:"tag:yaml.org,2002:bool",test:/^(?:N|n|[Nn]o|NO|[Ff]alse|FALSE|[Oo]ff|OFF)$/,resolve:()=>new by.Scalar(!1),stringify:Sy};Ah.falseTag=wy;Ah.trueTag=vy});var Py=M(Aa=>{"use strict";var hk=ne(),Th=Pr(),dk={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^(?:[-+]?\.(?:inf|Inf|INF)|\.nan|\.NaN|\.NAN)$/,resolve:n=>n.slice(-3).toLowerCase()==="nan"?NaN:n[0]==="-"?Number.NEGATIVE_INFINITY:Number.POSITIVE_INFINITY,stringify:Th.stringifyNumber},pk={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"EXP",test:/^[-+]?(?:[0-9][0-9_]*)?(?:\.[0-9_]*)?[eE][-+]?[0-9]+$/,resolve:n=>parseFloat(n.replace(/_/g,"")),stringify(n){let e=Number(n.value);return isFinite(e)?e.toExponential():Th.stringifyNumber(n)}},mk={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",test:/^[-+]?(?:[0-9][0-9_]*)?\.[0-9_]*$/,resolve(n){let e=new hk.Scalar(parseFloat(n.replace(/_/g,""))),t=n.indexOf(".");if(t!==-1){let i=n.substring(t+1).replace(/_/g,"");i[i.length-1]==="0"&&(e.minFractionDigits=i.length)}return e},stringify:Th.stringifyNumber};Aa.float=mk;Aa.floatExp=pk;Aa.floatNaN=dk});var Ay=M(Rn=>{"use strict";var ky=Pr(),In=n=>typeof n=="bigint"||Number.isInteger(n);function Ta(n,e,t,{intAsBigInt:i}){let r=n[0];if((r==="-"||r==="+")&&(e+=1),n=n.substring(e).replace(/_/g,""),i){switch(t){case 2:n=`0b${n}`;break;case 8:n=`0o${n}`;break;case 16:n=`0x${n}`;break}let s=BigInt(n);return r==="-"?BigInt(-1)*s:s}let o=parseInt(n,t);return r==="-"?-1*o:o}function Ch(n,e,t){let{value:i}=n;if(In(i)){let r=i.toString(e);return i<0?"-"+t+r.substr(1):t+r}return ky.stringifyNumber(n)}var fk={identify:In,default:!0,tag:"tag:yaml.org,2002:int",format:"BIN",test:/^[-+]?0b[0-1_]+$/,resolve:(n,e,t)=>Ta(n,2,2,t),stringify:n=>Ch(n,2,"0b")},gk={identify:In,default:!0,tag:"tag:yaml.org,2002:int",format:"OCT",test:/^[-+]?0[0-7_]+$/,resolve:(n,e,t)=>Ta(n,1,8,t),stringify:n=>Ch(n,8,"0")},yk={identify:In,default:!0,tag:"tag:yaml.org,2002:int",test:/^[-+]?[0-9][0-9_]*$/,resolve:(n,e,t)=>Ta(n,0,10,t),stringify:ky.stringifyNumber},bk={identify:In,default:!0,tag:"tag:yaml.org,2002:int",format:"HEX",test:/^[-+]?0x[0-9a-fA-F_]+$/,resolve:(n,e,t)=>Ta(n,2,16,t),stringify:n=>Ch(n,16,"0x")};Rn.int=yk;Rn.intBin=fk;Rn.intHex=bk;Rn.intOct=gk});var Dh=M(Mh=>{"use strict";var Da=G(),Ca=Kt(),Ma=Qt(),Oi=class n extends Ma.YAMLMap{constructor(e){super(e),this.tag=n.tag}add(e){let t;Da.isPair(e)?t=e:e&&typeof e=="object"&&"key"in e&&"value"in e&&e.value===null?t=new Ca.Pair(e.key,null):t=new Ca.Pair(e,null),Ma.findPair(this.items,t.key)||this.items.push(t)}get(e,t){let i=Ma.findPair(this.items,e);return!t&&Da.isPair(i)?Da.isScalar(i.key)?i.key.value:i.key:i}set(e,t){if(typeof t!="boolean")throw new Error(`Expected boolean value for set(key, value) in a YAML set, not ${typeof t}`);let i=Ma.findPair(this.items,e);i&&!t?this.items.splice(this.items.indexOf(i),1):!i&&t&&this.items.push(new Ca.Pair(e))}toJSON(e,t){return super.toJSON(e,t,Set)}toString(e,t,i){if(!e)return JSON.stringify(this);if(this.hasAllNullValues(!0))return super.toString(Object.assign({},e,{allNullValues:!0}),t,i);throw new Error("Set items must all have null values")}static from(e,t,i){let{replacer:r}=i,o=new this(e);if(t&&Symbol.iterator in Object(t))for(let s of t)typeof r=="function"&&(s=r.call(t,s,s)),o.items.push(Ca.createPair(s,null,i));return o}};Oi.tag="tag:yaml.org,2002:set";var Sk={collection:"map",identify:n=>n instanceof Set,nodeClass:Oi,default:!1,tag:"tag:yaml.org,2002:set",createNode:(n,e,t)=>Oi.from(n,e,t),resolve(n,e){if(Da.isMap(n)){if(n.hasAllNullValues(!0))return Object.assign(new Oi,n);e("Set items must all have null values")}else e("Expected a mapping for this tag");return n}};Mh.YAMLSet=Oi;Mh.set=Sk});var Nh=M(Ea=>{"use strict";var vk=Pr();function Eh(n,e){let t=n[0],i=t==="-"||t==="+"?n.substring(1):n,r=s=>e?BigInt(s):Number(s),o=i.replace(/_/g,"").split(":").reduce((s,a)=>s*r(60)+r(a),r(0));return t==="-"?r(-1)*o:o}function Ty(n){let{value:e}=n,t=s=>s;if(typeof e=="bigint")t=s=>BigInt(s);else if(isNaN(e)||!isFinite(e))return vk.stringifyNumber(n);let i="";e<0&&(i="-",e*=t(-1));let r=t(60),o=[e%r];return e<60?o.unshift(0):(e=(e-o[0])/r,o.unshift(e%r),e>=60&&(e=(e-o[0])/r,o.unshift(e))),i+o.map(s=>String(s).padStart(2,"0")).join(":").replace(/000000\d*$/,"")}var wk={identify:n=>typeof n=="bigint"||Number.isInteger(n),default:!0,tag:"tag:yaml.org,2002:int",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+$/,resolve:(n,e,{intAsBigInt:t})=>Eh(n,t),stringify:Ty},xk={identify:n=>typeof n=="number",default:!0,tag:"tag:yaml.org,2002:float",format:"TIME",test:/^[-+]?[0-9][0-9_]*(?::[0-5]?[0-9])+\.[0-9_]*$/,resolve:n=>Eh(n,!1),stringify:Ty},Cy={identify:n=>n instanceof Date,default:!0,tag:"tag:yaml.org,2002:timestamp",test:RegExp("^([0-9]{4})-([0-9]{1,2})-([0-9]{1,2})(?:(?:t|T|[ \\t]+)([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}(\\.[0-9]+)?)(?:[ \\t]*(Z|[-+][012]?[0-9](?::[0-9]{2})?))?)?$"),resolve(n){let e=n.match(Cy.test);if(!e)throw new Error("!!timestamp expects a date, starting with yyyy-mm-dd");let[,t,i,r,o,s,a]=e.map(Number),l=e[7]?Number((e[7]+"00").substr(1,3)):0,c=Date.UTC(t,i-1,r,o||0,s||0,a||0,l),u=e[8];if(u&&u!=="Z"){let h=Eh(u,!1);Math.abs(h)<30&&(h*=60),c-=6e4*h}return new Date(c)},stringify:({value:n})=>n?.toISOString().replace(/(T00:00:00)?\.000Z$/,"")??""};Ea.floatTime=xk;Ea.intTime=wk;Ea.timestamp=Cy});var Ey=M(Dy=>{"use strict";var Pk=wr(),kk=ya(),Ak=xr(),Tk=Dn(),Ck=vh(),My=xy(),Ih=Py(),Na=Ay(),Mk=ca(),Dk=kh(),Ek=ka(),Nk=Dh(),Rh=Nh(),Ik=[Pk.map,Ak.seq,Tk.string,kk.nullTag,My.trueTag,My.falseTag,Na.intBin,Na.intOct,Na.int,Na.intHex,Ih.floatNaN,Ih.floatExp,Ih.float,Ck.binary,Mk.merge,Dk.omap,Ek.pairs,Nk.set,Rh.intTime,Rh.floatTime,Rh.timestamp];Dy.schema=Ik});var zy=M(Vh=>{"use strict";var By=wr(),Rk=ya(),Oy=xr(),Bk=Dn(),Ok=dh(),Bh=mh(),Oh=gh(),Vk=cy(),Lk=dy(),Vy=vh(),Bn=ca(),Ly=kh(),_y=ka(),Ny=Ey(),Fy=Dh(),Ia=Nh(),Iy=new Map([["core",Vk.schema],["failsafe",[By.map,Oy.seq,Bk.string]],["json",Lk.schema],["yaml11",Ny.schema],["yaml-1.1",Ny.schema]]),Ry={binary:Vy.binary,bool:Ok.boolTag,float:Bh.float,floatExp:Bh.floatExp,floatNaN:Bh.floatNaN,floatTime:Ia.floatTime,int:Oh.int,intHex:Oh.intHex,intOct:Oh.intOct,intTime:Ia.intTime,map:By.map,merge:Bn.merge,null:Rk.nullTag,omap:Ly.omap,pairs:_y.pairs,seq:Oy.seq,set:Fy.set,timestamp:Ia.timestamp},_k={"tag:yaml.org,2002:binary":Vy.binary,"tag:yaml.org,2002:merge":Bn.merge,"tag:yaml.org,2002:omap":Ly.omap,"tag:yaml.org,2002:pairs":_y.pairs,"tag:yaml.org,2002:set":Fy.set,"tag:yaml.org,2002:timestamp":Ia.timestamp};function Fk(n,e,t){let i=Iy.get(e);if(i&&!n)return t&&!i.includes(Bn.merge)?i.concat(Bn.merge):i.slice();let r=i;if(!r)if(Array.isArray(n))r=[];else{let o=Array.from(Iy.keys()).filter(s=>s!=="yaml11").map(s=>JSON.stringify(s)).join(", ");throw new Error(`Unknown schema "${e}"; use one of ${o} or define customTags array`)}if(Array.isArray(n))for(let o of n)r=r.concat(o);else typeof n=="function"&&(r=n(r.slice()));return t&&(r=r.concat(Bn.merge)),r.reduce((o,s)=>{let a=typeof s=="string"?Ry[s]:s;if(!a){let l=JSON.stringify(s),c=Object.keys(Ry).map(u=>JSON.stringify(u)).join(", ");throw new Error(`Unknown custom tag ${l}; use one of ${c}`)}return o.includes(a)||o.push(a),o},[])}Vh.coreKnownTags=_k;Vh.getTags=Fk});var Fh=M(Uy=>{"use strict";var Lh=G(),zk=wr(),Uk=xr(),Wk=Dn(),Ra=zy(),Hk=(n,e)=>n.key<e.key?-1:n.key>e.key?1:0,_h=class n{constructor({compat:e,customTags:t,merge:i,resolveKnownTags:r,schema:o,sortMapEntries:s,toStringDefaults:a}){this.compat=Array.isArray(e)?Ra.getTags(e,"compat"):e?Ra.getTags(null,e):null,this.name=typeof o=="string"&&o||"core",this.knownTags=r?Ra.coreKnownTags:{},this.tags=Ra.getTags(t,this.name,i),this.toStringOptions=a??null,Object.defineProperty(this,Lh.MAP,{value:zk.map}),Object.defineProperty(this,Lh.SCALAR,{value:Wk.string}),Object.defineProperty(this,Lh.SEQ,{value:Uk.seq}),this.sortMapEntries=typeof s=="function"?s:s===!0?Hk:null}clone(){let e=Object.create(n.prototype,Object.getOwnPropertyDescriptors(this));return e.tags=this.tags.slice(),e}};Uy.Schema=_h});var Hy=M(Wy=>{"use strict";var qk=G(),zh=Tn(),On=xn();function Gk(n,e){let t=[],i=e.directives===!0;if(e.directives!==!1&&n.directives){let l=n.directives.toString(n);l?(t.push(l),i=!0):n.directives.docStart&&(i=!0)}i&&t.push("---");let r=zh.createStringifyContext(n,e),{commentString:o}=r.options;if(n.commentBefore){t.length!==1&&t.unshift("");let l=o(n.commentBefore);t.unshift(On.indentComment(l,""))}let s=!1,a=null;if(n.contents){if(qk.isNode(n.contents)){if(n.contents.spaceBefore&&i&&t.push(""),n.contents.commentBefore){let u=o(n.contents.commentBefore);t.push(On.indentComment(u,""))}r.forceBlockIndent=!!n.comment,a=n.contents.comment}let l=a?void 0:()=>s=!0,c=zh.stringify(n.contents,r,()=>a=null,l);a&&(c+=On.lineComment(c,"",o(a))),(c[0]==="|"||c[0]===">")&&t[t.length-1]==="---"?t[t.length-1]=`--- ${c}`:t.push(c)}else t.push(zh.stringify(n.contents,r));if(n.directives?.docEnd)if(n.comment){let l=o(n.comment);l.includes(`
56
+ `)?(t.push("..."),t.push(On.indentComment(l,""))):t.push(`... ${l}`)}else t.push("...");else{let l=n.comment;l&&s&&(l=l.replace(/^\n+/,"")),l&&((!s||a)&&t[t.length-1]!==""&&t.push(""),t.push(On.indentComment(o(l),"")))}return t.join(`
57
+ `)+`
58
+ `}Wy.stringifyDocument=Gk});var Vn=M(qy=>{"use strict";var jk=vn(),kr=Zs(),Re=G(),$k=Kt(),Yk=Gt(),Kk=Fh(),Xk=Hy(),Uh=Ks(),Qk=Gu(),Jk=wn(),Wh=qu(),Hh=class n{constructor(e,t,i){this.commentBefore=null,this.comment=null,this.errors=[],this.warnings=[],Object.defineProperty(this,Re.NODE_TYPE,{value:Re.DOC});let r=null;typeof t=="function"||Array.isArray(t)?r=t:i===void 0&&t&&(i=t,t=void 0);let o=Object.assign({intAsBigInt:!1,keepSourceTokens:!1,logLevel:"warn",prettyErrors:!0,strict:!0,stringKeys:!1,uniqueKeys:!0,version:"1.2"},i);this.options=o;let{version:s}=o;i?._directives?(this.directives=i._directives.atDocument(),this.directives.yaml.explicit&&(s=this.directives.yaml.version)):this.directives=new Wh.Directives({version:s}),this.setSchema(s,i),this.contents=e===void 0?null:this.createNode(e,r,i)}clone(){let e=Object.create(n.prototype,{[Re.NODE_TYPE]:{value:Re.DOC}});return e.commentBefore=this.commentBefore,e.comment=this.comment,e.errors=this.errors.slice(),e.warnings=this.warnings.slice(),e.options=Object.assign({},this.options),this.directives&&(e.directives=this.directives.clone()),e.schema=this.schema.clone(),e.contents=Re.isNode(this.contents)?this.contents.clone(e.schema):this.contents,this.range&&(e.range=this.range.slice()),e}add(e){Ar(this.contents)&&this.contents.add(e)}addIn(e,t){Ar(this.contents)&&this.contents.addIn(e,t)}createAlias(e,t){if(!e.anchor){let i=Uh.anchorNames(this);e.anchor=!t||i.has(t)?Uh.findNewAnchor(t||"a",i):t}return new jk.Alias(e.anchor)}createNode(e,t,i){let r;if(typeof t=="function")e=t.call({"":e},"",e),r=t;else if(Array.isArray(t)){let g=b=>typeof b=="number"||b instanceof String||b instanceof Number,y=t.filter(g).map(String);y.length>0&&(t=t.concat(y)),r=t}else i===void 0&&t&&(i=t,t=void 0);let{aliasDuplicateObjects:o,anchorPrefix:s,flow:a,keepUndefined:l,onTagObj:c,tag:u}=i??{},{onAnchor:h,setAnchors:d,sourceObjects:p}=Uh.createNodeAnchors(this,s||"a"),f={aliasDuplicateObjects:o??!0,keepUndefined:l??!1,onAnchor:h,onTagObj:c,replacer:r,schema:this.schema,sourceObjects:p},m=Jk.createNode(e,u,f);return a&&Re.isCollection(m)&&(m.flow=!0),d(),m}createPair(e,t,i={}){let r=this.createNode(e,null,i),o=this.createNode(t,null,i);return new $k.Pair(r,o)}delete(e){return Ar(this.contents)?this.contents.delete(e):!1}deleteIn(e){return kr.isEmptyPath(e)?this.contents==null?!1:(this.contents=null,!0):Ar(this.contents)?this.contents.deleteIn(e):!1}get(e,t){return Re.isCollection(this.contents)?this.contents.get(e,t):void 0}getIn(e,t){return kr.isEmptyPath(e)?!t&&Re.isScalar(this.contents)?this.contents.value:this.contents:Re.isCollection(this.contents)?this.contents.getIn(e,t):void 0}has(e){return Re.isCollection(this.contents)?this.contents.has(e):!1}hasIn(e){return kr.isEmptyPath(e)?this.contents!==void 0:Re.isCollection(this.contents)?this.contents.hasIn(e):!1}set(e,t){this.contents==null?this.contents=kr.collectionFromPath(this.schema,[e],t):Ar(this.contents)&&this.contents.set(e,t)}setIn(e,t){kr.isEmptyPath(e)?this.contents=t:this.contents==null?this.contents=kr.collectionFromPath(this.schema,Array.from(e),t):Ar(this.contents)&&this.contents.setIn(e,t)}setSchema(e,t={}){typeof e=="number"&&(e=String(e));let i;switch(e){case"1.1":this.directives?this.directives.yaml.version="1.1":this.directives=new Wh.Directives({version:"1.1"}),i={resolveKnownTags:!1,schema:"yaml-1.1"};break;case"1.2":case"next":this.directives?this.directives.yaml.version=e:this.directives=new Wh.Directives({version:e}),i={resolveKnownTags:!0,schema:"core"};break;case null:this.directives&&delete this.directives,i=null;break;default:{let r=JSON.stringify(e);throw new Error(`Expected '1.1', '1.2' or null as first argument, but found: ${r}`)}}if(t.schema instanceof Object)this.schema=t.schema;else if(i)this.schema=new Kk.Schema(Object.assign(i,t));else throw new Error("With a null YAML version, the { schema: Schema } option is required")}toJS({json:e,jsonArg:t,mapAsMap:i,maxAliasCount:r,onAnchor:o,reviver:s}={}){let a={anchors:new Map,doc:this,keep:!e,mapAsMap:i===!0,mapKeyWarned:!1,maxAliasCount:typeof r=="number"?r:100},l=Yk.toJS(this.contents,t??"",a);if(typeof o=="function")for(let{count:c,res:u}of a.anchors.values())o(u,c);return typeof s=="function"?Qk.applyReviver(s,{"":l},"",l):l}toJSON(e,t){return this.toJS({json:!0,jsonArg:e,mapAsMap:!1,onAnchor:t})}toString(e={}){if(this.errors.length>0)throw new Error("Document with errors cannot be stringified");if("indent"in e&&(!Number.isInteger(e.indent)||Number(e.indent)<=0)){let t=JSON.stringify(e.indent);throw new Error(`"indent" option must be a positive integer, not ${t}`)}return Xk.stringifyDocument(this,e)}};function Ar(n){if(Re.isCollection(n))return!0;throw new Error("Expected a YAML collection as document contents")}qy.Document=Hh});var Fn=M(_n=>{"use strict";var Ln=class extends Error{constructor(e,t,i,r){super(),this.name=e,this.code=i,this.message=r,this.pos=t}},qh=class extends Ln{constructor(e,t,i){super("YAMLParseError",e,t,i)}},Gh=class extends Ln{constructor(e,t,i){super("YAMLWarning",e,t,i)}},Zk=(n,e)=>t=>{if(t.pos[0]===-1)return;t.linePos=t.pos.map(a=>e.linePos(a));let{line:i,col:r}=t.linePos[0];t.message+=` at line ${i}, column ${r}`;let o=r-1,s=n.substring(e.lineStarts[i-1],e.lineStarts[i]).replace(/[\n\r]+$/,"");if(o>=60&&s.length>80){let a=Math.min(o-39,s.length-79);s="\u2026"+s.substring(a),o-=a-1}if(s.length>80&&(s=s.substring(0,79)+"\u2026"),i>1&&/^ *$/.test(s.substring(0,o))){let a=n.substring(e.lineStarts[i-2],e.lineStarts[i-1]);a.length>80&&(a=a.substring(0,79)+`\u2026
59
+ `),s=a+s}if(/[^ ]/.test(s)){let a=1,l=t.linePos[1];l?.line===i&&l.col>r&&(a=Math.max(1,Math.min(l.col-r,80-o)));let c=" ".repeat(o)+"^".repeat(a);t.message+=`:
60
+
61
+ ${s}
62
+ ${c}
63
+ `}};_n.YAMLError=Ln;_n.YAMLParseError=qh;_n.YAMLWarning=Gh;_n.prettifyError=Zk});var zn=M(Gy=>{"use strict";function eA(n,{flow:e,indicator:t,next:i,offset:r,onError:o,parentIndent:s,startOnNewline:a}){let l=!1,c=a,u=a,h="",d="",p=!1,f=!1,m=null,g=null,y=null,b=null,v=null,w=null,k=null;for(let A of n)switch(f&&(A.type!=="space"&&A.type!=="newline"&&A.type!=="comma"&&o(A.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),f=!1),m&&(c&&A.type!=="comment"&&A.type!=="newline"&&o(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),m=null),A.type){case"space":!e&&(t!=="doc-start"||i?.type!=="flow-collection")&&A.source.includes(" ")&&(m=A),u=!0;break;case"comment":{u||o(A,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let _=A.source.substring(1)||" ";h?h+=d+_:h=_,d="",c=!1;break}case"newline":c?h?h+=A.source:(!w||t!=="seq-item-ind")&&(l=!0):d+=A.source,c=!0,p=!0,(g||y)&&(b=A),u=!0;break;case"anchor":g&&o(A,"MULTIPLE_ANCHORS","A node can have at most one anchor"),A.source.endsWith(":")&&o(A.offset+A.source.length-1,"BAD_ALIAS","Anchor ending in : is ambiguous",!0),g=A,k??(k=A.offset),c=!1,u=!1,f=!0;break;case"tag":{y&&o(A,"MULTIPLE_TAGS","A node can have at most one tag"),y=A,k??(k=A.offset),c=!1,u=!1,f=!0;break}case t:(g||y)&&o(A,"BAD_PROP_ORDER",`Anchors and tags must be after the ${A.source} indicator`),w&&o(A,"UNEXPECTED_TOKEN",`Unexpected ${A.source} in ${e??"collection"}`),w=A,c=t==="seq-item-ind"||t==="explicit-key-ind",u=!1;break;case"comma":if(e){v&&o(A,"UNEXPECTED_TOKEN",`Unexpected , in ${e}`),v=A,c=!1,u=!1;break}default:o(A,"UNEXPECTED_TOKEN",`Unexpected ${A.type} token`),c=!1,u=!1}let T=n[n.length-1],E=T?T.offset+T.source.length:r;return f&&i&&i.type!=="space"&&i.type!=="newline"&&i.type!=="comma"&&(i.type!=="scalar"||i.source!=="")&&o(i.offset,"MISSING_CHAR","Tags and anchors must be separated from the next token by white space"),m&&(c&&m.indent<=s||i?.type==="block-map"||i?.type==="block-seq")&&o(m,"TAB_AS_INDENT","Tabs are not allowed as indentation"),{comma:v,found:w,spaceBefore:l,comment:h,hasNewline:p,anchor:g,tag:y,newlineAfterProp:b,end:E,start:k??E}}Gy.resolveProps=eA});var Ba=M(jy=>{"use strict";function jh(n){if(!n)return null;switch(n.type){case"alias":case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":if(n.source.includes(`
64
+ `))return!0;if(n.end){for(let e of n.end)if(e.type==="newline")return!0}return!1;case"flow-collection":for(let e of n.items){for(let t of e.start)if(t.type==="newline")return!0;if(e.sep){for(let t of e.sep)if(t.type==="newline")return!0}if(jh(e.key)||jh(e.value))return!0}return!1;default:return!0}}jy.containsNewline=jh});var $h=M($y=>{"use strict";var tA=Ba();function iA(n,e,t){if(e?.type==="flow-collection"){let i=e.end[0];i.indent===n&&(i.source==="]"||i.source==="}")&&tA.containsNewline(e)&&t(i,"BAD_INDENT","Flow end indicator should be more indented than parent",!0)}}$y.flowIndentCheck=iA});var Yh=M(Ky=>{"use strict";var Yy=G();function rA(n,e,t){let{uniqueKeys:i}=n.options;if(i===!1)return!1;let r=typeof i=="function"?i:(o,s)=>o===s||Yy.isScalar(o)&&Yy.isScalar(s)&&o.value===s.value;return e.some(o=>r(o.key,t))}Ky.mapIncludes=rA});var tb=M(eb=>{"use strict";var Xy=Kt(),nA=Qt(),Qy=zn(),oA=Ba(),Jy=$h(),sA=Yh(),Zy="All mapping items must start at the same column";function aA({composeNode:n,composeEmptyNode:e},t,i,r,o){let s=o?.nodeClass??nA.YAMLMap,a=new s(t.schema);t.atRoot&&(t.atRoot=!1);let l=i.offset,c=null;for(let u of i.items){let{start:h,key:d,sep:p,value:f}=u,m=Qy.resolveProps(h,{indicator:"explicit-key-ind",next:d??p?.[0],offset:l,onError:r,parentIndent:i.indent,startOnNewline:!0}),g=!m.found;if(g){if(d&&(d.type==="block-seq"?r(l,"BLOCK_AS_IMPLICIT_KEY","A block sequence may not be used as an implicit map key"):"indent"in d&&d.indent!==i.indent&&r(l,"BAD_INDENT",Zy)),!m.anchor&&!m.tag&&!p){c=m.end,m.comment&&(a.comment?a.comment+=`
65
+ `+m.comment:a.comment=m.comment);continue}(m.newlineAfterProp||oA.containsNewline(d))&&r(d??h[h.length-1],"MULTILINE_IMPLICIT_KEY","Implicit keys need to be on a single line")}else m.found?.indent!==i.indent&&r(l,"BAD_INDENT",Zy);t.atKey=!0;let y=m.end,b=d?n(t,d,m,r):e(t,y,h,null,m,r);t.schema.compat&&Jy.flowIndentCheck(i.indent,d,r),t.atKey=!1,sA.mapIncludes(t,a.items,b)&&r(y,"DUPLICATE_KEY","Map keys must be unique");let v=Qy.resolveProps(p??[],{indicator:"map-value-ind",next:f,offset:b.range[2],onError:r,parentIndent:i.indent,startOnNewline:!d||d.type==="block-scalar"});if(l=v.end,v.found){g&&(f?.type==="block-map"&&!v.hasNewline&&r(l,"BLOCK_AS_IMPLICIT_KEY","Nested mappings are not allowed in compact mappings"),t.options.strict&&m.start<v.found.offset-1024&&r(b.range,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit block mapping key"));let w=f?n(t,f,v,r):e(t,l,p,null,v,r);t.schema.compat&&Jy.flowIndentCheck(i.indent,f,r),l=w.range[2];let k=new Xy.Pair(b,w);t.options.keepSourceTokens&&(k.srcToken=u),a.items.push(k)}else{g&&r(b.range,"MISSING_CHAR","Implicit map keys need to be followed by map values"),v.comment&&(b.comment?b.comment+=`
66
+ `+v.comment:b.comment=v.comment);let w=new Xy.Pair(b);t.options.keepSourceTokens&&(w.srcToken=u),a.items.push(w)}}return c&&c<l&&r(c,"IMPOSSIBLE","Map comment with trailing content"),a.range=[i.offset,l,c??l],a}eb.resolveBlockMap=aA});var rb=M(ib=>{"use strict";var lA=Jt(),cA=zn(),uA=$h();function hA({composeNode:n,composeEmptyNode:e},t,i,r,o){let s=o?.nodeClass??lA.YAMLSeq,a=new s(t.schema);t.atRoot&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let l=i.offset,c=null;for(let{start:u,value:h}of i.items){let d=cA.resolveProps(u,{indicator:"seq-item-ind",next:h,offset:l,onError:r,parentIndent:i.indent,startOnNewline:!0});if(!d.found)if(d.anchor||d.tag||h)h?.type==="block-seq"?r(d.end,"BAD_INDENT","All sequence items must start at the same column"):r(l,"MISSING_CHAR","Sequence item without - indicator");else{c=d.end,d.comment&&(a.comment=d.comment);continue}let p=h?n(t,h,d,r):e(t,d.end,u,null,d,r);t.schema.compat&&uA.flowIndentCheck(i.indent,h,r),l=p.range[2],a.items.push(p)}return a.range=[i.offset,l,c??l],a}ib.resolveBlockSeq=hA});var Tr=M(nb=>{"use strict";function dA(n,e,t,i){let r="";if(n){let o=!1,s="";for(let a of n){let{source:l,type:c}=a;switch(c){case"space":o=!0;break;case"comment":{t&&!o&&i(a,"MISSING_CHAR","Comments must be separated from other tokens by white space characters");let u=l.substring(1)||" ";r?r+=s+u:r=u,s="";break}case"newline":r&&(s+=l),o=!0;break;default:i(a,"UNEXPECTED_TOKEN",`Unexpected ${c} at node end`)}e+=l.length}}return{comment:r,offset:e}}nb.resolveEnd=dA});var lb=M(ab=>{"use strict";var pA=G(),mA=Kt(),ob=Qt(),fA=Jt(),gA=Tr(),sb=zn(),yA=Ba(),bA=Yh(),Kh="Block collections are not allowed within flow collections",Xh=n=>n&&(n.type==="block-map"||n.type==="block-seq");function SA({composeNode:n,composeEmptyNode:e},t,i,r,o){let s=i.start.source==="{",a=s?"flow map":"flow sequence",l=o?.nodeClass??(s?ob.YAMLMap:fA.YAMLSeq),c=new l(t.schema);c.flow=!0;let u=t.atRoot;u&&(t.atRoot=!1),t.atKey&&(t.atKey=!1);let h=i.offset+i.start.source.length;for(let g=0;g<i.items.length;++g){let y=i.items[g],{start:b,key:v,sep:w,value:k}=y,T=sb.resolveProps(b,{flow:a,indicator:"explicit-key-ind",next:v??w?.[0],offset:h,onError:r,parentIndent:i.indent,startOnNewline:!1});if(!T.found){if(!T.anchor&&!T.tag&&!w&&!k){g===0&&T.comma?r(T.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`):g<i.items.length-1&&r(T.start,"UNEXPECTED_TOKEN",`Unexpected empty item in ${a}`),T.comment&&(c.comment?c.comment+=`
67
+ `+T.comment:c.comment=T.comment),h=T.end;continue}!s&&t.options.strict&&yA.containsNewline(v)&&r(v,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line")}if(g===0)T.comma&&r(T.comma,"UNEXPECTED_TOKEN",`Unexpected , in ${a}`);else if(T.comma||r(T.start,"MISSING_CHAR",`Missing , between ${a} items`),T.comment){let E="";e:for(let A of b)switch(A.type){case"comma":case"space":break;case"comment":E=A.source.substring(1);break e;default:break e}if(E){let A=c.items[c.items.length-1];pA.isPair(A)&&(A=A.value??A.key),A.comment?A.comment+=`
68
+ `+E:A.comment=E,T.comment=T.comment.substring(E.length+1)}}if(!s&&!w&&!T.found){let E=k?n(t,k,T,r):e(t,T.end,w,null,T,r);c.items.push(E),h=E.range[2],Xh(k)&&r(E.range,"BLOCK_IN_FLOW",Kh)}else{t.atKey=!0;let E=T.end,A=v?n(t,v,T,r):e(t,E,b,null,T,r);Xh(v)&&r(A.range,"BLOCK_IN_FLOW",Kh),t.atKey=!1;let _=sb.resolveProps(w??[],{flow:a,indicator:"map-value-ind",next:k,offset:A.range[2],onError:r,parentIndent:i.indent,startOnNewline:!1});if(_.found){if(!s&&!T.found&&t.options.strict){if(w)for(let ee of w){if(ee===_.found)break;if(ee.type==="newline"){r(ee,"MULTILINE_IMPLICIT_KEY","Implicit keys of flow sequence pairs need to be on a single line");break}}T.start<_.found.offset-1024&&r(_.found,"KEY_OVER_1024_CHARS","The : indicator must be at most 1024 chars after the start of an implicit flow sequence key")}}else k&&("source"in k&&k.source?.[0]===":"?r(k,"MISSING_CHAR",`Missing space after : in ${a}`):r(_.start,"MISSING_CHAR",`Missing , or : between ${a} items`));let J=k?n(t,k,_,r):_.found?e(t,_.end,w,null,_,r):null;J?Xh(k)&&r(J.range,"BLOCK_IN_FLOW",Kh):_.comment&&(A.comment?A.comment+=`
69
+ `+_.comment:A.comment=_.comment);let re=new mA.Pair(A,J);if(t.options.keepSourceTokens&&(re.srcToken=y),s){let ee=c;bA.mapIncludes(t,ee.items,A)&&r(E,"DUPLICATE_KEY","Map keys must be unique"),ee.items.push(re)}else{let ee=new ob.YAMLMap(t.schema);ee.flow=!0,ee.items.push(re);let Oe=(J??A).range;ee.range=[A.range[0],Oe[1],Oe[2]],c.items.push(ee)}h=J?J.range[2]:_.end}}let d=s?"}":"]",[p,...f]=i.end,m=h;if(p?.source===d)m=p.offset+p.source.length;else{let g=a[0].toUpperCase()+a.substring(1),y=u?`${g} must end with a ${d}`:`${g} in block collection must be sufficiently indented and end with a ${d}`;r(h,u?"MISSING_CHAR":"BAD_INDENT",y),p&&p.source.length!==1&&f.unshift(p)}if(f.length>0){let g=gA.resolveEnd(f,m,t.options.strict,r);g.comment&&(c.comment?c.comment+=`
70
+ `+g.comment:c.comment=g.comment),c.range=[i.offset,m,g.offset]}else c.range=[i.offset,m,m];return c}ab.resolveFlowCollection=SA});var ub=M(cb=>{"use strict";var vA=G(),wA=ne(),xA=Qt(),PA=Jt(),kA=tb(),AA=rb(),TA=lb();function Qh(n,e,t,i,r,o){let s=t.type==="block-map"?kA.resolveBlockMap(n,e,t,i,o):t.type==="block-seq"?AA.resolveBlockSeq(n,e,t,i,o):TA.resolveFlowCollection(n,e,t,i,o),a=s.constructor;return r==="!"||r===a.tagName?(s.tag=a.tagName,s):(r&&(s.tag=r),s)}function CA(n,e,t,i,r){let o=i.tag,s=o?e.directives.tagName(o.source,d=>r(o,"TAG_RESOLVE_FAILED",d)):null;if(t.type==="block-seq"){let{anchor:d,newlineAfterProp:p}=i,f=d&&o?d.offset>o.offset?d:o:d??o;f&&(!p||p.offset<f.offset)&&r(f,"MISSING_CHAR","Missing newline after block sequence props")}let a=t.type==="block-map"?"map":t.type==="block-seq"?"seq":t.start.source==="{"?"map":"seq";if(!o||!s||s==="!"||s===xA.YAMLMap.tagName&&a==="map"||s===PA.YAMLSeq.tagName&&a==="seq")return Qh(n,e,t,r,s);let l=e.schema.tags.find(d=>d.tag===s&&d.collection===a);if(!l){let d=e.schema.knownTags[s];if(d?.collection===a)e.schema.tags.push(Object.assign({},d,{default:!1})),l=d;else return d?r(o,"BAD_COLLECTION_TYPE",`${d.tag} used for ${a} collection, but expects ${d.collection??"scalar"}`,!0):r(o,"TAG_RESOLVE_FAILED",`Unresolved tag: ${s}`,!0),Qh(n,e,t,r,s)}let c=Qh(n,e,t,r,s,l),u=l.resolve?.(c,d=>r(o,"TAG_RESOLVE_FAILED",d),e.options)??c,h=vA.isNode(u)?u:new wA.Scalar(u);return h.range=c.range,h.tag=s,l?.format&&(h.format=l.format),h}cb.composeCollection=CA});var Zh=M(hb=>{"use strict";var Jh=ne();function MA(n,e,t){let i=e.offset,r=DA(e,n.options.strict,t);if(!r)return{value:"",type:null,comment:"",range:[i,i,i]};let o=r.mode===">"?Jh.Scalar.BLOCK_FOLDED:Jh.Scalar.BLOCK_LITERAL,s=e.source?EA(e.source):[],a=s.length;for(let m=s.length-1;m>=0;--m){let g=s[m][1];if(g===""||g==="\r")a=m;else break}if(a===0){let m=r.chomp==="+"&&s.length>0?`
71
+ `.repeat(Math.max(1,s.length-1)):"",g=i+r.length;return e.source&&(g+=e.source.length),{value:m,type:o,comment:r.comment,range:[i,g,g]}}let l=e.indent+r.indent,c=e.offset+r.length,u=0;for(let m=0;m<a;++m){let[g,y]=s[m];if(y===""||y==="\r")r.indent===0&&g.length>l&&(l=g.length);else{g.length<l&&t(c+g.length,"MISSING_CHAR","Block scalars with more-indented leading empty lines must use an explicit indentation indicator"),r.indent===0&&(l=g.length),u=m,l===0&&!n.atRoot&&t(c,"BAD_INDENT","Block scalar values in collections must be indented");break}c+=g.length+y.length+1}for(let m=s.length-1;m>=a;--m)s[m][0].length>l&&(a=m+1);let h="",d="",p=!1;for(let m=0;m<u;++m)h+=s[m][0].slice(l)+`
72
+ `;for(let m=u;m<a;++m){let[g,y]=s[m];c+=g.length+y.length+1;let b=y[y.length-1]==="\r";if(b&&(y=y.slice(0,-1)),y&&g.length<l){let w=`Block scalar lines must not be less indented than their ${r.indent?"explicit indentation indicator":"first line"}`;t(c-y.length-(b?2:1),"BAD_INDENT",w),g=""}o===Jh.Scalar.BLOCK_LITERAL?(h+=d+g.slice(l)+y,d=`
73
+ `):g.length>l||y[0]===" "?(d===" "?d=`
74
+ `:!p&&d===`
75
+ `&&(d=`
76
+
77
+ `),h+=d+g.slice(l)+y,d=`
78
+ `,p=!0):y===""?d===`
79
+ `?h+=`
80
+ `:d=`
81
+ `:(h+=d+y,d=" ",p=!1)}switch(r.chomp){case"-":break;case"+":for(let m=a;m<s.length;++m)h+=`
82
+ `+s[m][0].slice(l);h[h.length-1]!==`
83
+ `&&(h+=`
84
+ `);break;default:h+=`
85
+ `}let f=i+r.length+e.source.length;return{value:h,type:o,comment:r.comment,range:[i,f,f]}}function DA({offset:n,props:e},t,i){if(e[0].type!=="block-scalar-header")return i(e[0],"IMPOSSIBLE","Block scalar header not found"),null;let{source:r}=e[0],o=r[0],s=0,a="",l=-1;for(let d=1;d<r.length;++d){let p=r[d];if(!a&&(p==="-"||p==="+"))a=p;else{let f=Number(p);!s&&f?s=f:l===-1&&(l=n+d)}}l!==-1&&i(l,"UNEXPECTED_TOKEN",`Block scalar header includes extra characters: ${r}`);let c=!1,u="",h=r.length;for(let d=1;d<e.length;++d){let p=e[d];switch(p.type){case"space":c=!0;case"newline":h+=p.source.length;break;case"comment":t&&!c&&i(p,"MISSING_CHAR","Comments must be separated from other tokens by white space characters"),h+=p.source.length,u=p.source.substring(1);break;case"error":i(p,"UNEXPECTED_TOKEN",p.message),h+=p.source.length;break;default:{let f=`Unexpected token in block scalar header: ${p.type}`;i(p,"UNEXPECTED_TOKEN",f);let m=p.source;m&&typeof m=="string"&&(h+=m.length)}}}return{mode:o,indent:s,chomp:a,comment:u,length:h}}function EA(n){let e=n.split(/\n( *)/),t=e[0],i=t.match(/^( *)/),o=[i?.[1]?[i[1],t.slice(i[1].length)]:["",t]];for(let s=1;s<e.length;s+=2)o.push([e[s],e[s+1]]);return o}hb.resolveBlockScalar=MA});var td=M(pb=>{"use strict";var ed=ne(),NA=Tr();function IA(n,e,t){let{offset:i,type:r,source:o,end:s}=n,a,l,c=(d,p,f)=>t(i+d,p,f);switch(r){case"scalar":a=ed.Scalar.PLAIN,l=RA(o,c);break;case"single-quoted-scalar":a=ed.Scalar.QUOTE_SINGLE,l=BA(o,c);break;case"double-quoted-scalar":a=ed.Scalar.QUOTE_DOUBLE,l=OA(o,c);break;default:return t(n,"UNEXPECTED_TOKEN",`Expected a flow scalar value, but found: ${r}`),{value:"",type:null,comment:"",range:[i,i+o.length,i+o.length]}}let u=i+o.length,h=NA.resolveEnd(s,u,e,t);return{value:l,type:a,comment:h.comment,range:[i,u,h.offset]}}function RA(n,e){let t="";switch(n[0]){case" ":t="a tab character";break;case",":t="flow indicator character ,";break;case"%":t="directive indicator character %";break;case"|":case">":{t=`block scalar indicator ${n[0]}`;break}case"@":case"`":{t=`reserved character ${n[0]}`;break}}return t&&e(0,"BAD_SCALAR_START",`Plain value cannot start with ${t}`),db(n)}function BA(n,e){return(n[n.length-1]!=="'"||n.length===1)&&e(n.length,"MISSING_CHAR","Missing closing 'quote"),db(n.slice(1,-1)).replace(/''/g,"'")}function db(n){let e=/(.*?)\r?\n/sy,t=e.exec(n);if(!t)return n;let i,r;try{i=new RegExp("(?<![ ])[ ]+$"),r=new RegExp("^[ ]+|(?<![ ])[ ]+$","g")}catch{i=/[ \t]+$/,r=/^[ \t]+|[ \t]+$/g}let o=t[1].replace(i,""),s=" ",a=e.lastIndex;for(;t=e.exec(n);){let c=t[1].replace(r,"");c===""?s===`
86
+ `?o+=s:s=`
87
+ `:(o+=s+c,s=" "),a=e.lastIndex}let l=/[ \t]*(.*)/sy;return l.lastIndex=a,t=l.exec(n),o+s+(t?.[1]??"")}function OA(n,e){let t="";for(let i=1;i<n.length-1;++i){let r=n[i];if(!(r==="\r"&&n[i+1]===`
88
+ `))if(r===`
89
+ `){let{fold:o,offset:s}=VA(n,i);t+=o,i=s}else if(r==="\\"){let o=n[++i],s=LA[o];if(s)t+=s;else if(o===`
90
+ `)for(o=n[i+1];o===" "||o===" ";)o=n[++i+1];else if(o==="\r"&&n[i+1]===`
91
+ `)for(o=n[++i+1];o===" "||o===" ";)o=n[++i+1];else if(o==="x"||o==="u"||o==="U"){let a=o==="x"?2:o==="u"?4:8;t+=_A(n,i+1,a,e),i+=a}else{let a=n.substr(i-1,2);e(i-1,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),t+=a}}else if(r===" "||r===" "){let o=i,s=n[i+1];for(;s===" "||s===" ";)s=n[++i+1];s!==`
92
+ `&&!(s==="\r"&&n[i+2]===`
93
+ `)&&(t+=i>o?n.slice(o,i+1):r)}else t+=r}return(n[n.length-1]!=='"'||n.length===1)&&e(n.length,"MISSING_CHAR",'Missing closing "quote'),t}function VA(n,e){let t="",i=n[e+1];for(;(i===" "||i===" "||i===`
94
+ `||i==="\r")&&!(i==="\r"&&n[e+2]!==`
95
+ `);)i===`
96
+ `&&(t+=`
97
+ `),e+=1,i=n[e+1];return t||(t=" "),{fold:t,offset:e}}var LA={0:"\0",a:"\x07",b:"\b",e:"\x1B",f:"\f",n:`
98
+ `,r:"\r",t:" ",v:"\v",N:"\x85",_:"\xA0",L:"\u2028",P:"\u2029"," ":" ",'"':'"',"/":"/","\\":"\\"," ":" "};function _A(n,e,t,i){let r=n.substr(e,t),s=r.length===t&&/^[0-9a-fA-F]+$/.test(r)?parseInt(r,16):NaN;try{return String.fromCodePoint(s)}catch{let a=n.substr(e-2,t+2);return i(e-2,"BAD_DQ_ESCAPE",`Invalid escape sequence ${a}`),a}}pb.resolveFlowScalar=IA});var gb=M(fb=>{"use strict";var Vi=G(),mb=ne(),FA=Zh(),zA=td();function UA(n,e,t,i){let{value:r,type:o,comment:s,range:a}=e.type==="block-scalar"?FA.resolveBlockScalar(n,e,i):zA.resolveFlowScalar(e,n.options.strict,i),l=t?n.directives.tagName(t.source,h=>i(t,"TAG_RESOLVE_FAILED",h)):null,c;n.options.stringKeys&&n.atKey?c=n.schema[Vi.SCALAR]:l?c=WA(n.schema,r,l,t,i):e.type==="scalar"?c=HA(n,r,e,i):c=n.schema[Vi.SCALAR];let u;try{let h=c.resolve(r,d=>i(t??e,"TAG_RESOLVE_FAILED",d),n.options);u=Vi.isScalar(h)?h:new mb.Scalar(h)}catch(h){let d=h instanceof Error?h.message:String(h);i(t??e,"TAG_RESOLVE_FAILED",d),u=new mb.Scalar(r)}return u.range=a,u.source=r,o&&(u.type=o),l&&(u.tag=l),c.format&&(u.format=c.format),s&&(u.comment=s),u}function WA(n,e,t,i,r){if(t==="!")return n[Vi.SCALAR];let o=[];for(let a of n.tags)if(!a.collection&&a.tag===t)if(a.default&&a.test)o.push(a);else return a;for(let a of o)if(a.test?.test(e))return a;let s=n.knownTags[t];return s&&!s.collection?(n.tags.push(Object.assign({},s,{default:!1,test:void 0})),s):(r(i,"TAG_RESOLVE_FAILED",`Unresolved tag: ${t}`,t!=="tag:yaml.org,2002:str"),n[Vi.SCALAR])}function HA({atKey:n,directives:e,schema:t},i,r,o){let s=t.tags.find(a=>(a.default===!0||n&&a.default==="key")&&a.test?.test(i))||t[Vi.SCALAR];if(t.compat){let a=t.compat.find(l=>l.default&&l.test?.test(i))??t[Vi.SCALAR];if(s.tag!==a.tag){let l=e.tagString(s.tag),c=e.tagString(a.tag),u=`Value may be parsed as either ${l} or ${c}`;o(r,"TAG_RESOLVE_FAILED",u,!0)}}return s}fb.composeScalar=UA});var bb=M(yb=>{"use strict";function qA(n,e,t){if(e){t??(t=e.length);for(let i=t-1;i>=0;--i){let r=e[i];switch(r.type){case"space":case"comment":case"newline":n-=r.source.length;continue}for(r=e[++i];r?.type==="space";)n+=r.source.length,r=e[++i];break}}return n}yb.emptyScalarPosition=qA});var wb=M(rd=>{"use strict";var GA=vn(),jA=G(),$A=ub(),Sb=gb(),YA=Tr(),KA=bb(),XA={composeNode:vb,composeEmptyNode:id};function vb(n,e,t,i){let r=n.atKey,{spaceBefore:o,comment:s,anchor:a,tag:l}=t,c,u=!0;switch(e.type){case"alias":c=QA(n,e,i),(a||l)&&i(e,"ALIAS_PROPS","An alias node must not specify any properties");break;case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"block-scalar":c=Sb.composeScalar(n,e,l,i),a&&(c.anchor=a.source.substring(1));break;case"block-map":case"block-seq":case"flow-collection":try{c=$A.composeCollection(XA,n,e,t,i),a&&(c.anchor=a.source.substring(1))}catch(h){let d=h instanceof Error?h.message:String(h);i(e,"RESOURCE_EXHAUSTION",d)}break;default:{let h=e.type==="error"?e.message:`Unsupported token (type: ${e.type})`;i(e,"UNEXPECTED_TOKEN",h),u=!1}}return c??(c=id(n,e.offset,void 0,null,t,i)),a&&c.anchor===""&&i(a,"BAD_ALIAS","Anchor cannot be an empty string"),r&&n.options.stringKeys&&(!jA.isScalar(c)||typeof c.value!="string"||c.tag&&c.tag!=="tag:yaml.org,2002:str")&&i(l??e,"NON_STRING_KEY","With stringKeys, all keys must be strings"),o&&(c.spaceBefore=!0),s&&(e.type==="scalar"&&e.source===""?c.comment=s:c.commentBefore=s),n.options.keepSourceTokens&&u&&(c.srcToken=e),c}function id(n,e,t,i,{spaceBefore:r,comment:o,anchor:s,tag:a,end:l},c){let u={type:"scalar",offset:KA.emptyScalarPosition(e,t,i),indent:-1,source:""},h=Sb.composeScalar(n,u,a,c);return s&&(h.anchor=s.source.substring(1),h.anchor===""&&c(s,"BAD_ALIAS","Anchor cannot be an empty string")),r&&(h.spaceBefore=!0),o&&(h.comment=o,h.range[2]=l),h}function QA({options:n},{offset:e,source:t,end:i},r){let o=new GA.Alias(t.substring(1));o.source===""&&r(e,"BAD_ALIAS","Alias cannot be an empty string"),o.source.endsWith(":")&&r(e+t.length-1,"BAD_ALIAS","Alias ending in : is ambiguous",!0);let s=e+t.length,a=YA.resolveEnd(i,s,n.strict,r);return o.range=[e,s,a.offset],a.comment&&(o.comment=a.comment),o}rd.composeEmptyNode=id;rd.composeNode=vb});var kb=M(Pb=>{"use strict";var JA=Vn(),xb=wb(),ZA=Tr(),eT=zn();function tT(n,e,{offset:t,start:i,value:r,end:o},s){let a=Object.assign({_directives:e},n),l=new JA.Document(void 0,a),c={atKey:!1,atRoot:!0,directives:l.directives,options:l.options,schema:l.schema},u=eT.resolveProps(i,{indicator:"doc-start",next:r??o?.[0],offset:t,onError:s,parentIndent:0,startOnNewline:!0});u.found&&(l.directives.docStart=!0,r&&(r.type==="block-map"||r.type==="block-seq")&&!u.hasNewline&&s(u.end,"MISSING_CHAR","Block collection cannot start on same line with directives-end marker")),l.contents=r?xb.composeNode(c,r,u,s):xb.composeEmptyNode(c,u.end,i,null,u,s);let h=l.contents.range[2],d=ZA.resolveEnd(o,h,!1,s);return d.comment&&(l.comment=d.comment),l.range=[t,h,d.offset],l}Pb.composeDoc=tT});var od=M(Cb=>{"use strict";var iT=Yo("process"),rT=qu(),nT=Vn(),Un=Fn(),Ab=G(),oT=kb(),sT=Tr();function Wn(n){if(typeof n=="number")return[n,n+1];if(Array.isArray(n))return n.length===2?n:[n[0],n[1]];let{offset:e,source:t}=n;return[e,e+(typeof t=="string"?t.length:1)]}function Tb(n){let e="",t=!1,i=!1;for(let r=0;r<n.length;++r){let o=n[r];switch(o[0]){case"#":e+=(e===""?"":i?`
99
+
100
+ `:`
101
+ `)+(o.substring(1)||" "),t=!0,i=!1;break;case"%":n[r+1]?.[0]!=="#"&&(r+=1),t=!1;break;default:t||(i=!0),t=!1}}return{comment:e,afterEmptyLine:i}}var nd=class{constructor(e={}){this.doc=null,this.atDirectives=!1,this.prelude=[],this.errors=[],this.warnings=[],this.onError=(t,i,r,o)=>{let s=Wn(t);o?this.warnings.push(new Un.YAMLWarning(s,i,r)):this.errors.push(new Un.YAMLParseError(s,i,r))},this.directives=new rT.Directives({version:e.version||"1.2"}),this.options=e}decorate(e,t){let{comment:i,afterEmptyLine:r}=Tb(this.prelude);if(i){let o=e.contents;if(t)e.comment=e.comment?`${e.comment}
102
+ ${i}`:i;else if(r||e.directives.docStart||!o)e.commentBefore=i;else if(Ab.isCollection(o)&&!o.flow&&o.items.length>0){let s=o.items[0];Ab.isPair(s)&&(s=s.key);let a=s.commentBefore;s.commentBefore=a?`${i}
103
+ ${a}`:i}else{let s=o.commentBefore;o.commentBefore=s?`${i}
104
+ ${s}`:i}}if(t){for(let o=0;o<this.errors.length;++o)e.errors.push(this.errors[o]);for(let o=0;o<this.warnings.length;++o)e.warnings.push(this.warnings[o])}else e.errors=this.errors,e.warnings=this.warnings;this.prelude=[],this.errors=[],this.warnings=[]}streamInfo(){return{comment:Tb(this.prelude).comment,directives:this.directives,errors:this.errors,warnings:this.warnings}}*compose(e,t=!1,i=-1){for(let r of e)yield*this.next(r);yield*this.end(t,i)}*next(e){switch(iT.env.LOG_STREAM&&console.dir(e,{depth:null}),e.type){case"directive":this.directives.add(e.source,(t,i,r)=>{let o=Wn(e);o[0]+=t,this.onError(o,"BAD_DIRECTIVE",i,r)}),this.prelude.push(e.source),this.atDirectives=!0;break;case"document":{let t=oT.composeDoc(this.options,this.directives,e,this.onError);this.atDirectives&&!t.directives.docStart&&this.onError(e,"MISSING_CHAR","Missing directives-end/doc-start indicator line"),this.decorate(t,!1),this.doc&&(yield this.doc),this.doc=t,this.atDirectives=!1;break}case"byte-order-mark":case"space":break;case"comment":case"newline":this.prelude.push(e.source);break;case"error":{let t=e.source?`${e.message}: ${JSON.stringify(e.source)}`:e.message,i=new Un.YAMLParseError(Wn(e),"UNEXPECTED_TOKEN",t);this.atDirectives||!this.doc?this.errors.push(i):this.doc.errors.push(i);break}case"doc-end":{if(!this.doc){let i="Unexpected doc-end without preceding document";this.errors.push(new Un.YAMLParseError(Wn(e),"UNEXPECTED_TOKEN",i));break}this.doc.directives.docEnd=!0;let t=sT.resolveEnd(e.end,e.offset+e.source.length,this.doc.options.strict,this.onError);if(this.decorate(this.doc,!0),t.comment){let i=this.doc.comment;this.doc.comment=i?`${i}
105
+ ${t.comment}`:t.comment}this.doc.range[2]=t.offset;break}default:this.errors.push(new Un.YAMLParseError(Wn(e),"UNEXPECTED_TOKEN",`Unsupported token ${e.type}`))}}*end(e=!1,t=-1){if(this.doc)this.decorate(this.doc,!0),yield this.doc,this.doc=null;else if(e){let i=Object.assign({_directives:this.directives},this.options),r=new nT.Document(void 0,i);this.atDirectives&&this.onError(t,"MISSING_CHAR","Missing directives-end indicator line"),r.range=[0,t,t],this.decorate(r,!1),yield r}}};Cb.Composer=nd});var Eb=M(Oa=>{"use strict";var aT=Zh(),lT=td(),cT=Fn(),Mb=An();function uT(n,e=!0,t){if(n){let i=(r,o,s)=>{let a=typeof r=="number"?r:Array.isArray(r)?r[0]:r.offset;if(t)t(a,o,s);else throw new cT.YAMLParseError([a,a+1],o,s)};switch(n.type){case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return lT.resolveFlowScalar(n,e,i);case"block-scalar":return aT.resolveBlockScalar({options:{strict:e}},n,i)}}return null}function hT(n,e){let{implicitKey:t=!1,indent:i,inFlow:r=!1,offset:o=-1,type:s="PLAIN"}=e,a=Mb.stringifyString({type:s,value:n},{implicitKey:t,indent:i>0?" ".repeat(i):"",inFlow:r,options:{blockQuote:!0,lineWidth:-1}}),l=e.end??[{type:"newline",offset:-1,indent:i,source:`
106
+ `}];switch(a[0]){case"|":case">":{let c=a.indexOf(`
107
+ `),u=a.substring(0,c),h=a.substring(c+1)+`
108
+ `,d=[{type:"block-scalar-header",offset:o,indent:i,source:u}];return Db(d,l)||d.push({type:"newline",offset:-1,indent:i,source:`
109
+ `}),{type:"block-scalar",offset:o,indent:i,props:d,source:h}}case'"':return{type:"double-quoted-scalar",offset:o,indent:i,source:a,end:l};case"'":return{type:"single-quoted-scalar",offset:o,indent:i,source:a,end:l};default:return{type:"scalar",offset:o,indent:i,source:a,end:l}}}function dT(n,e,t={}){let{afterKey:i=!1,implicitKey:r=!1,inFlow:o=!1,type:s}=t,a="indent"in n?n.indent:null;if(i&&typeof a=="number"&&(a+=2),!s)switch(n.type){case"single-quoted-scalar":s="QUOTE_SINGLE";break;case"double-quoted-scalar":s="QUOTE_DOUBLE";break;case"block-scalar":{let c=n.props[0];if(c.type!=="block-scalar-header")throw new Error("Invalid block scalar header");s=c.source[0]===">"?"BLOCK_FOLDED":"BLOCK_LITERAL";break}default:s="PLAIN"}let l=Mb.stringifyString({type:s,value:e},{implicitKey:r||a===null,indent:a!==null&&a>0?" ".repeat(a):"",inFlow:o,options:{blockQuote:!0,lineWidth:-1}});switch(l[0]){case"|":case">":pT(n,l);break;case'"':sd(n,l,"double-quoted-scalar");break;case"'":sd(n,l,"single-quoted-scalar");break;default:sd(n,l,"scalar")}}function pT(n,e){let t=e.indexOf(`
110
+ `),i=e.substring(0,t),r=e.substring(t+1)+`
111
+ `;if(n.type==="block-scalar"){let o=n.props[0];if(o.type!=="block-scalar-header")throw new Error("Invalid block scalar header");o.source=i,n.source=r}else{let{offset:o}=n,s="indent"in n?n.indent:-1,a=[{type:"block-scalar-header",offset:o,indent:s,source:i}];Db(a,"end"in n?n.end:void 0)||a.push({type:"newline",offset:-1,indent:s,source:`
112
+ `});for(let l of Object.keys(n))l!=="type"&&l!=="offset"&&delete n[l];Object.assign(n,{type:"block-scalar",indent:s,props:a,source:r})}}function Db(n,e){if(e)for(let t of e)switch(t.type){case"space":case"comment":n.push(t);break;case"newline":return n.push(t),!0}return!1}function sd(n,e,t){switch(n.type){case"scalar":case"double-quoted-scalar":case"single-quoted-scalar":n.type=t,n.source=e;break;case"block-scalar":{let i=n.props.slice(1),r=e.length;n.props[0].type==="block-scalar-header"&&(r-=n.props[0].source.length);for(let o of i)o.offset+=r;delete n.props,Object.assign(n,{type:t,source:e,end:i});break}case"block-map":case"block-seq":{let r={type:"newline",offset:n.offset+e.length,indent:n.indent,source:`
113
+ `};delete n.items,Object.assign(n,{type:t,source:e,end:[r]});break}default:{let i="indent"in n?n.indent:-1,r="end"in n&&Array.isArray(n.end)?n.end.filter(o=>o.type==="space"||o.type==="comment"||o.type==="newline"):[];for(let o of Object.keys(n))o!=="type"&&o!=="offset"&&delete n[o];Object.assign(n,{type:t,indent:i,source:e,end:r})}}}Oa.createScalarToken=hT;Oa.resolveAsScalar=uT;Oa.setScalarValue=dT});var Ib=M(Nb=>{"use strict";var mT=n=>"type"in n?La(n):Va(n);function La(n){switch(n.type){case"block-scalar":{let e="";for(let t of n.props)e+=La(t);return e+n.source}case"block-map":case"block-seq":{let e="";for(let t of n.items)e+=Va(t);return e}case"flow-collection":{let e=n.start.source;for(let t of n.items)e+=Va(t);for(let t of n.end)e+=t.source;return e}case"document":{let e=Va(n);if(n.end)for(let t of n.end)e+=t.source;return e}default:{let e=n.source;if("end"in n&&n.end)for(let t of n.end)e+=t.source;return e}}}function Va({start:n,key:e,sep:t,value:i}){let r="";for(let o of n)r+=o.source;if(e&&(r+=La(e)),t)for(let o of t)r+=o.source;return i&&(r+=La(i)),r}Nb.stringify=mT});var Vb=M(Ob=>{"use strict";var ad=Symbol("break visit"),fT=Symbol("skip children"),Rb=Symbol("remove item");function Li(n,e){"type"in n&&n.type==="document"&&(n={start:n.start,value:n.value}),Bb(Object.freeze([]),n,e)}Li.BREAK=ad;Li.SKIP=fT;Li.REMOVE=Rb;Li.itemAtPath=(n,e)=>{let t=n;for(let[i,r]of e){let o=t?.[i];if(o&&"items"in o)t=o.items[r];else return}return t};Li.parentCollection=(n,e)=>{let t=Li.itemAtPath(n,e.slice(0,-1)),i=e[e.length-1][0],r=t?.[i];if(r&&"items"in r)return r;throw new Error("Parent collection not found")};function Bb(n,e,t){let i=t(e,n);if(typeof i=="symbol")return i;for(let r of["key","value"]){let o=e[r];if(o&&"items"in o){for(let s=0;s<o.items.length;++s){let a=Bb(Object.freeze(n.concat([[r,s]])),o.items[s],t);if(typeof a=="number")s=a-1;else{if(a===ad)return ad;a===Rb&&(o.items.splice(s,1),s-=1)}}typeof i=="function"&&r==="key"&&(i=i(e,n))}}return typeof i=="function"?i(e,n):i}Ob.visit=Li});var _a=M(Se=>{"use strict";var ld=Eb(),gT=Ib(),yT=Vb(),cd="\uFEFF",ud="",hd="",dd="",bT=n=>!!n&&"items"in n,ST=n=>!!n&&(n.type==="scalar"||n.type==="single-quoted-scalar"||n.type==="double-quoted-scalar"||n.type==="block-scalar");function vT(n){switch(n){case cd:return"<BOM>";case ud:return"<DOC>";case hd:return"<FLOW_END>";case dd:return"<SCALAR>";default:return JSON.stringify(n)}}function wT(n){switch(n){case cd:return"byte-order-mark";case ud:return"doc-mode";case hd:return"flow-error-end";case dd:return"scalar";case"---":return"doc-start";case"...":return"doc-end";case"":case`
114
+ `:case`\r
115
+ `:return"newline";case"-":return"seq-item-ind";case"?":return"explicit-key-ind";case":":return"map-value-ind";case"{":return"flow-map-start";case"}":return"flow-map-end";case"[":return"flow-seq-start";case"]":return"flow-seq-end";case",":return"comma"}switch(n[0]){case" ":case" ":return"space";case"#":return"comment";case"%":return"directive-line";case"*":return"alias";case"&":return"anchor";case"!":return"tag";case"'":return"single-quoted-scalar";case'"':return"double-quoted-scalar";case"|":case">":return"block-scalar-header"}return null}Se.createScalarToken=ld.createScalarToken;Se.resolveAsScalar=ld.resolveAsScalar;Se.setScalarValue=ld.setScalarValue;Se.stringify=gT.stringify;Se.visit=yT.visit;Se.BOM=cd;Se.DOCUMENT=ud;Se.FLOW_END=hd;Se.SCALAR=dd;Se.isCollection=bT;Se.isScalar=ST;Se.prettyToken=vT;Se.tokenType=wT});var fd=M(_b=>{"use strict";var Hn=_a();function qe(n){switch(n){case void 0:case" ":case`
116
+ `:case"\r":case" ":return!0;default:return!1}}var Lb=new Set("0123456789ABCDEFabcdef"),xT=new Set("0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz-#;/?:@&=+$_.!~*'()"),Fa=new Set(",[]{}"),PT=new Set(` ,[]{}
117
+ \r `),pd=n=>!n||PT.has(n),md=class{constructor(){this.atEnd=!1,this.blockScalarIndent=-1,this.blockScalarKeep=!1,this.buffer="",this.flowKey=!1,this.flowLevel=0,this.indentNext=0,this.indentValue=0,this.lineEndPos=null,this.next=null,this.pos=0}*lex(e,t=!1){if(e){if(typeof e!="string")throw TypeError("source is not a string");this.buffer=this.buffer?this.buffer+e:e,this.lineEndPos=null}this.atEnd=!t;let i=this.next??"stream";for(;i&&(t||this.hasChars(1));)i=yield*this.parseNext(i)}atLineEnd(){let e=this.pos,t=this.buffer[e];for(;t===" "||t===" ";)t=this.buffer[++e];return!t||t==="#"||t===`
118
+ `?!0:t==="\r"?this.buffer[e+1]===`
119
+ `:!1}charAt(e){return this.buffer[this.pos+e]}continueScalar(e){let t=this.buffer[e];if(this.indentNext>0){let i=0;for(;t===" ";)t=this.buffer[++i+e];if(t==="\r"){let r=this.buffer[i+e+1];if(r===`
120
+ `||!r&&!this.atEnd)return e+i+1}return t===`
121
+ `||i>=this.indentNext||!t&&!this.atEnd?e+i:-1}if(t==="-"||t==="."){let i=this.buffer.substr(e,3);if((i==="---"||i==="...")&&qe(this.buffer[e+3]))return-1}return e}getLine(){let e=this.lineEndPos;return(typeof e!="number"||e!==-1&&e<this.pos)&&(e=this.buffer.indexOf(`
122
+ `,this.pos),this.lineEndPos=e),e===-1?this.atEnd?this.buffer.substring(this.pos):null:(this.buffer[e-1]==="\r"&&(e-=1),this.buffer.substring(this.pos,e))}hasChars(e){return this.pos+e<=this.buffer.length}setNext(e){return this.buffer=this.buffer.substring(this.pos),this.pos=0,this.lineEndPos=null,this.next=e,null}peek(e){return this.buffer.substr(this.pos,e)}*parseNext(e){switch(e){case"stream":return yield*this.parseStream();case"line-start":return yield*this.parseLineStart();case"block-start":return yield*this.parseBlockStart();case"doc":return yield*this.parseDocument();case"flow":return yield*this.parseFlowCollection();case"quoted-scalar":return yield*this.parseQuotedScalar();case"block-scalar":return yield*this.parseBlockScalar();case"plain-scalar":return yield*this.parsePlainScalar()}}*parseStream(){let e=this.getLine();if(e===null)return this.setNext("stream");if(e[0]===Hn.BOM&&(yield*this.pushCount(1),e=e.substring(1)),e[0]==="%"){let t=e.length,i=e.indexOf("#");for(;i!==-1;){let o=e[i-1];if(o===" "||o===" "){t=i-1;break}else i=e.indexOf("#",i+1)}for(;;){let o=e[t-1];if(o===" "||o===" ")t-=1;else break}let r=(yield*this.pushCount(t))+(yield*this.pushSpaces(!0));return yield*this.pushCount(e.length-r),this.pushNewline(),"stream"}if(this.atLineEnd()){let t=yield*this.pushSpaces(!0);return yield*this.pushCount(e.length-t),yield*this.pushNewline(),"stream"}return yield Hn.DOCUMENT,yield*this.parseLineStart()}*parseLineStart(){let e=this.charAt(0);if(!e&&!this.atEnd)return this.setNext("line-start");if(e==="-"||e==="."){if(!this.atEnd&&!this.hasChars(4))return this.setNext("line-start");let t=this.peek(3);if((t==="---"||t==="...")&&qe(this.charAt(3)))return yield*this.pushCount(3),this.indentValue=0,this.indentNext=0,t==="---"?"doc":"stream"}return this.indentValue=yield*this.pushSpaces(!1),this.indentNext>this.indentValue&&!qe(this.charAt(1))&&(this.indentNext=this.indentValue),yield*this.parseBlockStart()}*parseBlockStart(){let[e,t]=this.peek(2);if(!t&&!this.atEnd)return this.setNext("block-start");if((e==="-"||e==="?"||e===":")&&qe(t)){let i=(yield*this.pushCount(1))+(yield*this.pushSpaces(!0));return this.indentNext=this.indentValue+1,this.indentValue+=i,"block-start"}return"doc"}*parseDocument(){yield*this.pushSpaces(!0);let e=this.getLine();if(e===null)return this.setNext("doc");let t=yield*this.pushIndicators();switch(e[t]){case"#":yield*this.pushCount(e.length-t);case void 0:return yield*this.pushNewline(),yield*this.parseLineStart();case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel=1,"flow";case"}":case"]":return yield*this.pushCount(1),"doc";case"*":return yield*this.pushUntil(pd),"doc";case'"':case"'":return yield*this.parseQuotedScalar();case"|":case">":return t+=yield*this.parseBlockScalarHeader(),t+=yield*this.pushSpaces(!0),yield*this.pushCount(e.length-t),yield*this.pushNewline(),yield*this.parseBlockScalar();default:return yield*this.parsePlainScalar()}}*parseFlowCollection(){let e,t,i=-1;do e=yield*this.pushNewline(),e>0?(t=yield*this.pushSpaces(!1),this.indentValue=i=t):t=0,t+=yield*this.pushSpaces(!0);while(e+t>0);let r=this.getLine();if(r===null)return this.setNext("flow");if((i!==-1&&i<this.indentNext&&r[0]!=="#"||i===0&&(r.startsWith("---")||r.startsWith("..."))&&qe(r[3]))&&!(i===this.indentNext-1&&this.flowLevel===1&&(r[0]==="]"||r[0]==="}")))return this.flowLevel=0,yield Hn.FLOW_END,yield*this.parseLineStart();let o=0;for(;r[o]===",";)o+=yield*this.pushCount(1),o+=yield*this.pushSpaces(!0),this.flowKey=!1;switch(o+=yield*this.pushIndicators(),r[o]){case void 0:return"flow";case"#":return yield*this.pushCount(r.length-o),"flow";case"{":case"[":return yield*this.pushCount(1),this.flowKey=!1,this.flowLevel+=1,"flow";case"}":case"]":return yield*this.pushCount(1),this.flowKey=!0,this.flowLevel-=1,this.flowLevel?"flow":"doc";case"*":return yield*this.pushUntil(pd),"flow";case'"':case"'":return this.flowKey=!0,yield*this.parseQuotedScalar();case":":{let s=this.charAt(1);if(this.flowKey||qe(s)||s===",")return this.flowKey=!1,yield*this.pushCount(1),yield*this.pushSpaces(!0),"flow"}default:return this.flowKey=!1,yield*this.parsePlainScalar()}}*parseQuotedScalar(){let e=this.charAt(0),t=this.buffer.indexOf(e,this.pos+1);if(e==="'")for(;t!==-1&&this.buffer[t+1]==="'";)t=this.buffer.indexOf("'",t+2);else for(;t!==-1;){let o=0;for(;this.buffer[t-1-o]==="\\";)o+=1;if(o%2===0)break;t=this.buffer.indexOf('"',t+1)}let i=this.buffer.substring(0,t),r=i.indexOf(`
123
+ `,this.pos);if(r!==-1){for(;r!==-1;){let o=this.continueScalar(r+1);if(o===-1)break;r=i.indexOf(`
124
+ `,o)}r!==-1&&(t=r-(i[r-1]==="\r"?2:1))}if(t===-1){if(!this.atEnd)return this.setNext("quoted-scalar");t=this.buffer.length}return yield*this.pushToIndex(t+1,!1),this.flowLevel?"flow":"doc"}*parseBlockScalarHeader(){this.blockScalarIndent=-1,this.blockScalarKeep=!1;let e=this.pos;for(;;){let t=this.buffer[++e];if(t==="+")this.blockScalarKeep=!0;else if(t>"0"&&t<="9")this.blockScalarIndent=Number(t)-1;else if(t!=="-")break}return yield*this.pushUntil(t=>qe(t)||t==="#")}*parseBlockScalar(){let e=this.pos-1,t=0,i;e:for(let o=this.pos;i=this.buffer[o];++o)switch(i){case" ":t+=1;break;case`
125
+ `:e=o,t=0;break;case"\r":{let s=this.buffer[o+1];if(!s&&!this.atEnd)return this.setNext("block-scalar");if(s===`
126
+ `)break}default:break e}if(!i&&!this.atEnd)return this.setNext("block-scalar");if(t>=this.indentNext){this.blockScalarIndent===-1?this.indentNext=t:this.indentNext=this.blockScalarIndent+(this.indentNext===0?1:this.indentNext);do{let o=this.continueScalar(e+1);if(o===-1)break;e=this.buffer.indexOf(`
127
+ `,o)}while(e!==-1);if(e===-1){if(!this.atEnd)return this.setNext("block-scalar");e=this.buffer.length}}let r=e+1;for(i=this.buffer[r];i===" ";)i=this.buffer[++r];if(i===" "){for(;i===" "||i===" "||i==="\r"||i===`
128
+ `;)i=this.buffer[++r];e=r-1}else if(!this.blockScalarKeep)do{let o=e-1,s=this.buffer[o];s==="\r"&&(s=this.buffer[--o]);let a=o;for(;s===" ";)s=this.buffer[--o];if(s===`
129
+ `&&o>=this.pos&&o+1+t>a)e=o;else break}while(!0);return yield Hn.SCALAR,yield*this.pushToIndex(e+1,!0),yield*this.parseLineStart()}*parsePlainScalar(){let e=this.flowLevel>0,t=this.pos-1,i=this.pos-1,r;for(;r=this.buffer[++i];)if(r===":"){let o=this.buffer[i+1];if(qe(o)||e&&Fa.has(o))break;t=i}else if(qe(r)){let o=this.buffer[i+1];if(r==="\r"&&(o===`
130
+ `?(i+=1,r=`
131
+ `,o=this.buffer[i+1]):t=i),o==="#"||e&&Fa.has(o))break;if(r===`
132
+ `){let s=this.continueScalar(i+1);if(s===-1)break;i=Math.max(i,s-2)}}else{if(e&&Fa.has(r))break;t=i}return!r&&!this.atEnd?this.setNext("plain-scalar"):(yield Hn.SCALAR,yield*this.pushToIndex(t+1,!0),e?"flow":"doc")}*pushCount(e){return e>0?(yield this.buffer.substr(this.pos,e),this.pos+=e,e):0}*pushToIndex(e,t){let i=this.buffer.slice(this.pos,e);return i?(yield i,this.pos+=i.length,i.length):(t&&(yield""),0)}*pushIndicators(){let e=0;e:for(;;){switch(this.charAt(0)){case"!":e+=yield*this.pushTag(),e+=yield*this.pushSpaces(!0);continue e;case"&":e+=yield*this.pushUntil(pd),e+=yield*this.pushSpaces(!0);continue e;case"-":case"?":case":":{let t=this.flowLevel>0,i=this.charAt(1);if(qe(i)||t&&Fa.has(i)){t?this.flowKey&&(this.flowKey=!1):this.indentNext=this.indentValue+1,e+=yield*this.pushCount(1),e+=yield*this.pushSpaces(!0);continue e}}}break e}return e}*pushTag(){if(this.charAt(1)==="<"){let e=this.pos+2,t=this.buffer[e];for(;!qe(t)&&t!==">";)t=this.buffer[++e];return yield*this.pushToIndex(t===">"?e+1:e,!1)}else{let e=this.pos+1,t=this.buffer[e];for(;t;)if(xT.has(t))t=this.buffer[++e];else if(t==="%"&&Lb.has(this.buffer[e+1])&&Lb.has(this.buffer[e+2]))t=this.buffer[e+=3];else break;return yield*this.pushToIndex(e,!1)}}*pushNewline(){let e=this.buffer[this.pos];return e===`
133
+ `?yield*this.pushCount(1):e==="\r"&&this.charAt(1)===`
134
+ `?yield*this.pushCount(2):0}*pushSpaces(e){let t=this.pos-1,i;do i=this.buffer[++t];while(i===" "||e&&i===" ");let r=t-this.pos;return r>0&&(yield this.buffer.substr(this.pos,r),this.pos=t),r}*pushUntil(e){let t=this.pos,i=this.buffer[t];for(;!e(i);)i=this.buffer[++t];return yield*this.pushToIndex(t,!1)}};_b.Lexer=md});var yd=M(Fb=>{"use strict";var gd=class{constructor(){this.lineStarts=[],this.addNewLine=e=>this.lineStarts.push(e),this.linePos=e=>{let t=0,i=this.lineStarts.length;for(;t<i;){let o=t+i>>1;this.lineStarts[o]<e?t=o+1:i=o}if(this.lineStarts[t]===e)return{line:t+1,col:1};if(t===0)return{line:0,col:e};let r=this.lineStarts[t-1];return{line:t,col:e-r+1}}}};Fb.LineCounter=gd});var Sd=M(qb=>{"use strict";var kT=Yo("process"),zb=_a(),AT=fd();function Zt(n,e){for(let t=0;t<n.length;++t)if(n[t].type===e)return!0;return!1}function Ub(n){for(let e=0;e<n.length;++e)switch(n[e].type){case"space":case"comment":case"newline":break;default:return e}return-1}function Hb(n){switch(n?.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":case"flow-collection":return!0;default:return!1}}function za(n){switch(n.type){case"document":return n.start;case"block-map":{let e=n.items[n.items.length-1];return e.sep??e.start}case"block-seq":return n.items[n.items.length-1].start;default:return[]}}function Cr(n){if(n.length===0)return[];let e=n.length;e:for(;--e>=0;)switch(n[e].type){case"doc-start":case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":case"newline":break e}for(;n[++e]?.type==="space";);return n.splice(e,n.length)}function Ua(n,e){if(e.length<1e5)Array.prototype.push.apply(n,e);else for(let t=0;t<e.length;++t)n.push(e[t])}function Wb(n){if(n.start.type==="flow-seq-start")for(let e of n.items)e.sep&&!e.value&&!Zt(e.start,"explicit-key-ind")&&!Zt(e.sep,"map-value-ind")&&(e.key&&(e.value=e.key),delete e.key,Hb(e.value)?e.value.end?Ua(e.value.end,e.sep):e.value.end=e.sep:Ua(e.start,e.sep),delete e.sep)}var bd=class{constructor(e){this.atNewLine=!0,this.atScalar=!1,this.indent=0,this.offset=0,this.onKeyLine=!1,this.stack=[],this.source="",this.type="",this.lexer=new AT.Lexer,this.onNewLine=e}*parse(e,t=!1){this.onNewLine&&this.offset===0&&this.onNewLine(0);for(let i of this.lexer.lex(e,t))yield*this.next(i);t||(yield*this.end())}*next(e){if(this.source=e,kT.env.LOG_TOKENS&&console.log("|",zb.prettyToken(e)),this.atScalar){this.atScalar=!1,yield*this.step(),this.offset+=e.length;return}let t=zb.tokenType(e);if(t)if(t==="scalar")this.atNewLine=!1,this.atScalar=!0,this.type="scalar";else{switch(this.type=t,yield*this.step(),t){case"newline":this.atNewLine=!0,this.indent=0,this.onNewLine&&this.onNewLine(this.offset+e.length);break;case"space":this.atNewLine&&e[0]===" "&&(this.indent+=e.length);break;case"explicit-key-ind":case"map-value-ind":case"seq-item-ind":this.atNewLine&&(this.indent+=e.length);break;case"doc-mode":case"flow-error-end":return;default:this.atNewLine=!1}this.offset+=e.length}else{let i=`Not a YAML token: ${e}`;yield*this.pop({type:"error",offset:this.offset,message:i,source:e}),this.offset+=e.length}}*end(){for(;this.stack.length>0;)yield*this.pop()}get sourceToken(){return{type:this.type,offset:this.offset,indent:this.indent,source:this.source}}*step(){let e=this.peek(1);if(this.type==="doc-end"&&e?.type!=="doc-end"){for(;this.stack.length>0;)yield*this.pop();this.stack.push({type:"doc-end",offset:this.offset,source:this.source});return}if(!e)return yield*this.stream();switch(e.type){case"document":return yield*this.document(e);case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return yield*this.scalar(e);case"block-scalar":return yield*this.blockScalar(e);case"block-map":return yield*this.blockMap(e);case"block-seq":return yield*this.blockSequence(e);case"flow-collection":return yield*this.flowCollection(e);case"doc-end":return yield*this.documentEnd(e)}yield*this.pop()}peek(e){return this.stack[this.stack.length-e]}*pop(e){let t=e??this.stack.pop();if(!t)yield{type:"error",offset:this.offset,source:"",message:"Tried to pop an empty stack"};else if(this.stack.length===0)yield t;else{let i=this.peek(1);switch(t.type==="block-scalar"?t.indent="indent"in i?i.indent:0:t.type==="flow-collection"&&i.type==="document"&&(t.indent=0),t.type==="flow-collection"&&Wb(t),i.type){case"document":i.value=t;break;case"block-scalar":i.props.push(t);break;case"block-map":{let r=i.items[i.items.length-1];if(r.value){i.items.push({start:[],key:t,sep:[]}),this.onKeyLine=!0;return}else if(r.sep)r.value=t;else{Object.assign(r,{key:t,sep:[]}),this.onKeyLine=!r.explicitKey;return}break}case"block-seq":{let r=i.items[i.items.length-1];r.value?i.items.push({start:[],value:t}):r.value=t;break}case"flow-collection":{let r=i.items[i.items.length-1];!r||r.value?i.items.push({start:[],key:t,sep:[]}):r.sep?r.value=t:Object.assign(r,{key:t,sep:[]});return}default:yield*this.pop(),yield*this.pop(t)}if((i.type==="document"||i.type==="block-map"||i.type==="block-seq")&&(t.type==="block-map"||t.type==="block-seq")){let r=t.items[t.items.length-1];r&&!r.sep&&!r.value&&r.start.length>0&&Ub(r.start)===-1&&(t.indent===0||r.start.every(o=>o.type!=="comment"||o.indent<t.indent))&&(i.type==="document"?i.end=r.start:i.items.push({start:r.start}),t.items.splice(-1,1))}}}*stream(){switch(this.type){case"directive-line":yield{type:"directive",offset:this.offset,source:this.source};return;case"byte-order-mark":case"space":case"comment":case"newline":yield this.sourceToken;return;case"doc-mode":case"doc-start":{let e={type:"document",offset:this.offset,start:[]};this.type==="doc-start"&&e.start.push(this.sourceToken),this.stack.push(e);return}}yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML stream`,source:this.source}}*document(e){if(e.value)return yield*this.lineEnd(e);switch(this.type){case"doc-start":{Ub(e.start)!==-1?(yield*this.pop(),yield*this.step()):e.start.push(this.sourceToken);return}case"anchor":case"tag":case"space":case"comment":case"newline":e.start.push(this.sourceToken);return}let t=this.startBlockValue(e);t?this.stack.push(t):yield{type:"error",offset:this.offset,message:`Unexpected ${this.type} token in YAML document`,source:this.source}}*scalar(e){if(this.type==="map-value-ind"){let t=za(this.peek(2)),i=Cr(t),r;e.end?(r=e.end,r.push(this.sourceToken),delete e.end):r=[this.sourceToken];let o={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:i,key:e,sep:r}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=o}else yield*this.lineEnd(e)}*blockScalar(e){switch(this.type){case"space":case"comment":case"newline":e.props.push(this.sourceToken);return;case"scalar":if(e.source=this.source,this.atNewLine=!0,this.indent=0,this.onNewLine){let t=this.source.indexOf(`
135
+ `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
136
+ `,t)+1}yield*this.pop();break;default:yield*this.pop(),yield*this.step()}}*blockMap(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(this.onKeyLine=!1,t.value){let i="end"in t.value?t.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else if(t.sep)t.sep.push(this.sourceToken);else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Ua(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return}if(this.indent>=e.indent){let i=!this.onKeyLine&&this.indent===e.indent,r=i&&(t.sep||t.explicitKey)&&this.type!=="seq-item-ind",o=[];if(r&&t.sep&&!t.value){let s=[];for(let a=0;a<t.sep.length;++a){let l=t.sep[a];switch(l.type){case"newline":s.push(a);break;case"space":break;case"comment":l.indent>e.indent&&(s.length=0);break;default:s.length=0}}s.length>=2&&(o=t.sep.splice(s[1]))}switch(this.type){case"anchor":case"tag":r||t.value?(o.push(this.sourceToken),e.items.push({start:o}),this.onKeyLine=!0):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"explicit-key-ind":!t.sep&&!t.explicitKey?(t.start.push(this.sourceToken),t.explicitKey=!0):r||t.value?(o.push(this.sourceToken),e.items.push({start:o,explicitKey:!0})):this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken],explicitKey:!0}]}),this.onKeyLine=!0;return;case"map-value-ind":if(t.explicitKey)if(t.sep)if(t.value)e.items.push({start:[],key:null,sep:[this.sourceToken]});else if(Zt(t.sep,"map-value-ind"))this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:o,key:null,sep:[this.sourceToken]}]});else if(Hb(t.key)&&!Zt(t.sep,"newline")){let s=Cr(t.start),a=t.key,l=t.sep;l.push(this.sourceToken),delete t.key,delete t.sep,this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:a,sep:l}]})}else o.length>0?t.sep=t.sep.concat(o,this.sourceToken):t.sep.push(this.sourceToken);else if(Zt(t.start,"newline"))Object.assign(t,{key:null,sep:[this.sourceToken]});else{let s=Cr(t.start);this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:s,key:null,sep:[this.sourceToken]}]})}else t.sep?t.value||r?e.items.push({start:o,key:null,sep:[this.sourceToken]}):Zt(t.sep,"map-value-ind")?this.stack.push({type:"block-map",offset:this.offset,indent:this.indent,items:[{start:[],key:null,sep:[this.sourceToken]}]}):t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});this.onKeyLine=!0;return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let s=this.flowScalar(this.type);r||t.value?(e.items.push({start:o,key:s,sep:[]}),this.onKeyLine=!0):t.sep?this.stack.push(s):(Object.assign(t,{key:s,sep:[]}),this.onKeyLine=!0);return}default:{let s=this.startBlockValue(e);if(s){if(s.type==="block-seq"){if(!t.explicitKey&&t.sep&&!Zt(t.sep,"newline")){yield*this.pop({type:"error",offset:this.offset,message:"Unexpected block-seq-ind on same line with key",source:this.source});return}}else i&&e.items.push({start:o});this.stack.push(s);return}}}}yield*this.pop(),yield*this.step()}*blockSequence(e){let t=e.items[e.items.length-1];switch(this.type){case"newline":if(t.value){let i="end"in t.value?t.value.end:void 0;(Array.isArray(i)?i[i.length-1]:void 0)?.type==="comment"?i?.push(this.sourceToken):e.items.push({start:[this.sourceToken]})}else t.start.push(this.sourceToken);return;case"space":case"comment":if(t.value)e.items.push({start:[this.sourceToken]});else{if(this.atIndentedComment(t.start,e.indent)){let r=e.items[e.items.length-2]?.value?.end;if(Array.isArray(r)){Ua(r,t.start),r.push(this.sourceToken),e.items.pop();return}}t.start.push(this.sourceToken)}return;case"anchor":case"tag":if(t.value||this.indent<=e.indent)break;t.start.push(this.sourceToken);return;case"seq-item-ind":if(this.indent!==e.indent)break;t.value||Zt(t.start,"seq-item-ind")?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return}if(this.indent>e.indent){let i=this.startBlockValue(e);if(i){this.stack.push(i);return}}yield*this.pop(),yield*this.step()}*flowCollection(e){let t=e.items[e.items.length-1];if(this.type==="flow-error-end"){let i;do yield*this.pop(),i=this.peek(1);while(i?.type==="flow-collection")}else if(e.end.length===0){switch(this.type){case"comma":case"explicit-key-ind":!t||t.sep?e.items.push({start:[this.sourceToken]}):t.start.push(this.sourceToken);return;case"map-value-ind":!t||t.value?e.items.push({start:[],key:null,sep:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):Object.assign(t,{key:null,sep:[this.sourceToken]});return;case"space":case"comment":case"newline":case"anchor":case"tag":!t||t.value?e.items.push({start:[this.sourceToken]}):t.sep?t.sep.push(this.sourceToken):t.start.push(this.sourceToken);return;case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":{let r=this.flowScalar(this.type);!t||t.value?e.items.push({start:[],key:r,sep:[]}):t.sep?this.stack.push(r):Object.assign(t,{key:r,sep:[]});return}case"flow-map-end":case"flow-seq-end":e.end.push(this.sourceToken);return}let i=this.startBlockValue(e);i?this.stack.push(i):(yield*this.pop(),yield*this.step())}else{let i=this.peek(2);if(i.type==="block-map"&&(this.type==="map-value-ind"&&i.indent===e.indent||this.type==="newline"&&!i.items[i.items.length-1].sep))yield*this.pop(),yield*this.step();else if(this.type==="map-value-ind"&&i.type!=="flow-collection"){let r=za(i),o=Cr(r);Wb(e);let s=e.end.splice(1,e.end.length);s.push(this.sourceToken);let a={type:"block-map",offset:e.offset,indent:e.indent,items:[{start:o,key:e,sep:s}]};this.onKeyLine=!0,this.stack[this.stack.length-1]=a}else yield*this.lineEnd(e)}}flowScalar(e){if(this.onNewLine){let t=this.source.indexOf(`
137
+ `)+1;for(;t!==0;)this.onNewLine(this.offset+t),t=this.source.indexOf(`
138
+ `,t)+1}return{type:e,offset:this.offset,indent:this.indent,source:this.source}}startBlockValue(e){switch(this.type){case"alias":case"scalar":case"single-quoted-scalar":case"double-quoted-scalar":return this.flowScalar(this.type);case"block-scalar-header":return{type:"block-scalar",offset:this.offset,indent:this.indent,props:[this.sourceToken],source:""};case"flow-map-start":case"flow-seq-start":return{type:"flow-collection",offset:this.offset,indent:this.indent,start:this.sourceToken,items:[],end:[]};case"seq-item-ind":return{type:"block-seq",offset:this.offset,indent:this.indent,items:[{start:[this.sourceToken]}]};case"explicit-key-ind":{this.onKeyLine=!0;let t=za(e),i=Cr(t);return i.push(this.sourceToken),{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,explicitKey:!0}]}}case"map-value-ind":{this.onKeyLine=!0;let t=za(e),i=Cr(t);return{type:"block-map",offset:this.offset,indent:this.indent,items:[{start:i,key:null,sep:[this.sourceToken]}]}}}return null}atIndentedComment(e,t){return this.type!=="comment"||this.indent<=t?!1:e.every(i=>i.type==="newline"||i.type==="space")}*documentEnd(e){this.type!=="doc-mode"&&(e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop()))}*lineEnd(e){switch(this.type){case"comma":case"doc-start":case"doc-end":case"flow-seq-end":case"flow-map-end":case"map-value-ind":yield*this.pop(),yield*this.step();break;case"newline":this.onKeyLine=!1;default:e.end?e.end.push(this.sourceToken):e.end=[this.sourceToken],this.type==="newline"&&(yield*this.pop())}}};qb.Parser=bd});var Kb=M(Gn=>{"use strict";var Gb=od(),TT=Vn(),qn=Fn(),CT=rh(),MT=G(),DT=yd(),jb=Sd();function $b(n){let e=n.prettyErrors!==!1;return{lineCounter:n.lineCounter||e&&new DT.LineCounter||null,prettyErrors:e}}function ET(n,e={}){let{lineCounter:t,prettyErrors:i}=$b(e),r=new jb.Parser(t?.addNewLine),o=new Gb.Composer(e),s=Array.from(o.compose(r.parse(n)));if(i&&t)for(let a of s)a.errors.forEach(qn.prettifyError(n,t)),a.warnings.forEach(qn.prettifyError(n,t));return s.length>0?s:Object.assign([],{empty:!0},o.streamInfo())}function Yb(n,e={}){let{lineCounter:t,prettyErrors:i}=$b(e),r=new jb.Parser(t?.addNewLine),o=new Gb.Composer(e),s=null;for(let a of o.compose(r.parse(n),!0,n.length))if(!s)s=a;else if(s.options.logLevel!=="silent"){s.errors.push(new qn.YAMLParseError(a.range.slice(0,2),"MULTIPLE_DOCS","Source contains multiple documents; please use YAML.parseAllDocuments()"));break}return i&&t&&(s.errors.forEach(qn.prettifyError(n,t)),s.warnings.forEach(qn.prettifyError(n,t))),s}function NT(n,e,t){let i;typeof e=="function"?i=e:t===void 0&&e&&typeof e=="object"&&(t=e);let r=Yb(n,t);if(!r)return null;if(r.warnings.forEach(o=>CT.warn(r.options.logLevel,o)),r.errors.length>0){if(r.options.logLevel!=="silent")throw r.errors[0];r.errors=[]}return r.toJS(Object.assign({reviver:i},t))}function IT(n,e,t){let i=null;if(typeof e=="function"||Array.isArray(e)?i=e:t===void 0&&e&&(t=e),typeof t=="string"&&(t=t.length),typeof t=="number"){let r=Math.round(t);t=r<1?void 0:r>8?{indent:8}:{indent:r}}if(n===void 0){let{keepUndefined:r}=t??e??{};if(!r)return}return MT.isDocument(n)&&!i?n.toString(t):new TT.Document(n,i,t).toString(t)}Gn.parse=NT;Gn.parseAllDocuments=ET;Gn.parseDocument=Yb;Gn.stringify=IT});var wd=M(Y=>{"use strict";var RT=od(),BT=Vn(),OT=Fh(),vd=Fn(),VT=vn(),ei=G(),LT=Kt(),_T=ne(),FT=Qt(),zT=Jt(),UT=_a(),WT=fd(),HT=yd(),qT=Sd(),Wa=Kb(),Xb=gn();Y.Composer=RT.Composer;Y.Document=BT.Document;Y.Schema=OT.Schema;Y.YAMLError=vd.YAMLError;Y.YAMLParseError=vd.YAMLParseError;Y.YAMLWarning=vd.YAMLWarning;Y.Alias=VT.Alias;Y.isAlias=ei.isAlias;Y.isCollection=ei.isCollection;Y.isDocument=ei.isDocument;Y.isMap=ei.isMap;Y.isNode=ei.isNode;Y.isPair=ei.isPair;Y.isScalar=ei.isScalar;Y.isSeq=ei.isSeq;Y.Pair=LT.Pair;Y.Scalar=_T.Scalar;Y.YAMLMap=FT.YAMLMap;Y.YAMLSeq=zT.YAMLSeq;Y.CST=UT;Y.Lexer=WT.Lexer;Y.LineCounter=HT.LineCounter;Y.Parser=qT.Parser;Y.parse=Wa.parse;Y.parseAllDocuments=Wa.parseAllDocuments;Y.parseDocument=Wa.parseDocument;Y.stringify=Wa.stringify;Y.visit=Xb.visit;Y.visitAsync=Xb.visitAsync});var Zl=class{baseUrl;embeddedResources;audioBuffers=new Map;constructor(e="/",t={}){this.baseUrl=e.endsWith("/")?e:`${e}/`,this.embeddedResources=new Map;for(let[i,r]of Object.entries(t)){let o=this.normalizeEmbeddedPath(i);this.embeddedResources.set(o,r)}}normalize(e){let t=this.getScheme(e);if(t==="res"){let i=e.substring(6);return this.buildUrl(i)}return t==="http"||t==="https"||t==="blob"||t==="data"?e:this.buildUrl(e)}getAudioBuffer(e){return this.audioBuffers.get(e)}setAudioBuffer(e,t){this.audioBuffers.set(e,t)}async readText(e){let t=this.getEmbeddedEntry(e);if(t){let r=this.decodeBase64ToBytes(t.base64);return new TextDecoder().decode(r)}let i=this.normalize(e);return await this.fetchText(i)}async readBlob(e){let t=this.getEmbeddedEntry(e);if(t){let r=this.decodeBase64ToBytes(t.base64),o=new Uint8Array(r.byteLength);return o.set(r),new Blob([o],{type:t.mimeType??"application/octet-stream"})}let i=this.normalize(e);return await this.fetchBlob(i)}async fetchText(e){let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status} while fetching ${e}`);return await t.text()}async fetchBlob(e){let t=await fetch(e);if(!t.ok)throw new Error(`HTTP ${t.status} while fetching blob from ${e}`);return await t.blob()}getScheme(e){let t=e.trim(),i=/^([a-z]+[a-z0-9+.-]*):\/\//i.exec(t)??/^(data|blob):/i.exec(t);return i?i[1].toLowerCase():""}buildUrl(e){let t=e.replace(/^\/+/,"");return`${this.baseUrl}${t}`}getEmbeddedEntry(e){let t=this.toEmbeddedPath(e);return t?this.embeddedResources.get(t)??null:null}toEmbeddedPath(e){let t=this.getScheme(e);return t==="res"?this.normalizeEmbeddedPath(e.substring(6)):t?null:this.normalizeEmbeddedPath(e)}normalizeEmbeddedPath(e){return e.replace(/\\/g,"/").replace(/^\/+/,"")}decodeBase64ToBytes(e){let t=atob(e),i=new Uint8Array(t.length);for(let r=0;r<t.length;r+=1)i[r]=t.charCodeAt(r);return i}};var Ur="__PIX3_GAME_DEBUG__";function Nw(n){let e=globalThis;return e[Ur]=n,()=>{e[Ur]===n&&delete e[Ur]}}function Iw(){return globalThis[Ur]??null}var ec="__PIX3_RUNTIME_SCENE__";function as(n){let e=globalThis;e[ec]=n??void 0}function Rw(){return globalThis[ec]??null}var tc="__PIX3_RUNTIME_PROPERTY_SINK__";function ls(n){let e=globalThis;e[tc]=n??void 0}function Bw(){return globalThis[tc]??null}var Wr="__PIX3_PHYSICS_DEBUG__";function Ow(n){let e=globalThis;return e[Wr]=n??void 0,()=>{e[Wr]===n&&delete e[Wr]}}function ic(){return globalThis[Wr]??null}var rc="__PIX3_PHYSICS_DEBUG_ENABLED__";function Vw(n){let e=globalThis;e[rc]=n}function Gr(){return globalThis[rc]===!0}var nc="__PIX3_DIRECTION_AXES_ENABLED__";function Lw(n){let e=globalThis;e[nc]=n}function oc(){return globalThis[nc]===!0}var Om="test:";function _w(n){return n?.startsWith(Om)===!0}var Hr="__PIX3_SCRIPT_ERROR_SINK__";function Fw(n){let e=globalThis;return e[Hr]=n??void 0,()=>{e[Hr]===n&&delete e[Hr]}}function Vm(){return globalThis[Hr]??null}var qr="__PIX3_SIGNAL_EMIT_SINK__";function zw(n){let e=globalThis;return e[qr]=n??void 0,()=>{e[qr]===n&&delete e[qr]}}function Lm(){return globalThis[qr]??null}function sc(n){let e=Lm();if(e)try{e(n)}catch{}}function Me(n){let e=Vm();if(e)try{e(n)}catch{}}function Le(n){return n instanceof Error?{message:`${n.name}: ${n.message}`,stack:n.stack}:{message:String(n)}}var De=new z(1,1);var sr=new WeakMap,ac=n=>typeof n=="object"&&n!==null||typeof n=="function";function _m(n,e){if(!ac(n))return;let t=sr.get(n);t||(t=new Set,sr.set(n,t)),t.add(e)}function cs(n,e){if(!ac(n))return;let t=sr.get(n);t&&(t.delete(e),t.size===0&&sr.delete(n))}function di(n){if(!ac(n))return;let e=sr.get(n);if(e){sr.delete(n);for(let t of e)try{t.host.disconnect(t.signal,n,t.method)}catch(i){console.error("[signals] Failed to disconnect a detached target",{signal:t.signal,error:i})}}}var I=class n extends Fr{nodeId;type;name;properties;metadata;_instancePath;isContainer=!0;components=[];pendingComponents=[];groups=new Set;_selfVisible=!0;hiddenByEditor=!1;_signals=new Map;_disposed=!1;get isDisposed(){return this._disposed}_input;_scene;constructor(e){super(),this.nodeId=e.id,this.uuid=e.id,this.type=e.type??"Group",this.name=e.name??this.type,this.properties={...e.properties??{}},this.metadata={...e.metadata??{}},this._instancePath=e.instancePath??null;for(let t of e.groups??[])typeof t=="string"&&t.trim().length>0&&this.groups.add(t.trim());this.properties.visible!==void 0&&(this.visible=!!this.properties.visible),this.properties.locked!==void 0&&(this.userData.locked=!!this.properties.locked),this.userData={...this.userData,nodeId:this.nodeId,metadata:this.metadata,properties:this.properties}}get instancePath(){return this._instancePath}setInstancePath(e){this._instancePath=e}get input(){return this._input}set input(e){this._input=e;for(let t of this.children)t instanceof n&&(t.input=e);for(let t of this.components)t.input=e}get scene(){return this._scene}set scene(e){this._scene=e;for(let t of this.children)t instanceof n&&(t.scene=e);for(let t of this.components)t.scene=e}get parentNode(){return this.parent instanceof n?this.parent:null}adoptChild(e){if(e===this)throw new Error("Cannot adopt node as its own child.");this.add(e),this._input&&(e.input=this._input),this._scene&&(e.scene=this._scene)}disownChild(e){this.remove(e)}findById(e){if(this.nodeId===e)return this;for(let t of this.children){let i=t instanceof n?t.findById(e):null;if(i)return i}return null}findByName(e){if(this.name===e)return this;for(let t of this.children){let i=t instanceof n?t.findByName(e):null;if(i)return i}return null}getChildByName(e){for(let t of this.children)if(t instanceof n&&t.name===e)return t;return null}findByPath(e){let t=e.split("/").map(r=>r.trim()).filter(r=>r.length>0);if(t.length===0)return null;let i=this;for(let r of t)if(i=i?i.getChildByName(r):null,!i)return null;return i}findNode(e){return e.includes("/")?this.findByPath(e):this.findById(e)??this.findByName(e)}addComponent(e){if(this.components.includes(e)){console.warn(`[NodeBase] Component ${e.id} is already attached to node ${this.nodeId}`);return}e.node=this,this._input&&(e.input=this._input),this._scene&&(e.scene=this._scene),this.components.push(e);let t=e.onAttach;t&&this.runComponentHook(e,"attach",()=>t.call(e,this));let i=this.components.some(o=>o._started),r=e.onStart;i&&e.enabled&&r&&(this.runComponentHook(e,"start",()=>r.call(e)),e._started=!0)}runComponentHook(e,t,i){try{return i(),!0}catch(r){e.enabled=!1;let{message:o,stack:s}=Le(r);return console.error(`[NodeBase] Script "${e.type}" threw in ${t} on node "${this.name}" (disabled):`,r),Me({phase:t,message:o,stack:s,nodeId:this.nodeId,nodeName:this.name,componentType:e.type,componentId:e.id}),!1}}getComponent(e){let t=this.components.find(i=>i instanceof e);return t||null}removeComponent(e){let t=this.components.indexOf(e);if(t===-1){console.warn(`[NodeBase] Component ${e.id} is not attached to node ${this.nodeId}`);return}e.onDetach&&e.onDetach(),di(e),e.resetStartedState&&e.resetStartedState(),e.node=null,this.components.splice(t,1)}isVisibleInTree(){let e=this;for(;e;){if(!e.visible)return!1;e=e.parent}return!0}get authoredVisible(){return this._selfVisible}tick(e){for(let t of this.components){if(!t.enabled)continue;let i=t.onStart;if(!t._started&&i){let o=this.runComponentHook(t,"start",()=>i.call(t));if(t._started=!0,!o)continue}let r=t.onUpdate;t.enabled&&r&&this.runComponentHook(t,"update",()=>r.call(t,e))}for(let t of this.children)t instanceof n&&t.tick(e)}signal(e){!e||!e.trim()||this._signals.has(e)||this._signals.set(e,new Set)}emit(e,...t){let i=this._signals.get(e);if(sc({nodeId:this.nodeId,nodeName:this.name,signal:e,listenerCount:i?.size??0,args:t}),!(!i||i.size===0))for(let r of i)try{r.method.call(r.target,...t)}catch(o){console.error("[NodeBase] Signal listener failed",{nodeId:this.nodeId,signal:e,error:o})}}connect(e,t,i){if(!e||!e.trim()||typeof i!="function")return;let r=this._signals.get(e)??new Set;for(let s of r)if(s.target===t&&s.method===i)return;let o={target:t,method:i,host:this,signal:e};r.add(o),this._signals.set(e,r),_m(t,o)}disconnect(e,t,i){let r=this._signals.get(e);if(r){for(let o of r)o.target===t&&o.method===i&&(r.delete(o),cs(t,o));r.size===0&&this._signals.delete(e)}}disconnectAll(e){if(!e){for(let i of this._signals.values())this.unregisterLinks(i);this._signals.clear();return}let t=this._signals.get(e);t&&this.unregisterLinks(t),this._signals.delete(e)}disconnectAllFromTarget(e){for(let[t,i]of this._signals.entries()){for(let r of i)r.target===e&&(i.delete(r),cs(e,r));i.size===0&&this._signals.delete(t)}}unregisterLinks(e){for(let t of e)cs(t.target,t)}addToGroup(e){let t=e.trim();if(!t)return!1;let i=this.groups.size;return this.groups.add(t),this.groups.size!==i}removeFromGroup(e){return this.groups.delete(e.trim())}isInGroup(e){return this.groups.has(e.trim())}static freeQueue=[];_freeQueued=!1;queueFree(){this._disposed||this._freeQueued||(this._freeQueued=!0,n.freeQueue.push(this))}static flushFreeQueue(){if(n.freeQueue.length===0)return;let e=n.freeQueue.splice(0,n.freeQueue.length);for(let t of e)t._freeQueued=!1,!t._disposed&&(t.detachComponentsDeep(),t.dispose())}detachComponentsDeep(){for(;this.components.length>0;)this.removeComponent(this.components[this.components.length-1]);for(let e of[...this.children])e instanceof n&&e.detachComponentsDeep()}dispose(){if(!this._disposed){this._disposed=!0;for(let e of[...this.children])e instanceof n&&e.dispose();for(let e of this.components)di(e),e.node=null;this.components.length=0,this.disconnectAll(),this.disposeResources(),this.removeFromParent()}}disposeResources(){let e=this.children;for(let t of e)t instanceof n||t.traverse(i=>{if(i instanceof n)return;let r=i.geometry;r&&r!==De&&r.dispose?.();let o=i.material;if(Array.isArray(o))for(let s of o)s?.dispose?.();else o?.dispose?.()})}static getPropertySchema(){return{nodeType:"NodeBase",properties:[{name:"id",type:"string",ui:{label:"Node ID",description:"Unique identifier for this node",group:"Base",readOnly:!0},getValue:e=>e.nodeId,setValue:()=>{}},{name:"name",type:"string",ui:{label:"Name",description:"Display name for this node",group:"Base"},getValue:e=>e.name,setValue:(e,t)=>{e.name=String(t)}},{name:"type",type:"string",ui:{label:"Type",description:"Node type",group:"Base",readOnly:!0},getValue:e=>e.type,setValue:()=>{}},{name:"groups",type:"object",ui:{label:"Groups",description:"Node groups used for runtime querying and call-group operations",group:"Base",hidden:!0},getValue:e=>Array.from(e.groups),setValue:(e,t)=>{let i=Array.isArray(t)?t.filter(o=>typeof o=="string"):[],r=e;r.groups.clear();for(let o of i){let s=o.trim();s&&r.groups.add(s)}}},{name:"visible",type:"boolean",ui:{label:"Visible",description:"Whether the node is visible in the viewport",group:"Editor"},getValue:e=>e.authoredVisible,setValue:(e,t)=>{let i=e,r=!!t;i.visible=r,i.properties.visible=r}},{name:"initiallyVisible",type:"boolean",ui:{label:"Initially Visible",description:"Whether the node starts visible when entering play mode",group:"Base"},getValue:e=>{let t=e;return typeof t.properties.initiallyVisible=="boolean"?t.properties.initiallyVisible:t.visible},setValue:(e,t)=>{let i=e;i.properties.initiallyVisible=!!t}},{name:"locked",type:"boolean",ui:{label:"Locked",description:"Whether the node is locked and cannot be selected in the viewport",group:"Editor"},getValue:e=>!!e.userData.locked,setValue:(e,t)=>{let i=e,r=!!t;i.userData.locked=r,i.properties.locked=r}},{name:"editorOnly",type:"boolean",ui:{label:"Editor Only",description:"Annotation node (label, guide): visible while authoring, stripped from play mode and exported games",group:"Editor"},getValue:e=>e.properties.editorOnly===!0,setValue:(e,t)=>{e.properties.editorOnly=!!t}}],groups:{Base:{label:"Base Properties",description:"Core node properties",expanded:!0},Editor:{label:"Editor",description:"Editor and play-mode defaults",expanded:!0}}}}};Object.defineProperty(I.prototype,"visible",{configurable:!0,enumerable:!0,get(){return this._selfVisible&&!this.hiddenByEditor},set(n){this._selfVisible=n,this.properties!==void 0&&(this.properties.visible=n)}});var U=class n extends I{_opacity;visibleOpacity;opacityMaterials=new Set;visibilityFade=null;constructor(e,t="Node3D"){super({...e,type:t}),e.position&&this.position.copy(e.position),e.rotation?this.rotation.copy(e.rotation):this.rotation.set(0,0,0),this.rotation.order=e.rotationOrder??this.rotation.order,e.scale&&this.scale.copy(e.scale),this._opacity=n.clampOpacity(e.opacity??1),this.visibleOpacity=this._opacity>0?this._opacity:1}get opacity(){return this._opacity}set opacity(e){let t=n.clampOpacity(e);this._opacity!==t&&(this._opacity=t,!this.visibilityFade&&t>0&&(this.visibleOpacity=t),this.applyOpacityToMaterials())}hide(e=0,t){let i=n.toNonNegativeSeconds(e);if(this.opacity>0&&(this.visibleOpacity=this.opacity),i===0){this.visibilityFade=null,this.opacity=0,this.setVisibleState(!1),t?.();return}this.setVisibleState(!0),this.visibilityFade={from:this.opacity,to:0,duration:i,elapsed:0,hideAfterComplete:!0,onComplete:t}}show(e=0,t){let i=n.toNonNegativeSeconds(e),r=this.visibleOpacity>0?this.visibleOpacity:1;if(this.setVisibleState(!0),i===0){this.visibilityFade=null,this.opacity=r,t?.();return}this.visibilityFade={from:this.opacity,to:r,duration:i,elapsed:0,hideAfterComplete:!1,onComplete:t}}tick(e){if(super.tick(e),!this.visibilityFade)return;let t=this.visibilityFade;t.elapsed=Math.min(t.duration,t.elapsed+Math.max(0,e));let i=t.duration>0?t.elapsed/t.duration:1;this.opacity=t.from+(t.to-t.from)*i,!(t.elapsed<t.duration)&&(this.opacity=t.to,this.visibilityFade=null,t.hideAfterComplete&&this.setVisibleState(!1),t.onComplete?.())}registerOpacityMaterial(e,t){t!==void 0?e.userData.__pix3BaseOpacity=n.clampOpacity(t):typeof e.userData.__pix3BaseOpacity!="number"&&(e.userData.__pix3BaseOpacity=n.clampOpacity(e.opacity)),e.userData.__pix3OriginalTransparent===void 0&&(e.userData.__pix3OriginalTransparent=e.transparent),this.opacityMaterials.add(e),this.applyOpacityToMaterial(e)}applyOpacityToMaterials(){for(let e of this.opacityMaterials)this.applyOpacityToMaterial(e)}applyOpacityToMaterial(e){let t=e.userData.__pix3BaseOpacity,i=typeof t=="number"?n.clampOpacity(t):n.clampOpacity(e.opacity);e.opacity=i*this._opacity;let r=e.userData.__pix3OriginalTransparent;e.transparent=!!r||e.opacity<1,e.needsUpdate=!0}setVisibleState(e){this.visible=e,this.properties.visible=e}static clampOpacity(e){let t=Number.isFinite(e)?e:1;return Math.max(0,Math.min(1,t))}static toNonNegativeSeconds(e){return Number.isFinite(e)?Math.max(0,e):0}get treeColor(){return"#fe9ebeff"}get treeIcon(){return"box"}static getPropertySchema(){let e=I.getPropertySchema();return{nodeType:"Node3D",extends:"NodeBase",properties:[...e.properties,{name:"position",type:"vector3",ui:{label:"Position",group:"Transform",step:.01,precision:2},getValue:t=>{let i=t;return{x:i.position.x,y:i.position.y,z:i.position.z}},setValue:(t,i)=>{let r=t,o=i;r.position.x=o.x,r.position.y=o.y,r.position.z=o.z}},{name:"rotation",type:"euler",ui:{label:"Rotation",description:"Pitch (X), Yaw (Y), Roll (Z)",group:"Transform",step:.1,precision:1,unit:"\xB0"},getValue:t=>{let i=t;return{x:i.rotation.x*(180/Math.PI),y:i.rotation.y*(180/Math.PI),z:i.rotation.z*(180/Math.PI)}},setValue:(t,i)=>{let r=t,o=i;r.rotation.x=o.x*(Math.PI/180),r.rotation.y=o.y*(Math.PI/180),r.rotation.z=o.z*(Math.PI/180)}},{name:"scale",type:"vector3",ui:{label:"Scale",group:"Transform",step:.01,precision:2,min:0},getValue:t=>{let i=t;return{x:i.scale.x,y:i.scale.y,z:i.scale.z}},setValue:(t,i)=>{let r=t,o=i;r.scale.x=o.x,r.scale.y=o.y,r.scale.z=o.z}}],groups:{...e.groups,Transform:{label:"Transform",description:"3D position, rotation, and scale",expanded:!0}}}}};var zm=Symbol("pix3.reactiveSchemaProperties"),Um=Symbol("pix3.reactiveSchemaPropertiesInFlight"),Wm=(n,e)=>{let t=Object.getOwnPropertyDescriptor(n,e);return t!==void 0&&t.writable===!0&&!("get"in t)};function Hm(n,e){let{name:t,setValue:i}=e,r=Object.getOwnPropertyDescriptor(n,t);if(r===void 0)return"skipped-missing";if(!Wm(n,t))return"skipped-accessor";let o=r.value,s=!1,a=n;return Object.defineProperty(n,t,{configurable:!0,enumerable:r.enumerable,get:()=>o,set(l){let c=a[Um]??=new Set;if(c.has(t)){o=l,s=!0;return}c.add(t),s=!1;try{i(n,l),!s&&(o===null||typeof o!="object")&&(o=e.getValue(n))}finally{c.delete(t)}}}),"installed"}var Fm=new WeakMap,Uw=n=>{if(typeof n!="function")return n;let e=Fm.get(n);if(e)return e;let t=n();return Fm.set(n,t),t};function H(n,e){let t=Uw(e),i=n,r=i[zm]??=new Set,o=[];for(let s of t.properties)r.has(s.name)&&!Wm(n,s.name)||Hm(n,s)==="installed"&&(r.add(s.name),o.push(s.name));return o}function Ww(n){return n[zm]??new Set}function Rt(n,e,t){let i=n,r=i[Um]??=new Set,o=r.has(e);r.add(e);try{n[e]=t}finally{o||r.delete(e)}}var ht=class n extends U{src;castShadow;receiveShadow;animations=[];mixer=null;currentAction=null;activeAnimation=null;initialAnimation;_isPlaying;_isLoop;hasAttemptedInitialAnimation=!1;constructor(e){super(e,"MeshInstance"),this.src=e.src??null,this.castShadow=e.castShadow??!0,this.receiveShadow=e.receiveShadow??!0,this.initialAnimation=e.initialAnimation??null,this._isPlaying=e.isPlaying??!0,this._isLoop=e.isLoop??!0,H(this,n.getPropertySchema)}get isPlaying(){return this._isPlaying}set isPlaying(e){let t=!!e;this._isPlaying!==t&&(this._isPlaying=t,this.currentAction&&(this.currentAction.paused=!t,t&&this.currentAction.play()),t&&!this.currentAction&&(this.hasAttemptedInitialAnimation=!1))}get isLoop(){return this._isLoop}set isLoop(e){let t=!!e;this._isLoop!==t&&(this._isLoop=t,this.currentAction&&this.applyLoopMode(this.currentAction))}playAnimation(e,t){this.isPlaying=!0,this.setAnimation(e,t)}setAnimation(e,t){let i=this.animations.find(r=>r.name===e);if(!i){console.warn(`[MeshInstance] Animation '${e}' not found on node ${this.nodeId}`);return}this.mixer||(this.mixer=new ss(this)),this.currentAction&&this.currentAction.stop(),this.currentAction=this.mixer.clipAction(i),this.applyLoopMode(this.currentAction,t),this.currentAction.reset().play(),this.mixer.update(0),this.currentAction.paused=!this._isPlaying,this.activeAnimation=e,this.hasAttemptedInitialAnimation=!0}showDefaultPose(){if(this.animations.length===0){this.mixer&&this.mixer.stopAllAction(),this.currentAction=null,this.activeAnimation=null,this.hasAttemptedInitialAnimation=!1;return}let t=(this.initialAnimation?this.animations.find(r=>r.name===this.initialAnimation):null)??this.animations[0];this.mixer||(this.mixer=new ss(this)),this.currentAction&&this.currentAction.stop();let i=this.mixer.clipAction(t);i.reset().play(),this.mixer.update(0),i.paused=!0,this.currentAction=i,this.activeAnimation=t.name,this.hasAttemptedInitialAnimation=!1}tick(e){super.tick(e),this.playInitialAnimationIfNeeded(),this.mixer&&this._isPlaying&&this.mixer.update(e)}playInitialAnimationIfNeeded(){if(this.hasAttemptedInitialAnimation||this.animations.length===0)return;let e=this.initialAnimation?this.animations.find(i=>i.name===this.initialAnimation):null;this.initialAnimation&&!e&&console.warn(`[MeshInstance] Initial animation '${this.initialAnimation}' not found on node ${this.nodeId}. Falling back to first clip.`);let t=e??this.animations[0];this.setAnimation(t.name)}applyLoopMode(e,t){if(t!==void 0?t:this._isLoop){e.setLoop(cm,1/0),e.clampWhenFinished=!1;return}e.setLoop(lm,1),e.clampWhenFinished=!0}static getPropertySchema(){let e=U.getPropertySchema();return{nodeType:"MeshInstance",extends:"Node3D",properties:[...e.properties,{name:"isPlaying",type:"boolean",ui:{label:"IsPlaying",description:"Whether animation starts and keeps advancing at runtime",group:"Animation"},getValue:t=>t.isPlaying,setValue:(t,i)=>{let r=t;r.isPlaying=!!i}},{name:"isLoop",type:"boolean",ui:{label:"IsLoop",description:"Whether animation repeats after reaching the end",group:"Animation"},getValue:t=>t.isLoop,setValue:(t,i)=>{let r=t;r.isLoop=!!i}},{name:"initialAnimation",type:"string",ui:{label:"Initial Animation",description:"Clip name to auto-play on scene start (uses first clip when empty)",group:"Animation"},getValue:t=>t.initialAnimation??"",setValue:(t,i)=>{let r=t,o=typeof i=="string"?i.trim():"";r.initialAnimation=o.length>0?o:null,r.showDefaultPose()}},{name:"castShadow",type:"boolean",ui:{label:"Cast Shadow",description:"Whether this mesh casts shadows in the scene",group:"Rendering"},getValue:t=>t.castShadow,setValue:(t,i)=>{let r=t,o=!!i;r.castShadow=o,n.applyShadowPropertiesToChildren(r,o,r.receiveShadow)}},{name:"receiveShadow",type:"boolean",ui:{label:"Receive Shadow",description:"Whether this mesh receives shadows from other objects",group:"Rendering"},getValue:t=>t.receiveShadow,setValue:(t,i)=>{let r=t,o=!!i;r.receiveShadow=o,n.applyShadowPropertiesToChildren(r,r.castShadow,o)}}],groups:{...e.groups,Animation:{label:"Animation",description:"Animation playback properties",expanded:!0},Rendering:{label:"Rendering",description:"Shadow and rendering properties",expanded:!0}}}}static applyShadowPropertiesToChildren(e,t,i){e instanceof O&&(e.castShadow=t,e.receiveShadow=i);for(let r of e.children)n.applyShadowPropertiesToChildren(r,t,i)}applyLoadedShadowProperties(){n.applyShadowPropertiesToChildren(this,this.castShadow,this.receiveShadow)}};function pi(n,e){return e?e.texturePath.trim().length>0?e.texturePath.trim():n?.texturePath?.trim()??"":""}function cc(n){return!!n?.texturePath?.trim()}function Hw(n){let e=typeof n=="object"&&n!==null?n:{},t=typeof e.x=="number"?e.x:.5,i=typeof e.y=="number"?e.y:.5;return{x:t,y:i}}function lc(n){let e=typeof n=="object"&&n!==null?n:{},t=typeof e.x=="number"?e.x:0,i=typeof e.y=="number"?e.y:0;return{x:t,y:i}}function $e(n,e=0){return typeof n=="number"&&Number.isFinite(n)?n:e}function qw(n){let e=typeof n=="object"&&n!==null?n:{};return{x:$e(e.x),y:$e(e.y),width:Math.max(0,$e(e.width)),height:Math.max(0,$e(e.height))}}function Gw(n){return lc(n)}function jw(n){if(!Array.isArray(n))return[];let e=[];for(let t of n){let i=typeof t=="object"&&t!==null?t:{},r=typeof i.signal=="string"?i.signal.trim():"";if(r.length===0)continue;let o=typeof i.args=="string"?i.args:"";e.push({signal:r,args:o})}return e}function $w(n){if(!Array.isArray(n))return[];let e=[],t=new Set;for(let i of n){let r=typeof i=="object"&&i!==null?i:{},o=typeof r.name=="string"?r.name.trim():"";if(o.length===0||t.has(o))continue;t.add(o);let s=$e(r.angle);e.push({name:o,x:$e(r.x,.5),y:$e(r.y,.5),...s!==0?{angle:s}:{}})}return e}function Yw(n,e){let t=typeof n=="object"&&n!==null?n:null,i=Math.max(0,$e(t?.width)),r=Math.max(0,$e(t?.height));return i>0&&r>0?{width:i,height:r}:{width:e.width,height:e.height}}function Kw(n){return n==="ping-pong"?"ping-pong":"normal"}function Xw(n){let e=typeof n=="object"&&n!==null?n:{},t=typeof e.textureIndex=="number"?Math.max(0,Math.floor(e.textureIndex)):0,i=qw(e.boundingBox);return{textureIndex:t,offset:lc(e.offset),repeat:lc(e.repeat),durationMultiplier:Math.max(.001,$e(e.durationMultiplier,1)),anchor:Hw(e.anchor),texturePath:typeof e.texturePath=="string"?e.texturePath.trim():"",boundingBox:i,collisionPolygon:Array.isArray(e.collisionPolygon)?(e.collisionPolygon??[]).map(Gw):[],events:jw(e.events),sourceSize:Yw(e.sourceSize,i),points:$w(e.points)}}function uc(n,e){return!n?.points||e.length===0?null:n.points.find(t=>t.name===e)??null}function hc(n){let e=[],t=new Set;for(let i of n?.frames??[])for(let r of i.points??[])t.has(r.name)||(t.add(r.name),e.push(r.name));return e}function Qw(n,e){let t=typeof n=="object"&&n!==null?n:{},i=Array.isArray(t.frames)?t.frames??[]:[];return{name:typeof t.name=="string"&&t.name.trim().length>0?t.name.trim():`clip-${e+1}`,frames:i.map(Xw),fps:typeof t.fps=="number"&&Number.isFinite(t.fps)&&t.fps>0?t.fps:12,loop:typeof t.loop=="boolean"?t.loop:!0,playbackMode:Kw(t.playbackMode)}}function dc(n){let e=typeof n=="object"&&n!==null?n:{},t=Array.isArray(e.clips)?e.clips??[]:[];return{version:typeof e.version=="string"&&e.version.trim().length>0?e.version.trim():"1.0.0",texturePath:typeof e.texturePath=="string"?e.texturePath.trim():"",clips:t.map(Qw)}}function pc(n,e){return!n||n.clips.length===0?null:e?n.clips.find(t=>t.name===e)??n.clips[0]??null:n.clips[0]??null}var qm=["linear","nearest"],Gm="__PIX3_PROJECT_TEXTURE_FILTERING__",Jw="linear";function mc(n){let e=typeof n=="string"?n.toLowerCase():"";return qm.includes(e)?e:Jw}function Zw(n){globalThis[Gm]=mc(n)}function fc(){return mc(globalThis[Gm])}function $(n){let e=fc()==="nearest"?Lr:Qi;n.colorSpace===Pe&&n.generateMipmaps===!1&&n.minFilter===e&&n.magFilter===e||(n.colorSpace=Pe,n.generateMipmaps=!1,n.minFilter=e,n.magFilter=e,n.needsUpdate=!0)}var us=n=>typeof n=="number"&&Number.isFinite(n),hs=n=>Math.min(1,Math.max(0,n));function gc(n){if(!n||!us(n.x)||!us(n.y)||!us(n.width)||!us(n.height))return null;let e=hs(n.width),t=hs(n.height);return e<=0||t<=0?null:{x:hs(n.x),y:hs(n.y),width:e,height:t}}function mi(n,e){e?(n.offset.set(e.x,e.y),n.repeat.set(e.width,e.height)):(n.offset.set(0,0),n.repeat.set(1,1))}function jr(n,e){return n?e?{x:n.x+e.x*n.width,y:n.y+e.y*n.height,width:e.width*n.width,height:e.height*n.height}:n:e}function ex(n,e){return n===e?!0:!n||!e?!1:n.x===e.x&&n.y===e.y&&n.width===e.width&&n.height===e.height}var tx="pix3atlas://",ix="pix3AtlasRegion",rx="pix3AtlasSize";function $r(n){return n?n.userData.pix3AtlasRegion??null:null}function Yr(n){return n?n.userData.pix3AtlasSize??null:null}function yc(n,e,t){let i=n.userData;i.pix3AtlasRegion=e,i.pix3AtlasSize=t}function bc(n,e){let t=n.userData,i=e.userData;t.pix3AtlasRegion&&(i.pix3AtlasRegion=t.pix3AtlasRegion),t.pix3AtlasSize&&(i.pix3AtlasSize=t.pix3AtlasSize)}function Sc(n,e){let t=new Map(n.sheets.map(r=>[r.id,r])),i=new Map;for(let[r,o]of Object.entries(n.frames)){let s=t.get(o.sheet);if(!s)continue;let a=s.width,l=s.height;i.set(r,{sheetPath:e(o.sheet),region:{x:o.x/a,y:1-(o.y+o.h)/l,width:o.w/a,height:o.h/l},pixelWidth:o.w,pixelHeight:o.h})}return{resolve(r){return i.get(r)??null}}}var ar=null,Kr=null;function nx(n){ar!==n&&(ar=n,Kr=null)}function ox(){return ar!==null}function vc(){if(!ar)return Promise.reject(new Error('[Spine] No Spine runtime registered. Install `@esotericsoftware/spine-threejs` (~4.3) and call `setSpineModuleLoader(() => import("@esotericsoftware/spine-threejs"))` during startup before using SpineSkeleton2D.'));if(!Kr){let n=ar;Kr=n().catch(e=>{throw ar===n&&(Kr=null),e})}return Kr}function lr(n){return`${n.skeletonPath}|${n.atlasPath}|${n.texturePath??""}`}function jm(n,e){let t=e.trim().replace(/^\.\//,"");if(/^[a-z]+[a-z0-9+.-]*:\/\//i.test(t)||t.startsWith("/"))return t;let i=n.lastIndexOf("/");return i<0?t:`${n.slice(0,i+1)}${t}`}var sx=/\.(png|jpg|jpeg|webp|ktx2|basis|bmp)$/i;function ax(n){let e=[],t=!0;for(let i of n.split(/\r?\n/)){if(i.trim().length===0){t=!0;continue}if(t){let r=i.trim();sx.test(r)&&e.push(r),t=!1}}return e}function lx(n){return n.trim().toLowerCase().endsWith(".skel")}function wc(n){return n instanceof Error?n.message:String(n)}async function xc(n,e){let t=await vc(),{skeletonPath:i,atlasPath:r}=e,o=await n.readText(r),s;try{s=new t.TextureAtlas(o)}catch(h){throw new Error(`[Spine] Failed to parse atlas ${r}: ${wc(h)}`)}let a=[],l=[],c=s.pages.length===1&&e.texturePath?e.texturePath:null;try{for(let h of s.pages){let d=c??jm(r,h.name);a.push(d);let p=await n.readBlob(d),f=await createImageBitmap(p),m=new t.ThreeJsTexture(f,h.pma);l.push(m),h.setTexture(m),$(m.texture)}}catch(h){for(let d of l)d.dispose();throw new Error(`[Spine] Failed to load atlas pages for ${r}: ${wc(h)}`)}let u;try{let h=new t.AtlasAttachmentLoader(s);if(lx(i)){let p=await(await n.readBlob(i)).arrayBuffer();u=new t.SkeletonBinary(h).readSkeletonData(new Uint8Array(p))}else{let d=await n.readText(i);u=new t.SkeletonJson(h).readSkeletonData(d)}}catch(h){for(let d of l)d.dispose();throw new Error(`[Spine] Failed to read skeleton ${i} (atlas ${r}): ${wc(h)}. Check that the skeleton was exported from a Spine version matching the installed @esotericsoftware/spine-threejs release.`)}return{key:lr(e),spine:t,skeletonData:u,atlas:s,pagePaths:a,dispose:()=>{s.dispose()}}}function Pc(n,e){if(e===hm)return console.warn("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Geometry already defined as triangles."),n;if(e===_r||e===Xo){let t=n.getIndex();if(t===null){let s=[],a=n.getAttribute("position");if(a!==void 0){for(let l=0;l<a.count;l++)s.push(l);n.setIndex(s),t=n.getIndex()}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Undefined position attribute. Processing not possible."),n}let i=t.count-2,r=[];if(e===_r)for(let s=1;s<=i;s++)r.push(t.getX(0)),r.push(t.getX(s)),r.push(t.getX(s+1));else for(let s=0;s<i;s++)s%2===0?(r.push(t.getX(s)),r.push(t.getX(s+1)),r.push(t.getX(s+2))):(r.push(t.getX(s+2)),r.push(t.getX(s+1)),r.push(t.getX(s)));r.length/3!==i&&console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unable to generate correct amount of triangles.");let o=n.clone();return o.setIndex(r),o.clearGroups(),o}else return console.error("THREE.BufferGeometryUtils.toTrianglesDrawMode(): Unknown draw mode:",e),n}function $m(n){let e=new Map,t=new Map,i=n.clone();return Ym(n,i,function(r,o){e.set(o,r),t.set(r,o)}),i.traverse(function(r){if(!r.isSkinnedMesh)return;let o=r,s=e.get(r),a=s.skeleton.bones;o.skeleton=s.skeleton.clone(),o.bindMatrix.copy(s.bindMatrix),o.skeleton.bones=a.map(function(l){return t.get(l)}),o.bind(o.skeleton,o.bindMatrix)}),i}function Ym(n,e,t){t(n,e);for(let i=0;i<n.children.length;i++)Ym(n.children[i],e.children[i],t)}var ds=class extends Cm{constructor(e){super(e),this.dracoLoader=null,this.ktx2Loader=null,this.meshoptDecoder=null,this.pluginCallbacks=[],this.register(function(t){return new Ec(t)}),this.register(function(t){return new Nc(t)}),this.register(function(t){return new zc(t)}),this.register(function(t){return new Uc(t)}),this.register(function(t){return new Wc(t)}),this.register(function(t){return new Rc(t)}),this.register(function(t){return new Bc(t)}),this.register(function(t){return new Oc(t)}),this.register(function(t){return new Vc(t)}),this.register(function(t){return new Dc(t)}),this.register(function(t){return new Lc(t)}),this.register(function(t){return new Ic(t)}),this.register(function(t){return new Fc(t)}),this.register(function(t){return new _c(t)}),this.register(function(t){return new Cc(t)}),this.register(function(t){return new ps(t,W.EXT_MESHOPT_COMPRESSION)}),this.register(function(t){return new ps(t,W.KHR_MESHOPT_COMPRESSION)}),this.register(function(t){return new Hc(t)})}load(e,t,i,r){let o=this,s;if(this.resourcePath!=="")s=this.resourcePath;else if(this.path!==""){let c=or.extractUrlBase(e);s=or.resolveURL(c,this.path)}else s=or.extractUrlBase(e);this.manager.itemStart(e);let a=function(c){r?r(c):console.error(c),o.manager.itemError(e),o.manager.itemEnd(e)},l=new Jl(this.manager);l.setPath(this.path),l.setResponseType("arraybuffer"),l.setRequestHeader(this.requestHeader),l.setWithCredentials(this.withCredentials),l.load(e,function(c){try{o.parse(c,s,function(u){t(u),o.manager.itemEnd(e)},a)}catch(u){a(u)}},i,a)}setDRACOLoader(e){return this.dracoLoader=e,this}setKTX2Loader(e){return this.ktx2Loader=e,this}setMeshoptDecoder(e){return this.meshoptDecoder=e,this}register(e){return this.pluginCallbacks.indexOf(e)===-1&&this.pluginCallbacks.push(e),this}unregister(e){return this.pluginCallbacks.indexOf(e)!==-1&&this.pluginCallbacks.splice(this.pluginCallbacks.indexOf(e),1),this}parse(e,t,i,r){let o,s={},a={},l=new TextDecoder;if(typeof e=="string")o=JSON.parse(e);else if(e instanceof ArrayBuffer)if(l.decode(new Uint8Array(e,0,4))===Zm){try{s[W.KHR_BINARY_GLTF]=new qc(e)}catch(h){r&&r(h);return}o=JSON.parse(s[W.KHR_BINARY_GLTF].content)}else o=JSON.parse(l.decode(e));else o=e;if(o.asset===void 0||o.asset.version[0]<2){r&&r(new Error("THREE.GLTFLoader: Unsupported asset. glTF versions >=2.0 are supported."));return}let c=new Qc(o,{path:t||this.resourcePath||"",crossOrigin:this.crossOrigin,requestHeader:this.requestHeader,manager:this.manager,ktx2Loader:this.ktx2Loader,meshoptDecoder:this.meshoptDecoder});c.fileLoader.setRequestHeader(this.requestHeader);for(let u=0;u<this.pluginCallbacks.length;u++){let h=this.pluginCallbacks[u](c);h.name||console.error("THREE.GLTFLoader: Invalid plugin found: missing name"),a[h.name]=h,s[h.name]=!0}if(o.extensionsUsed)for(let u=0;u<o.extensionsUsed.length;++u){let h=o.extensionsUsed[u],d=o.extensionsRequired||[];switch(h){case W.KHR_MATERIALS_UNLIT:s[h]=new Mc;break;case W.KHR_DRACO_MESH_COMPRESSION:s[h]=new Gc(o,this.dracoLoader);break;case W.KHR_TEXTURE_TRANSFORM:s[h]=new jc;break;case W.KHR_MESH_QUANTIZATION:s[h]=new $c;break;default:d.indexOf(h)>=0&&a[h]===void 0&&console.warn('THREE.GLTFLoader: Unknown extension "'+h+'".')}}c.setExtensions(s),c.setPlugins(a),c.parse(i,r)}parseAsync(e,t){let i=this;return new Promise(function(r,o){i.parse(e,t,r,o)})}};function cx(){let n={};return{get:function(e){return n[e]},add:function(e,t){n[e]=t},remove:function(e){delete n[e]},removeAll:function(){n={}}}}function te(n,e,t){let i=n.json.materials[e];return i.extensions&&i.extensions[t]?i.extensions[t]:null}var W={KHR_BINARY_GLTF:"KHR_binary_glTF",KHR_DRACO_MESH_COMPRESSION:"KHR_draco_mesh_compression",KHR_LIGHTS_PUNCTUAL:"KHR_lights_punctual",KHR_MATERIALS_CLEARCOAT:"KHR_materials_clearcoat",KHR_MATERIALS_DISPERSION:"KHR_materials_dispersion",KHR_MATERIALS_IOR:"KHR_materials_ior",KHR_MATERIALS_SHEEN:"KHR_materials_sheen",KHR_MATERIALS_SPECULAR:"KHR_materials_specular",KHR_MATERIALS_TRANSMISSION:"KHR_materials_transmission",KHR_MATERIALS_IRIDESCENCE:"KHR_materials_iridescence",KHR_MATERIALS_ANISOTROPY:"KHR_materials_anisotropy",KHR_MATERIALS_UNLIT:"KHR_materials_unlit",KHR_MATERIALS_VOLUME:"KHR_materials_volume",KHR_TEXTURE_BASISU:"KHR_texture_basisu",KHR_TEXTURE_TRANSFORM:"KHR_texture_transform",KHR_MESH_QUANTIZATION:"KHR_mesh_quantization",KHR_MATERIALS_EMISSIVE_STRENGTH:"KHR_materials_emissive_strength",EXT_MATERIALS_BUMP:"EXT_materials_bump",EXT_TEXTURE_WEBP:"EXT_texture_webp",EXT_TEXTURE_AVIF:"EXT_texture_avif",EXT_MESHOPT_COMPRESSION:"EXT_meshopt_compression",KHR_MESHOPT_COMPRESSION:"KHR_meshopt_compression",EXT_MESH_GPU_INSTANCING:"EXT_mesh_gpu_instancing"},Cc=class{constructor(e){this.parser=e,this.name=W.KHR_LIGHTS_PUNCTUAL,this.cache={refs:{},uses:{}}}_markDefs(){let e=this.parser,t=this.parser.json.nodes||[];for(let i=0,r=t.length;i<r;i++){let o=t[i];o.extensions&&o.extensions[this.name]&&o.extensions[this.name].light!==void 0&&e._addNodeRef(this.cache,o.extensions[this.name].light)}}_loadLight(e){let t=this.parser,i="light:"+e,r=t.cache.get(i);if(r)return r;let o=t.json,l=((o.extensions&&o.extensions[this.name]||{}).lights||[])[e],c,u=new L(16777215);l.color!==void 0&&u.setRGB(l.color[0],l.color[1],l.color[2],Ge);let h=l.range!==void 0?l.range:0;switch(l.type){case"directional":c=new os(u),c.target.position.set(0,0,-1),c.add(c.target);break;case"point":c=new ns(u),c.distance=h;break;case"spot":c=new rs(u),c.distance=h,l.spot=l.spot||{},l.spot.innerConeAngle=l.spot.innerConeAngle!==void 0?l.spot.innerConeAngle:0,l.spot.outerConeAngle=l.spot.outerConeAngle!==void 0?l.spot.outerConeAngle:Math.PI/4,c.angle=l.spot.outerConeAngle,c.penumbra=1-l.spot.innerConeAngle/l.spot.outerConeAngle,c.target.position.set(0,0,-1),c.add(c.target);break;default:throw new Error("THREE.GLTFLoader: Unexpected light type: "+l.type)}return c.position.set(0,0,0),Ye(c,l),l.intensity!==void 0&&(c.intensity=l.intensity),c.name=t.createUniqueName(l.name||"light_"+e),r=Promise.resolve(c),t.cache.add(i,r),r}getDependency(e,t){if(e==="light")return this._loadLight(t)}createNodeAttachment(e){let t=this,i=this.parser,o=i.json.nodes[e],a=(o.extensions&&o.extensions[this.name]||{}).light;return a===void 0?null:this._loadLight(a).then(function(l){return i._getNodeRef(t.cache,a,l)})}},Mc=class{constructor(){this.name=W.KHR_MATERIALS_UNLIT}getMaterialType(){return B}extendParams(e,t,i){let r=[];e.color=new L(1,1,1),e.opacity=1;let o=t.pbrMetallicRoughness;if(o){if(Array.isArray(o.baseColorFactor)){let s=o.baseColorFactor;e.color.setRGB(s[0],s[1],s[2],Ge),e.opacity=s[3]}o.baseColorTexture!==void 0&&r.push(i.assignTexture(e,"map",o.baseColorTexture,Pe))}return Promise.all(r)}},Dc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_EMISSIVE_STRENGTH}extendMaterialParams(e,t){let i=te(this.parser,e,this.name);return i===null||i.emissiveStrength!==void 0&&(t.emissiveIntensity=i.emissiveStrength),Promise.resolve()}},Ec=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_CLEARCOAT}getMaterialType(e){return te(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let i=te(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];if(i.clearcoatFactor!==void 0&&(t.clearcoat=i.clearcoatFactor),i.clearcoatTexture!==void 0&&r.push(this.parser.assignTexture(t,"clearcoatMap",i.clearcoatTexture)),i.clearcoatRoughnessFactor!==void 0&&(t.clearcoatRoughness=i.clearcoatRoughnessFactor),i.clearcoatRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,"clearcoatRoughnessMap",i.clearcoatRoughnessTexture)),i.clearcoatNormalTexture!==void 0&&(r.push(this.parser.assignTexture(t,"clearcoatNormalMap",i.clearcoatNormalTexture)),i.clearcoatNormalTexture.scale!==void 0)){let o=i.clearcoatNormalTexture.scale;t.clearcoatNormalScale=new N(o,o)}return Promise.all(r)}},Nc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_DISPERSION}getMaterialType(e){return te(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let i=te(this.parser,e,this.name);return i===null||(t.dispersion=i.dispersion!==void 0?i.dispersion:0),Promise.resolve()}},Ic=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_IRIDESCENCE}getMaterialType(e){return te(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let i=te(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];return i.iridescenceFactor!==void 0&&(t.iridescence=i.iridescenceFactor),i.iridescenceTexture!==void 0&&r.push(this.parser.assignTexture(t,"iridescenceMap",i.iridescenceTexture)),i.iridescenceIor!==void 0&&(t.iridescenceIOR=i.iridescenceIor),t.iridescenceThicknessRange===void 0&&(t.iridescenceThicknessRange=[100,400]),i.iridescenceThicknessMinimum!==void 0&&(t.iridescenceThicknessRange[0]=i.iridescenceThicknessMinimum),i.iridescenceThicknessMaximum!==void 0&&(t.iridescenceThicknessRange[1]=i.iridescenceThicknessMaximum),i.iridescenceThicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,"iridescenceThicknessMap",i.iridescenceThicknessTexture)),Promise.all(r)}},Rc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_SHEEN}getMaterialType(e){return te(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let i=te(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];if(t.sheenColor=new L(0,0,0),t.sheenRoughness=0,t.sheen=1,i.sheenColorFactor!==void 0){let o=i.sheenColorFactor;t.sheenColor.setRGB(o[0],o[1],o[2],Ge)}return i.sheenRoughnessFactor!==void 0&&(t.sheenRoughness=i.sheenRoughnessFactor),i.sheenColorTexture!==void 0&&r.push(this.parser.assignTexture(t,"sheenColorMap",i.sheenColorTexture,Pe)),i.sheenRoughnessTexture!==void 0&&r.push(this.parser.assignTexture(t,"sheenRoughnessMap",i.sheenRoughnessTexture)),Promise.all(r)}},Bc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_TRANSMISSION}getMaterialType(e){return te(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let i=te(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];return i.transmissionFactor!==void 0&&(t.transmission=i.transmissionFactor),i.transmissionTexture!==void 0&&r.push(this.parser.assignTexture(t,"transmissionMap",i.transmissionTexture)),Promise.all(r)}},Oc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_VOLUME}getMaterialType(e){return te(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let i=te(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];t.thickness=i.thicknessFactor!==void 0?i.thicknessFactor:0,i.thicknessTexture!==void 0&&r.push(this.parser.assignTexture(t,"thicknessMap",i.thicknessTexture)),t.attenuationDistance=i.attenuationDistance||1/0;let o=i.attenuationColor||[1,1,1];return t.attenuationColor=new L().setRGB(o[0],o[1],o[2],Ge),Promise.all(r)}},Vc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_IOR}getMaterialType(e){return te(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let i=te(this.parser,e,this.name);return i===null||(t.ior=i.ior!==void 0?i.ior:1.5),Promise.resolve()}},Lc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_SPECULAR}getMaterialType(e){return te(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let i=te(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];t.specularIntensity=i.specularFactor!==void 0?i.specularFactor:1,i.specularTexture!==void 0&&r.push(this.parser.assignTexture(t,"specularIntensityMap",i.specularTexture));let o=i.specularColorFactor||[1,1,1];return t.specularColor=new L().setRGB(o[0],o[1],o[2],Ge),i.specularColorTexture!==void 0&&r.push(this.parser.assignTexture(t,"specularColorMap",i.specularColorTexture,Pe)),Promise.all(r)}},_c=class{constructor(e){this.parser=e,this.name=W.EXT_MATERIALS_BUMP}getMaterialType(e){return te(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let i=te(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];return t.bumpScale=i.bumpFactor!==void 0?i.bumpFactor:1,i.bumpTexture!==void 0&&r.push(this.parser.assignTexture(t,"bumpMap",i.bumpTexture)),Promise.all(r)}},Fc=class{constructor(e){this.parser=e,this.name=W.KHR_MATERIALS_ANISOTROPY}getMaterialType(e){return te(this.parser,e,this.name)!==null?Ve:null}extendMaterialParams(e,t){let i=te(this.parser,e,this.name);if(i===null)return Promise.resolve();let r=[];return i.anisotropyStrength!==void 0&&(t.anisotropy=i.anisotropyStrength),i.anisotropyRotation!==void 0&&(t.anisotropyRotation=i.anisotropyRotation),i.anisotropyTexture!==void 0&&r.push(this.parser.assignTexture(t,"anisotropyMap",i.anisotropyTexture)),Promise.all(r)}},zc=class{constructor(e){this.parser=e,this.name=W.KHR_TEXTURE_BASISU}loadTexture(e){let t=this.parser,i=t.json,r=i.textures[e];if(!r.extensions||!r.extensions[this.name])return null;let o=r.extensions[this.name],s=t.options.ktx2Loader;if(!s){if(i.extensionsRequired&&i.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setKTX2Loader must be called before loading KTX2 textures");return null}return t.loadTextureImage(e,o.source,s)}},Uc=class{constructor(e){this.parser=e,this.name=W.EXT_TEXTURE_WEBP}loadTexture(e){let t=this.name,i=this.parser,r=i.json,o=r.textures[e];if(!o.extensions||!o.extensions[t])return null;let s=o.extensions[t],a=r.images[s.source],l=i.textureLoader;if(a.uri){let c=i.options.manager.getHandler(a.uri);c!==null&&(l=c)}return i.loadTextureImage(e,s.source,l)}},Wc=class{constructor(e){this.parser=e,this.name=W.EXT_TEXTURE_AVIF}loadTexture(e){let t=this.name,i=this.parser,r=i.json,o=r.textures[e];if(!o.extensions||!o.extensions[t])return null;let s=o.extensions[t],a=r.images[s.source],l=i.textureLoader;if(a.uri){let c=i.options.manager.getHandler(a.uri);c!==null&&(l=c)}return i.loadTextureImage(e,s.source,l)}},ps=class{constructor(e,t){this.name=t,this.parser=e}loadBufferView(e){let t=this.parser.json,i=t.bufferViews[e];if(i.extensions&&i.extensions[this.name]){let r=i.extensions[this.name],o=this.parser.getDependency("buffer",r.buffer),s=this.parser.options.meshoptDecoder;if(!s||!s.supported){if(t.extensionsRequired&&t.extensionsRequired.indexOf(this.name)>=0)throw new Error("THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed files");return null}return o.then(function(a){let l=r.byteOffset||0,c=r.byteLength||0,u=r.count,h=r.byteStride,d=new Uint8Array(a,l,c);return s.decodeGltfBufferAsync?s.decodeGltfBufferAsync(u,h,d,r.mode,r.filter).then(function(p){return p.buffer}):s.ready.then(function(){let p=new ArrayBuffer(u*h);return s.decodeGltfBuffer(new Uint8Array(p),u,h,d,r.mode,r.filter),p})})}else return null}},Hc=class{constructor(e){this.name=W.EXT_MESH_GPU_INSTANCING,this.parser=e}createNodeMesh(e){let t=this.parser.json,i=t.nodes[e];if(!i.extensions||!i.extensions[this.name]||i.mesh===void 0)return null;let r=t.meshes[i.mesh];for(let c of r.primitives)if(c.mode!==Ee.TRIANGLES&&c.mode!==Ee.TRIANGLE_STRIP&&c.mode!==Ee.TRIANGLE_FAN&&c.mode!==void 0)return null;let s=i.extensions[this.name].attributes,a=[],l={};for(let c in s)a.push(this.parser.getDependency("accessor",s[c]).then(u=>(l[c]=u,l[c])));return a.length<1?null:(a.push(this.parser.createNodeMesh(e)),Promise.all(a).then(c=>{let u=c.pop(),h=u.isGroup?u.children:[u],d=c[0].count,p=[];for(let f of h){let m=new se,g=new S,y=new F,b=new S(1,1,1),v=new tr(f.geometry,f.material,d);for(let w=0;w<d;w++)l.TRANSLATION&&g.fromBufferAttribute(l.TRANSLATION,w),l.ROTATION&&y.fromBufferAttribute(l.ROTATION,w),l.SCALE&&b.fromBufferAttribute(l.SCALE,w),v.setMatrixAt(w,m.compose(g,y,b));for(let w in l)if(w==="_COLOR_0"){let k=l[w];v.instanceColor=new je(k.array,k.itemSize,k.normalized)}else w!=="TRANSLATION"&&w!=="ROTATION"&&w!=="SCALE"&&f.geometry.setAttribute(w,l[w]);Fr.prototype.copy.call(v,f),this.parser.assignFinalMaterial(v),p.push(v)}return u.isGroup?(u.clear(),u.add(...p),u):p[0]}))}},Zm="glTF",Xr=12,Km={JSON:1313821514,BIN:5130562},qc=class{constructor(e){this.name=W.KHR_BINARY_GLTF,this.content=null,this.body=null;let t=new DataView(e,0,Xr),i=new TextDecoder;if(this.header={magic:i.decode(new Uint8Array(e.slice(0,4))),version:t.getUint32(4,!0),length:t.getUint32(8,!0)},this.header.magic!==Zm)throw new Error("THREE.GLTFLoader: Unsupported glTF-Binary header.");if(this.header.version<2)throw new Error("THREE.GLTFLoader: Legacy binary file detected.");let r=this.header.length-Xr,o=new DataView(e,Xr),s=0;for(;s<r;){let a=o.getUint32(s,!0);s+=4;let l=o.getUint32(s,!0);if(s+=4,l===Km.JSON){let c=new Uint8Array(e,Xr+s,a);this.content=i.decode(c)}else if(l===Km.BIN){let c=Xr+s;this.body=e.slice(c,c+a)}s+=a}if(this.content===null)throw new Error("THREE.GLTFLoader: JSON content not found.")}},Gc=class{constructor(e,t){if(!t)throw new Error("THREE.GLTFLoader: No DRACOLoader instance provided.");this.name=W.KHR_DRACO_MESH_COMPRESSION,this.json=e,this.dracoLoader=t,this.dracoLoader.preload()}decodePrimitive(e,t){let i=this.json,r=this.dracoLoader,o=e.extensions[this.name].bufferView,s=e.extensions[this.name].attributes,a={},l={},c={};for(let u in s){let h=Kc[u]||u.toLowerCase();a[h]=s[u]}for(let u in e.attributes){let h=Kc[u]||u.toLowerCase();if(s[u]!==void 0){let d=i.accessors[e.attributes[u]],p=cr[d.componentType];c[h]=p.name,l[h]=d.normalized===!0}}return t.getDependency("bufferView",o).then(function(u){return new Promise(function(h,d){r.decodeDracoFile(u,function(p){for(let f in p.attributes){let m=p.attributes[f],g=l[f];g!==void 0&&(m.normalized=g)}h(p)},a,c,Ge,d)})})}},jc=class{constructor(){this.name=W.KHR_TEXTURE_TRANSFORM}extendTexture(e,t){return(t.texCoord===void 0||t.texCoord===e.channel)&&t.offset===void 0&&t.rotation===void 0&&t.scale===void 0||(e=e.clone(),t.texCoord!==void 0&&(e.channel=t.texCoord),t.offset!==void 0&&e.offset.fromArray(t.offset),t.rotation!==void 0&&(e.rotation=t.rotation),t.scale!==void 0&&e.repeat.fromArray(t.scale),e.needsUpdate=!0),e}},$c=class{constructor(){this.name=W.KHR_MESH_QUANTIZATION}},ms=class extends Tm{constructor(e,t,i,r){super(e,t,i,r)}copySampleValue_(e){let t=this.resultBuffer,i=this.sampleValues,r=this.valueSize,o=e*r*3+r;for(let s=0;s!==r;s++)t[s]=i[o+s];return t}interpolate_(e,t,i,r){let o=this.resultBuffer,s=this.sampleValues,a=this.valueSize,l=a*2,c=a*3,u=r-t,h=(i-t)/u,d=h*h,p=d*h,f=e*c,m=f-c,g=-2*p+3*d,y=p-d,b=1-g,v=y-d+h;for(let w=0;w!==a;w++){let k=s[m+w+a],T=s[m+w+l]*u,E=s[f+w+a],A=s[f+w]*u;o[w]=b*k+v*T+g*E+y*A}return o}},ux=new F,Yc=class extends ms{interpolate_(e,t,i,r){let o=super.interpolate_(e,t,i,r);return ux.fromArray(o).normalize().toArray(o),o}},Ee={FLOAT:5126,FLOAT_MAT3:35675,FLOAT_MAT4:35676,FLOAT_VEC2:35664,FLOAT_VEC3:35665,FLOAT_VEC4:35666,LINEAR:9729,REPEAT:10497,SAMPLER_2D:35678,POINTS:0,LINES:1,LINE_LOOP:2,LINE_STRIP:3,TRIANGLES:4,TRIANGLE_STRIP:5,TRIANGLE_FAN:6,UNSIGNED_BYTE:5121,UNSIGNED_SHORT:5123},cr={5120:Int8Array,5121:Uint8Array,5122:Int16Array,5123:Uint16Array,5125:Uint32Array,5126:Float32Array},Xm={9728:Lr,9729:Qi,9984:nm,9985:sm,9986:om,9987:Hl},Qm={33071:im,33648:rm,10497:Ko},kc={SCALAR:1,VEC2:2,VEC3:3,VEC4:4,MAT2:4,MAT3:9,MAT4:16},Kc={POSITION:"position",NORMAL:"normal",TANGENT:"tangent",TEXCOORD_0:"uv",TEXCOORD_1:"uv1",TEXCOORD_2:"uv2",TEXCOORD_3:"uv3",COLOR_0:"color",WEIGHTS_0:"skinWeight",JOINTS_0:"skinIndex"},Bt={scale:"scale",translation:"position",rotation:"quaternion",weights:"morphTargetInfluences"},hx={CUBICSPLINE:void 0,LINEAR:ql,STEP:um},Ac={OPAQUE:"OPAQUE",MASK:"MASK",BLEND:"BLEND"};function dx(n){return n.DefaultMaterial===void 0&&(n.DefaultMaterial=new hi({color:16777215,emissive:0,metalness:1,roughness:1,transparent:!1,depthTest:!0,side:Zp})),n.DefaultMaterial}function fi(n,e,t){for(let i in t.extensions)n[i]===void 0&&(e.userData.gltfExtensions=e.userData.gltfExtensions||{},e.userData.gltfExtensions[i]=t.extensions[i])}function Ye(n,e){e.extras!==void 0&&(typeof e.extras=="object"?Object.assign(n.userData,e.extras):console.warn("THREE.GLTFLoader: Ignoring primitive type .extras, "+e.extras))}function px(n,e,t){let i=!1,r=!1,o=!1;for(let c=0,u=e.length;c<u;c++){let h=e[c];if(h.POSITION!==void 0&&(i=!0),h.NORMAL!==void 0&&(r=!0),h.COLOR_0!==void 0&&(o=!0),i&&r&&o)break}if(!i&&!r&&!o)return Promise.resolve(n);let s=[],a=[],l=[];for(let c=0,u=e.length;c<u;c++){let h=e[c];if(i){let d=h.POSITION!==void 0?t.getDependency("accessor",h.POSITION):n.attributes.position;s.push(d)}if(r){let d=h.NORMAL!==void 0?t.getDependency("accessor",h.NORMAL):n.attributes.normal;a.push(d)}if(o){let d=h.COLOR_0!==void 0?t.getDependency("accessor",h.COLOR_0):n.attributes.color;l.push(d)}}return Promise.all([Promise.all(s),Promise.all(a),Promise.all(l)]).then(function(c){let u=c[0],h=c[1],d=c[2];return i&&(n.morphAttributes.position=u),r&&(n.morphAttributes.normal=h),o&&(n.morphAttributes.color=d),n.morphTargetsRelative=!0,n})}function mx(n,e){if(n.updateMorphTargets(),e.weights!==void 0)for(let t=0,i=e.weights.length;t<i;t++)n.morphTargetInfluences[t]=e.weights[t];if(e.extras&&Array.isArray(e.extras.targetNames)){let t=e.extras.targetNames;if(n.morphTargetInfluences.length===t.length){n.morphTargetDictionary={};for(let i=0,r=t.length;i<r;i++)n.morphTargetDictionary[t[i]]=i}else console.warn("THREE.GLTFLoader: Invalid extras.targetNames length. Ignoring names.")}}function fx(n){let e,t=n.extensions&&n.extensions[W.KHR_DRACO_MESH_COMPRESSION];if(t?e="draco:"+t.bufferView+":"+t.indices+":"+Tc(t.attributes):e=n.indices+":"+Tc(n.attributes)+":"+n.mode,n.targets!==void 0)for(let i=0,r=n.targets.length;i<r;i++)e+=":"+Tc(n.targets[i]);return e}function Tc(n){let e="",t=Object.keys(n).sort();for(let i=0,r=t.length;i<r;i++)e+=t[i]+":"+n[t[i]]+";";return e}function Xc(n){switch(n){case Int8Array:return 1/127;case Uint8Array:return 1/255;case Int16Array:return 1/32767;case Uint16Array:return 1/65535;default:throw new Error("THREE.GLTFLoader: Unsupported normalized accessor component type.")}}function gx(n){return n.search(/\.jpe?g($|\?)/i)>0||n.search(/^data\:image\/jpeg/)===0?"image/jpeg":n.search(/\.webp($|\?)/i)>0||n.search(/^data\:image\/webp/)===0?"image/webp":n.search(/\.ktx2($|\?)/i)>0||n.search(/^data\:image\/ktx2/)===0?"image/ktx2":"image/png"}var yx=new se,Qc=class{constructor(e={},t={}){this.json=e,this.extensions={},this.plugins={},this.options=t,this.cache=new cx,this.associations=new Map,this.primitiveCache={},this.nodeCache={},this.meshCache={refs:{},uses:{}},this.cameraCache={refs:{},uses:{}},this.lightCache={refs:{},uses:{}},this.sourceCache={},this.textureCache={},this.nodeNamesUsed={};let i=!1,r=-1,o=!1,s=-1;if(typeof navigator<"u"&&typeof navigator.userAgent<"u"){let a=navigator.userAgent;i=/^((?!chrome|android).)*safari/i.test(a)===!0;let l=a.match(/Version\/(\d+)/);r=i&&l?parseInt(l[1],10):-1,o=a.indexOf("Firefox")>-1,s=o?a.match(/Firefox\/([0-9]+)\./)[1]:-1}typeof createImageBitmap>"u"||i&&r<17||o&&s<98?this.textureLoader=new nr(this.options.manager):this.textureLoader=new Em(this.options.manager),this.textureLoader.setCrossOrigin(this.options.crossOrigin),this.textureLoader.setRequestHeader(this.options.requestHeader),this.fileLoader=new Jl(this.options.manager),this.fileLoader.setResponseType("arraybuffer"),this.options.crossOrigin==="use-credentials"&&this.fileLoader.setWithCredentials(!0)}setExtensions(e){this.extensions=e}setPlugins(e){this.plugins=e}parse(e,t){let i=this,r=this.json,o=this.extensions;this.cache.removeAll(),this.nodeCache={},this._invokeAll(function(s){return s._markDefs&&s._markDefs()}),Promise.all(this._invokeAll(function(s){return s.beforeRoot&&s.beforeRoot()})).then(function(){return Promise.all([i.getDependencies("scene"),i.getDependencies("animation"),i.getDependencies("camera")])}).then(function(s){let a={scene:s[0][r.scene||0],scenes:s[0],animations:s[1],cameras:s[2],asset:r.asset,parser:i,userData:{}};return fi(o,a,r),Ye(a,r),Promise.all(i._invokeAll(function(l){return l.afterRoot&&l.afterRoot(a)})).then(function(){for(let l of a.scenes)l.updateMatrixWorld();e(a)})}).catch(t)}_markDefs(){let e=this.json.nodes||[],t=this.json.skins||[],i=this.json.meshes||[];for(let r=0,o=t.length;r<o;r++){let s=t[r].joints;for(let a=0,l=s.length;a<l;a++)e[s[a]].isBone=!0}for(let r=0,o=e.length;r<o;r++){let s=e[r];s.mesh!==void 0&&(this._addNodeRef(this.meshCache,s.mesh),s.skin!==void 0&&(i[s.mesh].isSkinnedMesh=!0)),s.camera!==void 0&&this._addNodeRef(this.cameraCache,s.camera)}}_addNodeRef(e,t){t!==void 0&&(e.refs[t]===void 0&&(e.refs[t]=e.uses[t]=0),e.refs[t]++)}_getNodeRef(e,t,i){if(e.refs[t]<=1)return i;let r=i.clone(),o=(s,a)=>{let l=this.associations.get(s);l!=null&&this.associations.set(a,l);for(let[c,u]of s.children.entries())o(u,a.children[c])};return o(i,r),r.name+="_instance_"+e.uses[t]++,r}_invokeOne(e){let t=Object.values(this.plugins);t.push(this);for(let i=0;i<t.length;i++){let r=e(t[i]);if(r)return r}return null}_invokeAll(e){let t=Object.values(this.plugins);t.unshift(this);let i=[];for(let r=0;r<t.length;r++){let o=e(t[r]);o&&i.push(o)}return i}getDependency(e,t){let i=e+":"+t,r=this.cache.get(i);if(!r){switch(e){case"scene":r=this.loadScene(t);break;case"node":r=this._invokeOne(function(o){return o.loadNode&&o.loadNode(t)});break;case"mesh":r=this._invokeOne(function(o){return o.loadMesh&&o.loadMesh(t)});break;case"accessor":r=this.loadAccessor(t);break;case"bufferView":r=this._invokeOne(function(o){return o.loadBufferView&&o.loadBufferView(t)});break;case"buffer":r=this.loadBuffer(t);break;case"material":r=this._invokeOne(function(o){return o.loadMaterial&&o.loadMaterial(t)});break;case"texture":r=this._invokeOne(function(o){return o.loadTexture&&o.loadTexture(t)});break;case"skin":r=this.loadSkin(t);break;case"animation":r=this._invokeOne(function(o){return o.loadAnimation&&o.loadAnimation(t)});break;case"camera":r=this.loadCamera(t);break;default:if(r=this._invokeOne(function(o){return o!=this&&o.getDependency&&o.getDependency(e,t)}),!r)throw new Error("Unknown type: "+e);break}this.cache.add(i,r)}return r}getDependencies(e){let t=this.cache.get(e);if(!t){let i=this,r=this.json[e+(e==="mesh"?"es":"s")]||[];t=Promise.all(r.map(function(o,s){return i.getDependency(e,s)})),this.cache.add(e,t)}return t}loadBuffer(e){let t=this.json.buffers[e],i=this.fileLoader;if(t.type&&t.type!=="arraybuffer")throw new Error("THREE.GLTFLoader: "+t.type+" buffer type is not supported.");if(t.uri===void 0&&e===0)return Promise.resolve(this.extensions[W.KHR_BINARY_GLTF].body);let r=this.options;return new Promise(function(o,s){i.load(or.resolveURL(t.uri,r.path),o,void 0,function(){s(new Error('THREE.GLTFLoader: Failed to load buffer "'+t.uri+'".'))})})}loadBufferView(e){let t=this.json.bufferViews[e];return this.getDependency("buffer",t.buffer).then(function(i){let r=t.byteLength||0,o=t.byteOffset||0;return i.slice(o,o+r)})}loadAccessor(e){let t=this,i=this.json,r=this.json.accessors[e];if(r.bufferView===void 0&&r.sparse===void 0){let s=kc[r.type],a=cr[r.componentType],l=r.normalized===!0,c=new a(r.count*s);return Promise.resolve(new ut(c,s,l))}let o=[];return r.bufferView!==void 0?o.push(this.getDependency("bufferView",r.bufferView)):o.push(null),r.sparse!==void 0&&(o.push(this.getDependency("bufferView",r.sparse.indices.bufferView)),o.push(this.getDependency("bufferView",r.sparse.values.bufferView))),Promise.all(o).then(function(s){let a=s[0],l=kc[r.type],c=cr[r.componentType],u=c.BYTES_PER_ELEMENT,h=u*l,d=r.byteOffset||0,p=r.bufferView!==void 0?i.bufferViews[r.bufferView].byteStride:void 0,f=r.normalized===!0,m,g;if(p&&p!==h){let y=Math.floor(d/p),b="InterleavedBuffer:"+r.bufferView+":"+r.componentType+":"+y+":"+r.count,v=t.cache.get(b);v||(m=new c(a,y*p,r.count*p/u),v=new $l(m,p/u),t.cache.add(b,v)),g=new Yl(v,l,d%p/u,f)}else a===null?m=new c(r.count*l):m=new c(a,d,r.count*l),g=new ut(m,l,f);if(r.sparse!==void 0){let y=kc.SCALAR,b=cr[r.sparse.indices.componentType],v=r.sparse.indices.byteOffset||0,w=r.sparse.values.byteOffset||0,k=new b(s[1],v,r.sparse.count*y),T=new c(s[2],w,r.sparse.count*l);a!==null&&(g=new ut(g.array.slice(),g.itemSize,g.normalized)),g.normalized=!1;for(let E=0,A=k.length;E<A;E++){let _=k[E];if(g.setX(_,T[E*l]),l>=2&&g.setY(_,T[E*l+1]),l>=3&&g.setZ(_,T[E*l+2]),l>=4&&g.setW(_,T[E*l+3]),l>=5)throw new Error("THREE.GLTFLoader: Unsupported itemSize in sparse BufferAttribute.")}g.normalized=f}return g})}loadTexture(e){let t=this.json,i=this.options,o=t.textures[e].source,s=t.images[o],a=this.textureLoader;if(s.uri){let l=i.manager.getHandler(s.uri);l!==null&&(a=l)}return this.loadTextureImage(e,o,a)}loadTextureImage(e,t,i){let r=this,o=this.json,s=o.textures[e],a=o.images[t],l=(a.uri||a.bufferView)+":"+s.sampler;if(this.textureCache[l])return this.textureCache[l];let c=this.loadImageSource(t,i).then(function(u){u.flipY=!1,u.name=s.name||a.name||"",u.name===""&&typeof a.uri=="string"&&a.uri.startsWith("data:image/")===!1&&(u.name=a.uri);let d=(o.samplers||{})[s.sampler]||{};return u.magFilter=Xm[d.magFilter]||Qi,u.minFilter=Xm[d.minFilter]||Hl,u.wrapS=Qm[d.wrapS]||Ko,u.wrapT=Qm[d.wrapT]||Ko,u.generateMipmaps=!u.isCompressedTexture&&u.minFilter!==Lr&&u.minFilter!==Qi,r.associations.set(u,{textures:e}),u}).catch(function(){return null});return this.textureCache[l]=c,c}loadImageSource(e,t){let i=this,r=this.json,o=this.options;if(this.sourceCache[e]!==void 0)return this.sourceCache[e].then(h=>h.clone());let s=r.images[e],a=self.URL||self.webkitURL,l=s.uri||"",c=!1;if(s.bufferView!==void 0)l=i.getDependency("bufferView",s.bufferView).then(function(h){c=!0;let d=new Blob([h],{type:s.mimeType});return l=a.createObjectURL(d),l});else if(s.uri===void 0)throw new Error("THREE.GLTFLoader: Image "+e+" is missing URI and bufferView");let u=Promise.resolve(l).then(function(h){return new Promise(function(d,p){let f=d;t.isImageBitmapLoader===!0&&(f=function(m){let g=new jl(m);g.needsUpdate=!0,d(g)}),t.load(or.resolveURL(h,o.path),f,void 0,p)})}).then(function(h){return c===!0&&a.revokeObjectURL(l),Ye(h,s),h.userData.mimeType=s.mimeType||gx(s.uri),h}).catch(function(h){throw console.error("THREE.GLTFLoader: Couldn't load texture",l),h});return this.sourceCache[e]=u,u}assignTexture(e,t,i,r){let o=this;return this.getDependency("texture",i.index).then(function(s){if(!s)return null;if(i.texCoord!==void 0&&i.texCoord>0&&(s=s.clone(),s.channel=i.texCoord),o.extensions[W.KHR_TEXTURE_TRANSFORM]){let a=i.extensions!==void 0?i.extensions[W.KHR_TEXTURE_TRANSFORM]:void 0;if(a){let l=o.associations.get(s);s=o.extensions[W.KHR_TEXTURE_TRANSFORM].extendTexture(s,a),o.associations.set(s,l)}}return r!==void 0&&(s.colorSpace=r),e[t]=s,s})}assignFinalMaterial(e){let t=e.geometry,i=e.material,r=t.attributes.tangent===void 0,o=t.attributes.color!==void 0,s=t.attributes.normal===void 0;if(e.isPoints){let a="PointsMaterial:"+i.uuid,l=this.cache.get(a);l||(l=new Sm,Jo.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,l.sizeAttenuation=!1,this.cache.add(a,l)),i=l}else if(e.isLine){let a="LineBasicMaterial:"+i.uuid,l=this.cache.get(a);l||(l=new Nt,Jo.prototype.copy.call(l,i),l.color.copy(i.color),l.map=i.map,this.cache.add(a,l)),i=l}if(r||o||s){let a="ClonedMaterial:"+i.uuid+":";r&&(a+="derivative-tangents:"),o&&(a+="vertex-colors:"),s&&(a+="flat-shading:");let l=this.cache.get(a);l||(l=i.clone(),o&&(l.vertexColors=!0),s&&(l.flatShading=!0),r&&(l.normalScale&&(l.normalScale.y*=-1),l.clearcoatNormalScale&&(l.clearcoatNormalScale.y*=-1)),this.cache.add(a,l),this.associations.set(l,this.associations.get(i))),i=l}e.material=i}getMaterialType(){return hi}loadMaterial(e){let t=this,i=this.json,r=this.extensions,o=i.materials[e],s,a={},l=o.extensions||{},c=[];if(l[W.KHR_MATERIALS_UNLIT]){let h=r[W.KHR_MATERIALS_UNLIT];s=h.getMaterialType(),c.push(h.extendParams(a,o,t))}else{let h=o.pbrMetallicRoughness||{};if(a.color=new L(1,1,1),a.opacity=1,Array.isArray(h.baseColorFactor)){let d=h.baseColorFactor;a.color.setRGB(d[0],d[1],d[2],Ge),a.opacity=d[3]}h.baseColorTexture!==void 0&&c.push(t.assignTexture(a,"map",h.baseColorTexture,Pe)),a.metalness=h.metallicFactor!==void 0?h.metallicFactor:1,a.roughness=h.roughnessFactor!==void 0?h.roughnessFactor:1,h.metallicRoughnessTexture!==void 0&&(c.push(t.assignTexture(a,"metalnessMap",h.metallicRoughnessTexture)),c.push(t.assignTexture(a,"roughnessMap",h.metallicRoughnessTexture))),s=this._invokeOne(function(d){return d.getMaterialType&&d.getMaterialType(e)}),c.push(Promise.all(this._invokeAll(function(d){return d.extendMaterialParams&&d.extendMaterialParams(e,a)})))}o.doubleSided===!0&&(a.side=xe);let u=o.alphaMode||Ac.OPAQUE;if(u===Ac.BLEND?(a.transparent=!0,a.depthWrite=!1):(a.transparent=!1,u===Ac.MASK&&(a.alphaTest=o.alphaCutoff!==void 0?o.alphaCutoff:.5)),o.normalTexture!==void 0&&s!==B&&(c.push(t.assignTexture(a,"normalMap",o.normalTexture)),a.normalScale=new N(1,1),o.normalTexture.scale!==void 0)){let h=o.normalTexture.scale;a.normalScale.set(h,h)}if(o.occlusionTexture!==void 0&&s!==B&&(c.push(t.assignTexture(a,"aoMap",o.occlusionTexture)),o.occlusionTexture.strength!==void 0&&(a.aoMapIntensity=o.occlusionTexture.strength)),o.emissiveFactor!==void 0&&s!==B){let h=o.emissiveFactor;a.emissive=new L().setRGB(h[0],h[1],h[2],Ge)}return o.emissiveTexture!==void 0&&s!==B&&c.push(t.assignTexture(a,"emissiveMap",o.emissiveTexture,Pe)),Promise.all(c).then(function(){let h=new s(a);return o.name&&(h.name=o.name),Ye(h,o),t.associations.set(h,{materials:e}),o.extensions&&fi(r,h,o),h})}createUniqueName(e){let t=Nm.sanitizeNodeName(e||"");return t in this.nodeNamesUsed?t+"_"+ ++this.nodeNamesUsed[t]:(this.nodeNamesUsed[t]=0,t)}loadGeometries(e){let t=this,i=this.extensions,r=this.primitiveCache;function o(a){return i[W.KHR_DRACO_MESH_COMPRESSION].decodePrimitive(a,t).then(function(l){return Jm(l,a,t)})}let s=[];for(let a=0,l=e.length;a<l;a++){let c=e[a],u=fx(c),h=r[u];if(h)s.push(h.promise);else{let d;c.extensions&&c.extensions[W.KHR_DRACO_MESH_COMPRESSION]?d=o(c):d=Jm(new ae,c,t),r[u]={primitive:c,promise:d},s.push(d)}}return Promise.all(s)}loadMesh(e){let t=this,i=this.json,r=this.extensions,o=i.meshes[e],s=o.primitives,a=[];for(let l=0,c=s.length;l<c;l++){let u=s[l].material===void 0?dx(this.cache):this.getDependency("material",s[l].material);a.push(u)}return a.push(t.loadGeometries(s)),Promise.all(a).then(function(l){let c=l.slice(0,l.length-1),u=l[l.length-1],h=[];for(let p=0,f=u.length;p<f;p++){let m=u[p],g=s[p],y,b=c[p];if(g.mode===Ee.TRIANGLES||g.mode===Ee.TRIANGLE_STRIP||g.mode===Ee.TRIANGLE_FAN||g.mode===void 0)y=o.isSkinnedMesh===!0?new fm(m,b):new O(m,b),y.isSkinnedMesh===!0&&y.normalizeSkinWeights(),g.mode===Ee.TRIANGLE_STRIP?y.geometry=Pc(y.geometry,Xo):g.mode===Ee.TRIANGLE_FAN&&(y.geometry=Pc(y.geometry,_r));else if(g.mode===Ee.LINES)y=new ir(m,b);else if(g.mode===Ee.LINE_STRIP)y=new bm(m,b);else if(g.mode===Ee.LINE_LOOP)y=new Zo(m,b);else if(g.mode===Ee.POINTS)y=new vm(m,b);else throw new Error("THREE.GLTFLoader: Primitive mode unsupported: "+g.mode);Object.keys(y.geometry.morphAttributes).length>0&&mx(y,o),y.name=t.createUniqueName(o.name||"mesh_"+e),Ye(y,o),g.extensions&&fi(r,y,g),t.assignFinalMaterial(y),h.push(y)}for(let p=0,f=h.length;p<f;p++)t.associations.set(h[p],{meshes:e,primitives:p});if(h.length===1)return o.extensions&&fi(r,h[0],o),h[0];let d=new Zi;o.extensions&&fi(r,d,o),t.associations.set(d,{meshes:e});for(let p=0,f=h.length;p<f;p++)d.add(h[p]);return d})}loadCamera(e){let t,i=this.json.cameras[e],r=i[i.type];if(!r){console.warn("THREE.GLTFLoader: Missing camera parameters.");return}return i.type==="perspective"?t=new ge(R.radToDeg(r.yfov),r.aspectRatio||1,r.znear||1,r.zfar||2e6):i.type==="orthographic"&&(t=new de(-r.xmag,r.xmag,r.ymag,-r.ymag,r.znear,r.zfar)),i.name&&(t.name=this.createUniqueName(i.name)),Ye(t,i),Promise.resolve(t)}loadSkin(e){let t=this.json.skins[e],i=[];for(let r=0,o=t.joints.length;r<o;r++)i.push(this._loadNodeShallow(t.joints[r]));return t.inverseBindMatrices!==void 0?i.push(this.getDependency("accessor",t.inverseBindMatrices)):i.push(null),Promise.all(i).then(function(r){let o=r.pop(),s=r,a=[],l=[];for(let c=0,u=s.length;c<u;c++){let h=s[c];if(h){a.push(h);let d=new se;o!==null&&d.fromArray(o.array,c*16),l.push(d)}else console.warn('THREE.GLTFLoader: Joint "%s" could not be found.',t.joints[c])}return new ym(a,l)})}loadAnimation(e){let t=this.json,i=this,r=t.animations[e],o=r.name?r.name:"animation_"+e,s=[],a=[],l=[],c=[],u=[];for(let h=0,d=r.channels.length;h<d;h++){let p=r.channels[h],f=r.samplers[p.sampler],m=p.target,g=m.node,y=r.parameters!==void 0?r.parameters[f.input]:f.input,b=r.parameters!==void 0?r.parameters[f.output]:f.output;m.node!==void 0&&(s.push(this.getDependency("node",g)),a.push(this.getDependency("accessor",y)),l.push(this.getDependency("accessor",b)),c.push(f),u.push(m))}return Promise.all([Promise.all(s),Promise.all(a),Promise.all(l),Promise.all(c),Promise.all(u)]).then(function(h){let d=h[0],p=h[1],f=h[2],m=h[3],g=h[4],y=[];for(let v=0,w=d.length;v<w;v++){let k=d[v],T=p[v],E=f[v],A=m[v],_=g[v];if(k===void 0)continue;k.updateMatrix&&k.updateMatrix();let J=i._createAnimationTracks(k,T,E,A,_);if(J)for(let re=0;re<J.length;re++)y.push(J[re])}let b=new Ql(o,void 0,y);return Ye(b,r),b})}createNodeMesh(e){let t=this.json,i=this,r=t.nodes[e];return r.mesh===void 0?null:i.getDependency("mesh",r.mesh).then(function(o){let s=i._getNodeRef(i.meshCache,r.mesh,o);return r.weights!==void 0&&s.traverse(function(a){if(a.isMesh)for(let l=0,c=r.weights.length;l<c;l++)a.morphTargetInfluences[l]=r.weights[l]}),s})}loadNode(e){let t=this.json,i=this,r=t.nodes[e],o=i._loadNodeShallow(e),s=[],a=r.children||[];for(let c=0,u=a.length;c<u;c++)s.push(i.getDependency("node",a[c]));let l=r.skin===void 0?Promise.resolve(null):i.getDependency("skin",r.skin);return Promise.all([o,Promise.all(s),l]).then(function(c){let u=c[0],h=c[1],d=c[2];d!==null&&u.traverse(function(p){p.isSkinnedMesh&&p.bind(d,yx)});for(let p=0,f=h.length;p<f;p++)u.add(h[p]);if(u.userData.pivot!==void 0&&h.length>0){let p=u.userData.pivot,f=h[0];u.pivot=new S().fromArray(p),u.position.x-=p[0],u.position.y-=p[1],u.position.z-=p[2],f.position.set(0,0,0),delete u.userData.pivot}return u})}_loadNodeShallow(e){let t=this.json,i=this.extensions,r=this;if(this.nodeCache[e]!==void 0)return this.nodeCache[e];let o=t.nodes[e],s=o.name?r.createUniqueName(o.name):"",a=[],l=r._invokeOne(function(c){return c.createNodeMesh&&c.createNodeMesh(e)});return l&&a.push(l),o.camera!==void 0&&a.push(r.getDependency("camera",o.camera).then(function(c){return r._getNodeRef(r.cameraCache,o.camera,c)})),r._invokeAll(function(c){return c.createNodeAttachment&&c.createNodeAttachment(e)}).forEach(function(c){a.push(c)}),this.nodeCache[e]=Promise.all(a).then(function(c){let u;if(o.isBone===!0?u=new gm:c.length>1?u=new Zi:c.length===1?u=c[0]:u=new Fr,u!==c[0])for(let h=0,d=c.length;h<d;h++)u.add(c[h]);if(o.name&&(u.userData.name=o.name,u.name=s),Ye(u,o),o.extensions&&fi(i,u,o),o.matrix!==void 0){let h=new se;h.fromArray(o.matrix),u.applyMatrix4(h)}else o.translation!==void 0&&u.position.fromArray(o.translation),o.rotation!==void 0&&u.quaternion.fromArray(o.rotation),o.scale!==void 0&&u.scale.fromArray(o.scale);if(!r.associations.has(u))r.associations.set(u,{});else if(o.mesh!==void 0&&r.meshCache.refs[o.mesh]>1){let h=r.associations.get(u);r.associations.set(u,{...h})}return r.associations.get(u).nodes=e,u}),this.nodeCache[e]}loadScene(e){let t=this.extensions,i=this.json.scenes[e],r=this,o=new Zi;i.name&&(o.name=r.createUniqueName(i.name)),Ye(o,i),i.extensions&&fi(t,o,i);let s=i.nodes||[],a=[];for(let l=0,c=s.length;l<c;l++)a.push(r.getDependency("node",s[l]));return Promise.all(a).then(function(l){for(let u=0,h=l.length;u<h;u++){let d=l[u];d.parent!==null?o.add($m(d)):o.add(d)}let c=u=>{let h=new Map;for(let[d,p]of r.associations)(d instanceof Jo||d instanceof jl)&&h.set(d,p);return u.traverse(d=>{let p=r.associations.get(d);p!=null&&h.set(d,p)}),h};return r.associations=c(o),o})}_createAnimationTracks(e,t,i,r,o){let s=[],a=e.name?e.name:e.uuid,l=[];Bt[o.path]===Bt.weights?e.traverse(function(d){d.morphTargetInfluences&&l.push(d.name?d.name:d.uuid)}):l.push(a);let c;switch(Bt[o.path]){case Bt.weights:c=Xl;break;case Bt.rotation:c=ts;break;case Bt.translation:case Bt.scale:c=is;break;default:i.itemSize===1?c=Xl:c=is;break}let u=r.interpolation!==void 0?hx[r.interpolation]:ql,h=this._getArrayFromAccessor(i);for(let d=0,p=l.length;d<p;d++){let f=new c(l[d]+"."+Bt[o.path],t.array,h,u);r.interpolation==="CUBICSPLINE"&&this._createCubicSplineTrackInterpolant(f),s.push(f)}return s}_getArrayFromAccessor(e){let t=e.array;if(e.normalized){let i=Xc(t.constructor),r=new Float32Array(t.length);for(let o=0,s=t.length;o<s;o++)r[o]=t[o]*i;t=r}return t}_createCubicSplineTrackInterpolant(e){e.createInterpolant=function(i){let r=this instanceof ts?Yc:ms;return new r(this.times,this.values,this.getValueSize()/3,i)},e.createInterpolant.isInterpolantFactoryMethodGLTFCubicSpline=!0}};function bx(n,e,t){let i=e.attributes,r=new dm;if(i.POSITION!==void 0){let a=t.json.accessors[i.POSITION],l=a.min,c=a.max;if(l!==void 0&&c!==void 0){if(r.set(new S(l[0],l[1],l[2]),new S(c[0],c[1],c[2])),a.normalized){let u=Xc(cr[a.componentType]);r.min.multiplyScalar(u),r.max.multiplyScalar(u)}}else{console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.");return}}else return;let o=e.targets;if(o!==void 0){let a=new S,l=new S;for(let c=0,u=o.length;c<u;c++){let h=o[c];if(h.POSITION!==void 0){let d=t.json.accessors[h.POSITION],p=d.min,f=d.max;if(p!==void 0&&f!==void 0){if(l.setX(Math.max(Math.abs(p[0]),Math.abs(f[0]))),l.setY(Math.max(Math.abs(p[1]),Math.abs(f[1]))),l.setZ(Math.max(Math.abs(p[2]),Math.abs(f[2]))),d.normalized){let m=Xc(cr[d.componentType]);l.multiplyScalar(m)}a.max(l)}else console.warn("THREE.GLTFLoader: Missing min/max properties for accessor POSITION.")}}r.expandByVector(a)}n.boundingBox=r;let s=new mm;r.getCenter(s.center),s.radius=r.min.distanceTo(r.max)/2,n.boundingSphere=s}function Jm(n,e,t){let i=e.attributes,r=[];function o(s,a){return t.getDependency("accessor",s).then(function(l){n.setAttribute(a,l)})}for(let s in i){let a=Kc[s]||s.toLowerCase();a in n.attributes||r.push(o(i[s],a))}if(e.indices!==void 0&&!n.index){let s=t.getDependency("accessor",e.indices).then(function(a){n.setIndex(a)});r.push(s)}return Gl.workingColorSpace!==Ge&&"COLOR_0"in i&&console.warn(`THREE.GLTFLoader: Converting vertex colors from "srgb-linear" to "${Gl.workingColorSpace}" not supported.`),Ye(n,e),bx(n,e,t),Promise.all(r).then(function(){return e.targets!==void 0?px(n,e.targets,t):n})}var Jc=class{resources;audioService;textureLoader;textureCache=new Map;textureLoadInFlight=new Map;animationResourceCache=new Map;animationResourceLoadInFlight=new Map;audioLoadInFlight=new Map;audioMetadataCache=new Map;spineAssetCache=new Map;spineAssetLoadInFlight=new Map;atlasResolver=null;constructor(e,t){this.resources=e,this.audioService=t,this.textureLoader=new nr}trackInFlight(e,t,i){e.set(t,i);let r=()=>{e.get(t)===i&&e.delete(t)};return i.then(r,r),i}getResourceManager(){return this.resources}setAtlasResolver(e){this.atlasResolver=e}seedTexture(e,t){this.textureCache.set(e,t)}evictTexture(e){this.textureCache.delete(e)}getAudioMetadata(e){let t=this.audioMetadataCache.get(e);return t?{...t}:null}async loadAsset(e,t,i){let r=this.getExtension(e);switch(r){case"glb":case"gltf":return this.loadGltfAsMeshInstance(e,t,i);case"png":case"jpg":case"jpeg":case"webp":throw new Error(`[AssetLoader] Generic image node creation not yet implemented. Use loadTexture. Path: ${e}`);case"mp3":case"ogg":case"wav":throw await this.loadAudio(e),new Error(`[AssetLoader] Audio assets are not node assets. Use loadAudio() instead. Path: ${e}`);case"pix3anim":throw await this.loadAnimationResource(e),new Error(`[AssetLoader] Animation assets are metadata assets. Use loadAnimationResource() instead. Path: ${e}`);default:throw new Error(`[AssetLoader] Unsupported asset type: ${r}`)}}async loadAudio(e){if(!this.audioService)throw new Error("[AssetLoader] AudioService is required to decode audio assets.");let t=this.audioService,i=this.resources.getAudioBuffer(e);if(i)return i;let r=this.audioLoadInFlight.get(e);if(r)return r;let o=(async()=>{try{let s,a=0;if(e.startsWith("res://")){let c=await this.resources.readBlob(e);a=c.size,s=await c.arrayBuffer()}else try{let c=this.resources.normalize(e),u=await fetch(c);if(!u.ok)throw new Error(`HTTP ${u.status} while fetching ${c}`);if((u.headers.get("content-type")??"").includes("text/html"))throw new Error(`Unexpected HTML response for audio at ${c}`);s=await u.arrayBuffer();let d=Number(u.headers.get("content-length"));a=Number.isFinite(d)&&d>0?d:s.byteLength}catch{let c=await this.resources.readBlob(e);a=c.size,s=await c.arrayBuffer()}let l=await t.decodeAudioData(s);return this.audioMetadataCache.set(e,{resourcePath:e,sizeBytes:Math.max(0,Math.round(a||s.byteLength))}),this.resources.setAudioBuffer(e,l),l}catch(s){throw console.error(`[AssetLoader] Failed to load audio: ${e}`,s),s}})();return this.trackInFlight(this.audioLoadInFlight,e,o)}async loadTexture(e,t){let i=this.textureCache.get(e);if(i)return i;let r=this.textureLoadInFlight.get(e);if(r)return r;if(t?.atlas!==!1&&this.atlasResolver){let s=this.atlasResolver.resolve(e);if(s)return this.trackInFlight(this.textureLoadInFlight,e,this.buildAtlasView(e,s))}let o=(async()=>{let s,a=!1;if(e.startsWith("res://"))try{let l=await this.resources.readBlob(e);s=URL.createObjectURL(l),a=!0}catch(l){throw console.error(`[AssetLoader] Failed to read blob for ${e}:`,l),l}else s=this.resources.normalize(e);return new Promise((l,c)=>{this.textureLoader.load(s,u=>{a&&URL.revokeObjectURL(s),this.textureCache.set(e,u),l(u)},void 0,u=>{console.error(`[AssetLoader] Failed to load texture: ${s}`,u),a&&URL.revokeObjectURL(s),c(u)})})})();return this.trackInFlight(this.textureLoadInFlight,e,o)}async buildAtlasView(e,t){let r=(await this.loadTexture(t.sheetPath,{atlas:!1})).clone();return $(r),mi(r,t.region),yc(r,t.region,{width:t.pixelWidth,height:t.pixelHeight}),this.textureCache.set(e,r),r}async loadAnimationResource(e){let t=this.animationResourceCache.get(e);if(t)return t;let i=this.animationResourceLoadInFlight.get(e);if(i)return i;let r=(async()=>{let o=await this.resources.readText(e),s;try{s=JSON.parse(o)}catch(l){throw new Error(`[AssetLoader] Failed to parse animation resource ${e}: ${l instanceof Error?l.message:String(l)}`)}let a=dc(s);return this.animationResourceCache.set(e,a),a})();return this.trackInFlight(this.animationResourceLoadInFlight,e,r)}async loadSpineAsset(e){let t=lr(e),i=this.spineAssetCache.get(t);if(i)return i;let r=this.spineAssetLoadInFlight.get(t);if(r)return r;let o=(async()=>{try{let s=await xc(this.resources,e);return this.spineAssetCache.set(t,s),s}finally{this.spineAssetLoadInFlight.delete(t)}})();return this.spineAssetLoadInFlight.set(t,o),o}getCachedSpineAsset(e){return this.spineAssetCache.get(lr(e))??null}evictSpineAsset(e){let t=lr(e),i=this.spineAssetCache.get(t);i&&(this.spineAssetCache.delete(t),i.dispose())}async loadInstancingModel(e){let t=await this.loadGltf(e),i=this.findFirstMesh(t.scene);if(!i)throw new Error(`[AssetLoader] No mesh found in model: ${e}`);return{geometry:i.geometry.clone(),material:Array.isArray(i.material)?i.material.map(r=>r.clone()):i.material.clone(),scene:t.scene}}async loadGltfAsMeshInstance(e,t,i){try{let r=await this.loadGltf(e),o=r.animations.map(c=>c.clone()),s=t||crypto.randomUUID(),a=i||"mesh",l=new ht({id:s,name:a,src:e});return l.add(r.scene),l.animations=o,{node:l}}catch(r){throw console.error(`[AssetLoader] Failed to load GLTF: ${e}`,r),new Error(`Failed to load asset: ${r instanceof Error?r.message:String(r)}`)}}async loadGltf(e){let i=await(await this.resources.readBlob(e)).arrayBuffer(),r=new ds;return new Promise((o,s)=>{r.parse(i,"",a=>o(a),a=>s(a))})}findFirstMesh(e){let t=null;return e.traverse(i=>{t||!(i instanceof O)||(t=i)}),t}getExtension(e){let t=e.match(/\.([a-z0-9]+)$/i);return t?t[1].toLowerCase():""}};var dt=["master","music","sfx"];function ef(n){return typeof n!="number"||!Number.isFinite(n)?0:Math.min(1,Math.max(0,n))}var Zc=class n{static LOWPASS_OPEN_HZ=2e4;context=null;buses=new Map;snapshots=new Map;activeSnapshotName="default";activePlaybacks=new Set;activePlaybackEntries=new Map;nextPlaybackId=0;wantsAudible=!0;pageActive=!0;pausedByHost=!1;unlockedByGesture=!1;unlockFromPointerDown=()=>{this.unlock()};unlockFromKeydown=()=>{this.unlock()};handleContextStateChange=()=>{this.reconcileContextState()};constructor(){let e=window,t=window.AudioContext??e.webkitAudioContext;if(!t){console.warn("[AudioService] Web Audio API is not supported in this environment.");return}try{this.context=new t;let i=this.createBus(this.context.destination),r=this.createBus(i.input),o=this.createBus(i.input);this.buses.set("master",i),this.buses.set("music",r),this.buses.set("sfx",o)}catch(i){this.context=null,this.buses.clear(),console.warn("[AudioService] Failed to initialize AudioContext:",i);return}this.snapshots.set("default",{name:"default"}),this.snapshots.set("muffled",{name:"muffled",lowpassHz:{master:700},volumeScale:{master:.85}}),window.addEventListener("pointerdown",this.unlockFromPointerDown),window.addEventListener("keydown",this.unlockFromKeydown),window.addEventListener("blur",this.handleActivityChange),window.addEventListener("focus",this.handleActivityChange),window.addEventListener("pageshow",this.handleActivityChange),window.addEventListener("pagehide",this.handleActivityChange),document.addEventListener("visibilitychange",this.handleActivityChange),this.context.addEventListener?.("statechange",this.handleContextStateChange),this.handleActivityChange()}setVolume(e){this.setBusVolume("master",e,.03)}mute(){this.setVolume(0)}unmute(){this.setVolume(1)}setBusVolume(e,t,i=.05){let r=this.buses.get(e);!r||!this.context||(r.userVolume=Math.max(0,Number.isFinite(t)?t:1),this.applyBusGain(e,Math.max(.001,i/3)))}getBusVolume(e){return this.buses.get(e)?.userVolume??1}applyBusGain(e,t){let i=this.buses.get(e);if(!i||!this.context)return;let r=this.snapshots.get(this.activeSnapshotName)?.volumeScale?.[e]??1;i.input.gain.setTargetAtTime(i.userVolume*r,this.context.currentTime,t)}applySnapshot(e,t){let i=this.snapshots.get(e);if(!i||!this.context){i||console.warn(`[AudioService] Unknown snapshot "${e}".`);return}this.activeSnapshotName=e;let r=Math.max(.001,t?.timeConstantSec??.08);for(let o of dt)this.applyBusGain(o,r),this.buses.get(o)?.filter?.frequency.setTargetAtTime(i.lowpassHz?.[o]??n.LOWPASS_OPEN_HZ,this.context.currentTime,r)}resetSnapshot(e){this.applySnapshot("default",e)}registerSnapshot(e){if(!e||typeof e.name!="string"||e.name.length===0){console.warn("[AudioService] registerSnapshot requires a non-empty name.");return}this.snapshots.set(e.name,e)}getActiveSnapshotName(){return this.activeSnapshotName}resetBuses(){for(let e of dt){let t=this.buses.get(e);t&&(t.userVolume=1)}this.applySnapshot("default",{timeConstantSec:.01})}createBus(e){let t=this.context,i=t.createGain(),r=null;return typeof t.createBiquadFilter=="function"?(r=t.createBiquadFilter(),r.type="lowpass",r.frequency.value=n.LOWPASS_OPEN_HZ,r.Q.value=.7071,i.connect(r),r.connect(e)):i.connect(e),{input:i,filter:r,userVolume:1}}getBusInput(e){return this.buses.get(e??"sfx")?.input??this.buses.get("master").input}handleActivityChange=()=>{let e=document.visibilityState==="visible",t=typeof document.hasFocus=="function"?document.hasFocus():!0;this.pageActive=e&&t,this.updateWantsAudible()};setPaused(e){this.pausedByHost!==e&&(this.pausedByHost=e,this.updateWantsAudible())}updateWantsAudible(){this.wantsAudible=this.pageActive&&!this.pausedByHost,this.reconcileContextState()}reconcileContextState(){let e=this.context;if(e){if(e.state==="running"&&(this.unlockedByGesture=!0),!this.wantsAudible){e.state==="running"&&e.suspend().catch(()=>{});return}e.state==="suspended"&&this.unlockedByGesture&&e.resume().catch(t=>{console.warn("[AudioService] Failed to resume AudioContext:",t)})}}unlock(){this.context&&(this.unlockedByGesture=!0,this.reconcileContextState())}stopAll(){let e=Array.from(this.activePlaybacks);this.activePlaybacks.clear(),this.activePlaybackEntries.clear();for(let t of e)try{t.stop()}catch{}}play(e,t){if(!this.context||this.buses.size===0)return console.warn("[AudioService] Cannot play audio: AudioContext is unavailable."),{stop:()=>{},ended:Promise.resolve()};this.context.state==="suspended"&&this.wantsAudible&&console.warn("[AudioService] Attempting to play audio while context is suspended. It might not be audible until user interaction.");let i=t?.loop??!1;if(!i&&!this.wantsAudible&&this.context.state!=="running")return{stop:()=>{},ended:Promise.resolve()};let r=this.context.createBufferSource();r.buffer=e,r.loop=i;let o=ef(t?.pitchVariation),s=ef(t?.volumeVariation),a=o>0?1+(Math.random()*2-1)*o:1,l=s>0?1+(Math.random()*2-1)*s:1,c=Math.max(.01,(t?.playbackRate??1)*a);r.playbackRate.value=c;let u=this.context.createGain(),h=Math.max(0,(t?.volume??1)*l);u.gain.value=h;let d=u,p=null,f=typeof t?.pan=="number"?Math.max(-1,Math.min(1,t.pan)):null;f!==null&&typeof this.context.createStereoPanner=="function"&&(p=this.context.createStereoPanner(),p.pan.value=f,u.connect(p),d=p);let m=t?.bus??"sfx";r.connect(u),d.connect(this.getBusInput(m));let g,y=new Promise(_=>{g=_}),b=!1,v=()=>{b||(b=!0,this.activePlaybacks.delete(w),this.activePlaybackEntries.delete(w),r.disconnect(),u.disconnect(),p?.disconnect(),g())},w={stop:()=>{try{r.stop()}catch{}finally{v()}},ended:y};r.onended=v;let k=this.normalizeResourcePath(t?.resourcePath),T=this.normalizePositiveNumber(e.duration),E=this.normalizePositiveNumber(e.numberOfChannels),A=this.normalizePositiveNumber(e.sampleRate);return this.activePlaybacks.add(w),this.activePlaybackEntries.set(w,{id:this.createPlaybackId(),label:this.normalizePlaybackLabel(t?.label,k),resourcePath:k,startedAtMs:this.readNowMs(),loop:r.loop,volume:h,playbackRate:c,pan:f,bus:m,durationSeconds:T,channelCount:E,sampleRate:A,bitrateKbps:this.computeBitrateKbps(T,t?.sizeBytes)}),r.start(),w}getActivePlaybackSnapshot(e=this.readNowMs()){let t=Number.isFinite(e)?e:this.readNowMs();return[...this.activePlaybackEntries.values()].map(i=>({...i,elapsedMs:Math.max(0,t-i.startedAtMs)})).sort((i,r)=>r.startedAtMs-i.startedAtMs||i.label.localeCompare(r.label)||i.id.localeCompare(r.id))}getSampleRate(){return this.context?.sampleRate??null}createBuffer(e,t=1){if(!this.context)return null;try{return this.context.createBuffer(Math.max(1,Math.floor(t)),Math.max(1,Math.floor(e)),this.context.sampleRate)}catch(i){return console.warn("[AudioService] Failed to allocate an AudioBuffer:",i),null}}async decodeAudioData(e){if(!this.context)throw new Error("AudioContext is unavailable.");return this.context.decodeAudioData(e)}dispose(){window.removeEventListener("pointerdown",this.unlockFromPointerDown),window.removeEventListener("keydown",this.unlockFromKeydown),window.removeEventListener("blur",this.handleActivityChange),window.removeEventListener("focus",this.handleActivityChange),window.removeEventListener("pageshow",this.handleActivityChange),window.removeEventListener("pagehide",this.handleActivityChange),document.removeEventListener("visibilitychange",this.handleActivityChange),this.context?.removeEventListener?.("statechange",this.handleContextStateChange),this.stopAll(),this.context?.close(),this.context=null,this.buses.clear(),this.wantsAudible=!0,this.pageActive=!0,this.pausedByHost=!1,this.unlockedByGesture=!1}createPlaybackId(){return this.nextPlaybackId+=1,`playback-${this.nextPlaybackId}`}normalizePlaybackLabel(e,t){let i=typeof e=="string"?e.trim():"";return i.length>0?i:this.extractFileName(t)??"Unknown"}normalizeResourcePath(e){let t=typeof e=="string"?e.trim():"";return t.length>0?t:null}extractFileName(e){if(!e)return null;let i=(e.split(/[?#]/,1)[0]??e).split(/[\\/]/).filter(Boolean);return i.length>0?i[i.length-1]??null:null}normalizePositiveNumber(e){return typeof e!="number"||!Number.isFinite(e)||e<=0?null:e}computeBitrateKbps(e,t){return typeof e!="number"||!Number.isFinite(e)||e<=0||typeof t!="number"||!Number.isFinite(t)||t<=0?null:t*8/e/1e3}readNowMs(){let e=globalThis.performance?.now?.();return typeof e=="number"&&Number.isFinite(e)?e:Date.now()}};var eu=class{components=new Map;constructor(){}registerComponent(e){this.components.has(e.id)&&console.warn(`[ScriptRegistry] Component "${e.id}" is already registered. Overwriting.`),this.components.set(e.id,e)}unregisterComponent(e){return this.components.delete(e)}getComponentType(e){return this.components.get(e)}getAllComponentTypes(){return Array.from(this.components.values())}createComponent(e,t,i={}){let r=this.components.get(e);if(!r)return i.expectRegistered!==!1&&console.error(`[ScriptRegistry] Component type "${e}" not found in registry.`),null;try{return new r.componentClass(t,e)}catch(o){return console.error(`[ScriptRegistry] Failed to instantiate component "${e}":`,o),null}}getComponentPropertySchema(e){let t=this.components.get(e);return t?t.componentClass.getPropertySchema():null}searchComponents(e){let t=e.toLowerCase();return this.getAllComponentTypes().filter(i=>i.displayName.toLowerCase().includes(t)||i.description.toLowerCase().includes(t)||i.keywords.some(r=>r.toLowerCase().includes(t)))}dispose(){this.components.clear()}};var V=class{id;type;node=null;enabled=!0;config={};_started=!1;input;scene;constructor(e,t){this.id=e,this.type=t}static getPropertySchema(){return{nodeType:"Script",properties:[],groups:{}}}findNode(e){if(this.scene)return this.scene.findNode(e);let t=this.node;for(;t?.parentNode;)t=t.parentNode;return t?.findNode(e)??null}getNode(e){let t=this.findNode(e);if(!t)throw new Error(`[${this.type}] getNode("${e}"): node not found in scene`);return t}onDetach(){di(this)}resetStartedState(){this._started=!1}};function Sx(n){return typeof n=="object"&&n!==null&&"id"in n&&"type"in n&&"enabled"in n&&"config"in n}var gs=new Set,tu=n=>`${n.family}|${n.weight??400}|${n.style??"normal"}|${n.path}`,Qr=n=>`${n.family} ${n.weight??400}${n.style==="italic"?" italic":""}`,fs=new Map;function vx(){gs.clear(),fs.clear()}function wx(n){return gs.has(tu(n))}async function iu(n,e,t=5e3){let i={loaded:[],failed:[]};return!n||n.length===0||typeof document>"u"||!document.fonts||typeof FontFace>"u"||await Promise.all(n.map(async r=>{let o=tu(r);if(gs.has(o))return;let s=fs.get(o);s||(s=xx(r,e,t).finally(()=>fs.delete(o)),fs.set(o,s));let a=await s;a.ok?i.loaded.push(Qr(r)):i.failed.push({face:Qr(r),reason:a.reason})})),i}async function xx(n,e,t){try{let i=n.path.startsWith("res://")?n.path:`res://${n.path}`,o=await(await e.readBlob(i)).arrayBuffer(),s=new FontFace(n.family,o,{weight:String(n.weight??400),style:n.style??"normal",...n.unicodeRange?{unicodeRange:n.unicodeRange}:{}}),a=await Px(s.load(),t,Qr(n));return document.fonts.add(a),gs.add(tu(n)),{ok:!0}}catch(i){let r=i instanceof Error?i.message:String(i);return console.warn(`[ProjectFontLoader] ${Qr(n)} (${n.path}) could not be loaded; captions in that family fall back to a system face: ${r}`),{ok:!1,reason:r}}}function Px(n,e,t){return!Number.isFinite(e)||e<=0?n:new Promise((i,r)=>{let o=setTimeout(()=>r(new Error(`${t}: timed out after ${e}ms`)),e);n.then(s=>{clearTimeout(o),i(s)},s=>{clearTimeout(o),r(s instanceof Error?s:new Error(String(s)))})})}function tf(n,e){let t=n.getComponentPropertySchema(e);if(!t)return null;if(!Array.isArray(t.properties))return console.warn(`[SceneLoader] Component "${e}" has a malformed property schema: getPropertySchema() must return an object with a "properties" array. Skipping config application for this component.`),null;let i=t.properties,r=[];for(let o of i){if(o&&typeof o.setValue=="function"&&typeof o.name=="string"){r.push(o);continue}let s=o&&typeof o.name=="string"?`"${o.name}"`:"(unnamed)";console.warn(`[SceneLoader] Component "${e}" has a malformed property definition ${s}: each property must expose a setValue(node, value) function. Skipping this property.`)}return r}function ru(n,e,t){let i=e.id||`${t}-${e.type}-${Date.now()}`,r=n.createComponent(e.type,i,{expectRegistered:!1});if(!r)return null;r.enabled=e.enabled??!0;let o=e.config??{};r.config={...r.config,...o};let s=tf(n,e.type);if(s)for(let a of s)o[a.name]!==void 0&&a.setValue(r,o[a.name]);return r}function ys(n,e,t){if(e)for(let i of e){let r=ru(t,i,n.nodeId);if(r){n.addComponent(r);continue}n.pendingComponents.push({...i,config:{...i.config??{}}}),console.warn(`[SceneLoader] Component type "${i.type}" is not registered yet \u2014 kept as pending on node "${n.nodeId}". It will attach once the type registers, and is preserved on save.`)}}var rf=n=>Array.isArray(n?.pendingComponents);function nu(n,e){let t=0,i=[...n];for(;i.length>0;){let r=i.pop();if(!r)continue;for(let s of r.children)rf(s)&&i.push(s);if(r.pendingComponents.length===0)continue;let o=[];for(let s of r.pendingComponents){let a=ru(e,s,r.nodeId);a?(r.addComponent(a),t+=1):o.push(s)}r.pendingComponents.length=0,r.pendingComponents.push(...o)}return t}function nf(n,e){let t=e.getComponentType(n.type);return t===void 0||n.constructor!==t.componentClass}function kx(n,e,t=(i,r)=>({...r.config??{}})){let i=0,r=[...n];for(;r.length>0;){let o=r.pop();if(o){for(let s of o.children)rf(s)&&r.push(s);for(let s of[...o.components]){if(!nf(s,e))continue;if(!e.getComponentType(s.type)){let c=t(o,s);o.removeComponent(s),o.pendingComponents.push({id:s.id,type:s.type,enabled:s.enabled,config:c}),i+=1;continue}let a=ru(e,{id:s.id,type:s.type,enabled:s.enabled,config:t(o,s)},o.nodeId);if(!a)continue;let l=o.components.indexOf(s);o.removeComponent(s),o.addComponent(a),o.components.splice(o.components.indexOf(a),1),o.components.splice(l,0,a),i+=1}}}return i}function Jr(n){let e=n.components.map(t=>({id:t.id,type:t.type,enabled:t.enabled,config:t.config&&Object.keys(t.config).length>0?t.config:{}}));for(let t of n.pendingComponents)e.push({...t,config:{...t.config??{}}});return e}function ke(n){let e=n.constructor,t=typeof e.getPropertySchema=="function"?e.getPropertySchema():{nodeType:"Unknown",properties:[]},i=n.getInstancePropertySchema?.();if(!i||i.properties.length===0)return t;let r=new Map(i.properties.map(a=>[a.name,a])),o=t.properties.map(a=>r.get(a.name)??a),s=new Set(t.properties.map(a=>a.name));for(let a of i.properties)s.has(a.name)||o.push(a);return{...t,properties:o,groups:{...t.groups,...i.groups}}}function Ax(n){let e=new Map;for(let t of n.properties){let i=t.ui?.group||"General";e.has(i)||e.set(i,[]),e.get(i).push(t)}return e}function Ot(n,e){return n.properties.find(t=>t.name===e)}function Tx(n,e){let t=e.getValue(n);if(e.type==="number"){let i=Number(t);if(isNaN(i))return"0";let r=e.ui?.precision??2;return parseFloat(i.toFixed(r)).toString()}return e.type==="boolean"?String(t===!0):e.type==="vector2"||e.type==="vector3"||e.type==="vector4"||e.type==="euler"||e.type==="object"?JSON.stringify(t):String(t??"")}function of(n,e){if(n.validation?.validate){let i=n.validation.validate(e);if(i===!1)return{isValid:!1,error:"Invalid value"};if(typeof i=="string")return{isValid:!1,error:i}}let t=e;return n.validation?.transform&&(t=n.validation.transform(e)),{isValid:!0,transformedValue:t}}function ur(n,e,t){let i=of(e,t);if(!i.isValid)return{success:!1,error:i.error};try{return e.setValue(n,i.transformedValue),{success:!0}}catch(r){return{success:!1,error:String(r)}}}var sf=["normal","additive","multiply","subtract"],ou={Normal:"normal",Additive:"additive",Multiply:"multiply",Subtract:"subtract"},Cx={normal:lt,additive:ct,multiply:tm,subtract:em};function Zr(n){return typeof n=="string"&&sf.includes(n)?n:"normal"}function af(n){return Cx[n]??lt}function en(n,e){let t=af(e),i=n.transparent||e!=="normal";n.blending===t&&n.transparent===i||(n.blending=t,n.transparent=i,n.needsUpdate=!0)}var Vt=["left","right","top","bottom"],hr={x:["left","right"],y:["bottom","top"]},tn=4096,C=class n extends I{static scratchUnproject=new S;isCanvasLayer=!1;_opacity;_computedOpacity;_blendMode;_zIndex;_zAsRelative;_layoutEnabled;_flow;_horizontalAlign;_verticalAlign;layoutMargins={};authoredLayoutPosition=new N;authoredLayoutSize=new N;tmpPointerWorld=new N;hasAuthoredLayoutSize=!1;opacityMaterials=new Set;visibleOpacity;visibilityFade=null;constructor(e,t="Node2D"){super({...e,type:t}),this.layers.set(1);let i=e.position??new N(0,0);this.position.set(i.x,i.y,0);let r=e.scale??new N(1,1);this.scale.set(r.x,r.y,1);let o=e.rotation??0,s=R.degToRad(o);this.rotation.set(0,0,s);let a=n.normalizeLayout(e.layout);this._flow=n.normalizeFlow(e.flow),this._layoutEnabled=a.enabled,this._horizontalAlign=a.horizontalAlign,this._verticalAlign=a.verticalAlign,Object.assign(this.layoutMargins,n.readMargins(e.layout)),this.authoredLayoutPosition.set(i.x,i.y);let l=n.readInitialLayoutSize(e);l&&(this.authoredLayoutSize.copy(l),this.hasAuthoredLayoutSize=!0),this._opacity=n.clampOpacity(e.opacity??1),this._computedOpacity=this._opacity,this.visibleOpacity=this._opacity>0?this._opacity:1,(e.opacity!==void 0||typeof this.properties.opacity=="number")&&(this.properties.opacity=this._opacity),this._blendMode=Zr(e.blendMode??this.properties.blendMode),this.syncBlendModeProperty(),this._zIndex=n.clampZIndex(e.zIndex??this.properties.zIndex),this._zAsRelative=typeof e.zAsRelative=="boolean"?e.zAsRelative:typeof this.properties.zAsRelative=="boolean"?this.properties.zAsRelative:!0,this.syncZOrderProperties(),this.syncLayoutProperties()}get opacity(){return this._opacity}set opacity(e){let t=n.clampOpacity(e);this._opacity!==t&&(this._opacity=t,this.properties.opacity=t,!this.visibilityFade&&t>0&&(this.visibleOpacity=t),this.refreshComputedOpacityRecursive())}get computedOpacity(){return this._computedOpacity}get blendMode(){return this._blendMode}set blendMode(e){let t=Zr(e);this._blendMode!==t&&(this._blendMode=t,this.syncBlendModeProperty(),this.refreshBlendMode())}refreshBlendMode(){for(let e of this.opacityMaterials)en(e,this._blendMode),this.applyOpacityToMaterial(e)}syncBlendModeProperty(){this._blendMode!=="normal"?this.properties.blendMode=this._blendMode:delete this.properties.blendMode}get zIndex(){return this._zIndex}set zIndex(e){let t=n.clampZIndex(e);this._zIndex!==t&&(this._zIndex=t,this.syncZOrderProperties())}get zAsRelative(){return this._zAsRelative}set zAsRelative(e){let t=!!e;this._zAsRelative!==t&&(this._zAsRelative=t,this.syncZOrderProperties())}get effectiveZIndex(){if(!this._zAsRelative)return this._zIndex;let e=this.parent;return e instanceof n?e.effectiveZIndex+this._zIndex:this._zIndex}get layoutEnabled(){return this._layoutEnabled}set layoutEnabled(e){let t=!!e;this._layoutEnabled!==t&&(this.captureAuthoredLayoutRectFromCurrent(),this._layoutEnabled=t,this.pruneLayoutMargins(),this.syncLayoutProperties())}get horizontalAlign(){return this._horizontalAlign}set horizontalAlign(e){let t=n.normalizeHorizontalAlign(e);this._horizontalAlign!==t&&(this.captureAuthoredLayoutRectFromCurrent(),this._horizontalAlign=t,this.pruneLayoutMargins(),this.syncLayoutProperties())}get verticalAlign(){return this._verticalAlign}set verticalAlign(e){let t=n.normalizeVerticalAlign(e);this._verticalAlign!==t&&(this.captureAuthoredLayoutRectFromCurrent(),this._verticalAlign=t,this.pruneLayoutMargins(),this.syncLayoutProperties())}getLayoutConfig(){return{enabled:this._layoutEnabled,horizontalAlign:this._horizontalAlign,verticalAlign:this._verticalAlign,...this.layoutMargins}}setLayoutConfig(e){let t=n.normalizeLayout(e);this.captureAuthoredLayoutRectFromCurrent(),this._layoutEnabled=t.enabled,this._horizontalAlign=t.horizontalAlign,this._verticalAlign=t.verticalAlign;for(let i of Vt)delete this.layoutMargins[i];Object.assign(this.layoutMargins,n.readMargins(e)),this.pruneLayoutMargins(),this.syncLayoutProperties()}getLayoutMargin(e){return this.layoutMargins[e]}setLayoutMargin(e,t){typeof t=="number"&&Number.isFinite(t)?this.layoutMargins[e]=t:delete this.layoutMargins[e],this.syncLayoutProperties()}usesLayoutMargin(e){let t=e==="left"||e==="right"?"x":"y",i=this.layoutAxisMode(t),[r,o]=hr[t];return i!=="none"&&(e===r&&i!=="hi"||e===o&&i!=="lo")&&!this.flowOwnsAxis(t)&&this.parent instanceof n}resolveLayoutMargins(){let e={};if(!this._layoutEnabled)return e;let t=this.parent instanceof n?this.parent:null,i=t?this.normalizeReferenceSize(t.getAuthoredLayoutSize()):null,r=this.getAuthoredLayoutSize();for(let o of["x","y"]){let s=this.layoutAxisMode(o);if(s==="none"||this.flowOwnsAxis(o))continue;let[a,l]=hr[o],c=i&&n.deriveMargins(o==="x"?this.authoredLayoutPosition.x:this.authoredLayoutPosition.y,o==="x"?r.width:r.height,o==="x"?i.width:i.height);if(s!=="hi"){let u=this.layoutMargins[a]??c?.lo;u!==void 0&&(e[a]=u)}if(s!=="lo"){let u=this.layoutMargins[l]??c?.hi;u!==void 0&&(e[l]=u)}}return e}isMarginAxis(e){let t=this.layoutAxisMode(e);if(t==="none"||this.flowOwnsAxis(e))return!1;let[i,r]=hr[e],o=this.resolveLayoutMargins();return(t==="hi"||o[i]!==void 0)&&(t==="lo"||o[r]!==void 0)}marginDerivedSizeKeys(){let e=this._horizontalAlign==="stretch"&&this.isMarginAxis("x"),t=this._verticalAlign==="stretch"&&this.isMarginAxis("y"),i=this.squareSizeKey();return i?e||t?[i]:[]:[...e?["width"]:[],...t?["height"]:[]]}squareSizeKey(){let e=this;return typeof e.width=="number"&&typeof e.height=="number"?null:typeof e.size=="number"?"size":typeof e.radius=="number"?"radius":null}stretchesAxis(e){return this.layoutAxisMode(e)==="both"&&!this.flowOwnsAxis(e)}captureAuthoredLayoutRectFromCurrent(e=!1){this.authoredLayoutPosition.set(this.position.x,this.position.y);let t=this.getCurrentLayoutSize();if(t.width>0&&t.height>0&&(this.authoredLayoutSize.set(t.width,t.height),this.hasAuthoredLayoutSize=!0),!e)return;for(let r of Vt)delete this.layoutMargins[r];if(!this._layoutEnabled||!(this.parent instanceof n))return;let i=this.normalizeReferenceSize(this.parent.getCurrentLayoutSize());for(let r of["x","y"]){let o=this.layoutAxisMode(r);if(o==="none"||this.flowOwnsAxis(r))continue;let[s,a]=hr[r],l=n.deriveMargins(r==="x"?this.position.x:this.position.y,r==="x"?t.width:t.height,r==="x"?i.width:i.height);o!=="hi"&&(this.layoutMargins[s]=l.lo),o!=="lo"&&(this.layoutMargins[a]=l.hi)}this.syncLayoutProperties()}pruneLayoutMargins(){for(let e of["x","y"]){let t=this._layoutEnabled?this.layoutAxisMode(e):"none",[i,r]=hr[e];(t==="none"||t==="hi")&&delete this.layoutMargins[i],(t==="none"||t==="lo")&&delete this.layoutMargins[r]}}layoutAxisMode(e){if(!this._layoutEnabled)return"none";switch(e==="x"?this._horizontalAlign:this._verticalAlign){case"left":case"bottom":return"lo";case"right":case"top":return"hi";case"stretch":return"both";default:return"none"}}flowOwnsAxis(e){let t=this.parent;return!(t instanceof n)||!t.flow.enabled?!1:t.flow.direction==="horizontal"==(e==="x")}static deriveMargins(e,t,i){let r=Math.max(0,t)/2;return{lo:e-r+i/2,hi:i/2-(e+r)}}static readMargins(e){let t={};for(let i of Vt){let r=e?.[i];typeof r=="number"&&Number.isFinite(r)&&(t[i]=r)}return t}getAuthoredLayoutPosition(){return{x:this.authoredLayoutPosition.x,y:this.authoredLayoutPosition.y}}setAuthoredLayoutPosition(e,t){this.authoredLayoutPosition.set(e,t)}getAuthoredLayoutSize(){return this.ensureAuthoredLayoutSize(),{width:this.authoredLayoutSize.x,height:this.authoredLayoutSize.y}}setAuthoredLayoutSize(e,t){this.authoredLayoutSize.set(Math.max(0,e),Math.max(0,t)),this.hasAuthoredLayoutSize=!0}getPointerWorldPosition(e=this.tmpPointerWorld){let t=this.input;return t?this.screenPointToWorld(t.pointerPosition.x,t.pointerPosition.y,e):null}screenPointToWorld(e,t,i=this.tmpPointerWorld){let r=this.input;if(!r)return null;let o=Math.max(1,r.width),s=Math.max(1,r.height),a=this.scene?.getUICamera();if(a&&!this.isInOverlayBand()){let h=e/o*2-1,d=-(t/s*2-1);return n.scratchUnproject.set(h,d,0).unproject(a),i.set(n.scratchUnproject.x,n.scratchUnproject.y),i}let l=this.scene?.getLogicalCameraSize(),c=l&&Number.isFinite(l.width)&&l.width>0?l.width:o,u=l&&Number.isFinite(l.height)&&l.height>0?l.height:s;return i.set(e/o*c-c/2,u/2-t/s*u),i}isInOverlayBand(){let e=this;for(;e;){if(e.isCanvasLayer)return!0;e=e.parent instanceof n?e.parent:null}return!1}get flow(){return this._flow}setFlow(e){this._flow=n.normalizeFlow(e??void 0),this._flow.enabled&&this.applyFlowLayout()}static normalizeFlow(e){return{enabled:e?.enabled===!0,direction:e?.direction==="horizontal"?"horizontal":"vertical",gap:Number.isFinite(e?.gap)?Math.max(0,Number(e?.gap)):0,paddingX:Number.isFinite(e?.paddingX)?Math.max(0,Number(e?.paddingX)):0,paddingY:Number.isFinite(e?.paddingY)?Math.max(0,Number(e?.paddingY)):0,align:e?.align==="center"||e?.align==="end"?e.align:"start",autoSize:e?.autoSize===!0}}applyFlowLayout(){if(!this._flow.enabled)return;let e=this._flow,t=this.getCurrentLayoutSize(),i=this.children.filter(l=>l instanceof n&&l.visible);if(i.length===0)return;let r=e.direction==="vertical",o=r?t.width:t.height,s=r?e.paddingX:e.paddingY,a=r?e.paddingY:e.paddingX;for(let l of i){let c=l.getCurrentLayoutSize(),u=r?c.height:c.width,h=r?c.width:c.height,d=l.layoutEnabled,p;d?p=r?l.position.x:l.position.y:e.align==="center"?p=0:e.align==="end"?p=o/2-s-h/2:p=-o/2+s+h/2;let f=r?t.height/2-a-u/2:-t.width/2+a+u/2,m=l.getAuthoredLayoutPosition();r?(l.position.set(p,f,l.position.z),l.setAuthoredLayoutPosition(d?m.x:p,f)):(l.position.set(f,p,l.position.z),l.setAuthoredLayoutPosition(f,d?m.y:p)),a+=u+e.gap}if(e.autoSize){let l=a-e.gap+(r?e.paddingY:e.paddingX),c=r?{width:t.width,height:Math.max(l,0)}:{width:Math.max(l,0),height:t.height};this.setLayoutSizeIfPossible(c),(c.height!==t.height||c.width!==t.width)&&this.applyFlowLayout()}}setLayoutSizeIfPossible(e){let t=this;typeof t.width=="number"&&typeof t.height=="number"&&(t.width=e.width,t.height=e.height),this.authoredLayoutSize.set(e.width,e.height)}serializeFlow(){let e=this._flow,t={};if(e.direction!=="vertical"&&(t.direction=e.direction),e.gap!==0&&(t.gap=e.gap),e.paddingX!==0&&(t.paddingX=e.paddingX),e.paddingY!==0&&(t.paddingY=e.paddingY),e.align!=="start"&&(t.align=e.align),e.autoSize&&(t.autoSize=!0),!(!e.enabled&&Object.keys(t).length===0))return{enabled:e.enabled,...t}}applyAnchoredLayoutRecursive(e,t){this._layoutEnabled&&this.applyAnchoredLayout(e,t),this.applyFlowLayout();let i=this.getCurrentLayoutSize(),r=this.getAuthoredLayoutSize();for(let o of this.children)o instanceof n&&o.applyAnchoredLayoutRecursive(i,r)}reflowAnchoredChildren(){let e=this.getCurrentLayoutSize(),t=this.getAuthoredLayoutSize();for(let i of this.children)i instanceof n&&i.applyAnchoredLayoutRecursive(e,t)}getCurrentLayoutSize(){let e=this.readCurrentLayoutSize();return e||(this.hasAuthoredLayoutSize?{width:this.authoredLayoutSize.x,height:this.authoredLayoutSize.y}:{width:0,height:0})}serializeLayout(){let e={};if(this._horizontalAlign!=="center"&&(e.horizontalAlign=this._horizontalAlign),this._verticalAlign!=="center"&&(e.verticalAlign=this._verticalAlign),this._layoutEnabled){let t=this.resolveLayoutMargins();for(let i of Vt)t[i]!==void 0&&(e[i]=t[i])}if(!(!this._layoutEnabled&&Object.keys(e).length===0))return{enabled:this._layoutEnabled,...e}}hide(e=0,t){let i=n.toNonNegativeSeconds(e);if(this.opacity>0&&(this.visibleOpacity=this.opacity),i===0){this.visibilityFade=null,this.opacity=0,this.setVisibleState(!1),t?.();return}this.setVisibleState(!0),this.visibilityFade={from:this.opacity,to:0,duration:i,elapsed:0,hideAfterComplete:!0,onComplete:t}}show(e=0,t){let i=n.toNonNegativeSeconds(e),r=this.visibleOpacity>0?this.visibleOpacity:1;if(this.setVisibleState(!0),i===0){this.visibilityFade=null,this.opacity=r,t?.();return}this.visibilityFade={from:this.opacity,to:r,duration:i,elapsed:0,hideAfterComplete:!1,onComplete:t}}tick(e){if(super.tick(e),!this.visibilityFade)return;let t=this.visibilityFade;t.elapsed=Math.min(t.duration,t.elapsed+Math.max(0,e));let i=t.duration>0?t.elapsed/t.duration:1,r=t.from+(t.to-t.from)*i;if(this.opacity=r,!(t.elapsed<t.duration)){if(this.opacity=t.to,this.visibilityFade=null,t.hideAfterComplete){this.setVisibleState(!1),t.onComplete?.();return}this.setVisibleState(!0),t.onComplete?.()}}registerOpacityMaterial(e,t){t!==void 0?e.userData.__pix3BaseOpacity=n.clampOpacity(t):typeof e.userData.__pix3BaseOpacity!="number"&&(e.userData.__pix3BaseOpacity=n.clampOpacity(e.opacity)),e.userData.__pix3OriginalTransparent===void 0&&(e.userData.__pix3OriginalTransparent=e.transparent),this.opacityMaterials.add(e),en(e,this._blendMode),this.applyOpacityToMaterial(e)}setOpacityMaterialBase(e,t){e.userData.__pix3BaseOpacity=n.clampOpacity(t),e.userData.__pix3OriginalTransparent===void 0&&(e.userData.__pix3OriginalTransparent=e.transparent),this.opacityMaterials.add(e),en(e,this._blendMode),this.applyOpacityToMaterial(e)}applyOpacityToMaterial(e){let t=e.userData.__pix3BaseOpacity,i=typeof t=="number"?n.clampOpacity(t):n.clampOpacity(e.opacity);e.opacity=i*this._computedOpacity;let r=e.userData.__pix3OriginalTransparent;e.transparent=r||e.opacity<1||this._blendMode!=="normal",e.needsUpdate=!0}refreshOpacity(){this.refreshComputedOpacityRecursive()}getParentComputedOpacity(){return this.parent instanceof n?this.parent.computedOpacity:1}refreshComputedOpacityRecursive(){this._computedOpacity=this._opacity*this.getParentComputedOpacity();for(let e of this.opacityMaterials)this.applyOpacityToMaterial(e);for(let e of this.children)e instanceof n&&e.refreshComputedOpacityRecursive()}static clampOpacity(e){let t=Number.isFinite(e)?e:1;return Math.max(0,Math.min(1,t))}static normalizeLayout(e){return{enabled:!!e?.enabled,horizontalAlign:n.normalizeHorizontalAlign(e?.horizontalAlign),verticalAlign:n.normalizeVerticalAlign(e?.verticalAlign)}}static normalizeHorizontalAlign(e){switch(e){case"left":case"right":case"stretch":return e;default:return"center"}}static normalizeVerticalAlign(e){switch(e){case"top":case"bottom":case"stretch":return e;default:return"center"}}static readInitialLayoutSize(e){let t=e,i=n.toFiniteNumber(t.width),r=n.toFiniteNumber(t.height);if(i!==void 0&&r!==void 0)return new N(Math.max(0,i),Math.max(0,r));let o=n.toFiniteNumber(t.size);if(o!==void 0)return new N(Math.max(0,o),Math.max(0,o));let s=n.toFiniteNumber(t.radius);return s!==void 0?new N(Math.max(0,s*2),Math.max(0,s*2)):null}static toFiniteNumber(e){return typeof e=="number"&&Number.isFinite(e)?e:void 0}static toNonNegativeSeconds(e){return Number.isFinite(e)?Math.max(0,e):0}setVisibleState(e){this.visible=e,this.properties.visible=e}ensureAuthoredLayoutSize(){if(this.hasAuthoredLayoutSize)return;let e=this.readCurrentLayoutSize();e&&(this.authoredLayoutSize.set(e.width,e.height),this.hasAuthoredLayoutSize=!0)}readCurrentLayoutSize(){let e=this,t=n.toFiniteNumber(e.width),i=n.toFiniteNumber(e.height);if(t!==void 0&&i!==void 0)return{width:Math.max(0,t),height:Math.max(0,i)};let r=n.toFiniteNumber(e.size);if(r!==void 0){let s=Math.max(0,r);return{width:s,height:s}}let o=n.toFiniteNumber(e.radius);if(o!==void 0){let s=Math.max(0,o*2);return{width:s,height:s}}return null}applyAnchoredLayout(e,t){this.ensureAuthoredLayoutSize();let i=this.getAuthoredLayoutSize(),r=this.normalizeReferenceSize(t??e),o=this.normalizeReferenceSize(e),s=this.parent instanceof n,a=(p,f)=>this.resolveAxisLayout(p,p==="x"?o.width:o.height,p==="x"?r.width:r.height,p==="x"?this.authoredLayoutPosition.x:this.authoredLayoutPosition.y,p==="x"?i.width:i.height,s,f),l=this.squareSizeKey()!==null,c=l&&this.stretchesAxis("x"),u=l&&this.stretchesAxis("y"),h,d;c&&!u?(h=a("x"),d=a("y",h.size)):u&&!c?(d=a("y"),h=a("x",d.size)):(h=a("x"),d=a("y")),this.position.set(h.center,d.center,this.position.z),this.applyCurrentLayoutSize(h.size,d.size)}normalizeReferenceSize(e){return{width:Math.max(1,e.width||0),height:Math.max(1,e.height||0)}}resolveAxisLayout(e,t,i,r,o,s,a){let l=Math.max(0,o),c=a===void 0?l:Math.max(0,a),u=this.layoutAxisMode(e);if(u==="none"||this.flowOwnsAxis(e))return{center:r,size:c};let[h,d]=hr[e],p=this.layoutMargins[h],f=this.layoutMargins[d];if(u!=="hi"&&p===void 0||u!=="lo"&&f===void 0){let m=n.deriveMargins(r,l,i);u!=="hi"&&p===void 0&&(p=m.lo,s&&(this.layoutMargins[h]=p)),u!=="lo"&&f===void 0&&(f=m.hi,s&&(this.layoutMargins[d]=f))}switch(u){case"lo":return{center:-t/2+p+c/2,size:c};case"hi":return{center:t/2-f-c/2,size:c};default:{let m=-t/2+p,g=t/2-f;return{center:(m+g)/2,size:Math.max(1,g-m)}}}}applyCurrentLayoutSize(e,t){let i=ke(this),r=Ot(i,"width"),o=Ot(i,"height");if(r&&o){ur(this,r,e),ur(this,o,t);return}let s=Ot(i,"size");if(s){ur(this,s,Math.max(e,t));return}let a=Ot(i,"radius");a&&ur(this,a,Math.min(e,t)/2)}static clampZIndex(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.max(-tn,Math.min(tn,Math.round(t))):0}syncZOrderProperties(){this._zIndex!==0?this.properties.zIndex=this._zIndex:delete this.properties.zIndex,this._zAsRelative?delete this.properties.zAsRelative:this.properties.zAsRelative=!1}syncLayoutProperties(){if(!this._layoutEnabled){delete this.properties.layout;return}this.properties.layout={enabled:!0,horizontalAlign:this._horizontalAlign,verticalAlign:this._verticalAlign,...this.layoutMargins}}add(...e){super.add(...e);for(let t of e)t.traverse(i=>{i.layers.set(1)}),t instanceof n&&t.refreshComputedOpacityRecursive();return this}static marginPropertyName(e){return`layout${e[0].toUpperCase()}${e.slice(1)}`}static marginPropertyDefinition(e){let t=e[0].toUpperCase()+e.slice(1);return{name:n.marginPropertyName(e),type:"number",ui:{label:t,description:`Distance from the parent's ${e} edge to this node's ${e} edge`,group:"Anchors",step:1,precision:2,readOnly:i=>!(i instanceof n)||!i.usesLayoutMargin(e)},getValue:i=>{let r=i;return r.getLayoutMargin(e)??r.resolveLayoutMargins()[e]??0},setValue:(i,r)=>{i.setLayoutMargin(e,Number(r))}}}static getPropertySchema(){let e=I.getPropertySchema();return{nodeType:"Node2D",extends:"NodeBase",properties:[...e.properties,{name:"position",type:"vector2",ui:{label:"Position",group:"Transform",step:.01,precision:2},getValue:t=>{let i=t;return{x:i.position.x,y:i.position.y}},setValue:(t,i)=>{let r=t,o=i;r.position.x=o.x,r.position.y=o.y,r.setAuthoredLayoutPosition(o.x,o.y)}},{name:"rotation",type:"number",ui:{label:"Rotation",description:"Z-axis rotation",group:"Transform",step:.1,precision:1,unit:"\xB0"},getValue:t=>t.rotation.z*(180/Math.PI),setValue:(t,i)=>{let r=t;r.rotation.z=Number(i)*(Math.PI/180)}},{name:"scale",type:"vector2",ui:{label:"Scale",group:"Transform",step:.01,precision:2,min:0},getValue:t=>{let i=t;return{x:i.scale.x,y:i.scale.y}},setValue:(t,i)=>{let r=t,o=i;r.scale.x=o.x,r.scale.y=o.y}},{name:"opacity",type:"number",ui:{label:"Opacity",description:"Local opacity multiplier inherited by child 2D nodes",group:"Style",step:.01,precision:2,min:0,max:1},getValue:t=>t.opacity,setValue:(t,i)=>{t.opacity=Number(i)}},{name:"blendMode",type:"select",ui:{label:"Blend Mode",description:"How this node's own visuals combine with what is behind them. Not inherited by child nodes; a non-normal mode opts the node out of 2D batching",group:"Style",options:ou},getValue:t=>t.blendMode,setValue:(t,i)=>{t.blendMode=Zr(i)}},{name:"zIndex",type:"number",ui:{label:"Z Index",description:"Draw-order override for the 2D pass. Higher draws on top; ties keep scene-tree order",group:"Ordering",step:1,precision:0,min:-tn,max:tn},getValue:t=>t.zIndex,setValue:(t,i)=>{t.zIndex=Number(i)}},{name:"zAsRelative",type:"boolean",ui:{label:"Z Relative",description:"Add Z Index to the parent's effective z instead of using it as absolute",group:"Ordering"},getValue:t=>t.zAsRelative,setValue:(t,i)=>{t.zAsRelative=!!i}},{name:"flowEnabled",type:"boolean",ui:{label:"Flow",description:"Stack this container\u2019s children in tree order. Anchors place ONE node against its parent; a flow decides where each child in a column or a row begins.",group:"Flow"},getValue:t=>t.flow.enabled,setValue:(t,i)=>{let r=t;r.setFlow({...r.flow,enabled:!!i})}},{name:"flowDirection",type:"select",ui:{label:"Direction",group:"Flow",options:["vertical","horizontal"]},getValue:t=>t.flow.direction,setValue:(t,i)=>{let r=t,o=i==="horizontal"?"horizontal":"vertical";r.setFlow({...r.flow,direction:o})}},{name:"flowGap",type:"number",ui:{label:"Gap",group:"Flow",min:0,max:400,step:1},getValue:t=>t.flow.gap,setValue:(t,i)=>{let r=t;r.setFlow({...r.flow,gap:Number(i)})}},{name:"flowPaddingX",type:"number",ui:{label:"Padding X",group:"Flow",min:0,max:400,step:1},getValue:t=>t.flow.paddingX,setValue:(t,i)=>{let r=t;r.setFlow({...r.flow,paddingX:Number(i)})}},{name:"flowPaddingY",type:"number",ui:{label:"Padding Y",group:"Flow",min:0,max:400,step:1},getValue:t=>t.flow.paddingY,setValue:(t,i)=>{let r=t;r.setFlow({...r.flow,paddingY:Number(i)})}},{name:"flowAlign",type:"select",ui:{label:"Cross Axis",group:"Flow",options:["start","center","end"],description:"Where each child sits on the axis the flow does NOT own"},getValue:t=>t.flow.align,setValue:(t,i)=>{let r=t,o=i==="center"||i==="end"?i:"start";r.setFlow({...r.flow,align:o})}},{name:"flowAutoSize",type:"boolean",ui:{label:"Auto Size",group:"Flow",description:"Grow the container along the flow axis so the last child fits"},getValue:t=>t.flow.autoSize,setValue:(t,i)=>{let r=t;r.setFlow({...r.flow,autoSize:!!i})}},{name:"layoutEnabled",type:"boolean",ui:{label:"Anchors",description:"Enable anchor-based layout for this 2D node",group:"Anchors"},getValue:t=>t.layoutEnabled,setValue:(t,i)=>{t.layoutEnabled=!!i}},{name:"horizontalAlign",type:"select",ui:{label:"Horizontal",description:"Horizontal anchor mode",group:"Anchors",options:["left","center","right","stretch"],readOnly:t=>!(t instanceof n)||!t.layoutEnabled},getValue:t=>t.horizontalAlign,setValue:(t,i)=>{t.horizontalAlign=i}},{name:"verticalAlign",type:"select",ui:{label:"Vertical",description:"Vertical anchor mode",group:"Anchors",options:["top","center","bottom","stretch"],readOnly:t=>!(t instanceof n)||!t.layoutEnabled},getValue:t=>t.verticalAlign,setValue:(t,i)=>{t.verticalAlign=i}},...Vt.map(t=>n.marginPropertyDefinition(t))],groups:{...e.groups,Transform:{label:"Transform",description:"2D position, rotation, and scale",expanded:!0},Style:{label:"Style",description:"2D visual styling properties",expanded:!1},Ordering:{label:"Ordering",description:"Draw order within the 2D pass",expanded:!1},Anchors:{label:"Anchors",description:"Anchor-based layout relative to the containing frame",expanded:!1},Flow:{label:"Flow",description:"Stack this container\u2019s children along one axis, in tree order",expanded:!1}}}}};function x(n,e,t){return{name:n,type:e,...t}}function bs(n,e){if(n==="number"&&typeof e=="string"){let t=e.trim();if(t==="")return e;let i=Number(t);return Number.isFinite(i)?i:e}if(n==="boolean"&&typeof e=="string"){let t=e.trim().toLowerCase();return t==="true"?!0:t==="false"?!1:e}return n==="string"&&(typeof e=="number"||typeof e=="boolean")?String(e):e}function Mx(n,e,t){return{[n]:{label:e,...t}}}function le(n,e){return{nodeType:e.nodeType,extends:e.extends||n.nodeType,properties:[...n.properties,...e.properties],groups:{...n.groups,...e.groups}}}function Ss(n,e){return(n.targets??["standard"]).includes(e)}var Dx={id:"core:dissolve",key:"dissolve",displayName:"Dissolve",description:"Noise-thresholded discard with a glowing edge. Animate Amount 0\u21921 to dissolve away.",category:"Surface",keywords:["dissolve","disintegrate","erode","discard","burn"],define:"PIX3_FX_DISSOLVE",targets:["standard"],fragmentPars:`
139
+ uniform float uPix3DissolveAmount;
140
+ uniform float uPix3DissolveScale;
141
+ uniform float uPix3DissolveEdgeWidth;
142
+ uniform vec3 uPix3DissolveEdgeColor;
143
+ float pix3Hash(vec2 p){ return fract(sin(dot(p, vec2(127.1, 311.7))) * 43758.5453123); }
144
+ float pix3Noise(vec2 p){
145
+ vec2 i = floor(p); vec2 f = fract(p); vec2 u = f * f * (3.0 - 2.0 * f);
146
+ return mix(mix(pix3Hash(i), pix3Hash(i + vec2(1.0, 0.0)), u.x),
147
+ mix(pix3Hash(i + vec2(0.0, 1.0)), pix3Hash(i + vec2(1.0, 1.0)), u.x), u.y);
148
+ }`,chunks:[{stage:"fragment",anchor:"emissivemap_fragment",position:"after",glsl:`
149
+ float pix3N = pix3Noise(vPix3Uv * uPix3DissolveScale)
150
+ - uPix3DissolveAmount * (1.0 + uPix3DissolveEdgeWidth);
151
+ if (pix3N < 0.0) discard;
152
+ totalEmissiveRadiance += uPix3DissolveEdgeColor
153
+ * (1.0 - smoothstep(0.0, max(uPix3DissolveEdgeWidth, 1e-4), pix3N));`}],params:[{key:"amount",type:"number",default:0,uniform:"uPix3DissolveAmount",ui:{label:"Amount",min:0,max:1,step:.01,precision:2,slider:!0}},{key:"scale",type:"number",default:8,uniform:"uPix3DissolveScale",ui:{label:"Noise Scale",min:.1,max:64,step:.1,precision:2}},{key:"edgeWidth",type:"number",default:.05,uniform:"uPix3DissolveEdgeWidth",ui:{label:"Edge Width",min:0,max:.5,step:.005,precision:3}},{key:"edgeColor",type:"color",default:"#ffae42",uniform:"uPix3DissolveEdgeColor",ui:{label:"Edge Color"}}],createUniforms:()=>({uPix3DissolveAmount:{value:0},uPix3DissolveScale:{value:8},uPix3DissolveEdgeWidth:{value:.05},uPix3DissolveEdgeColor:{value:new L("#ffae42")}})},Ex={id:"core:rim",key:"rim",displayName:"Rim Light",description:"Fresnel-based emissive rim glow, strongest at grazing angles.",category:"Surface",keywords:["rim","fresnel","glow","outline","edge"],define:"PIX3_FX_RIM",targets:["standard"],fragmentPars:`
154
+ uniform vec3 uPix3RimColor;
155
+ uniform float uPix3RimIntensity;
156
+ uniform float uPix3RimPower;`,chunks:[{stage:"fragment",anchor:"emissivemap_fragment",position:"after",glsl:`
157
+ float pix3Fr = pow(1.0 - saturate(dot(normalize(vViewPosition), normal)), uPix3RimPower);
158
+ totalEmissiveRadiance += uPix3RimColor * pix3Fr * uPix3RimIntensity;`}],params:[{key:"color",type:"color",default:"#ffffff",uniform:"uPix3RimColor",ui:{label:"Color"}},{key:"intensity",type:"number",default:1,uniform:"uPix3RimIntensity",ui:{label:"Intensity",min:0,max:5,step:.05,precision:2,slider:!0}},{key:"power",type:"number",default:2,uniform:"uPix3RimPower",ui:{label:"Power",min:.5,max:8,step:.1,precision:2}}],createUniforms:()=>({uPix3RimColor:{value:new L("#ffffff")},uPix3RimIntensity:{value:1},uPix3RimPower:{value:2}})},Nx={id:"core:uv-scroll",key:"uvScroll",displayName:"UV Scroll",description:"Scrolls the albedo map over time (play-mode only). Requires an Albedo Map.",category:"Texture",keywords:["uv","scroll","flow","conveyor","panner","texture"],define:"PIX3_FX_UVSCROLL",targets:["standard","basic"],vertexPars:"uniform vec2 uPix3UvOffset;",chunks:[{stage:"vertex",anchor:"uv_vertex",position:"after",glsl:`
159
+ #if defined( USE_MAP )
160
+ vMapUv += uPix3UvOffset;
161
+ #endif`}],params:[{key:"speed",type:"vector2",default:{x:.1,y:0},ui:{label:"Speed",step:.01,precision:2,unit:"uv/s"}}],createUniforms:()=>({uPix3UvOffset:{value:new N}}),onTick:(n,e)=>{let t=n.uniforms.uPix3UvOffset?.value,i=n.params.speed;!t||!i||(t.x=(t.x+i.x*e)%1,t.y=(t.y+i.y*e)%1)}},Ix={id:"core:flash",key:"flash",displayName:"Flash Tint",description:"Blends the final lit colour toward a flat colour \u2014 a hit / damage flash.",category:"Color",keywords:["flash","tint","hit","damage","blink"],define:"PIX3_FX_FLASH",targets:["standard","basic"],fragmentPars:`
162
+ uniform vec3 uPix3FlashColor;
163
+ uniform float uPix3FlashAmount;`,chunks:[{stage:"fragment",anchor:"opaque_fragment",position:"before",glsl:`
164
+ outgoingLight = mix(outgoingLight, uPix3FlashColor, saturate(uPix3FlashAmount));`}],params:[{key:"color",type:"color",default:"#ffffff",uniform:"uPix3FlashColor",ui:{label:"Color"}},{key:"amount",type:"number",default:0,uniform:"uPix3FlashAmount",ui:{label:"Amount",min:0,max:1,step:.01,precision:2,slider:!0}}],createUniforms:()=>({uPix3FlashColor:{value:new L("#ffffff")},uPix3FlashAmount:{value:0}})},Rx={id:"core:adjust",key:"adjust",displayName:"Adjust (Brightness/Contrast/Saturation)",description:"Brightness, contrast and saturation grade on the base color.",category:"Color",keywords:["adjust","brightness","contrast","saturation","darken","lighten","hover","grade","hsl"],define:"PIX3_FX_ADJUST",targets:["basic","standard"],fragmentPars:`
165
+ uniform float uPix3AdjustSaturation;
166
+ uniform float uPix3AdjustContrast;
167
+ uniform float uPix3AdjustBrightness;`,chunks:[{stage:"fragment",anchor:"color_fragment",position:"after",glsl:`
168
+ float pix3AdjL = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));
169
+ diffuseColor.rgb = mix(vec3(pix3AdjL), diffuseColor.rgb, uPix3AdjustSaturation);
170
+ diffuseColor.rgb = (diffuseColor.rgb - 0.5) * uPix3AdjustContrast + 0.5;
171
+ diffuseColor.rgb *= uPix3AdjustBrightness;`}],params:[{key:"saturation",type:"number",default:1,uniform:"uPix3AdjustSaturation",ui:{label:"Saturation",min:0,max:2,step:.01,precision:2,slider:!0}},{key:"contrast",type:"number",default:1,uniform:"uPix3AdjustContrast",ui:{label:"Contrast",min:0,max:2,step:.01,precision:2,slider:!0}},{key:"brightness",type:"number",default:1,uniform:"uPix3AdjustBrightness",ui:{label:"Brightness",min:0,max:2,step:.01,precision:2,slider:!0}}],createUniforms:()=>({uPix3AdjustSaturation:{value:1},uPix3AdjustContrast:{value:1},uPix3AdjustBrightness:{value:1}})},Bx={id:"core:grayscale",key:"grayscale",displayName:"Grayscale",description:"Desaturates the base color toward its luminance.",category:"Color",keywords:["grayscale","greyscale","desaturate","mono","monochrome","black","white"],define:"PIX3_FX_GRAYSCALE",targets:["basic","standard"],fragmentPars:`
172
+ uniform float uPix3GrayAmount;`,chunks:[{stage:"fragment",anchor:"color_fragment",position:"after",glsl:`
173
+ float pix3GrayL = dot(diffuseColor.rgb, vec3(0.2126, 0.7152, 0.0722));
174
+ diffuseColor.rgb = mix(diffuseColor.rgb, vec3(pix3GrayL), uPix3GrayAmount);`}],params:[{key:"amount",type:"number",default:1,uniform:"uPix3GrayAmount",ui:{label:"Amount",min:0,max:1,step:.01,precision:2,slider:!0}}],createUniforms:()=>({uPix3GrayAmount:{value:1}})},Ox={id:"core:tint",key:"tint",displayName:"Tint",description:"Multiplies the base color by a tint color.",category:"Color",keywords:["tint","color","colour","multiply","recolor","colorize","hue"],define:"PIX3_FX_TINT",targets:["basic","standard"],fragmentPars:`
175
+ uniform vec3 uPix3TintColor;
176
+ uniform float uPix3TintAmount;`,chunks:[{stage:"fragment",anchor:"color_fragment",position:"after",glsl:`
177
+ diffuseColor.rgb = mix(diffuseColor.rgb, diffuseColor.rgb * uPix3TintColor, saturate(uPix3TintAmount));`}],params:[{key:"color",type:"color",default:"#ffffff",uniform:"uPix3TintColor",ui:{label:"Color"}},{key:"amount",type:"number",default:1,uniform:"uPix3TintAmount",ui:{label:"Amount",min:0,max:1,step:.01,precision:2,slider:!0}}],createUniforms:()=>({uPix3TintColor:{value:new L("#ffffff")},uPix3TintAmount:{value:1}})},vs=[Dx,Ex,Nx,Ix,Rx,Bx,Ox];var rn=new Map,lf=!1,ws=/^[a-zA-Z][a-zA-Z0-9]*$/;function cf(){if(!lf){lf=!0;for(let n of vs)uf(n)}}function uf(n){if(!ws.test(n.key))throw new Error(`[ShaderEffectRegistry] invalid effect key "${n.key}" (must match ${ws})`);for(let e of n.params)if(!ws.test(e.key))throw new Error(`[ShaderEffectRegistry] effect "${n.id}" has invalid param key "${e.key}" (must match ${ws})`);if(rn.has(n.id))throw new Error(`[ShaderEffectRegistry] duplicate effect id "${n.id}"`);for(let e of rn.values())if(e.key===n.key)throw new Error(`[ShaderEffectRegistry] effect key "${n.key}" already used by "${e.id}"`);rn.set(n.id,n)}function xs(n){return cf(),rn.get(n)}function Vx(){return cf(),[...rn.values()]}var Ps={uv_vertex:"#include <uv_vertex>",emissivemap_fragment:"#include <emissivemap_fragment>",opaque_fragment:"#include <opaque_fragment>",color_fragment:"#include <color_fragment>"};function hf(n,e){return n.map(t=>e==="vertex"?t.info.vertexPars:t.info.fragmentPars).filter(t=>!!t).join(`
178
+ `)}function ks(n,e,t){let i=[];for(let r of n)for(let o of r.info.chunks)o.stage===e&&o.anchor===t&&i.push(`#ifdef ${r.info.define}
179
+ ${o.glsl}
180
+ #endif`);return i.join(`
181
+ `)}function su(n,e,t){return t?n.replace(e,`${e}
182
+ ${t}`):n}function Lx(n,e,t){return t?n.replace(e,`${t}
183
+ ${e}`):n}function au(n,e,t){if(e.length===0)return;Object.assign(n.uniforms,t);let i=hf(e,"vertex");n.vertexShader=`varying vec2 vPix3Uv;
184
+ ${i?i+`
185
+ `:""}${n.vertexShader}`,n.vertexShader=su(n.vertexShader,Ps.uv_vertex,`vPix3Uv = uv;
186
+ ${ks(e,"vertex","uv_vertex")}`);let r=hf(e,"fragment");n.fragmentShader=`varying vec2 vPix3Uv;
187
+ ${r?r+`
188
+ `:""}${n.fragmentShader}`,n.fragmentShader=su(n.fragmentShader,Ps.color_fragment,ks(e,"fragment","color_fragment")),n.fragmentShader=su(n.fragmentShader,Ps.emissivemap_fragment,ks(e,"fragment","emissivemap_fragment")),n.fragmentShader=Lx(n.fragmentShader,Ps.opaque_fragment,ks(e,"fragment","opaque_fragment"))}function lu(n){return"pix3-gmesh-fx-v2:"+n.map(e=>e.type).join("+")}function _x(n){return typeof n=="object"&&n!==null&&typeof n.getShaderEffectStack=="function"}var _e=class{nodeType;target;onAttachmentsChanged;effects=[];fxUniforms={};materials=new Set;revision=0;schemaCache=null;constructor(e){this.nodeType=e.nodeType,this.target=e.target,this.onAttachmentsChanged=e.onAttachmentsChanged}get materialTarget(){return this.target}retarget(e){if(e===this.target)return;this.target=e;let t=this.effects.filter(i=>{let r=xs(i.type);return r?!Ss(r,e):!0});for(let i of t)this.detach(i.type);t.length>0&&console.warn(`[ShaderEffectStack] Dropped ${t.map(i=>`"${i.type}"`).join(", ")} \u2014 no GLSL for the "${e}" material.`)}install(e){e.onBeforeCompile=t=>{au(t,this.effects,this.fxUniforms)},e.customProgramCacheKey=()=>lu(this.effects),this.materials.add(e),this.syncDefinesOn(e,!0)}uninstall(e){this.materials.delete(e)}attach(e,t){if(this.effects.some(o=>o.type===e))return!1;let i=xs(e);if(!i)return console.warn(`[ShaderEffectStack] Unknown shader effect "${e}" \u2014 skipped.`),!1;if(!Ss(i,this.target))return console.warn(`[ShaderEffectStack] Effect "${e}" does not support the "${this.target}" material \u2014 skipped.`),!1;let r={type:e,info:i,enabled:typeof t?.enabled=="boolean"?t.enabled:!0,params:{},uniforms:i.createUniforms()};for(let o of i.params){let s=t?.params?.[o.key];r.params[o.key]=s!==void 0?df(s,o.type):Fx(o.default)}return this.effects.push(r),this.applyParamsToUniforms(r),this.rebuildUniformBag(),this.revision+=1,this.schemaCache=null,this.syncDefines(!0),this.onAttachmentsChanged?.(),!0}detach(e){let t=this.effects.findIndex(r=>r.type===e);if(t<0)return null;let[i]=this.effects.splice(t,1);return this.rebuildUniformBag(),this.revision+=1,this.schemaCache=null,this.syncDefines(!0),this.onAttachmentsChanged?.(),i??null}setEnabled(e,t){let i=this.effects.find(r=>r.type===e);!i||i.enabled===t||(i.enabled=t,this.syncDefines(!0))}get(e){return this.effects.find(t=>t.type===e||t.info.id===e||t.info.key===e)}setParam(e,t,i){let r=this.get(e);if(!r)return!1;let o=r.info.params.find(s=>s.key===t);return o?(this.writeEffectParam(r,o,i),!0):!1}getParam(e,t){let i=this.get(e);if(!i)return;let r=i.info.params.find(o=>o.key===t);if(r)return pf(i,r)}getAttached(){return this.effects}get isEmpty(){return this.effects.length===0}buildInstanceSchema(){if(this.effects.length===0)return null;if(this.schemaCache&&this.schemaCache.rev===this.revision)return this.schemaCache.schema;let e=[],t={};for(let r of this.effects){let o=`Effect: ${r.info.displayName}`;t[o]={label:r.info.displayName,expanded:!0},e.push(x(`fx.${r.info.key}.enabled`,"boolean",{ui:{label:"Enabled",group:o},getValue:()=>r.enabled,setValue:(s,a)=>this.setEnabled(r.type,!!a)}));for(let s of r.info.params)e.push(x(`fx.${r.info.key}.${s.key}`,s.type,{ui:{...s.ui??{},group:o,readOnly:()=>!r.enabled},getValue:()=>pf(r,s),setValue:(a,l)=>this.writeEffectParam(r,s,l)}))}let i={nodeType:this.nodeType,properties:e,groups:t};return this.schemaCache={rev:this.revision,schema:i},i}tick(e){for(let t of this.effects)t.enabled&&t.info.onTick&&t.info.onTick({params:t.params,uniforms:t.uniforms},e)}serialize(){return this.effects.map(e=>Wx(e))}rebuildUniformBag(){let e={};for(let t of this.effects)Object.assign(e,t.uniforms);this.fxUniforms=e}syncDefines(e){for(let t of this.materials)this.syncDefinesOn(t,e)}syncDefinesOn(e,t){e.defines??={};let i=e.defines;for(let r of Object.keys(i))r.startsWith("PIX3_FX_")&&delete i[r];for(let r of this.effects)r.enabled&&(i[r.info.define]="");t&&(e.needsUpdate=!0)}applyParamsToUniforms(e){for(let t of e.info.params)this.applyParamToUniform(e,t)}applyParamToUniform(e,t){if(!t.uniform)return;let i=e.uniforms[t.uniform];if(!i)return;let r=e.params[t.key];switch(t.type){case"number":i.value=Number(r);break;case"color":i.value.set(String(r));break;case"vector2":{let o=r;i.value.set(o.x,o.y);break}case"boolean":i.value=r?1:0;break}}writeEffectParam(e,t,i){e.params[t.key]=df(i,t.type),this.applyParamToUniform(e,t)}};function Fx(n){return n&&typeof n=="object"?{...n}:n}function df(n,e){switch(e){case"number":{let t=Number(n);return Number.isFinite(t)?t:0}case"color":return String(n);case"vector2":{if(Array.isArray(n))return{x:Number(n[0])||0,y:Number(n[1])||0};let t=n;return{x:Number(t?.x)||0,y:Number(t?.y)||0}}case"boolean":return!!n}}function pf(n,e){let t=n.params[e.key];if(e.type==="vector2"){let i=t;return{x:i.x,y:i.y}}return t}function zx(n,e,t){if(t==="vector2"){let i=n,r=e;return i.x===r.x&&i.y===r.y}return n===e}function Ux(n,e){if(e==="vector2"){let t=n;return{x:t.x,y:t.y}}return n}function Wx(n){let e={type:n.type,enabled:n.enabled},t={};for(let i of n.info.params){let r=n.params[i.key];zx(r,i.default,i.type)||(t[i.key]=Ux(r,i.type))}return Object.keys(t).length>0&&(e.params=t),e}function mf(n){if(typeof n!="object"||n===null)return!1;let e=n;return e.type==="texture"&&typeof e.url=="string"}function D(n){if(typeof n=="string"){let e=n.trim();return e.length>0?{type:"texture",url:e}:null}if(mf(n)){let e=n.url.trim();return e.length>0?{type:"texture",url:e}:null}if(typeof n=="object"&&n!==null){let e=n;if(typeof e.url=="string"){let t=e.url.trim();return t.length>0?{type:"texture",url:t}:null}}return null}var Ne="pix3Batchable2D",ff=[[-.5,.5],[.5,.5],[-.5,-.5],[.5,-.5]],gf=[[0,1],[1,1],[0,0],[1,0]],Hx=[0,1,2,2,1,3],As=new S,yf=new WeakMap,qx=1,Gx=n=>{if(!n||n.length===0)return"";let e=yf.get(n);return e===void 0&&(e=qx++,yf.set(n,e)),`:clip${e}`},cu=class{mesh;geometry;positions;uvs;colors;index;capacity;constructor(e=64){this.capacity=e,this.geometry=new ae,this.positions=this.makeAttr(this.capacity*4,3),this.uvs=this.makeAttr(this.capacity*4,2),this.colors=this.makeAttr(this.capacity*4,4),this.index=this.makeIndex(this.capacity),this.geometry.setAttribute("position",this.positions),this.geometry.setAttribute("uv",this.uvs),this.geometry.setAttribute("color",this.colors),this.geometry.setIndex(this.index),this.mesh=new O(this.geometry),this.mesh.matrixAutoUpdate=!1,this.mesh.frustumCulled=!1,this.mesh.visible=!1}makeAttr(e,t){let i=new Q(new Float32Array(e*t),t);return i.setUsage(oe),i}makeIndex(e){let t=new Uint32Array(e*6);for(let i=0;i<e;i++){let r=i*4;for(let o=0;o<6;o++)t[i*6+o]=r+Hx[o]}return new pm(t,1)}ensureCapacity(e){if(e<=this.capacity)return;let t=this.capacity;for(;t<e;)t*=2;this.capacity=t,this.positions=this.makeAttr(t*4,3),this.uvs=this.makeAttr(t*4,2),this.colors=this.makeAttr(t*4,4),this.index=this.makeIndex(t),this.geometry.setAttribute("position",this.positions),this.geometry.setAttribute("uv",this.uvs),this.geometry.setAttribute("color",this.colors),this.geometry.setIndex(this.index)}fill(e){this.ensureCapacity(e.length);let t=this.positions.array,i=this.uvs.array,r=this.colors.array,o=new L;for(let s=0;s<e.length;s++){let a=e[s],l=a.material,c=l.map,u=c?c.offset.x:0,h=c?c.offset.y:0,d=c?c.repeat.x:1,p=c?c.repeat.y:1;o.copy(l.color);let f=l.opacity,m=s*4;for(let g=0;g<4;g++){As.set(ff[g][0],ff[g][1],0).applyMatrix4(a.matrixWorld);let y=(m+g)*3;t[y]=As.x,t[y+1]=As.y,t[y+2]=As.z;let b=(m+g)*2;i[b]=u+gf[g][0]*d,i[b+1]=h+gf[g][1]*p;let v=(m+g)*4;r[v]=o.r,r[v+1]=o.g,r[v+2]=o.b,r[v+3]=f}}this.positions.needsUpdate=!0,this.uvs.needsUpdate=!0,this.colors.needsUpdate=!0,this.geometry.setDrawRange(0,e.length*6)}dispose(){this.geometry.dispose()}},nn=class{group=new Zi;pool=[];materials=new Map;batchMaps=new Map;suppressed=new Set;stats={batches:0,quads:0,passthrough:0};constructor(e){this.group.matrixAutoUpdate=!1,this.group.name="Pix3Batch2D",e.add(this.group)}get activeBatchMeshes(){return this.pool.filter(e=>e.mesh.visible).map(e=>e.mesh)}update(e){let t=this.segment(e),i=new Set;for(let o of t)for(let s of o.members)i.add(s.material);for(let o of i)o.visible=!1;for(let o of this.suppressed)i.has(o)||(o.visible=!0);this.suppressed=i;let r=0;for(let o=0;o<t.length;o++){let s=t[o],a=this.pool[o];a||(a=new cu,this.pool[o]=a,this.group.add(a.mesh)),a.fill(s.members),a.mesh.material=this.materialFor(s),a.mesh.renderOrder=s.order,a.mesh.layers.set(s.overlay?3:1),a.mesh.visible=!0,r+=s.members.length}for(let o=t.length;o<this.pool.length;o++)this.pool[o].mesh.visible=!1;this.stats.batches=t.length,this.stats.quads=r}segment(e){let t=[],i=0,r=null,o=()=>{r&&(r.members.length>=2?t.push(r):i+=r.members.length,r=null)};for(let s of e){let a=this.keyFor(s);if(!a){o(),i++;continue}if(r&&r.key===a){r.members.push(s.mesh);continue}o();let l=s.mesh.material;r={members:[s.mesh],key:a,source:l.map,clippingPlanes:l.clippingPlanes?.length?l.clippingPlanes:null,overlay:s.overlay,order:s.order}}return o(),this.stats.passthrough=i,t}keyFor(e){if(!e.visible)return null;let t=e.mesh;if(!t.userData||t.userData[Ne]!==!0)return null;let i=t.material;if(Array.isArray(i)||!(i instanceof B)||i.opacity<=0||i.blending!==lt)return null;let r=i.map?i.map.source.uuid:"nomap";return`${e.overlay?"o":"m"}:${r}${Gx(i.clippingPlanes)}`}materialFor(e){let t=this.materials.get(e.key);return t||(t=new B({transparent:!0,depthTest:!1,vertexColors:!0,side:xe,color:16777215,map:e.source?this.batchMapFor(e.source):null}),e.clippingPlanes&&(t.clippingPlanes=e.clippingPlanes,t.clipIntersection=!1),this.materials.set(e.key,t)),t}batchMapFor(e){let t=e.source.uuid,i=this.batchMaps.get(t);return i||(i=e.clone(),i.offset.set(0,0),i.repeat.set(1,1),i.needsUpdate=!0,this.batchMaps.set(t,i)),i}dispose(){for(let e of this.suppressed)e.visible=!0;this.suppressed.clear();for(let e of this.pool)e.dispose();this.pool.length=0;for(let e of this.materials.values())e.dispose();this.materials.clear();for(let e of this.batchMaps.values())e.dispose();this.batchMaps.clear(),this.group.removeFromParent()}};var bf="__PIX3_ACTIVE_LOCALIZATION__";function Ts(n){globalThis[bf]=n??void 0}function Ke(){return globalThis[bf]??null}function on(n,e,t){if(!n)return e;let i=Ke();return i?i.tr(n,t):e}function Xe(n){return{width:n.naturalWidth??n.width,height:n.naturalHeight??n.height}}var Fe=class n extends C{texture;textureKey;width;height;textureAspectRatio;aspectRatioLocked;originalWidth;originalHeight;anchor;textureRegion=null;mesh;material;baseTexture=null;ownedTexture=null;effectStack;constructor(e){super(e,"Sprite2D"),this.texture=D(e.texture??e.texturePath??null),this.textureKey=e.textureKey??"",this.width=e.width,this.height=e.height,this.textureAspectRatio=e.textureAspectRatio??null,this.aspectRatioLocked=e.aspectRatioLocked??!1,this.originalWidth=null,this.originalHeight=null,this.anchor=n.normalizeAnchor(e.anchor),this.isContainer=!1,this.material=new B({color:e.color??"#ffffff",transparent:!0,depthTest:!1}),this.registerOpacityMaterial(this.material,1),this.mesh=new O(De,this.material),this.mesh.name=`${this.name}-Mesh`,this.mesh.scale.set(this.width??64,this.height??64,1),this.mesh.userData[Ne]=!0,this.applyAnchorOffset(),this.add(this.mesh),this.effectStack=new _e({nodeType:"Sprite2D",target:"basic",onAttachmentsChanged:()=>{this.mesh.userData[Ne]=this.effectStack.isEmpty}}),this.effectStack.install(this.material);let t=e.effects??this.properties.effects;for(let i of t??[])i&&typeof i.type=="string"&&this.effectStack.attach(i.type,{enabled:i.enabled,params:i.params});H(this,n.getPropertySchema)}getShaderEffectStack(){return this.effectStack}getInstancePropertySchema(){return this.effectStack.buildInstanceSchema()}attachEffect(e,t){return this.effectStack.attach(e,t)}detachEffect(e){return this.effectStack.detach(e)}setEffectEnabled(e,t){this.effectStack.setEnabled(e,t)}setEffectParam(e,t,i){return this.effectStack.setParam(e,t,i)}getAttachedEffects(){return this.effectStack.getAttached()}tick(e){this.effectStack.tick(e),super.tick(e)}static normalizeAnchor(e){if(!e)return{x:.5,y:.5};if(Array.isArray(e)){let r=Number(e[0]),o=Number(e[1]);return{x:Number.isFinite(r)?r:.5,y:Number.isFinite(o)?o:.5}}let t=Number(e.x),i=Number(e.y);return{x:Number.isFinite(t)?t:.5,y:Number.isFinite(i)?i:.5}}applyAnchorOffset(){let e=this.width??64,t=this.height??64;this.mesh.position.set((.5-this.anchor.x)*e,(.5-this.anchor.y)*t,0)}setAnchor(e){this.anchor=n.normalizeAnchor(e),this.applyAnchorOffset()}setTextureRegion(e){this.textureRegion=gc(e),this.applyTexturePresentation()}applyTexturePresentation(){let e=this.textureRegion;if(e&&this.baseTexture){this.ownedTexture||(this.ownedTexture=this.baseTexture.clone(),$(this.ownedTexture));let t=jr($r(this.baseTexture),e);mi(this.ownedTexture,t),this.material.map!==this.ownedTexture&&(this.material.map=this.ownedTexture,this.material.needsUpdate=!0);return}this.material.map!==this.baseTexture&&(this.material.map=this.baseTexture,this.material.needsUpdate=!0),this.ownedTexture&&(this.ownedTexture.dispose(),this.ownedTexture=null)}get texturePath(){return this.texture?.url??null}getEffectiveTexturePath(){if(this.textureKey){let e=Ke()?.trSprite(this.textureKey);if(e)return e}return this.texturePath}set texturePath(e){this.texture=D(e)}setTextureResource(e){this.texture=D(e)}setTexture(e){$(e),this.baseTexture!==e&&this.ownedTexture&&(this.ownedTexture.dispose(),this.ownedTexture=null),this.baseTexture=e,this.material.color.set("#ffffff"),this.applyTexturePresentation();let t=Yr(e);if(t||e.image){let i=Xe(e.image??{}),r=t?.width??i.width,o=t?.height??i.height;r&&o&&(this.textureAspectRatio=r/o,this.originalWidth=r,this.originalHeight=o,(this.width===void 0||this.height===void 0)&&this.updateSize(this.width??r,this.height??o))}}updateSize(e,t){this.width=e,this.height=t,this.mesh.scale.set(e,t,1),this.applyAnchorOffset(),this.refreshOpacity()}resetToOriginalSize(){!this.originalWidth||!this.originalHeight||this.updateSize(this.originalWidth,this.originalHeight)}disposeResources(){this.ownedTexture&&(this.ownedTexture.dispose(),this.ownedTexture=null),this.material.dispose()}static getPropertySchema(){let e=C.getPropertySchema();return{nodeType:"Sprite2D",extends:"Node2D",properties:[...e.properties,{name:"texture",type:"object",ui:{label:"Texture",description:"Path to the sprite texture",group:"Sprite",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.texture??{type:"texture",url:""},setValue:(t,i)=>{t.setTextureResource(i)}},{name:"textureKey",type:"string",ui:{label:"Texture Key",description:'Localization sprite key (locale table "sprites" section). When set and resolvable, the localized texture wins; the authored texture is the fallback',group:"Sprite",editor:"localization-key"},getValue:t=>t.textureKey,setValue:(t,i)=>{t.textureKey=String(i??"")}},{name:"anchor",type:"vector2",ui:{label:"Pivot",description:"Normalized pivot point used to position the sprite image",group:"Sprite",step:.01,precision:2},getValue:t=>{let i=t.anchor;return{x:i.x,y:i.y}},setValue:(t,i)=>{let r=t,o=i;r.setAnchor({x:o.x,y:o.y})}},{name:"width",type:"number",ui:{label:"Width",description:"Sprite width in pixels",group:"Size",editor:"sprite-size",step:1,precision:0,min:1,unit:"px"},getValue:t=>t.width??64,setValue:(t,i)=>{let r=t;r.updateSize(Number(i),r.height??64)}},{name:"height",type:"number",ui:{label:"Height",description:"Sprite height in pixels",group:"Size",editor:"sprite-size",step:1,precision:0,min:1,unit:"px"},getValue:t=>t.height??64,setValue:(t,i)=>{let r=t;r.updateSize(r.width??64,Number(i))}},{name:"aspectRatioLocked",type:"boolean",ui:{label:"Aspect Ratio Locked",description:"Maintain aspect ratio when resizing",group:"Size",hidden:!0},getValue:t=>t.aspectRatioLocked??!1,setValue:(t,i)=>{t.aspectRatioLocked=!!i}}],groups:{...e.groups,Sprite:{label:"Sprite",description:"Sprite-specific properties",expanded:!0},Size:{label:"Size",description:"Sprite dimensions in pixels",expanded:!0}}}}};function sn(n){let e=n.trim();if(e.length===0)return[];try{let t=JSON.parse(e);return Array.isArray(t)?t:[t]}catch{return[e]}}function uu(n){let e=Number.isFinite(n.nodeWidth)?n.nodeWidth:0,t=Number.isFinite(n.nodeHeight)?n.nodeHeight:0,i=e,r=t;if(n.sizeMode==="native"){let a=n.frameSourceSize,l=n.clipFirstFrameSourceSize??a;if(a&&a.width>0&&a.height>0&&l&&l.width>0){let c=e/l.width;i=a.width*c,r=a.height*c}}let o=n.frame?.anchor.x??.5,s=n.frame?.anchor.y??.5;return{width:i,height:r,offsetX:(.5-n.anchor.x)*e+(.5-o)*i,offsetY:(.5-n.anchor.y)*t+(s-.5)*r}}function hu(n,e){return{x:e.offsetX+(n.x-.5)*e.width,y:e.offsetY+(.5-n.y)*e.height,angle:n.angle??0}}function du(n,e,t){let i=t?.width??0,r=t?.height??0;return i<=0||r<=0||n.length===0?[]:n.map(o=>({x:e.offsetX+(o.x/i-.5)*e.width,y:e.offsetY+(.5-o.y/r)*e.height}))}var dr=class{timeAccumulator=0;direction=1;finished=!1;finishedAtIndex=null;advance(e,t,i){let r=[];if(this.finished){if(i===this.finishedAtIndex)return{nextIndex:i,framesAdvanced:r,finished:!1};this.finished=!1,this.finishedAtIndex=null,this.timeAccumulator=0,this.direction=1}let{frameCount:o,fps:s,loop:a}=t,l=t.playbackMode??"linear",c=t.frameDurationMultiplier??(()=>1),u=i,h=!1;for(this.timeAccumulator+=e;;){let d=Math.max(.001,1/s*c(u));if(this.timeAccumulator<d)break;this.timeAccumulator-=d;let p=u,f=this.computeNextIndex(u,o,a,l);if(u=f.nextIndex,u!==p&&r.push(u),f.finished){h=!0,this.finished=!0,this.finishedAtIndex=u,this.timeAccumulator=0;break}}return{nextIndex:u,framesAdvanced:r,finished:h}}reset(){this.timeAccumulator=0,this.direction=1,this.finished=!1,this.finishedAtIndex=null}computeNextIndex(e,t,i,r){if(r==="ping-pong"&&t>1){let s=e+this.direction;if(s>=t){if(!i)return{nextIndex:t-1,finished:!0};this.direction=-1,s=Math.max(0,t-2)}else if(s<0){if(!i)return{nextIndex:0,finished:!0};this.direction=1,s=Math.min(t-1,1)}return{nextIndex:s,finished:!1}}let o=e+1;return o<t?{nextIndex:o,finished:!1}:i?{nextIndex:0,finished:!1}:{nextIndex:t-1,finished:!0}}};var jx=new S,Sf=new se,vf=new Ji,ye=class n extends C{animationResourcePath;currentClip;isPlaying;freeOnFinish;width;height;color;anchor;sizeMode;_currentFrame;fallbackFor=null;frameSequencePlayer=new dr;animationResource=null;activeClip=null;spritesheetTexture=null;frameTextures=new Map;mesh;material;effectStack;constructor(e){super(e,"AnimatedSprite2D"),this.animationResourcePath=typeof e.animationResourcePath=="string"&&e.animationResourcePath.trim().length>0?e.animationResourcePath.trim():null,this.currentClip=typeof e.currentClip=="string"?e.currentClip.trim():"",this.isPlaying=e.isPlaying??!0,this.freeOnFinish=e.freeOnFinish??!1,this.width=e.width??64,this.height=e.height??64,this.color=e.color??"#ffffff",this.anchor=n.normalizeAnchor(e.anchor),this.sizeMode=e.sizeMode==="native"?"native":"stretch",this._currentFrame=Math.max(0,Math.floor(e.currentFrame??0)),this.isContainer=!1,this.animationResourcePath&&(this.properties.animationResourcePath=this.animationResourcePath),this.currentClip&&(this.properties.currentClip=this.currentClip),this.properties.isPlaying=this.isPlaying,this.freeOnFinish&&(this.properties.freeOnFinish=!0),this.properties.currentFrame=this._currentFrame,this.material=new B({color:this.color,transparent:!0,depthTest:!1}),this.registerOpacityMaterial(this.material,1),this.mesh=new O(De,this.material),this.mesh.name=`${this.name}-Mesh`,this.mesh.userData[Ne]=!0,this.updateSize(),this.add(this.mesh),this.effectStack=new _e({nodeType:"AnimatedSprite2D",target:"basic",onAttachmentsChanged:()=>{this.mesh.userData[Ne]=this.effectStack.isEmpty}}),this.effectStack.install(this.material);let t=e.effects??this.properties.effects;for(let i of t??[])i&&typeof i.type=="string"&&this.effectStack.attach(i.type,{enabled:i.enabled,params:i.params});H(this,n.getPropertySchema)}getShaderEffectStack(){return this.effectStack}getInstancePropertySchema(){return this.effectStack.buildInstanceSchema()}attachEffect(e,t){return this.effectStack.attach(e,t)}detachEffect(e){return this.effectStack.detach(e)}setEffectEnabled(e,t){this.effectStack.setEnabled(e,t)}setEffectParam(e,t,i){return this.effectStack.setParam(e,t,i)}getAttachedEffects(){return this.effectStack.getAttached()}get currentFrame(){return this._currentFrame}set currentFrame(e){let t=Math.max(0,Math.floor(e)),i=this.activeClip?.frames.length??0;this._currentFrame=i>0?Math.min(t,i-1):t,this.properties.currentFrame=this._currentFrame,this.refreshTexturePresentation()}get savedClipName(){return this.fallbackFor??this.currentClip}setAnimationResource(e){this.animationResource=e;let t=this.savedClipName;e&&t&&!e.clips.some(i=>i.name===t)&&console.warn(`[AnimatedSprite2D] Unknown clip "${t}" on node ${this.nodeId} (available: ${e.clips.map(i=>i.name).join(", ")||"none"}); using the first clip.`),this.syncActiveClip(!1)}setFrameTexture(e,t){let i=typeof e=="number"?pi(this.animationResource,this.activeClip?.frames[Math.max(0,Math.floor(e))]??null):e.trim();if(i.length===0)return;let r=this.frameTextures.get(i);r&&(r.dispose(),this.frameTextures.delete(i)),t&&this.frameTextures.set(i,this.cloneTexture(t)),this.currentFrameTexturePath()===i&&this.refreshTexturePresentation()}hasFrameTexture(e){return this.frameTextures.has(e.trim())}play(e,t={}){let i=(e??this.currentClip).trim();if(i.length===0||this.animationResource&&!this.animationResource.clips.some(o=>o.name===i))return!1;let r=this.activeClip!==null&&this.activeClip.name===i;return r||(this.currentClip=i,this.properties.currentClip=i,this.syncActiveClip(!0)),(t.restart||!r)&&(this._currentFrame=0,this.properties.currentFrame=0,this.frameSequencePlayer.reset(),this.refreshTexturePresentation()),this.isPlaying=!0,this.properties.isPlaying=!0,!0}getClipNames(){return this.animationResource?.clips.map(e=>e.name)??[]}setSpritesheetTexture(e){this.spritesheetTexture&&(this.spritesheetTexture.dispose(),this.spritesheetTexture=null),e&&(this.spritesheetTexture=this.cloneTexture(e)),this.refreshTexturePresentation()}tick(e){super.tick(e),this.effectStack.tick(e);let t=this.activeClip;if(!this.isPlaying||!t||t.frames.length<=1||t.fps<=0)return;let i=this.frameSequencePlayer.advance(e,{frameCount:t.frames.length,fps:t.fps,loop:t.loop,playbackMode:t.playbackMode==="ping-pong"?"ping-pong":"linear",frameDurationMultiplier:r=>t.frames[r]?.durationMultiplier??1},this._currentFrame);for(let r of i.framesAdvanced)this.currentFrame=r,this.emitFrameEvents(r);i.finished&&(this.isPlaying=!1,this.properties.isPlaying=!1,this.emit("animation-finished",t.name),this.freeOnFinish&&this.queueFree())}emitFrameEvents(e){let t=this.activeClip?.frames[e];if(!(!t||!t.events||t.events.length===0))for(let i of t.events)i.signal.length!==0&&this.emit(i.signal,...sn(i.args))}static getPropertySchema(){let e=C.getPropertySchema();return{...e,nodeType:"AnimatedSprite2D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Size",min:0,step:1},getValue:t=>t.width,setValue:(t,i)=>{let r=t;r.width=Number(i),r.updateSize()}},{name:"height",type:"number",ui:{label:"Height",group:"Size",min:0,step:1},getValue:t=>t.height,setValue:(t,i)=>{let r=t;r.height=Number(i),r.updateSize()}},{name:"sizeMode",type:"enum",ui:{label:"Size Mode",description:"Stretch: every frame fills Width\xD7Height. Native: each frame renders at its own pixel size, scaled uniformly from the clip\u2019s first frame.",group:"Size",options:{Stretch:"stretch",Native:"native"}},getValue:t=>t.sizeMode,setValue:(t,i)=>{let r=t;r.sizeMode=i==="native"?"native":"stretch",r.properties.sizeMode=r.sizeMode,r.updateSize()}},{name:"anchor",type:"vector2",ui:{label:"Pivot",description:"Normalized node pivot. Composes on top of each frame\u2019s own anchor, which is edited in the Sprite Editor.",group:"Size",step:.01,precision:2},getValue:t=>{let i=t.anchor;return{x:i.x,y:i.y}},setValue:(t,i)=>{let r=t,o=i;r.setAnchor({x:o.x,y:o.y}),r.properties.anchor={x:r.anchor.x,y:r.anchor.y}}},{name:"color",type:"color",ui:{label:"Color",group:"Style"},getValue:t=>t.color,setValue:(t,i)=>{let r=t;r.color=String(i),r.refreshTexturePresentation()}},{name:"animationResourcePath",type:"string",ui:{label:"Animation Asset",group:"Animation",editor:"animation-resource"},getValue:t=>t.animationResourcePath??"",setValue:(t,i)=>{let r=t,o=String(i??"").trim();r.animationResourcePath=o||null,r.animationResourcePath?r.properties.animationResourcePath=r.animationResourcePath:delete r.properties.animationResourcePath}},{name:"currentClip",type:"string",ui:{label:"Clip",group:"Animation"},getValue:t=>t.currentClip,setValue:(t,i)=>{let r=t;r.fallbackFor=null,r.currentClip=String(i??"").trim(),r.currentClip?r.properties.currentClip=r.currentClip:delete r.properties.currentClip,r.syncActiveClip(!0)}},{name:"isPlaying",type:"boolean",ui:{label:"Playing",group:"Animation"},getValue:t=>t.isPlaying,setValue:(t,i)=>{let r=t;r.isPlaying=!!i,r.properties.isPlaying=r.isPlaying}},{name:"currentFrame",type:"number",ui:{label:"Current Frame",group:"Animation",min:0,step:1},getValue:t=>t.currentFrame,setValue:(t,i)=>{t.currentFrame=Number(i)}},{name:"freeOnFinish",type:"boolean",ui:{label:"Free on Finish",description:"Destroy this node when a non-looping clip finishes (one-shot VFX)",group:"Animation"},getValue:t=>t.freeOnFinish,setValue:(t,i)=>{let r=t;r.freeOnFinish=!!i,r.freeOnFinish?r.properties.freeOnFinish=!0:delete r.properties.freeOnFinish}}],groups:{...e.groups,Size:{label:"Size",expanded:!0},Style:{label:"Style",expanded:!0},Animation:{label:"Animation",expanded:!0}}}}getCurrentFrameData(){let e=this.activeClip?.frames??[];return e.length===0?null:e[this._currentFrame]??null}currentFrameTexturePath(){return pi(this.animationResource,this.getCurrentFrameData())}refreshTexturePresentation(){this.updateSize();let e=this.getCurrentFrameData(),t=this.currentFrameTexturePath(),i=e&&t?this.frameTextures.get(t)??null:null,r=cc(e)&&!!i,o=r?i:this.spritesheetTexture;if(o){this.material.map!==o&&(this.material.map=o,this.material.needsUpdate=!0);let s=$r(o),a=null;!r&&e&&(a={x:e.offset.x,y:e.offset.y,width:e.repeat.x,height:e.repeat.y}),mi(o,jr(s,a)),this.material.color.set("#ffffff")}else this.material.map&&(this.material.map=null,this.material.needsUpdate=!0),this.material.color.set(this.color)}syncActiveClip(e){let t=this.activeClip?.name??null,i=this.savedClipName;this.activeClip=pc(this.animationResource,i);let r=this.activeClip?.name??i;this.fallbackFor=r===i?null:i,r!==this.currentClip&&Rt(this,"currentClip",r),i?this.properties.currentClip=i:delete this.properties.currentClip,e&&t!==this.activeClip?.name&&(this._currentFrame=0,this.properties.currentFrame=this._currentFrame,this.frameSequencePlayer.reset());let o=this.activeClip?.frames.length??0;o>0?(this._currentFrame=Math.max(0,Math.min(this._currentFrame,o-1)),this.properties.currentFrame=this._currentFrame):(this._currentFrame=Math.max(0,this._currentFrame),this.properties.currentFrame=this._currentFrame,this.frameSequencePlayer.reset()),this.refreshTexturePresentation()}cloneTexture(e){let t=e.clone();return $(t),bc(e,t),t}static normalizeAnchor(e){if(!e)return{x:.5,y:.5};let[t,i]=Array.isArray(e)?e:[e.x,e.y],r=Number(t),o=Number(i);return{x:Number.isFinite(r)?r:.5,y:Number.isFinite(o)?o:.5}}setAnchor(e){this.anchor=n.normalizeAnchor(e),this.updateSize()}resolveFrameSourceSize(e){let t=e?.sourceSize;if(t&&t.width>0&&t.height>0)return t;let i=pi(this.animationResource,e),r=(i?this.frameTextures.get(i):void 0)??this.spritesheetTexture,o=Yr(r);if(o&&o.width>0&&o.height>0)return o;let s=r?.image;return s&&Number(s.width)>0&&Number(s.height)>0?{width:Number(s.width),height:Number(s.height)}:null}resolveFrameLayout(e){return uu({nodeWidth:this.width,nodeHeight:this.height,anchor:this.anchor,sizeMode:this.sizeMode,frame:e,frameSourceSize:this.resolveFrameSourceSize(e),clipFirstFrameSourceSize:this.resolveFrameSourceSize(this.activeClip?.frames[0]??null)})}updateSize(){let e=this.getCurrentFrameData(),t=this.resolveFrameLayout(e);this.mesh.scale.set(t.width,t.height,1),this.mesh.position.set(t.offsetX,t.offsetY,0)}getFramePoint(e,t=this._currentFrame){let i=this.activeClip?.frames??[];if(i.length===0)return null;let r=Math.max(0,Math.min(Math.floor(t),i.length-1)),o=i[r]??null,s=uc(o,e);return s?hu(s,this.resolveFrameLayout(o)):null}getFramePointWorld(e,t=this._currentFrame){let i=this.getFramePoint(e,t);if(!i)return null;this.updateWorldMatrix(!0,!1);let r=jx.set(i.x,i.y,0).applyMatrix4(this.matrixWorld);return Sf.extractRotation(this.matrixWorld),vf.setFromRotationMatrix(Sf),{x:r.x,y:r.y,z:r.z,angle:i.angle+R.radToDeg(vf.z)}}getClipPointNames(){return hc(this.activeClip)}getFrameCollisionPolygon(e=this._currentFrame){let t=this.activeClip?.frames??[];if(t.length===0)return[];let i=Math.max(0,Math.min(Math.floor(e),t.length-1)),r=t[i]??null;return!r||!r.collisionPolygon||r.collisionPolygon.length<3?[]:du(r.collisionPolygon,this.resolveFrameLayout(r),this.resolveFrameSourceSize(r))}disposeResources(){this.spritesheetTexture&&(this.spritesheetTexture.dispose(),this.spritesheetTexture=null);for(let e of this.frameTextures.values())e.dispose();this.frameTextures.clear(),this.material.dispose()}};var an=class{constructor(e){this.options=e;this.asset=e.asset,this.object=new this.asset.spine.SkeletonMesh({skeletonData:this.asset.skeletonData,twoColorTint:e.twoColorTint??!1,materialFactory:Yx()}),this.object.name="SpineSkeletonMesh",this.object.zOffset=0,this.object.state.addListener({start:t=>{this.options.onStarted?.(wf(t),t.trackIndex)},complete:t=>{let i=wf(t);t.loop?this.options.onLooped?.(i,t.trackIndex):this.options.onFinished?.(i,t.trackIndex)},event:(t,i)=>{this.options.onEvent?.(i.data.name,{int:i.intValue,float:i.floatValue,string:i.stringValue},t.trackIndex)}}),this.object.update(0)}options;object;asset;disposed=!1;color={r:1,g:1,b:1};opacity=1;get skeletonAsset(){return this.asset}getAnimationNames(){return this.asset.skeletonData.animations.map(e=>e.name)}getSkinNames(){return this.asset.skeletonData.skins.map(e=>e.name)}getSetupBounds(){let e=this.asset.skeletonData;return{x:e.x,y:e.y,width:e.width,height:e.height}}getCurrentAnimation(e=0){return(this.object.state.tracks[e]??null)?.animation?.name??null}rewind(e=0){let t=this.object.state.tracks[e]??null,i=t?.animation?.name??null;if(!i){this.object.skeleton.setupPose(),this.object.update(0);return}let r=this.object.state.setAnimation(e,i,t?.loop??!1);r.mixDuration=0,this.object.update(0)}setDefaultMix(e){this.object.state.data.defaultMix=Math.max(0,e)}setMix(e,t,i){this.object.state.data.setMix(e,t,Math.max(0,i))}setTimeScale(e){this.object.state.timeScale=Number.isFinite(e)?e:1}play(e,t={}){let i=e.trim();if(!i||!this.asset.skeletonData.findAnimation(i))return!1;let r=this.object.state.setAnimation(t.trackIndex??0,i,t.loop??!1);return t.mixDuration!==void 0&&(r.mixDuration=Math.max(0,t.mixDuration)),!0}queue(e,t={}){let i=e.trim();if(!i||!this.asset.skeletonData.findAnimation(i))return!1;let r=this.object.state.addAnimation(t.trackIndex??0,i,t.loop??!1,t.delay??0);return t.mixDuration!==void 0&&(r.mixDuration=Math.max(0,t.mixDuration)),!0}stop(e={}){let{trackIndex:t,mixDuration:i}=e;if(i!==void 0&&i>0){this.object.state.setEmptyAnimation(t??0,i);return}t===void 0?this.object.state.clearTracks():this.object.state.clearTrack(t),this.object.skeleton.setupPose(),this.object.update(0)}setSkin(e){let t=e.trim();return t?this.asset.skeletonData.findSkin(t)?(this.object.skeleton.setSkin(t),this.object.skeleton.setupPoseSlots(),!0):!1:(this.object.skeleton.skin=null,this.object.skeleton.setupPoseSlots(),!0)}setTint(e,t){this.color=e,this.opacity=$x(t);let i=this.object.skeleton.color;i.r=e.r,i.g=e.g,i.b=e.b,i.a=this.opacity}setOpacity(e){this.setTint(this.color,e)}update(e){this.disposed||this.object.update(Math.max(0,e))}refresh(){this.update(0)}dispose(){this.disposed||(this.disposed=!0,this.object.removeFromParent(),this.object.dispose())}};function $x(n){return Number.isFinite(n)?Math.min(1,Math.max(0,n)):1}function wf(n){return n.animation?.name??""}function Yx(){return n=>new B({...n,depthTest:!1,depthWrite:!1,transparent:!0})}var gi=class n extends C{skeletonPath;atlasPath;texture;animation;loop;isPlaying;skin;timeScale;defaultMix;color;twoColorTint;freeOnFinish;previewInEditor;asset=null;view=null;tintColor=new L("#ffffff");appliedOpacity=-1;appliedTintHex="";constructor(e){super(e,"SpineSkeleton2D"),this.skeletonPath=Cs(e.skeletonPath),this.atlasPath=Cs(e.atlasPath),this.texture=D(e.texture??null),this.animation=typeof e.animation=="string"?e.animation.trim():"",this.loop=e.loop??!0,this.isPlaying=e.isPlaying??!0,this.skin=typeof e.skin=="string"?e.skin.trim():"",this.timeScale=e.timeScale??1,this.defaultMix=Math.max(0,e.defaultMix??0),this.color=e.color??"#ffffff",this.twoColorTint=e.twoColorTint??!1,this.freeOnFinish=e.freeOnFinish??!1,this.previewInEditor=e.previewInEditor??!1,this.isContainer=!1,this.tintColor.set(this.color),this.syncSerializedProperties(),H(this,n.getPropertySchema)}getAssetRequest(){return!this.skeletonPath||!this.atlasPath?null:{skeletonPath:this.skeletonPath,atlasPath:this.atlasPath,texturePath:this.texture?.url??null}}get texturePath(){return this.texture?.url??null}set texturePath(e){this.texture=D(e)}get isLoaded(){return this.view!==null}setSpineAsset(e){this.view&&(this.remove(this.view.object),this.view.dispose(),this.view=null),this.asset=e,this.appliedOpacity=-1,this.appliedTintHex="",e&&(this.view=new an({asset:e,twoColorTint:this.twoColorTint,onStarted:(t,i)=>this.emit("animation-started",t,i),onLooped:(t,i)=>this.emit("animation-looped",t,i),onFinished:(t,i)=>{this.isPlaying=!1,this.properties.isPlaying=!1,this.emit("animation-finished",t,i),this.freeOnFinish&&this.queueFree()},onEvent:(t,i,r)=>this.emit("spine-event",t,i,r)}),this.view.setDefaultMix(this.defaultMix),this.view.setTimeScale(this.timeScale),this.skin&&this.view.setSkin(this.skin),this.applyTint(!0),this.applyAuthoredAnimation(),this.add(this.view.object))}getView(){return this.view}getAnimationNames(){return this.view?.getAnimationNames()??[]}getSkinNames(){return this.view?.getSkinNames()??[]}getSetupBounds(){return this.view?.getSetupBounds()??null}getCurrentAnimation(e=0){return this.view?.getCurrentAnimation(e)??null}play(e,t={}){let i=(e??this.animation).trim();return!this.view||!i?!1:this.view.play(i,{loop:t.loop??this.loop,...t})?((t.trackIndex??0)===0&&(Rt(this,"animation",i),this.properties.animation=i),Rt(this,"isPlaying",!0),this.properties.isPlaying=!0,!0):(console.warn(`[SpineSkeleton2D] Unknown animation "${i}" on node ${this.nodeId} (available: ${this.getAnimationNames().join(", ")||"none"})`),!1)}queue(e,t={}){return this.view?this.view.queue(e,{loop:t.loop??!1,...t}):!1}stop(e={}){this.isPlaying=!1,this.properties.isPlaying=!1,this.view?.stop(e)}resetToFirstFrame(e=0){this.view?.rewind(e)}pause(){this.isPlaying=!1,this.properties.isPlaying=!1}resume(){this.isPlaying=!0,this.properties.isPlaying=!0}setSkin(e){let t=e.trim();return this.view&&!this.view.setSkin(t)?(console.warn(`[SpineSkeleton2D] Unknown skin "${t}" on node ${this.nodeId} (available: ${this.getSkinNames().join(", ")||"none"})`),!1):(this.skin=t,t?this.properties.skin=t:delete this.properties.skin,this.view?.refresh(),!0)}setMix(e,t,i){this.view?.setMix(e,t,i)}setTimeScale(e){this.timeScale=Number.isFinite(e)?e:1,this.properties.timeScale=this.timeScale,this.view?.setTimeScale(this.timeScale)}tick(e){if(super.tick(e),!this.view)return;let t=this.applyTint(!1);this.isPlaying?this.view.update(e):t&&this.view.refresh()}advancePreview(e){this.applyTint(!1),this.view?.update(e)}static getPropertySchema(){let e=C.getPropertySchema();return{...e,nodeType:"SpineSkeleton2D",properties:[...e.properties,{name:"skeletonPath",type:"string",ui:{label:"Skeleton",description:"Spine skeleton export (.json or .skel)",group:"Spine",editor:"file-resource",extensions:["json","skel"]},getValue:t=>t.skeletonPath??"",setValue:(t,i)=>{let r=t;r.skeletonPath=Cs(i),r.syncSerializedProperties()}},{name:"atlasPath",type:"string",ui:{label:"Atlas",description:"Spine atlas export (.atlas)",group:"Spine",editor:"file-resource",extensions:["atlas"]},getValue:t=>t.atlasPath??"",setValue:(t,i)=>{let r=t;r.atlasPath=Cs(i),r.syncSerializedProperties()}},{name:"texture",type:"object",ui:{label:"Page Texture",description:"Optional override for a single-page atlas. Multi-page atlases always use the page names inside the .atlas file.",group:"Spine",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.texture,setValue:(t,i)=>{let r=t;r.texture=D(i),r.syncSerializedProperties()}},{name:"animation",type:"string",ui:{label:"Animation",group:"Animation"},getValue:t=>t.animation,setValue:(t,i)=>{let r=t,o=String(i??"").trim();r.animation=o,o?r.properties.animation=o:delete r.properties.animation,r.applyAuthoredAnimation()}},{name:"loop",type:"boolean",ui:{label:"Loop",group:"Animation"},getValue:t=>t.loop,setValue:(t,i)=>{let r=t;r.loop=!!i,r.properties.loop=r.loop,r.applyAuthoredAnimation()}},{name:"isPlaying",type:"boolean",ui:{label:"Playing",group:"Animation"},getValue:t=>t.isPlaying,setValue:(t,i)=>{let r=t;r.isPlaying=!!i,r.properties.isPlaying=r.isPlaying}},{name:"skin",type:"string",ui:{label:"Skin",group:"Animation"},getValue:t=>t.skin,setValue:(t,i)=>{t.setSkin(String(i??""))}},{name:"timeScale",type:"number",ui:{label:"Time Scale",group:"Animation",min:0,step:.05},getValue:t=>t.timeScale,setValue:(t,i)=>{t.setTimeScale(Number(i))}},{name:"defaultMix",type:"number",ui:{label:"Default Mix",description:"Crossfade duration between animations, in seconds",group:"Animation",min:0,step:.01,unit:"s"},getValue:t=>t.defaultMix,setValue:(t,i)=>{let r=t;r.defaultMix=Math.max(0,Number(i)||0),r.properties.defaultMix=r.defaultMix,r.view?.setDefaultMix(r.defaultMix)}},{name:"freeOnFinish",type:"boolean",ui:{label:"Free on Finish",description:"Destroy this node when a non-looping animation finishes",group:"Animation"},getValue:t=>t.freeOnFinish,setValue:(t,i)=>{let r=t;r.freeOnFinish=!!i,r.freeOnFinish?r.properties.freeOnFinish=!0:delete r.properties.freeOnFinish}},{name:"previewInEditor",type:"boolean",ui:{label:"Editor Preview",description:"Animate in the editor viewport instead of holding a single pose. Playback is off by default; Reset rewinds to the first frame.",group:"Animation",editor:"spine-preview"},getValue:t=>t.previewInEditor,setValue:(t,i)=>{let r=t;r.previewInEditor=!!i,r.previewInEditor?r.properties.previewInEditor=!0:delete r.properties.previewInEditor}},{name:"color",type:"color",ui:{label:"Tint",group:"Style"},getValue:t=>t.color,setValue:(t,i)=>{let r=t;r.color=String(i??"#ffffff"),r.properties.color=r.color,r.tintColor.set(r.color),r.applyTint(!0),r.view?.refresh()}},{name:"twoColorTint",type:"boolean",ui:{label:"Two Color Tint",description:"Enable spine tint-black rendering (skeletons exported with dark tint)",group:"Style"},getValue:t=>t.twoColorTint,setValue:(t,i)=>{let r=t,o=!!i;o!==r.twoColorTint&&(r.twoColorTint=o,o?r.properties.twoColorTint=!0:delete r.properties.twoColorTint,r.setSpineAsset(r.asset))}}],groups:{...e.groups,Spine:{label:"Spine",expanded:!0},Animation:{label:"Animation",expanded:!0},Style:{label:"Style",expanded:!0}}}}getInstancePropertySchema(){if(!this.view)return null;let e=this.getAnimationNames(),t=this.getSkinNames();if(e.length===0&&t.length===0)return null;let i=[];return e.length>0&&i.push({name:"animation",type:"select",ui:{label:"Animation",group:"Animation",options:["",...e]},getValue:r=>r.animation,setValue:(r,o)=>{let s=r,a=String(o??"").trim();s.animation=a,a?s.properties.animation=a:delete s.properties.animation,s.applyAuthoredAnimation()}}),t.length>0&&i.push({name:"skin",type:"select",ui:{label:"Skin",group:"Animation",options:["",...t]},getValue:r=>r.skin,setValue:(r,o)=>{r.setSkin(String(o??""))}}),{nodeType:"SpineSkeleton2D",properties:i}}disposeResources(){this.view&&(this.view.dispose(),this.view=null),this.asset=null}applyAuthoredAnimation(){if(this.view){if(!this.animation){this.view.stop();return}if(!this.view.play(this.animation,{loop:this.loop})){console.warn(`[SpineSkeleton2D] Unknown animation "${this.animation}" on node ${this.nodeId} (available: ${this.getAnimationNames().join(", ")||"none"})`);return}this.view.refresh()}}applyTint(e){if(!this.view)return!1;let t=this.computedOpacity;return!e&&this.appliedOpacity===t&&this.appliedTintHex===this.color?!1:(this.appliedOpacity=t,this.appliedTintHex=this.color,this.view.setTint({r:this.tintColor.r,g:this.tintColor.g,b:this.tintColor.b},t),!0)}syncSerializedProperties(){this.skeletonPath?this.properties.skeletonPath=this.skeletonPath:delete this.properties.skeletonPath,this.atlasPath?this.properties.atlasPath=this.atlasPath:delete this.properties.atlasPath,this.texture?this.properties.texture={...this.texture}:delete this.properties.texture,this.animation?this.properties.animation=this.animation:delete this.properties.animation,this.skin?this.properties.skin=this.skin:delete this.properties.skin,this.properties.loop=this.loop,this.properties.isPlaying=this.isPlaying,this.properties.timeScale=this.timeScale,this.properties.defaultMix=this.defaultMix,this.properties.color=this.color,this.twoColorTint?this.properties.twoColorTint=!0:delete this.properties.twoColorTint,this.freeOnFinish?this.properties.freeOnFinish=!0:delete this.properties.freeOnFinish,this.previewInEditor?this.properties.previewInEditor=!0:delete this.properties.previewInEditor}};function Cs(n){if(typeof n!="string")return null;let e=n.trim();return e.length>0?e:null}var Qe=class n extends C{width;height;color;blocksPointerInput;pointerLocal=new S;mesh;material;constructor(e){super(e,"ColorRect2D"),this.width=e.width??100,this.height=e.height??100,this.color=e.color??"#ffffff",this.blocksPointerInput=e.blocksPointerInput??e.properties?.blocksPointerInput===!0,this.opacity=e.opacity??1,this.isContainer=!1,this.material=new B({color:this.color,transparent:!0,opacity:1,depthTest:!1}),this.registerOpacityMaterial(this.material,1),this.mesh=new O(De,this.material),this.mesh.name=`${this.name}-Mesh`,this.mesh.scale.set(this.width,this.height,1),this.mesh.userData[Ne]=!0,this.add(this.mesh),H(this,n.getPropertySchema)}blocksPointerAt(e,t){if(!this.blocksPointerInput||!this.isVisibleInTree())return!1;let i=this.screenPointToWorld(e,t,this.tmpPointerWorld);return i?(this.updateWorldMatrix(!0,!1),this.worldToLocal(this.pointerLocal.set(i.x,i.y,0)),Math.abs(this.pointerLocal.x)<=this.width/2&&Math.abs(this.pointerLocal.y)<=this.height/2):!1}static getPropertySchema(){let e=C.getPropertySchema();return{...e,nodeType:"ColorRect2D",properties:[...e.properties,{name:"blocksPointerInput",type:"boolean",defaultValue:!1,ui:{label:"Block Pointer Input",group:"Input",description:"Prevent hover and presses on controls behind this visible rectangle"},getValue:t=>t.blocksPointerInput,setValue:(t,i)=>{t.blocksPointerInput=!!i}},{name:"width",type:"number",ui:{label:"Width",group:"Size",min:0,step:1},getValue:t=>t.width,setValue:(t,i)=>{let r=t;r.width=Number(i),r.updateSize()}},{name:"height",type:"number",ui:{label:"Height",group:"Size",min:0,step:1},getValue:t=>t.height,setValue:(t,i)=>{let r=t;r.height=Number(i),r.updateSize()}},{name:"color",type:"color",ui:{label:"Color",group:"Style"},getValue:t=>t.color,setValue:(t,i)=>{let r=t;r.color=String(i),r.material.color.set(r.color)}}],groups:{...e.groups,Input:{label:"Input",expanded:!1},Size:{label:"Size",expanded:!0},Style:{label:"Style",expanded:!0}}}}updateSize(){this.mesh.scale.set(this.width,this.height,1)}disposeResources(){this.material.dispose()}};var Je=1e-4,xf=4096;function Ds(n,e,t,i,r,o){let s=e-n;if(s<=Je)return[];let a=[{start:n,end:e,uv0:t,uv1:i}];if(!Number.isFinite(r)||r<=Je||s/r>xf)return a;let l=i-t,c=o-Math.floor(o);Number.isFinite(c)||(c=0);let u=[],h=n,d=t+c*l,p=(1-c)*r;p<=Je&&(p=r,d=t);let f=0;for(;h<e-Je&&f<=xf+2;){f+=1;let m=Math.min(p,e-h),g=m/r;u.push({start:h,end:h+m,uv0:d,uv1:d+g*l}),h+=m,d=t,p=r}return u}function Es(n,e,t,i){return e-n<=Je?[]:[{start:n,end:e,uv0:t,uv1:i}]}function pu(n,e,t){for(let i of t)if(!(i.end-i.start<=Je))for(let r of e)r.end-r.start<=Je||n.push({x0:r.start,y0:i.start,x1:r.end,y1:i.end,u0:r.uv0,v0:i.uv0,u1:r.uv1,v1:i.uv1})}function Ms(n,e,t){let i=Math.max(0,Number.isFinite(n)?n:0),r=Math.max(0,Number.isFinite(e)?e:0),o=i+r;if(o>t&&o>Je){let s=t/o;return{a:i*s,b:r*s}}return{a:i,b:r}}function pr(n){let e=Math.max(0,Number.isFinite(n.width)?n.width:0),t=Math.max(0,Number.isFinite(n.height)?n.height:0),i=e/2,r=t/2,o=n.textureWidth>0?n.textureWidth:e>0?e:1,s=n.textureHeight>0?n.textureHeight:t>0?t:1,a=[];if(n.mode==="stretch")pu(a,Es(-i,i,0,1),Es(-r,r,0,1));else if(n.mode==="tile"){let l=Number.isFinite(n.tileScale.x)&&n.tileScale.x>0?n.tileScale.x:1,c=Number.isFinite(n.tileScale.y)&&n.tileScale.y>0?n.tileScale.y:1,u=Math.max(Je,o*l),h=Math.max(Je,s*c),d=Ds(-i,i,0,1,u,n.tileOffset.x||0),p=Ds(-r,r,0,1,h,n.tileOffset.y||0);pu(a,d,p)}else Kx(a,n,{width:e,height:t,halfW:i,halfH:r,srcW:o,srcH:s});return Xx(a)}function Kx(n,e,t){let{width:i,height:r,halfW:o,halfH:s,srcW:a,srcH:l}=t,c=Math.max(0,e.border.left),u=Math.max(0,e.border.right),h=Math.max(0,e.border.top),d=Math.max(0,e.border.bottom);e.mode==="three-slice-h"?(h=0,d=0):e.mode==="three-slice-v"&&(c=0,u=0);let p=Ms(c,u,a),f=Ms(d,h,l),m=p.a/a,g=1-p.b/a,y=f.a/l,b=1-f.b/l,v=Ms(c,u,i),w=Ms(d,h,r),k=[-o,-o+v.a,o-v.b,o],T=[-s,-s+w.a,s-w.b,s],E=[0,m,g,1],A=[0,y,b,1],_=a*(g-m),J=l*(b-y),re=e.axisStretchHorizontal==="tile",ee=e.axisStretchVertical==="tile";for(let Oe=0;Oe<3;Oe+=1)for(let Et=0;Et<3;Et+=1){if(Et===1&&Oe===1&&!e.drawCenter)continue;let Mw=Et===1&&re?Ds(k[1],k[2],E[1],E[2],_,0):Es(k[Et],k[Et+1],E[Et],E[Et+1]),Dw=Oe===1&&ee?Ds(T[1],T[2],A[1],A[2],J,0):Es(T[Oe],T[Oe+1],A[Oe],A[Oe+1]);pu(n,Mw,Dw)}}function Xx(n){let e=new Float32Array(n.length*18),t=new Float32Array(n.length*12),i=new Float32Array(n.length*18),r=0,o=0;for(let a of n){let l=[a.x0,a.y0,a.u0,a.v0,a.x1,a.y0,a.u1,a.v0,a.x1,a.y1,a.u1,a.v1,a.x0,a.y0,a.u0,a.v0,a.x1,a.y1,a.u1,a.v1,a.x0,a.y1,a.u0,a.v1];for(let c=0;c<6;c+=1){let u=c*4;e[r]=l[u],e[r+1]=l[u+1],e[r+2]=0,i[r]=0,i[r+1]=0,i[r+2]=1,r+=3,t[o]=l[u+2],t[o+1]=l[u+3],o+=2}}let s=new ae;return s.setAttribute("position",new Q(e,3)),s.setAttribute("uv",new Q(t,2)),s.setAttribute("normal",new Q(i,3)),s.computeBoundingBox(),s.computeBoundingSphere(),s}var Pf=Object.freeze({left:0,right:0,top:0,bottom:0});function Ie(n){let e=t=>{let i=Number(t);return Number.isFinite(i)&&i>0?i:0};return{left:e(n?.left),right:e(n?.right),top:e(n?.top),bottom:e(n?.bottom)}}function mr(n){return n?!(n.left>0||n.right>0||n.top>0||n.bottom>0):!0}function yi(n){let e=Math.max(0,Number.isFinite(n.width)?n.width:0),t=Math.max(0,Number.isFinite(n.height)?n.height:0),i=n.border??Pf;return mr(i)?new z(e,t):pr({mode:"nine-slice",width:e,height:t,textureWidth:n.textureWidth??0,textureHeight:n.textureHeight??0,border:i,drawCenter:!0,axisStretchHorizontal:"stretch",axisStretchVertical:"stretch",tileScale:{x:1,y:1},tileOffset:{x:0,y:0}})}var Qx=["stretch","tile","nine-slice","three-slice-h","three-slice-v"],Jx=["stretch","tile"],Zx=128,bi=class n extends C{texture;width;height;patchMode;sliceBorder;drawCenter;axisStretchHorizontal;axisStretchVertical;tileScale;tileOffset;anchor;textureWidth;textureHeight;mesh;geometry;material;constructor(e){super(e,"TiledSprite2D"),this.texture=D(e.texture??e.texturePath??null),this.width=n.toSize(e.width),this.height=n.toSize(e.height),this.patchMode=n.normalizePatchMode(e.patchMode),this.sliceBorder=n.normalizeBorder(e.sliceBorder),this.drawCenter=e.drawCenter??!0,this.axisStretchHorizontal=n.normalizeAxis(e.axisStretchHorizontal),this.axisStretchVertical=n.normalizeAxis(e.axisStretchVertical),this.tileScale=n.toVector2(e.tileScale,1,1),this.tileOffset=n.toVector2(e.tileOffset,0,0),this.anchor=n.normalizeAnchor(e.anchor),this.textureWidth=0,this.textureHeight=0,this.isContainer=!1,this.geometry=pr(this.buildGeometryParams()),this.material=new B({color:e.color??"#ffffff",transparent:!0,depthTest:!1}),this.registerOpacityMaterial(this.material,1),this.mesh=new O(this.geometry,this.material),this.mesh.name=`${this.name}-Mesh`,this.applyAnchorOffset(),this.add(this.mesh),H(this,n.getPropertySchema)}buildGeometryParams(){return{mode:this.patchMode,width:this.width,height:this.height,textureWidth:this.textureWidth,textureHeight:this.textureHeight,border:this.sliceBorder,drawCenter:this.drawCenter,axisStretchHorizontal:this.axisStretchHorizontal,axisStretchVertical:this.axisStretchVertical,tileScale:{x:this.tileScale.x,y:this.tileScale.y},tileOffset:{x:this.tileOffset.x,y:this.tileOffset.y}}}rebuildGeometry(){let e=pr(this.buildGeometryParams());this.geometry.dispose(),this.geometry=e,this.mesh.geometry=e,this.applyAnchorOffset(),this.material.needsUpdate=!0,this.refreshOpacity()}applyAnchorOffset(){this.mesh.position.set((.5-this.anchor.x)*this.width,(.5-this.anchor.y)*this.height,0)}updateSize(e,t){this.width=n.toSize(e),this.height=n.toSize(t),this.rebuildGeometry()}setPatchMode(e){this.patchMode=n.normalizePatchMode(e),this.rebuildGeometry()}setSliceBorder(e){this.sliceBorder=n.normalizeBorder({...this.sliceBorder,...e}),this.rebuildGeometry()}setDrawCenter(e){this.drawCenter=!!e,this.rebuildGeometry()}setAxisStretchHorizontal(e){this.axisStretchHorizontal=n.normalizeAxis(e),this.rebuildGeometry()}setAxisStretchVertical(e){this.axisStretchVertical=n.normalizeAxis(e),this.rebuildGeometry()}setTileScale(e,t){this.tileScale.set(Number.isFinite(e)?e:1,Number.isFinite(t)?t:1),this.rebuildGeometry()}setTileOffset(e,t){this.tileOffset.set(Number.isFinite(e)?e:0,Number.isFinite(t)?t:0),this.rebuildGeometry()}setAnchor(e){this.anchor=n.normalizeAnchor(e),this.applyAnchorOffset()}get texturePath(){return this.texture?.url??null}set texturePath(e){this.texture=D(e)}setTextureResource(e){this.texture=D(e)}setTexture(e){if($(e),this.material.map=e,this.material.color.set("#ffffff"),this.material.needsUpdate=!0,e.image){let t=e.image,i=t.naturalWidth??t.width,r=t.naturalHeight??t.height;i&&r&&(this.textureWidth=i,this.textureHeight=r)}this.rebuildGeometry()}disposeResources(){this.geometry.dispose(),this.material.dispose()}static toSize(e){let t=Number(e);return Number.isFinite(t)&&t>=0?t:Zx}static normalizePatchMode(e){return Qx.includes(e)?e:"stretch"}static normalizeAxis(e){return Jx.includes(e)?e:"stretch"}static normalizeBorder(e){return Ie(e)}static normalizeAnchor(e){if(!e)return{x:.5,y:.5};let t=Array.isArray(e)?e[0]:e.x,i=Array.isArray(e)?e[1]:e.y,r=Number(t),o=Number(i);return{x:Number.isFinite(r)?r:.5,y:Number.isFinite(o)?o:.5}}static toVector2(e,t,i){if(!e)return new N(t,i);let r=Array.isArray(e)?e[0]:e.x,o=Array.isArray(e)?e[1]:e.y,s=Number(r),a=Number(o);return new N(Number.isFinite(s)?s:t,Number.isFinite(a)?a:i)}static getPropertySchema(){let e=C.getPropertySchema();return{nodeType:"TiledSprite2D",extends:"Node2D",properties:[...e.properties,{name:"patchMode",type:"enum",ui:{label:"Mode",description:"How the texture fills the rectangle",group:"Patch",options:{Stretch:"stretch",Tile:"tile","9-Slice":"nine-slice","3-Slice Horizontal":"three-slice-h","3-Slice Vertical":"three-slice-v"}},getValue:t=>t.patchMode,setValue:(t,i)=>{t.setPatchMode(String(i))}},{name:"texture",type:"object",ui:{label:"Texture",description:"Path to the texture",group:"Patch",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.texture??{type:"texture",url:""},setValue:(t,i)=>{t.setTextureResource(i)}},{name:"anchor",type:"vector2",ui:{label:"Pivot",description:"Normalized pivot point used to position the image",group:"Patch",step:.01,precision:2},getValue:t=>{let i=t.anchor;return{x:i.x,y:i.y}},setValue:(t,i)=>{let r=i;t.setAnchor({x:r.x,y:r.y})}},{name:"width",type:"number",ui:{label:"Width",description:"Width in pixels",group:"Size",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.width,setValue:(t,i)=>{let r=t;r.updateSize(Number(i),r.height)}},{name:"height",type:"number",ui:{label:"Height",description:"Height in pixels",group:"Size",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.height,setValue:(t,i)=>{let r=t;r.updateSize(r.width,Number(i))}},{name:"sliceBorderLeft",type:"number",ui:{label:"Left",description:"Left border inset (source px)",group:"Slice",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.left,setValue:(t,i)=>{t.setSliceBorder({left:Number(i)})}},{name:"sliceBorderRight",type:"number",ui:{label:"Right",description:"Right border inset (source px)",group:"Slice",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.right,setValue:(t,i)=>{t.setSliceBorder({right:Number(i)})}},{name:"sliceBorderTop",type:"number",ui:{label:"Top",description:"Top border inset (source px)",group:"Slice",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.top,setValue:(t,i)=>{t.setSliceBorder({top:Number(i)})}},{name:"sliceBorderBottom",type:"number",ui:{label:"Bottom",description:"Bottom border inset (source px)",group:"Slice",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.bottom,setValue:(t,i)=>{t.setSliceBorder({bottom:Number(i)})}},{name:"drawCenter",type:"boolean",ui:{label:"Draw Center",description:"Draw the centre patch (uncheck for a hollow frame)",group:"Slice"},getValue:t=>t.drawCenter,setValue:(t,i)=>{t.setDrawCenter(!!i)}},{name:"axisStretchHorizontal",type:"enum",ui:{label:"Horizontal Fill",description:"How the horizontal middle fills in slice modes",group:"Slice",options:{Stretch:"stretch",Tile:"tile"}},getValue:t=>t.axisStretchHorizontal,setValue:(t,i)=>{t.setAxisStretchHorizontal(String(i))}},{name:"axisStretchVertical",type:"enum",ui:{label:"Vertical Fill",description:"How the vertical middle fills in slice modes",group:"Slice",options:{Stretch:"stretch",Tile:"tile"}},getValue:t=>t.axisStretchVertical,setValue:(t,i)=>{t.setAxisStretchVertical(String(i))}},{name:"tileScale",type:"vector2",ui:{label:"Tile Scale",description:"Tile size multiplier (Tile mode)",group:"Tile",step:.01,precision:2},getValue:t=>{let i=t.tileScale;return{x:i.x,y:i.y}},setValue:(t,i)=>{let r=i;t.setTileScale(r.x,r.y)}},{name:"tileOffset",type:"vector2",ui:{label:"Tile Offset",description:"UV phase offset in tiles (Tile mode)",group:"Tile",step:.01,precision:2},getValue:t=>{let i=t.tileOffset;return{x:i.x,y:i.y}},setValue:(t,i)=>{let r=i;t.setTileOffset(r.x,r.y)}}],groups:{...e.groups,Patch:{label:"Patch",description:"Texture and fill mode",expanded:!0},Size:{label:"Size",description:"Rectangle dimensions in pixels",expanded:!0},Slice:{label:"Slice",description:"9-slice / 3-slice borders",expanded:!0},Tile:{label:"Tile",description:"Tiling scale and offset",expanded:!1}}}}};var Ae=class extends C{_width;_height;constructor(e,t="Group2D"){super(e,t),this._width=Number.isFinite(e.width)?Math.max(0,e.width??0):100,this._height=Number.isFinite(e.height)?Math.max(0,e.height??0):100,this.isContainer=!0}get width(){return this._width}set width(e){let t=Number.isFinite(e)?Math.max(0,e):this._width;this._width!==t&&(this._width=t,this.reflowAnchoredChildren())}get height(){return this._height}set height(e){let t=Number.isFinite(e)?Math.max(0,e):this._height;this._height!==t&&(this._height=t,this.reflowAnchoredChildren())}getSize(){return new N(this._width,this._height)}setSize(e,t){let i=Number.isFinite(e)?Math.max(0,e):this._width,r=Number.isFinite(t)?Math.max(0,t):this._height,o=this._width!==i||this._height!==r;this._width=i,this._height=r,o&&this.reflowAnchoredChildren()}static getPropertySchema(){let e=C.getPropertySchema();return{nodeType:"Group2D",extends:"Node2D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Size",step:1,precision:0,min:0},getValue:t=>t.width,setValue:(t,i)=>{t.width=Number(i)}},{name:"height",type:"number",ui:{label:"Height",group:"Size",step:1,precision:0,min:0},getValue:t=>t.height,setValue:(t,i)=>{t.height=Number(i)}}],groups:{...e.groups,Size:{label:"Size",description:"Group dimensions",expanded:!0}}}}};var _t=class n extends V{active=!1;elapsed=0;appliedOffset=new S;onTriggerSignal=()=>{this.trigger()};constructor(e,t){super(e,t),this.config={amplitude:8,frequency:24,duration:.35,decay:1.5,triggerEvent:"",playOnStart:!1}}static getPropertySchema(){return{nodeType:"ShakeBehavior",properties:[{name:"amplitude",type:"number",ui:{label:"Amplitude",group:"Shake",min:0,step:.5},getValue:e=>e.getAmplitude(),setValue:(e,t)=>{e.config.amplitude=n.num(t,8,0)}},{name:"frequency",type:"number",ui:{label:"Frequency",group:"Shake",min:0,step:1},getValue:e=>e.getFrequency(),setValue:(e,t)=>{e.config.frequency=n.num(t,24,0)}},{name:"duration",type:"number",ui:{label:"Duration",group:"Shake",min:0,step:.05,precision:2,unit:"s"},getValue:e=>e.getDuration(),setValue:(e,t)=>{e.config.duration=n.num(t,.35,0)}},{name:"decay",type:"number",ui:{label:"Decay",description:"Falloff power (0 = steady, 1 = linear, >1 = punchy tail)",group:"Shake",min:0,step:.1,precision:2},getValue:e=>e.getDecay(),setValue:(e,t)=>{e.config.decay=n.num(t,1.5,0)}},{name:"triggerEvent",type:"string",ui:{label:"Trigger Event",description:"Node signal that starts the shake (empty = manual/API only)",group:"Shake"},getValue:e=>e.getTriggerEvent(),setValue:(e,t)=>{e.setTriggerEvent(t)}},{name:"playOnStart",type:"boolean",ui:{label:"Play On Start",group:"Shake"},getValue:e=>!!e.config.playOnStart,setValue:(e,t)=>{e.config.playOnStart=!!t}}],groups:{Shake:{label:"Shake",expanded:!0}}}}onStart(){this.bindTrigger(),this.config.playOnStart&&this.trigger()}onDetach(){this.unbindTrigger(),this.restore(),this.active=!1,super.onDetach()}play(e={}){e.amplitude!=null&&(this.config.amplitude=n.num(e.amplitude,8,0)),e.frequency!=null&&(this.config.frequency=n.num(e.frequency,24,0)),e.duration!=null&&(this.config.duration=n.num(e.duration,.35,0)),e.decay!=null&&(this.config.decay=n.num(e.decay,1.5,0)),this.trigger()}trigger(){this.elapsed=0,this.active=!0}stop(){this.active=!1,this.restore()}onUpdate(e){if(!this.node||(this.restore(),!this.active))return;this.elapsed+=e;let t=this.getDuration();if(t>0&&this.elapsed>=t){this.active=!1;return}let i=t>0?this.elapsed/t:0,r=Math.pow(Math.max(0,1-i),this.getDecay()),o=this.getAmplitude()*r,s=this.elapsed*this.getFrequency(),a=this.node instanceof U;this.appliedOffset.set(Si(s,0)*o,Si(s,100)*o,a?Si(s,200)*o*.5:0),this.node.position.add(this.appliedOffset)}restore(){this.node&&(this.appliedOffset.x||this.appliedOffset.y||this.appliedOffset.z)&&this.node.position.sub(this.appliedOffset),this.appliedOffset.set(0,0,0)}bindTrigger(){let e=this.getTriggerEvent();this.node&&e&&this.node.connect(e,this,this.onTriggerSignal)}unbindTrigger(){let e=this.getTriggerEvent();this.node&&e&&this.node.disconnect(e,this,this.onTriggerSignal)}getAmplitude(){return n.num(this.config.amplitude,8,0)}getFrequency(){return n.num(this.config.frequency,24,0)}getDuration(){return n.num(this.config.duration,.35,0)}getDecay(){return n.num(this.config.decay,1.5,0)}getTriggerEvent(){return typeof this.config.triggerEvent=="string"?this.config.triggerEvent.trim():""}setTriggerEvent(e){let t=!!this.node;t&&this.unbindTrigger(),this.config.triggerEvent=typeof e=="string"?e.trim():"",t&&this.bindTrigger()}static num(e,t,i){let r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.max(i,r):t}};function Si(n,e){return Math.sin(n*1.373+e*12.9898)*.5+Math.sin(n*2.917+e*7.233)*.3+Math.sin(n*5.109+e*19.19)*.2}function ln(n,e){if(n<=0||e<=0)return 1;let t=1-Math.exp(-n*e);return t<0?0:t>1?1:t}function vi(n,e,t){let i=e-n;return Math.abs(i)<=t?n:i>0?e-t:e+t}function wi(n,e,t){let i=e-t,r=e+t;return n<i?i:n>r?r:n}var Ns={priority:10,zoom:1,followDamping:8,shakeAmplitude:8,shakeFrequency:24,shakeDuration:.35,shakeDecay:1.5},Ft=class extends C{priorityValue;zoomValue;offset=new N;followTargetId;followDampingValue;followOffset=new N;deadzone=new N;limitsEnabledValue;limitsCenter=new N;limitsSize=new N(1e3,1e3);shakeAmplitudeValue;shakeFrequencyValue;shakeDurationValue;shakeDecayValue;shakeActive=!1;shakeElapsed=0;shakeOffset=new N;scratchWorld=new S;scratchTarget=new S;scratchLocal=new S;constructor(e){super(e,"Camera2D");let t=Ns;this.priorityValue=e.priority??t.priority,this.zoomValue=Math.max(.01,e.zoom??t.zoom),e.offset&&this.offset.set(e.offset.x,e.offset.y),this.followTargetId=e.followTargetId??"",this.followDampingValue=Math.max(0,e.followDamping??t.followDamping),e.followOffset&&this.followOffset.set(e.followOffset.x,e.followOffset.y),e.deadzone&&this.deadzone.set(Math.max(0,e.deadzone.x),Math.max(0,e.deadzone.y)),this.limitsEnabledValue=e.limitsEnabled??!1,e.limitsCenter&&this.limitsCenter.set(e.limitsCenter.x,e.limitsCenter.y),e.limitsSize&&this.limitsSize.set(Math.max(0,e.limitsSize.x),Math.max(0,e.limitsSize.y)),this.shakeAmplitudeValue=Math.max(0,e.shakeAmplitude??t.shakeAmplitude),this.shakeFrequencyValue=Math.max(0,e.shakeFrequency??t.shakeFrequency),this.shakeDurationValue=Math.max(0,e.shakeDuration??t.shakeDuration),this.shakeDecayValue=Math.max(0,e.shakeDecay??t.shakeDecay)}get priority(){return this.priorityValue}set priority(e){let t=Number(e);this.priorityValue=Number.isFinite(t)?t:this.priorityValue}get zoom(){return this.zoomValue}set zoom(e){let t=Number(e);Number.isFinite(t)&&t>0&&(this.zoomValue=t)}get limitsEnabled(){return this.limitsEnabledValue}set limitsEnabled(e){this.limitsEnabledValue=!!e}tick(e){super.tick(e),this.solve(e)}solve(e){this.solveFollow(e),this.advanceShake(e)}computeView(e){this.updateWorldMatrix(!0,!1),this.getWorldPosition(this.scratchWorld);let t=this.scratchWorld.x+this.offset.x,i=this.scratchWorld.y+this.offset.y,r=Math.max(.01,this.zoomValue);if(this.limitsEnabledValue){let o=e.width/2/r,s=e.height/2/r,a=Math.max(0,this.limitsSize.x/2-o),l=Math.max(0,this.limitsSize.y/2-s);t=wi(t,this.limitsCenter.x,a),i=wi(i,this.limitsCenter.y,l)}return{x:t,y:i,zoom:r}}getShakeOffset(e){return e.copy(this.shakeOffset)}shake(e={}){e.amplitude!=null&&Number.isFinite(e.amplitude)&&(this.shakeAmplitudeValue=Math.max(0,e.amplitude)),e.frequency!=null&&Number.isFinite(e.frequency)&&(this.shakeFrequencyValue=Math.max(0,e.frequency)),e.duration!=null&&Number.isFinite(e.duration)&&(this.shakeDurationValue=Math.max(0,e.duration)),e.decay!=null&&Number.isFinite(e.decay)&&(this.shakeDecayValue=Math.max(0,e.decay)),this.shakeElapsed=0,this.shakeActive=!0}stopShake(){this.shakeActive=!1,this.shakeOffset.set(0,0)}advanceShake(e){if(!this.shakeActive){this.shakeOffset.set(0,0);return}this.shakeElapsed+=Math.max(0,e);let t=this.shakeDurationValue;if(t>0&&this.shakeElapsed>=t){this.shakeActive=!1,this.shakeOffset.set(0,0);return}let i=t>0?this.shakeElapsed/t:0,r=Math.pow(Math.max(0,1-i),this.shakeDecayValue),o=this.shakeAmplitudeValue*r,s=this.shakeElapsed*this.shakeFrequencyValue;this.shakeOffset.set(Si(s,0)*o,Si(s,100)*o)}solveFollow(e){let t=this.resolveTarget(this.followTargetId);if(!t||t===this)return;t.getWorldPosition(this.scratchTarget);let i=this.scratchTarget.x+this.followOffset.x,r=this.scratchTarget.y+this.followOffset.y;this.updateWorldMatrix(!0,!1),this.getWorldPosition(this.scratchWorld);let o=vi(this.scratchWorld.x,i,this.deadzone.x),s=vi(this.scratchWorld.y,r,this.deadzone.y),a=ln(this.followDampingValue,e),l=this.scratchWorld.x+(o-this.scratchWorld.x)*a,c=this.scratchWorld.y+(s-this.scratchWorld.y)*a;this.setWorldPosition2D(l,c)}setWorldPosition2D(e,t){this.scratchLocal.set(e,t,0),this.parent&&(this.parent.updateWorldMatrix(!0,!1),this.parent.worldToLocal(this.scratchLocal)),this.position.x=this.scratchLocal.x,this.position.y=this.scratchLocal.y,this.updateWorldMatrix(!0,!1)}resolveTarget(e){if(!e)return null;if(this.scene)return this.scene.findNode(e);let t=this;for(;t.parentNode;)t=t.parentNode;return t.findNode(e)}serializeConfig(){return{priority:this.priorityValue,zoom:this.zoomValue,offset:[this.offset.x,this.offset.y],followTargetId:this.followTargetId,followDamping:this.followDampingValue,followOffset:[this.followOffset.x,this.followOffset.y],deadzone:[this.deadzone.x,this.deadzone.y],limitsEnabled:this.limitsEnabledValue,limitsCenter:[this.limitsCenter.x,this.limitsCenter.y],limitsSize:[this.limitsSize.x,this.limitsSize.y],shakeAmplitude:this.shakeAmplitudeValue,shakeFrequency:this.shakeFrequencyValue,shakeDuration:this.shakeDurationValue,shakeDecay:this.shakeDecayValue}}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"Camera2D",properties:[x("priority","number",{ui:{label:"Priority",description:"Highest-priority visible Camera2D drives the 2D view (animatable)",group:"Camera",step:1,precision:0},getValue:i=>i.priority,setValue:(i,r)=>{i.priority=Number(r)},validation:{validate:i=>Number.isFinite(Number(i))}}),x("zoom","number",{ui:{label:"Zoom",description:">1 magnifies (zooms in), <1 zooms out",group:"Camera",min:.01,step:.05,precision:2},getValue:i=>i.zoom,setValue:(i,r)=>{i.zoom=Number(r)},validation:{validate:i=>Number.isFinite(Number(i))&&Number(i)>0}}),x("offset","vector2",{ui:{label:"Offset",description:"Framing offset added to position (never written by follow / shake)",group:"Camera",step:1,precision:0},getValue:i=>cn(i.offset),setValue:(i,r)=>un(i.offset,r)}),x("followTargetId","node",{ui:{label:"Follow Target",description:"Node whose position this camera follows (empty = authored position)",group:"Follow"},getValue:i=>i.followTargetId,setValue:(i,r)=>{i.followTargetId=typeof r=="string"?r:""}}),x("followOffset","vector2",{ui:{label:"Follow Offset",group:"Follow",step:1,precision:0},getValue:i=>cn(i.followOffset),setValue:(i,r)=>un(i.followOffset,r)}),x("followDamping","number",{ui:{label:"Follow Damping",description:"Higher = snappier follow (0 = instant)",group:"Follow",min:0,step:.1,precision:2},getValue:i=>i.followDampingValue,setValue:(i,r)=>{let o=Number(r);Number.isFinite(o)&&o>=0&&(i.followDampingValue=o)}}),x("deadzone","vector2",{ui:{label:"Deadzone",description:"World half-extents the target can move within before the camera follows",group:"Follow",min:0,step:1,precision:0},getValue:i=>cn(i.deadzone),setValue:(i,r)=>un(i.deadzone,r,0)}),x("limitsEnabled","boolean",{ui:{label:"Limits",description:"Clamp the visible view inside an axis-aligned world box",group:"Limits"},getValue:i=>i.limitsEnabledValue,setValue:(i,r)=>{i.limitsEnabledValue=!!r}}),x("limitsCenter","vector2",{ui:{label:"Limits Center",group:"Limits",step:1,precision:0,readOnly:i=>!i.limitsEnabledValue},getValue:i=>cn(i.limitsCenter),setValue:(i,r)=>un(i.limitsCenter,r)}),x("limitsSize","vector2",{ui:{label:"Limits Size",group:"Limits",min:0,step:1,precision:0,readOnly:i=>!i.limitsEnabledValue},getValue:i=>cn(i.limitsSize),setValue:(i,r)=>un(i.limitsSize,r,0)}),x("shakeAmplitude","number",{ui:{label:"Shake Amplitude",group:"Shake",min:0,step:.5,precision:2},getValue:i=>i.shakeAmplitudeValue,setValue:(i,r)=>{let o=Number(r);Number.isFinite(o)&&o>=0&&(i.shakeAmplitudeValue=o)}}),x("shakeFrequency","number",{ui:{label:"Shake Frequency",group:"Shake",min:0,step:1,precision:1},getValue:i=>i.shakeFrequencyValue,setValue:(i,r)=>{let o=Number(r);Number.isFinite(o)&&o>=0&&(i.shakeFrequencyValue=o)}}),x("shakeDuration","number",{ui:{label:"Shake Duration",group:"Shake",min:0,step:.05,precision:2,unit:"s"},getValue:i=>i.shakeDurationValue,setValue:(i,r)=>{let o=Number(r);Number.isFinite(o)&&o>=0&&(i.shakeDurationValue=o)}}),x("shakeDecay","number",{ui:{label:"Shake Decay",description:"Falloff power (0 = steady, 1 = linear, >1 = punchy tail)",group:"Shake",min:0,step:.1,precision:2},getValue:i=>i.shakeDecayValue,setValue:(i,r)=>{let o=Number(r);Number.isFinite(o)&&o>=0&&(i.shakeDecayValue=o)}})],groups:{Camera:{label:"Camera",expanded:!0},Follow:{label:"Follow",expanded:!0},Limits:{label:"Limits",expanded:!1},Shake:{label:"Shake",expanded:!1}}};return le(e,t)}};function mu(n){let e=null,t=i=>{for(let r of i){r instanceof Ft&&r.visible&&(e===null||r.priority>e.priority)&&(e=r);let o=r.children.filter(s=>s instanceof I);o.length>0&&t(o)}};return t(n),e}function cn(n){return{x:n.x,y:n.y}}function un(n,e,t=Number.NEGATIVE_INFINITY){let i=e,r=Number(i?.x),o=Number(i?.y);n.set(Number.isFinite(r)?Math.max(t,r):n.x,Number.isFinite(o)?Math.max(t,o):n.y)}var hn=class extends Ae{constructor(e){super(e,"CanvasLayer2D"),this.isCanvasLayer=!0}static getPropertySchema(){return{...Ae.getPropertySchema(),nodeType:"CanvasLayer2D",extends:"Group2D"}}};var kf=5,zt=class extends U{light;constructor(e){super(e,"DirectionalLight");let t=new L(e.color??"#ffffff"),i=typeof e.intensity=="number"?e.intensity:1;this.light=new os(t,i),this.light.castShadow=e.castShadow??!0,this.light.position.set(0,0,0);let r=typeof e.shadowCameraSize=="number"?e.shadowCameraSize:20;this.light.shadow.camera.left=-r,this.light.shadow.camera.right=r,this.light.shadow.camera.top=r,this.light.shadow.camera.bottom=-r,this.light.shadow.camera.near=.1,this.light.shadow.camera.far=500,this.light.shadow.camera.updateProjectionMatrix();let o=typeof e.shadowMapSize=="number"?e.shadowMapSize:2048;this.light.shadow.mapSize.set(o,o),this.add(this.light),this.add(this.light.target),this.light.target.position.set(0,0,-kf),this.light.target.updateMatrixWorld(!0)}getTargetPosition(){return this.light.target.updateMatrixWorld(!0),this.light.target.getWorldPosition(new S)}setTargetPosition(e){let t=this.getWorldPosition(new S),i=e.clone().sub(t),r=i.lengthSq()>1e-8?i.normalize():new S(0,0,1).applyQuaternion(this.getWorldQuaternion(new F)),o=t.add(r.multiplyScalar(kf));this.lookAt(o);let s=o.clone();this.worldToLocal(s),this.light.target.position.copy(s),this.light.target.updateMatrixWorld(!0)}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"DirectionalLight",properties:[x("color","color",{ui:{label:"Color",group:"Light"},getValue:i=>"#"+i.light.color.getHexString(),setValue:(i,r)=>{i.light.color.set(String(r))}}),x("intensity","number",{ui:{label:"Intensity",group:"Light",step:.1,precision:2},getValue:i=>i.light.intensity,setValue:(i,r)=>{i.light.intensity=Number(r)}}),x("castShadow","boolean",{ui:{label:"Cast Shadow",group:"Light"},getValue:i=>i.light.castShadow,setValue:(i,r)=>{i.light.castShadow=!!r}}),x("shadowCameraSize","number",{ui:{label:"Shadow Area",group:"Shadow",step:1,precision:0,description:"Half-size of the shadow frustum (\xB1units from center)"},getValue:i=>i.light.shadow.camera.right,setValue:(i,r)=>{let o=i,s=Math.max(.1,Number(r));o.light.shadow.camera.left=-s,o.light.shadow.camera.right=s,o.light.shadow.camera.top=s,o.light.shadow.camera.bottom=-s,o.light.shadow.camera.updateProjectionMatrix()}}),x("shadowMapSize","number",{ui:{label:"Shadow Map Res",group:"Shadow",step:256,precision:0,description:"Shadow map resolution (pixels)"},getValue:i=>i.light.shadow.mapSize.width,setValue:(i,r)=>{let o=i,s=Math.max(64,Number(r));o.light.shadow.mapSize.set(s,s)}})],groups:{Light:{label:"Light",expanded:!0},Shadow:{label:"Shadow",expanded:!1}}};return le(e,t)}};var Ut=class extends U{light;constructor(e){super(e,"PointLight");let t=new L(e.color??"#ffffff"),i=typeof e.intensity=="number"?e.intensity:1,r=typeof e.distance=="number"?e.distance:0,o=typeof e.decay=="number"?e.decay:2;this.light=new ns(t,i,r,o),this.light.castShadow=e.castShadow??!0,this.add(this.light)}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"PointLight",properties:[x("color","color",{ui:{label:"Color",group:"Light"},getValue:i=>"#"+i.light.color.getHexString(),setValue:(i,r)=>{i.light.color.set(String(r))}}),x("intensity","number",{ui:{label:"Intensity",group:"Light",step:.1,precision:2},getValue:i=>i.light.intensity,setValue:(i,r)=>{i.light.intensity=Number(r)}}),x("distance","number",{ui:{label:"Range",group:"Light",step:.1,precision:2},getValue:i=>i.light.distance,setValue:(i,r)=>{i.light.distance=Number(r)}}),x("decay","number",{ui:{label:"Decay",group:"Light",step:.1,precision:2},getValue:i=>i.light.decay,setValue:(i,r)=>{i.light.decay=Number(r)}}),x("castShadow","boolean",{ui:{label:"Cast Shadow",group:"Light"},getValue:i=>i.light.castShadow,setValue:(i,r)=>{i.light.castShadow=!!r}})],groups:{Light:{label:"Light",expanded:!0}}};return le(e,t)}};var Af=5,Wt=class extends U{light;constructor(e){super(e,"SpotLight");let t=new L(e.color??"#ffffff"),i=typeof e.intensity=="number"?e.intensity:1,r=typeof e.distance=="number"?e.distance:0,o=typeof e.angle=="number"?e.angle:Math.PI/3,s=typeof e.penumbra=="number"?e.penumbra:0,a=typeof e.decay=="number"?e.decay:2;this.light=new rs(t,i,r,o,s,a),this.light.castShadow=e.castShadow??!0,this.light.position.set(0,0,0),this.add(this.light),this.add(this.light.target),this.light.target.position.set(0,0,-Af),this.light.target.updateMatrixWorld(!0)}getTargetPosition(){return this.light.target.updateMatrixWorld(!0),this.light.target.getWorldPosition(new S)}setTargetPosition(e){let t=this.getWorldPosition(new S),i=e.clone().sub(t),r=i.lengthSq()>1e-8?i.normalize():new S(0,0,1).applyQuaternion(this.getWorldQuaternion(new F)),o=t.add(r.multiplyScalar(Af));this.lookAt(o);let s=o.clone();this.worldToLocal(s),this.light.target.position.copy(s),this.light.target.updateMatrixWorld(!0)}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"SpotLight",properties:[x("color","color",{ui:{label:"Color",group:"Light"},getValue:i=>"#"+i.light.color.getHexString(),setValue:(i,r)=>{i.light.color.set(String(r))}}),x("intensity","number",{ui:{label:"Intensity",group:"Light",step:.1,precision:2},getValue:i=>i.light.intensity,setValue:(i,r)=>{i.light.intensity=Number(r)}}),x("distance","number",{ui:{label:"Range",group:"Light",step:.1,precision:2},getValue:i=>i.light.distance,setValue:(i,r)=>{i.light.distance=Number(r)}}),x("angle","number",{ui:{label:"Angle",group:"Light",unit:"\xB0",step:.1,precision:1},getValue:i=>i.light.angle*180/Math.PI,setValue:(i,r)=>{i.light.angle=Number(r)*Math.PI/180}}),x("penumbra","number",{ui:{label:"Penumbra",group:"Light",step:.01,precision:2},getValue:i=>i.light.penumbra,setValue:(i,r)=>{i.light.penumbra=Number(r)}}),x("decay","number",{ui:{label:"Decay",group:"Light",step:.1,precision:2},getValue:i=>i.light.decay,setValue:(i,r)=>{i.light.decay=Number(r)}}),x("castShadow","boolean",{ui:{label:"Cast Shadow",group:"Light"},getValue:i=>i.light.castShadow,setValue:(i,r)=>{i.light.castShadow=!!r}})],groups:{Light:{label:"Light",expanded:!0}}};return le(e,t)}};var Ht=class extends U{light;constructor(e){super(e,"AmbientLight");let t=new L(e.color??"#ffffff"),i=typeof e.intensity=="number"?e.intensity:.5;this.light=new Dm(t,i),this.add(this.light)}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"AmbientLight",properties:[x("color","color",{ui:{label:"Color",group:"Light"},getValue:i=>"#"+i.light.color.getHexString(),setValue:(i,r)=>{i.light.color.set(String(r))}}),x("intensity","number",{ui:{label:"Intensity",group:"Light",step:.1,precision:2},getValue:i=>i.light.intensity,setValue:(i,r)=>{i.light.intensity=Number(r)}})],groups:{Light:{label:"Light",expanded:!0}}};return le(e,t)}};var fu=["Group","Node2D","Node3D","ColorRect2D","Sprite2D","TiledSprite2D","AnimatedSprite2D","SpineSkeleton2D","Label2D","Layout2D","Group2D","CanvasLayer2D","Camera2D","Button2D","Slider2D","Bar2D","Checkbox2D","Joystick2D","ScrollContainer2D","InventorySlot2D","GeometryMesh","MeshInstance","InstancedMesh3D","Sprite3D","AnimatedSprite3D","Particles3D","AmbientLightNode","DirectionalLightNode","HemisphereLightNode","PointLightNode","SpotLightNode","Camera3D","VirtualCamera3D","PostProcess","AudioPlayer"],dn=n=>n.toLowerCase().replace(/[^a-z0-9]/g,""),Cf={ambientlight:"AmbientLightNode",ambientlight3d:"AmbientLightNode",directionallight:"DirectionalLightNode",directionallight3d:"DirectionalLightNode",hemispherelight:"HemisphereLightNode",hemispherelight3d:"HemisphereLightNode",pointlight:"PointLightNode",pointlight3d:"PointLightNode",spotlight:"SpotLightNode",spotlight3d:"SpotLightNode",meshinstance3d:"MeshInstance"},e0=new Map(fu.map(n=>[dn(n),n])),Is=n=>{if(typeof n!="string"||n.trim().length===0)return null;let e=dn(n);return e0.get(e)??Cf[e]??null},gu=n=>Is(n)!==null,Tf=[...fu.map(n=>[dn(n),n]),...Object.entries(Cf)],Mf=n=>{let e=dn(n);if(e.length===0)return;let t,i=Number.POSITIVE_INFINITY;for(let[s,a]of Tf){let l=t0(e,s);l<i&&(i=l,t=a)}if(i<=2)return t;let r,o=0;for(let[s,a]of Tf)s.length<5||s.length<=o||(e.includes(s)||s.includes(e))&&(r=a,o=s.length);return r},yu=(n,e)=>{let t=Mf(e),i=t?` Did you mean "${t}"?`:"";return`Unknown node type "${e}" on node "${n}" \u2014 it was loaded as an inert placeholder and does nothing.${i}`},t0=(n,e)=>{if(n===e)return 0;if(n.length===0)return e.length;if(e.length===0)return n.length;let t=Array.from({length:e.length+1},(i,r)=>r);for(let i=1;i<=n.length;i++){let r=[i];for(let o=1;o<=e.length;o++){let s=t[o-1]+(n[i-1]===e[o-1]?0:1);r[o]=Math.min(r[o-1]+1,t[o]+1,s)}t=r}return t[e.length]};var qt=class extends U{light;constructor(e){super(e,"HemisphereLight");let t=new L(e.skyColor??"#ffffff"),i=new L(e.groundColor??"#444444"),r=typeof e.intensity=="number"?e.intensity:.5;this.light=new Mm(t,i,r),this.add(this.light)}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"HemisphereLight",properties:[x("skyColor","color",{ui:{label:"Sky Color",group:"Light"},getValue:i=>"#"+i.light.color.getHexString(),setValue:(i,r)=>{i.light.color.set(String(r))}}),x("groundColor","color",{ui:{label:"Ground Color",group:"Light"},getValue:i=>"#"+i.light.groundColor.getHexString(),setValue:(i,r)=>{i.light.groundColor.set(String(r))}}),x("intensity","number",{ui:{label:"Intensity",group:"Light",step:.1,precision:2},getValue:i=>i.light.intensity,setValue:(i,r)=>{i.light.intensity=Number(r)}})],groups:{Light:{label:"Light",expanded:!0}}};return le(e,t)}};var mt=class n extends U{texture;width;height;color;billboard;billboardRoll;textureAspectRatio;aspectRatioLocked;originalWidth;originalHeight;mesh;geometry;material;billboardPivot;static tempWorldQuaternion=new F;static tempLocalQuaternion=new F;constructor(e){super(e,"Sprite3D"),this.texture=D(e.texture??e.texturePath??null),this.width=typeof e.width=="number"&&e.width>0?e.width:1,this.height=typeof e.height=="number"&&e.height>0?e.height:1,this.color=e.color??"#ffffff",this.billboard=e.billboard??!1,this.billboardRoll=e.billboardRoll??0,this.textureAspectRatio=e.textureAspectRatio??null,this.aspectRatioLocked=e.aspectRatioLocked??!1,this.originalWidth=null,this.originalHeight=null,this.geometry=new z(this.width,this.height),this.material=new B({color:this.color,transparent:!0,side:xe,depthWrite:!1}),this.mesh=new O(this.geometry,this.material),this.mesh.name=`${this.name}-Mesh`,this.billboardPivot=this.mesh,this.add(this.billboardPivot),this.registerOpacityMaterial(this.material),H(this,n.getPropertySchema)}get texturePath(){return this.texture?.url??null}set texturePath(e){this.texture=D(e)}setTextureResource(e){this.texture=D(e)}setTexture(e){if(e.colorSpace=Pe,this.material.map=e,this.material.color.set("#ffffff"),this.material.transparent=!0,this.material.needsUpdate=!0,e.image){let t=e.image,{width:i,height:r}=Xe(t);i&&r&&(this.textureAspectRatio=i/r,this.originalWidth=i,this.originalHeight=r)}}clearTexture(){this.material.map=null,this.material.needsUpdate=!0}setSize(e,t){let i=Number.isFinite(e)&&e>0?e:this.width,r=Number.isFinite(t)&&t>0?t:this.height;i===this.width&&r===this.height||(this.width=i,this.height=r,this.geometry.dispose(),this.geometry=new z(this.width,this.height),this.mesh.geometry=this.geometry)}resetToOriginalSize(){!this.originalWidth||!this.originalHeight||this.setSize(this.originalWidth,this.originalHeight)}applyBillboard(e){if(!this.billboard){this.billboardPivot.quaternion.identity();return}this.getWorldQuaternion(n.tempWorldQuaternion),n.tempLocalQuaternion.copy(n.tempWorldQuaternion).invert().multiply(e),this.billboardPivot.quaternion.copy(n.tempLocalQuaternion),this.billboardPivot.rotateZ(R.degToRad(this.billboardRoll))}static getPropertySchema(){let e=U.getPropertySchema();return{nodeType:"Sprite3D",extends:"Node3D",properties:[...e.properties,{name:"texture",type:"object",ui:{label:"Texture",description:"Path to the sprite texture",group:"Sprite",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.texture??{type:"texture",url:""},setValue:(t,i)=>{t.setTextureResource(i)}},{name:"width",type:"number",ui:{label:"Width",description:"Sprite width in world units",group:"Sprite",editor:"sprite-size",step:.01,precision:2,min:.01},getValue:t=>t.width,setValue:(t,i)=>{let r=t;r.setSize(Number(i),r.height)}},{name:"height",type:"number",ui:{label:"Height",description:"Sprite height in world units",group:"Sprite",editor:"sprite-size",step:.01,precision:2,min:.01},getValue:t=>t.height,setValue:(t,i)=>{let r=t;r.setSize(r.width,Number(i))}},{name:"billboard",type:"boolean",ui:{label:"Billboard",description:"Face the active camera while keeping world placement",group:"Sprite"},getValue:t=>t.billboard,setValue:(t,i)=>{t.billboard=!!i}},{name:"billboardRoll",type:"number",ui:{label:"Billboard Roll",description:"Additional roll angle when billboard is enabled",group:"Sprite",step:.1,precision:1,unit:"\xB0"},getValue:t=>t.billboardRoll,setValue:(t,i)=>{t.billboardRoll=Number(i)}},{name:"opacity",type:"number",ui:{label:"Opacity",description:"Sprite opacity (use show()/hide() to fade at runtime)",group:"Sprite",step:.01,precision:2,min:0,max:1},getValue:t=>t.opacity,setValue:(t,i)=>{t.opacity=Number(i)}},{name:"textureAspectRatio",type:"number",ui:{hidden:!0},getValue:t=>t.textureAspectRatio??null,setValue:(t,i)=>{t.textureAspectRatio=i===null?null:Number(i)}},{name:"aspectRatioLocked",type:"boolean",ui:{hidden:!0},getValue:t=>t.aspectRatioLocked,setValue:(t,i)=>{t.aspectRatioLocked=!!i}}],groups:{...e.groups,Sprite:{label:"Sprite",description:"3D sprite rendering properties",expanded:!0}}}}};var xi=class n extends U{frames;width;height;color;fps;playing;loop;freeOnFinish;billboard;_currentFrame=0;frameSequencePlayer=new dr;mesh;geometry;material;loadedTextures=[];billboardPivot;static tempWorldQuaternion=new F;static tempLocalQuaternion=new F;constructor(e){super(e,"AnimatedSprite3D"),this.frames=(e.frames||[]).map(D),this.width=e.width??1,this.height=e.height??1,this.color=e.color??"#ffffff",this.fps=e.fps??10,this.playing=e.playing??!0,this.loop=e.loop??!0,this.freeOnFinish=e.freeOnFinish??!1,this.billboard=e.billboard??!0,this.geometry=new z(this.width,this.height),this.material=new B({color:this.color,transparent:!0,side:xe,depthWrite:!1}),this.mesh=new O(this.geometry,this.material),this.mesh.name=`${this.name}-Mesh`,this.billboardPivot=this.mesh,this.add(this.billboardPivot),this.registerOpacityMaterial(this.material),H(this,n.getPropertySchema)}get currentFrame(){return this._currentFrame}set currentFrame(e){if(this.frames.length===0){this._currentFrame=0;return}this._currentFrame=Math.max(0,Math.min(e,this.frames.length-1)),this.updateTexture()}setTextureForFrame(e,t){this.loadedTextures[e]=t,e===this._currentFrame&&this.updateTexture()}updateTexture(){let e=this.loadedTextures[this._currentFrame];if(e){let t=e;"colorSpace"in e?t.colorSpace="srgb":"encoding"in e&&(t.encoding=3001),this.material.map=e,this.material.color.set("#ffffff")}else this.material.map=null,this.material.color.set(this.color);this.material.needsUpdate=!0}applyBillboard(e){if(!this.billboard){this.billboardPivot.quaternion.identity();return}this.getWorldQuaternion(n.tempWorldQuaternion),n.tempLocalQuaternion.copy(n.tempWorldQuaternion).invert().multiply(e),this.billboardPivot.quaternion.copy(n.tempLocalQuaternion)}tick(e){if(super.tick(e),!this.playing||this.frames.length<=1||this.fps<=0)return;let t=this.frameSequencePlayer.advance(e,{frameCount:this.frames.length,fps:this.fps,loop:this.loop,playbackMode:"linear"},this._currentFrame);t.framesAdvanced.length>0&&(this.currentFrame=t.nextIndex),t.finished&&(this.playing=!1,this.emit("animation-finished"),this.freeOnFinish&&this.queueFree())}static getPropertySchema(){let e=U.getPropertySchema();return{...e,nodeType:"AnimatedSprite3D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Size",min:0,step:.1},getValue:t=>t.width,setValue:(t,i)=>{let r=t;r.width=Number(i),r.updateGeometry()}},{name:"height",type:"number",ui:{label:"Height",group:"Size",min:0,step:.1},getValue:t=>t.height,setValue:(t,i)=>{let r=t;r.height=Number(i),r.updateGeometry()}},{name:"color",type:"color",ui:{label:"Color",group:"Style"},getValue:t=>t.color,setValue:(t,i)=>{let r=t;r.color=String(i),r.updateTexture()}},{name:"fps",type:"number",ui:{label:"FPS",group:"Animation",min:1,step:1},getValue:t=>t.fps,setValue:(t,i)=>{t.fps=Number(i)}},{name:"playing",type:"boolean",ui:{label:"Playing",group:"Animation"},getValue:t=>t.playing,setValue:(t,i)=>{t.playing=!!i}},{name:"loop",type:"boolean",ui:{label:"Loop",group:"Animation"},getValue:t=>t.loop,setValue:(t,i)=>{t.loop=!!i}},{name:"freeOnFinish",type:"boolean",ui:{label:"Free on Finish",description:"Destroy this node when a non-looping sequence finishes (one-shot VFX)",group:"Animation"},getValue:t=>t.freeOnFinish,setValue:(t,i)=>{t.freeOnFinish=!!i}},{name:"currentFrame",type:"number",ui:{label:"Current Frame",group:"Animation",min:0,step:1},getValue:t=>t.currentFrame,setValue:(t,i)=>{t.currentFrame=Number(i)}},{name:"billboard",type:"boolean",ui:{label:"Billboard",group:"Style"},getValue:t=>t.billboard,setValue:(t,i)=>{t.billboard=!!i}},{name:"opacity",type:"number",ui:{label:"Opacity",description:"Sprite opacity (use show()/hide() to fade at runtime)",group:"Style",step:.01,precision:2,min:0,max:1},getValue:t=>t.opacity,setValue:(t,i)=>{t.opacity=Number(i)}}],groups:{...e.groups,Size:{label:"Size",expanded:!0},Style:{label:"Style",expanded:!0},Animation:{label:"Animation",expanded:!0}}}}updateGeometry(){this.geometry.dispose(),this.geometry=new z(this.width,this.height),this.mesh.geometry=this.geometry}disposeResources(){this.geometry.dispose(),this.material.dispose()}};var Df=new S(0,1,0),Rs=new S(0,0,1),bu=new S(0,0,0),Ef=2,Nf=64,ft=class n extends U{texture;emitterShape;emitterRadius;emitterBoxSize;particleShape;emissionRate;maxParticles;lifetime;speed;speedSpread;gravity;particleSize;sizeRandomness;startColor;endColor;startAlpha;endAlpha;billboard;playing;loop;prewarm;preview;disableRotation;simulationSpace;trailEnabled;trailLifetime;trailWidth;trailSegments;trailFade;subEmitterId;subEmitterBurstCount;subEmitterInheritVelocity;particles=[];emissionAccumulator=0;activeCount=0;isPrewarming=!1;renderRoot;instancedMesh=null;material;instanceColorAttr;instanceAlphaAttr;trailMesh=null;trailMaterial=null;trailData=null;trailPositions=null;trailColors=null;trailIndices=null;subEmitterCacheId="";subEmitterCache=null;deathScratch=[];startColorVec=new L;endColorVec=new L;tempColor=new L;tempMatrix=new se;tempMatInv=new se;tempScale=new S(1,1,1);tempQuat=new F;tempQuatWorld=new F;tempQuatNode=new F;tempQuatRot=new F;tempVelocity=new S;tempDirection=new S;tempDeathPos=new S;tempDeathVel=new S;tempBurstPos=new S;tempBurstVel=new S;tempCamSim=new S;tempTrailP=new S;tempTrailPrev=new S;tempTrailNext=new S;tempTrailDir=new S;tempTrailView=new S;tempTrailSide=new S;constructor(e){super(e,"Particles3D"),this.texture=D(e.texture??e.texturePath??null),this.emitterShape=e.emitterShape??"point",this.emitterRadius=Math.max(0,e.emitterRadius??.5),this.emitterBoxSize=e.emitterBoxSize??{x:1,y:1,z:1},this.particleShape=e.particleShape??"plane",this.emissionRate=Math.max(0,e.emissionRate??24),this.maxParticles=Math.max(1,Math.floor(e.maxParticles??512)),this.lifetime=Math.max(.01,e.lifetime??2),this.speed=Math.max(0,e.speed??2),this.speedSpread=Math.max(0,e.speedSpread??.5),this.gravity=e.gravity??{x:0,y:0,z:0},this.particleSize=Math.max(.001,e.particleSize??.2),this.sizeRandomness=R.clamp(e.sizeRandomness??.2,0,1),this.startColor=e.startColor??"#ffffff",this.endColor=e.endColor??"#ffd24d",this.startAlpha=R.clamp(e.startAlpha??1,0,1),this.endAlpha=R.clamp(e.endAlpha??0,0,1),this.billboard=e.billboard??!0,this.playing=e.playing??!0,this.loop=e.loop??!0,this.prewarm=e.prewarm??!1,this.preview=e.preview??!1,this.disableRotation=e.disableRotation??!1,this.simulationSpace=e.simulationSpace??"local",this.trailEnabled=e.trailEnabled??!1,this.trailLifetime=Math.max(.05,e.trailLifetime??.3),this.trailWidth=R.clamp(e.trailWidth??.05,.001,2),this.trailSegments=R.clamp(Math.floor(e.trailSegments??16),Ef,Nf),this.trailFade=R.clamp(e.trailFade??1,0,1),this.subEmitterId=e.subEmitterId??"",this.subEmitterBurstCount=R.clamp(Math.floor(e.subEmitterBurstCount??8),0,128),this.subEmitterInheritVelocity=R.clamp(e.subEmitterInheritVelocity??0,0,1),this.material=new B({color:"#ffffff",transparent:!0,depthWrite:!1,blending:ct,vertexColors:!1,side:xe}),this.configureMaterialForInstanceAlpha(),this.renderRoot=new O,this.renderRoot.name=`${this.name}-Particles`,this.add(this.renderRoot),this.instanceColorAttr=new je(new Float32Array(this.maxParticles*3),3),this.instanceColorAttr.setUsage(oe),this.instanceAlphaAttr=new je(new Float32Array(this.maxParticles),1),this.instanceAlphaAttr.setUsage(oe),this.initializeParticles(),this.rebuildRenderer(),this.simulationSpace==="world"&&(this.renderRoot.matrixAutoUpdate=!1),this.trailEnabled&&(this.allocateTrailBuffers(),this.buildTrailMesh()),this.prewarm&&this.playing&&this.prewarmSimulation(),H(this,n.getPropertySchema)}get texturePath(){return this.texture?.url??null}set texturePath(e){this.texture=D(e)}setTextureResource(e){this.texture=D(e)}setTexture(e){this.material.map=e,this.material.needsUpdate=!0}clearTexture(){this.material.map=null,this.material.needsUpdate=!0}setMaxParticles(e){let t=Math.max(1,Math.floor(e));t!==this.maxParticles&&(this.maxParticles=t,this.instanceColorAttr=new je(new Float32Array(this.maxParticles*3),3),this.instanceColorAttr.setUsage(oe),this.instanceAlphaAttr=new je(new Float32Array(this.maxParticles),1),this.instanceAlphaAttr.setUsage(oe),this.initializeParticles(),this.rebuildRenderer(),this.trailEnabled&&(this.allocateTrailBuffers(),this.buildTrailMesh()))}setParticleShape(e){e!==this.particleShape&&(this.particleShape=e,this.rebuildRenderer())}restart(){for(let e of this.particles)e.active=!1,e.age=0,e.trailHead=0,e.trailLen=0,e.trailTimer=0;this.activeCount=0,this.emissionAccumulator=0,this.deathScratch.length=0,this.instancedMesh&&(this.instancedMesh.count=0,this.instancedMesh.instanceMatrix.needsUpdate=!0),this.collapseAllTrails()}syncRenderState(e,t){this.simulationSpace==="world"&&this.syncWorldCompensation(),this.applyBillboardInternal(e),this.updateTrailGeometry(t)}applyBillboard(e){this.syncRenderState(e,bu)}applyBillboardInternal(e){if(!this.billboard||this.particleShape!=="plane"||!this.instancedMesh)return;this.simulationSpace==="world"?this.tempQuatNode.copy(e):(this.getWorldQuaternion(this.tempQuatWorld),this.tempQuatNode.copy(this.tempQuatWorld).invert().multiply(e));let t=0;for(let i=0;i<this.particles.length;i+=1){let r=this.particles[i];r.active&&(this.tempQuat.copy(this.tempQuatNode),this.tempQuatRot.setFromAxisAngle(Rs,r.rotation),this.tempQuat.multiply(this.tempQuatRot),this.tempScale.set(r.size,r.size,r.size),this.tempMatrix.compose(r.position,this.tempQuat,this.tempScale),this.instancedMesh.setMatrixAt(t,this.tempMatrix),t+=1)}this.instancedMesh.instanceMatrix.needsUpdate=!0}tick(e){if(super.tick(e),!this.playing&&!this.preview||e<=0)return;this.simulationSpace==="world"&&this.syncWorldCompensation();let t=Math.min(e,1/20);this.spawnParticles(t),this.updateParticles(t)}initializeParticles(){this.particles=[];for(let e=0;e<this.maxParticles;e+=1)this.particles.push({active:!1,age:0,lifetime:this.lifetime,position:new S,velocity:new S,size:this.particleSize,rotation:0,angularVelocity:0,trailHead:0,trailLen:0,trailTimer:0})}prewarmSimulation(){let e=.016666666666666666,t=Math.min(this.lifetime,3),i=Math.floor(t/e);this.isPrewarming=!0;try{for(let r=0;r<i;r+=1)this.spawnParticles(e),this.updateParticles(e)}finally{this.isPrewarming=!1}}spawnParticles(e){if(!this.loop&&this.activeCount>=this.maxParticles)return;this.emissionAccumulator+=this.emissionRate*e;let t=Math.floor(this.emissionAccumulator);if(!(t<=0)){this.emissionAccumulator-=t;for(let i=0;i<this.particles.length&&t>0;i+=1){let r=this.particles[i];r.active||(this.activateParticle(r,i),t-=1)}}}activateParticle(e,t=-1,i,r){e.active=!0,e.age=0,e.lifetime=this.lifetime*R.lerp(.85,1.15,Math.random()),e.rotation=this.disableRotation?0:Math.random()*Math.PI*2,e.angularVelocity=this.disableRotation?0:R.lerp(-3,3,Math.random()),this.assignSpawnPosition(e.position),this.tempDirection.set(R.randFloatSpread(2),Math.random()*1.5,R.randFloatSpread(2)),this.tempDirection.lengthSq()<1e-5&&this.tempDirection.copy(Df),this.tempDirection.normalize();let o=R.randFloatSpread(this.speedSpread*2),s=Math.max(0,this.speed+o);e.velocity.copy(this.tempDirection.multiplyScalar(s)),i?e.position.add(i):this.simulationSpace==="world"&&(e.position.applyMatrix4(this.matrixWorld),e.velocity.applyQuaternion(this.getWorldQuaternion(this.tempQuatWorld))),r&&e.velocity.addScaledVector(r,1);let a=1-this.sizeRandomness+Math.random()*this.sizeRandomness;e.size=Math.max(.001,this.particleSize*a),e.trailHead=0,e.trailLen=0,e.trailTimer=0,this.trailEnabled&&this.trailData&&t>=0&&(this.writeTrailSample(t,e),e.trailLen=1)}assignSpawnPosition(e){if(this.emitterShape==="sphere"){this.tempDirection.set(R.randFloatSpread(2),R.randFloatSpread(2),R.randFloatSpread(2)),this.tempDirection.lengthSq()<1e-5&&this.tempDirection.copy(Df),this.tempDirection.normalize().multiplyScalar(Math.random()*this.emitterRadius),e.copy(this.tempDirection);return}if(this.emitterShape==="box"){e.set(R.randFloatSpread(this.emitterBoxSize.x),R.randFloatSpread(this.emitterBoxSize.y),R.randFloatSpread(this.emitterBoxSize.z));return}e.set(0,0,0)}updateParticles(e){if(!this.instancedMesh)return;this.startColorVec.set(this.startColor),this.endColorVec.set(this.endColor);let t=0;for(let i=0;i<this.particles.length;i+=1){let r=this.particles[i];if(!r.active)continue;if(r.age+=e,r.age>=r.lifetime){r.active=!1,this.subEmitterId!==""&&this.recordDeath(r);continue}this.tempVelocity.set(this.gravity.x,this.gravity.y,this.gravity.z).multiplyScalar(e),r.velocity.add(this.tempVelocity),r.position.addScaledVector(r.velocity,e),r.rotation+=r.angularVelocity*e,this.trailEnabled&&this.trailData&&this.advanceTrailSampling(i,r,e);let o=R.clamp(r.age/r.lifetime,0,1),s=R.lerp(this.startAlpha,this.endAlpha,o);this.tempColor.copy(this.startColorVec).lerp(this.endColorVec,o),this.tempQuat.identity(),(!this.billboard||this.particleShape!=="plane")&&this.tempQuat.setFromAxisAngle(Rs,r.rotation),this.tempScale.set(r.size,r.size,r.size),this.tempMatrix.compose(r.position,this.tempQuat,this.tempScale),this.instancedMesh.setMatrixAt(t,this.tempMatrix),this.instanceColorAttr.setXYZ(t,this.tempColor.r,this.tempColor.g,this.tempColor.b),this.instanceAlphaAttr.setX(t,s),t+=1}this.activeCount=t,this.instancedMesh.count=t,this.instancedMesh.instanceMatrix.needsUpdate=!0,this.instanceColorAttr.needsUpdate=!0,this.instanceAlphaAttr.needsUpdate=!0,this.flushSubEmission()}buildRenderGeometry(){return this.particleShape==="cube"?new rr(1,1,1):this.particleShape==="sphere"?new es(.5,8,8):new z(1,1)}rebuildRenderer(){this.instancedMesh&&(this.renderRoot.remove(this.instancedMesh),this.instancedMesh.geometry.dispose());let e=this.buildRenderGeometry();this.instancedMesh=new tr(e,this.material,this.maxParticles),this.instancedMesh.instanceMatrix.setUsage(oe),this.instancedMesh.frustumCulled=!1,this.instancedMesh.count=0,this.instancedMesh.instanceColor=this.instanceColorAttr,this.instancedMesh.geometry.setAttribute("instanceAlpha",this.instanceAlphaAttr),this.renderRoot.add(this.instancedMesh)}configureMaterialForInstanceAlpha(){this.material.onBeforeCompile=e=>{e.vertexShader=e.vertexShader.replace("#include <color_pars_vertex>",`#include <color_pars_vertex>
189
+ attribute float instanceAlpha;
190
+ varying float vInstanceAlpha;`).replace("#include <color_vertex>",`#include <color_vertex>
191
+ vInstanceAlpha = instanceAlpha;`),e.fragmentShader=e.fragmentShader.replace("#include <color_pars_fragment>",`#include <color_pars_fragment>
192
+ varying float vInstanceAlpha;`).replace("vec4 diffuseColor = vec4( diffuse, opacity );","vec4 diffuseColor = vec4( diffuse, opacity * vInstanceAlpha );")},this.material.customProgramCacheKey=()=>"pix3-particles3d-instance-alpha-v1",this.material.needsUpdate=!0}syncWorldCompensation(){if(this.simulationSpace!=="world")return;this.updateWorldMatrix(!0,!1);let e=this.matrixWorld.determinant();Math.abs(e)<1e-8||(this.tempMatInv.copy(this.matrixWorld).invert(),this.renderRoot.matrix.copy(this.tempMatInv),this.renderRoot.matrixWorldNeedsUpdate=!0)}setSimulationSpace(e){e!==this.simulationSpace&&(this.simulationSpace=e,this.restart(),e==="world"?(this.renderRoot.matrixAutoUpdate=!1,this.syncWorldCompensation()):(this.renderRoot.matrix.identity(),this.renderRoot.matrixAutoUpdate=!0,this.renderRoot.matrixWorldNeedsUpdate=!0))}recordDeath(e){this.tempDeathPos.copy(e.position),this.tempDeathVel.copy(e.velocity),this.simulationSpace==="local"&&(this.tempDeathPos.applyMatrix4(this.matrixWorld),this.tempDeathVel.applyQuaternion(this.getWorldQuaternion(this.tempQuatWorld))),this.deathScratch.push(this.tempDeathPos.x,this.tempDeathPos.y,this.tempDeathPos.z,this.tempDeathVel.x,this.tempDeathVel.y,this.tempDeathVel.z)}flushSubEmission(){if(this.deathScratch.length===0)return;if(this.isPrewarming){this.deathScratch.length=0;return}let e=this.resolveSubEmitter();if(!e){this.deathScratch.length=0;return}let t=this.subEmitterInheritVelocity;for(let i=0;i+5<this.deathScratch.length;i+=6)this.tempDeathPos.set(this.deathScratch[i],this.deathScratch[i+1],this.deathScratch[i+2]),this.tempDeathVel.set(this.deathScratch[i+3],this.deathScratch[i+4],this.deathScratch[i+5]).multiplyScalar(t),e.emitBurstAt(this.tempDeathPos,this.subEmitterBurstCount,this.tempDeathVel);this.deathScratch.length=0}resolveSubEmitter(){let e=this.subEmitterId;if(!e)return this.subEmitterCache=null,this.subEmitterCacheId="",null;if(this.subEmitterCache&&this.subEmitterCacheId===e)return this.subEmitterCache;let t=null;if(this.scene)t=this.scene.findNode(e);else{let i=this;for(;i.parentNode;)i=i.parentNode;t=i.findNode(e)}return this.subEmitterCache=t instanceof n?t:null,this.subEmitterCacheId=e,this.subEmitterCache}emitBurstAt(e,t,i){let r=Math.max(0,Math.floor(t));if(r<=0)return;let o=this.tempBurstPos.copy(e),s;i&&(s=this.tempBurstVel.copy(i)),this.simulationSpace==="local"&&(this.updateWorldMatrix(!0,!1),this.tempMatInv.copy(this.matrixWorld).invert(),o.applyMatrix4(this.tempMatInv),s&&s.applyQuaternion(this.getWorldQuaternion(this.tempQuatWorld).invert()));let a=r;for(let l=0;l<this.particles.length&&a>0;l+=1){let c=this.particles[l];c.active||(this.activateParticle(c,l,o,s),a-=1)}}setTrailEnabled(e){let t=!!e;t!==this.trailEnabled&&(this.trailEnabled=t,t?(this.allocateTrailBuffers(),this.buildTrailMesh(),this.resetTrailState()):(this.disposeTrailMesh(),this.trailData=null,this.trailPositions=null,this.trailColors=null,this.trailIndices=null))}setTrailSegments(e){let t=R.clamp(Math.floor(e),Ef,Nf);t!==this.trailSegments&&(this.trailSegments=t,this.trailEnabled&&(this.allocateTrailBuffers(),this.buildTrailMesh(),this.resetTrailState()))}resetTrailState(){for(let e of this.particles)e.trailHead=0,e.trailLen=0,e.trailTimer=0}allocateTrailBuffers(){let e=this.trailSegments,t=this.maxParticles;this.trailData=new Float32Array(t*e*3),this.trailPositions=new Float32Array(t*e*2*3),this.trailColors=new Float32Array(t*e*2*4);let i=new Uint32Array(t*(e-1)*6),r=0;for(let o=0;o<t;o+=1){let s=o*e*2;for(let a=0;a<e-1;a+=1){let l=s+a*2,c=l+1,u=s+(a+1)*2,h=u+1;i[r]=l,i[r+1]=c,i[r+2]=u,i[r+3]=c,i[r+4]=h,i[r+5]=u,r+=6}}this.trailIndices=i}buildTrailMesh(){if(this.disposeTrailMesh(),!this.trailPositions||!this.trailColors||!this.trailIndices)return;let e=new ae,t=new ut(this.trailPositions,3);t.setUsage(oe);let i=new ut(this.trailColors,4);i.setUsage(oe),e.setAttribute("position",t),e.setAttribute("color",i),e.setIndex(new ut(this.trailIndices,1)),this.trailMaterial=new B({transparent:!0,depthWrite:!1,blending:ct,side:xe,vertexColors:!0}),this.trailMesh=new O(e,this.trailMaterial),this.trailMesh.frustumCulled=!1,this.trailMesh.name=`${this.name}-Trails`,this.renderRoot.add(this.trailMesh)}disposeTrailMesh(){this.trailMesh&&(this.renderRoot.remove(this.trailMesh),this.trailMesh.geometry.dispose(),this.trailMesh=null),this.trailMaterial&&(this.trailMaterial.dispose(),this.trailMaterial=null)}writeTrailSample(e,t){if(!this.trailData)return;let i=(e*this.trailSegments+t.trailHead)*3;this.trailData[i]=t.position.x,this.trailData[i+1]=t.position.y,this.trailData[i+2]=t.position.z}advanceTrailSampling(e,t,i){let r=this.trailSegments,o=this.trailLifetime/(r-1);if(o<=0)return;t.trailTimer+=i;let s=r;for(;t.trailTimer>=o&&s>0;)t.trailTimer-=o,t.trailHead=(t.trailHead+1)%r,this.writeTrailSample(e,t),t.trailLen=Math.min(t.trailLen+1,r),s-=1}readTrailPoint(e,t,i,r){if(i<=0||!this.trailData){r.copy(t.position);return}let o=this.trailSegments,s=Math.min(i,t.trailLen),a=((t.trailHead-(s-1))%o+o)%o,l=(e*o+a)*3;r.set(this.trailData[l],this.trailData[l+1],this.trailData[l+2])}writeTrailVertex(e,t,i,r,o,s){let a=this.trailPositions,l=this.trailColors;if(!a||!l)return;let c=e*3;a[c]=t.x,a[c+1]=t.y,a[c+2]=t.z;let u=e*4;l[u]=i,l[u+1]=r,l[u+2]=o,l[u+3]=s}collapseAllTrails(){if(!this.trailMesh||!this.trailPositions||!this.trailColors)return;this.trailPositions.fill(0),this.trailColors.fill(0);let e=this.trailMesh.geometry;e.getAttribute("position").needsUpdate=!0,e.getAttribute("color").needsUpdate=!0}updateTrailGeometry(e){if(!this.trailEnabled||!this.trailMesh||!this.trailData)return;let t=this.trailSegments;this.tempCamSim.copy(e),this.simulationSpace==="local"&&(this.updateWorldMatrix(!0,!1),this.tempMatInv.copy(this.matrixWorld).invert(),this.tempCamSim.applyMatrix4(this.tempMatInv)),this.startColorVec.set(this.startColor),this.endColorVec.set(this.endColor);let i=this.trailWidth/2;for(let o=0;o<this.particles.length;o+=1){let s=this.particles[o],a=o*t*2;if(!s.active||s.trailLen<1){for(let h=0;h<t;h+=1){let d=a+h*2;this.writeTrailVertex(d,bu,0,0,0,0),this.writeTrailVertex(d+1,bu,0,0,0,0)}continue}let l=R.clamp(s.age/s.lifetime,0,1),c=R.lerp(this.startAlpha,this.endAlpha,l);this.tempColor.copy(this.startColorVec).lerp(this.endColorVec,l);let u=s.trailLen;for(let h=0;h<t;h+=1){let d=a+h*2,p=d+1;if(h>u){this.writeTrailVertex(d,s.position,0,0,0,0),this.writeTrailVertex(p,s.position,0,0,0,0);continue}this.readTrailPoint(o,s,h,this.tempTrailP),this.readTrailPoint(o,s,Math.max(h-1,0),this.tempTrailPrev),this.readTrailPoint(o,s,Math.min(h+1,u),this.tempTrailNext),this.tempTrailDir.copy(this.tempTrailPrev).sub(this.tempTrailNext),this.tempTrailDir.lengthSq()<1e-10&&this.tempTrailDir.copy(Rs),this.tempTrailDir.normalize(),this.tempTrailView.copy(this.tempCamSim).sub(this.tempTrailP),this.tempTrailView.lengthSq()<1e-10&&this.tempTrailView.copy(Rs),this.tempTrailView.normalize(),this.tempTrailSide.copy(this.tempTrailDir).cross(this.tempTrailView);let f=h/(t-1);if(this.tempTrailSide.lengthSq()<1e-12){this.writeTrailVertex(d,this.tempTrailP,0,0,0,0),this.writeTrailVertex(p,this.tempTrailP,0,0,0,0);continue}this.tempTrailSide.normalize().multiplyScalar(i*(1-f));let m=c*(1-this.trailFade*f);this.tempTrailPrev.copy(this.tempTrailP).add(this.tempTrailSide),this.writeTrailVertex(d,this.tempTrailPrev,this.tempColor.r,this.tempColor.g,this.tempColor.b,m),this.tempTrailNext.copy(this.tempTrailP).sub(this.tempTrailSide),this.writeTrailVertex(p,this.tempTrailNext,this.tempColor.r,this.tempColor.g,this.tempColor.b,m)}}let r=this.trailMesh.geometry;r.getAttribute("position").needsUpdate=!0,r.getAttribute("color").needsUpdate=!0}static getPropertySchema(){let e=U.getPropertySchema();return{nodeType:"Particles3D",extends:"Node3D",properties:[...e.properties,{name:"texture",type:"object",ui:{label:"Texture",group:"Rendering",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.texture??{type:"texture",url:""},setValue:(t,i)=>t.setTextureResource(i)},{name:"particleShape",type:"enum",ui:{label:"Particle Shape",group:"Rendering",options:["plane","sphere","cube"]},getValue:t=>t.particleShape,setValue:(t,i)=>{let r=String(i);(r==="plane"||r==="sphere"||r==="cube")&&t.setParticleShape(r)}},{name:"particleSize",type:"number",ui:{label:"Particle Size",group:"Rendering",min:.01,max:5,step:.01,precision:2,slider:!0},getValue:t=>t.particleSize,setValue:(t,i)=>{t.particleSize=Math.max(.01,Number(i))}},{name:"sizeRandomness",type:"number",ui:{label:"Size Randomness",group:"Rendering",min:0,max:1,step:.01,precision:2,slider:!0},getValue:t=>t.sizeRandomness,setValue:(t,i)=>{t.sizeRandomness=R.clamp(Number(i),0,1)}},{name:"startColor",type:"color",ui:{label:"Start Color",group:"Rendering"},getValue:t=>t.startColor,setValue:(t,i)=>{t.startColor=String(i)}},{name:"endColor",type:"color",ui:{label:"End Color",group:"Rendering"},getValue:t=>t.endColor,setValue:(t,i)=>{t.endColor=String(i)}},{name:"startAlpha",type:"number",ui:{label:"Start Alpha",group:"Rendering",min:0,max:1,step:.01,precision:2,slider:!0},getValue:t=>t.startAlpha,setValue:(t,i)=>{t.startAlpha=R.clamp(Number(i),0,1)}},{name:"endAlpha",type:"number",ui:{label:"End Alpha",group:"Rendering",min:0,max:1,step:.01,precision:2,slider:!0},getValue:t=>t.endAlpha,setValue:(t,i)=>{t.endAlpha=R.clamp(Number(i),0,1)}},{name:"billboard",type:"boolean",ui:{label:"Billboard",group:"Rendering"},getValue:t=>t.billboard,setValue:(t,i)=>{t.billboard=!!i}},{name:"emitterShape",type:"enum",ui:{label:"Emitter Shape",group:"Emitter",options:["point","sphere","box"]},getValue:t=>t.emitterShape,setValue:(t,i)=>{let r=String(i);(r==="point"||r==="sphere"||r==="box")&&(t.emitterShape=r)}},{name:"emitterRadius",type:"number",ui:{label:"Emitter Radius",group:"Emitter",min:0,max:10,step:.01,precision:2,slider:!0},getValue:t=>t.emitterRadius,setValue:(t,i)=>{t.emitterRadius=Math.max(0,Number(i))}},{name:"emitterBoxSize",type:"vector3",ui:{label:"Emitter Box Size",group:"Emitter",step:.01,precision:2},getValue:t=>({...t.emitterBoxSize}),setValue:(t,i)=>{let r=i;t.emitterBoxSize={x:Math.max(0,Number(r.x)),y:Math.max(0,Number(r.y)),z:Math.max(0,Number(r.z))}}},{name:"emissionRate",type:"number",ui:{label:"Emission Rate",group:"Emission",min:0,max:1e3,step:1,precision:0,slider:!0},getValue:t=>t.emissionRate,setValue:(t,i)=>{t.emissionRate=Math.max(0,Number(i))}},{name:"maxParticles",type:"number",ui:{label:"Max Particles",group:"Emission",min:1,max:1e4,step:1,precision:0,slider:!0},getValue:t=>t.maxParticles,setValue:(t,i)=>t.setMaxParticles(Number(i))},{name:"lifetime",type:"number",ui:{label:"Lifetime",group:"Emission",unit:"s",min:.01,max:30,step:.01,precision:2,slider:!0},getValue:t=>t.lifetime,setValue:(t,i)=>{t.lifetime=Math.max(.01,Number(i))}},{name:"speed",type:"number",ui:{label:"Speed",group:"Emission",min:0,max:100,step:.01,precision:2,slider:!0},getValue:t=>t.speed,setValue:(t,i)=>{t.speed=Math.max(0,Number(i))}},{name:"speedSpread",type:"number",ui:{label:"Speed Spread",group:"Emission",min:0,max:20,step:.01,precision:2,slider:!0},getValue:t=>t.speedSpread,setValue:(t,i)=>{t.speedSpread=Math.max(0,Number(i))}},{name:"gravity",type:"vector3",ui:{label:"Gravity",group:"Emission",step:.01,precision:2},getValue:t=>({...t.gravity}),setValue:(t,i)=>{let r=i;t.gravity={x:Number(r.x),y:Number(r.y),z:Number(r.z)}}},{name:"disableRotation",type:"boolean",ui:{label:"Disable Rotation",group:"Emission"},getValue:t=>t.disableRotation,setValue:(t,i)=>{t.disableRotation=!!i}},{name:"playing",type:"boolean",ui:{label:"Playing",group:"Runtime"},getValue:t=>t.playing,setValue:(t,i)=>{t.playing=!!i}},{name:"loop",type:"boolean",ui:{label:"Loop",group:"Runtime"},getValue:t=>t.loop,setValue:(t,i)=>{t.loop=!!i}},{name:"prewarm",type:"boolean",ui:{label:"Prewarm",group:"Runtime"},getValue:t=>t.prewarm,setValue:(t,i)=>{t.prewarm=!!i}},{name:"preview",type:"boolean",ui:{label:"Preview",group:"Runtime"},getValue:t=>t.preview,setValue:(t,i)=>{let r=t,o=!!i;r.preview&&!o&&r.restart(),r.preview=o}},{name:"simulationSpace",type:"enum",ui:{label:"Simulation Space",group:"Runtime",options:["local","world"]},getValue:t=>t.simulationSpace,setValue:(t,i)=>{let r=String(i);(r==="local"||r==="world")&&t.setSimulationSpace(r)}},{name:"trailEnabled",type:"boolean",ui:{label:"Enable Trails",group:"Trails",description:"Draw a camera-facing ribbon behind each particle. Best with Simulation Space = world."},getValue:t=>t.trailEnabled,setValue:(t,i)=>{t.setTrailEnabled(!!i)}},{name:"trailLifetime",type:"number",ui:{label:"Trail Lifetime",group:"Trails",unit:"s",min:.05,max:5,step:.01,precision:2,slider:!0},getValue:t=>t.trailLifetime,setValue:(t,i)=>{t.trailLifetime=Math.max(.05,Number(i))}},{name:"trailWidth",type:"number",ui:{label:"Trail Width",group:"Trails",min:.001,max:2,step:.001,precision:3,slider:!0},getValue:t=>t.trailWidth,setValue:(t,i)=>{t.trailWidth=R.clamp(Number(i),.001,2)}},{name:"trailSegments",type:"number",ui:{label:"Trail Segments",group:"Trails",description:"Ribbon resolution. Keep Max Particles moderate when trails are enabled.",min:2,max:64,step:1,precision:0,slider:!0},getValue:t=>t.trailSegments,setValue:(t,i)=>{t.setTrailSegments(Number(i))}},{name:"trailFade",type:"number",ui:{label:"Trail Fade",group:"Trails",min:0,max:1,step:.01,precision:2,slider:!0},getValue:t=>t.trailFade,setValue:(t,i)=>{t.trailFade=R.clamp(Number(i),0,1)}},{name:"subEmitterId",type:"node",ui:{label:"Sub Emitter",group:"Sub Emitter",description:"Particles3D fired as a burst at each particle death (author it with Emission Rate = 0).",nodeTypes:["Particles3D"]},getValue:t=>t.subEmitterId,setValue:(t,i)=>{t.subEmitterId=i==null?"":String(i)}},{name:"subEmitterBurstCount",type:"number",ui:{label:"Burst Count",group:"Sub Emitter",min:0,max:128,step:1,precision:0,slider:!0},getValue:t=>t.subEmitterBurstCount,setValue:(t,i)=>{t.subEmitterBurstCount=R.clamp(Math.floor(Number(i)),0,128)}},{name:"subEmitterInheritVelocity",type:"number",ui:{label:"Inherit Velocity",group:"Sub Emitter",min:0,max:1,step:.01,precision:2,slider:!0},getValue:t=>t.subEmitterInheritVelocity,setValue:(t,i)=>{t.subEmitterInheritVelocity=R.clamp(Number(i),0,1)}}],groups:{...e.groups,Rendering:{label:"Rendering",description:"Particle rendering settings",expanded:!0},Emitter:{label:"Emitter",description:"Emitter shape and spawn volume",expanded:!0},Emission:{label:"Emission",description:"Emission rates and movement",expanded:!0},Runtime:{label:"Runtime",description:"Simulation runtime controls",expanded:!0},Trails:{label:"Trails",description:"Per-particle ribbon trails",expanded:!1},"Sub Emitter":{label:"Sub Emitter",description:"Burst another emitter on particle death",expanded:!1}}}}};function i0(n){if(typeof n!="object"||n===null)return!1;let e=n;return typeof e.getInteractions=="function"&&typeof e.invokeInteraction=="function"}function Ze(n,e,t=null){let i=n?.[e];if(i==null)return t;let r=bs("number",i);return typeof r=="number"&&Number.isFinite(r)?r:t}function Su(n,e,t=null){let i=n?.[e];if(i==null)return t;let r=bs("boolean",i);return typeof r=="boolean"?r:t}function r0(n,e,t=null){let i=n?.[e];if(typeof i!="string")return t;let r=i.trim();return r.length>0?r:t}var vu=-1,wu=-2,Pi=class n extends C{static BASE_OPACITY=.3;static HANDLE_OPACITY=.8;static FADE_SPEED=6;enabled;radius;handleRadius;axisHorizontal;axisVertical;baseColor;handleColor;floating;baseMesh;handleMesh;baseMaterial;handleMaterial;isDragging=!1;inputVector=new N;authoredLocalPosition=new S;dragCenterWorld=new N;visibilityAlpha=1;visibilityTarget=1;tmpWorldPos=new S;pendingResetAfterHide=!1;ownedPointerId=null;legacyPointerWasDown=!1;candidateWorld=new N;constructor(e){super(e,"Joystick2D");let t=this.properties.enabled;this.enabled=e.enabled??(typeof t=="boolean"?t:!0),this.radius=e.radius??50,this.handleRadius=e.handleRadius??20,this.axisHorizontal=e.axisHorizontal??"Horizontal",this.axisVertical=e.axisVertical??"Vertical",this.baseColor=e.baseColor??"#ffffff",this.handleColor=e.handleColor??"#cccccc",this.floating=e.floating??!1;let i=new Kl(this.radius,32);this.baseMaterial=new B({color:this.baseColor,transparent:!0,opacity:n.BASE_OPACITY,depthTest:!1}),this.registerOpacityMaterial(this.baseMaterial,n.BASE_OPACITY),this.baseMesh=new O(i,this.baseMaterial),this.baseMesh.renderOrder=999,this.add(this.baseMesh);let r=new Kl(this.handleRadius,32);this.handleMaterial=new B({color:this.handleColor,transparent:!0,opacity:n.HANDLE_OPACITY,depthTest:!1}),this.registerOpacityMaterial(this.handleMaterial,n.HANDLE_OPACITY),this.handleMesh=new O(r,this.handleMaterial),this.handleMesh.position.z=1,this.handleMesh.renderOrder=1e3,this.add(this.handleMesh),this.authoredLocalPosition.copy(this.position),this.floating&&(this.visibilityAlpha=0,this.visibilityTarget=0,this.applyVisibility()),H(this,n.getPropertySchema)}tick(e){super.tick(e),this.updateFromPointers(),this.floating&&this.updateVisibility(e)}updateFromPointers(){if(!this.enabled){this.abortDrag();return}let e=this.input,t=e&&e.width?this.collectCandidatePointers(e):[],i=t.length===1&&t[0].pointerId===wu?t[0]:null,r=i!==null&&i.down&&!this.legacyPointerWasDown;this.legacyPointerWasDown=i?.down??!1;let o=this.semanticPointer;if(o){let l=e?this.findClaimingPointer(e,t,r):null;if(!l){this.driveDragFrame({pointerId:vu,worldX:o.x,worldY:o.y,down:o.down},!1);return}this.semanticPointer=null,this.ownedPointerId=l.pointerId,this.driveDragFrame(l,!0);return}if(!e||t.length===0)return;let s=this.ownedPointerId;if(s!==null){let l=t.find(u=>u.pointerId===s);if(!l){this.finishOwnedPointer();return}let c=this.screenPointToWorld(l.x,l.y,this.candidateWorld);if(!c)return;this.driveDragFrame({pointerId:s,worldX:c.x,worldY:c.y,down:l.down},!1);return}let a=this.findClaimingPointer(e,t,r);a&&(this.ownedPointerId=a.pointerId,this.driveDragFrame(a,!0))}collectCandidatePointers(e){let t=e.getActivePointers();return t.length>0?t.map(i=>({pointerId:i.pointerId,x:i.x,y:i.y,down:!0})):[{pointerId:wu,x:e.pointerPosition.x,y:e.pointerPosition.y,down:e.isPointerDown}]}findClaimingPointer(e,t,i){for(let r of t){if(!r.down)continue;let o=r.pointerId===wu;if(this.floating&&(!(o?i:n.hasDownEventThisFrame(e,r.pointerId))||(o?e.isHoveringUI:e.isPointerOverUI(r.pointerId))))continue;let s=this.screenPointToWorld(r.x,r.y,this.candidateWorld);if(!s)return null;if(!(!this.floating&&!this.isWithinBase(s.x,s.y)))return{pointerId:r.pointerId,worldX:s.x,worldY:s.y,down:!0}}return null}static hasDownEventThisFrame(e,t){for(let i of e.pointerEvents)if(i.type==="down"&&i.pointerId===t)return!0;return!1}isWithinBase(e,t){this.getWorldPosition(this.tmpWorldPos);let i=e-this.tmpWorldPos.x,r=t-this.tmpWorldPos.y;return Math.sqrt(i*i+r*r)<this.radius}driveDragFrame(e,t){if(this.isDragging){e.down?this.continueDrag(e.worldX,e.worldY):this.releaseDrag();return}if(!(!t||!e.down)){if(this.floating){this.beginFloatingDrag(e.worldX,e.worldY),this.continueDrag(e.worldX,e.worldY);return}this.isDragging=!0}}beginFloatingDrag(e,t){this.isDragging=!0,this.pendingResetAfterHide=!1,this.handleMesh.position.set(0,0,this.handleMesh.position.z),this.setCenterFromWorld(e,t),this.visibilityTarget=1}continueDrag(e,t){if(this.floating){this.updateHandleAndAxes(e-this.dragCenterWorld.x,t-this.dragCenterWorld.y);return}this.getWorldPosition(this.tmpWorldPos),this.updateHandleAndAxes(e-this.tmpWorldPos.x,t-this.tmpWorldPos.y)}finishOwnedPointer(){this.releaseDrag()}releaseDrag(){this.semanticPointer=null,this.ownedPointerId=null,this.isDragging&&this.endDrag()}abortDrag(){!this.isDragging&&this.ownedPointerId===null&&this.semanticPointer===null||this.releaseDrag()}static DIRECTIONS={right:[1,0],left:[-1,0],up:[0,1],down:[0,-1],upright:[Math.SQRT1_2,Math.SQRT1_2],upleft:[-Math.SQRT1_2,Math.SQRT1_2],downright:[Math.SQRT1_2,-Math.SQRT1_2],downleft:[-Math.SQRT1_2,-Math.SQRT1_2]};semanticPointer=null;getInteractions(){return[{name:"setStick",description:"Push the stick in a direction and hold it there",args:[{name:"dir",type:"string",ui:{label:"Direction",description:"up/down/left/right/upleft/\u2026 or an angle in degrees (0 = right, CCW)",options:Object.keys(n.DIRECTIONS)}},{name:"magnitude",type:"number",defaultValue:1,ui:{label:"Magnitude",min:0,max:1,description:"0..1 of the stick radius"}}]},{name:"releaseStick",description:"Let go of the stick (axes return to zero)"}]}invokeInteraction(e,t){if(!this.enabled)return!1;switch(e){case"setStick":{let i=this.resolveDirection(t?.dir);if(!i)return!1;let r=Math.max(0,Math.min(1,Ze(t,"magnitude",1)??1));return this.pushStick(i,r)}case"releaseStick":return this.releaseStick();default:return!1}}resolveDirection(e){if(typeof e=="number"&&Number.isFinite(e)){let o=e*Math.PI/180;return[Math.cos(o),Math.sin(o)]}if(typeof e!="string")return null;let t=e.trim().toLowerCase().replace(/[\s_-]/g,""),i=n.DIRECTIONS[t];if(i)return i;let r=Number(t);if(Number.isFinite(r)&&t.length>0){let o=r*Math.PI/180;return[Math.cos(o),Math.sin(o)]}return null}pushStick(e,t){this.getWorldPosition(this.tmpWorldPos);let i=this.tmpWorldPos.x,r=this.tmpWorldPos.y;this.runSemanticStickFrame(i,r);let o=this.radius*t,s=i+e[0]*o,a=r+e[1]*o;return this.runSemanticStickFrame(s,a),!0}runSemanticStickFrame(e,t){this.semanticPointer={x:e,y:t,down:!0},this.ownedPointerId=vu;let i=this.floating||this.isWithinBase(e,t);this.driveDragFrame({pointerId:vu,worldX:e,worldY:t,down:!0},i),this.isDragging||(this.semanticPointer=null,this.ownedPointerId=null)}releaseStick(){return this.releaseDrag(),!0}updateHandleAndAxes(e,t){let i=Math.atan2(t,e),r=Math.sqrt(e*e+t*t),o=Math.min(r,this.radius),s=Math.cos(i)*o,a=Math.sin(i)*o;this.handleMesh.position.x=s,this.handleMesh.position.y=a,this.inputVector.set(s/this.radius,a/this.radius),this.input?.setAxis(this.axisHorizontal,this.inputVector.x),this.input?.setAxis(this.axisVertical,this.inputVector.y)}endDrag(){if(this.isDragging=!1,this.inputVector.set(0,0),this.input?.setAxis(this.axisHorizontal,0),this.input?.setAxis(this.axisVertical,0),this.floating){this.visibilityTarget=0,this.pendingResetAfterHide=!0;return}this.handleMesh.position.x=0,this.handleMesh.position.y=0}updateVisibility(e){let t=this.visibilityTarget-this.visibilityAlpha;if(Math.abs(t)<=Number.EPSILON){this.visibilityAlpha=this.visibilityTarget,this.applyVisibility();return}let i=Math.min(e,1/30),r=n.FADE_SPEED*i;Math.abs(t)<=r?this.visibilityAlpha=this.visibilityTarget:this.visibilityAlpha+=Math.sign(t)*r,this.applyVisibility(),this.visibilityAlpha===0&&this.pendingResetAfterHide&&(this.pendingResetAfterHide=!1,this.position.copy(this.authoredLocalPosition),this.handleMesh.position.x=0,this.handleMesh.position.y=0)}applyVisibility(){this.setOpacityMaterialBase(this.baseMaterial,n.BASE_OPACITY*this.visibilityAlpha),this.setOpacityMaterialBase(this.handleMaterial,n.HANDLE_OPACITY*this.visibilityAlpha)}setCenterFromWorld(e,t){this.position.set(e,t,this.position.z),this.dragCenterWorld.set(e,t)}static getPropertySchema(){let e=C.getPropertySchema();return{nodeType:"Joystick2D",extends:"Node2D",properties:[...e.properties,{name:"enabled",type:"boolean",ui:{label:"Enabled",group:"Joystick"},getValue:t=>t.enabled,setValue:(t,i)=>{let r=t;r.enabled=!!i,r.properties.enabled=r.enabled,r.enabled||r.abortDrag()}},{name:"radius",type:"number",ui:{label:"Radius",group:"Joystick"},getValue:t=>t.radius,setValue:(t,i)=>{t.radius=Number(i)}},{name:"floating",type:"boolean",ui:{label:"Floating Position",group:"Joystick"},getValue:t=>t.floating,setValue:(t,i)=>{let r=t;r.floating=!!i,r.semanticPointer=null,r.ownedPointerId=null,r.endDrag(),r.floating?(r.visibilityAlpha=0,r.visibilityTarget=0,r.pendingResetAfterHide=!1,r.position.copy(r.authoredLocalPosition),r.handleMesh.position.set(0,0,r.handleMesh.position.z)):(r.pendingResetAfterHide=!1,r.position.copy(r.authoredLocalPosition),r.handleMesh.position.set(0,0,r.handleMesh.position.z),r.visibilityAlpha=1,r.visibilityTarget=1),r.applyVisibility()}},{name:"axisHorizontal",type:"string",ui:{label:"Horz Axis",group:"Input"},getValue:t=>t.axisHorizontal,setValue:(t,i)=>{t.axisHorizontal=String(i)}},{name:"axisVertical",type:"string",ui:{label:"Vert Axis",group:"Input"},getValue:t=>t.axisVertical,setValue:(t,i)=>{t.axisVertical=String(i)}}],groups:{...e.groups,Joystick:{label:"Joystick",expanded:!0},Input:{label:"Input Mapping",expanded:!0}}}}};var n0=new Set(["serif","sans-serif","monospace","cursive","fantasy","system-ui","ui-serif","ui-sans-serif","ui-monospace","ui-rounded","math","emoji","fangsong","inherit","initial","unset"]),o0=/^-?[A-Za-z_][A-Za-z0-9_-]*$/;function If(n){let e=(n??"").trim();return e.length===0?"sans-serif":e.split(",").map(t=>t.trim()).filter(t=>t.length>0).map(t=>t.startsWith('"')||t.startsWith("'")||n0.has(t.toLowerCase())||o0.test(t)?t:`"${t.replace(/["\\]/g,"\\$&")}"`).join(", ")}function Rf(n){if(n==null)return"";if(typeof n=="number")return Number.isFinite(n)&&n>0?String(Math.round(n)):"";let e=n.trim().toLowerCase();return e.length===0||e==="normal"||e==="400"?"":e}function Bf(n,e,t){let i=Number.isFinite(n)&&n>0?n:16,r=Rf(t);return`${r?`${r} `:""}${i}px ${If(e)}`}function pn(n,e,t,i,r){if(e.length===0)return;let o=Math.max(0,r.outlineWidth??0),s=r.shadowColor?.trim()?r.shadowColor:"",a=r.shadowOffsetX??0,l=r.shadowOffsetY??0,c=Math.max(0,r.shadowBlur??0),u=Math.max(0,r.glowBlur??0),h=Math.max(0,Math.round(r.glowPasses??0));if(n.fillStyle=r.color,o>0&&(n.lineJoin="round",n.miterLimit=2,n.lineWidth=o*2,n.strokeStyle=r.outlineColor?.trim()?r.outlineColor:"#000000"),s&&(a!==0||l!==0||c>0)&&(n.save(),n.shadowColor=s,n.shadowOffsetX=a,n.shadowOffsetY=l,n.shadowBlur=c,o>0&&n.strokeText(e,t,i),n.fillText(e,t,i),n.restore()),o>0&&n.strokeText(e,t,i),u>0&&h>0){n.save(),n.shadowColor=r.glowColor?.trim()?r.glowColor:r.color,n.shadowBlur=u;for(let d=0;d<h;d++)n.fillText(e,t,i);n.restore()}n.fillText(e,t,i)}function ki(n,e){n.font=Bf(e.fontSize,e.fontFamily,e.fontWeight);let t=e.letterSpacing??0,i=n;t!==0&&"letterSpacing"in i?i.letterSpacing=`${t}px`:t===0&&i.letterSpacing&&(i.letterSpacing="0px")}function mn(n){let e=Math.max(0,n.outlineWidth??0),t=Math.max(0,n.glowBlur??0),r=!!n.shadowColor?.trim()?Math.max(Math.abs(n.shadowOffsetX??0),Math.abs(n.shadowOffsetY??0))+Math.max(0,n.shadowBlur??0):0;return e<=0&&t<=0&&r<=0?0:Math.ceil(t*1.5+e+r+2)}var ze="pix3Overlay2D",s0=[],a0=[],xu=0,l0=(n,e)=>n.z-e.z;function Of(n,e,t,i){let r=n.units[n.count];r?(r.obj=e,r.z=t,r.visible=i):n.units.push({obj:e,z:t,visible:i}),n.count++}function Vf(n){return!!(n.userData&&n.userData[ze])}function Lf(n){return n.obj?n.obj.renderOrder:0}function _f(n,e){let t=n.units;for(let i=e+1;i<n.count;i++){let r=t[i],o=Lf(r),s=i-1;for(;s>=e&&Lf(t[s])>o;)t[s+1]=t[s],s--;t[s+1]=r}}function Ff(n,e,t,i){n.renderOrder=e.next++;let r=t&&n.visible!==!1;i&&i(n,n.renderOrder,n.layers.isEnabled(3),r);let o=n.children;for(let s=0;s<o.length;s++)Ff(o[s],e,r,i)}function zf(n,e,t,i){let r=t&&n.visible!==!1,o=n.zAsRelative?i+n.zIndex:n.zIndex;o!==0&&(e.needsSort=!0);let s=n.children,a=s.length,l=e.count;for(let u=0;u<a;u++){let h=s[u];!(h instanceof C)&&!Vf(h)&&Of(e,h,o,r)}_f(e,l);for(let u=0;u<a;u++){let h=s[u];h instanceof C&&zf(h,e,r,o)}let c=e.count;for(let u=0;u<a;u++){let h=s[u];!(h instanceof C)&&Vf(h)&&Of(e,h,o,r)}_f(e,c)}function Bs(n,e){let t=xu===0;xu++;try{let i={units:t?s0:[],count:0,needsSort:!1};for(let s=0;s<n.length;s++){let a=n[s];a instanceof C&&zf(a,i,!0,0)}let r=i.units;if(i.needsSort){let s=t?a0:[];s.length=i.count;for(let a=0;a<i.count;a++)s[a]=r[a];s.sort(l0),r=s}let o={next:0};for(let s=0;s<i.count;s++){let a=r[s],l=a.obj;l&&Ff(l,o,a.visible,e)}for(let s=0;s<i.count;s++)i.units[s].obj=null}finally{xu--}}var Uf=-1,c0=-2,et=class n extends Ae{dragScrollEnabled;wheelScrollEnabled;inertiaEnabled;showScrollbar;wheelSensitivity;dragThreshold;inertiaDamping;scrollbarWidth;scrollbarMinHeight;scrollbarInset;scrollbarColor;scrollbarTrackColor;scrollbarThumbTexture;scrollbarTrackTexture;_scrollY;tmpWorldPos=new S;tmpWorldScale=new S;pointerWorld=new N;candidateWorld=new N;ownedPointerId=null;clippingPlanes=[new zr(new S(1,0,0),0),new zr(new S(-1,0,0),0),new zr(new S(0,1,0),0),new zr(new S(0,-1,0),0)];appliedClippingMaterials=new Set;childBasePositions=new Map;dragMode=null;pointerStartedInside=!1;pointerWasDown=!1;lastAppliedScrollY=0;lastPointerWorldY=0;pointerDownWorldY=0;pointerDownScrollY=0;scrollVelocity=0;thumbHeight=0;thumbCenterY=0;trackCenterX=0;trackGeometry;thumbGeometry;trackMaterial;thumbMaterial;trackMesh;thumbMesh;constructor(e){super(e,"ScrollContainer2D"),this.dragScrollEnabled=e.dragScrollEnabled??!0,this.wheelScrollEnabled=e.wheelScrollEnabled??!0,this.inertiaEnabled=e.inertiaEnabled??!0,this.showScrollbar=e.showScrollbar??!0,this.wheelSensitivity=e.wheelSensitivity??1,this.dragThreshold=Math.max(0,e.dragThreshold??6),this.inertiaDamping=Math.max(.01,e.inertiaDamping??14),this.scrollbarWidth=Math.max(2,e.scrollbarWidth??8),this.scrollbarMinHeight=Math.max(8,e.scrollbarMinHeight??24),this.scrollbarInset=Math.max(0,e.scrollbarInset??8),this.scrollbarColor=e.scrollbarColor??"#f5f7ff",this.scrollbarTrackColor=e.scrollbarTrackColor??"#ffffff",this.scrollbarThumbTexture=D(e.scrollbarThumbTexture??null),this.scrollbarTrackTexture=D(e.scrollbarTrackTexture??null),this._scrollY=Math.max(0,e.scrollY??0),this.trackGeometry=new z(this.scrollbarWidth,Math.max(1,this.height)),this.thumbGeometry=new z(this.scrollbarWidth,Math.max(1,this.height)),this.trackMaterial=new B({color:this.scrollbarTrackColor,transparent:!0,opacity:.18,depthTest:!1}),this.thumbMaterial=new B({color:this.scrollbarColor,transparent:!0,opacity:.92,depthTest:!1}),this.registerOpacityMaterial(this.trackMaterial,.18),this.registerOpacityMaterial(this.thumbMaterial,.92),this.trackMesh=new O(this.trackGeometry,this.trackMaterial),this.trackMesh.renderOrder=1e3,this.trackMesh.userData[ze]=!0,this.trackMesh.position.z=.25,this.trackMesh.visible=!1,this.trackMesh.name=`${this.name}-ScrollbarTrack`,this.add(this.trackMesh),this.thumbMesh=new O(this.thumbGeometry,this.thumbMaterial),this.thumbMesh.renderOrder=1001,this.thumbMesh.userData[ze]=!0,this.thumbMesh.position.z=.3,this.thumbMesh.visible=!1,this.thumbMesh.name=`${this.name}-ScrollbarThumb`,this.add(this.thumbMesh),H(this,n.getPropertySchema)}get scrollY(){return this._scrollY}set scrollY(e){let t=this.hasScrollableChildren()?this.getMaxScrollY():Number.POSITIVE_INFINITY,i=n.clampScroll(e,t);this._scrollY!==i&&(this._scrollY=i,this.properties.scrollY=i,this.syncScrollbarVisuals())}setScrollbarThumbTexture(e){e&&$(e),this.thumbMaterial.map=e,this.setOpacityMaterialBase(this.thumbMaterial,e?1:.92),this.thumbMaterial.needsUpdate=!0}setScrollbarTrackTexture(e){e&&$(e),this.trackMaterial.map=e,this.setOpacityMaterialBase(this.trackMaterial,e?1:.18),this.trackMaterial.needsUpdate=!0}setScrollbarThumbTextureRef(e){let t=D(e),i=this.scrollbarThumbTexture?.url!==t?.url;this.scrollbarThumbTexture=t,i&&!t&&this.setScrollbarThumbTexture(null)}setScrollbarTrackTextureRef(e){let t=D(e),i=this.scrollbarTrackTexture?.url!==t?.url;this.scrollbarTrackTexture=t,i&&!t&&this.setScrollbarTrackTexture(null)}hasActivePointerCapture(){return this.dragMode!==null}isPointInViewportBounds(e){this.getWorldPosition(this.tmpWorldPos),this.getWorldScale(this.tmpWorldScale);let t=this.width*Math.abs(this.tmpWorldScale.x)/2,i=this.height*Math.abs(this.tmpWorldScale.y)/2,r=Math.abs(e.x-this.tmpWorldPos.x),o=Math.abs(e.y-this.tmpWorldPos.y);return r<=t&&o<=i}getContentNode(){let e=this.getScrollableChildren();return e.length===1?e[0]:null}getContentHeight(){let e=this.getContentBounds();return e?Math.max(0,e.maxY-e.minY):0}getMaxScrollY(){let e=this.getContentBounds();if(!e)return 0;let t=-this.height/2;return Math.max(0,t-e.minY)}tick(e){this.updatePointerAndScroll(e),this.applyScrollOffset(),this.applyClippingPlanes(),this.syncScrollbarVisuals(),super.tick(e)}semanticPointer=null;static SEMANTIC_FRAME_DT=1/60;getInteractions(){return[{name:"scrollBy",description:"Drag the content by an offset",args:[{name:"delta",type:"number",ui:{label:"Delta",description:"Change in scroll offset, in scene units"}}]},{name:"scrollTo",description:"Drag the content to an absolute scroll offset",args:[{name:"offset",type:"number",ui:{label:"Offset",min:0,description:"Target scrollY"}}]},{name:"fling",description:"Flick the content and let inertia carry it",args:[{name:"velocity",type:"number",ui:{label:"Velocity",description:"Scene units per second at release"}}]}]}invokeInteraction(e,t){switch(e){case"scrollBy":{let i=Ze(t,"delta");return i===null?!1:this.dragScrollBy(i,0)}case"scrollTo":{let i=Ze(t,"offset");return i===null?!1:this.dragScrollBy(i-this.scrollY,0)}case"fling":{let i=Ze(t,"velocity");return i===null?!1:this.dragScrollBy(0,i)}default:return!1}}dragScrollBy(e,t){if(!this.dragScrollEnabled)return!1;let i=n.SEMANTIC_FRAME_DT;this.getWorldPosition(this.tmpWorldPos);let r=this.tmpWorldPos.x,o=this.tmpWorldPos.y,s=Math.sign(e||t||1);this.pointerWasDown=!1,this.dragMode=null,this.ownedPointerId=Uf;try{this.runSemanticScrollFrame(r,o,!0,i),this.dragMode!=="content"&&(o+=s*(this.dragThreshold+1),this.runSemanticScrollFrame(r,o,!0,i)),e!==0&&(o+=e,this.runSemanticScrollFrame(r,o,!0,i)),t!==0?(o+=t*i,this.runSemanticScrollFrame(r,o,!0,i)):this.runSemanticScrollFrame(r,o,!0,i),this.runSemanticScrollFrame(r,o,!1,i)}finally{this.semanticPointer=null,this.ownedPointerId=null}return!0}runSemanticScrollFrame(e,t,i,r){this.semanticPointer={x:e,y:t,down:i},this.updatePointerAndScroll(r),this.applyScrollOffset(),this.syncScrollbarVisuals()}static getPropertySchema(){let e=Ae.getPropertySchema();return{nodeType:"ScrollContainer2D",extends:"Group2D",properties:[...e.properties,{name:"scrollY",type:"number",ui:{label:"Scroll Y",group:"Scroll",min:0,step:1,precision:0},getValue:t=>t.scrollY,setValue:(t,i)=>{t.scrollY=Number(i)}},{name:"dragScrollEnabled",type:"boolean",ui:{label:"Drag Scroll",group:"Scroll"},getValue:t=>t.dragScrollEnabled,setValue:(t,i)=>{t.dragScrollEnabled=!!i}},{name:"wheelScrollEnabled",type:"boolean",ui:{label:"Wheel Scroll",group:"Scroll"},getValue:t=>t.wheelScrollEnabled,setValue:(t,i)=>{t.wheelScrollEnabled=!!i}},{name:"inertiaEnabled",type:"boolean",ui:{label:"Inertia",group:"Scroll"},getValue:t=>t.inertiaEnabled,setValue:(t,i)=>{t.inertiaEnabled=!!i}},{name:"showScrollbar",type:"boolean",ui:{label:"Show Scrollbar",group:"Scrollbar"},getValue:t=>t.showScrollbar,setValue:(t,i)=>{t.showScrollbar=!!i}},{name:"wheelSensitivity",type:"number",ui:{label:"Wheel Sensitivity",group:"Scroll",min:.1,step:.1,precision:2},getValue:t=>t.wheelSensitivity,setValue:(t,i)=>{t.wheelSensitivity=Math.max(.1,Number(i))}},{name:"dragThreshold",type:"number",ui:{label:"Drag Threshold",group:"Scroll",min:0,step:1,precision:0},getValue:t=>t.dragThreshold,setValue:(t,i)=>{t.dragThreshold=Math.max(0,Number(i))}},{name:"inertiaDamping",type:"number",ui:{label:"Inertia Damping",group:"Scroll",min:.01,step:.1,precision:2},getValue:t=>t.inertiaDamping,setValue:(t,i)=>{t.inertiaDamping=Math.max(.01,Number(i))}},{name:"scrollbarWidth",type:"number",ui:{label:"Width",group:"Scrollbar",min:2,step:1,precision:0},getValue:t=>t.scrollbarWidth,setValue:(t,i)=>{t.scrollbarWidth=Math.max(2,Number(i))}},{name:"scrollbarMinHeight",type:"number",ui:{label:"Min Height",group:"Scrollbar",min:8,step:1,precision:0},getValue:t=>t.scrollbarMinHeight,setValue:(t,i)=>{t.scrollbarMinHeight=Math.max(8,Number(i))}},{name:"scrollbarInset",type:"number",ui:{label:"Inset",group:"Scrollbar",min:0,step:1,precision:0},getValue:t=>t.scrollbarInset,setValue:(t,i)=>{t.scrollbarInset=Math.max(0,Number(i))}},{name:"scrollbarColor",type:"color",ui:{label:"Thumb Color",group:"Scrollbar"},getValue:t=>t.scrollbarColor,setValue:(t,i)=>{let r=t;r.scrollbarColor=String(i),r.thumbMaterial.color.setStyle(r.scrollbarColor)}},{name:"scrollbarTrackColor",type:"color",ui:{label:"Track Color",group:"Scrollbar"},getValue:t=>t.scrollbarTrackColor,setValue:(t,i)=>{let r=t;r.scrollbarTrackColor=String(i),r.trackMaterial.color.setStyle(r.scrollbarTrackColor)}},{name:"scrollbarThumbTexture",type:"object",ui:{label:"Thumb Sprite",group:"Scrollbar",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.scrollbarThumbTexture??{type:"texture",url:""},setValue:(t,i)=>{t.setScrollbarThumbTextureRef(i)}},{name:"scrollbarTrackTexture",type:"object",ui:{label:"Track Sprite",group:"Scrollbar",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.scrollbarTrackTexture??{type:"texture",url:""},setValue:(t,i)=>{t.setScrollbarTrackTextureRef(i)}}],groups:{...e.groups,Scroll:{label:"Scroll",expanded:!0},Scrollbar:{label:"Scrollbar",expanded:!0}}}}disposeResources(){this.clearClippingPlanes(),this.trackGeometry.dispose(),this.thumbGeometry.dispose(),this.trackMaterial.dispose(),this.thumbMaterial.dispose()}updatePointerAndScroll(e){let t=this.input,i=this.semanticPointer,r,o;if(i)this.pointerWorld.set(i.x,i.y),r=i.down,o=Uf;else{if(!t){this.pointerWasDown=!1,this.ownedPointerId=null;return}let l=this.resolveDrivingPointer(t);if(!l){this.pointerWasDown=!1;return}this.pointerWorld.set(l.worldX,l.worldY),r=l.down,o=l.pointerId}let s=this.pointerWorld,a=this.isPointInViewportBounds(s);if((a||this.dragMode!==null)&&(o>=0?t?.registerHover(this.nodeId,o):t?.registerHover(this.nodeId)),!this.pointerWasDown&&r?(this.pointerStartedInside=a,this.pointerDownWorldY=s.y,this.lastPointerWorldY=s.y,this.pointerDownScrollY=this.scrollY,this.scrollVelocity=0,a&&this.isPointInThumbBounds(s)&&(this.dragMode="thumb")):this.pointerWasDown&&!r&&(this.pointerStartedInside=!1,this.dragMode=null,this.ownedPointerId=null),this.wheelScrollEnabled&&t&&a&&t.wheelDelta.y!==0&&(this.scrollY+=t.wheelDelta.y*this.wheelSensitivity,this.scrollVelocity=0),r&&this.dragMode==="thumb"){let l=Math.max(1,this.height-this.thumbHeight),c=Math.max(0,this.getMaxScrollY());if(c>0){let u=this.pointerWorld.y-this.pointerDownWorldY;this.scrollY=this.pointerDownScrollY-u*c/l}}else if(this.dragScrollEnabled&&r&&this.pointerStartedInside){let l=this.pointerWorld.y-this.pointerDownWorldY;if(this.dragMode==="content"){let c=this.pointerWorld.y-this.lastPointerWorldY;this.scrollY+=c;let u=Math.max(1/240,e);this.scrollVelocity=c/u}else Math.abs(l)>=this.dragThreshold&&this.getMaxScrollY()>0&&(this.dragMode="content",this.lastPointerWorldY=this.pointerWorld.y)}else if(!r&&this.dragMode===null&&this.inertiaEnabled&&Math.abs(this.scrollVelocity)>.5){let l=Math.exp(-this.inertiaDamping*Math.max(0,e)),c=this.scrollVelocity*(1+l)*.5;this.scrollY+=c*Math.max(0,e),this.scrollVelocity*=l,Math.abs(this.scrollVelocity)<.5&&(this.scrollVelocity=0)}!r&&(this.scrollY<=0||this.scrollY>=this.getMaxScrollY())&&(this.scrollVelocity=0),this.lastPointerWorldY=this.pointerWorld.y,this.pointerWasDown=r,this.scrollY=this._scrollY}resolveDrivingPointer(e){let t=this.collectCandidatePointers(e),i=this.ownedPointerId;if(i!==null){let o=t.find(s=>s.pointerId===i);return o?this.resolveCandidate(o):this.finishOwnedPointer(e,i)}let r=null;for(let o of t){let s=this.resolveCandidate(o);if(!s)continue;let a=this.isPointInViewportBounds(this.candidateWorld);if(o.down&&a)return this.ownedPointerId=o.pointerId,s;if((a||r===null)&&(r={...s,down:!1}),a)break}return r}collectCandidatePointers(e){let t=e.getActivePointers();return t.length>0?t.map(i=>({pointerId:i.pointerId,x:i.x,y:i.y,down:!0})):[{pointerId:c0,x:e.pointerPosition.x,y:e.pointerPosition.y,down:e.isPointerDown}]}resolveCandidate(e){let t=this.screenPointToWorld(e.x,e.y,this.candidateWorld);return t?{pointerId:e.pointerId,worldX:t.x,worldY:t.y,down:e.down}:null}finishOwnedPointer(e,t){let i=n.findTerminalEvent(e,t);if(i?.type==="up"){let r=this.screenPointToWorld(i.x,i.y,this.candidateWorld);if(r)return{pointerId:t,worldX:r.x,worldY:r.y,down:!1}}else this.scrollVelocity=0;return{pointerId:t,worldX:this.pointerWorld.x,worldY:this.pointerWorld.y,down:!1}}static findTerminalEvent(e,t){let i=e.pointerEvents;for(let r=i.length-1;r>=0;r-=1){let o=i[r];if(o.pointerId===t&&(o.type==="up"||o.type==="cancel"))return o}return null}getScrollableChildren(){let e=[];for(let t of this.children)t instanceof C&&e.push(t);return e}hasScrollableChildren(){return this.getScrollableChildren().length>0}applyScrollOffset(){let e=this.getScrollableChildren();if(e.length===0){this.lastAppliedScrollY=0;return}let t=n.clampScroll(this._scrollY,this.getMaxScrollY());n.areClose(this._scrollY,t)||(this._scrollY=t);for(let i of e){let r=this.syncChildBasePosition(i);i.position.set(r.x,r.y+t,r.z)}this.lastAppliedScrollY=t}syncChildBasePosition(e){let t=this.childBasePositions.get(e.nodeId);if(!t){let r=e.position.clone();return this.childBasePositions.set(e.nodeId,r),r}let i=t.y+this.lastAppliedScrollY;return(!n.areClose(e.position.x,t.x)||!n.areClose(e.position.z,t.z)||!n.areClose(e.position.y,i))&&t.set(e.position.x,e.position.y-this.lastAppliedScrollY,e.position.z),t}applyClippingPlanes(){let e=this.getScrollableChildren();if(e.length===0){this.clearClippingPlanes();return}this.getWorldPosition(this.tmpWorldPos),this.getWorldScale(this.tmpWorldScale);let t=this.width*Math.abs(this.tmpWorldScale.x)/2,i=this.height*Math.abs(this.tmpWorldScale.y)/2,r=this.tmpWorldPos.x-t,o=this.tmpWorldPos.x+t,s=this.tmpWorldPos.y-i,a=this.tmpWorldPos.y+i;this.clippingPlanes[0].constant=-r,this.clippingPlanes[1].constant=o,this.clippingPlanes[2].constant=-s,this.clippingPlanes[3].constant=a;let l=new Set;for(let c of e)c.traverse(u=>{let h=u;if(!h.material)return;let d=Array.isArray(h.material)?h.material:[h.material];for(let p of d)p.clippingPlanes=this.clippingPlanes,p.clipIntersection=!1,p.needsUpdate=!0,l.add(p)});for(let c of this.appliedClippingMaterials)l.has(c)||(c.clippingPlanes=null,c.needsUpdate=!0);this.appliedClippingMaterials.clear();for(let c of l)this.appliedClippingMaterials.add(c)}clearClippingPlanes(){for(let e of this.appliedClippingMaterials)e.clippingPlanes=null,e.needsUpdate=!0;this.appliedClippingMaterials.clear()}syncScrollbarVisuals(){let e=this.getContentHeight(),t=this.getMaxScrollY(),i=this.showScrollbar&&e>this.height+.001;if(this.trackMesh.visible=i,this.thumbMesh.visible=i,!i)return;this.trackCenterX=this.width/2-this.scrollbarInset-this.scrollbarWidth/2;let r=Math.max(1,this.height),o=r/Math.max(r,e);this.thumbHeight=Math.max(this.scrollbarMinHeight,Math.min(r,r*o));let s=Math.max(0,r-this.thumbHeight),a=t>0?Math.min(1,this.scrollY/t):0;this.thumbCenterY=r/2-this.thumbHeight/2-a*s,this.trackMesh.position.set(this.trackCenterX,0,.25),this.thumbMesh.position.set(this.trackCenterX,this.thumbCenterY,.3),(!n.areClose(this.trackGeometry.parameters.width,this.scrollbarWidth)||!n.areClose(this.trackGeometry.parameters.height,r))&&(this.trackGeometry.dispose(),this.trackGeometry=new z(this.scrollbarWidth,r),this.trackMesh.geometry=this.trackGeometry),(!n.areClose(this.thumbGeometry.parameters.width,this.scrollbarWidth)||!n.areClose(this.thumbGeometry.parameters.height,this.thumbHeight))&&(this.thumbGeometry.dispose(),this.thumbGeometry=new z(this.scrollbarWidth,this.thumbHeight),this.thumbMesh.geometry=this.thumbGeometry),this.trackMaterial.color.setStyle(this.scrollbarTrackColor),this.thumbMaterial.color.setStyle(this.scrollbarColor)}getContentBounds(){let e=this.getScrollableChildren();if(e.length===0)return null;let t=Number.POSITIVE_INFINITY,i=Number.NEGATIVE_INFINITY;for(let r of e){let o=this.syncChildBasePosition(r),s=this.getChildVerticalExtents(r);t=Math.min(t,o.y+s.minY),i=Math.max(i,o.y+s.maxY)}return!Number.isFinite(t)||!Number.isFinite(i)?null:{minY:t,maxY:i}}getChildVerticalExtents(e){let t=e.getCurrentLayoutSize(),i=Math.max(0,t.height),r=e,o=n.clampNormalizedAnchor(r.anchor?.y??.5);return{minY:-o*i,maxY:(1-o)*i}}isPointInThumbBounds(e){if(!this.showScrollbar||!this.thumbMesh.visible)return!1;this.getWorldPosition(this.tmpWorldPos),this.getWorldScale(this.tmpWorldScale);let t=this.tmpWorldPos.x+this.trackCenterX*this.tmpWorldScale.x,i=this.tmpWorldPos.y+this.thumbCenterY*this.tmpWorldScale.y,r=this.scrollbarWidth*Math.abs(this.tmpWorldScale.x)/2,o=this.thumbHeight*Math.abs(this.tmpWorldScale.y)/2;return e.x>=t-r&&e.x<=t+r&&e.y>=i-o&&e.y<=i+o}static areClose(e,t){return Math.abs(e-t)<=.001}static clampScroll(e,t){let i=Number.isFinite(e)?e:0,r=Number.isFinite(t)?Math.max(0,t):i;return Math.max(0,Math.min(i,r))}static clampNormalizedAnchor(e){return Number.isFinite(e)?Math.max(0,Math.min(1,e)):.5}};var fr=-1,u0=-2,Z=class n extends C{acceptsPointerInput=!0;_enabled=!0;_label;_labelKey;_labelFontFamily;_labelFontSize;_labelColor;_labelAlign;_labelFontWeight;_labelOutlineWidth;_labelOutlineColor;_labelShadowColor;_labelShadowOffsetX;_labelShadowOffsetY;_labelLetterSpacing;labelReactive=!1;texturePath;get label(){return this._label}set label(e){this._label!==e&&(this._label=e,this.refreshLabelIfReactive())}get labelKey(){return this._labelKey}set labelKey(e){this._labelKey!==e&&(this._labelKey=e,this.refreshLabelIfReactive())}get labelFontFamily(){return this._labelFontFamily}set labelFontFamily(e){this._labelFontFamily!==e&&(this._labelFontFamily=e,this.refreshLabelIfReactive())}get labelFontSize(){return this._labelFontSize}set labelFontSize(e){this._labelFontSize!==e&&(this._labelFontSize=e,this.refreshLabelIfReactive())}get labelColor(){return this._labelColor}set labelColor(e){this._labelColor!==e&&(this._labelColor=e,this.refreshLabelIfReactive())}get labelFontWeight(){return this._labelFontWeight}set labelFontWeight(e){this._labelFontWeight!==e&&(this._labelFontWeight=e,this.refreshLabelIfReactive())}get labelOutlineWidth(){return this._labelOutlineWidth}set labelOutlineWidth(e){let t=Math.max(0,Number.isFinite(e)?e:0);this._labelOutlineWidth!==t&&(this._labelOutlineWidth=t,this.refreshLabelIfReactive())}get labelOutlineColor(){return this._labelOutlineColor}set labelOutlineColor(e){this._labelOutlineColor!==e&&(this._labelOutlineColor=e,this.refreshLabelIfReactive())}get labelShadowColor(){return this._labelShadowColor}set labelShadowColor(e){let t=e&&e.trim().length>0?e:null;this._labelShadowColor!==t&&(this._labelShadowColor=t,this.refreshLabelIfReactive())}get labelShadowOffsetX(){return this._labelShadowOffsetX}set labelShadowOffsetX(e){let t=Number.isFinite(e)?e:0;this._labelShadowOffsetX!==t&&(this._labelShadowOffsetX=t,this.refreshLabelIfReactive())}get labelShadowOffsetY(){return this._labelShadowOffsetY}set labelShadowOffsetY(e){let t=Number.isFinite(e)?e:0;this._labelShadowOffsetY!==t&&(this._labelShadowOffsetY=t,this.refreshLabelIfReactive())}get labelLetterSpacing(){return this._labelLetterSpacing}set labelLetterSpacing(e){let t=Number.isFinite(e)?e:0;this._labelLetterSpacing!==t&&(this._labelLetterSpacing=t,this.refreshLabelIfReactive())}get labelAlign(){return this._labelAlign}set labelAlign(e){this._labelAlign!==e&&(this._labelAlign=e,this.refreshLabelIfReactive())}refreshLabelIfReactive(){this.labelReactive&&this.updateLabel()}isHovering=!1;isPressed=!1;tmpWorldPos=new S;onHoverEnter;onHoverExit;onPressed;onReleased;labelMesh=null;labelTexture=null;skinTexture=null;skinMaterials=new Set;constructor(e,t){super(e,t),this._enabled=e.enabled??!0,this._label=e.label??"",this._labelKey=e.labelKey??"",this._labelFontFamily=e.labelFontFamily??"Arial",this._labelFontSize=e.labelFontSize??16,this._labelColor=e.labelColor??"#ffffff",this._labelAlign=e.labelAlign??"center",this._labelFontWeight=e.labelFontWeight??"normal",this._labelOutlineWidth=Math.max(0,e.labelOutlineWidth??0),this._labelOutlineColor=e.labelOutlineColor??"#000000",this._labelShadowColor=e.labelShadowColor?.trim()?e.labelShadowColor:null,this._labelShadowOffsetX=e.labelShadowOffsetX??0,this._labelShadowOffsetY=e.labelShadowOffsetY??0,this._labelLetterSpacing=e.labelLetterSpacing??0,this.texturePath=e.texturePath??null,this.texturePath&&this.tryLoadTextureFromPath(this.texturePath),(this._label.trim().length>0||this._labelKey.length>0)&&this.updateLabel(),this.labelReactive=!0}disposeResources(){super.disposeResources(),this.labelTexture?.dispose(),this.labelTexture=null}get enabled(){return this._enabled}set enabled(e){let t=!!e;this._enabled!==t&&(this._enabled=t,this.onEnabledChanged(t))}onEnabledChanged(e){}registerSkinMaterial(e){this.registerOpacityMaterial(e),this.skinMaterials.add(e),this.skinTexture&&(e.map=this.skinTexture,e.color.set("#ffffff"),e.transparent=!0,e.needsUpdate=!0)}applySkinTexture(e){this.skinTexture=e;for(let t of this.skinMaterials)t.map=e,e&&(t.color.set("#ffffff"),t.transparent=!0),t.needsUpdate=!0}tryLoadTextureFromPath(e){let t=/^([a-z]+[a-z0-9+.-]*):\/\//i.exec(e),i=t?t[1].toLowerCase():"";if(!(i===""||i==="http"||i==="https"))return;new nr().load(e,o=>{$(o),this.applySkinTexture(o)},void 0,()=>{})}isPointInBounds(e){return!1}updatePointerStateFromInput(){let e=this.input,t=this.semanticPointer;if(t){let s=e?this.collectCandidatePointers(e):null,a=s?this.findClaimingPointer(s):null;return a?(this.semanticPointer=null,this.ownedPointerId=null,this.driveWithPointer(a)):(this.currentPointerId=fr,this.updatePointerState(t.x,t.y,t.down),this.currentPointerId=null,!0)}if(!e)return!1;let i=this.collectCandidatePointers(e),r=this.ownedPointerId;if(r!==null){let s=i.find(a=>a.pointerId===r);if(s){let a=this.resolveCandidate(s);return a?this.driveWithPointer(a):!1}return this.finishOwnedPointer(r)}let o=this.findClaimingPointer(i);return o?this.driveWithPointer(o):this.observeWithoutOwnership(i)}collectCandidatePointers(e){let t=e.getActivePointers();return t.length>0?t.map(i=>({pointerId:i.pointerId,x:i.x,y:i.y,down:!0})):[{pointerId:u0,x:e.pointerPosition.x,y:e.pointerPosition.y,down:e.isPointerDown}]}resolveCandidate(e){let t=this.screenPointToWorld(e.x,e.y,this.candidateWorld);return t?{pointerId:e.pointerId,down:e.down,worldX:t.x,worldY:t.y,screenX:e.x,screenY:e.y}:null}findClaimingPointer(e){if(!this.enabled||!this.isVisibleInTree())return null;for(let t of e){if(!t.down)continue;let i=this.resolveCandidate(t);if(!i)return null;if(this.isPointInBounds(this.candidateWorld)&&this.isPointerAllowedByAncestorScrollContainers(this.candidateWorld)&&this.input?.claimUIPointer(t.pointerId,this,()=>this.findPointerTarget(t)))return i}return null}findPointerTarget(e){let t=this;for(;t.parent;)t=t.parent;let i=this.scene?.getRootNodes(),r=i?.length?i:[t],o=null,s=-1,a=-1/0;for(let l of r)l.traverse(c=>{if(c instanceof Qe){if(!c.blocksPointerAt(e.x,e.y))return}else if(c instanceof n){if(!c.acceptsPointerInput||!c.enabled||!c.isVisibleInTree())return;let p=c.screenPointToWorld(e.x,e.y,c.candidateWorld);if(!p||!c.isPointInBounds(p)||!c.isPointerAllowedByAncestorScrollContainers(p))return}else return;let u=c,h=0;for(;u;){if(u.isCanvasLayer){h=1;break}if(!(u.parent instanceof C))break;u=u.parent}let d=c.effectiveZIndex;(h>s||h===s&&d>=a)&&(o=c,s=h,a=d)});return o}driveWithPointer(e){let t=this.getPhysicalHoverTarget(e);return t!==this&&(!this.capturesPointer()||t instanceof Qe)?(this.cancelPointerInteraction(),!0):(this.ownedPointerId=e.pointerId,this.currentPointerId=e.pointerId,this.updatePointerState(e.worldX,e.worldY,e.down),this.ownedPointerId!==fr&&!this.isPressed&&(this.ownedPointerId=null),!0)}finishOwnedPointer(e){let t=this.findTerminalEvent(e);if(this.ownedPointerId=null,this.currentPointerId=null,t?.type==="up"){let i=this.screenPointToWorld(t.x,t.y,this.candidateWorld);if(i)return this.getPhysicalHoverTarget({pointerId:e,down:!1,worldX:i.x,worldY:i.y,screenX:t.x,screenY:t.y})!==this&&!this.capturesPointer()?(this.cancelPointerInteraction(),!0):(this.currentPointerId=e,this.updatePointerState(i.x,i.y,!1),this.currentPointerId=null,!0)}return this.cancelPointerInteraction(),!0}findTerminalEvent(e){let t=this.input?.pointerEvents;if(!t)return null;for(let i=t.length-1;i>=0;i-=1){let r=t[i];if(r.pointerId===e&&(r.type==="up"||r.type==="cancel"))return r}return null}observeWithoutOwnership(e){if(!this.enabled||!this.isVisibleInTree())return this.cancelPointerInteraction(),!0;let t=null;for(let i of e){let r=this.resolveCandidate(i);if(r&&this.isPointInBounds(this.candidateWorld)&&this.getPhysicalHoverTarget(r)===this){t=r;break}}return t?(this.currentPointerId=t.pointerId,this.updatePointerState(t.worldX,t.worldY,!1),this.currentPointerId=null,!0):(this.cancelPointerInteraction(),!0)}getPhysicalHoverTarget(e){return this.input?.getUIHoverTarget(e.pointerId,e.screenX,e.screenY,()=>this.findPointerTarget({pointerId:e.pointerId,x:e.screenX,y:e.screenY,down:e.down}))??null}ownedPointerId=null;currentPointerId=null;candidateWorld=new N;semanticPointer=null;get hasSemanticPointerHold(){return this.semanticPointer!==null}getSemanticPointerPoint(e=new N){return this.getWorldPosition(this.tmpWorldPos),e.set(this.tmpWorldPos.x,this.tmpWorldPos.y)}runSemanticPointerFrame(e,t,i){return this.canAcceptSemanticPointer(e)?(this.semanticPointer=i?{x:e.x,y:e.y,down:t}:null,this.ownedPointerId=i?fr:null,this.currentPointerId=fr,this.updatePointerState(e.x,e.y,t),this.currentPointerId=null,!0):!1}canAcceptSemanticPointer(e=this.getSemanticPointerPoint()){return this.enabled&&this.isVisibleInTree()&&this.isPointerAllowedByAncestorScrollContainers(e)}clearSemanticPointer(){this.semanticPointer=null,this.ownedPointerId===fr&&(this.ownedPointerId=null)}getInteractions(){return[{name:"hover",description:"Rest the pointer on the control (stays hovered)"},{name:"press",description:"Press and hold the control"},{name:"release",description:"Release a held press"},{name:"click",description:"Press and release inside the control"}]}invokeInteraction(e,t){return this.performInteraction(e,t)}performInteraction(e,t){switch(e){case"hover":return this.runSemanticPointerFrame(this.getSemanticPointerPoint(),!1,!0);case"press":return this.runSemanticPointerFrame(this.getSemanticPointerPoint(),!0,!0);case"release":return this.runSemanticPointerFrame(this.getSemanticPointerPoint(),!1,!1);case"click":return this.runSemanticClick();default:return!1}}runSemanticClick(e=this.getSemanticPointerPoint()){return this.runSemanticPointerFrame(e,!0,!0)?this.runSemanticPointerFrame(e,!1,!1):!1}updatePointerState(e,t,i){if(!this.enabled){this.cancelPointerInteraction();return}if(!this.isVisibleInTree()){this.cancelPointerInteraction();return}let r=new N(e,t);if(!this.isPointerAllowedByAncestorScrollContainers(r)){this.cancelPointerInteraction();return}let o=this.isPointInBounds(r),s=this.isPressed&&this.capturesPointer();if(o&&!this.isHovering?(this.isHovering=!0,this.onHoverEnter?.(),this.onHover(!0)):!o&&this.isHovering&&(this.isHovering=!1,this.onHoverExit?.(),this.onHover(!1),this.isPressed&&!s&&(this.isPressed=!1,this.onReleased?.(),this.onPress(!1))),this.isHovering&&this.input){let a=this.currentPointerId;a!==null&&a>=0?this.input.registerHover(this.nodeId,a):this.input.registerHover(this.nodeId)}o&&i&&!this.isPressed?(this.isPressed=!0,this.emit("pointerdown"),this.emit("pressed"),this.onPressed?.(),this.onPress(!0)):!i&&this.isPressed&&(this.isPressed=!1,this.emit("pointerup"),this.emit("released"),o&&this.emit("click"),this.onReleased?.(),this.onPress(!1),o&&this.onClick()),this.isPressed&&i&&this.onPointerDrag(r)}cancelPointerInteraction(){this.semanticPointer=null,this.ownedPointerId=null,this.isHovering&&(this.isHovering=!1,this.onHoverExit?.(),this.onHover(!1)),this.isPressed&&(this.isPressed=!1,this.onReleased?.(),this.onPress(!1))}onHover(e){}onPress(e){}onClick(){}onPointerDrag(e){}capturesPointer(){return!1}isPointerAllowedByAncestorScrollContainers(e){let t=this.parent;for(;t;){if(t instanceof et&&(!t.isPointInViewportBounds(e)||t.hasActivePointerCapture()))return!1;t=t.parent}return!0}createLabelTexture(e,t=256,i=64){let r=typeof window<"u"&&window.devicePixelRatio||1,o=Math.max(1,Math.min(3,r)),s=document.createElement("canvas");s.width=Math.max(1,Math.round(t*o)),s.height=Math.max(1,Math.round(i*o));let a=s.getContext("2d");if(!a)throw new Error("Could not get canvas 2D context");a.setTransform(1,0,0,1,0,0),a.scale(o,o),a.fillStyle="rgba(0, 0, 0, 0)",a.fillRect(0,0,t,i),ki(a,{fontSize:this.labelFontSize,fontFamily:this.labelFontFamily,fontWeight:this.labelFontWeight,letterSpacing:this.labelLetterSpacing}),a.textBaseline="middle";let l=mn({outlineWidth:this.labelOutlineWidth,shadowColor:this.labelShadowColor,shadowOffsetX:this.labelShadowOffsetX,shadowOffsetY:this.labelShadowOffsetY}),c=t/2;this.labelAlign==="left"?(a.textAlign="left",c=10+l):this.labelAlign==="right"?(a.textAlign="right",c=t-10-l):a.textAlign="center",pn(a,e,c,i/2,{color:this.labelColor,outlineWidth:this.labelOutlineWidth,outlineColor:this.labelOutlineColor,shadowColor:this.labelShadowColor,shadowOffsetX:this.labelShadowOffsetX,shadowOffsetY:this.labelShadowOffsetY});let u=new It(s);return u.userData={...u.userData??{},logicalWidth:t,logicalHeight:i,dpr:o},$(u),u}getDisplayText(){return this.labelKey?on(this.labelKey,this.label):this.label}refreshLocalizedLabel(){this.updateLabel()}updateLabel(){let e=this.getDisplayText();if(!e){this.labelMesh&&(this.remove(this.labelMesh),this.labelMesh=null,this.labelTexture&&(this.labelTexture.dispose(),this.labelTexture=null));return}this.labelTexture&&(this.labelTexture.dispose(),this.labelTexture=null);let t=Math.max(128,Math.ceil(e.length*this.labelFontSize*.75)+24),i=Math.max(32,Math.ceil(this.labelFontSize*2));if(this.labelTexture=this.createLabelTexture(e,t,i),this.labelMesh)this.labelMesh.material.map=this.labelTexture,this.labelMesh.material.needsUpdate=!0;else{let r=new B({map:this.labelTexture,transparent:!0,depthTest:!1});this.registerOpacityMaterial(r,1);let o=new z(1,1);this.labelMesh=new O(o,r),this.labelMesh.renderOrder=1001,this.labelMesh.position.z=2,this.add(this.labelMesh)}if(this.labelMesh&&this.labelTexture){let r=this.labelTexture.image,o=this.labelTexture.userData??{},s=o.dpr??1,a=o.logicalWidth??r.width/s,l=o.logicalHeight??r.height/s;this.labelMesh.scale.set(a,l,1)}}static getPropertySchema(){let e=C.getPropertySchema();return{nodeType:"UIControl2D",extends:"Node2D",properties:[...e.properties,{name:"enabled",type:"boolean",ui:{label:"Enabled",group:"Control"},getValue:t=>t.enabled,setValue:(t,i)=>{t.enabled=!!i}},{name:"label",type:"string",ui:{label:"Label",group:"Label",description:"Text displayed on the control"},getValue:t=>t.label,setValue:(t,i)=>{t.label=String(i)}},{name:"labelKey",type:"string",ui:{label:"Label Key",group:"Label",editor:"localization-key",description:"Localization key; when set, its translation is shown instead of the literal label"},getValue:t=>t.labelKey,setValue:(t,i)=>{t.labelKey=String(i)}},{name:"labelFontSize",type:"number",ui:{label:"Font Size",group:"Label",min:8,max:200,step:1},getValue:t=>t.labelFontSize,setValue:(t,i)=>{t.labelFontSize=Number(i)}},{name:"labelFontFamily",type:"string",ui:{label:"Font Family",group:"Label",description:"A family registered by the project manifest, or a system font"},getValue:t=>t.labelFontFamily,setValue:(t,i)=>{t.labelFontFamily=String(i)}},{name:"labelFontWeight",type:"number",ui:{label:"Font Weight",group:"Label",min:100,max:900,step:100},getValue:t=>{let i=t.labelFontWeight;if(typeof i=="number")return i;let r=i.trim().toLowerCase();if(r==="bold")return 700;let o=Number(r);return Number.isFinite(o)&&o>0?o:400},setValue:(t,i)=>{t.labelFontWeight=Number(i)}},{name:"labelOutlineWidth",type:"number",ui:{label:"Outline Width",group:"Label",min:0,max:12,step:.5,description:"Half-width in px; the sticker outline the UI kit draws captions with"},getValue:t=>t.labelOutlineWidth,setValue:(t,i)=>{t.labelOutlineWidth=Number(i)}},{name:"labelOutlineColor",type:"color",ui:{label:"Outline Color",group:"Label"},getValue:t=>t.labelOutlineColor,setValue:(t,i)=>{t.labelOutlineColor=String(i)}},{name:"labelShadowColor",type:"color",ui:{label:"Shadow Color",group:"Label",description:"Empty = no drop shadow"},getValue:t=>t.labelShadowColor??"",setValue:(t,i)=>{let r=String(i).trim();t.labelShadowColor=r.length>0?r:null}},{name:"labelShadowOffsetY",type:"number",ui:{label:"Shadow Offset Y",group:"Label",min:-12,max:12,step:.5},getValue:t=>t.labelShadowOffsetY,setValue:(t,i)=>{t.labelShadowOffsetY=Number(i)}},{name:"labelShadowOffsetX",type:"number",ui:{label:"Shadow Offset X",group:"Label",min:-12,max:12,step:.5},getValue:t=>t.labelShadowOffsetX,setValue:(t,i)=>{t.labelShadowOffsetX=Number(i)}},{name:"labelLetterSpacing",type:"number",ui:{label:"Letter Spacing",group:"Label",min:-4,max:12,step:.1},getValue:t=>t.labelLetterSpacing,setValue:(t,i)=>{t.labelLetterSpacing=Number(i)}},{name:"labelColor",type:"color",ui:{label:"Font Color",group:"Label"},getValue:t=>t.labelColor,setValue:(t,i)=>{t.labelColor=String(i)}},{name:"labelAlign",type:"select",ui:{label:"Alignment",group:"Label",options:["left","center","right"]},getValue:t=>t.labelAlign,setValue:(t,i)=>{let r=String(i);(r==="left"||r==="center"||r==="right")&&(t.labelAlign=r)}},{name:"texturePath",type:"string",ui:{label:"Texture",group:"Skin",description:"Optional skin texture path (png/webp with transparency)"},getValue:t=>t.texturePath??"",setValue:(t,i)=>{let r=t,o=String(i).trim();r.texturePath=o.length>0?o:null,r.texturePath?r.tryLoadTextureFromPath(r.texturePath):r.applySkinTexture(null)}}],groups:{...e.groups,Control:{label:"Control",expanded:!0},Label:{label:"Label",expanded:!1},Skin:{label:"Skin",expanded:!1}}}}};var gt=class n extends Z{width;height;backgroundColor;hoverColor;pressedColor;buttonAction;textureNormal;textureHover;texturePressed;textureDisabled;stateTextureKeys;sliceBorder;buttonMesh;buttonMaterial;skinGeometry=null;skinTextureWidth=0;skinTextureHeight=0;skinEffectsActive=!1;effectStack;stateTextures={normal:null,hover:null,pressed:null,disabled:null};constructor(e){super(e,"Button2D"),this.width=e.width??100,this.height=e.height??40,this.backgroundColor=e.backgroundColor??"#4a4a4a",this.hoverColor=e.hoverColor??"#5a5a5a",this.pressedColor=e.pressedColor??"#3a3a3a",this.buttonAction=e.buttonAction??"Submit",this.textureNormal=D(e.textureNormal??null),this.textureHover=D(e.textureHover??null),this.texturePressed=D(e.texturePressed??null),this.textureDisabled=D(e.textureDisabled??null),this.stateTextureKeys={...e.stateTextureKeys??{}},this.sliceBorder=Ie(e.sliceBorder),this.buttonMaterial=new B({color:this.backgroundColor,transparent:!0,opacity:1,depthTest:!1}),this.registerSkinMaterial(this.buttonMaterial),this.buttonMesh=new O(De,this.buttonMaterial),this.buttonMesh.scale.set(this.width,this.height,1),this.buttonMesh.renderOrder=999,this.add(this.buttonMesh),this.applySkinGeometry(),this.refreshSkinState(),this.effectStack=new _e({nodeType:"Button2D",target:"basic",onAttachmentsChanged:()=>{this.skinEffectsActive=!this.effectStack.isEmpty,this.updateSkinBatchable()}}),this.effectStack.install(this.buttonMaterial);let t=e.effects??this.properties.effects;for(let i of t??[])i&&typeof i.type=="string"&&this.effectStack.attach(i.type,{enabled:i.enabled,params:i.params});H(this,n.getPropertySchema)}getShaderEffectStack(){return this.effectStack}getInstancePropertySchema(){return this.effectStack.buildInstanceSchema()}attachEffect(e,t){return this.effectStack.attach(e,t)}detachEffect(e){return this.effectStack.detach(e)}setEffectEnabled(e,t){this.effectStack.setEnabled(e,t)}setEffectParam(e,t,i){return this.effectStack.setParam(e,t,i)}getAttachedEffects(){return this.effectStack.getAttached()}isPointInBounds(e){this.getWorldPosition(this.tmpWorldPos);let t=Math.abs(e.x-this.tmpWorldPos.x),i=Math.abs(e.y-this.tmpWorldPos.y);return t<=this.width/2&&i<=this.height/2}tick(e){super.tick(e),this.effectStack.tick(e),this.updatePointerStateFromInput()}onPress(e){this.refreshSkinState(),this.input?.setButton(this.buttonAction,e)}onHover(e){this.refreshSkinState()}onEnabledChanged(e){!e&&this.isPressed&&(this.isPressed=!1,this.input?.setButton(this.buttonAction,!1)),this.refreshSkinState()}applySkinTexture(e){this.skinTexture=e,this.refreshSkinState()}setStateTexture(e,t){t&&$(t),this.stateTextures[e]=t,this.refreshSkinState()}resolveStateTexture(){let e=this.stateTextures.normal??this.skinTexture;return this.enabled?this.isPressed?this.stateTextures.pressed??e:this.isHovering?this.stateTextures.hover??e:e:this.stateTextures.disabled??e}resolveStateColor(){return this.enabled?this.isPressed?this.pressedColor:this.isHovering?this.hoverColor:this.backgroundColor:this.backgroundColor}refreshSkinState(){if(!this.buttonMaterial)return;let e=this.resolveStateTexture(),t=this.buttonMaterial.map!==null;e?(this.buttonMaterial.map=e,this.buttonMaterial.color.set("#ffffff"),this.buttonMaterial.transparent=!0):(this.buttonMaterial.map=null,this.buttonMaterial.color.setStyle(this.resolveStateColor())),t!==(e!==null)&&(this.buttonMaterial.needsUpdate=!0),this.captureSkinTextureSize(e)}captureSkinTextureSize(e){let t=0,i=0;if(e?.image){let r=Xe(e.image);t=r.width??0,i=r.height??0}t===this.skinTextureWidth&&i===this.skinTextureHeight||(this.skinTextureWidth=t,this.skinTextureHeight=i,mr(this.sliceBorder)||this.applySkinGeometry())}applySkinGeometry(){if(mr(this.sliceBorder))this.skinGeometry&&(this.skinGeometry.dispose(),this.skinGeometry=null),this.buttonMesh.geometry=De,this.buttonMesh.scale.set(this.width,this.height,1);else{let e=yi({width:this.width,height:this.height,textureWidth:this.skinTextureWidth,textureHeight:this.skinTextureHeight,border:this.sliceBorder});this.skinGeometry?.dispose(),this.skinGeometry=e,this.buttonMesh.geometry=e,this.buttonMesh.scale.set(1,1,1)}this.updateSkinBatchable()}updateSkinBatchable(){this.buttonMesh.userData[Ne]=!this.skinEffectsActive&&mr(this.sliceBorder)}setSliceBorder(e){this.sliceBorder=Ie({...this.sliceBorder,...e}),this.applySkinGeometry()}getEffectiveStateTexturePath(e){let t=this.stateTextureKeys[e];if(t){let i=Ke()?.trSprite(t);if(i)return i}switch(e){case"normal":return this.textureNormal?.url??null;case"hover":return this.textureHover?.url??null;case"pressed":return this.texturePressed?.url??null;case"disabled":return this.textureDisabled?.url??null}}hasLocalizedStateTextures(){return!!(this.stateTextureKeys.normal||this.stateTextureKeys.hover||this.stateTextureKeys.pressed||this.stateTextureKeys.disabled)}setStateTextureKey(e,t){let i=String(t??"");(this.stateTextureKeys[e]??"")!==i&&(i?this.stateTextureKeys[e]=i:delete this.stateTextureKeys[e])}setStateTextureRef(e,t){let i=D(t),r=null;switch(e){case"normal":r=this.textureNormal,this.textureNormal=i;break;case"hover":r=this.textureHover,this.textureHover=i;break;case"pressed":r=this.texturePressed,this.texturePressed=i;break;case"disabled":r=this.textureDisabled,this.textureDisabled=i;break}r?.url!==i?.url&&(this.stateTextures[e]=null,this.refreshSkinState())}static getPropertySchema(){let e=Z.getPropertySchema();return{nodeType:"Button2D",extends:"UIControl2D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Button",min:10,max:500,step:1},getValue:t=>t.width,setValue:(t,i)=>{let r=t;r.width=Number(i),r.applySkinGeometry()}},{name:"height",type:"number",ui:{label:"Height",group:"Button",min:10,max:500,step:1},getValue:t=>t.height,setValue:(t,i)=>{let r=t;r.height=Number(i),r.applySkinGeometry()}},{name:"backgroundColor",type:"color",ui:{label:"Color",group:"Button"},getValue:t=>t.backgroundColor,setValue:(t,i)=>{let r=t;r.backgroundColor=String(i),r.refreshSkinState()}},{name:"hoverColor",type:"color",ui:{label:"Hover Color",group:"Button"},getValue:t=>t.hoverColor,setValue:(t,i)=>{let r=t;r.hoverColor=String(i),r.refreshSkinState()}},{name:"pressedColor",type:"color",ui:{label:"Pressed Color",group:"Button"},getValue:t=>t.pressedColor,setValue:(t,i)=>{let r=t;r.pressedColor=String(i),r.refreshSkinState()}},{name:"buttonAction",type:"string",ui:{label:"Button Action",group:"Input",description:"Virtual button name"},getValue:t=>t.buttonAction,setValue:(t,i)=>{t.buttonAction=String(i)}},{name:"textureNormal",type:"object",ui:{label:"Normal Sprite",group:"Skin",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureNormal??{type:"texture",url:""},setValue:(t,i)=>{t.setStateTextureRef("normal",i)}},{name:"textureHover",type:"object",ui:{label:"Hover Sprite",group:"Skin",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureHover??{type:"texture",url:""},setValue:(t,i)=>{t.setStateTextureRef("hover",i)}},{name:"texturePressed",type:"object",ui:{label:"Pressed Sprite",group:"Skin",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.texturePressed??{type:"texture",url:""},setValue:(t,i)=>{t.setStateTextureRef("pressed",i)}},{name:"textureDisabled",type:"object",ui:{label:"Disabled Sprite",group:"Skin",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureDisabled??{type:"texture",url:""},setValue:(t,i)=>{t.setStateTextureRef("disabled",i)}},{name:"sliceBorderLeft",type:"number",ui:{label:"Slice Left",group:"Skin",description:"Left 9-slice inset of the state skins (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.left,setValue:(t,i)=>{t.setSliceBorder({left:Number(i)})}},{name:"sliceBorderRight",type:"number",ui:{label:"Slice Right",group:"Skin",description:"Right 9-slice inset of the state skins (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.right,setValue:(t,i)=>{t.setSliceBorder({right:Number(i)})}},{name:"sliceBorderTop",type:"number",ui:{label:"Slice Top",group:"Skin",description:"Top 9-slice inset of the state skins (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.top,setValue:(t,i)=>{t.setSliceBorder({top:Number(i)})}},{name:"sliceBorderBottom",type:"number",ui:{label:"Slice Bottom",group:"Skin",description:"Bottom 9-slice inset of the state skins (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.bottom,setValue:(t,i)=>{t.setSliceBorder({bottom:Number(i)})}},{name:"textureNormalKey",type:"string",ui:{label:"Normal Sprite Key",group:"Skin",editor:"localization-key",description:"Localization sprite key for the normal state (wins over the authored sprite when resolvable)"},getValue:t=>t.stateTextureKeys.normal??"",setValue:(t,i)=>{t.setStateTextureKey("normal",i)}},{name:"textureHoverKey",type:"string",ui:{label:"Hover Sprite Key",group:"Skin",editor:"localization-key",description:"Localization sprite key for the hover state"},getValue:t=>t.stateTextureKeys.hover??"",setValue:(t,i)=>{t.setStateTextureKey("hover",i)}},{name:"texturePressedKey",type:"string",ui:{label:"Pressed Sprite Key",group:"Skin",editor:"localization-key",description:"Localization sprite key for the pressed state"},getValue:t=>t.stateTextureKeys.pressed??"",setValue:(t,i)=>{t.setStateTextureKey("pressed",i)}},{name:"textureDisabledKey",type:"string",ui:{label:"Disabled Sprite Key",group:"Skin",editor:"localization-key",description:"Localization sprite key for the disabled state"},getValue:t=>t.stateTextureKeys.disabled??"",setValue:(t,i)=>{t.setStateTextureKey("disabled",i)}}],groups:{...e.groups,Button:{label:"Button",expanded:!0}}}}};var Ai=class n extends Z{width;height;handleSize;trackBackgroundColor;trackFilledColor;handleColor;minValue;maxValue;value;axisName;textureTrack;textureFill;textureThumb;sliceBorder;trackMesh;filledTrackMesh;handleMesh;trackMaterial;filledTrackMaterial;handleMaterial;trackGeometry;filledTrackGeometry;handleGeometry;slotTextures={track:null,fill:null,thumb:null};slotTextureSizes={track:{width:0,height:0},fill:{width:0,height:0},thumb:{width:0,height:0}};constructor(e){super(e,"Slider2D"),this.width=e.width??200,this.height=e.height??20,this.handleSize=e.handleSize??20,this.trackBackgroundColor=e.trackBackgroundColor??"#333333",this.trackFilledColor=e.trackFilledColor??"#4a9eff",this.handleColor=e.handleColor??"#ffffff",this.minValue=e.minValue??0,this.maxValue=e.maxValue??100,this.value=Math.max(this.minValue,Math.min(this.maxValue,e.value??50)),this.axisName=e.axisName??"Slider",this.textureTrack=D(e.textureTrack??null),this.textureFill=D(e.textureFill??null),this.textureThumb=D(e.textureThumb??null),this.sliceBorder=Ie(e.sliceBorder),this.trackGeometry=this.buildSlotGeometry("track",this.width,this.height),this.trackMaterial=new B({color:this.trackBackgroundColor,transparent:!0,opacity:1,depthTest:!1}),this.registerSkinMaterial(this.trackMaterial),this.trackMesh=new O(this.trackGeometry,this.trackMaterial),this.trackMesh.renderOrder=999,this.add(this.trackMesh),this.filledTrackGeometry=new z(0,this.height),this.filledTrackMaterial=new B({color:this.trackFilledColor,transparent:!0,opacity:1,depthTest:!1}),this.registerOpacityMaterial(this.filledTrackMaterial,1),this.filledTrackMesh=new O(this.filledTrackGeometry,this.filledTrackMaterial),this.filledTrackMesh.renderOrder=1e3,this.filledTrackMesh.position.z=.1,this.add(this.filledTrackMesh),this.handleGeometry=new z(this.handleSize,this.height),this.handleMaterial=new B({color:this.handleColor,transparent:!0,opacity:1,depthTest:!1}),this.registerOpacityMaterial(this.handleMaterial,1),this.handleMesh=new O(this.handleGeometry,this.handleMaterial),this.handleMesh.renderOrder=1001,this.handleMesh.position.z=.2,this.add(this.handleMesh),this.updateSliderVisuals(),H(this,n.getPropertySchema)}isPointInBounds(e){this.getWorldPosition(this.tmpWorldPos);let t=Math.abs(e.x-this.tmpWorldPos.x),i=Math.abs(e.y-this.tmpWorldPos.y);return t<=this.width/2&&i<=this.height/2}tick(e){super.tick(e),this.updatePointerStateFromInput()}capturesPointer(){return!0}onPointerDrag(e){this.updateSliderFromPointer(e.x)}get isDragging(){return this.isPressed}getInteractions(){let e={name:"value",type:"number",ui:{label:"Value",min:this.minValue,max:this.maxValue}};return[...super.getInteractions(),{name:"setValue",description:"Set the value programmatically (tests the reaction to a value change)",args:[e]},{name:"dragTo",description:"Grab the handle and drag it to a value (tests the drag itself)",args:[e]}]}performInteraction(e,t){switch(e){case"setValue":{let i=Ze(t,"value");return i===null||!this.canAcceptSemanticPointer()?!1:(this.setValue(i),!0)}case"dragTo":{let i=Ze(t,"value");return i===null?!1:this.dragHandleTo(i)}default:return super.performInteraction(e,t)}}dragHandleTo(e){let t=Math.max(this.minValue,Math.min(this.maxValue,e)),i=this.getSemanticPointerPoint(),r=this.worldXForValue(this.value),o=this.worldXForValue(t),s=(r+o)/2;return!this.runSemanticPointerFrame(i.set(r,i.y),!0,!0)||!this.runSemanticPointerFrame(i.set(s,i.y),!0,!0)||!this.runSemanticPointerFrame(i.set(o,i.y),!0,!0)?!1:this.runSemanticPointerFrame(i.set(o,i.y),!1,!1)}worldXForValue(e){this.getWorldPosition(this.tmpWorldPos);let t=this.maxValue-this.minValue,i=t===0?0:(e-this.minValue)/t;return this.tmpWorldPos.x+(i-.5)*this.width}updateSliderFromPointer(e){this.getWorldPosition(this.tmpWorldPos);let t=e-this.tmpWorldPos.x,i=Math.max(0,Math.min(1,(t+this.width/2)/this.width)),r=this.minValue+i*(this.maxValue-this.minValue);this.setValue(r)}setValue(e){let t=this.value;if(this.value=Math.max(this.minValue,Math.min(this.maxValue,e)),this.value!==t){this.updateSliderVisuals();let i=(this.value-this.minValue)/(this.maxValue-this.minValue);this.input?.setAxis(this.axisName,i)}}updateSliderVisuals(){let e=(this.value-this.minValue)/(this.maxValue-this.minValue),t=this.width*e;this.filledTrackGeometry.dispose(),this.filledTrackGeometry=this.buildSlotGeometry("fill",t,this.height),this.filledTrackMesh.geometry=this.filledTrackGeometry,this.filledTrackMesh.position.x=-this.width/2+t/2;let i=-this.width/2+t;this.handleMesh.position.x=i}buildSlotGeometry(e,t,i){let r=this.slotTextureSizes[e];return yi({width:t,height:i,textureWidth:r.width,textureHeight:r.height,border:e==="thumb"?null:this.sliceBorder})}rebuildTrackGeometry(){this.trackGeometry.dispose(),this.trackGeometry=this.buildSlotGeometry("track",this.width,this.height),this.trackMesh.geometry=this.trackGeometry,this.updateSliderVisuals()}setSliceBorder(e){this.sliceBorder=Ie({...this.sliceBorder,...e}),this.rebuildTrackGeometry()}setSlotTexture(e,t){t&&$(t),this.slotTextures[e]=t;let i=t?.image!==void 0&&t.image!==null?Xe(t.image):{};this.slotTextureSizes[e]={width:i.width??0,height:i.height??0};let r=this.materialForSlot(e);t?(r.map=t,r.color.set("#ffffff"),r.transparent=!0):(r.map=null,r.color.setStyle(this.colorForSlot(e))),r.needsUpdate=!0,e==="thumb"?(this.handleGeometry.dispose(),this.handleGeometry=new z(this.handleSize,this.height),this.handleMesh.geometry=this.handleGeometry):this.rebuildTrackGeometry()}getSlotTexturePath(e){switch(e){case"track":return this.textureTrack?.url??null;case"fill":return this.textureFill?.url??null;case"thumb":return this.textureThumb?.url??null}}materialForSlot(e){switch(e){case"track":return this.trackMaterial;case"fill":return this.filledTrackMaterial;case"thumb":return this.handleMaterial}}colorForSlot(e){switch(e){case"track":return this.trackBackgroundColor;case"fill":return this.trackFilledColor;case"thumb":return this.handleColor}}setSlotTextureRef(e,t){let i=D(t),r=this.getSlotTexturePath(e);switch(e){case"track":this.textureTrack=i;break;case"fill":this.textureFill=i;break;case"thumb":this.textureThumb=i;break}r!==(i?.url??null)&&this.setSlotTexture(e,null)}refreshSlotColor(e){this.slotTextures[e]||this.materialForSlot(e).color.setStyle(this.colorForSlot(e))}static getPropertySchema(){let e=Z.getPropertySchema();return{nodeType:"Slider2D",extends:"UIControl2D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Slider",min:50,max:500,step:1},getValue:t=>t.width,setValue:(t,i)=>{let r=t;r.width=Number(i),r.rebuildTrackGeometry()}},{name:"height",type:"number",ui:{label:"Height",group:"Slider",min:5,max:100,step:1},getValue:t=>t.height,setValue:(t,i)=>{let r=t;r.height=Number(i),r.handleGeometry.dispose(),r.handleGeometry=new z(r.handleSize,r.height),r.handleMesh.geometry=r.handleGeometry,r.rebuildTrackGeometry()}},{name:"handleSize",type:"number",ui:{label:"Handle Size",group:"Slider",min:5,max:100,step:1},getValue:t=>t.handleSize,setValue:(t,i)=>{let r=t;r.handleSize=Number(i),r.handleGeometry.dispose(),r.handleGeometry=new z(r.handleSize,r.height),r.handleMesh.geometry=r.handleGeometry,r.updateSliderVisuals()}},{name:"value",type:"number",ui:{label:"Value",group:"Slider",step:.1},getValue:t=>t.value,setValue:(t,i)=>{t.setValue(Number(i))}},{name:"minValue",type:"number",ui:{label:"Min Value",group:"Slider",step:.1},getValue:t=>t.minValue,setValue:(t,i)=>{let r=t;r.minValue=Number(i),r.value<r.minValue&&r.setValue(r.minValue),r.updateSliderVisuals()}},{name:"maxValue",type:"number",ui:{label:"Max Value",group:"Slider",step:.1},getValue:t=>t.maxValue,setValue:(t,i)=>{let r=t;r.maxValue=Number(i),r.value>r.maxValue&&r.setValue(r.maxValue),r.updateSliderVisuals()}},{name:"trackBackgroundColor",type:"color",ui:{label:"Background Color",group:"Slider"},getValue:t=>t.trackBackgroundColor,setValue:(t,i)=>{let r=t;r.trackBackgroundColor=String(i),r.refreshSlotColor("track")}},{name:"trackFilledColor",type:"color",ui:{label:"Filled Color",group:"Slider"},getValue:t=>t.trackFilledColor,setValue:(t,i)=>{let r=t;r.trackFilledColor=String(i),r.refreshSlotColor("fill")}},{name:"handleColor",type:"color",ui:{label:"Handle Color",group:"Slider"},getValue:t=>t.handleColor,setValue:(t,i)=>{let r=t;r.handleColor=String(i),r.refreshSlotColor("thumb")}},{name:"textureTrack",type:"object",ui:{label:"Track Sprite",group:"Skin",description:"Sprite for the track background",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureTrack??{type:"texture",url:""},setValue:(t,i)=>{t.setSlotTextureRef("track",i)}},{name:"textureFill",type:"object",ui:{label:"Fill Sprite",group:"Skin",description:"Sprite for the filled portion of the track",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureFill??{type:"texture",url:""},setValue:(t,i)=>{t.setSlotTextureRef("fill",i)}},{name:"textureThumb",type:"object",ui:{label:"Thumb Sprite",group:"Skin",description:"Sprite for the draggable handle (never sliced)",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureThumb??{type:"texture",url:""},setValue:(t,i)=>{t.setSlotTextureRef("thumb",i)}},{name:"sliceBorderLeft",type:"number",ui:{label:"Slice Left",group:"Skin",description:"Left 9-slice inset of the track/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.left,setValue:(t,i)=>{t.setSliceBorder({left:Number(i)})}},{name:"sliceBorderRight",type:"number",ui:{label:"Slice Right",group:"Skin",description:"Right 9-slice inset of the track/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.right,setValue:(t,i)=>{t.setSliceBorder({right:Number(i)})}},{name:"sliceBorderTop",type:"number",ui:{label:"Slice Top",group:"Skin",description:"Top 9-slice inset of the track/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.top,setValue:(t,i)=>{t.setSliceBorder({top:Number(i)})}},{name:"sliceBorderBottom",type:"number",ui:{label:"Slice Bottom",group:"Skin",description:"Bottom 9-slice inset of the track/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.bottom,setValue:(t,i)=>{t.setSliceBorder({bottom:Number(i)})}},{name:"axisName",type:"string",ui:{label:"Axis Name",group:"Input",description:"Virtual axis name"},getValue:t=>t.axisName,setValue:(t,i)=>{t.axisName=String(i)}}],groups:{...e.groups,Slider:{label:"Slider",expanded:!0},Skin:{label:"Skin",description:"Sprites replacing the flat colours",expanded:!0}}}}};var Ti=class n extends Z{acceptsPointerInput=!1;width;height;backBackgroundColor;barColor;minValue;maxValue;value;showBorder;borderColor;borderWidth;textureTrough;textureFill;sliceBorder;backgroundMesh;barMesh;borderMesh=null;backgroundMaterial;barMaterial;borderMaterial=null;backgroundGeometry;barGeometry;borderGeometry=null;slotTextures={trough:null,fill:null};slotTextureSizes={trough:{width:0,height:0},fill:{width:0,height:0}};constructor(e){super(e,"Bar2D"),this.width=e.width??150,this.height=e.height??20,this.backBackgroundColor=e.backBackgroundColor??"#333333",this.barColor=e.barColor??"#ff4444",this.minValue=e.minValue??0,this.maxValue=e.maxValue??100,this.value=Math.max(this.minValue,Math.min(this.maxValue,e.value??100)),this.showBorder=e.showBorder??!0,this.borderColor=e.borderColor??"#000000",this.borderWidth=e.borderWidth??2,this.textureTrough=D(e.textureTrough??null),this.textureFill=D(e.textureFill??null),this.sliceBorder=Ie(e.sliceBorder),this.backgroundGeometry=this.buildSlotGeometry("trough",this.width,this.height),this.backgroundMaterial=new B({color:this.backBackgroundColor,transparent:!0,opacity:1,depthTest:!1}),this.registerSkinMaterial(this.backgroundMaterial),this.backgroundMesh=new O(this.backgroundGeometry,this.backgroundMaterial),this.backgroundMesh.renderOrder=999,this.add(this.backgroundMesh),this.barGeometry=new z(0,this.height),this.barMaterial=new B({color:this.barColor,transparent:!0,opacity:1,depthTest:!1}),this.registerOpacityMaterial(this.barMaterial,1),this.barMesh=new O(this.barGeometry,this.barMaterial),this.barMesh.renderOrder=1e3,this.barMesh.position.z=.1,this.add(this.barMesh),this.showBorder&&this.createBorder(),this.updateBarVisuals(),H(this,n.getPropertySchema)}createBorder(){this.borderGeometry=this.buildBorderGeometry(),this.borderMaterial=new B({color:this.borderColor,transparent:!0,opacity:1,depthTest:!1,wireframe:!1}),this.registerOpacityMaterial(this.borderMaterial,1),this.borderMesh=new O(this.borderGeometry,this.borderMaterial),this.borderMesh.renderOrder=998,this.borderMesh.position.z=-.1,this.add(this.borderMesh)}buildBorderGeometry(){return new z(this.width+this.borderWidth*2,this.height+this.borderWidth*2)}rebuildBorderGeometry(){this.borderMesh&&(this.borderGeometry?.dispose(),this.borderGeometry=this.buildBorderGeometry(),this.borderMesh.geometry=this.borderGeometry)}isPointInBounds(e){return!1}setValue(e){let t=this.value;this.value=Math.max(this.minValue,Math.min(this.maxValue,e)),this.value!==t&&this.updateBarVisuals()}updateBarVisuals(){let e=(this.value-this.minValue)/(this.maxValue-this.minValue),t=Math.max(0,this.width*e);this.barGeometry.dispose(),this.barGeometry=this.buildSlotGeometry("fill",t,this.height),this.barMesh.geometry=this.barGeometry,this.barMesh.position.x=-this.width/2+t/2}buildSlotGeometry(e,t,i){let r=this.slotTextureSizes[e];return yi({width:t,height:i,textureWidth:r.width,textureHeight:r.height,border:this.sliceBorder})}rebuildTroughGeometry(){this.backgroundGeometry.dispose(),this.backgroundGeometry=this.buildSlotGeometry("trough",this.width,this.height),this.backgroundMesh.geometry=this.backgroundGeometry,this.rebuildBorderGeometry(),this.updateBarVisuals()}setSliceBorder(e){this.sliceBorder=Ie({...this.sliceBorder,...e}),this.rebuildTroughGeometry()}setSlotTexture(e,t){t&&$(t),this.slotTextures[e]=t;let i=t?.image!==void 0&&t.image!==null?Xe(t.image):{};this.slotTextureSizes[e]={width:i.width??0,height:i.height??0};let r=e==="trough"?this.backgroundMaterial:this.barMaterial;t?(r.map=t,r.color.set("#ffffff"),r.transparent=!0):(r.map=null,r.color.setStyle(e==="trough"?this.backBackgroundColor:this.barColor)),r.needsUpdate=!0,this.rebuildTroughGeometry()}getSlotTexturePath(e){return e==="trough"?this.textureTrough?.url??null:this.textureFill?.url??null}setSlotTextureRef(e,t){let i=D(t),r=this.getSlotTexturePath(e);e==="trough"?this.textureTrough=i:this.textureFill=i,r!==(i?.url??null)&&this.setSlotTexture(e,null)}refreshSlotColor(e){if(this.slotTextures[e])return;(e==="trough"?this.backgroundMaterial:this.barMaterial).color.setStyle(e==="trough"?this.backBackgroundColor:this.barColor)}static getPropertySchema(){let e=Z.getPropertySchema();return{nodeType:"Bar2D",extends:"UIControl2D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Bar",min:20,max:500,step:1},getValue:t=>t.width,setValue:(t,i)=>{let r=t;r.width=Number(i),r.rebuildTroughGeometry()}},{name:"height",type:"number",ui:{label:"Height",group:"Bar",min:5,max:200,step:1},getValue:t=>t.height,setValue:(t,i)=>{let r=t;r.height=Number(i),r.rebuildTroughGeometry()}},{name:"value",type:"number",ui:{label:"Value",group:"Bar",step:.1},getValue:t=>t.value,setValue:(t,i)=>{t.setValue(Number(i))}},{name:"minValue",type:"number",ui:{label:"Min Value",group:"Bar",step:.1},getValue:t=>t.minValue,setValue:(t,i)=>{let r=t;r.minValue=Number(i),r.value<r.minValue&&r.setValue(r.minValue),r.updateBarVisuals()}},{name:"maxValue",type:"number",ui:{label:"Max Value",group:"Bar",step:.1},getValue:t=>t.maxValue,setValue:(t,i)=>{let r=t;r.maxValue=Number(i),r.value>r.maxValue&&r.setValue(r.maxValue),r.updateBarVisuals()}},{name:"backBackgroundColor",type:"color",ui:{label:"Background Color",group:"Bar"},getValue:t=>t.backBackgroundColor,setValue:(t,i)=>{let r=t;r.backBackgroundColor=String(i),r.refreshSlotColor("trough")}},{name:"barColor",type:"color",ui:{label:"Bar Color",group:"Bar"},getValue:t=>t.barColor,setValue:(t,i)=>{let r=t;r.barColor=String(i),r.refreshSlotColor("fill")}},{name:"textureTrough",type:"object",ui:{label:"Trough Sprite",group:"Skin",description:"Sprite for the empty trough behind the fill",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureTrough??{type:"texture",url:""},setValue:(t,i)=>{t.setSlotTextureRef("trough",i)}},{name:"textureFill",type:"object",ui:{label:"Fill Sprite",group:"Skin",description:"Sprite for the filled portion",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureFill??{type:"texture",url:""},setValue:(t,i)=>{t.setSlotTextureRef("fill",i)}},{name:"sliceBorderLeft",type:"number",ui:{label:"Slice Left",group:"Skin",description:"Left 9-slice inset of the trough/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.left,setValue:(t,i)=>{t.setSliceBorder({left:Number(i)})}},{name:"sliceBorderRight",type:"number",ui:{label:"Slice Right",group:"Skin",description:"Right 9-slice inset of the trough/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.right,setValue:(t,i)=>{t.setSliceBorder({right:Number(i)})}},{name:"sliceBorderTop",type:"number",ui:{label:"Slice Top",group:"Skin",description:"Top 9-slice inset of the trough/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.top,setValue:(t,i)=>{t.setSliceBorder({top:Number(i)})}},{name:"sliceBorderBottom",type:"number",ui:{label:"Slice Bottom",group:"Skin",description:"Bottom 9-slice inset of the trough/fill sprites (source px); 0 = stretch",min:0,step:1,precision:0,unit:"px"},getValue:t=>t.sliceBorder.bottom,setValue:(t,i)=>{t.setSliceBorder({bottom:Number(i)})}},{name:"showBorder",type:"boolean",ui:{label:"Show Border",group:"Bar"},getValue:t=>t.showBorder,setValue:(t,i)=>{let r=t;r.showBorder=!!i,r.showBorder&&!r.borderMesh?r.createBorder():!r.showBorder&&r.borderMesh&&(r.remove(r.borderMesh),r.borderGeometry?.dispose(),r.borderMaterial?.dispose(),r.borderMesh=null,r.borderGeometry=null,r.borderMaterial=null)}},{name:"borderColor",type:"color",ui:{label:"Border Color",group:"Bar"},getValue:t=>t.borderColor,setValue:(t,i)=>{let r=t;r.borderColor=String(i),r.borderMaterial&&r.borderMaterial.color.setStyle(r.borderColor)}}],groups:{...e.groups,Bar:{label:"Bar",expanded:!0},Skin:{label:"Skin",description:"Sprites replacing the flat colours",expanded:!0}}}}};var Ci=class n extends Z{size;checked;uncheckedColor;checkedColor;checkmarkColor;checkmarkAction;textureBox;textureBoxChecked;textureMark;slotTextures={box:null,boxChecked:null,mark:null};boxMesh;boxMaterial;checkMesh=null;checkMaterial=null;geometry;checkGeometry=null;constructor(e){super(e,"Checkbox2D"),this.size=e.size??30,this.checked=e.checked??!1,this.uncheckedColor=e.uncheckedColor??"#ffffff",this.checkedColor=e.checkedColor??"#4a9eff",this.checkmarkColor=e.checkmarkColor??"#ffffff",this.checkmarkAction=e.checkmarkAction??"Checkbox",this.textureBox=D(e.textureBox??null),this.textureBoxChecked=D(e.textureBoxChecked??null),this.textureMark=D(e.textureMark??null),this.geometry=new z(this.size,this.size),this.boxMaterial=new B({color:this.checked?this.checkedColor:this.uncheckedColor,transparent:!0,opacity:1,depthTest:!1}),this.registerSkinMaterial(this.boxMaterial),this.boxMesh=new O(this.geometry,this.boxMaterial),this.boxMesh.renderOrder=999,this.add(this.boxMesh),this.checked&&this.createCheckmark(),e.labelAlign===void 0&&(this.labelAlign="left"),this.label.trim().length>0&&this.updateLabel(),H(this,n.getPropertySchema)}static LABEL_GAP=6;updateLabel(){super.updateLabel(),this.labelMesh&&(this.labelMesh.position.x=this.size/2+this.labelMesh.scale.x/2+n.LABEL_GAP,this.labelMesh.position.y=0)}createCheckmark(){let e=this.slotTextures.mark;this.checkGeometry=n.buildMarkGeometry(this.size,e!==null),this.checkMaterial=new B({color:e?"#ffffff":this.checkmarkColor,map:e,transparent:!0,opacity:1,depthTest:!1}),this.registerOpacityMaterial(this.checkMaterial,1),this.checkMesh=new O(this.checkGeometry,this.checkMaterial),this.checkMesh.renderOrder=1e3,this.checkMesh.position.z=.1,this.checkMesh.rotation.z=e?0:Math.PI/4,this.add(this.checkMesh)}static buildMarkGeometry(e,t){if(t)return new z(e,e);let i=e*.6;return new z(i,i*.5)}destroyCheckmark(){this.checkMesh&&(this.remove(this.checkMesh),this.checkGeometry?.dispose(),this.checkMaterial?.dispose(),this.checkMesh=null,this.checkGeometry=null,this.checkMaterial=null)}setSlotTexture(e,t){if(t&&$(t),this.slotTextures[e]=t,e==="mark"){this.checked&&(this.destroyCheckmark(),this.createCheckmark());return}this.refreshBoxSkin()}getSlotTexturePath(e){switch(e){case"box":return this.textureBox?.url??null;case"boxChecked":return this.textureBoxChecked?.url??null;case"mark":return this.textureMark?.url??null}}setSlotTextureRef(e,t){let i=D(t),r=this.getSlotTexturePath(e);switch(e){case"box":this.textureBox=i;break;case"boxChecked":this.textureBoxChecked=i;break;case"mark":this.textureMark=i;break}r!==(i?.url??null)&&this.setSlotTexture(e,null)}resolveBoxTexture(){return this.checked?this.slotTextures.boxChecked??this.slotTextures.box:this.slotTextures.box}refreshBoxSkin(){if(!this.boxMaterial)return;let e=this.resolveBoxTexture(),t=this.boxMaterial.map!==null;e?(this.boxMaterial.map=e,this.boxMaterial.color.set("#ffffff"),this.boxMaterial.transparent=!0):(this.boxMaterial.map=null,this.boxMaterial.color.setStyle(this.checked?this.checkedColor:this.uncheckedColor)),t!==(e!==null)&&(this.boxMaterial.needsUpdate=!0)}isPointInBounds(e){this.getWorldPosition(this.tmpWorldPos);let t=e.x-this.tmpWorldPos.x,i=e.y-this.tmpWorldPos.y,r=this.size/2;return this.labelMesh&&(r=Math.max(r,this.labelMesh.position.x+this.labelMesh.scale.x/2)),t>=-this.size/2&&t<=r&&Math.abs(i)<=this.size/2}pendingActionRelease=!1;tick(e){super.tick(e),this.pendingActionRelease&&(this.pendingActionRelease=!1,this.input?.setButton(this.checkmarkAction,!1)),this.updatePointerStateFromInput()}onClick(){this.toggle()}getInteractions(){return[...super.getInteractions(),{name:"toggle",description:"Flip the checkbox by clicking it"},{name:"setChecked",description:"Click the checkbox only if that reaches the requested state",args:[{name:"checked",type:"boolean",ui:{label:"Checked",description:"Desired state after the interaction"}}]}]}performInteraction(e,t){switch(e){case"toggle":return this.runSemanticClick();case"setChecked":{let i=Su(t,"checked");return i===null||!this.canAcceptSemanticPointer()?!1:this.checked===i?!0:this.runSemanticClick()}default:return super.performInteraction(e,t)}}toggle(){let e=!this.checked;this.input?.setButton(this.checkmarkAction,!0),this.input?.setAxis(this.checkmarkAction,e?1:0),this.pendingActionRelease=!0,this.applyChecked(e)}applyChecked(e){this.checked!==e&&(Rt(this,"checked",e),this.updateCheckboxVisuals(),this.emit("toggled",e))}updateCheckboxVisuals(){this.refreshBoxSkin(),this.checked&&!this.checkMesh?this.createCheckmark():!this.checked&&this.checkMesh&&this.destroyCheckmark()}static getPropertySchema(){let e=Z.getPropertySchema();return{nodeType:"Checkbox2D",extends:"UIControl2D",properties:[...e.properties,{name:"size",type:"number",ui:{label:"Size",group:"Checkbox",min:10,max:100,step:1},getValue:t=>t.size,setValue:(t,i)=>{let r=t;r.size=Number(i),r.geometry.dispose(),r.geometry=new z(r.size,r.size),r.boxMesh.geometry=r.geometry,r.checked&&r.checkGeometry&&(r.checkGeometry.dispose(),r.checkGeometry=n.buildMarkGeometry(r.size,r.slotTextures.mark!==null),r.checkMesh&&(r.checkMesh.geometry=r.checkGeometry))}},{name:"checked",type:"boolean",ui:{label:"Checked",group:"Checkbox"},getValue:t=>t.checked,setValue:(t,i)=>{t.applyChecked(!!i)}},{name:"uncheckedColor",type:"color",ui:{label:"Unchecked Color",group:"Checkbox"},getValue:t=>t.uncheckedColor,setValue:(t,i)=>{let r=t;r.uncheckedColor=String(i),r.refreshBoxSkin()}},{name:"checkedColor",type:"color",ui:{label:"Checked Color",group:"Checkbox"},getValue:t=>t.checkedColor,setValue:(t,i)=>{let r=t;r.checkedColor=String(i),r.refreshBoxSkin()}},{name:"checkmarkColor",type:"color",ui:{label:"Checkmark Color",group:"Checkbox"},getValue:t=>t.checkmarkColor,setValue:(t,i)=>{let r=t;r.checkmarkColor=String(i),r.checkMaterial&&!r.slotTextures.mark&&r.checkMaterial.color.setStyle(r.checkmarkColor)}},{name:"textureBox",type:"object",ui:{label:"Box Sprite",group:"Skin",description:"Sprite for the box (also the checked fallback)",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureBox??{type:"texture",url:""},setValue:(t,i)=>{t.setSlotTextureRef("box",i)}},{name:"textureBoxChecked",type:"object",ui:{label:"Checked Box Sprite",group:"Skin",description:"Optional sprite for the box while checked",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureBoxChecked??{type:"texture",url:""},setValue:(t,i)=>{t.setSlotTextureRef("boxChecked",i)}},{name:"textureMark",type:"object",ui:{label:"Mark Sprite",group:"Skin",description:"Sprite drawn over the box while checked",editor:"texture-resource",resourceType:"texture"},getValue:t=>t.textureMark??{type:"texture",url:""},setValue:(t,i)=>{t.setSlotTextureRef("mark",i)}},{name:"checkmarkAction",type:"string",ui:{label:"Action",group:"Input",description:"Virtual button/axis name"},getValue:t=>t.checkmarkAction,setValue:(t,i)=>{t.checkmarkAction=String(i)}}],groups:{...e.groups,Checkbox:{label:"Checkbox",expanded:!0},Skin:{label:"Skin",description:"Sprites replacing the flat colours",expanded:!0}}}}};var Mi=class n extends Z{width;height;backdropColor;borderColor;borderWidth;quantity;showQuantity;quantityFontSize;selectionColor;selectedAction;selected=!1;slotMesh;slotMaterial;borderMesh=null;borderMaterial=null;quantityMesh=null;quantityTexture=null;slotGeometry;borderGeometry=null;constructor(e){super(e,"InventorySlot2D"),this.width=e.width??60,this.height=e.height??60,this.backdropColor=e.backdropColor??"#555555",this.borderColor=e.borderColor??"#888888",this.borderWidth=e.borderWidth??2,this.quantity=Math.max(0,e.quantity??0),this.showQuantity=e.showQuantity??!0,this.quantityFontSize=e.quantityFontSize??12,this.selectionColor=e.selectionColor??"#ffff00",this.selectedAction=e.selectedAction??"SlotSelected",this.slotGeometry=new z(this.width,this.height),this.slotMaterial=new B({color:this.backdropColor,transparent:!0,opacity:1,depthTest:!1}),this.registerSkinMaterial(this.slotMaterial),this.slotMesh=new O(this.slotGeometry,this.slotMaterial),this.slotMesh.renderOrder=999,this.add(this.slotMesh),this.createBorder(),this.showQuantity&&this.quantity>0&&this.updateQuantityDisplay(),H(this,n.getPropertySchema)}createBorder(){this.borderGeometry=new z(this.width,this.height),this.borderMaterial=new B({color:this.borderColor,transparent:!0,opacity:1,depthTest:!1,wireframe:!1}),this.registerOpacityMaterial(this.borderMaterial,1),this.borderMesh=new O(this.borderGeometry,this.borderMaterial),this.borderMesh.renderOrder=1e3,this.borderMesh.position.z=.1,this.add(this.borderMesh)}createQuantityTexture(){let e=document.createElement("canvas");e.width=64,e.height=64;let t=e.getContext("2d");if(!t)throw new Error("Could not get canvas 2D context");t.fillStyle="rgba(0, 0, 0, 0)",t.fillRect(0,0,64,64),t.fillStyle="#ffffff",t.font=`bold ${this.quantityFontSize}px Arial`,t.textAlign="right",t.textBaseline="bottom",t.fillText(String(this.quantity),60,60);let i=new It(e);return $(i),i}updateQuantityDisplay(){if(!this.showQuantity||this.quantity<=0){this.quantityMesh&&(this.remove(this.quantityMesh),this.quantityMesh=null,this.quantityTexture?.dispose(),this.quantityTexture=null);return}if(this.quantityTexture?.dispose(),this.quantityTexture=this.createQuantityTexture(),!this.quantityMesh){let t=new B({map:this.quantityTexture,transparent:!0,depthTest:!1});this.registerOpacityMaterial(t,1);let i=new z(this.width*.8,this.height*.8);this.quantityMesh=new O(i,t),this.quantityMesh.renderOrder=1001,this.quantityMesh.position.z=.2,this.add(this.quantityMesh);return}let e=this.quantityMesh.material;e.map=this.quantityTexture,e.needsUpdate=!0}isPointInBounds(e){this.getWorldPosition(this.tmpWorldPos);let t=Math.abs(e.x-this.tmpWorldPos.x),i=Math.abs(e.y-this.tmpWorldPos.y);return t<=this.width/2&&i<=this.height/2}tick(e){super.tick(e),this.updatePointerStateFromInput()}onClick(){this.select()}getInteractions(){return[...super.getInteractions(),{name:"activate",description:"Click the slot to select/deselect it"}]}performInteraction(e,t){return e==="activate"?this.runSemanticClick():super.performInteraction(e,t)}select(){this.selected=!this.selected,this.updateSlotVisuals(),this.input?.setButton(this.selectedAction,this.selected),this.emit("toggled",this.selected)}setQuantity(e){this.quantity=Math.max(0,e),this.updateQuantityDisplay()}updateSlotVisuals(){this.selected?(this.slotMaterial.color.setStyle(this.selectionColor),this.borderMaterial&&this.borderMaterial.color.setStyle(this.selectionColor)):(this.slotMaterial.color.setStyle(this.backdropColor),this.borderMaterial&&this.borderMaterial.color.setStyle(this.borderColor))}static getPropertySchema(){let e=Z.getPropertySchema();return{nodeType:"InventorySlot2D",extends:"UIControl2D",properties:[...e.properties,{name:"width",type:"number",ui:{label:"Width",group:"Slot",min:20,max:200,step:1},getValue:t=>t.width,setValue:(t,i)=>{let r=t;r.width=Number(i),r.slotGeometry.dispose(),r.slotGeometry=new z(r.width,r.height),r.slotMesh.geometry=r.slotGeometry,r.borderGeometry&&(r.borderGeometry.dispose(),r.borderGeometry=new z(r.width,r.height),r.borderMesh&&(r.borderMesh.geometry=r.borderGeometry))}},{name:"height",type:"number",ui:{label:"Height",group:"Slot",min:20,max:200,step:1},getValue:t=>t.height,setValue:(t,i)=>{let r=t;r.height=Number(i),r.slotGeometry.dispose(),r.slotGeometry=new z(r.width,r.height),r.slotMesh.geometry=r.slotGeometry,r.borderGeometry&&(r.borderGeometry.dispose(),r.borderGeometry=new z(r.width,r.height),r.borderMesh&&(r.borderMesh.geometry=r.borderGeometry))}},{name:"quantity",type:"number",ui:{label:"Quantity",group:"Slot",min:0,step:1},getValue:t=>t.quantity,setValue:(t,i)=>{t.setQuantity(Number(i))}},{name:"showQuantity",type:"boolean",ui:{label:"Show Quantity",group:"Slot"},getValue:t=>t.showQuantity,setValue:(t,i)=>{let r=t;r.showQuantity=!!i,r.updateQuantityDisplay()}},{name:"backdropColor",type:"color",ui:{label:"Backdrop Color",group:"Slot"},getValue:t=>t.backdropColor,setValue:(t,i)=>{let r=t;r.backdropColor=String(i),r.selected||r.slotMaterial.color.setStyle(r.backdropColor)}},{name:"borderColor",type:"color",ui:{label:"Border Color",group:"Slot"},getValue:t=>t.borderColor,setValue:(t,i)=>{let r=t;r.borderColor=String(i),!r.selected&&r.borderMaterial&&r.borderMaterial.color.setStyle(r.borderColor)}},{name:"selectionColor",type:"color",ui:{label:"Selection Color",group:"Slot"},getValue:t=>t.selectionColor,setValue:(t,i)=>{t.selectionColor=String(i)}},{name:"selectedAction",type:"string",ui:{label:"Selection Action",group:"Input",description:"Virtual button name"},getValue:t=>t.selectedAction,setValue:(t,i)=>{t.selectedAction=String(i)}}],groups:{...e.groups,Slot:{label:"Slot",expanded:!0}}}}};var Pu=["left","center","right"],Os=["top","middle","bottom"],Wf=1.25,Vs=4,gr=4;function ku(n,e){return!(e>0)||!(n>0)?0:n*.35*Math.min(e,gr)}function Hf(n){return n>0?Math.min(3,Math.max(1,Math.ceil(n))):0}function Au(n,e=0,t=0,i){return mn({glowBlur:ku(n,e),outlineWidth:t,shadowColor:i?.color??null,shadowOffsetX:i?.offsetX??0,shadowOffsetY:i?.offsetY??0,shadowBlur:i?.blur??0})}function Tu(n,e,t){let i=t.maxWidth&&t.maxWidth>0?t.maxWidth:0,r=t.fontSize*(t.lineHeightFactor??Wf),o=[],s=c=>{o.push({text:c,width:c.length>0?e(c):0})};for(let c of n.split(`
193
+ `)){if(i<=0||c.length===0||e(c)<=i){s(c);continue}let u="";for(let h of c.split(" ")){let d=u.length>0?`${u} ${h}`:h;if(e(d)<=i||u.length===0){u=d;continue}s(u),u=h}for(;u.length>1&&e(u)>i;){let h=u.length-1;for(;h>1&&e(u.slice(0,h))>i;)h-=1;s(u.slice(0,h)),u=u.slice(h)}s(u)}let a=0,l=0;for(let c of o)a=Math.max(a,c.width),l+=c.text.length;return{lines:o,lineHeight:r,textWidth:a,textHeight:o.length*r,totalChars:l}}function Cu(n,e){let{layout:t,width:i,height:r}=e,o=e.paddingX??0,s=e.paddingY??0;n.clearRect(0,0,i,r),n.fillStyle=e.color,ki(n,{fontSize:e.fontSize,fontFamily:e.fontFamily,fontWeight:e.fontWeight,letterSpacing:e.letterSpacing}),n.textBaseline="middle";let a=i/2;e.align==="left"?(n.textAlign="left",a=o):e.align==="right"?(n.textAlign="right",a=i-o):n.textAlign="center";let l=(r-t.textHeight)/2;e.vAlign==="top"?l=s:e.vAlign==="bottom"&&(l=r-s-t.textHeight);let c=Math.min(gr,Math.max(0,e.glowStrength??0)),u=ku(e.fontSize,c),h=Hf(c),d=e.glowColor?.trim()?e.glowColor:e.color,p={color:e.color,outlineWidth:e.outlineWidth,outlineColor:e.outlineColor,shadowColor:e.shadowColor,shadowOffsetX:e.shadowOffsetX,shadowOffsetY:e.shadowOffsetY,shadowBlur:e.shadowBlur,glowColor:d,glowBlur:u,glowPasses:h},f=e.visibleCharacters??1/0;for(let m=0;m<t.lines.length&&!(f<=0);m++){let g=t.lines[m].text,y=f>=g.length?g:g.slice(0,Math.max(0,Math.floor(f)));if(f-=g.length,y.length===0)continue;let b=l+m*t.lineHeight+t.lineHeight/2;pn(n,y,a,b,p)}}var yt=class n extends Z{acceptsPointerInput=!1;width;height;labelVAlign;typewriterSpeed;glowColor;glowStrength;outlineColor;outlineWidth;renderState=null;typewriterVisible=0;typewriterActive=!1;labelKeyParams=null;constructor(e){super(e,"Label2D"),this.width=e.width??0,this.height=e.height??0,this.labelVAlign=e.labelVAlign??"middle",this.typewriterSpeed=e.typewriterSpeed??0,this.glowColor=e.glowColor??"#ffffff",this.glowStrength=n.clampGlowStrength(e.glowStrength??0),this.outlineColor=e.outlineColor??e.labelOutlineColor??"#000000",this.outlineWidth=Math.max(0,e.outlineWidth??e.labelOutlineWidth??0),this.updateLabel(),H(this,n.getPropertySchema)}get labelOutlineWidth(){return this.outlineWidth??0}set labelOutlineWidth(e){let t=Math.max(0,Number.isFinite(e)?e:0);this.outlineWidth!==t&&(this.outlineWidth=t,this.updateLabel())}get labelOutlineColor(){return this.outlineColor??"#000000"}set labelOutlineColor(e){this.outlineColor!==e&&(this.outlineColor=e,this.updateLabel())}getDisplayText(){return this.labelKey?on(this.labelKey,this.label,this.labelKeyParams??void 0):this.label}setText(e){this.labelKey===""&&this.label===e||(this.labelKeyParams=null,this.labelKey="",this.label=e,this.updateLabel())}setTextKey(e,t){this.labelKeyParams=t??null,this.labelKey=e,this.updateLabel()}get isTyping(){return this.typewriterActive}skipTypewriter(){this.typewriterActive&&(this.typewriterVisible=this.renderState?.layout.totalChars??0,this.finishTypewriter())}restartTypewriter(){this.typewriterSpeed<=0||!this.renderState||(this.typewriterVisible=0,this.typewriterActive=this.renderState.layout.totalChars>0,this.repaint())}tick(e){if(super.tick(e),this.typewriterActive&&this.typewriterSpeed>0&&this.renderState){let t=Math.floor(this.typewriterVisible);this.typewriterVisible+=e*this.typewriterSpeed,this.typewriterVisible>=this.renderState.layout.totalChars?this.finishTypewriter():Math.floor(this.typewriterVisible)!==t&&this.repaint()}this.updatePointerStateFromInput()}isPointInBounds(e){let t=this.renderState;if(!t)return!1;this.getWorldPosition(this.tmpWorldPos);let i=Math.abs(e.x-this.tmpWorldPos.x),r=Math.abs(e.y-this.tmpWorldPos.y);return i<=(t.boxWidth-t.pad*2)/2&&r<=(t.boxHeight-t.pad*2)/2}updateLabel(){let e=this.getDisplayText();if(e.length===0){this.renderState=null,this.typewriterActive=!1,this.labelMesh&&(this.remove(this.labelMesh),this.labelMesh=null),this.labelTexture?.dispose(),this.labelTexture=null;return}let t=this.width??0,i=this.height??0,r=Math.max(1,this.labelFontSize||16),o=this.renderState?.canvas??document.createElement("canvas"),s=this.renderState?.ctx??o.getContext("2d");if(!s)throw new Error("Could not get canvas 2D context");ki(s,{fontSize:r,fontFamily:this.labelFontFamily,fontWeight:this.labelFontWeight,letterSpacing:this.labelLetterSpacing});let a=Tu(e,b=>s.measureText(b).width,{fontSize:r,maxWidth:t>0?t:0}),l=Au(r,this.glowStrength??0,this.outlineWidth??0,{color:this.labelShadowColor,offsetX:this.labelShadowOffsetX,offsetY:this.labelShadowOffsetY}),c=(t>0?t:Math.ceil(a.textWidth)+Vs)+l*2,u=(i>0?i:Math.ceil(a.textHeight)+Vs)+l*2,h=typeof window<"u"&&window.devicePixelRatio||1,d=Math.max(1,Math.min(3,h)),p=Math.max(1,Math.round(c*d)),f=Math.max(1,Math.round(u*d)),m=o.width!==p||o.height!==f;m&&(o.width=p,o.height=f),s.setTransform(d,0,0,d,0,0);let g=this.renderState?.text!==e;this.renderState={canvas:o,ctx:s,layout:a,boxWidth:c,boxHeight:u,text:e,pad:l};let y=(this.typewriterSpeed??0)>0;if(g?(this.typewriterVisible=0,this.typewriterActive=y&&a.totalChars>0):y||(this.typewriterActive=!1),(!this.labelTexture||this.labelTexture.image!==o||m)&&(this.labelTexture?.dispose(),this.labelTexture=new It(o),$(this.labelTexture)),this.labelTexture.userData={...this.labelTexture.userData??{},logicalWidth:c,logicalHeight:u,dpr:d},this.labelMesh){let b=this.labelMesh.material;b.map=this.labelTexture,b.needsUpdate=!0}else{let b=new B({map:this.labelTexture,transparent:!0,depthTest:!1});this.registerOpacityMaterial(b,1),this.labelMesh=new O(new z(1,1),b),this.labelMesh.renderOrder=1001,this.labelMesh.position.z=2,this.add(this.labelMesh)}this.labelMesh.scale.set(c,u,1),this.repaint()}finishTypewriter(){this.typewriterVisible=this.renderState?.layout.totalChars??0,this.typewriterActive=!1,this.repaint(),this.emit("typewriter-complete")}repaint(){let e=this.renderState;!e||!this.labelTexture||(Cu(e.ctx,{layout:e.layout,fontFamily:this.labelFontFamily,fontSize:Math.max(1,this.labelFontSize||16),color:this.labelColor,align:this.labelAlign,vAlign:this.labelVAlign??"middle",width:e.boxWidth,height:e.boxHeight,paddingX:e.pad,paddingY:e.pad,visibleCharacters:this.typewriterActive?Math.floor(this.typewriterVisible):1/0,glowColor:this.glowColor,glowStrength:this.glowStrength??0,outlineColor:this.outlineColor,outlineWidth:this.outlineWidth??0,fontWeight:this.labelFontWeight,shadowColor:this.labelShadowColor,shadowOffsetX:this.labelShadowOffsetX,shadowOffsetY:this.labelShadowOffsetY,letterSpacing:this.labelLetterSpacing}),this.labelTexture.needsUpdate=!0)}static getPropertySchema(){let e=Z.getPropertySchema(),t=new Set(["labelOutlineWidth","labelOutlineColor"]);return{nodeType:"Label2D",extends:"UIControl2D",properties:[...e.properties.filter(r=>!t.has(r.name)).map(r=>r.name==="labelAlign"?{...r,type:"enum",ui:{...r.ui,options:[...Pu]}}:r),{name:"width",type:"number",ui:{label:"Width",group:"Label",min:0,step:1,unit:"px",description:"Fixed box width; text word-wraps to it. 0 = auto-size, no wrapping"},getValue:r=>r.width,setValue:(r,o)=>{let s=r;s.width=Math.max(0,Number(o)||0),s.updateLabel()}},{name:"height",type:"number",ui:{label:"Height",group:"Label",min:0,step:1,unit:"px",description:"Fixed box height for vertical alignment. 0 = auto-size to the lines"},getValue:r=>r.height,setValue:(r,o)=>{let s=r;s.height=Math.max(0,Number(o)||0),s.updateLabel()}},{name:"labelVAlign",type:"enum",ui:{label:"V-Alignment",group:"Label",options:[...Os],description:"Vertical text placement inside a fixed-height box"},getValue:r=>r.labelVAlign,setValue:(r,o)=>{let s=r,a=String(o);Os.includes(a)&&(s.labelVAlign=a,s.updateLabel())}},{name:"typewriterSpeed",type:"number",ui:{label:"Typewriter Speed",group:"Label",min:0,step:1,unit:"chars/s",description:"Reveal the text character by character in play mode; 0 = off"},getValue:r=>r.typewriterSpeed,setValue:(r,o)=>{let s=r;s.typewriterSpeed=Math.max(0,Number(o)||0),s.restartTypewriter()}},{name:"glowColor",type:"color",ui:{label:"Glow Color",group:"Label",description:"Colour of the canvas glow; only visible while Glow Strength > 0"},getValue:r=>r.glowColor,setValue:(r,o)=>{let s=r;s.glowColor=String(o),s.updateLabel()}},{name:"glowStrength",type:"number",ui:{label:"Glow Strength",group:"Label",min:0,max:gr,step:.1,precision:2,description:"Neon glow around the glyphs (canvas shadow); 0 = off. Works on HUD text, which never blooms"},getValue:r=>r.glowStrength,setValue:(r,o)=>{let s=r;s.glowStrength=n.clampGlowStrength(Number(o)),s.updateLabel()}},{name:"outlineColor",type:"color",ui:{label:"Outline Color",group:"Label",description:"Colour of the outline; only visible while Outline Width > 0"},getValue:r=>r.outlineColor,setValue:(r,o)=>{let s=r;s.outlineColor=String(o),s.updateLabel()}},{name:"outlineWidth",type:"number",ui:{label:"Outline Width",group:"Label",min:0,max:16,step:.5,precision:2,unit:"px",description:"Contrast outline drawn under the text; 0 = off"},getValue:r=>r.outlineWidth,setValue:(r,o)=>{let s=r;s.outlineWidth=Math.max(0,Number(o)||0),s.updateLabel()}}],groups:{...e.groups,Label:{...e.groups?.Label,label:"Label",expanded:!0}}}}static clampGlowStrength(e){return Number.isFinite(e)?Math.min(gr,Math.max(0,e)):0}};var bt=class n extends I{audioTrack;autoplay;loop;volume;bus;pitchVariation;volumeVariation;playback=null;autoPlayed=!1;constructor(e){super({...e,type:"AudioPlayer"}),this.audioTrack=n.normalizeTrack(e.audioTrack??this.properties.audioTrack),this.autoplay=n.toBoolean(e.autoplay??this.properties.autoplay,!1),this.loop=n.toBoolean(e.loop??this.properties.loop,!1),this.volume=n.clampVolume(e.volume??this.properties.volume,1),this.bus=n.normalizeBus(e.bus??this.properties.bus),this.pitchVariation=n.clampVariation(e.pitchVariation??this.properties.pitchVariation),this.volumeVariation=n.clampVariation(e.volumeVariation??this.properties.volumeVariation),H(this,n.getPropertySchema)}get treeIcon(){return"speaker"}tick(e){super.tick(e),!this.autoPlayed&&this.autoplay&&(this.autoPlayed=!0,this.play())}async play(){if(!this.audioTrack){console.warn(`[AudioPlayer] Node "${this.name}" has no audio track configured.`);return}let e=this.scene;if(!e){console.warn(`[AudioPlayer] Node "${this.name}" is not attached to a running scene.`);return}let t=e.getAssetLoader(),i=e.getAudioService();if(!t||!i){console.warn("[AudioPlayer] Audio services are not available in the current runtime context.");return}try{let r=await t.loadAudio(this.audioTrack),o=e.getAudioService();if(!o)return;let s=t.getAudioMetadata(this.audioTrack);this.stop(),this.playback=o.play(r,{resourcePath:this.audioTrack,sizeBytes:s?.sizeBytes,loop:this.loop,volume:this.volume,bus:this.bus,pitchVariation:this.pitchVariation,volumeVariation:this.volumeVariation})}catch(r){console.warn(`[AudioPlayer] Failed to play "${this.audioTrack}":`,r)}}stop(){this.playback?.stop(),this.playback=null}serializeConfig(){return{audioTrack:this.audioTrack??void 0,autoplay:this.autoplay,loop:this.loop,volume:this.volume,bus:this.bus,pitchVariation:this.pitchVariation,volumeVariation:this.volumeVariation}}static getPropertySchema(){let e=I.getPropertySchema();return{nodeType:"AudioPlayer",extends:"NodeBase",properties:[...e.properties,{name:"audioTrack",type:"string",ui:{label:"Audio Track",description:"Asset URL (res://..., data:audio/..., or absolute URL)",group:"Audio",editor:"audio-resource"},getValue:t=>t.audioTrack??"",setValue:(t,i)=>{t.audioTrack=n.normalizeTrack(i)}},{name:"autoplay",type:"boolean",ui:{label:"Autoplay",group:"Audio"},getValue:t=>t.autoplay,setValue:(t,i)=>{let r=t;r.autoplay=n.toBoolean(i,!1),r.autoplay||(r.autoPlayed=!1)}},{name:"loop",type:"boolean",ui:{label:"Loop",group:"Audio"},getValue:t=>t.loop,setValue:(t,i)=>{t.loop=n.toBoolean(i,!1)}},{name:"volume",type:"number",ui:{label:"Volume",group:"Audio",min:0,max:1,step:.01,precision:2},getValue:t=>t.volume,setValue:(t,i)=>{t.volume=n.clampVolume(i,1)}},{name:"bus",type:"enum",ui:{label:"Bus",group:"Audio",options:[...dt]},getValue:t=>t.bus,setValue:(t,i)=>{t.bus=n.normalizeBus(i)}},{name:"pitchVariation",type:"number",ui:{label:"Pitch Variation",description:"Random \xB1 playback-rate spread per shot",group:"Audio",min:0,max:1,step:.01,precision:2},getValue:t=>t.pitchVariation,setValue:(t,i)=>{t.pitchVariation=n.clampVariation(i)}},{name:"volumeVariation",type:"number",ui:{label:"Volume Variation",description:"Random \xB1 volume spread per shot",group:"Audio",min:0,max:1,step:.01,precision:2},getValue:t=>t.volumeVariation,setValue:(t,i)=>{t.volumeVariation=n.clampVariation(i)}}],groups:{...e.groups,Audio:{label:"Audio",expanded:!0}}}}static normalizeTrack(e){if(typeof e!="string")return null;let t=e.trim();return t.length>0?t:null}static toBoolean(e,t){if(typeof e=="boolean")return e;if(typeof e=="string"){let i=e.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return t}static clampVolume(e,t){let i=typeof e=="number"?e:Number(e);return Number.isFinite(i)?Math.min(1,Math.max(0,i)):t}static normalizeBus(e){return typeof e=="string"&&dt.includes(e)?e:"sfx"}static clampVariation(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.min(1,Math.max(0,t)):0}};var Di=["standard","lambert","basic"],Mu="standard",Ei=n=>typeof n=="string"&&Di.includes(n)?n:Mu,Du=n=>n==="basic"?"basic":"standard",Eu=n=>{let e=n;return e?.isMeshStandardMaterial===!0||e?.isMeshPhysicalMaterial===!0?"standard":e?.isMeshLambertMaterial===!0?"lambert":e?.isMeshBasicMaterial===!0?"basic":null},Ni=(n,e)=>{switch(n){case"basic":return new B({color:e.color});case"lambert":return new Am({color:e.color});default:return new hi({color:e.color,roughness:e.roughness,metalness:e.metalness})}};var Nu=["box","sphere","plane","cylinder","cone","torus"],St=class n extends U{_geometry;_material;_geometryKind;_size;_aoMapSrc;_aoMapIntensity=1;_aoSuppressed=!1;_mapSrc="";_materialType;effectStack;constructor(e){super(e,"GeometryMesh");let t=qf(e.geometry),i=e.size??[1,1,1];this._geometryKind=t,this._size=[i[0],i[1],i[2]];let r=n.buildGeometry(t,this._size),o=e.material??{},s=new L(o.color??"#4e8df5"),a=typeof o.roughness=="number"?o.roughness:.35,l=typeof o.metalness=="number"?o.metalness:.25;this._materialType=Ei(o.type),this.effectStack=new _e({nodeType:"GeometryMesh",target:Du(this._materialType)});let c=Ni(this._materialType,{color:s,roughness:a,metalness:l});this._aoMapIntensity=typeof o.aoMapIntensity=="number"?Gf(o.aoMapIntensity):1,c.aoMapIntensity=this._aoMapIntensity,this.installEffectComposer(c);let u=new O(r,c);this.castShadow=e.castShadow??!0,this.receiveShadow=e.receiveShadow??!0,u.castShadow=this.castShadow,u.receiveShadow=this.receiveShadow,u.name=`${this.name}-Mesh`,this.add(u),this._geometry=r,this._material=c,this._aoMapSrc=typeof o.aoMap=="string"?o.aoMap:"",this._mapSrc=typeof o.map=="string"?o.map:"";for(let h of o.effects??[])h&&typeof h.type=="string"&&this.attachEffect(h.type,{enabled:h.enabled,params:h.params})}disposeResources(){try{this._geometry?.dispose()}catch{}try{this._material?.dispose?.()}catch{}}static buildGeometry(e,t){let i=Math.max(1e-4,t[0]),r=Math.max(1e-4,t[1]),o=Math.max(1e-4,t[2]);switch(e){case"sphere":return new es(i/2,32,16);case"plane":{let s=new z(i,o);return s.rotateX(-Math.PI/2),s}case"cylinder":return new wm(i/2,i/2,r,32);case"cone":return new xm(i/2,r,32);case"torus":{let s=i/2,a=Math.max(.02,Math.min(s*.6,r*.25));return new Pm(s,a,20,40)}default:return new rr(i,r,o)}}get materialType(){return this._materialType}set materialType(e){let t=Ei(e);if(t===this._materialType)return;let i=this._material,r=this._colorMaterial?.color.clone()??new L("#4e8df5"),o=this._colorMaterial?.map??null,s=this._stdMaterial,a=Ni(t,{color:r,roughness:s?.roughness??.35,metalness:s?.metalness??.25});this._materialType=t,this.effectStack.retarget(Du(t)),i&&this.effectStack.uninstall(i),this.installEffectComposer(a);let l=a;o&&(l.map=o);let c=s?.aoMap??null;c&&(l.aoMap=c,a.aoMapIntensity=this._aoSuppressed?0:this._aoMapIntensity);let u=this._mesh;u&&(u.material=a),this._material=a,a.needsUpdate=!0;try{i?.dispose?.()}catch{}}rebuildGeometry(){let e=n.buildGeometry(this._geometryKind,this._size),t=this._geometry,i=this._mesh;i&&(i.geometry=e),this._geometry=e,this._colorMaterial?.aoMap&&n.applyLightmapUV(this._geometryKind,e);try{t?.dispose()}catch{}}ensureLightmapUV(){n.applyLightmapUV(this._geometryKind,this._geometry)}get renderMesh(){return this._mesh}setAOMap(e){let t=this._colorMaterial;t&&(e&&(e.channel=1,e.flipY=!1,n.applyLightmapUV(this._geometryKind,this._geometry)),t.aoMap=e,t.needsUpdate=!0)}get aoMapIntensity(){return this._aoMapIntensity}set aoMapIntensity(e){this._aoMapIntensity=Gf(e);let t=this._colorMaterial;t&&!this._aoSuppressed&&(t.aoMapIntensity=this._aoMapIntensity)}setAOSuppressed(e){this._aoSuppressed=e;let t=this._colorMaterial;t&&(t.aoMapIntensity=e?0:this._aoMapIntensity)}get aoMapSrc(){return this._aoMapSrc}set aoMapSrc(e){this._aoMapSrc=typeof e=="string"?e:""}setMap(e){let t=this._colorMaterial;t&&(e&&(e.colorSpace=Pe),t.map=e,t.needsUpdate=!0)}setMapResource(e){this._mapSrc=h0(e)}get mapSrc(){return this._mapSrc}set mapSrc(e){this._mapSrc=typeof e=="string"?e:""}getShaderEffectStack(){return this.effectStack}installEffectComposer(e){this.effectStack.install(e)}attachEffect(e,t){return this.effectStack.attach(e,t)}detachEffect(e){return this.effectStack.detach(e)}setEffectEnabled(e,t){this.effectStack.setEnabled(e,t)}getAttachedEffects(){return this.effectStack.getAttached()}getInstancePropertySchema(){return this.effectStack.buildInstanceSchema()}tick(e){this.effectStack.tick(e),super.tick(e)}static applyLightmapUV(e,t){if(!t)return;let i=t.getAttribute("uv");if(i){if(e==="box"){let s=.3333333333333333,a=1/2,l=.04,c=new Float32Array(i.count*2);for(let u=0;u<i.count;u+=1){let h=Math.floor(u/4)%6,d=h%3,p=Math.floor(h/3),f=i.getX(u),m=i.getY(u);c[u*2]=(d+l+f*(1-2*l))*s,c[u*2+1]=(p+l+m*(1-2*l))*a}t.setAttribute("uv1",new Q(c,2));return}t.setAttribute("uv1",new Q(i.array.slice(0),i.itemSize))}}get geometryKind(){return this._geometryKind}set geometryKind(e){let t=qf(e);t!==this._geometryKind&&(this._geometryKind=t,this.rebuildGeometry())}get size(){return[this._size[0],this._size[1],this._size[2]]}set size(e){this._size=[Number.isFinite(e[0])?e[0]:this._size[0],Number.isFinite(e[1])?e[1]:this._size[1],Number.isFinite(e[2])?e[2]:this._size[2]],this.rebuildGeometry()}serializeConfig(){let e=this._colorMaterial,t={type:this._materialType};e&&(t.color="#"+e.color.getHexString());let i=this._stdMaterial;return i&&(t.roughness=i.roughness,t.metalness=i.metalness),this._aoMapSrc&&(t.aoMap=this._aoMapSrc,t.aoMapIntensity=this._aoMapIntensity),this._mapSrc&&(t.map=this._mapSrc),this.effectStack.isEmpty||(t.effects=this.effectStack.serialize()),{geometry:this._geometryKind,size:[this._size[0],this._size[1],this._size[2]],castShadow:this.castShadow,receiveShadow:this.receiveShadow,material:t}}applyShadowFlags(){let e=this._mesh;e&&(e.castShadow=this.castShadow,e.receiveShadow=this.receiveShadow)}get _mesh(){return this.children.find(e=>e instanceof O)}get _colorMaterial(){let e=this._mesh?.material;return e&&!Array.isArray(e)&&"color"in e?e:void 0}get _stdMaterial(){let e=this._mesh?.material;return e instanceof hi?e:void 0}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"GeometryMesh",properties:[x("geometry","enum",{ui:{label:"Shape",group:"Geometry",options:[...Nu]},getValue:i=>i.geometryKind,setValue:(i,r)=>{i.geometryKind=String(r)}}),x("size","vector3",{ui:{label:"Size",description:"Interpreted per shape (box: extents, sphere: diameter, etc.)",group:"Geometry",min:0,step:.01,precision:2},getValue:i=>{let r=i._size;return{x:r[0],y:r[1],z:r[2]}},setValue:(i,r)=>{let o=r;i.size=[Number(o?.x),Number(o?.y),Number(o?.z)]}}),x("materialType","enum",{ui:{label:"Material",description:"standard = PBR (desktop look), lambert = diffuse-only (the mobile default), basic = unlit (needs no light at all)",group:"Material",options:[...Di]},getValue:i=>i.materialType,setValue:(i,r)=>{i.materialType=String(r)}}),x("color","color",{ui:{label:"Color",group:"Material"},getValue:i=>{let r=i._colorMaterial;return r?"#"+r.color.getHexString():"#4e8df5"},setValue:(i,r)=>{let o=i._colorMaterial;o&&o.color.set(String(r))}}),x("roughness","number",{ui:{label:"Roughness",group:"Material",step:.01,precision:2,min:0,max:1,readOnly:i=>!i._stdMaterial},getValue:i=>i._stdMaterial?.roughness??.35,setValue:(i,r)=>{let o=i._stdMaterial;o&&(o.roughness=Number(r))}}),x("metalness","number",{ui:{label:"Metalness",group:"Material",step:.01,precision:2,min:0,max:1,readOnly:i=>!i._stdMaterial},getValue:i=>i._stdMaterial?.metalness??.25,setValue:(i,r)=>{let o=i._stdMaterial;o&&(o.metalness=Number(r))}}),x("aoMapIntensity","number",{ui:{label:"AO Intensity",description:"Strength of the baked ambient-occlusion map (0 = off)",group:"Material",min:0,max:1,step:.01,precision:2,slider:!0,readOnly:i=>!i._colorMaterial?.aoMap},getValue:i=>i.aoMapIntensity,setValue:(i,r)=>{i.aoMapIntensity=Number(r)}}),x("castShadow","boolean",{ui:{label:"Cast Shadow",description:"Whether this mesh casts shadows in the scene",group:"Rendering"},getValue:i=>i.castShadow,setValue:(i,r)=>{let o=i;o.castShadow=!!r,o.applyShadowFlags()}}),x("receiveShadow","boolean",{ui:{label:"Receive Shadow",description:"Whether this mesh receives shadows cast by other objects",group:"Rendering"},getValue:i=>i.receiveShadow,setValue:(i,r)=>{let o=i;o.receiveShadow=!!r,o.applyShadowFlags()}}),x("map","object",{ui:{label:"Albedo Map",description:"Diffuse texture (res://). Required for the UV Scroll effect to be visible.",group:"Material",editor:"texture-resource",resourceType:"texture"},getValue:i=>({type:"texture",url:i._mapSrc}),setValue:(i,r)=>{i.setMapResource(r)}})],groups:{Geometry:{label:"Geometry",expanded:!0},Material:{label:"Material",expanded:!0},Rendering:{label:"Rendering",description:"Shadow and rendering properties",expanded:!0}}};return le(e,t)}};function qf(n){let e=typeof n=="string"?n.toLowerCase():"";return Nu.includes(e)?e:"box"}function Gf(n){let e=Number(n);return Number.isFinite(e)?e<0?0:e>1?1:e:1}function h0(n){if(typeof n=="string")return n;if(n&&typeof n=="object"){let e=n.url;if(typeof e=="string")return e}return""}var jf=new rr(1,1,1),Ls="#ffffff",Iu=1,Ru=0,d0="standard",$f=n=>Array.isArray(n)?n[0]:n,Bu=new S,Ou=new F,Vu=new S(1,1,1),Yf=new se,p0=new L,vt=class extends U{mesh;maxInstances;castShadow;receiveShadow;enablePerInstanceColor;matrixBuffer;colorBuffer;_materialType;_ownsMaterial;transformsDirty=!1;colorsDirty=!1;boundsDirty=!1;constructor(e){super(e,"InstancedMesh3D");let t=Math.floor(e.maxInstances);if(!Number.isFinite(t)||t<=0)throw new Error("[InstancedMesh3D] maxInstances must be a positive integer.");this.maxInstances=t,this.castShadow=e.castShadow??!1,this.receiveShadow=e.receiveShadow??!1,this.enablePerInstanceColor=e.enablePerInstanceColor??!1;let i=e.geometry??jf,r=e.materialConfig??{};this._ownsMaterial=e.material===void 0;let o=e.material??Ni(Ei(r.type),{color:new L(r.color??Ls),roughness:typeof r.roughness=="number"?r.roughness:Iu,metalness:typeof r.metalness=="number"?r.metalness:Ru});this._materialType=(e.material?Eu($f(e.material)):null)??Ei(r.type),this.mesh=new tr(i,o,t),this.mesh.name=`${this.name}-mesh`,this.mesh.castShadow=this.castShadow,this.mesh.receiveShadow=this.receiveShadow,this.mesh.frustumCulled=e.frustumCulled??!1,this.mesh.count=0,this.mesh.instanceMatrix.setUsage(oe),this.matrixBuffer=this.mesh.instanceMatrix.array,this.enablePerInstanceColor?(this.colorBuffer=new Float32Array(t*3),this.mesh.instanceColor=new je(this.colorBuffer,3),this.mesh.instanceColor.setUsage(oe),p0.toArray(this.colorBuffer,0)):this.colorBuffer=null,this.add(this.mesh)}disposeResources(){this.mesh.dispose(),this.mesh.geometry!==jf&&this.mesh.geometry.dispose();let e=this.mesh.material;for(let t of Array.isArray(e)?e:[e])t?.dispose()}get materialSlots(){let e=this.mesh.material;return Array.isArray(e)?e.filter(Boolean):e?[e]:[]}get singleMaterial(){return this.materialSlots[0]??null}get materialType(){return this._materialType}set materialType(e){let t=Ei(e);if(t===this._materialType&&this._ownsMaterial)return;let i=this.materialSlots,r=i.map(o=>Ni(t,{color:this.colorOf(o)?.clone()??new L(Ls),...this.pbrOf(o)}));this._materialType=t,this.mesh.material=Array.isArray(this.mesh.material)?r:r[0]??Ni(t,{color:new L(Ls),roughness:Iu,metalness:Ru}),this._ownsMaterial=!0;for(let o of i)o.dispose()}get color(){let e=this.colorOf(this.singleMaterial);return e?`#${e.getHexString()}`:Ls}set color(e){for(let t of this.materialSlots)this.colorOf(t)?.set(e)}serializeMaterialConfig(){if(Array.isArray(this.mesh.material)||!this.singleMaterial)return null;let e={type:this._materialType,color:this.color};return this._materialType==="standard"&&Object.assign(e,this.pbrOf(this.singleMaterial)),e}colorOf(e){let t=e?.color;return t instanceof L?t:null}pbrOf(e){let t=e;return{roughness:typeof t?.roughness=="number"?t.roughness:Iu,metalness:typeof t?.metalness=="number"?t.metalness:Ru}}get visibleInstanceCount(){return this.mesh.count}set visibleInstanceCount(e){this.mesh.count=this.clampVisibleCount(e)}setGeometry(e){this.mesh.geometry=e,this.boundsDirty=!0}setMaterial(e){let t=this.materialSlots;this.mesh.material=e,this._materialType=Eu($f(e))??d0,this._ownsMaterial=!1;for(let i of t)(Array.isArray(e)?e.includes(i):e===i)||i.dispose()}writeMatrices(e,t={}){let i=this.validateCount(e.count),r=i*16;if(e.matrices.length<r)throw new Error("[InstancedMesh3D] Matrices array is smaller than count * 16.");this.matrixBuffer.set(e.matrices.subarray(0,r),0),this.applyWriteOptions(i,t,!0,!1)}writeTransforms(e,t={}){let i=this.validateCount(e.count);this.validateOptionalArrayLength(e.positions,i*3,"positions"),this.validateOptionalArrayLength(e.rotations,i*4,"rotations"),this.validateOptionalArrayLength(e.scales,i*3,"scales");for(let r=0;r<i;r+=1){let o=r*3,s=r*4,a=r*16;e.positions?Bu.set(e.positions[o]??0,e.positions[o+1]??0,e.positions[o+2]??0):Bu.set(0,0,0),e.rotations?Ou.set(e.rotations[s]??0,e.rotations[s+1]??0,e.rotations[s+2]??0,e.rotations[s+3]??1):Ou.set(0,0,0,1),e.scales?Vu.set(e.scales[o]??1,e.scales[o+1]??1,e.scales[o+2]??1):Vu.set(1,1,1),Yf.compose(Bu,Ou,Vu),Yf.toArray(this.matrixBuffer,a)}this.applyWriteOptions(i,t,!0,!1)}writeColors(e,t={}){if(!this.colorBuffer||!this.mesh.instanceColor)throw new Error("[InstancedMesh3D] Per-instance colors are disabled. Enable enablePerInstanceColor first.");let i=this.validateCount(e.count),r=i*3;if(e.colors.length<r)throw new Error("[InstancedMesh3D] Colors array is smaller than count * 3.");this.colorBuffer.set(e.colors.subarray(0,r),0),this.applyWriteOptions(i,t,!1,!0)}markTransformsDirty(){this.transformsDirty=!0}markColorsDirty(){this.colorBuffer&&(this.colorsDirty=!0)}flush(){this.transformsDirty&&(this.mesh.instanceMatrix.needsUpdate=!0,this.transformsDirty=!1),this.colorsDirty&&this.mesh.instanceColor&&(this.mesh.instanceColor.needsUpdate=!0,this.colorsDirty=!1),this.boundsDirty&&(this.mesh.computeBoundingBox(),this.mesh.computeBoundingSphere(),this.boundsDirty=!1)}clearInstances(){this.mesh.count=0}getInstanceMatrixBuffer(){return this.matrixBuffer}getInstanceColorBuffer(){return this.colorBuffer}static getPropertySchema(){let e=U.getPropertySchema();return{nodeType:"InstancedMesh3D",extends:"Node3D",properties:[...e.properties,{name:"maxInstances",type:"number",ui:{label:"Max Instances",group:"Rendering",readOnly:!0},getValue:t=>t.maxInstances,setValue:()=>{}},{name:"materialType",type:"enum",ui:{label:"Material Type",description:"standard = PBR (desktop-class cost), lambert = diffuse-only (the mobile default), basic = unlit",group:"Material",options:[...Di]},getValue:t=>t.materialType,setValue:(t,i)=>{t.materialType=String(i)}},{name:"color",type:"color",ui:{label:"Color",description:"Shared by every instance; per-instance colour multiplies it",group:"Material"},getValue:t=>t.color,setValue:(t,i)=>{t.color=String(i)}},{name:"castShadow",type:"boolean",ui:{label:"Cast Shadow",group:"Rendering"},getValue:t=>t.mesh.castShadow,setValue:(t,i)=>{t.mesh.castShadow=!!i}},{name:"receiveShadow",type:"boolean",ui:{label:"Receive Shadow",group:"Rendering"},getValue:t=>t.mesh.receiveShadow,setValue:(t,i)=>{t.mesh.receiveShadow=!!i}},{name:"enablePerInstanceColor",type:"boolean",ui:{label:"Per-Instance Color",group:"Rendering",readOnly:!0},getValue:t=>t.enablePerInstanceColor,setValue:()=>{}},{name:"visibleInstanceCount",type:"number",ui:{label:"Visible Instances",group:"Debug",readOnly:!0},getValue:t=>t.visibleInstanceCount,setValue:()=>{}}],groups:{...e.groups,Material:{label:"Material",description:"The one material every instance renders with",expanded:!0},Rendering:{label:"Rendering",description:"Instanced mesh rendering options",expanded:!0},Debug:{label:"Debug",description:"Runtime-only instancing diagnostics",expanded:!1}}}}applyWriteOptions(e,t,i,r){t.visibleCount!==void 0?this.visibleInstanceCount=t.visibleCount:this.mesh.count<e&&(this.visibleInstanceCount=e),i&&t.markTransformDirty!==!1&&(this.transformsDirty=!0),r&&t.markColorDirty!==!1&&(this.colorsDirty=!0),t.computeBoundingSphere&&(this.boundsDirty=!0)}validateCount(e){let t=Math.floor(e);if(!Number.isFinite(t)||t<0)throw new Error("[InstancedMesh3D] Instance count must be a non-negative integer.");if(t>this.maxInstances)throw new Error(`[InstancedMesh3D] Instance count ${t} exceeds maxInstances ${this.maxInstances}.`);return t}clampVisibleCount(e){let t=Math.floor(e);if(!Number.isFinite(t)||t<0)throw new Error("[InstancedMesh3D] visibleInstanceCount must be a non-negative integer.");return Math.min(t,this.maxInstances)}validateOptionalArrayLength(e,t,i){if(e&&e.length<t)throw new Error(`[InstancedMesh3D] ${i} array is smaller than required stride.`)}};var Qf=3,_s=new se,Lu=new S,Kf=new S,Xf=new F,Fs=(n,e,t,i)=>{e instanceof S?Lu.copy(e):Lu.set(e,t??0,i??0),n.updateWorldMatrix(!0,!1),Kf.setFromMatrixPosition(n.matrixWorld),_s.lookAt(Kf,Lu,n.up),n.quaternion.setFromRotationMatrix(_s);let r=n.parent;r&&(_s.extractRotation(r.matrixWorld),Xf.setFromRotationMatrix(_s),n.quaternion.premultiply(Xf.invert()))},pe=class extends U{camera;targetDistance=Qf;shakeRafId=null;projectionMode;perspectiveFov;orthographicSizeValue;constructor(e){super(e,"Camera3D"),this.projectionMode=e.projection??"perspective",this.perspectiveFov=e.fov??60,this.orthographicSizeValue=e.orthographicSize??5,this.camera=new ge,this.add(this.camera),this.rebuildCamera({projection:this.projectionMode,fov:this.perspectiveFov,near:e.near??.1,far:e.far??1e3,orthographicSize:this.orthographicSizeValue})}lookAt(e,t,i){Fs(this,e,t,i)}getTargetPosition(){let e=this.getWorldPosition(new S),t=this.getWorldQuaternion(new F),i=new S(0,0,-1).applyQuaternion(t);return e.add(i.multiplyScalar(this.targetDistance))}setTargetPosition(e){let t=this.getWorldPosition(new S),i=e.clone().sub(t),r=i.length();r>1e-6&&(this.targetDistance=r);let s=(i.lengthSq()>1e-8?i.normalize():new S(0,0,-1).applyQuaternion(this.getWorldQuaternion(new F))).clone(),a=this.parent;if(a){let c=a.getWorldQuaternion(new F);s.applyQuaternion(c.invert())}s.normalize();let l=new F().setFromUnitVectors(new S(0,0,-1),s);this.quaternion.copy(l),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0)}get fov(){return this.perspectiveFov}set fov(e){this.perspectiveFov=Number(e),this.camera instanceof ge&&(this.camera.fov=this.perspectiveFov,this.camera.updateProjectionMatrix())}get projection(){return this.projectionMode}set projection(e){this.rebuildCamera({projection:e})}get near(){return this.camera.near}set near(e){let t=Number(e);(this.camera instanceof ge||this.camera instanceof de)&&(this.camera.near=t,this.camera.updateProjectionMatrix())}get far(){return this.camera.far}set far(e){let t=Number(e);(this.camera instanceof ge||this.camera instanceof de)&&(this.camera.far=t,this.camera.updateProjectionMatrix())}get orthographicSize(){return this.orthographicSizeValue}set orthographicSize(e){let t=Math.max(1e-4,Number(e));this.orthographicSizeValue=t,this.camera instanceof de&&this.applyOrthographicSize(this.camera,t)}updateAspectRatio(e){if(this.camera instanceof ge){this.camera.aspect!==e&&(this.camera.aspect=e,this.camera.updateProjectionMatrix());return}if(this.camera instanceof de){let t=Number.isFinite(e)&&e>0?e:1,i=this.orthographicSize/2,r=i*t;(this.camera.left!==-r||this.camera.right!==r||this.camera.top!==i||this.camera.bottom!==-i)&&(this.camera.left=-r,this.camera.right=r,this.camera.top=i,this.camera.bottom=-i,this.camera.updateProjectionMatrix())}}shake(e=.2,t=.35){if(e<=0||t<=0)return;this.stopShake();let i=performance.now(),r=o=>{let s=(o-i)/1e3,a=Math.min(1,s/t);if(a>=1){this.stopShake();return}let l=1-a,c=e*l;this.camera.position.set((Math.random()*2-1)*c,(Math.random()*2-1)*c,(Math.random()*2-1)*c*.35),this.shakeRafId=requestAnimationFrame(r)};this.shakeRafId=requestAnimationFrame(r)}stopShake(){this.shakeRafId!==null&&(cancelAnimationFrame(this.shakeRafId),this.shakeRafId=null),this.camera.position.set(0,0,0)}rebuildCamera(e){let t=e.projection??this.projectionMode,i=e.near??this.near??.1,r=e.far??this.far??1e3;this.projectionMode=t,this.perspectiveFov=e.fov??this.perspectiveFov??60,this.orthographicSizeValue=Math.max(1e-4,e.orthographicSize??this.orthographicSizeValue??5);let o=this.camera,s=t==="perspective"?new ge(this.perspectiveFov,1,i,r):new de(-1,1,1,-1,i,r);s.layers.mask=o.layers.mask,s.position.copy(o.position),s.quaternion.copy(o.quaternion),s.scale.copy(o.scale),s.visible=o.visible,s.name=o.name,s.matrixAutoUpdate=o.matrixAutoUpdate,s.matrix.copy(o.matrix),s.matrixWorld.copy(o.matrixWorld),s.matrixWorldAutoUpdate=o.matrixWorldAutoUpdate,s.matrixWorldNeedsUpdate=o.matrixWorldNeedsUpdate,this.remove(o),this.camera=s,this.add(this.camera),this.camera.position.set(0,0,0),this.camera.rotation.set(0,0,0),this.camera instanceof de?this.applyOrthographicSize(this.camera,this.orthographicSizeValue):this.camera instanceof ge&&(this.camera.fov=this.perspectiveFov,this.camera.updateProjectionMatrix())}applyOrthographicSize(e,t){let i=Math.max(1e-4,t)/2;e.left=-i,e.right=i,e.top=i,e.bottom=-i,e.updateProjectionMatrix()}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"Camera3D",properties:[x("projection","enum",{ui:{label:"Projection",group:"Camera",options:["perspective","orthographic"]},getValue:i=>i.projection,setValue:(i,r)=>{i.projection=r==="orthographic"?"orthographic":"perspective"}}),x("fov","number",{getValue:i=>i.fov,setValue:(i,r)=>{i.fov=Number(r)},validation:{validate:i=>Number.isFinite(Number(i))&&Number(i)>0},ui:{label:"Field of View",group:"Camera",unit:"\xB0",step:.1,precision:1,readOnly:i=>i.projection!=="perspective"}}),x("orthographicSize","number",{ui:{label:"Orthographic Size",group:"Camera",step:.1,precision:2,readOnly:i=>i.projection!=="orthographic"},getValue:i=>i.orthographicSize,setValue:(i,r)=>{i.orthographicSize=Number(r)},validation:{validate:i=>Number.isFinite(Number(i))&&Number(i)>0}}),x("near","number",{ui:{label:"Near Plane",group:"Camera",step:.01,precision:2},getValue:i=>i.near,setValue:(i,r)=>{i.near=Number(r)},validation:{validate:i=>Number.isFinite(Number(i))&&Number(i)>0}}),x("far","number",{ui:{label:"Far Plane",group:"Camera",step:1,precision:0},getValue:i=>i.far,setValue:(i,r)=>{i.far=Number(r)},validation:{validate:i=>Number.isFinite(Number(i))&&Number(i)>0}})],groups:{Camera:{label:"Camera",expanded:!0}}};return le(e,t)}};var zs=2.5949095,Jf=1.70158+1,Zf=2*Math.PI/3,eg=2*Math.PI/4.5;function Us(n){if(n<1/2.75)return 7.5625*n*n;if(n<2/2.75){let r=n-.5454545454545454;return 7.5625*r*r+.75}if(n<2.5/2.75){let r=n-.8181818181818182;return 7.5625*r*r+.9375}let i=n-2.625/2.75;return 7.5625*i*i+.984375}var Ws={linear:n=>n,step:()=>0,sineIn:n=>1-Math.cos(n*Math.PI/2),sineOut:n=>Math.sin(n*Math.PI/2),sineInOut:n=>-(Math.cos(Math.PI*n)-1)/2,quadIn:n=>n*n,quadOut:n=>1-(1-n)*(1-n),quadInOut:n=>n<.5?2*n*n:1-Math.pow(-2*n+2,2)/2,cubicIn:n=>n*n*n,cubicOut:n=>1-Math.pow(1-n,3),cubicInOut:n=>n<.5?4*n*n*n:1-Math.pow(-2*n+2,3)/2,expoIn:n=>n===0?0:Math.pow(2,10*n-10),expoOut:n=>n===1?1:1-Math.pow(2,-10*n),expoInOut:n=>n===0?0:n===1?1:n<.5?Math.pow(2,20*n-10)/2:(2-Math.pow(2,-20*n+10))/2,backIn:n=>Jf*n*n*n-1.70158*n*n,backOut:n=>1+Jf*Math.pow(n-1,3)+1.70158*Math.pow(n-1,2),backInOut:n=>n<.5?Math.pow(2*n,2)*((zs+1)*2*n-zs)/2:(Math.pow(2*n-2,2)*((zs+1)*(n*2-2)+zs)+2)/2,elasticIn:n=>n===0?0:n===1?1:-Math.pow(2,10*n-10)*Math.sin((n*10-10.75)*Zf),elasticOut:n=>n===0?0:n===1?1:Math.pow(2,-10*n)*Math.sin((n*10-.75)*Zf)+1,elasticInOut:n=>n===0?0:n===1?1:n<.5?-(Math.pow(2,20*n-10)*Math.sin((20*n-11.125)*eg))/2:Math.pow(2,-20*n+10)*Math.sin((20*n-11.125)*eg)/2+1,bounceIn:n=>1-Us(1-n),bounceOut:Us,bounceInOut:n=>n<.5?(1-Us(1-2*n))/2:(1+Us(2*n-1))/2},_u=Object.keys(Ws);function Ue(n){return typeof n=="string"&&n in Ws}function wt(n,e){let t=e<=0?0:e>=1?1:e;return(Ws[n]??Ws.linear)(t)}var m0=new S(0,1,0),We={priority:10,fov:60,orthographicSize:5,followDamping:8,rotationDamping:8,lookAtWeight:1,blendDuration:1,blendEasing:"cubicInOut"},xt=class extends U{priorityValue;fovValue;orthographicSizeValue;followTargetId;followDampingValue;followOffset=new S;deadzone=new S;lookAtTargetId;lookAtWeightValue;rotationDampingValue;confinerEnabledValue;confinerCenter=new S;confinerSize=new S(10,10,10);blendDurationValue;blendEasingValue;authoredQuaternion=null;scratchWorldPos=new S;scratchTargetPos=new S;scratchDesired=new S;scratchLocal=new S;scratchLookMatrix=new se;scratchLookQuat=new F;scratchBlendQuat=new F;scratchCurrentQuat=new F;scratchParentQuat=new F;constructor(e){super(e,"VirtualCamera3D");let t=We;this.priorityValue=e.priority??t.priority,this.fovValue=e.fov??t.fov,this.orthographicSizeValue=Math.max(1e-4,e.orthographicSize??t.orthographicSize),this.followTargetId=e.followTargetId??"",this.followDampingValue=Math.max(0,e.followDamping??t.followDamping),e.followOffset&&this.followOffset.set(e.followOffset.x,e.followOffset.y,e.followOffset.z),e.deadzone&&this.deadzone.set(Math.max(0,e.deadzone.x),Math.max(0,e.deadzone.y),Math.max(0,e.deadzone.z)),this.lookAtTargetId=e.lookAtTargetId??"",this.lookAtWeightValue=tg(e.lookAtWeight??t.lookAtWeight),this.rotationDampingValue=Math.max(0,e.rotationDamping??t.rotationDamping),this.confinerEnabledValue=e.confinerEnabled??!1,e.confinerCenter&&this.confinerCenter.set(e.confinerCenter.x,e.confinerCenter.y,e.confinerCenter.z),e.confinerSize&&this.confinerSize.set(Math.max(0,e.confinerSize.x),Math.max(0,e.confinerSize.y),Math.max(0,e.confinerSize.z)),this.blendDurationValue=Math.max(0,e.blendDuration??t.blendDuration),this.blendEasingValue=e.blendEasing??t.blendEasing}get priority(){return this.priorityValue}set priority(e){let t=Number(e);this.priorityValue=Number.isFinite(t)?t:this.priorityValue}get fov(){return this.fovValue}set fov(e){let t=Number(e);Number.isFinite(t)&&t>0&&(this.fovValue=t)}get orthographicSize(){return this.orthographicSizeValue}set orthographicSize(e){let t=Number(e);Number.isFinite(t)&&t>0&&(this.orthographicSizeValue=t)}get blendDuration(){return this.blendDurationValue}set blendDuration(e){let t=Number(e);this.blendDurationValue=Number.isFinite(t)?Math.max(0,t):this.blendDurationValue}get blendEasing(){return this.blendEasingValue}set blendEasing(e){Ue(e)&&(this.blendEasingValue=e)}solve(e){this.authoredQuaternion===null&&(this.authoredQuaternion=this.getWorldQuaternion(new F)),this.solveFollow(e),this.applyConfiner(),this.solveLookAt(e)}getDesiredWorldPosition(e){return this.getWorldPosition(e)}getDesiredWorldQuaternion(e){return this.getWorldQuaternion(e)}serializeConfig(){return{priority:this.priorityValue,fov:this.fovValue,orthographicSize:this.orthographicSizeValue,followTargetId:this.followTargetId,followDamping:this.followDampingValue,followOffset:[this.followOffset.x,this.followOffset.y,this.followOffset.z],deadzone:[this.deadzone.x,this.deadzone.y,this.deadzone.z],lookAtTargetId:this.lookAtTargetId,lookAtWeight:this.lookAtWeightValue,rotationDamping:this.rotationDampingValue,confinerEnabled:this.confinerEnabledValue,confinerCenter:[this.confinerCenter.x,this.confinerCenter.y,this.confinerCenter.z],confinerSize:[this.confinerSize.x,this.confinerSize.y,this.confinerSize.z],blendDuration:this.blendDurationValue,blendEasing:this.blendEasingValue}}resolveTarget(e){if(!e)return null;if(this.scene)return this.scene.findNode(e);let t=this;for(;t.parentNode;)t=t.parentNode;return t.findNode(e)}solveFollow(e){let t=this.resolveTarget(this.followTargetId);if(!t||t===this)return;t.getWorldPosition(this.scratchTargetPos),this.scratchDesired.copy(this.scratchTargetPos).add(this.followOffset),this.getWorldPosition(this.scratchWorldPos);let i=vi(this.scratchWorldPos.x,this.scratchDesired.x,this.deadzone.x),r=vi(this.scratchWorldPos.y,this.scratchDesired.y,this.deadzone.y),o=vi(this.scratchWorldPos.z,this.scratchDesired.z,this.deadzone.z),s=ln(this.followDampingValue,e),a=this.scratchWorldPos.x+(i-this.scratchWorldPos.x)*s,l=this.scratchWorldPos.y+(r-this.scratchWorldPos.y)*s,c=this.scratchWorldPos.z+(o-this.scratchWorldPos.z)*s;this.setWorldPosition(a,l,c)}applyConfiner(){if(!this.confinerEnabledValue)return;this.getWorldPosition(this.scratchWorldPos);let e=this.confinerSize.x/2,t=this.confinerSize.y/2,i=this.confinerSize.z/2,r=wi(this.scratchWorldPos.x,this.confinerCenter.x,e),o=wi(this.scratchWorldPos.y,this.confinerCenter.y,t),s=wi(this.scratchWorldPos.z,this.confinerCenter.z,i);(r!==this.scratchWorldPos.x||o!==this.scratchWorldPos.y||s!==this.scratchWorldPos.z)&&this.setWorldPosition(r,o,s)}lookAt(e,t,i){Fs(this,e,t,i)}solveLookAt(e){let t=this.resolveTarget(this.lookAtTargetId);if(!t||t===this||this.authoredQuaternion===null||(this.getWorldPosition(this.scratchWorldPos),t.getWorldPosition(this.scratchTargetPos),this.scratchWorldPos.distanceToSquared(this.scratchTargetPos)<1e-10))return;this.scratchLookMatrix.lookAt(this.scratchWorldPos,this.scratchTargetPos,m0),this.scratchLookQuat.setFromRotationMatrix(this.scratchLookMatrix),this.scratchBlendQuat.copy(this.authoredQuaternion).slerp(this.scratchLookQuat,this.lookAtWeightValue),this.getWorldQuaternion(this.scratchCurrentQuat);let i=ln(this.rotationDampingValue,e);this.scratchCurrentQuat.slerp(this.scratchBlendQuat,i),this.setWorldQuaternion(this.scratchCurrentQuat)}setWorldPosition(e,t,i){this.scratchLocal.set(e,t,i),this.parent&&(this.parent.updateWorldMatrix(!0,!1),this.parent.worldToLocal(this.scratchLocal)),this.position.copy(this.scratchLocal),this.updateWorldMatrix(!0,!1)}setWorldQuaternion(e){this.parent?(this.parent.getWorldQuaternion(this.scratchParentQuat),this.scratchParentQuat.invert().multiply(e),this.quaternion.copy(this.scratchParentQuat)):this.quaternion.copy(e),this.updateWorldMatrix(!0,!1)}get treeIcon(){return"camera"}static getPropertySchema(){let e=super.getPropertySchema(),t={nodeType:"VirtualCamera3D",properties:[x("priority","number",{ui:{label:"Priority",description:"Highest-priority live virtual camera wins (animatable)",group:"Virtual Camera",step:1,precision:0},getValue:i=>i.priority,setValue:(i,r)=>{i.priority=Number(r)},validation:{validate:i=>Number.isFinite(Number(i))}}),x("fov","number",{ui:{label:"Field of View",group:"Virtual Camera",unit:"\xB0",step:.1,precision:1},getValue:i=>i.fov,setValue:(i,r)=>{i.fov=Number(r)},validation:{validate:i=>Number.isFinite(Number(i))&&Number(i)>0}}),x("orthographicSize","number",{ui:{label:"Orthographic Size",description:"Applied when the render camera is orthographic",group:"Virtual Camera",step:.1,precision:2},getValue:i=>i.orthographicSize,setValue:(i,r)=>{i.orthographicSize=Number(r)},validation:{validate:i=>Number.isFinite(Number(i))&&Number(i)>0}}),x("followTargetId","node",{ui:{label:"Follow Target",description:"Node whose position this camera follows (empty = authored position)",group:"Follow"},getValue:i=>i.followTargetId,setValue:(i,r)=>{i.followTargetId=typeof r=="string"?r:""}}),x("followOffset","vector3",{ui:{label:"Follow Offset",group:"Follow",step:.01,precision:2},getValue:i=>Hs(i.followOffset),setValue:(i,r)=>qs(i.followOffset,r)}),x("followDamping","number",{ui:{label:"Follow Damping",description:"Higher = snappier follow (0 = instant)",group:"Follow",min:0,step:.1,precision:2},getValue:i=>i.followDampingValue,setValue:(i,r)=>{let o=Number(r);Number.isFinite(o)&&o>=0&&(i.followDampingValue=o)}}),x("deadzone","vector3",{ui:{label:"Deadzone",description:"World half-extents the target can move within before the camera follows",group:"Follow",min:0,step:.01,precision:2},getValue:i=>Hs(i.deadzone),setValue:(i,r)=>qs(i.deadzone,r,0)}),x("lookAtTargetId","node",{ui:{label:"Look At Target",description:"Node this camera orients toward (empty = authored rotation)",group:"Look At"},getValue:i=>i.lookAtTargetId,setValue:(i,r)=>{i.lookAtTargetId=typeof r=="string"?r:""}}),x("lookAtWeight","number",{ui:{label:"Look At Weight",description:"0 = keep authored rotation, 1 = fully track the target",group:"Look At",min:0,max:1,step:.01,precision:2,slider:!0},getValue:i=>i.lookAtWeightValue,setValue:(i,r)=>{i.lookAtWeightValue=tg(Number(r))}}),x("rotationDamping","number",{ui:{label:"Rotation Damping",description:"Higher = snappier aim (0 = instant)",group:"Look At",min:0,step:.1,precision:2},getValue:i=>i.rotationDampingValue,setValue:(i,r)=>{let o=Number(r);Number.isFinite(o)&&o>=0&&(i.rotationDampingValue=o)}}),x("confinerEnabled","boolean",{ui:{label:"Confiner",description:"Clamp the camera position inside an axis-aligned box",group:"Confiner"},getValue:i=>i.confinerEnabledValue,setValue:(i,r)=>{i.confinerEnabledValue=!!r}}),x("confinerCenter","vector3",{ui:{label:"Confiner Center",group:"Confiner",step:.01,precision:2,readOnly:i=>!i.confinerEnabledValue},getValue:i=>Hs(i.confinerCenter),setValue:(i,r)=>qs(i.confinerCenter,r)}),x("confinerSize","vector3",{ui:{label:"Confiner Size",group:"Confiner",min:0,step:.01,precision:2,readOnly:i=>!i.confinerEnabledValue},getValue:i=>Hs(i.confinerSize),setValue:(i,r)=>qs(i.confinerSize,r,0)}),x("blendDuration","number",{ui:{label:"Blend In",description:"Seconds to blend the render camera toward this one when it becomes active",group:"Blend",min:0,step:.05,precision:2,unit:"s"},getValue:i=>i.blendDuration,setValue:(i,r)=>{i.blendDuration=Number(r)}}),x("blendEasing","enum",{ui:{label:"Blend Easing",group:"Blend",options:[..._u]},getValue:i=>i.blendEasing,setValue:(i,r)=>{i.blendEasing=r}})],groups:{"Virtual Camera":{label:"Virtual Camera",expanded:!0},Follow:{label:"Follow",expanded:!0},"Look At":{label:"Look At",expanded:!0},Confiner:{label:"Confiner",expanded:!1},Blend:{label:"Blend",expanded:!1}}};return le(e,t)}};function tg(n){return Number.isFinite(n)?n<0?0:n>1?1:n:0}function Hs(n){return{x:n.x,y:n.y,z:n.z}}function qs(n,e,t=Number.NEGATIVE_INFINITY){let i=e,r=Number(i?.x),o=Number(i?.y),s=Number(i?.z);n.set(Number.isFinite(r)?Math.max(t,r):n.x,Number.isFinite(o)?Math.max(t,o):n.y,Number.isFinite(s)?Math.max(t,s):n.z)}var zu=["inherit","off","baked","realtime","adaptive"],rg=["off","baked","realtime","adaptive"],ng="__PIX3_PROJECT_AO_MODE__";function f0(n){globalThis[ng]=sg(n)}function og(){let n=globalThis[ng];return sg(n)}function sg(n){let e=typeof n=="string"?n.toLowerCase():"";return rg.includes(e)?e:"baked"}var ag={affect2D:!0,bloomEnabled:!0,bloomIntensity:1,bloomThreshold:.9,bloomSmoothing:.025,bloomRadius:.85,vignetteEnabled:!1,vignetteOffset:.35,vignetteDarkness:.5,chromaticAberrationEnabled:!1,chromaticAberrationOffset:.002,aoMode:"inherit",ssaoIntensity:2.5,ssaoRadius:.25,lutEnabled:!1,lutSrc:"",lutIntensity:1},it=class extends I{affect2DValue;bloomEnabledValue;bloomIntensityValue;bloomThresholdValue;bloomSmoothingValue;bloomRadiusValue;vignetteEnabledValue;vignetteOffsetValue;vignetteDarknessValue;chromaticAberrationEnabledValue;chromaticAberrationOffsetValue;aoModeValue;ssaoIntensityValue;ssaoRadiusValue;lutEnabledValue;lutSrcValue;lutIntensityValue;constructor(e){super({...e,type:"PostProcess"}),this.isContainer=!1;let t=ag,i=this.properties;this.affect2DValue=fn(e.affect2D??i.affect2D,t.affect2D),this.bloomEnabledValue=fn(e.bloomEnabled??i.bloomEnabled,t.bloomEnabled),this.bloomIntensityValue=tt(e.bloomIntensity??i.bloomIntensity,t.bloomIntensity,0),this.bloomThresholdValue=tt(e.bloomThreshold??i.bloomThreshold,t.bloomThreshold,0),this.bloomSmoothingValue=tt(e.bloomSmoothing??i.bloomSmoothing,t.bloomSmoothing,0),this.bloomRadiusValue=tt(e.bloomRadius??i.bloomRadius,t.bloomRadius,0),this.vignetteEnabledValue=fn(e.vignetteEnabled??i.vignetteEnabled,t.vignetteEnabled),this.vignetteOffsetValue=tt(e.vignetteOffset??i.vignetteOffset,t.vignetteOffset,0),this.vignetteDarknessValue=tt(e.vignetteDarkness??i.vignetteDarkness,t.vignetteDarkness,0),this.chromaticAberrationEnabledValue=fn(e.chromaticAberrationEnabled??i.chromaticAberrationEnabled,t.chromaticAberrationEnabled),this.chromaticAberrationOffsetValue=tt(e.chromaticAberrationOffset??i.chromaticAberrationOffset,t.chromaticAberrationOffset,0),this.aoModeValue=ig(e.aoMode??i.aoMode??t.aoMode),this.ssaoIntensityValue=tt(e.ssaoIntensity??i.ssaoIntensity,t.ssaoIntensity,0),this.ssaoRadiusValue=tt(e.ssaoRadius??i.ssaoRadius,t.ssaoRadius,0),this.lutEnabledValue=fn(e.lutEnabled??i.lutEnabled,t.lutEnabled),this.lutSrcValue=g0(e.lutSrc??i.lutSrc,t.lutSrc),this.lutIntensityValue=tt(e.lutIntensity??i.lutIntensity,t.lutIntensity,0)}get treeIcon(){return"sparkles"}get affect2D(){return this.affect2DValue}set affect2D(e){this.affect2DValue=!!e}get bloomEnabled(){return this.bloomEnabledValue}set bloomEnabled(e){this.bloomEnabledValue=!!e}get bloomIntensity(){return this.bloomIntensityValue}set bloomIntensity(e){this.bloomIntensityValue=Pt(e,0,this.bloomIntensityValue)}get bloomThreshold(){return this.bloomThresholdValue}set bloomThreshold(e){this.bloomThresholdValue=Pt(e,0,this.bloomThresholdValue)}get bloomSmoothing(){return this.bloomSmoothingValue}set bloomSmoothing(e){this.bloomSmoothingValue=Pt(e,0,this.bloomSmoothingValue)}get bloomRadius(){return this.bloomRadiusValue}set bloomRadius(e){this.bloomRadiusValue=Pt(e,0,this.bloomRadiusValue)}get vignetteEnabled(){return this.vignetteEnabledValue}set vignetteEnabled(e){this.vignetteEnabledValue=!!e}get vignetteOffset(){return this.vignetteOffsetValue}set vignetteOffset(e){this.vignetteOffsetValue=Pt(e,0,this.vignetteOffsetValue)}get vignetteDarkness(){return this.vignetteDarknessValue}set vignetteDarkness(e){this.vignetteDarknessValue=Pt(e,0,this.vignetteDarknessValue)}get chromaticAberrationEnabled(){return this.chromaticAberrationEnabledValue}set chromaticAberrationEnabled(e){this.chromaticAberrationEnabledValue=!!e}get chromaticAberrationOffset(){return this.chromaticAberrationOffsetValue}set chromaticAberrationOffset(e){this.chromaticAberrationOffsetValue=Pt(e,0,this.chromaticAberrationOffsetValue)}get aoMode(){return this.aoModeValue}set aoMode(e){this.aoModeValue=ig(e)}getResolvedAOMode(){let e=this.aoModeValue==="inherit"?og():this.aoModeValue;return e==="adaptive"?lg()?"realtime":"baked":e}get ssaoIntensity(){return this.ssaoIntensityValue}set ssaoIntensity(e){this.ssaoIntensityValue=Pt(e,0,this.ssaoIntensityValue)}get ssaoRadius(){return this.ssaoRadiusValue}set ssaoRadius(e){this.ssaoRadiusValue=Pt(e,0,this.ssaoRadiusValue)}get lutEnabled(){return this.lutEnabledValue}set lutEnabled(e){this.lutEnabledValue=!!e}get lutSrc(){return this.lutSrcValue}set lutSrc(e){this.lutSrcValue=typeof e=="string"?e:""}get lutIntensity(){return this.lutIntensityValue}set lutIntensity(e){this.lutIntensityValue=y0(e,this.lutIntensityValue)}isActive(){return this.bloomEnabledValue||this.vignetteEnabledValue||this.chromaticAberrationEnabledValue||this.getResolvedAOMode()==="realtime"||this.lutEnabledValue&&this.lutSrcValue.length>0}getConfig(){return{affect2D:this.affect2DValue,bloom:{enabled:this.bloomEnabledValue,intensity:this.bloomIntensityValue,threshold:this.bloomThresholdValue,smoothing:this.bloomSmoothingValue,radius:this.bloomRadiusValue},vignette:{enabled:this.vignetteEnabledValue,offset:this.vignetteOffsetValue,darkness:this.vignetteDarknessValue},chromaticAberration:{enabled:this.chromaticAberrationEnabledValue,offset:this.chromaticAberrationOffsetValue},ssao:{enabled:this.getResolvedAOMode()==="realtime",intensity:this.ssaoIntensityValue,radius:this.ssaoRadiusValue},lut:{enabled:this.lutEnabledValue,src:this.lutSrcValue,intensity:this.lutIntensityValue}}}serializeConfig(){return{affect2D:this.affect2DValue,bloomEnabled:this.bloomEnabledValue,bloomIntensity:this.bloomIntensityValue,bloomThreshold:this.bloomThresholdValue,bloomSmoothing:this.bloomSmoothingValue,bloomRadius:this.bloomRadiusValue,vignetteEnabled:this.vignetteEnabledValue,vignetteOffset:this.vignetteOffsetValue,vignetteDarkness:this.vignetteDarknessValue,chromaticAberrationEnabled:this.chromaticAberrationEnabledValue,chromaticAberrationOffset:this.chromaticAberrationOffsetValue,aoMode:this.aoModeValue,ssaoIntensity:this.ssaoIntensityValue,ssaoRadius:this.ssaoRadiusValue,lutEnabled:this.lutEnabledValue,lutSrc:this.lutSrcValue,lutIntensity:this.lutIntensityValue}}static getPropertySchema(){return{nodeType:"PostProcess",extends:"NodeBase",properties:[...I.getPropertySchema().properties,x("affect2D","boolean",{ui:{label:"Affect 2D",description:"When on, the 2D content layer also passes through the effect stack",group:"General"},getValue:t=>t.affect2D,setValue:(t,i)=>{t.affect2D=!!i}}),x("bloomEnabled","boolean",{ui:{label:"Enabled",group:"Bloom"},getValue:t=>t.bloomEnabled,setValue:(t,i)=>{t.bloomEnabled=!!i}}),x("bloomIntensity","number",{ui:{label:"Intensity",description:"Overall bloom strength (animatable \u2014 a flash is 3 keys)",group:"Bloom",min:0,step:.05,precision:2,readOnly:t=>!t.bloomEnabled},getValue:t=>t.bloomIntensity,setValue:(t,i)=>{t.bloomIntensity=Number(i)},validation:{validate:t=>Number.isFinite(Number(t))&&Number(t)>=0}}),x("bloomThreshold","number",{ui:{label:"Threshold",description:"Luminance below this is not bloomed",group:"Bloom",min:0,max:1,step:.01,precision:2,slider:!0,readOnly:t=>!t.bloomEnabled},getValue:t=>t.bloomThreshold,setValue:(t,i)=>{t.bloomThreshold=Number(i)}}),x("bloomSmoothing","number",{ui:{label:"Smoothing",group:"Bloom",min:0,max:1,step:.005,precision:3,readOnly:t=>!t.bloomEnabled},getValue:t=>t.bloomSmoothing,setValue:(t,i)=>{t.bloomSmoothing=Number(i)}}),x("bloomRadius","number",{ui:{label:"Radius",group:"Bloom",min:0,max:1,step:.01,precision:2,slider:!0,readOnly:t=>!t.bloomEnabled},getValue:t=>t.bloomRadius,setValue:(t,i)=>{t.bloomRadius=Number(i)}}),x("vignetteEnabled","boolean",{ui:{label:"Enabled",group:"Vignette"},getValue:t=>t.vignetteEnabled,setValue:(t,i)=>{t.vignetteEnabled=!!i}}),x("vignetteOffset","number",{ui:{label:"Offset",group:"Vignette",min:0,max:1,step:.01,precision:2,slider:!0,readOnly:t=>!t.vignetteEnabled},getValue:t=>t.vignetteOffset,setValue:(t,i)=>{t.vignetteOffset=Number(i)}}),x("vignetteDarkness","number",{ui:{label:"Darkness",group:"Vignette",min:0,max:1,step:.01,precision:2,slider:!0,readOnly:t=>!t.vignetteEnabled},getValue:t=>t.vignetteDarkness,setValue:(t,i)=>{t.vignetteDarkness=Number(i)}}),x("chromaticAberrationEnabled","boolean",{ui:{label:"Enabled",group:"Chromatic Aberration"},getValue:t=>t.chromaticAberrationEnabled,setValue:(t,i)=>{t.chromaticAberrationEnabled=!!i}}),x("chromaticAberrationOffset","number",{ui:{label:"Offset",description:"RGB channel separation (animatable \u2014 a damage pulse)",group:"Chromatic Aberration",min:0,max:.1,step:5e-4,precision:4,readOnly:t=>!t.chromaticAberrationEnabled},getValue:t=>t.chromaticAberrationOffset,setValue:(t,i)=>{t.chromaticAberrationOffset=Number(i)}}),x("aoMode","enum",{ui:{label:"Mode",description:"Off \xB7 Baked (per-mesh maps, cheap) \xB7 Realtime (SSAO, desktop) \xB7 Adaptive (by device)",group:"Ambient Occlusion",options:[...zu]},getValue:t=>t.aoMode,setValue:(t,i)=>{t.aoMode=String(i)}}),x("ssaoIntensity","number",{ui:{label:"SSAO Intensity",group:"Ambient Occlusion",min:0,max:4,step:.05,precision:2,slider:!0,readOnly:t=>!Fu(t.aoMode)},getValue:t=>t.ssaoIntensity,setValue:(t,i)=>{t.ssaoIntensity=Number(i)}}),x("ssaoRadius","number",{ui:{label:"SSAO Radius",description:"Sampling radius (larger = broader, softer occlusion)",group:"Ambient Occlusion",min:0,max:2,step:.01,precision:2,slider:!0,readOnly:t=>!Fu(t.aoMode)},getValue:t=>t.ssaoRadius,setValue:(t,i)=>{t.ssaoRadius=Number(i)}}),x("lutEnabled","boolean",{ui:{label:"Enabled",description:"Color grading via a lookup table (.cube / .3dl)",group:"Color Grading"},getValue:t=>t.lutEnabled,setValue:(t,i)=>{t.lutEnabled=!!i}}),x("lutSrc","string",{ui:{label:"LUT",description:"Asset URL of a .cube or .3dl lookup table",group:"Color Grading",readOnly:t=>!t.lutEnabled},getValue:t=>t.lutSrc,setValue:(t,i)=>{t.lutSrc=typeof i=="string"?i:""}}),x("lutIntensity","number",{ui:{label:"Intensity",group:"Color Grading",min:0,max:1,step:.01,precision:2,slider:!0,readOnly:t=>!t.lutEnabled},getValue:t=>t.lutIntensity,setValue:(t,i)=>{t.lutIntensity=Number(i)}})],groups:{General:{label:"General",expanded:!0},Bloom:{label:"Bloom",expanded:!0},Vignette:{label:"Vignette",expanded:!1},"Chromatic Aberration":{label:"Chromatic Aberration",expanded:!1},"Ambient Occlusion":{label:"Ambient Occlusion",expanded:!0},"Color Grading":{label:"Color Grading",expanded:!1}}}}};function ig(n){let e=typeof n=="string"?n.toLowerCase():"";return zu.includes(e)?e:"baked"}function Fu(n){return n==="realtime"||n==="adaptive"}function lg(){if(typeof navigator>"u")return!1;let n=navigator;if(typeof n.userAgentData?.mobile=="boolean"?n.userAgentData.mobile:/Mobi|Android|iPhone|iPad|iPod/i.test(n.userAgent??""))return!1;let t=typeof n.hardwareConcurrency=="number"?n.hardwareConcurrency:4,i=typeof n.deviceMemory=="number"?n.deviceMemory:8;return t>=6&&i>=4}function fn(n,e){return typeof n=="boolean"?n:e}function g0(n,e){return typeof n=="string"?n:e}function tt(n,e,t=Number.NEGATIVE_INFINITY){let i=Number(n);return Number.isFinite(i)?Math.max(t,i):e}function Pt(n,e,t){let i=Number(n);return Number.isFinite(i)?Math.max(e,i):t}function y0(n,e){let t=Number(n);return Number.isFinite(t)?t<0?0:t>1?1:t:e}var Jb=Qp(wd(),1);var Mr=new S(0,0,0),Qb=new S(1,1,1),ti=new N(0,0),GT=new N(1,1),ve=class extends Error{details;constructor(e,t){super(e),this.name="SceneValidationError",this.details=t}},xd=class{assetLoader;scriptRegistry;resourceManager;constructor(e,t,i){this.assetLoader=e,this.scriptRegistry=t,this.resourceManager=i}async parseScene(e,t={}){let i;console.debug("[SceneLoader.parseScene] Starting parse",{contentLength:e.length,contentPreview:e.substring(0,100),filePath:t.filePath});try{i=(0,Jb.parse)(e)}catch(a){throw new ve(`Failed to parse scene YAML${t.filePath?` (${t.filePath})`:""}.`,[a.message])}if(!i)throw console.error("[SceneLoader.parseScene] YAML parser returned null",{contentLength:e.length,contentPreview:e.substring(0,100),filePath:t.filePath}),new ve(`Scene document is empty or invalid${t.filePath?` (${t.filePath})`:""}.`,["The YAML parser returned null or undefined"]);let r=new Map,o=[],s=[...t.instanceStack??[]];for(let a of i.root??[]){let l=await this.instantiateNode(a,null,r,t.filePath??"unknown",s);o.push(l)}return{version:i.version,description:i.description,metadata:i.metadata??{},rootNodes:o,nodeMap:r}}async instantiateNode(e,t,i,r,o){if(e.instance)return await this.instantiateInstanceNode(e,t,i,r,o);if(i.has(e.id))throw new ve(`Duplicate node id "${e.id}" detected.`,[r]);let s=await this.createNodeFromDefinition(e);if(Array.isArray(e.groups))for(let l of e.groups)typeof l=="string"&&l.trim().length>0&&s.addToGroup(l);i.set(s.nodeId,s),ys(s,e.components,this.scriptRegistry),t&&t.adoptChild(s);let a=e.children??[];for(let l of a)await this.instantiateNode(l,s,i,r,o);return s}async instantiatePrefab(e,t){let i={id:t,instance:e};return await this.instantiateInstanceNode(i,null,new Map,`runtime-instantiate:${e}`,[])}async instantiateInstanceNode(e,t,i,r,o){if(i.has(e.id))throw new ve(`Duplicate node id "${e.id}" detected.`,[r]);let s=e.instance;if(!s)throw new ve("Instance node is missing an instance path.",[r]);let a=this.normalizeInstancePath(s);if(o.includes(a)){let f=[...o,a].join(" -> ");throw new ve(`Instance cycle detected for "${a}".`,[f])}let l=[...o,a],c=await this.resourceManager.readText(a),u=await this.parseScene(c,{filePath:a,instanceStack:l});if(!u.rootNodes.length)throw new ve(`Instance "${a}" has no root nodes.`,[r]);if(u.rootNodes.length>1)throw new ve(`Instance "${a}" must contain exactly one root node.`,[r]);let h=u.rootNodes[0],d=new Set(i.keys());d.add(e.id);let p=await this.cloneNodeWithRuntimeIds(h,e.id,i,e.id,a,this.normalizeLocalId(h.nodeId),a,d);return p.name=e.name??p.name,this.addGroupsFromDefinition(p,e),this.mergeMetadata(p,e.metadata??{}),this.remapNodeReferences(p),this.snapshotPrefabBaseProperties(p),this.applyLegacyInstanceRootProperties(p,e.properties??{}),this.applyInstanceOverrides(p,e.overrides??null),t&&t.adoptChild(p),this.registerSubtree(i,p,r),p}normalizeInstancePath(e){return e.replace(/\\/g,"/").trim()}normalizeLocalId(e){return e.replace(/\\/g,"/").replace(/^\/+/,"").trim()}addGroupsFromDefinition(e,t){if(Array.isArray(t.groups))for(let i of t.groups)typeof i=="string"&&i.trim().length>0&&e.addToGroup(i)}mergeMetadata(e,t){Object.assign(e.metadata,t)}registerSubtree(e,t,i){let r=[t];for(;r.length>0;){let o=r.pop();if(o){if(e.has(o.nodeId))throw new ve(`Duplicate node id "${o.nodeId}" detected.`,[i]);e.set(o.nodeId,o);for(let s of o.children)s instanceof I&&r.push(s)}}}async cloneNodeWithRuntimeIds(e,t,i,r,o,s,a,l){let c=this.getPrefabMarker(e),u=this.normalizeLocalId(c?.localId??e.nodeId),h=c?.sourcePath??o,d={id:t,type:e.type,name:e.name,instancePath:t===r?a??e.instancePath??void 0:e.instancePath??void 0,groups:Array.from(e.groups),properties:this.captureNodeComparableProperties(e),metadata:{...e.metadata},components:Jr(e)},p=this.createPrefabMarker({localId:u,effectiveLocalId:s,instanceRootId:r,sourcePath:h}),f=d.metadata??{};f.__pix3Prefab=p,d.metadata=f;let m=await this.createNodeFromDefinition(d);this.populateNodeComponents(m,d.components??[]);for(let g of e.children){if(!(g instanceof I))continue;let y=this.generateUniqueRuntimeNodeId(this.normalizeLocalId(g.nodeId),i,l),b=this.getPrefabMarker(g),v=this.normalizeLocalId(b?.localId??g.nodeId),w=`${s}/${v}`,k=await this.cloneNodeWithRuntimeIds(g,y,i,r,h,w,null,l);m.adoptChild(k)}return m}createPrefabMarker(e){return{localId:this.normalizeLocalId(e.localId),effectiveLocalId:this.normalizeLocalId(e.effectiveLocalId),instanceRootId:e.instanceRootId,sourcePath:e.sourcePath}}populateNodeComponents(e,t){ys(e,t,this.scriptRegistry)}resolvePendingComponents(e){return nu(e,this.scriptRegistry)}generateUniqueRuntimeNodeId(e,t,i){let r=e.replace(/[^a-zA-Z0-9_-]/g,"-").toLowerCase()||"node",o=r,s=1;for(;t.has(o)||i.has(o);)o=`${r}-${s}`,s+=1;return i.add(o),o}remapNodeReferences(e){let t=new Map,i=new Map;this.walkSubtree(e,r=>{let o=this.getPrefabMarker(r);o&&(t.has(o.sourcePath)||t.set(o.sourcePath,new Map),t.get(o.sourcePath)?.set(o.localId,r.nodeId),i.set(o.effectiveLocalId,r.nodeId))}),this.walkSubtree(e,r=>{let o=this.getPrefabMarker(r),s=o?t.get(o.sourcePath)??null:null,a=ke(r);this.remapPropertiesBySchema(r,a.properties,s,i);for(let l of r.components){let c=this.scriptRegistry.getComponentPropertySchema(l.type);c&&this.remapPropertiesBySchema(l,c.properties,s,i)}})}remapPropertiesBySchema(e,t,i,r){for(let o of t){if(o.type!=="node")continue;let s=o.getValue(e);if(typeof s!="string"||!s.trim())continue;let a=(i?i.get(this.normalizeLocalId(s)):void 0)??r.get(this.normalizeLocalId(s));a&&a!==s&&o.setValue(e,a)}}snapshotPrefabBaseProperties(e){let t={};this.walkSubtree(e,o=>{let s=this.getPrefabMarker(o);s&&(t[s.effectiveLocalId]=this.captureNodeComparableProperties(o))});let i=this.getPrefabMarker(e);if(!i)return;let r={...i,basePropertiesByLocalId:t};e.metadata.__pix3Prefab=r}captureNodeComparableProperties(e){let t=ke(e),i={};for(let r of t.properties)r.ui?.hidden||r.ui?.readOnly===!0||(i[r.name]=this.cloneValue(r.getValue(e)));return i}applyInstanceOverrides(e,t){if(!t||!t.byLocalId)return;let i=new Map;this.walkSubtree(e,s=>{let a=this.getPrefabMarker(s);a&&i.set(a.effectiveLocalId,s)});let o=this.getPrefabMarker(e)?.effectiveLocalId??"";for(let[s,a]of Object.entries(t.byLocalId)){let l=this.normalizeLocalId(s),c=o&&l!==o?`${o}/${l}`:l,u=i.get(c)??i.get(l);if(!u){console.warn(`[SceneLoader] Override target "${s}" not found in instance.`);continue}this.applyLegacyInstanceRootProperties(u,a.properties??{})}}applyLegacyInstanceRootProperties(e,t){if(!t||Object.keys(t).length===0)return;let i=ke(e),r=new Map(i.properties.map(l=>[l.name,l])),o=Object.entries(t),s=new Set(Vt.map(l=>C.marginPropertyName(l))),a=[...o.filter(([l])=>!s.has(l)),...o.filter(([l])=>s.has(l))];for(let[l,c]of a){if(l==="transform"){this.applyTransformOverride(e,r,c);continue}let u=r.get(l);if(!u){e.properties[l]=this.cloneValue(c);continue}u.setValue(e,this.normalizePropertyValue(c,u))}}applyTransformOverride(e,t,i){let r=this.asRecord(i);if(!r)return;let o=r.position??r.translate,s=r.rotationEuler??r.rotation??r.euler,a=r.scale,l=t.get("position");l&&o!==void 0&&l.setValue(e,this.normalizePropertyValue(o,l));let c=t.get("rotation");c&&s!==void 0&&c.setValue(e,this.normalizePropertyValue(s,c));let u=t.get("scale");u&&a!==void 0&&u.setValue(e,this.normalizePropertyValue(a,u))}normalizePropertyValue(e,t){if(t.type==="vector2"){let i=this.readVector2(e,ti);return{x:i.x,y:i.y}}if(t.type==="vector3"||t.type==="euler"){let i=this.readVector3(e,Mr);return{x:i.x,y:i.y,z:i.z}}return e}walkSubtree(e,t){let i=[e];for(;i.length>0;){let r=i.pop();if(r){t(r);for(let o of r.children)o instanceof I&&i.push(o)}}}getPrefabMarker(e){let i=e.metadata.__pix3Prefab;if(!i||typeof i!="object")return null;let r=i;return typeof r.localId!="string"||typeof r.effectiveLocalId!="string"||typeof r.instanceRootId!="string"||typeof r.sourcePath!="string"?null:r}cloneValue(e){return e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e))}readNode2DPlacement(e){let t=this.asRecord(e.transform),i=t?.rotation??e.rotation;return{position:this.readVector2(t?.position??e.position,ti),scale:this.readVector2(t?.scale??e.scale,GT),rotation:typeof i=="number"?i:0,layout:this.parseNode2DLayout(e),flow:this.parseNode2DFlow(e)}}async createNodeFromDefinition(e){let t={id:e.id,name:e.name,instancePath:e.instancePath??null,properties:{...e.properties??{}},metadata:e.metadata??{}};switch(Is(e.type)??e.type){case"ColorRect2D":{let i=t.properties;return new Qe({...t,properties:i,...this.readNode2DPlacement(i),width:this.asNumber(i.width,void 0),height:this.asNumber(i.height,void 0),color:typeof i.color=="string"?i.color:void 0,opacity:typeof i.opacity=="number"?i.opacity:void 0})}case"AnimatedSprite2D":{let i=t.properties,r=typeof i.animationResourcePath=="string"&&i.animationResourcePath.trim().length>0?i.animationResourcePath.trim():null,o=new ye({...t,properties:i,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),animationResourcePath:r,currentClip:typeof i.currentClip=="string"?i.currentClip:void 0,isPlaying:typeof i.isPlaying=="boolean"?i.isPlaying:void 0,freeOnFinish:typeof i.freeOnFinish=="boolean"?i.freeOnFinish:void 0,currentFrame:typeof i.currentFrame=="number"?i.currentFrame:void 0,width:this.asNumber(i.width,void 0),height:this.asNumber(i.height,void 0),color:typeof i.color=="string"?i.color:void 0,anchor:this.readVector2(i.anchor,new N(.5,.5)),sizeMode:i.sizeMode==="native"?"native":void 0});return r&&this.loadAnimatedSprite2DAsset(o,r),o}case"SpineSkeleton2D":{let i=t.properties,r=new gi({...t,properties:i,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),skeletonPath:this.asString(i.skeletonPath)??null,atlasPath:this.asString(i.atlasPath)??null,texture:D(i.texture??i.texturePath??null),animation:this.asString(i.animation),loop:typeof i.loop=="boolean"?i.loop:void 0,isPlaying:typeof i.isPlaying=="boolean"?i.isPlaying:void 0,skin:this.asString(i.skin),timeScale:this.asNumber(i.timeScale,void 0),defaultMix:this.asNumber(i.defaultMix,void 0),color:this.asString(i.color),twoColorTint:typeof i.twoColorTint=="boolean"?i.twoColorTint:void 0,freeOnFinish:typeof i.freeOnFinish=="boolean"?i.freeOnFinish:void 0,previewInEditor:typeof i.previewInEditor=="boolean"?i.previewInEditor:void 0});return this.loadSpineSkeleton2DAsset(r),r}case"Sprite2D":{let i=t.properties,r=D(i.texture??i.texturePath??null),o=new Fe({...t,properties:i,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),texture:r,textureKey:this.asString(i.textureKey),width:this.asNumber(i.width,void 0),height:this.asNumber(i.height,void 0),aspectRatioLocked:typeof i.aspectRatioLocked=="boolean"?i.aspectRatioLocked:void 0,anchor:this.readVector2(i.anchor,new N(.5,.5)),color:typeof i.color=="string"?i.color:void 0}),s=o.getEffectiveTexturePath();if(s)try{let a=await this.assetLoader.loadTexture(s);o.setTexture(a)}catch(a){console.warn(`[SceneLoader] Error loading texture for Sprite2D "${o.nodeId}":`,a)}return o}case"TiledSprite2D":{let i=t.properties,r=D(i.texture??i.texturePath??null),o=r?.url??null,s=new bi({...t,properties:i,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),texture:r,width:this.asNumber(i.width,void 0),height:this.asNumber(i.height,void 0),patchMode:typeof i.patchMode=="string"?i.patchMode:void 0,sliceBorder:{left:this.asNumber(i.sliceBorderLeft,0),right:this.asNumber(i.sliceBorderRight,0),top:this.asNumber(i.sliceBorderTop,0),bottom:this.asNumber(i.sliceBorderBottom,0)},drawCenter:typeof i.drawCenter=="boolean"?i.drawCenter:void 0,axisStretchHorizontal:typeof i.axisStretchHorizontal=="string"?i.axisStretchHorizontal:void 0,axisStretchVertical:typeof i.axisStretchVertical=="string"?i.axisStretchVertical:void 0,tileScale:this.readVector2(i.tileScale,new N(1,1)),tileOffset:this.readVector2(i.tileOffset,ti),anchor:this.readVector2(i.anchor,new N(.5,.5)),color:typeof i.color=="string"?i.color:void 0});if(o)try{let a=await this.assetLoader.loadTexture(o,{atlas:!1});s.setTexture(a)}catch(a){console.warn(`[SceneLoader] Error loading texture for TiledSprite2D "${s.nodeId}":`,a)}return s}case"AudioPlayer":{let i=t.properties;return new bt({...t,audioTrack:this.asString(i.audioTrack),autoplay:typeof i.autoplay=="boolean"?i.autoplay:void 0,loop:typeof i.loop=="boolean"?i.loop:void 0,volume:this.asNumber(i.volume,void 0),bus:this.asString(i.bus),pitchVariation:this.asNumber(i.pitchVariation,void 0),volumeVariation:this.asNumber(i.volumeVariation,void 0)})}case"PostProcess":return new it({...t});case"Group":return new I({...t,type:"Group"});case"Node3D":case void 0:{let i=this.parseNode3DTransforms(t.properties);return new U({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale})}case"Node2D":{let i=t.properties;return new C({...t,...this.readNode2DPlacement(t.properties),opacity:this.asNumber(i.opacity,void 0)})}case"Layout2D":throw new ve("Layout2D nodes are no longer supported.",[`Node ${e.id} still uses legacy type Layout2D. Replace it with root Node2D/Group2D anchors and project viewport settings.`]);case"Group2D":{let i=t.properties;return new Ae({...t,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),width:this.asNumber(i.width,100),height:this.asNumber(i.height,100)})}case"CanvasLayer2D":{let i=t.properties;return new hn({...t,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),width:this.asNumber(i.width,100),height:this.asNumber(i.height,100)})}case"Camera2D":{let i=t.properties,r=Ns;return new Ft({...t,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),priority:this.asNumber(i.priority,r.priority),zoom:this.asNumber(i.zoom,r.zoom),offset:this.readVector2(i.offset,ti),followTargetId:this.asString(i.followTargetId)??"",followDamping:this.asNumber(i.followDamping,r.followDamping),followOffset:this.readVector2(i.followOffset,ti),deadzone:this.readVector2(i.deadzone,ti),limitsEnabled:typeof i.limitsEnabled=="boolean"?i.limitsEnabled:!1,limitsCenter:this.readVector2(i.limitsCenter,ti),limitsSize:i.limitsSize!==void 0?this.readVector2(i.limitsSize,ti):void 0,shakeAmplitude:this.asNumber(i.shakeAmplitude,r.shakeAmplitude),shakeFrequency:this.asNumber(i.shakeFrequency,r.shakeFrequency),shakeDuration:this.asNumber(i.shakeDuration,r.shakeDuration),shakeDecay:this.asNumber(i.shakeDecay,r.shakeDecay)})}case"ScrollContainer2D":{let i=t.properties,r=D(i.scrollbarThumbTexture??null),o=D(i.scrollbarTrackTexture??null),s=new et({...t,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),width:this.asNumber(i.width,100),height:this.asNumber(i.height,100),scrollY:this.asNumber(i.scrollY,0),dragScrollEnabled:typeof i.dragScrollEnabled=="boolean"?i.dragScrollEnabled:void 0,wheelScrollEnabled:typeof i.wheelScrollEnabled=="boolean"?i.wheelScrollEnabled:void 0,inertiaEnabled:typeof i.inertiaEnabled=="boolean"?i.inertiaEnabled:void 0,showScrollbar:typeof i.showScrollbar=="boolean"?i.showScrollbar:void 0,wheelSensitivity:this.asNumber(i.wheelSensitivity,void 0),dragThreshold:this.asNumber(i.dragThreshold,void 0),inertiaDamping:this.asNumber(i.inertiaDamping,void 0),scrollbarWidth:this.asNumber(i.scrollbarWidth,void 0),scrollbarMinHeight:this.asNumber(i.scrollbarMinHeight,void 0),scrollbarInset:this.asNumber(i.scrollbarInset,void 0),scrollbarColor:this.asString(i.scrollbarColor),scrollbarTrackColor:this.asString(i.scrollbarTrackColor),scrollbarThumbTexture:r,scrollbarTrackTexture:o});if(r)try{s.setScrollbarThumbTexture(await this.assetLoader.loadTexture(r.url))}catch(a){console.warn(`[SceneLoader] Error loading scrollbar thumb texture for ScrollContainer2D "${s.nodeId}":`,a)}if(o)try{s.setScrollbarTrackTexture(await this.assetLoader.loadTexture(o.url))}catch(a){console.warn(`[SceneLoader] Error loading scrollbar track texture for ScrollContainer2D "${s.nodeId}":`,a)}return s}case"Joystick2D":{let i=t.properties;return new Pi({...t,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),radius:this.asNumber(i.radius,void 0),handleRadius:this.asNumber(i.handleRadius,void 0),axisHorizontal:this.asString(i.axisHorizontal),axisVertical:this.asString(i.axisVertical),baseColor:this.asString(i.baseColor),handleColor:this.asString(i.handleColor),floating:typeof i.floating=="boolean"?i.floating:void 0})}case"Button2D":{let i=t.properties,r=[["normal",D(i.textureNormal??null)],["hover",D(i.textureHover??null)],["pressed",D(i.texturePressed??null)],["disabled",D(i.textureDisabled??null)]],o={};{let a=this.asRecord(i.stateTextureKeys);for(let l of["normal","hover","pressed","disabled"]){let c=a?this.asString(a[l]):void 0;c&&(o[l]=c)}}let s=new gt({...t,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),width:this.asNumber(i.width,void 0),height:this.asNumber(i.height,void 0),backgroundColor:this.asString(i.backgroundColor),hoverColor:this.asString(i.hoverColor),pressedColor:this.asString(i.pressedColor),buttonAction:this.asString(i.buttonAction),label:this.asString(i.label),labelKey:this.asString(i.labelKey),...this.readLabelStyle(i),labelAlign:this.asString(i.labelAlign),texturePath:this.asString(i.texturePath),enabled:typeof i.enabled=="boolean"?i.enabled:void 0,textureNormal:r[0][1],textureHover:r[1][1],texturePressed:r[2][1],textureDisabled:r[3][1],stateTextureKeys:o,sliceBorder:this.readSliceBorder(i)});for(let[a]of r){let l=s.getEffectiveStateTexturePath(a);if(l)try{s.setStateTexture(a,await this.assetLoader.loadTexture(l))}catch(c){console.warn(`[SceneLoader] Error loading ${a} texture for Button2D "${s.nodeId}":`,c)}}return s}case"Label2D":{let i=t.properties;return new yt({...t,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),label:this.asString(i.label),labelKey:this.asString(i.labelKey),...this.readLabelStyle(i),labelAlign:this.asString(i.labelAlign),labelVAlign:this.asString(i.labelVAlign),width:this.asNumber(i.width,void 0),height:this.asNumber(i.height,void 0),typewriterSpeed:this.asNumber(i.typewriterSpeed,void 0),glowColor:this.asString(i.glowColor),glowStrength:this.asNumber(i.glowStrength,void 0),outlineColor:this.asString(i.outlineColor),outlineWidth:this.asNumber(i.outlineWidth,void 0),enabled:typeof i.enabled=="boolean"?i.enabled:void 0})}case"Slider2D":{let i=t.properties,r=new Ai({...t,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),width:this.asNumber(i.width,void 0),height:this.asNumber(i.height,void 0),handleSize:this.asNumber(i.handleSize,void 0),trackBackgroundColor:this.asString(i.trackBackgroundColor),trackFilledColor:this.asString(i.trackFilledColor),handleColor:this.asString(i.handleColor),minValue:this.asNumber(i.minValue,void 0),maxValue:this.asNumber(i.maxValue,void 0),value:this.asNumber(i.value,void 0),axisName:this.asString(i.axisName),label:this.asString(i.label),labelKey:this.asString(i.labelKey),...this.readLabelStyle(i),labelAlign:this.asString(i.labelAlign),texturePath:this.asString(i.texturePath),enabled:typeof i.enabled=="boolean"?i.enabled:void 0,textureTrack:D(i.textureTrack??null),textureFill:D(i.textureFill??null),textureThumb:D(i.textureThumb??null),sliceBorder:this.readSliceBorder(i)});for(let o of["track","fill","thumb"]){let s=r.getSlotTexturePath(o);if(s)try{r.setSlotTexture(o,await this.assetLoader.loadTexture(s))}catch(a){console.warn(`[SceneLoader] Error loading ${o} texture for Slider2D "${r.nodeId}":`,a)}}return r}case"Bar2D":{let i=t.properties,r=new Ti({...t,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),width:this.asNumber(i.width,void 0),height:this.asNumber(i.height,void 0),backBackgroundColor:this.asString(i.backBackgroundColor),barColor:this.asString(i.barColor),minValue:this.asNumber(i.minValue,void 0),maxValue:this.asNumber(i.maxValue,void 0),value:this.asNumber(i.value,void 0),showBorder:typeof i.showBorder=="boolean"?i.showBorder:void 0,borderColor:this.asString(i.borderColor),borderWidth:this.asNumber(i.borderWidth,void 0),label:this.asString(i.label),labelKey:this.asString(i.labelKey),...this.readLabelStyle(i),labelAlign:this.asString(i.labelAlign),texturePath:this.asString(i.texturePath),enabled:typeof i.enabled=="boolean"?i.enabled:void 0,textureTrough:D(i.textureTrough??null),textureFill:D(i.textureFill??null),sliceBorder:this.readSliceBorder(i)});for(let o of["trough","fill"]){let s=r.getSlotTexturePath(o);if(s)try{r.setSlotTexture(o,await this.assetLoader.loadTexture(s))}catch(a){console.warn(`[SceneLoader] Error loading ${o} texture for Bar2D "${r.nodeId}":`,a)}}return r}case"Checkbox2D":{let i=t.properties,r=new Ci({...t,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),size:this.asNumber(i.size,void 0),checked:typeof i.checked=="boolean"?i.checked:void 0,uncheckedColor:this.asString(i.uncheckedColor),checkedColor:this.asString(i.checkedColor),checkmarkColor:this.asString(i.checkmarkColor),checkmarkAction:this.asString(i.checkmarkAction),label:this.asString(i.label),labelKey:this.asString(i.labelKey),...this.readLabelStyle(i),labelAlign:this.asString(i.labelAlign),texturePath:this.asString(i.texturePath),enabled:typeof i.enabled=="boolean"?i.enabled:void 0,textureBox:D(i.textureBox??null),textureBoxChecked:D(i.textureBoxChecked??null),textureMark:D(i.textureMark??null)});for(let o of["box","boxChecked","mark"]){let s=r.getSlotTexturePath(o);if(s)try{r.setSlotTexture(o,await this.assetLoader.loadTexture(s))}catch(a){console.warn(`[SceneLoader] Error loading ${o} texture for Checkbox2D "${r.nodeId}":`,a)}}return r}case"InventorySlot2D":{let i=t.properties;return new Mi({...t,...this.readNode2DPlacement(i),opacity:this.asNumber(i.opacity,void 0),width:this.asNumber(i.width,void 0),height:this.asNumber(i.height,void 0),backdropColor:this.asString(i.backdropColor),borderColor:this.asString(i.borderColor),borderWidth:this.asNumber(i.borderWidth,void 0),quantity:this.asNumber(i.quantity,void 0),showQuantity:typeof i.showQuantity=="boolean"?i.showQuantity:void 0,quantityFontSize:this.asNumber(i.quantityFontSize,void 0),selectionColor:this.asString(i.selectionColor),selectedAction:this.asString(i.selectedAction),label:this.asString(i.label),labelKey:this.asString(i.labelKey),...this.readLabelStyle(i),labelAlign:this.asString(i.labelAlign),texturePath:this.asString(i.texturePath),enabled:typeof i.enabled=="boolean"?i.enabled:void 0})}case"GeometryMesh":{let i=this.parseNode3DTransforms(t.properties),r=t.properties,o=this.asString(r.geometry)??"box",s=this.readVector3(r.size,Qb),a=typeof r.castShadow=="boolean"?r.castShadow:!0,l=typeof r.receiveShadow=="boolean"?r.receiveShadow:!0,c=this.asRecord(r.material),h={color:this.asString(c?.color)??"#4e8df5"},d=this.asString(c?.type);d&&(h.type=d),typeof c?.roughness=="number"&&(h.roughness=c.roughness),typeof c?.metalness=="number"&&(h.metalness=c.metalness);let p=this.asString(c?.aoMap);p&&(h.aoMap=p),typeof c?.aoMapIntensity=="number"&&(h.aoMapIntensity=c.aoMapIntensity);let f=this.asString(c?.map);f&&(h.map=f);let m=this.parseGeometryMeshEffects(c?.effects);m&&(h.effects=m);let g=new St({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale,geometry:o,size:[s.x,s.y,s.z],castShadow:a,receiveShadow:l,material:h});if(p)try{let y=await this.assetLoader.loadTexture(p,{atlas:!1});g.setAOMap(y)}catch(y){console.warn(`[SceneLoader] Error loading AO map for GeometryMesh "${g.nodeId}":`,y)}if(f)try{let y=await this.assetLoader.loadTexture(f,{atlas:!1});g.setMap(y)}catch(y){console.warn(`[SceneLoader] Error loading albedo map for GeometryMesh "${g.nodeId}":`,y)}return g}case"InstancedMesh3D":{let i=this.parseNode3DTransforms(t.properties),r=t.properties,o=this.asPositiveInteger(r.maxInstances),s=this.asRecord(r.material),a={type:this.asString(s?.type),color:this.asString(s?.color),roughness:typeof s?.roughness=="number"?s.roughness:void 0,metalness:typeof s?.metalness=="number"?s.metalness:void 0};if(o===null)throw new ve(`Node "${e.id}" has invalid InstancedMesh3D.maxInstances value.`,["maxInstances must be a positive integer."]);return new vt({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale,maxInstances:o,castShadow:typeof r.castShadow=="boolean"?r.castShadow:!1,receiveShadow:typeof r.receiveShadow=="boolean"?r.receiveShadow:!1,enablePerInstanceColor:typeof r.enablePerInstanceColor=="boolean"?r.enablePerInstanceColor:!1,frustumCulled:typeof r.frustumCulled=="boolean"?r.frustumCulled:void 0,materialConfig:a})}case"DirectionalLightNode":{let i=this.parseNode3DTransforms(t.properties),r=t.properties;return new zt({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale,color:r.color??"#ffffff",intensity:r.intensity??1,castShadow:typeof r.castShadow=="boolean"?r.castShadow:!0,shadowCameraSize:typeof r.shadowCameraSize=="number"?r.shadowCameraSize:20,shadowMapSize:typeof r.shadowMapSize=="number"?r.shadowMapSize:2048})}case"PointLightNode":{let i=this.parseNode3DTransforms(t.properties),r=t.properties;return new Ut({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale,color:r.color??"#ffffff",intensity:r.intensity??1,distance:r.distance??0,decay:r.decay??2,castShadow:typeof r.castShadow=="boolean"?r.castShadow:!0})}case"SpotLightNode":{let i=this.parseNode3DTransforms(t.properties),r=t.properties;return new Wt({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale,color:r.color??"#ffffff",intensity:r.intensity??1,distance:r.distance??0,angle:typeof r.angle=="number"?r.angle*Math.PI/180:Math.PI/3,penumbra:r.penumbra??0,decay:r.decay??2,castShadow:typeof r.castShadow=="boolean"?r.castShadow:!0})}case"AmbientLightNode":{let i=this.parseNode3DTransforms(t.properties),r=t.properties;return new Ht({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale,color:r.color??"#ffffff",intensity:r.intensity??.5})}case"HemisphereLightNode":{let i=this.parseNode3DTransforms(t.properties),r=t.properties;return new qt({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale,skyColor:r.skyColor??"#ffffff",groundColor:r.groundColor??"#444444",intensity:r.intensity??.5})}case"Camera3D":{let i=this.parseNode3DTransforms(t.properties),r=t.properties;return new pe({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale,projection:r.projection??"perspective",fov:r.fov??60,near:r.near??.1,far:r.far??1e3,orthographicSize:r.orthographicSize??5})}case"VirtualCamera3D":{let i=this.parseNode3DTransforms(t.properties),r=t.properties;return new xt({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale,priority:this.asNumber(r.priority,We.priority),fov:this.asNumber(r.fov,We.fov),orthographicSize:this.asNumber(r.orthographicSize,We.orthographicSize),followTargetId:this.asString(r.followTargetId)??"",followDamping:this.asNumber(r.followDamping,We.followDamping),followOffset:this.readVector3(r.followOffset,Mr),deadzone:this.readVector3(r.deadzone,Mr),lookAtTargetId:this.asString(r.lookAtTargetId)??"",lookAtWeight:this.asNumber(r.lookAtWeight,We.lookAtWeight),rotationDamping:this.asNumber(r.rotationDamping,We.rotationDamping),confinerEnabled:typeof r.confinerEnabled=="boolean"?r.confinerEnabled:!1,confinerCenter:this.readVector3(r.confinerCenter,Mr),confinerSize:this.readVector3(r.confinerSize,new S(10,10,10)),blendDuration:this.asNumber(r.blendDuration,We.blendDuration),blendEasing:Ue(r.blendEasing)?r.blendEasing:We.blendEasing})}case"MeshInstance":{let i=this.parseNode3DTransforms(t.properties),r=t.properties,o=this.asString(r.src)??null,s=typeof r.castShadow=="boolean"?r.castShadow:!0,a=typeof r.receiveShadow=="boolean"?r.receiveShadow:!0,l=this.asString(r.initialAnimation)??null,c=typeof r.isPlaying=="boolean"?r.isPlaying:!0,u=typeof r.isLoop=="boolean"?r.isLoop:!0,h=new ht({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale,src:o,castShadow:s,receiveShadow:a,initialAnimation:l,isPlaying:c,isLoop:u});if(o)try{let p=(await this.assetLoader.loadAsset(o)).node;if(p.children&&p.children.length>0)for(let f of p.children)h.add(f);"animations"in p&&Array.isArray(p.animations)&&(h.animations=p.animations),h.applyLoadedShadowProperties(),h.showDefaultPose()}catch(d){console.warn(`[SceneLoader] Error loading GLB model from "${o}":`,d)}return h}case"AnimatedSprite3D":{let i=this.parseNode3DTransforms(t.properties),r=t.properties,o=Array.isArray(r.frames)?r.frames.map(D):[],s=new xi({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale,frames:o,width:this.asNumber(r.width,1),height:this.asNumber(r.height,1),color:this.asString(r.color)??"#ffffff",fps:typeof r.fps=="number"?r.fps:void 0,playing:typeof r.playing=="boolean"?r.playing:void 0,loop:typeof r.loop=="boolean"?r.loop:void 0,freeOnFinish:typeof r.freeOnFinish=="boolean"?r.freeOnFinish:void 0,billboard:typeof r.billboard=="boolean"?r.billboard:!1,opacity:this.asNumber(r.opacity,void 0)});return o.forEach(async(a,l)=>{if(a?.url)try{let c=await this.assetLoader.loadTexture(a.url);s.setTextureForFrame(l,c)}catch(c){console.warn(`[SceneLoader] Error loading texture for AnimatedSprite3D "${s.nodeId}":`,c)}}),s}case"Sprite3D":{let i=this.parseNode3DTransforms(t.properties),r=t.properties,o=D(r.texture??r.texturePath??null),s=new mt({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale,texture:o,width:this.asNumber(r.width,1),height:this.asNumber(r.height,1),color:this.asString(r.color)??"#ffffff",billboard:typeof r.billboard=="boolean"?r.billboard:!1,billboardRoll:this.asNumber(r.billboardRoll,0),opacity:this.asNumber(r.opacity,void 0)});if(s.texturePath)try{let a=await this.assetLoader.loadTexture(s.texturePath);s.setTexture(a)}catch(a){console.warn(`[SceneLoader] Error loading texture for Sprite3D "${s.nodeId}":`,a)}return s}case"Particles3D":{let i=this.parseNode3DTransforms(t.properties),r=t.properties,o=D(r.texture??r.texturePath??null),s=this.readVector3(r.emitterBoxSize,new S(1,1,1)),a=this.readVector3(r.gravity,new S(0,0,0)),l=new ft({...t,properties:i.restProps,position:i.position,rotation:i.rotation,rotationOrder:i.rotationOrder,scale:i.scale,texture:o,emitterShape:r.emitterShape,emitterRadius:this.asNumber(r.emitterRadius,.5),emitterBoxSize:{x:s.x,y:s.y,z:s.z},particleShape:r.particleShape,emissionRate:this.asNumber(r.emissionRate,24),maxParticles:this.asNumber(r.maxParticles,512),lifetime:this.asNumber(r.lifetime,2),speed:this.asNumber(r.speed,2),speedSpread:this.asNumber(r.speedSpread,.5),gravity:{x:a.x,y:a.y,z:a.z},particleSize:this.asNumber(r.particleSize,.2),sizeRandomness:this.asNumber(r.sizeRandomness,.2),startColor:this.asString(r.startColor)??"#ffffff",endColor:this.asString(r.endColor)??"#ffd24d",startAlpha:this.asNumber(r.startAlpha,1),endAlpha:this.asNumber(r.endAlpha,0),billboard:typeof r.billboard=="boolean"?r.billboard:!0,disableRotation:typeof r.disableRotation=="boolean"?r.disableRotation:!1,playing:typeof r.playing=="boolean"?r.playing:!0,loop:typeof r.loop=="boolean"?r.loop:!0,prewarm:typeof r.prewarm=="boolean"?r.prewarm:!1,preview:typeof r.preview=="boolean"?r.preview:!1,simulationSpace:r.simulationSpace==="world"?"world":"local",trailEnabled:typeof r.trailEnabled=="boolean"?r.trailEnabled:!1,trailLifetime:this.asNumber(r.trailLifetime,.3),trailWidth:this.asNumber(r.trailWidth,.05),trailSegments:this.asNumber(r.trailSegments,16),trailFade:this.asNumber(r.trailFade,1),subEmitterId:this.asString(r.subEmitterId)??"",subEmitterBurstCount:this.asNumber(r.subEmitterBurstCount,8),subEmitterInheritVelocity:this.asNumber(r.subEmitterInheritVelocity,0)});if(l.texturePath)try{let c=await this.assetLoader.loadTexture(l.texturePath);l.setTexture(c)}catch(c){console.warn(`[SceneLoader] Error loading texture for Particles3D "${l.nodeId}":`,c)}return l}default:return new I({...t,type:e.type})}}async loadSpineSkeleton2DAsset(e){let t=e.getAssetRequest();if(!t){e.setSpineAsset(null);return}try{let i=await this.assetLoader.loadSpineAsset(t),r=e.getAssetRequest();if(!r||r.skeletonPath!==t.skeletonPath||r.atlasPath!==t.atlasPath||r.texturePath!==t.texturePath)return;e.setSpineAsset(i)}catch(i){console.warn(`[SceneLoader] Error loading Spine asset for SpineSkeleton2D "${e.nodeId}":`,i)}}async loadAnimatedSprite2DAsset(e,t){try{let i=await this.assetLoader.loadAnimationResource(t);e.setAnimationResource(i);let r=new Set;for(let o of i.clips)for(let s of o.frames){let a=pi(i,s);a&&r.add(a)}if(await Promise.all(Array.from(r).map(async o=>{try{let s=await this.assetLoader.loadTexture(o);e.setFrameTexture(o,s)}catch(s){console.warn(`[SceneLoader] Error loading frame texture for AnimatedSprite2D "${e.nodeId}":`,s)}})),!i.texturePath)return;try{let o=await this.assetLoader.loadTexture(i.texturePath);e.setSpritesheetTexture(o)}catch(o){console.warn(`[SceneLoader] Error loading spritesheet for AnimatedSprite2D "${e.nodeId}":`,o)}}catch(i){console.warn(`[SceneLoader] Error loading animation resource for AnimatedSprite2D "${e.nodeId}":`,i)}}parseNode3DTransforms(e){let{position:t,rotation:i,scale:r,transform:o,...s}=e,a=this.readVector3(t,Mr),l=this.readVector3(i,Mr),c=this.readVector3(r,Qb),u=this.asRecord(o),h=a,d=l,p=c,f="XYZ";if(u){f=this.readRotationOrder(u.rotationOrder)??f,h=this.readVector3(u.position??u.translate,a),d=this.readVector3(u.rotationEuler??u.rotation??u.euler,l),p=this.readVector3(u.scale,c);let g=Object.entries(u).filter(([y])=>!["position","translate","rotation","rotationEuler","euler","scale","rotationOrder"].includes(y));g.length>0&&(s.transform=Object.fromEntries(g))}let m=new Ji(R.degToRad(d.x),R.degToRad(d.y),R.degToRad(d.z),f);return{position:h,rotation:m,rotationOrder:f,scale:p,restProps:s}}readVector3(e,t){if(!e)return t.clone();if(e instanceof S)return e.clone();if(Array.isArray(e))return new S(this.asNumber(e[0],t.x),this.asNumber(e[1],t.y),this.asNumber(e[2],t.z));if(typeof e=="object"){let i=e;return new S(this.asNumber(i.x,t.x),this.asNumber(i.y,t.y),this.asNumber(i.z,t.z))}return t.clone()}readLabelStyle(e){let t=e.labelFontWeight;return{labelFontFamily:this.asString(e.labelFontFamily),labelFontSize:this.asNumber(e.labelFontSize,void 0),labelColor:this.asString(e.labelColor),labelFontWeight:typeof t=="number"||typeof t=="string"?t:void 0,labelOutlineWidth:this.asNumber(e.labelOutlineWidth,void 0),labelOutlineColor:this.asString(e.labelOutlineColor),labelShadowColor:this.asString(e.labelShadowColor),labelShadowOffsetX:this.asNumber(e.labelShadowOffsetX,void 0),labelShadowOffsetY:this.asNumber(e.labelShadowOffsetY,void 0),labelLetterSpacing:this.asNumber(e.labelLetterSpacing,void 0)}}readSliceBorder(e){return{left:this.asNumber(e.sliceBorderLeft,0),right:this.asNumber(e.sliceBorderRight,0),top:this.asNumber(e.sliceBorderTop,0),bottom:this.asNumber(e.sliceBorderBottom,0)}}readVector2(e,t){if(!e)return t.clone();if(e instanceof N)return e.clone();if(Array.isArray(e))return new N(this.asNumber(e[0],t.x),this.asNumber(e[1],t.y));if(typeof e=="object"){let i=e;return new N(this.asNumber(i.x,t.x),this.asNumber(i.y,t.y))}return t.clone()}parseGeometryMeshEffects(e){if(!Array.isArray(e))return;let t=[];for(let i of e){let r=this.asRecord(i),o=this.asString(r?.type);if(!o)continue;let s={type:o};r&&typeof r.enabled=="boolean"&&(s.enabled=r.enabled);let a=this.asRecord(r?.params);a&&(s.params={...a}),t.push(s)}return t.length>0?t:void 0}readRotationOrder(e){if(typeof e!="string")return;let t=e.trim().toUpperCase();return["XYZ","XZY","YXZ","YZX","ZXY","ZYX"].includes(t)?t:void 0}asNumber(e,t){return typeof e=="number"&&Number.isFinite(e)?e:t}asPositiveInteger(e){if(typeof e!="number"||!Number.isFinite(e))return null;let t=Math.floor(e);return t>0?t:null}asRecord(e){return!e||typeof e!="object"||Array.isArray(e)?null:e}asString(e){return typeof e=="string"?e:void 0}parseNode2DFlow(e){let t=e.flow;if(!t||typeof t!="object")return;let i=t,r=a=>typeof a=="number"&&Number.isFinite(a)?a:void 0,o=i.direction==="horizontal"?"horizontal":"vertical",s=i.align==="center"||i.align==="end"?i.align:"start";return{enabled:i.enabled===!0,direction:o,gap:r(i.gap),paddingX:r(i.paddingX),paddingY:r(i.paddingY),align:s,autoSize:i.autoSize===!0}}parseNode2DLayout(e){let t=this.asRecord(e.layout);if(!t)return;let i=["left","center","right","stretch"],r=["top","center","bottom","stretch"],o=i.find(l=>l===t.horizontalAlign),s=r.find(l=>l===t.verticalAlign),a=l=>typeof l=="number"&&Number.isFinite(l)?l:void 0;return{enabled:typeof t.enabled=="boolean"?t.enabled:void 0,horizontalAlign:o,verticalAlign:s,left:a(t.left),right:a(t.right),top:a(t.top),bottom:a(t.bottom)}}};var jT=new Set(["AmbientLight","DirectionalLight","HemisphereLight","PointLight","SpotLight"]),Zb=new Set(["GeometryMesh","MeshInstance","InstancedMesh3D"]),$T=new Set([...Zb,"Sprite3D","AnimatedSprite3D","Particles3D"]),YT=new Set(["Camera3D","VirtualCamera3D"]),jn=8,KT=(n,e={})=>{let t=[],i=[],r=[],o=0,s=0,a=!1,l=0,c=d=>{if(d.visible===!1)return;let p=XT(d);p?(jT.has(p.type)&&o++,YT.has(p.type)&&s++,$T.has(p.type)&&i.push(p),Zb.has(p.type)&&t.push(p),eS(p)&&r.push(p)):eC(d)&&(a=!0,ZT(d)&&l++);for(let f of d.children)c(f)};for(let d of n)c(d);let u=[];if((a||t.some(d=>!tC(d)))&&t.length>0&&o===0&&u.push({code:"lit-material-no-light",severity:"blocking",message:`${t.length} 3D mesh node(s) use lit materials but the scene has no enabled light \u2014 they will render black. Add a HemisphereLightNode (plus a DirectionalLightNode for shading), or give the meshes an unlit material.`,nodeIds:t.slice(0,jn).map(d=>d.nodeId),nodeCount:t.length}),i.length>0&&s===0&&u.push({code:"no-camera-3d",severity:"blocking",message:`The scene has ${i.length} 3D node(s) but no enabled Camera3D \u2014 nothing 3D will be drawn. Add a Camera3D and position it to look at the content.`,nodeIds:i.slice(0,jn).map(d=>d.nodeId),nodeCount:i.length}),l>0&&e.targetPlatform&&e.targetPlatform!=="desktop"&&u.push({code:"pbr-on-mobile",severity:"advice",message:`${l} material(s) use PBR (standard/physical) in a ${e.targetPlatform} project. PBR shading is a desktop-class per-pixel cost; set the meshes' materialType to 'lambert' (or 'basic' for unlit) unless the user asked for a high-end look.`,nodeIds:t.slice(0,jn).map(d=>d.nodeId),nodeCount:l}),r.length>0){let d=r.slice(0,jn).map(p=>yu(p.name,p.type)).join(" ");u.push({code:"inert-nodes",severity:"blocking",message:`${r.length} node(s) have an unrecognised type and do nothing. ${d}`,nodeIds:r.slice(0,jn).map(p=>p.nodeId),nodeCount:r.length})}return u},XT=n=>n instanceof I?n:null,eS=n=>Object.getPrototypeOf(n)===I.prototype&&!gu(n.type),QT=["isMeshStandardMaterial","isMeshPhysicalMaterial"],JT=["isMeshStandardMaterial","isMeshPhysicalMaterial","isMeshLambertMaterial","isMeshPhongMaterial","isMeshToonMaterial"],Pd=n=>{let e=n.material;return e?Array.isArray(e)?e:[e]:[]},ZT=n=>Pd(n).some(e=>QT.some(t=>e[t]===!0)),eC=n=>Pd(n).some(e=>JT.some(t=>e[t]===!0)),tC=n=>{let e=!1;return n.traverse(t=>{!e&&Pd(t).length>0&&(e=!0)}),e};var iC="1.0.0",rC=["version","description","metadata","root"],nC=["id","type","name","instance","instancePath","groups","properties","metadata","children","components","overrides"],oC=["id","type","enabled","config"],sC={kind:"record",nested:{position:{schemaName:"position"},scale:{schemaName:"scale"},rotation:{schemaName:"rotation"}}},aC=["XYZ","XZY","YXZ","YZX","ZXY","ZYX"],lC={kind:"record",nested:{position:{schemaName:"position"},translate:{schemaName:"position",preferred:"transform.position"},rotationEuler:{schemaName:"rotation"},rotation:{schemaName:"rotation",preferred:"transform.rotationEuler"},euler:{schemaName:"rotation",preferred:"transform.rotationEuler"},scale:{schemaName:"scale"},rotationOrder:{kind:"enum",options:aC}}},cC={kind:"record",nested:{enabled:{schemaName:"layoutEnabled"},horizontalAlign:{schemaName:"horizontalAlign"},verticalAlign:{schemaName:"verticalAlign"},left:{schemaName:"layoutLeft"},right:{schemaName:"layoutRight"},top:{schemaName:"layoutTop"},bottom:{schemaName:"layoutBottom"}}},uC={kind:"record",nested:{enabled:{schemaName:"flowEnabled"},direction:{schemaName:"flowDirection"},gap:{schemaName:"flowGap"},paddingX:{schemaName:"flowPaddingX"},paddingY:{schemaName:"flowPaddingY"},align:{schemaName:"flowAlign"},autoSize:{schemaName:"flowAutoSize"}}},Ha={kind:"array"},hC={id:"the node id is the entry's own `id:`, not a property",name:"the node name is the entry's own `name:`, not a property",type:"the node type is the entry's own `type:`, not a property",groups:"groups are the entry's own `groups:` list, not a property"},tS=["position","rotation","scale"],iS={Group:{family:"base",classExport:"NodeBase"},Node2D:{family:"2d"},Node3D:{family:"3d"},ColorRect2D:{family:"2d"},Sprite2D:{family:"2d",extras:{effects:Ha,texturePath:{kind:"resource-path",preferred:"texture"},color:{kind:"color"}}},TiledSprite2D:{family:"2d",extras:{texturePath:{kind:"resource-path",preferred:"texture"},color:{kind:"color"}}},AnimatedSprite2D:{family:"2d",extras:{effects:Ha}},SpineSkeleton2D:{family:"2d",extras:{texturePath:{kind:"resource-path",preferred:"texture"}}},Label2D:{family:"2d",writeOnly:["texturePath"],extras:{labelOutlineWidth:{schemaName:"outlineWidth",preferred:"outlineWidth"},labelOutlineColor:{schemaName:"outlineColor",preferred:"outlineColor"}}},Group2D:{family:"2d"},CanvasLayer2D:{family:"2d"},Camera2D:{family:"2d"},Button2D:{family:"2d",extras:{effects:Ha,stateTextureKeys:{kind:"record",nested:{normal:{schemaName:"textureNormalKey"},hover:{schemaName:"textureHoverKey"},pressed:{schemaName:"texturePressedKey"},disabled:{schemaName:"textureDisabledKey"}}}}},Slider2D:{family:"2d"},Bar2D:{family:"2d",extras:{borderWidth:{kind:"number"}}},Checkbox2D:{family:"2d"},Joystick2D:{family:"2d",extras:{handleRadius:{kind:"number"},baseColor:{kind:"color"},handleColor:{kind:"color"}}},ScrollContainer2D:{family:"2d"},InventorySlot2D:{family:"2d",extras:{borderWidth:{kind:"number"},quantityFontSize:{kind:"number"}}},GeometryMesh:{family:"3d",extras:{material:{kind:"record",nested:{type:{schemaName:"materialType"},color:{schemaName:"color"},roughness:{schemaName:"roughness"},metalness:{schemaName:"metalness"},aoMap:{kind:"resource-path"},aoMapIntensity:{schemaName:"aoMapIntensity"},map:{kind:"resource-path"},effects:Ha}}},relocated:{map:"material.map"}},MeshInstance:{family:"3d",extras:{src:{kind:"resource-path"}}},InstancedMesh3D:{family:"3d",extras:{material:{kind:"record",nested:{type:{schemaName:"materialType"},color:{schemaName:"color"},roughness:{kind:"number"},metalness:{kind:"number"}}},frustumCulled:{kind:"boolean"}},notStored:{visibleInstanceCount:"computed at runtime from the instance buffer"}},Sprite3D:{family:"3d",extras:{texturePath:{kind:"resource-path",preferred:"texture"},color:{kind:"color"}},notStored:{textureAspectRatio:"derived from the loaded texture",aspectRatioLocked:"an inspector-only toggle on Sprite3D"}},AnimatedSprite3D:{family:"3d",extras:{frames:{kind:"array"}},notStored:{currentFrame:"playback state, not saved on AnimatedSprite3D"}},Particles3D:{family:"3d",extras:{texturePath:{kind:"resource-path",preferred:"texture"}}},AmbientLightNode:{family:"3d"},DirectionalLightNode:{family:"3d"},HemisphereLightNode:{family:"3d"},PointLightNode:{family:"3d"},SpotLightNode:{family:"3d"},Camera3D:{family:"3d"},VirtualCamera3D:{family:"3d"},PostProcess:{family:"base"},AudioPlayer:{family:"base"}},dC=Object.keys(iS),pC=(n,e,t)=>{for(let[i,r]of Object.entries(n.nested??{}))r.schemaName&&!r.preferred&&!(r.schemaName in t)&&(t[r.schemaName]=`${e}.${i}`)},mC=(n,e)=>{let i={...e.family==="2d"?{transform:sC,layout:cC,flow:uC}:e.family==="3d"?{transform:lC}:{},...e.extras},r={};for(let[o,s]of Object.entries(i))pC(s,o,r);for(let o of tS)delete r[o];return Object.assign(r,e.relocated),{type:n,classExport:e.classExport??n,family:e.family,extras:i,relocated:r,notStored:{...hC,...e.notStored},writeOnly:e.writeOnly??[]}},fC=new Map(Object.entries(iS).map(([n,e])=>[n,mC(n,e)])),gC=n=>fC.get(n)??null,yC=(n,e,t)=>{let i=n.extras[t];if(i)return{kind:"extra",rule:i};let r=e.find(a=>a.name===t);if(!r)return{kind:"unknown"};let o=n.notStored[t];if(o!==void 0)return{kind:"not-stored",property:r,reason:o};let s=n.relocated[t];if(s!==void 0)return{kind:"relocated",property:r,diskPath:s};if(n.writeOnly.includes(t))return{kind:"write-only",property:r};if(n.family!=="base"&&tS.includes(t)){let a=n.family==="3d"&&t==="rotation"?"transform.rotationEuler":`transform.${t}`;return{kind:"schema",property:r,preferred:a}}return{kind:"schema",property:r}},bC={position:"position",translate:"position",rotationEuler:"rotation",rotation:"rotation",euler:"rotation",scale:"scale"};var SC=new RegExp("\\p{Extended_Pictographic}","u"),vC=new RegExp("\\p{Extended_Pictographic}","gu"),wC=new RegExp("\\s|\\u{FE0F}|\\u{200D}|\\u{20E3}|\\u{FE0E}|\\p{Emoji_Modifier}|\\p{Emoji_Component}","gu"),rS=new Set(["label","text","placeholder","title","caption","buttonText","labelText","content"]),nS=n=>SC.test(n)?n.replace(vC,"").replace(wC,"").trim().length===0:!1,oS=n=>rS.has(n.split(".").pop()??n),xC=(n,e)=>typeof e!="string"||!oS(n)||!nS(e)?null:{message:`${n.split(".").pop()??n} is ${e.trim()} \u2014 nothing but emoji, i.e. a picture standing in for art. It draws differently on every platform, cannot be recoloured, atlased or animated, and is a hollow box where the font lacks it.`,fix:"use a Sprite2D with a real sprite (or a ColorRect2D placeholder); an emoji inside a sentence is fine"};var qa=["scripts","src/scripts"],sS=/\.(?:spec|test)\.ts$|\.d\.ts$/,PC=(n=qa)=>n.flatMap(e=>[`/${e}/**/*.ts`,`!/${e}/**/*.spec.ts`,`!/${e}/**/*.test.ts`,`!/${e}/**/*.d.ts`]),aS="user:",Ga=n=>`${aS}${n}`,lS=n=>n.replace(/\\/g,"/").replace(/^res:\/\//,"").replace(/^\.?\/+/,""),cS=(n,e=qa)=>{let t=lS(n);return e.some(i=>t===i||t.startsWith(`${i}/`))},kC=(n,e=qa)=>{let t=lS(n);return t.endsWith(".ts")&&!sS.test(t)&&cS(t,e)},uS=(n,e=V)=>{if(typeof n!="function"||typeof n.getPropertySchema!="function")return!1;if(n===e)return!0;let t=e.prototype,i=n.prototype;for(;i;){if(i===t)return!0;i=Object.getPrototypeOf(i)}return!1},AC=(n,e,t)=>{let i=[];for(let[r,o]of Object.entries(e)){if(!uS(o))continue;let s=Ga(r);n.registerComponent({id:s,displayName:r,description:`Project component from ${t}`,category:"Project",componentClass:o,keywords:["project","component",r.toLowerCase(),t.toLowerCase()]}),i.push(s)}return i};var TC="__autoloads__",CC=n=>`autoload:${n}`,kd=n=>{let e=n.replace(/\\/g,"/"),t=e.split("/").pop()??e;return Ga(t.replace(/\.[cm]?[jt]sx?$/i,""))},MC=n=>!!n&&typeof n=="object"&&!Array.isArray(n),hS=n=>{if(!Array.isArray(n))return[];let e=[],t=new Set;for(let i of n){if(!MC(i))continue;let r=typeof i.scriptPath=="string"?i.scriptPath.trim():"",o=typeof i.singleton=="string"?i.singleton.trim():"";!r||!o||t.has(o)||(t.add(o),e.push({scriptPath:r,singleton:o,enabled:i.enabled!==!1}))}return e},ja=class{entries=[];registry=null;root=null;instances=new Map;configure(e,t){this.entries=e.map(i=>({...i})),this.registry=t}start(e,t){if(this.root)return;let i=new I({id:TC,type:"Autoloads",name:"Autoloads",metadata:{internal:!0}});this.root=i,i.input=e,i.scene=t;for(let r of this.entries){if(!r.enabled)continue;let o=kd(r.scriptPath),s=CC(r.singleton),a=this.registry?.createComponent(o,s,{expectRegistered:!1})??null;if(!a){let c=`Autoload "${r.singleton}": ${r.scriptPath} does not register ${o} (the file must be under scripts/ and export a Script class named like the file).`;console.error(`[Autoloads] ${c}`),Me({phase:"attach",message:c,componentType:o,componentId:s});continue}let l=new I({id:s,type:"Autoload",name:r.singleton});i.adoptChild(l);try{l.addComponent(a)}catch(c){let{message:u,stack:h}=Le(c);Me({phase:"attach",message:u,stack:h,componentType:o,componentId:s})}this.instances.set(r.singleton,a)}}tick(e){this.root?.tick(e)}stop(){let e=this.root;if(!e)return;this.root=null;let t=[...e.children].filter(i=>i instanceof I);for(let i of t.reverse())for(let r of[...i.components])try{i.removeComponent(r)}catch(o){let{message:s,stack:a}=Le(o);console.error("[Autoloads] onDetach failed",{componentId:r.id,thrown:o}),Me({phase:"detach",message:s,stack:a,componentType:r.type,componentId:r.id})}this.instances.clear(),e.dispose()}get(e){if(typeof e=="string")return this.instances.get(e)??null;for(let t of this.instances.values())if(t instanceof e)return t;return null}};var dS=Qp(wd(),1);var Ad=class{constructor(){}serializeSceneDocument(e){let t=e.rootNodes.map(i=>this.serializeNode(i));return{version:e.version??"1.0.0",description:e.description,metadata:e.metadata,root:t}}serializeScene(e){let t=this.serializeSceneDocument(e),i=(0,dS.stringify)(t,{indent:2});return i=i.replace(/position:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"position: [$1, $2, $3]"),i=i.replace(/position:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)(?!\s*-)/g,"position: [$1, $2]"),i=i.replace(/rotationEuler:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"rotationEuler: [$1, $2, $3]"),i=i.replace(/scale:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"scale: [$1, $2, $3]"),i=i.replace(/scale:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)(?!\s*-)/g,"scale: [$1, $2]"),i=i.replace(/rotation:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- (\w+)/g,"rotation: [$1, $2, $3, $4]"),i=i.replace(/rotation:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)(?!\s*-)/g,"rotation: [$1, $2]"),i=i.replace(/size:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"size: [$1, $2, $3]"),i=i.replace(/size:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)(?!\s*-)/g,"size: [$1, $2]"),i=i.replace(/pivot:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"pivot: [$1, $2]"),i=i.replace(/emitterBoxSize:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"emitterBoxSize: [$1, $2, $3]"),i=i.replace(/gravity:\s*\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)\n\s*- ([\d.-]+)/g,"gravity: [$1, $2, $3]"),i}serializeNode(e){if(e.instancePath)return this.serializeInstanceNode(e);let t=this.serializeNodeProperties(e),i={id:e.nodeId,type:e.type!=="Group"?e.type:void 0,name:e.name,groups:e.groups.size>0?Array.from(e.groups.values()):void 0,properties:t,metadata:this.serializeMetadata(e.metadata)};e instanceof zt?i.type="DirectionalLightNode":e instanceof Ut?i.type="PointLightNode":e instanceof Wt?i.type="SpotLightNode":e instanceof Ht?i.type="AmbientLightNode":e instanceof qt&&(i.type="HemisphereLightNode");let r=Jr(e);return r.length>0&&(i.components=r.map(o=>({...o,config:o.config&&Object.keys(o.config).length>0?o.config:void 0}))),e.children&&e.children.length>0&&(i.children=e.children.filter(o=>o instanceof I).map(o=>this.serializeNode(o))),Object.keys(i).forEach(o=>{i[o]===void 0&&delete i[o]}),i}serializeInstanceNode(e){let t={id:e.nodeId,type:e.type!=="Group"?e.type:void 0,name:e.name,instance:e.instancePath??void 0,groups:e.groups.size>0?Array.from(e.groups.values()):void 0,metadata:this.serializeMetadata(e.metadata)},i=this.getPrefabMarker(e),r=i?.basePropertiesByLocalId??{},o=this.captureInstanceComparableMap(e),s=i?i.effectiveLocalId:this.normalizeLocalId(e.nodeId),a=this.dropMarginDerivedComparable(e,o[s]?.values??{}),l=this.dropMarginDerivedComparable(e,r[s]??{}),c=this.diffRecord(l,a);Object.keys(c).length>0&&(t.properties=c);let u={};for(let[h,d]of Object.entries(o)){if(h===s)continue;let p=this.dropMarginDerivedComparable(d.node,d.values),f=this.dropMarginDerivedComparable(d.node,r[h]??{}),m=this.diffRecord(f,p);if(Object.keys(m).length===0)continue;let g=h.startsWith(`${s}/`)?h.slice(s.length+1):h;u[g]={properties:m}}if(Object.keys(u).length>0){let h={byLocalId:u};t.overrides=h}return Object.keys(t).forEach(h=>{t[h]===void 0&&delete t[h]}),t}serializeMetadata(e){let t=Object.entries(e).filter(([i])=>i!=="__pix3Prefab");if(t.length!==0)return Object.fromEntries(t)}serializeNodeProperties(e){let t={...e.properties};if(delete t.position,delete t.rotation,delete t.scale,delete t.rotationEuler,delete t.rotationOrder,delete t.transform,e instanceof U){let i=e.rotation,r={position:[e.position.x,e.position.y,e.position.z],rotationEuler:[R.radToDeg(i.x),R.radToDeg(i.y),R.radToDeg(i.z)],scale:[e.scale.x,e.scale.y,e.scale.z]};i.order&&i.order!=="XYZ"&&(r.rotationOrder=i.order),t.transform=r,e.opacity!==1?t.opacity=e.opacity:delete t.opacity}else if(e instanceof et){t.width=e.width,t.height=e.height;let i={position:[e.position.x,e.position.y],scale:[e.scale.x,e.scale.y],rotation:R.radToDeg(e.rotation.z)};t.transform=i;let r=e.serializeLayout();r?t.layout=r:delete t.layout;let o=e.serializeFlow();o?t.flow=o:delete t.flow}else if(e instanceof Ae){t.width=e.width,t.height=e.height;let i={position:[e.position.x,e.position.y],scale:[e.scale.x,e.scale.y],rotation:R.radToDeg(e.rotation.z)};t.transform=i;let r=e.serializeLayout();r?t.layout=r:delete t.layout;let o=e.serializeFlow();o?t.flow=o:delete t.flow}else if(e instanceof C){let i={position:[e.position.x,e.position.y],scale:[e.scale.x,e.scale.y],rotation:R.radToDeg(e.rotation.z)};t.transform=i;let r=e.serializeLayout();r?t.layout=r:delete t.layout;let o=e.serializeFlow();o?t.flow=o:delete t.flow,e.opacity!==1?t.opacity=e.opacity:delete t.opacity}if(e instanceof Qe)e.blocksPointerInput?t.blocksPointerInput=!0:delete t.blocksPointerInput,t.width=e.width,t.height=e.height,t.color=e.color;else if(e instanceof et)t.scrollY=e.scrollY,t.dragScrollEnabled=e.dragScrollEnabled,t.wheelScrollEnabled=e.wheelScrollEnabled,t.inertiaEnabled=e.inertiaEnabled,t.showScrollbar=e.showScrollbar,t.wheelSensitivity=e.wheelSensitivity,t.dragThreshold=e.dragThreshold,t.inertiaDamping=e.inertiaDamping,t.scrollbarWidth=e.scrollbarWidth,t.scrollbarMinHeight=e.scrollbarMinHeight,t.scrollbarInset=e.scrollbarInset,t.scrollbarColor=e.scrollbarColor,t.scrollbarTrackColor=e.scrollbarTrackColor,e.scrollbarThumbTexture?t.scrollbarThumbTexture={...e.scrollbarThumbTexture}:delete t.scrollbarThumbTexture,e.scrollbarTrackTexture?t.scrollbarTrackTexture={...e.scrollbarTrackTexture}:delete t.scrollbarTrackTexture;else if(e instanceof Fe){e.texture&&(t.texture={...e.texture}),e.textureKey?t.textureKey=e.textureKey:delete t.textureKey,t.width=e.width,t.height=e.height,e.aspectRatioLocked&&(t.aspectRatioLocked=!0),(e.anchor.x!==.5||e.anchor.y!==.5)&&(t.anchor=[Math.round(e.anchor.x*1e3)/1e3,Math.round(e.anchor.y*1e3)/1e3]),delete t.effects;let i=e.getShaderEffectStack();i.isEmpty||(t.effects=i.serialize())}else if(e instanceof bi)e.texture&&(t.texture={...e.texture}),t.patchMode=e.patchMode,t.width=e.width,t.height=e.height,t.sliceBorderLeft=e.sliceBorder.left,t.sliceBorderRight=e.sliceBorder.right,t.sliceBorderTop=e.sliceBorder.top,t.sliceBorderBottom=e.sliceBorder.bottom,t.drawCenter=e.drawCenter,t.axisStretchHorizontal=e.axisStretchHorizontal,t.axisStretchVertical=e.axisStretchVertical,t.tileScale=[e.tileScale.x,e.tileScale.y],t.tileOffset=[e.tileOffset.x,e.tileOffset.y],(e.anchor.x!==.5||e.anchor.y!==.5)&&(t.anchor=[Math.round(e.anchor.x*1e3)/1e3,Math.round(e.anchor.y*1e3)/1e3]);else if(e instanceof gi)e.skeletonPath?t.skeletonPath=e.skeletonPath:delete t.skeletonPath,e.atlasPath?t.atlasPath=e.atlasPath:delete t.atlasPath,e.texture?t.texture={...e.texture}:delete t.texture,delete t.texturePath,e.animation?t.animation=e.animation:delete t.animation,e.skin?t.skin=e.skin:delete t.skin,t.loop=e.loop,t.isPlaying=e.isPlaying,t.timeScale=e.timeScale,t.defaultMix=e.defaultMix,t.color=e.color,e.twoColorTint?t.twoColorTint=!0:delete t.twoColorTint,e.freeOnFinish?t.freeOnFinish=!0:delete t.freeOnFinish,e.previewInEditor?t.previewInEditor=!0:delete t.previewInEditor;else if(e instanceof ye){delete t.frames,delete t.fps,delete t.playing,delete t.loop,e.animationResourcePath?t.animationResourcePath=e.animationResourcePath:delete t.animationResourcePath,e.savedClipName?t.currentClip=e.savedClipName:delete t.currentClip,t.isPlaying=e.isPlaying,e.freeOnFinish?t.freeOnFinish=!0:delete t.freeOnFinish,t.currentFrame=e.currentFrame,t.width=e.width,t.height=e.height,t.color=e.color,e.sizeMode==="native"?t.sizeMode="native":delete t.sizeMode,e.anchor.x!==.5||e.anchor.y!==.5?t.anchor=[Math.round(e.anchor.x*1e3)/1e3,Math.round(e.anchor.y*1e3)/1e3]:delete t.anchor,delete t.effects;let i=e.getShaderEffectStack();i.isEmpty||(t.effects=i.serialize())}else if(e instanceof Pi)e.radius!==50&&(t.radius=e.radius),e.handleRadius!==20&&(t.handleRadius=e.handleRadius),e.axisHorizontal!=="Horizontal"&&(t.axisHorizontal=e.axisHorizontal),e.axisVertical!=="Vertical"&&(t.axisVertical=e.axisVertical),e.baseColor!=="#ffffff"&&(t.baseColor=e.baseColor),e.handleColor!=="#cccccc"&&(t.handleColor=e.handleColor),e.floating!==!1&&(t.floating=e.floating);else if(e instanceof gt){this.serializeCommonUIControlProps(e,t),t.width=e.width,t.height=e.height,t.backgroundColor=e.backgroundColor,t.hoverColor=e.hoverColor,t.pressedColor=e.pressedColor,t.buttonAction=e.buttonAction,e.textureNormal?t.textureNormal={...e.textureNormal}:delete t.textureNormal,e.textureHover?t.textureHover={...e.textureHover}:delete t.textureHover,e.texturePressed?t.texturePressed={...e.texturePressed}:delete t.texturePressed,e.textureDisabled?t.textureDisabled={...e.textureDisabled}:delete t.textureDisabled,e.hasLocalizedStateTextures()?t.stateTextureKeys={...e.stateTextureKeys}:delete t.stateTextureKeys,this.serializeSliceBorder(e.sliceBorder,t),delete t.effects;let i=e.getShaderEffectStack();i.isEmpty||(t.effects=i.serialize())}else if(e instanceof yt)this.serializeCommonUIControlProps(e,t),e.width>0&&(t.width=e.width),e.height>0&&(t.height=e.height),e.labelVAlign!=="middle"&&(t.labelVAlign=e.labelVAlign),e.typewriterSpeed>0&&(t.typewriterSpeed=e.typewriterSpeed),e.glowStrength>0?(t.glowStrength=e.glowStrength,e.glowColor!=="#ffffff"&&(t.glowColor=e.glowColor)):(delete t.glowStrength,delete t.glowColor),e.outlineWidth>0?(t.outlineWidth=e.outlineWidth,e.outlineColor!=="#000000"&&(t.outlineColor=e.outlineColor)):(delete t.outlineWidth,delete t.outlineColor),delete t.labelOutlineWidth,delete t.labelOutlineColor;else if(e instanceof Ai)this.serializeCommonUIControlProps(e,t),t.width=e.width,t.height=e.height,t.handleSize=e.handleSize,t.trackBackgroundColor=e.trackBackgroundColor,t.trackFilledColor=e.trackFilledColor,t.handleColor=e.handleColor,t.minValue=e.minValue,t.maxValue=e.maxValue,t.value=e.value,t.axisName=e.axisName,this.serializeTextureRef(t,"textureTrack",e.textureTrack),this.serializeTextureRef(t,"textureFill",e.textureFill),this.serializeTextureRef(t,"textureThumb",e.textureThumb),this.serializeSliceBorder(e.sliceBorder,t);else if(e instanceof Ti)this.serializeCommonUIControlProps(e,t),t.width=e.width,t.height=e.height,t.backBackgroundColor=e.backBackgroundColor,t.barColor=e.barColor,t.minValue=e.minValue,t.maxValue=e.maxValue,t.value=e.value,t.showBorder=e.showBorder,t.borderColor=e.borderColor,t.borderWidth=e.borderWidth,this.serializeTextureRef(t,"textureTrough",e.textureTrough),this.serializeTextureRef(t,"textureFill",e.textureFill),this.serializeSliceBorder(e.sliceBorder,t);else if(e instanceof Ci)this.serializeCommonUIControlProps(e,t),t.size=e.size,t.checked=e.checked,t.uncheckedColor=e.uncheckedColor,t.checkedColor=e.checkedColor,t.checkmarkColor=e.checkmarkColor,t.checkmarkAction=e.checkmarkAction,this.serializeTextureRef(t,"textureBox",e.textureBox),this.serializeTextureRef(t,"textureBoxChecked",e.textureBoxChecked),this.serializeTextureRef(t,"textureMark",e.textureMark);else if(e instanceof Mi)this.serializeCommonUIControlProps(e,t),t.width=e.width,t.height=e.height,t.backdropColor=e.backdropColor,t.borderColor=e.borderColor,t.borderWidth=e.borderWidth,t.quantity=e.quantity,t.showQuantity=e.showQuantity,t.quantityFontSize=e.quantityFontSize,t.selectionColor=e.selectionColor,t.selectedAction=e.selectedAction;else if(e instanceof St)Object.assign(t,e.serializeConfig());else if(e instanceof vt){t.maxInstances=e.maxInstances;let i=e.serializeMaterialConfig();i?t.material=i:delete t.material,t.castShadow=e.mesh.castShadow,t.receiveShadow=e.mesh.receiveShadow,t.enablePerInstanceColor=e.enablePerInstanceColor,e.mesh.frustumCulled?t.frustumCulled=!0:delete t.frustumCulled,delete t.visibleInstanceCount}else if(e instanceof zt)t.color="#"+e.light.color.getHexString(),t.intensity=e.light.intensity,t.castShadow=e.light.castShadow,t.shadowCameraSize=e.light.shadow.camera.right,t.shadowMapSize=e.light.shadow.mapSize.width;else if(e instanceof Ut)t.color="#"+e.light.color.getHexString(),t.intensity=e.light.intensity,t.distance=e.light.distance,t.decay=e.light.decay,t.castShadow=e.light.castShadow;else if(e instanceof Wt)t.color="#"+e.light.color.getHexString(),t.intensity=e.light.intensity,t.distance=e.light.distance,t.angle=e.light.angle*180/Math.PI,t.penumbra=e.light.penumbra,t.decay=e.light.decay,t.castShadow=e.light.castShadow;else if(e instanceof Ht)t.color="#"+e.light.color.getHexString(),t.intensity=e.light.intensity;else if(e instanceof qt)t.skyColor="#"+e.light.color.getHexString(),t.groundColor="#"+e.light.groundColor.getHexString(),t.intensity=e.light.intensity;else if(e instanceof pe)e.camera instanceof ge?(t.projection="perspective",t.fov=e.fov,t.near=e.near,t.far=e.far):e.camera instanceof de&&(t.projection="orthographic",t.orthographicSize=e.orthographicSize,t.near=e.near,t.far=e.far);else if(e instanceof xt)Object.assign(t,e.serializeConfig());else if(e instanceof Ft)Object.assign(t,e.serializeConfig());else if(e instanceof it)Object.assign(t,e.serializeConfig());else if(e instanceof bt)Object.assign(t,e.serializeConfig());else if(e instanceof ht){let i=e;i.src&&(t.src=i.src),i.initialAnimation&&(t.initialAnimation=i.initialAnimation),t.isPlaying=i.isPlaying,t.isLoop=i.isLoop,t.castShadow=i.castShadow,t.receiveShadow=i.receiveShadow}else e instanceof mt?(e.texture&&(t.texture={...e.texture}),t.width=e.width,t.height=e.height,t.color=e.color,t.billboard=e.billboard,t.billboardRoll=e.billboardRoll):e instanceof ft&&(e.texture&&(t.texture={...e.texture}),t.emitterShape=e.emitterShape,t.emitterRadius=e.emitterRadius,t.emitterBoxSize=[e.emitterBoxSize.x,e.emitterBoxSize.y,e.emitterBoxSize.z],t.particleShape=e.particleShape,t.emissionRate=e.emissionRate,t.maxParticles=e.maxParticles,t.lifetime=e.lifetime,t.speed=e.speed,t.speedSpread=e.speedSpread,t.gravity=[e.gravity.x,e.gravity.y,e.gravity.z],t.particleSize=e.particleSize,t.sizeRandomness=e.sizeRandomness,t.startColor=e.startColor,t.endColor=e.endColor,t.startAlpha=e.startAlpha,t.endAlpha=e.endAlpha,t.billboard=e.billboard,t.disableRotation=e.disableRotation,t.playing=e.playing,t.loop=e.loop,t.prewarm=e.prewarm,t.preview=e.preview,t.simulationSpace=e.simulationSpace,t.trailEnabled=e.trailEnabled,t.trailLifetime=e.trailLifetime,t.trailWidth=e.trailWidth,t.trailSegments=e.trailSegments,t.trailFade=e.trailFade,t.subEmitterId=e.subEmitterId,t.subEmitterBurstCount=e.subEmitterBurstCount,t.subEmitterInheritVelocity=e.subEmitterInheritVelocity);return e instanceof C&&this.dropMarginDerivedRect(e,t),DC(t,Object.keys(e.properties))}dropMarginDerivedRect(e,t){let i=e.isMarginAxis("x"),r=e.isMarginAxis("y");if(!i&&!r)return;let o=t.transform;if(o&&typeof o=="object"){let s=o.position;Array.isArray(s)&&(i&&(s[0]=0),r&&(s[1]=0))}for(let s of e.marginDerivedSizeKeys())delete t[s]}dropMarginDerivedComparable(e,t){if(!(e instanceof C))return t;let i=e.isMarginAxis("x"),r=e.isMarginAxis("y");if(!i&&!r)return t;let o={...t},s=o.position;if(s&&typeof s=="object"&&!Array.isArray(s)){let a={...s};i&&(a.x=0),r&&(a.y=0),o.position=a}for(let a of e.marginDerivedSizeKeys())delete o[a];return o}captureInstanceComparableMap(e){let t={},i=[e];for(;i.length>0;){let r=i.pop();if(!r)continue;let o=this.getPrefabMarker(r);o&&(t[o.effectiveLocalId]={node:r,values:this.captureComparableProperties(r)});for(let s of r.children)s instanceof I&&i.push(s)}return t}captureComparableProperties(e){let t=ke(e),i={};for(let r of t.properties)r.ui?.hidden||r.ui?.readOnly===!0||(i[r.name]=this.cloneValue(r.getValue(e)));return i}diffRecord(e,t){let i={},r=new Set([...Object.keys(e),...Object.keys(t)]);for(let o of r){let s=e[o],a=t[o];this.isEqualValue(s,a)||(i[o]=this.cloneValue(a))}return i}isEqualValue(e,t){return JSON.stringify(e)===JSON.stringify(t)}getPrefabMarker(e){let i=e.metadata.__pix3Prefab;if(!i||typeof i!="object")return null;let r=i;return typeof r.localId!="string"||typeof r.effectiveLocalId!="string"||typeof r.instanceRootId!="string"||typeof r.sourcePath!="string"?null:r}normalizeLocalId(e){return e.replace(/\\/g,"/").replace(/^\/+/,"").trim()}cloneValue(e){return e==null||typeof e!="object"?e:JSON.parse(JSON.stringify(e))}serializeCommonUIControlProps(e,t){e.enabled!==!0&&(t.enabled=e.enabled),e.label!==""&&(t.label=e.label),e.labelKey!==""&&(t.labelKey=e.labelKey),e.labelFontFamily!=="Arial"&&(t.labelFontFamily=e.labelFontFamily),e.labelFontSize!==16&&(t.labelFontSize=e.labelFontSize),e.labelColor!=="#ffffff"&&(t.labelColor=e.labelColor),e.labelAlign!=="center"&&(t.labelAlign=e.labelAlign),e.labelFontWeight!=="normal"&&e.labelFontWeight!==400&&(t.labelFontWeight=e.labelFontWeight),e.labelOutlineWidth!==0&&(t.labelOutlineWidth=e.labelOutlineWidth),e.labelOutlineColor!=="#000000"&&(t.labelOutlineColor=e.labelOutlineColor),e.labelShadowColor?t.labelShadowColor=e.labelShadowColor:delete t.labelShadowColor,e.labelShadowOffsetX!==0&&(t.labelShadowOffsetX=e.labelShadowOffsetX),e.labelShadowOffsetY!==0&&(t.labelShadowOffsetY=e.labelShadowOffsetY),e.labelLetterSpacing!==0&&(t.labelLetterSpacing=e.labelLetterSpacing),e.texturePath&&(t.texturePath=e.texturePath)}serializeTextureRef(e,t,i){i?e[t]={...i}:delete e[t]}serializeSliceBorder(e,t){let i=[["sliceBorderLeft",e.left],["sliceBorderRight",e.right],["sliceBorderTop",e.top],["sliceBorderBottom",e.bottom]];for(let[r,o]of i)o>0?t[r]=o:delete t[r]}};function DC(n,e){let t={};for(let i of e)i!=="transform"&&i in n&&(t[i]=n[i]);for(let[i,r]of Object.entries(n))i!=="transform"&&!(i in t)&&(t[i]=r);return"transform"in n&&(t.transform=n.transform),t}var Td=class{sceneLoader;sceneSaver;sceneGraphs=new Map;activeSceneId=null;constructor(e,t){this.sceneLoader=e,this.sceneSaver=t??null}async instantiatePrefab(e,t){return await this.sceneLoader.instantiatePrefab(e,t)}resolvePendingComponents(){let e=0;for(let t of this.sceneGraphs.values())e+=this.sceneLoader.resolvePendingComponents(t.rootNodes);return e}async parseScene(e,t={}){return await this.sceneLoader.parseScene(e,t)}serializeScene(e){if(!this.sceneSaver)throw new Error("[SceneManager] No SceneSaver was provided \u2014 this host cannot serialize scenes. Pass a SceneSaver to the SceneManager constructor if you need to save or clone scenes.");return this.sceneSaver.serializeScene(e)}serializeSceneDocument(e){if(!this.sceneSaver)throw new Error("[SceneManager] No SceneSaver was provided \u2014 this host cannot serialize scenes.");return this.sceneSaver.serializeSceneDocument(e)}setActiveSceneGraph(e,t,i={}){let r=this.sceneGraphs.get(e);r&&r!==t&&i.disposePrevious!==!1&&this.disposeSceneGraph(r),this.sceneGraphs.set(e,t),this.activeSceneId=e,console.debug("[SceneManager] setActiveSceneGraph",{sceneId:e,rootCount:t.rootNodes.length})}setActiveScene(e){return this.sceneGraphs.has(e)?(this.activeSceneId=e,!0):!1}getSceneGraph(e){return this.sceneGraphs.get(e)??null}getActiveSceneGraph(){return this.activeSceneId?this.sceneGraphs.get(this.activeSceneId)??null:null}resizeRoot(e,t,i=!1){let r=this.getActiveSceneGraph();if(r)for(let o of r.rootNodes)o instanceof C&&o.applyAnchoredLayoutRecursive({width:e,height:t},{width:e,height:t})}removeSceneGraph(e){let t=this.sceneGraphs.get(e);t&&this.disposeSceneGraph(t),this.sceneGraphs.delete(e),this.activeSceneId===e&&(this.activeSceneId=null)}dispose(){for(let e of this.sceneGraphs.values())this.disposeSceneGraph(e);this.sceneGraphs.clear(),this.activeSceneId=null}disposeSceneGraph(e){for(let t of e.rootNodes)t.dispose();e.nodeMap.clear()}};var pS=()=>({ctrl:!1,meta:!1,shift:!1,alt:!1}),Cd=n=>{n.ctrl=!1,n.meta=!1,n.shift=!1,n.alt=!1},EC=n=>n.ctrlKey||n.metaKey,NC=64,$n=class{axes=new Map;buttons=new Map;pointerPosition=new N;isPointerDown=!1;activePointerId=null;wheelDelta=new N;wheelZoomDelta=new N;currentWheelModifiers=pS();wheelModifiers=this.currentWheelModifiers;pointerEvents=[];keyEvents=[];width=0;height=0;hoveredUIElements=new Set;hoveredUIPointers=new Set;activePointers=new Map;uiPointerOwners=new Map;uiHoverTargets=new Map;pendingWheelDelta=new N;pendingWheelZoomDelta=new N;pendingWheelModifiers=pS();pendingPointerEvents=[];pendingKeyEvents=[];element=null;previousTouchAction=null;lockDepth=0;polledActions=null;pollsTruncated=!1;lockedDuringPollWindow=!1;beginFrame(){this.uiHoverTargets.clear();for(let e of this.uiPointerOwners.keys())(e<0?!this.isPointerDown:!this.activePointers.has(e))&&this.uiPointerOwners.delete(e);this.hoveredUIElements.clear(),this.hoveredUIPointers.clear(),this.wheelDelta.copy(this.pendingWheelDelta),this.pendingWheelDelta.set(0,0),this.wheelZoomDelta.copy(this.pendingWheelZoomDelta),this.pendingWheelZoomDelta.set(0,0),Object.assign(this.currentWheelModifiers,this.pendingWheelModifiers),Cd(this.pendingWheelModifiers),this.pointerEvents=this.pendingPointerEvents,this.pendingPointerEvents=[],this.keyEvents=this.pendingKeyEvents,this.pendingKeyEvents=[]}claimUIPointer(e,t,i){let r=this.uiPointerOwners.get(e);if(r)return r===t;let o=i();return o?(this.uiPointerOwners.set(e,o),o===t):!1}getUIHoverTarget(e,t,i,r){let o=this.uiHoverTargets.get(e);if(o&&o.x===t&&o.y===i)return o.target;let s=r();return this.uiHoverTargets.set(e,{x:t,y:i,target:s}),s}registerHover(e,t){this.hoveredUIElements.add(e);let i=t??this.activePointerId;i!=null&&this.hoveredUIPointers.add(i)}get isHoveringUI(){return this.hoveredUIElements.size>0}isPointerOverUI(e){return this.hoveredUIPointers.has(e)}getActivePointers(){return[...this.activePointers.values()]}getPointer(e){return this.activePointers.get(e)??null}get pointerDownCount(){return this.activePointers.size}lock(){this.lockDepth+=1,this.polledActions!==null&&(this.lockedDuringPollWindow=!0),this.lockDepth===1&&(this.pendingPointerEvents=[],this.pendingKeyEvents=[],this.clearWheelState(),this.cancelActivePointers(!0),this.isPointerDown=!1,this.activePointerId=null,this.setButton("Action_Primary",!1),this.clearHeldKeyButtons())}cancelActivePointers(e){for(let t of this.activePointers.values())this.releasePointer(t.pointerId),e&&this.pendingPointerEvents.push({type:"cancel",pointerId:t.pointerId,x:t.x,y:t.y});this.activePointers.clear(),this.uiPointerOwners.clear(),this.uiHoverTargets.clear(),this.syncDerivedPointerState()}clearHeldKeyButtons(){for(let e of this.buttons.keys())e.startsWith("Key_")&&this.buttons.set(e,!1)}unlock(){this.lockDepth>0&&(this.lockDepth-=1)}get isLocked(){return this.lockDepth>0}setAxis(e,t){this.axes.set(e,t)}getAxis(e){return this.polledActions!==null&&this.recordPoll(e),this.axes.get(e)||0}setButton(e,t){this.buttons.set(e,t)}getButton(e){return this.polledActions!==null&&this.recordPoll(e),this.buttons.get(e)||!1}startPollRecording(){this.polledActions=new Set,this.pollsTruncated=!1,this.lockedDuringPollWindow=this.lockDepth>0}stopPollRecording(){this.polledActions=null,this.pollsTruncated=!1,this.lockedDuringPollWindow=!1}get isPollRecording(){return this.polledActions!==null}getObservedPolls(){return{observedPolls:this.polledActions?[...this.polledActions]:[],locked:this.lockDepth>0,lockedDuringWindow:this.lockedDuringPollWindow||this.lockDepth>0,truncated:this.pollsTruncated}}takeObservedPolls(){let e=this.getObservedPolls();return this.polledActions!==null&&(this.polledActions.clear(),this.pollsTruncated=!1,this.lockedDuringPollWindow=this.lockDepth>0),e}recordPoll(e){let t=this.polledActions;if(!(!t||t.has(e))){if(t.size>=NC){this.pollsTruncated=!0;return}t.add(e)}}attach(e){this.detach(),this.element=e,this.previousTouchAction=e.style.touchAction,e.style.touchAction="none";let t=this.getInputDimensions();this.width=t.width,this.height=t.height,console.log(`[InputService] Attached to element. Dimensions: ${this.width}x${this.height}`),e.addEventListener("pointerdown",this.onPointerDown),e.addEventListener("pointermove",this.onPointerMove),e.addEventListener("pointerup",this.onPointerUp),e.addEventListener("pointercancel",this.onPointerCancel),e.addEventListener("pointerleave",this.onPointerLeave),e.addEventListener("wheel",this.onWheel,{passive:!1}),window.addEventListener("keydown",this.onKeyDown),window.addEventListener("keyup",this.onKeyUp),window.addEventListener("blur",this.onWindowBlur),e.addEventListener("contextmenu",this.onContextMenu)}detach(){this.element&&(this.element.removeEventListener("pointerdown",this.onPointerDown),this.element.removeEventListener("pointermove",this.onPointerMove),this.element.removeEventListener("pointerup",this.onPointerUp),this.element.removeEventListener("pointercancel",this.onPointerCancel),this.element.removeEventListener("pointerleave",this.onPointerLeave),this.element.removeEventListener("wheel",this.onWheel),this.element.removeEventListener("contextmenu",this.onContextMenu),window.removeEventListener("keydown",this.onKeyDown),window.removeEventListener("keyup",this.onKeyUp),window.removeEventListener("blur",this.onWindowBlur),this.cancelActivePointers(!1),this.previousTouchAction!==null&&(this.element.style.touchAction=this.previousTouchAction,this.previousTouchAction=null),this.element=null,this.isPointerDown=!1,this.activePointerId=null,this.clearWheelState(),this.pointerEvents=[],this.pendingPointerEvents=[],this.keyEvents=[],this.pendingKeyEvents=[],this.setButton("Action_Primary",!1),this.lockDepth=0,this.stopPollRecording())}onPointerDown=e=>{if(this.lockDepth>0||this.activePointers.has(e.pointerId))return;this.uiPointerOwners.delete(e.pointerId);let t=this.computePointerPosition(e),i=this.activePointers.size===0;this.activePointers.set(e.pointerId,{pointerId:e.pointerId,x:t.x,y:t.y,isPrimary:i}),this.syncDerivedPointerState(),this.pendingPointerEvents.push({type:"down",pointerId:e.pointerId,x:t.x,y:t.y}),this.capturePointer(e.pointerId),i&&this.setButton("Action_Primary",!0)};onPointerMove=e=>{if(this.lockDepth>0)return;let t=this.activePointers.get(e.pointerId),i=this.computePointerPosition(e);if(!t){this.activePointers.size===0&&this.pointerPosition.set(i.x,i.y);return}t.x=i.x,t.y=i.y,t.isPrimary&&this.pointerPosition.set(i.x,i.y),this.pendingPointerEvents.push({type:"move",pointerId:e.pointerId,x:i.x,y:i.y})};onPointerUp=e=>{this.endPointer(e,"up")};onPointerCancel=e=>{this.endPointer(e,"cancel")};onPointerLeave=e=>{this.endPointer(e,"cancel")};onWindowBlur=()=>{this.activePointers.size!==0&&(this.cancelActivePointers(!0),this.setButton("Action_Primary",!1))};endPointer(e,t){if(this.lockDepth>0)return;let i=this.activePointers.get(e.pointerId);if(!i)return;let r=this.computePointerPosition(e);i.isPrimary&&this.pointerPosition.set(r.x,r.y),this.activePointers.delete(e.pointerId),this.syncDerivedPointerState(),this.pendingPointerEvents.push({type:t,pointerId:e.pointerId,x:r.x,y:r.y}),this.releasePointer(e.pointerId),this.activePointers.size===0&&this.setButton("Action_Primary",!1)}syncDerivedPointerState(){let e=null;for(let t of this.activePointers.values()){let i=e===null;t.isPrimary=i,i&&(e=t)}this.isPointerDown=this.activePointers.size>0,this.activePointerId=e?e.pointerId:null,e&&this.pointerPosition.set(e.x,e.y)}capturePointer(e){try{this.element?.setPointerCapture?.(e)}catch{}}releasePointer(e){try{this.element?.releasePointerCapture?.(e)}catch{}}onContextMenu=e=>{e.preventDefault()};onWheel=e=>{if(e.preventDefault(),this.lockDepth>0)return;let t=EC(e)?this.pendingWheelZoomDelta:this.pendingWheelDelta;t.x+=e.deltaX,t.y+=e.deltaY;let i=this.pendingWheelModifiers;e.ctrlKey&&(i.ctrl=!0),e.metaKey&&(i.meta=!0),e.shiftKey&&(i.shift=!0),e.altKey&&(i.alt=!0)};clearWheelState(){this.wheelDelta.set(0,0),this.pendingWheelDelta.set(0,0),this.wheelZoomDelta.set(0,0),this.pendingWheelZoomDelta.set(0,0),Cd(this.currentWheelModifiers),Cd(this.pendingWheelModifiers)}onKeyDown=e=>{this.lockDepth>0||(this.setButton(`Key_${e.code}`,!0),this.setButton(`Key_${e.key.toUpperCase()}`,!0),this.pendingKeyEvents.push({type:"down",code:e.code,key:e.key,repeat:e.repeat}))};onKeyUp=e=>{this.lockDepth>0||(this.setButton(`Key_${e.code}`,!1),this.setButton(`Key_${e.key.toUpperCase()}`,!1),this.pendingKeyEvents.push({type:"up",code:e.code,key:e.key,repeat:e.repeat}))};computePointerPosition(e){if(!this.element)return{x:this.pointerPosition.x,y:this.pointerPosition.y};let t=this.element.getBoundingClientRect(),i=this.getInputDimensions();this.width=i.width,this.height=i.height;let r=t.width>0?t.width:1,o=t.height>0?t.height:1,s=this.width/r,a=this.height/o,l=(e.clientX-t.left)*s,c=(e.clientY-t.top)*a;return{x:l,y:c}}getInputDimensions(){if(!this.element)return{width:0,height:0};if(this.element instanceof HTMLCanvasElement){let t=this.element.width,i=this.element.height;if(t>0&&i>0)return{width:t,height:i}}let e=this.element.getBoundingClientRect();return{width:e.width,height:e.height}}};var j_=3,$_=512;function ii(n,e,t,i,r,o){return(t-n)*(o-e)-(i-e)*(r-n)}function Ya(n){let e=n.length;if(e<3)return 0;let t=0;for(let i=0,r=e-1;i<e;r=i++)t+=n[r].x*n[i].y-n[i].x*n[r].y;return t/2}function Dd(n){return Math.abs(Ya(n))}function Yn(n){let e=n.length;if(e===0)return{x:0,y:0};let t=Ya(n);if(Math.abs(t)<1e-9){let o=0,s=0;for(let a of n)o+=a.x,s+=a.y;return{x:o/e,y:s/e}}let i=0,r=0;for(let o=0,s=e-1;o<e;s=o++){let a=n[s],l=n[o],c=a.x*l.y-l.x*a.y;i+=(a.x+l.x)*c,r+=(a.y+l.y)*c}return{x:i/(6*t),y:r/(6*t)}}function gS(n){let e=n.length;if(e<3)return!1;let t=0;for(let i=0;i<e;i++){let r=n[i],o=n[(i+1)%e],s=n[(i+2)%e],a=ii(r.x,r.y,o.x,o.y,s.x,s.y);if(Math.abs(a)<1e-9)continue;let l=a>0?1:-1;if(t===0)t=l;else if(t!==l)return!1}return!0}function Dr(n){let e=n.map(t=>({x:t.x,y:t.y}));return Ya(e)<0&&e.reverse(),e}function Ed(n,e=1e-6){let t=[];for(let o of n){if(!Number.isFinite(o?.x)||!Number.isFinite(o?.y))continue;let s=t[t.length-1];s&&Math.abs(s.x-o.x)<=e&&Math.abs(s.y-o.y)<=e||t.push({x:o.x,y:o.y})}for(;t.length>1;){let o=t[0],s=t[t.length-1];if(Math.abs(o.x-s.x)<=e&&Math.abs(o.y-s.y)<=e)t.pop();else break}if(t.length<3)return t;let i=[],r=t.length;for(let o=0;o<r;o++){let s=t[(o-1+r)%r],a=t[o],l=t[(o+1)%r];Math.abs(ii(s.x,s.y,a.x,a.y,l.x,l.y))<=e||i.push(a)}return i.length>=3?i:t}function $a(n){let e=n.filter(o=>Number.isFinite(o?.x)&&Number.isFinite(o?.y)).map(o=>({x:o.x,y:o.y})).sort((o,s)=>o.x===s.x?o.y-s.y:o.x-s.x);if(e.length<3)return e;let t=o=>{let s=[];for(let a of o){for(;s.length>=2;){let l=s[s.length-2],c=s[s.length-1];if(ii(l.x,l.y,c.x,c.y,a.x,a.y)>1e-9)break;s.pop()}s.push(a)}return s.pop(),s},i=t(e),r=t([...e].reverse());return[...i,...r]}function Nd(n){if(n.length===0)return{minX:0,minY:0,maxX:0,maxY:0};let e=1/0,t=1/0,i=-1/0,r=-1/0;for(let o of n)o.x<e&&(e=o.x),o.y<t&&(t=o.y),o.x>i&&(i=o.x),o.y>r&&(r=o.y);return{minX:e,minY:t,maxX:i,maxY:r}}function _i(n,e){let t=Math.cos(e.rotation),i=Math.sin(e.rotation),r=new Array(n.length);for(let o=0;o<n.length;o++){let s=n[o].x*e.scaleX,a=n[o].y*e.scaleY;r[o]={x:e.x+s*t-a*i,y:e.y+s*i+a*t}}return e.scaleX*e.scaleY<0&&r.reverse(),r}function Er(n,e,t){let i=t?.x??0,r=t?.y??0,o=Math.abs(n),s=Math.abs(e);return[{x:i-o,y:r-s},{x:i+o,y:r-s},{x:i+o,y:r+s},{x:i-o,y:r+s}]}function yS(n,e=16,t){let i=t?.x??0,r=t?.y??0,o=Math.max(3,Math.floor(e)),s=new Array(o);for(let a=0;a<o;a++){let l=a/o*Math.PI*2;s[a]={x:i+Math.cos(l)*n,y:r+Math.sin(l)*n}}return s}function Id(n,e,t=8,i){let r=Math.abs(e),o=i?.x??0,s=i?.y??0;if(r<=0)return[];let a=Math.max(0,Math.abs(n)/2-r);if(a<=1e-6)return yS(r,t*2,i);let l=Math.max(2,Math.floor(t)),c=[];for(let u=0;u<=l;u++){let h=Math.PI*(u/l);c.push({x:o+Math.cos(h)*r,y:s+a+Math.sin(h)*r})}for(let u=0;u<=l;u++){let h=Math.PI+Math.PI*(u/l);c.push({x:o+Math.cos(h)*r,y:s-a+Math.sin(h)*r})}return Dr(Ed(c))}function Tt(n,e,t){let i=t.length;if(i<3)return!1;let r=!1;for(let o=0,s=i-1;o<i;s=o++){let a=t[s],l=t[o];if(a.y>e!=l.y>e){let c=(e-a.y)/(l.y-a.y);n<a.x+c*(l.x-a.x)&&(r=!r)}}return r}function IC(n,e,t,i){let r=i.x-t.x,o=i.y-t.y,s=r*r+o*o,a=s>1e-9?((n-t.x)*r+(e-t.y)*o)/s:0;a=a<0?0:a>1?1:a;let l=t.x+r*a-n,c=t.y+o*a-e;return l*l+c*c}function bS(n,e,t){let i=1/0,r=t.length;for(let o=0,s=r-1;o<r;s=o++){let a=IC(n,e,t[s],t[o]);a<i&&(i=a)}return Math.sqrt(i)}function Kn(n,e,t,i){return i.length<3?!1:Tt(n,e,i)?!0:bS(n,e,i)<=Math.abs(t)}function Rd(n,e,t,i,r){let o=r.length;if(o<3)return!1;let s=Math.abs(t),a=Math.abs(i),l=n-s,c=n+s,u=e-a,h=e+a;for(let p of r)if(p.x>=l&&p.x<=c&&p.y>=u&&p.y<=h)return!0;let d=Er(s,a,{x:n,y:e});if(Tt(d[0].x,d[0].y,r))return!0;for(let p=0,f=o-1;p<o;f=p++){let m=r[f],g=r[p],y=g.x-m.x,b=g.y-m.y;for(let v=0,w=3;v<4;w=v++)if(vS(m.x,m.y,y,b,d[w],d[v])!==null)return!0}return!1}function RC(n,e,t,i,r){return SS(Er(t,i,{x:n,y:e}),r)}function SS(n,e){return n.length<3||e.length<3?!1:!mS(n,e)&&!mS(e,n)}function mS(n,e){let t=n.length;for(let i=0,r=t-1;i<t;r=i++){let o=n[i].x-n[r].x,s=n[i].y-n[r].y,a=Math.hypot(o,s);if(a<1e-9)continue;let l=s/a,c=-o/a,u=1/0,h=-1/0;for(let f of n){let m=f.x*l+f.y*c;m<u&&(u=m),m>h&&(h=m)}let d=1/0,p=-1/0;for(let f of e){let m=f.x*l+f.y*c;m<d&&(d=m),m>p&&(p=m)}if(h<d-1e-9||p<u-1e-9)return!0}return!1}function Bd(n,e,t,i,r){let o=r.length;if(o<3)return null;if(Tt(n,e,r))return 0;let s=null;for(let a=0,l=o-1;a<o;l=a++){let c=vS(n,e,t,i,r[l],r[a]);c!==null&&(s===null||c<s)&&(s=c)}return s}function vS(n,e,t,i,r,o){let s=o.x-r.x,a=o.y-r.y,l=t*a-i*s;if(Math.abs(l)<1e-9)return null;let c=r.x-n,u=r.y-e,h=(c*a-u*s)/l,d=(c*i-u*t)/l;return h<0||h>1||d<0||d>1?null:h}function Ka(n){let e=Ed(n);if(e.length<3)return[];if(e.length>512){let i=$a(e);return i.length>=3?[Dr(i)]:[]}let t=[];return Md(Dr(e),t,0),t}var BC=512;function Md(n,e,t){if(n.length<3)return;if(n.length===3||gS(n)){e.push(n);return}if(t>=BC){let o=$a(n);o.length>=3&&e.push(Dr(o));return}let i=n.length;for(let o=0;o<i;o++){if(!OC(n,o))continue;let s=-1,a=1/0;for(let l=2;l<=i-2;l++){let c=(o+l)%i;if(!VC(n,o,c))continue;let u=n[c].x-n[o].x,h=n[c].y-n[o].y,d=u*u+h*h;d<a&&(a=d,s=c)}if(!(s<0)){Md(fS(n,o,s),e,t+1),Md(fS(n,s,o),e,t+1);return}}let r=$a(n);r.length>=3&&e.push(Dr(r))}function OC(n,e){let t=n.length,i=n[(e-1+t)%t],r=n[e],o=n[(e+1)%t];return ii(i.x,i.y,r.x,r.y,o.x,o.y)<-1e-9}function VC(n,e,t){let i=n.length,r=n[e],o=n[t];for(let s=0,a=i-1;s<i;a=s++)if(!(a===e||a===t||s===e||s===t)&&LC(r,o,n[a],n[s]))return!1;return Tt((r.x+o.x)/2,(r.y+o.y)/2,n)}function LC(n,e,t,i){let r=ii(t.x,t.y,i.x,i.y,n.x,n.y),o=ii(t.x,t.y,i.x,i.y,e.x,e.y),s=ii(n.x,n.y,e.x,e.y,t.x,t.y),a=ii(n.x,n.y,e.x,e.y,i.x,i.y);return(r>1e-9&&o<-1e-9||r<-1e-9&&o>1e-9)&&(s>1e-9&&a<-1e-9||s<-1e-9&&a>1e-9)}function fS(n,e,t){let i=n.length,r=[];for(let o=e;r.push({x:n[o].x,y:n[o].y}),o!==t;o=(o+1)%i);return r}var wS=new se,Od=new S,xS=new F,Vd=new S;function ot(n,e){let t=e??{x:0,y:0,rotation:0,scaleX:1,scaleY:1};return n.updateWorldMatrix(!0,!1),wS.copy(n.matrixWorld),wS.decompose(Od,xS,Vd),t.x=Od.x,t.y=Od.y,t.rotation=PS(xS),t.scaleX=Vd.x||1,t.scaleY=Vd.y||1,t}function PS(n){return Math.atan2(2*(n.w*n.z+n.x*n.y),1-2*(n.y*n.y+n.z*n.z))}var Ld=new S,_d=new S,kS={x:0,y:0,rotation:0,scaleX:1,scaleY:1},Xn=class{sources=new Set;register(e){this.sources.add(e)}unregister(e){this.sources.delete(e)}get count(){return this.sources.size}overlapPoint(e,t,i){let r=[];for(let o of this.resolve(i))(o.polygon?Tt(e,t,o.polygon):o.shape==="circle"?Qa(e,t,o.cx,o.cy)<=o.r*o.r:Math.abs(e-o.cx)<=o.hw&&Math.abs(t-o.cy)<=o.hh)&&r.push(Fd(o));return r}overlapCircle(e,t,i,r){let o=[];for(let s of this.resolve(r)){let a;if(s.polygon)a=Kn(e,t,i,s.polygon);else if(s.shape==="circle"){let l=s.r+i;a=Qa(e,t,s.cx,s.cy)<=l*l}else{let l=Xa(e,s.cx-s.hw,s.cx+s.hw),c=Xa(t,s.cy-s.hh,s.cy+s.hh);a=Qa(e,t,l,c)<=i*i}a&&o.push(Fd(s))}return o}overlapRect(e,t,i,r,o){let s=Math.abs(i)/2,a=Math.abs(r)/2,l=[];for(let c of this.resolve(o)){let u;if(c.polygon)u=Rd(e,t,s,a,c.polygon);else if(c.shape==="circle"){let h=Xa(c.cx,e-s,e+s),d=Xa(c.cy,t-a,t+a);u=Qa(c.cx,c.cy,h,d)<=c.r*c.r}else u=Math.abs(c.cx-e)<=c.hw+s&&Math.abs(c.cy-t)<=c.hh+a;u&&l.push(Fd(c))}return l}raycast(e,t,i,r,o){let s=i-e,a=r-t,l=Math.hypot(s,a);if(l<=1e-6){let h=this.overlapPoint(e,t,o);return h.length>0?{...h[0],distance:0,x:e,y:t}:null}let c=null,u=1/0;for(let h of this.resolve(o)){let d=h.polygon?Bd(e,t,s,a,h.polygon):h.shape==="circle"?_C(e,t,s,a,h.cx,h.cy,h.r):FC(e,t,s,a,h.cx-h.hw,h.cy-h.hh,h.cx+h.hw,h.cy+h.hh);d!==null&&d<u&&(u=d,c={node:h.node,source:h.source,group:h.group,x:e+s*d,y:t+a*d,distance:l*d})}return c}*resolve(e){for(let t of this.sources){let i=t.node;if(!i||!t.enabled||!i.visible)continue;let r=t.getHitboxGroup();if(e!==void 0&&r!==e)continue;let o=t.getHitboxOffset(),s=t.getHitboxSize(),a=t.getHitboxShape();if(a==="polygon"){let u=t.getHitboxPolygon?.();if(!u||u.length<3)continue;ot(i,kS);let h=_i(u.map(p=>({x:p.x+o.x,y:p.y+o.y})),kS),d=Yn(h);yield{source:t,node:i,group:r,shape:a,cx:d.x,cy:d.y,hw:0,hh:0,r:0,polygon:h};continue}i.getWorldPosition(Ld),i.getWorldScale(_d);let l=Math.abs(_d.x)||1,c=Math.abs(_d.y)||1;yield{source:t,node:i,group:r,shape:a,cx:Ld.x+o.x*l,cy:Ld.y+o.y*c,hw:Math.abs(s.width)/2*l,hh:Math.abs(s.height)/2*c,r:Math.abs(s.radius)*Math.max(l,c),polygon:null}}}};function Fd(n){return{node:n.node,source:n.source,group:n.group,x:n.cx,y:n.cy}}function Xa(n,e,t){return n<e?e:n>t?t:n}function Qa(n,e,t,i){let r=t-n,o=i-e;return r*r+o*o}function _C(n,e,t,i,r,o,s){let a=n-r,l=e-o,c=t*t+i*i,u=2*(a*t+l*i),h=a*a+l*l-s*s;if(h<=0)return 0;let d=u*u-4*c*h;if(d<0||c<=1e-12)return null;let p=Math.sqrt(d),f=(-u-p)/(2*c);return f>=0&&f<=1?f:null}function FC(n,e,t,i,r,o,s,a){let l=0,c=1;for(let[u,h,d,p]of[[n,t,r,s],[e,i,o,a]])if(Math.abs(h)<1e-12){if(u<d||u>p)return null}else{let f=(d-u)/h,m=(p-u)/h;if(f>m){let g=f;f=m,m=g}if(l=Math.max(l,f),c=Math.min(c,m),l>c)return null}return l}var Te=1e-9,Fi=.5;function zd(n,e,t,i,r,o){let s=i-n,a=r-e,l=s*s+a*a,c=t+o,u=c+Fi;if(l>u*u)return null;let h=Math.sqrt(l),d=h>Te?s/h:1,p=h>Te?a/h:0,f=c-h;return{normalX:d,normalY:p,contacts:[{x:n+d*(t-f/2),y:e+p*(t-f/2),penetration:f,featureId:0}]}}function Ja(n,e,t,i){let r=i.length;if(r<3)return null;let o=-1/0,s=0;for(let w=0,k=r-1;w<r;k=w++){let T=i[w].x-i[k].x,E=i[w].y-i[k].y,A=Math.hypot(T,E);if(A<Te)continue;let _=E/A,J=-T/A,re=(n-i[k].x)*_+(e-i[k].y)*J;re>o&&(o=re,s=k)}if(o>t+Fi)return null;let a=i[s],l=i[(s+1)%r];if(o<Te){let w=l.x-a.x,k=l.y-a.y,T=Math.hypot(w,k)||1,E=k/T,A=-w/T;return{normalX:-E,normalY:-A,contacts:[{x:n+E*-o,y:e+A*-o,penetration:t-o,featureId:s}]}}let c=l.x-a.x,u=l.y-a.y,h=c*c+u*u,d=h>Te?((n-a.x)*c+(e-a.y)*u)/h:0;d=d<0?0:d>1?1:d;let p=a.x+c*d,f=a.y+u*d,m=p-n,g=f-e,y=Math.hypot(m,g);if(y>t+Fi)return null;let b=y>Te?m/y:0,v=y>Te?g/y:1;return{normalX:b,normalY:v,contacts:[{x:p,y:f,penetration:t-y,featureId:s}]}}function AS(n,e){let t=-1/0,i=0,r=n.length;for(let o=0;o<r;o++){let s=n[o],a=n[(o+1)%r],l=a.x-s.x,c=a.y-s.y,u=Math.hypot(l,c);if(u<Te)continue;let h=c/u,d=-l/u,p=1/0;for(let f of e){let m=(f.x-s.x)*h+(f.y-s.y)*d;m<p&&(p=m)}p>t&&(t=p,i=o)}return{separation:t,edgeIndex:i}}function zC(n,e,t){let i=n.length,r=1/0,o=0;for(let s=0;s<i;s++){let a=n[s],l=n[(s+1)%i],c=l.x-a.x,u=l.y-a.y,h=Math.hypot(c,u);if(h<Te)continue;let d=u/h*e+-c/h*t;d<r&&(r=d,o=s)}return o}function TS(n,e,t,i,r){let o=[],s=e*n[0].x+t*n[0].y-i,a=e*n[1].x+t*n[1].y-i;if(s<=0&&o.push(n[0]),a<=0&&o.push(n[1]),s*a<0){let l=s/(s-a);o.push({x:n[0].x+l*(n[1].x-n[0].x),y:n[0].y+l*(n[1].y-n[0].y),id:r})}return o}function Ud(n,e){if(n.length<3||e.length<3)return null;let t=AS(n,e);if(t.separation>Fi)return null;let i=AS(e,n);if(i.separation>Fi)return null;let r=i.separation>t.separation+1e-5,o=r?e:n,s=r?n:e,a=r?i.edgeIndex:t.edgeIndex,l=o.length,c=o[a],u=o[(a+1)%l],h=u.x-c.x,d=u.y-c.y,p=Math.hypot(h,d);if(p<Te)return null;let f=h/p,m=d/p,g=m,y=-f,b=zC(s,g,y),v=s.length,w=s[b],k=s[(b+1)%v],T=[{x:w.x,y:w.y,id:b*4+0},{x:k.x,y:k.y,id:b*4+1}];if(T=TS(T,-f,-m,-(f*c.x+m*c.y),a*4+2),T.length<2||(T=TS(T,f,m,f*u.x+m*u.y,a*4+3),T.length<2))return null;let E=g*c.x+y*c.y,A=[];for(let _ of T){let J=g*_.x+y*_.y-E;J<=Fi&&A.push({x:_.x,y:_.y,penetration:-J,featureId:_.id})}return A.length===0?null:r?{normalX:-g,normalY:-y,contacts:A}:{normalX:g,normalY:y,contacts:A}}function Qn(n,e,t,i,r,o){let s=o.length;if(s<3)return null;if(Kn(n,e,r,o))return 0;let a=null,l=c=>{c>=0&&c<=1&&(a===null||c<a)&&(a=c)};for(let c=0,u=s-1;c<s;u=c++){let h=o[u],d=o[c],p=d.x-h.x,f=d.y-h.y,m=Math.hypot(p,f);if(m<Te)continue;let g=f/m,y=-p/m,b=t*g+i*y;if(b<-Te){let k=-((n-h.x)*g+(e-h.y)*y-r)/b;if(k>=0&&k<=1){let T=n+t*k-g*r,E=e+i*k-y*r,A=((T-h.x)*p+(E-h.y)*f)/(m*m);A>=0&&A<=1&&l(k)}}let v=UC(n,e,t,i,h.x,h.y,r);v!==null&&l(v)}return a}function UC(n,e,t,i,r,o,s){let a=n-r,l=e-o,c=t*t+i*i;if(c<Te)return null;let u=2*(a*t+l*i),h=a*a+l*l-s*s;if(h<=0)return 0;let d=u*u-4*c*h;if(d<0)return null;let p=(-u-Math.sqrt(d))/(2*c);return p>=0&&p<=1?p:null}var CS=-1960,WC=8,HC=3,Wd=.05,qC=.2,MS=4,GC=.2,jC=40,$C=4,YC=.15,KC=.5,XC=8,Za=128,Jn=class{gravityX=0;gravityY=CS;bodies=new Map;colliders=new Map;staticBody;contacts=new Map;joints=new Map;jointedPairs=new Set;touching=new Map;signalQueue=[];orderCounter=0;constructor(){this.staticBody=QC()}setGravity(e,t){this.gravityX=Number.isFinite(e)?e:0,this.gravityY=Number.isFinite(t)?t:CS}getGravity(){return{x:this.gravityX,y:this.gravityY}}get bodyCount(){return this.bodies.size}get colliderCount(){return this.colliders.size}registerBody(e){let t=e.node;if(!t)return;let i=this.bodies.get(t);if(i){i.source=e;return}let r=ot(t);this.bodies.set(t,{node:t,source:e,bodyType:e.getBodyType(),x:r.x,y:r.y,rotation:r.rotation,vx:0,vy:0,w:0,forceX:0,forceY:0,torque:0,mass:1,invMass:1,inertia:1,invInertia:1,prevX:r.x,prevY:r.y,prevRotation:r.rotation,gravityScale:1,linearDamping:0,angularDamping:0,fixedRotation:!1,bullet:!1,canSleep:!0,emitContacts:!1,sleepTimer:0,sleeping:!1,colliders:[],order:this.orderCounter++,transformDirty:!1}),this.rebindColliders()}unregisterBody(e){let t=e.node;t&&(this.bodies.delete(t),this.rebindColliders())}registerCollider(e){if(!e.node)return;let t={source:e,body:this.staticBody,shape:el(),friction:.4,restitution:0,density:1,sensor:!1,group:"default",revision:"",bounds:{minX:0,minY:0,maxX:0,maxY:0},order:this.orderCounter++};this.colliders.set(e,t),this.rebindColliders()}unregisterCollider(e){let t=this.colliders.get(e);if(t){this.colliders.delete(e),t.body.colliders=t.body.colliders.filter(i=>i!==t);for(let[i,r]of this.contacts)(r.a===t||r.b===t)&&this.contacts.delete(i);for(let[i,r]of this.touching)r[0]!==t&&r[1]!==t||(this.wakeBody(r[0].body),this.wakeBody(r[1].body),this.touching.delete(i))}}registerJoint(e){let t=e.node;if(!t||this.joints.has(e))return;let i=this.bodies.get(t);if(!i)return;let r=e.getConnectedNode(),o=(r?this.bodies.get(r):null)??this.staticBody,s=i,a=e.getJointAnchor(),l=ot(t),c=Math.cos(l.rotation),u=Math.sin(l.rotation),h=l.x+a.x*c-a.y*u,d=l.y+a.x*u+a.y*c,p=IS(o,h,d),f=IS(s,h,d);this.joints.set(e,{source:e,bodyA:o,bodyB:s,localAX:p.x,localAY:p.y,localBX:f.x,localBY:f.y,referenceAngle:s.rotation-o.rotation,rax:0,ray:0,rbx:0,rby:0,massXX:0,massXY:0,massYY:0,angularMass:0,impulseX:0,impulseY:0,motorImpulse:0,lowerImpulse:0,upperImpulse:0,order:this.orderCounter++}),this.refreshJointedPairs()}unregisterJoint(e){this.joints.delete(e),this.refreshJointedPairs()}refreshJointedPairs(){this.jointedPairs=new Set;for(let e of this.joints.values())e.source.getJointConfig().collideConnected||this.jointedPairs.add(Gd(e.bodyA,e.bodyB))}get jointCount(){return this.joints.size}getBody(e){let t=e?this.bodies.get(e):null;return t?iM(t):null}step(e){if(!Number.isFinite(e)||e<=0||this.colliders.size===0)return;this.syncFromNodes();for(let i of this.bodies.values())i.prevX=i.x,i.prevY=i.y,i.prevRotation=i.rotation;this.refreshShapes(),this.integrateVelocities(e);let t=this.broadphase();this.narrowphase(t),this.prepareJoints(),this.warmStart(),this.warmStartJoints();for(let i=0;i<WC;i++)this.solveJointVelocities(e),this.solveVelocities(e);this.integratePositions(e),this.applyContinuousCollision(e);for(let i=0;i<HC;i++)this.solvePositions(),this.solveJointPositions();this.writeBackToNodes(),this.updateSleep(e),this.flushSignals()}interpolate(e){if(!Number.isFinite(e)||this.bodies.size===0)return;let t=e<0?0:e>1?1:e;for(let i of this.orderedBodies()){if(i.bodyType!=="dynamic"||i.sleeping)continue;let r=i.x,o=i.y,s=i.rotation;i.x=i.prevX+(r-i.prevX)*t,i.y=i.prevY+(o-i.prevY)*t,i.rotation=i.prevRotation+tM(i.prevRotation,s)*t,this.writeBodyToNode(i),i.x=r,i.y=o,i.rotation=s}}raycast(e,t,i,r,o={}){this.refreshShapes();let s=i-e,a=r-t,l=Math.hypot(s,a);if(l<1e-6)return null;let c=null,u=1/0;for(let h of this.orderedColliders(o)){let d=ZC(h.shape,e,t,s,a);d!==null&&d<u&&(u=d,c={node:h.source.node,group:h.group,x:e+s*d,y:t+a*d,distance:l*d})}return c}overlapCircle(e,t,i,r={}){this.refreshShapes();let o=DS(0,0,Math.abs(i));return o.worldCx=e,o.worldCy=t,this.orderedColliders(r).filter(s=>ES(o,s.shape)).map(s=>s.source.node)}overlapRect(e,t,i,r,o={}){this.refreshShapes();let s=tl([Er(Math.abs(i)/2,Math.abs(r)/2)]);return s.worldParts=s.parts.map(a=>_i(a,{x:e,y:t,rotation:0,scaleX:1,scaleY:1})),s.worldCx=e,s.worldCy=t,this.orderedColliders(o).filter(a=>ES(s,a.shape)).map(a=>a.source.node)}moveAndCollide(e,t,i,r={}){let o={movedX:0,movedY:0,collided:!1,normalX:0,normalY:0,collider:null},s=e?this.bodies.get(e):null;if(!s||!Number.isFinite(t)||!Number.isFinite(i))return o;this.refreshShapes();let a=s.x,l=s.y,c=Math.hypot(t,i),u=Math.max(1,Math.ceil(c/Math.max(1,this.bodyStepLimit(s)))),h=!1,d=0,p=0,f=-1/0,m=null;for(let g=0;g<u;g++){s.x+=t/u,s.y+=i/u;let y=this.depenetrate(s,r);y&&(h=!0,y.depth>f&&(f=y.depth,d=y.normalX,p=y.normalY,m=y.collider))}return this.writeBodyToNode(s),{movedX:s.x-a,movedY:s.y-l,collided:h,normalX:d,normalY:p,collider:m}}moveAndSlide(e,t,i,r,o={}){let s=o.upX??0,a=o.upY??1,l=Math.hypot(s,a)||1,c=s/l,u=a/l,h=Math.cos((o.floorMaxAngle??45)*Math.PI/180),d=Math.max(1,Math.floor(o.maxSlides??4)),p=t,f=i,m=t*r,g=i*r,y={velocityX:p,velocityY:f,isOnFloor:!1,isOnWall:!1,isOnCeiling:!1,floorNormalX:0,floorNormalY:0,collider:null};for(let v=0;v<d&&!(Math.hypot(m,g)<1e-6);v++){let w=this.moveAndCollide(e,m,g,o);if(!w.collided)break;let k=w.normalX,T=w.normalY,E=k*c+T*u;E>=h?(y.isOnFloor=!0,y.floorNormalX=k,y.floorNormalY=T):E<=-h?y.isOnCeiling=!0:y.isOnWall=!0,y.collider=w.collider,m-=w.movedX,g-=w.movedY;let A=m*k+g*T;A<0&&(m-=k*A,g-=T*A);let _=p*k+f*T;_<0&&(p-=k*_,f-=T*_)}y.velocityX=p,y.velocityY=f;let b=e?this.bodies.get(e):null;return b&&(b.vx=p,b.vy=f),y}bodyStepLimit(e){let t=1/0;for(let i of e.colliders){if(i.sensor||i.shape.kind==="empty")continue;let r=i.shape.kind==="circle"?i.shape.radius*2:Math.min(i.bounds.maxX-i.bounds.minX,i.bounds.maxY-i.bounds.minY);t=Math.min(t,r)}return Number.isFinite(t)?Math.max(1,t/2):1/0}depenetrate(e,t){let i=null;for(let r=0;r<4;r++){for(let s of e.colliders)this.refreshColliderWorldShape(s);let o=null;for(let s of e.colliders)if(!(s.sensor||s.shape.kind==="empty")){for(let a of this.orderedColliders(t))if(!(a.body===e||a.shape.kind==="empty"))for(let l of jd(s.shape,a.shape))for(let c of l.manifold.contacts)c.penetration<=Wd||(!o||c.penetration>o.depth)&&(o={normalX:-l.manifold.normalX,normalY:-l.manifold.normalY,depth:c.penetration,collider:a.source.node})}if(!o)break;e.x+=o.normalX*o.depth,e.y+=o.normalY*o.depth,(!i||o.depth>i.depth)&&(i=o)}return i}writeBodyToNode(e){let t=e.node,i=t.parentNode;if(!i){t.position.set(e.x,e.y,t.position.z),t.rotation.z=e.rotation;return}let r=ot(i),o=e.x-r.x,s=e.y-r.y,a=Math.cos(-r.rotation),l=Math.sin(-r.rotation),c=r.scaleX||1,u=r.scaleY||1;t.position.set((o*a-s*l)/c,(o*l+s*a)/u,t.position.z),t.rotation.z=e.rotation-r.rotation}buildDebugBuffers(){this.refreshShapes();let e=[],t=[];for(let i of this.orderedColliders({includeSensors:!0})){let r=i.shape.kind==="circle"?[BS(i.shape)]:i.shape.worldParts,o=i.sensor?[.5,.95,.4]:i.body.sleeping?[.45,.5,.55]:[.12,.74,.89];for(let s of r)for(let a=0,l=s.length-1;a<s.length;l=a++)e.push(s[l].x,s[l].y,0,s[a].x,s[a].y,0),t.push(o[0],o[1],o[2],1,o[0],o[1],o[2],1)}return{vertices:new Float32Array(e),colors:new Float32Array(t)}}clear(){this.bodies.clear(),this.colliders.clear(),this.contacts.clear(),this.touching.clear(),this.joints.clear(),this.jointedPairs.clear(),this.signalQueue.length=0,this.staticBody.colliders=[]}rebindColliders(){this.staticBody.colliders=[];for(let e of this.bodies.values())e.colliders=[];for(let e of this.colliders.values()){let t=this.findOwningBody(e.source.node)??this.staticBody;e.body=t,t.colliders.push(e)}for(let e of this.bodies.values())e.colliders.sort((t,i)=>t.order-i.order),this.recomputeMass(e);this.staticBody.colliders.sort((e,t)=>e.order-t.order)}findOwningBody(e){let t=e;for(;t;){let i=this.bodies.get(t);if(i)return i;t=t.parentNode??null}return null}syncFromNodes(){for(let e of this.bodies.values()){let t=e.source;if(t){let i=t.getBodyConfig(),r=t.getBodyType();r!==e.bodyType&&(e.bodyType=r,this.recomputeMass(e),e.sleeping=!1),e.gravityScale=i.gravityScale,e.linearDamping=i.linearDamping,e.angularDamping=i.angularDamping,e.bullet=i.bullet,e.canSleep=i.canSleep,e.emitContacts=i.emitContacts,i.fixedRotation!==e.fixedRotation&&(e.fixedRotation=i.fixedRotation,this.recomputeMass(e),i.fixedRotation&&(e.w=0))}if(e.bodyType!=="dynamic"||e.transformDirty){let i=ot(e.node);e.bodyType==="kinematic"&&!e.transformDirty&&(e.vx=0,e.vy=0),e.x=i.x,e.y=i.y,e.rotation=i.rotation,e.transformDirty=!1}}}refreshShapes(){for(let e of this.colliders.values()){let t=e.source;if(!t.node)continue;let r=t.getColliderRevision();if(r!==e.revision){e.revision=r;let o=t.getColliderMaterial();e.friction=o.friction,e.restitution=o.restitution,e.density=o.density,e.sensor=t.isSensor(),e.group=t.getColliderGroup(),e.shape=this.bakeShape(e),this.recomputeMass(e.body)}this.refreshColliderWorldShape(e)}}refreshColliderWorldShape(e){let t=e.body,i=this.colliderLocalTransform(e),r=Math.cos(t.rotation),o=Math.sin(t.rotation),s=i.x*r-i.y*o,a=i.x*o+i.y*r,l={x:t.x+s,y:t.y+a,rotation:t.rotation+i.rotation,scaleX:1,scaleY:1};if(e.shape.kind==="circle"){let p=_i([{x:e.shape.cx,y:e.shape.cy}],l);e.shape.worldCx=p[0].x,e.shape.worldCy=p[0].y,e.bounds={minX:e.shape.worldCx-e.shape.radius,minY:e.shape.worldCy-e.shape.radius,maxX:e.shape.worldCx+e.shape.radius,maxY:e.shape.worldCy+e.shape.radius};return}e.shape.worldParts=e.shape.parts.map(p=>_i(p,l));let c=1/0,u=1/0,h=-1/0,d=-1/0;for(let p of e.shape.worldParts){let f=Nd(p);c=Math.min(c,f.minX),u=Math.min(u,f.minY),h=Math.max(h,f.maxX),d=Math.max(d,f.maxY)}e.bounds={minX:c,minY:u,maxX:h,maxY:d},e.shape.worldCx=(c+h)/2,e.shape.worldCy=(u+d)/2}colliderLocalTransform(e){let t=e.source.node,i=e.body;if(!t||t===i.node)return{x:0,y:0,rotation:0,scaleX:1,scaleY:1};let r=ot(t),o=r.x-i.x,s=r.y-i.y,a=Math.cos(-i.rotation),l=Math.sin(-i.rotation);return{x:o*a-s*l,y:o*l+s*a,rotation:r.rotation-i.rotation,scaleX:1,scaleY:1}}bakeShape(e){let t=e.source,i=t.node,r=t.getColliderSize(),o=t.getColliderOffset(),s=i?ot(i):{scaleX:1,scaleY:1},a=Math.abs(s.scaleX)||1,l=Math.abs(s.scaleY)||1;switch(t.getColliderShape()){case"circle":return DS(o.x*a,o.y*l,Math.abs(r.radius)*Math.max(a,l));case"capsule":{let c=Ka(Id(Math.abs(r.height)*l,Math.abs(r.radius)*Math.max(a,l),XC,{x:o.x*a,y:o.y*l}));return c.length>0?tl(c):el()}case"polygon":{let u=t.getColliderPolygon().map(d=>({x:(d.x+o.x)*a,y:(d.y+o.y)*l})),h=Ka(u);return h.length>0?tl(h):el()}default:{let c=Math.abs(r.width)/2*a,u=Math.abs(r.height)/2*l;return c<=0||u<=0?el():tl([Er(c,u,{x:o.x*a,y:o.y*l})])}}}recomputeMass(e){if(e.bodyType!=="dynamic"){e.mass=0,e.invMass=0,e.inertia=0,e.invInertia=0;return}let t=0,i=0;for(let o of e.colliders)o.sensor||(t+=o.shape.area*o.density,i+=o.shape.inertiaPerDensity*o.density);let r=e.source?.getBodyConfig().mass??0;if(r>0){let o=t>0?r/t:0;i=o>0?i*o:r,t=r}t<=0&&(t=1,i=1),e.mass=t,e.invMass=1/t,e.inertia=e.fixedRotation?0:i,e.invInertia=e.fixedRotation||i<=0?0:1/i}integrateVelocities(e){for(let t of this.orderedBodies()){if(t.bodyType!=="dynamic"||t.sleeping){t.forceX=0,t.forceY=0,t.torque=0;continue}t.vx+=(this.gravityX*t.gravityScale+t.forceX*t.invMass)*e,t.vy+=(this.gravityY*t.gravityScale+t.forceY*t.invMass)*e,t.fixedRotation||(t.w+=t.torque*t.invInertia*e),t.vx*=1/(1+e*t.linearDamping),t.vy*=1/(1+e*t.linearDamping),t.w*=1/(1+e*t.angularDamping),t.forceX=0,t.forceY=0,t.torque=0}}broadphase(){let e=new Map,t=[...this.colliders.values()].sort((o,s)=>o.order-s.order);for(let o of t){if(!o.source.enabled||!o.source.node||o.shape.kind==="empty")continue;let s=Math.floor(o.bounds.minX/Za),a=Math.floor(o.bounds.maxX/Za),l=Math.floor(o.bounds.minY/Za),c=Math.floor(o.bounds.maxY/Za);for(let u=s;u<=a;u++)for(let h=l;h<=c;h++){let d=`${u},${h}`,p=e.get(d);p?p.push(o):e.set(d,[o])}}let i=new Set,r=[];for(let o of e.values())for(let s=0;s<o.length;s++)for(let a=s+1;a<o.length;a++){let l=o[s],c=o[a];if(!this.shouldCollide(l,c)||!eM(l.bounds,c.bounds))continue;let u=NS(l,c);i.has(u)||(i.add(u),r.push(l.order<c.order?[l,c]:[c,l]))}return r.sort((o,s)=>o[0].order-s[0].order||o[1].order-s[1].order),r}shouldCollide(e,t){return!(e.body===t.body||this.jointedPairs.has(Gd(e.body,t.body))||e.body.bodyType!=="dynamic"&&t.body.bodyType!=="dynamic")}narrowphase(e){let t=new Map,i=new Map;for(let[r,o]of e){let s=jd(r.shape,o.shape),a=NS(r,o);if(!(s.length===0||(t.set(a,[r,o]),r.sensor||o.sensor))){for(let c of s){let u=c.manifold,h=a+":"+c.partA+":"+c.partB,d=this.contacts.get(h),p={a:r,b:o,partA:c.partA,partB:c.partB,normalX:u.normalX,normalY:u.normalY,friction:Math.sqrt(Math.max(0,r.friction)*Math.max(0,o.friction)),restitution:Math.max(r.restitution,o.restitution),points:u.contacts.map(f=>{let m=d?.points.find(g=>g.featureId===f.featureId);return{featureId:f.featureId,normalImpulse:m?.normalImpulse??0,tangentImpulse:m?.tangentImpulse??0,rax:0,ray:0,rbx:0,rby:0,normalMass:0,tangentMass:0,bias:0,penetration:f.penetration,x:f.x,y:f.y}}),approachSpeed:[],prepAx:0,prepAy:0,prepBx:0,prepBy:0};this.prepareContact(p),i.set(h,p)}this.touching.has(a)||(this.wakeBody(r.body),this.wakeBody(o.body)),this.wakeIfTouchedByAwake(r.body,o.body)}}this.emitTransitions(t),this.contacts.clear();for(let[r,o]of i)this.contacts.set(r,o);this.touching=t}emitTransitions(e){for(let[t,i]of e)this.touching.has(t)||this.queueContactSignal(i[0],i[1],!0);for(let[t,i]of this.touching)e.has(t)||this.queueContactSignal(i[0],i[1],!1)}queueContactSignal(e,t,i){let r=e.source.node,o=t.source.node;if(!r||!o)return;let s=e.sensor||t.sensor,a=s?i?"body-entered":"body-exited":i?"contact-started":"contact-ended",l=(c,u,h)=>{!s&&!c.body.emitContacts||s&&!c.sensor||this.signalQueue.push({node:u,name:a,args:[h]})};l(e,r,o),l(t,o,r)}prepareContact(e){let t=e.a.body,i=e.b.body,r=e.normalX,o=e.normalY,s=-o,a=r;e.approachSpeed=[],e.prepAx=t.x,e.prepAy=t.y,e.prepBx=i.x,e.prepBy=i.y;for(let l of e.points){l.rax=l.x-t.x,l.ray=l.y-t.y,l.rbx=l.x-i.x,l.rby=l.y-i.y;let c=l.rax*o-l.ray*r,u=l.rbx*o-l.rby*r,h=t.invMass+i.invMass+t.invInertia*c*c+i.invInertia*u*u;l.normalMass=h>0?1/h:0;let d=l.rax*a-l.ray*s,p=l.rbx*a-l.rby*s,f=t.invMass+i.invMass+t.invInertia*d*d+i.invInertia*p*p;l.tangentMass=f>0?1/f:0;let m=rl(t,i,l,r,o);e.approachSpeed.push(m<-jC?m:0),l.bias=0}}warmStart(){for(let e of this.orderedContacts()){if(qd(e))continue;let t=e.a.body,i=e.b.body,r=-e.normalY,o=e.normalX;for(let s of e.points){let a=e.normalX*s.normalImpulse+r*s.tangentImpulse,l=e.normalY*s.normalImpulse+o*s.tangentImpulse;we(t,-a,-l,s.rax,s.ray),we(i,a,l,s.rbx,s.rby)}}}solveVelocities(e){for(let t of this.orderedContacts()){if(qd(t))continue;let i=t.a.body,r=t.b.body,o=t.normalX,a=-t.normalY,l=o;for(let c of t.points){let h=-OS(i,r,c,a,l)*c.tangentMass,d=t.friction*c.normalImpulse,p=RS(c.tangentImpulse+h,-d,d);h=p-c.tangentImpulse,c.tangentImpulse=p,we(i,-a*h,-l*h,c.rax,c.ray),we(r,a*h,l*h,c.rbx,c.rby)}if(!(t.points.length===2&&this.solveNormalBlock(t,e)))for(let c=0;c<t.points.length;c++)this.solveNormalPoint(t,t.points[c],Hd(t,c,e))}}solveNormalPoint(e,t,i){let r=e.a.body,o=e.b.body,s=e.normalX,a=e.normalY,c=-(rl(r,o,t,s,a)-i)*t.normalMass,u=Math.max(0,t.normalImpulse+c);c=u-t.normalImpulse,t.normalImpulse=u,we(r,-s*c,-a*c,t.rax,t.ray),we(o,s*c,a*c,t.rbx,t.rby)}solveNormalBlock(e,t){let i=e.a.body,r=e.b.body,[o,s]=e.points,a=e.normalX,l=e.normalY,c=o.rax*l-o.ray*a,u=o.rbx*l-o.rby*a,h=s.rax*l-s.ray*a,d=s.rbx*l-s.rby*a,p=i.invMass+r.invMass,f=p+i.invInertia*c*c+r.invInertia*u*u,m=p+i.invInertia*h*h+r.invInertia*d*d,g=p+i.invInertia*c*h+r.invInertia*u*d,y=f*m-g*g;if(!(f*f<1e3*y)||y===0)return!1;let b=o.normalImpulse,v=s.normalImpulse,w=rl(i,r,o,a,l)-Hd(e,0,t),k=rl(i,r,s,a,l)-Hd(e,1,t);w-=f*b+g*v,k-=g*b+m*v;let T=[[(-m*w+g*k)/y,(g*w-f*k)/y],[-w/f,0],[0,-k/m],[0,0]];for(let E=0;E<T.length;E++){let[A,_]=T[E];if(A<0||_<0||E===1&&g*A+k<0||E===2&&g*_+w<0||E===3&&(w<0||k<0))continue;let J=A-b,re=_-v;return we(i,-a*J,-l*J,o.rax,o.ray),we(r,a*J,l*J,o.rbx,o.rby),we(i,-a*re,-l*re,s.rax,s.ray),we(r,a*re,l*re,s.rbx,s.rby),o.normalImpulse=A,s.normalImpulse=_,!0}return!1}orderedJoints(){return[...this.joints.values()].sort((e,t)=>e.order-t.order)}prepareJoints(){for(let e of this.orderedJoints()){let t=e.bodyA,i=e.bodyB,r=Math.cos(t.rotation),o=Math.sin(t.rotation),s=Math.cos(i.rotation),a=Math.sin(i.rotation);e.rax=e.localAX*r-e.localAY*o,e.ray=e.localAX*o+e.localAY*r,e.rbx=e.localBX*s-e.localBY*a,e.rby=e.localBX*a+e.localBY*s;let l=t.invMass,c=i.invMass,u=t.invInertia,h=i.invInertia,d=l+c+u*e.ray*e.ray+h*e.rby*e.rby,p=-u*e.rax*e.ray-h*e.rbx*e.rby,f=l+c+u*e.rax*e.rax+h*e.rbx*e.rbx,m=d*f-p*p;Math.abs(m)>1e-12?(e.massXX=f/m,e.massXY=-p/m,e.massYY=d/m):(e.massXX=0,e.massXY=0,e.massYY=0);let g=u+h;e.angularMass=g>0?1/g:0;let y=e.source.getJointConfig();this.syncJointedPair(e,y.collideConnected),y.motorEnabled&&y.motorSpeed!==0&&(this.wakeBody(t),this.wakeBody(i))}}syncJointedPair(e,t){let i=Gd(e.bodyA,e.bodyB);t?this.jointedPairs.delete(i):this.jointedPairs.add(i)}warmStartJoints(){for(let e of this.orderedJoints()){let t=e.bodyA,i=e.bodyB,r=e.motorImpulse+e.lowerImpulse-e.upperImpulse;we(t,-e.impulseX,-e.impulseY,e.rax,e.ray),we(i,e.impulseX,e.impulseY,e.rbx,e.rby),ri(t,-r),ri(i,r)}}solveJointVelocities(e){for(let t of this.orderedJoints()){let i=t.bodyA,r=t.bodyB;if(!t.source.enabled)continue;let o=t.source.getJointConfig();if(o.motorEnabled&&t.angularMass>0){let f=r.w-i.w-o.motorSpeed,m=-t.angularMass*f,g=o.maxMotorTorque*e,y=RS(t.motorImpulse+m,-g,g);m=y-t.motorImpulse,t.motorImpulse=y,ri(i,-m),ri(r,m)}else t.motorImpulse=0;if(o.limitEnabled&&t.angularMass>0){let f=r.rotation-i.rotation-t.referenceAngle;{let m=f-o.lowerAngle,g=-t.angularMass*(r.w-i.w+Math.max(m,0)/e),y=Math.max(t.lowerImpulse+g,0);g=y-t.lowerImpulse,t.lowerImpulse=y,ri(i,-g),ri(r,g)}{let m=o.upperAngle-f,g=-t.angularMass*(i.w-r.w+Math.max(m,0)/e),y=Math.max(t.upperImpulse+g,0);g=y-t.upperImpulse,t.upperImpulse=y,ri(i,g),ri(r,-g)}}else t.lowerImpulse=0,t.upperImpulse=0;let s=i.vx-i.w*t.ray,a=i.vy+i.w*t.rax,l=r.vx-r.w*t.rby,c=r.vy+r.w*t.rbx,u=l-s,h=c-a,d=-(t.massXX*u+t.massXY*h),p=-(t.massXY*u+t.massYY*h);t.impulseX+=d,t.impulseY+=p,we(i,-d,-p,t.rax,t.ray),we(r,d,p,t.rbx,t.rby)}}solveJointPositions(){for(let e of this.orderedJoints()){let t=e.bodyA,i=e.bodyB,r=t.invMass+i.invMass;if(r<=0)continue;let o=Math.cos(t.rotation),s=Math.sin(t.rotation),a=Math.cos(i.rotation),l=Math.sin(i.rotation),c=t.x+e.localAX*o-e.localAY*s,u=t.y+e.localAX*s+e.localAY*o,h=i.x+e.localBX*a-e.localBY*l,d=i.y+e.localBX*l+e.localBY*a,p=h-c,f=d-u,m=Math.hypot(p,f);if(m<Wd)continue;let g=Math.min(m,MS)*GC,y=p/m,b=f/m;t.x+=y*g*t.invMass/r,t.y+=b*g*t.invMass/r,i.x-=y*g*i.invMass/r,i.y-=b*g*i.invMass/r}}integratePositions(e){for(let t of this.orderedBodies())t.bodyType!=="dynamic"||t.sleeping||(t.x+=t.vx*e,t.y+=t.vy*e,t.fixedRotation||(t.rotation+=t.w*e))}applyContinuousCollision(e){for(let t of this.orderedBodies()){if(t.bodyType!=="dynamic"||!t.bullet||t.sleeping)continue;let i=t.vx*e,r=t.vy*e,o=Math.hypot(i,r),s=t.colliders.find(u=>!u.sensor&&u.shape.kind==="circle");if(!s||o<s.shape.radius)continue;let a=t.x-i,l=t.y-r,c=null;for(let u of this.colliders.values())if(!(u.body===t||u.sensor||u.body.bodyType==="dynamic"))for(let h of u.shape.worldParts){let d=Qn(a,l,i,r,s.shape.radius,h);d!==null&&(c===null||d<c)&&(c=d)}c!==null&&c<1&&(t.x=a+i*c,t.y=l+r*c)}}solvePositions(){for(let e of this.orderedContacts()){if(qd(e))continue;let t=e.a.body,i=e.b.body,r=t.invMass+i.invMass;if(r<=0)continue;let o=i.x-e.prepBx-(t.x-e.prepAx),s=i.y-e.prepBy-(t.y-e.prepAy),a=o*e.normalX+s*e.normalY;for(let l of e.points){let c=l.penetration-a,u=Math.min(Math.max(c-Wd,0)*qC/r,MS/r);u<=0||(t.x-=e.normalX*u*t.invMass,t.y-=e.normalY*u*t.invMass,i.x+=e.normalX*u*i.invMass,i.y+=e.normalY*u*i.invMass)}}}updateSleep(e){let t=this.orderedBodies().filter(s=>s.bodyType==="dynamic");if(t.length===0)return;let i=new Map;for(let s of t)i.set(s,s);let r=s=>{let a=s;for(;i.get(a)!==a;)a=i.get(a);let l=s;for(;i.get(l)!==a;){let c=i.get(l);i.set(l,a),l=c}return a};for(let s of this.contacts.values()){let a=s.a.body,l=s.b.body;if(a.bodyType!=="dynamic"||l.bodyType!=="dynamic")continue;let c=r(a),u=r(l);c!==u&&i.set(c,u)}let o=new Map;for(let s of t){let a=r(s),l=o.get(a);l?l.push(s):o.set(a,[s])}for(let s of o.values()){if(!(s.every(u=>u.canSleep)&&s.every(u=>Math.hypot(u.vx,u.vy)<$C&&Math.abs(u.w)<YC))){for(let u of s)u.sleepTimer=0,u.sleeping=!1;continue}let c=1/0;for(let u of s)u.sleepTimer+=e,c=Math.min(c,u.sleepTimer);if(!(c<KC))for(let u of s)u.sleeping=!0,u.vx=0,u.vy=0,u.w=0}}wakeIfTouchedByAwake(e,t){let i=e.bodyType==="dynamic"&&!e.sleeping,r=t.bodyType==="dynamic"&&!t.sleeping;i&&t.sleeping&&this.wakeBody(t),r&&e.sleeping&&this.wakeBody(e)}wakeBody(e){e.bodyType==="dynamic"&&(e.sleeping=!1,e.sleepTimer=0)}writeBackToNodes(){for(let e of this.orderedBodies())e.bodyType!=="dynamic"||e.sleeping||this.writeBodyToNode(e)}flushSignals(){if(this.signalQueue.length===0)return;let e=this.signalQueue.splice(0,this.signalQueue.length);for(let t of e)t.node.emit(t.name,...t.args)}orderedBodies(){return[...this.bodies.values()].sort((e,t)=>e.order-t.order)}orderedContacts(){return[...this.contacts.values()].sort((e,t)=>e.a.order-t.a.order||e.b.order-t.b.order||e.partA-t.partA||e.partB-t.partB)}orderedColliders(e){return[...this.colliders.values()].filter(t=>!t.source.enabled||!t.source.node||t.shape.kind==="empty"||!e.includeSensors&&t.sensor?!1:e.group===void 0||t.group===e.group).sort((t,i)=>t.order-i.order)}};function QC(){return{node:null,source:null,bodyType:"static",x:0,y:0,rotation:0,vx:0,vy:0,w:0,forceX:0,forceY:0,torque:0,mass:0,invMass:0,inertia:0,invInertia:0,prevX:0,prevY:0,prevRotation:0,gravityScale:0,linearDamping:0,angularDamping:0,fixedRotation:!0,bullet:!1,canSleep:!1,emitContacts:!1,sleepTimer:0,sleeping:!1,colliders:[],order:-1,transformDirty:!1}}function el(){return{kind:"empty",cx:0,cy:0,radius:0,parts:[],worldParts:[],worldCx:0,worldCy:0,area:0,inertiaPerDensity:0,centroidX:0,centroidY:0}}function DS(n,e,t){let i=Math.PI*t*t;return{kind:"circle",cx:n,cy:e,radius:t,parts:[],worldParts:[],worldCx:n,worldCy:e,area:i,inertiaPerDensity:i*(.5*t*t+n*n+e*e),centroidX:n,centroidY:e}}function tl(n){let e=0,t=0,i=0,r=0;for(let o of n){let s=Dd(o),a=Yn(o);e+=s,i+=a.x*s,r+=a.y*s,t+=JC(o)}return{kind:"polygon",cx:0,cy:0,radius:0,parts:n,worldParts:n.map(o=>o.map(s=>({x:s.x,y:s.y}))),worldCx:0,worldCy:0,area:e,inertiaPerDensity:t,centroidX:e>0?i/e:0,centroidY:e>0?r/e:0}}function JC(n){let e=0,t=0,i=n.length;for(let r=0,o=i-1;r<i;o=r++){let s=n[o],a=n[r],l=Math.abs(s.x*a.y-a.x*s.y);e+=l*(s.x*s.x+s.x*a.x+a.x*a.x+s.y*s.y+s.y*a.y+a.y*a.y),t+=l}return t>0?e/12:0}function jd(n,e){let t=[];if(n.kind==="circle"&&e.kind==="circle"){let i=zd(n.worldCx,n.worldCy,n.radius,e.worldCx,e.worldCy,e.radius);return i&&t.push({manifold:i,partA:0,partB:0}),t}return n.kind==="circle"?(e.worldParts.forEach((i,r)=>{let o=Ja(n.worldCx,n.worldCy,n.radius,i);o&&!il(o,e,r)&&t.push({manifold:o,partA:0,partB:r})}),t):e.kind==="circle"?(n.worldParts.forEach((i,r)=>{let o=Ja(e.worldCx,e.worldCy,e.radius,i);o&&!il(o,n,r)&&t.push({manifold:{...o,normalX:-o.normalX,normalY:-o.normalY},partA:r,partB:0})}),t):(n.worldParts.forEach((i,r)=>{e.worldParts.forEach((o,s)=>{let a=Ud(i,o);a&&!il(a,n,r)&&!il(a,e,s)&&t.push({manifold:a,partA:r,partB:s})})}),t)}function il(n,e,t){return e.worldParts.length<2?!1:n.contacts.every(i=>{for(let r=0;r<e.worldParts.length;r++)if(r!==t&&Tt(i.x,i.y,e.worldParts[r]))return!0;return!1})}function ES(n,e){return jd(n,e).length>0}function ZC(n,e,t,i,r){if(n.kind==="circle")return Qn(e,t,i,r,0,BS(n));let o=null;for(let s of n.worldParts){let a=Qn(e,t,i,r,0,s);a!==null&&(o===null||a<o)&&(o=a)}return o}function BS(n){let t=new Array(16);for(let i=0;i<16;i++){let r=i/16*Math.PI*2;t[i]={x:n.worldCx+Math.cos(r)*n.radius,y:n.worldCy+Math.sin(r)*n.radius}}return t}function Hd(n,e,t){let i=-n.points[e].penetration;return i>0?-i/t:-n.restitution*n.approachSpeed[e]}function qd(n){let e=n.a.body,t=n.b.body,i=e.bodyType!=="dynamic"||e.sleeping,r=t.bodyType!=="dynamic"||t.sleeping;return i&&r}function eM(n,e){return n.minX<=e.maxX&&n.maxX>=e.minX&&n.minY<=e.maxY&&n.maxY>=e.minY}function Gd(n,e){return n.order<e.order?`${n.order}/${e.order}`:`${e.order}/${n.order}`}function NS(n,e){return n.order<e.order?`${n.order}:${e.order}`:`${e.order}:${n.order}`}function OS(n,e,t,i,r){let o=n.vx-n.w*t.ray,s=n.vy+n.w*t.rax,a=e.vx-e.w*t.rby,l=e.vy+e.w*t.rbx;return(a-o)*i+(l-s)*r}function rl(n,e,t,i,r){return OS(n,e,t,i,r)}function we(n,e,t,i,r){n.sleeping||n.invMass<=0&&n.invInertia<=0||(n.vx+=e*n.invMass,n.vy+=t*n.invMass,n.w+=(i*t-r*e)*n.invInertia)}function IS(n,e,t){let i=e-n.x,r=t-n.y,o=Math.cos(-n.rotation),s=Math.sin(-n.rotation);return{x:i*o-r*s,y:i*s+r*o}}function ri(n,e){n.sleeping||n.invInertia<=0||(n.w+=e*n.invInertia)}function tM(n,e){let t=(e-n)%(Math.PI*2);return t>Math.PI?t-=Math.PI*2:t<-Math.PI&&(t+=Math.PI*2),t}function RS(n,e,t){return n<e?e:n>t?t:n}function iM(n){return{node:n.node,get bodyType(){return n.bodyType},get velocityX(){return n.vx},get velocityY(){return n.vy},get angularVelocity(){return n.w},get isSleeping(){return n.sleeping},setVelocity(e,t){n.vx=e,n.vy=t,n.sleeping=!1,n.sleepTimer=0},setAngularVelocity(e){n.w=e,n.sleeping=!1,n.sleepTimer=0},applyImpulse(e,t){n.vx+=e*n.invMass,n.vy+=t*n.invMass,n.sleeping=!1,n.sleepTimer=0},applyForce(e,t){n.forceX+=e,n.forceY+=t,n.sleeping=!1,n.sleepTimer=0},teleport(e,t,i){n.x=e,n.y=t,typeof i=="number"&&(n.rotation=i),n.vx=0,n.vy=0,n.w=0,n.prevX=n.x,n.prevY=n.y,n.prevRotation=n.rotation,n.sleeping=!1,n.sleepTimer=0},wake(){n.sleeping=!1,n.sleepTimer=0}}}var q={None:0,ProtocolVersionMismatch:1,InvalidToken:2,TokenExpired:3,TokenRoomMismatch:4,RoomNotFound:5,RoomFull:6,RoomClosing:7,RateLimited:8,PayloadTooLarge:9,QuotaExceeded:10,ServerShuttingDown:11,IdleTimeout:12,BadRequest:13,SessionReplaced:14,EntityLimitReached:15,NotEntityOwner:16,InternalError:17,KindNotAllowed:18,SendQueueOverflow:19};var Zn={Server:0,AllPeers:1,SinglePeer:2,AoiPeers:3};var LS={Relay:0,Authoritative:1};var j={None:0,X:1,Y:2,Rot:4,Vx:8,Vy:16,Flags:32,ColdDirty:64,Teleport:128,TwoByteFieldBits:27,OneByteFieldBits:36,PayloadBits:63,SignalBits:192,MaxPayloadSize:10};function $d(n){return(VS(n&j.TwoByteFieldBits)<<1)+VS(n&j.OneByteFieldBits)}function VS(n){let e=n&255,t=0;for(;e!==0;)e&=e-1,t+=1;return t}var rM=j.PayloadBits|j.Teleport,aF=~rM&255;var nM={None:0,Final:1,ReservedBits:254};function Yd(n){return(n&nM.Final)!==0}var cF=65535;function _S(n){let e=n.trim().replace(/\\/g,"/");return(e.startsWith("res://")?e.slice(6):e).replace(/^\.\//,"").replace(/^\/+/,"")}var eo=class{entries=[];byKey=new Map;authoredCount=0;constructor(e){e&&this.replaceAll(e)}get size(){return this.entries.length}get prefabCount(){return this.entries.length-this.authoredCount}get isEmpty(){return this.entries.length===0}replaceAll(e){let t=Array.isArray(e),i=t?e:e.prefabs,r=t?[]:e.authored??[];this.entries.length=0,this.byKey.clear(),this.authoredCount=0;for(let o of i)this.append(o);for(let o of r){if(this.entries.length>65535)break;this.entries.push(o),this.authoredCount+=1}}register(e){let t=this.kindOf(e);if(t!==null)return t;if(this.authoredCount>0)throw new RangeError("Cannot register a prefab into a net kind table that already carries an authored-binding segment: appending would shift every authored index.");return this.append(e)}kindOf(e){return this.byKey.get(_S(e))??null}prefabPathOf(e){return!Number.isInteger(e)||e<0||e>=this.prefabCount?null:this.entries[e]}toArray(){return[...this.entries]}clear(){this.entries.length=0,this.byKey.clear(),this.authoredCount=0}append(e){let t=_S(e),i=this.byKey.get(t);if(i!==void 0)return i;if(this.entries.length>65535)throw new RangeError("A net kind table holds at most 65536 entries.");let r=this.entries.length;return this.entries.push(e.trim()),this.byKey.set(t,r),r}},nl=new eo;function Kd(){return nl}function oM(n){nl.replaceAll(n)}function sM(n){return nl.register(n)}function aM(){nl=new eo}var lM={initialDelayMs:500,maxDelayMs:15e3,factor:2,jitterRatio:.25,maxAttempts:8},Xd=4007,ol=1e3;function cM(n){if(typeof WebSocket>"u")throw new Error("WsTransport: no global WebSocket in this environment. Pass options.socketFactory.");return new WebSocket(n)}var to=class{url;socketFactory;now;random;backoff;shouldReconnect;socket=null;currentState="idle";retryTimer=null;attempt=0;disposed=!1;closingLocally=!1;lastClose=null;lastFrameAtMs=0;counters={framesSent:0,framesReceived:0,bytesSent:0,bytesReceived:0,framesDropped:0,textFramesReceived:0,unusableFramesReceived:0,reconnectAttempts:0,opens:0};onFrame=null;onStateChange=null;constructor(e){this.url=e.url,this.socketFactory=e.socketFactory??cM,this.now=e.now??Date.now,this.random=e.random??Math.random,this.backoff={...lM,...e.backoff},this.shouldReconnect=e.shouldReconnect??(()=>!0)}get state(){return this.currentState}get isOpen(){return this.currentState==="open"}get closeInfo(){return this.currentState==="closed"?this.lastClose:null}get lastCloseInfo(){return this.lastClose}get stats(){return{...this.counters}}get attemptCount(){return this.attempt}get msSinceLastFrame(){return this.lastFrameAtMs===0?null:Math.max(0,this.now()-this.lastFrameAtMs)}connect(){this.disposed||this.currentState==="connecting"||this.currentState==="open"||this.retryTimer===null&&(this.attempt=0,this.openSocket("connecting"))}send(e){let t=this.socket;if(this.disposed||this.currentState!=="open"||!t)return this.counters.framesDropped+=1,!1;try{t.send(e)}catch{return this.counters.framesDropped+=1,!1}return this.counters.framesSent+=1,this.counters.bytesSent+=e.byteLength,!0}close(e=ol,t=""){this.currentState==="closed"||this.disposed||(this.closingLocally=!0,this.cancelRetry(),this.closeSocket(e,t),this.finish({reason:"client",code:e,message:t,wasClean:!0}))}dispose(){this.disposed||(this.closingLocally=!0,this.cancelRetry(),this.closeSocket(ol,"disposed"),this.disposed=!0,this.currentState!=="closed"&&this.finish({reason:"client",code:ol,message:"disposed",wasClean:!0}),this.onFrame=null,this.onStateChange=null)}openSocket(e){this.closingLocally=!1,this.setState(e);let t;try{t=this.socketFactory(this.url)}catch(i){let r=i instanceof Error?i.message:String(i);this.finish({reason:"error",code:null,message:r,wasClean:!1});return}this.socket=t,t.binaryType="arraybuffer",t.onopen=()=>this.handleOpen(),t.onmessage=i=>this.handleMessage(i),t.onerror=()=>this.handleError(),t.onclose=i=>this.handleClose(i)}handleOpen(){this.disposed||(this.attempt=0,this.counters.opens+=1,this.setState("open"))}handleMessage(e){if(this.disposed)return;let t=e.data;if(typeof t=="string"){this.counters.textFramesReceived+=1,this.closingLocally=!0,this.cancelRetry(),this.closeSocket(Xd,"text frame"),this.finish({reason:"protocol-violation",code:Xd,message:"The server sent a text frame; this protocol is binary-only.",wasClean:!1});return}let i;if(t instanceof ArrayBuffer)i=new Uint8Array(t);else if(ArrayBuffer.isView(t))i=new Uint8Array(t.buffer,t.byteOffset,t.byteLength);else{this.counters.unusableFramesReceived+=1;return}this.counters.framesReceived+=1,this.counters.bytesReceived+=i.byteLength,this.lastFrameAtMs=this.now(),this.onFrame?.(i)}handleError(){}handleClose(e){if(this.detachSocket(),!(this.disposed||this.currentState==="closed")){if(this.closingLocally){this.closingLocally=!1;return}this.handleUnexpectedClose({reason:"server",code:typeof e.code=="number"?e.code:null,message:typeof e.reason=="string"?e.reason:"",wasClean:!!e.wasClean})}}handleUnexpectedClose(e){if(this.lastClose=e,!this.shouldReconnect(e)){this.finish(e);return}if(this.attempt>=this.backoff.maxAttempts){this.finish({...e,reason:"attempts-exhausted"});return}let t=this.nextDelay(this.attempt);this.attempt+=1,this.counters.reconnectAttempts+=1,this.setState("reconnecting"),this.retryTimer=setTimeout(()=>{this.retryTimer=null,!(this.disposed||this.currentState==="closed")&&this.openSocket("reconnecting")},t)}nextDelay(e){let t=Math.min(this.backoff.maxDelayMs,this.backoff.initialDelayMs*Math.pow(this.backoff.factor,e)),i=t*this.backoff.jitterRatio*(this.random()*2-1);return Math.max(0,Math.round(t+i))}cancelRetry(){this.retryTimer!==null&&(clearTimeout(this.retryTimer),this.retryTimer=null)}closeSocket(e,t){let i=this.socket;if(i){this.detachSocket();try{i.close(e,t)}catch{}}}detachSocket(){let e=this.socket;e&&(e.onopen=null,e.onmessage=null,e.onerror=null,e.onclose=null,this.socket=null)}finish(e){this.lastClose=e,this.cancelRetry(),this.setState("closed",e)}setState(e,t=null){this.currentState===e&&e!=="closed"||(this.currentState=e,this.onStateChange?.(e,t))}};var P={HelloCommand:1,WelcomeEvent:2,RejectedEvent:3,PingCommand:4,PongEvent:5,PeerJoinedEvent:6,PeerLeftEvent:7,RoomInfoEvent:8,SendChatCommand:9,ChatMessageEvent:10,LeaveCommand:11,SetRoomVarCommand:12,RoomVarsChangedEvent:13,ResyncCommand:14,SetClientPrefsCommand:15,HostChangedEvent:16,RoomRosterEvent:17,SpawnEntityRequest:64,SpawnEntityResponse:65,DespawnEntityCommand:66,EntityUpdatePacket:67,SnapshotPacket:68,DeltaPacket:69,SetEntityPropsCommand:70,EntityPropsChangedEvent:71,EmitSignalCommand:128,SignalEvent:129,SignalBatchPacket:130};var dF=new Map(Object.entries(P).map(([n,e])=>[e,n]));function FS(n,e){let t=new Uint8Array(e.length+1);return t[0]=n,t.set(e,1),t}function zS(n){return n.length===0?-1:n[0]}function US(n){return n.subarray(1)}var sl=class{counts=new Map;total=0;get count(){return this.total}record(e){return this.counts.set(e,(this.counts.get(e)??0)+1),this.total+=1,this.total}countFor(e){return this.counts.get(e)??0}seenTypeIds(){return[...this.counts.keys()]}reset(){this.counts.clear(),this.total=0}};var ro=20,io=3,gF=io+j.MaxPayloadSize,ep=5,yF=ep+j.MaxPayloadSize,tp=2,Nr=2,Qd=10,uM=7,hM=8,HS=7,dM=HS+Nr*3,al=6,Zd=5,pM=255,Jd=8,mM=7;var qS=6,GS=1,fM=64;var jS=qS+GS;function no(){return{qx:0,qy:0,qrot:0,qvx:0,qvy:0,kind:0,ownerId:0,flags:0}}function oo(n){n.qx=0,n.qy=0,n.qrot=0,n.qvx=0,n.qvy=0,n.kind=0,n.ownerId=0,n.flags=0}function $S(n,e,t){(e&j.X)!==0&&(n.qx=t.qx),(e&j.Y)!==0&&(n.qy=t.qy),(e&j.Rot)!==0&&(n.qrot=t.qrot),(e&j.Vx)!==0&&(n.qvx=t.qvx),(e&j.Vy)!==0&&(n.qvy=t.qvy),(e&j.Flags)!==0&&(n.flags=t.flags)}function YS(){return{netId:0,state:no()}}function KS(n,e,t){return t.netId=0,oo(t.state),e<0||n.byteLength-e<ro?!1:(t.netId=n.getUint32(e,!0),t.state.kind=n.getUint16(e+4,!0),t.state.ownerId=n.getUint32(e+6,!0),t.state.qx=n.getUint16(e+10,!0),t.state.qy=n.getUint16(e+12,!0),t.state.qrot=n.getUint8(e+14),t.state.qvx=n.getInt16(e+15,!0),t.state.qvy=n.getInt16(e+17,!0),t.state.flags=n.getUint8(e+19),!0)}function XS(){return{slot:0,mask:0,state:no(),bytesRead:0}}function gM(n){return io+$d(n)}function yM(n,e,t){if(t.slot=0,t.mask=0,t.bytesRead=0,oo(t.state),e<0||n.byteLength-e<io)return!1;let i=n.getUint8(e+2),r=gM(i);return n.byteLength-e<r?!1:(t.slot=n.getUint16(e,!0),t.mask=i,SM(n,e+io,i,t.state),t.bytesRead=r,!0)}function ip(n){return ep+$d(n)}function QS(n,e,t,i,r){let o=ip(i);return n.byteLength-e<o?0:(n.setUint32(e,t,!0),n.setUint8(e+4,i),bM(n,e+ep,i,r),o)}function bM(n,e,t,i){let r=e;(t&j.X)!==0&&(n.setUint16(r,i.qx,!0),r+=2),(t&j.Y)!==0&&(n.setUint16(r,i.qy,!0),r+=2),(t&j.Rot)!==0&&(n.setUint8(r,i.qrot),r+=1),(t&j.Vx)!==0&&(n.setInt16(r,i.qvx,!0),r+=2),(t&j.Vy)!==0&&(n.setInt16(r,i.qvy,!0),r+=2),(t&j.Flags)!==0&&n.setUint8(r,i.flags)}function SM(n,e,t,i){let r=e;(t&j.X)!==0&&(i.qx=n.getUint16(r,!0),r+=2),(t&j.Y)!==0&&(i.qy=n.getUint16(r,!0),r+=2),(t&j.Rot)!==0&&(i.qrot=n.getUint8(r),r+=1),(t&j.Vx)!==0&&(i.qvx=n.getInt16(r,!0),r+=2),(t&j.Vy)!==0&&(i.qvy=n.getInt16(r,!0),r+=2),(t&j.Flags)!==0&&(i.flags=n.getUint8(r))}function vM(n,e){return e<0||n.byteLength-e<tp?-1:n.getUint16(e,!0)}function JS(){return{seq:0,serverTick:0,frameFlags:0,count:0,recordsOffset:0,recordsLength:0}}function ZS(n,e){if(e.seq=0,e.serverTick=0,e.frameFlags=0,e.count=0,e.recordsOffset=0,e.recordsLength=0,n.byteLength<Qd||n.getUint8(0)!==P.SnapshotPacket)return!1;let t=n.getUint16(hM,!0),i=t*ro;return n.byteLength-Qd<i?!1:(e.seq=n.getUint16(1,!0),e.serverTick=n.getUint32(3,!0),e.frameFlags=n.getUint8(uM),e.count=t,e.recordsOffset=Qd,e.recordsLength=i,!0)}function ev(n,e,t,i){return t<0||t>=e.count?(i.netId=0,oo(i.state),!1):KS(n,e.recordsOffset+t*ro,i)}function tv(){return{seq:0,serverTick:0,removedCount:0,removedOffset:0,enterCount:0,enterOffset:0,updateCount:0,updatesOffset:0,updatesLength:0}}function iv(n,e){if(e.seq=0,e.serverTick=0,e.removedCount=0,e.removedOffset=0,e.enterCount=0,e.enterOffset=0,e.updateCount=0,e.updatesOffset=0,e.updatesLength=0,n.byteLength<dM||n.getUint8(0)!==P.DeltaPacket)return!1;let t=n.getUint16(1,!0),i=n.getUint32(3,!0),r=HS,o=n.getUint16(r,!0);r+=Nr;let s=o*tp;if(n.byteLength-r<s)return!1;let a=r;if(r+=s,n.byteLength-r<Nr)return!1;let l=n.getUint16(r,!0);r+=Nr;let c=l*ro;if(n.byteLength-r<c)return!1;let u=r;if(r+=c,n.byteLength-r<Nr)return!1;let h=n.getUint16(r,!0);r+=Nr;let d=n.byteLength-r;return d<h*io?!1:(e.seq=t,e.serverTick=i,e.removedCount=o,e.removedOffset=a,e.enterCount=l,e.enterOffset=u,e.updateCount=h,e.updatesOffset=r,e.updatesLength=d,!0)}function rv(n,e,t){return t<0||t>=e.removedCount?-1:vM(n,e.removedOffset+t*tp)}function nv(n,e,t,i){return t<0||t>=e.enterCount?(i.netId=0,oo(i.state),!1):KS(n,e.enterOffset+t*ro,i)}function ov(n,e,t,i){return t<0||t>=e.updatesLength?(i.slot=0,i.mask=0,i.bytesRead=0,oo(i.state),!1):yM(n,e.updatesOffset+t,i)}function sv(n,e,t){return n.byteLength-e<al?0:(n.setUint8(e,P.EntityUpdatePacket),n.setUint32(e+1,t,!0),n.setUint8(e+Zd,0),al)}function av(n,e){return e<0||e>pM||n.byteLength<=Zd?!1:(n.setUint8(Zd,e),!0)}function lv(){return{seq:0,serverTick:0,count:0,entriesOffset:0,entriesLength:0}}var Ir=new Uint8Array(0);function cv(){return{senderClientId:0,name:Ir,payload:Ir,bytesRead:0}}function wM(n,e,t){if(t.senderClientId=0,t.name=Ir,t.payload=Ir,t.bytesRead=0,e<0||n.byteLength-e<jS)return!1;let i=n.getUint8(e+4);if(i<GS||i>fM)return!1;let r=e+5+i;if(n.byteLength<=r)return!1;let o=n.getUint8(r),s=qS+i+o;return n.byteLength-e<s?!1:(t.senderClientId=n.getUint32(e,!0),t.name=WS(n,e+5,i),t.payload=WS(n,r+1,o),t.bytesRead=s,!0)}function uv(n,e){if(e.seq=0,e.serverTick=0,e.count=0,e.entriesOffset=0,e.entriesLength=0,n.byteLength<Jd||n.getUint8(0)!==P.SignalBatchPacket)return!1;let t=n.getUint8(mM),i=n.byteLength-Jd;return i<t*jS?!1:(e.seq=n.getUint16(1,!0),e.serverTick=n.getUint32(3,!0),e.count=t,e.entriesOffset=Jd,e.entriesLength=i,!0)}function hv(n,e,t,i){return t<0||t>=e.entriesLength?(i.senderClientId=0,i.name=Ir,i.payload=Ir,i.bytesRead=0,!1):wM(n,e.entriesOffset+t,i)}function WS(n,e,t){return new Uint8Array(n.buffer,n.byteOffset+e,t)}var K=class n{static MAX_MEMBER_COUNT=249;static NULL_OBJECT_MARKER=255;bytes;view;memberOffsets=[];cursor=0;static utf8=new TextDecoder("utf-8",{fatal:!1});static utf16=new TextDecoder("utf-16le",{fatal:!1});memberCount;constructor(e){if(this.bytes=e,this.view=new DataView(e.buffer,e.byteOffset,e.byteLength),e.length===0)throw new RangeError("A version-tolerant object needs at least its member-count byte.");let t=e[0];if(t===n.NULL_OBJECT_MARKER)throw new RangeError("Unexpected null object (memberCount 0xFF) on the control plane.");if(t>n.MAX_MEMBER_COUNT)throw new RangeError(`Illegal member count ${t}; the maximum is ${n.MAX_MEMBER_COUNT}.`);this.memberCount=t;let i=1,r=[];for(let o=0;o<t;o++){let[s,a]=xM(this.bytes,this.view,i);r.push(s),i=a}for(let o of r){if(o<0)throw new RangeError(`Negative member byte-length ${o}.`);this.memberOffsets.push(i),i+=o}if(this.memberOffsets.push(i),i>e.length)throw new RangeError(`Truncated object: members declare ${i} bytes but the payload is ${e.length}.`)}hasMember(e){return e>=0&&e<this.memberCount}memberLength(e){return this.requireMember(e),this.memberOffsets[e+1]-this.memberOffsets[e]}seekMember(e){this.requireMember(e),this.cursor=this.memberOffsets[e]}requireMember(e){if(!this.hasMember(e))throw new RangeError(`Member ${e} was not written; the object declares ${this.memberCount}.`)}require(e){let t=this.cursor;if(t+e>this.bytes.length)throw new RangeError(`Truncated value: ${e} bytes needed at offset ${t}.`);return this.cursor=t+e,t}readBool(){return this.bytes[this.require(1)]!==0}readUint8(){return this.bytes[this.require(1)]}readInt8(){return this.view.getInt8(this.require(1))}readUint16(){return this.view.getUint16(this.require(2),!0)}readInt16(){return this.view.getInt16(this.require(2),!0)}readUint32(){return this.view.getUint32(this.require(4),!0)}readInt32(){return this.view.getInt32(this.require(4),!0)}readFloat32(){return this.view.getFloat32(this.require(4),!0)}readInt64(){return this.view.getBigInt64(this.require(8),!0)}readInt64AsNumber(){let e=this.readInt64();if(e>BigInt(Number.MAX_SAFE_INTEGER)||e<BigInt(Number.MIN_SAFE_INTEGER))throw new RangeError(`i64 value ${e} does not fit a JavaScript number exactly.`);return Number(e)}readString(){let e=this.readInt32();if(e===-1)return null;if(e===0)return"";if(e<0){let i=~e;this.readInt32();let r=this.require(i);return n.utf8.decode(this.bytes.subarray(r,r+i))}let t=this.require(e*2);return n.utf16.decode(this.bytes.subarray(t,t+e*2))}readBytes(){let e=this.readInt32();if(e===-1)return null;if(e<0)throw new RangeError(`Illegal array element count ${e}.`);let t=this.require(e);return this.bytes.slice(t,t+e)}readUint32Array(){let e=this.readInt32();if(e===-1)return null;if(e<0)throw new RangeError(`Illegal array element count ${e}.`);let t=[];for(let i=0;i<e;i++)t.push(this.readUint32());return t}readStringArray(){let e=this.readInt32();if(e===-1)return null;if(e<0)throw new RangeError(`Illegal array element count ${e}.`);let t=[];for(let i=0;i<e;i++)t.push(this.readString());return t}readBytesArray(){let e=this.readInt32();if(e===-1)return null;if(e<0)throw new RangeError(`Illegal array element count ${e}.`);let t=[];for(let i=0;i<e;i++)t.push(this.readBytes());return t}};function xM(n,e,t){if(t>=n.length)throw new RangeError(`Truncated member length at offset ${t}.`);let i=n[t];if(i<=127)return[i,t+1];if(i===132){if(t+3>n.length)throw new RangeError(`Truncated u16 member length at offset ${t}.`);return[e.getUint16(t+1,!0),t+3]}if(i===130){if(t+5>n.length)throw new RangeError(`Truncated i32 member length at offset ${t}.`);return[e.getInt32(t+1,!0),t+5]}throw new RangeError(`Unsupported member-length marker 0x${i.toString(16).toUpperCase().padStart(2,"0")} at offset ${t}.`)}var X=class n{static MAX_MEMBER_COUNT=249;bytes;view;length=0;boundaries=[];static utf8=new TextEncoder;constructor(e=128){this.bytes=new Uint8Array(e),this.view=new DataView(this.bytes.buffer)}endMember(){this.boundaries.push(this.length)}finish(){let e=this.boundaries.length;if(e>n.MAX_MEMBER_COUNT)throw new RangeError(`A version-tolerant object may declare at most ${n.MAX_MEMBER_COUNT} members, got ${e}.`);if((e===0?0:this.boundaries[e-1])!==this.length)throw new Error("The last member was never closed \u2014 call endMember() after every member.");let i=1,r=0;for(let l of this.boundaries)i+=PM(l-r),r=l;let o=new Uint8Array(i+this.length),s=new DataView(o.buffer);o[0]=e;let a=1;r=0;for(let l of this.boundaries)a=kM(o,s,a,l-r),r=l;return o.set(this.bytes.subarray(0,this.length),a),o}writeBool(e){this.reserve(1),this.bytes[this.length]=e?1:0,this.length+=1}writeUint8(e){this.reserve(1),this.bytes[this.length]=e&255,this.length+=1}writeInt8(e){this.reserve(1),this.view.setInt8(this.length,e),this.length+=1}writeUint16(e){this.reserve(2),this.view.setUint16(this.length,e,!0),this.length+=2}writeInt16(e){this.reserve(2),this.view.setInt16(this.length,e,!0),this.length+=2}writeUint32(e){this.reserve(4),this.view.setUint32(this.length,e,!0),this.length+=4}writeInt32(e){this.reserve(4),this.view.setInt32(this.length,e,!0),this.length+=4}writeFloat32(e){this.reserve(4),this.view.setFloat32(this.length,e,!0),this.length+=4}writeInt64(e){this.reserve(8),this.view.setBigInt64(this.length,typeof e=="bigint"?e:BigInt(Math.trunc(e)),!0),this.length+=8}writeString(e){if(e===null){this.writeInt32(-1);return}if(e.length===0){this.writeInt32(0);return}let t=n.utf8.encode(e);this.writeInt32(~t.length),this.writeInt32(e.length),this.writeRaw(t)}writeBytes(e){if(e===null){this.writeInt32(-1);return}this.writeInt32(e.length),this.writeRaw(e)}writeUint32Array(e){if(e===null){this.writeInt32(-1);return}this.writeInt32(e.length);for(let t of e)this.writeUint32(t)}writeStringArray(e){if(e===null){this.writeInt32(-1);return}this.writeInt32(e.length);for(let t of e)this.writeString(t)}writeBytesArray(e){if(e===null){this.writeInt32(-1);return}this.writeInt32(e.length);for(let t of e)this.writeBytes(t)}writeRaw(e){this.reserve(e.length),this.bytes.set(e,this.length),this.length+=e.length}reserve(e){let t=this.length+e;if(t<=this.bytes.length)return;let i=this.bytes.length===0?32:this.bytes.length;for(;i<t;)i*=2;let r=new Uint8Array(i);r.set(this.bytes.subarray(0,this.length)),this.bytes=r,this.view=new DataView(r.buffer)}};function PM(n){return n>=0&&n<=127?1:n>=0&&n<=65535?3:5}function kM(n,e,t,i){return i>=0&&i<=127?(n[t]=i,t+1):i>=0&&i<=65535?(n[t]=132,e.setUint16(t+1,i,!0),t+3):(n[t]=130,e.setInt32(t+1,i,!0),t+5)}var Ce=new Uint8Array(0);function AM(){return{protocolVersion:0,token:"",roomId:"",displayName:"",capabilities:0,resumeKey:null}}function TM(n){let e=new X;return e.writeUint16(n.protocolVersion),e.endMember(),e.writeString(n.token),e.endMember(),e.writeString(n.roomId),e.endMember(),e.writeString(n.displayName),e.endMember(),e.writeUint16(n.capabilities),e.endMember(),e.writeBytes(n.resumeKey),e.endMember(),e.finish()}function CM(n){let e=new K(n),t=AM();return e.hasMember(0)&&(e.seekMember(0),t.protocolVersion=e.readUint16()),e.hasMember(1)&&(e.seekMember(1),t.token=e.readString()??""),e.hasMember(2)&&(e.seekMember(2),t.roomId=e.readString()??""),e.hasMember(3)&&(e.seekMember(3),t.displayName=e.readString()??""),e.hasMember(4)&&(e.seekMember(4),t.capabilities=e.readUint16()),e.hasMember(5)&&(e.seekMember(5),t.resumeKey=e.readBytes()),t}function MM(){return{clientId:0,roomId:"",tickHz:0,serverTimeMs:0,serverTick:0,aoiRadius:0,maxPlayers:0,protocolVersion:0,worldOriginX:0,worldOriginY:0,worldSize:0,mode:0,maxVisibleEntities:0,hostClientId:0,resumeKey:Ce,resumed:!1}}function DM(n){let e=new X;return e.writeUint32(n.clientId),e.endMember(),e.writeString(n.roomId),e.endMember(),e.writeUint8(n.tickHz),e.endMember(),e.writeInt64(n.serverTimeMs),e.endMember(),e.writeUint32(n.serverTick),e.endMember(),e.writeFloat32(n.aoiRadius),e.endMember(),e.writeUint16(n.maxPlayers),e.endMember(),e.writeUint16(n.protocolVersion),e.endMember(),e.writeFloat32(n.worldOriginX),e.endMember(),e.writeFloat32(n.worldOriginY),e.endMember(),e.writeFloat32(n.worldSize),e.endMember(),e.writeUint8(n.mode),e.endMember(),e.writeUint16(n.maxVisibleEntities),e.endMember(),e.writeUint32(n.hostClientId),e.endMember(),e.writeBytes(n.resumeKey),e.endMember(),e.writeBool(n.resumed),e.endMember(),e.finish()}function EM(n){let e=new K(n),t=MM();return e.hasMember(0)&&(e.seekMember(0),t.clientId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.roomId=e.readString()??""),e.hasMember(2)&&(e.seekMember(2),t.tickHz=e.readUint8()),e.hasMember(3)&&(e.seekMember(3),t.serverTimeMs=e.readInt64AsNumber()),e.hasMember(4)&&(e.seekMember(4),t.serverTick=e.readUint32()),e.hasMember(5)&&(e.seekMember(5),t.aoiRadius=e.readFloat32()),e.hasMember(6)&&(e.seekMember(6),t.maxPlayers=e.readUint16()),e.hasMember(7)&&(e.seekMember(7),t.protocolVersion=e.readUint16()),e.hasMember(8)&&(e.seekMember(8),t.worldOriginX=e.readFloat32()),e.hasMember(9)&&(e.seekMember(9),t.worldOriginY=e.readFloat32()),e.hasMember(10)&&(e.seekMember(10),t.worldSize=e.readFloat32()),e.hasMember(11)&&(e.seekMember(11),t.mode=e.readUint8()),e.hasMember(12)&&(e.seekMember(12),t.maxVisibleEntities=e.readUint16()),e.hasMember(13)&&(e.seekMember(13),t.hostClientId=e.readUint32()),e.hasMember(14)&&(e.seekMember(14),t.resumeKey=e.readBytes()??Ce),e.hasMember(15)&&(e.seekMember(15),t.resumed=e.readBool()),t}function NM(){return{code:0,message:""}}function IM(n){let e=new X;return e.writeUint16(n.code),e.endMember(),e.writeString(n.message),e.endMember(),e.finish()}function RM(n){let e=new K(n),t=NM();return e.hasMember(0)&&(e.seekMember(0),t.code=e.readUint16()),e.hasMember(1)&&(e.seekMember(1),t.message=e.readString()??""),t}function BM(){return{clientTimeMs:0}}function OM(n){let e=new X;return e.writeInt64(n.clientTimeMs),e.endMember(),e.finish()}function VM(n){let e=new K(n),t=BM();return e.hasMember(0)&&(e.seekMember(0),t.clientTimeMs=e.readInt64AsNumber()),t}function LM(){return{clientTimeMs:0,serverTimeMs:0,serverTick:0}}function _M(n){let e=new X;return e.writeInt64(n.clientTimeMs),e.endMember(),e.writeInt64(n.serverTimeMs),e.endMember(),e.writeUint32(n.serverTick),e.endMember(),e.finish()}function FM(n){let e=new K(n),t=LM();return e.hasMember(0)&&(e.seekMember(0),t.clientTimeMs=e.readInt64AsNumber()),e.hasMember(1)&&(e.seekMember(1),t.serverTimeMs=e.readInt64AsNumber()),e.hasMember(2)&&(e.seekMember(2),t.serverTick=e.readUint32()),t}function zM(){return{clientId:0,displayName:""}}function UM(n){let e=new X;return e.writeUint32(n.clientId),e.endMember(),e.writeString(n.displayName),e.endMember(),e.finish()}function WM(n){let e=new K(n),t=zM();return e.hasMember(0)&&(e.seekMember(0),t.clientId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.displayName=e.readString()??""),t}function HM(){return{clientId:0,reason:0}}function qM(n){let e=new X;return e.writeUint32(n.clientId),e.endMember(),e.writeUint8(n.reason),e.endMember(),e.finish()}function GM(n){let e=new K(n),t=HM();return e.hasMember(0)&&(e.seekMember(0),t.clientId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.reason=e.readUint8()),t}function jM(){return{playerCount:0,entityCount:0,serverTick:0}}function $M(n){let e=new X;return e.writeUint16(n.playerCount),e.endMember(),e.writeUint16(n.entityCount),e.endMember(),e.writeUint32(n.serverTick),e.endMember(),e.finish()}function YM(n){let e=new K(n),t=jM();return e.hasMember(0)&&(e.seekMember(0),t.playerCount=e.readUint16()),e.hasMember(1)&&(e.seekMember(1),t.entityCount=e.readUint16()),e.hasMember(2)&&(e.seekMember(2),t.serverTick=e.readUint32()),t}function KM(){return{text:""}}function XM(n){let e=new X;return e.writeString(n.text),e.endMember(),e.finish()}function QM(n){let e=new K(n),t=KM();return e.hasMember(0)&&(e.seekMember(0),t.text=e.readString()??""),t}function JM(){return{clientId:0,text:""}}function ZM(n){let e=new X;return e.writeUint32(n.clientId),e.endMember(),e.writeString(n.text),e.endMember(),e.finish()}function eD(n){let e=new K(n),t=JM();return e.hasMember(0)&&(e.seekMember(0),t.clientId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.text=e.readString()??""),t}function dv(){return new X(1).finish()}function pv(n){return new K(n),{}}function tD(){return{key:"",value:Ce}}function iD(n){let e=new X;return e.writeString(n.key),e.endMember(),e.writeBytes(n.value),e.endMember(),e.finish()}function rD(n){let e=new K(n),t=tD();return e.hasMember(0)&&(e.seekMember(0),t.key=e.readString()??""),e.hasMember(1)&&(e.seekMember(1),t.value=e.readBytes()??Ce),t}function nD(){return{keys:[],values:[]}}function oD(n){let e=new X;return e.writeStringArray(n.keys),e.endMember(),e.writeBytesArray(n.values),e.endMember(),e.finish()}function sD(n){let e=new K(n),t=nD();return e.hasMember(0)&&(e.seekMember(0),t.keys=(e.readStringArray()??[]).map(i=>i??"")),e.hasMember(1)&&(e.seekMember(1),t.values=(e.readBytesArray()??[]).map(i=>i??Ce)),t}function aD(){return{hidden:!1,sendRateDivisor:0}}function lD(n){let e=new X;return e.writeBool(n.hidden),e.endMember(),e.writeUint8(n.sendRateDivisor),e.endMember(),e.finish()}function cD(n){let e=new K(n),t=aD();return e.hasMember(0)&&(e.seekMember(0),t.hidden=e.readBool()),e.hasMember(1)&&(e.seekMember(1),t.sendRateDivisor=e.readUint8()),t}function uD(){return{hostClientId:0,previousHostClientId:0}}function hD(n){let e=new X;return e.writeUint32(n.hostClientId),e.endMember(),e.writeUint32(n.previousHostClientId),e.endMember(),e.finish()}function dD(n){let e=new K(n),t=uD();return e.hasMember(0)&&(e.seekMember(0),t.hostClientId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.previousHostClientId=e.readUint32()),t}function pD(){return{clientIds:[],displayNames:[],frameFlags:0}}function mD(n){let e=new X;return e.writeUint32Array(n.clientIds),e.endMember(),e.writeStringArray(n.displayNames),e.endMember(),e.writeUint8(n.frameFlags),e.endMember(),e.finish()}function fD(n){let e=new K(n),t=pD();return e.hasMember(0)&&(e.seekMember(0),t.clientIds=e.readUint32Array()??[]),e.hasMember(1)&&(e.seekMember(1),t.displayNames=(e.readStringArray()??[]).map(i=>i??"")),e.hasMember(2)&&(e.seekMember(2),t.frameFlags=e.readUint8()),t}function gD(){return{requestId:0,kind:0,qx:0,qy:0,qrot:0,qvx:0,qvy:0,flags:0,props:null}}function yD(n){let e=new X;return e.writeUint32(n.requestId),e.endMember(),e.writeUint16(n.kind),e.endMember(),e.writeUint16(n.qx),e.endMember(),e.writeUint16(n.qy),e.endMember(),e.writeUint8(n.qrot),e.endMember(),e.writeInt16(n.qvx),e.endMember(),e.writeInt16(n.qvy),e.endMember(),e.writeUint8(n.flags),e.endMember(),e.writeBytes(n.props),e.endMember(),e.finish()}function bD(n){let e=new K(n),t=gD();return e.hasMember(0)&&(e.seekMember(0),t.requestId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.kind=e.readUint16()),e.hasMember(2)&&(e.seekMember(2),t.qx=e.readUint16()),e.hasMember(3)&&(e.seekMember(3),t.qy=e.readUint16()),e.hasMember(4)&&(e.seekMember(4),t.qrot=e.readUint8()),e.hasMember(5)&&(e.seekMember(5),t.qvx=e.readInt16()),e.hasMember(6)&&(e.seekMember(6),t.qvy=e.readInt16()),e.hasMember(7)&&(e.seekMember(7),t.flags=e.readUint8()),e.hasMember(8)&&(e.seekMember(8),t.props=e.readBytes()),t}function SD(){return{requestId:0,netId:0,rejectCode:0}}function vD(n){let e=new X;return e.writeUint32(n.requestId),e.endMember(),e.writeUint32(n.netId),e.endMember(),e.writeUint16(n.rejectCode),e.endMember(),e.finish()}function wD(n){let e=new K(n),t=SD();return e.hasMember(0)&&(e.seekMember(0),t.requestId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.netId=e.readUint32()),e.hasMember(2)&&(e.seekMember(2),t.rejectCode=e.readUint16()),t}function xD(){return{netId:0}}function PD(n){let e=new X;return e.writeUint32(n.netId),e.endMember(),e.finish()}function kD(n){let e=new K(n),t=xD();return e.hasMember(0)&&(e.seekMember(0),t.netId=e.readUint32()),t}function AD(){return{netId:0,json:Ce}}function TD(n){let e=new X;return e.writeUint32(n.netId),e.endMember(),e.writeBytes(n.json),e.endMember(),e.finish()}function CD(n){let e=new K(n),t=AD();return e.hasMember(0)&&(e.seekMember(0),t.netId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.json=e.readBytes()??Ce),t}function MD(){return{netId:0,json:Ce}}function DD(n){let e=new X;return e.writeUint32(n.netId),e.endMember(),e.writeBytes(n.json),e.endMember(),e.finish()}function ED(n){let e=new K(n),t=MD();return e.hasMember(0)&&(e.seekMember(0),t.netId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.json=e.readBytes()??Ce),t}function ND(){return{name:"",target:0,targetClientId:0,payload:Ce}}function ID(n){let e=new X;return e.writeString(n.name),e.endMember(),e.writeUint8(n.target),e.endMember(),e.writeUint32(n.targetClientId),e.endMember(),e.writeBytes(n.payload),e.endMember(),e.finish()}function RD(n){let e=new K(n),t=ND();return e.hasMember(0)&&(e.seekMember(0),t.name=e.readString()??""),e.hasMember(1)&&(e.seekMember(1),t.target=e.readUint8()),e.hasMember(2)&&(e.seekMember(2),t.targetClientId=e.readUint32()),e.hasMember(3)&&(e.seekMember(3),t.payload=e.readBytes()??Ce),t}function BD(){return{senderClientId:0,name:"",payload:Ce}}function OD(n){let e=new X;return e.writeUint32(n.senderClientId),e.endMember(),e.writeString(n.name),e.endMember(),e.writeBytes(n.payload),e.endMember(),e.finish()}function VD(n){let e=new K(n),t=BD();return e.hasMember(0)&&(e.seekMember(0),t.senderClientId=e.readUint32()),e.hasMember(1)&&(e.seekMember(1),t.name=e.readString()??""),e.hasMember(2)&&(e.seekMember(2),t.payload=e.readBytes()??Ce),t}var kF=new Set([P.HelloCommand,P.WelcomeEvent,P.RejectedEvent,P.PingCommand,P.PongEvent,P.PeerJoinedEvent,P.PeerLeftEvent,P.RoomInfoEvent,P.SendChatCommand,P.ChatMessageEvent,P.LeaveCommand,P.SetRoomVarCommand,P.RoomVarsChangedEvent,P.ResyncCommand,P.SetClientPrefsCommand,P.HostChangedEvent,P.RoomRosterEvent,P.SpawnEntityRequest,P.SpawnEntityResponse,P.DespawnEntityCommand,P.SetEntityPropsCommand,P.EntityPropsChangedEvent,P.EmitSignalCommand,P.SignalEvent]);function mv(n,e){switch(n){case P.HelloCommand:return{typeId:n,body:CM(e)};case P.WelcomeEvent:return{typeId:n,body:EM(e)};case P.RejectedEvent:return{typeId:n,body:RM(e)};case P.PingCommand:return{typeId:n,body:VM(e)};case P.PongEvent:return{typeId:n,body:FM(e)};case P.PeerJoinedEvent:return{typeId:n,body:WM(e)};case P.PeerLeftEvent:return{typeId:n,body:GM(e)};case P.RoomInfoEvent:return{typeId:n,body:YM(e)};case P.SendChatCommand:return{typeId:n,body:QM(e)};case P.ChatMessageEvent:return{typeId:n,body:eD(e)};case P.LeaveCommand:return{typeId:n,body:pv(e)};case P.SetRoomVarCommand:return{typeId:n,body:rD(e)};case P.RoomVarsChangedEvent:return{typeId:n,body:sD(e)};case P.ResyncCommand:return{typeId:n,body:pv(e)};case P.SetClientPrefsCommand:return{typeId:n,body:cD(e)};case P.HostChangedEvent:return{typeId:n,body:dD(e)};case P.RoomRosterEvent:return{typeId:n,body:fD(e)};case P.SpawnEntityRequest:return{typeId:n,body:bD(e)};case P.SpawnEntityResponse:return{typeId:n,body:wD(e)};case P.DespawnEntityCommand:return{typeId:n,body:kD(e)};case P.SetEntityPropsCommand:return{typeId:n,body:CD(e)};case P.EntityPropsChangedEvent:return{typeId:n,body:ED(e)};case P.EmitSignalCommand:return{typeId:n,body:RD(e)};case P.SignalEvent:return{typeId:n,body:VD(e)};default:return}}function fv(n){return FS(n.typeId,LD(n))}function LD(n){switch(n.typeId){case P.HelloCommand:return TM(n.body);case P.WelcomeEvent:return DM(n.body);case P.RejectedEvent:return IM(n.body);case P.PingCommand:return OM(n.body);case P.PongEvent:return _M(n.body);case P.PeerJoinedEvent:return UM(n.body);case P.PeerLeftEvent:return qM(n.body);case P.RoomInfoEvent:return $M(n.body);case P.SendChatCommand:return XM(n.body);case P.ChatMessageEvent:return ZM(n.body);case P.LeaveCommand:return dv();case P.SetRoomVarCommand:return iD(n.body);case P.RoomVarsChangedEvent:return oD(n.body);case P.ResyncCommand:return dv();case P.SetClientPrefsCommand:return lD(n.body);case P.HostChangedEvent:return hD(n.body);case P.RoomRosterEvent:return mD(n.body);case P.SpawnEntityRequest:return yD(n.body);case P.SpawnEntityResponse:return vD(n.body);case P.DespawnEntityCommand:return PD(n.body);case P.SetEntityPropsCommand:return TD(n.body);case P.EntityPropsChangedEvent:return DD(n.body);case P.EmitSignalCommand:return ID(n.body);case P.SignalEvent:return OD(n.body)}}function rp(n){return n&65535}var ll=Math.PI*2;function gv(){return{qx:0,qy:0}}function yv(n,e,t){return Number.isFinite(n)&&Number.isFinite(e)&&Number.isFinite(t)&&t>=1&&bv(n,e,t)}function bv(n,e,t){let i=Math.fround(128*t);return Math.abs(n)<i&&Math.abs(e)<i&&Math.abs(Math.fround(n+t))<i&&Math.abs(Math.fround(e+t))<i}function np(n){return Math.floor(n+.5)}var cl=class{originX;originY;size;constructor(e,t,i){if(!Number.isFinite(e))throw new RangeError(`World origin X must be finite, got ${e}.`);if(!Number.isFinite(t))throw new RangeError(`World origin Y must be finite, got ${t}.`);if(!Number.isFinite(i)||i<1)throw new RangeError(`World size must be finite and at least 1, got ${i}.`);if(!bv(e,t,i))throw new RangeError("World bounds are too far from the origin for their size: every coordinate magnitude must stay below 128 \xD7 size, or float32 round-tripping stops being a fixed point and positions oscillate by a quantum forever.");this.originX=e,this.originY=t,this.size=i}get maxX(){return this.originX+this.size}get maxY(){return this.originY+this.size}tryQuantizePosition(e,t,i){return!Number.isFinite(e)||!Number.isFinite(t)?(i.qx=0,i.qy=0,!1):(i.qx=this.quantizeAxis(e,this.originX),i.qy=this.quantizeAxis(t,this.originY),!0)}dequantizeX(e){return Math.fround(this.originX+e*this.size/65535)}dequantizeY(e){return Math.fround(this.originY+e*this.size/65535)}quantizeAxis(e,t){let i=np((e-t)*65535/this.size);return i<=0?0:i>=65535?65535:i}};function ul(n){if(!Number.isFinite(n))return null;let e=n%ll;return e<0&&(e+=ll),np(e/ll*256)&255}function Sv(n){return Math.fround(n*ll/256)}function so(n){if(!Number.isFinite(n))return null;let e=np(n*8);return e<=-32768?-32768:e>=32767?32767:e}var sp={owned:0,shared:1,transferable:2},ap=3,Av=3;function lp(n){switch(n&ap){case sp.shared:return"shared";case sp.transferable:return"transferable";default:return"owned"}}function Tv(n,e=0){return sp[n]&ap|(e&31)<<Av}function cp(n){return(n&j.Teleport)!==0}var me=class extends Error{kind;prefabPath;rejectCode;constructor(e,t,i,r=0){super(i),this.name="NetworkSpawnError",this.kind=e,this.prefabPath=t,this.rejectCode=r}},st=class extends Error{kind;rejectCode;closeCode;constructor(e,t,i=0,r=null){super(t),this.name="NetworkConnectError",this.kind=e,this.rejectCode=i,this.closeCode=r}},vv=8,FD=2,zD=1e3,wv=240,UD=6e4,xv=64,WD=4294967296,HD=65536,qD=new Set([4001,4002,4003,4007,4008]),GD=new Set([q.ProtocolVersionMismatch,q.InvalidToken,q.TokenExpired,q.TokenRoomMismatch,q.RoomNotFound,q.RoomFull,q.RoomClosing,q.BadRequest,q.SessionReplaced]),jD=new Map([[q.None,"No error."],[q.ProtocolVersionMismatch,"This build speaks an unsupported protocol version \u2014 update the game."],[q.InvalidToken,"The room token is missing, malformed or not signed by pix3-cloud."],[q.TokenExpired,"The room token has expired \u2014 request a new one and rejoin."],[q.TokenRoomMismatch,"The room token was minted for a different room."],[q.RoomNotFound,"No such room on this server."],[q.RoomFull,"The room is full."],[q.RoomClosing,"The room is shutting down and is not accepting members."],[q.RateLimited,"Rate limit tripped \u2014 this client sent too much, too fast."],[q.PayloadTooLarge,"A frame exceeded the 4 KiB control-frame limit."],[q.QuotaExceeded,"A room or connection quota was exceeded."],[q.ServerShuttingDown,"The server is draining and closed the session."],[q.IdleTimeout,"The connection was idle for too long."],[q.BadRequest,"The server refused a malformed or out-of-order frame."],[q.SessionReplaced,"This session was displaced by a newer connection for the same identity."],[q.EntityLimitReached,"The room is holding as many entities as it can."],[q.NotEntityOwner,"That entity belongs to someone else."],[q.InternalError,"The server hit an internal error."],[q.KindNotAllowed,"That entity kind is not on the room allowlist."],[q.SendQueueOverflow,"The send queue overflowed \u2014 this client could not keep up."]]);function hl(n){return jD.get(n)??`The server refused the session (code ${n}).`}var up=new TextEncoder,hp=new TextDecoder,dl=class{constructor(e){this.send=e}send;values=new Map;get(e){return this.values.get(e)}getText(e){let t=this.values.get(e);return t===void 0?void 0:hp.decode(t)}getJson(e){let t=this.getText(e);if(t!==void 0)try{return JSON.parse(t)}catch{return}}has(e){return this.values.has(e)}keys(){return[...this.values.keys()]}get size(){return this.values.size}set(e,t){let i=typeof t=="string"?up.encode(t):t;return this.send(e,i)}replaceAll(e,t){let i=new Set(this.values.keys());this.values.clear();for(let r=0;r<e.length;r+=1)this.values.set(e[r],t[r]??new Uint8Array(0)),i.add(e[r]);return[...i]}merge(e,t){for(let i=0;i<e.length;i+=1)this.values.set(e[i],t[i]??new Uint8Array(0));return[...e]}clear(){this.values.clear()}},ao=class{sendIntervalMs;pingIntervalMs;now;socketFactory;backoffOptions;random;visibility;transport=null;credentials=null;disposed=!1;currentStatus="offline";session=null;worldQuantizer=null;resumeKey=null;hasWelcomed=!1;lastRejectCode=null;rttMs=0;clockOffsetMs=0;lastPingSentAtMs=0;lastPingClientTimeMs=0;pumpTimer=null;clientTick=0;peerMap=new Map;entityMap=new Map;slotToNetId=new Map;publishStates=new Map;pendingSpawns=new Map;nextRequestId=1;spawnTimestamps=[];ownedNetIds=new Set;kindTableOverride;roomVars;receivedRoomVarsForSession=!1;pendingSnapshot=new Map;snapshotInProgress=!1;snapshotComplete=!1;pendingRoster=[];rosterInProgress=!1;lastSeq=null;desynced=!1;resyncTimestamps=[];unknownTypeIds=new sl;counters={framesReceived:0,unknownTypeIds:0,malformedFrames:0,seqGaps:0,resyncsSent:0,resyncsSuppressed:0,entityPacketsSent:0,entityRecordsSent:0,unknownSlotUpdates:0,nonFiniteRejected:0,signalHandlerErrors:0,spawnsSent:0,spawnsRejected:0,spawnsThrottled:0,despawnsSent:0};signalHandlers=new Map;statusListeners=new Set;peerListeners=new Set;entityListeners=new Set;roomVarListeners=new Set;errorListeners=new Set;pendingConnect=null;connectPromise=null;hidden=!1;onVisibilityChange=()=>this.handleVisibilityChange();snapshotView=JS();deltaSections=tv();fullRecord=YS();updateRecord=XS();signalSections=lv();signalEntry=cv();quantizedPosition=gv();scratchChanges=[];constructor(e={}){let t=e.sendRateHz&&e.sendRateHz>0?e.sendRateHz:20;this.sendIntervalMs=Math.max(1,Math.round(1e3/t)),this.pingIntervalMs=e.pingIntervalMs??2e3,this.now=e.now??Date.now,this.socketFactory=e.socketFactory,this.backoffOptions=e.backoff,this.random=e.random,this.visibility=e.visibility===void 0?XD():e.visibility,this.kindTableOverride=e.kindTable??null,this.roomVars=new dl((i,r)=>this.sendSetRoomVar(i,r))}get status(){return this.currentStatus}get isOnline(){return this.currentStatus==="online"}get clientId(){return this.session?.clientId??0}get roomId(){return this.session?.roomId??""}get tickHz(){return this.session?.tickHz??0}get mode(){return this.session?.mode??LS.Relay}get hostClientId(){return this.session?.hostClientId??0}get isHost(){let e=this.session?.hostClientId??0;return e!==0&&e===this.clientId}get maxVisibleEntities(){return this.session?.maxVisibleEntities??0}get maxPlayers(){return this.session?.maxPlayers??0}get aoiRadius(){return this.session?.aoiRadius??0}get sessionInfo(){return this.session}get quantizer(){return this.worldQuantizer}get rtt(){return this.rttMs}get clockOffset(){return this.clockOffsetMs}get serverTimeMs(){return this.now()+this.clockOffsetMs}get peers(){return[...this.peerMap.values()]}get entities(){return this.entityMap}get entityCount(){return this.entityMap.size}get hasCompleteSnapshot(){return this.snapshotComplete&&!this.desynced}get isDesynced(){return this.desynced}get vars(){return this.roomVars}get stats(){return{...this.counters}}get transportStats(){return this.transport?this.transport.stats:null}getEntity(e){return this.entityMap.get(e)}resolveSlot(e){return this.slotToNetId.get(e)??0}connect(e){if(this.disposed)return Promise.reject(new st("cancelled","This NetworkService has been disposed."));if(!e.url||!e.roomId)return Promise.reject(new st("invalid","connect() needs both a url and a roomId."));if(this.connectPromise)return this.connectPromise;if(this.session)return Promise.resolve(this.session);if(this.transport)return Promise.reject(new st("invalid","This session is still reconnecting; call disconnect() before joining another room."));this.credentials={url:e.url,token:e.token??"",roomId:e.roomId,displayName:e.displayName??"",capabilities:e.capabilities??0},this.lastRejectCode=null,this.hasWelcomed=!1,this.resumeKey=null;let t=new Promise((i,r)=>{this.pendingConnect={resolve:i,reject:r}});return this.connectPromise=t,this.transport=new to({url:this.credentials.url,socketFactory:this.socketFactory,now:this.now,random:this.random,backoff:this.backoffOptions,shouldReconnect:i=>this.shouldReconnect(i)}),this.transport.onFrame=i=>this.handleFrame(i),this.transport.onStateChange=(i,r)=>this.handleTransportState(i,r),this.attachVisibility(),this.startPump(),this.transport.connect(),t}disconnect(){this.transport&&(this.sendControl({typeId:P.LeaveCommand,body:{}}),this.transport.onFrame=null,this.transport.onStateChange=null,this.transport.dispose(),this.transport=null),this.rejectPendingConnect(new st("cancelled","The session was disconnected locally.")),this.rejectPendingSpawns("cancelled","The session was disconnected locally."),this.stopPump(),this.detachVisibility(),this.resetSessionState(),this.session=null,this.worldQuantizer=null,this.hasWelcomed=!1,this.resumeKey=null,this.credentials=null,this.setStatus("offline")}dispose(){this.disposed||(this.disconnect(),this.disposed=!0,this.signalHandlers.clear(),this.statusListeners.clear(),this.peerListeners.clear(),this.entityListeners.clear(),this.roomVarListeners.clear(),this.errorListeners.clear())}onStatusChange(e){return this.statusListeners.add(e),()=>this.statusListeners.delete(e)}onPeersChange(e){return this.peerListeners.add(e),()=>this.peerListeners.delete(e)}onEntitiesChange(e){return this.entityListeners.add(e),()=>this.entityListeners.delete(e)}onRoomVarsChange(e){return this.roomVarListeners.add(e),()=>this.roomVarListeners.delete(e)}onError(e){return this.errorListeners.add(e),()=>this.errorListeners.delete(e)}on(e,t){let i=this.signalHandlers.get(e);return i||(i=new Set,this.signalHandlers.set(e,i)),i.add(t),()=>this.off(e,t)}off(e,t){let i=this.signalHandlers.get(e);i&&(t?i.delete(t):i.clear(),i.size===0&&this.signalHandlers.delete(e))}emit(e,t=null,i={}){if(!this.isOnline)return!1;let r=i.to??"peers",o=Zn.AllPeers,s=0;return typeof r=="number"?(o=Zn.SinglePeer,s=r):r==="server"?o=Zn.Server:r==="aoi"&&(o=Zn.AoiPeers),this.sendControl({typeId:P.EmitSignalCommand,body:{name:e,target:o,targetClientId:s,payload:Cv(t)}})}publish(e,t){let i=this.worldQuantizer;if(!this.isOnline||!i)return!1;let r=this.getPublishEntry(e),o=r.mask;if(t.x!==void 0||t.y!==void 0){let s=t.x??i.dequantizeX(r.next.qx),a=t.y??i.dequantizeY(r.next.qy);if(!i.tryQuantizePosition(s,a,this.quantizedPosition))return this.counters.nonFiniteRejected+=1,!1;t.x!==void 0&&(!r.hasSent||this.quantizedPosition.qx!==r.sent.qx)&&(r.next.qx=this.quantizedPosition.qx,o|=j.X),t.y!==void 0&&(!r.hasSent||this.quantizedPosition.qy!==r.sent.qy)&&(r.next.qy=this.quantizedPosition.qy,o|=j.Y)}if(t.rotation!==void 0){let s=ul(t.rotation);if(s===null)return this.counters.nonFiniteRejected+=1,!1;(!r.hasSent||s!==r.sent.qrot)&&(r.next.qrot=s,o|=j.Rot)}if(t.vx!==void 0){let s=so(t.vx);if(s===null)return this.counters.nonFiniteRejected+=1,!1;(!r.hasSent||s!==r.sent.qvx)&&(r.next.qvx=s,o|=j.Vx)}if(t.vy!==void 0){let s=so(t.vy);if(s===null)return this.counters.nonFiniteRejected+=1,!1;(!r.hasSent||s!==r.sent.qvy)&&(r.next.qvy=s,o|=j.Vy)}if(t.flags!==void 0){let s=t.flags&255;(!r.hasSent||s!==r.sent.flags)&&(r.next.flags=s,o|=j.Flags)}return t.teleport&&(o|=j.Teleport),r.mask=o,!0}clearPublished(e){this.publishStates.delete(e)}get kinds(){return this.kindTableOverride??Kd()}get ownedEntityCount(){return this.ownedNetIds.size}ownsEntity(e){return this.ownedNetIds.has(e)}spawn(e,t={}){let i=this.kinds.kindOf(e);if(i===null)return Promise.reject(new me("unknown-kind",e,`"${e}" is not in this build's netKindTable, so it has no wire kind. Run it from the plugin's player (the build emits the table) or call registerNetworkPrefab() on every client.`));let r=this.worldQuantizer;if(!this.isOnline||!r)return Promise.reject(new me("offline",e,"Cannot spawn: this session is not in a room."));if(this.ownedNetIds.size>=xv)return this.counters.spawnsThrottled+=1,Promise.reject(new me("quota",e,`This client already owns ${xv} entities \u2014 despawn one first.`,q.QuotaExceeded));let o=this.now();for(;this.spawnTimestamps.length>0&&o-this.spawnTimestamps[0]>=UD;)this.spawnTimestamps.shift();if(this.spawnTimestamps.length>=wv)return this.counters.spawnsThrottled+=1,Promise.reject(new me("rate-limited",e,`Spawn rate limit: ${wv} spawns per minute per connection.`,q.RateLimited));let s=t.position;if(!r.tryQuantizePosition(s?.x??0,s?.y??0,this.quantizedPosition))return this.counters.nonFiniteRejected+=1,Promise.reject(new me("invalid",e,"Spawn position must be finite."));let a=ul(t.rotation??0),l=so(t.velocity?.x??0),c=so(t.velocity?.y??0);if(a===null||l===null||c===null)return this.counters.nonFiniteRejected+=1,Promise.reject(new me("invalid",e,"Spawn rotation and velocity must be finite."));let u=this.nextRequestId;return this.nextRequestId=(this.nextRequestId+1)%WD||1,this.sendControl({typeId:P.SpawnEntityRequest,body:{requestId:u,kind:i,qx:this.quantizedPosition.qx,qy:this.quantizedPosition.qy,qrot:a,qvx:l,qvy:c,flags:Tv(t.ownership??"owned",t.appFlags??0),props:YD(t.props)}})?(this.spawnTimestamps.push(o),this.counters.spawnsSent+=1,new Promise((d,p)=>{this.pendingSpawns.set(u,{prefabPath:e,resolve:d,reject:p})})):Promise.reject(new me("invalid",e,"The spawn request could not be sent."))}despawn(e){return!this.isOnline||!this.sendControl({typeId:P.DespawnEntityCommand,body:{netId:e}})?!1:(this.counters.despawnsSent+=1,this.ownedNetIds.delete(e),this.publishStates.delete(e),!0)}snapPosition(e,t,i){let r=this.worldQuantizer;return!r||!r.tryQuantizePosition(e,t,this.quantizedPosition)?!1:(i.x=r.dequantizeX(this.quantizedPosition.qx),i.y=r.dequantizeY(this.quantizedPosition.qy),!0)}snapRotation(e){let t=ul(e);return t===null?null:Sv(t)}flush(){this.pump()}requestResync(){if(!this.isOnline)return!1;let e=this.now();for(;this.resyncTimestamps.length>0&&e-this.resyncTimestamps[0]>=zD;)this.resyncTimestamps.shift();return this.resyncTimestamps.length>=FD?(this.counters.resyncsSuppressed+=1,!1):this.sendControl({typeId:P.ResyncCommand,body:{}})?(this.resyncTimestamps.push(e),this.counters.resyncsSent+=1,!0):!1}sendChat(e){return this.isOnline?this.sendControl({typeId:P.SendChatCommand,body:{text:e}}):!1}shouldReconnect(e){return!(!this.hasWelcomed||e.code!==null&&qD.has(e.code)||this.lastRejectCode!==null&&GD.has(this.lastRejectCode))}handleTransportState(e,t){switch(e){case"connecting":this.setStatus("connecting");break;case"open":this.sendHello();break;case"reconnecting":this.session=null,this.rejectPendingSpawns("transport","The room connection dropped before the spawn was answered."),this.setStatus("reconnecting");break;case"closed":{let i=this.describeClose(t);this.session=null,this.rejectPendingSpawns("transport",`The room connection closed: ${i.message}`),this.setStatus("offline"),this.rejectPendingConnect(i),this.notifyError(i);break}default:break}}describeClose(e){if(this.lastRejectCode!==null)return new st("rejected",hl(this.lastRejectCode),this.lastRejectCode,e?.code??null);let t=e?`${e.reason}${e.message?`: ${e.message}`:""}`:"connection closed";return new st("transport",`The room connection closed (${t}).`,0,e?.code??null)}sendHello(){let e=this.credentials;e&&this.sendControl({typeId:P.HelloCommand,body:{protocolVersion:2,token:e.token,roomId:e.roomId,displayName:e.displayName,capabilities:e.capabilities,resumeKey:this.resumeKey}})}sendControl(e){let t=this.transport;return t?t.send(fv(e)):!1}sendSetRoomVar(e,t){return this.isOnline?this.sendControl({typeId:P.SetRoomVarCommand,body:{key:e,value:t}}):!1}handleFrame(e){this.counters.framesReceived+=1;let t=zS(e);if(t<0){this.counters.malformedFrames+=1;return}switch(t){case P.SnapshotPacket:this.applySnapshotPacket(e);return;case P.DeltaPacket:this.applyDeltaPacket(e);return;case P.SignalBatchPacket:this.applySignalBatchPacket(e);return;default:break}let i;try{i=mv(t,US(e))}catch{this.counters.malformedFrames+=1;return}if(!i){this.unknownTypeIds.record(t),this.counters.unknownTypeIds+=1;return}this.dispatchControl(i)}dispatchControl(e){switch(e.typeId){case P.WelcomeEvent:this.handleWelcome(e.body);break;case P.RejectedEvent:this.handleRejected(e.body.code,e.body.message);break;case P.PongEvent:this.handlePong(e.body.clientTimeMs,e.body.serverTimeMs);break;case P.PeerJoinedEvent:this.peerMap.set(e.body.clientId,{clientId:e.body.clientId,displayName:e.body.displayName,isLocal:e.body.clientId===this.clientId}),this.notifyPeers();break;case P.PeerLeftEvent:this.peerMap.delete(e.body.clientId)&&this.notifyPeers();break;case P.HostChangedEvent:this.session&&(this.session={...this.session,hostClientId:e.body.hostClientId}),this.notifyPeers();break;case P.RoomVarsChangedEvent:this.handleRoomVars(e.body.keys,e.body.values);break;case P.RoomRosterEvent:this.handleRoomRoster(e.body);break;case P.SignalEvent:this.dispatchSignal(e.body.name,e.body.payload,e.body.senderClientId);break;case P.SpawnEntityResponse:this.handleSpawnResponse(e.body);break;default:break}}handleWelcome(e){let t=e.resumed&&this.hasWelcomed;t||this.resetSessionState(),this.slotToNetId.clear(),this.pendingSnapshot.clear(),this.snapshotInProgress=!1,this.snapshotComplete=!1,this.lastSeq=null,this.desynced=!1,this.lastRejectCode=null,this.pendingRoster.length=0,this.rosterInProgress=!1,this.receivedRoomVarsForSession=!1,this.worldQuantizer=yv(e.worldOriginX,e.worldOriginY,e.worldSize)?new cl(e.worldOriginX,e.worldOriginY,e.worldSize):null,this.resumeKey=e.resumeKey.length>0?e.resumeKey.slice():null,this.hasWelcomed=!0,this.session={clientId:e.clientId,roomId:e.roomId,tickHz:e.tickHz,mode:e.mode,protocolVersion:e.protocolVersion,maxPlayers:e.maxPlayers,maxVisibleEntities:e.maxVisibleEntities,aoiRadius:e.aoiRadius,hostClientId:e.hostClientId,resumed:t,world:{originX:e.worldOriginX,originY:e.worldOriginY,size:e.worldSize}},this.peerMap.set(e.clientId,{clientId:e.clientId,displayName:this.credentials?.displayName??"",isLocal:!0}),this.clockOffsetMs=e.serverTimeMs-this.now(),this.setStatus("online"),this.notifyPeers(),this.hidden&&this.sendClientPrefs();let i=this.pendingConnect?.resolve;this.pendingConnect=null,this.connectPromise=null,i?.(this.session)}handleSpawnResponse(e){let t=this.pendingSpawns.get(e.requestId);if(t){if(this.pendingSpawns.delete(e.requestId),e.rejectCode!==q.None||e.netId===0){this.counters.spawnsRejected+=1,t.reject(new me($D(e.rejectCode),t.prefabPath,hl(e.rejectCode),e.rejectCode));return}this.ownedNetIds.add(e.netId),t.resolve(e.netId)}}rejectPendingSpawns(e,t){if(this.pendingSpawns.size===0)return;let i=[...this.pendingSpawns.values()];this.pendingSpawns.clear();for(let r of i)r.reject(new me(e,r.prefabPath,t))}handleRejected(e,t){this.lastRejectCode=e;let i=new st("rejected",t&&t.length>0?t:hl(e),e,null);this.rejectPendingConnect(i),this.notifyError(i)}handlePong(e,t){if(e!==this.lastPingClientTimeMs){this.clockOffsetMs=t-this.now();return}let i=this.now();this.rttMs=Math.max(0,i-e),this.clockOffsetMs=t+this.rttMs/2-i}handleRoomVars(e,t){let i=!this.receivedRoomVarsForSession;this.receivedRoomVarsForSession=!0;let r=i?this.roomVars.replaceAll(e,t.map(kv)):this.roomVars.merge(e,t.map(kv));if(r.length>0)for(let o of[...this.roomVarListeners])o(r)}handleRoomRoster(e){this.rosterInProgress||(this.pendingRoster.length=0,this.rosterInProgress=!0);let t=Math.min(e.clientIds.length,e.displayNames.length);(t!==e.clientIds.length||t!==e.displayNames.length)&&(this.counters.malformedFrames+=1);for(let i=0;i<t;i+=1){let r=e.clientIds[i];this.pendingRoster.push({clientId:r,displayName:e.displayNames[i],isLocal:r===this.clientId})}Yd(e.frameFlags)&&this.commitRoster()}commitRoster(){let e=this.peerMap.get(this.clientId);this.peerMap.clear();for(let t of this.pendingRoster)t.isLocal&&this.peerMap.set(t.clientId,t);this.peerMap.size===0&&e&&this.peerMap.set(e.clientId,e);for(let t of this.pendingRoster)t.isLocal||this.peerMap.set(t.clientId,t);this.pendingRoster.length=0,this.rosterInProgress=!1,this.notifyPeers()}applySnapshotPacket(e){let t=op(e);if(!ZS(t,this.snapshotView)){this.counters.malformedFrames+=1;return}if(this.acceptHotFrame(this.snapshotView.seq,!0)){this.snapshotInProgress||(this.pendingSnapshot.clear(),this.snapshotInProgress=!0);for(let i=0;i<this.snapshotView.count;i+=1){if(!ev(t,this.snapshotView,i,this.fullRecord)){this.counters.malformedFrames+=1;break}this.pendingSnapshot.set(this.fullRecord.netId,Pv(this.fullRecord.netId,this.fullRecord.state))}Yd(this.snapshotView.frameFlags)&&this.commitSnapshot()}}commitSnapshot(){let e=this.beginChanges();for(let[t,i]of this.entityMap)this.pendingSnapshot.has(t)||e.push({kind:"leave",netId:t,entity:i,mask:0});this.entityMap.clear(),this.slotToNetId.clear();for(let[t,i]of this.pendingSnapshot)this.entityMap.set(t,i),this.slotToNetId.set(rp(t),t),e.push({kind:"enter",netId:t,entity:i,mask:0});this.pendingSnapshot.clear(),this.snapshotInProgress=!1,this.snapshotComplete=!0,this.desynced=!1,this.flushChanges(e)}applyDeltaPacket(e){let t=op(e);if(!iv(t,this.deltaSections)){this.counters.malformedFrames+=1;return}if(!this.acceptHotFrame(this.deltaSections.seq,!1))return;let i=this.beginChanges();for(let o=0;o<this.deltaSections.removedCount;o+=1){let s=rv(t,this.deltaSections,o);if(s<0){this.counters.malformedFrames+=1;break}let a=this.slotToNetId.get(s);if(a===void 0)continue;let l=this.entityMap.get(a);this.slotToNetId.delete(s),this.entityMap.delete(a),this.publishStates.delete(a),l&&i.push({kind:"leave",netId:a,entity:l,mask:0})}for(let o=0;o<this.deltaSections.enterCount;o+=1){if(!nv(t,this.deltaSections,o,this.fullRecord)){this.counters.malformedFrames+=1;break}let s=this.fullRecord.netId,a=Pv(s,this.fullRecord.state);this.entityMap.set(s,a),this.slotToNetId.set(rp(s),s),i.push({kind:"enter",netId:s,entity:a,mask:0})}let r=0;for(let o=0;o<this.deltaSections.updateCount;o+=1){if(!ov(t,this.deltaSections,r,this.updateRecord)){this.counters.malformedFrames+=1;break}r+=this.updateRecord.bytesRead;let s=this.slotToNetId.get(this.updateRecord.slot),a=s===void 0?void 0:this.entityMap.get(s);if(!a){this.counters.unknownSlotUpdates+=1;continue}$S(a,this.updateRecord.mask,this.updateRecord.state),i.push({kind:"update",netId:a.netId,entity:a,mask:this.updateRecord.mask})}this.flushChanges(i)}applySignalBatchPacket(e){let t=op(e);if(!uv(t,this.signalSections)){this.counters.malformedFrames+=1;return}if(!this.acceptHotFrame(this.signalSections.seq,!1))return;let i=0;for(let r=0;r<this.signalSections.count;r+=1){if(!hv(t,this.signalSections,i,this.signalEntry)){this.counters.malformedFrames+=1;break}i+=this.signalEntry.bytesRead,this.dispatchSignal(hp.decode(this.signalEntry.name),this.signalEntry.payload,this.signalEntry.senderClientId)}}acceptHotFrame(e,t){if(this.desynced&&!t)return!1;let i=this.lastSeq===null?e:(this.lastSeq+1)%HD;if(e!==i){if(this.counters.seqGaps+=1,!t)return this.desynced=!0,this.snapshotComplete=!1,this.requestResync(),!1;this.pendingSnapshot.clear(),this.snapshotInProgress=!1}return t&&(this.desynced=!1),this.lastSeq=e,!0}dispatchSignal(e,t,i){let r=this.signalHandlers.get(e);if(!(!r||r.size===0))for(let o of[...r])try{o(t,i)}catch(s){this.counters.signalHandlerErrors+=1,console.error(`[NetworkService] Signal handler for "${e}" threw:`,s)}}startPump(){this.pumpTimer===null&&(this.pumpTimer=setInterval(()=>this.pump(),this.sendIntervalMs))}stopPump(){this.pumpTimer!==null&&(clearInterval(this.pumpTimer),this.pumpTimer=null)}pump(){this.isOnline&&(this.flushDirtyEntities(),this.maybePing())}maybePing(){let e=this.now();this.lastPingSentAtMs!==0&&e-this.lastPingSentAtMs<this.pingIntervalMs||(this.lastPingSentAtMs=e,this.lastPingClientTimeMs=e,this.sendControl({typeId:P.PingCommand,body:{clientTimeMs:e}}))}flushDirtyEntities(){let e=[];for(let t of this.publishStates.values())t.mask!==0&&e.push(t);if(e.length!==0){this.clientTick=this.clientTick+1>>>0;for(let t=0;t<e.length;t+=vv){let i=e.slice(t,t+vv),r=al;for(let l of i)r+=ip(l.mask);let o=new ArrayBuffer(r),s=new DataView(o),a=sv(s,0,this.clientTick);for(let l of i)a+=QS(s,a,l.netId,l.mask,l.next);if(av(s,i.length),!this.transport?.send(new Uint8Array(o)))return;this.counters.entityPacketsSent+=1,this.counters.entityRecordsSent+=i.length;for(let l of i)l.sent.qx=l.next.qx,l.sent.qy=l.next.qy,l.sent.qrot=l.next.qrot,l.sent.qvx=l.next.qvx,l.sent.qvy=l.next.qvy,l.sent.flags=l.next.flags,l.mask=0,l.hasSent=!0}}}getPublishEntry(e){let t=this.publishStates.get(e);return t||(t={netId:e,sent:no(),next:no(),mask:0,hasSent:!1},this.publishStates.set(e,t)),t}attachVisibility(){this.visibility&&(this.hidden=this.visibility.hidden,this.visibility.addEventListener("visibilitychange",this.onVisibilityChange))}detachVisibility(){this.visibility?.removeEventListener("visibilitychange",this.onVisibilityChange)}handleVisibilityChange(){let e=this.visibility?.hidden??!1;e!==this.hidden&&(this.hidden=e,this.sendClientPrefs())}sendClientPrefs(){this.sendControl({typeId:P.SetClientPrefsCommand,body:{hidden:this.hidden,sendRateDivisor:0}})}resetSessionState(){this.entityMap.clear(),this.slotToNetId.clear(),this.pendingSnapshot.clear(),this.publishStates.clear(),this.peerMap.clear(),this.pendingRoster.length=0,this.rosterInProgress=!1,this.roomVars.clear(),this.receivedRoomVarsForSession=!1,this.snapshotInProgress=!1,this.snapshotComplete=!1,this.desynced=!1,this.lastSeq=null,this.resyncTimestamps.length=0,this.clientTick=0,this.lastPingSentAtMs=0,this.lastPingClientTimeMs=0,this.rttMs=0,this.ownedNetIds.clear(),this.spawnTimestamps.length=0,this.rejectPendingSpawns("transport","The session was reset before the spawn was answered.")}setStatus(e){if(this.currentStatus!==e){this.currentStatus=e;for(let t of[...this.statusListeners])t(e)}}notifyPeers(){let e=this.peers;for(let t of[...this.peerListeners])t(e)}notifyError(e){for(let t of[...this.errorListeners])t(e)}rejectPendingConnect(e){let t=this.pendingConnect?.reject;this.pendingConnect=null,this.connectPromise=null,t?.(e)}beginChanges(){return this.scratchChanges.length=0,this.scratchChanges}flushChanges(e){for(let i of e)i.kind==="leave"&&(this.ownedNetIds.delete(i.netId),this.publishStates.delete(i.netId));if(e.length===0||this.entityListeners.size===0){e.length=0;return}let t=[...e];e.length=0;for(let i of[...this.entityListeners])i(t)}};function op(n){return new DataView(n.buffer,n.byteOffset,n.byteLength)}function Pv(n,e){return{netId:n,qx:e.qx,qy:e.qy,qrot:e.qrot,qvx:e.qvx,qvy:e.qvy,kind:e.kind,ownerId:e.ownerId,flags:e.flags}}function $D(n){switch(n){case q.QuotaExceeded:return"quota";case q.EntityLimitReached:return"entity-limit";case q.KindNotAllowed:return"kind-not-allowed";default:return"rejected"}}function YD(n){return n==null?null:n instanceof Uint8Array?n:up.encode(JSON.stringify(n))}function kv(n){return n.slice()}function Cv(n){return n===null?new Uint8Array(0):n instanceof Uint8Array?n:up.encode(JSON.stringify(n))}function KD(n){if(n.length!==0)try{return JSON.parse(hp.decode(n))}catch{return}}function XD(){let n=globalThis.document;return n&&typeof n.addEventListener=="function"?n:null}var lo=class{constructor(e){this.host=e;this.unsubscribe=e.network.onEntitiesChange(t=>this.applyChanges(t))}host;byNetId=new Map;byNode=new WeakMap;inFlight=new Set;pending=new Set;unsubscribe=null;disposed=!1;counters={remoteSpawned:0,remoteFreed:0,unknownKinds:0,instantiateFailures:0};get stats(){return{...this.counters}}get boundCount(){return this.byNetId.size}get pendingCount(){return this.pending.size+this.inFlight.size}bind(e,t,i=null){this.adopt({netId:e,node:t,remote:!1,listener:i})}setListener(e,t){let i=this.byNetId.get(e);i&&(i.listener=t)}unbind(e){let t=this.byNetId.get(e);t&&(this.byNetId.delete(e),this.byNode.get(t.node)===e&&this.byNode.delete(t.node))}getNode(e){return this.byNetId.get(e)?.node??null}getNetId(e){return this.byNode.get(e)??0}isRemote(e){return this.byNetId.get(e)?.remote??!1}reconcile(){if(!this.disposed)for(let[e,t]of this.host.network.entities)this.byNetId.has(e)||this.inFlight.has(e)||this.isLocallyOwned(e)||(this.pending.add(e),this.instantiateRemote(e,t.kind))}handleSceneStopped(){for(let e of this.byNetId.values())e.remote&&this.pending.add(e.netId);this.byNetId.clear(),this.inFlight.clear()}dispose(){this.disposed||(this.disposed=!0,this.unsubscribe?.(),this.unsubscribe=null,this.byNetId.clear(),this.inFlight.clear(),this.pending.clear())}adopt(e){let t=this.byNetId.get(e.netId);t&&t.node!==e.node&&this.byNode.delete(t.node),this.byNetId.set(e.netId,e),this.byNode.set(e.node,e.netId),this.pending.delete(e.netId)}applyChanges(e){if(!this.disposed)for(let t of e){let i=this.byNetId.get(t.netId);if(i?.listener)try{i.listener(t)}catch(r){console.error(`[NetworkNodeBinder] Listener for entity ${t.netId} threw:`,r)}if(t.kind==="leave"){this.releaseEntity(t.netId);continue}t.kind!=="enter"||i||this.inFlight.has(t.netId)||this.isLocallyOwned(t.netId)||(this.pending.add(t.netId),this.instantiateRemote(t.netId,t.entity.kind))}}releaseEntity(e){this.pending.delete(e);let t=this.byNetId.get(e);t&&(this.byNetId.delete(e),this.byNode.delete(t.node),t.remote&&(t.node.queueFree(),this.counters.remoteFreed+=1))}isLocallyOwned(e){let t=this.host.network;if(t.ownsEntity(e))return!0;let i=t.entities.get(e);return i!==void 0&&i.ownerId!==0&&i.ownerId===t.clientId}async instantiateRemote(e,t){if(this.host.isSceneRunning&&!this.host.isSceneRunning())return;let i=this.host.network.kinds.prefabPathOf(t);if(!i){this.pending.delete(e),this.counters.unknownKinds+=1;return}this.inFlight.add(e);let r;try{r=await this.host.instantiate(i,{instanceId:`net:${e}`})}catch(o){this.inFlight.delete(e),this.counters.instantiateFailures+=1,console.warn(`[NetworkNodeBinder] Could not instantiate "${i}":`,o);return}if(this.inFlight.delete(e),this.disposed||!this.host.network.entities.has(e)){r.queueFree(),this.pending.delete(e);return}this.adopt({netId:e,node:r,remote:!0,listener:null}),this.counters.remoteSpawned+=1}};var zi=class{effectiveScale=1;blendedScale=1;blendFrom=1;blendTo=1;blendDurationSec=0;blendElapsedSec=0;autoRelease=!1;holdRemainingSec=1/0;releaseBlendSec=0;hitstopRemainingSec=0;hitstopWindowSec=0;frameIndex=0;lastHitstopFrame=-1;hitstopFrameStreak=0;warnedAboutHitstopStreak=!1;get scale(){return this.effectiveScale}get baseScale(){return Math.max(0,this.blendedScale)}get isFrozen(){return this.hitstopRemainingSec>0}hitstop(e){let t=Number.isFinite(e)?Math.max(0,e)/1e3:0;if(this.noteHitstopRequest(),!(t<=0)){if(this.hitstopRemainingSec>0){t>this.hitstopWindowSec&&(this.hitstopRemainingSec=t,this.hitstopWindowSec=t);return}this.hitstopRemainingSec=t,this.hitstopWindowSec=t}}slowMotion(e,t={}){let i=this.sanitizeScale(e,.3),r=this.sanitizeMs(t.blendMs,150)/1e3;this.startBlend(i,r),t.durationMs!=null&&Number.isFinite(t.durationMs)?(this.autoRelease=!0,this.holdRemainingSec=Math.max(0,t.durationMs)/1e3,this.releaseBlendSec=r):(this.autoRelease=!1,this.holdRemainingSec=1/0)}setScale(e){let t=this.sanitizeScale(e,1);this.blendedScale=t,this.blendFrom=t,this.blendTo=t,this.blendDurationSec=0,this.blendElapsedSec=0,this.autoRelease=!1,this.holdRemainingSec=1/0,this.updateEffective()}reset(){this.hitstopRemainingSec=0,this.hitstopWindowSec=0,this.lastHitstopFrame=-1,this.hitstopFrameStreak=0,this.setScale(1)}advance(e){let t=Number.isFinite(e)&&e>0?e:0;if(this.frameIndex+=1,this.hitstopRemainingSec>0&&(this.hitstopRemainingSec=Math.max(0,this.hitstopRemainingSec-t),this.hitstopRemainingSec===0&&(this.hitstopWindowSec=0)),this.blendElapsedSec<this.blendDurationSec){this.blendElapsedSec=Math.min(this.blendDurationSec,this.blendElapsedSec+t);let r=this.blendDurationSec>0?this.blendElapsedSec/this.blendDurationSec:1;this.blendedScale=this.blendFrom+(this.blendTo-this.blendFrom)*r}else this.blendedScale=this.blendTo;let i=this.blendElapsedSec>=this.blendDurationSec;this.autoRelease&&i&&this.blendTo!==1&&(this.holdRemainingSec-=t,this.holdRemainingSec<=0&&(this.autoRelease=!1,this.holdRemainingSec=1/0,this.startBlend(1,this.releaseBlendSec))),this.updateEffective()}noteHitstopRequest(){this.hitstopFrameStreak=this.lastHitstopFrame>=this.frameIndex-1?this.hitstopFrameStreak+1:1,this.lastHitstopFrame=this.frameIndex,this.hitstopFrameStreak>=30&&!this.warnedAboutHitstopStreak&&(this.warnedAboutHitstopStreak=!0,console.warn(`[GameTime] hitstop() has been called on ${this.hitstopFrameStreak} consecutive frames. Hitstop is edge-triggered juice: call it once when a contact BEGINS (a signal handler, or a "was overlapping last frame" guard), not every frame while an overlap lasts. Requests during a freeze are ignored, so the game runs slowly instead of freezing.`))}startBlend(e,t){this.blendFrom=this.blendedScale,this.blendTo=e,this.blendDurationSec=Math.max(0,t),this.blendElapsedSec=0,this.blendDurationSec===0&&(this.blendedScale=e),this.updateEffective()}updateEffective(){this.effectiveScale=this.hitstopRemainingSec>0?0:Math.max(0,this.blendedScale)}sanitizeScale(e,t){return!Number.isFinite(e)||e<0?t:e}sanitizeMs(e,t){return typeof e!="number"||!Number.isFinite(e)||e<0?t:e}};var QD=50,pl=8,JD=32,Mv=64,ZD=200,Dv=6,eE=/^[a-z][a-z0-9]*(?:-[a-z0-9]+)*(?:\.[a-z][a-z0-9]*(?:-[a-z0-9]+)*)*$/;function dp(n,e,t,i){if(n===null)return null;let r=typeof n;if(r==="string"||r==="boolean")return null;if(r==="number")return Number.isFinite(n)?null:`${e} is ${String(n)}, which JSON cannot carry`;if(r==="undefined")return`${e} is undefined \u2014 use null for an absent value`;if(r!=="object")return`${e} is a ${r}, which is not JSON-serialisable`;let o=n;if(i.has(o))return`${e} is a circular reference`;if(t>Dv)return`${e} nests deeper than ${Dv} levels`;let s=Object.getPrototypeOf(o),a=s===Object.prototype||s===null;if(!Array.isArray(o)&&!a){let l=o.constructor?.name??"object";return`${e} is a ${l} instance \u2014 pass plain data, not live objects`}i.add(o);try{if(Array.isArray(o)){for(let l=0;l<o.length;l++){let c=dp(o[l],`${e}[${l}]`,t+1,i);if(c)return c}return null}for(let[l,c]of Object.entries(o)){let u=dp(c,`${e}.${l}`,t+1,i);if(u)return u}return null}finally{i.delete(o)}}var co=class{constructor(e=()=>0){this.frameProvider=e}frameProvider;commands=new Map;entries=[];undoStack=[];depth=0;dropped=0;register(e,t,i){let r=()=>{};if(typeof e!="string"||e.length===0||e.length>Mv)return this.reject(String(e),`command names are 1..${Mv} characters of kebab-case, optionally namespaced (e.g. "settings.toggle-music")`),r;if(!eE.test(e))return this.reject(e,`"${e}" is not a valid command name \u2014 use kebab-case, optionally namespaced with dots (e.g. "settings.toggle-music")`),r;if(typeof t!="function")return this.reject(e,`"${e}" was registered without a handler function`),r;if(this.commands.has(e))return this.reject(e,`"${e}" is already registered \u2014 command names are unique per scene`),r;let o={name:e,handler:t,meta:i};return this.commands.set(e,o),()=>{this.commands.get(e)===o&&this.commands.delete(e)}}dispatch(e,t){let i=this.commands.get(e);if(!i)return this.push({frame:this.frame(),name:String(e),status:"unknown",error:`no command named "${String(e)}" is registered`}),console.warn(`[commands] No command named "${String(e)}" is registered.`),!1;if(t!==void 0){let o=typeof t!="object"||t===null||Array.isArray(t)?"args must be a plain object of JSON values":dp(t,"args",0,new Set);if(o)return this.reject(e,o),!1}if(this.depth>=pl)return this.reject(e,`dispatch nested deeper than ${pl} commands \u2014 a command is dispatching itself, directly or in a cycle`),!1;let r=this.push({frame:this.frame(),name:e,status:"ok",...this.describeArgs(t)});this.depth+=1;try{let o=i.handler(t);return o&&typeof o.undo=="function"&&(this.undoStack.push({name:e,undo:()=>o.undo()}),this.undoStack.length>JD&&this.undoStack.shift()),!0}catch(o){let{message:s,stack:a}=Le(o);return r.status="error",r.error=s,console.error(`[commands] Command "${e}" failed:`,o),Me({phase:"command",message:`command "${e}": ${s}`,stack:a}),!1}finally{this.depth-=1}}undo(){let e=this.undoStack.pop();if(!e)return this.reject("(undo)","nothing to undo \u2014 no dispatched command declared a reverse step"),!1;if(this.depth>=pl)return this.reject(e.name,`undo nested deeper than ${pl} commands`),!1;let t=this.push({frame:this.frame(),name:e.name,status:"undo"});this.depth+=1;try{return e.undo(),!0}catch(i){let{message:r,stack:o}=Le(i);return t.status="error",t.error=r,console.error(`[commands] Undo of "${e.name}" failed:`,i),Me({phase:"command",message:`undo of command "${e.name}": ${r}`,stack:o}),!1}finally{this.depth-=1}}list(){return[...this.commands.values()].map(e=>({name:e.name,...e.meta?.description?{description:e.meta.description}:{},...e.meta?.params?{params:e.meta.params}:{},undoable:e.meta?.undoable===!0})).sort((e,t)=>e.name<t.name?-1:e.name>t.name?1:0)}get log(){return this.entries}get droppedLogEntries(){return this.dropped}get canUndo(){return this.undoStack.length>0}clear(){this.commands.clear(),this.entries.length=0,this.undoStack.length=0,this.depth=0,this.dropped=0}frame(){let e=this.frameProvider();return Number.isFinite(e)?e:0}reject(e,t){this.push({frame:this.frame(),name:e,status:"rejected",error:t}),console.error(`[commands] ${t}`)}describeArgs(e){if(e===void 0)return{};let t=JSON.stringify(e);return t===void 0||t.length>ZD?{argsOmitted:!0}:{args:JSON.parse(t)}}push(e){for(this.entries.push(e);this.entries.length>QD;)this.entries.shift(),this.dropped+=1;return e}};var ni=class n extends V{active=!1;elapsed=0;baseScale=new S(1,1,1);onTriggerSignal=()=>{this.trigger()};constructor(e,t){super(e,t),this.config={amount:.3,duration:.35,vibrato:3,triggerEvent:"",playOnStart:!1}}static getPropertySchema(){return{nodeType:"PunchScaleBehavior",properties:[{name:"amount",type:"number",ui:{label:"Amount",description:"Peak scale delta (0.3 = +30%)",group:"Punch Scale",min:0,step:.05,precision:2},getValue:e=>e.getAmount(),setValue:(e,t)=>{e.config.amount=n.num(t,.3,0)}},{name:"duration",type:"number",ui:{label:"Duration",group:"Punch Scale",min:0,step:.05,precision:2,unit:"s"},getValue:e=>e.getDuration(),setValue:(e,t)=>{e.config.duration=n.num(t,.35,0)}},{name:"vibrato",type:"number",ui:{label:"Vibrato",description:"Oscillations before settling",group:"Punch Scale",min:0,step:1},getValue:e=>e.getVibrato(),setValue:(e,t)=>{e.config.vibrato=n.num(t,3,0)}},{name:"triggerEvent",type:"string",ui:{label:"Trigger Event",description:"Node signal that triggers the punch (empty = manual/API only)",group:"Punch Scale"},getValue:e=>e.getTriggerEvent(),setValue:(e,t)=>{e.setTriggerEvent(t)}},{name:"playOnStart",type:"boolean",ui:{label:"Play On Start",group:"Punch Scale"},getValue:e=>!!e.config.playOnStart,setValue:(e,t)=>{e.config.playOnStart=!!t}}],groups:{"Punch Scale":{label:"Punch Scale",expanded:!0}}}}onStart(){this.bindTrigger(),this.config.playOnStart&&this.trigger()}onDetach(){this.unbindTrigger(),this.restore(),this.active=!1,super.onDetach()}play(e={}){e.amount!=null&&(this.config.amount=n.num(e.amount,.3,0)),e.duration!=null&&(this.config.duration=n.num(e.duration,.35,0)),e.vibrato!=null&&(this.config.vibrato=n.num(e.vibrato,3,0)),this.trigger()}trigger(){this.node&&(this.active||this.baseScale.copy(this.node.scale),this.elapsed=0,this.active=!0)}onUpdate(e){if(!this.active||!this.node)return;this.elapsed+=e;let t=this.getDuration();if(t<=0||this.elapsed>=t){this.node.scale.copy(this.baseScale),this.active=!1;return}let i=this.elapsed/t,r=Math.pow(1-i,2),o=Math.cos(i*this.getVibrato()*Math.PI*2),s=1+this.getAmount()*r*o;this.node.scale.set(this.baseScale.x*s,this.baseScale.y*s,this.baseScale.z*s)}restore(){this.node&&this.active&&this.node.scale.copy(this.baseScale)}bindTrigger(){let e=this.getTriggerEvent();this.node&&e&&this.node.connect(e,this,this.onTriggerSignal)}unbindTrigger(){let e=this.getTriggerEvent();this.node&&e&&this.node.disconnect(e,this,this.onTriggerSignal)}getAmount(){return n.num(this.config.amount,.3,0)}getDuration(){return n.num(this.config.duration,.35,0)}getVibrato(){return n.num(this.config.vibrato,3,0)}getTriggerEvent(){return typeof this.config.triggerEvent=="string"?this.config.triggerEvent.trim():""}setTriggerEvent(e){let t=!!this.node;t&&this.unbindTrigger(),this.config.triggerEvent=typeof e=="string"?e.trim():"",t&&this.bindTrigger()}static num(e,t,i){let r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.max(i,r):t}};var pp="backOut",oi=class n extends V{active=!1;elapsed=0;captured=!1;baseScale=new S(1,1,1);onTriggerSignal=()=>{this.trigger()};constructor(e,t){super(e,t),this.config={from:0,duration:.4,easing:pp,triggerEvent:"",playOnStart:!0}}static getPropertySchema(){return{nodeType:"PopInBehavior",properties:[{name:"from",type:"number",ui:{label:"From Scale",description:"Starting fraction of the authored scale",group:"Pop In",min:0,step:.05,precision:2},getValue:e=>e.getFrom(),setValue:(e,t)=>{e.config.from=n.num(t,0,0)}},{name:"duration",type:"number",ui:{label:"Duration",group:"Pop In",min:0,step:.05,precision:2,unit:"s"},getValue:e=>e.getDuration(),setValue:(e,t)=>{e.config.duration=n.num(t,.4,0)}},{name:"easing",type:"select",ui:{label:"Easing",group:"Pop In",options:["backOut","elasticOut","bounceOut","cubicOut","quadOut","linear"]},getValue:e=>e.getEasing(),setValue:(e,t)=>{e.config.easing=Ue(t)?t:pp}},{name:"triggerEvent",type:"string",ui:{label:"Trigger Event",description:"Node signal that triggers the pop (empty = manual/API only)",group:"Pop In"},getValue:e=>e.getTriggerEvent(),setValue:(e,t)=>{e.setTriggerEvent(t)}},{name:"playOnStart",type:"boolean",ui:{label:"Play On Start",group:"Pop In"},getValue:e=>!!e.config.playOnStart,setValue:(e,t)=>{e.config.playOnStart=!!t}}],groups:{"Pop In":{label:"Pop In",expanded:!0}}}}onStart(){this.captureBase(),this.bindTrigger(),this.config.playOnStart&&this.trigger()}onDetach(){this.unbindTrigger(),this.node&&this.captured&&this.node.scale.copy(this.baseScale),this.active=!1,super.onDetach()}play(e={}){e.from!=null&&(this.config.from=n.num(e.from,0,0)),e.duration!=null&&(this.config.duration=n.num(e.duration,.4,0)),e.easing!=null&&Ue(e.easing)&&(this.config.easing=e.easing),this.trigger()}trigger(){if(!this.node)return;this.captureBase(),this.elapsed=0,this.active=!0;let e=this.getFrom();this.node.scale.set(this.baseScale.x*e,this.baseScale.y*e,this.baseScale.z*e)}onUpdate(e){if(!this.active||!this.node)return;this.elapsed+=e;let t=this.getDuration(),i=t>0?Math.min(this.elapsed/t,1):1,r=this.getFrom(),o=r+(1-r)*wt(this.getEasing(),i);this.node.scale.set(this.baseScale.x*o,this.baseScale.y*o,this.baseScale.z*o),i>=1&&(this.node.scale.copy(this.baseScale),this.active=!1)}captureBase(){!this.node||this.captured||(this.baseScale.copy(this.node.scale),this.captured=!0)}bindTrigger(){let e=this.getTriggerEvent();this.node&&e&&this.node.connect(e,this,this.onTriggerSignal)}unbindTrigger(){let e=this.getTriggerEvent();this.node&&e&&this.node.disconnect(e,this,this.onTriggerSignal)}getFrom(){return n.num(this.config.from,0,0)}getDuration(){return n.num(this.config.duration,.4,0)}getEasing(){return Ue(this.config.easing)?this.config.easing:pp}getTriggerEvent(){return typeof this.config.triggerEvent=="string"?this.config.triggerEvent.trim():""}setTriggerEvent(e){let t=!!this.node;t&&this.unbindTrigger(),this.config.triggerEvent=typeof e=="string"?e.trim():"",t&&this.bindTrigger()}static num(e,t,i){let r=typeof e=="number"?e:Number(e);return Number.isFinite(r)?Math.max(i,r):t}};var Ui={count:14,speed:260,spread:Math.PI*2,direction:Math.PI/2,lifeSec:.5,sizePx:10,gravityY:-600},Rv=512,ml={fontSizePx:28,driftPx:60,durationSec:.8,glowStrength:1.5},Ev=.22,mp=.45,tE=[[-.5,.5],[.5,.5],[-.5,-.5],[.5,-.5]],Nv=[[0,1],[1,1],[0,0],[1,0]],Iv=[0,1,2,2,1,3],fl;function iE(){return fl!==void 0||(fl=rE()),fl}function rE(){if(typeof document>"u")return null;try{let e=document.createElement("canvas");e.width=64,e.height=64;let t=e.getContext("2d");if(!t||typeof t.createRadialGradient!="function")return null;let i=64/2,r=t.createRadialGradient(i,i,0,i,i,i);r.addColorStop(0,"rgba(255,255,255,1)"),r.addColorStop(.4,"rgba(255,255,255,0.9)"),r.addColorStop(1,"rgba(255,255,255,0)"),t.fillStyle=r,t.fillRect(0,0,64,64);let o=new It(e);return $(o),o}catch{return null}}function Be(n,e,t,i){let r=typeof n=="number"?n:Number(n);return Number.isFinite(r)?Math.min(i,Math.max(t,r)):e}function nE(n){let t=(Array.isArray(n.colors)?n.colors:[]).filter(i=>typeof i=="string"&&!!i.trim());return t.length===0&&typeof n.color=="string"&&n.color.trim()&&t.push(n.color),t.length===0&&t.push("#ffffff"),t.map(i=>{try{return new L(i)}catch{return new L("#ffffff")}})}var uo=class extends C{particles=[];geometry;positionAttribute;colorAttribute;gravityY;fadeOut;aliveParticles;constructor(e,t={}){super(e,"ParticleBurst2D"),this.isContainer=!1;let i=Math.round(Be(t.count,Ui.count,1,Rv)),r=Be(t.speed,Ui.speed,0,2e4),o=Be(t.spread,Ui.spread,0,Math.PI*2),s=Be(t.direction,Ui.direction,-1e6,1e6),a=Be(t.lifeSec,Ui.lifeSec,.05,10),l=Be(t.sizePx,Ui.sizePx,.5,1024);this.gravityY=Be(t.gravityY,Ui.gravityY,-1e5,1e5),this.fadeOut=t.fadeOut!==!1,t.zIndex!==void 0&&(this.zIndex=Be(t.zIndex,0,-4096,4096));let c=nE(t);this.geometry=new ae,this.positionAttribute=new Q(new Float32Array(i*4*3),3),this.colorAttribute=new Q(new Float32Array(i*4*4),4);let u=new Q(new Float32Array(i*4*2),2),h=new Uint16Array(i*6);for(let f=0;f<i;f++){let m=s+(Math.random()-.5)*o,g=r*(.55+Math.random()*.45),y={x:0,y:0,vx:Math.cos(m)*g,vy:Math.sin(m)*g,age:0,life:a*(.7+Math.random()*.6),size:l*(.7+Math.random()*.6)};this.particles.push(y);let b=c[Math.floor(Math.random()*c.length)]??c[0];for(let v=0;v<4;v++){let w=f*4+v;u.setXY(w,Nv[v][0],Nv[v][1]),this.colorAttribute.setXYZW(w,b.r,b.g,b.b,1)}for(let v=0;v<Iv.length;v++)h[f*6+v]=f*4+Iv[v];this.writeQuad(f,y.x,y.y,y.size)}this.geometry.setAttribute("position",this.positionAttribute),this.geometry.setAttribute("uv",u),this.geometry.setAttribute("color",this.colorAttribute),this.geometry.setIndex(new Qo(h,1)),this.aliveParticles=i;let d=new B({map:iE(),transparent:!0,depthTest:!1,depthWrite:!1,vertexColors:!0,blending:t.additive===!1?lt:ct});this.registerOpacityMaterial(d,1);let p=new O(this.geometry,d);p.frustumCulled=!1,p.userData[ze]=!0,this.add(p)}get particleCount(){return this.particles.length}get aliveCount(){return this.aliveParticles}tick(e){if(super.tick(e),this.aliveParticles===0)return;let t=Math.max(0,e),i=0;for(let r=0;r<this.particles.length;r++){let o=this.particles[r];if(o.age>=o.life)continue;o.age+=t;let s=o.age/o.life;if(s>=1){this.writeQuad(r,o.x,o.y,0),this.writeAlpha(r,0);continue}o.vy+=this.gravityY*t,o.x+=o.vx*t,o.y+=o.vy*t,this.writeQuad(r,o.x,o.y,o.size*(1-.6*s)),this.writeAlpha(r,this.fadeOut?1-s*s:1),i++}this.positionAttribute.needsUpdate=!0,this.colorAttribute.needsUpdate=!0,this.aliveParticles=i,i===0&&this.queueFree()}writeQuad(e,t,i,r){for(let o=0;o<4;o++){let[s,a]=tE[o];this.positionAttribute.setXYZ(e*4+o,t+s*r,i+a*r,0)}}writeAlpha(e,t){let i=this.colorAttribute.array;for(let r=0;r<4;r++)i[(e*4+r)*4+3]=t}};function oE(n){return 1-Math.pow(1-n,3)}function sE(n){return 1+2.70158*Math.pow(n-1,3)+1.70158*Math.pow(n-1,2)}var ho=class extends yt{totalDuration;driftPx;elapsed=0;captured=!1;baseY=0;baseScaleX=1;baseScaleY=1;finished=!1;constructor(e,t,i={}){let r=typeof i.color=="string"&&i.color.trim()?i.color:"#ffffff",o=i.glow===!0?r:typeof i.glow=="string"&&i.glow.trim()?i.glow:"";super({...e,label:t,labelColor:r,labelFontFamily:typeof i.fontFamily=="string"&&i.fontFamily.trim()?i.fontFamily:"Arial",labelFontSize:Be(i.fontSizePx,ml.fontSizePx,1,512),glowColor:o||void 0,glowStrength:o?Be(i.glowStrength,ml.glowStrength,0,4):0,zIndex:i.zIndex}),this.isContainer=!1,this.totalDuration=Be(i.durationSec,ml.durationSec,.05,30),this.driftPx=Be(i.driftPx,ml.driftPx,-1e4,1e4)}isPointInBounds(){return!1}tick(e){if(super.tick(e),this.finished)return;this.captured||(this.baseY=this.position.y,this.baseScaleX=this.scale.x,this.baseScaleY=this.scale.y,this.captured=!0),this.elapsed+=Math.max(0,e);let t=Math.min(1,this.elapsed/this.totalDuration);this.position.y=this.baseY+this.driftPx*oE(t);let i=t<Ev?sE(t/Ev):1;this.scale.set(this.baseScaleX*i,this.baseScaleY*i,1),this.opacity=t<mp?1:Math.max(0,1-(t-mp)/(1-mp)),t>=1&&(this.finished=!0,this.queueFree())}};var fp={lifeSec:.35,widthPx:14,maxPoints:48},Bv=256,aE=1e-4;function gl(n,e,t,i){let r=typeof n=="number"?n:Number(n);return Number.isFinite(r)?Math.min(i,Math.max(t,r)):e}function lE(n){let t=(Array.isArray(n.colors)?n.colors:Array.isArray(n.color)?n.color:typeof n.color=="string"?[n.color]:[]).filter(i=>typeof i=="string"&&i.trim().length>0);return t.length===0&&t.push("#ffffff"),t.map(i=>{try{return new L(i)}catch{return new L("#ffffff")}})}var po=class extends C{points=[];geometry;positionAttribute;colorAttribute;palette;lifeSec;halfWidth;maxPoints;scratchWorld=new S;scratchColor=new L;target;following=!0;freed=!1;constructor(e,t,i={}){super(e,"Trail2D"),this.isContainer=!1,this.target=t,this.lifeSec=gl(i.lifeSec,fp.lifeSec,.02,10),this.halfWidth=gl(i.widthPx,fp.widthPx,.1,4096)/2,this.maxPoints=Math.round(gl(i.maxPoints,fp.maxPoints,2,Bv)),this.palette=lE(i),i.zIndex!==void 0&&(this.zIndex=gl(i.zIndex,0,-4096,4096)),this.geometry=new ae,this.positionAttribute=new Q(new Float32Array(this.maxPoints*2*3),3),this.colorAttribute=new Q(new Float32Array(this.maxPoints*2*4),4);let r=new Uint16Array((this.maxPoints-1)*6);for(let a=0;a<this.maxPoints-1;a++){let l=a*2,c=a*6;r[c]=l,r[c+1]=l+1,r[c+2]=l+2,r[c+3]=l+2,r[c+4]=l+1,r[c+5]=l+3}this.geometry.setAttribute("position",this.positionAttribute),this.geometry.setAttribute("color",this.colorAttribute),this.geometry.setIndex(new Qo(r,1)),this.geometry.setDrawRange(0,0);let o=new B({transparent:!0,depthTest:!1,depthWrite:!1,vertexColors:!0,side:xe,blending:i.additive===!1?lt:ct});this.registerOpacityMaterial(o,1);let s=new O(this.geometry,o);s.frustumCulled=!1,s.userData[ze]=!0,this.add(s)}get pointCount(){return this.points.length}get isFollowing(){return this.following}stop(){this.following=!1,this.target=null}tick(e){if(super.tick(e),this.freed)return;let t=Math.max(0,e);for(let r of this.points)r.age+=t;for(;this.points.length>0&&this.points[this.points.length-1].age>=this.lifeSec;)this.points.pop();let i=this.target;i&&i.isDisposed?this.stop():i&&this.following&&this.sample(i),this.rebuild(),!this.following&&this.points.length===0&&(this.freed=!0,this.queueFree())}sample(e){e.updateWorldMatrix(!0,!1),e.getWorldPosition(this.scratchWorld),this.updateWorldMatrix(!0,!1);let t=this.worldToLocal(this.scratchWorld);for(this.points.unshift({x:t.x,y:t.y,age:0});this.points.length>this.maxPoints;)this.points.pop()}rebuild(){let e=this.points.length;if(e<2){this.geometry.setDrawRange(0,0);return}let t=0,i=1;for(let r=0;r<e;r++){let o=this.points[r],s=this.points[r-1]??o,a=this.points[r+1]??o,l=s.x-a.x,c=s.y-a.y,u=Math.hypot(l,c);u>aE&&(t=-c/u,i=l/u);let h=e>1?r/(e-1):0,d=1-h,p=this.halfWidth*d,f=Math.max(0,1-o.age/this.lifeSec)*d;this.sampleRamp(h);let m=r*2;this.positionAttribute.setXYZ(m,o.x+t*p,o.y+i*p,0),this.positionAttribute.setXYZ(m+1,o.x-t*p,o.y-i*p,0),this.colorAttribute.setXYZW(m,this.scratchColor.r,this.scratchColor.g,this.scratchColor.b,f),this.colorAttribute.setXYZW(m+1,this.scratchColor.r,this.scratchColor.g,this.scratchColor.b,f)}this.positionAttribute.needsUpdate=!0,this.colorAttribute.needsUpdate=!0,this.geometry.setDrawRange(0,(e-1)*6)}sampleRamp(e){let t=this.palette;if(t.length===1){this.scratchColor.copy(t[0]);return}let i=e*(t.length-1),r=Math.min(t.length-2,Math.floor(i));this.scratchColor.copy(t[r]).lerp(t[r+1],i-r)}};function Ov(n){return typeof n=="object"&&n!==null&&typeof n.x=="number"&&typeof n.y=="number"&&!(n instanceof I)}var mo=class{constructor(e){this.scene=e}scene;transientCounter=0;warned=new Set;shake(e,t={}){if(typeof e=="string"){let o=e.toLowerCase();if(o==="camera2d"){let s=this.scene.getActiveCamera2D();return s?(s.shake(t),null):(this.warnOnce("camera2d","juice.shake('camera2d') found no active Camera2D \u2014 nothing shook. Add a Camera2D to the scene, or shake a node instead."),null)}if(o==="camera"&&!this.scene.getActiveCamera()){let s=this.scene.getActiveCamera2D();if(s)return s.shake(t),null}}let i=this.resolveNode(e);if(!i)return null;let r=i.getComponent(_t);return r||(r=new _t("core:Shake","core:Shake"),r.config.playOnStart=!1,r.config.triggerEvent="",i.addComponent(r)),r.play(t),r}punchScale(e,t={}){let i=this.resolveNode(e);if(!i)return null;let r=i.getComponent(ni);return r||(r=new ni("core:PunchScale","core:PunchScale"),r.config.playOnStart=!1,r.config.triggerEvent="",i.addComponent(r)),r.play(t),r}popIn(e,t={}){let i=this.resolveNode(e);if(!i)return null;let r=i.getComponent(oi);return r||(r=new oi("core:PopIn","core:PopIn"),r.config.playOnStart=!1,r.config.triggerEvent="",i.addComponent(r)),r.play(t),r}flash(e={}){this.scene.flash(e)}burst(e,t={}){let i=this.resolveAnchorNode(e,"burst");if(i===void 0)return null;let r=this.resolve2DHost(i);if(!r)return console.warn("[JuiceApi] burst: the scene has no 2D node to host the effect."),null;let o=new uo({id:this.nextTransientId("burst"),name:"JuiceBurst"},t);r.adoptChild(o);let s=this.resolveHostLocalPoint(r,i,e);return o.position.set(s.x,s.y,0),o}floatText(e,t={}){let i=typeof e=="string"?e:String(e??"");if(i.length===0)return null;let r=t.at===void 0?null:this.resolveAnchorNode(t.at,"floatText");if(r===void 0)return null;let o=this.resolve2DHost(r);if(!o)return console.warn("[JuiceApi] floatText: the scene has no 2D node to host the popup."),null;let s=new ho({id:this.nextTransientId("float-text"),name:"JuiceFloatText"},i,t);if(o.adoptChild(s),t.at!==void 0){let a=this.resolveHostLocalPoint(o,r,t.at);s.position.set(a.x,a.y,0)}return s}trail(e,t={}){let i=this.resolveNode(e);if(!i)return null;let r=this.resolve2DHost(i);if(!r)return console.warn("[JuiceApi] trail: the scene has no 2D node to host the ribbon."),null;let o=new po({id:this.nextTransientId("trail"),name:"JuiceTrail"},i,t);return r.adoptChild(o),o}resolveAnchorNode(e,t){if(Ov(e))return null;let i=this.resolveNode(e);if(!i){console.warn(`[JuiceApi] ${t}: target "${String(e)}" not found.`);return}return i}resolve2DHost(e){if(e){let r=null,o=e;for(;o;)o instanceof C&&(r=o),o=o.parent;if(r)return r}let t=null,i=null;for(let r of this.scene.getRootNodes())r instanceof C&&(i=r,r.isCanvasLayer||(t=r));return t??i}resolveHostLocalPoint(e,t,i){let r=new S;return t?(t.updateWorldMatrix(!0,!1),t.getWorldPosition(r)):Ov(i)&&r.set(i.x,i.y,0),e.updateWorldMatrix(!0,!1),e.worldToLocal(r)}nextTransientId(e){return this.transientCounter+=1,`juice:${e}:${this.transientCounter}`}resolveNode(e){if(e instanceof I)return e;if(typeof e=="string"){let t=e.toLowerCase()==="camera"?this.scene.getActiveCamera():this.scene.findNode(e);return t||this.warnOnce(e,`juice: no node named "${e}" \u2014 the effect did nothing.`),t}return null}warnOnce(e,t){this.warned.has(e)||(this.warned.add(e),console.warn(`[Juice] ${t}`))}};var yl=.3,cE="cubicOut",uE={x:"position.x",y:"position.y",rotation:"rotation.z"},hE=1024,dE=1e-6;function si(n){return typeof n=="number"&&Number.isFinite(n)}function pE(n){return typeof n=="object"&&n!==null}function mE(n,e){let t=e.split(".").filter(r=>r.length>0);if(t.length===0)return null;let i=n;for(let r=0;r<t.length-1;r++){if(typeof i!="object"||i===null)return null;i=i[t[r]]}return typeof i!="object"||i===null?null:{owner:i,key:t[t.length-1]}}function gp(n){return{cancel:()=>{},finished:Promise.resolve(n),isRunning:!1}}var yp=class{constructor(e,t,i,r){this.target=e;this.props=t;this.warn=r;let o=si(i.durationSec)?i.durationSec:yl;this.duration=Math.max(0,o),this.ease=i.ease??cE,this.yoyo=i.yoyo===!0;let s=si(i.repeat)?Math.trunc(i.repeat):0;this.totalIterations=s<0?Number.POSITIVE_INFINITY:Math.max(0,s)+1,this.delayRemaining=si(i.delaySec)?Math.max(0,i.delaySec):0,this.onUpdate=i.onUpdate,this.onComplete=i.onComplete,this.finished=new Promise(a=>{this.resolveFinished=a})}target;props;warn;finished;resolveFinished;duration;ease;yoyo;totalIterations;onUpdate;onComplete;channels=[];delayRemaining;elapsed=0;iteration=0;captured=!1;running=!0;get isRunning(){return this.running}cancel(){this.end("cancelled")}advance(e){if(!this.running)return!1;if(this.target instanceof I&&this.target.isDisposed)return this.end("cancelled"),!1;let t=Math.max(0,e);if(this.delayRemaining>0){let c=Math.min(this.delayRemaining,t);if(this.delayRemaining-=c,t-=c,this.delayRemaining>0)return!0}if(!this.captured&&(this.captureChannels(),this.captured=!0,this.channels.length===0))return this.end("completed"),!1;if(this.elapsed+=t,this.duration<=0)return this.applyProgress(1),this.end("completed"),!1;let i=this.duration-dE,r=0;for(;this.elapsed>=i&&this.iteration+1<this.totalIterations&&r<hE;)this.elapsed-=this.duration,this.iteration+=1,r+=1;let o=this.elapsed>=i&&this.iteration+1>=this.totalIterations,s=o?1:Math.min(1,Math.max(0,this.elapsed/this.duration)),l=this.yoyo&&this.iteration%2===1?1-s:s;return this.applyProgress(l),this.onUpdate?.(l),o?(this.end("completed"),!1):!0}applyProgress(e){let t=wt(this.ease,e);for(let i of this.channels)i.owner[i.key]=i.from+(i.to-i.from)*t}end(e){this.running&&(this.running=!1,e==="completed"&&this.onComplete?.(),this.resolveFinished(e))}captureChannels(){let e=this.target instanceof I;for(let[t,i]of Object.entries(this.props))if(i!=null){if(e&&t==="scale"&&si(i)){this.addChannel("scale.x",i),this.addChannel("scale.y",i);continue}if(si(i)){this.addChannel(e?uE[t]??t:t,i);continue}if(pE(i))for(let r of["x","y","z"]){let o=i[r];si(o)&&this.addChannel(`${t}.${r}`,o)}}}addChannel(e,t){let i=mE(this.target,e);if(!i){this.warn(e,`tween: "${e}" is not a property path on the target \u2014 skipped.`);return}let r=i.owner[i.key];if(!si(r)){this.warn(e,`tween: "${e}" is not a finite number on the target (got ${typeof r}) \u2014 skipped.`);return}this.channels.push({owner:i.owner,key:i.key,from:r,to:t})}},bp=class{constructor(e){this.parts=e;this.finished=Promise.all(e.map(t=>t.finished)).then(t=>t.some(i=>i==="cancelled")?"cancelled":"completed")}parts;finished;cancel(){for(let e of this.parts)e.cancel()}get isRunning(){return this.parts.some(e=>e.isRunning)}};function Vv(n){return si(n.opacity)}var fo=class{constructor(e){this.scene=e}scene;active=new Set;warned=new Set;get activeCount(){return this.active.size}to(e,t,i={}){let r=this.resolveTarget(e);if(!r)return gp("cancelled");let o=new yp(r,t,i,(s,a)=>this.warnOnce(s,a));return this.active.add(o),o}fadeIn(e,t=yl){let i=this.resolveTarget(e);if(!i||!Vv(i))return this.warnOpacityless(e,"fadeIn"),gp("cancelled");let r=i.opacity>0?i.opacity:1;return i.visible=!0,i.opacity=0,this.to(i,{opacity:r},{durationSec:t,ease:"quadOut"})}fadeOut(e,t=yl,i={}){let r=this.resolveTarget(e);if(!r||!Vv(r))return this.warnOpacityless(e,"fadeOut"),gp("cancelled");let o=i.hide!==!1;return this.to(r,{opacity:0},{durationSec:t,ease:"quadIn",onComplete:o?()=>{r.visible=!1}:void 0})}crossFade(e,t,i=yl){return new bp([this.fadeOut(e,i),this.fadeIn(t,i)])}killAll(e){if(e===void 0){for(let i of[...this.active])i.cancel();this.active.clear();return}let t=this.resolveTarget(e);if(t)for(let i of[...this.active])i.target===t&&(i.cancel(),this.active.delete(i))}update(e){if(this.active.size!==0)for(let t of[...this.active])t.advance(e)||this.active.delete(t)}cancelAll(){for(let e of[...this.active])e.cancel();this.active.clear(),this.warned.clear()}resolveTarget(e){if(e instanceof I)return e;if(typeof e=="string"){let t=this.scene.findNode(e);return t||(this.warnOnce(e,`tween: no node named "${e}" \u2014 the tween did nothing.`),null)}return typeof e=="object"&&e!==null?e:null}warnOpacityless(e,t){typeof e!="string"&&this.warnOnce(`${t}:no-opacity`,`tween.${t}: the target has no \`opacity\` \u2014 nothing faded.`)}warnOnce(e,t){this.warned.has(e)||(this.warned.add(e),console.warn(`[Tween] ${t}`))}};var bl=["tap","score","bounce","explosion","powerup","win","lose","laser","tick"],fE={tap:[{wave:"sine",freq:880,freqEnd:620,duration:.09,decay:3,gain:.7},{wave:"square",freq:1320,duration:.035,decay:4,gain:.15}],tick:[{wave:"square",freq:2200,freqEnd:1700,duration:.035,decay:5,gain:.35}],bounce:[{wave:"sine",freq:420,freqEnd:140,duration:.18,decay:2.5,gain:.9},{wave:"triangle",freq:840,freqEnd:280,duration:.1,decay:3,gain:.3}],score:[{wave:"square",freq:880,duration:.08,decay:2.5,gain:.35},{wave:"square",freq:1174,start:.06,duration:.08,decay:2.5,gain:.35},{wave:"triangle",freq:1568,start:.12,duration:.18,decay:2,gain:.45}],powerup:[{wave:"square",freq:440,freqEnd:1760,duration:.3,decay:1.2,gain:.35},{wave:"sine",freq:880,freqEnd:3520,duration:.3,decay:1.6,gain:.25}],laser:[{wave:"saw",freq:1800,freqEnd:180,duration:.22,decay:2,gain:.45},{wave:"square",freq:900,freqEnd:90,duration:.22,decay:2.5,gain:.18}],explosion:[{wave:"noise",duration:.55,decay:1.6,gain:.9,lowpassHz:900,attack:.002},{wave:"noise",duration:.12,decay:3,gain:.45,lowpassHz:3500,attack:.001},{wave:"sine",freq:120,freqEnd:40,duration:.45,decay:2,gain:.6}],win:[{wave:"triangle",freq:523,duration:.22,decay:2,gain:.4},{wave:"triangle",freq:659,start:.1,duration:.22,decay:2,gain:.4},{wave:"triangle",freq:784,start:.2,duration:.24,decay:2,gain:.4},{wave:"square",freq:1046,start:.3,duration:.34,decay:1.6,gain:.3}],lose:[{wave:"square",freq:392,duration:.22,decay:2,gain:.3},{wave:"square",freq:311,start:.12,duration:.22,decay:2,gain:.3},{wave:"square",freq:233,start:.24,duration:.3,decay:1.8,gain:.3},{wave:"sine",freq:160,freqEnd:60,start:.24,duration:.4,decay:1.6,gain:.5}]},gE=.02,yE=64,Lv=.9;function Rr(n){return typeof n=="string"&&bl.includes(n)}function Wi(n){let e=typeof n=="number"?n:Number(n);return!Number.isFinite(e)||e<=0?1:Math.min(4,Math.max(.25,e))}var go=class{cache=new Map;get size(){return this.cache.size}getBuffer(e,t,i=1){let r=e.getSampleRate();if(!r||!Number.isFinite(r)||r<=0)return null;let o=Wi(i),s=`${t}|${o.toFixed(2)}|${Math.round(r)}`,a=this.cache.get(s);if(a)return a;let l=null;try{l=this.render(e,t,o,r)}catch(c){return console.warn(`[SfxSynth] Failed to render preset "${t}":`,c),null}if(!l)return null;if(this.cache.size>=yE){let c=this.cache.keys().next();c.done||this.cache.delete(c.value)}return this.cache.set(s,l),l}clear(){this.cache.clear()}render(e,t,i,r){let o=fE[t],s=0;for(let h of o)s=Math.max(s,(h.start??0)+h.duration);let a=Math.max(1,Math.ceil((s+gE)*r)),l=e.createBuffer(a,1);if(!l)return null;let c=l.getChannelData(0);c.fill(0);for(let h of o)bE(c,h,i,r);let u=0;for(let h=0;h<c.length;h++){let d=Math.abs(c[h]);d>u&&(u=d)}if(u>Lv){let h=Lv/u;for(let d=0;d<c.length;d++)c[d]*=h}return l}};function bE(n,e,t,i){let r=Math.max(0,Math.floor((e.start??0)*i)),o=Math.max(1,Math.floor(e.duration*i)),s=e.gain??.7,a=Math.max(1/i,e.attack??.004),l=e.decay??2,c=Math.max(1,(e.freq??440)*t),h=Math.max(1,(e.freqEnd??e.freq??440)*t)/c,d=e.lowpassHz?e.lowpassHz*t:0,p=d>0?1-Math.exp(-2*Math.PI*d/i):1,f=0,m=0;for(let g=0;g<o;g++){let y=r+g;if(y>=n.length)break;let b=g/i,v=g/o,w;if(e.wave==="noise"){let T=Math.random()*2-1;f+=p*(T-f),w=f}else{let T=c*Math.pow(h,v);m+=2*Math.PI*T/i,w=SE(e.wave,m)}let k=Math.min(1,b/a)*Math.pow(Math.max(0,1-v),Math.max(.1,l));n[y]+=w*k*s}}function SE(n,e){switch(n){case"sine":return Math.sin(e);case"square":return Math.sin(e)>=0?1:-1;case"saw":{let t=e/(Math.PI*2)%1;return 2*(t<0?t+1:t)-1}case"triangle":{let t=e/(Math.PI*2)%1,i=t<0?t+1:t;return 2*Math.abs(2*i-1)-1}}}var yo=class{constructor(e){this.scene=e}scene;sfxSynth=null;async play(e,t={}){let i=this.scene.getAssetLoader();if(!i||!this.scene.getAudioService())return null;let r=await i.loadAudio(e),o=this.scene.getAudioService();return o?o.play(r,{...t,resourcePath:e,sizeBytes:i.getAudioMetadata(e)?.sizeBytes}):null}sfx(e,t={}){let i=this.scene.getAudioService();if(!i)return null;if(!Rr(e))return console.warn(`[AudioApi] sfx: unknown preset "${String(e)}".`),null;let r=Wi(t.pitch);this.sfxSynth??=new go;let o=this.sfxSynth.getBuffer(i,e,r);if(!o)return null;let s=typeof t.volume=="number"?t.volume:1;return i.play(o,{bus:"sfx",label:`sfx:${e}`,volume:Math.min(1,Math.max(0,Number.isFinite(s)?s:1))})}setBusVolume(e,t,i){this.scene.getAudioService()?.setBusVolume(e,t,i)}getBusVolume(e){return this.scene.getAudioService()?.getBusVolume(e)??1}applySnapshot(e,t){this.scene.getAudioService()?.applySnapshot(e,t)}resetSnapshot(e){this.scene.getAudioService()?.resetSnapshot(e)}registerSnapshot(e){this.scene.getAudioService()?.registerSnapshot(e)}getActiveSnapshotName(){return this.scene.getAudioService()?.getActiveSnapshotName()??"default"}stopAll(){this.scene.getAudioService()?.stopAll()}};function Ct(n,e,t){return n+(e-n)*t}function _v(n){let e=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.exec(n.trim());if(!e)return null;let t=e[1];return t.length===3&&(t=t.split("").map(i=>i+i).join("")),[parseInt(t.slice(0,2),16),parseInt(t.slice(2,4),16),parseInt(t.slice(4,6),16)]}function vE(n,e,t){let i=o=>Math.min(255,Math.max(0,Math.round(o))),r=o=>i(o).toString(16).padStart(2,"0");return`#${r(n)}${r(e)}${r(t)}`}function Fv(n,e,t,i){switch(n){case"number":return Ct(e,t,i);case"vector2":{let r=e,o=t;return[Ct(r[0],o[0],i),Ct(r[1],o[1],i)]}case"vector3":case"euler":{let r=e,o=t;return[Ct(r[0],o[0],i),Ct(r[1],o[1],i),Ct(r[2],o[2],i)]}case"color":{let r=_v(e),o=_v(t);return!r||!o?e:vE(Ct(r[0],o[0],i),Ct(r[1],o[1],i),Ct(r[2],o[2],i))}case"boolean":case"string":return e}}function zv(n,e){let t=n.keys;if(t.length===0)return null;if(e<=t[0].time)return t[0].value;let i=t[t.length-1];if(e>=i.time)return i.value;let r=0,o=t.length-1;for(;o-r>1;){let u=r+o>>1;t[u].time<=e?r=u:o=u}let s=t[r],a=t[o];if(s.easing==="step"||n.valueType==="boolean"||n.valueType==="string")return s.value;let l=a.time-s.time,c=l>0?(e-s.time)/l:1;return Fv(n.valueType,s.value,a.value,wt(s.easing,c))}function vp(n,e,t,i={}){if(n.length===0)return[];let r=i.includeStart===!0,o=(s,a,l,c)=>(c?s>=a:s>a)&&s<=l;if(i.wrapDuration!==void 0&&t<e){let s=i.wrapDuration;return n.filter(a=>o(a.time,e,s,r)||o(a.time,0,t,!0))}return n.filter(s=>o(s.time,e,t,r))}function wp(n,e,t,i={}){return n.enabled?vp(n.keys,e,t,i):[]}function xp(n,e,t,i={}){return n.enabled?vp(n.keys,e,t,i):[]}function Pp(n,e){e.signal.length!==0&&n.emit(e.signal,...sn(e.args))}function Uv(n,e){switch(n){case"vector2":{let t=e;return{x:t[0],y:t[1]}}case"vector3":case"euler":{let t=e;return{x:t[0],y:t[1],z:t[2]}}default:return e}}function wE(n,e){switch(n){case"number":return typeof e=="number"&&Number.isFinite(e)?e:null;case"boolean":return typeof e=="boolean"?e:null;case"string":case"color":return typeof e=="string"?e:null;case"vector2":{let t=e;return t&&typeof t.x=="number"&&typeof t.y=="number"?[t.x,t.y]:null}case"vector3":case"euler":{let t=e;return t&&typeof t.x=="number"&&typeof t.y=="number"&&typeof t.z=="number"?[t.x,t.y,t.z]:null}}}function Sp(n,e){let t=e.trim();return t.length===0||t==="."?n:n.findByPath(t)}function kp(n,e){let t=[],i=[],r=[],o=[];for(let s of e.tracks){if(s.kind==="audio"){i.push(s);continue}if(s.kind==="event"){let c=Sp(n,s.targetPath);if(!c){o.push(`${s.targetPath||"."} \u2192 ${s.name} (node not found)`);continue}r.push({track:s,node:c});continue}let a=Sp(n,s.targetPath);if(!a){o.push(`${s.targetPath||"."} \u2192 ${s.property} (node not found)`);continue}let l=Ot(ke(a),s.property);if(!l){o.push(`${s.targetPath||"."} \u2192 ${s.property} (property not found)`);continue}t.push({track:s,node:a,propDef:l})}return{clip:e,entries:t,audioTracks:i,eventEntries:r,missingTargets:o}}function Hi(n,e){let t=Math.min(Math.max(0,e),n.clip.duration);for(let i of n.entries){if(!i.track.enabled)continue;let r=zv(i.track,t);r!==null&&i.propDef.setValue(i.node,Uv(i.track.valueType,r))}}var Hv=.01,Ap=1,xE=["number","vector2","vector3","euler","color","boolean","string"];function qv(n){return typeof n=="string"&&xE.includes(n)}function Gv(){return`track-${Date.now().toString(36)}-${Math.random().toString(36).slice(2,8)}`}function qi(n,e){let t=typeof n=="number"?n:Number(n);return Number.isFinite(t)?t:e}function ai(n,e){if(typeof n!="string")return e;let t=n.trim();return t.length>0?t:e}function Tp(n,e){return typeof n=="boolean"?n:e}function PE(n){return typeof n=="string"&&/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/.test(n.trim())?n.trim().toLowerCase():"#ffffff"}function Wv(n,e){let t=Array.isArray(n)?n:[],i=[];for(let r=0;r<e;r+=1)i.push(qi(t[r],0));return i}function jv(n,e){switch(n){case"number":return qi(e,0);case"boolean":return Tp(e,!1);case"string":return typeof e=="string"?e:String(e??"");case"color":return PE(e);case"vector2":return Wv(e,2);case"vector3":case"euler":return Wv(e,3)}}function kE(n,e){let t=typeof n=="object"&&n!==null?n:{},i=t.easing;return{time:Math.max(0,qi(t.time,0)),value:jv(e,t.value),easing:Ue(i)?i:"linear"}}function AE(n){let e=typeof n=="object"&&n!==null?n:{};return{time:Math.max(0,qi(e.time,0)),audioPath:ai(e.audioPath,""),volume:Math.min(1,Math.max(0,qi(e.volume,1)))}}function TE(n){let e=typeof n=="object"&&n!==null?n:{};return{time:Math.max(0,qi(e.time,0)),signal:ai(e.signal,""),args:typeof e.args=="string"?e.args:""}}function CE(n,e){let t=typeof n=="object"&&n!==null?n:{},i=ai(t.id,"");(i.length===0||e.has(i))&&(i=Gv()),e.add(i);let r=Tp(t.enabled,!0),o=Array.isArray(t.keys)?t.keys:[];if(t.kind==="audio"){let u=o.map(AE).filter(h=>h.audioPath.length>0);return u.sort((h,d)=>h.time-d.time),{id:i,kind:"audio",name:ai(t.name,"Audio"),enabled:r,keys:u}}if(t.kind==="event"){let u=o.map(TE).filter(d=>d.signal.length>0);u.sort((d,p)=>d.time-p.time);let h=typeof t.targetPath=="string"?t.targetPath.trim():"";return{id:i,kind:"event",name:ai(t.name,"Events"),targetPath:h==="."?"":h,enabled:r,keys:u}}let s=ai(t.property,"");if(s.length===0)return null;let a=qv(t.valueType)?t.valueType:"number",l=typeof t.targetPath=="string"?t.targetPath.trim():"",c=o.map(u=>kE(u,a));return c.sort((u,h)=>u.time-h.time),{id:i,kind:"property",targetPath:l==="."?"":l,property:s,valueType:a,enabled:r,keys:c}}function ME(n,e,t){let i=typeof n=="object"&&n!==null?n:{},r=ai(i.name,`clip-${e+1}`);if(t.has(r)){let l=2;for(;t.has(`${r}-${l}`);)l+=1;r=`${r}-${l}`}t.add(r);let o=new Set,a=(Array.isArray(i.tracks)?i.tracks:[]).map(l=>CE(l,o)).filter(l=>l!==null);return{name:r,duration:Math.max(Hv,qi(i.duration,Ap)),loop:Tp(i.loop,!1),tracks:a}}function Sl(n){let e=typeof n=="object"&&n!==null?n:{},t=Array.isArray(e.clips)?e.clips:[],i=new Set;return{version:ai(e.version,"1.0.0"),clips:t.map((r,o)=>ME(r,o,i))}}function Cp(){return{version:"1.0.0",clips:[]}}function DE(n){return{name:n,duration:Ap,loop:!1,tracks:[]}}function Gi(n,e){return!n||n.clips.length===0?null:e?n.clips.find(t=>t.name===e)??null:n.clips[0]??null}var li=class extends V{cachedSet=null;activeClipName=null;binding=null;time=0;playing=!1;paused=!1;pendingStartAudio=!1;missingTargetsWarned=!1;constructor(e,t){super(e,t),this.config={autoplay:"",speed:1,animations:Cp()}}static getPropertySchema(){return{nodeType:"AnimationPlayerBehavior",properties:[{name:"autoplay",type:"string",ui:{label:"Autoplay Clip",description:"Clip name to play automatically on start (empty = none)",group:"Animation"},getValue:e=>e.getAutoplay(),setValue:(e,t)=>{e.config.autoplay=typeof t=="string"?t.trim():""}},{name:"speed",type:"number",ui:{label:"Speed",description:"Playback speed multiplier",group:"Animation",min:0,step:.1,precision:2},getValue:e=>e.getSpeed(),setValue:(e,t)=>{let i=typeof t=="number"?t:Number(t);e.config.speed=Number.isFinite(i)?Math.max(0,i):1}},{name:"animations",type:"object",ui:{label:"Animations",group:"Animation",hidden:!0},getValue:e=>e.getAnimationSet(),setValue:(e,t)=>{let i=e;i.config.animations=Sl(t),i.invalidateBindings()}}],groups:{Animation:{label:"Animation",expanded:!0}}}}onStart(){this.warmUpAudio();let e=this.getAutoplay();e.length>0&&this.play(e)}onUpdate(e){if(!this.playing||this.paused)return;let t=this.getActiveClip();if(!t){this.playing=!1;return}let i=this.ensureBinding(t),r=this.pendingStartAudio;this.pendingStartAudio=!1;let o=this.time,s=o+e*this.getSpeed();if(s>=t.duration){t.loop&&t.duration>0?(this.fireTimeWindow(i,o,t.duration,r),s=s%t.duration,this.time=s,Hi(i,s),this.fireTimeWindow(i,0,s,!0)):(this.fireTimeWindow(i,o,t.duration,r),this.time=t.duration,Hi(i,t.duration),this.playing=!1,this.node?.emit("animation_finished",t.name));return}this.time=s,Hi(i,s),this.fireTimeWindow(i,o,s,r)}onDetach(){this.playing=!1,this.paused=!1,this.binding=null,super.onDetach()}play(e){let t=this.getAnimationSet(),i=e??(this.getAutoplay()||void 0),r=Gi(t,i)??(i?null:t.clips[0]??null);return r?(this.activeClipName=r.name,this.binding=null,this.time=0,this.playing=!0,this.paused=!1,this.pendingStartAudio=!0,this.node?.emit("animation_started",r.name),!0):!1}stop(){this.playing=!1,this.paused=!1,this.pendingStartAudio=!1}finish(e=!0){if(!this.playing)return;let t=this.getActiveClip();if(!t){this.playing=!1,this.paused=!1,this.pendingStartAudio=!1;return}if(t.loop){this.playing=!1,this.paused=!1,this.pendingStartAudio=!1,this.node?.emit("animation_finished",t.name);return}let i=this.ensureBinding(t);e&&this.fireTimeWindow(i,this.time,t.duration,this.pendingStartAudio),this.pendingStartAudio=!1,this.time=t.duration,Hi(i,t.duration),this.playing=!1,this.paused=!1,this.node?.emit("animation_finished",t.name)}pause(){this.playing&&(this.paused=!0)}resume(){this.paused=!1}seek(e,t=!0){let i=this.getActiveClip();i&&(this.time=Math.min(Math.max(0,e),i.duration),t&&Hi(this.ensureBinding(i),this.time))}get currentTime(){return this.time}get duration(){return this.getActiveClip()?.duration??0}get isPlaying(){return this.playing&&!this.paused}get isPaused(){return this.playing&&this.paused}get currentClipName(){return this.activeClipName}getAnimationSet(){return this.cachedSet||(this.cachedSet=Sl(this.config.animations)),this.cachedSet}invalidateBindings(){this.cachedSet=null,this.binding=null,this.missingTargetsWarned=!1}getActiveClip(){return this.activeClipName?Gi(this.getAnimationSet(),this.activeClipName):null}ensureBinding(e){if(!this.binding||this.binding.clip!==e){let t=this.node;if(!t)return{clip:e,entries:[],audioTracks:[],eventEntries:[],missingTargets:[]};this.binding=kp(t,e),this.binding.missingTargets.length>0&&!this.missingTargetsWarned&&(this.missingTargetsWarned=!0,console.warn(`[AnimationPlayer] Clip "${e.name}" has unresolved tracks on node "${t.name}":`,this.binding.missingTargets))}return this.binding}fireTimeWindow(e,t,i,r){for(let o of e.audioTracks){let s=wp(o,t,i,{wrapDuration:e.clip.duration,includeStart:r});for(let a of s)this.playAudioKey(a)}for(let o of e.eventEntries){let s=xp(o.track,t,i,{wrapDuration:e.clip.duration,includeStart:r});for(let a of s)Pp(o.node,a)}}async playAudioKey(e){let t=this.scene;if(!t||e.audioPath.length===0)return;let i=t.getAssetLoader(),r=t.getAudioService();if(!(!i||!r))try{let o=await i.loadAudio(e.audioPath),s=t.getAudioService();if(!s)return;let a=i.getAudioMetadata(e.audioPath);s.play(o,{resourcePath:e.audioPath,sizeBytes:a?.sizeBytes,volume:e.volume})}catch(o){console.warn(`[AnimationPlayer] Failed to play audio key "${e.audioPath}":`,o)}}warmUpAudio(){let e=this.scene?.getAssetLoader();if(!e)return;let t=new Set;for(let i of this.getAnimationSet().clips)for(let r of i.tracks)if(r.kind==="audio")for(let o of r.keys)o.audioPath.length>0&&t.add(o.audioPath);for(let i of t)e.loadAudio(i).catch(r=>{console.warn(`[AnimationPlayer] Failed to preload audio "${i}":`,r)})}getAutoplay(){let e=this.config.autoplay;return typeof e=="string"?e.trim():""}getSpeed(){let e=this.config.speed,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:1}};var ji=class extends V{currentActiveId=null;blending=!1;blendElapsed=0;blendDuration=0;blendEasing="linear";pendingBlendOverride=null;blendFromPos=new S;blendFromQuat=new F;blendFromFov=60;blendFromOrtho=5;targetPos=new S;targetQuat=new F;outPos=new S;outQuat=new F;parentQuat=new F;localPos=new S;constructor(e,t){super(e,t),this.config={blendEnabled:!0}}static getPropertySchema(){return{nodeType:"CameraBrainBehavior",properties:[{name:"blendEnabled",type:"boolean",ui:{label:"Blend On Switch",description:"Ease between cameras on activation. Off = hard cut.",group:"Camera Brain"},getValue:e=>e.config.blendEnabled!==!1,setValue:(e,t)=>{e.config.blendEnabled=!!t}}],groups:{"Camera Brain":{label:"Camera Brain",expanded:!0}}}}onStart(){this.currentActiveId=null,this.blending=!1,this.pendingBlendOverride=null}overrideNextBlend(e,t){this.pendingBlendOverride={duration:Math.max(0,e),easing:t}}onUpdate(e){let t=this.node;if(!(t instanceof pe))return;let i=this.collectVirtualCameras();for(let a of i)a.solve(e);let r=this.pickActive(i);if(!r){this.currentActiveId=null,this.blending=!1;return}r.nodeId!==this.currentActiveId&&(this.beginBlend(t,r),this.currentActiveId=r.nodeId),r.getDesiredWorldPosition(this.targetPos),r.getDesiredWorldQuaternion(this.targetQuat);let o=r.fov,s=r.orthographicSize;if(this.blending){this.blendElapsed+=Math.max(0,e);let a=this.blendDuration>0?this.blendElapsed/this.blendDuration:1,l=wt(this.blendEasing,a);this.outPos.copy(this.blendFromPos).lerp(this.targetPos,l),this.outQuat.copy(this.blendFromQuat).slerp(this.targetQuat,l);let c=this.blendFromFov+(o-this.blendFromFov)*l,u=this.blendFromOrtho+(s-this.blendFromOrtho)*l;this.applyToHost(t,this.outPos,this.outQuat,c,u),a>=1&&(this.blending=!1)}else this.applyToHost(t,this.targetPos,this.targetQuat,o,s)}beginBlend(e,t){let i=this.pendingBlendOverride;this.pendingBlendOverride=null;let r=this.config.blendEnabled!==!1,o=i?i.duration:r?t.blendDuration:0;if(o<=0){this.blending=!1;return}e.getWorldPosition(this.blendFromPos),e.getWorldQuaternion(this.blendFromQuat),this.blendFromFov=e.fov,this.blendFromOrtho=e.orthographicSize,this.blendElapsed=0,this.blendDuration=o,this.blendEasing=i?.easing??t.blendEasing,this.blending=!0}applyToHost(e,t,i,r,o){this.localPos.copy(t),e.parent?(e.parent.updateWorldMatrix(!0,!1),e.parent.worldToLocal(this.localPos),e.parent.getWorldQuaternion(this.parentQuat),this.parentQuat.invert().multiply(i),e.quaternion.copy(this.parentQuat)):e.quaternion.copy(i),e.position.copy(this.localPos),e.fov=r,e.orthographicSize=o}pickActive(e){let t=null;for(let i of e)i.visible&&(t===null||i.priority>t.priority)&&(t=i);return t}collectVirtualCameras(){let e=this.scene?.getRootNodes()??this.rootsFromHost(),t=[],i=[...e];for(;i.length>0;){let r=i.pop();if(r){r instanceof xt&&t.push(r);for(let o of r.children)o instanceof I&&i.push(o)}}return t}rootsFromHost(){let e=this.node;for(;e?.parentNode;)e=e.parentNode;return e?[e]:[]}};var EE=["Escape","Space","Enter"],NE=.1,IE=.4,RE=.45;function BE(n){let e=typeof n.letterboxSize=="number"&&Number.isFinite(n.letterboxSize)?Math.max(0,Math.min(RE,n.letterboxSize)):NE,t=typeof n.letterboxEnterSec=="number"&&Number.isFinite(n.letterboxEnterSec)?Math.max(0,n.letterboxEnterSec):IE;return{skippableAfter:typeof n.skippableAfter=="number"&&Number.isFinite(n.skippableAfter)?Math.max(0,n.skippableAfter):null,blendDuration:typeof n.blendDuration=="number"&&Number.isFinite(n.blendDuration)?Math.max(0,n.blendDuration):null,blendEasing:n.blendEasing,letterbox:n.letterbox!==!1,letterboxSize:e,letterboxEnterSec:t,lockInput:n.lockInput!==!1,fireSkippedEvents:n.fireSkippedEvents!==!1,skipKeys:Array.isArray(n.skipKeys)&&n.skipKeys.length>0?n.skipKeys.slice():EE}}function OE(n){let e=n.getComponent(li);if(e)return e;let t=$v(n);for(;t.length>0;){let i=t.pop();if(!i)continue;let r=i.getComponent(li);if(r)return r;t.push(...$v(i))}return null}function $v(n){return n.children.filter(e=>e instanceof I)}function VE(n,e){let t=n.getAnimationSet();if(e)return Gi(t,e);let i=typeof n.config.autoplay=="string"?n.config.autoplay.trim():"";return(i?Gi(t,i):null)??t.clips[0]??null}var Mp=class{constructor(e,t,i,r,o){this.scene=e;this.hostNode=t;this.player=i;this.clip=r;this.opts=o;this.done=new Promise(s=>{this.resolveDone=s})}scene;hostNode;player;clip;opts;done;resolveDone;settled=!1;input=null;holdsLock=!1;topBar=null;bottomBar=null;barAnimId=null;barT=0;startedAtMs=0;finishConnected=!1;get isActive(){return!this.settled}start(){if(this.opts.lockInput){let e=this.scene.getInputService();e&&(e.lock(),this.input=e,this.holdsLock=!0)}this.opts.letterbox&&(this.ensureBars(),this.animateBars(0,1,this.opts.letterboxEnterSec)),this.startedAtMs=performance.now(),this.attachSkipListeners(),this.armBlendOverride(),this.clip.loop?console.warn(`[Cutscene] clip "${this.clip.name}" loops \u2014 cutscene will only end via skip()/stop().`):(this.hostNode.connect("animation_finished",this,this.onFinished),this.finishConnected=!0),this.player.play(this.clip.name)||this.hardSettle("stopped")}skip(){this.settled||(this.detachFinishSignal(),this.player.finish(this.opts.fireSkippedEvents),this.settleSoft("skipped"))}stop(){this.hardSettle("stopped")}forceStop(e){this.hardSettle(e)}onSkipPointer=()=>{this.onSkipGesture()};onSkipKey=e=>{this.opts.skipKeys.includes(e.code)&&this.onSkipGesture()};onSkipGesture(){this.opts.skippableAfter!==null&&(performance.now()-this.startedAtMs<this.opts.skippableAfter*1e3||this.skip())}attachSkipListeners(){this.scene.getCanvas()?.addEventListener("pointerdown",this.onSkipPointer),typeof window<"u"&&window.addEventListener("keydown",this.onSkipKey)}detachSkipListeners(){this.scene.getCanvas()?.removeEventListener("pointerdown",this.onSkipPointer),typeof window<"u"&&window.removeEventListener("keydown",this.onSkipKey)}onFinished=(...e)=>{e[0]===this.clip.name&&this.settleSoft("finished")};detachFinishSignal(){this.finishConnected&&(this.hostNode.disconnect("animation_finished",this,this.onFinished),this.finishConnected=!1)}armBlendOverride(){if(this.opts.blendDuration===null)return;(this.scene.getActiveCamera()?.getComponent(ji)??null)?.overrideNextBlend(this.opts.blendDuration,this.opts.blendEasing)}ensureBars(){let e=this.scene.getCanvas()?.parentElement;if(!e){console.warn("[Cutscene] Cannot create letterbox bars: canvas has no parent element.");return}getComputedStyle(e).position==="static"&&(e.style.position="relative");let i=["position: absolute","left: 0","right: 0","height: 0%","background: #000","pointer-events: none","z-index: 9998"];this.topBar=document.createElement("div"),this.topBar.style.cssText=[...i,"top: 0"].join("; "),this.bottomBar=document.createElement("div"),this.bottomBar.style.cssText=[...i,"bottom: 0"].join("; "),e.appendChild(this.topBar),e.appendChild(this.bottomBar)}animateBars(e,t,i,r){if(this.cancelBarAnim(),!this.topBar||!this.bottomBar){this.barT=t,r?.();return}let o=Math.max(0,i*1e3);if(o===0){this.setBarHeight(t),r?.();return}let s=performance.now(),a=l=>{let c=Math.min((l-s)/o,1);this.setBarHeight(e+(t-e)*c),c<1?this.barAnimId=requestAnimationFrame(a):(this.barAnimId=null,r?.())};this.barAnimId=requestAnimationFrame(a)}setBarHeight(e){this.barT=e;let t=`${(this.opts.letterboxSize*e*100).toFixed(4)}%`;this.topBar&&(this.topBar.style.height=t),this.bottomBar&&(this.bottomBar.style.height=t)}cancelBarAnim(){this.barAnimId!==null&&(cancelAnimationFrame(this.barAnimId),this.barAnimId=null)}removeBars(){this.cancelBarAnim(),this.topBar?.remove(),this.bottomBar?.remove(),this.topBar=null,this.bottomBar=null}settleSoft(e){this.settled||(this.settled=!0,this.armBlendOverride(),this.detachSkipListeners(),this.detachFinishSignal(),this.releaseLock(),this.animateBars(this.barT,0,this.opts.letterboxEnterSec,()=>this.removeBars()),this.resolveDone(e))}hardSettle(e){this.settled||(this.settled=!0,this.player.stop(),this.resolveDone(e)),this.teardownResources()}teardownResources(){this.removeBars(),this.detachSkipListeners(),this.detachFinishSignal(),this.releaseLock()}releaseLock(){this.holdsLock&&(this.input?.unlock(),this.holdsLock=!1)}};function Yv(){return{done:Promise.resolve("stopped"),isActive:!1,skip:()=>{},stop:()=>{}}}var bo=class{constructor(e){this.scene=e}scene;active=null;playCinematic(e,t={}){this.active?.stop(),this.active=null;let i=this.scene.findNode(e),r=i?OE(i):null,o=r?.node??null;if(!i||!r||!o)return console.warn(`[Cutscene] playCinematic: no AnimationPlayer found for "${e}".`),Yv();let s=VE(r,t.clip);if(!s)return console.warn(`[Cutscene] playCinematic: clip "${t.clip??"(default)"}" not found on "${e}".`),Yv();let a=new Mp(this.scene,o,r,s,BE(t));return this.active=a,a.start(),a}stopAll(e="stopped"){this.active?.forceStop(e),this.active=null}dispose(){this.stopAll("stopped"),this.active=null}};var LE="res://locales/{locale}.json";function _E(n,e){return n.replace(/\{(\w+)\}/g,(t,i)=>i in e?String(e[i]):t)}function Kv(n){if(!n||typeof n!="object")return{};let e={};for(let[t,i]of Object.entries(n))typeof i=="string"&&(e[t]=i);return e}function Xv(n){return{locale:n.locale,strings:Kv(n.strings),sprites:Kv(n.sprites),meta:n.meta}}var $i=class{config={defaultLocale:"en"};resources=null;tables=new Map;currentLocale="en";listeners=new Set;configure(e){this.config={...e},this.currentLocale=e.defaultLocale}attachResources(e){this.resources=e}get locale(){return this.currentLocale}get locales(){return this.config.locales??[...this.tables.keys()]}get fallbackLocale(){return this.config.fallbackLocale??this.config.defaultLocale}async setLocale(e){!this.tables.has(e)&&this.resources&&await this.loadTable(e),this.currentLocale=e,this.notify()}setTable(e){this.tables.set(e.locale,Xv(e)),this.notify()}async loadTable(e){if(!this.resources)return;let t=(this.config.tablePathTemplate??LE).replace("{locale}",e);try{let i=await this.resources.readText(t),r=JSON.parse(i);this.tables.set(e,Xv({locale:e,strings:r.strings,sprites:r.sprites,meta:r.$meta??r.meta}))}catch(i){console.warn(`[Localization] Failed to load locale "${e}" from ${t}`,i),this.tables.set(e,{locale:e,strings:{},sprites:{}})}}tr(e,t){if(!e)return"";let i=this.lookupString(e)??e;return t?_E(i,t):i}lookupString(e){let t=this.tables.get(this.currentLocale)?.strings[e];return t||this.tables.get(this.fallbackLocale)?.strings[e]||void 0}trPlural(e,t,i){let r={count:t,...i},o=this.pluralCategory(t);return this.has(`${e}.${o}`)?this.tr(`${e}.${o}`,r):this.has(`${e}.other`)?this.tr(`${e}.other`,r):this.tr(e,r)}pluralRulesCache=new Map;pluralCategory(e){let t=this.pluralRulesCache.get(this.currentLocale);if(t===void 0){try{t=new Intl.PluralRules(this.currentLocale)}catch{t=null}this.pluralRulesCache.set(this.currentLocale,t)}return t?t.select(e):"other"}trSprite(e){if(!e)return null;let t=this.tables.get(this.currentLocale)?.sprites[e];return t||this.tables.get(this.fallbackLocale)?.sprites[e]||null}has(e){return this.lookupString(e)!==void 0}onChange(e){return this.listeners.add(e),()=>{this.listeners.delete(e)}}notify(){for(let e of[...this.listeners])try{e()}catch(t){console.error("[Localization] onChange listener threw",t)}}dispose(){this.listeners.clear(),this.tables.clear(),this.resources=null}};var So=class{delegate=null;fadeOverlay=null;fadeAnimationId=null;flashOverlay=null;flashAnimationId=null;juiceApi=null;tweenApi=null;audioApi=null;inertLocalization=null;cutsceneApi=null;collision2dService=null;physics2dService=null;commandRegistry=null;networkService=null;autoloads=null;networkNodeBinder=null;sceneRunning=!1;scratchPointerUnproject=new S;changeScenePromise=null;fallbackGameTime=null;canvas=null;viewportWidth=0;viewportHeight=0;viewportListeners=new Set;setDelegate(e){this.delegate=e,e||(this.sceneRunning=!1,this.networkNodeBinder?.handleSceneStopped())}handleSceneStarted(){this.sceneRunning=!0,this.networkNodeBinder?.reconcile()}attachCanvas(e){this.canvas=e}dispose(){this.cancelFade(),this.cancelFlash(),this.changeScenePromise=null,this.cutsceneApi?.dispose(),this.cutsceneApi=null,this.clearTweens(),this.collision2dService=null,this.commandRegistry?.clear(),this.networkNodeBinder?.dispose(),this.networkNodeBinder=null,this.fadeOverlay?.remove(),this.fadeOverlay=null,this.flashOverlay?.remove(),this.flashOverlay=null,this.canvas=null,this.delegate=null,this.viewportListeners.clear()}get time(){let e=this.delegate?.getGameTime();return e||(this.fallbackGameTime||(this.fallbackGameTime=new zi),this.fallbackGameTime)}get juice(){return this.juiceApi||(this.juiceApi=new mo(this)),this.juiceApi}get tween(){return this.tweenApi||(this.tweenApi=new fo(this)),this.tweenApi}updateTweens(e){this.tweenApi?.update(e)}clearTweens(){this.tweenApi?.cancelAll()}get audio(){return this.audioApi||(this.audioApi=new yo(this)),this.audioApi}get localization(){let e=this.delegate?.getLocalizationService?.()??null;if(e)return e;let t=Ke();return t||(this.inertLocalization??=new $i)}get cutscene(){return this.cutsceneApi||(this.cutsceneApi=new bo(this)),this.cutsceneApi}cancelActiveCutscene(){this.cutsceneApi?.stopAll("stopped")}get commands(){return this.commandRegistry||(this.commandRegistry=new co(()=>this.delegate?.getFrameNumber?.()??0)),this.commandRegistry}clearCommands(){this.commandRegistry?.clear()}get collision2d(){return this.collision2dService||(this.collision2dService=new Xn),this.collision2dService}get physics2d(){return this.physics2dService||(this.physics2dService=new Jn),this.physics2dService}stepPhysics2D(e){this.physics2dService?.step(e)}buildPhysics2DDebugBuffers(){return this.physics2dService?this.physics2dService.buildDebugBuffers():null}interpolatePhysics2D(e){this.physics2dService?.interpolate(e)}clearPhysics2D(){this.physics2dService?.clear(),this.physics2dService=null}get network(){return this.networkService||(this.networkService=new ao),this.networkService}getAutoload(e){return this.autoloads?.get(e)??null}setAutoloads(e){this.autoloads=e}setNetworkService(e){e!==null&&e===this.networkService||(this.networkService=e,this.networkNodeBinder?.dispose(),this.networkNodeBinder=null,e&&this.netNodes)}get netNodes(){return this.networkNodeBinder||(this.networkNodeBinder=new lo({network:this.network,instantiate:(e,t)=>this.instantiate(e,t),isSceneRunning:()=>this.sceneRunning})),this.networkNodeBinder}getPointer2DWorldPosition(e,t){let i=typeof e=="number"?e:null,r=(typeof e=="number"?t:e)??new N,o=this.delegate?.getInputService();if(!o)return null;let s=i===null?o.pointerPosition:o.getPointer(i);if(!s)return null;let a=Math.max(1,o.width),l=Math.max(1,o.height),c=this.delegate?.getUICamera();if(c){let p=s.x/a*2-1,f=-(s.y/l*2-1);return this.scratchPointerUnproject.set(p,f,0).unproject(c),r.set(this.scratchPointerUnproject.x,this.scratchPointerUnproject.y),r}let u=this.delegate?.getLogicalCameraSize(),h=u&&Number.isFinite(u.width)&&u.width>0?u.width:a,d=u&&Number.isFinite(u.height)&&u.height>0?u.height:l;return r.set(s.x/a*h-h/2,d/2-s.y/l*d),r}async instantiate(e,t={}){if(!this.delegate?.instantiatePrefab)throw new Error("[SceneService] instantiate requires a running scene.");let i=null;if(typeof t.parent=="string"){if(i=this.findNode(t.parent),!i)throw new Error(`[SceneService] instantiate: parent "${t.parent}" not found.`)}else i=t.parent??null;return this.delegate.instantiatePrefab(e,i,t.instanceId)}getInputService(){return this.delegate?.getInputService()??null}getCanvas(){return this.canvas}setActiveCamera(e){if(!this.delegate){console.warn("[SceneService] setActiveCamera: no scene delegate.");return}let t=this.delegate.findNodeById(e);if(!t){console.warn(`[SceneService] setActiveCamera: node "${e}" not found.`);return}if(!(t instanceof pe)){console.warn(`[SceneService] setActiveCamera: node "${e}" is not a Camera3D.`);return}t.camera.layers.disableAll(),t.camera.layers.enable(0),this.delegate.setActiveCameraNode(t)}getActiveCamera(){return this.delegate?.getActiveCameraNode()??null}getActiveCamera2D(){return this.delegate?.getActiveCamera2DNode()??null}getRootNodes(){return this.delegate?.getRootNodes()??[]}findNodeById(e){return this.delegate?.findNodeById(e)??null}findNodeByName(e){for(let t of this.getRootNodes()){let i=t.findByName(e);if(i)return i}return null}findNodeByPath(e){let t=e.split("/").map(s=>s.trim()).filter(s=>s.length>0);if(t.length===0)return null;let[i,...r]=t,o=this.getRootNodes().find(s=>s.name===i)??null;return o?r.length===0?o:o.findByPath(r.join("/")):null}findNode(e){return e.includes("/")?this.findNodeByPath(e):this.findNodeById(e)??this.findNodeByName(e)}getNodesInGroup(e){let t=e.trim(),i=[];if(!t)return i;let r=o=>{o.groups.has(t)&&i.push(o);for(let s of o.children)s instanceof I&&r(s)};for(let o of this.getRootNodes())r(o);return i}callGroup(e,t,...i){let r=this.getNodesInGroup(e),o=0;for(let s of r)for(let a of[...s.components]){let l=Reflect.get(a,t);typeof l=="function"&&(l.apply(a,i),o+=1)}return r.length>0&&o===0&&console.warn(`[SceneService] callGroup("${e}", "${t}"): no component of the ${r.length} node(s) in the group has that method.`),o}getUICamera(){return this.delegate?.getUICamera()??null}getAudioService(){return this.delegate?.getAudioService()??null}getAssetLoader(){return this.delegate?.getAssetLoader()??null}getResourceManager(){return this.delegate?.getResourceManager()??null}getECSService(){return this.delegate?.getECSService()??null}raycastViewport(e,t){return this.delegate?.raycastViewport(e,t)??null}reportFrameProfilerActivities(e){this.delegate?.reportFrameProfilerActivities(e)}setViewportSize(e,t){let i=Number.isFinite(e)?Math.max(0,Math.round(e)):0,r=Number.isFinite(t)?Math.max(0,Math.round(t)):0;if(this.viewportWidth===i&&this.viewportHeight===r)return;this.viewportWidth=i,this.viewportHeight=r;let o=this.getViewportInfo();for(let s of this.viewportListeners)s(o)}getViewportInfo(){let e=this.resolveViewportDimensions(),t=e.width>=e.height?"landscape":"portrait";return{width:e.width,height:e.height,orientation:t,aspect:e.height>0?e.width/e.height:1}}getViewportSize(){let e=this.getViewportInfo();return{width:e.width,height:e.height}}getLogicalCameraSize(){return this.delegate?.getLogicalCameraSize()??this.getViewportSize()}getOrientation(){return this.getViewportInfo().orientation}isPortrait(){return this.getOrientation()==="portrait"}isLandscape(){return this.getOrientation()==="landscape"}onViewportChanged(e){return this.viewportListeners.add(e),e(this.getViewportInfo()),()=>{this.viewportListeners.delete(e)}}switchCameraWithFade(e,t=.5,i=.5,r){this.fadeToBlack(t,()=>{this.setActiveCamera(e),this.fadeFromBlack(i,r)})}async changeScene(e,t={}){let i=this.delegate;if(!i)throw new Error("[SceneService] changeScene: no scene is running.");if(this.changeScenePromise)return console.warn("[SceneService] changeScene ignored: a scene change is already in progress."),this.changeScenePromise;let r=t.transition??"fade",o=Math.max(0,t.durationSec??.3),s=async()=>{r==="fade"&&await this.awaitFade("out",o);try{await i.loadAndStartScene(e)}catch(a){throw console.error("[SceneService] changeScene failed:",a),r==="fade"&&this.fadeFromBlack(o),a}t.onLoaded?.(),r==="fade"&&await this.awaitFade("in",o)};return this.changeScenePromise=s().finally(()=>{this.changeScenePromise=null}),this.changeScenePromise}awaitFade(e,t){return new Promise(i=>{let r=!1,o=()=>{r||(r=!0,i())};e==="out"?this.fadeToBlack(t,o):this.fadeFromBlack(t,o),setTimeout(o,t*1e3+100)})}fadeToBlack(e,t){if(this.ensureFadeOverlay(),!this.fadeOverlay)return;let i=parseFloat(this.fadeOverlay.style.opacity??"0");this.cancelFade(),this.animateFade(i,1,e,t)}fadeFromBlack(e,t){if(this.ensureFadeOverlay(),!this.fadeOverlay)return;let i=parseFloat(this.fadeOverlay.style.opacity??"1");this.cancelFade(),this.animateFade(i,0,e,t)}setFadeOpacity(e){this.ensureFadeOverlay(),this.fadeOverlay&&(this.cancelFade(),this.fadeOverlay.style.opacity=String(Math.max(0,Math.min(1,e))))}flash(e={}){let t=typeof e.color=="string"&&e.color.trim()?e.color.trim():"#ffffff",i=Math.max(0,Math.min(1,e.intensity??1)),r=Math.max(0,e.durationSec??.2);this.ensureFlashOverlay();let o=this.flashOverlay;if(!o)return;if(this.cancelFlash(),o.style.background=t,i<=0){o.style.opacity="0";return}o.style.opacity=String(i);let s=r*1e3;if(s===0){o.style.opacity="0";return}let a=performance.now(),l=c=>{let u=Math.min((c-a)/s,1);o.style.opacity=String(i*(1-u)),u<1?this.flashAnimationId=requestAnimationFrame(l):this.flashAnimationId=null};this.flashAnimationId=requestAnimationFrame(l)}ensureFlashOverlay(){if(this.flashOverlay)return;let e=this.canvas?.parentElement;if(!e){console.warn("[SceneService] Cannot create flash overlay: canvas has no parent element.");return}getComputedStyle(e).position==="static"&&(e.style.position="relative"),this.flashOverlay=document.createElement("div"),this.flashOverlay.style.cssText=["position: absolute","inset: 0","background: #ffffff","opacity: 0","pointer-events: none","z-index: 10000"].join("; "),e.appendChild(this.flashOverlay)}cancelFlash(){this.flashAnimationId!==null&&(cancelAnimationFrame(this.flashAnimationId),this.flashAnimationId=null)}ensureFadeOverlay(){if(this.fadeOverlay)return;let e=this.canvas?.parentElement;if(!e){console.warn("[SceneService] Cannot create fade overlay: canvas has no parent element.");return}getComputedStyle(e).position==="static"&&(e.style.position="relative"),this.fadeOverlay=document.createElement("div"),this.fadeOverlay.style.cssText=["position: absolute","inset: 0","background: #000000","opacity: 0","pointer-events: none","z-index: 9999"].join("; "),e.appendChild(this.fadeOverlay)}cancelFade(){this.fadeAnimationId!==null&&(cancelAnimationFrame(this.fadeAnimationId),this.fadeAnimationId=null)}animateFade(e,t,i,r){if(!this.fadeOverlay)return;let o=this.fadeOverlay,s=Math.max(0,i*1e3);if(s===0){o.style.opacity=String(t),r?.();return}let a=performance.now(),l=c=>{let u=c-a,h=Math.min(u/s,1);o.style.opacity=String(e+(t-e)*h),h<1?this.fadeAnimationId=requestAnimationFrame(l):(this.fadeAnimationId=null,r?.())};this.fadeAnimationId=requestAnimationFrame(l)}resolveViewportDimensions(){if(this.viewportWidth>0&&this.viewportHeight>0)return{width:this.viewportWidth,height:this.viewportHeight};let e=this.canvas?.width??0,t=this.canvas?.height??0;if(e>0&&t>0)return{width:e,height:t};if(typeof window<"u"){let i=Number.isFinite(window.devicePixelRatio)?window.devicePixelRatio:1,r=Math.max(0,Math.round(window.innerWidth*i)),o=Math.max(0,Math.round(window.innerHeight*i));return{width:r,height:o}}return{width:0,height:0}}};var vl=null,Dp=()=>import("./build-ADF5EEE2.js");function FE(n){Dp!==n&&(Dp=n,vl=null)}function zE(){return vl||(vl=Dp()),vl}var wo=class{renderer;pp=null;loadingStarted=!1;composer=null;render3DPass=null;normalPass=null;depthDownsampling=null;ssaoPass=null;clearDepthPass=null;render2DPass=null;effectPass=null;bloom=null;vignette=null;chromaticAberration=null;ssao=null;caOffset=new N;structuralSignature="";lastCamera3D=null;lastOrthoCamera=null;width=0;height=0;sizeScratch=new N;constructor(e){this.renderer=e}ensureLoading(){this.pp||this.loadingStarted||(this.loadingStarted=!0,zE().then(e=>{this.pp=e}))}isReady(){return this.pp!==null}syncSizeFromRenderer(){let e=this.renderer.getSize(this.sizeScratch),t=Math.max(1,Math.round(e.width)),i=Math.max(1,Math.round(e.height));t===this.width&&i===this.height||(this.width=t,this.height=i,this.composer?.setSize(t,i,!1))}render(e,t,i,r){let o=this.pp;if(!o)return;this.syncSizeFromRenderer(),this.sync(o,e,t,i,r);let s=this.renderer.getSize(this.sizeScratch);this.renderer.setScissorTest(!1),this.renderer.setViewport(0,0,s.width,s.height),this.composer?.render()}sync(e,t,i,r,o){let s=this.computeSignature(o,i),a=this.lastCamera3D!==i||this.lastOrthoCamera!==r;(!this.composer||s!==this.structuralSignature||a)&&(this.rebuild(e,t,i,r,o),this.structuralSignature=s,this.lastCamera3D=i,this.lastOrthoCamera=r),this.applyLiveValues(o)}computeSignature(e,t){let i=e.bloom,r=e.lut.enabled&&e.lut.src.length>0;return[t?"3d":"no3d",e.affect2D?"2d":"2d-",i.enabled?`bloom:${i.threshold}:${i.smoothing}:${i.radius}`:"bloom-",e.vignette.enabled?"vig":"vig-",e.chromaticAberration.enabled?"ca":"ca-",e.ssao.enabled&&t?"ssao":"ssao-",r?`lut:${e.lut.src}`:"lut-"].join("|")}rebuild(e,t,i,r,o){this.composer||(this.composer=new e.EffectComposer(this.renderer,{frameBufferType:am}),this.composer.setSize(this.width,this.height,!1));let s=this.composer;if(s.removeAllPasses(),this.disposeEffects(),i?(this.render3DPass=new e.RenderPass(t,i),s.addPass(this.render3DPass)):this.render3DPass=null,o.ssao.enabled&&i?(this.normalPass=new e.NormalPass(t,i),this.depthDownsampling=new e.DepthDownsamplingPass({normalBuffer:this.normalPass.texture,resolutionScale:1}),s.addPass(this.normalPass),s.addPass(this.depthDownsampling),this.ssao=new e.SSAOEffect(i,this.normalPass.texture,{blendFunction:e.BlendFunction.MULTIPLY,distanceScaling:!0,depthAwareUpsampling:!0,normalDepthBuffer:this.depthDownsampling.texture,samples:30,rings:11,worldDistanceThreshold:40,worldDistanceFalloff:8,worldProximityThreshold:4,worldProximityFalloff:2,luminanceInfluence:.6,radius:o.ssao.radius,intensity:o.ssao.intensity,fade:.02,bias:.03}),this.ssaoPass=new e.EffectPass(i,this.ssao),s.addPass(this.ssaoPass)):(this.normalPass=null,this.depthDownsampling=null,this.ssaoPass=null,this.ssao=null),o.affect2D||!i){let u=!this.render3DPass;u?this.clearDepthPass=null:(this.clearDepthPass=new e.ClearPass(!1,!0,!1),s.addPass(this.clearDepthPass)),this.render2DPass=new e.RenderPass(t,r),this.render2DPass.clearPass.enabled=u,this.render2DPass.ignoreBackground=!u,s.addPass(this.render2DPass)}else this.clearDepthPass=null,this.render2DPass=null;let l=i??r,c=[];o.bloom.enabled&&(this.bloom=new e.BloomEffect({mipmapBlur:!0,intensity:o.bloom.intensity,luminanceThreshold:o.bloom.threshold,luminanceSmoothing:o.bloom.smoothing,radius:o.bloom.radius}),c.push(this.bloom)),o.vignette.enabled&&(this.vignette=new e.VignetteEffect({offset:o.vignette.offset,darkness:o.vignette.darkness}),c.push(this.vignette)),o.chromaticAberration.enabled&&(this.caOffset.set(o.chromaticAberration.offset,o.chromaticAberration.offset),this.chromaticAberration=new e.ChromaticAberrationEffect({offset:this.caOffset,radialModulation:!1,modulationOffset:0}),c.push(this.chromaticAberration)),c.length>0?(this.effectPass=new e.EffectPass(l,...c),s.addPass(this.effectPass)):this.effectPass=null}applyLiveValues(e){this.bloom&&(this.bloom.intensity=e.bloom.intensity),this.vignette&&(this.vignette.offset=e.vignette.offset,this.vignette.darkness=e.vignette.darkness),this.chromaticAberration&&(this.caOffset.set(e.chromaticAberration.offset,e.chromaticAberration.offset),this.chromaticAberration.offset=this.caOffset),this.ssao&&(this.ssao.intensity=e.ssao.intensity,this.ssao.radius=e.ssao.radius)}disposeEffects(){this.effectPass?.dispose(),this.bloom?.dispose(),this.vignette?.dispose(),this.chromaticAberration?.dispose(),this.ssaoPass?.dispose(),this.ssao?.dispose(),this.depthDownsampling?.dispose(),this.normalPass?.dispose(),this.effectPass=null,this.bloom=null,this.vignette=null,this.chromaticAberration=null,this.ssaoPass=null,this.ssao=null,this.depthDownsampling=null,this.normalPass=null}dispose(){this.disposeEffects(),this.composer?.dispose(),this.composer=null,this.render3DPass=null,this.clearDepthPass=null,this.render2DPass=null,this.structuralSignature="",this.lastCamera3D=null,this.lastOrthoCamera=null}};var UE=["normal","hover","pressed","disabled"];function wl(n,e){let t=i=>{i instanceof Z&&i.labelKey&&i.refreshLocalizedLabel(),e&&(i instanceof Fe&&i.textureKey?WE(i,e):i instanceof gt&&i.hasLocalizedStateTextures()&&HE(i,e));for(let r of i.children)t(r)};for(let i of n)t(i)}function WE(n,e){let t=n.getEffectiveTexturePath();t&&e.loadTexture(t).then(i=>{n.getEffectiveTexturePath()===t&&n.setTexture(i)}).catch(i=>{console.warn(`[Localization] Failed to load localized texture "${t}"`,i)})}function HE(n,e){for(let t of UE){if(!n.stateTextureKeys[t])continue;let i=n.getEffectiveStateTexturePath(t);i&&e.loadTexture(i).then(r=>{n.getEffectiveStateTexturePath(t)===i&&n.setStateTexture(t,r)}).catch(r=>{console.warn(`[Localization] Failed to load localized ${t} texture "${i}"`,r)})}}var qE=.016666666666666666,GE=4,xo=class{fixedTimeStep;maxFixedStepsPerFrame;registrations=[];scene=null;input=null;elapsedTime=0;frame=0;alpha=0;constructor(e={}){this.fixedTimeStep=typeof e.fixedTimeStep=="number"&&e.fixedTimeStep>0?e.fixedTimeStep:qE,this.maxFixedStepsPerFrame=typeof e.maxFixedStepsPerFrame=="number"&&e.maxFixedStepsPerFrame>0?Math.max(1,Math.floor(e.maxFixedStepsPerFrame)):GE}registerWorld(e){let t={world:e.world,systems:[...e.systems]};this.registrations.push(t);let i=this.tryCreateContext(0,this.elapsedTime,this.frame,this.alpha);return i&&t.world.initialize&&t.world.initialize(i),()=>{let r=this.registrations.indexOf(t);r!==-1&&(this.disposeRegistration(t),this.registrations.splice(r,1))}}clear(){for(;this.registrations.length>0;){let e=this.registrations.pop();e&&this.disposeRegistration(e)}}dispose(){this.clear(),this.scene=null,this.input=null,this.elapsedTime=0,this.frame=0,this.alpha=0}beginScene(e,t){this.scene=e,this.input=t,this.elapsedTime=0,this.frame=0,this.alpha=0;let i=this.tryCreateContext(0,0,0,0);if(i)for(let r of this.registrations)r.world.initialize?.(i)}endScene(){this.scene=null,this.input=null,this.elapsedTime=0,this.frame=0,this.alpha=0}setInterpolationAlpha(e){this.alpha=Number.isFinite(e)?Math.max(0,e):0}setFrameMetrics(e,t){this.elapsedTime=Number.isFinite(e)?Math.max(0,e):this.elapsedTime,this.frame=Number.isFinite(t)?Math.max(0,Math.floor(t)):this.frame}update(e,t=this.alpha){let i=Number.isFinite(e)?Math.max(0,e):0;this.alpha=Number.isFinite(t)?Math.max(0,t):this.alpha;let r=this.tryCreateContext(i,this.elapsedTime,this.frame,this.alpha);r&&this.runPhase("update",r)}fixedUpdate(e){let t=Number.isFinite(e)?Math.max(0,e):0,i=this.tryCreateContext(t,this.elapsedTime,this.frame,this.alpha);i&&this.runPhase("fixedUpdate",i)}runPhase(e,t){for(let i of this.registrations)for(let r of i.systems)r.phase===e&&r.update(t)}tryCreateContext(e,t,i,r){return!this.scene||!this.input?null:{dt:e,time:t,frame:i,fixedTimeStep:this.fixedTimeStep,alpha:r,scene:this.scene,input:this.input}}disposeRegistration(e){e.world.dispose?.()}};function Ep(n,e,t,i){return!(t.width>0)||!(t.height>0)||!(i.width>0)||!(i.height>0)?null:{x:(n+t.width/2)/t.width*i.width,y:(t.height/2-e)/t.height*i.height}}function xl(n,e,t){return!(t.width>0)||!(t.height>0)||(n.project(e),!Number.isFinite(n.x)||!Number.isFinite(n.y))?null:{x:(n.x+1)/2*t.width,y:(1-n.y)/2*t.height}}var Np=.016666666666666666,Jv=240,Ip=Object.freeze({mode:"realtime",fixedDeltaSec:Np,ticksPerFrame:1,renderEveryNTicks:1,muteAudio:!0});function jE(n){return n==="realtime"||n==="fixed"||n==="manual"}function Rp(n){if(!n||!jE(n.mode))throw new TypeError(`[RuntimeTime] mode must be one of 'realtime' | 'fixed' | 'manual' (got ${String(n?.mode)}).`);let e=n.fixedDeltaSec,t=Np;if(e!==void 0){if(typeof e!="number"||!Number.isFinite(e)||e<=0)throw new RangeError(`[RuntimeTime] fixedDeltaSec must be a finite number > 0 (got ${String(e)}).`);t=e}let i=Qv(n.ticksPerFrame,1,1,Jv),r=n.mode==="fixed"?i:1,o=Qv(n.renderEveryNTicks,r,1,Number.MAX_SAFE_INTEGER);return{mode:n.mode,fixedDeltaSec:t,ticksPerFrame:i,renderEveryNTicks:o,muteAudio:n.muteAudio??!0}}function Qv(n,e,t,i){return n===void 0||typeof n!="number"||!Number.isFinite(n)?e:Math.min(i,Math.max(t,Math.round(n)))}var Al=null,ew="",Pl=!1,Bp=new Set,Op=new Set,Zv=!1;function Vp(){let n=typeof window<"u"?window.innerWidth:0,e=typeof window<"u"?window.innerHeight:0;return{width:n,height:e,orientation:n>=e?"landscape":"portrait"}}function kl(){let n=Vp();for(let e of Op)try{e(n)}catch(t){console.warn("[PlayableSdk] resize listener failed:",t)}}function $E(){if(Zv||typeof window>"u")return;Zv=!0,window.addEventListener("resize",kl),window.addEventListener("orientationchange",kl),globalThis.mraid?.addEventListener?.("sizeChange",kl),globalThis.dapi?.addEventListener?.("adResized",kl)}function YE(n){Al=n}function KE(n){ew=typeof n=="string"?n.trim():""}var Lp={openStore(n){let e=(n??"").trim()||ew;if(Al?.openStore){if(!e){console.warn("[PlayableSdk] openStore called without a store URL.");return}Al.openStore(e);return}let t=globalThis.dapi;if(t?.openStoreUrl){t.openStoreUrl();return}if(!e){console.warn("[PlayableSdk] openStore called without a store URL.");return}let i=globalThis.mraid;if(i?.open){i.open(e);return}typeof window<"u"&&window.open(e,"_blank","noopener")},getViewport(){return Vp()},getOrientation(){return Vp().orientation},onResize(n){return $E(),Op.add(n),()=>Op.delete(n)},gameEnd(){if(!Pl){Pl=!0,Al?.gameEnd?.();for(let n of Bp)try{n()}catch(e){console.warn("[PlayableSdk] gameEnd listener failed:",e)}}},hasGameEnded(){return Pl},onGameEnd(n){return Bp.add(n),()=>Bp.delete(n)},reset(){Pl=!1}};function tw(n){let e={hasOverlay:!1};for(let t of n)t instanceof C&&iw(t,!1,e);return e.hasOverlay}function iw(n,e,t){n instanceof C&&n.isCanvasLayer&&(e=!0),e&&(t.hasOverlay=!0),n.layers.set(e?3:1);for(let i of n.children)iw(i,e,t)}var XE=57508,Br=.3,Or=class{geometry=new ae;material=new Nt({vertexColors:!0,transparent:!0,depthTest:!1,depthWrite:!1,toneMapped:!1});lines=new ir(this.geometry,this.material);overlayScene=new er;positionAttr=null;colorAttr=null;constructor(){this.overlayScene.background=null,this.lines.frustumCulled=!1,this.lines.raycast=()=>{},this.overlayScene.add(this.lines)}sync(){let e=ic();if(!e)return!1;let t;try{t=e()}catch{return!1}return this.upload(t)}upload(e){if(!e?.vertices)return!1;let t=e.vertices,i=t.length;if(i<6)return this.geometry.setDrawRange(0,0),!1;(!this.positionAttr||this.positionAttr.array.length<i)&&(this.positionAttr=new Q(new Float32Array(i),3),this.positionAttr.setUsage(oe),this.geometry.setAttribute("position",this.positionAttr)),this.positionAttr.array.set(t),this.positionAttr.needsUpdate=!0;let r=Math.floor(i/3);this.geometry.setDrawRange(0,r);let o=e.colors,s=!!o&&o.length>=r*4;if(s&&o){(!this.colorAttr||this.colorAttr.array.length<o.length)&&(this.colorAttr=new Q(new Float32Array(o.length),4),this.colorAttr.setUsage(oe),this.geometry.setAttribute("color",this.colorAttr));let a=this.colorAttr.array,l=r*4;for(let c=0;c<l;c+=4)a[c]=Br+(1-Br)*o[c],a[c+1]=Br+(1-Br)*o[c+1],a[c+2]=Br+(1-Br)*o[c+2],a[c+3]=o[c+3];this.colorAttr.needsUpdate=!0}return this.material.vertexColors!==s&&(this.material.vertexColors=s,s||this.material.color.set(XE),this.material.needsUpdate=!0),!0}render(e,t){this.sync()&&e.render(this.overlayScene,t)}renderBuffers(e,t,i){this.upload(i)&&e.render(this.overlayScene,t)}dispose(){this.geometry.dispose(),this.material.dispose()}};var QE=[1,.23,.23],JE=[.35,.92,.35],ZE=[.32,.55,1],rw=.05,eN=1,tN=.28,iN=.14,Tl=class{geometry=new ae;material=new Nt({vertexColors:!0,transparent:!0,opacity:.95,depthTest:!1,depthWrite:!1,toneMapped:!1});lines=new ir(this.geometry,this.material);overlayScene=new er;positionAttr=null;colorAttr=null;positions=[];colors=[];origin=new S;axis=new S;perp=new S;cameraPosition=new S;constructor(){this.overlayScene.background=null,this.lines.frustumCulled=!1,this.lines.layers.enableAll(),this.lines.raycast=()=>{},this.overlayScene.add(this.lines)}render(e,t,i,r){this.positions.length=0,this.colors.length=0;let o=t instanceof ge?t:null,s=o?Math.tan(R.degToRad(o.fov)/2):0;o&&this.cameraPosition.setFromMatrixPosition(o.matrixWorld);let a=t instanceof de?(t.top-t.bottom)/t.zoom*rw:null;this.collect(i,r,o,s,a);let l=this.positions.length;if(l<6){this.geometry.setDrawRange(0,0);return}(!this.positionAttr||this.positionAttr.array.length<l)&&(this.positionAttr=new Q(new Float32Array(l),3),this.positionAttr.setUsage(oe),this.geometry.setAttribute("position",this.positionAttr),this.colorAttr=new Q(new Float32Array(l),3),this.colorAttr.setUsage(oe),this.geometry.setAttribute("color",this.colorAttr)),this.positionAttr.array.set(this.positions),this.positionAttr.needsUpdate=!0,this.colorAttr.array.set(this.colors),this.colorAttr.needsUpdate=!0,this.geometry.setDrawRange(0,Math.floor(l/3)),e.render(this.overlayScene,t)}collect(e,t,i,r,o){for(let s of e){if(!s.visible)continue;(t==="node2d"?s instanceof C:s instanceof U)&&this.emitForNode(s,t,i,r,o),s.children.length>0&&this.collect(s.children,t,i,r,o)}}emitForNode(e,t,i,r,o){let s=e.matrixWorld.elements;this.origin.set(s[12],s[13],s[14]);let a;i?a=2*this.cameraPosition.distanceTo(this.origin)*r*rw:a=o??eN,!(a<=0)&&(this.axis.set(s[0],s[1],s[2]),this.emitArrow(t,a,QE),this.axis.set(s[4],s[5],s[6]),this.emitArrow(t,a,JE),t==="node3d"&&(this.axis.set(s[8],s[9],s[10]),this.emitArrow(t,a,ZE)))}emitArrow(e,t,i){if(this.axis.lengthSq()<1e-12)return;this.axis.normalize();let r=this.origin.x,o=this.origin.y,s=this.origin.z,a=r+this.axis.x*t,l=o+this.axis.y*t,c=s+this.axis.z*t,u=t*tN,h=t*iN,d=a-this.axis.x*u,p=l-this.axis.y*u,f=c-this.axis.z*u;e==="node2d"?this.perp.set(-this.axis.y,this.axis.x,0):this.perpendicular3(this.axis,this.perp);let m=this.perp.x*h,g=this.perp.y*h,y=this.perp.z*h;this.pushSegment(r,o,s,a,l,c,i),this.pushSegment(a,l,c,d+m,p+g,f+y,i),this.pushSegment(a,l,c,d-m,p-g,f-y,i)}pushSegment(e,t,i,r,o,s,a){this.positions.push(e,t,i,r,o,s),this.colors.push(a[0],a[1],a[2],a[0],a[1],a[2])}perpendicular3(e,t){let i=Math.abs(e.x),r=Math.abs(e.y),o=Math.abs(e.z);i<=r&&i<=o?t.set(1,0,0):r<=o?t.set(0,1,0):t.set(0,0,1),t.cross(e).normalize()}dispose(){this.geometry.dispose(),this.material.dispose()}};var nw={request:n=>requestAnimationFrame(n),cancel:n=>cancelAnimationFrame(n)},rN=.999,_p=Object.freeze([]);function nN(n){return n.trim().replace(/\\/g,"/").replace(/^res:\/\//i,"").replace(/^\/+/,"")}var Fp=class n{sceneManager;renderer;assetLoader;inputService;sceneService;ecsService;autoloads=new ja;audioService;resourceManager;clock;gameTime=new zi;audioMuffled=!1;raycaster=new Im;raycastPointer=new N;animationFrameId=null;frameScheduler=nw;isRunning=!1;fixedTimeAccumulator=0;elapsedTime=0;frameNumber=0;timeConfig={...Ip};ticksSinceRender=0;inTick=!1;audioSilenced=!1;masterVolumeBeforeSilence=1;scene;activeCamera=null;activeCamera2D=null;scratchShake2D=new N;orthographicCamera;overlayCamera;overlay2DActive=!1;viewportSize={width:0,height:0};canvasCssSize=null;canvasSizeObserver=null;observedCanvas=null;logicalCameraSize={width:1,height:1};rootLayoutAuthoredSize;frameListeners=new Set;currentRafLatenessMs=0;currentFrameProfilerActivities=_p;physicsDebugOverlay=null;physics2DDebugOverlay=null;directionAxesOverlay=null;postFx=null;batch2D=null;batch2DEnabled=!1;localization=null;previousActiveLocalization=null;localizationUnsub=null;projectFonts=null;localizationConfig=null;seedLocale=null;ordered2DBuffer=[];ordered2DCount=0;collectOrdered2D=(e,t,i,r)=>{if(!e.isMesh)return;let o=this.ordered2DBuffer[this.ordered2DCount];o?(o.mesh=e,o.order=t,o.overlay=i,o.visible=r):this.ordered2DBuffer.push({mesh:e,order:t,overlay:i,visible:r}),this.ordered2DCount++};constructor(e,t,i,r,o={width:1920,height:1080}){this.sceneManager=e,this.renderer=t,this.assetLoader=r,this.inputService=new $n,this.sceneService=new So,this.ecsService=new xo,this.audioService=i,this.resourceManager=r.getResourceManager(),this.clock=new Rm,this.scene=new er,this.rootLayoutAuthoredSize={width:Math.max(1,o.width),height:Math.max(1,o.height)},this.scene.background=new L("#202020"),this.orthographicCamera=new de(-1,1,1,-1,.1,1e3),this.orthographicCamera.position.z=100,this.orthographicCamera.layers.disableAll(),this.orthographicCamera.layers.enable(1),this.overlayCamera=new de(-1,1,1,-1,.1,1e3),this.overlayCamera.position.z=100,this.overlayCamera.layers.disableAll(),this.overlayCamera.layers.enable(3),this.sceneService.setAutoloads(this.autoloads),this.bindSceneServiceDelegate()}setAutoloads(e,t){this.autoloads.configure(e,t)}setNetworkService(e){this.sceneService.setNetworkService(e)}setBatching2DEnabled(e){this.batch2DEnabled=e,!e&&this.batch2D&&(this.batch2D.dispose(),this.batch2D=null)}getBatch2DStats(){return this.batch2D?this.batch2D.stats:null}setProjectFonts(e){this.projectFonts=e&&e.length>0?e:null}setLocalizationConfig(e,t){this.localizationConfig=e,this.seedLocale=t??null}runtimeGraph=null;async startScene(e){let t=this.sceneManager.getSceneGraph(e);if(!t){console.warn(`[SceneRunner] Scene "${e}" not found.`);return}let i=this.stopEpoch,r;try{let o=this.sceneManager.serializeScene(t);r=await this.sceneManager.parseScene(o)}catch(o){throw console.error("[SceneRunner] Failed to clone scene for runtime:",o),o}this.abandonIfStopped(i,r)||await this.runGraph(r)}async loadAndStartScene(e){let t=this.stopEpoch,i=nN(e),r=await this.resourceManager.readText(`res://${i}`),o=await this.sceneManager.parseScene(r,{filePath:i});this.abandonIfStopped(t,o)||await this.runGraph(o)}abandonIfStopped(e,t){if(this.stopEpoch===e)return!1;for(let i of t.rootNodes)i.dispose();return!0}spawnCounter=0;async instantiatePrefab(e,t,i){if(!this.isRunning||!this.runtimeGraph)throw new Error("[SceneRunner] instantiatePrefab requires a running scene.");this.spawnCounter+=1;let r=i?.trim()||`spawn:${this.spawnCounter}`,o=await this.sceneManager.instantiatePrefab(e,r),s=t??this.runtimeGraph.rootNodes[0]??null;if(!s)throw o.dispose(),new Error("[SceneRunner] instantiatePrefab: no parent node available.");return s.adoptChild(o),this.stripEditorOnly(o.children.filter(a=>a instanceof I)),this.applyInitialVisibility([o]),o}async runGraph(e){this.stopScene(),this.bindSceneServiceDelegate(),Lp.reset(),this.sceneService.attachCanvas(this.renderer.domElement),this.scene.clear(),this.activeCamera=null,this.activeCamera2D=null,this.lastTickErrorMessage=null,this.runtimeGraph=e;for(let i of this.runtimeGraph.rootNodes)i.input=this.inputService,i.scene=this.sceneService,this.scene.add(i);as(this.scene),ls((i,r,o)=>this.applyLivePropertyUpdate(i,r,o)),this.runtimeGraph.rootNodes=this.stripEditorOnly(this.runtimeGraph.rootNodes),this.applyInitialVisibility(this.runtimeGraph.rootNodes),this.applyEditorPeekMask(this.runtimeGraph.rootNodes),this.inputService.attach(this.renderer.domElement),this.activeCamera=this.findActiveCamera(this.runtimeGraph.rootNodes),this.activeCamera&&(this.activeCamera.camera.layers.disableAll(),this.activeCamera.camera.layers.enable(0)),this.viewportSize={width:0,height:0},this.logicalCameraSize={width:1,height:1},this.fixedTimeAccumulator=0,this.elapsedTime=0,this.frameNumber=0,this.ticksSinceRender=0,this.gameTime.reset(),this.audioMuffled=!1,this.audioSilenced=!1,this.applyTimeModeAudio(),this.projectFonts&&await iu(this.projectFonts,this.resourceManager),await this.setupLocalization(this.runtimeGraph.rootNodes),this.ecsService.beginScene(this.sceneService,this.inputService),this.isRunning=!0;let t=this.measureCanvas();t.width>0&&t.height>0&&(this.updateViewportSize(t.width,t.height),this.reflowRoot2DNodes()),this.autoloads.start(this.inputService,this.sceneService),this.updateNodes(0),this.flushInstancedNodes(),this.sceneService.handleSceneStarted(),this.clock.start(),this.timeConfig.mode==="manual"?this.render():this.tick()}async setupLocalization(e){let t=new $i;t.configure(this.localizationConfig??{defaultLocale:"en"}),t.attachResources(this.resourceManager),this.previousActiveLocalization=Ke(),this.localization=t,Ts(t),this.localizationUnsub=t.onChange(()=>{this.runtimeGraph&&wl(this.runtimeGraph.rootNodes,this.assetLoader)});let i=this.seedLocale??this.localizationConfig?.defaultLocale??"en";if(this.localizationConfig)try{await t.setLocale(i)}catch{}wl(e,this.assetLoader)}teardownLocalization(){this.localizationUnsub&&(this.localizationUnsub(),this.localizationUnsub=null),this.localization&&(Ts(this.previousActiveLocalization),this.localization.dispose(),this.localization=null),this.previousActiveLocalization=null}isPaused=!1;stopEpoch=0;stop(){this.stopScene(),this.autoloads.stop()}stopScene(){if(this.stopEpoch+=1,this.isRunning=!1,this.sceneService.cancelActiveCutscene(),this.teardownLocalization(),as(null),ls(null),this.physicsDebugOverlay&&(this.physicsDebugOverlay.dispose(),this.physicsDebugOverlay=null),this.physics2DDebugOverlay&&(this.physics2DDebugOverlay.dispose(),this.physics2DDebugOverlay=null),this.directionAxesOverlay&&(this.directionAxesOverlay.dispose(),this.directionAxesOverlay=null),this.postFx&&(this.postFx.dispose(),this.postFx=null),this.batch2D&&(this.batch2D.dispose(),this.batch2D=null),this.ordered2DBuffer.length=0,this.ordered2DCount=0,this.clock.stop(),this.animationFrameId!==null&&(this.frameScheduler.cancel(this.animationFrameId),this.animationFrameId=null),this.audioSilenced&&(this.audioSilenced=!1,this.audioService.setBusVolume("master",this.masterVolumeBeforeSilence,.01)),this.ecsService.endScene(),this.ecsService.clear(),this.fixedTimeAccumulator=0,this.elapsedTime=0,this.frameNumber=0,this.ticksSinceRender=0,this.isPaused=!1,this.audioService.setPaused(!1),this.gameTime.reset(),this.currentFrameProfilerActivities=_p,this.lastAOSuppress=null,I.flushFreeQueue(),this.runtimeGraph){for(let e of this.runtimeGraph.rootNodes)this.detachScripts(e),this.stopAudioPlayers(e);this.audioService.stopAll(),this.audioService.resetBuses(),this.audioMuffled=!1,this.sceneService.setDelegate(null),this.scene.clear();for(let e of this.runtimeGraph.rootNodes)e.dispose();this.runtimeGraph=null}this.sceneService.clearCommands(),this.sceneService.clearTweens(),this.sceneService.clearPhysics2D(),this.activeCamera2D=null,this.overlay2DActive=!1,this.orthographicCamera.position.set(0,0,100),this.orthographicCamera.zoom!==1&&(this.orthographicCamera.zoom=1,this.orthographicCamera.updateProjectionMatrix()),this.canvasSizeObserver?.disconnect(),this.canvasSizeObserver=null,this.observedCanvas=null,this.canvasCssSize=null,this.inputService.detach()}setFrameScheduler(e){let t=e??nw;if(t===this.frameScheduler)return;let i=this.animationFrameId!==null;this.animationFrameId!==null&&(this.frameScheduler.cancel(this.animationFrameId),this.animationFrameId=null),this.frameScheduler=t,i&&this.scheduleNextFrame()}pause(){!this.isRunning||this.isPaused||(this.isPaused=!0,this.audioService.setPaused(!0),this.animationFrameId!==null&&(this.frameScheduler.cancel(this.animationFrameId),this.animationFrameId=null))}resume(){!this.isRunning||!this.isPaused||(this.isPaused=!1,this.audioService.setPaused(!1),this.clock.getDelta(),this.timeConfig.mode!=="manual"&&this.tick())}get paused(){return this.isPaused}get running(){return this.isRunning}renderOnce(){return this.isRunning?(this.render(),!0):!1}getLiveNodeById(e){return this.findNodeById(e)}getLiveRootNodes(){return this.runtimeGraph?.rootNodes??[]}getActiveCamera3D(){return this.activeCamera}findLiveNodeByName(e){return this.findLiveNodesByName(e,1)[0]??null}findLiveNodesByName(e,t=Number.POSITIVE_INFINITY){let i=e.toLowerCase(),r=[],o=[...this.runtimeGraph?.rootNodes??[]].reverse();for(;o.length>0;){let s=o.pop();if(s){if(s.name.toLowerCase()===i&&(r.push(s),r.length>=t))return r;for(let a=s.children.length-1;a>=0;a-=1){let l=s.children[a];l instanceof I&&o.push(l)}}}return r}projectNodeToCanvas(e){let t=e.getWorldPosition(n.scratchProject);return e instanceof C?this.projectWorldPointToCanvas(t.x,t.y,{overlay:this.isInOverlayBand(e)}):this.activeCamera?xl(t,this.activeCamera.camera,this.canvasBackingSize()):null}projectWorldPointToCanvas(e,t,i){let r=this.canvasBackingSize();return!i?.overlay&&this.orthographicCamera?(n.scratchProject.set(e,t,0),xl(n.scratchProject,this.orthographicCamera,r)):Ep(e,t,this.logicalCameraSize,r)}static scratchProject=new S;canvasBackingSize(){let e=this.renderer.domElement;return{width:e.width,height:e.height}}isInOverlayBand(e){let t=e,i=0;for(;t&&i++<128;){if(t instanceof C&&t.isCanvasLayer)return!0;t=t.parent instanceof I?t.parent:null}return!1}setTimeMode(e){let t=Rp(e),i=this.timeConfig.mode;if(this.timeConfig=t,this.fixedTimeAccumulator=0,this.ticksSinceRender=0,t.mode==="realtime"&&i!=="realtime"&&this.clock.getDelta(),this.applyTimeModeAudio(),t.mode==="manual"){this.animationFrameId!==null&&(this.frameScheduler.cancel(this.animationFrameId),this.animationFrameId=null);return}this.scheduleNextFrame()}getTimeMode(){return{...this.timeConfig}}stepFrames(e=1){if(this.timeConfig.mode!=="manual")return console.warn(`[SceneRunner] stepFrames() is only available in 'manual' time mode (current: '${this.timeConfig.mode}').`),0;if(!this.isRunning||this.isPaused)return 0;if(this.inTick)return console.warn("[SceneRunner] stepFrames() called from inside a tick \u2014 ignored (reentrancy)."),0;let t=typeof e=="number"&&Number.isFinite(e)?Math.floor(e):0,i=0;for(let r=0;r<t&&!(!this.isRunning||this.isPaused);r+=1){try{this.runOneTick(this.timeConfig.fixedDeltaSec)}catch(o){console.error("[SceneRunner] stepFrames aborted by an error during the tick:",o);break}if(i+=1,this.timeConfig.mode!=="manual")break}return i}applyTimeModeAudio(){let e=this.timeConfig.muteAudio&&this.timeConfig.mode!=="realtime";e!==this.audioSilenced&&(this.audioSilenced=e,e?(this.masterVolumeBeforeSilence=this.audioService.getBusVolume("master"),this.audioService.setBusVolume("master",0,.01)):this.audioService.setBusVolume("master",this.masterVolumeBeforeSilence,.01))}scheduleNextFrame(){!this.isRunning||this.isPaused||this.timeConfig.mode!=="manual"&&this.animationFrameId===null&&(this.animationFrameId=this.frameScheduler.request(this.tick))}tick=e=>{if(this.currentRafLatenessMs=this.frameListeners.size>0&&typeof e=="number"&&Number.isFinite(e)?Math.max(0,performance.now()-e):0,this.animationFrameId=null,!this.isRunning||this.isPaused)return;let{mode:t,ticksPerFrame:i,fixedDeltaSec:r}=this.timeConfig;if(t!=="manual"){if(t==="realtime")this.runOneTick(this.clock.getDelta());else{this.clock.getDelta();for(let o=0;o<i&&!(!this.isRunning||this.isPaused||(this.runOneTick(r),this.timeConfig.mode!=="fixed"));o+=1);}this.scheduleNextFrame()}};runOneTick(e){this.inTick=!0;try{this.runFrameBody(e)}finally{this.inTick=!1}}runFrameBody(e){this.gameTime.advance(e);let t=this.gameTime.baseScale<rN;t!==this.audioMuffled&&(this.audioMuffled=t,this.audioService.applySnapshot(t?"muffled":"default"));let i=e*this.gameTime.scale,r=performance.now();this.currentFrameProfilerActivities=_p,this.inputService.beginFrame(),this.frameNumber+=1,this.elapsedTime+=i,this.fixedTimeAccumulator+=i,this.runFixedUpdates();let o=this.ecsService.fixedTimeStep>0?Math.min(this.fixedTimeAccumulator/this.ecsService.fixedTimeStep,1):0;this.ecsService.setFrameMetrics(this.elapsedTime,this.frameNumber),this.ecsService.setInterpolationAlpha(o),this.ecsService.update(i,o),this.sceneService.interpolatePhysics2D(o),this.renderer.beginStatsFrame(),this.sceneService.updateTweens(i),this.updateGameLogicSafe(i),this.flushInstancedNodes();let s=performance.now()-r;this.ticksSinceRender+=1;let a=0;if(this.ticksSinceRender>=this.timeConfig.renderEveryNTicks){this.ticksSinceRender=0;let l=performance.now();this.render(),a=performance.now()-l}this.frameListeners.size!==0&&this.notifyFrameListeners({dt:e,elapsedTime:this.elapsedTime,frameNumber:this.frameNumber,logicMs:s,renderMs:a,totalFrameMs:s+a,unaccountedMs:Math.max(0,e*1e3-(s+a)),rafLatenessMs:this.currentRafLatenessMs,profilerActivities:this.getFrameProfilerActivitiesSnapshot()})}subscribeFrameStats(e){return this.frameListeners.add(e),()=>{this.frameListeners.delete(e)}}lastTickErrorMessage=null;updateGameLogicSafe(e){try{this.updateNodes(e),this.lastTickErrorMessage=null}catch(t){let{message:i,stack:r}=Le(t);i!==this.lastTickErrorMessage&&(this.lastTickErrorMessage=i,console.error("[SceneRunner] Error during game update:",t),Me({phase:"tick",message:i,stack:r}))}}observeCanvasSize(e){this.observedCanvas===e&&this.canvasSizeObserver!==null||(this.canvasSizeObserver?.disconnect(),this.canvasSizeObserver=null,this.observedCanvas=e,this.canvasCssSize=null,!(typeof ResizeObserver>"u")&&(this.canvasSizeObserver=new ResizeObserver(t=>{let i=t[t.length-1]?.contentRect;i&&(this.canvasCssSize={width:Math.round(i.width),height:Math.round(i.height)})}),this.canvasSizeObserver.observe(e)))}updateNodes(e){this.autoloads.tick(e);let t=this.runtimeGraph;if(t)for(let i of t.rootNodes)i.tick(e);I.flushFreeQueue()}measureCanvas(){let e=this.renderer.domElement;this.observeCanvasSize(e);let t=this.canvasCssSize,i=t&&t.width>0?t.width:e.clientWidth>0?e.clientWidth:e.width,r=t&&t.height>0?t.height:e.clientHeight>0?e.clientHeight:e.height;return{width:i,height:r}}updateViewportSize(e,t){if(!(this.viewportSize.width!==e||this.viewportSize.height!==t))return!1;this.viewportSize.width=e,this.viewportSize.height=t;let r=this.rootLayoutAuthoredSize.width,o=this.rootLayoutAuthoredSize.height,s=r/o,a=e/t,l=r,c=o;return a>=s?(c=o,l=c*a):(l=r,c=l/a),this.logicalCameraSize={width:l,height:c},!0}render(){let{width:e,height:t}=this.measureCanvas(),i=this.updateViewportSize(e,t);if(!this.activeCamera){let l=this.runtimeGraph;l&&(this.activeCamera=this.findActiveCamera(l.rootNodes),this.activeCamera&&(this.activeCamera.camera.layers.disableAll(),this.activeCamera.camera.layers.enable(0)))}if(this.activeCamera){let l=e/t;this.activeCamera.updateAspectRatio(l)}if(this.orthographicCamera){let l=this.logicalCameraSize.width/2,c=this.logicalCameraSize.height/2;(this.orthographicCamera.left!==-l||this.orthographicCamera.right!==l||this.orthographicCamera.top!==c||this.orthographicCamera.bottom!==-c)&&(this.orthographicCamera.left=-l,this.orthographicCamera.right=l,this.orthographicCamera.top=c,this.orthographicCamera.bottom=-c,this.orthographicCamera.updateProjectionMatrix(),this.overlayCamera.left=-l,this.overlayCamera.right=l,this.overlayCamera.top=c,this.overlayCamera.bottom=-c,this.overlayCamera.updateProjectionMatrix()),this.activeCamera2D=mu(this.runtimeGraph?.rootNodes??[]);let u=0,h=0,d=1;if(this.activeCamera2D){let p=this.activeCamera2D.computeView(this.logicalCameraSize);this.activeCamera2D.getShakeOffset(this.scratchShake2D),u=p.x+this.scratchShake2D.x,h=p.y+this.scratchShake2D.y,d=p.zoom}this.orthographicCamera.position.x=u,this.orthographicCamera.position.y=h,this.orthographicCamera.zoom!==d&&(this.orthographicCamera.zoom=d,this.orthographicCamera.updateProjectionMatrix())}this.reflowRoot2DNodes(),i&&this.sceneService.setViewportSize(e,t),this.applyAOModeSuppression();let r=this.findActivePostProcessNode(),o=r?r.getConfig():null,s=!!o&&(!!this.activeCamera||o.affect2D);if(s?(this.postFx||(this.postFx=new wo(this.renderer.getWebGLRenderer())),this.postFx.ensureLoading()):this.postFx&&(this.postFx.dispose(),this.postFx=null),s&&!!this.postFx&&this.postFx.isReady()&&o&&this.postFx){let l=this.activeCamera?.camera??null;l&&this.updateBillboardSprites(this.runtimeGraph?.rootNodes??[],l),this.postFx.render(this.scene,l,this.orthographicCamera,o),l&&Gr()&&(this.physicsDebugOverlay||(this.physicsDebugOverlay=new Or),this.renderer.setAutoClear(!1),this.physicsDebugOverlay.render(this.renderer,l)),l&&this.renderDirectionAxes("node3d",l),!o.affect2D&&l&&this.renderScene2D(),this.renderDirectionAxes("node2d",this.orthographicCamera)}else this.activeCamera?(this.updateBillboardSprites(this.runtimeGraph?.rootNodes??[],this.activeCamera.camera),this.renderer.setAutoClear(!0),this.renderer.render(this.scene,this.activeCamera.camera)):(this.renderer.setAutoClear(!0),this.renderer.clear()),this.activeCamera&&Gr()&&(this.physicsDebugOverlay||(this.physicsDebugOverlay=new Or),this.renderer.setAutoClear(!1),this.physicsDebugOverlay.render(this.renderer,this.activeCamera.camera)),this.activeCamera&&this.renderDirectionAxes("node3d",this.activeCamera.camera),this.renderScene2D(),this.renderDirectionAxes("node2d",this.orthographicCamera);this.overlay2DActive&&this.renderOverlay2D()}renderDirectionAxes(e,t){oc()&&(this.directionAxesOverlay||(this.directionAxesOverlay=new Tl),this.renderer.setAutoClear(!1),this.directionAxesOverlay.render(this.renderer,t,this.runtimeGraph?.rootNodes??[],e))}renderScene2D(){this.renderer.setAutoClear(!1),this.renderer.clearDepth();let e=this.scene.background;this.scene.background=null,this.renderer.render(this.scene,this.orthographicCamera),this.scene.background=e,this.renderPhysics2DDebug()}renderPhysics2DDebug(){if(!Gr())return;let e=this.sceneService.buildPhysics2DDebugBuffers();e&&(this.physics2DDebugOverlay||(this.physics2DDebugOverlay=new Or),this.renderer.setAutoClear(!1),this.physics2DDebugOverlay.renderBuffers(this.renderer,this.orthographicCamera,e))}renderOverlay2D(){this.renderer.setAutoClear(!1),this.renderer.clearDepth();let e=this.scene.background;this.scene.background=null,this.renderer.render(this.scene,this.overlayCamera),this.scene.background=e}lastAOSuppress=null;applyAOModeSuppression(){let e=this.runtimeGraph;if(!e)return;let t=null,i=[],r=[...e.rootNodes];for(;r.length>0;){let s=r.pop();if(s){s instanceof it&&!t?t=s:s instanceof St&&i.push(s);for(let a of s.children)r.push(a)}}let o=t?t.getResolvedAOMode()!=="baked":!1;if(o!==this.lastAOSuppress){this.lastAOSuppress=o;for(let s of i)s.setAOSuppressed(o)}}findActivePostProcessNode(){let e=this.runtimeGraph;if(!e)return null;let t=[...e.rootNodes];for(;t.length>0;){let i=t.pop();if(i){if(i instanceof it&&i.isActive())return i;for(let r of i.children)t.push(r)}}return null}findActiveCamera(e){for(let t of e){if(t instanceof pe&&t.visible)return t;if(t.children&&t.children.length>0){let i=t.children.filter(o=>o instanceof I),r=this.findActiveCamera(i);if(r)return r}}return null}findNodeById(e){if(!this.runtimeGraph)return null;for(let t of this.runtimeGraph.rootNodes){let i=t.findById(e);if(i)return i}return null}applyLivePropertyUpdate(e,t,i){if(!this.isRunning||!this.runtimeGraph)return!1;let r=this.findNodeById(e);if(!r)return!1;let s=ke(r).properties.find(a=>a.name===t);if(!s){if(t==="opacity"&&r instanceof C){let a=Number(i);return Number.isFinite(a)?(r.opacity=Math.max(0,Math.min(1,a)),!0):!1}return!1}return s.setValue(r,i),this.afterLivePropertyApplied(r,t),!0}afterLivePropertyApplied(e,t){e instanceof C&&(["position","width","height","size","radius"].includes(t)&&e.captureAuthoredLayoutRectFromCurrent(!0),["width","height","size","radius","resolutionPreset"].includes(t)&&e.isContainer&&(e.reflowAnchoredChildren(),this.captureAnchoredDescendantRects(e)))}captureAnchoredDescendantRects(e){for(let t of e.children)t instanceof C&&t.captureAuthoredLayoutRectFromCurrent(),t instanceof I&&this.captureAnchoredDescendantRects(t)}bindSceneServiceDelegate(){let e=this;this.sceneService.setDelegate({getActiveCameraNode(){return e.activeCamera},getActiveCamera2DNode(){return e.activeCamera2D},getInputService(){return e.inputService},getUICamera(){return e.orthographicCamera},getLogicalCameraSize(){return{...e.logicalCameraSize}},setActiveCameraNode(t){e.activeCamera=t},findNodeById(t){return e.findNodeById(t)},getRootNodes(){return e.runtimeGraph?.rootNodes??[]},getAudioService(){return e.audioService},getLocalizationService(){return e.localization},getAssetLoader(){return e.assetLoader},getResourceManager(){return e.resourceManager},getECSService(){return e.runtimeGraph?e.ecsService:null},getGameTime(){return e.gameTime},getFrameNumber(){return e.frameNumber},raycastViewport(t,i){return e.raycastViewport(t,i)},reportFrameProfilerActivities(t){e.reportFrameProfilerActivities(t)},loadAndStartScene(t){return e.loadAndStartScene(t)},instantiatePrefab(t,i,r){return e.instantiatePrefab(t,i,r)}})}reportFrameProfilerActivities(e){this.currentFrameProfilerActivities=this.normalizeFrameProfilerActivities(e)}getFrameProfilerActivitiesSnapshot(){return this.currentFrameProfilerActivities.length===0?void 0:this.currentFrameProfilerActivities}normalizeFrameProfilerActivities(e){let t=[];for(let i of e){let r=typeof i.label=="string"?i.label.trim():"";if(!r)continue;let o=this.normalizeFrameProfilerValue(i.selfTimeMs);if(o===null)continue;let s=this.normalizeFrameProfilerValue(i.totalTimeMs);t.push(s===null?{label:r,selfTimeMs:o}:{label:r,selfTimeMs:o,totalTimeMs:Math.max(s,o)})}return t}normalizeFrameProfilerValue(e){return typeof e!="number"||!Number.isFinite(e)||e<0?null:e}runFixedUpdates(){let e=this.ecsService.fixedTimeStep;if(e<=0||this.fixedTimeAccumulator<e)return;let t=0,i=this.elapsedTime-this.fixedTimeAccumulator;for(;this.fixedTimeAccumulator>=e&&t<this.ecsService.maxFixedStepsPerFrame;)this.fixedTimeAccumulator-=e,i+=e,this.ecsService.setFrameMetrics(i,this.frameNumber),this.ecsService.fixedUpdate(e),this.sceneService.stepPhysics2D(e),t+=1;t===this.ecsService.maxFixedStepsPerFrame&&(this.fixedTimeAccumulator=Math.min(this.fixedTimeAccumulator,e))}flushInstancedNodes(){let e=this.runtimeGraph;if(!e)return;let t=[...e.rootNodes];for(;t.length>0;){let i=t.pop();if(i){i instanceof vt&&i.flush();for(let r of i.children)r instanceof I&&t.push(r)}}}raycastViewport(e,t){if(!this.runtimeGraph)return null;if(this.overlay2DActive){let r=this.raycastWithCamera(e,t,this.overlayCamera,3);if(r)return r}let i=this.raycastWithCamera(e,t,this.orthographicCamera,1);return i||(this.activeCamera?this.raycastWithCamera(e,t,this.activeCamera.camera,0):null)}raycastWithCamera(e,t,i,r){this.raycastPointer.set(e,t),this.raycaster.layers.set(r),this.raycaster.setFromCamera(this.raycastPointer,i);let o=this.raycaster.intersectObjects(this.scene.children,!0);for(let s of o){if(!this.isObjectVisibleInHierarchy(s.object))continue;let a=this.resolveNodeFromObject(s.object);if(a)return{node:a,distance:s.distance,point:s.point.clone(),object:s.object,instanceId:typeof s.instanceId=="number"?s.instanceId:void 0}}return null}resolveNodeFromObject(e){let t=e;for(;t;){if(t instanceof I)return t;t=t.parent}return null}isObjectVisibleInHierarchy(e){let t=e;for(;t;){if(!t.visible)return!1;t=t.parent}return!0}updateBillboardSprites(e,t){let i=t.getWorldQuaternion(new F),r=t.getWorldPosition(new S);for(let o of e)o instanceof ft?o.syncRenderState(i,r):(o instanceof mt||o instanceof xi)&&o.applyBillboard(i),o.children.length>0&&this.updateBillboardSprites(o.children,t)}stripEditorOnly(e){let t=[];for(let i of e){if(this.isEditorOnly(i)){i.removeFromParent(),i.dispose();continue}let r=i.children.filter(o=>o instanceof I);r.length>0&&this.stripEditorOnly(r),t.push(i)}return t}isEditorOnly(e){let t=e.properties;return this.toBooleanLike(t?.editorOnly)===!0}editorPeekMask=null;setEditorPeekMask(e){let t=e?new Set(e):null;this.editorPeekMask=t&&t.size>0?t:null,this.runtimeGraph&&this.applyEditorPeekMask(this.runtimeGraph.rootNodes)}applyEditorPeekMask(e){let t=this.editorPeekMask;for(let i of e){i.hiddenByEditor=t!==null&&t.has(i.nodeId);let r=i.children.filter(o=>o instanceof I);r.length>0&&this.applyEditorPeekMask(r)}}applyInitialVisibility(e){for(let t of e){let i=this.readInitialVisibility(t);i!==void 0&&(t.visible=i,t.properties.visible=i);let r=t.children.filter(o=>o instanceof I);r.length>0&&this.applyInitialVisibility(r)}}readInitialVisibility(e){let t=e.properties,i=t?.initiallyVisible,r=t?.initially_visible,o=e.userData.properties?.initiallyVisible;return this.toBooleanLike(i)??this.toBooleanLike(r)??this.toBooleanLike(o)}toBooleanLike(e){if(typeof e=="boolean")return e;if(typeof e=="string"){let t=e.trim().toLowerCase();return t==="true"?!0:t==="false"?!1:void 0}}reflowRoot2DNodes(){if(!this.runtimeGraph)return;let e={width:Math.max(1,this.logicalCameraSize.width),height:Math.max(1,this.logicalCameraSize.height)};for(let t of this.runtimeGraph.rootNodes)t instanceof C&&t.applyAnchoredLayoutRecursive(e,this.rootLayoutAuthoredSize);if(this.overlay2DActive=tw(this.runtimeGraph.rootNodes),this.batch2DEnabled){this.batch2D||(this.batch2D=new nn(this.scene)),this.ordered2DCount=0,Bs(this.runtimeGraph.rootNodes,this.collectOrdered2D);let t=this.ordered2DBuffer;t.length=this.ordered2DCount,this.scene.updateMatrixWorld(!0),this.batch2D.update(t)}else Bs(this.runtimeGraph.rootNodes)}stopAudioPlayers(e){e instanceof bt&&e.stop();for(let t of e.children)this.stopAudioPlayers(t)}detachScripts(e){for(let t of e.components){if(t.onDetach)try{t.onDetach()}catch(i){console.error("[SceneRunner] Component onDetach failed during stop()",{componentId:t.id,nodeId:e.nodeId,error:i})}di(t),t.resetStartedState?t.resetStartedState():t._started=!1}for(let t of e.children)t instanceof I&&this.detachScripts(t)}notifyFrameListeners(e){for(let t of this.frameListeners)t(e)}};var zp=class{renderer;canvas;resizeObserver=null;constructor(e={}){this.canvas=document.createElement("canvas"),this.canvas.style.display="block",this.canvas.style.width="100%",this.canvas.style.height="100%",this.renderer=new Bm({canvas:this.canvas,antialias:e.antialias??!0,alpha:!1,powerPreference:"high-performance"}),this.renderer.info.autoReset=!1,this.renderer.setPixelRatio(e.pixelRatio??window.devicePixelRatio),this.renderer.setClearColor(e.clearColor??"#000000"),this.renderer.localClippingEnabled=!0,e.shadows&&(this.renderer.shadowMap.enabled=!0,this.renderer.shadowMap.type=Jp)}get domElement(){return this.canvas}getWebGLRenderer(){return this.renderer}attach(e){this.resizeObserver?.disconnect(),e.appendChild(this.canvas),this.resize(),this.resizeObserver=new ResizeObserver(()=>{this.resize()}),this.resizeObserver.observe(e)}resize(){let e=this.canvas.parentElement;if(e){let t=e.clientWidth,i=e.clientHeight;this.renderer.setSize(t,i,!1)}}render(e,t){this.renderer.render(e,t)}beginStatsFrame(){this.renderer.info.reset()}getStatsSnapshot(){return{calls:this.renderer.info.render.calls,triangles:this.renderer.info.render.triangles,points:this.renderer.info.render.points,lines:this.renderer.info.render.lines,geometries:this.renderer.info.memory.geometries,textures:this.renderer.info.memory.textures,programs:this.renderer.info.programs?.length??0}}setAutoClear(e){this.renderer.autoClear=e}clear(){this.renderer.clear()}clearDepth(){this.renderer.clearDepth()}dispose(){this.resizeObserver?.disconnect(),this.resizeObserver=null,this.renderer.dispose(),this.canvas.remove()}};var oN=/\b(tr|trSprite|trPlural|setTextKey)\s*\(\s*(['"`])([^'"`\r\n]+?)\2/g;function sN(n){let e=[];for(let t of n.matchAll(oN)){if(t[3].includes("${"))continue;let i=n.slice(0,t.index??0).split(`
194
+ `).length;e.push({fn:t[1],key:t[3],line:i})}return e}var ow="res://assets/.atlas/atlas-manifest.json",sw="res://assets/.atlas/";async function aN(n,e){try{let t=await e.readText(ow),i=JSON.parse(t);if(!i||i.formatVersion!==1||!Array.isArray(i.sheets))return!1;let r=new Map(i.sheets.map(o=>[o.id,o.file]));return n.setAtlasResolver(Sc(i,o=>`${sw}${r.get(o)??`${o}.png`}`)),!0}catch{return!1}}var Po=class extends V{rotationSpeed=1;constructor(e,t){super(e,t),this.config={rotationSpeed:this.rotationSpeed}}static getPropertySchema(){return{nodeType:"RotateBehavior",properties:[{name:"rotationSpeed",type:"number",ui:{label:"Rotation Speed",description:"Speed of rotation in radians per second",group:"Component",min:0,max:10,step:.1},getValue:e=>e.getRotationSpeed(),setValue:(e,t)=>{let i=e,r=Number(t);!Number.isFinite(r)||r<0||i.setRotationSpeed(r)}}],groups:{Component:{label:"Component Parameters",description:"Configuration for rotation component",expanded:!0}}}}onAttach(){this.setRotationSpeed(this.getRotationSpeed())}onUpdate(e){!this.node||!(this.node instanceof U)||(this.node.rotation.y+=this.rotationSpeed*e)}getRotationSpeed(){let e=this.config.rotationSpeed,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:1}setRotationSpeed(e){this.rotationSpeed=e,this.config.rotationSpeed=e}};var ko=class extends V{constructor(e,t){super(e,t),this.config={speed:5,axisHorizontal:"Horizontal",axisVertical:"Vertical",movementPlane:"xz",invertVertical:!0}}static getPropertySchema(){return{nodeType:"SimpleMoveBehavior",properties:[{name:"speed",type:"number",ui:{label:"Speed",description:"Movement speed units per second",group:"Movement",min:0,max:50,step:.1},getValue:e=>e.getSpeed(),setValue:(e,t)=>{let i=e,r=Number(t);!Number.isFinite(r)||r<0||(i.config.speed=r)}},{name:"axisHorizontal",type:"string",ui:{label:"Horizontal Axis",description:"Input axis name for horizontal movement",group:"Input"},getValue:e=>e.getHorizontalAxis(),setValue:(e,t)=>{typeof t!="string"||t.trim().length===0||(e.config.axisHorizontal=t)}},{name:"axisVertical",type:"string",ui:{label:"Vertical Axis",description:"Input axis name for vertical movement",group:"Input"},getValue:e=>e.getVerticalAxis(),setValue:(e,t)=>{typeof t!="string"||t.trim().length===0||(e.config.axisVertical=t)}},{name:"movementPlane",type:"select",ui:{label:"Movement Plane",description:"Select whether vertical input moves on XY or XZ plane",group:"Movement",options:["xz","xy"]},getValue:e=>e.getMovementPlane(),setValue:(e,t)=>{(t==="xz"||t==="xy")&&(e.config.movementPlane=t)}},{name:"invertVertical",type:"boolean",ui:{label:"Invert Vertical",description:"Invert sign for vertical input axis",group:"Movement"},getValue:e=>e.isVerticalInverted(),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.invertVertical=t)}}],groups:{Movement:{label:"Movement",description:"Movement settings",expanded:!0},Input:{label:"Input",description:"Input axis mapping",expanded:!0}}}}onUpdate(e){if(!this.input||!this.node)return;let t=this.input.getAxis(this.getHorizontalAxis()),i=this.input.getAxis(this.getVerticalAxis());if(t===0&&i===0)return;let r=this.isVerticalInverted()?-i:i,o=t*this.getSpeed()*e,s=r*this.getSpeed()*e;this.node.position.x+=o,this.getMovementPlane()==="xy"?this.node.position.y+=s:this.node.position.z+=s}getSpeed(){let e=this.config.speed,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:5}getHorizontalAxis(){let e=this.config.axisHorizontal;return typeof e=="string"&&e.length>0?e:"Horizontal"}getVerticalAxis(){let e=this.config.axisVertical;return typeof e=="string"&&e.length>0?e:"Vertical"}getMovementPlane(){let e=this.config.movementPlane;return e==="xy"||e==="xz"?e:"xz"}isVerticalInverted(){let e=this.config.invertVertical;return typeof e=="boolean"?e:!0}};var Ao=class extends V{elapsedTime=0;initialPositionX=0;initialPositionY=0;initialPositionZ=0;constructor(e,t){super(e,t),this.config={amplitude:1,frequency:1,axis:"y"}}static getPropertySchema(){return{nodeType:"SineBehavior",properties:[{name:"amplitude",type:"number",ui:{label:"Amplitude",description:"Maximum displacement from the center",group:"Oscillation",min:0,step:.1},getValue:e=>e.getAmplitude(),setValue:(e,t)=>{let i=e,r=Number(t);!Number.isFinite(r)||r<0||(i.config.amplitude=r)}},{name:"frequency",type:"number",ui:{label:"Frequency (Hz)",description:"Oscillations per second",group:"Oscillation",min:0,step:.1},getValue:e=>e.getFrequency(),setValue:(e,t)=>{let i=e,r=Number(t);!Number.isFinite(r)||r<0||(i.config.frequency=r)}},{name:"axis",type:"select",ui:{label:"Axis",description:"The axis to oscillate along",group:"Oscillation",options:["x","y","z"]},getValue:e=>e.getAxis(),setValue:(e,t)=>{let i=e;(t==="x"||t==="y"||t==="z")&&(i.config.axis=t)}}],groups:{Oscillation:{label:"Oscillation Settings",expanded:!0}}}}onStart(){this.node&&(this.initialPositionX=this.node.position.x,this.initialPositionY=this.node.position.y,this.initialPositionZ=this.node.position.z)}onUpdate(e){if(!this.node)return;this.elapsedTime+=e;let t=Math.sin(this.elapsedTime*this.getFrequency()*Math.PI*2)*this.getAmplitude();this.node.position.set(this.initialPositionX,this.initialPositionY,this.initialPositionZ);let i=this.getAxis();i==="x"?this.node.position.x+=t:i==="y"?this.node.position.y+=t:this.node.position.z+=t}getAmplitude(){let e=this.config.amplitude,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:1}getFrequency(){let e=this.config.frequency,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:1}getAxis(){let e=this.config.axis;return e==="x"||e==="y"||e==="z"?e:"y"}};var To=class extends V{targetNodeId="";yOffset=2;targetNode=null;cameraNode=null;_unsubscribeViewport=null;_tempWorldPos=new S;_tempPinnedWorldPos=new S;_tempPinnedLocalPos=new S;static getPropertySchema(){return{nodeType:"PinToNodeBehavior",properties:[x("targetNodeId","node",{ui:{label:"Target Model",nodeTypes:["MeshInstance","Node3D","Sprite3D"]},getValue:e=>e.targetNodeId,setValue:(e,t)=>{e.setTargetNodeId(String(t))}}),x("yOffset","number",{ui:{label:"Y Offset",step:.1},getValue:e=>e.yOffset,setValue:(e,t)=>{e.yOffset=Number(t)}})],groups:{}}}setTargetNodeId(e){this.targetNodeId=e,this.targetNode=null}getSceneRoot(){if(!this.node)return null;let e=this.node;for(;e.parent;)e=e.parent;return e}resolveProjectionCamera(e){let t=this.scene?.getActiveCamera()??null;return t?(this.cameraNode=t,t):this.cameraNode?this.cameraNode:(e&&this.findCamera(e),this.cameraNode)}onStart(){if(this.targetNode=null,this.cameraNode=null,this._unsubscribeViewport?.(),this._unsubscribeViewport=this.scene?.onViewportChanged(()=>{this.updatePinning()})??null,!this.node)return;let e=this.getSceneRoot();e&&(this.targetNodeId&&(this.targetNode=this.findNode(this.targetNodeId)),this.resolveProjectionCamera(e),this.updatePinning())}onDetach(){this._unsubscribeViewport?.(),this._unsubscribeViewport=null}findCamera(e){if(e instanceof pe){this.cameraNode=e;return}for(let t of e.children)if(this.findCamera(t),this.cameraNode)return}onUpdate(e){this.updatePinning()}updatePinning(){if(!this.node||!(this.node instanceof C))return;let e=this.getSceneRoot();if(!e)return;!this.targetNode&&this.targetNodeId&&(this.targetNode=this.findNode(this.targetNodeId));let t=this.resolveProjectionCamera(e);if(!this.targetNode||!t)return;let i=this.targetNode,r=t.camera;if(!i||!r)return;i.updateMatrixWorld(!0),this._tempWorldPos.setFromMatrixPosition(i.matrixWorld),this._tempWorldPos.y+=this.yOffset,this._tempWorldPos.project(r);let o=this.getLogicalCameraSize();if(o.width<=0||o.height<=0)return;this._tempPinnedWorldPos.set(this._tempWorldPos.x*(o.width*.5),this._tempWorldPos.y*(o.height*.5),0);let s=this.node.parent;s&&(s.updateMatrixWorld(!0),this._tempPinnedLocalPos.copy(this._tempPinnedWorldPos),s.worldToLocal(this._tempPinnedLocalPos),this.node.position.set(this._tempPinnedLocalPos.x,this._tempPinnedLocalPos.y,this.node.position.z))}getLogicalCameraSize(){let e=this.scene?.getLogicalCameraSize();if(e&&e.width>0&&e.height>0)return e;let t=this.scene?.getViewportSize(),i=t&&t.width>0?t.width:window.innerWidth,r=t&&t.height>0?t.height:window.innerHeight;return i<=0||r<=0?{width:1,height:1}:{width:i,height:r}}};var Co=class n extends V{fadeDirection=null;phase="idle";pendingDestroy=!1;delayRemaining=0;sequenceStarted=!1;constructor(e,t){super(e,t),this.config={FadeInTime:.5,FadeOutTime:.5,FadeInDelay:0,FadeOutDelay:0,DestroyOnFadeOut:!1,FadeOnStart:!1}}static getPropertySchema(){return{nodeType:"FadeBehavior",properties:[{name:"FadeInTime",type:"number",ui:{label:"FadeInTime",group:"Fade",min:0,step:.01,precision:2,unit:"s"},getValue:e=>e.getFadeInTime(),setValue:(e,t)=>{e.setFadeInTime(t)}},{name:"FadeOutTime",type:"number",ui:{label:"FadeOutTime",group:"Fade",min:0,step:.01,precision:2,unit:"s"},getValue:e=>e.getFadeOutTime(),setValue:(e,t)=>{e.setFadeOutTime(t)}},{name:"FadeInDelay",type:"number",ui:{label:"FadeInDelay",group:"Fade",min:0,step:.01,precision:2,unit:"s"},getValue:e=>e.getFadeInDelay(),setValue:(e,t)=>{e.setFadeInDelay(t)}},{name:"FadeOutDelay",type:"number",ui:{label:"FadeOutDelay",group:"Fade",min:0,step:.01,precision:2,unit:"s"},getValue:e=>e.getFadeOutDelay(),setValue:(e,t)=>{e.setFadeOutDelay(t)}},{name:"DestroyOnFadeOut",type:"boolean",ui:{label:"DestroyOnFadeOut",group:"Fade"},getValue:e=>e.getDestroyOnFadeOut(),setValue:(e,t)=>{e.setDestroyOnFadeOut(t)}},{name:"FadeOnStart",type:"boolean",ui:{label:"FadeOnStart",group:"Fade"},getValue:e=>e.getFadeOnStart(),setValue:(e,t)=>{e.setFadeOnStart(t)}}],groups:{Fade:{label:"Fade",description:"Opacity fade settings",expanded:!0}}}}onStart(){this.isNode2D()&&this.getFadeOnStart()&&(this.sequenceStarted=!0,this.node.opacity=0,this.startFade("in"))}onUpdate(e){if(this.isNode2D()){if(this.pendingDestroy){this.pendingDestroy=!1,this.destroyNode();return}this.phase==="delay"&&(this.delayRemaining=Math.max(0,this.delayRemaining-e),this.delayRemaining===0&&(this.phase="idle",this.executeFade()))}}onDetach(){super.onDetach(),this.stopFade(),this.pendingDestroy=!1,this.sequenceStarted=!1}fadeIn(){this.sequenceStarted=!1,this.startFade("in")}fadeOut(){this.sequenceStarted=!1,this.startFade("out")}startFade(e){if(!this.isNode2D())return;this.pendingDestroy=!1,this.fadeDirection=e;let t=e==="in"?this.getFadeInDelay():this.getFadeOutDelay();if(t>0){this.phase="delay",this.delayRemaining=t;return}this.executeFade()}executeFade(){if(!this.isNode2D()||!this.fadeDirection)return;let e=this.fadeDirection==="in"?this.getFadeInTime():this.getFadeOutTime(),t=()=>this.onFadeComplete();this.fadeDirection==="in"?this.node.show(e,t):this.node.hide(e,t)}onFadeComplete(){let e=this.fadeDirection;if(this.stopFade(),e==="in"&&this.sequenceStarted){this.startFade("out");return}e==="out"&&this.getDestroyOnFadeOut()&&(this.pendingDestroy=!0)}stopFade(){this.fadeDirection=null,this.phase="idle",this.delayRemaining=0}destroyNode(){if(!this.node)return;let e=this.node.parentNode;e&&e.disownChild(this.node)}isNode2D(){return this.node instanceof C}getFadeInTime(){return n.toNonNegativeNumber(this.config.FadeInTime,.5)}setFadeInTime(e){this.config.FadeInTime=n.toNonNegativeNumber(e,.5)}getFadeOutTime(){return n.toNonNegativeNumber(this.config.FadeOutTime,.5)}setFadeOutTime(e){this.config.FadeOutTime=n.toNonNegativeNumber(e,.5)}getFadeInDelay(){return n.toNonNegativeNumber(this.config.FadeInDelay,0)}setFadeInDelay(e){this.config.FadeInDelay=n.toNonNegativeNumber(e,0)}getFadeOutDelay(){return n.toNonNegativeNumber(this.config.FadeOutDelay,0)}setFadeOutDelay(e){this.config.FadeOutDelay=n.toNonNegativeNumber(e,0)}getDestroyOnFadeOut(){return!!this.config.DestroyOnFadeOut}setDestroyOnFadeOut(e){this.config.DestroyOnFadeOut=!!e}getFadeOnStart(){return!!this.config.FadeOnStart}setFadeOnStart(e){this.config.FadeOnStart=!!e}static toNonNegativeNumber(e,t){let i=typeof e=="number"?e:Number(e);return Number.isFinite(i)?Math.max(0,i):t}};var lN=`
195
+ varying vec2 vUv;
196
+ void main() {
197
+ vUv = uv;
198
+ gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);
199
+ }
200
+ `,cN=`
201
+ uniform sampler2D map;
202
+ uniform bool hasMap;
203
+ uniform vec3 color;
204
+ uniform float opacity;
205
+ uniform float progress;
206
+ uniform float startAngleCos;
207
+ uniform float startAngleSin;
208
+ uniform float direction;
209
+
210
+ varying vec2 vUv;
211
+
212
+ void main() {
213
+ vec4 texColor = hasMap ? texture2D(map, vUv) : vec4(1.0);
214
+ texColor.rgb *= color;
215
+
216
+ vec2 uv = vUv - 0.5;
217
+ // Rotate by -startAngle: new_x = cos*x - sin*y, new_y = sin*x + cos*y (clockwise rotation)
218
+ // We rotate the uv point to align the start angle with "up" (positive y)
219
+ vec2 rotated = vec2(
220
+ startAngleCos * uv.x + startAngleSin * uv.y,
221
+ -startAngleSin * uv.x + startAngleCos * uv.y
222
+ );
223
+
224
+ // atan(x, y) gives angle from +y axis (top), going clockwise for positive x
225
+ float angle = atan(rotated.x * direction, rotated.y);
226
+
227
+ const float TWO_PI = 6.28318530718;
228
+ if (angle < 0.0) angle += TWO_PI;
229
+
230
+ float threshold = clamp(progress, 0.0, 1.0) * TWO_PI;
231
+ if (angle > threshold) {
232
+ discard;
233
+ }
234
+
235
+ gl_FragColor = vec4(texColor.rgb, texColor.a * opacity);
236
+ }
237
+ `,Mo=class extends V{_value=1;_currentValue=1;_animationSpeed=3;_startAngle=0;_clockwise=!0;_opacity=1;_radialMaterial=null;_originalMaterial=null;_spriteMesh=null;_lastKnownTexture=null;constructor(e,t){super(e,t),this.config={value:this._value,animationSpeed:this._animationSpeed,startAngle:this._startAngle,clockwise:this._clockwise}}static getPropertySchema(){return{nodeType:"RadialProgressBehavior",properties:[{name:"value",type:"number",ui:{label:"Value",description:"Target progress from 0.0 (empty) to 1.0 (full)",group:"Progress",min:0,max:1,step:.01,precision:2},getValue:e=>e.getValue(),setValue:(e,t)=>e.setValue(Number(t))},{name:"animationSpeed",type:"number",ui:{label:"Animation Speed",description:"How fast the progress bar animates (higher = faster)",group:"Progress",min:0,max:20,step:.1,precision:1},getValue:e=>e.getAnimationSpeed(),setValue:(e,t)=>e.setAnimationSpeed(Number(t))},{name:"startAngle",type:"number",ui:{label:"Start Angle",description:"Starting angle in degrees. 0 = top (12 o'clock), 90 = right",group:"Progress",min:-360,max:360,step:1,precision:0,unit:"\xB0"},getValue:e=>Math.round(e.getStartAngle()*(180/Math.PI)),setValue:(e,t)=>e.setStartAngle(Number(t)*(Math.PI/180))},{name:"clockwise",type:"boolean",ui:{label:"Clockwise",description:"Fill direction: clockwise or counter-clockwise",group:"Progress"},getValue:e=>e.getClockwise(),setValue:(e,t)=>e.setClockwise(!!t)}],groups:{Progress:{label:"Radial Progress",description:"Parameters for radial progress masking",expanded:!0}}}}onAttach(){if(!(this.node instanceof Fe)){console.warn("[RadialProgressBehavior] Must be attached to a Sprite2D node");return}let t=this.node.children.find(s=>s instanceof O);if(!t){console.warn("[RadialProgressBehavior] No mesh found on Sprite2D");return}this._spriteMesh=t,this._originalMaterial=t.material;let r=Array.isArray(t.material)?t.material[0]:t.material,o=r.map??null;this._lastKnownTexture=o,this._opacity=r.opacity??1,this._radialMaterial=this._buildMaterial(o,r),t.material=this._radialMaterial,this._currentValue=this._value,this._updateUniforms()}onUpdate(e){if(!this._radialMaterial||!this._spriteMesh)return;let t=this._animationSpeed;if(t<=0)this._currentValue=this._value;else{let i=this._value-this._currentValue,r=i*Math.min(t*e,1);this._currentValue+=r,Math.abs(i)<1e-4&&(this._currentValue=this._value)}this._syncTexture(),this._updateUniforms()}onDetach(){this._spriteMesh&&this._originalMaterial!==null&&(this._spriteMesh.material=this._originalMaterial)}getValue(){return this._value}setValue(e,t=!1){let i=Math.max(0,Math.min(1,e));this._value=i,this.config.value=i,t&&(this._currentValue=i,this._updateUniforms())}setValueImmediate(e){this.setValue(e,!0)}getAnimationSpeed(){return this._animationSpeed}setAnimationSpeed(e){this._animationSpeed=Math.max(0,e),this.config.animationSpeed=this._animationSpeed}getStartAngle(){return this._startAngle}setStartAngle(e){this._startAngle=e,this.config.startAngle=Math.round(e*(180/Math.PI)),this._updateAngleUniforms()}getClockwise(){return this._clockwise}setClockwise(e){this._clockwise=e,this.config.clockwise=e,this._radialMaterial&&(this._radialMaterial.uniforms.direction.value=e?1:-1)}_buildMaterial(e,t){let i=t.color?.r??1,r=t.color?.g??1,o=t.color?.b??1;return new km({uniforms:{map:{value:e},hasMap:{value:e!==null},color:{value:[i,r,o]},opacity:{value:this._opacity},progress:{value:this._currentValue},startAngleCos:{value:Math.cos(this._startAngle)},startAngleSin:{value:Math.sin(this._startAngle)},direction:{value:this._clockwise?1:-1}},vertexShader:lN,fragmentShader:cN,transparent:!0,depthTest:!1})}_syncTexture(){if(!this._originalMaterial||!this._radialMaterial)return;let t=(Array.isArray(this._originalMaterial)?this._originalMaterial[0]:this._originalMaterial).map??null;t!==this._lastKnownTexture&&(this._lastKnownTexture=t,this._radialMaterial.uniforms.map.value=t,this._radialMaterial.uniforms.hasMap.value=t!==null)}_updateUniforms(){this._radialMaterial&&(this._radialMaterial.uniforms.progress.value=this._currentValue,this._radialMaterial.uniforms.opacity.value=this._opacity)}_updateAngleUniforms(){this._radialMaterial&&(this._radialMaterial.uniforms.startAngleCos.value=Math.cos(this._startAngle),this._radialMaterial.uniforms.startAngleSin.value=Math.sin(this._startAngle))}};var Do=class extends V{onNodeSignal=()=>{this.playConfiguredSound()};constructor(e,t){super(e,t),this.config={audioTrack:"",triggerEvent:"pointerdown",volume:1,loop:!1,bus:"sfx",pitchVariation:0,volumeVariation:0}}static getPropertySchema(){return{nodeType:"PlaySoundBehavior",properties:[{name:"audioTrack",type:"string",ui:{label:"Audio Track",description:"Asset URL (res://..., data:audio/..., or absolute URL)",group:"Audio",editor:"audio-resource"},getValue:e=>e.getAudioTrack(),setValue:(e,t)=>{e.setAudioTrack(t)}},{name:"triggerEvent",type:"string",ui:{label:"Trigger Event",description:"Node signal or UI event (pointerdown, pointerup, click)",group:"Audio"},getValue:e=>e.getTriggerEvent(),setValue:(e,t)=>{e.setTriggerEvent(t)}},{name:"volume",type:"number",ui:{label:"Volume",group:"Audio",min:0,max:1,step:.01,precision:2},getValue:e=>e.getVolume(),setValue:(e,t)=>{e.setVolume(t)}},{name:"loop",type:"boolean",ui:{label:"Loop",group:"Audio"},getValue:e=>e.getLoop(),setValue:(e,t)=>{e.setLoop(t)}},{name:"bus",type:"enum",ui:{label:"Bus",group:"Audio",options:[...dt]},getValue:e=>e.getBus(),setValue:(e,t)=>{e.setBus(t)}},{name:"pitchVariation",type:"number",ui:{label:"Pitch Variation",description:"Random \xB1 playback-rate spread per shot",group:"Audio",min:0,max:1,step:.01,precision:2},getValue:e=>e.getPitchVariation(),setValue:(e,t)=>{e.setPitchVariation(t)}},{name:"volumeVariation",type:"number",ui:{label:"Volume Variation",description:"Random \xB1 volume spread per shot",group:"Audio",min:0,max:1,step:.01,precision:2},getValue:e=>e.getVolumeVariation(),setValue:(e,t)=>{e.setVolumeVariation(t)}}],groups:{Audio:{label:"Audio",expanded:!0}}}}onStart(){this.bindTrigger()}onDetach(){this.unbindTrigger(),super.onDetach()}bindTrigger(){if(!this.node)return;let e=this.getTriggerEvent();this.node.connect(e,this,this.onNodeSignal)}unbindTrigger(){if(!this.node)return;let e=this.getTriggerEvent();this.node.disconnect(e,this,this.onNodeSignal)}async playConfiguredSound(){let e=this.scene,t=this.node;if(!e||!t)return;let i=this.getAudioTrack();if(!i){console.warn("[PlaySoundBehavior] audioTrack is not configured.");return}let r=e.getAssetLoader(),o=e.getAudioService();if(!r||!o){console.warn("[PlaySoundBehavior] Audio services are not available in this runtime context.");return}try{let s=await r.loadAudio(i),a=e.getAudioService();if(!a)return;let l=r.getAudioMetadata(i);a.play(s,{resourcePath:i,sizeBytes:l?.sizeBytes,volume:this.getVolume(),loop:this.getLoop(),bus:this.getBus(),pitchVariation:this.getPitchVariation(),volumeVariation:this.getVolumeVariation()})}catch(s){console.warn(`[PlaySoundBehavior] Failed to play "${i}" on node "${t.name}":`,s)}}getAudioTrack(){return this.normalizeTrack(this.config.audioTrack)}setAudioTrack(e){this.config.audioTrack=this.normalizeTrack(e)}getTriggerEvent(){let e=this.config.triggerEvent;if(typeof e!="string")return"pointerdown";let t=e.trim();return t.length>0?t:"pointerdown"}setTriggerEvent(e){let t=!!this.node;t&&this.unbindTrigger(),this.config.triggerEvent=this.toTrimmedString(e,"pointerdown"),t&&this.bindTrigger()}getVolume(){return this.toVolume(this.config.volume,1)}setVolume(e){this.config.volume=this.toVolume(e,1)}getLoop(){return this.toBoolean(this.config.loop,!1)}setLoop(e){this.config.loop=this.toBoolean(e,!1)}getBus(){return this.toBus(this.config.bus)}setBus(e){this.config.bus=this.toBus(e)}getPitchVariation(){return this.toVariation(this.config.pitchVariation)}setPitchVariation(e){this.config.pitchVariation=this.toVariation(e)}getVolumeVariation(){return this.toVariation(this.config.volumeVariation)}setVolumeVariation(e){this.config.volumeVariation=this.toVariation(e)}normalizeTrack(e){return this.toTrimmedString(e,"")}toTrimmedString(e,t){if(typeof e!="string")return t;let i=e.trim();return i.length>0?i:t}toBoolean(e,t){if(typeof e=="boolean")return e;if(typeof e=="string"){let i=e.trim().toLowerCase();if(i==="true")return!0;if(i==="false")return!1}return t}toVolume(e,t){let i=typeof e=="number"?e:Number(e);return Number.isFinite(i)?Math.min(1,Math.max(0,i)):t}toBus(e){return typeof e=="string"&&dt.includes(e)?e:"sfx"}toVariation(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.min(1,Math.max(0,t)):0}};var Eo=class n extends V{boundSignal=null;onSignal=()=>{this.scene?.audio.sfx(this.getPreset(),{volume:this.getVolume(),pitch:this.getPitch()})};constructor(e,t){super(e,t),this.config={signal:"pointerdown",preset:"tap",volume:1,pitch:1}}static getPropertySchema(){return{nodeType:"SfxOnSignalBehavior",properties:[{name:"signal",type:"string",ui:{label:"Signal",description:"Node signal that plays the sound (pointerdown, hit, damaged, \u2026)",group:"Procedural SFX"},getValue:e=>e.getSignal(),setValue:(e,t)=>{e.setSignal(t)}},{name:"preset",type:"enum",ui:{label:"Preset",description:"Built-in synth patch played on the sfx bus",group:"Procedural SFX",options:[...bl]},getValue:e=>e.getPreset(),setValue:(e,t)=>{e.config.preset=Rr(t)?t:"tap"}},{name:"volume",type:"number",ui:{label:"Volume",group:"Procedural SFX",min:0,max:1,step:.01,precision:2},getValue:e=>e.getVolume(),setValue:(e,t)=>{e.config.volume=n.clamp01(t)}},{name:"pitch",type:"number",ui:{label:"Pitch",description:"Frequency multiplier: 2 = an octave up, 0.5 = an octave down",group:"Procedural SFX",min:.25,max:4,step:.05,precision:2},getValue:e=>e.getPitch(),setValue:(e,t)=>{e.config.pitch=Wi(t)}}],groups:{"Procedural SFX":{label:"Procedural SFX",description:"Synthesized one-shot played when the signal fires",expanded:!0}}}}onStart(){this.bind()}onDetach(){this.unbind(),super.onDetach()}bind(){this.node&&(this.boundSignal=this.getSignal(),this.node.connect(this.boundSignal,this,this.onSignal))}unbind(){!this.node||!this.boundSignal||(this.node.disconnect(this.boundSignal,this,this.onSignal),this.boundSignal=null)}getSignal(){let e=this.config.signal;if(typeof e!="string")return"pointerdown";let t=e.trim();return t.length>0?t:"pointerdown"}setSignal(e){let t=!!this.node;t&&this.unbind(),this.config.signal=typeof e=="string"&&e.trim().length>0?e.trim():"pointerdown",t&&this.bind()}getPreset(){return Rr(this.config.preset)?this.config.preset:"tap"}getVolume(){return n.clamp01(this.config.volume)}getPitch(){return Wi(this.config.pitch)}static clamp01(e){let t=typeof e=="number"?e:Number(e);return Number.isFinite(t)?Math.min(1,Math.max(0,t)):1}};var No=class n extends V{boundSignal=null;onSignal=()=>{let e=this.node,t=this.scene;!e||!t||t.juice.burst(e,this.buildOptions())};constructor(e,t){super(e,t),this.config={signal:"hit",count:14,color:"",speed:260,sizePx:10,lifeSec:.5,gravityY:-600}}static getPropertySchema(){return{nodeType:"BurstOnSignalBehavior",properties:[{name:"signal",type:"string",ui:{label:"Signal",description:"Node signal that fires the burst (e.g. hit, damaged, pointerdown)",group:"Burst"},getValue:e=>e.getSignal(),setValue:(e,t)=>{e.setSignal(t)}},{name:"count",type:"number",ui:{label:"Count",description:"Particles per burst",group:"Burst",min:1,max:512,step:1,precision:0},getValue:e=>e.getNumber("count",14),setValue:(e,t)=>{e.config.count=n.num(t,14)}},{name:"color",type:"color",ui:{label:"Color",description:"Particle colour; empty = white",group:"Burst"},getValue:e=>e.getColor(),setValue:(e,t)=>{e.config.color=typeof t=="string"?t.trim():""}},{name:"speed",type:"number",ui:{label:"Speed",description:"Initial particle speed",group:"Burst",min:0,step:10,precision:0,unit:"px/s"},getValue:e=>e.getNumber("speed",260),setValue:(e,t)=>{e.config.speed=n.num(t,260)}},{name:"sizePx",type:"number",ui:{label:"Size",group:"Burst",min:.5,step:1,precision:1,unit:"px"},getValue:e=>e.getNumber("sizePx",10),setValue:(e,t)=>{e.config.sizePx=n.num(t,10)}},{name:"lifeSec",type:"number",ui:{label:"Life",group:"Burst",min:.05,step:.05,precision:2,unit:"s"},getValue:e=>e.getNumber("lifeSec",.5),setValue:(e,t)=>{e.config.lifeSec=n.num(t,.5)}},{name:"gravityY",type:"number",ui:{label:"Gravity Y",description:"Vertical acceleration; negative falls, 0 = weightless",group:"Burst",step:50,precision:0,unit:"px/s\xB2"},getValue:e=>e.getNumber("gravityY",-600),setValue:(e,t)=>{e.config.gravityY=n.num(t,-600)}}],groups:{Burst:{label:"Particle Burst",description:"One-shot particles spawned when the signal fires",expanded:!0}}}}onStart(){this.bind()}onDetach(){this.unbind(),super.onDetach()}buildOptions(){let e=this.getColor();return{count:this.getNumber("count",14),speed:this.getNumber("speed",260),sizePx:this.getNumber("sizePx",10),lifeSec:this.getNumber("lifeSec",.5),gravityY:this.getNumber("gravityY",-600),...e?{color:e}:{}}}bind(){this.node&&(this.boundSignal=this.getSignal(),this.node.connect(this.boundSignal,this,this.onSignal))}unbind(){!this.node||!this.boundSignal||(this.node.disconnect(this.boundSignal,this,this.onSignal),this.boundSignal=null)}getSignal(){let e=this.config.signal;if(typeof e!="string")return"hit";let t=e.trim();return t.length>0?t:"hit"}setSignal(e){let t=!!this.node;t&&this.unbind(),this.config.signal=typeof e=="string"&&e.trim().length>0?e.trim():"hit",t&&this.bind()}getColor(){return typeof this.config.color=="string"?this.config.color.trim():""}getNumber(e,t){return n.num(this.config[e],t)}static num(e,t){if(e==null||e==="")return t;let i=typeof e=="number"?e:Number(e);return Number.isFinite(i)?i:t}};function Yi(n){if(!Array.isArray(n)||n.length===0)return[];if(typeof n[0]=="number"){let t=[];for(let i=0;i+1<n.length;i+=2){let r=Number(n[i]),o=Number(n[i+1]);Number.isFinite(r)&&Number.isFinite(o)&&t.push({x:r,y:o})}return t}let e=[];for(let t of n){if(Array.isArray(t)){let i=Number(t[0]),r=Number(t[1]);Number.isFinite(i)&&Number.isFinite(r)&&e.push({x:i,y:r});continue}if(t&&typeof t=="object"){let i=Number(t.x),r=Number(t.y);Number.isFinite(i)&&Number.isFinite(r)&&e.push({x:i,y:r})}}return e}function uN(n){return n.map(e=>({x:Math.round(e.x*100)/100,y:Math.round(e.y*100)/100}))}var Io=class extends V{debugLine=null;debugKey="";polygonCacheInput=void 0;polygonCache=[];constructor(e,t){super(e,t),this.config={shape:"rect",width:64,height:64,radius:32,offsetX:0,offsetY:0,points:[],polygonSource:"manual",group:"default",debugDraw:!1}}static getPropertySchema(){let e=(t,i,r)=>({name:t,type:"number",ui:{label:i,group:r,step:1},getValue:o=>o.config[t],setValue:(o,s)=>{o.config[t]=Number(s)}});return{nodeType:"Hitbox2D",properties:[{name:"shape",type:"select",ui:{label:"Shape",description:"Rect and circle are axis-aligned (rotation ignored, scale honored); polygon is rotation-aware and may be concave",group:"Shape",options:["rect","circle","polygon"]},getValue:t=>t.config.shape,setValue:(t,i)=>{t.config.shape=i==="circle"?"circle":i==="polygon"?"polygon":"rect"}},e("width","Width","Shape"),e("height","Height","Shape"),e("radius","Radius","Shape"),e("offsetX","Offset X","Shape"),e("offsetY","Offset Y","Shape"),{name:"polygonSource",type:"select",ui:{label:"Polygon Source",description:"manual: the vertices below. frame: the collision polygon of the animation frame currently showing on this AnimatedSprite2D.",group:"Shape",options:["manual","frame"]},getValue:t=>t.config.polygonSource??"manual",setValue:(t,i)=>{t.config.polygonSource=i==="frame"?"frame":"manual"}},{name:"points",type:"object",ui:{label:"Polygon",description:"Vertices in node-local pixels (y up). Edit them in the viewport.",group:"Shape",editor:"collision-polygon"},getValue:t=>t.config.points??[],setValue:(t,i)=>{t.config.points=Yi(i)}},{name:"group",type:"string",ui:{label:"Group",description:"Collision group tag used to filter queries (Godot-style group)",group:"Filtering"},getValue:t=>t.config.group,setValue:(t,i)=>{t.config.group=String(i??"default")}},{name:"debugDraw",type:"boolean",ui:{label:"Debug Draw",description:"Render the shape outline in play mode",group:"Debug"},getValue:t=>t.config.debugDraw,setValue:(t,i)=>{t.config.debugDraw=!!i}}],groups:{Shape:{label:"Shape",expanded:!0},Filtering:{label:"Filtering",expanded:!0},Debug:{label:"Debug",expanded:!1}}}}getHitboxShape(){let e=this.config.shape;return e==="circle"?"circle":e==="polygon"?"polygon":"rect"}getHitboxSize(){return{width:Number(this.config.width)||0,height:Number(this.config.height)||0,radius:Number(this.config.radius)||0}}getHitboxOffset(){return{x:Number(this.config.offsetX)||0,y:Number(this.config.offsetY)||0}}getHitboxGroup(){return String(this.config.group??"default")}getHitboxPolygon(){if(this.config.polygonSource==="frame"){let t=this.node;return typeof t?.getFrameCollisionPolygon=="function"?t.getFrameCollisionPolygon():[]}let e=this.config.points;return e!==this.polygonCacheInput&&(this.polygonCacheInput=e,this.polygonCache=Yi(e)),this.polygonCache}onStart(){this.scene?.collision2d.register(this)}onUpdate(){this.syncDebugDraw()}onDetach(){this.scene?.collision2d.unregister(this),this.removeDebugLine(),super.onDetach()}syncDebugDraw(){let e=this.node;if(!e)return;if(!this.config.debugDraw){this.removeDebugLine();return}let t=this.getHitboxSize(),i=this.getHitboxOffset(),r=this.getHitboxShape(),o=r==="polygon"?this.getHitboxPolygon():null,s=r==="polygon"?`polygon|${i.x}|${i.y}|${o?.map(h=>`${h.x},${h.y}`).join(" ")}`:`${r}|${t.width}|${t.height}|${t.radius}|${i.x}|${i.y}`;if(this.debugLine&&s===this.debugKey)return;this.removeDebugLine(),this.debugKey=s;let a=[];if(r==="polygon"){if(!o||o.length<3)return;for(let h of o)a.push(i.x+h.x,i.y+h.y,0)}else if(r==="circle")for(let d=0;d<32;d++){let p=d/32*Math.PI*2;a.push(i.x+Math.cos(p)*t.radius,i.y+Math.sin(p)*t.radius,0)}else{let h=t.width/2,d=t.height/2;a.push(i.x-h,i.y-d,0,i.x+h,i.y-d,0,i.x+h,i.y+d,0,i.x-h,i.y+d,0)}let l=new ae;l.setAttribute("position",new Q(a,3));let c=new Nt({color:8255999,depthTest:!1,transparent:!0,opacity:.9}),u=new Zo(l,c);u.renderOrder=5e3,u.userData[ze]=!0,e.add(u),this.debugLine=u}removeDebugLine(){this.debugLine&&(this.debugLine.removeFromParent(),this.debugLine.geometry.dispose(),this.debugLine.material.dispose(),this.debugLine=null,this.debugKey="")}};var Ro=class extends V{constructor(e,t){super(e,t),this.config={bodyType:"dynamic",gravityScale:1,mass:0,linearDamping:0,angularDamping:.05,fixedRotation:!1,bullet:!1,canSleep:!0,emitContacts:!1}}static getPropertySchema(){let e=(i,r,o,s,a=.05)=>({name:i,type:"number",ui:{label:r,group:o,step:a,description:s},getValue:l=>l.config[i],setValue:(l,c)=>{l.config[i]=Number(c)}}),t=(i,r,o,s)=>({name:i,type:"boolean",ui:{label:r,group:o,description:s},getValue:a=>a.config[i],setValue:(a,l)=>{a.config[i]=!!l}});return{nodeType:"PhysicsBody2D",properties:[{name:"bodyType",type:"select",ui:{label:"Body Type",description:"static: never moves. kinematic: moved by scripts/animation, pushes others, is not pushed. dynamic: simulated.",group:"Body",options:["static","kinematic","dynamic"]},getValue:i=>i.config.bodyType,setValue:(i,r)=>{i.config.bodyType=r==="static"?"static":r==="kinematic"?"kinematic":"dynamic"}},e("gravityScale","Gravity Scale","Body","Multiplier on world gravity. 0 makes the body float; negative makes it rise."),e("mass","Mass","Body","Explicit mass. 0 derives it from the collider area times its density.",.1),e("linearDamping","Linear Damping","Damping","Per-second velocity decay."),e("angularDamping","Angular Damping","Damping","Per-second spin decay."),t("fixedRotation","Fixed Rotation","Body","Lock the rotation \u2014 the usual choice for a character or a UI prop."),t("bullet","Bullet (CCD)","Body","Sweep this body against static geometry so a fast circle cannot tunnel through a wall."),t("canSleep","Can Sleep","Body","Let the body stop simulating once it has been at rest for half a second."),t("emitContacts","Emit Contacts","Signals","Fire contact-started / contact-ended on this node. Off by default: most games never read them.")],groups:{Body:{label:"Body",expanded:!0},Damping:{label:"Damping",expanded:!1},Signals:{label:"Signals",expanded:!1}}}}getBodyType(){let e=this.config.bodyType;return e==="static"?"static":e==="kinematic"?"kinematic":"dynamic"}getBodyConfig(){return{gravityScale:Cl(this.config.gravityScale,1),mass:Math.max(0,Cl(this.config.mass,0)),linearDamping:Math.max(0,Cl(this.config.linearDamping,0)),angularDamping:Math.max(0,Cl(this.config.angularDamping,0)),fixedRotation:!!this.config.fixedRotation,bullet:!!this.config.bullet,canSleep:this.config.canSleep!==!1,emitContacts:!!this.config.emitContacts}}onStart(){this.scene?.physics2d.registerBody(this)}onDetach(){this.scene?.physics2d.unregisterBody(this),super.onDetach()}};function Cl(n,e){let t=Number(n);return Number.isFinite(t)?t:e}var Bo=class extends V{polygonCacheInput=void 0;polygonCache=[];constructor(e,t){super(e,t),this.config={shape:"rect",width:64,height:64,radius:32,offsetX:0,offsetY:0,points:[],polygonSource:"manual",friction:.4,restitution:.2,density:1,sensor:!1,group:"default"}}static getPropertySchema(){let e=(t,i,r,o,s=1)=>({name:t,type:"number",ui:{label:i,group:r,step:s,description:o},getValue:a=>a.config[t],setValue:(a,l)=>{a.config[t]=Number(l)}});return{nodeType:"Collider2D",properties:[{name:"shape",type:"select",ui:{label:"Shape",description:"All of them follow the node rotation and scale. A capsule is upright along local Y and sized by height + radius (Godot\u2019s convention). A polygon may be concave; it is split into convex parts for you.",group:"Shape",options:["rect","circle","polygon","capsule"]},getValue:t=>t.config.shape,setValue:(t,i)=>{let r=String(i);t.config.shape=["circle","polygon","capsule"].includes(r)?r:"rect"}},e("width","Width","Shape","Rect width in design pixels."),e("height","Height","Shape","Rect height, or a capsule\u2019s TOTAL height including both caps."),e("radius","Radius","Shape","Circle radius, or a capsule\u2019s cap radius (its half-width)."),e("offsetX","Offset X","Shape","Shape offset from the node origin."),e("offsetY","Offset Y","Shape","Shape offset from the node origin."),{name:"polygonSource",type:"select",ui:{label:"Polygon Source",description:"manual: the vertices below. frame: the collision polygon of the animation frame showing right now.",group:"Shape",options:["manual","frame"]},getValue:t=>t.config.polygonSource??"manual",setValue:(t,i)=>{t.config.polygonSource=i==="frame"?"frame":"manual"}},{name:"points",type:"object",ui:{label:"Polygon",description:"Vertices in node-local pixels (y up). Edit them in the viewport.",group:"Shape",editor:"collision-polygon"},getValue:t=>t.config.points??[],setValue:(t,i)=>{t.config.points=Yi(i)}},e("friction","Friction","Material","Coulomb friction. Combined between two colliders as the geometric mean.",.05),e("restitution","Restitution","Material","Bounciness, 0 to 1. Combined as the maximum of the two. Slow contacts never bounce.",.05),e("density","Density","Material","Mass per unit area, used when the body derives its own mass.",.1),{name:"sensor",type:"boolean",ui:{label:"Sensor",description:"Detect overlaps and report body-entered / body-exited without pushing anything (Godot Area2D).",group:"Filtering"},getValue:t=>t.config.sensor,setValue:(t,i)=>{t.config.sensor=!!i}},{name:"group",type:"string",ui:{label:"Group",description:"Tag used to filter physics queries (same convention as Hitbox2D).",group:"Filtering"},getValue:t=>t.config.group,setValue:(t,i)=>{t.config.group=String(i??"default")}}],groups:{Shape:{label:"Shape",expanded:!0},Material:{label:"Material",expanded:!0},Filtering:{label:"Filtering",expanded:!1}}}}getColliderShape(){let e=this.config.shape;return e==="circle"||e==="polygon"||e==="capsule"?e:"rect"}getColliderSize(){return{width:Number(this.config.width)||0,height:Number(this.config.height)||0,radius:Number(this.config.radius)||0}}getColliderOffset(){return{x:Number(this.config.offsetX)||0,y:Number(this.config.offsetY)||0}}getColliderPolygon(){if(this.config.polygonSource==="frame"){let t=this.node;return typeof t?.getFrameCollisionPolygon=="function"?t.getFrameCollisionPolygon():[]}let e=this.config.points;return e!==this.polygonCacheInput&&(this.polygonCacheInput=e,this.polygonCache=Yi(e)),this.polygonCache}getColliderMaterial(){return{friction:Math.max(0,Number(this.config.friction)||0),restitution:Math.min(1,Math.max(0,Number(this.config.restitution)||0)),density:Math.max(1e-4,Number(this.config.density)||1)}}isSensor(){return!!this.config.sensor}getColliderGroup(){return String(this.config.group??"default")}getColliderRevision(){let e=this.config;if(e.polygonSource==="frame"){let i=this.getColliderPolygon(),r=i[0];return`frame|${i.length}|${r?.x??0},${r?.y??0}|${e.friction}|${e.restitution}|${e.density}|${e.sensor}|${e.group}`}let t=this.getColliderPolygon();return[e.shape,e.width,e.height,e.radius,e.offsetX,e.offsetY,t.length,t.map(i=>`${i.x},${i.y}`).join(" "),e.friction,e.restitution,e.density,e.sensor,e.group].join("|")}onStart(){this.scene?.physics2d.registerCollider(this)}onDetach(){this.scene?.physics2d.unregisterCollider(this),super.onDetach()}};var Oo=class extends V{constructor(e,t){super(e,t),this.config={gravityX:0,gravityY:-1960}}static getPropertySchema(){let e=(t,i,r)=>({name:t,type:"number",ui:{label:i,group:"Gravity",step:10,description:r},getValue:o=>o.config[t],setValue:(o,s)=>{o.config[t]=Number(s)}});return{nodeType:"PhysicsWorld2D",properties:[e("gravityX","Gravity X","Sideways gravity in px/s^2. 0 for most games."),e("gravityY","Gravity Y","Vertical gravity in px/s^2. Y is up, so falling is NEGATIVE.")],groups:{Gravity:{label:"Gravity",expanded:!0}}}}onStart(){this.applyGravity()}onUpdate(){this.applyGravity()}applyGravity(){this.scene?.physics2d.setGravity(Number(this.config.gravityX)||0,Number(this.config.gravityY)||0)}};var Vo=class extends V{constructor(e,t){super(e,t),this.config={anchorX:0,anchorY:0,connectedNode:"",limitEnabled:!1,lowerAngle:-45,upperAngle:45,motorEnabled:!1,motorSpeed:0,maxMotorTorque:1e5,collideConnected:!1}}static getPropertySchema(){let e=(i,r,o,s)=>({name:i,type:"number",ui:{label:r,group:o,step:1,description:s},getValue:a=>a.config[i],setValue:(a,l)=>{a.config[i]=Number(l)}}),t=(i,r,o,s)=>({name:i,type:"boolean",ui:{label:r,group:o,description:s},getValue:a=>a.config[i],setValue:(a,l)=>{a.config[i]=!!l}});return{nodeType:"RevoluteJoint2D",properties:[e("anchorX","Anchor X","Hinge","Pivot point in this node\u2019s local pixels. (0, 0) hinges on the node origin."),e("anchorY","Anchor Y","Hinge","Pivot point in this node\u2019s local pixels."),{name:"connectedNode",type:"string",ui:{label:"Connected Node",description:"Name, id or path of the body to hinge to. Empty pins the hinge to the world, which is what a flipper or a swinging door wants.",group:"Hinge"},getValue:i=>i.config.connectedNode??"",setValue:(i,r)=>{i.config.connectedNode=String(r??"")}},t("limitEnabled","Limit","Limits","Restrict the swing to an angle range."),e("lowerAngle","Lower Angle","Limits","Degrees, relative to the rest pose."),e("upperAngle","Upper Angle","Limits","Degrees, relative to the rest pose."),t("motorEnabled","Motor","Motor","Drive the hinge towards a target spin."),e("motorSpeed","Motor Speed","Motor","Target spin in degrees per second. Flip its sign to swing the other way."),e("maxMotorTorque","Max Motor Torque","Motor","Torque ceiling. Too low and the motor cannot lift the arm; too high and it ignores everything it hits."),t("collideConnected","Collide Connected","Hinge","Let the two hinged bodies collide. Off by default: they overlap at the pivot, and a contact there fights the joint.")],groups:{Hinge:{label:"Hinge",expanded:!0},Limits:{label:"Limits",expanded:!0},Motor:{label:"Motor",expanded:!0}}}}getJointAnchor(){return{x:Number(this.config.anchorX)||0,y:Number(this.config.anchorY)||0}}getConnectedNode(){let e=String(this.config.connectedNode??"").trim();return e?this.findNode(e):null}getJointConfig(){let e=t=>(Number(t)||0)*Math.PI/180;return{limitEnabled:!!this.config.limitEnabled,lowerAngle:e(this.config.lowerAngle),upperAngle:e(this.config.upperAngle),motorEnabled:!!this.config.motorEnabled,motorSpeed:e(this.config.motorSpeed),maxMotorTorque:Math.max(0,Number(this.config.maxMotorTorque)||0),collideConnected:!!this.config.collideConnected}}onStart(){this.scene?.physics2d.registerJoint(this)}onDetach(){this.scene?.physics2d.unregisterJoint(this),super.onDetach()}};var aw="state-finished",Lo=class extends V{variant="";state="";separator=".";spriteNodeId="";sprite=null;warnedMissingSprite=!1;onAnimationFinished=e=>{!this.node||typeof e!="string"||e!==this.currentClipName()||this.node.emit(aw,this.state,this.variant)};static getPropertySchema(){return{nodeType:"CharacterVisual2DBehavior",properties:[x("variant","string",{ui:{label:"Variant",description:"Clip-name prefix (sword, bow). Empty when clips are named by state alone",group:"Character"},getValue:e=>e.variant,setValue:(e,t)=>{e.variant=String(t??"").trim()}}),x("state","string",{ui:{label:"State",description:"State played on start (idle)",group:"Character"},getValue:e=>e.state,setValue:(e,t)=>{e.state=String(t??"").trim()}}),x("separator","string",{ui:{label:"Separator",description:"Text between variant and state in clip names",group:"Character"},getValue:e=>e.separator,setValue:(e,t)=>{let i=String(t??"");e.separator=i.length>0?i:"."}}),x("spriteNodeId","string",{ui:{label:"Sprite Node",description:"AnimatedSprite2D to drive; empty = this node or its first sprite child",group:"Character"},getValue:e=>e.spriteNodeId,setValue:(e,t)=>{e.spriteNodeId=String(t??"").trim()}})],groups:{Character:{label:"Character",description:"variant + state \u2192 clip on the AnimatedSprite2D",expanded:!0}}}}onStart(){this.bind(),this.state&&this.playState(this.state)}onDetach(){this.unbind(),super.onDetach()}clipNameFor(e,t){return e?`${e}${this.separator}${t}`:t}currentClipName(){return this.clipNameFor(this.variant,this.state)}getSprite(){return this.sprite||(this.sprite=this.resolveSprite()),this.sprite}playState(e,t={}){let i=e.trim(),r=this.getSprite();return!i||!r||!r.play(this.clipNameFor(this.variant,i),{restart:t.restart})?!1:(this.state=i,!0)}setVariant(e){let t=e.trim(),i=this.getSprite();return!i||this.state&&!i.play(this.clipNameFor(t,this.state),{restart:!0})?!1:(this.variant=t,!0)}getVariants(){let e=new Set;for(let{variant:t}of this.parsedClips())e.add(t);return[...e]}getStates(e=this.variant){let t=new Set;for(let i of this.parsedClips())i.variant===e&&t.add(i.state);return[...t]}parsedClips(){let e=this.getSprite();return e?e.getClipNames().map(t=>{let i=t.indexOf(this.separator);return i>0?{variant:t.slice(0,i),state:t.slice(i+this.separator.length)}:{variant:"",state:t}}):[]}resolveSprite(){let e=this.node;if(!e)return null;let t=null;return this.spriteNodeId?t=this.scene?.findNodeById(this.spriteNodeId)??null:e instanceof ye?t=e:t=e.children.find(i=>i instanceof ye)??null,t instanceof ye?t:(this.warnedMissingSprite||(this.warnedMissingSprite=!0,console.warn(`[CharacterVisual2D] No AnimatedSprite2D to drive on node ${e.nodeId}`+(this.spriteNodeId?` (spriteNodeId "${this.spriteNodeId}" not found)`:""))),null)}bind(){this.getSprite()?.connect("animation-finished",this,this.onAnimationFinished)}unbind(){this.sprite?.disconnect("animation-finished",this,this.onAnimationFinished),this.sprite=null}};var lw=["owned","shared","transferable"];function Up(n){return lw.includes(n)?n:"owned"}var ci=class extends V{boundNetId=0;spawnedLocally=!1;spawnInFlight=!1;lastSpawnError=null;constructor(e,t){super(e,t),this.config={prefabPath:"",ownership:"owned",appFlags:0,spawnOnStart:!0,despawnOnDetach:!0}}static getPropertySchema(){return{nodeType:"NetworkedNode",properties:[{name:"prefabPath",type:"string",ui:{label:"Prefab",description:"This node's own prefab (res:// path). Indexes the build's netKindTable to the wire kind, and is what every other client instantiates for this entity.",group:"Identity"},getValue:e=>e.config.prefabPath,setValue:(e,t)=>{e.config.prefabPath=String(t??"")}},{name:"ownership",type:"select",ui:{label:"Ownership",description:"What happens when the owner leaves: owned = despawned, shared = reassigned to the new host, transferable = reassignable to anyone.",group:"Identity",options:[...lw]},getValue:e=>e.config.ownership,setValue:(e,t)=>{e.config.ownership=Up(t)}},{name:"spawnOnStart",type:"boolean",ui:{label:"Spawn On Start",description:"Request an entity as soon as this node starts. Turn it off for a node a script spawns explicitly, or for a prefab that only ever represents a peer.",group:"Lifecycle"},getValue:e=>e.config.spawnOnStart!==!1,setValue:(e,t)=>{e.config.spawnOnStart=!!t}},{name:"despawnOnDetach",type:"boolean",ui:{label:"Despawn On Detach",description:"Despawn the entity when this node goes away (scene change, queueFree). Off leaves a ghost in the room until its owner disconnects.",group:"Lifecycle"},getValue:e=>e.config.despawnOnDetach!==!1,setValue:(e,t)=>{e.config.despawnOnDetach=!!t}},{name:"appFlags",type:"number",ui:{label:"App Flags",description:"Game-defined flag bits 3\u20137 (0\u201331), replicated verbatim.",group:"Identity",min:0,max:31,step:1},getValue:e=>e.config.appFlags,setValue:(e,t)=>{let i=Number(t);e.config.appFlags=Number.isFinite(i)?Math.max(0,Math.min(31,Math.round(i))):0}}],groups:{Identity:{label:"Identity",expanded:!0},Lifecycle:{label:"Lifecycle",expanded:!0}}}}get netId(){return this.boundNetId}get isBound(){return this.boundNetId!==0}get isMine(){if(!this.isBound)return!1;if(this.spawnedLocally)return!0;let e=this.network,t=e?.getEntity(this.boundNetId)?.ownerId??0;return t!==0&&t===e?.clientId}get ownerId(){let e=this.network;if(!this.isBound||!e)return 0;let t=e.getEntity(this.boundNetId)?.ownerId??0;return t!==0?t:this.spawnedLocally?e.clientId:0}get ownership(){let e=this.network?.getEntity(this.boundNetId)?.flags;return e===void 0?Up(this.config.ownership):lp(e)}get spawnError(){return this.lastSpawnError}async spawn(){if(this.isBound||this.spawnInFlight)return this.boundNetId;let e=this.network,t=this.node;if(!e||!t||!e.isOnline)return 0;let i=String(this.config.prefabPath??"");this.spawnInFlight=!0;try{let r=await e.spawn(i,{position:{x:t.position.x,y:t.position.y},rotation:t.rotation.z,ownership:Up(this.config.ownership),appFlags:Number(this.config.appFlags)||0});return this.lastSpawnError=null,this.spawnedLocally=!0,this.adopt(r),r}catch(r){return this.lastSpawnError=r instanceof me?r:new me("invalid",i,String(r)),console.warn(`[core:NetworkedNode] Spawn of "${i}" failed (${this.lastSpawnError.kind}): `+this.lastSpawnError.message),0}finally{this.spawnInFlight=!1}}despawn(){let e=this.boundNetId;e!==0&&(this.spawnedLocally&&this.network?.despawn(e),this.binder?.unbind(e),this.boundNetId=0,this.spawnedLocally=!1)}onStart(){let e=this.binder,t=this.node;if(!e||!t)return;e.reconcile();let i=e.getNetId(t);if(i!==0){this.boundNetId=i,this.spawnedLocally=!1;return}this.config.spawnOnStart!==!1&&this.spawn()}onDetach(){this.boundNetId!==0&&this.config.despawnOnDetach!==!1?this.despawn():this.boundNetId!==0&&(this.binder?.unbind(this.boundNetId),this.boundNetId=0),super.onDetach()}adopt(e){let t=this.node;!t||e===0||(this.boundNetId=e,this.binder?.bind(e,t))}get network(){return this.scene?.network??null}get binder(){return this.scene?.netNodes??null}};var Ml=Math.PI*2,hN=50,dN=20,Wp=500,pN=.2,mN=1e3,cw=64;function fN(n,e,t){let i=(e-n)%Ml;return i>Math.PI?i-=Ml:i<-Math.PI&&(i+=Ml),n+i*t}var _o=class extends V{timeSource=()=>Date.now();boundNetId=0;listener=null;sendAccumulatorMs=0;buffer=[];lastArrivalMs=0;jitterMs=0;snapPending=!1;scratchSnap={x:0,y:0};constructor(e,t){super(e,t),this.config={sendRateHz:20,replicateRotation:!0,interpolationDelayMs:0,plane:"xy"}}static getPropertySchema(){return{nodeType:"ReplicatedTransform",properties:[{name:"sendRateHz",type:"number",ui:{label:"Send Rate (Hz)",description:"How often the owner publishes. The session still only sends what actually changed (dirty detection compares quantized integers), so an idle entity costs nothing.",group:"Send",min:1,max:60,step:1},getValue:e=>e.config.sendRateHz,setValue:(e,t)=>{let i=Number(t);e.config.sendRateHz=Number.isFinite(i)&&i>0?Math.min(60,i):20}},{name:"replicateRotation",type:"boolean",ui:{label:"Replicate Rotation",description:"Send rotation as well as position (256 steps per turn, 1.41\xB0).",group:"Send"},getValue:e=>e.config.replicateRotation!==!1,setValue:(e,t)=>{e.config.replicateRotation=!!t}},{name:"plane",type:"select",ui:{label:"Plane",description:"Which axes the wire's X/Y drive: xy for 2D nodes, xz for a top-down 3D game.",group:"Send",options:["xy","xz"]},getValue:e=>e.config.plane,setValue:(e,t)=>{e.config.plane=t==="xz"?"xz":"xy"}},{name:"interpolationDelayMs",type:"number",ui:{label:"Interpolation Delay (ms)",description:"0 = adaptive (two room ticks plus measured jitter). Raise it for a lossy link, lower it for a LAN \u2014 it is latency traded for smoothness.",group:"Receive",min:0,max:Wp,step:5},getValue:e=>e.config.interpolationDelayMs,setValue:(e,t)=>{let i=Number(t);e.config.interpolationDelayMs=Number.isFinite(i)&&i>0?Math.min(Wp,i):0}}],groups:{Send:{label:"Send (owner)",expanded:!0},Receive:{label:"Receive (remote)",expanded:!0}}}}get netId(){return this.boundNetId}get isOwner(){let e=this.node?.getComponent(ci);if(e)return e.isMine;let t=this.network;return t!==null&&this.boundNetId!==0&&t.ownsEntity(this.boundNetId)}get interpolationDelayMs(){let e=Number(this.config.interpolationDelayMs)||0;if(e>0)return e;let t=this.tickIntervalMs*2+this.jitterMs;return Math.min(Wp,Math.max(dN,t))}get bufferedSampleCount(){return this.buffer.length}teleportTo(e,t,i){!this.network||this.boundNetId===0||(this.writeNodeTransform(e,t,i??this.readNodeRotation()),this.publishFromNode(!0))}onStart(){let e=this.node;e instanceof C&&e.layoutEnabled&&(console.warn(`[core:ReplicatedTransform] Disabling anchored layout on "${e.nodeId}": a replicated transform and the per-frame anchor reflow cannot both own the position.`),e.layoutEnabled=!1),this.rebind()}onUpdate(e){this.boundNetId===0&&(this.rebind(),this.boundNetId===0)||(this.isOwner?this.tickOwner(e):this.tickRemote())}onDetach(){this.boundNetId!==0&&this.binder?.setListener(this.boundNetId,null),this.boundNetId=0,this.listener=null,this.buffer.length=0,super.onDetach()}tickOwner(e){let t=1e3/(Number(this.config.sendRateHz)||20);this.sendAccumulatorMs+=Math.max(0,e)*1e3,!(this.sendAccumulatorMs<t)&&(this.sendAccumulatorMs%=t,this.publishFromNode(!1))}publishFromNode(e){let t=this.network,i=this.node;if(!t||!i)return;let{x:r,y:o}=this.readNodePosition();if(!t.snapPosition(r,o,this.scratchSnap))return;let a=this.config.replicateRotation!==!1?t.snapRotation(this.readNodeRotation()):null;t.publish(this.boundNetId,{x:this.scratchSnap.x,y:this.scratchSnap.y,rotation:a??void 0,teleport:e}),this.writeNodeTransform(this.scratchSnap.x,this.scratchSnap.y,a??void 0)}tickRemote(){if(this.buffer.length===0)return;if(this.snapPending){this.snapPending=!1;let r=this.buffer[this.buffer.length-1];this.buffer.length=0,this.buffer.push(r),this.writeNodeTransform(r.x,r.y,r.rotation);return}let e=this.timeSource()-this.interpolationDelayMs;this.trimBuffer(e);let t=this.buffer[0];if(e<=t.t||this.buffer.length===1){this.writeNodeTransform(t.x,t.y,t.rotation);return}let i=this.buffer[this.buffer.length-1];if(e>=i.t){this.writeNodeTransform(i.x,i.y,i.rotation);return}for(let r=this.buffer.length-1;r>0;r-=1){let o=this.buffer[r],s=this.buffer[r-1];if(e<s.t)continue;let a=o.t-s.t,l=a>0?(e-s.t)/a:1;this.writeNodeTransform(s.x+(o.x-s.x)*l,s.y+(o.y-s.y)*l,fN(s.rotation,o.rotation,l));return}}trimBuffer(e){for(;this.buffer.length>2&&this.buffer[1].t<=e;)this.buffer.shift();for(;this.buffer.length>1&&e-this.buffer[0].t>mN;)this.buffer.shift();for(;this.buffer.length>cw;)this.buffer.shift()}handleChange(e){if(e.kind==="leave"){this.buffer.length=0;return}let i=this.network?.quantizer;if(!i)return;let r=this.timeSource();if(this.lastArrivalMs!==0){let s=Math.abs(r-this.lastArrivalMs-this.tickIntervalMs);this.jitterMs+=(s-this.jitterMs)*pN}this.lastArrivalMs=r;let o={t:r,x:i.dequantizeX(e.entity.qx),y:i.dequantizeY(e.entity.qy),rotation:e.entity.qrot*Ml/256};(e.kind==="enter"||cp(e.mask))&&(this.snapPending=!0,this.buffer.length=0),this.buffer.push(o),this.buffer.length>cw&&this.buffer.shift()}rebind(){let e=this.node,t=this.binder;if(!e||!t)return;let i=e.getComponent(ci)?.netId||t.getNetId(e);if(i===this.boundNetId||(this.boundNetId!==0&&t.setListener(this.boundNetId,null),this.boundNetId=i,this.buffer.length=0,this.lastArrivalMs=0,this.snapPending=!1,i===0))return;this.listener??=o=>this.handleChange(o),t.setListener(i,this.listener);let r=this.network?.getEntity(i);r&&this.handleChange({kind:"enter",netId:i,entity:r,mask:0})}get plane(){return this.config.plane==="xz"?"xz":"xy"}readNodePosition(){let e=this.node?.position;return e?this.plane==="xz"?{x:e.x,y:e.z}:{x:e.x,y:e.y}:{x:0,y:0}}readNodeRotation(){let e=this.node?.rotation;return e?this.plane==="xz"?e.y:e.z:0}writeNodeTransform(e,t,i){let r=this.node;r&&(this.plane==="xz"?(r.position.x=e,r.position.z=t):(r.position.x=e,r.position.y=t),i!==void 0&&this.config.replicateRotation!==!1&&(this.plane==="xz"?r.rotation.y=i:r.rotation.z=i))}get tickIntervalMs(){let e=this.network?.tickHz??0;return e>0?1e3/e:hN}get network(){return this.scene?.network??null}get binder(){return this.scene?.netNodes??null}};var Dl=class extends V{targetNode=null;targetWorldPosition=new S;targetLocalPosition=new S;targetWorldQuaternion=new F;targetLocalQuaternion=new F;parentWorldQuaternion=new F;parentWorldQuaternionInverse=new F;targetEuler=new Ji;constructor(e,t){super(e,t),this.config={targetNodeId:"",positionSmoothing:8,rotationSmoothing:8,followPositionX:!0,followPositionY:!0,followPositionZ:!0,followRotationX:!1,followRotationY:!0,followRotationZ:!1}}static getPropertySchema(){return{nodeType:"FollowBehavior",properties:[{name:"targetNodeId",type:"node",ui:{label:"Target Node",description:"Node to follow",group:"Target"},getValue:e=>e.getTargetNodeId(),setValue:(e,t)=>{e.setTargetNodeId(typeof t=="string"?t:"")}},{name:"positionSmoothing",type:"number",ui:{label:"Position Smoothing",description:"Higher values follow position faster",group:"Position",min:0,step:.1},getValue:e=>e.getPositionSmoothing(),setValue:(e,t)=>{let i=e,r=Number(t);!Number.isFinite(r)||r<0||(i.config.positionSmoothing=r)}},{name:"followPositionX",type:"boolean",ui:{label:"Follow Position X",group:"Position"},getValue:e=>e.isPositionAxisEnabled("x"),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.followPositionX=t)}},{name:"followPositionY",type:"boolean",ui:{label:"Follow Position Y",group:"Position"},getValue:e=>e.isPositionAxisEnabled("y"),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.followPositionY=t)}},{name:"followPositionZ",type:"boolean",ui:{label:"Follow Position Z",group:"Position"},getValue:e=>e.isPositionAxisEnabled("z"),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.followPositionZ=t)}},{name:"rotationSmoothing",type:"number",ui:{label:"Rotation Smoothing",description:"Higher values follow rotation faster",group:"Rotation",min:0,step:.1},getValue:e=>e.getRotationSmoothing(),setValue:(e,t)=>{let i=e,r=Number(t);!Number.isFinite(r)||r<0||(i.config.rotationSmoothing=r)}},{name:"followRotationX",type:"boolean",ui:{label:"Follow Rotation X",group:"Rotation"},getValue:e=>e.isRotationAxisEnabled("x"),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.followRotationX=t)}},{name:"followRotationY",type:"boolean",ui:{label:"Follow Rotation Y",group:"Rotation"},getValue:e=>e.isRotationAxisEnabled("y"),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.followRotationY=t)}},{name:"followRotationZ",type:"boolean",ui:{label:"Follow Rotation Z",group:"Rotation"},getValue:e=>e.isRotationAxisEnabled("z"),setValue:(e,t)=>{typeof t=="boolean"&&(e.config.followRotationZ=t)}}],groups:{Target:{label:"Target",expanded:!0},Position:{label:"Position",expanded:!0},Rotation:{label:"Rotation",expanded:!0}}}}onStart(){this.targetNode=null,this.resolveTargetNode()}onUpdate(e){!this.node||e<=0||((!this.targetNode||!this.targetNode.parent)&&this.resolveTargetNode(),!(!this.targetNode||this.targetNode===this.node)&&(this.updatePosition(e),this.updateRotation(e)))}updatePosition(e){if(!this.node||!this.targetNode)return;let t=this.isPositionAxisEnabled("x"),i=this.isPositionAxisEnabled("y"),r=this.isPositionAxisEnabled("z");if(!t&&!i&&!r)return;this.targetNode.getWorldPosition(this.targetWorldPosition),this.node.parent?(this.targetLocalPosition.copy(this.targetWorldPosition),this.node.parent.worldToLocal(this.targetLocalPosition)):this.targetLocalPosition.copy(this.targetWorldPosition);let o=this.getDampingAlpha(this.getPositionSmoothing(),e),s=t?R.lerp(this.node.position.x,this.targetLocalPosition.x,o):this.node.position.x,a=i?R.lerp(this.node.position.y,this.targetLocalPosition.y,o):this.node.position.y,l=r?R.lerp(this.node.position.z,this.targetLocalPosition.z,o):this.node.position.z;this.node.position.set(s,a,l)}updateRotation(e){if(!this.node||!this.targetNode)return;let t=this.isRotationAxisEnabled("x"),i=this.isRotationAxisEnabled("y"),r=this.isRotationAxisEnabled("z");if(!t&&!i&&!r)return;this.targetNode.getWorldQuaternion(this.targetWorldQuaternion),this.node.parent?(this.node.parent.getWorldQuaternion(this.parentWorldQuaternion),this.parentWorldQuaternionInverse.copy(this.parentWorldQuaternion).invert(),this.targetLocalQuaternion.copy(this.parentWorldQuaternionInverse).multiply(this.targetWorldQuaternion)):this.targetLocalQuaternion.copy(this.targetWorldQuaternion),this.targetEuler.setFromQuaternion(this.targetLocalQuaternion,this.node.rotation.order);let o=this.getDampingAlpha(this.getRotationSmoothing(),e),s=t?this.dampAngle(this.node.rotation.x,this.targetEuler.x,o):this.node.rotation.x,a=i?this.dampAngle(this.node.rotation.y,this.targetEuler.y,o):this.node.rotation.y,l=r?this.dampAngle(this.node.rotation.z,this.targetEuler.z,o):this.node.rotation.z;this.node.rotation.set(s,a,l,this.node.rotation.order)}resolveTargetNode(){if(!this.node)return;let e=this.getTargetNodeId();if(!e){this.targetNode=null;return}this.targetNode=this.findNode(e)}getTargetNodeId(){let e=this.config.targetNodeId;return typeof e=="string"?e:""}setTargetNodeId(e){this.config.targetNodeId=e,this.targetNode=null}getPositionSmoothing(){let e=this.config.positionSmoothing,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:8}getRotationSmoothing(){let e=this.config.rotationSmoothing,t=typeof e=="number"?e:Number(e);return Number.isFinite(t)&&t>=0?t:8}isPositionAxisEnabled(e){let t=e==="x"?"followPositionX":e==="y"?"followPositionY":"followPositionZ",i=this.config[t];return typeof i=="boolean"?i:!0}isRotationAxisEnabled(e){let t=e==="x"?"followRotationX":e==="y"?"followRotationY":"followRotationZ",i=this.config[t];return typeof i=="boolean"?i:!1}getDampingAlpha(e,t){return e<=0?1:1-Math.exp(-e*t)}dampAngle(e,t,i){let r=Math.atan2(Math.sin(t-e),Math.cos(t-e));return e+r*i}};var El=class extends V{armed=!1;remaining=0;boundSignal=null;onSignal=()=>{this.armed||(this.armed=!0,this.remaining=this.getDelay())};constructor(e,t){super(e,t),this.config={signal:"animation-finished",delay:0}}static getPropertySchema(){return{nodeType:"FreeOnSignalBehavior",properties:[{name:"signal",type:"string",ui:{label:"Signal",description:"Node signal that triggers the free (e.g. animation-finished)",group:"Lifecycle"},getValue:e=>e.getSignal(),setValue:(e,t)=>{e.setSignal(t)}},{name:"delay",type:"number",ui:{label:"Delay",description:"Seconds to wait after the signal before freeing",group:"Lifecycle",min:0,step:.01,precision:2,unit:"s"},getValue:e=>e.getDelay(),setValue:(e,t)=>{e.setDelay(t)}}],groups:{Lifecycle:{label:"Lifecycle",description:"Free this node when a signal fires",expanded:!0}}}}onStart(){this.bind()}onUpdate(e){!this.armed||!this.node||(this.remaining-=e,this.remaining<=0&&(this.armed=!1,this.node.queueFree()))}onDetach(){this.unbind(),this.armed=!1,super.onDetach()}bind(){this.node&&(this.boundSignal=this.getSignal(),this.node.connect(this.boundSignal,this,this.onSignal))}unbind(){!this.node||!this.boundSignal||(this.node.disconnect(this.boundSignal,this,this.onSignal),this.boundSignal=null)}getSignal(){let e=this.config.signal;if(typeof e!="string")return"animation-finished";let t=e.trim();return t.length>0?t:"animation-finished"}setSignal(e){let t=!!this.node;t&&this.unbind(),this.config.signal=typeof e=="string"&&e.trim().length>0?e.trim():"animation-finished",t&&this.bind()}getDelay(){let e=typeof this.config.delay=="number"?this.config.delay:Number(this.config.delay);return Number.isFinite(e)?Math.max(0,e):0}setDelay(e){let t=typeof e=="number"?e:Number(e);this.config.delay=Number.isFinite(t)?Math.max(0,t):0}};var Nl=class extends V{point="";applyRotation=!0;offsetX=0;offsetY=0;spriteNodeId="";sprite=null;static getPropertySchema(){return{nodeType:"PointAttachmentBehavior",properties:[x("point","string",{ui:{label:"Point",description:"Named frame point to follow"},getValue:e=>e.point,setValue:(e,t)=>{e.point=String(t??"").trim()}}),x("applyRotation","boolean",{ui:{label:"Apply Rotation",description:"Copy the point's angle into this node"},getValue:e=>e.applyRotation,setValue:(e,t)=>{e.applyRotation=!!t}}),x("offsetX","number",{ui:{label:"Offset X",step:1},getValue:e=>e.offsetX,setValue:(e,t)=>{e.offsetX=Number(t)||0}}),x("offsetY","number",{ui:{label:"Offset Y",step:1},getValue:e=>e.offsetY,setValue:(e,t)=>{e.offsetY=Number(t)||0}}),x("spriteNodeId","node",{ui:{label:"Sprite",description:"AnimatedSprite2D to read points from (empty = nearest ancestor)",nodeTypes:["AnimatedSprite2D"]},getValue:e=>e.spriteNodeId,setValue:(e,t)=>{let i=e;i.spriteNodeId=String(t??"").trim(),i.sprite=null}})],groups:{}}}onStart(){this.sprite=null}onUpdate(e){let t=this.node;if(!t||!(t instanceof C)||this.point.length===0)return;let i=this.resolveSprite();if(!i)return;let r=i.getFramePoint(this.point);if(!r)return;let o=t.parent;if(o){if(o===i)t.position.set(r.x+this.offsetX,r.y+this.offsetY,t.position.z);else{let s=i.getFramePointWorld(this.point);if(!s)return;o.updateMatrixWorld(!0),t.position.set(s.x,s.y,s.z),o.worldToLocal(t.position),t.position.x+=this.offsetX,t.position.y+=this.offsetY}this.applyRotation&&(t.rotation.z=R.degToRad(r.angle))}}resolveSprite(){if(this.sprite)return this.sprite;if(this.spriteNodeId){let t=this.findNode(this.spriteNodeId);return this.sprite=t instanceof ye?t:null,this.sprite}let e=this.node?.parent??null;for(;e;){if(e instanceof ye)return this.sprite=e,e;e=e.parent}return null}};function gN(n){n.registerComponent({id:"core:Rotate",displayName:"Rotate",description:"Rotates a 3D node continuously",category:"Transform",componentClass:Po,keywords:["rotate","animation"]}),n.registerComponent({id:"core:SimpleMove",displayName:"Simple Move",description:"Moves a 3D node in a simple pattern (for testing)",category:"Test",componentClass:ko,keywords:["move","test","animation"]}),n.registerComponent({id:"core:Sine",displayName:"Sine Oscillator",description:"Oscillates a node along a selected axis",category:"Animation",componentClass:Ao,keywords:["sine","oscillation","animation"]}),n.registerComponent({id:"core:PinToNode",displayName:"Pin to Node",description:"Pins a 2D UI node to a 3D target node",category:"UI",componentClass:To,keywords:["ui","tracking","pin"]}),n.registerComponent({id:"core:Follow",displayName:"Follow",description:"Smoothly follows a target node position and/or rotation",category:"Transform",componentClass:Dl,keywords:["follow","camera","tracking","smooth"]}),n.registerComponent({id:"core:Fade",displayName:"Fade",description:"Fades 2D node opacity in and out with optional auto-destroy",category:"Animation",componentClass:Co,keywords:["fade","opacity","animation"]}),n.registerComponent({id:"core:RadialProgress",displayName:"Radial Progress",description:"Masks a Sprite2D texture as a circular progress bar",category:"UI",componentClass:Mo,keywords:["radial","progress","bar","circle","mask","ui"]}),n.registerComponent({id:"core:AnimationPlayer",displayName:"Animation Player",description:"Plays keyframe animation clips on this node and its descendants",category:"Animation",componentClass:li,keywords:["animation","keyframe","tween","timeline","player","clip"]}),n.registerComponent({id:"core:PlaySound",displayName:"Play Sound",description:"Plays an audio track when a node signal is emitted",category:"Audio",componentClass:Do,keywords:["audio","sound","sfx","trigger","event"]}),n.registerComponent({id:"core:SfxOnSignal",displayName:"SFX on Signal",description:"Play a procedural (asset-free) sound preset when a node signal fires",category:"Audio",componentClass:Eo,keywords:["audio","sfx","sound","procedural","synth","preset","signal","juice"]}),n.registerComponent({id:"core:BurstOnSignal",displayName:"Burst on Signal",description:"Spawn a one-shot 2D particle burst at this node when a signal fires (juice)",category:"Juice",componentClass:No,keywords:["particles","burst","juice","vfx","sparks","confetti","signal","impact"]}),n.registerComponent({id:"core:FreeOnSignal",displayName:"Free on Signal",description:"Frees this node when a signal fires on it (e.g. animation-finished) \u2014 one-shot VFX lifecycle",category:"Lifecycle",componentClass:El,keywords:["free","destroy","despawn","queuefree","one-shot","lifecycle","signal","vfx","finished"]}),n.registerComponent({id:"core:Shake",displayName:"Shake",description:"Smooth positional shake, additive over other motion (juice)",category:"Juice",componentClass:_t,keywords:["shake","juice","camera","impact","screenshake"]}),n.registerComponent({id:"core:PunchScale",displayName:"Punch Scale",description:"Squash-and-stretch scale punch on a signal or on start (juice)",category:"Juice",componentClass:ni,keywords:["punch","scale","squash","stretch","juice","pop"]}),n.registerComponent({id:"core:PopIn",displayName:"Pop In",description:"Scales a node up from zero with an overshoot on spawn (juice)",category:"Juice",componentClass:oi,keywords:["pop","spawn","scale","juice","appear","intro"]}),n.registerComponent({id:"core:CameraBrain",displayName:"Camera Brain",description:"Blends the render camera between virtual cameras by priority (Cinemachine-lite)",category:"Camera",componentClass:ji,keywords:["camera","brain","cinemachine","virtual","blend","priority","follow"]}),n.registerComponent({id:"core:Hitbox2D",displayName:"Hitbox 2D",description:"Queryable 2D collision shape (rect/circle) with group filtering \u2014 hit-test via scene.collision2d",category:"Physics",componentClass:Io,keywords:["hitbox","collision","collider","area","2d","overlap","raycast","hit"]}),n.registerComponent({id:"core:PhysicsBody2D",displayName:"Physics Body 2D",description:"Rigid body simulated by scene.physics2d \u2014 static, kinematic or dynamic. Shape comes from sibling or descendant Collider 2D components.",category:"Physics",componentClass:Ro,keywords:["physics","rigidbody","body","dynamic","gravity","mass","2d","simulate"]}),n.registerComponent({id:"core:Collider2D",displayName:"Collider 2D",description:"Physics shape (rect/circle/polygon, rotation-aware, may be concave). With no Physics Body above it this is static world geometry; as a sensor it reports body-entered / body-exited.",category:"Physics",componentClass:Bo,keywords:["collider","physics","shape","polygon","sensor","area","2d","collision"]}),n.registerComponent({id:"core:RevoluteJoint2D",displayName:"Revolute Joint 2D",description:"Hinge: pins this body to a pivot so it can only rotate about it. With no connected node the hinge is fixed to the world \u2014 the pinball flipper / swinging door case. Optional angle limits and a motor.",category:"Physics",componentClass:Vo,keywords:["joint","hinge","revolute","pivot","flipper","door","motor","physics","2d"]}),n.registerComponent({id:"core:PhysicsWorld2D",displayName:"Physics World 2D",description:"Sets the 2D world gravity. Attach to the scene root.",category:"Physics",componentClass:Oo,keywords:["physics","gravity","world","2d"]}),n.registerComponent({id:"core:PointAttachment",displayName:"Point Attachment",description:"Keeps this node on a named frame point of a parent AnimatedSprite2D (hand socket, muzzle) every tick",category:"Animation",componentClass:Nl,keywords:["point","socket","attach","muzzle","hand","bone","sprite","animation"]}),n.registerComponent({id:"core:CharacterVisual2D",displayName:"Character Visual 2D",description:"Plays variant + state as a clip of an AnimatedSprite2D whose clips are named <variant>.<state> (sword.idle); swap the variant, keep the state vocabulary",category:"Animation",componentClass:Lo,keywords:["character","variant","state","skin","weapon","clip","sprite","animation"]}),n.registerComponent({id:"core:NetworkedNode",displayName:"Networked Node",description:"Binds this node to a replicated entity \u2014 spawns one for the local player, or adopts the entity a peer spawned",category:"Network",componentClass:ci,keywords:["network","multiplayer","net","entity","spawn","despawn","owner","authority","online"]}),n.registerComponent({id:"core:ReplicatedTransform",displayName:"Replicated Transform",description:"Replicates this node's position and rotation: the owner publishes quantized values, peers render them on a timed interpolation buffer",category:"Network",componentClass:_o,keywords:["network","multiplayer","replicate","transform","position","sync","interpolation","lerp","online"]}),console.log("[ScriptRegistry] Registered built-in script components")}var uw=class{get shadowRoot(){return this.__host.__shadowRoot}constructor(e){this.ariaActiveDescendantElement=null,this.ariaAtomic="",this.ariaAutoComplete="",this.ariaBrailleLabel="",this.ariaBrailleRoleDescription="",this.ariaBusy="",this.ariaChecked="",this.ariaColCount="",this.ariaColIndex="",this.ariaColIndexText="",this.ariaColSpan="",this.ariaControlsElements=null,this.ariaCurrent="",this.ariaDescribedByElements=null,this.ariaDescription="",this.ariaDetailsElements=null,this.ariaDisabled="",this.ariaErrorMessageElements=null,this.ariaExpanded="",this.ariaFlowToElements=null,this.ariaHasPopup="",this.ariaHidden="",this.ariaInvalid="",this.ariaKeyShortcuts="",this.ariaLabel="",this.ariaLabelledByElements=null,this.ariaLevel="",this.ariaLive="",this.ariaModal="",this.ariaMultiLine="",this.ariaMultiSelectable="",this.ariaOrientation="",this.ariaOwnsElements=null,this.ariaPlaceholder="",this.ariaPosInSet="",this.ariaPressed="",this.ariaReadOnly="",this.ariaRelevant="",this.ariaRequired="",this.ariaRoleDescription="",this.ariaRowCount="",this.ariaRowIndex="",this.ariaRowIndexText="",this.ariaRowSpan="",this.ariaSelected="",this.ariaSetSize="",this.ariaSort="",this.ariaValueMax="",this.ariaValueMin="",this.ariaValueNow="",this.ariaValueText="",this.role="",this.form=null,this.labels=[],this.states=new Set,this.validationMessage="",this.validity={},this.willValidate=!0,this.__host=e}checkValidity(){return console.warn("`ElementInternals.checkValidity()` was called on the server.This method always returns true."),!0}reportValidity(){return!0}setFormValue(){}setValidity(){}};var at=function(n,e,t,i,r){if(i==="m")throw new TypeError("Private method is not writable");if(i==="a"&&!r)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?n!==e||!r:!e.has(n))throw new TypeError("Cannot write private member to an object whose class did not declare it");return i==="a"?r.call(n,t):r?r.value=t:e.set(n,t),t},he=function(n,e,t,i){if(t==="a"&&!i)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?n!==e||!i:!e.has(n))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?i:t==="a"?i.call(n):i?i.value:e.get(n)},Vr,Il,Rl,Fo,Hp,zo,Bl,Ki,Uo,ui,Ol,hw;var ie={__proto__:null};ie.enumerable=!0;Object.freeze(ie);var qp=(ui=class{constructor(e,t={}){if(Vr.set(this,!1),Il.set(this,!1),Rl.set(this,!1),Fo.set(this,!1),Hp.set(this,Date.now()),zo.set(this,!1),Bl.set(this,void 0),Ki.set(this,void 0),Uo.set(this,void 0),this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,arguments.length===0)throw new Error("The type argument must be specified");if(typeof t!="object"||!t)throw new Error('The "options" argument must be an object');let{bubbles:i,cancelable:r,composed:o}=t;at(this,Vr,!!r,"f"),at(this,Il,!!i,"f"),at(this,Rl,!!o,"f"),at(this,Bl,`${e}`,"f"),at(this,Ki,null,"f"),at(this,Uo,!1,"f")}initEvent(e,t,i){throw new Error("Method not implemented.")}stopImmediatePropagation(){this.stopPropagation()}preventDefault(){at(this,Fo,!0,"f")}get target(){return he(this,Ki,"f")}get currentTarget(){return he(this,Ki,"f")}get srcElement(){return he(this,Ki,"f")}get type(){return he(this,Bl,"f")}get cancelable(){return he(this,Vr,"f")}get defaultPrevented(){return he(this,Vr,"f")&&he(this,Fo,"f")}get timeStamp(){return he(this,Hp,"f")}composedPath(){return he(this,Uo,"f")?[he(this,Ki,"f")]:[]}get returnValue(){return!he(this,Vr,"f")||!he(this,Fo,"f")}get bubbles(){return he(this,Il,"f")}get composed(){return he(this,Rl,"f")}get eventPhase(){return he(this,Uo,"f")?ui.AT_TARGET:ui.NONE}get cancelBubble(){return he(this,zo,"f")}set cancelBubble(e){e&&at(this,zo,!0,"f")}stopPropagation(){at(this,zo,!0,"f")}get isTrusted(){return!1}},Vr=new WeakMap,Il=new WeakMap,Rl=new WeakMap,Fo=new WeakMap,Hp=new WeakMap,zo=new WeakMap,Bl=new WeakMap,Ki=new WeakMap,Uo=new WeakMap,ui.NONE=0,ui.CAPTURING_PHASE=1,ui.AT_TARGET=2,ui.BUBBLING_PHASE=3,ui);Object.defineProperties(qp.prototype,{initEvent:ie,stopImmediatePropagation:ie,preventDefault:ie,target:ie,currentTarget:ie,srcElement:ie,type:ie,cancelable:ie,defaultPrevented:ie,timeStamp:ie,composedPath:ie,returnValue:ie,bubbles:ie,composed:ie,eventPhase:ie,cancelBubble:ie,stopPropagation:ie,isTrusted:ie});var dw=(hw=class extends qp{constructor(e,t={}){super(e,t),Ol.set(this,void 0),at(this,Ol,t?.detail??null,"f")}initCustomEvent(e,t,i,r){throw new Error("Method not implemented.")}get detail(){return he(this,Ol,"f")}},Ol=new WeakMap,hw);Object.defineProperties(dw.prototype,{detail:ie});var Mt=qp,Gp=dw;var fe;var yH=(fe=class{constructor(){this.STYLE_RULE=1,this.CHARSET_RULE=2,this.IMPORT_RULE=3,this.MEDIA_RULE=4,this.FONT_FACE_RULE=5,this.PAGE_RULE=6,this.NAMESPACE_RULE=10,this.KEYFRAMES_RULE=7,this.KEYFRAME_RULE=8,this.SUPPORTS_RULE=12,this.COUNTER_STYLE_RULE=11,this.FONT_FEATURE_VALUES_RULE=14,this.MARGIN_RULE=9,this.__parentStyleSheet=null,this.cssText=""}get parentRule(){return null}get parentStyleSheet(){return this.__parentStyleSheet}get type(){return 0}},fe.STYLE_RULE=1,fe.CHARSET_RULE=2,fe.IMPORT_RULE=3,fe.MEDIA_RULE=4,fe.FONT_FACE_RULE=5,fe.PAGE_RULE=6,fe.NAMESPACE_RULE=10,fe.KEYFRAMES_RULE=7,fe.KEYFRAME_RULE=8,fe.SUPPORTS_RULE=12,fe.COUNTER_STYLE_RULE=11,fe.FONT_FEATURE_VALUES_RULE=14,fe.MARGIN_RULE=9,fe);globalThis.Event??=Mt;globalThis.CustomEvent??=Gp;var $p=Symbol(),pw=n=>typeof n=="boolean"?n:n?.capture??!1,Dt={__proto__:null};Dt.enumerable=!0;Object.freeze(Dt);var Vl=class{constructor(){this.__eventListeners=new Map,this.__captureEventListeners=new Map}addEventListener(e,t,i){if(t==null)return;let r=pw(i)?this.__captureEventListeners:this.__eventListeners,o=r.get(e);if(o===void 0)o=new Map,r.set(e,o);else if(o.has(t))return;let s=typeof i=="object"&&i?i:{};s.signal?.addEventListener("abort",()=>this.removeEventListener(e,t,i)),o.set(t,s??{})}removeEventListener(e,t,i){if(t==null)return;let r=pw(i)?this.__captureEventListeners:this.__eventListeners,o=r.get(e);o!==void 0&&(o.delete(t),o.size||r.delete(e))}dispatchEvent(e){let t=this.__resolveFullEventPath();!e.composed&&this.__host&&(t=t.slice(0,t.indexOf(this.__host)));let i=!1,r=!1,o=Mt.NONE,s=null,a=null,l=null,c=e.stopPropagation,u=e.stopImmediatePropagation;Object.defineProperties(e,{target:{get(){return s??a},...Dt},srcElement:{get(){return e.target},...Dt},currentTarget:{get(){return l},...Dt},eventPhase:{get(){return o},...Dt},composedPath:{value:()=>t,...Dt},stopPropagation:{value:()=>{i=!0,c.call(e)},...Dt},stopImmediatePropagation:{value:()=>{r=!0,u.call(e)},...Dt}});let h=(g,y,b)=>{typeof g=="function"?g(e):typeof g?.handleEvent=="function"&&g.handleEvent(e),y.once&&b.delete(g)},d=()=>(l=null,o=Mt.NONE,!e.defaultPrevented),p=t.slice().reverse();s=!this.__host||!e.composed?this:null;let f=g=>{for(a=this;a.__host&&g.includes(a.__host);)a=a.__host};for(let g of p){!s&&(!a||a===g.__host)&&f(p.slice(p.indexOf(g))),l=g,o=g===e.target?Mt.AT_TARGET:Mt.CAPTURING_PHASE;let y=g.__captureEventListeners.get(e.type);if(y){for(let[b,v]of y)if(h(b,v,y),r)return d()}if(i)return d()}let m=e.bubbles?t:[this];a=null;for(let g of m){!s&&(!a||g===a.__host)&&f(m.slice(0,m.indexOf(g)+1)),l=g,o=g===e.target?Mt.AT_TARGET:Mt.BUBBLING_PHASE;let y=g.__eventListeners.get(e.type);if(y){for(let[b,v]of y)if(h(b,v,y),r)return d()}if(i)return d()}return d()}__resolveFullEventPath(){return this.__eventPathCache?this.__eventPathCache:this.__eventTargetParent?this.__eventPathCache=[this,...this.__eventTargetParent.__resolveFullEventPath()]:this.__eventPathCache=[this,gw,SN]}};var mw=new WeakMap,Wo=n=>{let e=mw.get(n);return e===void 0&&mw.set(n,e=new Map),e},Ho=class extends Vl{getRootNode(e){return e?.composed?jp:this.__host?.__shadowRoot??jp}};var fw=class extends Ho{get adoptedStyleSheets(){return[]}createTreeWalker(){return{}}createTextNode(){return{}}createElement(){return{}}};var gw=new fw,jp=gw;var yw=class extends Ho{constructor(e){if(super(),e!==$p)throw new TypeError("Illegal constructor");Object.assign(this,globalThis,{CustomElementRegistry:Ll,customElements:Kp,document:jp,Document:fw,Element:bw,EventTarget:Vl,HTMLElement:Sw,Node:Ho,ShadowRoot:vw,window:this,Window:yw})}};var bw=class extends Ho{constructor(){super(...arguments),this.__shadowRootMode=null,this.__shadowRoot=null,this.__internals=null}get attributes(){return Array.from(Wo(this)).map(([e,t])=>({name:e,value:t}))}get shadowRoot(){return this.__shadowRootMode==="closed"?null:this.__shadowRoot}get localName(){return this.constructor.__localName}get tagName(){return this.localName?.toUpperCase()}setAttribute(e,t){Wo(this).set(e,String(t))}removeAttribute(e){Wo(this).delete(e)}toggleAttribute(e,t){if(this.hasAttribute(e)){if(t===void 0||!t)return this.removeAttribute(e),!1}else return t===void 0||t?(this.setAttribute(e,""),!0):!1;return!0}hasAttribute(e){return Wo(this).has(e)}attachShadow(e){this.__shadowRootMode=e.mode;let t=new vw($p,e);return t.__eventTargetParent=this,t.__host=this,this.__shadowRoot=t}attachInternals(){if(this.__internals!==null)throw new Error("Failed to execute 'attachInternals' on 'HTMLElement': ElementInternals for the specified element was already attached.");let e=new uw(this);return this.__internals=e,e}getAttribute(e){return Wo(this).get(e)??null}};var Sw=class extends bw{},Yp=Sw;var vw=class extends Ho{get host(){return this.__host}constructor(e,t){if(super(),e!==e)throw new TypeError("Illegal constructor");this.mode=t.mode}};globalThis.litServerRoot??=Object.defineProperty(new Yp,"localName",{get(){return"lit-server-root"}});function yN(){let n,e;return{promise:new Promise((i,r)=>{n=i,e=r}),resolve:n,reject:e}}var Ll=class{constructor(){this.__definitions=new Map,this.__reverseDefinitions=new Map,this.__pendingWhenDefineds=new Map}define(e,t){if(this.__definitions.has(e))if(process.env.NODE_ENV==="development")console.warn(`'CustomElementRegistry' already has "${e}" defined. This may have been caused by live reload or hot module replacement in which case it can be safely ignored.
238
+ Make sure to test your application with a production build as repeat registrations will throw in production.`);else throw new Error(`Failed to execute 'define' on 'CustomElementRegistry': the name "${e}" has already been used with this registry`);if(this.__reverseDefinitions.has(t))throw new Error(`Failed to execute 'define' on 'CustomElementRegistry': the constructor has already been used with this registry for the tag name ${this.__reverseDefinitions.get(t)}`);t.__localName=e,this.__definitions.set(e,{ctor:t,observedAttributes:t.observedAttributes??[]}),this.__reverseDefinitions.set(t,e),this.__pendingWhenDefineds.get(e)?.resolve(t),this.__pendingWhenDefineds.delete(e)}get(e){return this.__definitions.get(e)?.ctor}getName(e){return this.__reverseDefinitions.get(e)??null}initialize(e){throw new Error("customElements.initialize is not currently supported in SSR. Please file a bug if you need it.")}upgrade(e){throw new Error("customElements.upgrade is not currently supported in SSR. Please file a bug if you need it.")}async whenDefined(e){let t=this.__definitions.get(e);if(t)return t.ctor;let i=this.__pendingWhenDefineds.get(e);return i||(i=yN(),this.__pendingWhenDefineds.set(e,i)),i.promise}},bN=Ll;var Kp=new bN,SN=new yw($p);var qo=globalThis,Fl=qo.ShadowRoot&&(qo.ShadyCSS===void 0||qo.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,xw=Symbol(),ww=new WeakMap,_l=class{constructor(e,t,i){if(this._$cssResult$=!0,i!==xw)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(Fl&&e===void 0){let i=t!==void 0&&t.length===1;i&&(e=ww.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),i&&ww.set(t,e))}return e}toString(){return this.cssText}},Pw=n=>new _l(typeof n=="string"?n:n+"",void 0,xw);var kw=(n,e)=>{if(Fl)n.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let i=document.createElement("style"),r=qo.litNonce;r!==void 0&&i.setAttribute("nonce",r),i.textContent=t.cssText,n.appendChild(i)}},Xp=Fl||qo.CSSStyleSheet===void 0?n=>n:n=>n instanceof CSSStyleSheet?(e=>{let t="";for(let i of e.cssRules)t+=i.cssText;return Pw(t)})(n):n;var{is:vN,defineProperty:wN,getOwnPropertyDescriptor:xN,getOwnPropertyNames:PN,getOwnPropertySymbols:kN,getPrototypeOf:AN}=Object,$o=globalThis;$o.customElements??=Kp;var Aw=$o.trustedTypes,TN=Aw?Aw.emptyScript:"",CN=$o.reactiveElementPolyfillSupport,Go=(n,e)=>n,jo={toAttribute(n,e){switch(e){case Boolean:n=n?TN:null;break;case Object:case Array:n=n==null?n:JSON.stringify(n)}return n},fromAttribute(n,e){let t=n;switch(e){case Boolean:t=n!==null;break;case Number:t=n===null?null:Number(n);break;case Object:case Array:try{t=JSON.parse(n)}catch{t=null}}return t}},zl=(n,e)=>!vN(n,e),Tw={attribute:!0,type:String,converter:jo,reflect:!1,useDefault:!1,hasChanged:zl};Symbol.metadata??=Symbol("metadata"),$o.litPropertyMetadata??=new WeakMap;var Xi=class extends(globalThis.HTMLElement??Yp){static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=Tw){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let i=Symbol(),r=this.getPropertyDescriptor(e,i,t);r!==void 0&&wN(this.prototype,e,r)}}static getPropertyDescriptor(e,t,i){let{get:r,set:o}=xN(this.prototype,e)??{get(){return this[t]},set(s){this[t]=s}};return{get:r,set(s){let a=r?.call(this);o?.call(this,s),this.requestUpdate(e,a,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??Tw}static _$Ei(){if(this.hasOwnProperty(Go("elementProperties")))return;let e=AN(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(Go("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(Go("properties"))){let t=this.properties,i=[...PN(t),...kN(t)];for(let r of i)this.createProperty(r,t[r])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[i,r]of t)this.elementProperties.set(i,r)}this._$Eh=new Map;for(let[t,i]of this.elementProperties){let r=this._$Eu(t,i);r!==void 0&&this._$Eh.set(r,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let i=new Set(e.flat(1/0).reverse());for(let r of i)t.unshift(Xp(r))}else e!==void 0&&t.push(Xp(e));return t}static _$Eu(e,t){let i=t.attribute;return i===!1?void 0:typeof i=="string"?i:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return kw(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){let i=this.constructor.elementProperties.get(e),r=this.constructor._$Eu(e,i);if(r!==void 0&&i.reflect===!0){let o=(i.converter?.toAttribute!==void 0?i.converter:jo).toAttribute(t,i.type);this._$Em=e,o==null?this.removeAttribute(r):this.setAttribute(r,o),this._$Em=null}}_$AK(e,t){let i=this.constructor,r=i._$Eh.get(e);if(r!==void 0&&this._$Em!==r){let o=i.getPropertyOptions(r),s=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:jo;this._$Em=r;let a=s.fromAttribute(t,o.type);this[r]=a??this._$Ej?.get(r)??a,this._$Em=null}}requestUpdate(e,t,i,r=!1,o){if(e!==void 0){let s=this.constructor;if(r===!1&&(o=this[e]),i??=s.getPropertyOptions(e),!((i.hasChanged??zl)(o,t)||i.useDefault&&i.reflect&&o===this._$Ej?.get(e)&&!this.hasAttribute(s._$Eu(e,i))))return;this.C(e,t,i)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:r,wrapped:o},s){i&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,s??t??this[e]),o!==!0||s!==void 0)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),r===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[r,o]of this._$Ep)this[r]=o;this._$Ep=void 0}let i=this.constructor.elementProperties;if(i.size>0)for(let[r,o]of i){let{wrapped:s}=o,a=this[r];s!==!0||this._$AL.has(r)||a===void 0||this.C(r,void 0,o,a)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(i=>i.hostUpdate?.()),this.update(t)):this._$EM()}catch(i){throw e=!1,this._$EM(),i}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(e){}firstUpdated(e){}};Xi.elementStyles=[],Xi.shadowRootOptions={mode:"open"},Xi[Go("elementProperties")]=new Map,Xi[Go("finalized")]=new Map,CN?.({ReactiveElement:Xi}),($o.reactiveElementVersions??=[]).push("2.1.2");var MN={attribute:!0,type:String,converter:jo,reflect:!1,hasChanged:zl},DN=(n=MN,e,t)=>{let{kind:i,metadata:r}=t,o=globalThis.litPropertyMetadata.get(r);if(o===void 0&&globalThis.litPropertyMetadata.set(r,o=new Map),i==="setter"&&((n=Object.create(n)).wrapped=!0),o.set(t.name,n),i==="accessor"){let{name:s}=t;return{set(a){let l=e.get.call(this);e.set.call(this,a),this.requestUpdate(s,l,n,!0,a)},init(a){return a!==void 0&&this.C(s,void 0,n,a),a}}}if(i==="setter"){let{name:s}=t;return function(a){let l=this[s];e.call(this,a),this.requestUpdate(s,l,n,!0,a)}}throw Error("Unsupported decorator location: "+i)};function Ul(n){return(e,t)=>typeof t=="object"?DN(n,e,t):((i,r,o)=>{let s=r.hasOwnProperty(o);return r.constructor.createProperty(o,i),s?Object.getOwnPropertyDescriptor(r,o):void 0})(n,e,t)}function Cw(n){return Ul({...n,state:!0,attribute:!1})}var EN={};Ew(EN,{AO_MODES:()=>zu,ATLAS_MANIFEST_PATH:()=>ow,ATLAS_REGION_KEY:()=>ix,ATLAS_SHEET_DIR:()=>sw,ATLAS_SHEET_SCHEME:()=>tx,ATLAS_SIZE_KEY:()=>rx,AUDIO_BUS_NAMES:()=>dt,AmbientLightNode:()=>Ht,AnimatedSprite2D:()=>ye,AnimatedSprite3D:()=>xi,AnimationPlayerBehavior:()=>li,AssetLoader:()=>Jc,AudioApi:()=>yo,AudioPlayer:()=>bt,AudioService:()=>Zc,BATCHABLE_2D_KEY:()=>Ne,BLEND_MODES_2D:()=>sf,BLEND_MODE_2D_OPTIONS:()=>ou,BUILTIN_SHADER_EFFECTS:()=>vs,BURST_MAX_PARTICLES:()=>Rv,Bar2D:()=>Ti,Batch2DSystem:()=>nn,BurstOnSignalBehavior:()=>No,Button2D:()=>gt,CAMERA2D_DEFAULTS:()=>Ns,CHARACTER_STATE_FINISHED_SIGNAL:()=>aw,CONTACT_MARGIN:()=>Fi,CURRENT_SCENE_FORMAT_VERSION:()=>iC,Camera2D:()=>Ft,Camera3D:()=>pe,CameraBrainBehavior:()=>ji,CanvasLayer2D:()=>hn,CharacterVisual2DBehavior:()=>Lo,Checkbox2D:()=>Ci,Collider2DBehavior:()=>Bo,Collision2DService:()=>Xn,ColorRect2D:()=>Qe,CutsceneApi:()=>bo,DEFAULT_CLIP_DURATION:()=>Ap,DEFAULT_FIXED_DELTA_SEC:()=>Np,DEFAULT_GEOMETRY_MATERIAL_TYPE:()=>Mu,DEFAULT_RUNTIME_TIME_CONFIG:()=>Ip,DIRECTION_AXES_ENABLED_KEY:()=>nc,DirectionalLightNode:()=>zt,EASING_NAMES:()=>_u,ECSService:()=>xo,EMOJI_GUARDED_TEXT_PROPERTIES:()=>rS,FadeBehavior:()=>Co,FloatText2D:()=>ho,GAME_DEBUG_GLOBAL_KEY:()=>Ur,GEOMETRY_KINDS:()=>Nu,GEOMETRY_MATERIAL_TYPES:()=>Di,GameCommandRegistry:()=>co,GameTime:()=>zi,GeometryMesh:()=>St,Group2D:()=>Ae,HemisphereLightNode:()=>qt,Hitbox2DBehavior:()=>Io,INSTANCE_TRANSFORM_KEYS:()=>bC,InputService:()=>$n,InstancedMesh3D:()=>vt,InventorySlot2D:()=>Mi,Joystick2D:()=>Pi,JuiceApi:()=>mo,KNOWN_SCENE_NODE_TYPES:()=>fu,LABEL_AUTO_SIZE_BLEED:()=>Vs,LABEL_GLOW_STRENGTH_LIMIT:()=>gr,LABEL_H_ALIGN_VALUES:()=>Pu,LABEL_LINE_HEIGHT_FACTOR:()=>Wf,LABEL_V_ALIGN_VALUES:()=>Os,Label2D:()=>yt,LocalizationService:()=>$i,MAX_NET_KIND:()=>cF,MAX_POLYGON_VERTICES:()=>$_,MAX_TICKS_PER_FRAME:()=>Jv,MIN_CLIP_DURATION:()=>Hv,MIN_POLYGON_VERTICES:()=>j_,MeshInstance:()=>ht,NET_APP_FLAGS_SHIFT:()=>Av,NET_OWNERSHIP_MASK:()=>ap,NODE2D_MARGIN_SIDES:()=>Vt,NetKindTable:()=>eo,NetRoomVars:()=>dl,NetworkConnectError:()=>st,NetworkNodeBinder:()=>lo,NetworkService:()=>ao,NetworkSpawnError:()=>me,NetworkedNodeBehavior:()=>ci,Node2D:()=>C,Node3D:()=>U,NodeBase:()=>I,OVERLAY_2D_FLAG:()=>ze,PHYSICS_DEBUG_ENABLED_KEY:()=>rc,PHYSICS_DEBUG_GLOBAL_KEY:()=>Wr,POST_PROCESS_DEFAULTS:()=>ag,PROJECT_AO_MODES:()=>rg,PROJECT_SCRIPT_DIRECTORIES:()=>qa,PROJECT_SCRIPT_EXCLUDE_PATTERN:()=>sS,PROJECT_TEXTURE_FILTERING_MODES:()=>qm,ParticleBurst2D:()=>uo,Particles3D:()=>ft,Physics2DService:()=>Jn,PhysicsBody2DBehavior:()=>Ro,PhysicsWorld2DBehavior:()=>Oo,PinToNodeBehavior:()=>To,PlaySoundBehavior:()=>Do,PointLightNode:()=>Ut,PopInBehavior:()=>oi,PostProcess:()=>it,PostProcessingPipeline:()=>wo,PunchScaleBehavior:()=>ni,RUNTIME_PROPERTY_SINK_GLOBAL_KEY:()=>tc,RUNTIME_SCENE_GLOBAL_KEY:()=>ec,RadialProgressBehavior:()=>Mo,RejectCode:()=>q,ReplicatedTransformBehavior:()=>_o,ResourceManager:()=>Zl,RevoluteJoint2DBehavior:()=>Vo,RotateBehavior:()=>Po,RuntimeRenderer:()=>zp,SCENE_COMPONENT_DEFINITION_KEYS:()=>oC,SCENE_DISK_FORMAT_TYPES:()=>dC,SCENE_DOCUMENT_KEYS:()=>rC,SCENE_NODE_DEFINITION_KEYS:()=>nC,SCRIPT_ERROR_SINK_GLOBAL_KEY:()=>Hr,SEMANTIC_POINTER_ID:()=>fr,SFX_PRESETS:()=>bl,SHARED_UNIT_QUAD_GEOMETRY:()=>De,SIGNAL_EMIT_SINK_GLOBAL_KEY:()=>qr,SceneLoader:()=>xd,SceneManager:()=>Td,SceneRunner:()=>Fp,SceneSaver:()=>Ad,SceneService:()=>So,SceneValidationError:()=>ve,Script:()=>V,ScriptRegistry:()=>eu,ScrollContainer2D:()=>et,SfxOnSignalBehavior:()=>Eo,SfxSynth:()=>go,ShaderEffectStack:()=>_e,ShakeBehavior:()=>_t,SimpleMoveBehavior:()=>ko,SineBehavior:()=>Ao,Slider2D:()=>Ai,SpineSkeleton2D:()=>gi,SpineSkeletonView:()=>an,SpotLightNode:()=>Wt,Sprite2D:()=>Fe,Sprite3D:()=>mt,TARGET_DISTANCE:()=>Qf,TEST_COMPONENT_TYPE_PREFIX:()=>Om,TRAIL_MAX_POINTS:()=>Bv,TiledSprite2D:()=>bi,Trail2D:()=>po,TweenApi:()=>fo,UIControl2D:()=>Z,USER_SCRIPT_ID_PREFIX:()=>aS,VIRTUAL_CAMERA_DEFAULTS:()=>We,VirtualCamera3D:()=>xt,WS_CLOSE_NORMAL:()=>ol,WS_CLOSE_PROTOCOL_VIOLATION:()=>Xd,WsTransport:()=>to,ZERO_SLICE_BORDER:()=>Pf,Z_INDEX_LIMIT:()=>tn,aimCameraNodeAt:()=>Fs,aoModeUsesSSAO:()=>Fu,applyBlendMode2DToMaterial:()=>en,applyClipAtTime:()=>Hi,applyEasing:()=>wt,applyLocaleToTree:()=>wl,applyTextStyle:()=>ki,applyTextureRegionToTexture:()=>mi,assign2DRenderOrder:()=>Bs,assignWithoutSchemaRefresh:()=>Rt,atlasSizeOf:()=>Yr,attachComponentDefinitions:()=>ys,autoloadComponentType:()=>kd,baseRegionOf:()=>$r,blendingForMode2D:()=>af,boxPolygon:()=>Er,buildSkinGeometry:()=>yi,buildTiledSpriteGeometry:()=>pr,capsulePolygon:()=>Id,circleIntersectsPolygon:()=>Kn,circlePolygon:()=>yS,clampSfxPitch:()=>Wi,cleanPolygon:()=>Ed,coerceKeyframeValue:()=>jv,coerceTextureResource:()=>D,coerceToPropertyType:()=>bs,collectAudioKeysInRange:()=>wp,collectClipPointNames:()=>hc,collectComponentDefinitions:()=>Jr,collectEventKeysInRange:()=>xp,collectRenderabilityIssues:()=>KT,collectTimedKeysInRange:()=>vp,collideCirclePolygon:()=>Ja,collideCircles:()=>zd,collidePolygons:()=>Ud,composeEffectShaders:()=>au,composeTextureRegion:()=>jr,configure2DTexture:()=>$,convexHull:()=>$a,convexPolygonsIntersect:()=>SS,copyAtlasMetadata:()=>bc,createAtlasResolver:()=>Sc,createClipBindings:()=>kp,createDefaultClip:()=>DE,createEmptyAnimationSet:()=>Cp,cssFont:()=>Bf,cssFontFamily:()=>If,cssFontWeight:()=>Rf,decodeSignalPayload:()=>KD,decomposeConvex:()=>Ka,defineGroup:()=>Mx,defineProperty:()=>x,describeEmojiAsArt:()=>xC,describeFontFace:()=>Qr,describeRejectCode:()=>hl,describeThrown:()=>Le,describeUnknownNodeType:()=>yu,distanceToPolygonBoundary:()=>bS,drawStyledText:()=>pn,effectSupportsTarget:()=>Ss,encodeSignalPayload:()=>Cv,ensureCounterClockwise:()=>Dr,findActiveCamera2D:()=>mu,findAnimationClip:()=>pc,findAnimationFramePoint:()=>uc,findKeyframeClip:()=>Gi,fireEventKey:()=>Pp,fromSchemaValue:()=>wE,generateTrackId:()=>Gv,getActiveLocalization:()=>Ke,getAllShaderEffectTypes:()=>Vx,getAnimationFrameTexturePath:()=>pi,getComponentSchemaProperties:()=>tf,getGameDebug:()=>Iw,getNetKindTable:()=>Kd,getNodePropertySchema:()=>ke,getPhysicsDebugSource:()=>ic,getProjectAODefault:()=>og,getProjectTextureFiltering:()=>fc,getPropertiesByGroup:()=>Ax,getPropertyDefinition:()=>Ot,getPropertyDisplayValue:()=>Tx,getRuntimeLivePropertySink:()=>Bw,getRuntimeSceneRoot:()=>Rw,getSceneNodeDiskFormat:()=>gC,getScriptErrorSink:()=>Vm,getShaderEffectType:()=>xs,getSignalEmitSink:()=>Lm,installAtlasFromManifest:()=>aN,installReactiveSchemaProperties:()=>H,interpolateValue:()=>Fv,isDirectionAxesEnabled:()=>oc,isEmojiOnlyText:()=>nS,isFontFaceRegistered:()=>wx,isHighEndDevice:()=>lg,isInertNode:()=>eS,isInteractive:()=>i0,isKeyframeEasing:()=>Ue,isKnownSceneNodeType:()=>gu,isNetTeleport:()=>cp,isPhysicsDebugEnabled:()=>Gr,isPolygonConvex:()=>gS,isProjectScriptEntry:()=>kC,isProjectScriptPath:()=>cS,isSameTextureRegion:()=>ex,isScriptComponent:()=>Sx,isScriptComponentClass:()=>uS,isSequenceAnimationFrame:()=>cc,isSfxPreset:()=>Rr,isShaderEffectHost:()=>_x,isSliceBorderEmpty:()=>mr,isSpineModuleAvailable:()=>ox,isStaleComponent:()=>nf,isTestHarnessComponentType:()=>_w,isTextProperty:()=>oS,isTextureResourceRef:()=>mf,isTrackValueType:()=>qv,labelDecorationPadding:()=>Au,labelGlowBlurPx:()=>ku,labelGlowPasses:()=>Hf,layoutLabelText:()=>Tu,loadProjectFonts:()=>iu,loadSpineAsset:()=>xc,loadSpineModule:()=>vc,makeSchemaPropertyReactive:()=>Hm,mergeSchemas:()=>le,netFlagsByte:()=>Tv,netOwnershipOf:()=>lp,normalizeAnimationResource:()=>dc,normalizeAutoloads:()=>hS,normalizeBlendMode2D:()=>Zr,normalizeKeyframeAnimationSet:()=>Sl,normalizeNodeTypeName:()=>dn,normalizePolygonConfig:()=>Yi,normalizeProjectTextureFiltering:()=>mc,normalizeSliceBorder:()=>Ie,paintLabelCanvas:()=>Cu,parseEventArgs:()=>sn,parseSpineAtlasPageNames:()=>ax,playable:()=>Lp,pointInPolygon:()=>Tt,polygonArea:()=>Dd,polygonBounds:()=>Nd,polygonCentroid:()=>Yn,polygonSignedArea:()=>Ya,projectScriptGlobPatterns:()=>PC,property:()=>Ul,quaternionToRotationZ:()=>PS,reactiveSchemaPropertyNames:()=>Ww,readBooleanArg:()=>Su,readNumberArg:()=>Ze,readStringArg:()=>r0,readWorldTransform2D:()=>ot,rectIntersectsConvexPolygon:()=>RC,rectIntersectsPolygon:()=>Rd,registerBuiltInScripts:()=>gN,registerGameDebug:()=>Nw,registerNetworkPrefab:()=>sM,registerPhysicsDebugSource:()=>Ow,registerProjectScriptExports:()=>AC,registerRuntimeLivePropertySink:()=>ls,registerRuntimeSceneRoot:()=>as,registerScriptErrorSink:()=>Fw,registerShaderEffect:()=>uf,registerSignalEmitSink:()=>zw,replaceStaleComponents:()=>kx,reportScriptError:()=>Me,reportSignalEmit:()=>sc,resetNetKindTable:()=>aM,resetProjectFontRegistry:()=>vx,resolveAnimatedSpriteFrameLayout:()=>uu,resolveFramePointToLocal:()=>hu,resolveFramePolygonToLocal:()=>du,resolveLocalizedText:()=>on,resolvePendingComponents:()=>nu,resolveRuntimeTimeConfig:()=>Rp,resolveSceneDiskKey:()=>yC,resolveSceneNodeType:()=>Is,resolveSpinePagePath:()=>jm,resolveTrackTarget:()=>Sp,sampleTrack:()=>zv,sanitizeTextureRegion:()=>gc,scanScriptLocalizationKeys:()=>sN,segmentPolygonT:()=>Bd,serializePolygonConfig:()=>uN,setActiveLocalization:()=>Ts,setDefaultStoreUrl:()=>KE,setDirectionAxesEnabled:()=>Lw,setNetworkPrefabTable:()=>oM,setNodePropertyValue:()=>ur,setPhysicsDebugEnabled:()=>Vw,setPlayableAdapter:()=>YE,setPostprocessingModuleLoader:()=>FE,setProjectAODefault:()=>f0,setProjectTextureFiltering:()=>Zw,setSpineModuleLoader:()=>nx,shaderEffectsCacheKey:()=>lu,shakeNoise:()=>Si,spineAssetKey:()=>lr,stampAtlasView:()=>yc,state:()=>Cw,styledTextPadding:()=>mn,suggestSceneNodeType:()=>Mf,sweepCircleAgainstPolygon:()=>Qn,toSchemaValue:()=>Uv,transformPolygon:()=>_i,userScriptComponentId:()=>Ga,validatePropertyValue:()=>of,worldToCanvasLogical:()=>Ep,worldToCanvasThroughCamera:()=>xl});export{wd as a,Zl as b,Ur as c,Nw as d,Iw as e,ec as f,as as g,Rw as h,tc as i,ls as j,Bw as k,Wr as l,Ow as m,ic as n,rc as o,Vw as p,Gr as q,nc as r,Lw as s,oc as t,Om as u,_w as v,Hr as w,Fw as x,Vm as y,qr as z,zw as A,Lm as B,sc as C,Me as D,Le as E,De as F,I as G,U as H,Hm as I,H as J,Ww as K,Rt as L,ht as M,pi as N,cc as O,uc as P,hc as Q,dc as R,pc as S,qm as T,mc as U,Zw as V,fc as W,$ as X,gc as Y,mi as Z,jr as _,ex as $,tx as aa,ix as ba,rx as ca,$r as da,Yr as ea,yc as fa,bc as ga,Sc as ha,nx as ia,ox as ja,vc as ka,lr as la,jm as ma,ax as na,xc as oa,Jc as pa,dt as qa,Zc as ra,eu as sa,V as ta,Sx as ua,Qr as va,vx as wa,wx as xa,iu as ya,tf as za,ys as Aa,nu as Ba,nf as Ca,kx as Da,Jr as Ea,ke as Fa,Ax as Ga,Ot as Ha,Tx as Ia,of as Ja,ur as Ka,sf as La,ou as Ma,Zr as Na,af as Oa,en as Pa,Vt as Qa,tn as Ra,C as Sa,x as Ta,bs as Ua,Mx as Va,le as Wa,Ss as Xa,vs as Ya,uf as Za,xs as _a,Vx as $a,au as ab,lu as bb,_x as cb,_e as db,mf as eb,D as fb,Ne as gb,nn as hb,Ts as ib,Ke as jb,on as kb,Fe as lb,sn as mb,uu as nb,hu as ob,du as pb,ye as qb,an as rb,gi as sb,Qe as tb,pr as ub,Pf as vb,Ie as wb,mr as xb,yi as yb,bi as zb,Ae as Ab,_t as Bb,Si as Cb,Ns as Db,Ft as Eb,mu as Fb,hn as Gb,zt as Hb,Ut as Ib,Wt as Jb,Ht as Kb,fu as Lb,dn as Mb,Is as Nb,gu as Ob,Mf as Pb,yu as Qb,qt as Rb,mt as Sb,xi as Tb,ft as Ub,i0 as Vb,Ze as Wb,Su as Xb,r0 as Yb,Pi as Zb,If as _b,Rf as $b,Bf as ac,pn as bc,ki as cc,mn as dc,ze as ec,Bs as fc,et as gc,fr as hc,Z as ic,gt as jc,Ai as kc,Ti as lc,Ci as mc,Mi as nc,Pu as oc,Os as pc,Wf as qc,Vs as rc,gr as sc,ku as tc,Hf as uc,Au as vc,Tu as wc,Cu as xc,yt as yc,bt as zc,Di as Ac,Mu as Bc,Nu as Cc,St as Dc,vt as Ec,Qf as Fc,Fs as Gc,pe as Hc,_u as Ic,Ue as Jc,wt as Kc,We as Lc,xt as Mc,zu as Nc,rg as Oc,f0 as Pc,og as Qc,ag as Rc,it as Sc,Fu as Tc,lg as Uc,ve as Vc,xd as Wc,KT as Xc,eS as Yc,iC as Zc,rC as _c,nC as $c,oC as ad,dC as bd,gC as cd,yC as dd,bC as ed,rS as fd,nS as gd,oS as hd,xC as id,qa as jd,sS as kd,PC as ld,aS as md,Ga as nd,cS as od,kC as pd,uS as qd,AC as rd,kd as sd,hS as td,Ad as ud,Td as vd,$n as wd,j_ as xd,$_ as yd,Ya as zd,Dd as Ad,Yn as Bd,gS as Cd,Dr as Dd,Ed,$a as Fd,Nd as Gd,_i as Hd,Er as Id,yS as Jd,Id as Kd,Tt as Ld,bS as Md,Kn as Nd,Rd as Od,RC as Pd,SS as Qd,Bd as Rd,Ka as Sd,ot as Td,PS as Ud,Xn as Vd,Fi as Wd,zd as Xd,Ja as Yd,Ud as Zd,Qn as _d,Jn as $d,q as ae,cF as be,eo as ce,Kd as de,oM as ee,sM as fe,aM as ge,Xd as he,ol as ie,to as je,ap as ke,Av as le,lp as me,Tv as ne,cp as oe,me as pe,st as qe,hl as re,dl as se,ao as te,Cv as ue,KD as ve,lo as we,zi as xe,co as ye,ni as ze,oi as Ae,Rv as Be,uo as Ce,ho as De,Bv as Ee,po as Fe,mo as Ge,fo as He,bl as Ie,Rr as Je,Wi as Ke,go as Le,yo as Me,Fv as Ne,zv as Oe,vp as Pe,wp as Qe,xp as Re,Pp as Se,Uv as Te,wE as Ue,Sp as Ve,kp as We,Hi as Xe,Hv as Ye,Ap as Ze,qv as _e,Gv as $e,jv as af,Sl as bf,Cp as cf,DE as df,Gi as ef,li as ff,ji as gf,bo as hf,$i as if,So as jf,FE as kf,wo as lf,wl as mf,xo as nf,Ep as of,xl as pf,Np as qf,Jv as rf,Ip as sf,Rp as tf,YE as uf,KE as vf,Lp as wf,Fp as xf,zp as yf,sN as zf,ow as Af,sw as Bf,aN as Cf,Po as Df,ko as Ef,Ao as Ff,To as Gf,Co as Hf,Mo as If,Do as Jf,Eo as Kf,No as Lf,Yi as Mf,uN as Nf,Io as Of,Ro as Pf,Bo as Qf,Oo as Rf,Vo as Sf,aw as Tf,Lo as Uf,ci as Vf,_o as Wf,gN as Xf,Ul as Yf,Cw as Zf,EN as _f};