@ray-js/robot-map-sdk 0.0.16-beta.9 → 0.0.17-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/constant/methods.js +1 -1
  2. package/dist/index.d.ts +141 -2
  3. package/dist/index.rjs.js +1 -1
  4. package/dist-app/assets/index-BhBznOX2.js +1 -0
  5. package/dist-app/index.html +1 -1
  6. package/dist-docs/404.html +2 -2
  7. package/dist-docs/adr/0001-threshold-mirrors-virtual-wall.html +25 -0
  8. package/dist-docs/adr/0002-threshold-edit-surface-quad-family.html +25 -0
  9. package/dist-docs/agents/domain.html +3 -3
  10. package/dist-docs/agents/issue-tracker.html +3 -3
  11. package/dist-docs/agents/triage-labels.html +3 -3
  12. package/dist-docs/assets/adr_0001-threshold-mirrors-virtual-wall.md.BGtyf9GS.js +1 -0
  13. package/dist-docs/assets/adr_0001-threshold-mirrors-virtual-wall.md.BGtyf9GS.lean.js +1 -0
  14. package/dist-docs/assets/adr_0002-threshold-edit-surface-quad-family.md.BlvHYJT5.js +1 -0
  15. package/dist-docs/assets/adr_0002-threshold-edit-surface-quad-family.md.BlvHYJT5.lean.js +1 -0
  16. package/dist-docs/assets/{app.B8hs7_X-.js → app.tuTOhCpg.js} +1 -1
  17. package/dist-docs/assets/chunks/@localSearchIndexroot.7eWxrBA2.js +1 -0
  18. package/dist-docs/assets/chunks/{BitmapFont.DLy0SZnT.js → BitmapFont.Bn4Xj5K-.js} +1 -1
  19. package/dist-docs/assets/chunks/{BufferResource.BFWw7m1Q.js → BufferResource.DTCsTJzt.js} +1 -1
  20. package/dist-docs/assets/chunks/{CanvasRenderer.Bc_dThoq.js → CanvasRenderer.DflYBGLD.js} +1 -1
  21. package/dist-docs/assets/chunks/{RenderTargetSystem.BOdX2jvG.js → RenderTargetSystem.DBrMOqFS.js} +1 -1
  22. package/dist-docs/assets/chunks/{VPLocalSearchBox.6OPr0A3R.js → VPLocalSearchBox.D4ShZjav.js} +1 -1
  23. package/dist-docs/assets/chunks/{WebGLRenderer.hhgrJQl3.js → WebGLRenderer.CmlR6hDG.js} +1 -1
  24. package/dist-docs/assets/chunks/{WebGPURenderer.BAD7ncFI.js → WebGPURenderer.C7Xo_Nj6.js} +1 -1
  25. package/dist-docs/assets/chunks/{browserAll.D3TQ4Ojs.js → browserAll.CIjY9VGZ.js} +1 -1
  26. package/dist-docs/assets/chunks/index.BCZVCQiT.js +744 -0
  27. package/dist-docs/assets/chunks/theme.BwMYfKet.js +4 -0
  28. package/dist-docs/assets/chunks/{webworkerAll.BKEKVYer.js → webworkerAll.rjNztTjs.js} +1 -1
  29. package/dist-docs/assets/{guide_advanced-usage.md.B1LO3kNP.js → guide_advanced-usage.md.dxD8u9v3.js} +75 -3
  30. package/dist-docs/assets/{guide_advanced-usage.md.B1LO3kNP.lean.js → guide_advanced-usage.md.dxD8u9v3.lean.js} +1 -1
  31. package/dist-docs/assets/{guide_getting-started.md.RnJcv_dw.js → guide_getting-started.md.DcbNPHUc.js} +1 -1
  32. package/dist-docs/assets/reference_callbacks.md.Cm_LNx97.js +33 -0
  33. package/dist-docs/assets/{reference_callbacks.md.4Y7lqLLW.lean.js → reference_callbacks.md.Cm_LNx97.lean.js} +1 -1
  34. package/dist-docs/assets/{reference_config.md.Dr5HxVZt.js → reference_config.md.DpjGhNQS.js} +3 -3
  35. package/dist-docs/assets/reference_config.md.DpjGhNQS.lean.js +1 -0
  36. package/dist-docs/assets/{reference_data.md.C3E1VcWx.js → reference_data.md.DL6rfzez.js} +15 -3
  37. package/dist-docs/assets/{reference_data.md.C3E1VcWx.lean.js → reference_data.md.DL6rfzez.lean.js} +1 -1
  38. package/dist-docs/assets/{reference_methods.md.CxMQMj53.js → reference_methods.md.yWEfqPKf.js} +3 -3
  39. package/dist-docs/assets/{reference_methods.md.CxMQMj53.lean.js → reference_methods.md.yWEfqPKf.lean.js} +1 -1
  40. package/dist-docs/assets/reference_runtime.md.CE2QTAiD.js +20 -0
  41. package/dist-docs/assets/{reference_runtime.md.CX2K6JLY.lean.js → reference_runtime.md.CE2QTAiD.lean.js} +1 -1
  42. package/dist-docs/assets/{reference_types.md.Btpi6Kd9.js → reference_types.md.ZQU03iAA.js} +15 -2
  43. package/dist-docs/assets/reference_types.md.ZQU03iAA.lean.js +1 -0
  44. package/dist-docs/guide/advanced-usage.html +78 -6
  45. package/dist-docs/guide/concepts.html +3 -3
  46. package/dist-docs/guide/getting-started.html +5 -5
  47. package/dist-docs/guide/mcp.html +3 -3
  48. package/dist-docs/guide/spot-room-binding.html +3 -3
  49. package/dist-docs/hashmap.json +1 -1
  50. package/dist-docs/index.html +3 -3
  51. package/dist-docs/plans/2026-03-04-detected-objects-visibility-design.html +3 -3
  52. package/dist-docs/plans/2026-03-04-show-detected-objects-implementation-plan.html +3 -3
  53. package/dist-docs/plans/2026-03-10-simulator-debug-design.html +3 -3
  54. package/dist-docs/plans/2026-03-10-simulator-events-console-design.html +3 -3
  55. package/dist-docs/plans/2026-03-10-simulator-events-console-implementation-plan.html +3 -3
  56. package/dist-docs/plans/2026-03-10-simulator-runtime-controls-design.html +3 -3
  57. package/dist-docs/plans/2026-03-10-simulator-runtime-controls-implementation-plan.html +3 -3
  58. package/dist-docs/plans/2026-03-10-testing-rollout-next-steps-plan.html +3 -3
  59. package/dist-docs/plans/2026-03-11-simulator-logger-dump-implementation-plan.html +3 -3
  60. package/dist-docs/reference/callbacks.html +5 -5
  61. package/dist-docs/reference/config.html +6 -6
  62. package/dist-docs/reference/data.html +18 -6
  63. package/dist-docs/reference/methods.html +6 -6
  64. package/dist-docs/reference/runtime.html +5 -5
  65. package/dist-docs/reference/types.html +18 -5
  66. package/dist-docs/reference/utils.html +3 -3
  67. package/dist-docs/simulator/index.html +3 -3
  68. package/package.json +1 -1
  69. package/dist-app/assets/index-ZtQQb8gt.js +0 -1
  70. package/dist-docs/assets/chunks/@localSearchIndexroot.CHVWB7VI.js +0 -1
  71. package/dist-docs/assets/chunks/index.D_0j0U-Y.js +0 -744
  72. package/dist-docs/assets/chunks/theme.DDBFso_7.js +0 -4
  73. package/dist-docs/assets/reference_callbacks.md.4Y7lqLLW.js +0 -33
  74. package/dist-docs/assets/reference_config.md.Dr5HxVZt.lean.js +0 -1
  75. package/dist-docs/assets/reference_runtime.md.CX2K6JLY.js +0 -20
  76. package/dist-docs/assets/reference_types.md.Btpi6Kd9.lean.js +0 -1
  77. /package/dist-docs/assets/{guide_getting-started.md.RnJcv_dw.lean.js → guide_getting-started.md.DcbNPHUc.lean.js} +0 -0
@@ -0,0 +1,744 @@
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/chunks/browserAll.CIjY9VGZ.js","assets/chunks/webworkerAll.rjNztTjs.js","assets/chunks/framework.CBLqO2Q1.js","assets/chunks/mapValues.D2X8cRgC.js","assets/chunks/theme.BwMYfKet.js","assets/chunks/WebGPURenderer.C7Xo_Nj6.js","assets/chunks/BufferResource.DTCsTJzt.js","assets/chunks/RenderTargetSystem.DBrMOqFS.js","assets/chunks/WebGLRenderer.CmlR6hDG.js","assets/chunks/CanvasRenderer.DflYBGLD.js","assets/chunks/BitmapFont.Bn4Xj5K-.js"])))=>i.map(i=>d[i]);
2
+ var Kc=Object.defineProperty;var Qc=(n,e,t)=>e in n?Kc(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var f=(n,e,t)=>Qc(n,typeof e!="symbol"?e+"":e,t);import{V as Re}from"./framework.CBLqO2Q1.js";import{L as xh,u as Sh,m as vh,G as Jc,E as td,d as De,y as ed,Q as id,v as bh,H as sd,R as nd,T as rd,i as wr,U as wh,V as od,W as ad,I as hd,X as ld,K as ao,Y as cd,e as dd,w as ud,l as Hn,f as pd,a as fd,x as ho,Z as gd,h as md,_ as yd,j as xd,$ as Ch,a0 as Sd,a1 as vd,C as bd,a2 as wd,N as Vn,O as Cd,P as _d,M as lo}from"./mapValues.D2X8cRgC.js";import{a as ae,N as Ks,i as $e,D as _h,b as co,M as uo,d as Pd,H as Md,e as Ad}from"./theme.BwMYfKet.js";var I=(n=>(n.Application="application",n.WebGLPipes="webgl-pipes",n.WebGLPipesAdaptor="webgl-pipes-adaptor",n.WebGLSystem="webgl-system",n.WebGPUPipes="webgpu-pipes",n.WebGPUPipesAdaptor="webgpu-pipes-adaptor",n.WebGPUSystem="webgpu-system",n.CanvasSystem="canvas-system",n.CanvasPipesAdaptor="canvas-pipes-adaptor",n.CanvasPipes="canvas-pipes",n.Asset="asset",n.LoadParser="load-parser",n.ResolveParser="resolve-parser",n.CacheParser="cache-parser",n.DetectionParser="detection-parser",n.MaskEffect="mask-effect",n.BlendMode="blend-mode",n.TextureSource="texture-source",n.Environment="environment",n.ShapeBuilder="shape-builder",n.Batcher="batcher",n))(I||{});const Nn=n=>{if(typeof n=="function"||typeof n=="object"&&n.extension){if(!n.extension)throw new Error("Extension class must have an extension object");n={...typeof n.extension!="object"?{type:n.extension}:n.extension,ref:n}}if(typeof n=="object")n={...n};else throw new Error("Invalid extension type");return typeof n.type=="string"&&(n.type=[n.type]),n},Zi=(n,e)=>Nn(n).priority??e,K={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...n){return n.map(Nn).forEach(e=>{e.type.forEach(t=>{var i,s;return(s=(i=this._removeHandlers)[t])==null?void 0:s.call(i,e)})}),this},add(...n){return n.map(Nn).forEach(e=>{e.type.forEach(t=>{var r,o;const i=this._addHandlers,s=this._queue;i[t]?(o=i[t])==null||o.call(i,e):(s[t]=s[t]||[],(r=s[t])==null||r.push(e))})}),this},handle(n,e,t){var o;const i=this._addHandlers,s=this._removeHandlers;if(i[n]||s[n])throw new Error(`Extension type ${n} already has a handler`);i[n]=e,s[n]=t;const r=this._queue;return r[n]&&((o=r[n])==null||o.forEach(a=>e(a)),delete r[n]),this},handleByMap(n,e){return this.handle(n,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByNamedList(n,e,t=-1){return this.handle(n,i=>{e.findIndex(r=>r.name===i.name)>=0||(e.push({name:i.name,value:i.ref}),e.sort((r,o)=>Zi(o.value,t)-Zi(r.value,t)))},i=>{const s=e.findIndex(r=>r.name===i.name);s!==-1&&e.splice(s,1)})},handleByList(n,e,t=-1){return this.handle(n,i=>{e.includes(i.ref)||(e.push(i.ref),e.sort((s,r)=>Zi(r,t)-Zi(s,t)))},i=>{const s=e.indexOf(i.ref);s!==-1&&e.splice(s,1)})},mixin(n,...e){for(const t of e)Object.defineProperties(n.prototype,Object.getOwnPropertyDescriptors(t))}},Td={extension:{type:I.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await Re(()=>import("./browserAll.CIjY9VGZ.js"),__vite__mapDeps([0,1,2,3,4]))}},Rd={extension:{type:I.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await Re(()=>import("./webworkerAll.rjNztTjs.js"),__vite__mapDeps([1,2,3,4]))}};class ct{constructor(e,t,i){this._x=t||0,this._y=i||0,this._observer=e}clone(e){return new ct(e??this._observer,this._x,this._y)}set(e=0,t=e){return(this._x!==e||this._y!==t)&&(this._x=e,this._y=t,this._observer._onUpdate(this)),this}copyFrom(e){return(this._x!==e.x||this._y!==e.y)&&(this._x=e.x,this._y=e.y,this._observer._onUpdate(this)),this}copyTo(e){return e.set(this._x,this._y),e}equals(e){return e.x===this._x&&e.y===this._y}toString(){return`[pixi.js/math:ObservablePoint x=${this._x} y=${this._y} scope=${this._observer}]`}get x(){return this._x}set x(e){this._x!==e&&(this._x=e,this._observer._onUpdate(this))}get y(){return this._y}set y(e){this._y!==e&&(this._y=e,this._observer._onUpdate(this))}}var Ph={exports:{}};(function(n){var e=Object.prototype.hasOwnProperty,t="~";function i(){}Object.create&&(i.prototype=Object.create(null),new i().__proto__||(t=!1));function s(h,l,c){this.fn=h,this.context=l,this.once=c||!1}function r(h,l,c,d,u){if(typeof c!="function")throw new TypeError("The listener must be a function");var p=new s(c,d||h,u),g=t?t+l:l;return h._events[g]?h._events[g].fn?h._events[g]=[h._events[g],p]:h._events[g].push(p):(h._events[g]=p,h._eventsCount++),h}function o(h,l){--h._eventsCount===0?h._events=new i:delete h._events[l]}function a(){this._events=new i,this._eventsCount=0}a.prototype.eventNames=function(){var l=[],c,d;if(this._eventsCount===0)return l;for(d in c=this._events)e.call(c,d)&&l.push(t?d.slice(1):d);return Object.getOwnPropertySymbols?l.concat(Object.getOwnPropertySymbols(c)):l},a.prototype.listeners=function(l){var c=t?t+l:l,d=this._events[c];if(!d)return[];if(d.fn)return[d.fn];for(var u=0,p=d.length,g=new Array(p);u<p;u++)g[u]=d[u].fn;return g},a.prototype.listenerCount=function(l){var c=t?t+l:l,d=this._events[c];return d?d.fn?1:d.length:0},a.prototype.emit=function(l,c,d,u,p,g){var m=t?t+l:l;if(!this._events[m])return!1;var y=this._events[m],x=arguments.length,S,v;if(y.fn){switch(y.once&&this.removeListener(l,y.fn,void 0,!0),x){case 1:return y.fn.call(y.context),!0;case 2:return y.fn.call(y.context,c),!0;case 3:return y.fn.call(y.context,c,d),!0;case 4:return y.fn.call(y.context,c,d,u),!0;case 5:return y.fn.call(y.context,c,d,u,p),!0;case 6:return y.fn.call(y.context,c,d,u,p,g),!0}for(v=1,S=new Array(x-1);v<x;v++)S[v-1]=arguments[v];y.fn.apply(y.context,S)}else{var b=y.length,P;for(v=0;v<b;v++)switch(y[v].once&&this.removeListener(l,y[v].fn,void 0,!0),x){case 1:y[v].fn.call(y[v].context);break;case 2:y[v].fn.call(y[v].context,c);break;case 3:y[v].fn.call(y[v].context,c,d);break;case 4:y[v].fn.call(y[v].context,c,d,u);break;default:if(!S)for(P=1,S=new Array(x-1);P<x;P++)S[P-1]=arguments[P];y[v].fn.apply(y[v].context,S)}}return!0},a.prototype.on=function(l,c,d){return r(this,l,c,d,!1)},a.prototype.once=function(l,c,d){return r(this,l,c,d,!0)},a.prototype.removeListener=function(l,c,d,u){var p=t?t+l:l;if(!this._events[p])return this;if(!c)return o(this,p),this;var g=this._events[p];if(g.fn)g.fn===c&&(!u||g.once)&&(!d||g.context===d)&&o(this,p);else{for(var m=0,y=[],x=g.length;m<x;m++)(g[m].fn!==c||u&&!g[m].once||d&&g[m].context!==d)&&y.push(g[m]);y.length?this._events[p]=y.length===1?y[0]:y:o(this,p)}return this},a.prototype.removeAllListeners=function(l){var c;return l?(c=t?t+l:l,this._events[c]&&o(this,c)):(this._events=new i,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=t,a.EventEmitter=a,n.exports=a})(Ph);var kd=Ph.exports;const jt=xh(kd),Id=Math.PI*2,Ed=180/Math.PI,Dd=Math.PI/180;class J{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new J(this.x,this.y)}copyFrom(e){return this.set(e.x,e.y),this}copyTo(e){return e.set(this.x,this.y),e}equals(e){return e.x===this.x&&e.y===this.y}set(e=0,t=e){return this.x=e,this.y=t,this}toString(){return`[pixi.js/math:Point x=${this.x} y=${this.y}]`}static get shared(){return Qs.x=0,Qs.y=0,Qs}}const Qs=new J;class H{constructor(e=1,t=0,i=0,s=1,r=0,o=0){this.array=null,this.a=e,this.b=t,this.c=i,this.d=s,this.tx=r,this.ty=o}fromArray(e){this.a=e[0],this.b=e[1],this.c=e[3],this.d=e[4],this.tx=e[2],this.ty=e[5]}set(e,t,i,s,r,o){return this.a=e,this.b=t,this.c=i,this.d=s,this.tx=r,this.ty=o,this}toArray(e,t){this.array||(this.array=new Float32Array(9));const i=t||this.array;return e?(i[0]=this.a,i[1]=this.b,i[2]=0,i[3]=this.c,i[4]=this.d,i[5]=0,i[6]=this.tx,i[7]=this.ty,i[8]=1):(i[0]=this.a,i[1]=this.c,i[2]=this.tx,i[3]=this.b,i[4]=this.d,i[5]=this.ty,i[6]=0,i[7]=0,i[8]=1),i}apply(e,t){t=t||new J;const i=e.x,s=e.y;return t.x=this.a*i+this.c*s+this.tx,t.y=this.b*i+this.d*s+this.ty,t}applyInverse(e,t){t=t||new J;const i=this.a,s=this.b,r=this.c,o=this.d,a=this.tx,h=this.ty,l=1/(i*o+r*-s),c=e.x,d=e.y;return t.x=o*l*c+-r*l*d+(h*r-a*o)*l,t.y=i*l*d+-s*l*c+(-h*i+a*s)*l,t}translate(e,t){return this.tx+=e,this.ty+=t,this}scale(e,t){return this.a*=e,this.d*=t,this.c*=e,this.b*=t,this.tx*=e,this.ty*=t,this}rotate(e){const t=Math.cos(e),i=Math.sin(e),s=this.a,r=this.c,o=this.tx;return this.a=s*t-this.b*i,this.b=s*i+this.b*t,this.c=r*t-this.d*i,this.d=r*i+this.d*t,this.tx=o*t-this.ty*i,this.ty=o*i+this.ty*t,this}append(e){const t=this.a,i=this.b,s=this.c,r=this.d;return this.a=e.a*t+e.b*s,this.b=e.a*i+e.b*r,this.c=e.c*t+e.d*s,this.d=e.c*i+e.d*r,this.tx=e.tx*t+e.ty*s+this.tx,this.ty=e.tx*i+e.ty*r+this.ty,this}appendFrom(e,t){const i=e.a,s=e.b,r=e.c,o=e.d,a=e.tx,h=e.ty,l=t.a,c=t.b,d=t.c,u=t.d;return this.a=i*l+s*d,this.b=i*c+s*u,this.c=r*l+o*d,this.d=r*c+o*u,this.tx=a*l+h*d+t.tx,this.ty=a*c+h*u+t.ty,this}setTransform(e,t,i,s,r,o,a,h,l){return this.a=Math.cos(a+l)*r,this.b=Math.sin(a+l)*r,this.c=-Math.sin(a-h)*o,this.d=Math.cos(a-h)*o,this.tx=e-(i*this.a+s*this.c),this.ty=t-(i*this.b+s*this.d),this}prepend(e){const t=this.tx;if(e.a!==1||e.b!==0||e.c!==0||e.d!==1){const i=this.a,s=this.c;this.a=i*e.a+this.b*e.c,this.b=i*e.b+this.b*e.d,this.c=s*e.a+this.d*e.c,this.d=s*e.b+this.d*e.d}return this.tx=t*e.a+this.ty*e.c+e.tx,this.ty=t*e.b+this.ty*e.d+e.ty,this}decompose(e){const t=this.a,i=this.b,s=this.c,r=this.d,o=e.pivot,a=-Math.atan2(-s,r),h=Math.atan2(i,t),l=Math.abs(a+h);return l<1e-5||Math.abs(Id-l)<1e-5?(e.rotation=h,e.skew.x=e.skew.y=0):(e.rotation=0,e.skew.x=a,e.skew.y=h),e.scale.x=Math.sqrt(t*t+i*i),e.scale.y=Math.sqrt(s*s+r*r),e.position.x=this.tx+(o.x*t+o.y*s),e.position.y=this.ty+(o.x*i+o.y*r),e}invert(){const e=this.a,t=this.b,i=this.c,s=this.d,r=this.tx,o=e*s-t*i;return this.a=s/o,this.b=-t/o,this.c=-i/o,this.d=e/o,this.tx=(i*this.ty-s*r)/o,this.ty=-(e*this.ty-t*r)/o,this}isIdentity(){return this.a===1&&this.b===0&&this.c===0&&this.d===1&&this.tx===0&&this.ty===0}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const e=new H;return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyTo(e){return e.a=this.a,e.b=this.b,e.c=this.c,e.d=this.d,e.tx=this.tx,e.ty=this.ty,e}copyFrom(e){return this.a=e.a,this.b=e.b,this.c=e.c,this.d=e.d,this.tx=e.tx,this.ty=e.ty,this}equals(e){return e.a===this.a&&e.b===this.b&&e.c===this.c&&e.d===this.d&&e.tx===this.tx&&e.ty===this.ty}toString(){return`[pixi.js:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`}static get IDENTITY(){return Bd.identity()}static get shared(){return Fd.identity()}}const Fd=new H,Bd=new H,be=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],we=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],Ce=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],_e=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],$n=[],Mh=[],qi=Math.sign;function zd(){for(let n=0;n<16;n++){const e=[];$n.push(e);for(let t=0;t<16;t++){const i=qi(be[n]*be[t]+Ce[n]*we[t]),s=qi(we[n]*be[t]+_e[n]*we[t]),r=qi(be[n]*Ce[t]+Ce[n]*_e[t]),o=qi(we[n]*Ce[t]+_e[n]*_e[t]);for(let a=0;a<16;a++)if(be[a]===i&&we[a]===s&&Ce[a]===r&&_e[a]===o){e.push(a);break}}}for(let n=0;n<16;n++){const e=new H;e.set(be[n],we[n],Ce[n],_e[n],0,0),Mh.push(e)}}zd();const X={E:0,SE:1,S:2,SW:3,W:4,NW:5,N:6,NE:7,MIRROR_VERTICAL:8,MAIN_DIAGONAL:10,MIRROR_HORIZONTAL:12,REVERSE_DIAGONAL:14,uX:n=>be[n],uY:n=>we[n],vX:n=>Ce[n],vY:n=>_e[n],inv:n=>n&8?n&15:-n&7,add:(n,e)=>$n[n][e],sub:(n,e)=>$n[n][X.inv(e)],rotate180:n=>n^4,isVertical:n=>(n&3)===2,byDirection:(n,e)=>Math.abs(n)*2<=Math.abs(e)?e>=0?X.S:X.N:Math.abs(e)*2<=Math.abs(n)?n>0?X.E:X.W:e>0?n>0?X.SE:X.SW:n>0?X.NE:X.NW,matrixAppendRotationInv:(n,e,t=0,i=0,s=0,r=0)=>{const o=Mh[X.inv(e)],a=o.a,h=o.b,l=o.c,c=o.d,d=t-Math.min(0,a*s,l*r,a*s+l*r),u=i-Math.min(0,h*s,c*r,h*s+c*r),p=n.a,g=n.b,m=n.c,y=n.d;n.a=a*p+h*m,n.b=a*g+h*y,n.c=l*p+c*m,n.d=l*g+c*y,n.tx=d*p+u*m+n.tx,n.ty=d*g+u*y+n.ty},transformRectCoords:(n,e,t,i)=>{const{x:s,y:r,width:o,height:a}=n,{x:h,y:l,width:c,height:d}=e;return t===X.E?(i.set(s+h,r+l,o,a),i):t===X.S?i.set(c-r-a+h,s+l,a,o):t===X.W?i.set(c-s-o+h,d-r-a+l,o,a):t===X.N?i.set(r+h,d-s-o+l,a,o):i.set(s+h,r+l,o,a)}},Ki=[new J,new J,new J,new J];class tt{constructor(e=0,t=0,i=0,s=0){this.type="rectangle",this.x=Number(e),this.y=Number(t),this.width=Number(i),this.height=Number(s)}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}isEmpty(){return this.left===this.right||this.top===this.bottom}static get EMPTY(){return new tt(0,0,0,0)}clone(){return new tt(this.x,this.y,this.width,this.height)}copyFromBounds(e){return this.x=e.minX,this.y=e.minY,this.width=e.maxX-e.minX,this.height=e.maxY-e.minY,this}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){return this.width<=0||this.height<=0?!1:e>=this.x&&e<this.x+this.width&&t>=this.y&&t<this.y+this.height}strokeContains(e,t,i,s=.5){const{width:r,height:o}=this;if(r<=0||o<=0)return!1;const a=this.x,h=this.y,l=i*(1-s),c=i-l,d=a-l,u=a+r+l,p=h-l,g=h+o+l,m=a+c,y=a+r-c,x=h+c,S=h+o-c;return e>=d&&e<=u&&t>=p&&t<=g&&!(e>m&&e<y&&t>x&&t<S)}intersects(e,t){if(!t){const R=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=R)return!1;const T=this.y<e.y?e.y:this.y;return(this.bottom>e.bottom?e.bottom:this.bottom)>T}const i=this.left,s=this.right,r=this.top,o=this.bottom;if(s<=i||o<=r)return!1;const a=Ki[0].set(e.left,e.top),h=Ki[1].set(e.left,e.bottom),l=Ki[2].set(e.right,e.top),c=Ki[3].set(e.right,e.bottom);if(l.x<=a.x||h.y<=a.y)return!1;const d=Math.sign(t.a*t.d-t.b*t.c);if(d===0||(t.apply(a,a),t.apply(h,h),t.apply(l,l),t.apply(c,c),Math.max(a.x,h.x,l.x,c.x)<=i||Math.min(a.x,h.x,l.x,c.x)>=s||Math.max(a.y,h.y,l.y,c.y)<=r||Math.min(a.y,h.y,l.y,c.y)>=o))return!1;const u=d*(h.y-a.y),p=d*(a.x-h.x),g=u*i+p*r,m=u*s+p*r,y=u*i+p*o,x=u*s+p*o;if(Math.max(g,m,y,x)<=u*a.x+p*a.y||Math.min(g,m,y,x)>=u*c.x+p*c.y)return!1;const S=d*(a.y-l.y),v=d*(l.x-a.x),b=S*i+v*r,P=S*s+v*r,C=S*i+v*o,_=S*s+v*o;return!(Math.max(b,P,C,_)<=S*a.x+v*a.y||Math.min(b,P,C,_)>=S*c.x+v*c.y)}pad(e=0,t=e){return this.x-=e,this.y-=t,this.width+=e*2,this.height+=t*2,this}fit(e){const t=Math.max(this.x,e.x),i=Math.min(this.x+this.width,e.x+e.width),s=Math.max(this.y,e.y),r=Math.min(this.y+this.height,e.y+e.height);return this.x=t,this.width=Math.max(i-t,0),this.y=s,this.height=Math.max(r-s,0),this}ceil(e=1,t=.001){const i=Math.ceil((this.x+this.width-t)*e)/e,s=Math.ceil((this.y+this.height-t)*e)/e;return this.x=Math.floor((this.x+t)*e)/e,this.y=Math.floor((this.y+t)*e)/e,this.width=i-this.x,this.height=s-this.y,this}scale(e,t=e){return this.x*=e,this.y*=t,this.width*=e,this.height*=t,this}enlarge(e){const t=Math.min(this.x,e.x),i=Math.max(this.x+this.width,e.x+e.width),s=Math.min(this.y,e.y),r=Math.max(this.y+this.height,e.y+e.height);return this.x=t,this.width=i-t,this.y=s,this.height=r-s,this}getBounds(e){return e||(e=new tt),e.copyFrom(this),e}containsRect(e){if(this.width<=0||this.height<=0)return!1;const t=e.x,i=e.y,s=e.x+e.width,r=e.y+e.height;return t>=this.x&&t<this.x+this.width&&i>=this.y&&i<this.y+this.height&&s>=this.x&&s<this.x+this.width&&r>=this.y&&r<this.y+this.height}set(e,t,i,s){return this.x=e,this.y=t,this.width=i,this.height=s,this}toString(){return`[pixi.js/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`}}const Js={default:-1};function dt(n="default"){return Js[n]===void 0&&(Js[n]=-1),++Js[n]}const po=new Set,Q="8.0.0",Ld="8.3.4",Ye={quiet:!1,noColor:!1},V=(n,e,t=3)=>{if(Ye.quiet||po.has(e))return;let i=new Error().stack;const s=`${e}
3
+ Deprecated since v${n}`,r=typeof console.groupCollapsed=="function"&&!Ye.noColor;typeof i>"u"?console.warn("PixiJS Deprecation Warning: ",s):(i=i.split(`
4
+ `).splice(t).join(`
5
+ `),r?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",s),console.warn(i),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",s),console.warn(i))),po.add(e)};Object.defineProperties(V,{quiet:{get:()=>Ye.quiet,set:n=>{Ye.quiet=n},enumerable:!0,configurable:!1},noColor:{get:()=>Ye.noColor,set:n=>{Ye.noColor=n},enumerable:!0,configurable:!1}});const Ah=()=>{};function Qe(n){return n+=n===0?1:0,--n,n|=n>>>1,n|=n>>>2,n|=n>>>4,n|=n>>>8,n|=n>>>16,n+1}function fo(n){return!(n&n-1)&&!!n}function Th(n){const e={};for(const t in n)n[t]!==void 0&&(e[t]=n[t]);return e}const go=Object.create(null);function Od(n){const e=go[n];return e===void 0&&(go[n]=dt("resource")),e}const Rh=class kh extends jt{constructor(e={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,e={...kh.defaultOptions,...e},this.addressMode=e.addressMode,this.addressModeU=e.addressModeU??this.addressModeU,this.addressModeV=e.addressModeV??this.addressModeV,this.addressModeW=e.addressModeW??this.addressModeW,this.scaleMode=e.scaleMode,this.magFilter=e.magFilter??this.magFilter,this.minFilter=e.minFilter??this.minFilter,this.mipmapFilter=e.mipmapFilter??this.mipmapFilter,this.lodMinClamp=e.lodMinClamp,this.lodMaxClamp=e.lodMaxClamp,this.compare=e.compare,this.maxAnisotropy=e.maxAnisotropy??1}set addressMode(e){this.addressModeU=e,this.addressModeV=e,this.addressModeW=e}get addressMode(){return this.addressModeU}set wrapMode(e){V(Q,"TextureStyle.wrapMode is now TextureStyle.addressMode"),this.addressMode=e}get wrapMode(){return this.addressMode}set scaleMode(e){this.magFilter=e,this.minFilter=e,this.mipmapFilter=e}get scaleMode(){return this.magFilter}set maxAnisotropy(e){this._maxAnisotropy=Math.min(e,16),this._maxAnisotropy>1&&(this.scaleMode="linear")}get maxAnisotropy(){return this._maxAnisotropy}get _resourceId(){return this._sharedResourceId||this._generateResourceId()}update(){this._sharedResourceId=null,this.emit("change",this)}_generateResourceId(){const e=`${this.addressModeU}-${this.addressModeV}-${this.addressModeW}-${this.magFilter}-${this.minFilter}-${this.mipmapFilter}-${this.lodMinClamp}-${this.lodMaxClamp}-${this.compare}-${this._maxAnisotropy}`;return this._sharedResourceId=Od(e),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};Rh.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let Je=Rh;const Ih=class Eh extends jt{constructor(e={}){super(),this.options=e,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=dt("textureSource"),this._resourceType="textureSource",this._resourceId=dt("resource"),this.uploadMethodId="unknown",this._resolution=1,this.pixelWidth=1,this.pixelHeight=1,this.width=1,this.height=1,this.sampleCount=1,this.mipLevelCount=1,this.autoGenerateMipmaps=!1,this.format="rgba8unorm",this.dimension="2d",this.viewDimension="2d",this.arrayLayerCount=1,this.antialias=!1,this._touched=0,this._batchTick=-1,this._textureBindLocation=-1,e={...Eh.defaultOptions,...e},this.label=e.label??"",this.resource=e.resource,this.autoGarbageCollect=e.autoGarbageCollect,this._resolution=e.resolution,e.width?this.pixelWidth=e.width*this._resolution:this.pixelWidth=this.resource?this.resourceWidth??1:1,e.height?this.pixelHeight=e.height*this._resolution:this.pixelHeight=this.resource?this.resourceHeight??1:1,this.width=this.pixelWidth/this._resolution,this.height=this.pixelHeight/this._resolution,this.format=e.format,this.dimension=e.dimensions,this.viewDimension=e.viewDimension??e.dimensions,this.arrayLayerCount=e.arrayLayerCount,this.mipLevelCount=e.mipLevelCount,this.autoGenerateMipmaps=e.autoGenerateMipmaps,this.sampleCount=e.sampleCount,this.antialias=e.antialias,this.alphaMode=e.alphaMode,this.style=new Je(Th(e)),this.destroyed=!1,this._refreshPOT()}get source(){return this}get style(){return this._style}set style(e){var t,i;this.style!==e&&((t=this._style)==null||t.off("change",this._onStyleChange,this),this._style=e,(i=this._style)==null||i.on("change",this._onStyleChange,this),this._onStyleChange())}set maxAnisotropy(e){this._style.maxAnisotropy=e}get maxAnisotropy(){return this._style.maxAnisotropy}get addressMode(){return this._style.addressMode}set addressMode(e){this._style.addressMode=e}get repeatMode(){return this._style.addressMode}set repeatMode(e){this._style.addressMode=e}get magFilter(){return this._style.magFilter}set magFilter(e){this._style.magFilter=e}get minFilter(){return this._style.minFilter}set minFilter(e){this._style.minFilter=e}get mipmapFilter(){return this._style.mipmapFilter}set mipmapFilter(e){this._style.mipmapFilter=e}get lodMinClamp(){return this._style.lodMinClamp}set lodMinClamp(e){this._style.lodMinClamp=e}get lodMaxClamp(){return this._style.lodMaxClamp}set lodMaxClamp(e){this._style.lodMaxClamp=e}_onStyleChange(){this.emit("styleChange",this)}update(){if(this.resource){const e=this._resolution;if(this.resize(this.resourceWidth/e,this.resourceHeight/e))return}this.emit("update",this)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this._style&&(this._style.destroy(),this._style=null),this.uploadMethodId=null,this.resource=null,this.removeAllListeners()}unload(){var e,t;this._resourceId=dt("resource"),this.emit("change",this),this.emit("unload",this);for(const i in this._gpuData)(t=(e=this._gpuData[i])==null?void 0:e.destroy)==null||t.call(e);this._gpuData=Object.create(null)}get resourceWidth(){const{resource:e}=this;return e.naturalWidth||e.videoWidth||e.displayWidth||e.width}get resourceHeight(){const{resource:e}=this;return e.naturalHeight||e.videoHeight||e.displayHeight||e.height}get resolution(){return this._resolution}set resolution(e){this._resolution!==e&&(this._resolution=e,this.width=this.pixelWidth/e,this.height=this.pixelHeight/e)}resize(e,t,i){i||(i=this._resolution),e||(e=this.width),t||(t=this.height);const s=Math.round(e*i),r=Math.round(t*i);return this.width=s/i,this.height=r/i,this._resolution=i,this.pixelWidth===s&&this.pixelHeight===r?!1:(this._refreshPOT(),this.pixelWidth=s,this.pixelHeight=r,this.emit("resize",this),this._resourceId=dt("resource"),this.emit("change",this),!0)}updateMipmaps(){this.autoGenerateMipmaps&&this.mipLevelCount>1&&this.emit("updateMipmaps",this)}set wrapMode(e){this._style.wrapMode=e}get wrapMode(){return this._style.wrapMode}set scaleMode(e){this._style.scaleMode=e}get scaleMode(){return this._style.scaleMode}_refreshPOT(){this.isPowerOfTwo=fo(this.pixelWidth)&&fo(this.pixelHeight)}static test(e){throw new Error("Unimplemented")}};Ih.defaultOptions={resolution:1,format:"bgra8unorm",alphaMode:"premultiply-alpha-on-upload",dimensions:"2d",viewDimension:"2d",arrayLayerCount:1,mipLevelCount:1,autoGenerateMipmaps:!1,sampleCount:1,antialias:!1,autoGarbageCollect:!1};let zt=Ih;class Cr extends zt{constructor(e){const t=e.resource||new Float32Array(e.width*e.height*4);let i=e.format;i||(t instanceof Float32Array?i="rgba32float":t instanceof Int32Array||t instanceof Uint32Array?i="rgba32uint":t instanceof Int16Array||t instanceof Uint16Array?i="rgba16uint":(t instanceof Int8Array,i="bgra8unorm")),super({...e,resource:t,format:i}),this.uploadMethodId="buffer"}static test(e){return e instanceof Int8Array||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Int16Array||e instanceof Uint16Array||e instanceof Int32Array||e instanceof Uint32Array||e instanceof Float32Array}}Cr.extension=I.TextureSource;const mo=new H;class Wd{constructor(e,t){this.mapCoord=new H,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,typeof t>"u"?this.clampMargin=e.width<10?0:.5:this.clampMargin=t,this.isSimple=!1,this.texture=e}get texture(){return this._texture}set texture(e){var t;this.texture!==e&&((t=this._texture)==null||t.removeListener("update",this.update,this),this._texture=e,this._texture.addListener("update",this.update,this),this.update())}multiplyUvs(e,t){t===void 0&&(t=e);const i=this.mapCoord;for(let s=0;s<e.length;s+=2){const r=e[s],o=e[s+1];t[s]=r*i.a+o*i.c+i.tx,t[s+1]=r*i.b+o*i.d+i.ty}return t}update(){const e=this._texture;this._updateID++;const t=e.uvs;this.mapCoord.set(t.x1-t.x0,t.y1-t.y0,t.x3-t.x0,t.y3-t.y0,t.x0,t.y0);const i=e.orig,s=e.trim;s&&(mo.set(i.width/s.width,0,0,i.height/s.height,-s.x/s.width,-s.y/s.height),this.mapCoord.append(mo));const r=e.source,o=this.uClampFrame,a=this.clampMargin/r._resolution,h=this.clampOffset/r._resolution;return o[0]=(e.frame.x+a+h)/r.width,o[1]=(e.frame.y+a+h)/r.height,o[2]=(e.frame.x+e.frame.width-a+h)/r.width,o[3]=(e.frame.y+e.frame.height-a+h)/r.height,this.uClampOffset[0]=this.clampOffset/r.pixelWidth,this.uClampOffset[1]=this.clampOffset/r.pixelHeight,this.isSimple=e.frame.width===r.width&&e.frame.height===r.height&&e.rotate===0,!0}}class G extends jt{constructor({source:e,label:t,frame:i,orig:s,trim:r,defaultAnchor:o,defaultBorders:a,rotate:h,dynamic:l}={}){if(super(),this.uid=dt("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new tt,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=t,this.source=(e==null?void 0:e.source)??new zt,this.noFrame=!i,i)this.frame.copyFrom(i);else{const{width:c,height:d}=this._source;this.frame.width=c,this.frame.height=d}this.orig=s||this.frame,this.trim=r,this.rotate=h??0,this.defaultAnchor=o,this.defaultBorders=a,this.destroyed=!1,this.dynamic=l||!1,this.updateUvs()}set source(e){this._source&&this._source.off("resize",this.update,this),this._source=e,e.on("resize",this.update,this),this.emit("update",this)}get source(){return this._source}get textureMatrix(){return this._textureMatrix||(this._textureMatrix=new Wd(this)),this._textureMatrix}get width(){return this.orig.width}get height(){return this.orig.height}updateUvs(){const{uvs:e,frame:t}=this,{width:i,height:s}=this._source,r=t.x/i,o=t.y/s,a=t.width/i,h=t.height/s;let l=this.rotate;if(l){const c=a/2,d=h/2,u=r+c,p=o+d;l=X.add(l,X.NW),e.x0=u+c*X.uX(l),e.y0=p+d*X.uY(l),l=X.add(l,2),e.x1=u+c*X.uX(l),e.y1=p+d*X.uY(l),l=X.add(l,2),e.x2=u+c*X.uX(l),e.y2=p+d*X.uY(l),l=X.add(l,2),e.x3=u+c*X.uX(l),e.y3=p+d*X.uY(l)}else e.x0=r,e.y0=o,e.x1=r+a,e.y1=o,e.x2=r+a,e.y2=o+h,e.x3=r,e.y3=o+h}destroy(e=!1){this._source&&(this._source.off("resize",this.update,this),e&&(this._source.destroy(),this._source=null)),this._textureMatrix=null,this.destroyed=!0,this.emit("destroy",this),this.removeAllListeners()}update(){this.noFrame&&(this.frame.width=this._source.width,this.frame.height=this._source.height),this.updateUvs(),this.emit("update",this)}get baseTexture(){return V(Q,"Texture.baseTexture is now Texture.source"),this._source}}G.EMPTY=new G({label:"EMPTY",source:new zt({label:"EMPTY"})});G.EMPTY.destroy=Ah;G.WHITE=new G({source:new Cr({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"});G.WHITE.destroy=Ah;function Dh(n,e,t){const{width:i,height:s}=t.orig,r=t.trim;if(r){const o=r.width,a=r.height;n.minX=r.x-e._x*i,n.maxX=n.minX+o,n.minY=r.y-e._y*s,n.maxY=n.minY+a}else n.minX=-e._x*i,n.maxX=n.minX+i,n.minY=-e._y*s,n.maxY=n.minY+s}const yo=new H;class Ft{constructor(e=1/0,t=1/0,i=-1/0,s=-1/0){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=yo,this.minX=e,this.minY=t,this.maxX=i,this.maxY=s}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}get rectangle(){this._rectangle||(this._rectangle=new tt);const e=this._rectangle;return this.minX>this.maxX||this.minY>this.maxY?(e.x=0,e.y=0,e.width=0,e.height=0):e.copyFromBounds(this),e}clear(){return this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.matrix=yo,this}set(e,t,i,s){this.minX=e,this.minY=t,this.maxX=i,this.maxY=s}addFrame(e,t,i,s,r){r||(r=this.matrix);const o=r.a,a=r.b,h=r.c,l=r.d,c=r.tx,d=r.ty;let u=this.minX,p=this.minY,g=this.maxX,m=this.maxY,y=o*e+h*t+c,x=a*e+l*t+d;y<u&&(u=y),x<p&&(p=x),y>g&&(g=y),x>m&&(m=x),y=o*i+h*t+c,x=a*i+l*t+d,y<u&&(u=y),x<p&&(p=x),y>g&&(g=y),x>m&&(m=x),y=o*e+h*s+c,x=a*e+l*s+d,y<u&&(u=y),x<p&&(p=x),y>g&&(g=y),x>m&&(m=x),y=o*i+h*s+c,x=a*i+l*s+d,y<u&&(u=y),x<p&&(p=x),y>g&&(g=y),x>m&&(m=x),this.minX=u,this.minY=p,this.maxX=g,this.maxY=m}addRect(e,t){this.addFrame(e.x,e.y,e.x+e.width,e.y+e.height,t)}addBounds(e,t){this.addFrame(e.minX,e.minY,e.maxX,e.maxY,t)}addBoundsMask(e){this.minX=this.minX>e.minX?this.minX:e.minX,this.minY=this.minY>e.minY?this.minY:e.minY,this.maxX=this.maxX<e.maxX?this.maxX:e.maxX,this.maxY=this.maxY<e.maxY?this.maxY:e.maxY}applyMatrix(e){const t=this.minX,i=this.minY,s=this.maxX,r=this.maxY,{a:o,b:a,c:h,d:l,tx:c,ty:d}=e;let u=o*t+h*i+c,p=a*t+l*i+d;this.minX=u,this.minY=p,this.maxX=u,this.maxY=p,u=o*s+h*i+c,p=a*s+l*i+d,this.minX=u<this.minX?u:this.minX,this.minY=p<this.minY?p:this.minY,this.maxX=u>this.maxX?u:this.maxX,this.maxY=p>this.maxY?p:this.maxY,u=o*t+h*r+c,p=a*t+l*r+d,this.minX=u<this.minX?u:this.minX,this.minY=p<this.minY?p:this.minY,this.maxX=u>this.maxX?u:this.maxX,this.maxY=p>this.maxY?p:this.maxY,u=o*s+h*r+c,p=a*s+l*r+d,this.minX=u<this.minX?u:this.minX,this.minY=p<this.minY?p:this.minY,this.maxX=u>this.maxX?u:this.maxX,this.maxY=p>this.maxY?p:this.maxY}fit(e){return this.minX<e.left&&(this.minX=e.left),this.maxX>e.right&&(this.maxX=e.right),this.minY<e.top&&(this.minY=e.top),this.maxY>e.bottom&&(this.maxY=e.bottom),this}fitBounds(e,t,i,s){return this.minX<e&&(this.minX=e),this.maxX>t&&(this.maxX=t),this.minY<i&&(this.minY=i),this.maxY>s&&(this.maxY=s),this}pad(e,t=e){return this.minX-=e,this.maxX+=e,this.minY-=t,this.maxY+=t,this}ceil(){return this.minX=Math.floor(this.minX),this.minY=Math.floor(this.minY),this.maxX=Math.ceil(this.maxX),this.maxY=Math.ceil(this.maxY),this}clone(){return new Ft(this.minX,this.minY,this.maxX,this.maxY)}scale(e,t=e){return this.minX*=e,this.minY*=t,this.maxX*=e,this.maxY*=t,this}get x(){return this.minX}set x(e){const t=this.maxX-this.minX;this.minX=e,this.maxX=e+t}get y(){return this.minY}set y(e){const t=this.maxY-this.minY;this.minY=e,this.maxY=e+t}get width(){return this.maxX-this.minX}set width(e){this.maxX=this.minX+e}get height(){return this.maxY-this.minY}set height(e){this.maxY=this.minY+e}get left(){return this.minX}get right(){return this.maxX}get top(){return this.minY}get bottom(){return this.maxY}get isPositive(){return this.maxX-this.minX>0&&this.maxY-this.minY>0}get isValid(){return this.minX+this.minY!==1/0}addVertexData(e,t,i,s){let r=this.minX,o=this.minY,a=this.maxX,h=this.maxY;s||(s=this.matrix);const l=s.a,c=s.b,d=s.c,u=s.d,p=s.tx,g=s.ty;for(let m=t;m<i;m+=2){const y=e[m],x=e[m+1],S=l*y+d*x+p,v=c*y+u*x+g;r=S<r?S:r,o=v<o?v:o,a=S>a?S:a,h=v>h?v:h}this.minX=r,this.minY=o,this.maxX=a,this.maxY=h}containsPoint(e,t){return this.minX<=e&&this.minY<=t&&this.maxX>=e&&this.maxY>=t}toString(){return`[pixi.js:Bounds minX=${this.minX} minY=${this.minY} maxX=${this.maxX} maxY=${this.maxY} width=${this.width} height=${this.height}]`}copyFrom(e){return this.minX=e.minX,this.minY=e.minY,this.maxX=e.maxX,this.maxY=e.maxY,this}}var Gd={grad:.9,turn:360,rad:360/(2*Math.PI)},qt=function(n){return typeof n=="string"?n.length>0:typeof n=="number"},St=function(n,e,t){return e===void 0&&(e=0),t===void 0&&(t=Math.pow(10,e)),Math.round(t*n)/t+0},Dt=function(n,e,t){return e===void 0&&(e=0),t===void 0&&(t=1),n>t?t:n>e?n:e},Fh=function(n){return(n=isFinite(n)?n%360:0)>0?n:n+360},xo=function(n){return{r:Dt(n.r,0,255),g:Dt(n.g,0,255),b:Dt(n.b,0,255),a:Dt(n.a)}},tn=function(n){return{r:St(n.r),g:St(n.g),b:St(n.b),a:St(n.a,3)}},Ud=/^#([0-9a-f]{3,8})$/i,Qi=function(n){var e=n.toString(16);return e.length<2?"0"+e:e},Bh=function(n){var e=n.r,t=n.g,i=n.b,s=n.a,r=Math.max(e,t,i),o=r-Math.min(e,t,i),a=o?r===e?(t-i)/o:r===t?2+(i-e)/o:4+(e-t)/o:0;return{h:60*(a<0?a+6:a),s:r?o/r*100:0,v:r/255*100,a:s}},zh=function(n){var e=n.h,t=n.s,i=n.v,s=n.a;e=e/360*6,t/=100,i/=100;var r=Math.floor(e),o=i*(1-t),a=i*(1-(e-r)*t),h=i*(1-(1-e+r)*t),l=r%6;return{r:255*[i,a,o,o,h,i][l],g:255*[h,i,i,a,o,o][l],b:255*[o,o,h,i,i,a][l],a:s}},So=function(n){return{h:Fh(n.h),s:Dt(n.s,0,100),l:Dt(n.l,0,100),a:Dt(n.a)}},vo=function(n){return{h:St(n.h),s:St(n.s),l:St(n.l),a:St(n.a,3)}},bo=function(n){return zh((t=(e=n).s,{h:e.h,s:(t*=((i=e.l)<50?i:100-i)/100)>0?2*t/(i+t)*100:0,v:i+t,a:e.a}));var e,t,i},_i=function(n){return{h:(e=Bh(n)).h,s:(s=(200-(t=e.s))*(i=e.v)/100)>0&&s<200?t*i/100/(s<=100?s:200-s)*100:0,l:s/2,a:e.a};var e,t,i,s},Hd=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Vd=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Nd=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,$d=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Yn={string:[[function(n){var e=Ud.exec(n);return e?(n=e[1]).length<=4?{r:parseInt(n[0]+n[0],16),g:parseInt(n[1]+n[1],16),b:parseInt(n[2]+n[2],16),a:n.length===4?St(parseInt(n[3]+n[3],16)/255,2):1}:n.length===6||n.length===8?{r:parseInt(n.substr(0,2),16),g:parseInt(n.substr(2,2),16),b:parseInt(n.substr(4,2),16),a:n.length===8?St(parseInt(n.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(n){var e=Nd.exec(n)||$d.exec(n);return e?e[2]!==e[4]||e[4]!==e[6]?null:xo({r:Number(e[1])/(e[2]?100/255:1),g:Number(e[3])/(e[4]?100/255:1),b:Number(e[5])/(e[6]?100/255:1),a:e[7]===void 0?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(n){var e=Hd.exec(n)||Vd.exec(n);if(!e)return null;var t,i,s=So({h:(t=e[1],i=e[2],i===void 0&&(i="deg"),Number(t)*(Gd[i]||1)),s:Number(e[3]),l:Number(e[4]),a:e[5]===void 0?1:Number(e[5])/(e[6]?100:1)});return bo(s)},"hsl"]],object:[[function(n){var e=n.r,t=n.g,i=n.b,s=n.a,r=s===void 0?1:s;return qt(e)&&qt(t)&&qt(i)?xo({r:Number(e),g:Number(t),b:Number(i),a:Number(r)}):null},"rgb"],[function(n){var e=n.h,t=n.s,i=n.l,s=n.a,r=s===void 0?1:s;if(!qt(e)||!qt(t)||!qt(i))return null;var o=So({h:Number(e),s:Number(t),l:Number(i),a:Number(r)});return bo(o)},"hsl"],[function(n){var e=n.h,t=n.s,i=n.v,s=n.a,r=s===void 0?1:s;if(!qt(e)||!qt(t)||!qt(i))return null;var o=function(a){return{h:Fh(a.h),s:Dt(a.s,0,100),v:Dt(a.v,0,100),a:Dt(a.a)}}({h:Number(e),s:Number(t),v:Number(i),a:Number(r)});return zh(o)},"hsv"]]},wo=function(n,e){for(var t=0;t<e.length;t++){var i=e[t][0](n);if(i)return[i,e[t][1]]}return[null,void 0]},Yd=function(n){return typeof n=="string"?wo(n.trim(),Yn.string):typeof n=="object"&&n!==null?wo(n,Yn.object):[null,void 0]},en=function(n,e){var t=_i(n);return{h:t.h,s:Dt(t.s+100*e,0,100),l:t.l,a:t.a}},sn=function(n){return(299*n.r+587*n.g+114*n.b)/1e3/255},Co=function(n,e){var t=_i(n);return{h:t.h,s:t.s,l:Dt(t.l+100*e,0,100),a:t.a}},Xn=function(){function n(e){this.parsed=Yd(e)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return n.prototype.isValid=function(){return this.parsed!==null},n.prototype.brightness=function(){return St(sn(this.rgba),2)},n.prototype.isDark=function(){return sn(this.rgba)<.5},n.prototype.isLight=function(){return sn(this.rgba)>=.5},n.prototype.toHex=function(){return e=tn(this.rgba),t=e.r,i=e.g,s=e.b,o=(r=e.a)<1?Qi(St(255*r)):"","#"+Qi(t)+Qi(i)+Qi(s)+o;var e,t,i,s,r,o},n.prototype.toRgb=function(){return tn(this.rgba)},n.prototype.toRgbString=function(){return e=tn(this.rgba),t=e.r,i=e.g,s=e.b,(r=e.a)<1?"rgba("+t+", "+i+", "+s+", "+r+")":"rgb("+t+", "+i+", "+s+")";var e,t,i,s,r},n.prototype.toHsl=function(){return vo(_i(this.rgba))},n.prototype.toHslString=function(){return e=vo(_i(this.rgba)),t=e.h,i=e.s,s=e.l,(r=e.a)<1?"hsla("+t+", "+i+"%, "+s+"%, "+r+")":"hsl("+t+", "+i+"%, "+s+"%)";var e,t,i,s,r},n.prototype.toHsv=function(){return e=Bh(this.rgba),{h:St(e.h),s:St(e.s),v:St(e.v),a:St(e.a,3)};var e},n.prototype.invert=function(){return Vt({r:255-(e=this.rgba).r,g:255-e.g,b:255-e.b,a:e.a});var e},n.prototype.saturate=function(e){return e===void 0&&(e=.1),Vt(en(this.rgba,e))},n.prototype.desaturate=function(e){return e===void 0&&(e=.1),Vt(en(this.rgba,-e))},n.prototype.grayscale=function(){return Vt(en(this.rgba,-1))},n.prototype.lighten=function(e){return e===void 0&&(e=.1),Vt(Co(this.rgba,e))},n.prototype.darken=function(e){return e===void 0&&(e=.1),Vt(Co(this.rgba,-e))},n.prototype.rotate=function(e){return e===void 0&&(e=15),this.hue(this.hue()+e)},n.prototype.alpha=function(e){return typeof e=="number"?Vt({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):St(this.rgba.a,3);var t},n.prototype.hue=function(e){var t=_i(this.rgba);return typeof e=="number"?Vt({h:e,s:t.s,l:t.l,a:t.a}):St(t.h)},n.prototype.isEqual=function(e){return this.toHex()===Vt(e).toHex()},n}(),Vt=function(n){return n instanceof Xn?n:new Xn(n)},_o=[],Xd=function(n){n.forEach(function(e){_o.indexOf(e)<0&&(e(Xn,Yn),_o.push(e))})};function jd(n,e){var t={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},i={};for(var s in t)i[t[s]]=s;var r={};n.prototype.toName=function(o){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var a,h,l=i[this.toHex()];if(l)return l;if(o!=null&&o.closest){var c=this.toRgb(),d=1/0,u="black";if(!r.length)for(var p in t)r[p]=new n(t[p]).toRgb();for(var g in t){var m=(a=c,h=r[g],Math.pow(a.r-h.r,2)+Math.pow(a.g-h.g,2)+Math.pow(a.b-h.b,2));m<d&&(d=m,u=g)}return u}},e.string.push([function(o){var a=o.toLowerCase(),h=a==="transparent"?"#0000":t[a];return h?new n(h).toRgb():null},"name"])}Xd([jd]);const ti=class vi{constructor(e=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=e}get red(){return this._components[0]}get green(){return this._components[1]}get blue(){return this._components[2]}get alpha(){return this._components[3]}setValue(e){return this.value=e,this}set value(e){if(e instanceof vi)this._value=this._cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(e===null)throw new Error("Cannot set Color#value to null");(this._value===null||!this._isSourceEqual(this._value,e))&&(this._value=this._cloneSource(e),this._normalize(this._value))}}get value(){return this._value}_cloneSource(e){return typeof e=="string"||typeof e=="number"||e instanceof Number||e===null?e:Array.isArray(e)||ArrayBuffer.isView(e)?e.slice(0):typeof e=="object"&&e!==null?{...e}:e}_isSourceEqual(e,t){const i=typeof e;if(i!==typeof t)return!1;if(i==="number"||i==="string"||e instanceof Number)return e===t;if(Array.isArray(e)&&Array.isArray(t)||ArrayBuffer.isView(e)&&ArrayBuffer.isView(t))return e.length!==t.length?!1:e.every((r,o)=>r===t[o]);if(e!==null&&t!==null){const r=Object.keys(e),o=Object.keys(t);return r.length!==o.length?!1:r.every(a=>e[a]===t[a])}return e===t}toRgba(){const[e,t,i,s]=this._components;return{r:e,g:t,b:i,a:s}}toRgb(){const[e,t,i]=this._components;return{r:e,g:t,b:i}}toRgbaString(){const[e,t,i]=this.toUint8RgbArray();return`rgba(${e},${t},${i},${this.alpha})`}toUint8RgbArray(e){const[t,i,s]=this._components;return this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb),e[0]=Math.round(t*255),e[1]=Math.round(i*255),e[2]=Math.round(s*255),e}toArray(e){this._arrayRgba||(this._arrayRgba=[]),e||(e=this._arrayRgba);const[t,i,s,r]=this._components;return e[0]=t,e[1]=i,e[2]=s,e[3]=r,e}toRgbArray(e){this._arrayRgb||(this._arrayRgb=[]),e||(e=this._arrayRgb);const[t,i,s]=this._components;return e[0]=t,e[1]=i,e[2]=s,e}toNumber(){return this._int}toBgrNumber(){const[e,t,i]=this.toUint8RgbArray();return(i<<16)+(t<<8)+e}toLittleEndianNumber(){const e=this._int;return(e>>16)+(e&65280)+((e&255)<<16)}multiply(e){const[t,i,s,r]=vi._temp.setValue(e)._components;return this._components[0]*=t,this._components[1]*=i,this._components[2]*=s,this._components[3]*=r,this._refreshInt(),this._value=null,this}premultiply(e,t=!0){return t&&(this._components[0]*=e,this._components[1]*=e,this._components[2]*=e),this._components[3]=e,this._refreshInt(),this._value=null,this}toPremultiplied(e,t=!0){if(e===1)return(255<<24)+this._int;if(e===0)return t?0:this._int;let i=this._int>>16&255,s=this._int>>8&255,r=this._int&255;return t&&(i=i*e+.5|0,s=s*e+.5|0,r=r*e+.5|0),(e*255<<24)+(i<<16)+(s<<8)+r}toHex(){const e=this._int.toString(16);return`#${"000000".substring(0,6-e.length)+e}`}toHexa(){const t=Math.round(this._components[3]*255).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(e){return this._components[3]=this._clamp(e),this}_normalize(e){let t,i,s,r;if((typeof e=="number"||e instanceof Number)&&e>=0&&e<=16777215){const o=e;t=(o>>16&255)/255,i=(o>>8&255)/255,s=(o&255)/255,r=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[t,i,s,r=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[t,i,s,r=255]=e,t/=255,i/=255,s/=255,r/=255;else if(typeof e=="string"||typeof e=="object"){if(typeof e=="string"){const a=vi.HEX_PATTERN.exec(e);a&&(e=`#${a[2]}`)}const o=Vt(e);o.isValid()&&({r:t,g:i,b:s,a:r}=o.rgba,t/=255,i/=255,s/=255)}if(t!==void 0)this._components[0]=t,this._components[1]=i,this._components[2]=s,this._components[3]=r,this._refreshInt();else throw new Error(`Unable to convert color ${e}`)}_refreshInt(){this._clamp(this._components);const[e,t,i]=this._components;this._int=(e*255<<16)+(t*255<<8)+(i*255|0)}_clamp(e,t=0,i=1){return typeof e=="number"?Math.min(Math.max(e,t),i):(e.forEach((s,r)=>{e[r]=Math.min(Math.max(s,t),i)}),e)}static isColorLike(e){return typeof e=="number"||typeof e=="string"||e instanceof Number||e instanceof vi||Array.isArray(e)||e instanceof Uint8Array||e instanceof Uint8ClampedArray||e instanceof Float32Array||e.r!==void 0&&e.g!==void 0&&e.b!==void 0||e.r!==void 0&&e.g!==void 0&&e.b!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0||e.h!==void 0&&e.s!==void 0&&e.l!==void 0&&e.a!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0||e.h!==void 0&&e.s!==void 0&&e.v!==void 0&&e.a!==void 0}};ti.shared=new ti;ti._temp=new ti;ti.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let rt=ti;const Zd={cullArea:null,cullable:!1,cullableChildren:!0};let nn=0;const Po=500;function nt(...n){nn!==Po&&(nn++,nn===Po?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...n))}const Vi={_registeredResources:new Set,register(n){this._registeredResources.add(n)},unregister(n){this._registeredResources.delete(n)},release(){this._registeredResources.forEach(n=>n.clear())},get registeredCount(){return this._registeredResources.size},isRegistered(n){return this._registeredResources.has(n)},reset(){this._registeredResources.clear()}};class qd{constructor(e,t){this._pool=[],this._count=0,this._index=0,this._classType=e,t&&this.prepopulate(t)}prepopulate(e){for(let t=0;t<e;t++)this._pool[this._index++]=new this._classType;this._count+=e}get(e){var i;let t;return this._index>0?t=this._pool[--this._index]:(t=new this._classType,this._count++),(i=t.init)==null||i.call(t,e),t}return(e){var t;(t=e.reset)==null||t.call(e),this._pool[this._index++]=e}get totalSize(){return this._count}get totalFree(){return this._index}get totalUsed(){return this._count-this._index}clear(){if(this._pool.length>0&&this._pool[0].destroy)for(let e=0;e<this._index;e++)this._pool[e].destroy();this._pool.length=0,this._count=0,this._index=0}}class Kd{constructor(){this._poolsByClass=new Map}prepopulate(e,t){this.getPool(e).prepopulate(t)}get(e,t){return this.getPool(e).get(t)}return(e){this.getPool(e.constructor).return(e)}getPool(e){return this._poolsByClass.has(e)||this._poolsByClass.set(e,new qd(e)),this._poolsByClass.get(e)}stats(){const e={};return this._poolsByClass.forEach(t=>{const i=e[t._classType.name]?t._classType.name+t._classType.ID:t._classType.name;e[i]={free:t.totalFree,used:t.totalUsed,size:t.totalSize}}),e}clear(){this._poolsByClass.forEach(e=>e.clear()),this._poolsByClass.clear()}}const Rt=new Kd;Vi.register(Rt);const Qd={get isCachedAsTexture(){var n;return!!((n=this.renderGroup)!=null&&n.isCachedAsTexture)},cacheAsTexture(n){typeof n=="boolean"&&n===!1?this.disableRenderGroup():(this.enableRenderGroup(),this.renderGroup.enableCacheAsTexture(n===!0?{}:n))},updateCacheTexture(){var n;(n=this.renderGroup)==null||n.updateCacheTexture()},get cacheAsBitmap(){return this.isCachedAsTexture},set cacheAsBitmap(n){V("v8.6.0","cacheAsBitmap is deprecated, use cacheAsTexture instead."),this.cacheAsTexture(n)}};function Jd(n,e,t){const i=n.length;let s;if(e>=i||t===0)return;t=e+t>i?i-e:t;const r=i-t;for(s=e;s<r;++s)n[s]=n[s+t];n.length=r}const tu={allowChildren:!0,removeChildren(n=0,e){var r;const t=e??this.children.length,i=t-n,s=[];if(i>0&&i<=t){for(let a=t-1;a>=n;a--){const h=this.children[a];h&&(s.push(h),h.parent=null)}Jd(this.children,n,t);const o=this.renderGroup||this.parentRenderGroup;o&&o.removeChildren(s);for(let a=0;a<s.length;++a){const h=s[a];(r=h.parentRenderLayer)==null||r.detach(h),this.emit("childRemoved",h,this,a),s[a].emit("removed",this)}return s.length>0&&this._didViewChangeTick++,s}else if(i===0&&this.children.length===0)return s;throw new RangeError("removeChildren: numeric values are outside the acceptable range.")},removeChildAt(n){const e=this.getChildAt(n);return this.removeChild(e)},getChildAt(n){if(n<0||n>=this.children.length)throw new Error(`getChildAt: Index (${n}) does not exist.`);return this.children[n]},setChildIndex(n,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);this.getChildIndex(n),this.addChildAt(n,e)},getChildIndex(n){const e=this.children.indexOf(n);if(e===-1)throw new Error("The supplied Container must be a child of the caller");return e},addChildAt(n,e){this.allowChildren||V(Q,"addChildAt: Only Containers will be allowed to add children in v8.0.0");const{children:t}=this;if(e<0||e>t.length)throw new Error(`${n}addChildAt: The index ${e} supplied is out of bounds ${t.length}`);if(n.parent){const s=n.parent.children.indexOf(n);if(n.parent===this&&s===e)return n;s!==-1&&n.parent.children.splice(s,1)}e===t.length?t.push(n):t.splice(e,0,n),n.parent=this,n.didChange=!0,n._updateFlags=15;const i=this.renderGroup||this.parentRenderGroup;return i&&i.addChild(n),this.sortableChildren&&(this.sortDirty=!0),this.emit("childAdded",n,this,e),n.emit("added",this),n},swapChildren(n,e){if(n===e)return;const t=this.getChildIndex(n),i=this.getChildIndex(e);this.children[t]=e,this.children[i]=n;const s=this.renderGroup||this.parentRenderGroup;s&&(s.structureDidChange=!0),this._didContainerChangeTick++},removeFromParent(){var n;(n=this.parent)==null||n.removeChild(this)},reparentChild(...n){return n.length===1?this.reparentChildAt(n[0],this.children.length):(n.forEach(e=>this.reparentChildAt(e,this.children.length)),n[0])},reparentChildAt(n,e){if(n.parent===this)return this.setChildIndex(n,e),n;const t=n.worldTransform.clone();n.removeFromParent(),this.addChildAt(n,e);const i=this.worldTransform.clone();return i.invert(),t.prepend(i),n.setFromMatrix(t),n},replaceChild(n,e){n.updateLocalTransform(),this.addChildAt(e,this.getChildIndex(n)),e.setFromMatrix(n.localTransform),e.updateLocalTransform(),this.removeChild(n)}},eu={collectRenderables(n,e,t){this.parentRenderLayer&&this.parentRenderLayer!==t||this.globalDisplayStatus<7||!this.includeInBuild||(this.sortableChildren&&this.sortChildren(),this.isSimple?this.collectRenderablesSimple(n,e,t):this.renderGroup?e.renderPipes.renderGroup.addRenderGroup(this.renderGroup,n):this.collectRenderablesWithEffects(n,e,t))},collectRenderablesSimple(n,e,t){const i=this.children,s=i.length;for(let r=0;r<s;r++)i[r].collectRenderables(n,e,t)},collectRenderablesWithEffects(n,e,t){const{renderPipes:i}=e;for(let s=0;s<this.effects.length;s++){const r=this.effects[s];i[r.pipe].push(r,this,n)}this.collectRenderablesSimple(n,e,t);for(let s=this.effects.length-1;s>=0;s--){const r=this.effects[s];i[r.pipe].pop(r,this,n)}}};class Mo{constructor(){this.pipe="filter",this.priority=1}destroy(){for(let e=0;e<this.filters.length;e++)this.filters[e].destroy();this.filters=null,this.filterArea=null}}class iu{constructor(){this._effectClasses=[],this._tests=[],this._initialized=!1}init(){this._initialized||(this._initialized=!0,this._effectClasses.forEach(e=>{this.add({test:e.test,maskClass:e})}))}add(e){this._tests.push(e)}getMaskEffect(e){this._initialized||this.init();for(let t=0;t<this._tests.length;t++){const i=this._tests[t];if(i.test(e))return Rt.get(i.maskClass,e)}return e}returnMaskEffect(e){Rt.return(e)}}const jn=new iu;K.handleByList(I.MaskEffect,jn._effectClasses);const su={_maskEffect:null,_maskOptions:{inverse:!1},_filterEffect:null,effects:[],_markStructureAsChanged(){const n=this.renderGroup||this.parentRenderGroup;n&&(n.structureDidChange=!0)},addEffect(n){this.effects.indexOf(n)===-1&&(this.effects.push(n),this.effects.sort((t,i)=>t.priority-i.priority),this._markStructureAsChanged(),this._updateIsSimple())},removeEffect(n){const e=this.effects.indexOf(n);e!==-1&&(this.effects.splice(e,1),this._markStructureAsChanged(),this._updateIsSimple())},set mask(n){const e=this._maskEffect;(e==null?void 0:e.mask)!==n&&(e&&(this.removeEffect(e),jn.returnMaskEffect(e),this._maskEffect=null),n!=null&&(this._maskEffect=jn.getMaskEffect(n),this.addEffect(this._maskEffect)))},get mask(){var n;return(n=this._maskEffect)==null?void 0:n.mask},setMask(n){this._maskOptions={...this._maskOptions,...n},n.mask&&(this.mask=n.mask),this._markStructureAsChanged()},set filters(n){var r;!Array.isArray(n)&&n&&(n=[n]);const e=this._filterEffect||(this._filterEffect=new Mo);n=n;const t=(n==null?void 0:n.length)>0,i=((r=e.filters)==null?void 0:r.length)>0,s=t!==i;n=Array.isArray(n)?n.slice(0):n,e.filters=Object.freeze(n),s&&(t?this.addEffect(e):(this.removeEffect(e),e.filters=n??null))},get filters(){var n;return(n=this._filterEffect)==null?void 0:n.filters},set filterArea(n){this._filterEffect||(this._filterEffect=new Mo),this._filterEffect.filterArea=n},get filterArea(){var n;return(n=this._filterEffect)==null?void 0:n.filterArea}},nu={label:null,get name(){return V(Q,"Container.name property has been removed, use Container.label instead"),this.label},set name(n){V(Q,"Container.name property has been removed, use Container.label instead"),this.label=n},getChildByName(n,e=!1){return this.getChildByLabel(n,e)},getChildByLabel(n,e=!1){const t=this.children;for(let i=0;i<t.length;i++){const s=t[i];if(s.label===n||n instanceof RegExp&&n.test(s.label))return s}if(e)for(let i=0;i<t.length;i++){const r=t[i].getChildByLabel(n,!0);if(r)return r}return null},getChildrenByLabel(n,e=!1,t=[]){const i=this.children;for(let s=0;s<i.length;s++){const r=i[s];(r.label===n||n instanceof RegExp&&n.test(r.label))&&t.push(r)}if(e)for(let s=0;s<i.length;s++)i[s].getChildrenByLabel(n,!0,t);return t}},Pt=Rt.getPool(H),ee=Rt.getPool(Ft),ru=new H,ou={getFastGlobalBounds(n,e){e||(e=new Ft),e.clear(),this._getGlobalBoundsRecursive(!!n,e,this.parentRenderLayer),e.isValid||e.set(0,0,0,0);const t=this.renderGroup||this.parentRenderGroup;return e.applyMatrix(t.worldTransform),e},_getGlobalBoundsRecursive(n,e,t){let i=e;if(n&&this.parentRenderLayer&&this.parentRenderLayer!==t||this.localDisplayStatus!==7||!this.measurable)return;const s=!!this.effects.length;if((this.renderGroup||s)&&(i=ee.get().clear()),this.boundsArea)e.addRect(this.boundsArea,this.worldTransform);else{if(this.renderPipeId){const o=this.bounds;i.addFrame(o.minX,o.minY,o.maxX,o.maxY,this.groupTransform)}const r=this.children;for(let o=0;o<r.length;o++)r[o]._getGlobalBoundsRecursive(n,i,t)}if(s){let r=!1;const o=this.renderGroup||this.parentRenderGroup;for(let a=0;a<this.effects.length;a++)this.effects[a].addBounds&&(r||(r=!0,i.applyMatrix(o.worldTransform)),this.effects[a].addBounds(i,!0));r&&i.applyMatrix(o.worldTransform.copyTo(ru).invert()),e.addBounds(i),ee.return(i)}else this.renderGroup&&(e.addBounds(i,this.relativeGroupTransform),ee.return(i))}};function Lh(n,e,t){t.clear();let i,s;return n.parent?e?i=n.parent.worldTransform:(s=Pt.get().identity(),i=_r(n,s)):i=H.IDENTITY,Oh(n,t,i,e),s&&Pt.return(s),t.isValid||t.set(0,0,0,0),t}function Oh(n,e,t,i){var a,h;if(!n.visible||!n.measurable)return;let s;i?s=n.worldTransform:(n.updateLocalTransform(),s=Pt.get(),s.appendFrom(n.localTransform,t));const r=e,o=!!n.effects.length;if(o&&(e=ee.get().clear()),n.boundsArea)e.addRect(n.boundsArea,s);else{const l=n.bounds;l&&!l.isEmpty()&&(e.matrix=s,e.addBounds(l));for(let c=0;c<n.children.length;c++)Oh(n.children[c],e,s,i)}if(o){for(let l=0;l<n.effects.length;l++)(h=(a=n.effects[l]).addBounds)==null||h.call(a,e);r.addBounds(e,H.IDENTITY),ee.return(e)}i||Pt.return(s)}function _r(n,e){const t=n.parent;return t&&(_r(t,e),t.updateLocalTransform(),e.append(t.localTransform)),e}function Pr(n,e){if(n===16777215||!e)return e;if(e===16777215||!n)return n;const t=n>>16&255,i=n>>8&255,s=n&255,r=e>>16&255,o=e>>8&255,a=e&255,h=t*r/255|0,l=i*o/255|0,c=s*a/255|0;return(h<<16)+(l<<8)+c}const Ao=16777215;function To(n,e){return n===Ao?e:e===Ao?n:Pr(n,e)}function Pi(n){return((n&255)<<16)+(n&65280)+(n>>16&255)}const au={getGlobalAlpha(n){if(n)return this.renderGroup?this.renderGroup.worldAlpha:this.parentRenderGroup?this.parentRenderGroup.worldAlpha*this.alpha:this.alpha;let e=this.alpha,t=this.parent;for(;t;)e*=t.alpha,t=t.parent;return e},getGlobalTransform(n=new H,e){if(e)return n.copyFrom(this.worldTransform);this.updateLocalTransform();const t=_r(this,Pt.get().identity());return n.appendFrom(this.localTransform,t),Pt.return(t),n},getGlobalTint(n){if(n)return this.renderGroup?Pi(this.renderGroup.worldColor):this.parentRenderGroup?Pi(To(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let e=this.localColor,t=this.parent;for(;t;)e=To(e,t.localColor),t=t.parent;return Pi(e)}};function Wh(n,e,t){return e.clear(),t||(t=H.IDENTITY),Gh(n,e,t,n,!0),e.isValid||e.set(0,0,0,0),e}function Gh(n,e,t,i,s){var h,l;let r;if(s)r=Pt.get(),r=t.copyTo(r);else{if(!n.visible||!n.measurable)return;n.updateLocalTransform();const c=n.localTransform;r=Pt.get(),r.appendFrom(c,t)}const o=e,a=!!n.effects.length;if(a&&(e=ee.get().clear()),n.boundsArea)e.addRect(n.boundsArea,r);else{n.renderPipeId&&(e.matrix=r,e.addBounds(n.bounds));const c=n.children;for(let d=0;d<c.length;d++)Gh(c[d],e,r,i,!1)}if(a){for(let c=0;c<n.effects.length;c++)(l=(h=n.effects[c]).addLocalBounds)==null||l.call(h,e,i);o.addBounds(e,H.IDENTITY),ee.return(e)}Pt.return(r)}function Uh(n,e){const t=n.children;for(let i=0;i<t.length;i++){const s=t[i],r=s.uid,o=(s._didViewChangeTick&65535)<<16|s._didContainerChangeTick&65535,a=e.index;(e.data[a]!==r||e.data[a+1]!==o)&&(e.data[e.index]=r,e.data[e.index+1]=o,e.didChange=!0),e.index=a+2,s.children.length&&Uh(s,e)}return e.didChange}const hu=new H,lu={_localBoundsCacheId:-1,_localBoundsCacheData:null,_setWidth(n,e){const t=Math.sign(this.scale.x)||1;e!==0?this.scale.x=n/e*t:this.scale.x=t},_setHeight(n,e){const t=Math.sign(this.scale.y)||1;e!==0?this.scale.y=n/e*t:this.scale.y=t},getLocalBounds(){this._localBoundsCacheData||(this._localBoundsCacheData={data:[],index:1,didChange:!1,localBounds:new Ft});const n=this._localBoundsCacheData;return n.index=1,n.didChange=!1,n.data[0]!==this._didViewChangeTick&&(n.didChange=!0,n.data[0]=this._didViewChangeTick),Uh(this,n),n.didChange&&Wh(this,n.localBounds,hu),n.localBounds},getBounds(n,e){return Lh(this,n,e||new Ft)}},cu={_onRender:null,set onRender(n){const e=this.renderGroup||this.parentRenderGroup;if(!n){this._onRender&&(e==null||e.removeOnRender(this)),this._onRender=null;return}this._onRender||e==null||e.addOnRender(this),this._onRender=n},get onRender(){return this._onRender}},du={_zIndex:0,sortDirty:!1,sortableChildren:!1,get zIndex(){return this._zIndex},set zIndex(n){this._zIndex!==n&&(this._zIndex=n,this.depthOfChildModified())},depthOfChildModified(){this.parent&&(this.parent.sortableChildren=!0,this.parent.sortDirty=!0),this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0)},sortChildren(){this.sortDirty&&(this.sortDirty=!1,this.children.sort(uu))}};function uu(n,e){return n._zIndex-e._zIndex}const pu={getGlobalPosition(n=new J,e=!1){return this.parent?this.parent.toGlobal(this._position,n,e):(n.x=this._position.x,n.y=this._position.y),n},toGlobal(n,e,t=!1){const i=this.getGlobalTransform(Pt.get(),t);return e=i.apply(n,e),Pt.return(i),e},toLocal(n,e,t,i){e&&(n=e.toGlobal(n,t,i));const s=this.getGlobalTransform(Pt.get(),i);return t=s.applyInverse(n,t),Pt.return(s),t}};class Mr{constructor(){this.uid=dt("instructionSet"),this.instructions=[],this.instructionSize=0,this.renderables=[],this.gcTick=0}reset(){this.instructionSize=0}destroy(){this.instructions.length=0,this.renderables.length=0,this.renderPipes=null,this.gcTick=0}add(e){this.instructions[this.instructionSize++]=e}log(){this.instructions.length=this.instructionSize,console.table(this.instructions,["type","action"])}}let fu=0;class gu{constructor(e){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=e||{},this.enableFullScreen=!1,this.textureStyle=new Je(this.textureOptions)}createTexture(e,t,i){const s=new zt({...this.textureOptions,width:e,height:t,resolution:1,antialias:i,autoGarbageCollect:!1});return new G({source:s,label:`texturePool_${fu++}`})}getOptimalTexture(e,t,i=1,s){let r=Math.ceil(e*i-1e-6),o=Math.ceil(t*i-1e-6);r=Qe(r),o=Qe(o);const a=(r<<17)+(o<<1)+(s?1:0);this._texturePool[a]||(this._texturePool[a]=[]);let h=this._texturePool[a].pop();return h||(h=this.createTexture(r,o,s)),h.source._resolution=i,h.source.width=r/i,h.source.height=o/i,h.source.pixelWidth=r,h.source.pixelHeight=o,h.frame.x=0,h.frame.y=0,h.frame.width=e,h.frame.height=t,h.updateUvs(),this._poolKeyHash[h.uid]=a,h}getSameSizeTexture(e,t=!1){const i=e.source;return this.getOptimalTexture(e.width,e.height,i._resolution,t)}returnTexture(e,t=!1){const i=this._poolKeyHash[e.uid];t&&(e.source.style=this.textureStyle),this._texturePool[i].push(e)}clear(e){if(e=e!==!1,e)for(const t in this._texturePool){const i=this._texturePool[t];if(i)for(let s=0;s<i.length;s++)i[s].destroy(!0)}this._texturePool={}}}const Ds=new gu;Vi.register(Ds);class mu{constructor(){this.renderPipeId="renderGroup",this.root=null,this.canBundle=!1,this.renderGroupParent=null,this.renderGroupChildren=[],this.worldTransform=new H,this.worldColorAlpha=4294967295,this.worldColor=16777215,this.worldAlpha=1,this.childrenToUpdate=Object.create(null),this.updateTick=0,this.gcTick=0,this.childrenRenderablesToUpdate={list:[],index:0},this.structureDidChange=!0,this.instructionSet=new Mr,this._onRenderContainers=[],this.textureNeedsUpdate=!0,this.isCachedAsTexture=!1,this._matrixDirty=7}init(e){this.root=e,e._onRender&&this.addOnRender(e),e.didChange=!0;const t=e.children;for(let i=0;i<t.length;i++){const s=t[i];s._updateFlags=15,this.addChild(s)}}enableCacheAsTexture(e={}){this.textureOptions=e,this.isCachedAsTexture=!0,this.textureNeedsUpdate=!0}disableCacheAsTexture(){this.isCachedAsTexture=!1,this.texture&&(Ds.returnTexture(this.texture,!0),this.texture=null)}updateCacheTexture(){this.textureNeedsUpdate=!0;const e=this._parentCacheAsTextureRenderGroup;e&&!e.textureNeedsUpdate&&e.updateCacheTexture()}reset(){this.renderGroupChildren.length=0;for(const e in this.childrenToUpdate){const t=this.childrenToUpdate[e];t.list.fill(null),t.index=0}this.childrenRenderablesToUpdate.index=0,this.childrenRenderablesToUpdate.list.fill(null),this.root=null,this.updateTick=0,this.structureDidChange=!0,this._onRenderContainers.length=0,this.renderGroupParent=null,this.disableCacheAsTexture()}get localTransform(){return this.root.localTransform}addRenderGroupChild(e){e.renderGroupParent&&e.renderGroupParent._removeRenderGroupChild(e),e.renderGroupParent=this,this.renderGroupChildren.push(e)}_removeRenderGroupChild(e){const t=this.renderGroupChildren.indexOf(e);t>-1&&this.renderGroupChildren.splice(t,1),e.renderGroupParent=null}addChild(e){if(this.structureDidChange=!0,e.parentRenderGroup=this,e.updateTick=-1,e.parent===this.root?e.relativeRenderGroupDepth=1:e.relativeRenderGroupDepth=e.parent.relativeRenderGroupDepth+1,e.didChange=!0,this.onChildUpdate(e),e.renderGroup){this.addRenderGroupChild(e.renderGroup);return}e._onRender&&this.addOnRender(e);const t=e.children;for(let i=0;i<t.length;i++)this.addChild(t[i])}removeChild(e){if(this.structureDidChange=!0,e._onRender&&(e.renderGroup||this.removeOnRender(e)),e.parentRenderGroup=null,e.renderGroup){this._removeRenderGroupChild(e.renderGroup);return}const t=e.children;for(let i=0;i<t.length;i++)this.removeChild(t[i])}removeChildren(e){for(let t=0;t<e.length;t++)this.removeChild(e[t])}onChildUpdate(e){let t=this.childrenToUpdate[e.relativeRenderGroupDepth];t||(t=this.childrenToUpdate[e.relativeRenderGroupDepth]={index:0,list:[]}),t.list[t.index++]=e}updateRenderable(e){e.globalDisplayStatus<7||(this.instructionSet.renderPipes[e.renderPipeId].updateRenderable(e),e.didViewUpdate=!1)}onChildViewUpdate(e){this.childrenRenderablesToUpdate.list[this.childrenRenderablesToUpdate.index++]=e}get isRenderable(){return this.root.localDisplayStatus===7&&this.worldAlpha>0}addOnRender(e){this._onRenderContainers.push(e)}removeOnRender(e){this._onRenderContainers.splice(this._onRenderContainers.indexOf(e),1)}runOnRender(e){for(let t=0;t<this._onRenderContainers.length;t++)this._onRenderContainers[t]._onRender(e)}destroy(){this.disableCacheAsTexture(),this.renderGroupParent=null,this.root=null,this.childrenRenderablesToUpdate=null,this.childrenToUpdate=null,this.renderGroupChildren=null,this._onRenderContainers=null,this.instructionSet=null}getChildren(e=[]){const t=this.root.children;for(let i=0;i<t.length;i++)this._getChildren(t[i],e);return e}_getChildren(e,t=[]){if(t.push(e),e.renderGroup)return t;const i=e.children;for(let s=0;s<i.length;s++)this._getChildren(i[s],t);return t}invalidateMatrices(){this._matrixDirty=7}get inverseWorldTransform(){return this._matrixDirty&1?(this._matrixDirty&=-2,this._inverseWorldTransform||(this._inverseWorldTransform=new H),this._inverseWorldTransform.copyFrom(this.worldTransform).invert()):this._inverseWorldTransform}get textureOffsetInverseTransform(){return this._matrixDirty&2?(this._matrixDirty&=-3,this._textureOffsetInverseTransform||(this._textureOffsetInverseTransform=new H),this._textureOffsetInverseTransform.copyFrom(this.inverseWorldTransform).translate(-this._textureBounds.x,-this._textureBounds.y)):this._textureOffsetInverseTransform}get inverseParentTextureTransform(){if(!(this._matrixDirty&4))return this._inverseParentTextureTransform;this._matrixDirty&=-5;const e=this._parentCacheAsTextureRenderGroup;return e?(this._inverseParentTextureTransform||(this._inverseParentTextureTransform=new H),this._inverseParentTextureTransform.copyFrom(this.worldTransform).prepend(e.inverseWorldTransform).translate(-e._textureBounds.x,-e._textureBounds.y)):this.worldTransform}get cacheToLocalTransform(){return this.isCachedAsTexture?this.textureOffsetInverseTransform:this._parentCacheAsTextureRenderGroup?this._parentCacheAsTextureRenderGroup.textureOffsetInverseTransform:null}}function yu(n,e,t={}){for(const i in e)!t[i]&&e[i]!==void 0&&(n[i]=e[i])}const rn=new ct(null),Ji=new ct(null),on=new ct(null,1,1),ts=new ct(null),Ro=1,xu=2,an=4;class L extends jt{constructor(e={}){var t,i;super(),this.uid=dt("renderable"),this._updateFlags=15,this.renderGroup=null,this.parentRenderGroup=null,this.parentRenderGroupIndex=0,this.didChange=!1,this.didViewUpdate=!1,this.relativeRenderGroupDepth=0,this.children=[],this.parent=null,this.includeInBuild=!0,this.measurable=!0,this.isSimple=!0,this.parentRenderLayer=null,this.updateTick=-1,this.localTransform=new H,this.relativeGroupTransform=new H,this.groupTransform=this.relativeGroupTransform,this.destroyed=!1,this._position=new ct(this,0,0),this._scale=on,this._pivot=Ji,this._origin=ts,this._skew=rn,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._rotation=0,this.localColor=16777215,this.localAlpha=1,this.groupAlpha=1,this.groupColor=16777215,this.groupColorAlpha=4294967295,this.localBlendMode="inherit",this.groupBlendMode="normal",this.localDisplayStatus=7,this.globalDisplayStatus=7,this._didContainerChangeTick=0,this._didViewChangeTick=0,this._didLocalTransformChangeId=-1,this.effects=[],yu(this,e,{children:!0,parent:!0,effects:!0}),(t=e.children)==null||t.forEach(s=>this.addChild(s)),(i=e.parent)==null||i.addChild(this)}static mixin(e){V("8.8.0","Container.mixin is deprecated, please use extensions.mixin instead."),K.mixin(L,e)}set _didChangeId(e){this._didViewChangeTick=e>>12&4095,this._didContainerChangeTick=e&4095}get _didChangeId(){return this._didContainerChangeTick&4095|(this._didViewChangeTick&4095)<<12}addChild(...e){if(this.allowChildren||V(Q,"addChild: Only Containers will be allowed to add children in v8.0.0"),e.length>1){for(let s=0;s<e.length;s++)this.addChild(e[s]);return e[0]}const t=e[0],i=this.renderGroup||this.parentRenderGroup;return t.parent===this?(this.children.splice(this.children.indexOf(t),1),this.children.push(t),i&&(i.structureDidChange=!0),t):(t.parent&&t.parent.removeChild(t),this.children.push(t),this.sortableChildren&&(this.sortDirty=!0),t.parent=this,t.didChange=!0,t._updateFlags=15,i&&i.addChild(t),this.emit("childAdded",t,this,this.children.length-1),t.emit("added",this),this._didViewChangeTick++,t._zIndex!==0&&t.depthOfChildModified(),t)}removeChild(...e){if(e.length>1){for(let s=0;s<e.length;s++)this.removeChild(e[s]);return e[0]}const t=e[0],i=this.children.indexOf(t);return i>-1&&(this._didViewChangeTick++,this.children.splice(i,1),this.renderGroup?this.renderGroup.removeChild(t):this.parentRenderGroup&&this.parentRenderGroup.removeChild(t),t.parentRenderLayer&&t.parentRenderLayer.detach(t),t.parent=null,this.emit("childRemoved",t,this,i),t.emit("removed",this)),t}_onUpdate(e){e&&e===this._skew&&this._updateSkew(),this._didContainerChangeTick++,!this.didChange&&(this.didChange=!0,this.parentRenderGroup&&this.parentRenderGroup.onChildUpdate(this))}set isRenderGroup(e){!!this.renderGroup!==e&&(e?this.enableRenderGroup():this.disableRenderGroup())}get isRenderGroup(){return!!this.renderGroup}enableRenderGroup(){if(this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),this.renderGroup=Rt.get(mu,this),this.groupTransform=H.IDENTITY,e==null||e.addChild(this),this._updateIsSimple()}disableRenderGroup(){if(!this.renderGroup)return;const e=this.parentRenderGroup;e==null||e.removeChild(this),Rt.return(this.renderGroup),this.renderGroup=null,this.groupTransform=this.relativeGroupTransform,e==null||e.addChild(this),this._updateIsSimple()}_updateIsSimple(){this.isSimple=!this.renderGroup&&this.effects.length===0}get worldTransform(){return this._worldTransform||(this._worldTransform=new H),this.renderGroup?this._worldTransform.copyFrom(this.renderGroup.worldTransform):this.parentRenderGroup&&this._worldTransform.appendFrom(this.relativeGroupTransform,this.parentRenderGroup.worldTransform),this._worldTransform}get x(){return this._position.x}set x(e){this._position.x=e}get y(){return this._position.y}set y(e){this._position.y=e}get position(){return this._position}set position(e){this._position.copyFrom(e)}get rotation(){return this._rotation}set rotation(e){this._rotation!==e&&(this._rotation=e,this._onUpdate(this._skew))}get angle(){return this.rotation*Ed}set angle(e){this.rotation=e*Dd}get pivot(){return this._pivot===Ji&&(this._pivot=new ct(this,0,0)),this._pivot}set pivot(e){this._pivot===Ji&&(this._pivot=new ct(this,0,0),this._origin!==ts&&nt("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._pivot.set(e):this._pivot.copyFrom(e)}get skew(){return this._skew===rn&&(this._skew=new ct(this,0,0)),this._skew}set skew(e){this._skew===rn&&(this._skew=new ct(this,0,0)),this._skew.copyFrom(e)}get scale(){return this._scale===on&&(this._scale=new ct(this,1,1)),this._scale}set scale(e){this._scale===on&&(this._scale=new ct(this,0,0)),typeof e=="string"&&(e=parseFloat(e)),typeof e=="number"?this._scale.set(e):this._scale.copyFrom(e)}get origin(){return this._origin===ts&&(this._origin=new ct(this,0,0)),this._origin}set origin(e){this._origin===ts&&(this._origin=new ct(this,0,0),this._pivot!==Ji&&nt("Setting both a pivot and origin on a Container is not recommended. This can lead to unexpected behavior if not handled carefully.")),typeof e=="number"?this._origin.set(e):this._origin.copyFrom(e)}get width(){return Math.abs(this.scale.x*this.getLocalBounds().width)}set width(e){const t=this.getLocalBounds().width;this._setWidth(e,t)}get height(){return Math.abs(this.scale.y*this.getLocalBounds().height)}set height(e){const t=this.getLocalBounds().height;this._setHeight(e,t)}getSize(e){e||(e={});const t=this.getLocalBounds();return e.width=Math.abs(this.scale.x*t.width),e.height=Math.abs(this.scale.y*t.height),e}setSize(e,t){const i=this.getLocalBounds();typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,i.width),t!==void 0&&this._setHeight(t,i.height)}_updateSkew(){const e=this._rotation,t=this._skew;this._cx=Math.cos(e+t._y),this._sx=Math.sin(e+t._y),this._cy=-Math.sin(e-t._x),this._sy=Math.cos(e-t._x)}updateTransform(e){return this.position.set(typeof e.x=="number"?e.x:this.position.x,typeof e.y=="number"?e.y:this.position.y),this.scale.set(typeof e.scaleX=="number"?e.scaleX||1:this.scale.x,typeof e.scaleY=="number"?e.scaleY||1:this.scale.y),this.rotation=typeof e.rotation=="number"?e.rotation:this.rotation,this.skew.set(typeof e.skewX=="number"?e.skewX:this.skew.x,typeof e.skewY=="number"?e.skewY:this.skew.y),this.pivot.set(typeof e.pivotX=="number"?e.pivotX:this.pivot.x,typeof e.pivotY=="number"?e.pivotY:this.pivot.y),this.origin.set(typeof e.originX=="number"?e.originX:this.origin.x,typeof e.originY=="number"?e.originY:this.origin.y),this}setFromMatrix(e){e.decompose(this)}updateLocalTransform(){const e=this._didContainerChangeTick;if(this._didLocalTransformChangeId===e)return;this._didLocalTransformChangeId=e;const t=this.localTransform,i=this._scale,s=this._pivot,r=this._origin,o=this._position,a=i._x,h=i._y,l=s._x,c=s._y,d=-r._x,u=-r._y;t.a=this._cx*a,t.b=this._sx*a,t.c=this._cy*h,t.d=this._sy*h,t.tx=o._x-(l*t.a+c*t.c)+(d*t.a+u*t.c)-d,t.ty=o._y-(l*t.b+c*t.d)+(d*t.b+u*t.d)-u}set alpha(e){e!==this.localAlpha&&(this.localAlpha=e,this._updateFlags|=Ro,this._onUpdate())}get alpha(){return this.localAlpha}set tint(e){const i=rt.shared.setValue(e??16777215).toBgrNumber();i!==this.localColor&&(this.localColor=i,this._updateFlags|=Ro,this._onUpdate())}get tint(){return Pi(this.localColor)}set blendMode(e){this.localBlendMode!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=xu,this.localBlendMode=e,this._onUpdate())}get blendMode(){return this.localBlendMode}get visible(){return!!(this.localDisplayStatus&2)}set visible(e){const t=e?2:0;(this.localDisplayStatus&2)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=an,this.localDisplayStatus^=2,this._onUpdate())}get culled(){return!(this.localDisplayStatus&4)}set culled(e){const t=e?0:4;(this.localDisplayStatus&4)!==t&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=an,this.localDisplayStatus^=4,this._onUpdate())}get renderable(){return!!(this.localDisplayStatus&1)}set renderable(e){const t=e?1:0;(this.localDisplayStatus&1)!==t&&(this._updateFlags|=an,this.localDisplayStatus^=1,this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._onUpdate())}get isRenderable(){return this.localDisplayStatus===7&&this.groupAlpha>0}destroy(e=!1){var s;if(this.destroyed)return;this.destroyed=!0;let t;if(this.children.length&&(t=this.removeChildren(0,this.children.length)),this.removeFromParent(),this.parent=null,this._maskEffect=null,this._filterEffect=null,this.effects=null,this._position=null,this._scale=null,this._pivot=null,this._origin=null,this._skew=null,this.emit("destroyed",this),this.removeAllListeners(),(typeof e=="boolean"?e:e==null?void 0:e.children)&&t)for(let r=0;r<t.length;++r)t[r].destroy(e);(s=this.renderGroup)==null||s.destroy(),this.renderGroup=null}}K.mixin(L,tu,ou,pu,cu,lu,su,nu,du,Zd,Qd,au,eu);class ai extends L{constructor(e){super(e),this.canBundle=!0,this.allowChildren=!1,this._roundPixels=0,this._lastUsed=-1,this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this._bounds=new Ft(0,1,0,0),this._boundsDirty=!0,this.autoGarbageCollect=e.autoGarbageCollect??!0}get bounds(){return this._boundsDirty?(this.updateBounds(),this._boundsDirty=!1,this._bounds):this._bounds}get roundPixels(){return!!this._roundPixels}set roundPixels(e){this._roundPixels=e?1:0}containsPoint(e){const t=this.bounds,{x:i,y:s}=e;return i>=t.minX&&i<=t.maxX&&s>=t.minY&&s<=t.maxY}onViewUpdate(){if(this._didViewChangeTick++,this._boundsDirty=!0,this.didViewUpdate)return;this.didViewUpdate=!0;const e=this.renderGroup||this.parentRenderGroup;e&&e.onChildViewUpdate(this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null),this.onViewUpdate()}destroy(e){this.unload(),super.destroy(e),this._bounds=null}collectRenderablesSimple(e,t,i){const{renderPipes:s}=t;s.blendMode.pushBlendMode(this,this.groupBlendMode,e);const o=s[this.renderPipeId];o!=null&&o.addRenderable&&o.addRenderable(this,e),this.didViewUpdate=!1;const a=this.children,h=a.length;for(let l=0;l<h;l++)a[l].collectRenderables(e,t,i);s.blendMode.popBlendMode(e)}}class Xt extends ai{constructor(e=G.EMPTY){e instanceof G&&(e={texture:e});const{texture:t=G.EMPTY,anchor:i,roundPixels:s,width:r,height:o,...a}=e;super({label:"Sprite",...a}),this.renderPipeId="sprite",this.batched=!0,this._visualBounds={minX:0,maxX:1,minY:0,maxY:0},this._anchor=new ct({_onUpdate:()=>{this.onViewUpdate()}}),i?this.anchor=i:t.defaultAnchor&&(this.anchor=t.defaultAnchor),this.texture=t,this.allowChildren=!1,this.roundPixels=s??!1,r!==void 0&&(this.width=r),o!==void 0&&(this.height=o)}static from(e,t=!1){return e instanceof G?new Xt(e):new Xt(G.from(e,t))}set texture(e){e||(e=G.EMPTY);const t=this._texture;t!==e&&(t&&t.dynamic&&t.off("update",this.onViewUpdate,this),e.dynamic&&e.on("update",this.onViewUpdate,this),this._texture=e,this._width&&this._setWidth(this._width,this._texture.orig.width),this._height&&this._setHeight(this._height,this._texture.orig.height),this.onViewUpdate())}get texture(){return this._texture}get visualBounds(){return Dh(this._visualBounds,this._anchor,this._texture),this._visualBounds}get sourceBounds(){return V("8.6.1","Sprite.sourceBounds is deprecated, use visualBounds instead."),this.visualBounds}updateBounds(){const e=this._anchor,t=this._texture,i=this._bounds,{width:s,height:r}=t.orig;i.minX=-e._x*s,i.maxX=i.minX+s,i.minY=-e._y*r,i.maxY=i.minY+r}destroy(e=!1){if(super.destroy(e),typeof e=="boolean"?e:e==null?void 0:e.texture){const i=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._texture.destroy(i)}this._texture=null,this._visualBounds=null,this._bounds=null,this._anchor=null}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(e){this._setWidth(e,this._texture.orig.width),this._width=e}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(e){this._setHeight(e,this._texture.orig.height),this._height=e}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this._texture.orig.width,e.height=Math.abs(this.scale.y)*this._texture.orig.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this._texture.orig.width),t!==void 0&&this._setHeight(t,this._texture.orig.height)}}const Su=new Ft;function Hh(n,e,t){const i=Su;n.measurable=!0,Lh(n,t,i),e.addBoundsMask(i),n.measurable=!1}function Vh(n,e,t){const i=ee.get();n.measurable=!0;const s=Pt.get().identity(),r=Nh(n,t,s);Wh(n,i,r),n.measurable=!1,e.addBoundsMask(i),Pt.return(s),ee.return(i)}function Nh(n,e,t){return n?(n!==e&&(Nh(n.parent,e,t),n.updateLocalTransform(),t.append(n.localTransform)),t):(nt("Mask bounds, renderable is not inside the root container"),t)}class $h{constructor(e){this.priority=0,this.inverse=!1,this.pipe="alphaMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.renderMaskToTexture=!(e instanceof Xt),this.mask.renderable=this.renderMaskToTexture,this.mask.includeInBuild=!this.renderMaskToTexture,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask=null)}addBounds(e,t){this.inverse||Hh(this.mask,e,t)}addLocalBounds(e,t){Vh(this.mask,e,t)}containsPoint(e,t){const i=this.mask;return t(i,e)}destroy(){this.reset()}static test(e){return e instanceof Xt}}$h.extension=I.MaskEffect;class Yh{constructor(e){this.priority=0,this.pipe="colorMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e}destroy(){}static test(e){return typeof e=="number"}}Yh.extension=I.MaskEffect;class Xh{constructor(e){this.priority=0,this.pipe="stencilMask",e!=null&&e.mask&&this.init(e.mask)}init(e){this.mask=e,this.mask.includeInBuild=!1,this.mask.measurable=!1}reset(){this.mask!==null&&(this.mask.measurable=!0,this.mask.includeInBuild=!0,this.mask=null)}addBounds(e,t){Hh(this.mask,e,t)}addLocalBounds(e,t){Vh(this.mask,e,t)}containsPoint(e,t){const i=this.mask;return t(i,e)}destroy(){this.reset()}static test(e){return e instanceof L}}Xh.extension=I.MaskEffect;const vu={createCanvas:(n,e)=>{const t=document.createElement("canvas");return t.width=n,t.height=e,t},createImage:()=>new Image,getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(n,e)=>fetch(n,e),parseXML:n=>new DOMParser().parseFromString(n,"text/xml")};let ko=vu;const $={get(){return ko},set(n){ko=n}};class Ar extends zt{constructor(e){e.resource||(e.resource=$.get().createCanvas()),e.width||(e.width=e.resource.width,e.autoDensity||(e.width/=e.resolution)),e.height||(e.height=e.resource.height,e.autoDensity||(e.height/=e.resolution)),super(e),this.uploadMethodId="image",this.autoDensity=e.autoDensity,this.resizeCanvas(),this.transparent=!!e.transparent}resizeCanvas(){this.autoDensity&&"style"in this.resource&&(this.resource.style.width=`${this.width}px`,this.resource.style.height=`${this.height}px`),(this.resource.width!==this.pixelWidth||this.resource.height!==this.pixelHeight)&&(this.resource.width=this.pixelWidth,this.resource.height=this.pixelHeight)}resize(e=this.width,t=this.height,i=this._resolution){const s=super.resize(e,t,i);return s&&this.resizeCanvas(),s}static test(e){return globalThis.HTMLCanvasElement&&e instanceof HTMLCanvasElement||globalThis.OffscreenCanvas&&e instanceof OffscreenCanvas}get context2D(){return this._context2D||(this._context2D=this.resource.getContext("2d"))}}Ar.extension=I.TextureSource;class ei extends zt{constructor(e){super(e),this.uploadMethodId="image",this.autoGarbageCollect=!0}static test(e){return globalThis.HTMLImageElement&&e instanceof HTMLImageElement||typeof ImageBitmap<"u"&&e instanceof ImageBitmap||globalThis.VideoFrame&&e instanceof VideoFrame}}ei.extension=I.TextureSource;var Fe=(n=>(n[n.INTERACTION=50]="INTERACTION",n[n.HIGH=25]="HIGH",n[n.NORMAL=0]="NORMAL",n[n.LOW=-25]="LOW",n[n.UTILITY=-50]="UTILITY",n))(Fe||{});class hn{constructor(e,t=null,i=0,s=!1){this.next=null,this.previous=null,this._destroyed=!1,this._fn=e,this._context=t,this.priority=i,this._once=s}match(e,t=null){return this._fn===e&&this._context===t}emit(e){this._fn&&(this._context?this._fn.call(this._context,e):this._fn(e));const t=this.next;return this._once&&this.destroy(!0),this._destroyed&&(this.next=null),t}connect(e){this.previous=e,e.next&&(e.next.previous=this),this.next=e.next,e.next=this}destroy(e=!1){this._destroyed=!0,this._fn=null,this._context=null,this.previous&&(this.previous.next=this.next),this.next&&(this.next.previous=this.previous);const t=this.next;return this.next=e?null:t,this.previous=null,t}}const jh=class kt{constructor(){this.autoStart=!1,this.deltaTime=1,this.lastTime=-1,this.speed=1,this.started=!1,this._requestId=null,this._maxElapsedMS=100,this._minElapsedMS=0,this._protected=!1,this._lastFrame=-1,this._head=new hn(null,null,1/0),this.deltaMS=1/kt.targetFPMS,this.elapsedMS=1/kt.targetFPMS,this._tick=e=>{this._requestId=null,this.started&&(this.update(e),this.started&&this._requestId===null&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){this._requestId===null&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){this._requestId!==null&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(e,t,i=Fe.NORMAL){return this._addListener(new hn(e,t,i))}addOnce(e,t,i=Fe.NORMAL){return this._addListener(new hn(e,t,i,!0))}_addListener(e){let t=this._head.next,i=this._head;if(!t)e.connect(i);else{for(;t;){if(e.priority>t.priority){e.connect(i);break}i=t,t=t.next}e.previous||e.connect(i)}return this._startIfPossible(),this}remove(e,t){let i=this._head.next;for(;i;)i.match(e,t)?i=i.destroy():i=i.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let e=0,t=this._head;for(;t=t.next;)e++;return e}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let e=this._head.next;for(;e;)e=e.destroy(!0);this._head.destroy(),this._head=null}}update(e=performance.now()){let t;if(e>this.lastTime){if(t=this.elapsedMS=e-this.lastTime,t>this._maxElapsedMS&&(t=this._maxElapsedMS),t*=this.speed,this._minElapsedMS){const r=e-this._lastFrame|0;if(r<this._minElapsedMS)return;this._lastFrame=e-r%this._minElapsedMS}this.deltaMS=t,this.deltaTime=this.deltaMS*kt.targetFPMS;const i=this._head;let s=i.next;for(;s;)s=s.emit(this);i.next||this._cancelIfNeeded()}else this.deltaTime=this.deltaMS=this.elapsedMS=0;this.lastTime=e}get FPS(){return 1e3/this.elapsedMS}get minFPS(){return 1e3/this._maxElapsedMS}set minFPS(e){const t=Math.min(this.maxFPS,e),i=Math.min(Math.max(0,t)/1e3,kt.targetFPMS);this._maxElapsedMS=1/i}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(e){if(e===0)this._minElapsedMS=0;else{const t=Math.max(this.minFPS,e);this._minElapsedMS=1/(t/1e3)}}static get shared(){if(!kt._shared){const e=kt._shared=new kt;e.autoStart=!0,e._protected=!0}return kt._shared}static get system(){if(!kt._system){const e=kt._system=new kt;e.autoStart=!0,e._protected=!0}return kt._system}};jh.targetFPMS=.06;let yt=jh,ln;async function Zh(){return ln??(ln=(async()=>{var o;const e=$.get().createCanvas(1,1).getContext("webgl");if(!e)return"premultiply-alpha-on-upload";const t=await new Promise(a=>{const h=document.createElement("video");h.onloadeddata=()=>a(h),h.onerror=()=>a(null),h.autoplay=!1,h.crossOrigin="anonymous",h.preload="auto",h.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",h.load()});if(!t)return"premultiply-alpha-on-upload";const i=e.createTexture();e.bindTexture(e.TEXTURE_2D,i);const s=e.createFramebuffer();e.bindFramebuffer(e.FRAMEBUFFER,s),e.framebufferTexture2D(e.FRAMEBUFFER,e.COLOR_ATTACHMENT0,e.TEXTURE_2D,i,0),e.pixelStorei(e.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),e.pixelStorei(e.UNPACK_COLORSPACE_CONVERSION_WEBGL,e.NONE),e.texImage2D(e.TEXTURE_2D,0,e.RGBA,e.RGBA,e.UNSIGNED_BYTE,t);const r=new Uint8Array(4);return e.readPixels(0,0,1,1,e.RGBA,e.UNSIGNED_BYTE,r),e.deleteFramebuffer(s),e.deleteTexture(i),(o=e.getExtension("WEBGL_lose_context"))==null||o.loseContext(),r[0]<=r[3]?"premultiplied-alpha":"premultiply-alpha-on-upload"})()),ln}const Fs=class qh extends zt{constructor(e){super(e),this.isReady=!1,this.uploadMethodId="video",e={...qh.defaultOptions,...e},this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=e.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=e.autoPlay!==!1,this.alphaMode=e.alphaMode??"premultiply-alpha-on-upload",this._videoFrameRequestCallback=this._videoFrameRequestCallback.bind(this),this._videoFrameRequestCallbackHandle=null,this._load=null,this._resolve=null,this._reject=null,this._onCanPlay=this._onCanPlay.bind(this),this._onCanPlayThrough=this._onCanPlayThrough.bind(this),this._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),e.autoLoad!==!1&&this.load()}updateFrame(){if(!this.destroyed){if(this._updateFPS){const e=yt.shared.elapsedMS*this.resource.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-e)}(!this._updateFPS||this._msToNextUpdate<=0)&&(this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0),this.isValid&&this.update()}}_videoFrameRequestCallback(){this.updateFrame(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback)}get isValid(){return!!this.resource.videoWidth&&!!this.resource.videoHeight}async load(){if(this._load)return this._load;const e=this.resource,t=this.options;return(e.readyState===e.HAVE_ENOUGH_DATA||e.readyState===e.HAVE_FUTURE_DATA)&&e.width&&e.height&&(e.complete=!0),e.addEventListener("play",this._onPlayStart),e.addEventListener("pause",this._onPlayStop),e.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._mediaReady():(t.preload||e.addEventListener("canplay",this._onCanPlay),e.addEventListener("canplaythrough",this._onCanPlayThrough),e.addEventListener("error",this._onError,!0)),this.alphaMode=await Zh(),this._load=new Promise((i,s)=>{this.isValid?i(this):(this._resolve=i,this._reject=s,t.preloadTimeoutMs!==void 0&&(this._preloadTimeout=setTimeout(()=>{this._onError(new ErrorEvent(`Preload exceeded timeout of ${t.preloadTimeoutMs}ms`))})),e.load())}),this._load}_onError(e){this.resource.removeEventListener("error",this._onError,!0),this.emit("error",e),this._reject&&(this._reject(e),this._reject=null,this._resolve=null)}_isSourcePlaying(){const e=this.resource;return!e.paused&&!e.ended}_isSourceReady(){return this.resource.readyState>2}_onPlayStart(){this.isValid||this._mediaReady(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0)}_onCanPlay(){this.resource.removeEventListener("canplay",this._onCanPlay),this._mediaReady()}_onCanPlayThrough(){this.resource.removeEventListener("canplaythrough",this._onCanPlay),this._preloadTimeout&&(clearTimeout(this._preloadTimeout),this._preloadTimeout=void 0),this._mediaReady()}_mediaReady(){const e=this.resource;this.isValid&&(this.isReady=!0,this.resize(e.videoWidth,e.videoHeight)),this._msToNextUpdate=0,this.updateFrame(),this._msToNextUpdate=0,this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&this.resource.play()}destroy(){this._configureAutoUpdate();const e=this.resource;e&&(e.removeEventListener("play",this._onPlayStart),e.removeEventListener("pause",this._onPlayStop),e.removeEventListener("seeked",this._onSeeked),e.removeEventListener("canplay",this._onCanPlay),e.removeEventListener("canplaythrough",this._onCanPlayThrough),e.removeEventListener("error",this._onError,!0),e.pause(),e.src="",e.load()),super.destroy()}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){e!==this._autoUpdate&&(this._autoUpdate=e,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(e){e!==this._updateFPS&&(this._updateFPS=e,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.resource.requestVideoFrameCallback?(this._isConnectedToTicker&&(yt.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),this._videoFrameRequestCallbackHandle===null&&(this._videoFrameRequestCallbackHandle=this.resource.requestVideoFrameCallback(this._videoFrameRequestCallback))):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(yt.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(yt.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement}};Fs.extension=I.TextureSource;Fs.defaultOptions={...zt.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1};Fs.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Mi=Fs;const Ot=(n,e,t=!1)=>(Array.isArray(n)||(n=[n]),e?n.map(i=>typeof i=="string"||t?e(i):i):n);class bu{constructor(){this._parsers=[],this._cache=new Map,this._cacheMap=new Map}reset(){this._cacheMap.clear(),this._cache.clear()}has(e){return this._cache.has(e)}get(e){const t=this._cache.get(e);return t||nt(`[Assets] Asset id ${e} was not found in the Cache`),t}set(e,t){const i=Ot(e);let s;for(let h=0;h<this.parsers.length;h++){const l=this.parsers[h];if(l.test(t)){s=l.getCacheableAssets(i,t);break}}const r=new Map(Object.entries(s||{}));s||i.forEach(h=>{r.set(h,t)});const o=[...r.keys()],a={cacheKeys:o,keys:i};i.forEach(h=>{this._cacheMap.set(h,a)}),o.forEach(h=>{const l=s?s[h]:t;this._cache.has(h)&&this._cache.get(h)!==l&&nt("[Cache] already has key:",h),this._cache.set(h,r.get(h))})}remove(e){if(!this._cacheMap.has(e)){nt(`[Assets] Asset id ${e} was not found in the Cache`);return}const t=this._cacheMap.get(e);t.cacheKeys.forEach(s=>{this._cache.delete(s)}),t.keys.forEach(s=>{this._cacheMap.delete(s)})}get parsers(){return this._parsers}}const xt=new bu,Zn=[];K.handleByList(I.TextureSource,Zn);function Kh(n={}){const e=n&&n.resource,t=e?n.resource:n,i=e?n:{resource:n};for(let s=0;s<Zn.length;s++){const r=Zn[s];if(r.test(t))return new r(i)}throw new Error(`Could not find a source type for resource: ${i.resource}`)}function wu(n={},e=!1){const t=n&&n.resource,i=t?n.resource:n,s=t?n:{resource:n};if(!e&&xt.has(i))return xt.get(i);const r=new G({source:Kh(s)});return r.on("destroy",()=>{xt.has(i)&&xt.remove(i)}),e||xt.set(i,r),r}function Cu(n,e=!1){return typeof n=="string"?xt.get(n):n instanceof zt?new G({source:n}):wu(n,e)}G.from=Cu;zt.from=Kh;K.add($h,Yh,Xh,Mi,ei,Ar,Cr);var pe=(n=>(n[n.Low=0]="Low",n[n.Normal=1]="Normal",n[n.High=2]="High",n))(pe||{});function Lt(n){if(typeof n!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(n)}`)}function di(n){return n.split("?")[0].split("#")[0]}function _u(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Pu(n,e,t){return n.replace(new RegExp(_u(e),"g"),t)}function Mu(n,e){let t="",i=0,s=-1,r=0,o=-1;for(let a=0;a<=n.length;++a){if(a<n.length)o=n.charCodeAt(a);else{if(o===47)break;o=47}if(o===47){if(!(s===a-1||r===1))if(s!==a-1&&r===2){if(t.length<2||i!==2||t.charCodeAt(t.length-1)!==46||t.charCodeAt(t.length-2)!==46){if(t.length>2){const h=t.lastIndexOf("/");if(h!==t.length-1){h===-1?(t="",i=0):(t=t.slice(0,h),i=t.length-1-t.lastIndexOf("/")),s=a,r=0;continue}}else if(t.length===2||t.length===1){t="",i=0,s=a,r=0;continue}}}else t.length>0?t+=`/${n.slice(s+1,a)}`:t=n.slice(s+1,a),i=a-s-1;s=a,r=0}else o===46&&r!==-1?++r:r=-1}return t}const Mt={toPosix(n){return Pu(n,"\\","/")},isUrl(n){return/^https?:/.test(this.toPosix(n))},isDataUrl(n){return/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(n)},isBlobUrl(n){return n.startsWith("blob:")},hasProtocol(n){return/^[^/:]+:/.test(this.toPosix(n))},getProtocol(n){Lt(n),n=this.toPosix(n);const e=/^file:\/\/\//.exec(n);if(e)return e[0];const t=/^[^/:]+:\/{0,2}/.exec(n);return t?t[0]:""},toAbsolute(n,e,t){if(Lt(n),this.isDataUrl(n)||this.isBlobUrl(n))return n;const i=di(this.toPosix(e??$.get().getBaseUrl())),s=di(this.toPosix(t??this.rootname(i)));return n=this.toPosix(n),n.startsWith("/")?Mt.join(s,n.slice(1)):this.isAbsolute(n)?n:this.join(i,n)},normalize(n){if(Lt(n),n.length===0)return".";if(this.isDataUrl(n)||this.isBlobUrl(n))return n;n=this.toPosix(n);let e="";const t=n.startsWith("/");this.hasProtocol(n)&&(e=this.rootname(n),n=n.slice(e.length));const i=n.endsWith("/");return n=Mu(n),n.length>0&&i&&(n+="/"),t?`/${n}`:e+n},isAbsolute(n){return Lt(n),n=this.toPosix(n),this.hasProtocol(n)?!0:n.startsWith("/")},join(...n){if(n.length===0)return".";let e;for(let t=0;t<n.length;++t){const i=n[t];if(Lt(i),i.length>0)if(e===void 0)e=i;else{const s=n[t-1]??"";this.joinExtensions.includes(this.extname(s).toLowerCase())?e+=`/../${i}`:e+=`/${i}`}}return e===void 0?".":this.normalize(e)},dirname(n){if(Lt(n),n.length===0)return".";n=this.toPosix(n);let e=n.charCodeAt(0);const t=e===47;let i=-1,s=!0;const r=this.getProtocol(n),o=n;n=n.slice(r.length);for(let a=n.length-1;a>=1;--a)if(e=n.charCodeAt(a),e===47){if(!s){i=a;break}}else s=!1;return i===-1?t?"/":this.isUrl(o)?r+n:r:t&&i===1?"//":r+n.slice(0,i)},rootname(n){Lt(n),n=this.toPosix(n);let e="";if(n.startsWith("/")?e="/":e=this.getProtocol(n),this.isUrl(n)){const t=n.indexOf("/",e.length);t!==-1?e=n.slice(0,t):e=n,e.endsWith("/")||(e+="/")}return e},basename(n,e){Lt(n),e&&Lt(e),n=di(this.toPosix(n));let t=0,i=-1,s=!0,r;if(e!==void 0&&e.length>0&&e.length<=n.length){if(e.length===n.length&&e===n)return"";let o=e.length-1,a=-1;for(r=n.length-1;r>=0;--r){const h=n.charCodeAt(r);if(h===47){if(!s){t=r+1;break}}else a===-1&&(s=!1,a=r+1),o>=0&&(h===e.charCodeAt(o)?--o===-1&&(i=r):(o=-1,i=a))}return t===i?i=a:i===-1&&(i=n.length),n.slice(t,i)}for(r=n.length-1;r>=0;--r)if(n.charCodeAt(r)===47){if(!s){t=r+1;break}}else i===-1&&(s=!1,i=r+1);return i===-1?"":n.slice(t,i)},extname(n){Lt(n),n=di(this.toPosix(n));let e=-1,t=0,i=-1,s=!0,r=0;for(let o=n.length-1;o>=0;--o){const a=n.charCodeAt(o);if(a===47){if(!s){t=o+1;break}continue}i===-1&&(s=!1,i=o+1),a===46?e===-1?e=o:r!==1&&(r=1):e!==-1&&(r=-1)}return e===-1||i===-1||r===0||r===1&&e===i-1&&e===t+1?"":n.slice(e,i)},parse(n){Lt(n);const e={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return e;n=di(this.toPosix(n));let t=n.charCodeAt(0);const i=this.isAbsolute(n);let s;e.root=this.rootname(n),i||this.hasProtocol(n)?s=1:s=0;let r=-1,o=0,a=-1,h=!0,l=n.length-1,c=0;for(;l>=s;--l){if(t=n.charCodeAt(l),t===47){if(!h){o=l+1;break}continue}a===-1&&(h=!1,a=l+1),t===46?r===-1?r=l:c!==1&&(c=1):r!==-1&&(c=-1)}return r===-1||a===-1||c===0||c===1&&r===a-1&&r===o+1?a!==-1&&(o===0&&i?e.base=e.name=n.slice(1,a):e.base=e.name=n.slice(o,a)):(o===0&&i?(e.name=n.slice(1,r),e.base=n.slice(1,a)):(e.name=n.slice(o,r),e.base=n.slice(o,a)),e.ext=n.slice(r,a)),e.dir=this.dirname(n),e},sep:"/",delimiter:":",joinExtensions:[".html"]};function Qh(n,e,t,i,s){const r=e[t];for(let o=0;o<r.length;o++){const a=r[o];t<e.length-1?Qh(n.replace(i[t],a),e,t+1,i,s):s.push(n.replace(i[t],a))}}function Au(n){const e=/\{(.*?)\}/g,t=n.match(e),i=[];if(t){const s=[];t.forEach(r=>{const o=r.substring(1,r.length-1).split(",");s.push(o)}),Qh(n,s,0,t,i)}else i.push(n);return i}const ws=n=>!Array.isArray(n);class hi{constructor(){this._defaultBundleIdentifierOptions={connector:"-",createBundleAssetId:(e,t)=>`${e}${this._bundleIdConnector}${t}`,extractAssetIdFromBundle:(e,t)=>t.replace(`${e}${this._bundleIdConnector}`,"")},this._bundleIdConnector=this._defaultBundleIdentifierOptions.connector,this._createBundleAssetId=this._defaultBundleIdentifierOptions.createBundleAssetId,this._extractAssetIdFromBundle=this._defaultBundleIdentifierOptions.extractAssetIdFromBundle,this._assetMap={},this._preferredOrder=[],this._parsers=[],this._resolverHash={},this._bundles={}}setBundleIdentifier(e){if(this._bundleIdConnector=e.connector??this._bundleIdConnector,this._createBundleAssetId=e.createBundleAssetId??this._createBundleAssetId,this._extractAssetIdFromBundle=e.extractAssetIdFromBundle??this._extractAssetIdFromBundle,this._extractAssetIdFromBundle("foo",this._createBundleAssetId("foo","bar"))!=="bar")throw new Error("[Resolver] GenerateBundleAssetId are not working correctly")}prefer(...e){e.forEach(t=>{this._preferredOrder.push(t),t.priority||(t.priority=Object.keys(t.params))}),this._resolverHash={}}set basePath(e){this._basePath=e}get basePath(){return this._basePath}set rootPath(e){this._rootPath=e}get rootPath(){return this._rootPath}get parsers(){return this._parsers}reset(){this.setBundleIdentifier(this._defaultBundleIdentifierOptions),this._assetMap={},this._preferredOrder=[],this._resolverHash={},this._rootPath=null,this._basePath=null,this._manifest=null,this._bundles={},this._defaultSearchParams=null}setDefaultSearchParams(e){if(typeof e=="string")this._defaultSearchParams=e;else{const t=e;this._defaultSearchParams=Object.keys(t).map(i=>`${encodeURIComponent(i)}=${encodeURIComponent(t[i])}`).join("&")}}getAlias(e){const{alias:t,src:i}=e;return Ot(t||i,r=>typeof r=="string"?r:Array.isArray(r)?r.map(o=>(o==null?void 0:o.src)??o):r!=null&&r.src?r.src:r,!0)}addManifest(e){this._manifest&&nt("[Resolver] Manifest already exists, this will be overwritten"),this._manifest=e,e.bundles.forEach(t=>{this.addBundle(t.name,t.assets)})}addBundle(e,t){const i=[];let s=t;Array.isArray(t)||(s=Object.entries(t).map(([r,o])=>typeof o=="string"||Array.isArray(o)?{alias:r,src:o}:{alias:r,...o})),s.forEach(r=>{const o=r.src,a=r.alias;let h;if(typeof a=="string"){const l=this._createBundleAssetId(e,a);i.push(l),h=[a,l]}else{const l=a.map(c=>this._createBundleAssetId(e,c));i.push(...l),h=[...a,...l]}this.add({...r,alias:h,src:o})}),this._bundles[e]=i}add(e){const t=[];Array.isArray(e)?t.push(...e):t.push(e);let i;i=r=>{this.hasKey(r)&&nt(`[Resolver] already has key: ${r} overwriting`)},Ot(t).forEach(r=>{const{src:o}=r;let{data:a,format:h,loadParser:l,parser:c}=r;const d=Ot(o).map(m=>typeof m=="string"?Au(m):Array.isArray(m)?m:[m]),u=this.getAlias(r);Array.isArray(u)?u.forEach(i):i(u);const p=[],g=m=>{const y=this._parsers.find(x=>x.test(m));return{src:m,...y==null?void 0:y.parse(m)}};d.forEach(m=>{m.forEach(y=>{let x={};if(typeof y!="object"?x=g(y):(a=y.data??a,h=y.format??h,(y.loadParser||y.parser)&&(l=y.loadParser??l,c=y.parser??c),x={...g(y.src),...y}),!u)throw new Error(`[Resolver] alias is undefined for this asset: ${x.src}`);x=this._buildResolvedAsset(x,{aliases:u,data:a,format:h,loadParser:l,parser:c,progressSize:r.progressSize}),p.push(x)})}),u.forEach(m=>{this._assetMap[m]=p})})}resolveBundle(e){const t=ws(e);e=Ot(e);const i={};return e.forEach(s=>{const r=this._bundles[s];if(r){const o=this.resolve(r),a={};for(const h in o){const l=o[h];a[this._extractAssetIdFromBundle(s,h)]=l}i[s]=a}}),t?i[e[0]]:i}resolveUrl(e){const t=this.resolve(e);if(typeof e!="string"){const i={};for(const s in t)i[s]=t[s].src;return i}return t.src}resolve(e){const t=ws(e);e=Ot(e);const i={};return e.forEach(s=>{if(!this._resolverHash[s])if(this._assetMap[s]){let r=this._assetMap[s];const o=this._getPreferredOrder(r);o==null||o.priority.forEach(a=>{o.params[a].forEach(h=>{const l=r.filter(c=>c[a]?c[a]===h:!1);l.length&&(r=l)})}),this._resolverHash[s]=r[0]}else this._resolverHash[s]=this._buildResolvedAsset({alias:[s],src:s},{});i[s]=this._resolverHash[s]}),t?i[e[0]]:i}hasKey(e){return!!this._assetMap[e]}hasBundle(e){return!!this._bundles[e]}_getPreferredOrder(e){for(let t=0;t<e.length;t++){const i=e[t],s=this._preferredOrder.find(r=>r.params.format.includes(i.format));if(s)return s}return this._preferredOrder[0]}_appendDefaultSearchParams(e){if(!this._defaultSearchParams)return e;const t=/\?/.test(e)?"&":"?";return`${e}${t}${this._defaultSearchParams}`}_buildResolvedAsset(e,t){const{aliases:i,data:s,loadParser:r,parser:o,format:a,progressSize:h}=t;return(this._basePath||this._rootPath)&&(e.src=Mt.toAbsolute(e.src,this._basePath,this._rootPath)),e.alias=i??e.alias??[e.src],e.src=this._appendDefaultSearchParams(e.src),e.data={...s||{},...e.data},e.loadParser=r??e.loadParser,e.parser=o??e.parser,e.format=a??e.format??Tu(e.src),h!==void 0&&(e.progressSize=h),e}}hi.RETINA_PREFIX=/@([0-9\.]+)x/;function Tu(n){return n.split(".").pop().split("?").shift().split("#").shift()}const qn=(n,e)=>{const t=e.split("?")[1];return t&&(n+=`?${t}`),n},Jh=class bi{constructor(e,t){this.linkedSheets=[];let i=e;(e==null?void 0:e.source)instanceof zt&&(i={texture:e,data:t});const{texture:s,data:r,cachePrefix:o=""}=i;this.cachePrefix=o,this._texture=s instanceof G?s:null,this.textureSource=s.source,this.textures={},this.animations={},this.data=r;const a=parseFloat(r.meta.scale);a?(this.resolution=a,s.source.resolution=this.resolution):this.resolution=s.source._resolution,this._frames=this.data.frames,this._frameKeys=Object.keys(this._frames),this._batchIndex=0,this._callback=null}parse(){return new Promise(e=>{this._callback=e,this._batchIndex=0,this._frameKeys.length<=bi.BATCH_SIZE?(this._processFrames(0),this._processAnimations(),this._parseComplete()):this._nextBatch()})}parseSync(){return this._processFrames(0,!0),this._processAnimations(),this.textures}_processFrames(e,t=!1){let i=e;const s=t?1/0:bi.BATCH_SIZE;for(;i-e<s&&i<this._frameKeys.length;){const r=this._frameKeys[i],o=this._frames[r],a=o.frame;if(a){let h=null,l=null;const c=o.trimmed!==!1&&o.sourceSize?o.sourceSize:o.frame,d=new tt(0,0,Math.floor(c.w)/this.resolution,Math.floor(c.h)/this.resolution);o.rotated?h=new tt(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.h)/this.resolution,Math.floor(a.w)/this.resolution):h=new tt(Math.floor(a.x)/this.resolution,Math.floor(a.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution),o.trimmed!==!1&&o.spriteSourceSize&&(l=new tt(Math.floor(o.spriteSourceSize.x)/this.resolution,Math.floor(o.spriteSourceSize.y)/this.resolution,Math.floor(a.w)/this.resolution,Math.floor(a.h)/this.resolution)),this.textures[r]=new G({source:this.textureSource,frame:h,orig:d,trim:l,rotate:o.rotated?2:0,defaultAnchor:o.anchor,defaultBorders:o.borders,label:r.toString()})}i++}}_processAnimations(){const e=this.data.animations||{};for(const t in e){this.animations[t]=[];for(let i=0;i<e[t].length;i++){const s=e[t][i];this.animations[t].push(this.textures[s])}}}_parseComplete(){const e=this._callback;this._callback=null,this._batchIndex=0,e.call(this,this.textures)}_nextBatch(){this._processFrames(this._batchIndex*bi.BATCH_SIZE),this._batchIndex++,setTimeout(()=>{this._batchIndex*bi.BATCH_SIZE<this._frameKeys.length?this._nextBatch():(this._processAnimations(),this._parseComplete())},0)}destroy(e=!1){var t;for(const i in this.textures)this.textures[i].destroy();this._frames=null,this._frameKeys=null,this.data=null,this.textures=null,e&&((t=this._texture)==null||t.destroy(),this.textureSource.destroy()),this._texture=null,this.textureSource=null,this.linkedSheets=[]}};Jh.BATCH_SIZE=1e3;let Kn=Jh;const Ru=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function tl(n,e,t){const i={};if(n.forEach(s=>{i[s]=e}),Object.keys(e.textures).forEach(s=>{i[`${e.cachePrefix}${s}`]=e.textures[s]}),!t){const s=Mt.dirname(n[0]);e.linkedSheets.forEach((r,o)=>{const a=tl([`${s}/${e.data.meta.related_multi_packs[o]}`],r,!0);Object.assign(i,a)})}return i}const ku={extension:I.Asset,cache:{test:n=>n instanceof Kn,getCacheableAssets:(n,e)=>tl(n,e,!1)},resolver:{extension:{type:I.ResolveParser,name:"resolveSpritesheet"},test:n=>{const t=n.split("?")[0].split("."),i=t.pop(),s=t.pop();return i==="json"&&Ru.includes(s)},parse:n=>{var t;const e=n.split(".");return{resolution:parseFloat(((t=hi.RETINA_PREFIX.exec(n))==null?void 0:t[1])??"1"),format:e[e.length-2],src:n}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:I.LoadParser,priority:pe.Normal,name:"spritesheetLoader"},async testParse(n,e){return Mt.extname(e.src).toLowerCase()===".json"&&!!n.frames},async parse(n,e,t){var d,u;const{texture:i,imageFilename:s,textureOptions:r,cachePrefix:o}=(e==null?void 0:e.data)??{};let a=Mt.dirname(e.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let h;if(i instanceof G)h=i;else{const p=qn(a+(s??n.meta.image),e.src);h=(await t.load([{src:p,data:r}]))[p]}const l=new Kn({texture:h.source,data:n,cachePrefix:o});await l.parse();const c=(d=n==null?void 0:n.meta)==null?void 0:d.related_multi_packs;if(Array.isArray(c)){const p=[];for(const m of c){if(typeof m!="string")continue;let y=a+m;(u=e.data)!=null&&u.ignoreMultiPack||(y=qn(y,e.src),p.push(t.load({src:y,data:{textureOptions:r,ignoreMultiPack:!0}})))}const g=await Promise.all(p);l.linkedSheets=g,g.forEach(m=>{m.linkedSheets=[l].concat(l.linkedSheets.filter(y=>y!==m))})}return l},async unload(n,e,t){await t.unload(n.textureSource._sourceOrigin),n.destroy(!1)}}};K.add(ku);class Iu{constructor(e){this._lastTransform="",this._observer=null,this._tickerAttached=!1,this.updateTranslation=()=>{if(!this._canvas)return;const t=this._canvas.getBoundingClientRect(),i=this._canvas.width,s=this._canvas.height,r=t.width/i*this._renderer.resolution,o=t.height/s*this._renderer.resolution,a=t.left,h=t.top,l=`translate(${a}px, ${h}px) scale(${r}, ${o})`;l!==this._lastTransform&&(this._domElement.style.transform=l,this._lastTransform=l)},this._domElement=e.domElement,this._renderer=e.renderer,!(globalThis.OffscreenCanvas&&this._renderer.canvas instanceof OffscreenCanvas)&&(this._canvas=this._renderer.canvas,this._attachObserver())}get canvas(){return this._canvas}ensureAttached(){!this._domElement.parentNode&&this._canvas.parentNode&&(this._canvas.parentNode.appendChild(this._domElement),this.updateTranslation())}_attachObserver(){"ResizeObserver"in globalThis?(this._observer&&(this._observer.disconnect(),this._observer=null),this._observer=new ResizeObserver(e=>{for(const t of e){if(t.target!==this._canvas)continue;const i=this.canvas.width,s=this.canvas.height,r=t.contentRect.width/i*this._renderer.resolution,o=t.contentRect.height/s*this._renderer.resolution;(this._lastScaleX!==r||this._lastScaleY!==o)&&(this.updateTranslation(),this._lastScaleX=r,this._lastScaleY=o)}}),this._observer.observe(this._canvas)):this._tickerAttached||yt.shared.add(this.updateTranslation,this,Fe.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&yt.shared.remove(this.updateTranslation),this._domElement=null,this._renderer=null,this._canvas=null,this._tickerAttached=!1,this._lastTransform="",this._lastScaleX=null,this._lastScaleY=null}}class Tr{constructor(e){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=Tr.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new J,this.page=new J,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=e}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(e,t,i){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(e,t,i,s,r){throw new Error("initUIEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}preventDefault(){this.nativeEvent instanceof Event&&this.nativeEvent.cancelable&&this.nativeEvent.preventDefault(),this.defaultPrevented=!0}stopImmediatePropagation(){this.propagationImmediatelyStopped=!0}stopPropagation(){this.propagationStopped=!0}}var cn=/iPhone/i,Io=/iPod/i,Eo=/iPad/i,Do=/\biOS-universal(?:.+)Mac\b/i,dn=/\bAndroid(?:.+)Mobile\b/i,Fo=/Android/i,We=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,es=/Silk/i,Kt=/Windows Phone/i,Bo=/\bWindows(?:.+)ARM\b/i,zo=/BlackBerry/i,Lo=/BB10/i,Oo=/Opera Mini/i,Wo=/\b(CriOS|Chrome)(?:.+)Mobile/i,Go=/Mobile(?:.+)Firefox\b/i,Uo=function(n){return typeof n<"u"&&n.platform==="MacIntel"&&typeof n.maxTouchPoints=="number"&&n.maxTouchPoints>1&&typeof MSStream>"u"};function Eu(n){return function(e){return e.test(n)}}function Ho(n){var e={userAgent:"",platform:"",maxTouchPoints:0};!n&&typeof navigator<"u"?e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0}:typeof n=="string"?e.userAgent=n:n&&n.userAgent&&(e={userAgent:n.userAgent,platform:n.platform,maxTouchPoints:n.maxTouchPoints||0});var t=e.userAgent,i=t.split("[FBAN");typeof i[1]<"u"&&(t=i[0]),i=t.split("Twitter"),typeof i[1]<"u"&&(t=i[0]);var s=Eu(t),r={apple:{phone:s(cn)&&!s(Kt),ipod:s(Io),tablet:!s(cn)&&(s(Eo)||Uo(e))&&!s(Kt),universal:s(Do),device:(s(cn)||s(Io)||s(Eo)||s(Do)||Uo(e))&&!s(Kt)},amazon:{phone:s(We),tablet:!s(We)&&s(es),device:s(We)||s(es)},android:{phone:!s(Kt)&&s(We)||!s(Kt)&&s(dn),tablet:!s(Kt)&&!s(We)&&!s(dn)&&(s(es)||s(Fo)),device:!s(Kt)&&(s(We)||s(es)||s(dn)||s(Fo))||s(/\bokhttp\b/i)},windows:{phone:s(Kt),tablet:s(Bo),device:s(Kt)||s(Bo)},other:{blackberry:s(zo),blackberry10:s(Lo),opera:s(Oo),firefox:s(Go),chrome:s(Wo),device:s(zo)||s(Lo)||s(Oo)||s(Go)||s(Wo)},any:!1,phone:!1,tablet:!1};return r.any=r.apple.device||r.android.device||r.windows.device||r.other.device,r.phone=r.apple.phone||r.android.phone||r.windows.phone,r.tablet=r.apple.tablet||r.android.tablet||r.windows.tablet,r}const Du=Ho.default??Ho,Fu=Du(globalThis.navigator),un=Object.create(null),Vo=Object.create(null);function Rr(n,e){let t=Vo[n];return t===void 0&&(un[e]===void 0&&(un[e]=1),Vo[n]=t=un[e]++),t}let Ge;function el(){return(!Ge||Ge!=null&&Ge.isContextLost())&&(Ge=$.get().createCanvas().getContext("webgl",{})),Ge}let is;function Bu(){if(!is){is="mediump";const n=el();n&&n.getShaderPrecisionFormat&&(is=n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision?"highp":"mediump")}return is}function zu(n,e,t){return e?n:t?(n=n.replace("out vec4 finalColor;",""),`
6
+
7
+ #ifdef GL_ES // This checks if it is WebGL1
8
+ #define in varying
9
+ #define finalColor gl_FragColor
10
+ #define texture texture2D
11
+ #endif
12
+ ${n}
13
+ `):`
14
+
15
+ #ifdef GL_ES // This checks if it is WebGL1
16
+ #define in attribute
17
+ #define out varying
18
+ #endif
19
+ ${n}
20
+ `}function Lu(n,e,t){const i=t?e.maxSupportedFragmentPrecision:e.maxSupportedVertexPrecision;if(n.substring(0,9)!=="precision"){let s=t?e.requestedFragmentPrecision:e.requestedVertexPrecision;return s==="highp"&&i!=="highp"&&(s="mediump"),`precision ${s} float;
21
+ ${n}`}else if(i!=="highp"&&n.substring(0,15)==="precision highp")return n.replace("precision highp","precision mediump");return n}function Ou(n,e){return e?`#version 300 es
22
+ ${n}`:n}const Wu={},Gu={};function Uu(n,{name:e="pixi-program"},t=!0){e=e.replace(/\s+/g,"-"),e+=t?"-fragment":"-vertex";const i=t?Wu:Gu;return i[e]?(i[e]++,e+=`-${i[e]}`):i[e]=1,n.indexOf("#define SHADER_NAME")!==-1?n:`${`#define SHADER_NAME ${e}`}
23
+ ${n}`}function Hu(n,e){return e?n.replace("#version 300 es",""):n}const pn={stripVersion:Hu,ensurePrecision:Lu,addProgramDefines:zu,setProgramName:Uu,insertVersion:Ou},ui=Object.create(null),il=class Qn{constructor(e){e={...Qn.defaultOptions,...e};const t=e.fragment.indexOf("#version 300 es")!==-1,i={stripVersion:t,ensurePrecision:{requestedFragmentPrecision:e.preferredFragmentPrecision,requestedVertexPrecision:e.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:Bu()},setProgramName:{name:e.name},addProgramDefines:t,insertVersion:t};let s=e.fragment,r=e.vertex;Object.keys(pn).forEach(o=>{const a=i[o];s=pn[o](s,a,!0),r=pn[o](r,a,!1)}),this.fragment=s,this.vertex=r,this.transformFeedbackVaryings=e.transformFeedbackVaryings,this._key=Rr(`${this.vertex}:${this.fragment}`,"gl-program")}destroy(){this.fragment=null,this.vertex=null,this._attributeData=null,this._uniformData=null,this._uniformBlockData=null,this.transformFeedbackVaryings=null,ui[this._cacheKey]=null}static from(e){const t=`${e.vertex}:${e.fragment}`;return ui[t]||(ui[t]=new Qn(e),ui[t]._cacheKey=t),ui[t]}};il.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let ii=il;const No={uint8x2:{size:2,stride:2,normalised:!1},uint8x4:{size:4,stride:4,normalised:!1},sint8x2:{size:2,stride:2,normalised:!1},sint8x4:{size:4,stride:4,normalised:!1},unorm8x2:{size:2,stride:2,normalised:!0},unorm8x4:{size:4,stride:4,normalised:!0},snorm8x2:{size:2,stride:2,normalised:!0},snorm8x4:{size:4,stride:4,normalised:!0},uint16x2:{size:2,stride:4,normalised:!1},uint16x4:{size:4,stride:8,normalised:!1},sint16x2:{size:2,stride:4,normalised:!1},sint16x4:{size:4,stride:8,normalised:!1},unorm16x2:{size:2,stride:4,normalised:!0},unorm16x4:{size:4,stride:8,normalised:!0},snorm16x2:{size:2,stride:4,normalised:!0},snorm16x4:{size:4,stride:8,normalised:!0},float16x2:{size:2,stride:4,normalised:!1},float16x4:{size:4,stride:8,normalised:!1},float32:{size:1,stride:4,normalised:!1},float32x2:{size:2,stride:8,normalised:!1},float32x3:{size:3,stride:12,normalised:!1},float32x4:{size:4,stride:16,normalised:!1},uint32:{size:1,stride:4,normalised:!1},uint32x2:{size:2,stride:8,normalised:!1},uint32x3:{size:3,stride:12,normalised:!1},uint32x4:{size:4,stride:16,normalised:!1},sint32:{size:1,stride:4,normalised:!1},sint32x2:{size:2,stride:8,normalised:!1},sint32x3:{size:3,stride:12,normalised:!1},sint32x4:{size:4,stride:16,normalised:!1}};function Vu(n){return No[n]??No.float32}const Nu={f32:"float32","vec2<f32>":"float32x2","vec3<f32>":"float32x3","vec4<f32>":"float32x4",vec2f:"float32x2",vec3f:"float32x3",vec4f:"float32x4",i32:"sint32","vec2<i32>":"sint32x2","vec3<i32>":"sint32x3","vec4<i32>":"sint32x4",vec2i:"sint32x2",vec3i:"sint32x3",vec4i:"sint32x4",u32:"uint32","vec2<u32>":"uint32x2","vec3<u32>":"uint32x3","vec4<u32>":"uint32x4",vec2u:"uint32x2",vec3u:"uint32x3",vec4u:"uint32x4",bool:"uint32","vec2<bool>":"uint32x2","vec3<bool>":"uint32x3","vec4<bool>":"uint32x4"},$o=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function Yo(n,e){let t;for(;(t=$o.exec(n))!==null;){const i=Nu[t[3]]??"float32";e[t[2]]={location:parseInt(t[1],10),format:i,stride:Vu(i).stride,offset:0,instance:!1,start:0}}$o.lastIndex=0}function $u(n){return n.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function Yu({source:n,entryPoint:e}){const t={},i=$u(n),s=i.indexOf(`fn ${e}(`);if(s===-1)return t;const r=i.indexOf("->",s);if(r===-1)return t;const o=i.substring(s,r);if(Yo(o,t),Object.keys(t).length===0){const a=o.match(/\(\s*\w+\s*:\s*(\w+)/);if(a){const h=a[1],l=new RegExp(`struct\\s+${h}\\s*\\{([^}]+)\\}`,"s"),c=i.match(l);c&&Yo(c[1],t)}}return t}function fn(n){var d,u;const e=/(^|[^/])@(group|binding)\(\d+\)[^;]+;/g,t=/@group\((\d+)\)/,i=/@binding\((\d+)\)/,s=/var(<[^>]+>)? (\w+)/,r=/:\s*([\w<>]+)/,o=/struct\s+(\w+)\s*{([^}]+)}/g,a=/(\w+)\s*:\s*([\w\<\>]+)/g,h=/struct\s+(\w+)/,l=(d=n.match(e))==null?void 0:d.map(p=>({group:parseInt(p.match(t)[1],10),binding:parseInt(p.match(i)[1],10),name:p.match(s)[2],isUniform:p.match(s)[1]==="<uniform>",type:p.match(r)[1]}));if(!l)return{groups:[],structs:[]};const c=((u=n.match(o))==null?void 0:u.map(p=>{const g=p.match(h)[1],m=p.match(a).reduce((y,x)=>{const[S,v]=x.split(":");return y[S.trim()]=v.trim(),y},{});return m?{name:g,members:m}:null}).filter(({name:p})=>l.some(g=>g.type===p||g.type.includes(`<${p}>`))))??[];return{groups:l,structs:c}}var Pe=(n=>(n[n.VERTEX=1]="VERTEX",n[n.FRAGMENT=2]="FRAGMENT",n[n.COMPUTE=4]="COMPUTE",n))(Pe||{});function Xu({groups:n}){const e=[];for(let t=0;t<n.length;t++){const i=n[t];e[i.group]||(e[i.group]=[]),i.isUniform?e[i.group].push({binding:i.binding,visibility:Pe.VERTEX|Pe.FRAGMENT,buffer:{type:"uniform"}}):i.type==="sampler"?e[i.group].push({binding:i.binding,visibility:Pe.FRAGMENT,sampler:{type:"filtering"}}):i.type==="texture_2d"||i.type.startsWith("texture_2d<")?e[i.group].push({binding:i.binding,visibility:Pe.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d",multisampled:!1}}):i.type==="texture_2d_array"||i.type.startsWith("texture_2d_array<")?e[i.group].push({binding:i.binding,visibility:Pe.FRAGMENT,texture:{sampleType:"float",viewDimension:"2d-array",multisampled:!1}}):(i.type==="texture_cube"||i.type.startsWith("texture_cube<"))&&e[i.group].push({binding:i.binding,visibility:Pe.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube",multisampled:!1}})}for(let t=0;t<e.length;t++)e[t]||(e[t]=[]);return e}function ju({groups:n}){const e=[];for(let t=0;t<n.length;t++){const i=n[t];e[i.group]||(e[i.group]={}),e[i.group][i.name]=i.binding}return e}function Zu(n,e){const t=new Set,i=new Set,s=[...n.structs,...e.structs].filter(o=>t.has(o.name)?!1:(t.add(o.name),!0)),r=[...n.groups,...e.groups].filter(o=>{const a=`${o.name}-${o.binding}`;return i.has(a)?!1:(i.add(a),!0)});return{structs:s,groups:r}}const pi=Object.create(null);class de{constructor(e){var a,h;this._layoutKey=0,this._attributeLocationsKey=0;const{fragment:t,vertex:i,layout:s,gpuLayout:r,name:o}=e;if(this.name=o,this.fragment=t,this.vertex=i,t.source===i.source){const l=fn(t.source);this.structsAndGroups=l}else{const l=fn(i.source),c=fn(t.source);this.structsAndGroups=Zu(l,c)}this.layout=s??ju(this.structsAndGroups),this.gpuLayout=r??Xu(this.structsAndGroups),this.autoAssignGlobalUniforms=((a=this.layout[0])==null?void 0:a.globalUniforms)!==void 0,this.autoAssignLocalUniforms=((h=this.layout[1])==null?void 0:h.localUniforms)!==void 0,this._generateProgramKey()}_generateProgramKey(){const{vertex:e,fragment:t}=this,i=e.source+t.source+e.entryPoint+t.entryPoint;this._layoutKey=Rr(i,"program")}get attributeData(){return this._attributeData??(this._attributeData=Yu(this.vertex)),this._attributeData}destroy(){this.gpuLayout=null,this.layout=null,this.structsAndGroups=null,this.fragment=null,this.vertex=null,pi[this._cacheKey]=null}static from(e){const t=`${e.vertex.source}:${e.fragment.source}:${e.fragment.entryPoint}:${e.vertex.entryPoint}`;return pi[t]||(pi[t]=new de(e),pi[t]._cacheKey=t),pi[t]}}const sl=["f32","i32","vec2<f32>","vec3<f32>","vec4<f32>","mat2x2<f32>","mat3x3<f32>","mat4x4<f32>","mat3x2<f32>","mat4x2<f32>","mat2x3<f32>","mat4x3<f32>","mat2x4<f32>","mat3x4<f32>","vec2<i32>","vec3<i32>","vec4<i32>"],qu=sl.reduce((n,e)=>(n[e]=!0,n),{});function Ku(n,e){switch(n){case"f32":return 0;case"vec2<f32>":return new Float32Array(2*e);case"vec3<f32>":return new Float32Array(3*e);case"vec4<f32>":return new Float32Array(4*e);case"mat2x2<f32>":return new Float32Array([1,0,0,1]);case"mat3x3<f32>":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4x4<f32>":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const nl=class rl{constructor(e,t){this._touched=0,this.uid=dt("uniform"),this._resourceType="uniformGroup",this._resourceId=dt("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,t={...rl.defaultOptions,...t},this.uniformStructures=e;const i={};for(const s in e){const r=e[s];if(r.name=s,r.size=r.size??1,!qu[r.type]){const o=r.type.match(/^array<(\w+(?:<\w+>)?),\s*(\d+)>$/);if(o){const[,a,h]=o;throw new Error(`Uniform type ${r.type} is not supported. Use type: '${a}', size: ${h} instead.`)}throw new Error(`Uniform type ${r.type} is not supported. Supported uniform types are: ${sl.join(", ")}`)}r.value??(r.value=Ku(r.type,r.size)),i[s]=r.value}this.uniforms=i,this._dirtyId=1,this.ubo=t.ubo,this.isStatic=t.isStatic,this._signature=Rr(Object.keys(i).map(s=>`${s}-${e[s].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};nl.defaultOptions={ubo:!1,isStatic:!1};let si=nl;class Ai{constructor(e){this.resources=Object.create(null),this._dirty=!0;let t=0;for(const i in e){const s=e[i];this.setResource(s,t++)}this._updateKey()}_updateKey(){if(!this._dirty)return;this._dirty=!1;const e=[];let t=0;for(const i in this.resources)e[t++]=this.resources[i]._resourceId;this._key=e.join("|")}setResource(e,t){var s,r;const i=this.resources[t];e!==i&&(i&&((s=i.off)==null||s.call(i,"change",this.onResourceChange,this)),(r=e.on)==null||r.call(e,"change",this.onResourceChange,this),this.resources[t]=e,this._dirty=!0)}getResource(e){return this.resources[e]}_touch(e,t){const i=this.resources;for(const s in i)i[s]._gcLastUsed=e,i[s]._touched=t}destroy(){var t;const e=this.resources;for(const i in e){const s=e[i];(t=s==null?void 0:s.off)==null||t.call(s,"change",this.onResourceChange,this)}this.resources=null}onResourceChange(e){if(this._dirty=!0,e.destroyed){const t=this.resources;for(const i in t)t[i]===e&&(t[i]=null)}else this._updateKey()}}var te=(n=>(n[n.WEBGL=1]="WEBGL",n[n.WEBGPU=2]="WEBGPU",n[n.CANVAS=4]="CANVAS",n[n.BOTH=3]="BOTH",n))(te||{});class Be extends jt{constructor(e){super(),this.uid=dt("shader"),this._uniformBindMap=Object.create(null),this._ownedBindGroups=[],this._destroyed=!1;let{gpuProgram:t,glProgram:i,groups:s,resources:r,compatibleRenderers:o,groupMap:a}=e;this.gpuProgram=t,this.glProgram=i,o===void 0&&(o=0,t&&(o|=te.WEBGPU),i&&(o|=te.WEBGL)),this.compatibleRenderers=o;const h={};if(!r&&!s&&(r={}),r&&s)throw new Error("[Shader] Cannot have both resources and groups");if(!t&&s&&!a)throw new Error("[Shader] No group map or WebGPU shader provided - consider using resources instead.");if(!t&&s&&a)for(const l in a)for(const c in a[l]){const d=a[l][c];h[d]={group:l,binding:c,name:d}}else if(t&&s&&!a){const l=t.structsAndGroups.groups;a={},l.forEach(c=>{a[c.group]=a[c.group]||{},a[c.group][c.binding]=c.name,h[c.name]=c})}else if(r){s={},a={},t&&t.structsAndGroups.groups.forEach(d=>{a[d.group]=a[d.group]||{},a[d.group][d.binding]=d.name,h[d.name]=d});let l=0;for(const c in r)h[c]||(s[99]||(s[99]=new Ai,this._ownedBindGroups.push(s[99])),h[c]={group:99,binding:l,name:c},a[99]=a[99]||{},a[99][l]=c,l++);for(const c in r){const d=c;let u=r[c];!u.source&&!u._resourceType&&(u=new si(u));const p=h[d];p&&(s[p.group]||(s[p.group]=new Ai,this._ownedBindGroups.push(s[p.group])),s[p.group].setResource(u,p.binding))}}this.groups=s,this._uniformBindMap=a,this.resources=this._buildResourceAccessor(s,h)}addResource(e,t,i){var s,r;(s=this._uniformBindMap)[t]||(s[t]={}),(r=this._uniformBindMap[t])[i]||(r[i]=e),this.groups[t]||(this.groups[t]=new Ai,this._ownedBindGroups.push(this.groups[t]))}_buildResourceAccessor(e,t){const i={};for(const s in t){const r=t[s];Object.defineProperty(i,r.name,{get(){return e[r.group].getResource(r.binding)},set(o){e[r.group].setResource(o,r.binding)}})}return i}destroy(e=!1){var t,i;this._destroyed||(this._destroyed=!0,this.emit("destroy",this),e&&((t=this.gpuProgram)==null||t.destroy(),(i=this.glProgram)==null||i.destroy()),this.gpuProgram=null,this.glProgram=null,this.removeAllListeners(),this._uniformBindMap=null,this._ownedBindGroups.forEach(s=>{s.destroy()}),this._ownedBindGroups=null,this.resources=null,this.groups=null)}static from(e){const{gpu:t,gl:i,...s}=e;let r,o;return t&&(r=de.from(t)),i&&(o=ii.from(i)),new Be({gpuProgram:r,glProgram:o,...s})}}const Qu={normal:0,add:1,multiply:2,screen:3,overlay:4,erase:5,"normal-npm":6,"add-npm":7,"screen-npm":8,min:9,max:10},gn=0,mn=1,yn=2,xn=3,Sn=4,vn=5,Jn=class ol{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<gn)}set blend(e){!!(this.data&1<<gn)!==e&&(this.data^=1<<gn)}get offsets(){return!!(this.data&1<<mn)}set offsets(e){!!(this.data&1<<mn)!==e&&(this.data^=1<<mn)}set cullMode(e){if(e==="none"){this.culling=!1;return}this.culling=!0,this.clockwiseFrontFace=e==="front"}get cullMode(){return this.culling?this.clockwiseFrontFace?"front":"back":"none"}get culling(){return!!(this.data&1<<yn)}set culling(e){!!(this.data&1<<yn)!==e&&(this.data^=1<<yn)}get depthTest(){return!!(this.data&1<<xn)}set depthTest(e){!!(this.data&1<<xn)!==e&&(this.data^=1<<xn)}get depthMask(){return!!(this.data&1<<vn)}set depthMask(e){!!(this.data&1<<vn)!==e&&(this.data^=1<<vn)}get clockwiseFrontFace(){return!!(this.data&1<<Sn)}set clockwiseFrontFace(e){!!(this.data&1<<Sn)!==e&&(this.data^=1<<Sn)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!=="none",this._blendMode=e,this._blendModeId=Qu[e]||0}get polygonOffset(){return this._polygonOffset}set polygonOffset(e){this.offsets=!!e,this._polygonOffset=e}toString(){return`[pixi.js/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`}static for2d(){const e=new ol;return e.depthTest=!1,e.blend=!0,e}};Jn.default2d=Jn.for2d();let Ni=Jn;const al=class tr extends Be{constructor(e){e={...tr.defaultOptions,...e},super(e),this.enabled=!0,this._state=Ni.for2d(),this.blendMode=e.blendMode,this.padding=e.padding,typeof e.antialias=="boolean"?this.antialias=e.antialias?"on":"off":this.antialias=e.antialias,this.resolution=e.resolution,this.blendRequired=e.blendRequired,this.clipToViewport=e.clipToViewport,this.addResource("uTexture",0,1),e.blendRequired&&this.addResource("uBackTexture",0,3)}apply(e,t,i,s){e.applyFilter(this,t,i,s)}get blendMode(){return this._state.blendMode}set blendMode(e){this._state.blendMode=e}static from(e){const{gpu:t,gl:i,...s}=e;let r,o;return t&&(r=de.from(t)),i&&(o=ii.from(i)),new tr({gpuProgram:r,glProgram:o,...s})}};al.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let Ju=al;const er=[];K.handleByNamedList(I.Environment,er);async function tp(n){if(!n)for(let e=0;e<er.length;e++){const t=er[e];if(t.value.test()){await t.value.load();return}}}let fi;function ep(){if(typeof fi=="boolean")return fi;try{fi=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{fi=!1}return fi}function Xo(n,e,t=2){const i=e&&e.length,s=i?e[0]*t:n.length;let r=hl(n,0,s,t,!0);const o=[];if(!r||r.next===r.prev)return o;let a,h,l;if(i&&(r=op(n,e,r,t)),n.length>80*t){a=n[0],h=n[1];let c=a,d=h;for(let u=t;u<s;u+=t){const p=n[u],g=n[u+1];p<a&&(a=p),g<h&&(h=g),p>c&&(c=p),g>d&&(d=g)}l=Math.max(c-a,d-h),l=l!==0?32767/l:0}return Bi(r,o,t,a,h,l,0),o}function hl(n,e,t,i,s){let r;if(s===yp(n,e,t,i)>0)for(let o=e;o<t;o+=i)r=jo(o/i|0,n[o],n[o+1],r);else for(let o=t-i;o>=e;o-=i)r=jo(o/i|0,n[o],n[o+1],r);return r&&ni(r,r.next)&&(Li(r),r=r.next),r}function ze(n,e){if(!n)return n;e||(e=n);let t=n,i;do if(i=!1,!t.steiner&&(ni(t,t.next)||at(t.prev,t,t.next)===0)){if(Li(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function Bi(n,e,t,i,s,r,o){if(!n)return;!o&&r&&dp(n,i,s,r);let a=n;for(;n.prev!==n.next;){const h=n.prev,l=n.next;if(r?sp(n,i,s,r):ip(n)){e.push(h.i,n.i,l.i),Li(n),n=l.next,a=l.next;continue}if(n=l,n===a){o?o===1?(n=np(ze(n),e),Bi(n,e,t,i,s,r,2)):o===2&&rp(n,e,t,i,s,r):Bi(ze(n),e,t,i,s,r,1);break}}}function ip(n){const e=n.prev,t=n,i=n.next;if(at(e,t,i)>=0)return!1;const s=e.x,r=t.x,o=i.x,a=e.y,h=t.y,l=i.y,c=Math.min(s,r,o),d=Math.min(a,h,l),u=Math.max(s,r,o),p=Math.max(a,h,l);let g=i.next;for(;g!==e;){if(g.x>=c&&g.x<=u&&g.y>=d&&g.y<=p&&wi(s,a,r,h,o,l,g.x,g.y)&&at(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function sp(n,e,t,i){const s=n.prev,r=n,o=n.next;if(at(s,r,o)>=0)return!1;const a=s.x,h=r.x,l=o.x,c=s.y,d=r.y,u=o.y,p=Math.min(a,h,l),g=Math.min(c,d,u),m=Math.max(a,h,l),y=Math.max(c,d,u),x=ir(p,g,e,t,i),S=ir(m,y,e,t,i);let v=n.prevZ,b=n.nextZ;for(;v&&v.z>=x&&b&&b.z<=S;){if(v.x>=p&&v.x<=m&&v.y>=g&&v.y<=y&&v!==s&&v!==o&&wi(a,c,h,d,l,u,v.x,v.y)&&at(v.prev,v,v.next)>=0||(v=v.prevZ,b.x>=p&&b.x<=m&&b.y>=g&&b.y<=y&&b!==s&&b!==o&&wi(a,c,h,d,l,u,b.x,b.y)&&at(b.prev,b,b.next)>=0))return!1;b=b.nextZ}for(;v&&v.z>=x;){if(v.x>=p&&v.x<=m&&v.y>=g&&v.y<=y&&v!==s&&v!==o&&wi(a,c,h,d,l,u,v.x,v.y)&&at(v.prev,v,v.next)>=0)return!1;v=v.prevZ}for(;b&&b.z<=S;){if(b.x>=p&&b.x<=m&&b.y>=g&&b.y<=y&&b!==s&&b!==o&&wi(a,c,h,d,l,u,b.x,b.y)&&at(b.prev,b,b.next)>=0)return!1;b=b.nextZ}return!0}function np(n,e){let t=n;do{const i=t.prev,s=t.next.next;!ni(i,s)&&cl(i,t,t.next,s)&&zi(i,s)&&zi(s,i)&&(e.push(i.i,t.i,s.i),Li(t),Li(t.next),t=n=s),t=t.next}while(t!==n);return ze(t)}function rp(n,e,t,i,s,r){let o=n;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&fp(o,a)){let h=dl(o,a);o=ze(o,o.next),h=ze(h,h.next),Bi(o,e,t,i,s,r,0),Bi(h,e,t,i,s,r,0);return}a=a.next}o=o.next}while(o!==n)}function op(n,e,t,i){const s=[];for(let r=0,o=e.length;r<o;r++){const a=e[r]*i,h=r<o-1?e[r+1]*i:n.length,l=hl(n,a,h,i,!1);l===l.next&&(l.steiner=!0),s.push(pp(l))}s.sort(ap);for(let r=0;r<s.length;r++)t=hp(s[r],t);return t}function ap(n,e){let t=n.x-e.x;if(t===0&&(t=n.y-e.y,t===0)){const i=(n.next.y-n.y)/(n.next.x-n.x),s=(e.next.y-e.y)/(e.next.x-e.x);t=i-s}return t}function hp(n,e){const t=lp(n,e);if(!t)return e;const i=dl(t,n);return ze(i,i.next),ze(t,t.next)}function lp(n,e){let t=e;const i=n.x,s=n.y;let r=-1/0,o;if(ni(n,t))return t;do{if(ni(n,t.next))return t.next;if(s<=t.y&&s>=t.next.y&&t.next.y!==t.y){const d=t.x+(s-t.y)*(t.next.x-t.x)/(t.next.y-t.y);if(d<=i&&d>r&&(r=d,o=t.x<t.next.x?t:t.next,d===i))return o}t=t.next}while(t!==e);if(!o)return null;const a=o,h=o.x,l=o.y;let c=1/0;t=o;do{if(i>=t.x&&t.x>=h&&i!==t.x&&ll(s<l?i:r,s,h,l,s<l?r:i,s,t.x,t.y)){const d=Math.abs(s-t.y)/(i-t.x);zi(t,n)&&(d<c||d===c&&(t.x>o.x||t.x===o.x&&cp(o,t)))&&(o=t,c=d)}t=t.next}while(t!==a);return o}function cp(n,e){return at(n.prev,n,e.prev)<0&&at(e.next,n,n.next)<0}function dp(n,e,t,i){let s=n;do s.z===0&&(s.z=ir(s.x,s.y,e,t,i)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next;while(s!==n);s.prevZ.nextZ=null,s.prevZ=null,up(s)}function up(n){let e,t=1;do{let i=n,s;n=null;let r=null;for(e=0;i;){e++;let o=i,a=0;for(let l=0;l<t&&(a++,o=o.nextZ,!!o);l++);let h=t;for(;a>0||h>0&&o;)a!==0&&(h===0||!o||i.z<=o.z)?(s=i,i=i.nextZ,a--):(s=o,o=o.nextZ,h--),r?r.nextZ=s:n=s,s.prevZ=r,r=s;i=o}r.nextZ=null,t*=2}while(e>1);return n}function ir(n,e,t,i,s){return n=(n-t)*s|0,e=(e-i)*s|0,n=(n|n<<8)&16711935,n=(n|n<<4)&252645135,n=(n|n<<2)&858993459,n=(n|n<<1)&1431655765,e=(e|e<<8)&16711935,e=(e|e<<4)&252645135,e=(e|e<<2)&858993459,e=(e|e<<1)&1431655765,n|e<<1}function pp(n){let e=n,t=n;do(e.x<t.x||e.x===t.x&&e.y<t.y)&&(t=e),e=e.next;while(e!==n);return t}function ll(n,e,t,i,s,r,o,a){return(s-o)*(e-a)>=(n-o)*(r-a)&&(n-o)*(i-a)>=(t-o)*(e-a)&&(t-o)*(r-a)>=(s-o)*(i-a)}function wi(n,e,t,i,s,r,o,a){return!(n===o&&e===a)&&ll(n,e,t,i,s,r,o,a)}function fp(n,e){return n.next.i!==e.i&&n.prev.i!==e.i&&!gp(n,e)&&(zi(n,e)&&zi(e,n)&&mp(n,e)&&(at(n.prev,n,e.prev)||at(n,e.prev,e))||ni(n,e)&&at(n.prev,n,n.next)>0&&at(e.prev,e,e.next)>0)}function at(n,e,t){return(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y)}function ni(n,e){return n.x===e.x&&n.y===e.y}function cl(n,e,t,i){const s=ns(at(n,e,t)),r=ns(at(n,e,i)),o=ns(at(t,i,n)),a=ns(at(t,i,e));return!!(s!==r&&o!==a||s===0&&ss(n,t,e)||r===0&&ss(n,i,e)||o===0&&ss(t,n,i)||a===0&&ss(t,e,i))}function ss(n,e,t){return e.x<=Math.max(n.x,t.x)&&e.x>=Math.min(n.x,t.x)&&e.y<=Math.max(n.y,t.y)&&e.y>=Math.min(n.y,t.y)}function ns(n){return n>0?1:n<0?-1:0}function gp(n,e){let t=n;do{if(t.i!==n.i&&t.next.i!==n.i&&t.i!==e.i&&t.next.i!==e.i&&cl(t,t.next,n,e))return!0;t=t.next}while(t!==n);return!1}function zi(n,e){return at(n.prev,n,n.next)<0?at(n,e,n.next)>=0&&at(n,n.prev,e)>=0:at(n,e,n.prev)<0||at(n,n.next,e)<0}function mp(n,e){let t=n,i=!1;const s=(n.x+e.x)/2,r=(n.y+e.y)/2;do t.y>r!=t.next.y>r&&t.next.y!==t.y&&s<(t.next.x-t.x)*(r-t.y)/(t.next.y-t.y)+t.x&&(i=!i),t=t.next;while(t!==n);return i}function dl(n,e){const t=sr(n.i,n.x,n.y),i=sr(e.i,e.x,e.y),s=n.next,r=e.prev;return n.next=e,e.prev=n,t.next=s,s.prev=t,i.next=t,t.prev=i,r.next=i,i.prev=r,i}function jo(n,e,t,i){const s=sr(n,e,t);return i?(s.next=i.next,s.prev=i,i.next.prev=s,i.next=s):(s.prev=s,s.next=s),s}function Li(n){n.next.prev=n.prev,n.prev.next=n.next,n.prevZ&&(n.prevZ.nextZ=n.nextZ),n.nextZ&&(n.nextZ.prevZ=n.prevZ)}function sr(n,e,t){return{i:n,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function yp(n,e,t,i){let s=0;for(let r=e,o=t-i;r<t;r+=i)s+=(n[o]-n[r])*(n[r+1]+n[o+1]),o=r;return s}const xp=Xo.default||Xo;var ul=(n=>(n[n.NONE=0]="NONE",n[n.COLOR=16384]="COLOR",n[n.STENCIL=1024]="STENCIL",n[n.DEPTH=256]="DEPTH",n[n.COLOR_DEPTH=16640]="COLOR_DEPTH",n[n.COLOR_STENCIL=17408]="COLOR_STENCIL",n[n.DEPTH_STENCIL=1280]="DEPTH_STENCIL",n[n.ALL=17664]="ALL",n))(ul||{});class Sp{constructor(e){this.items=[],this._name=e}emit(e,t,i,s,r,o,a,h){const{name:l,items:c}=this;for(let d=0,u=c.length;d<u;d++)c[d][l](e,t,i,s,r,o,a,h);return this}add(e){return e[this._name]&&(this.remove(e),this.items.push(e)),this}remove(e){const t=this.items.indexOf(e);return t!==-1&&this.items.splice(t,1),this}contains(e){return this.items.indexOf(e)!==-1}removeAll(){return this.items.length=0,this}destroy(){this.removeAll(),this.items=null,this._name=null}get empty(){return this.items.length===0}get name(){return this._name}}const vp=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],pl=class fl extends jt{constructor(e){super(),this.tick=0,this.uid=dt("renderer"),this.runners=Object.create(null),this.renderPipes=Object.create(null),this._initOptions={},this._systemsHash=Object.create(null),this.type=e.type,this.name=e.name,this.config=e;const t=[...vp,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(e={}){const t=e.skipExtensionImports===!0?!0:e.manageImports===!1;await tp(t),this._addSystems(this.config.systems),this._addPipes(this.config.renderPipes,this.config.renderPipeAdaptors);for(const i in this._systemsHash)e={...this._systemsHash[i].constructor.defaultOptions,...e};e={...fl.defaultOptions,...e},this._roundPixels=e.roundPixels?1:0;for(let i=0;i<this.runners.init.items.length;i++)await this.runners.init.items[i].init(e);this._initOptions=e}render(e,t){this.tick++;let i=e;if(i instanceof L&&(i={container:i},t&&(V(Q,"passing a second argument is deprecated, please use render options instead"),i.target=t.renderTexture)),i.target||(i.target=this.view.renderTarget),i.target===this.view.renderTarget&&(this._lastObjectRendered=i.container,i.clearColor??(i.clearColor=this.background.colorRgba),i.clear??(i.clear=this.background.clearBeforeRender)),i.clearColor){const s=Array.isArray(i.clearColor)&&i.clearColor.length===4;i.clearColor=s?i.clearColor:rt.shared.setValue(i.clearColor).toArray()}i.transform||(i.container.updateLocalTransform(),i.transform=i.container.localTransform),i.container.visible&&(i.container.enableRenderGroup(),this.runners.prerender.emit(i),this.runners.renderStart.emit(i),this.runners.render.emit(i),this.runners.renderEnd.emit(i),this.runners.postrender.emit(i))}resize(e,t,i){const s=this.view.resolution;this.view.resize(e,t,i),this.emit("resize",this.view.screen.width,this.view.screen.height,this.view.resolution),i!==void 0&&i!==s&&this.runners.resolutionChange.emit(i)}clear(e={}){const t=this;e.target||(e.target=t.renderTarget.renderTarget),e.clearColor||(e.clearColor=this.background.colorRgba),e.clear??(e.clear=ul.ALL);const{clear:i,clearColor:s,target:r,mipLevel:o,layer:a}=e;rt.shared.setValue(s??this.background.colorRgba),t.renderTarget.clear(r,i,rt.shared.toArray(),o??0,a??0)}get resolution(){return this.view.resolution}set resolution(e){this.view.resolution=e,this.runners.resolutionChange.emit(e)}get width(){return this.view.texture.frame.width}get height(){return this.view.texture.frame.height}get canvas(){return this.view.canvas}get lastObjectRendered(){return this._lastObjectRendered}get renderingToScreen(){return this.renderTarget.renderingToScreen}get screen(){return this.view.screen}_addRunners(...e){e.forEach(t=>{this.runners[t]=new Sp(t)})}_addSystems(e){let t;for(t in e){const i=e[t];this._addSystem(i.value,i.name)}}_addSystem(e,t){const i=new e(this);if(this[t])throw new Error(`Whoops! The name "${t}" is already in use`);this[t]=i,this._systemsHash[t]=i;for(const s in this.runners)this.runners[s].add(i);return this}_addPipes(e,t){const i=t.reduce((s,r)=>(s[r.name]=r.value,s),{});e.forEach(s=>{const r=s.value,o=s.name,a=i[o];this.renderPipes[o]=new r(this,a?new a:null),this.runners.destroy.add(this.renderPipes[o])})}destroy(e=!1){this.runners.destroy.items.reverse(),this.runners.destroy.emit(e),(e===!0||typeof e=="object"&&e.releaseGlobalResources)&&Vi.release(),Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash=null,this.renderPipes=null}generateTexture(e){return this.textureGenerator.generateTexture(e)}get roundPixels(){return!!this._roundPixels}_unsafeEvalCheck(){if(!ep())throw new Error("Current environment does not allow unsafe-eval, please use pixi.js/unsafe-eval module to enable support.")}resetState(){this.runners.resetState.emit()}};pl.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let gl=pl,rs;function bp(n){return rs!==void 0||(rs=(()=>{var t;const e={stencil:!0,failIfMajorPerformanceCaveat:n??gl.defaultOptions.failIfMajorPerformanceCaveat};try{if(!$.get().getWebGLRenderingContext())return!1;let s=$.get().createCanvas().getContext("webgl",e);const r=!!((t=s==null?void 0:s.getContextAttributes())!=null&&t.stencil);if(s){const o=s.getExtension("WEBGL_lose_context");o&&o.loseContext()}return s=null,r}catch{return!1}})()),rs}let os;async function wp(n={}){return os!==void 0||(os=await(async()=>{const e=$.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(n)).requestDevice(),!0}catch{return!1}})()),os}const Zo=["webgl","webgpu","canvas"];async function Cp(n){let e=[];n.preference?(e.push(n.preference),Zo.forEach(r=>{r!==n.preference&&e.push(r)})):e=Zo.slice();let t,i={};for(let r=0;r<e.length;r++){const o=e[r];if(o==="webgpu"&&await wp()){const{WebGPURenderer:a}=await Re(async()=>{const{WebGPURenderer:h}=await import("./WebGPURenderer.C7Xo_Nj6.js");return{WebGPURenderer:h}},__vite__mapDeps([5,6,7,2,3,4]));t=a,i={...n,...n.webgpu};break}else if(o==="webgl"&&bp(n.failIfMajorPerformanceCaveat??gl.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await Re(async()=>{const{WebGLRenderer:h}=await import("./WebGLRenderer.CmlR6hDG.js");return{WebGLRenderer:h}},__vite__mapDeps([8,6,7,2,3,4]));t=a,i={...n,...n.webgl};break}else if(o==="canvas"){const{CanvasRenderer:a}=await Re(async()=>{const{CanvasRenderer:h}=await import("./CanvasRenderer.DflYBGLD.js");return{CanvasRenderer:h}},__vite__mapDeps([9,7,2,3,4]));t=a,i={...n,...n.canvasOptions};break}}if(delete i.webgpu,delete i.webgl,delete i.canvasOptions,!t)throw new Error("No available renderer for the current environment");const s=new t;return await s.init(i),s}const ml="8.16.0";class yl{static init(){var e;(e=globalThis.__PIXI_APP_INIT__)==null||e.call(globalThis,this,ml)}static destroy(){}}yl.extension=I.Application;class _p{constructor(e){this._renderer=e}init(){var e;(e=globalThis.__PIXI_RENDERER_INIT__)==null||e.call(globalThis,this._renderer,ml)}destroy(){this._renderer=null}}_p.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:"initHook",priority:-10};class xl{static init(e){Object.defineProperty(this,"resizeTo",{configurable:!0,set(t){globalThis.removeEventListener("resize",this.queueResize),this._resizeTo=t,t&&(globalThis.addEventListener("resize",this.queueResize),this.resize())},get(){return this._resizeTo}}),this.queueResize=()=>{this._resizeTo&&(this._cancelResize(),this._resizeId=requestAnimationFrame(()=>this.resize()))},this._cancelResize=()=>{this._resizeId&&(cancelAnimationFrame(this._resizeId),this._resizeId=null)},this.resize=()=>{if(!this._resizeTo)return;this._cancelResize();let t,i;if(this._resizeTo===globalThis.window)t=globalThis.innerWidth,i=globalThis.innerHeight;else{const{clientWidth:s,clientHeight:r}=this._resizeTo;t=s,i=r}this.renderer.resize(t,i),this.render()},this._resizeId=null,this._resizeTo=null,this.resizeTo=e.resizeTo||null}static destroy(){globalThis.removeEventListener("resize",this.queueResize),this._cancelResize(),this._cancelResize=null,this.queueResize=null,this.resizeTo=null,this.resize=null}}xl.extension=I.Application;class Sl{static init(e){e=Object.assign({autoStart:!0,sharedTicker:!1},e),Object.defineProperty(this,"ticker",{configurable:!0,set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,Fe.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?yt.shared:new yt,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}Sl.extension=I.Application;K.add(xl);K.add(Sl);const vl=class nr{constructor(...e){this.stage=new L,e[0]!==void 0&&V(Q,"Application constructor options are deprecated, please use Application.init() instead.")}async init(e){e={...e},this.stage||(this.stage=new L),this.renderer=await Cp(e),nr._plugins.forEach(t=>{t.init.call(this,e)})}render(){this.renderer.render({container:this.stage})}get canvas(){return this.renderer.canvas}get view(){return V(Q,"Application.view is deprecated, please use Application.canvas instead."),this.renderer.canvas}get screen(){return this.renderer.screen}destroy(e=!1,t=!1){const i=nr._plugins.slice(0);i.reverse(),i.forEach(s=>{s.destroy.call(this)}),this.stage.destroy(t),this.stage=null,this.renderer.destroy(e),this.renderer=null}};vl._plugins=[];let bl=vl;K.handleByList(I.Application,bl._plugins);K.add(yl);const bn={test(n){return typeof n=="string"&&n.startsWith("info face=")},parse(n){const e=n.match(/^[a-z]+\s+.+$/gm),t={info:[],common:[],page:[],char:[],chars:[],kerning:[],kernings:[],distanceField:[]};for(const d in e){const u=e[d].match(/^[a-z]+/gm)[0],p=e[d].match(/[a-zA-Z]+=([^\s"']+|"([^"]*)")/gm),g={};for(const m in p){const y=p[m].split("="),x=y[0],S=y[1].replace(/"/gm,""),v=parseFloat(S),b=isNaN(v)?S:v;g[x]=b}t[u].push(g)}const i={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},[s]=t.info,[r]=t.common,[o]=t.distanceField??[];o&&(i.distanceField={range:parseInt(o.distanceRange,10),type:o.fieldType}),i.fontSize=parseInt(s.size,10),i.fontFamily=s.face,i.lineHeight=parseInt(r.lineHeight,10);const a=t.page;for(let d=0;d<a.length;d++)i.pages.push({id:parseInt(a[d].id,10)||0,file:a[d].file});const h={};i.baseLineOffset=i.lineHeight-parseInt(r.base,10);const l=t.char;for(let d=0;d<l.length;d++){const u=l[d],p=parseInt(u.id,10);let g=u.letter??u.char??String.fromCharCode(p);g==="space"&&(g=" "),h[p]=g,i.chars[g]={id:p,page:parseInt(u.page,10)||0,x:parseInt(u.x,10),y:parseInt(u.y,10),width:parseInt(u.width,10),height:parseInt(u.height,10),xOffset:parseInt(u.xoffset,10),yOffset:parseInt(u.yoffset,10),xAdvance:parseInt(u.xadvance,10),kerning:{}}}const c=t.kerning||[];for(let d=0;d<c.length;d++){const u=parseInt(c[d].first,10),p=parseInt(c[d].second,10),g=parseInt(c[d].amount,10);i.chars[h[p]].kerning[h[u]]=g}return i}},qo={test(n){const e=n;return typeof e!="string"&&"getElementsByTagName"in e&&e.getElementsByTagName("page").length&&e.getElementsByTagName("info")[0].getAttribute("face")!==null},parse(n){const e={chars:{},pages:[],lineHeight:0,fontSize:0,fontFamily:"",distanceField:null,baseLineOffset:0},t=n.getElementsByTagName("info")[0],i=n.getElementsByTagName("common")[0],s=n.getElementsByTagName("distanceField")[0];s&&(e.distanceField={type:s.getAttribute("fieldType"),range:parseInt(s.getAttribute("distanceRange"),10)});const r=n.getElementsByTagName("page"),o=n.getElementsByTagName("char"),a=n.getElementsByTagName("kerning");e.fontSize=parseInt(t.getAttribute("size"),10),e.fontFamily=t.getAttribute("face"),e.lineHeight=parseInt(i.getAttribute("lineHeight"),10);for(let l=0;l<r.length;l++)e.pages.push({id:parseInt(r[l].getAttribute("id"),10)||0,file:r[l].getAttribute("file")});const h={};e.baseLineOffset=e.lineHeight-parseInt(i.getAttribute("base"),10);for(let l=0;l<o.length;l++){const c=o[l],d=parseInt(c.getAttribute("id"),10);let u=c.getAttribute("letter")??c.getAttribute("char")??String.fromCharCode(d);u==="space"&&(u=" "),h[d]=u,e.chars[u]={id:d,page:parseInt(c.getAttribute("page"),10)||0,x:parseInt(c.getAttribute("x"),10),y:parseInt(c.getAttribute("y"),10),width:parseInt(c.getAttribute("width"),10),height:parseInt(c.getAttribute("height"),10),xOffset:parseInt(c.getAttribute("xoffset"),10),yOffset:parseInt(c.getAttribute("yoffset"),10),xAdvance:parseInt(c.getAttribute("xadvance"),10),kerning:{}}}for(let l=0;l<a.length;l++){const c=parseInt(a[l].getAttribute("first"),10),d=parseInt(a[l].getAttribute("second"),10),u=parseInt(a[l].getAttribute("amount"),10);e.chars[h[d]].kerning[h[c]]=u}return e}},Ko={test(n){return typeof n=="string"&&n.match(/<font(\s|>)/)?qo.test($.get().parseXML(n)):!1},parse(n){return qo.parse($.get().parseXML(n))}},Pp=[".xml",".fnt"],Mp={extension:{type:I.CacheParser,name:"cacheBitmapFont"},test:n=>!!(n!=null&&n.pages)&&!!(n!=null&&n.chars)&&typeof(n==null?void 0:n.fontFamily)=="string",getCacheableAssets(n,e){const t={};return n.forEach(i=>{t[i]=e,t[`${i}-bitmap`]=e}),t[`${e.fontFamily}-bitmap`]=e,t}},Ap={extension:{type:I.LoadParser,priority:pe.Normal},name:"loadBitmapFont",id:"bitmap-font",test(n){return Pp.includes(Mt.extname(n).toLowerCase())},async testParse(n){return bn.test(n)||Ko.test(n)},async parse(n,e,t){const i=bn.test(n)?bn.parse(n):Ko.parse(n),{src:s}=e,{pages:r}=i,o=[],a=i.distanceField?{scaleMode:"linear",alphaMode:"premultiply-alpha-on-upload",autoGenerateMipmaps:!1,resolution:1}:{};for(let u=0;u<r.length;++u){const p=r[u].file;let g=Mt.join(Mt.dirname(s),p);g=qn(g,s),o.push({src:g,data:a})}const[h,{BitmapFont:l}]=await Promise.all([t.load(o),Re(()=>import("./BitmapFont.Bn4Xj5K-.js"),__vite__mapDeps([10,2,3,4]))]),c=o.map(u=>h[u.src]);return new l({data:i,textures:c},s)},async load(n,e){return await(await $.get().fetch(n)).text()},async unload(n,e,t){await Promise.all(n.pages.map(i=>t.unload(i.texture.source._sourceOrigin))),n.destroy()}};class Tp{constructor(e,t=!1){this._loader=e,this._assetList=[],this._isLoading=!1,this._maxConcurrent=1,this.verbose=t}add(e){e.forEach(t=>{this._assetList.push(t)}),this.verbose&&console.log("[BackgroundLoader] assets: ",this._assetList),this._isActive&&!this._isLoading&&this._next()}async _next(){if(this._assetList.length&&this._isActive){this._isLoading=!0;const e=[],t=Math.min(this._assetList.length,this._maxConcurrent);for(let i=0;i<t;i++)e.push(this._assetList.pop());await this._loader.load(e),this._isLoading=!1,this._next()}}get active(){return this._isActive}set active(e){this._isActive!==e&&(this._isActive=e,e&&!this._isLoading&&this._next())}}const Rp={extension:{type:I.CacheParser,name:"cacheTextureArray"},test:n=>Array.isArray(n)&&n.every(e=>e instanceof G),getCacheableAssets:(n,e)=>{const t={};return n.forEach(i=>{e.forEach((s,r)=>{t[i+(r===0?"":r+1)]=s})}),t}};async function wl(n){if("Image"in globalThis)return new Promise(e=>{const t=new Image;t.onload=()=>{e(!0)},t.onerror=()=>{e(!1)},t.src=n});if("createImageBitmap"in globalThis&&"fetch"in globalThis){try{const e=await(await fetch(n)).blob();await createImageBitmap(e)}catch{return!1}return!0}return!1}const kp={extension:{type:I.DetectionParser,priority:1},test:async()=>wl("data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A="),add:async n=>[...n,"avif"],remove:async n=>n.filter(e=>e!=="avif")},Qo=["png","jpg","jpeg"],Ip={extension:{type:I.DetectionParser,priority:-1},test:()=>Promise.resolve(!0),add:async n=>[...n,...Qo],remove:async n=>n.filter(e=>!Qo.includes(e))},Ep="WorkerGlobalScope"in globalThis&&globalThis instanceof globalThis.WorkerGlobalScope;function Bs(n){return Ep?!1:document.createElement("video").canPlayType(n)!==""}const Dp={extension:{type:I.DetectionParser,priority:0},test:async()=>Bs("video/mp4"),add:async n=>[...n,"mp4","m4v"],remove:async n=>n.filter(e=>e!=="mp4"&&e!=="m4v")},Fp={extension:{type:I.DetectionParser,priority:0},test:async()=>Bs("video/ogg"),add:async n=>[...n,"ogv"],remove:async n=>n.filter(e=>e!=="ogv")},Bp={extension:{type:I.DetectionParser,priority:0},test:async()=>Bs("video/webm"),add:async n=>[...n,"webm"],remove:async n=>n.filter(e=>e!=="webm")},zp={extension:{type:I.DetectionParser,priority:0},test:async()=>wl("data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA="),add:async n=>[...n,"webp"],remove:async n=>n.filter(e=>e!=="webp")},Cl=class ms{constructor(){this.loadOptions={...ms.defaultOptions},this._parsers=[],this._parsersValidated=!1,this.parsers=new Proxy(this._parsers,{set:(e,t,i)=>(this._parsersValidated=!1,e[t]=i,!0)}),this.promiseCache={}}reset(){this._parsersValidated=!1,this.promiseCache={}}_getLoadPromiseAndParser(e,t){const i={promise:null,parser:null};return i.promise=(async()=>{var o,a;let s=null,r=null;if((t.parser||t.loadParser)&&(r=this._parserHash[t.parser||t.loadParser],t.loadParser&&nt(`[Assets] "loadParser" is deprecated, use "parser" instead for ${e}`),r||nt(`[Assets] specified load parser "${t.parser||t.loadParser}" not found while loading ${e}`)),!r){for(let h=0;h<this.parsers.length;h++){const l=this.parsers[h];if(l.load&&((o=l.test)!=null&&o.call(l,e,t,this))){r=l;break}}if(!r)return nt(`[Assets] ${e} could not be loaded as we don't know how to parse it, ensure the correct parser has been added`),null}s=await r.load(e,t,this),i.parser=r;for(let h=0;h<this.parsers.length;h++){const l=this.parsers[h];l.parse&&l.parse&&await((a=l.testParse)==null?void 0:a.call(l,s,t,this))&&(s=await l.parse(s,t,this)||s,i.parser=l)}return s})(),i}async load(e,t){this._parsersValidated||this._validateParsers();const i=typeof t=="function"?{...ms.defaultOptions,...this.loadOptions,onProgress:t}:{...ms.defaultOptions,...this.loadOptions,...t||{}},{onProgress:s,onError:r,strategy:o,retryCount:a,retryDelay:h}=i;let l=0;const c={},d=ws(e),u=Ot(e,m=>({alias:[m],src:m,data:{}})),p=u.reduce((m,y)=>m+(y.progressSize||1),0),g=u.map(async m=>{const y=Mt.toAbsolute(m.src);c[m.src]||(await this._loadAssetWithRetry(y,m,{onProgress:s,onError:r,strategy:o,retryCount:a,retryDelay:h},c),l+=m.progressSize||1,s&&s(l/p))});return await Promise.all(g),d?c[u[0].src]:c}async unload(e){const i=Ot(e,s=>({alias:[s],src:s})).map(async s=>{var a,h;const r=Mt.toAbsolute(s.src),o=this.promiseCache[r];if(o){const l=await o.promise;delete this.promiseCache[r],await((h=(a=o.parser)==null?void 0:a.unload)==null?void 0:h.call(a,l,s,this))}});await Promise.all(i)}_validateParsers(){this._parsersValidated=!0,this._parserHash=this._parsers.filter(e=>e.name||e.id).reduce((e,t)=>(!t.name&&!t.id?nt("[Assets] parser should have an id"):(e[t.name]||e[t.id])&&nt(`[Assets] parser id conflict "${t.id}"`),e[t.name]=t,t.id&&(e[t.id]=t),e),{})}async _loadAssetWithRetry(e,t,i,s){let r=0;const{onError:o,strategy:a,retryCount:h,retryDelay:l}=i,c=d=>new Promise(u=>setTimeout(u,d));for(;;)try{this.promiseCache[e]||(this.promiseCache[e]=this._getLoadPromiseAndParser(e,t)),s[t.src]=await this.promiseCache[e].promise;return}catch(d){delete this.promiseCache[e],delete s[t.src],r++;const u=a!=="retry"||r>h;if(a==="retry"&&!u){o&&o(d,t),await c(l);continue}if(a==="skip"){o&&o(d,t);return}o&&o(d,t);const p=new Error(`[Loader.load] Failed to load ${e}.
24
+ ${d}`);throw d instanceof Error&&d.stack&&(p.stack=d.stack),p}}};Cl.defaultOptions={onProgress:void 0,onError:void 0,strategy:"throw",retryCount:3,retryDelay:250};let Lp=Cl;function fe(n,e){if(Array.isArray(e)){for(const t of e)if(n.startsWith(`data:${t}`))return!0;return!1}return n.startsWith(`data:${e}`)}function li(n,e){const t=n.split("?")[0],i=Mt.extname(t).toLowerCase();return Array.isArray(e)?e.includes(i):i===e}const Op=".json",Wp="application/json",Gp={extension:{type:I.LoadParser,priority:pe.Low},name:"loadJson",id:"json",test(n){return fe(n,Wp)||li(n,Op)},async load(n){return await(await $.get().fetch(n)).json()}},Up=".txt",Hp="text/plain",Vp={name:"loadTxt",id:"text",extension:{type:I.LoadParser,priority:pe.Low,name:"loadTxt"},test(n){return fe(n,Hp)||li(n,Up)},async load(n){return await(await $.get().fetch(n)).text()}},Np=["normal","bold","100","200","300","400","500","600","700","800","900"],$p=[".ttf",".otf",".woff",".woff2"],Yp=["font/ttf","font/otf","font/woff","font/woff2"],Xp=/^(--|-?[A-Z_])[0-9A-Z_-]*$/i;function jp(n){const e=Mt.extname(n),s=Mt.basename(n,e).replace(/(-|_)/g," ").toLowerCase().split(" ").map(a=>a.charAt(0).toUpperCase()+a.slice(1));let r=s.length>0;for(const a of s)if(!a.match(Xp)){r=!1;break}let o=s.join(" ");return r||(o=`"${o.replace(/[\\"]/g,"\\$&")}"`),o}const Zp=/^[0-9A-Za-z%:/?#\[\]@!\$&'()\*\+,;=\-._~]*$/;function qp(n){return Zp.test(n)?n:encodeURI(n)}const Kp={extension:{type:I.LoadParser,priority:pe.Low},name:"loadWebFont",id:"web-font",test(n){return fe(n,Yp)||li(n,$p)},async load(n,e){var i,s,r;const t=$.get().getFontFaceSet();if(t){const o=[],a=((i=e.data)==null?void 0:i.family)??jp(n),h=((r=(s=e.data)==null?void 0:s.weights)==null?void 0:r.filter(c=>Np.includes(c)))??["normal"],l=e.data??{};for(let c=0;c<h.length;c++){const d=h[c],u=new FontFace(a,`url(${qp(n)})`,{...l,weight:d});await u.load(),t.add(u),o.push(u)}return xt.has(`${a}-and-url`)?xt.get(`${a}-and-url`).entries.push({url:n,faces:o}):xt.set(`${a}-and-url`,{entries:[{url:n,faces:o}]}),o.length===1?o[0]:o}return nt("[loadWebFont] FontFace API is not supported. Skipping loading font"),null},unload(n){const e=Array.isArray(n)?n:[n],t=e[0].family,i=xt.get(`${t}-and-url`),s=i.entries.find(r=>r.faces.some(o=>e.indexOf(o)!==-1));s.faces=s.faces.filter(r=>e.indexOf(r)===-1),s.faces.length===0&&(i.entries=i.entries.filter(r=>r!==s)),e.forEach(r=>{$.get().getFontFaceSet().delete(r)}),i.entries.length===0&&xt.remove(`${t}-and-url`)}};var Qp=tf,wn={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},Jp=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function tf(n){var e=[];return n.replace(Jp,function(t,i,s){var r=i.toLowerCase();for(s=sf(s),r=="m"&&s.length>2&&(e.push([i].concat(s.splice(0,2))),r="l",i=i=="m"?"l":"L");;){if(s.length==wn[r])return s.unshift(i),e.push(s);if(s.length<wn[r])throw new Error("malformed path data");e.push([i].concat(s.splice(0,wn[r])))}}),e}var ef=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function sf(n){var e=n.match(ef);return e?e.map(Number):[]}const nf=xh(Qp);function rf(n,e){const t=nf(n),i=[];let s=null,r=0,o=0;for(let a=0;a<t.length;a++){const h=t[a],l=h[0],c=h;switch(l){case"M":r=c[1],o=c[2],e.moveTo(r,o);break;case"m":r+=c[1],o+=c[2],e.moveTo(r,o);break;case"H":r=c[1],e.lineTo(r,o);break;case"h":r+=c[1],e.lineTo(r,o);break;case"V":o=c[1],e.lineTo(r,o);break;case"v":o+=c[1],e.lineTo(r,o);break;case"L":r=c[1],o=c[2],e.lineTo(r,o);break;case"l":r+=c[1],o+=c[2],e.lineTo(r,o);break;case"C":r=c[5],o=c[6],e.bezierCurveTo(c[1],c[2],c[3],c[4],r,o);break;case"c":e.bezierCurveTo(r+c[1],o+c[2],r+c[3],o+c[4],r+c[5],o+c[6]),r+=c[5],o+=c[6];break;case"S":r=c[3],o=c[4],e.bezierCurveToShort(c[1],c[2],r,o);break;case"s":e.bezierCurveToShort(r+c[1],o+c[2],r+c[3],o+c[4]),r+=c[3],o+=c[4];break;case"Q":r=c[3],o=c[4],e.quadraticCurveTo(c[1],c[2],r,o);break;case"q":e.quadraticCurveTo(r+c[1],o+c[2],r+c[3],o+c[4]),r+=c[3],o+=c[4];break;case"T":r=c[1],o=c[2],e.quadraticCurveToShort(r,o);break;case"t":r+=c[1],o+=c[2],e.quadraticCurveToShort(r,o);break;case"A":r=c[6],o=c[7],e.arcToSvg(c[1],c[2],c[3],c[4],c[5],r,o);break;case"a":r+=c[6],o+=c[7],e.arcToSvg(c[1],c[2],c[3],c[4],c[5],r,o);break;case"Z":case"z":e.closePath(),i.length>0&&(s=i.pop(),s?(r=s.startX,o=s.startY):(r=0,o=0)),s=null;break;default:nt(`Unknown SVG path command: ${l}`)}l!=="Z"&&l!=="z"&&s===null&&(s={startX:r,startY:o},i.push(s))}return e}class zs{constructor(e=0,t=0,i=0){this.type="circle",this.x=e,this.y=t,this.radius=i}clone(){return new zs(this.x,this.y,this.radius)}contains(e,t){if(this.radius<=0)return!1;const i=this.radius*this.radius;let s=this.x-e,r=this.y-t;return s*=s,r*=r,s+r<=i}strokeContains(e,t,i,s=.5){if(this.radius===0)return!1;const r=this.x-e,o=this.y-t,a=this.radius,h=(1-s)*i,l=Math.sqrt(r*r+o*o);return l<=a+h&&l>a-(i-h)}getBounds(e){return e||(e=new tt),e.x=this.x-this.radius,e.y=this.y-this.radius,e.width=this.radius*2,e.height=this.radius*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.radius=e.radius,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`}}class kr{constructor(e=0,t=0,i=0,s=0){this.type="ellipse",this.x=e,this.y=t,this.halfWidth=i,this.halfHeight=s}clone(){return new kr(this.x,this.y,this.halfWidth,this.halfHeight)}contains(e,t){if(this.halfWidth<=0||this.halfHeight<=0)return!1;let i=(e-this.x)/this.halfWidth,s=(t-this.y)/this.halfHeight;return i*=i,s*=s,i+s<=1}strokeContains(e,t,i,s=.5){const{halfWidth:r,halfHeight:o}=this;if(r<=0||o<=0)return!1;const a=i*(1-s),h=i-a,l=r-h,c=o-h,d=r+a,u=o+a,p=e-this.x,g=t-this.y,m=p*p/(l*l)+g*g/(c*c),y=p*p/(d*d)+g*g/(u*u);return m>1&&y<=1}getBounds(e){return e||(e=new tt),e.x=this.x-this.halfWidth,e.y=this.y-this.halfHeight,e.width=this.halfWidth*2,e.height=this.halfHeight*2,e}copyFrom(e){return this.x=e.x,this.y=e.y,this.halfWidth=e.halfWidth,this.halfHeight=e.halfHeight,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:Ellipse x=${this.x} y=${this.y} halfWidth=${this.halfWidth} halfHeight=${this.halfHeight}]`}}function of(n,e,t,i,s,r){const o=n-t,a=e-i,h=s-t,l=r-i,c=o*h+a*l,d=h*h+l*l;let u=-1;d!==0&&(u=c/d);let p,g;u<0?(p=t,g=i):u>1?(p=s,g=r):(p=t+u*h,g=i+u*l);const m=n-p,y=e-g;return m*m+y*y}let af,hf;class ke{constructor(...e){this.type="polygon";let t=Array.isArray(e[0])?e[0]:e;if(typeof t[0]!="number"){const i=[];for(let s=0,r=t.length;s<r;s++)i.push(t[s].x,t[s].y);t=i}this.points=t,this.closePath=!0}isClockwise(){let e=0;const t=this.points,i=t.length;for(let s=0;s<i;s+=2){const r=t[s],o=t[s+1],a=t[(s+2)%i],h=t[(s+3)%i];e+=(a-r)*(h+o)}return e<0}containsPolygon(e){const t=this.getBounds(af),i=e.getBounds(hf);if(!t.containsRect(i))return!1;const s=e.points;for(let r=0;r<s.length;r+=2){const o=s[r],a=s[r+1];if(!this.contains(o,a))return!1}return!0}clone(){const e=this.points.slice(),t=new ke(e);return t.closePath=this.closePath,t}contains(e,t){let i=!1;const s=this.points.length/2;for(let r=0,o=s-1;r<s;o=r++){const a=this.points[r*2],h=this.points[r*2+1],l=this.points[o*2],c=this.points[o*2+1];h>t!=c>t&&e<(l-a)*((t-h)/(c-h))+a&&(i=!i)}return i}strokeContains(e,t,i,s=.5){const r=i*i,o=r*(1-s),a=r-o,{points:h}=this,l=h.length-(this.closePath?0:2);for(let c=0;c<l;c+=2){const d=h[c],u=h[c+1],p=h[(c+2)%h.length],g=h[(c+3)%h.length],m=of(e,t,d,u,p,g),y=Math.sign((p-d)*(t-u)-(g-u)*(e-d));if(m<=(y<0?a:o))return!0}return!1}getBounds(e){e||(e=new tt);const t=this.points;let i=1/0,s=-1/0,r=1/0,o=-1/0;for(let a=0,h=t.length;a<h;a+=2){const l=t[a],c=t[a+1];i=l<i?l:i,s=l>s?l:s,r=c<r?c:r,o=c>o?c:o}return e.x=i,e.width=s-i,e.y=r,e.height=o-r,e}copyFrom(e){return this.points=e.points.slice(),this.closePath=e.closePath,this}copyTo(e){return e.copyFrom(this),e}toString(){return`[pixi.js/math:PolygoncloseStroke=${this.closePath}points=${this.points.reduce((e,t)=>`${e}, ${t}`,"")}]`}get lastX(){return this.points[this.points.length-2]}get lastY(){return this.points[this.points.length-1]}get x(){return V("8.11.0","Polygon.lastX is deprecated, please use Polygon.lastX instead."),this.points[this.points.length-2]}get y(){return V("8.11.0","Polygon.y is deprecated, please use Polygon.lastY instead."),this.points[this.points.length-1]}get startX(){return this.points[0]}get startY(){return this.points[1]}}const as=(n,e,t,i,s,r,o)=>{const a=n-t,h=e-i,l=Math.sqrt(a*a+h*h);return l>=s-r&&l<=s+o};class Ir{constructor(e=0,t=0,i=0,s=0,r=20){this.type="roundedRectangle",this.x=e,this.y=t,this.width=i,this.height=s,this.radius=r}getBounds(e){return e||(e=new tt),e.x=this.x,e.y=this.y,e.width=this.width,e.height=this.height,e}clone(){return new Ir(this.x,this.y,this.width,this.height,this.radius)}copyFrom(e){return this.x=e.x,this.y=e.y,this.width=e.width,this.height=e.height,this}copyTo(e){return e.copyFrom(this),e}contains(e,t){if(this.width<=0||this.height<=0)return!1;if(e>=this.x&&e<=this.x+this.width&&t>=this.y&&t<=this.y+this.height){const i=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(t>=this.y+i&&t<=this.y+this.height-i||e>=this.x+i&&e<=this.x+this.width-i)return!0;let s=e-(this.x+i),r=t-(this.y+i);const o=i*i;if(s*s+r*r<=o||(s=e-(this.x+this.width-i),s*s+r*r<=o)||(r=t-(this.y+this.height-i),s*s+r*r<=o)||(s=e-(this.x+i),s*s+r*r<=o))return!0}return!1}strokeContains(e,t,i,s=.5){const{x:r,y:o,width:a,height:h,radius:l}=this,c=i*(1-s),d=i-c,u=r+l,p=o+l,g=a-l*2,m=h-l*2,y=r+a,x=o+h;return(e>=r-c&&e<=r+d||e>=y-d&&e<=y+c)&&t>=p&&t<=p+m||(t>=o-c&&t<=o+d||t>=x-d&&t<=x+c)&&e>=u&&e<=u+g?!0:e<u&&t<p&&as(e,t,u,p,l,d,c)||e>y-l&&t<p&&as(e,t,y-l,p,l,d,c)||e>y-l&&t>x-l&&as(e,t,y-l,x-l,l,d,c)||e<u&&t>x-l&&as(e,t,u,x-l,l,d,c)}toString(){return`[pixi.js/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`}}const _l={};function lf(n,e,t){let i=2166136261;for(let s=0;s<e;s++)i^=n[s].uid,i=Math.imul(i,16777619),i>>>=0;return _l[i]||cf(n,e,i,t)}function cf(n,e,t,i){const s={};let r=0;for(let a=0;a<i;a++){const h=a<e?n[a]:G.EMPTY.source;s[r++]=h.source,s[r++]=h.style}const o=new Ai(s);return _l[t]=o,o}class Jo{constructor(e){typeof e=="number"?this.rawBinaryData=new ArrayBuffer(e):e instanceof Uint8Array?this.rawBinaryData=e.buffer:this.rawBinaryData=e,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData),this.size=this.rawBinaryData.byteLength}get int8View(){return this._int8View||(this._int8View=new Int8Array(this.rawBinaryData)),this._int8View}get uint8View(){return this._uint8View||(this._uint8View=new Uint8Array(this.rawBinaryData)),this._uint8View}get int16View(){return this._int16View||(this._int16View=new Int16Array(this.rawBinaryData)),this._int16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}get float64View(){return this._float64Array||(this._float64Array=new Float64Array(this.rawBinaryData)),this._float64Array}get bigUint64View(){return this._bigUint64Array||(this._bigUint64Array=new BigUint64Array(this.rawBinaryData)),this._bigUint64Array}view(e){return this[`${e}View`]}destroy(){this.rawBinaryData=null,this.uint32View=null,this.float32View=null,this.uint16View=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._int32View=null,this._float64Array=null,this._bigUint64Array=null}static sizeOf(e){switch(e){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${e} isn't a valid view type`)}}}function ta(n,e,t,i){if(t??(t=0),i??(i=Math.min(n.byteLength-t,e.byteLength)),!(t&7)&&!(i&7)){const s=i/8;new Float64Array(e,0,s).set(new Float64Array(n,t,s))}else if(!(t&3)&&!(i&3)){const s=i/4;new Float32Array(e,0,s).set(new Float32Array(n,t,s))}else new Uint8Array(e).set(new Uint8Array(n,t,i))}const df={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var uf=(n=>(n[n.DISABLED=0]="DISABLED",n[n.RENDERING_MASK_ADD=1]="RENDERING_MASK_ADD",n[n.MASK_ACTIVE=2]="MASK_ACTIVE",n[n.INVERSE_MASK_ACTIVE=3]="INVERSE_MASK_ACTIVE",n[n.RENDERING_MASK_REMOVE=4]="RENDERING_MASK_REMOVE",n[n.NONE=5]="NONE",n))(uf||{});function Cs(n,e){return e.alphaMode==="no-premultiply-alpha"&&df[n]||n}const pf=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
25
+ `);function ff(n){let e="";for(let t=0;t<n;++t)t>0&&(e+=`
26
+ else `),t<n-1&&(e+=`if(test == ${t}.0){}`);return e}function gf(n,e){if(n===0)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const t=e.createShader(e.FRAGMENT_SHADER);try{for(;;){const i=pf.replace(/%forloop%/gi,ff(n));if(e.shaderSource(t,i),e.compileShader(t),!e.getShaderParameter(t,e.COMPILE_STATUS))n=n/2|0;else break}}finally{e.deleteShader(t)}return n}let Ue=null;function mf(){var e;if(Ue)return Ue;const n=el();return Ue=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),Ue=gf(Ue,n),(e=n.getExtension("WEBGL_lose_context"))==null||e.loseContext(),Ue}class yf{constructor(){this.ids=Object.create(null),this.textures=[],this.count=0}clear(){for(let e=0;e<this.count;e++){const t=this.textures[e];this.textures[e]=null,this.ids[t.uid]=null}this.count=0}}class xf{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new yf,this.blendMode="normal",this.topology="triangle-strip",this.canBundle=!0}destroy(){this.textures=null,this.gpuBindGroup=null,this.bindGroup=null,this.batcher=null,this.elements=null}}const Ti=[];let _s=0;Vi.register({clear:()=>{if(Ti.length>0)for(const n of Ti)n&&n.destroy();Ti.length=0,_s=0}});function ea(){return _s>0?Ti[--_s]:new xf}function ia(n){n.elements=null,Ti[_s++]=n}let gi=0;const Pl=class Ml{constructor(e){this.uid=dt("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],e={...Ml.defaultOptions,...e},e.maxTextures||(V("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),e.maxTextures=mf());const{maxTextures:t,attributesInitialSize:i,indicesInitialSize:s}=e;this.attributeBuffer=new Jo(i*4),this.indexBuffer=new Uint16Array(s),this.maxTextures=t}begin(){this.elementSize=0,this.elementStart=0,this.indexSize=0,this.attributeSize=0;for(let e=0;e<this.batchIndex;e++)ia(this.batches[e]);this.batchIndex=0,this._batchIndexStart=0,this._batchIndexSize=0,this.dirty=!0}add(e){this._elements[this.elementSize++]=e,e._indexStart=this.indexSize,e._attributeStart=this.attributeSize,e._batcher=this,this.indexSize+=e.indexSize,this.attributeSize+=e.attributeSize*this.vertexSize}checkAndUpdateTexture(e,t){const i=e._batch.textures.ids[t._source.uid];return!i&&i!==0?!1:(e._textureId=i,e.texture=t,!0)}updateElement(e){this.dirty=!0;const t=this.attributeBuffer;e.packAsQuad?this.packQuadAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId):this.packAttributes(e,t.float32View,t.uint32View,e._attributeStart,e._textureId)}break(e){const t=this._elements;if(!t[this.elementStart])return;let i=ea(),s=i.textures;s.clear();const r=t[this.elementStart];let o=Cs(r.blendMode,r.texture._source),a=r.topology;this.attributeSize*4>this.attributeBuffer.size&&this._resizeAttributeBuffer(this.attributeSize*4),this.indexSize>this.indexBuffer.length&&this._resizeIndexBuffer(this.indexSize);const h=this.attributeBuffer.float32View,l=this.attributeBuffer.uint32View,c=this.indexBuffer;let d=this._batchIndexSize,u=this._batchIndexStart,p="startBatch",g=[];const m=this.maxTextures;for(let y=this.elementStart;y<this.elementSize;++y){const x=t[y];t[y]=null;const v=x.texture._source,b=Cs(x.blendMode,v),P=o!==b||a!==x.topology;if(v._batchTick===gi&&!P){x._textureId=v._textureBindLocation,d+=x.indexSize,x.packAsQuad?(this.packQuadAttributes(x,h,l,x._attributeStart,x._textureId),this.packQuadIndex(c,x._indexStart,x._attributeStart/this.vertexSize)):(this.packAttributes(x,h,l,x._attributeStart,x._textureId),this.packIndex(x,c,x._indexStart,x._attributeStart/this.vertexSize)),x._batch=i,g.push(x);continue}v._batchTick=gi,(s.count>=m||P)&&(this._finishBatch(i,u,d-u,s,o,a,e,p,g),p="renderBatch",u=d,o=b,a=x.topology,i=ea(),s=i.textures,s.clear(),g=[],++gi),x._textureId=v._textureBindLocation=s.count,s.ids[v.uid]=s.count,s.textures[s.count++]=v,x._batch=i,g.push(x),d+=x.indexSize,x.packAsQuad?(this.packQuadAttributes(x,h,l,x._attributeStart,x._textureId),this.packQuadIndex(c,x._indexStart,x._attributeStart/this.vertexSize)):(this.packAttributes(x,h,l,x._attributeStart,x._textureId),this.packIndex(x,c,x._indexStart,x._attributeStart/this.vertexSize))}s.count>0&&(this._finishBatch(i,u,d-u,s,o,a,e,p,g),u=d,++gi),this.elementStart=this.elementSize,this._batchIndexStart=u,this._batchIndexSize=d}_finishBatch(e,t,i,s,r,o,a,h,l){e.gpuBindGroup=null,e.bindGroup=null,e.action=h,e.batcher=this,e.textures=s,e.blendMode=r,e.topology=o,e.start=t,e.size=i,e.elements=l,++gi,this.batches[this.batchIndex++]=e,a.add(e)}finish(e){this.break(e)}ensureAttributeBuffer(e){e*4<=this.attributeBuffer.size||this._resizeAttributeBuffer(e*4)}ensureIndexBuffer(e){e<=this.indexBuffer.length||this._resizeIndexBuffer(e)}_resizeAttributeBuffer(e){const t=Math.max(e,this.attributeBuffer.size*2),i=new Jo(t);ta(this.attributeBuffer.rawBinaryData,i.rawBinaryData),this.attributeBuffer=i}_resizeIndexBuffer(e){const t=this.indexBuffer;let i=Math.max(e,t.length*1.5);i+=i%2;const s=i>65535?new Uint32Array(i):new Uint16Array(i);if(s.BYTES_PER_ELEMENT!==t.BYTES_PER_ELEMENT)for(let r=0;r<t.length;r++)s[r]=t[r];else ta(t.buffer,s.buffer);this.indexBuffer=s}packQuadIndex(e,t,i){e[t]=i+0,e[t+1]=i+1,e[t+2]=i+2,e[t+3]=i+0,e[t+4]=i+2,e[t+5]=i+3}packIndex(e,t,i,s){const r=e.indices,o=e.indexSize,a=e.indexOffset,h=e.attributeOffset;for(let l=0;l<o;l++)t[i++]=s+r[l+a]-h}destroy(e={}){var t;if(this.batches!==null){for(let i=0;i<this.batchIndex;i++)ia(this.batches[i]);this.batches=null,this.geometry.destroy(!0),this.geometry=null,e.shader&&((t=this.shader)==null||t.destroy(),this.shader=null);for(let i=0;i<this._elements.length;i++)this._elements[i]&&(this._elements[i]._batch=null);this._elements=null,this.indexBuffer=null,this.attributeBuffer.destroy(),this.attributeBuffer=null}}};Pl.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let Sf=Pl;var ft=(n=>(n[n.MAP_READ=1]="MAP_READ",n[n.MAP_WRITE=2]="MAP_WRITE",n[n.COPY_SRC=4]="COPY_SRC",n[n.COPY_DST=8]="COPY_DST",n[n.INDEX=16]="INDEX",n[n.VERTEX=32]="VERTEX",n[n.UNIFORM=64]="UNIFORM",n[n.STORAGE=128]="STORAGE",n[n.INDIRECT=256]="INDIRECT",n[n.QUERY_RESOLVE=512]="QUERY_RESOLVE",n[n.STATIC=1024]="STATIC",n))(ft||{});class le extends jt{constructor(e){let{data:t,size:i}=e;const{usage:s,label:r,shrinkToFit:o}=e;super(),this._gpuData=Object.create(null),this._gcLastUsed=-1,this.autoGarbageCollect=!0,this.uid=dt("buffer"),this._resourceType="buffer",this._resourceId=dt("resource"),this._touched=0,this._updateID=1,this._dataInt32=null,this.shrinkToFit=!0,this.destroyed=!1,t instanceof Array&&(t=new Float32Array(t)),this._data=t,i??(i=t==null?void 0:t.byteLength);const a=!!t;this.descriptor={size:i,usage:s,mappedAtCreation:a,label:r},this.shrinkToFit=o??!0}get data(){return this._data}set data(e){this.setDataWithSize(e,e.length,!0)}get dataInt32(){return this._dataInt32||(this._dataInt32=new Int32Array(this.data.buffer)),this._dataInt32}get static(){return!!(this.descriptor.usage&ft.STATIC)}set static(e){e?this.descriptor.usage|=ft.STATIC:this.descriptor.usage&=~ft.STATIC}setDataWithSize(e,t,i){if(this._updateID++,this._updateSize=t*e.BYTES_PER_ELEMENT,this._data===e){i&&this.emit("update",this);return}const s=this._data;if(this._data=e,this._dataInt32=null,!s||s.length!==e.length){!this.shrinkToFit&&s&&e.byteLength<s.byteLength?i&&this.emit("update",this):(this.descriptor.size=e.byteLength,this._resourceId=dt("resource"),this.emit("change",this));return}i&&this.emit("update",this)}update(e){this._updateSize=e??this._updateSize,this._updateID++,this.emit("update",this)}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(){this.destroyed=!0,this.unload(),this.emit("destroy",this),this.emit("change",this),this._data=null,this.descriptor=null,this.removeAllListeners()}}function Al(n,e){if(!(n instanceof le)){let t=e?ft.INDEX:ft.VERTEX;n instanceof Array&&(e?(n=new Uint32Array(n),t=ft.INDEX|ft.COPY_DST):(n=new Float32Array(n),t=ft.VERTEX|ft.COPY_DST)),n=new le({data:n,label:e?"index-mesh-buffer":"vertex-mesh-buffer",usage:t})}return n}function vf(n,e,t){const i=n.getAttribute(e);if(!i)return t.minX=0,t.minY=0,t.maxX=0,t.maxY=0,t;const s=i.buffer.data;let r=1/0,o=1/0,a=-1/0,h=-1/0;const l=s.BYTES_PER_ELEMENT,c=(i.offset||0)/l,d=(i.stride||2*4)/l;for(let u=c;u<s.length;u+=d){const p=s[u],g=s[u+1];p>a&&(a=p),g>h&&(h=g),p<r&&(r=p),g<o&&(o=g)}return t.minX=r,t.minY=o,t.maxX=a,t.maxY=h,t}function bf(n){return(n instanceof le||Array.isArray(n)||n.BYTES_PER_ELEMENT)&&(n={buffer:n}),n.buffer=Al(n.buffer,!1),n}class Oi extends jt{constructor(e={}){super(),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=dt("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new Ft,this._boundsDirty=!0;const{attributes:t,indexBuffer:i,topology:s}=e;if(this.buffers=[],this.attributes={},t)for(const r in t)this.addAttribute(r,t[r]);this.instanceCount=e.instanceCount??1,i&&this.addIndex(i),this.topology=s||"triangle-list"}onBufferUpdate(){this._boundsDirty=!0,this.emit("update",this)}getAttribute(e){return this.attributes[e]}getIndex(){return this.indexBuffer}getBuffer(e){return this.getAttribute(e).buffer}getSize(){for(const e in this.attributes){const t=this.attributes[e];return t.buffer.data.length/(t.stride/4||t.size)}return 0}addAttribute(e,t){const i=bf(t);this.buffers.indexOf(i.buffer)===-1&&(this.buffers.push(i.buffer),i.buffer.on("update",this.onBufferUpdate,this),i.buffer.on("change",this.onBufferUpdate,this)),this.attributes[e]=i}addIndex(e){this.indexBuffer=Al(e,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,vf(this,"aPosition",this._bounds)):this._bounds}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(e=!1){var t;this.emit("destroy",this),this.removeAllListeners(),e&&this.buffers.forEach(i=>i.destroy()),this.unload(),(t=this.indexBuffer)==null||t.destroy(),this.attributes=null,this.buffers=null,this.indexBuffer=null,this._bounds=null}}const wf=new Float32Array(1),Cf=new Uint32Array(1);class _f extends Oi{constructor(){const t=new le({data:wf,label:"attribute-batch-buffer",usage:ft.VERTEX|ft.COPY_DST,shrinkToFit:!1}),i=new le({data:Cf,label:"index-batch-buffer",usage:ft.INDEX|ft.COPY_DST,shrinkToFit:!1}),s=6*4;super({attributes:{aPosition:{buffer:t,format:"float32x2",stride:s,offset:0},aUV:{buffer:t,format:"float32x2",stride:s,offset:2*4},aColor:{buffer:t,format:"unorm8x4",stride:s,offset:4*4},aTextureIdAndRound:{buffer:t,format:"uint16x2",stride:s,offset:5*4}},indexBuffer:i})}}function sa(n,e,t){if(n)for(const i in n){const s=i.toLocaleLowerCase(),r=e[s];if(r){let o=n[i];i==="header"&&(o=o.replace(/@in\s+[^;]+;\s*/g,"").replace(/@out\s+[^;]+;\s*/g,"")),t&&r.push(`//----${t}----//`),r.push(o)}else nt(`${i} placement hook does not exist in shader`)}}const Pf=/\{\{(.*?)\}\}/g;function na(n){var i;const e={};return(((i=n.match(Pf))==null?void 0:i.map(s=>s.replace(/[{()}]/g,"")))??[]).forEach(s=>{e[s]=[]}),e}function ra(n,e){let t;const i=/@in\s+([^;]+);/g;for(;(t=i.exec(n))!==null;)e.push(t[1])}function oa(n,e,t=!1){const i=[];ra(e,i),n.forEach(a=>{a.header&&ra(a.header,i)});const s=i;t&&s.sort();const r=s.map((a,h)=>` @location(${h}) ${a},`).join(`
27
+ `);let o=e.replace(/@in\s+[^;]+;\s*/g,"");return o=o.replace("{{in}}",`
28
+ ${r}
29
+ `),o}function aa(n,e){let t;const i=/@out\s+([^;]+);/g;for(;(t=i.exec(n))!==null;)e.push(t[1])}function Mf(n){const t=/\b(\w+)\s*:/g.exec(n);return t?t[1]:""}function Af(n){const e=/@.*?\s+/g;return n.replace(e,"")}function Tf(n,e){const t=[];aa(e,t),n.forEach(h=>{h.header&&aa(h.header,t)});let i=0;const s=t.sort().map(h=>h.indexOf("builtin")>-1?h:`@location(${i++}) ${h}`).join(`,
30
+ `),r=t.sort().map(h=>` var ${Af(h)};`).join(`
31
+ `),o=`return VSOutput(
32
+ ${t.sort().map(h=>` ${Mf(h)}`).join(`,
33
+ `)});`;let a=e.replace(/@out\s+[^;]+;\s*/g,"");return a=a.replace("{{struct}}",`
34
+ ${s}
35
+ `),a=a.replace("{{start}}",`
36
+ ${r}
37
+ `),a=a.replace("{{return}}",`
38
+ ${o}
39
+ `),a}function ha(n,e){let t=n;for(const i in e){const s=e[i];s.join(`
40
+ `).length?t=t.replace(`{{${i}}}`,`//-----${i} START-----//
41
+ ${s.join(`
42
+ `)}
43
+ //----${i} FINISH----//`):t=t.replace(`{{${i}}}`,"")}return t}const he=Object.create(null),Cn=new Map;let Rf=0;function kf({template:n,bits:e}){const t=Tl(n,e);if(he[t])return he[t];const{vertex:i,fragment:s}=Ef(n,e);return he[t]=Rl(i,s,e),he[t]}function If({template:n,bits:e}){const t=Tl(n,e);return he[t]||(he[t]=Rl(n.vertex,n.fragment,e)),he[t]}function Ef(n,e){const t=e.map(o=>o.vertex).filter(o=>!!o),i=e.map(o=>o.fragment).filter(o=>!!o);let s=oa(t,n.vertex,!0);s=Tf(t,s);const r=oa(i,n.fragment,!0);return{vertex:s,fragment:r}}function Tl(n,e){return e.map(t=>(Cn.has(t)||Cn.set(t,Rf++),Cn.get(t))).sort((t,i)=>t-i).join("-")+n.vertex+n.fragment}function Rl(n,e,t){const i=na(n),s=na(e);return t.forEach(r=>{sa(r.vertex,i,r.name),sa(r.fragment,s,r.name)}),{vertex:ha(n,i),fragment:ha(e,s)}}const Df=`
44
+ @in aPosition: vec2<f32>;
45
+ @in aUV: vec2<f32>;
46
+
47
+ @out @builtin(position) vPosition: vec4<f32>;
48
+ @out vUV : vec2<f32>;
49
+ @out vColor : vec4<f32>;
50
+
51
+ {{header}}
52
+
53
+ struct VSOutput {
54
+ {{struct}}
55
+ };
56
+
57
+ @vertex
58
+ fn main( {{in}} ) -> VSOutput {
59
+
60
+ var worldTransformMatrix = globalUniforms.uWorldTransformMatrix;
61
+ var modelMatrix = mat3x3<f32>(
62
+ 1.0, 0.0, 0.0,
63
+ 0.0, 1.0, 0.0,
64
+ 0.0, 0.0, 1.0
65
+ );
66
+ var position = aPosition;
67
+ var uv = aUV;
68
+
69
+ {{start}}
70
+
71
+ vColor = vec4<f32>(1., 1., 1., 1.);
72
+
73
+ {{main}}
74
+
75
+ vUV = uv;
76
+
77
+ var modelViewProjectionMatrix = globalUniforms.uProjectionMatrix * worldTransformMatrix * modelMatrix;
78
+
79
+ vPosition = vec4<f32>((modelViewProjectionMatrix * vec3<f32>(position, 1.0)).xy, 0.0, 1.0);
80
+
81
+ vColor *= globalUniforms.uWorldColorAlpha;
82
+
83
+ {{end}}
84
+
85
+ {{return}}
86
+ };
87
+ `,Ff=`
88
+ @in vUV : vec2<f32>;
89
+ @in vColor : vec4<f32>;
90
+
91
+ {{header}}
92
+
93
+ @fragment
94
+ fn main(
95
+ {{in}}
96
+ ) -> @location(0) vec4<f32> {
97
+
98
+ {{start}}
99
+
100
+ var outColor:vec4<f32>;
101
+
102
+ {{main}}
103
+
104
+ var finalColor:vec4<f32> = outColor * vColor;
105
+
106
+ {{end}}
107
+
108
+ return finalColor;
109
+ };
110
+ `,Bf=`
111
+ in vec2 aPosition;
112
+ in vec2 aUV;
113
+
114
+ out vec4 vColor;
115
+ out vec2 vUV;
116
+
117
+ {{header}}
118
+
119
+ void main(void){
120
+
121
+ mat3 worldTransformMatrix = uWorldTransformMatrix;
122
+ mat3 modelMatrix = mat3(
123
+ 1.0, 0.0, 0.0,
124
+ 0.0, 1.0, 0.0,
125
+ 0.0, 0.0, 1.0
126
+ );
127
+ vec2 position = aPosition;
128
+ vec2 uv = aUV;
129
+
130
+ {{start}}
131
+
132
+ vColor = vec4(1.);
133
+
134
+ {{main}}
135
+
136
+ vUV = uv;
137
+
138
+ mat3 modelViewProjectionMatrix = uProjectionMatrix * worldTransformMatrix * modelMatrix;
139
+
140
+ gl_Position = vec4((modelViewProjectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);
141
+
142
+ vColor *= uWorldColorAlpha;
143
+
144
+ {{end}}
145
+ }
146
+ `,zf=`
147
+
148
+ in vec4 vColor;
149
+ in vec2 vUV;
150
+
151
+ out vec4 finalColor;
152
+
153
+ {{header}}
154
+
155
+ void main(void) {
156
+
157
+ {{start}}
158
+
159
+ vec4 outColor;
160
+
161
+ {{main}}
162
+
163
+ finalColor = outColor * vColor;
164
+
165
+ {{end}}
166
+ }
167
+ `,Lf={name:"global-uniforms-bit",vertex:{header:`
168
+ struct GlobalUniforms {
169
+ uProjectionMatrix:mat3x3<f32>,
170
+ uWorldTransformMatrix:mat3x3<f32>,
171
+ uWorldColorAlpha: vec4<f32>,
172
+ uResolution: vec2<f32>,
173
+ }
174
+
175
+ @group(0) @binding(0) var<uniform> globalUniforms : GlobalUniforms;
176
+ `}},Of={name:"global-uniforms-bit",vertex:{header:`
177
+ uniform mat3 uProjectionMatrix;
178
+ uniform mat3 uWorldTransformMatrix;
179
+ uniform vec4 uWorldColorAlpha;
180
+ uniform vec2 uResolution;
181
+ `}};function kl({bits:n,name:e}){const t=kf({template:{fragment:Ff,vertex:Df},bits:[Lf,...n]});return de.from({name:e,vertex:{source:t.vertex,entryPoint:"main"},fragment:{source:t.fragment,entryPoint:"main"}})}function Il({bits:n,name:e}){return new ii({name:e,...If({template:{vertex:Bf,fragment:zf},bits:[Of,...n]})})}const Wf={name:"color-bit",vertex:{header:`
182
+ @in aColor: vec4<f32>;
183
+ `,main:`
184
+ vColor *= vec4<f32>(aColor.rgb * aColor.a, aColor.a);
185
+ `}},Gf={name:"color-bit",vertex:{header:`
186
+ in vec4 aColor;
187
+ `,main:`
188
+ vColor *= vec4(aColor.rgb * aColor.a, aColor.a);
189
+ `}},_n={};function Uf(n){const e=[];if(n===1)e.push("@group(1) @binding(0) var textureSource1: texture_2d<f32>;"),e.push("@group(1) @binding(1) var textureSampler1: sampler;");else{let t=0;for(let i=0;i<n;i++)e.push(`@group(1) @binding(${t++}) var textureSource${i+1}: texture_2d<f32>;`),e.push(`@group(1) @binding(${t++}) var textureSampler${i+1}: sampler;`)}return e.join(`
190
+ `)}function Hf(n){const e=[];if(n===1)e.push("outColor = textureSampleGrad(textureSource1, textureSampler1, vUV, uvDx, uvDy);");else{e.push("switch vTextureId {");for(let t=0;t<n;t++)t===n-1?e.push(" default:{"):e.push(` case ${t}:{`),e.push(` outColor = textureSampleGrad(textureSource${t+1}, textureSampler${t+1}, vUV, uvDx, uvDy);`),e.push(" break;}");e.push("}")}return e.join(`
191
+ `)}function Vf(n){return _n[n]||(_n[n]={name:"texture-batch-bit",vertex:{header:`
192
+ @in aTextureIdAndRound: vec2<u32>;
193
+ @out @interpolate(flat) vTextureId : u32;
194
+ `,main:`
195
+ vTextureId = aTextureIdAndRound.y;
196
+ `,end:`
197
+ if(aTextureIdAndRound.x == 1)
198
+ {
199
+ vPosition = vec4<f32>(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
200
+ }
201
+ `},fragment:{header:`
202
+ @in @interpolate(flat) vTextureId: u32;
203
+
204
+ ${Uf(n)}
205
+ `,main:`
206
+ var uvDx = dpdx(vUV);
207
+ var uvDy = dpdy(vUV);
208
+
209
+ ${Hf(n)}
210
+ `}}),_n[n]}const Pn={};function Nf(n){const e=[];for(let t=0;t<n;t++)t>0&&e.push("else"),t<n-1&&e.push(`if(vTextureId < ${t}.5)`),e.push("{"),e.push(` outColor = texture(uTextures[${t}], vUV);`),e.push("}");return e.join(`
211
+ `)}function $f(n){return Pn[n]||(Pn[n]={name:"texture-batch-bit",vertex:{header:`
212
+ in vec2 aTextureIdAndRound;
213
+ out float vTextureId;
214
+
215
+ `,main:`
216
+ vTextureId = aTextureIdAndRound.y;
217
+ `,end:`
218
+ if(aTextureIdAndRound.x == 1.)
219
+ {
220
+ gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
221
+ }
222
+ `},fragment:{header:`
223
+ in float vTextureId;
224
+
225
+ uniform sampler2D uTextures[${n}];
226
+
227
+ `,main:`
228
+
229
+ ${Nf(n)}
230
+ `}}),Pn[n]}const El={name:"round-pixels-bit",vertex:{header:`
231
+ fn roundPixels(position: vec2<f32>, targetSize: vec2<f32>) -> vec2<f32>
232
+ {
233
+ return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
234
+ }
235
+ `}},Dl={name:"round-pixels-bit",vertex:{header:`
236
+ vec2 roundPixels(vec2 position, vec2 targetSize)
237
+ {
238
+ return (floor(((position * 0.5 + 0.5) * targetSize) + 0.5) / targetSize) * 2.0 - 1.0;
239
+ }
240
+ `}},la={};function Yf(n){let e=la[n];if(e)return e;const t=new Int32Array(n);for(let i=0;i<n;i++)t[i]=i;return e=la[n]=new si({uTextures:{value:t,type:"i32",size:n}},{isStatic:!0}),e}class ca extends Be{constructor(e){const t=Il({name:"batch",bits:[Gf,$f(e),Dl]}),i=kl({name:"batch",bits:[Wf,Vf(e),El]});super({glProgram:t,gpuProgram:i,resources:{batchSamplers:Yf(e)}}),this.maxTextures=e}}let mi=null;const Fl=class Bl extends Sf{constructor(e){super(e),this.geometry=new _f,this.name=Bl.extension.name,this.vertexSize=6,mi??(mi=new ca(e.maxTextures)),this.shader=mi}packAttributes(e,t,i,s,r){const o=r<<16|e.roundPixels&65535,a=e.transform,h=a.a,l=a.b,c=a.c,d=a.d,u=a.tx,p=a.ty,{positions:g,uvs:m}=e,y=e.color,x=e.attributeOffset,S=x+e.attributeSize;for(let v=x;v<S;v++){const b=v*2,P=g[b],C=g[b+1];t[s++]=h*P+c*C+u,t[s++]=d*C+l*P+p,t[s++]=m[b],t[s++]=m[b+1],i[s++]=y,i[s++]=o}}packQuadAttributes(e,t,i,s,r){const o=e.texture,a=e.transform,h=a.a,l=a.b,c=a.c,d=a.d,u=a.tx,p=a.ty,g=e.bounds,m=g.maxX,y=g.minX,x=g.maxY,S=g.minY,v=o.uvs,b=e.color,P=r<<16|e.roundPixels&65535;t[s+0]=h*y+c*S+u,t[s+1]=d*S+l*y+p,t[s+2]=v.x0,t[s+3]=v.y0,i[s+4]=b,i[s+5]=P,t[s+6]=h*m+c*S+u,t[s+7]=d*S+l*m+p,t[s+8]=v.x1,t[s+9]=v.y1,i[s+10]=b,i[s+11]=P,t[s+12]=h*m+c*x+u,t[s+13]=d*x+l*m+p,t[s+14]=v.x2,t[s+15]=v.y2,i[s+16]=b,i[s+17]=P,t[s+18]=h*y+c*x+u,t[s+19]=d*x+l*y+p,t[s+20]=v.x3,t[s+21]=v.y3,i[s+22]=b,i[s+23]=P}_updateMaxTextures(e){this.shader.maxTextures!==e&&(mi=new ca(e),this.shader=mi)}destroy(){this.shader=null,super.destroy()}};Fl.extension={type:[I.Batcher],name:"default"};let Xf=Fl;class ci{constructor(e){this.items=Object.create(null);const{renderer:t,type:i,onUnload:s,priority:r,name:o}=e;this._renderer=t,t.gc.addResourceHash(this,"items",i,r??0),this._onUnload=s,this.name=o}add(e){return this.items[e.uid]?!1:(this.items[e.uid]=e,e.once("unload",this.remove,this),e._gcLastUsed=this._renderer.gc.now,!0)}remove(e,...t){var s;if(!this.items[e.uid])return;const i=e._gpuData[this._renderer.uid];i&&((s=this._onUnload)==null||s.call(this,e,...t),i.destroy(),e._gpuData[this._renderer.uid]=null,this.items[e.uid]=null)}removeAll(...e){Object.values(this.items).forEach(t=>t&&this.remove(t,...e))}destroy(...e){this.removeAll(...e),this.items=Object.create(null),this._renderer=null,this._onUnload=null}}function jf(n,e,t,i,s,r,o,a=null){let h=0;t*=e,s*=r;const l=a.a,c=a.b,d=a.c,u=a.d,p=a.tx,g=a.ty;for(;h<o;){const m=n[t],y=n[t+1];i[s]=l*m+d*y+p,i[s+1]=c*m+u*y+g,s+=r,t+=e,h++}}function Zf(n,e,t,i){let s=0;for(e*=t;s<i;)n[e]=0,n[e+1]=0,e+=t,s++}function zl(n,e,t,i,s){const r=e.a,o=e.b,a=e.c,h=e.d,l=e.tx,c=e.ty;t||(t=0),i||(i=2),s||(s=n.length/i-t);let d=t*i;for(let u=0;u<s;u++){const p=n[d],g=n[d+1];n[d]=r*p+a*g+l,n[d+1]=o*p+h*g+c,d+=i}}const qf=new H;class Er{constructor(){this.packAsQuad=!1,this.batcherName="default",this.topology="triangle-list",this.applyTransform=!0,this.roundPixels=0,this._batcher=null,this._batch=null}get uvs(){return this.geometryData.uvs}get positions(){return this.geometryData.vertices}get indices(){return this.geometryData.indices}get blendMode(){return this.renderable&&this.applyTransform?this.renderable.groupBlendMode:"normal"}get color(){const e=this.baseColor,t=e>>16|e&65280|(e&255)<<16,i=this.renderable;return i?Pr(t,i.groupColor)+(this.alpha*i.groupAlpha*255<<24):t+(this.alpha*255<<24)}get transform(){var e;return((e=this.renderable)==null?void 0:e.groupTransform)||qf}copyTo(e){e.indexOffset=this.indexOffset,e.indexSize=this.indexSize,e.attributeOffset=this.attributeOffset,e.attributeSize=this.attributeSize,e.baseColor=this.baseColor,e.alpha=this.alpha,e.texture=this.texture,e.geometryData=this.geometryData,e.topology=this.topology}reset(){this.applyTransform=!0,this.renderable=null,this.topology="triangle-list"}destroy(){this.renderable=null,this.texture=null,this.geometryData=null,this._batcher=null,this._batch=null}}const Wi={extension:{type:I.ShapeBuilder,name:"circle"},build(n,e){let t,i,s,r,o,a;if(n.type==="circle"){const b=n;if(o=a=b.radius,o<=0)return!1;t=b.x,i=b.y,s=r=0}else if(n.type==="ellipse"){const b=n;if(o=b.halfWidth,a=b.halfHeight,o<=0||a<=0)return!1;t=b.x,i=b.y,s=r=0}else{const b=n,P=b.width/2,C=b.height/2;t=b.x+P,i=b.y+C,o=a=Math.max(0,Math.min(b.radius,Math.min(P,C))),s=P-o,r=C-a}if(s<0||r<0)return!1;const h=Math.ceil(2.3*Math.sqrt(o+a)),l=h*8+(s?4:0)+(r?4:0);if(l===0)return!1;if(h===0)return e[0]=e[6]=t+s,e[1]=e[3]=i+r,e[2]=e[4]=t-s,e[5]=e[7]=i-r,!0;let c=0,d=h*4+(s?2:0)+2,u=d,p=l,g=s+o,m=r,y=t+g,x=t-g,S=i+m;if(e[c++]=y,e[c++]=S,e[--d]=S,e[--d]=x,r){const b=i-m;e[u++]=x,e[u++]=b,e[--p]=b,e[--p]=y}for(let b=1;b<h;b++){const P=Math.PI/2*(b/h),C=s+Math.cos(P)*o,_=r+Math.sin(P)*a,R=t+C,M=t-C,T=i+_,A=i-_;e[c++]=R,e[c++]=T,e[--d]=T,e[--d]=M,e[u++]=M,e[u++]=A,e[--p]=A,e[--p]=R}g=s,m=r+a,y=t+g,x=t-g,S=i+m;const v=i-m;return e[c++]=y,e[c++]=S,e[--p]=v,e[--p]=y,s&&(e[c++]=x,e[c++]=S,e[--p]=v,e[--p]=x),!0},triangulate(n,e,t,i,s,r){if(n.length===0)return;let o=0,a=0;for(let c=0;c<n.length;c+=2)o+=n[c],a+=n[c+1];o/=n.length/2,a/=n.length/2;let h=i;e[h*t]=o,e[h*t+1]=a;const l=h++;for(let c=0;c<n.length;c+=2)e[h*t]=n[c],e[h*t+1]=n[c+1],c>0&&(s[r++]=h,s[r++]=l,s[r++]=h-1),h++;s[r++]=l+1,s[r++]=l,s[r++]=h-1}},Kf={...Wi,extension:{...Wi.extension,name:"ellipse"}},Qf={...Wi,extension:{...Wi.extension,name:"roundedRectangle"}},Ll=1e-4,da=1e-4;function Jf(n){const e=n.length;if(e<6)return 1;let t=0;for(let i=0,s=n[e-2],r=n[e-1];i<e;i+=2){const o=n[i],a=n[i+1];t+=(o-s)*(a+r),s=o,r=a}return t<0?-1:1}function ua(n,e,t,i,s,r,o,a){const h=n-t*s,l=e-i*s,c=n+t*r,d=e+i*r;let u,p;o?(u=i,p=-t):(u=-i,p=t);const g=h+u,m=l+p,y=c+u,x=d+p;return a.push(g,m),a.push(y,x),2}function Se(n,e,t,i,s,r,o,a){const h=t-n,l=i-e;let c=Math.atan2(h,l),d=Math.atan2(s-n,r-e);a&&c<d?c+=Math.PI*2:!a&&c>d&&(d+=Math.PI*2);let u=c;const p=d-c,g=Math.abs(p),m=Math.sqrt(h*h+l*l),y=(15*g*Math.sqrt(m)/Math.PI>>0)+1,x=p/y;if(u+=x,a){o.push(n,e),o.push(t,i);for(let S=1,v=u;S<y;S++,v+=x)o.push(n,e),o.push(n+Math.sin(v)*m,e+Math.cos(v)*m);o.push(n,e),o.push(s,r)}else{o.push(t,i),o.push(n,e);for(let S=1,v=u;S<y;S++,v+=x)o.push(n+Math.sin(v)*m,e+Math.cos(v)*m),o.push(n,e);o.push(s,r),o.push(n,e)}return y*2}function tg(n,e,t,i,s,r){const o=Ll;if(n.length===0)return;const a=e;let h=a.alignment;if(e.alignment!==.5){let z=Jf(n);h=(h-.5)*z+.5}const l=new J(n[0],n[1]),c=new J(n[n.length-2],n[n.length-1]),d=i,u=Math.abs(l.x-c.x)<o&&Math.abs(l.y-c.y)<o;if(d){n=n.slice(),u&&(n.pop(),n.pop(),c.set(n[n.length-2],n[n.length-1]));const z=(l.x+c.x)*.5,Z=(c.y+l.y)*.5;n.unshift(z,Z),n.push(z,Z)}const p=s,g=n.length/2;let m=n.length;const y=p.length/2,x=a.width/2,S=x*x,v=a.miterLimit*a.miterLimit;let b=n[0],P=n[1],C=n[2],_=n[3],R=0,M=0,T=-(P-_),A=b-C,E=0,D=0,B=Math.sqrt(T*T+A*A);T/=B,A/=B,T*=x,A*=x;const j=h,k=(1-j)*2,F=j*2;d||(a.cap==="round"?m+=Se(b-T*(k-F)*.5,P-A*(k-F)*.5,b-T*k,P-A*k,b+T*F,P+A*F,p,!0)+2:a.cap==="square"&&(m+=ua(b,P,T,A,k,F,!0,p))),p.push(b-T*k,P-A*k),p.push(b+T*F,P+A*F);for(let z=1;z<g-1;++z){b=n[(z-1)*2],P=n[(z-1)*2+1],C=n[z*2],_=n[z*2+1],R=n[(z+1)*2],M=n[(z+1)*2+1],T=-(P-_),A=b-C,B=Math.sqrt(T*T+A*A),T/=B,A/=B,T*=x,A*=x,E=-(_-M),D=C-R,B=Math.sqrt(E*E+D*D),E/=B,D/=B,E*=x,D*=x;const Z=C-b,Y=P-_,ht=C-R,wt=M-_,Ct=Z*ht+Y*wt,Et=Y*ht-wt*Z,Ut=Et<0;if(Math.abs(Et)<.001*Math.abs(Ct)){p.push(C-T*k,_-A*k),p.push(C+T*F,_+A*F),Ct>=0&&(a.join==="round"?m+=Se(C,_,C-T*k,_-A*k,C-E*k,_-D*k,p,!1)+4:m+=2,p.push(C-E*F,_-D*F),p.push(C+E*k,_+D*k));continue}const Yi=(-T+b)*(-A+_)-(-T+C)*(-A+P),ro=(-E+R)*(-D+_)-(-E+C)*(-D+M),Xi=(Z*ro-ht*Yi)/Et,ji=(wt*Yi-Y*ro)/Et,qs=(Xi-C)*(Xi-C)+(ji-_)*(ji-_),ge=C+(Xi-C)*k,me=_+(ji-_)*k,ye=C-(Xi-C)*F,xe=_-(ji-_)*F,Zc=Math.min(Z*Z+Y*Y,ht*ht+wt*wt),oo=Ut?k:F,qc=Zc+oo*oo*S;qs<=qc?a.join==="bevel"||qs/S>v?(Ut?(p.push(ge,me),p.push(C+T*F,_+A*F),p.push(ge,me),p.push(C+E*F,_+D*F)):(p.push(C-T*k,_-A*k),p.push(ye,xe),p.push(C-E*k,_-D*k),p.push(ye,xe)),m+=2):a.join==="round"?Ut?(p.push(ge,me),p.push(C+T*F,_+A*F),m+=Se(C,_,C+T*F,_+A*F,C+E*F,_+D*F,p,!0)+4,p.push(ge,me),p.push(C+E*F,_+D*F)):(p.push(C-T*k,_-A*k),p.push(ye,xe),m+=Se(C,_,C-T*k,_-A*k,C-E*k,_-D*k,p,!1)+4,p.push(C-E*k,_-D*k),p.push(ye,xe)):(p.push(ge,me),p.push(ye,xe)):(p.push(C-T*k,_-A*k),p.push(C+T*F,_+A*F),a.join==="round"?Ut?m+=Se(C,_,C+T*F,_+A*F,C+E*F,_+D*F,p,!0)+2:m+=Se(C,_,C-T*k,_-A*k,C-E*k,_-D*k,p,!1)+2:a.join==="miter"&&qs/S<=v&&(Ut?(p.push(ye,xe),p.push(ye,xe)):(p.push(ge,me),p.push(ge,me)),m+=2),p.push(C-E*k,_-D*k),p.push(C+E*F,_+D*F),m+=2)}b=n[(g-2)*2],P=n[(g-2)*2+1],C=n[(g-1)*2],_=n[(g-1)*2+1],T=-(P-_),A=b-C,B=Math.sqrt(T*T+A*A),T/=B,A/=B,T*=x,A*=x,p.push(C-T*k,_-A*k),p.push(C+T*F,_+A*F),d||(a.cap==="round"?m+=Se(C-T*(k-F)*.5,_-A*(k-F)*.5,C-T*k,_-A*k,C+T*F,_+A*F,p,!1)+2:a.cap==="square"&&(m+=ua(C,_,T,A,k,F,!1,p)));const ot=da*da;for(let z=y;z<m+y-2;++z)b=p[z*2],P=p[z*2+1],C=p[(z+1)*2],_=p[(z+1)*2+1],R=p[(z+2)*2],M=p[(z+2)*2+1],!(Math.abs(b*(_-M)+C*(M-P)+R*(P-_))<ot)&&r.push(z,z+1,z+2)}function eg(n,e,t,i){const s=Ll;if(n.length===0)return;const r=n[0],o=n[1],a=n[n.length-2],h=n[n.length-1],l=e||Math.abs(r-a)<s&&Math.abs(o-h)<s,c=t,d=n.length/2,u=c.length/2;for(let p=0;p<d;p++)c.push(n[p*2]),c.push(n[p*2+1]);for(let p=0;p<d-1;p++)i.push(u+p,u+p+1);l&&i.push(u+d-1,u)}function Ol(n,e,t,i,s,r,o){const a=xp(n,e,2);if(!a)return;for(let l=0;l<a.length;l+=3)r[o++]=a[l]+s,r[o++]=a[l+1]+s,r[o++]=a[l+2]+s;let h=s*i;for(let l=0;l<n.length;l+=2)t[h]=n[l],t[h+1]=n[l+1],h+=i}const ig=[],sg={extension:{type:I.ShapeBuilder,name:"polygon"},build(n,e){for(let t=0;t<n.points.length;t++)e[t]=n.points[t];return!0},triangulate(n,e,t,i,s,r){Ol(n,ig,e,t,i,s,r)}},ng={extension:{type:I.ShapeBuilder,name:"rectangle"},build(n,e){const t=n,i=t.x,s=t.y,r=t.width,o=t.height;return r>0&&o>0?(e[0]=i,e[1]=s,e[2]=i+r,e[3]=s,e[4]=i+r,e[5]=s+o,e[6]=i,e[7]=s+o,!0):!1},triangulate(n,e,t,i,s,r){let o=0;i*=t,e[i+o]=n[0],e[i+o+1]=n[1],o+=t,e[i+o]=n[2],e[i+o+1]=n[3],o+=t,e[i+o]=n[6],e[i+o+1]=n[7],o+=t,e[i+o]=n[4],e[i+o+1]=n[5],o+=t;const a=i/t;s[r++]=a,s[r++]=a+1,s[r++]=a+2,s[r++]=a+1,s[r++]=a+3,s[r++]=a+2}},rg={extension:{type:I.ShapeBuilder,name:"triangle"},build(n,e){return e[0]=n.x,e[1]=n.y,e[2]=n.x2,e[3]=n.y2,e[4]=n.x3,e[5]=n.y3,!0},triangulate(n,e,t,i,s,r){let o=0;i*=t,e[i+o]=n[0],e[i+o+1]=n[1],o+=t,e[i+o]=n[2],e[i+o+1]=n[3],o+=t,e[i+o]=n[4],e[i+o+1]=n[5];const a=i/t;s[r++]=a,s[r++]=a+1,s[r++]=a+2}},pa=[{offset:0,color:"white"},{offset:1,color:"black"}],Dr=class rr{constructor(...e){this.uid=dt("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let t=og(e);t={...t.type==="radial"?rr.defaultRadialOptions:rr.defaultLinearOptions,...Th(t)},this._textureSize=t.textureSize,this._wrapMode=t.wrapMode,t.type==="radial"?(this.center=t.center,this.outerCenter=t.outerCenter??this.center,this.innerRadius=t.innerRadius,this.outerRadius=t.outerRadius,this.scale=t.scale,this.rotation=t.rotation):(this.start=t.start,this.end=t.end),this.textureSpace=t.textureSpace,this.type=t.type,t.colorStops.forEach(s=>{this.addColorStop(s.offset,s.color)})}addColorStop(e,t){return this.colorStops.push({offset:e,color:rt.shared.setValue(t).toHexa()}),this}buildLinearGradient(){if(this.texture)return;let{x:e,y:t}=this.start,{x:i,y:s}=this.end,r=i-e,o=s-t;const a=r<0||o<0;if(this._wrapMode==="clamp-to-edge"){if(r<0){const y=e;e=i,i=y,r*=-1}if(o<0){const y=t;t=s,s=y,o*=-1}}const h=this.colorStops.length?this.colorStops:pa,l=this._textureSize,{canvas:c,context:d}=ga(l,1),u=a?d.createLinearGradient(this._textureSize,0,0,0):d.createLinearGradient(0,0,this._textureSize,0);fa(u,h),d.fillStyle=u,d.fillRect(0,0,l,1),this.texture=new G({source:new ei({resource:c,addressMode:this._wrapMode})});const p=Math.sqrt(r*r+o*o),g=Math.atan2(o,r),m=new H;m.scale(p/l,1),m.rotate(g),m.translate(e,t),this.textureSpace==="local"&&m.scale(l,l),this.transform=m}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const e=this.colorStops.length?this.colorStops:pa,t=this._textureSize,{canvas:i,context:s}=ga(t,t),{x:r,y:o}=this.center,{x:a,y:h}=this.outerCenter,l=this.innerRadius,c=this.outerRadius,d=a-c,u=h-c,p=t/(c*2),g=(r-d)*p,m=(o-u)*p,y=s.createRadialGradient(g,m,l*p,(a-d)*p,(h-u)*p,c*p);fa(y,e),s.fillStyle=e[e.length-1].color,s.fillRect(0,0,t,t),s.fillStyle=y,s.translate(g,m),s.rotate(this.rotation),s.scale(1,this.scale),s.translate(-g,-m),s.fillRect(0,0,t,t),this.texture=new G({source:new ei({resource:i,addressMode:this._wrapMode})});const x=new H;x.scale(1/p,1/p),x.translate(d,u),this.textureSpace==="local"&&x.scale(t,t),this.transform=x}destroy(){var e;(e=this.texture)==null||e.destroy(!0),this.texture=null,this.transform=null,this.colorStops=[],this.start=null,this.end=null,this.center=null,this.outerCenter=null}get styleKey(){return`fill-gradient-${this.uid}-${this._tick}`}};Dr.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"};Dr.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let Gt=Dr;function fa(n,e){for(let t=0;t<e.length;t++){const i=e[t];n.addColorStop(i.offset,i.color)}}function ga(n,e){const t=$.get().createCanvas(n,e),i=t.getContext("2d");return{canvas:t,context:i}}function og(n){let e=n[0]??{};return(typeof e=="number"||n[1])&&(V("8.5.2","use options object instead"),e={type:"linear",start:{x:n[0],y:n[1]},end:{x:n[2],y:n[3]},textureSpace:n[4],textureSize:n[5]??Gt.defaultLinearOptions.textureSize}),e}const ag=new H,hg=new tt;function lg(n,e,t,i){const s=e.matrix?n.copyFrom(e.matrix).invert():n.identity();if(e.textureSpace==="local"){const o=t.getBounds(hg);e.width&&o.pad(e.width);const{x:a,y:h}=o,l=1/o.width,c=1/o.height,d=-a*l,u=-h*c,p=s.a,g=s.b,m=s.c,y=s.d;s.a*=l,s.b*=l,s.c*=c,s.d*=c,s.tx=d*p+u*m+s.tx,s.ty=d*g+u*y+s.ty}else s.translate(e.texture.frame.x,e.texture.frame.y),s.scale(1/e.texture.source.width,1/e.texture.source.height);const r=e.texture.source.style;return!(e.fill instanceof Gt)&&r.addressMode==="clamp-to-edge"&&(r.addressMode="repeat",r.update()),i&&s.append(ag.copyFrom(i).invert()),s}const Ls={};K.handleByMap(I.ShapeBuilder,Ls);K.add(ng,sg,rg,Wi,Kf,Qf);const cg=new tt,dg=new H;function ug(n,e){const{geometryData:t,batches:i}=e;i.length=0,t.indices.length=0,t.vertices.length=0,t.uvs.length=0;for(let s=0;s<n.instructions.length;s++){const r=n.instructions[s];if(r.action==="texture")pg(r.data,i,t);else if(r.action==="fill"||r.action==="stroke"){const o=r.action==="stroke",a=r.data.path.shapePath,h=r.data.style,l=r.data.hole;o&&l&&ma(l.shapePath,h,!0,i,t),l&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=l.shapePath.shapePrimitives),ma(a,h,o,i,t)}}}function pg(n,e,t){const i=[],s=Ls.rectangle,r=cg;r.x=n.dx,r.y=n.dy,r.width=n.dw,r.height=n.dh;const o=n.transform;if(!s.build(r,i))return;const{vertices:a,uvs:h,indices:l}=t,c=l.length,d=a.length/2;o&&zl(i,o),s.triangulate(i,a,2,d,l,c);const u=n.image,p=u.uvs;h.push(p.x0,p.y0,p.x1,p.y1,p.x3,p.y3,p.x2,p.y2);const g=Rt.get(Er);g.indexOffset=c,g.indexSize=l.length-c,g.attributeOffset=d,g.attributeSize=a.length/2-d,g.baseColor=n.style,g.alpha=n.alpha,g.texture=u,g.geometryData=t,e.push(g)}function ma(n,e,t,i,s){const{vertices:r,uvs:o,indices:a}=s;n.shapePrimitives.forEach(({shape:h,transform:l,holes:c})=>{const d=[],u=Ls[h.type];if(!u.build(h,d))return;const p=a.length,g=r.length/2;let m="triangle-list";if(l&&zl(d,l),t){const v=h.closePath??!0,b=e;b.pixelLine?(eg(d,v,r,a),m="line-list"):tg(d,b,!1,v,r,a)}else if(c){const v=[],b=d.slice();fg(c).forEach(C=>{v.push(b.length/2),b.push(...C)}),Ol(b,v,r,2,g,a,p)}else u.triangulate(d,r,2,g,a,p);const y=o.length/2,x=e.texture;if(x!==G.WHITE){const v=lg(dg,e,h,l);jf(r,2,g,o,y,2,r.length/2-g,v)}else Zf(o,y,2,r.length/2-g);const S=Rt.get(Er);S.indexOffset=p,S.indexSize=a.length-p,S.attributeOffset=g,S.attributeSize=r.length/2-g,S.baseColor=e.color,S.alpha=e.alpha,S.texture=x,S.geometryData=s,S.topology=m,i.push(S)})}function fg(n){const e=[];for(let t=0;t<n.length;t++){const i=n[t].shape,s=[];Ls[i.type].build(i,s)&&e.push(s)}return e}class gg{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(e=>{Rt.return(e)}),this.graphicsData&&Rt.return(this.graphicsData),this.isBatchable=!1,this.context=null,this.batches.length=0,this.geometryData.indices.length=0,this.geometryData.vertices.length=0,this.geometryData.uvs.length=0,this.graphicsData=null}destroy(){this.reset(),this.batches=null,this.geometryData=null}}class mg{constructor(){this.instructions=new Mr}init(e){const t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new Xf({maxTextures:t}),this.instructions.reset()}get geometry(){return V(Ld,"GraphicsContextRenderData#geometry is deprecated, please use batcher.geometry instead."),this.batcher.geometry}destroy(){this.batcher.destroy(),this.instructions.destroy(),this.batcher=null,this.instructions=null}}const Fr=class or{constructor(e){this._renderer=e,this._managedContexts=new ci({renderer:e,type:"resource",name:"graphicsContext"})}init(e){or.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??or.defaultOptions.bezierSmoothness}getContextRenderData(e){return e._gpuData[this._renderer.uid].graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=!!e._gpuData[this._renderer.uid],i=e._gpuData[this._renderer.uid]||this._initContext(e);if(e.dirty||!t){t&&i.reset(),ug(e,i);const s=e.batchMode;e.customShader||s==="no-batch"?i.isBatchable=!1:s==="auto"?i.isBatchable=i.geometryData.vertices.length<400:i.isBatchable=!0,e.dirty=!1}return i}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=Rt.get(mg,{maxTextures:this._renderer.limits.maxBatchableTextures}),i=e._gpuData[this._renderer.uid],{batches:s,geometryData:r}=i;i.graphicsData=t;const o=r.vertices.length,a=r.indices.length;for(let d=0;d<s.length;d++)s[d].applyTransform=!1;const h=t.batcher;h.ensureAttributeBuffer(o),h.ensureIndexBuffer(a),h.begin();for(let d=0;d<s.length;d++){const u=s[d];h.add(u)}h.finish(t.instructions);const l=h.geometry;l.indexBuffer.setDataWithSize(h.indexBuffer,h.indexSize,!0),l.buffers[0].setDataWithSize(h.attributeBuffer.float32View,h.attributeSize,!0);const c=h.batches;for(let d=0;d<c.length;d++){const u=c[d];u.bindGroup=lf(u.textures.textures,u.textures.count,this._renderer.limits.maxBatchableTextures)}return t}_initContext(e){const t=new gg;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};Fr.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:"graphicsContext"};Fr.defaultOptions={bezierSmoothness:.5};let Br=Fr;const yg=8,hs=11920929e-14,xg=1;function Wl(n,e,t,i,s,r,o,a,h,l){const d=Math.min(.99,Math.max(0,l??Br.defaultOptions.bezierSmoothness));let u=(xg-d)/1;return u*=u,Sg(e,t,i,s,r,o,a,h,n,u),n}function Sg(n,e,t,i,s,r,o,a,h,l){ar(n,e,t,i,s,r,o,a,h,l,0),h.push(o,a)}function ar(n,e,t,i,s,r,o,a,h,l,c){if(c>yg)return;const d=(n+t)/2,u=(e+i)/2,p=(t+s)/2,g=(i+r)/2,m=(s+o)/2,y=(r+a)/2,x=(d+p)/2,S=(u+g)/2,v=(p+m)/2,b=(g+y)/2,P=(x+v)/2,C=(S+b)/2;if(c>0){let _=o-n,R=a-e;const M=Math.abs((t-o)*R-(i-a)*_),T=Math.abs((s-o)*R-(r-a)*_);if(M>hs&&T>hs){if((M+T)*(M+T)<=l*(_*_+R*R)){h.push(P,C);return}}else if(M>hs){if(M*M<=l*(_*_+R*R)){h.push(P,C);return}}else if(T>hs){if(T*T<=l*(_*_+R*R)){h.push(P,C);return}}else if(_=P-(n+o)/2,R=C-(e+a)/2,_*_+R*R<=l){h.push(P,C);return}}ar(n,e,d,u,x,S,P,C,h,l,c+1),ar(P,C,v,b,m,y,o,a,h,l,c+1)}const vg=8,bg=11920929e-14,wg=1;function Cg(n,e,t,i,s,r,o,a){const l=Math.min(.99,Math.max(0,a??Br.defaultOptions.bezierSmoothness));let c=(wg-l)/1;return c*=c,_g(e,t,i,s,r,o,n,c),n}function _g(n,e,t,i,s,r,o,a){hr(o,n,e,t,i,s,r,a,0),o.push(s,r)}function hr(n,e,t,i,s,r,o,a,h){if(h>vg)return;const l=(e+i)/2,c=(t+s)/2,d=(i+r)/2,u=(s+o)/2,p=(l+d)/2,g=(c+u)/2;let m=r-e,y=o-t;const x=Math.abs((i-r)*y-(s-o)*m);if(x>bg){if(x*x<=a*(m*m+y*y)){n.push(p,g);return}}else if(m=p-(e+r)/2,y=g-(t+o)/2,m*m+y*y<=a){n.push(p,g);return}hr(n,e,t,l,c,p,g,a,h+1),hr(n,p,g,d,u,r,o,a,h+1)}function Gl(n,e,t,i,s,r,o,a){let h=Math.abs(s-r);(!o&&s>r||o&&r>s)&&(h=2*Math.PI-h),a||(a=Math.max(6,Math.floor(6*Math.pow(i,1/3)*(h/Math.PI)))),a=Math.max(a,3);let l=h/a,c=s;l*=o?-1:1;for(let d=0;d<a+1;d++){const u=Math.cos(c),p=Math.sin(c),g=e+u*i,m=t+p*i;n.push(g,m),c+=l}}function Pg(n,e,t,i,s,r){const o=n[n.length-2],h=n[n.length-1]-t,l=o-e,c=s-t,d=i-e,u=Math.abs(h*d-l*c);if(u<1e-8||r===0){(n[n.length-2]!==e||n[n.length-1]!==t)&&n.push(e,t);return}const p=h*h+l*l,g=c*c+d*d,m=h*c+l*d,y=r*Math.sqrt(p)/u,x=r*Math.sqrt(g)/u,S=y*m/p,v=x*m/g,b=y*d+x*l,P=y*c+x*h,C=l*(x+S),_=h*(x+S),R=d*(y+v),M=c*(y+v),T=Math.atan2(_-P,C-b),A=Math.atan2(M-P,R-b);Gl(n,b+e,P+t,r,T,A,l*c>d*h)}const Ri=Math.PI*2,Mn={centerX:0,centerY:0,ang1:0,ang2:0},An=({x:n,y:e},t,i,s,r,o,a,h)=>{n*=t,e*=i;const l=s*n-r*e,c=r*n+s*e;return h.x=l+o,h.y=c+a,h};function Mg(n,e){const t=e===-1.5707963267948966?-.551915024494:1.3333333333333333*Math.tan(e/4),i=e===1.5707963267948966?.551915024494:t,s=Math.cos(n),r=Math.sin(n),o=Math.cos(n+e),a=Math.sin(n+e);return[{x:s-r*i,y:r+s*i},{x:o+a*i,y:a-o*i},{x:o,y:a}]}const ya=(n,e,t,i)=>{const s=n*i-e*t<0?-1:1;let r=n*t+e*i;return r>1&&(r=1),r<-1&&(r=-1),s*Math.acos(r)},Ag=(n,e,t,i,s,r,o,a,h,l,c,d,u)=>{const p=Math.pow(s,2),g=Math.pow(r,2),m=Math.pow(c,2),y=Math.pow(d,2);let x=p*g-p*y-g*m;x<0&&(x=0),x/=p*y+g*m,x=Math.sqrt(x)*(o===a?-1:1);const S=x*s/r*d,v=x*-r/s*c,b=l*S-h*v+(n+t)/2,P=h*S+l*v+(e+i)/2,C=(c-S)/s,_=(d-v)/r,R=(-c-S)/s,M=(-d-v)/r,T=ya(1,0,C,_);let A=ya(C,_,R,M);a===0&&A>0&&(A-=Ri),a===1&&A<0&&(A+=Ri),u.centerX=b,u.centerY=P,u.ang1=T,u.ang2=A};function Tg(n,e,t,i,s,r,o,a=0,h=0,l=0){if(r===0||o===0)return;const c=Math.sin(a*Ri/360),d=Math.cos(a*Ri/360),u=d*(e-i)/2+c*(t-s)/2,p=-c*(e-i)/2+d*(t-s)/2;if(u===0&&p===0)return;r=Math.abs(r),o=Math.abs(o);const g=Math.pow(u,2)/Math.pow(r,2)+Math.pow(p,2)/Math.pow(o,2);g>1&&(r*=Math.sqrt(g),o*=Math.sqrt(g)),Ag(e,t,i,s,r,o,h,l,c,d,u,p,Mn);let{ang1:m,ang2:y}=Mn;const{centerX:x,centerY:S}=Mn;let v=Math.abs(y)/(Ri/4);Math.abs(1-v)<1e-7&&(v=1);const b=Math.max(Math.ceil(v),1);y/=b;let P=n[n.length-2],C=n[n.length-1];const _={x:0,y:0};for(let R=0;R<b;R++){const M=Mg(m,y),{x:T,y:A}=An(M[0],r,o,d,c,x,S,_),{x:E,y:D}=An(M[1],r,o,d,c,x,S,_),{x:B,y:j}=An(M[2],r,o,d,c,x,S,_);Wl(n,P,C,T,A,E,D,B,j),P=B,C=j,m+=y}}function Rg(n,e,t){const i=(o,a)=>{const h=a.x-o.x,l=a.y-o.y,c=Math.sqrt(h*h+l*l),d=h/c,u=l/c;return{len:c,nx:d,ny:u}},s=(o,a)=>{o===0?n.moveTo(a.x,a.y):n.lineTo(a.x,a.y)};let r=e[e.length-1];for(let o=0;o<e.length;o++){const a=e[o%e.length],h=a.radius??t;if(h<=0){s(o,a),r=a;continue}const l=e[(o+1)%e.length],c=i(a,r),d=i(a,l);if(c.len<1e-4||d.len<1e-4){s(o,a),r=a;continue}let u=Math.asin(c.nx*d.ny-c.ny*d.nx),p=1,g=!1;c.nx*d.nx-c.ny*-d.ny<0?u<0?u=Math.PI+u:(u=Math.PI-u,p=-1,g=!0):u>0&&(p=-1,g=!0);const m=u/2;let y,x=Math.abs(Math.cos(m)*h/Math.sin(m));x>Math.min(c.len/2,d.len/2)?(x=Math.min(c.len/2,d.len/2),y=Math.abs(x*Math.sin(m)/Math.cos(m))):y=h;const S=a.x+d.nx*x+-d.ny*y*p,v=a.y+d.ny*x+d.nx*y*p,b=Math.atan2(c.ny,c.nx)+Math.PI/2*p,P=Math.atan2(d.ny,d.nx)-Math.PI/2*p;o===0&&n.moveTo(S+Math.cos(b)*y,v+Math.sin(b)*y),n.arc(S,v,y,b,P,g),r=a}}function kg(n,e,t,i){const s=(a,h)=>Math.sqrt((a.x-h.x)**2+(a.y-h.y)**2),r=(a,h,l)=>({x:a.x+(h.x-a.x)*l,y:a.y+(h.y-a.y)*l}),o=e.length;for(let a=0;a<o;a++){const h=e[(a+1)%o],l=h.radius??t;if(l<=0){a===0?n.moveTo(h.x,h.y):n.lineTo(h.x,h.y);continue}const c=e[a],d=e[(a+2)%o],u=s(c,h);let p;if(u<1e-4)p=h;else{const y=Math.min(u/2,l);p=r(h,c,y/u)}const g=s(d,h);let m;if(g<1e-4)m=h;else{const y=Math.min(g/2,l);m=r(h,d,y/g)}a===0?n.moveTo(p.x,p.y):n.lineTo(p.x,p.y),n.quadraticCurveTo(h.x,h.y,m.x,m.y,i)}}const Ig=new tt;class Eg{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new Ft,this._graphicsPath2D=e,this.signed=e.checkForHoles}moveTo(e,t){return this.startPoly(e,t),this}lineTo(e,t){this._ensurePoly();const i=this._currentPoly.points,s=i[i.length-2],r=i[i.length-1];return(s!==e||r!==t)&&i.push(e,t),this}arc(e,t,i,s,r,o){this._ensurePoly(!1);const a=this._currentPoly.points;return Gl(a,e,t,i,s,r,o),this}arcTo(e,t,i,s,r){this._ensurePoly();const o=this._currentPoly.points;return Pg(o,e,t,i,s,r),this}arcToSvg(e,t,i,s,r,o,a){const h=this._currentPoly.points;return Tg(h,this._currentPoly.lastX,this._currentPoly.lastY,o,a,e,t,i,s,r),this}bezierCurveTo(e,t,i,s,r,o,a){this._ensurePoly();const h=this._currentPoly;return Wl(this._currentPoly.points,h.lastX,h.lastY,e,t,i,s,r,o,a),this}quadraticCurveTo(e,t,i,s,r){this._ensurePoly();const o=this._currentPoly;return Cg(this._currentPoly.points,o.lastX,o.lastY,e,t,i,s,r),this}closePath(){return this.endPoly(!0),this}addPath(e,t){this.endPoly(),t&&!t.isIdentity()&&(e=e.clone(!0),e.transform(t));const i=this.shapePrimitives,s=i.length;for(let r=0;r<e.instructions.length;r++){const o=e.instructions[r];this[o.action](...o.data)}if(e.checkForHoles&&i.length-s>1){let r=null;for(let o=s;o<i.length;o++){const a=i[o];if(a.shape.type==="polygon"){const h=a.shape,l=r==null?void 0:r.shape;l&&l.containsPolygon(h)?(r.holes||(r.holes=[]),r.holes.push(a),i.copyWithin(o,o+1),i.length--,o--):r=a}}}return this}finish(e=!1){this.endPoly(e)}rect(e,t,i,s,r){return this.drawShape(new tt(e,t,i,s),r),this}circle(e,t,i,s){return this.drawShape(new zs(e,t,i),s),this}poly(e,t,i){const s=new ke(e);return s.closePath=t,this.drawShape(s,i),this}regularPoly(e,t,i,s,r=0,o){s=Math.max(s|0,3);const a=-1*Math.PI/2+r,h=Math.PI*2/s,l=[];for(let c=0;c<s;c++){const d=a-c*h;l.push(e+i*Math.cos(d),t+i*Math.sin(d))}return this.poly(l,!0,o),this}roundPoly(e,t,i,s,r,o=0,a){if(s=Math.max(s|0,3),r<=0)return this.regularPoly(e,t,i,s,o);const h=i*Math.sin(Math.PI/s)-.001;r=Math.min(r,h);const l=-1*Math.PI/2+o,c=Math.PI*2/s,d=(s-2)*Math.PI/s/2;for(let u=0;u<s;u++){const p=u*c+l,g=e+i*Math.cos(p),m=t+i*Math.sin(p),y=p+Math.PI+d,x=p-Math.PI-d,S=g+r*Math.cos(y),v=m+r*Math.sin(y),b=g+r*Math.cos(x),P=m+r*Math.sin(x);u===0?this.moveTo(S,v):this.lineTo(S,v),this.quadraticCurveTo(g,m,b,P,a)}return this.closePath()}roundShape(e,t,i=!1,s){return e.length<3?this:(i?kg(this,e,t,s):Rg(this,e,t),this.closePath())}filletRect(e,t,i,s,r){if(r===0)return this.rect(e,t,i,s);const o=Math.min(i,s)/2,a=Math.min(o,Math.max(-o,r)),h=e+i,l=t+s,c=a<0?-a:0,d=Math.abs(a);return this.moveTo(e,t+d).arcTo(e+c,t+c,e+d,t,d).lineTo(h-d,t).arcTo(h-c,t+c,h,t+d,d).lineTo(h,l-d).arcTo(h-c,l-c,e+i-d,l,d).lineTo(e+d,l).arcTo(e+c,l-c,e,l-d,d).closePath()}chamferRect(e,t,i,s,r,o){if(r<=0)return this.rect(e,t,i,s);const a=Math.min(r,Math.min(i,s)/2),h=e+i,l=t+s,c=[e+a,t,h-a,t,h,t+a,h,l-a,h-a,l,e+a,l,e,l-a,e,t+a];for(let d=c.length-1;d>=2;d-=2)c[d]===c[d-2]&&c[d-1]===c[d-3]&&c.splice(d-1,2);return this.poly(c,!0,o)}ellipse(e,t,i,s,r){return this.drawShape(new kr(e,t,i,s),r),this}roundRect(e,t,i,s,r,o){return this.drawShape(new Ir(e,t,i,s,r),o),this}drawShape(e,t){return this.endPoly(),this.shapePrimitives.push({shape:e,transform:t}),this}startPoly(e,t){let i=this._currentPoly;return i&&this.endPoly(),i=new ke,i.points.push(e,t),this._currentPoly=i,this}endPoly(e=!1){const t=this._currentPoly;return t&&t.points.length>2&&(t.closePath=e,this.shapePrimitives.push({shape:t})),this._currentPoly=null,this}_ensurePoly(e=!0){if(!this._currentPoly&&(this._currentPoly=new ke,e)){const t=this.shapePrimitives[this.shapePrimitives.length-1];if(t){let i=t.shape.x,s=t.shape.y;if(t.transform&&!t.transform.isIdentity()){const r=t.transform,o=i;i=r.a*i+r.c*s+r.tx,s=r.b*o+r.d*s+r.ty}this._currentPoly.points.push(i,s)}else this._currentPoly.points.push(0,0)}}buildPath(){const e=this._graphicsPath2D;this.shapePrimitives.length=0,this._currentPoly=null;for(let t=0;t<e.instructions.length;t++){const i=e.instructions[t];this[i.action](...i.data)}this.finish()}get bounds(){const e=this._bounds;e.clear();const t=this.shapePrimitives;for(let i=0;i<t.length;i++){const s=t[i],r=s.shape.getBounds(Ig);s.transform?e.addRect(r,s.transform):e.addRect(r)}return e}}class ie{constructor(e,t=!1){this.instructions=[],this.uid=dt("graphicsPath"),this._dirty=!0,this.checkForHoles=t,typeof e=="string"?rf(e,this):this.instructions=(e==null?void 0:e.slice())??[]}get shapePath(){return this._shapePath||(this._shapePath=new Eg(this)),this._dirty&&(this._dirty=!1,this._shapePath.buildPath()),this._shapePath}addPath(e,t){return e=e.clone(),this.instructions.push({action:"addPath",data:[e,t]}),this._dirty=!0,this}arc(...e){return this.instructions.push({action:"arc",data:e}),this._dirty=!0,this}arcTo(...e){return this.instructions.push({action:"arcTo",data:e}),this._dirty=!0,this}arcToSvg(...e){return this.instructions.push({action:"arcToSvg",data:e}),this._dirty=!0,this}bezierCurveTo(...e){return this.instructions.push({action:"bezierCurveTo",data:e}),this._dirty=!0,this}bezierCurveToShort(e,t,i,s,r){const o=this.instructions[this.instructions.length-1],a=this.getLastPoint(J.shared);let h=0,l=0;if(!o||o.action!=="bezierCurveTo")h=a.x,l=a.y;else{h=o.data[2],l=o.data[3];const c=a.x,d=a.y;h=c+(c-h),l=d+(d-l)}return this.instructions.push({action:"bezierCurveTo",data:[h,l,e,t,i,s,r]}),this._dirty=!0,this}closePath(){return this.instructions.push({action:"closePath",data:[]}),this._dirty=!0,this}ellipse(...e){return this.instructions.push({action:"ellipse",data:e}),this._dirty=!0,this}lineTo(...e){return this.instructions.push({action:"lineTo",data:e}),this._dirty=!0,this}moveTo(...e){return this.instructions.push({action:"moveTo",data:e}),this}quadraticCurveTo(...e){return this.instructions.push({action:"quadraticCurveTo",data:e}),this._dirty=!0,this}quadraticCurveToShort(e,t,i){const s=this.instructions[this.instructions.length-1],r=this.getLastPoint(J.shared);let o=0,a=0;if(!s||s.action!=="quadraticCurveTo")o=r.x,a=r.y;else{o=s.data[0],a=s.data[1];const h=r.x,l=r.y;o=h+(h-o),a=l+(l-a)}return this.instructions.push({action:"quadraticCurveTo",data:[o,a,e,t,i]}),this._dirty=!0,this}rect(e,t,i,s,r){return this.instructions.push({action:"rect",data:[e,t,i,s,r]}),this._dirty=!0,this}circle(e,t,i,s){return this.instructions.push({action:"circle",data:[e,t,i,s]}),this._dirty=!0,this}roundRect(...e){return this.instructions.push({action:"roundRect",data:e}),this._dirty=!0,this}poly(...e){return this.instructions.push({action:"poly",data:e}),this._dirty=!0,this}regularPoly(...e){return this.instructions.push({action:"regularPoly",data:e}),this._dirty=!0,this}roundPoly(...e){return this.instructions.push({action:"roundPoly",data:e}),this._dirty=!0,this}roundShape(...e){return this.instructions.push({action:"roundShape",data:e}),this._dirty=!0,this}filletRect(...e){return this.instructions.push({action:"filletRect",data:e}),this._dirty=!0,this}chamferRect(...e){return this.instructions.push({action:"chamferRect",data:e}),this._dirty=!0,this}star(e,t,i,s,r,o,a){r||(r=s/2);const h=-1*Math.PI/2+o,l=i*2,c=Math.PI*2/l,d=[];for(let u=0;u<l;u++){const p=u%2?r:s,g=u*c+h;d.push(e+p*Math.cos(g),t+p*Math.sin(g))}return this.poly(d,!0,a),this}clone(e=!1){const t=new ie;if(t.checkForHoles=this.checkForHoles,!e)t.instructions=this.instructions.slice();else for(let i=0;i<this.instructions.length;i++){const s=this.instructions[i];t.instructions.push({action:s.action,data:s.data.slice()})}return t}clear(){return this.instructions.length=0,this._dirty=!0,this}transform(e){if(e.isIdentity())return this;const t=e.a,i=e.b,s=e.c,r=e.d,o=e.tx,a=e.ty;let h=0,l=0,c=0,d=0,u=0,p=0,g=0,m=0;for(let y=0;y<this.instructions.length;y++){const x=this.instructions[y],S=x.data;switch(x.action){case"moveTo":case"lineTo":h=S[0],l=S[1],S[0]=t*h+s*l+o,S[1]=i*h+r*l+a;break;case"bezierCurveTo":c=S[0],d=S[1],u=S[2],p=S[3],h=S[4],l=S[5],S[0]=t*c+s*d+o,S[1]=i*c+r*d+a,S[2]=t*u+s*p+o,S[3]=i*u+r*p+a,S[4]=t*h+s*l+o,S[5]=i*h+r*l+a;break;case"quadraticCurveTo":c=S[0],d=S[1],h=S[2],l=S[3],S[0]=t*c+s*d+o,S[1]=i*c+r*d+a,S[2]=t*h+s*l+o,S[3]=i*h+r*l+a;break;case"arcToSvg":h=S[5],l=S[6],g=S[0],m=S[1],S[0]=t*g+s*m,S[1]=i*g+r*m,S[5]=t*h+s*l+o,S[6]=i*h+r*l+a;break;case"circle":S[4]=yi(S[3],e);break;case"rect":S[4]=yi(S[4],e);break;case"ellipse":S[8]=yi(S[8],e);break;case"roundRect":S[5]=yi(S[5],e);break;case"addPath":S[0].transform(e);break;case"poly":S[2]=yi(S[2],e);break;default:nt("unknown transform action",x.action);break}}return this._dirty=!0,this}get bounds(){return this.shapePath.bounds}getLastPoint(e){let t=this.instructions.length-1,i=this.instructions[t];if(!i)return e.x=0,e.y=0,e;for(;i.action==="closePath";){if(t--,t<0)return e.x=0,e.y=0,e;i=this.instructions[t]}switch(i.action){case"moveTo":case"lineTo":e.x=i.data[0],e.y=i.data[1];break;case"quadraticCurveTo":e.x=i.data[2],e.y=i.data[3];break;case"bezierCurveTo":e.x=i.data[4],e.y=i.data[5];break;case"arc":case"arcToSvg":e.x=i.data[5],e.y=i.data[6];break;case"addPath":i.data[0].getLastPoint(e);break}return e}}function yi(n,e){return n?n.prepend(e):e.clone()}function lt(n,e,t){const i=n.getAttribute(e);return i?Number(i):t}function Dg(n,e){const t=n.querySelectorAll("defs");for(let i=0;i<t.length;i++){const s=t[i];for(let r=0;r<s.children.length;r++){const o=s.children[r];switch(o.nodeName.toLowerCase()){case"lineargradient":e.defs[o.id]=Fg(o);break;case"radialgradient":e.defs[o.id]=Bg();break}}}}function Fg(n){const e=lt(n,"x1",0),t=lt(n,"y1",0),i=lt(n,"x2",1),s=lt(n,"y2",0),r=n.getAttribute("gradientUnits")||"objectBoundingBox",o=new Gt(e,t,i,s,r==="objectBoundingBox"?"local":"global");for(let a=0;a<n.children.length;a++){const h=n.children[a],l=lt(h,"offset",0),c=rt.shared.setValue(h.getAttribute("stop-color")).toNumber();o.addColorStop(l,c)}return o}function Bg(n){return nt("[SVG Parser] Radial gradients are not yet supported"),new Gt(0,0,1,0)}function xa(n){const e=n.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return e?e[1]:""}const Sa={fill:{type:"paint",default:0},"fill-opacity":{type:"number",default:1},stroke:{type:"paint",default:0},"stroke-width":{type:"number",default:1},"stroke-opacity":{type:"number",default:1},"stroke-linecap":{type:"string",default:"butt"},"stroke-linejoin":{type:"string",default:"miter"},"stroke-miterlimit":{type:"number",default:10},"stroke-dasharray":{type:"string",default:"none"},"stroke-dashoffset":{type:"number",default:0},opacity:{type:"number",default:1}};function Ul(n,e){const t=n.getAttribute("style"),i={},s={},r={strokeStyle:i,fillStyle:s,useFill:!1,useStroke:!1};for(const o in Sa){const a=n.getAttribute(o);a&&va(e,r,o,a.trim())}if(t){const o=t.split(";");for(let a=0;a<o.length;a++){const h=o[a].trim(),[l,c]=h.split(":");Sa[l]&&va(e,r,l,c.trim())}}return{strokeStyle:r.useStroke?i:null,fillStyle:r.useFill?s:null,useFill:r.useFill,useStroke:r.useStroke}}function va(n,e,t,i){switch(t){case"stroke":if(i!=="none"){if(i.startsWith("url(")){const s=xa(i);e.strokeStyle.fill=n.defs[s]}else e.strokeStyle.color=rt.shared.setValue(i).toNumber();e.useStroke=!0}break;case"stroke-width":e.strokeStyle.width=Number(i);break;case"fill":if(i!=="none"){if(i.startsWith("url(")){const s=xa(i);e.fillStyle.fill=n.defs[s]}else e.fillStyle.color=rt.shared.setValue(i).toNumber();e.useFill=!0}break;case"fill-opacity":e.fillStyle.alpha=Number(i);break;case"stroke-opacity":e.strokeStyle.alpha=Number(i);break;case"opacity":e.fillStyle.alpha=Number(i),e.strokeStyle.alpha=Number(i);break}}function zg(n){if(n.length<=2)return!0;const e=n.map(a=>a.area).sort((a,h)=>h-a),[t,i]=e,s=e[e.length-1],r=t/i,o=i/s;return!(r>3&&o<2)}function Lg(n){return n.split(/(?=[Mm])/).filter(i=>i.trim().length>0)}function Og(n){const e=n.match(/[-+]?[0-9]*\.?[0-9]+/g);if(!e||e.length<4)return 0;const t=e.map(Number),i=[],s=[];for(let c=0;c<t.length;c+=2)c+1<t.length&&(i.push(t[c]),s.push(t[c+1]));if(i.length===0||s.length===0)return 0;const r=Math.min(...i),o=Math.max(...i),a=Math.min(...s),h=Math.max(...s);return(o-r)*(h-a)}function ba(n,e){const t=new ie(n,!1);for(const i of t.instructions)e.instructions.push(i)}function Wg(n,e){if(typeof n=="string"){const o=document.createElement("div");o.innerHTML=n.trim(),n=o.querySelector("svg")}const t={context:e,defs:{},path:new ie};Dg(n,t);const i=n.children,{fillStyle:s,strokeStyle:r}=Ul(n,t);for(let o=0;o<i.length;o++){const a=i[o];a.nodeName.toLowerCase()!=="defs"&&Hl(a,t,s,r)}return e}function Hl(n,e,t,i){const s=n.children,{fillStyle:r,strokeStyle:o}=Ul(n,e);r&&t?t={...t,...r}:r&&(t=r),o&&i?i={...i,...o}:o&&(i=o);const a=!t&&!i;a&&(t={color:0});let h,l,c,d,u,p,g,m,y,x,S,v,b,P,C,_,R;switch(n.nodeName.toLowerCase()){case"path":{P=n.getAttribute("d");const M=n.getAttribute("fill-rule"),T=Lg(P),A=M==="evenodd",E=T.length>1;if(A&&E){const B=T.map(k=>({path:k,area:Og(k)}));if(B.sort((k,F)=>F.area-k.area),T.length>3||!zg(B))for(let k=0;k<B.length;k++){const F=B[k],ot=k===0;e.context.beginPath();const z=new ie(void 0,!0);ba(F.path,z),e.context.path(z),ot?(t&&e.context.fill(t),i&&e.context.stroke(i)):e.context.cut()}else for(let k=0;k<B.length;k++){const F=B[k],ot=k%2===1;e.context.beginPath();const z=new ie(void 0,!0);ba(F.path,z),e.context.path(z),ot?e.context.cut():(t&&e.context.fill(t),i&&e.context.stroke(i))}}else{const B=M?M==="evenodd":!0;C=new ie(P,B),e.context.path(C),t&&e.context.fill(t),i&&e.context.stroke(i)}break}case"circle":g=lt(n,"cx",0),m=lt(n,"cy",0),y=lt(n,"r",0),e.context.ellipse(g,m,y,y),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"rect":h=lt(n,"x",0),l=lt(n,"y",0),_=lt(n,"width",0),R=lt(n,"height",0),x=lt(n,"rx",0),S=lt(n,"ry",0),x||S?e.context.roundRect(h,l,_,R,x||S):e.context.rect(h,l,_,R),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"ellipse":g=lt(n,"cx",0),m=lt(n,"cy",0),x=lt(n,"rx",0),S=lt(n,"ry",0),e.context.beginPath(),e.context.ellipse(g,m,x,S),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"line":c=lt(n,"x1",0),d=lt(n,"y1",0),u=lt(n,"x2",0),p=lt(n,"y2",0),e.context.beginPath(),e.context.moveTo(c,d),e.context.lineTo(u,p),i&&e.context.stroke(i);break;case"polygon":b=n.getAttribute("points"),v=b.match(/-?\d+/g).map(M=>parseInt(M,10)),e.context.poly(v,!0),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"polyline":b=n.getAttribute("points"),v=b.match(/-?\d+/g).map(M=>parseInt(M,10)),e.context.poly(v,!1),i&&e.context.stroke(i);break;case"g":case"svg":break;default:{nt(`[SVG parser] <${n.nodeName}> elements unsupported`);break}}a&&(t=null);for(let M=0;M<s.length;M++)Hl(s[M],e,t,i)}const wa={repeat:{addressModeU:"repeat",addressModeV:"repeat"},"repeat-x":{addressModeU:"repeat",addressModeV:"clamp-to-edge"},"repeat-y":{addressModeU:"clamp-to-edge",addressModeV:"repeat"},"no-repeat":{addressModeU:"clamp-to-edge",addressModeV:"clamp-to-edge"}};class Os{constructor(e,t){this.uid=dt("fillPattern"),this._tick=0,this.transform=new H,this.texture=e,this.transform.scale(1/e.frame.width,1/e.frame.height),t&&(e.source.style.addressModeU=wa[t].addressModeU,e.source.style.addressModeV=wa[t].addressModeV)}setTransform(e){const t=this.texture;this.transform.copyFrom(e),this.transform.invert(),this.transform.scale(1/t.frame.width,1/t.frame.height),this._tick++}get texture(){return this._texture}set texture(e){this._texture!==e&&(this._texture=e,this._tick++)}get styleKey(){return`fill-pattern-${this.uid}-${this._tick}`}destroy(){this.texture.destroy(!0),this.texture=null}}function Gg(n){return rt.isColorLike(n)}function Ca(n){return n instanceof Os}function _a(n){return n instanceof Gt}function Ug(n){return n instanceof G}function Hg(n,e,t){const i=rt.shared.setValue(e??0);return n.color=i.toNumber(),n.alpha=i.alpha===1?t.alpha:i.alpha,n.texture=G.WHITE,{...t,...n}}function Vg(n,e,t){return n.texture=e,{...t,...n}}function Pa(n,e,t){return n.fill=e,n.color=16777215,n.texture=e.texture,n.matrix=e.transform,{...t,...n}}function Ma(n,e,t){return e.buildGradient(),n.fill=e,n.color=16777215,n.texture=e.texture,n.matrix=e.transform,n.textureSpace=e.textureSpace,{...t,...n}}function Ng(n,e){const t={...e,...n},i=rt.shared.setValue(t.color);return t.alpha*=i.alpha,t.color=i.toNumber(),t}function Ae(n,e){if(n==null)return null;const t={},i=n;return Gg(n)?Hg(t,n,e):Ug(n)?Vg(t,n,e):Ca(n)?Pa(t,n,e):_a(n)?Ma(t,n,e):i.fill&&Ca(i.fill)?Pa(i,i.fill,e):i.fill&&_a(i.fill)?Ma(i,i.fill,e):Ng(i,e)}function Ps(n,e){const{width:t,alignment:i,miterLimit:s,cap:r,join:o,pixelLine:a,...h}=e,l=Ae(n,h);return l?{width:t,alignment:i,miterLimit:s,cap:r,join:o,pixelLine:a,...l}:null}const $g=new J,Aa=new H,zr=class Nt extends jt{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=dt("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this.destroyed=!1,this._activePath=new ie,this._transform=new H,this._fillStyle={...Nt.defaultFillStyle},this._strokeStyle={...Nt.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new Ft,this._boundsDirty=!0}clone(){const e=new Nt;return e.batchMode=this.batchMode,e.instructions=this.instructions.slice(),e._activePath=this._activePath.clone(),e._transform=this._transform.clone(),e._fillStyle={...this._fillStyle},e._strokeStyle={...this._strokeStyle},e._stateStack=this._stateStack.slice(),e._bounds=this._bounds.clone(),e._boundsDirty=!0,e}get fillStyle(){return this._fillStyle}set fillStyle(e){this._fillStyle=Ae(e,Nt.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(e){this._strokeStyle=Ps(e,Nt.defaultStrokeStyle)}setFillStyle(e){return this._fillStyle=Ae(e,Nt.defaultFillStyle),this}setStrokeStyle(e){return this._strokeStyle=Ae(e,Nt.defaultStrokeStyle),this}texture(e,t,i,s,r,o){return this.instructions.push({action:"texture",data:{image:e,dx:i||0,dy:s||0,dw:r||e.frame.width,dh:o||e.frame.height,transform:this._transform.clone(),alpha:this._fillStyle.alpha,style:t||t===0?rt.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new ie,this}fill(e,t){let i;const s=this.instructions[this.instructions.length-1];return this._tick===0&&(s==null?void 0:s.action)==="stroke"?i=s.data.path:i=this._activePath.clone(),i?(e!=null&&(t!==void 0&&typeof e=="number"&&(V(Q,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),e={color:e,alpha:t}),this._fillStyle=Ae(e,Nt.defaultFillStyle)),this.instructions.push({action:"fill",data:{style:this.fillStyle,path:i}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}_initNextPathLocation(){const{x:e,y:t}=this._activePath.getLastPoint(J.shared);this._activePath.clear(),this._activePath.moveTo(e,t)}stroke(e){let t;const i=this.instructions[this.instructions.length-1];return this._tick===0&&(i==null?void 0:i.action)==="fill"?t=i.data.path:t=this._activePath.clone(),t?(e!=null&&(this._strokeStyle=Ps(e,Nt.defaultStrokeStyle)),this.instructions.push({action:"stroke",data:{style:this.strokeStyle,path:t}}),this.onUpdate(),this._initNextPathLocation(),this._tick=0,this):this}cut(){for(let e=0;e<2;e++){const t=this.instructions[this.instructions.length-1-e],i=this._activePath.clone();if(t&&(t.action==="stroke"||t.action==="fill"))if(t.data.hole)t.data.hole.addPath(i);else{t.data.hole=i;break}}return this._initNextPathLocation(),this}arc(e,t,i,s,r,o){this._tick++;const a=this._transform;return this._activePath.arc(a.a*e+a.c*t+a.tx,a.b*e+a.d*t+a.ty,i,s,r,o),this}arcTo(e,t,i,s,r){this._tick++;const o=this._transform;return this._activePath.arcTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*i+o.c*s+o.tx,o.b*i+o.d*s+o.ty,r),this}arcToSvg(e,t,i,s,r,o,a){this._tick++;const h=this._transform;return this._activePath.arcToSvg(e,t,i,s,r,h.a*o+h.c*a+h.tx,h.b*o+h.d*a+h.ty),this}bezierCurveTo(e,t,i,s,r,o,a){this._tick++;const h=this._transform;return this._activePath.bezierCurveTo(h.a*e+h.c*t+h.tx,h.b*e+h.d*t+h.ty,h.a*i+h.c*s+h.tx,h.b*i+h.d*s+h.ty,h.a*r+h.c*o+h.tx,h.b*r+h.d*o+h.ty,a),this}closePath(){var e;return this._tick++,(e=this._activePath)==null||e.closePath(),this}ellipse(e,t,i,s){return this._tick++,this._activePath.ellipse(e,t,i,s,this._transform.clone()),this}circle(e,t,i){return this._tick++,this._activePath.circle(e,t,i,this._transform.clone()),this}path(e){return this._tick++,this._activePath.addPath(e,this._transform.clone()),this}lineTo(e,t){this._tick++;const i=this._transform;return this._activePath.lineTo(i.a*e+i.c*t+i.tx,i.b*e+i.d*t+i.ty),this}moveTo(e,t){this._tick++;const i=this._transform,s=this._activePath.instructions,r=i.a*e+i.c*t+i.tx,o=i.b*e+i.d*t+i.ty;return s.length===1&&s[0].action==="moveTo"?(s[0].data[0]=r,s[0].data[1]=o,this):(this._activePath.moveTo(r,o),this)}quadraticCurveTo(e,t,i,s,r){this._tick++;const o=this._transform;return this._activePath.quadraticCurveTo(o.a*e+o.c*t+o.tx,o.b*e+o.d*t+o.ty,o.a*i+o.c*s+o.tx,o.b*i+o.d*s+o.ty,r),this}rect(e,t,i,s){return this._tick++,this._activePath.rect(e,t,i,s,this._transform.clone()),this}roundRect(e,t,i,s,r){return this._tick++,this._activePath.roundRect(e,t,i,s,r,this._transform.clone()),this}poly(e,t){return this._tick++,this._activePath.poly(e,t,this._transform.clone()),this}regularPoly(e,t,i,s,r=0,o){return this._tick++,this._activePath.regularPoly(e,t,i,s,r,o),this}roundPoly(e,t,i,s,r,o){return this._tick++,this._activePath.roundPoly(e,t,i,s,r,o),this}roundShape(e,t,i,s){return this._tick++,this._activePath.roundShape(e,t,i,s),this}filletRect(e,t,i,s,r){return this._tick++,this._activePath.filletRect(e,t,i,s,r),this}chamferRect(e,t,i,s,r,o){return this._tick++,this._activePath.chamferRect(e,t,i,s,r,o),this}star(e,t,i,s,r=0,o=0){return this._tick++,this._activePath.star(e,t,i,s,r,o,this._transform.clone()),this}svg(e){return this._tick++,Wg(e,this),this}restore(){const e=this._stateStack.pop();return e&&(this._transform=e.transform,this._fillStyle=e.fillStyle,this._strokeStyle=e.strokeStyle),this}save(){return this._stateStack.push({transform:this._transform.clone(),fillStyle:{...this._fillStyle},strokeStyle:{...this._strokeStyle}}),this}getTransform(){return this._transform}resetTransform(){return this._transform.identity(),this}rotate(e){return this._transform.rotate(e),this}scale(e,t=e){return this._transform.scale(e,t),this}setTransform(e,t,i,s,r,o){return e instanceof H?(this._transform.set(e.a,e.b,e.c,e.d,e.tx,e.ty),this):(this._transform.set(e,t,i,s,r,o),this)}transform(e,t,i,s,r,o){return e instanceof H?(this._transform.append(e),this):(Aa.set(e,t,i,s,r,o),this._transform.append(Aa),this)}translate(e,t=e){return this._transform.translate(e,t),this}clear(){return this._activePath.clear(),this.instructions.length=0,this.resetTransform(),this.onUpdate(),this}onUpdate(){this._boundsDirty=!0,!this.dirty&&(this.emit("update",this,16),this.dirty=!0)}get bounds(){if(!this._boundsDirty)return this._bounds;this._boundsDirty=!1;const e=this._bounds;e.clear();for(let t=0;t<this.instructions.length;t++){const i=this.instructions[t],s=i.action;if(s==="fill"){const r=i.data;e.addBounds(r.path.bounds)}else if(s==="texture"){const r=i.data;e.addFrame(r.dx,r.dy,r.dx+r.dw,r.dy+r.dh,r.transform)}if(s==="stroke"){const r=i.data,o=r.style.alignment,a=r.style.width*(1-o),h=r.path.bounds;e.addFrame(h.minX-a,h.minY-a,h.maxX+a,h.maxY+a)}}return e}containsPoint(e){var s;if(!this.bounds.containsPoint(e.x,e.y))return!1;const t=this.instructions;let i=!1;for(let r=0;r<t.length;r++){const o=t[r],a=o.data,h=a.path;if(!o.action||!h)continue;const l=a.style,c=h.shapePath.shapePrimitives;for(let d=0;d<c.length;d++){const u=c[d].shape;if(!l||!u)continue;const p=c[d].transform,g=p?p.applyInverse(e,$g):e;if(o.action==="fill")i=u.contains(g.x,g.y);else{const y=l;i=u.strokeContains(g.x,g.y,y.width,y.alignment)}const m=a.hole;if(m){const y=(s=m.shapePath)==null?void 0:s.shapePrimitives;if(y)for(let x=0;x<y.length;x++)y[x].shape.contains(g.x,g.y)&&(i=!1)}if(i)return!0}}return i}unload(){var e;this.emit("unload",this);for(const t in this._gpuData)(e=this._gpuData[t])==null||e.destroy();this._gpuData=Object.create(null)}destroy(e=!1){if(this.destroyed)return;if(this.destroyed=!0,this._stateStack.length=0,this._transform=null,this.unload(),this.emit("destroy",this),this.removeAllListeners(),typeof e=="boolean"?e:e==null?void 0:e.texture){const i=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._fillStyle.texture&&(this._fillStyle.fill&&"uid"in this._fillStyle.fill?this._fillStyle.fill.destroy():this._fillStyle.texture.destroy(i)),this._strokeStyle.texture&&(this._strokeStyle.fill&&"uid"in this._strokeStyle.fill?this._strokeStyle.fill.destroy():this._strokeStyle.texture.destroy(i))}this._fillStyle=null,this._strokeStyle=null,this.instructions=null,this._activePath=null,this._bounds=null,this._stateStack=null,this.customShader=null,this._transform=null}};zr.defaultFillStyle={color:16777215,alpha:1,texture:G.WHITE,matrix:null,fill:null,textureSpace:"local"};zr.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:G.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let gt=zr;function Lr(n,e=1){var i;const t=(i=hi.RETINA_PREFIX)==null?void 0:i.exec(n);return t?parseFloat(t[1]):e}function Or(n,e,t){n.label=t,n._sourceOrigin=t;const i=new G({source:n,label:t}),s=()=>{delete e.promiseCache[t],xt.has(t)&&xt.remove(t)};return i.source.once("destroy",()=>{e.promiseCache[t]&&(nt("[Assets] A TextureSource managed by Assets was destroyed instead of unloaded! Use Assets.unload() instead of destroying the TextureSource."),s())}),i.once("destroy",()=>{n.destroyed||(nt("[Assets] A Texture managed by Assets was destroyed instead of unloaded! Use Assets.unload() instead of destroying the Texture."),s())}),i}const Yg=".svg",Wr="image/svg+xml",Xg={extension:{type:I.LoadParser,priority:pe.Low,name:"loadSVG"},name:"loadSVG",id:"svg",config:{crossOrigin:"anonymous",parseAsGraphicsContext:!1},test(n){return fe(n,Wr)||li(n,Yg)},async load(n,e,t){var i;return((i=e.data)==null?void 0:i.parseAsGraphicsContext)??this.config.parseAsGraphicsContext?qg(n):jg(n,e,t,this.config.crossOrigin)},unload(n){n.destroy(!0)}};async function jg(n,e,t,i){var y,x,S;const s=fe(n,Wr),r=$.get().createImage();r.crossOrigin=i,r.src=n,await new Promise((v,b)=>{r.complete?v(r):(r.onload=()=>v(r),r.onerror=b)}),await r.decode();const o=((y=e.data)==null?void 0:y.width)??r.width,a=((x=e.data)==null?void 0:x.height)??r.height,h=((S=e.data)==null?void 0:S.resolution)||Lr(n),l=Math.ceil(o*h),c=Math.ceil(a*h),d=$.get().createCanvas(l,c),u=d.getContext("2d");u.imageSmoothingEnabled=!0,u.imageSmoothingQuality="high",u.drawImage(r,0,0,o*h,a*h);const{parseAsGraphicsContext:p,...g}=e.data??{},m=new ei({resource:d,alphaMode:"premultiply-alpha-on-upload",resolution:h,...g});return Or(m,t,n)}function Zg(n){const e="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";let t="",i=0;for(n=n.replace(/[^A-Za-z0-9\+\/\=]/g,"");i<n.length;){const s=e.indexOf(n.charAt(i++)),r=e.indexOf(n.charAt(i++)),o=e.indexOf(n.charAt(i++)),a=e.indexOf(n.charAt(i++)),h=s<<2|r>>4,l=(r&15)<<4|o>>2,c=(o&3)<<6|a;t+=String.fromCharCode(h),o!==64&&(t+=String.fromCharCode(l)),a!==64&&(t+=String.fromCharCode(c))}return t}async function qg(n){const e=fe(n,Wr);let t;if(e)if(n.includes(";base64,")){const s=n.split(";base64,")[1];t=Zg(s)}else{const s=n.split(",")[1];t=decodeURIComponent(s)}else t=await(await $.get().fetch(n)).text();const i=new gt;return i.svg(t),i}const Kg=`(function () {
241
+ 'use strict';
242
+
243
+ const WHITE_PNG = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII=";
244
+ async function checkImageBitmap() {
245
+ try {
246
+ if (typeof createImageBitmap !== "function") return false;
247
+ const response = await fetch(WHITE_PNG);
248
+ const imageBlob = await response.blob();
249
+ const imageBitmap = await createImageBitmap(imageBlob);
250
+ return imageBitmap.width === 1 && imageBitmap.height === 1;
251
+ } catch (_e) {
252
+ return false;
253
+ }
254
+ }
255
+ void checkImageBitmap().then((result) => {
256
+ self.postMessage(result);
257
+ });
258
+
259
+ })();
260
+ `;let Ze=null,lr=class{constructor(){Ze||(Ze=URL.createObjectURL(new Blob([Kg],{type:"application/javascript"}))),this.worker=new Worker(Ze)}};lr.revokeObjectURL=function(){Ze&&(URL.revokeObjectURL(Ze),Ze=null)};const Qg=`(function () {
261
+ 'use strict';
262
+
263
+ async function loadImageBitmap(url, alphaMode) {
264
+ const response = await fetch(url);
265
+ if (!response.ok) {
266
+ throw new Error(\`[WorkerManager.loadImageBitmap] Failed to fetch \${url}: \${response.status} \${response.statusText}\`);
267
+ }
268
+ const imageBlob = await response.blob();
269
+ return alphaMode === "premultiplied-alpha" ? createImageBitmap(imageBlob, { premultiplyAlpha: "none" }) : createImageBitmap(imageBlob);
270
+ }
271
+ self.onmessage = async (event) => {
272
+ try {
273
+ const imageBitmap = await loadImageBitmap(event.data.data[0], event.data.data[1]);
274
+ self.postMessage({
275
+ data: imageBitmap,
276
+ uuid: event.data.uuid,
277
+ id: event.data.id
278
+ }, [imageBitmap]);
279
+ } catch (e) {
280
+ self.postMessage({
281
+ error: e,
282
+ uuid: event.data.uuid,
283
+ id: event.data.id
284
+ });
285
+ }
286
+ };
287
+
288
+ })();
289
+ `;let qe=null;class Vl{constructor(){qe||(qe=URL.createObjectURL(new Blob([Qg],{type:"application/javascript"}))),this.worker=new Worker(qe)}}Vl.revokeObjectURL=function(){qe&&(URL.revokeObjectURL(qe),qe=null)};let Ta=0,Tn;class Jg{constructor(){this._initialized=!1,this._createdWorkers=0,this._workerPool=[],this._queue=[],this._resolveHash={}}isImageBitmapSupported(){return this._isImageBitmapSupported!==void 0?this._isImageBitmapSupported:(this._isImageBitmapSupported=new Promise(e=>{const{worker:t}=new lr;t.addEventListener("message",i=>{t.terminate(),lr.revokeObjectURL(),e(i.data)})}),this._isImageBitmapSupported)}loadImageBitmap(e,t){var i;return this._run("loadImageBitmap",[e,(i=t==null?void 0:t.data)==null?void 0:i.alphaMode])}async _initWorkers(){this._initialized||(this._initialized=!0)}_getWorker(){Tn===void 0&&(Tn=navigator.hardwareConcurrency||4);let e=this._workerPool.pop();return!e&&this._createdWorkers<Tn&&(this._createdWorkers++,e=new Vl().worker,e.addEventListener("message",t=>{this._complete(t.data),this._returnWorker(t.target),this._next()})),e}_returnWorker(e){this._workerPool.push(e)}_complete(e){this._resolveHash[e.uuid]&&(e.error!==void 0?this._resolveHash[e.uuid].reject(e.error):this._resolveHash[e.uuid].resolve(e.data),delete this._resolveHash[e.uuid])}async _run(e,t){await this._initWorkers();const i=new Promise((s,r)=>{this._queue.push({id:e,arguments:t,resolve:s,reject:r})});return this._next(),i}_next(){if(!this._queue.length)return;const e=this._getWorker();if(!e)return;const t=this._queue.pop(),i=t.id;this._resolveHash[Ta]={resolve:t.resolve,reject:t.reject},e.postMessage({data:t.arguments,uuid:Ta++,id:i})}reset(){this._workerPool.forEach(e=>e.terminate()),this._workerPool.length=0,Object.values(this._resolveHash).forEach(({reject:e})=>{e==null||e(new Error("WorkerManager has been reset before completion"))}),this._resolveHash={},this._queue.length=0,this._initialized=!1,this._createdWorkers=0}}const Ra=new Jg,tm=[".jpeg",".jpg",".png",".webp",".avif"],em=["image/jpeg","image/png","image/webp","image/avif"];async function im(n,e){var s;const t=await $.get().fetch(n);if(!t.ok)throw new Error(`[loadImageBitmap] Failed to fetch ${n}: ${t.status} ${t.statusText}`);const i=await t.blob();return((s=e==null?void 0:e.data)==null?void 0:s.alphaMode)==="premultiplied-alpha"?createImageBitmap(i,{premultiplyAlpha:"none"}):createImageBitmap(i)}const Nl={name:"loadTextures",id:"texture",extension:{type:I.LoadParser,priority:pe.High,name:"loadTextures"},config:{preferWorkers:!0,preferCreateImageBitmap:!0,crossOrigin:"anonymous"},test(n){return fe(n,em)||li(n,tm)},async load(n,e,t){var r;let i=null;globalThis.createImageBitmap&&this.config.preferCreateImageBitmap?this.config.preferWorkers&&await Ra.isImageBitmapSupported()?i=await Ra.loadImageBitmap(n,e):i=await im(n,e):i=await new Promise((o,a)=>{i=$.get().createImage(),i.crossOrigin=this.config.crossOrigin,i.src=n,i.complete?o(i):(i.onload=()=>{o(i)},i.onerror=a)});const s=new ei({resource:i,alphaMode:"premultiply-alpha-on-upload",resolution:((r=e.data)==null?void 0:r.resolution)||Lr(n),...e.data});return Or(s,t,n)},unload(n){n.destroy(!0)}},sm=[".mp4",".m4v",".webm",".ogg",".ogv",".h264",".avi",".mov"];let Rn,kn;function nm(n,e,t){t===void 0&&!e.startsWith("data:")?n.crossOrigin=om(e):t!==!1&&(n.crossOrigin=typeof t=="string"?t:"anonymous")}function rm(n){return new Promise((e,t)=>{n.addEventListener("canplaythrough",i),n.addEventListener("error",s),n.load();function i(){r(),e()}function s(o){r(),t(o)}function r(){n.removeEventListener("canplaythrough",i),n.removeEventListener("error",s)}})}function om(n,e=globalThis.location){if(n.startsWith("data:"))return"";e||(e=globalThis.location);const t=new URL(n,document.baseURI);return t.hostname!==e.hostname||t.port!==e.port||t.protocol!==e.protocol?"anonymous":""}function am(){const n=[],e=[];for(const t of sm){const i=Mi.MIME_TYPES[t.substring(1)]||`video/${t.substring(1)}`;Bs(i)&&(n.push(t),e.includes(i)||e.push(i))}return{validVideoExtensions:n,validVideoMime:e}}const hm={name:"loadVideo",id:"video",extension:{type:I.LoadParser,name:"loadVideo"},test(n){if(!Rn||!kn){const{validVideoExtensions:i,validVideoMime:s}=am();Rn=i,kn=s}const e=fe(n,kn),t=li(n,Rn);return e||t},async load(n,e,t){var h,l;const i={...Mi.defaultOptions,resolution:((h=e.data)==null?void 0:h.resolution)||Lr(n),alphaMode:((l=e.data)==null?void 0:l.alphaMode)||await Zh(),...e.data},s=document.createElement("video"),r={preload:i.autoLoad!==!1?"auto":void 0,"webkit-playsinline":i.playsinline!==!1?"":void 0,playsinline:i.playsinline!==!1?"":void 0,muted:i.muted===!0?"":void 0,loop:i.loop===!0?"":void 0,autoplay:i.autoPlay!==!1?"":void 0};Object.keys(r).forEach(c=>{const d=r[c];d!==void 0&&s.setAttribute(c,d)}),i.muted===!0&&(s.muted=!0),nm(s,n,i.crossorigin);const o=document.createElement("source");let a;if(i.mime)a=i.mime;else if(n.startsWith("data:"))a=n.slice(5,n.indexOf(";"));else if(!n.startsWith("blob:")){const c=n.split("?")[0].slice(n.lastIndexOf(".")+1).toLowerCase();a=Mi.MIME_TYPES[c]||`video/${c}`}return o.src=n,a&&(o.type=a),new Promise((c,d)=>{i.preload&&!i.autoPlay&&s.load(),s.addEventListener("canplay",u),s.addEventListener("error",p),o.addEventListener("error",p),s.appendChild(o);async function u(){const m=new Mi({...i,resource:s});g(),e.data.preload&&await rm(s),c(Or(m,t,n))}function p(m){g(),d(m)}function g(){s.removeEventListener("canplay",u),s.removeEventListener("error",p),o.removeEventListener("error",p)}})},unload(n){n.destroy(!0)}},$l={extension:{type:I.ResolveParser,name:"resolveTexture"},test:Nl.test,parse:n=>{var e;return{resolution:parseFloat(((e=hi.RETINA_PREFIX.exec(n))==null?void 0:e[1])??"1"),format:n.split(".").pop(),src:n}}},lm={extension:{type:I.ResolveParser,priority:-2,name:"resolveJson"},test:n=>hi.RETINA_PREFIX.test(n)&&n.endsWith(".json"),parse:$l.parse};class cm{constructor(){this._detections=[],this._initialized=!1,this.resolver=new hi,this.loader=new Lp,this.cache=xt,this._backgroundLoader=new Tp(this.loader),this._backgroundLoader.active=!0,this.reset()}async init(e={}){var r,o;if(this._initialized){nt("[Assets]AssetManager already initialized, did you load before calling this Assets.init()?");return}if(this._initialized=!0,e.defaultSearchParams&&this.resolver.setDefaultSearchParams(e.defaultSearchParams),e.basePath&&(this.resolver.basePath=e.basePath),e.bundleIdentifier&&this.resolver.setBundleIdentifier(e.bundleIdentifier),e.manifest){let a=e.manifest;typeof a=="string"&&(a=await this.load(a)),this.resolver.addManifest(a)}const t=((r=e.texturePreference)==null?void 0:r.resolution)??1,i=typeof t=="number"?[t]:t,s=await this._detectFormats({preferredFormats:(o=e.texturePreference)==null?void 0:o.format,skipDetections:e.skipDetections,detections:this._detections});this.resolver.prefer({params:{format:s,resolution:i}}),e.preferences&&this.setPreferences(e.preferences),e.loadOptions&&(this.loader.loadOptions={...this.loader.loadOptions,...e.loadOptions})}add(e){this.resolver.add(e)}async load(e,t){this._initialized||await this.init();const i=ws(e),s=Ot(e).map(a=>{if(typeof a!="string"){const h=this.resolver.getAlias(a);return h.some(l=>!this.resolver.hasKey(l))&&this.add(a),Array.isArray(h)?h[0]:h}return this.resolver.hasKey(a)||this.add({alias:a,src:a}),a}),r=this.resolver.resolve(s),o=await this._mapLoadToResolve(r,t);return i?o[s[0]]:o}addBundle(e,t){this.resolver.addBundle(e,t)}async loadBundle(e,t){this._initialized||await this.init();let i=!1;typeof e=="string"&&(i=!0,e=[e]);const s=this.resolver.resolveBundle(e),r={},o=Object.keys(s);let a=0;const h=[],l=()=>{t==null||t(h.reduce((d,u)=>d+u,0)/a)},c=o.map((d,u)=>{const p=s[d],g=Object.values(p),y=[...new Set(g.flat())].reduce((x,S)=>x+(S.progressSize||1),0);return h.push(0),a+=y,this._mapLoadToResolve(p,x=>{h[u]=x*y,l()}).then(x=>{r[d]=x})});return await Promise.all(c),i?r[e[0]]:r}async backgroundLoad(e){this._initialized||await this.init(),typeof e=="string"&&(e=[e]);const t=this.resolver.resolve(e);this._backgroundLoader.add(Object.values(t))}async backgroundLoadBundle(e){this._initialized||await this.init(),typeof e=="string"&&(e=[e]);const t=this.resolver.resolveBundle(e);Object.values(t).forEach(i=>{this._backgroundLoader.add(Object.values(i))})}reset(){this.resolver.reset(),this.loader.reset(),this.cache.reset(),this._initialized=!1}get(e){if(typeof e=="string")return xt.get(e);const t={};for(let i=0;i<e.length;i++)t[i]=xt.get(e[i]);return t}async _mapLoadToResolve(e,t){const i=[...new Set(Object.values(e))];this._backgroundLoader.active=!1;const s=await this.loader.load(i,t);this._backgroundLoader.active=!0;const r={};return i.forEach(o=>{const a=s[o.src],h=[o.src];o.alias&&h.push(...o.alias),h.forEach(l=>{r[l]=a}),xt.set(h,a)}),r}async unload(e){this._initialized||await this.init();const t=Ot(e).map(s=>typeof s!="string"?s.src:s),i=this.resolver.resolve(t);await this._unloadFromResolved(i)}async unloadBundle(e){this._initialized||await this.init(),e=Ot(e);const t=this.resolver.resolveBundle(e),i=Object.keys(t).map(s=>this._unloadFromResolved(t[s]));await Promise.all(i)}async _unloadFromResolved(e){const t=Object.values(e);t.forEach(i=>{xt.remove(i.src)}),await this.loader.unload(t)}async _detectFormats(e){let t=[];e.preferredFormats&&(t=Array.isArray(e.preferredFormats)?e.preferredFormats:[e.preferredFormats]);for(const i of e.detections)e.skipDetections||await i.test()?t=await i.add(t):e.skipDetections||(t=await i.remove(t));return t=t.filter((i,s)=>t.indexOf(i)===s),t}get detections(){return this._detections}setPreferences(e){this.loader.parsers.forEach(t=>{t.config&&Object.keys(t.config).filter(i=>i in e).forEach(i=>{t.config[i]=e[i]})})}}const N=new cm;K.handleByList(I.LoadParser,N.loader.parsers).handleByList(I.ResolveParser,N.resolver.parsers).handleByList(I.CacheParser,N.cache.parsers).handleByList(I.DetectionParser,N.detections);K.add(Rp,Ip,kp,zp,Dp,Fp,Bp,Gp,Vp,Kp,Xg,Nl,hm,Ap,Mp,$l,lm);const ka={loader:I.LoadParser,resolver:I.ResolveParser,cache:I.CacheParser,detection:I.DetectionParser};K.handle(I.Asset,n=>{const e=n.ref;Object.entries(ka).filter(([t])=>!!e[t]).forEach(([t,i])=>K.add(Object.assign(e[t],{extension:e[t].extension??i})))},n=>{const e=n.ref;Object.keys(ka).filter(t=>!!e[t]).forEach(t=>K.remove(e[t]))});class Yl{constructor(e){this._attachedDomElements=[],this._renderer=e,this._renderer.runners.postrender.add(this),this._renderer.runners.init.add(this),this._domElement=document.createElement("div"),this._domElement.style.position="absolute",this._domElement.style.top="0",this._domElement.style.left="0",this._domElement.style.pointerEvents="none",this._domElement.style.zIndex="1000"}init(){this._canvasObserver=new Iu({domElement:this._domElement,renderer:this._renderer})}addRenderable(e,t){this._attachedDomElements.includes(e)||this._attachedDomElements.push(e)}updateRenderable(e){}validateRenderable(e){return!0}postrender(){const e=this._attachedDomElements;if(e.length===0){this._domElement.remove();return}this._canvasObserver.ensureAttached();for(let t=0;t<e.length;t++){const i=e[t],s=i.element;if(!i.parent||i.globalDisplayStatus<7)s==null||s.remove(),e.splice(t,1),t--;else{this._domElement.contains(s)||(s.style.position="absolute",s.style.pointerEvents="auto",this._domElement.appendChild(s));const r=i.worldTransform,o=i._anchor,a=i.width*o.x,h=i.height*o.y;s.style.transformOrigin=`${a}px ${h}px`,s.style.transform=`matrix(${r.a}, ${r.b}, ${r.c}, ${r.d}, ${r.tx-a}, ${r.ty-h})`,s.style.opacity=i.groupAlpha.toString()}}}destroy(){var e;this._renderer.runners.postrender.remove(this);for(let t=0;t<this._attachedDomElements.length;t++)(e=this._attachedDomElements[t].element)==null||e.remove();this._attachedDomElements.length=0,this._domElement.remove(),this._canvasObserver.destroy(),this._renderer=null}}Yl.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:"dom"};K.add(Yl);class dm extends ai{constructor(e={}){const{element:t,anchor:i,...s}=e;super({label:"DOMContainer",...s}),this.renderPipeId="dom",this.batched=!1,this._anchor=new J(0,0),i&&(this.anchor=i),this.element=e.element||document.createElement("div")}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}set element(e){this._element!==e&&(this._element=e,this.onViewUpdate())}get element(){return this._element}updateBounds(){const e=this._bounds,t=this._element;if(!t){e.minX=0,e.minY=0,e.maxX=0,e.maxY=0;return}const{offsetWidth:i,offsetHeight:s}=t;e.minX=0,e.maxX=i,e.minY=0,e.maxY=s}destroy(e=!1){var t,i;super.destroy(e),(i=(t=this._element)==null?void 0:t.parentNode)==null||i.removeChild(this._element),this._element=null,this._anchor=null}}class um extends Tr{constructor(){super(...arguments),this.client=new J,this.movement=new J,this.offset=new J,this.global=new J,this.screen=new J}get clientX(){return this.client.x}get clientY(){return this.client.y}get x(){return this.clientX}get y(){return this.clientY}get movementX(){return this.movement.x}get movementY(){return this.movement.y}get offsetX(){return this.offset.x}get offsetY(){return this.offset.y}get globalX(){return this.global.x}get globalY(){return this.global.y}get screenX(){return this.screen.x}get screenY(){return this.screen.y}getLocalPosition(e,t,i){return e.worldTransform.applyInverse(i||this.global,t)}getModifierState(e){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(e)}initMouseEvent(e,t,i,s,r,o,a,h,l,c,d,u,p,g,m){throw new Error("Method not implemented.")}}class Ia extends um{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return this.type==="pointermove"||this.type==="mousemove"||this.type==="touchmove"?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}var pm=`in vec2 aPosition;
290
+ out vec2 vTextureCoord;
291
+
292
+ uniform vec4 uInputSize;
293
+ uniform vec4 uOutputFrame;
294
+ uniform vec4 uOutputTexture;
295
+
296
+ vec4 filterVertexPosition( void )
297
+ {
298
+ vec2 position = aPosition * uOutputFrame.zw + uOutputFrame.xy;
299
+
300
+ position.x = position.x * (2.0 / uOutputTexture.x) - 1.0;
301
+ position.y = position.y * (2.0*uOutputTexture.z / uOutputTexture.y) - uOutputTexture.z;
302
+
303
+ return vec4(position, 0.0, 1.0);
304
+ }
305
+
306
+ vec2 filterTextureCoord( void )
307
+ {
308
+ return aPosition * (uOutputFrame.zw * uInputSize.zw);
309
+ }
310
+
311
+ void main(void)
312
+ {
313
+ gl_Position = filterVertexPosition();
314
+ vTextureCoord = filterTextureCoord();
315
+ }
316
+ `,fm=`
317
+ in vec2 vTextureCoord;
318
+
319
+ out vec4 finalColor;
320
+
321
+ uniform float uAlpha;
322
+ uniform sampler2D uTexture;
323
+
324
+ void main()
325
+ {
326
+ finalColor = texture(uTexture, vTextureCoord) * uAlpha;
327
+ }
328
+ `,Ea=`struct GlobalFilterUniforms {
329
+ uInputSize:vec4<f32>,
330
+ uInputPixel:vec4<f32>,
331
+ uInputClamp:vec4<f32>,
332
+ uOutputFrame:vec4<f32>,
333
+ uGlobalFrame:vec4<f32>,
334
+ uOutputTexture:vec4<f32>,
335
+ };
336
+
337
+ struct AlphaUniforms {
338
+ uAlpha:f32,
339
+ };
340
+
341
+ @group(0) @binding(0) var<uniform> gfu: GlobalFilterUniforms;
342
+ @group(0) @binding(1) var uTexture: texture_2d<f32>;
343
+ @group(0) @binding(2) var uSampler : sampler;
344
+
345
+ @group(1) @binding(0) var<uniform> alphaUniforms : AlphaUniforms;
346
+
347
+ struct VSOutput {
348
+ @builtin(position) position: vec4<f32>,
349
+ @location(0) uv : vec2<f32>
350
+ };
351
+
352
+ fn filterVertexPosition(aPosition:vec2<f32>) -> vec4<f32>
353
+ {
354
+ var position = aPosition * gfu.uOutputFrame.zw + gfu.uOutputFrame.xy;
355
+
356
+ position.x = position.x * (2.0 / gfu.uOutputTexture.x) - 1.0;
357
+ position.y = position.y * (2.0*gfu.uOutputTexture.z / gfu.uOutputTexture.y) - gfu.uOutputTexture.z;
358
+
359
+ return vec4(position, 0.0, 1.0);
360
+ }
361
+
362
+ fn filterTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
363
+ {
364
+ return aPosition * (gfu.uOutputFrame.zw * gfu.uInputSize.zw);
365
+ }
366
+
367
+ fn globalTextureCoord( aPosition:vec2<f32> ) -> vec2<f32>
368
+ {
369
+ return (aPosition.xy / gfu.uGlobalFrame.zw) + (gfu.uGlobalFrame.xy / gfu.uGlobalFrame.zw);
370
+ }
371
+
372
+ fn getSize() -> vec2<f32>
373
+ {
374
+ return gfu.uGlobalFrame.zw;
375
+ }
376
+
377
+ @vertex
378
+ fn mainVertex(
379
+ @location(0) aPosition : vec2<f32>,
380
+ ) -> VSOutput {
381
+ return VSOutput(
382
+ filterVertexPosition(aPosition),
383
+ filterTextureCoord(aPosition)
384
+ );
385
+ }
386
+
387
+ @fragment
388
+ fn mainFragment(
389
+ @location(0) uv: vec2<f32>,
390
+ @builtin(position) position: vec4<f32>
391
+ ) -> @location(0) vec4<f32> {
392
+
393
+ var sample = textureSample(uTexture, uSampler, uv);
394
+
395
+ return sample * alphaUniforms.uAlpha;
396
+ }`;const Xl=class jl extends Ju{constructor(e){e={...jl.defaultOptions,...e};const t=de.from({vertex:{source:Ea,entryPoint:"mainVertex"},fragment:{source:Ea,entryPoint:"mainFragment"}}),i=ii.from({vertex:pm,fragment:fm,name:"alpha-filter"}),{alpha:s,...r}=e,o=new si({uAlpha:{value:s,type:"f32"}});super({...r,gpuProgram:t,glProgram:i,resources:{alphaUniforms:o}})}get alpha(){return this.resources.alphaUniforms.uniforms.uAlpha}set alpha(e){this.resources.alphaUniforms.uniforms.uAlpha=e}};Xl.defaultOptions={alpha:1};let gm=Xl;function Da(n,e,t,i,s,r,o,a){const h=o-t,l=a-i,c=s-t,d=r-i,u=n-t,p=e-i,g=h*h+l*l,m=h*c+l*d,y=h*u+l*p,x=c*c+d*d,S=c*u+d*p,v=1/(g*x-m*m),b=(x*y-m*S)*v,P=(g*S-m*y)*v;return b>=0&&P>=0&&b+P<1}class mm{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&(this.graphicsData.destroy(),this.graphicsData=null)}destroy(){this.reset()}}class ym{constructor(){this.instructions=new Mr}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}}const Gr=class cr{constructor(e){this._renderer=e,this._managedContexts=new ci({renderer:e,type:"resource",name:"graphicsContext"})}init(e){cr.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??cr.defaultOptions.bezierSmoothness}getContextRenderData(e){return this.getGpuContext(e).graphicsData||this._initContextRenderData(e)}updateGpuContext(e){const t=e._gpuData,i=!!t[this._renderer.uid],s=t[this._renderer.uid]||this._initContext(e);return(e.dirty||!i)&&(i&&s.reset(),s.isBatchable=!1,e.dirty=!1),s}getGpuContext(e){return e._gpuData[this._renderer.uid]||this._initContext(e)}_initContextRenderData(e){const t=new ym,i=this.getGpuContext(e);return i.graphicsData=t,t.init(),t}_initContext(e){const t=new mm;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};Gr.extension={type:[I.CanvasSystem],name:"graphicsContext"};Gr.defaultOptions={bezierSmoothness:.5};let xm=Gr;class Zl{constructor(e,t){this.state=Ni.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new ci({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){return!1}addRenderable(e,t){this._managedGraphics.add(e),this.renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){e.isRenderable&&this._adaptor.execute(this,e)}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null}}Zl.extension={type:[I.CanvasPipes],name:"graphics"};function Ur(n,e,t){const i=(n>>24&255)/255;e[t++]=(n&255)/255*i,e[t++]=(n>>8&255)/255*i,e[t++]=(n>>16&255)/255*i,e[t++]=i}class Sm{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{Rt.return(e)}),this.batches.length=0}}class ql{constructor(e,t){this.state=Ni.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new ci({renderer:e,type:"renderable",priority:-1,name:"graphics"})}contextChange(){this._adaptor.contextChange(this.renderer)}validateRenderable(e){const t=e.context,i=!!e._gpuData,r=this.renderer.graphicsContext.updateGpuContext(t);return!!(r.isBatchable||i!==r.isBatchable)}addRenderable(e,t){const s=this.renderer.graphicsContext.updateGpuContext(e.context);e.didViewUpdate&&this._rebuild(e),s.isBatchable?this._addToBatcher(e,t):(this.renderer.renderPipes.batch.break(t),t.add(e))}updateRenderable(e){const i=this._getGpuDataForRenderable(e).batches;for(let s=0;s<i.length;s++){const r=i[s];r._batcher.updateElement(r)}}execute(e){if(!e.isRenderable)return;const t=this.renderer,i=e.context;if(!t.graphicsContext.getGpuContext(i).batches.length)return;const r=i.customShader||this._adaptor.shader;this.state.blendMode=e.groupBlendMode;const o=r.resources.localUniforms.uniforms;o.uTransformMatrix=e.groupTransform,o.uRound=t._roundPixels|e._roundPixels,Ur(e.groupColorAlpha,o.uColor,0),this._adaptor.execute(this,e)}_rebuild(e){const t=this._getGpuDataForRenderable(e),s=this.renderer.graphicsContext.updateGpuContext(e.context);t.destroy(),s.isBatchable&&this._updateBatchesForRenderable(e,t)}_addToBatcher(e,t){const i=this.renderer.renderPipes.batch,s=this._getGpuDataForRenderable(e).batches;for(let r=0;r<s.length;r++){const o=s[r];i.addToBatch(o,t)}}_getGpuDataForRenderable(e){return e._gpuData[this.renderer.uid]||this._initGpuDataForRenderable(e)}_initGpuDataForRenderable(e){const t=new Sm;return e._gpuData[this.renderer.uid]=t,this._managedGraphics.add(e),t}_updateBatchesForRenderable(e,t){const i=e.context,r=this.renderer.graphicsContext.getGpuContext(i),o=this.renderer._roundPixels|e._roundPixels;t.batches=r.batches.map(a=>{const h=Rt.get(Er);return a.copyTo(h),h.renderable=e,h.roundPixels=o,h})}destroy(){this._managedGraphics.destroy(),this.renderer=null,this._adaptor.destroy(),this._adaptor=null,this.state=null}}ql.extension={type:[I.WebGLPipes,I.WebGPUPipes],name:"graphics"};K.add(Zl);K.add(ql);K.add(xm);K.add(Br);class U extends ai{constructor(e){e instanceof gt&&(e={context:e});const{context:t,roundPixels:i,...s}=e||{};super({label:"Graphics",...s}),this.renderPipeId="graphics",t?this.context=t:(this.context=this._ownedContext=new gt,this.context.autoGarbageCollect=this.autoGarbageCollect),this.didViewUpdate=!0,this.allowChildren=!1,this.roundPixels=i??!1}set context(e){e!==this._context&&(this._context&&(this._context.off("update",this.onViewUpdate,this),this._context.off("unload",this.unload,this)),this._context=e,this._context.on("update",this.onViewUpdate,this),this._context.on("unload",this.unload,this),this.onViewUpdate())}get context(){return this._context}get bounds(){return this._context.bounds}updateBounds(){}containsPoint(e){return this._context.containsPoint(e)}destroy(e){this._ownedContext&&!e?this._ownedContext.destroy(e):(e===!0||(e==null?void 0:e.context)===!0)&&this._context.destroy(e),this._ownedContext=null,this._context=null,super.destroy(e)}_onTouch(e){this._gcLastUsed=e,this._context._gcLastUsed=e}_callContextMethod(e,t){return this.context[e](...t),this}setFillStyle(...e){return this._callContextMethod("setFillStyle",e)}setStrokeStyle(...e){return this._callContextMethod("setStrokeStyle",e)}fill(...e){return this._callContextMethod("fill",e)}stroke(...e){return this._callContextMethod("stroke",e)}texture(...e){return this._callContextMethod("texture",e)}beginPath(){return this._callContextMethod("beginPath",[])}cut(){return this._callContextMethod("cut",[])}arc(...e){return this._callContextMethod("arc",e)}arcTo(...e){return this._callContextMethod("arcTo",e)}arcToSvg(...e){return this._callContextMethod("arcToSvg",e)}bezierCurveTo(...e){return this._callContextMethod("bezierCurveTo",e)}closePath(){return this._callContextMethod("closePath",[])}ellipse(...e){return this._callContextMethod("ellipse",e)}circle(...e){return this._callContextMethod("circle",e)}path(...e){return this._callContextMethod("path",e)}lineTo(...e){return this._callContextMethod("lineTo",e)}moveTo(...e){return this._callContextMethod("moveTo",e)}quadraticCurveTo(...e){return this._callContextMethod("quadraticCurveTo",e)}rect(...e){return this._callContextMethod("rect",e)}roundRect(...e){return this._callContextMethod("roundRect",e)}poly(...e){return this._callContextMethod("poly",e)}regularPoly(...e){return this._callContextMethod("regularPoly",e)}roundPoly(...e){return this._callContextMethod("roundPoly",e)}roundShape(...e){return this._callContextMethod("roundShape",e)}filletRect(...e){return this._callContextMethod("filletRect",e)}chamferRect(...e){return this._callContextMethod("chamferRect",e)}star(...e){return this._callContextMethod("star",e)}svg(...e){return this._callContextMethod("svg",e)}restore(...e){return this._callContextMethod("restore",e)}save(){return this._callContextMethod("save",[])}getTransform(){return this.context.getTransform()}resetTransform(){return this._callContextMethod("resetTransform",[])}rotateTransform(...e){return this._callContextMethod("rotate",e)}scaleTransform(...e){return this._callContextMethod("scale",e)}setTransform(...e){return this._callContextMethod("setTransform",e)}transform(...e){return this._callContextMethod("transform",e)}translateTransform(...e){return this._callContextMethod("translate",e)}clear(){return this._callContextMethod("clear",[])}get fillStyle(){return this._context.fillStyle}set fillStyle(e){this._context.fillStyle=e}get strokeStyle(){return this._context.strokeStyle}set strokeStyle(e){this._context.strokeStyle=e}clone(e=!1){return e?new U(this._context.clone()):(this._ownedContext=null,new U(this._context))}lineStyle(e,t,i){V(Q,"Graphics#lineStyle is no longer needed. Use Graphics#setStrokeStyle to set the stroke style.");const s={};return e&&(s.width=e),t&&(s.color=t),i&&(s.alpha=i),this.context.strokeStyle=s,this}beginFill(e,t){V(Q,"Graphics#beginFill is no longer needed. Use Graphics#fill to fill the shape with the desired style.");const i={};return e!==void 0&&(i.color=e),t!==void 0&&(i.alpha=t),this.context.fillStyle=i,this}endFill(){V(Q,"Graphics#endFill is no longer needed. Use Graphics#fill to fill the shape with the desired style."),this.context.fill();const e=this.context.strokeStyle;return(e.width!==gt.defaultStrokeStyle.width||e.color!==gt.defaultStrokeStyle.color||e.alpha!==gt.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return V(Q,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",e)}drawEllipse(...e){return V(Q,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",e)}drawPolygon(...e){return V(Q,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",e)}drawRect(...e){return V(Q,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",e)}drawRoundedRect(...e){return V(Q,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",e)}drawStar(...e){return V(Q,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",e)}}const Kl=class Ql extends Oi{constructor(...e){let t=e[0]??{};t instanceof Float32Array&&(V(Q,"use new MeshGeometry({ positions, uvs, indices }) instead"),t={positions:t,uvs:e[1],indices:e[2]}),t={...Ql.defaultOptions,...t};const i=t.positions||new Float32Array([0,0,1,0,1,1,0,1]);let s=t.uvs;s||(t.positions?s=new Float32Array(i.length):s=new Float32Array([0,0,1,0,1,1,0,1]));const r=t.indices||new Uint32Array([0,1,2,0,2,3]),o=t.shrinkBuffersToFit,a=new le({data:i,label:"attribute-mesh-positions",shrinkToFit:o,usage:ft.VERTEX|ft.COPY_DST}),h=new le({data:s,label:"attribute-mesh-uvs",shrinkToFit:o,usage:ft.VERTEX|ft.COPY_DST}),l=new le({data:r,label:"index-mesh-buffer",shrinkToFit:o,usage:ft.INDEX|ft.COPY_DST});super({attributes:{aPosition:{buffer:a,format:"float32x2",stride:2*4,offset:0},aUV:{buffer:h,format:"float32x2",stride:2*4,offset:0}},indexBuffer:l,topology:t.topology}),this.batchMode="auto"}get positions(){return this.attributes.aPosition.buffer.data}set positions(e){this.attributes.aPosition.buffer.data=e}get uvs(){return this.attributes.aUV.buffer.data}set uvs(e){this.attributes.aUV.buffer.data=e}get indices(){return this.indexBuffer.data}set indices(e){this.indexBuffer.data=e}};Kl.defaultOptions={topology:"triangle-list",shrinkBuffersToFit:!1};let Hr=Kl;class Jl{constructor(){this.batcherName="default",this.packAsQuad=!1,this.indexOffset=0,this.attributeOffset=0,this.roundPixels=0,this._batcher=null,this._batch=null,this._textureMatrixUpdateId=-1,this._uvUpdateId=-1}get blendMode(){return this.renderable.groupBlendMode}get topology(){return this._topology||this.geometry.topology}set topology(e){this._topology=e}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.geometry=null,this._uvUpdateId=-1,this._textureMatrixUpdateId=-1}setTexture(e){this.texture!==e&&(this.texture=e,this._textureMatrixUpdateId=-1)}get uvs(){const t=this.geometry.getBuffer("aUV"),i=t.data;let s=i;const r=this.texture.textureMatrix;return r.isSimple||(s=this._transformedUvs,(this._textureMatrixUpdateId!==r._updateID||this._uvUpdateId!==t._updateID)&&((!s||s.length<i.length)&&(s=this._transformedUvs=new Float32Array(i.length)),this._textureMatrixUpdateId=r._updateID,this._uvUpdateId=t._updateID,r.multiplyUvs(i,s))),s}get positions(){return this.geometry.positions}get indices(){return this.geometry.indices}get color(){return this.renderable.groupColorAlpha}get groupTransform(){return this.renderable.groupTransform}get attributeSize(){return this.geometry.positions.length/2}get indexSize(){return this.geometry.indices.length}}class Fa{destroy(){}}class tc{constructor(e,t){this.localUniforms=new si({uTransformMatrix:{value:new H,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),this.localUniformsBindGroup=new Ai({0:this.localUniforms}),this.renderer=e,this._adaptor=t,this._adaptor.init()}validateRenderable(e){const t=this._getMeshData(e),i=t.batched,s=e.batched;if(t.batched=s,i!==s)return!0;if(s){const r=e._geometry;if(r.indices.length!==t.indexSize||r.positions.length!==t.vertexSize)return t.indexSize=r.indices.length,t.vertexSize=r.positions.length,!0;const o=this._getBatchableMesh(e);return o.texture.uid!==e._texture.uid&&(o._textureMatrixUpdateId=-1),!o._batcher.checkAndUpdateTexture(o,e._texture)}return!1}addRenderable(e,t){var r,o;const i=this.renderer.renderPipes.batch,s=this._getMeshData(e);if(e.didViewUpdate&&(s.indexSize=(r=e._geometry.indices)==null?void 0:r.length,s.vertexSize=(o=e._geometry.positions)==null?void 0:o.length),s.batched){const a=this._getBatchableMesh(e);a.setTexture(e._texture),a.geometry=e._geometry,i.addToBatch(a,t)}else i.break(t),t.add(e)}updateRenderable(e){if(e.batched){const t=this._getBatchableMesh(e);t.setTexture(e._texture),t.geometry=e._geometry,t._batcher.updateElement(t)}}execute(e){if(!e.isRenderable)return;e.state.blendMode=Cs(e.groupBlendMode,e.texture._source);const t=this.localUniforms;t.uniforms.uTransformMatrix=e.groupTransform,t.uniforms.uRound=this.renderer._roundPixels|e._roundPixels,t.update(),Ur(e.groupColorAlpha,t.uniforms.uColor,0),this._adaptor.execute(this,e)}_getMeshData(e){var t,i;return(t=e._gpuData)[i=this.renderer.uid]||(t[i]=new Fa),e._gpuData[this.renderer.uid].meshData||this._initMeshData(e)}_initMeshData(e){return e._gpuData[this.renderer.uid].meshData={batched:e.batched,indexSize:0,vertexSize:0},e._gpuData[this.renderer.uid].meshData}_getBatchableMesh(e){var t,i;return(t=e._gpuData)[i=this.renderer.uid]||(t[i]=new Fa),e._gpuData[this.renderer.uid].batchableMesh||this._initBatchableMesh(e)}_initBatchableMesh(e){const t=new Jl;return t.renderable=e,t.setTexture(e._texture),t.transform=e.groupTransform,t.roundPixels=this.renderer._roundPixels|e._roundPixels,e._gpuData[this.renderer.uid].batchableMesh=t,t}destroy(){this.localUniforms=null,this.localUniformsBindGroup=null,this._adaptor.destroy(),this._adaptor=null,this.renderer=null}}tc.extension={type:[I.WebGLPipes,I.WebGPUPipes],name:"mesh"};K.add(tc);class Ba extends ai{constructor(...e){let t=e[0];t instanceof Oi&&(V(Q,"Mesh: use new Mesh({ geometry, shader }) instead"),t={geometry:t,shader:e[1]},e[3]&&(V(Q,"Mesh: drawMode argument has been removed, use geometry.topology instead"),t.geometry.topology=e[3]));const{geometry:i,shader:s,texture:r,roundPixels:o,state:a,...h}=t;super({label:"Mesh",...h}),this.renderPipeId="mesh",this._shader=null,this.allowChildren=!1,this.shader=s??null,this.texture=r??(s==null?void 0:s.texture)??G.WHITE,this.state=a??Ni.for2d(),this._geometry=i,this._geometry.on("update",this.onViewUpdate,this),this.roundPixels=o??!1}get material(){return V(Q,"mesh.material property has been removed, use mesh.shader instead"),this._shader}set shader(e){this._shader!==e&&(this._shader=e,this.onViewUpdate())}get shader(){return this._shader}set geometry(e){var t;this._geometry!==e&&((t=this._geometry)==null||t.off("update",this.onViewUpdate,this),e.on("update",this.onViewUpdate,this),this._geometry=e,this.onViewUpdate())}get geometry(){return this._geometry}set texture(e){e||(e=G.EMPTY);const t=this._texture;t!==e&&(t&&t.dynamic&&t.off("update",this.onViewUpdate,this),e.dynamic&&e.on("update",this.onViewUpdate,this),this.shader&&(this.shader.texture=e),this._texture=e,this.onViewUpdate())}get texture(){return this._texture}get batched(){return this._shader||this.state.data&12?!1:this._geometry instanceof Hr?this._geometry.batchMode==="auto"?this._geometry.positions.length/2<=100:this._geometry.batchMode==="batch":!1}get bounds(){return this._geometry.bounds}updateBounds(){this._bounds=this._geometry.bounds}containsPoint(e){const{x:t,y:i}=e;if(!this.bounds.containsPoint(t,i))return!1;const s=this.geometry.getBuffer("aPosition").data,r=this.geometry.topology==="triangle-strip"?3:1;if(this.geometry.getIndex()){const o=this.geometry.getIndex().data,a=o.length;for(let h=0;h+2<a;h+=r){const l=o[h]*2,c=o[h+1]*2,d=o[h+2]*2;if(Da(t,i,s[l],s[l+1],s[c],s[c+1],s[d],s[d+1]))return!0}}else{const o=s.length/2;for(let a=0;a+2<o;a+=r){const h=a*2,l=(a+1)*2,c=(a+2)*2;if(Da(t,i,s[h],s[h+1],s[l],s[l+1],s[c],s[c+1]))return!0}}return!1}destroy(e){var i;if(super.destroy(e),typeof e=="boolean"?e:e==null?void 0:e.texture){const s=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._texture.destroy(s)}(i=this._geometry)==null||i.off("update",this.onViewUpdate,this),this._texture=null,this._geometry=null,this._shader=null}}class Ms extends Xt{constructor(...e){let t=e[0];Array.isArray(e[0])&&(t={textures:e[0],autoUpdate:e[1]});const{animationSpeed:i=1,autoPlay:s=!1,autoUpdate:r=!0,loop:o=!0,onComplete:a=null,onFrameChange:h=null,onLoop:l=null,textures:c,updateAnchor:d=!1,...u}=t,[p]=c;super({...u,texture:p instanceof G?p:p.texture}),this._textures=null,this._durations=null,this._autoUpdate=r,this._isConnectedToTicker=!1,this.animationSpeed=i,this.loop=o,this.updateAnchor=d,this.onComplete=a,this.onFrameChange=h,this.onLoop=l,this._currentTime=0,this._playing=!1,this._previousFrame=null,this.textures=c,s&&this.play()}stop(){this._playing&&(this._playing=!1,this._autoUpdate&&this._isConnectedToTicker&&(yt.shared.remove(this.update,this),this._isConnectedToTicker=!1))}play(){this._playing||(this._playing=!0,this._autoUpdate&&!this._isConnectedToTicker&&(yt.shared.add(this.update,this,Fe.HIGH),this._isConnectedToTicker=!0))}gotoAndStop(e){this.stop(),this.currentFrame=e}gotoAndPlay(e){this.currentFrame=e,this.play()}update(e){if(!this._playing)return;const t=e.deltaTime,i=this.animationSpeed*t,s=this.currentFrame;if(this._durations!==null){let r=this._currentTime%1*this._durations[this.currentFrame];for(r+=i/60*1e3;r<0;)this._currentTime--,r+=this._durations[this.currentFrame];const o=Math.sign(this.animationSpeed*t);for(this._currentTime=Math.floor(this._currentTime);r>=this._durations[this.currentFrame];)r-=this._durations[this.currentFrame]*o,this._currentTime+=o;this._currentTime+=r/this._durations[this.currentFrame]}else this._currentTime+=i;this._currentTime<0&&!this.loop?(this.gotoAndStop(0),this.onComplete&&this.onComplete()):this._currentTime>=this._textures.length&&!this.loop?(this.gotoAndStop(this._textures.length-1),this.onComplete&&this.onComplete()):s!==this.currentFrame&&(this.loop&&this.onLoop&&(this.animationSpeed>0&&this.currentFrame<s||this.animationSpeed<0&&this.currentFrame>s)&&this.onLoop(),this._updateTexture())}_updateTexture(){const e=this.currentFrame;this._previousFrame!==e&&(this._previousFrame=e,this.texture=this._textures[e],this.updateAnchor&&this.texture.defaultAnchor&&this.anchor.copyFrom(this.texture.defaultAnchor),this.onFrameChange&&this.onFrameChange(this.currentFrame))}destroy(e=!1){if(typeof e=="boolean"?e:e==null?void 0:e.texture){const i=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._textures.forEach(s=>{this.texture!==s&&s.destroy(i)})}this._textures=[],this._durations=null,this.stop(),super.destroy(e),this.onComplete=null,this.onFrameChange=null,this.onLoop=null}static fromFrames(e){const t=[];for(let i=0;i<e.length;++i)t.push(G.from(e[i]));return new Ms(t)}static fromImages(e){const t=[];for(let i=0;i<e.length;++i)t.push(G.from(e[i]));return new Ms(t)}get totalFrames(){return this._textures.length}get textures(){return this._textures}set textures(e){if(e[0]instanceof G)this._textures=e,this._durations=null;else{this._textures=[],this._durations=[];for(let t=0;t<e.length;t++)this._textures.push(e[t].texture),this._durations.push(e[t].time)}this._previousFrame=null,this.gotoAndStop(0),this._updateTexture()}get currentFrame(){let e=Math.floor(this._currentTime)%this._textures.length;return e<0&&(e+=this._textures.length),e}set currentFrame(e){if(e<0||e>this.totalFrames-1)throw new Error(`[AnimatedSprite]: Invalid frame index value ${e}, expected to be between 0 and totalFrames ${this.totalFrames}.`);const t=this.currentFrame;this._currentTime=e,t!==this.currentFrame&&this._updateTexture()}get playing(){return this._playing}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){e!==this._autoUpdate&&(this._autoUpdate=e,!this._autoUpdate&&this._isConnectedToTicker?(yt.shared.remove(this.update,this),this._isConnectedToTicker=!1):this._autoUpdate&&!this._isConnectedToTicker&&this._playing&&(yt.shared.add(this.update,this),this._isConnectedToTicker=!0))}}class vm{constructor({matrix:e,observer:t}={}){this.dirty=!0,this._matrix=e??new H,this.observer=t,this.position=new ct(this,0,0),this.scale=new ct(this,1,1),this.pivot=new ct(this,0,0),this.skew=new ct(this,0,0),this._rotation=0,this._cx=1,this._sx=0,this._cy=0,this._sy=1}get matrix(){const e=this._matrix;return this.dirty&&(e.a=this._cx*this.scale.x,e.b=this._sx*this.scale.x,e.c=this._cy*this.scale.y,e.d=this._sy*this.scale.y,e.tx=this.position.x-(this.pivot.x*e.a+this.pivot.y*e.c),e.ty=this.position.y-(this.pivot.x*e.b+this.pivot.y*e.d),this.dirty=!1),e}_onUpdate(e){var t;this.dirty=!0,e===this.skew&&this.updateSkew(),(t=this.observer)==null||t._onUpdate(this)}updateSkew(){this._cx=Math.cos(this._rotation+this.skew.y),this._sx=Math.sin(this._rotation+this.skew.y),this._cy=-Math.sin(this._rotation-this.skew.x),this._sy=Math.cos(this._rotation-this.skew.x),this.dirty=!0}toString(){return`[pixi.js/math:Transform position=(${this.position.x}, ${this.position.y}) rotation=${this.rotation} scale=(${this.scale.x}, ${this.scale.y}) skew=(${this.skew.x}, ${this.skew.y}) ]`}setFromMatrix(e){e.decompose(this),this.dirty=!0}get rotation(){return this._rotation}set rotation(e){this._rotation!==e&&(this._rotation=e,this._onUpdate(this.skew))}}let He;function za(n){const e=$.get().createCanvas(6,1),t=e.getContext("2d");return t.fillStyle=n,t.fillRect(0,0,6,1),e}function bm(){if(He!==void 0)return He;try{const n=za("#ff00ff"),e=za("#ffff00"),i=$.get().createCanvas(6,1).getContext("2d");i.globalCompositeOperation="multiply",i.drawImage(n,0,0),i.drawImage(e,2,0);const s=i.getImageData(2,0,1,1);if(!s)He=!1;else{const r=s.data;He=r[0]===255&&r[1]===0&&r[2]===0}}catch{He=!1}return He}const st={canvas:null,convertTintToImage:!1,cacheStepsPerColorChannel:8,canUseMultiply:bm(),tintMethod:null,_canvasSourceCache:new WeakMap,_unpremultipliedCache:new WeakMap,getCanvasSource:n=>{const e=n.source,t=e==null?void 0:e.resource;if(!t)return null;const i=e.alphaMode==="premultiplied-alpha",s=e.resourceWidth??e.pixelWidth,r=e.resourceHeight??e.pixelHeight,o=s!==e.pixelWidth||r!==e.pixelHeight;if(i){if((t instanceof HTMLCanvasElement||typeof OffscreenCanvas<"u"&&t instanceof OffscreenCanvas)&&!o)return t;const a=st._unpremultipliedCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas}if(t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int8Array||t instanceof Uint16Array||t instanceof Int16Array||t instanceof Uint32Array||t instanceof Int32Array||t instanceof Float32Array||t instanceof ArrayBuffer){const a=st._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const h=$.get().createCanvas(e.pixelWidth,e.pixelHeight),l=h.getContext("2d"),c=l.createImageData(e.pixelWidth,e.pixelHeight),d=c.data,u=t instanceof ArrayBuffer?new Uint8Array(t):new Uint8Array(t.buffer,t.byteOffset,t.byteLength);if(e.format==="bgra8unorm")for(let p=0;p<d.length&&p+3<u.length;p+=4)d[p]=u[p+2],d[p+1]=u[p+1],d[p+2]=u[p],d[p+3]=u[p+3];else d.set(u.subarray(0,d.length));return l.putImageData(c,0,0),st._canvasSourceCache.set(e,{canvas:h,resourceId:e._resourceId}),h}if(i){const a=$.get().createCanvas(e.pixelWidth,e.pixelHeight),h=a.getContext("2d",{willReadFrequently:!0});a.width=e.pixelWidth,a.height=e.pixelHeight,h.drawImage(t,0,0);const l=h.getImageData(0,0,a.width,a.height),c=l.data;for(let d=0;d<c.length;d+=4){const u=c[d+3];if(u>0){const p=255/u;c[d]=Math.min(255,c[d]*p+.5),c[d+1]=Math.min(255,c[d+1]*p+.5),c[d+2]=Math.min(255,c[d+2]*p+.5)}}return h.putImageData(l,0,0),st._unpremultipliedCache.set(e,{canvas:a,resourceId:e._resourceId}),a}if(o){const a=st._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const h=$.get().createCanvas(e.pixelWidth,e.pixelHeight),l=h.getContext("2d");return h.width=e.pixelWidth,h.height=e.pixelHeight,l.drawImage(t,0,0),st._canvasSourceCache.set(e,{canvas:h,resourceId:e._resourceId}),h}return t},getTintedCanvas:(n,e)=>{const t=n.texture,i=rt.shared.setValue(e).toHex(),s=t.tintCache||(t.tintCache={}),r=s[i],o=t.source._resourceId;if((r==null?void 0:r.tintId)===o)return r;const a=r&&"getContext"in r?r:$.get().createCanvas();return st.tintMethod(t,e,a),a.tintId=o,s[i]=a,s[i]},getTintedPattern:(n,e)=>{const t=rt.shared.setValue(e).toHex(),i=n.patternCache||(n.patternCache={}),s=n.source._resourceId;let r=i[t];return(r==null?void 0:r.tintId)===s||(st.canvas||(st.canvas=$.get().createCanvas()),st.tintMethod(n,e,st.canvas),r=st.canvas.getContext("2d").createPattern(st.canvas,"repeat"),r.tintId=s,i[t]=r),r},applyPatternTransform:(n,e,t=!0)=>{if(!e)return;const i=n;if(!i.setTransform)return;const s=globalThis.DOMMatrix;if(!s)return;const r=new s([e.a,e.b,e.c,e.d,e.tx,e.ty]);i.setTransform(t?r.inverse():r)},tintWithMultiply:(n,e,t)=>{const i=t.getContext("2d"),s=n.frame.clone(),r=n.source._resolution??n.source.resolution??1,o=n.rotate;s.x*=r,s.y*=r,s.width*=r,s.height*=r;const a=X.isVertical(o),h=a?s.height:s.width,l=a?s.width:s.height;t.width=Math.ceil(h),t.height=Math.ceil(l),i.save(),i.fillStyle=rt.shared.setValue(e).toHex(),i.fillRect(0,0,h,l),i.globalCompositeOperation="multiply";const c=st.getCanvasSource(n);if(!c){i.restore();return}o&&st._applyInverseRotation(i,o,s.width,s.height),i.drawImage(c,s.x,s.y,s.width,s.height,0,0,s.width,s.height),i.globalCompositeOperation="destination-atop",i.drawImage(c,s.x,s.y,s.width,s.height,0,0,s.width,s.height),i.restore()},tintWithOverlay:(n,e,t)=>{const i=t.getContext("2d"),s=n.frame.clone(),r=n.source._resolution??n.source.resolution??1,o=n.rotate;s.x*=r,s.y*=r,s.width*=r,s.height*=r;const a=X.isVertical(o),h=a?s.height:s.width,l=a?s.width:s.height;t.width=Math.ceil(h),t.height=Math.ceil(l),i.save(),i.globalCompositeOperation="copy",i.fillStyle=rt.shared.setValue(e).toHex(),i.fillRect(0,0,h,l),i.globalCompositeOperation="destination-atop";const c=st.getCanvasSource(n);if(!c){i.restore();return}o&&st._applyInverseRotation(i,o,s.width,s.height),i.drawImage(c,s.x,s.y,s.width,s.height,0,0,s.width,s.height),i.restore()},tintWithPerPixel:(n,e,t)=>{const i=t.getContext("2d"),s=n.frame.clone(),r=n.source._resolution??n.source.resolution??1,o=n.rotate;s.x*=r,s.y*=r,s.width*=r,s.height*=r;const a=X.isVertical(o),h=a?s.height:s.width,l=a?s.width:s.height;t.width=Math.ceil(h),t.height=Math.ceil(l),i.save(),i.globalCompositeOperation="copy";const c=st.getCanvasSource(n);if(!c){i.restore();return}o&&st._applyInverseRotation(i,o,s.width,s.height),i.drawImage(c,s.x,s.y,s.width,s.height,0,0,s.width,s.height),i.restore();const d=e>>16&255,u=e>>8&255,p=e&255,g=i.getImageData(0,0,h,l),m=g.data;for(let y=0;y<m.length;y+=4)m[y]=m[y]*d/255,m[y+1]=m[y+1]*u/255,m[y+2]=m[y+2]*p/255;i.putImageData(g,0,0)},_applyInverseRotation:(n,e,t,i)=>{const s=X.inv(e),r=X.uX(s),o=X.uY(s),a=X.vX(s),h=X.vY(s),l=-Math.min(0,r*t,a*i,r*t+a*i),c=-Math.min(0,o*t,h*i,o*t+h*i);n.transform(r,o,a,h,l,c)}};st.tintMethod=st.canUseMultiply?st.tintWithMultiply:st.tintWithPerPixel;const ls=new H,xi=new H,Ht=[new J,new J,new J,new J];class ec{constructor(e){this._renderer=e}validateRenderable(e){return!1}addRenderable(e,t){this._renderer.renderPipes.batch.break(t),t.add(e)}updateRenderable(e){}execute(e){var _,R;const t=this._renderer,i=t.canvasContext,s=i.activeContext;s.save(),i.setBlendMode(e.groupBlendMode);const r=((_=t.globalUniforms.globalUniformData)==null?void 0:_.worldColor)??4294967295,o=e.groupColorAlpha,a=(r>>>24&255)/255,h=(o>>>24&255)/255,l=((R=t.filter)==null?void 0:R.alphaMultiplier)??1,c=a*h*l;if(c<=0){s.restore();return}s.globalAlpha=c;const d=r&16777215,u=o&16777215,p=Pi(Pr(u,d)),g=e.texture,m=st.getTintedPattern(g,p),y=e.width,x=e.height,S=e.groupTransform,v=g.source._resolution??g.source.resolution??1;xi.copyFrom(e._tileTransform.matrix),e.applyAnchorToTexture||xi.translate(-e.anchor.x*y,-e.anchor.y*x),xi.scale(1/v,1/v),ls.identity(),ls.prepend(xi),ls.prepend(S);const b=t._roundPixels|e._roundPixels;i.setContextTransform(ls,b===1),s.fillStyle=m;const P=e.anchor.x*-y,C=e.anchor.y*-x;Ht[0].set(P,C),Ht[1].set(P+y,C),Ht[2].set(P+y,C+x),Ht[3].set(P,C+x);for(let M=0;M<4;M++)xi.applyInverse(Ht[M],Ht[M]);s.beginPath(),s.moveTo(Ht[0].x,Ht[0].y);for(let M=1;M<4;M++)s.lineTo(Ht[M].x,Ht[M].y);s.closePath(),s.fill(),s.restore()}destroy(){this._renderer=null}}ec.extension={type:[I.CanvasPipes],name:"tilingSprite"};const ys={name:"local-uniform-bit",vertex:{header:`
397
+
398
+ struct LocalUniforms {
399
+ uTransformMatrix:mat3x3<f32>,
400
+ uColor:vec4<f32>,
401
+ uRound:f32,
402
+ }
403
+
404
+ @group(1) @binding(0) var<uniform> localUniforms : LocalUniforms;
405
+ `,main:`
406
+ vColor *= localUniforms.uColor;
407
+ modelMatrix *= localUniforms.uTransformMatrix;
408
+ `,end:`
409
+ if(localUniforms.uRound == 1)
410
+ {
411
+ vPosition = vec4(roundPixels(vPosition.xy, globalUniforms.uResolution), vPosition.zw);
412
+ }
413
+ `}},Av={...ys,vertex:{...ys.vertex,header:ys.vertex.header.replace("group(1)","group(2)")}},wm={name:"local-uniform-bit",vertex:{header:`
414
+
415
+ uniform mat3 uTransformMatrix;
416
+ uniform vec4 uColor;
417
+ uniform float uRound;
418
+ `,main:`
419
+ vColor *= uColor;
420
+ modelMatrix = uTransformMatrix;
421
+ `,end:`
422
+ if(uRound == 1.)
423
+ {
424
+ gl_Position.xy = roundPixels(gl_Position.xy, uResolution);
425
+ }
426
+ `}},Cm={name:"tiling-bit",vertex:{header:`
427
+ struct TilingUniforms {
428
+ uMapCoord:mat3x3<f32>,
429
+ uClampFrame:vec4<f32>,
430
+ uClampOffset:vec2<f32>,
431
+ uTextureTransform:mat3x3<f32>,
432
+ uSizeAnchor:vec4<f32>
433
+ };
434
+
435
+ @group(2) @binding(0) var<uniform> tilingUniforms: TilingUniforms;
436
+ @group(2) @binding(1) var uTexture: texture_2d<f32>;
437
+ @group(2) @binding(2) var uSampler: sampler;
438
+ `,main:`
439
+ uv = (tilingUniforms.uTextureTransform * vec3(uv, 1.0)).xy;
440
+
441
+ position = (position - tilingUniforms.uSizeAnchor.zw) * tilingUniforms.uSizeAnchor.xy;
442
+ `},fragment:{header:`
443
+ struct TilingUniforms {
444
+ uMapCoord:mat3x3<f32>,
445
+ uClampFrame:vec4<f32>,
446
+ uClampOffset:vec2<f32>,
447
+ uTextureTransform:mat3x3<f32>,
448
+ uSizeAnchor:vec4<f32>
449
+ };
450
+
451
+ @group(2) @binding(0) var<uniform> tilingUniforms: TilingUniforms;
452
+ @group(2) @binding(1) var uTexture: texture_2d<f32>;
453
+ @group(2) @binding(2) var uSampler: sampler;
454
+ `,main:`
455
+
456
+ var coord = vUV + ceil(tilingUniforms.uClampOffset - vUV);
457
+ coord = (tilingUniforms.uMapCoord * vec3(coord, 1.0)).xy;
458
+ var unclamped = coord;
459
+ coord = clamp(coord, tilingUniforms.uClampFrame.xy, tilingUniforms.uClampFrame.zw);
460
+
461
+ var bias = 0.;
462
+
463
+ if(unclamped.x == coord.x && unclamped.y == coord.y)
464
+ {
465
+ bias = -32.;
466
+ }
467
+
468
+ outColor = textureSampleBias(uTexture, uSampler, coord, bias);
469
+ `}},_m={name:"tiling-bit",vertex:{header:`
470
+ uniform mat3 uTextureTransform;
471
+ uniform vec4 uSizeAnchor;
472
+
473
+ `,main:`
474
+ uv = (uTextureTransform * vec3(aUV, 1.0)).xy;
475
+
476
+ position = (position - uSizeAnchor.zw) * uSizeAnchor.xy;
477
+ `},fragment:{header:`
478
+ uniform sampler2D uTexture;
479
+ uniform mat3 uMapCoord;
480
+ uniform vec4 uClampFrame;
481
+ uniform vec2 uClampOffset;
482
+ `,main:`
483
+
484
+ vec2 coord = vUV + ceil(uClampOffset - vUV);
485
+ coord = (uMapCoord * vec3(coord, 1.0)).xy;
486
+ vec2 unclamped = coord;
487
+ coord = clamp(coord, uClampFrame.xy, uClampFrame.zw);
488
+
489
+ outColor = texture(uTexture, coord, unclamped == coord ? 0.0 : -32.0);// lod-bias very negative to force lod 0
490
+
491
+ `}};let In,En;class Pm extends Be{constructor(){In??(In=kl({name:"tiling-sprite-shader",bits:[ys,Cm,El]})),En??(En=Il({name:"tiling-sprite-shader",bits:[wm,_m,Dl]}));const e=new si({uMapCoord:{value:new H,type:"mat3x3<f32>"},uClampFrame:{value:new Float32Array([0,0,1,1]),type:"vec4<f32>"},uClampOffset:{value:new Float32Array([0,0]),type:"vec2<f32>"},uTextureTransform:{value:new H,type:"mat3x3<f32>"},uSizeAnchor:{value:new Float32Array([100,100,.5,.5]),type:"vec4<f32>"}});super({glProgram:En,gpuProgram:In,resources:{localUniforms:new si({uTransformMatrix:{value:new H,type:"mat3x3<f32>"},uColor:{value:new Float32Array([1,1,1,1]),type:"vec4<f32>"},uRound:{value:0,type:"f32"}}),tilingUniforms:e,uTexture:G.EMPTY.source,uSampler:G.EMPTY.source.style}})}updateUniforms(e,t,i,s,r,o){const a=this.resources.tilingUniforms,h=o.width,l=o.height,c=o.textureMatrix,d=a.uniforms.uTextureTransform;d.set(i.a*h/e,i.b*h/t,i.c*l/e,i.d*l/t,i.tx/e,i.ty/t),d.invert(),a.uniforms.uMapCoord=c.mapCoord,a.uniforms.uClampFrame=c.uClampFrame,a.uniforms.uClampOffset=c.uClampOffset,a.uniforms.uTextureTransform=d,a.uniforms.uSizeAnchor[0]=e,a.uniforms.uSizeAnchor[1]=t,a.uniforms.uSizeAnchor[2]=s,a.uniforms.uSizeAnchor[3]=r,o&&(this.resources.uTexture=o.source,this.resources.uSampler=o.source.style)}}class Mm extends Hr{constructor(){super({positions:new Float32Array([0,0,1,0,1,1,0,1]),uvs:new Float32Array([0,0,1,0,1,1,0,1]),indices:new Uint32Array([0,1,2,0,2,3])})}}function Am(n,e){const t=n.anchor.x,i=n.anchor.y;e[0]=-t*n.width,e[1]=-i*n.height,e[2]=(1-t)*n.width,e[3]=-i*n.height,e[4]=(1-t)*n.width,e[5]=(1-i)*n.height,e[6]=-t*n.width,e[7]=(1-i)*n.height}function Tm(n,e,t,i){let s=0;const r=n.length/e,o=i.a,a=i.b,h=i.c,l=i.d,c=i.tx,d=i.ty;for(t*=e;s<r;){const u=n[t],p=n[t+1];n[t]=o*u+h*p+c,n[t+1]=a*u+l*p+d,t+=e,s++}}function Rm(n,e){const t=n.texture,i=t.frame.width,s=t.frame.height;let r=0,o=0;n.applyAnchorToTexture&&(r=n.anchor.x,o=n.anchor.y),e[0]=e[6]=-r,e[2]=e[4]=1-r,e[1]=e[3]=-o,e[5]=e[7]=1-o;const a=H.shared;a.copyFrom(n._tileTransform.matrix),a.tx/=n.width,a.ty/=n.height,a.invert(),a.scale(n.width/i,n.height/s),Tm(e,2,0,a)}const xs=new Mm;class km{constructor(){this.canBatch=!0,this.geometry=new Hr({indices:xs.indices.slice(),positions:xs.positions.slice(),uvs:xs.uvs.slice()})}destroy(){var e;this.geometry.destroy(),(e=this.shader)==null||e.destroy()}}class ic{constructor(e){this._state=Ni.default2d,this._renderer=e,this._managedTilingSprites=new ci({renderer:e,type:"renderable",name:"tilingSprite"})}validateRenderable(e){const t=this._getTilingSpriteData(e),i=t.canBatch;this._updateCanBatch(e);const s=t.canBatch;if(s&&s===i){const{batchableMesh:r}=t;return!r._batcher.checkAndUpdateTexture(r,e.texture)}return i!==s}addRenderable(e,t){const i=this._renderer.renderPipes.batch;this._updateCanBatch(e);const s=this._getTilingSpriteData(e),{geometry:r,canBatch:o}=s;if(o){s.batchableMesh||(s.batchableMesh=new Jl);const a=s.batchableMesh;e.didViewUpdate&&(this._updateBatchableMesh(e),a.geometry=r,a.renderable=e,a.transform=e.groupTransform,a.setTexture(e._texture)),a.roundPixels=this._renderer._roundPixels|e._roundPixels,i.addToBatch(a,t)}else i.break(t),s.shader||(s.shader=new Pm),this.updateRenderable(e),t.add(e)}execute(e){const t=this._renderer,{shader:i}=this._getTilingSpriteData(e);i.groups[0]=t.globalUniforms.bindGroup;const s=i.resources.localUniforms.uniforms;s.uTransformMatrix=e.groupTransform,s.uRound=t._roundPixels|e._roundPixels,Ur(e.groupColorAlpha,s.uColor,0),this._state.blendMode=Cs(e.groupBlendMode,e.texture._source),t.encoder.draw({geometry:xs,shader:i,state:this._state})}updateRenderable(e){const t=this._getTilingSpriteData(e),{canBatch:i}=t;if(i){const{batchableMesh:s}=t;e.didViewUpdate&&this._updateBatchableMesh(e),s._batcher.updateElement(s)}else if(e.didViewUpdate){const{shader:s}=t;s.updateUniforms(e.width,e.height,e._tileTransform.matrix,e.anchor.x,e.anchor.y,e.texture)}}_getTilingSpriteData(e){return e._gpuData[this._renderer.uid]||this._initTilingSpriteData(e)}_initTilingSpriteData(e){const t=new km;return t.renderable=e,e._gpuData[this._renderer.uid]=t,this._managedTilingSprites.add(e),t}_updateBatchableMesh(e){const t=this._getTilingSpriteData(e),{geometry:i}=t,s=e.texture.source.style;s.addressMode!=="repeat"&&(s.addressMode="repeat",s.update()),Rm(e,i.uvs),Am(e,i.positions)}destroy(){this._managedTilingSprites.destroy(),this._renderer=null}_updateCanBatch(e){const t=this._getTilingSpriteData(e),i=e.texture;let s=!0;return this._renderer.type===te.WEBGL&&(s=this._renderer.context.supports.nonPowOf2wrapping),t.canBatch=i.textureMatrix.isSimple&&(s||i.source.isPowerOfTwo),t.canBatch}}ic.extension={type:[I.WebGLPipes,I.WebGPUPipes],name:"tilingSprite"};K.add(ec);K.add(ic);const sc=class Ss extends ai{constructor(...e){let t=e[0]||{};t instanceof G&&(t={texture:t}),e.length>1&&(V(Q,"use new TilingSprite({ texture, width:100, height:100 }) instead"),t.width=e[1],t.height=e[2]),t={...Ss.defaultOptions,...t};const{texture:i,anchor:s,tilePosition:r,tileScale:o,tileRotation:a,width:h,height:l,applyAnchorToTexture:c,roundPixels:d,...u}=t??{};super({label:"TilingSprite",...u}),this.renderPipeId="tilingSprite",this.batched=!0,this.allowChildren=!1,this._anchor=new ct({_onUpdate:()=>{this.onViewUpdate()}}),this.applyAnchorToTexture=c,this.texture=i,this._width=h??i.width,this._height=l??i.height,this._tileTransform=new vm({observer:{_onUpdate:()=>this.onViewUpdate()}}),s&&(this.anchor=s),this.tilePosition=r,this.tileScale=o,this.tileRotation=a,this.roundPixels=d??!1}static from(e,t={}){return typeof e=="string"?new Ss({texture:xt.get(e),...t}):new Ss({texture:e,...t})}get uvRespectAnchor(){return V(Q,"uvRespectAnchor is deprecated, please use applyAnchorToTexture instead"),this.applyAnchorToTexture}set uvRespectAnchor(e){V(Q,"uvRespectAnchor is deprecated, please use applyAnchorToTexture instead"),this.applyAnchorToTexture=e}get clampMargin(){return this._texture.textureMatrix.clampMargin}set clampMargin(e){this._texture.textureMatrix.clampMargin=e}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}get tilePosition(){return this._tileTransform.position}set tilePosition(e){this._tileTransform.position.copyFrom(e)}get tileScale(){return this._tileTransform.scale}set tileScale(e){typeof e=="number"?this._tileTransform.scale.set(e):this._tileTransform.scale.copyFrom(e)}set tileRotation(e){this._tileTransform.rotation=e}get tileRotation(){return this._tileTransform.rotation}get tileTransform(){return this._tileTransform}set texture(e){e||(e=G.EMPTY);const t=this._texture;t!==e&&(t&&t.dynamic&&t.off("update",this.onViewUpdate,this),e.dynamic&&e.on("update",this.onViewUpdate,this),this._texture=e,this.onViewUpdate())}get texture(){return this._texture}set width(e){this._width=e,this.onViewUpdate()}get width(){return this._width}set height(e){this._height=e,this.onViewUpdate()}get height(){return this._height}setSize(e,t){typeof e=="object"&&(t=e.height??e.width,e=e.width),this._width=e,this._height=t??e,this.onViewUpdate()}getSize(e){return e||(e={}),e.width=this._width,e.height=this._height,e}updateBounds(){const e=this._bounds,t=this._anchor,i=this._width,s=this._height;e.minX=-t._x*i,e.maxX=e.minX+i,e.minY=-t._y*s,e.maxY=e.minY+s}containsPoint(e){const t=this._width,i=this._height,s=-t*this._anchor._x;let r=0;return e.x>=s&&e.x<=s+t&&(r=-i*this._anchor._y,e.y>=r&&e.y<=r+i)}destroy(e=!1){if(super.destroy(e),this._anchor=null,this._tileTransform=null,this._bounds=null,typeof e=="boolean"?e:e==null?void 0:e.texture){const i=typeof e=="boolean"?e:e==null?void 0:e.textureSource;this._texture.destroy(i)}this._texture=null}};sc.defaultOptions={texture:G.EMPTY,anchor:{x:0,y:0},tilePosition:{x:0,y:0},tileScale:{x:1,y:1},tileRotation:0,applyAnchorToTexture:!1};let As=sc;class Im extends ai{constructor(e,t){const{text:i,resolution:s,style:r,anchor:o,width:a,height:h,roundPixels:l,...c}=e;super({...c}),this.batched=!0,this._resolution=null,this._autoResolution=!0,this._didTextUpdate=!0,this._styleClass=t,this.text=i??"",this.style=r,this.resolution=s??null,this.allowChildren=!1,this._anchor=new ct({_onUpdate:()=>{this.onViewUpdate()}}),o&&(this.anchor=o),this.roundPixels=l??!1,a!==void 0&&(this.width=a),h!==void 0&&(this.height=h)}get anchor(){return this._anchor}set anchor(e){typeof e=="number"?this._anchor.set(e):this._anchor.copyFrom(e)}set text(e){e=e.toString(),this._text!==e&&(this._text=e,this.onViewUpdate())}get text(){return this._text}set resolution(e){this._autoResolution=e===null,this._resolution=e,this.onViewUpdate()}get resolution(){return this._resolution}get style(){return this._style}set style(e){var t;e||(e={}),(t=this._style)==null||t.off("update",this.onViewUpdate,this),e instanceof this._styleClass?this._style=e:this._style=new this._styleClass(e),this._style.on("update",this.onViewUpdate,this),this.onViewUpdate()}get width(){return Math.abs(this.scale.x)*this.bounds.width}set width(e){this._setWidth(e,this.bounds.width)}get height(){return Math.abs(this.scale.y)*this.bounds.height}set height(e){this._setHeight(e,this.bounds.height)}getSize(e){return e||(e={}),e.width=Math.abs(this.scale.x)*this.bounds.width,e.height=Math.abs(this.scale.y)*this.bounds.height,e}setSize(e,t){typeof e=="object"?(t=e.height??e.width,e=e.width):t??(t=e),e!==void 0&&this._setWidth(e,this.bounds.width),t!==void 0&&this._setHeight(t,this.bounds.height)}containsPoint(e){const t=this.bounds.width,i=this.bounds.height,s=-t*this.anchor.x;let r=0;return e.x>=s&&e.x<=s+t&&(r=-i*this.anchor.y,e.y>=r&&e.y<=r+i)}onViewUpdate(){this.didViewUpdate||(this._didTextUpdate=!0),super.onViewUpdate()}destroy(e=!1){super.destroy(e),this.owner=null,this._bounds=null,this._anchor=null,(typeof e=="boolean"?e:e!=null&&e.style)&&this._style.destroy(e),this._style=null,this._text=null}get styleKey(){return`${this._text}:${this._style.styleKey}:${this._resolution}`}}function Em(n,e){let t=n[0]??{};return(typeof t=="string"||n[1])&&(V(Q,`use new ${e}({ text: "hi!", style }) instead`),t={text:t,style:n[1]}),t}class Dm{constructor(e){this._canvasPool=Object.create(null),this.canvasOptions=e||{},this.enableFullScreen=!1}_createCanvasAndContext(e,t){const i=$.get().createCanvas();i.width=e,i.height=t;const s=i.getContext("2d");return{canvas:i,context:s}}getOptimalCanvasAndContext(e,t,i=1){e=Math.ceil(e*i-1e-6),t=Math.ceil(t*i-1e-6),e=Qe(e),t=Qe(t);const s=(e<<17)+(t<<1);this._canvasPool[s]||(this._canvasPool[s]=[]);let r=this._canvasPool[s].pop();return r||(r=this._createCanvasAndContext(e,t)),r}returnCanvasAndContext(e){const t=e.canvas,{width:i,height:s}=t,r=(i<<17)+(s<<1);e.context.resetTransform(),e.context.clearRect(0,0,i,s),this._canvasPool[r].push(e)}clear(){this._canvasPool={}}}const dr=new Dm;Vi.register(dr);let ve=null,Jt=null;function Fm(n,e){ve||(ve=$.get().createCanvas(256,128),Jt=ve.getContext("2d",{willReadFrequently:!0}),Jt.globalCompositeOperation="copy",Jt.globalAlpha=1),(ve.width<n||ve.height<e)&&(ve.width=Qe(n),ve.height=Qe(e))}function La(n,e,t){for(let i=0,s=4*t*e;i<e;++i,s+=4)if(n[s+3]!==0)return!1;return!0}function Oa(n,e,t,i,s){const r=4*e;for(let o=i,a=i*r+4*t;o<=s;++o,a+=r)if(n[a+3]!==0)return!1;return!0}function Bm(...n){let e=n[0];e.canvas||(e={canvas:n[0],resolution:n[1]});const{canvas:t}=e,i=Math.min(e.resolution??1,1),s=e.width??t.width,r=e.height??t.height;let o=e.output;if(Fm(s,r),!Jt)throw new TypeError("Failed to get canvas 2D context");Jt.drawImage(t,0,0,s,r,0,0,s*i,r*i);const h=Jt.getImageData(0,0,s,r).data;let l=0,c=0,d=s-1,u=r-1;for(;c<r&&La(h,s,c);)++c;if(c===r)return tt.EMPTY;for(;La(h,s,u);)--u;for(;Oa(h,s,l,c,u);)++l;for(;Oa(h,s,d,c,u);)--d;return++d,++u,Jt.globalCompositeOperation="source-over",Jt.strokeRect(l,c,d-l,u-c),Jt.globalCompositeOperation="copy",o??(o=new tt),o.set(l/i,c/i,(d-l)/i,(u-c)/i),o}/**
492
+ * tiny-lru
493
+ *
494
+ * @copyright 2026 Jason Mulligan <jason.mulligan@avoidwork.com>
495
+ * @license BSD-3-Clause
496
+ * @version 11.4.7
497
+ */class zm{constructor(e=0,t=0,i=!1){this.first=null,this.items=Object.create(null),this.last=null,this.max=e,this.resetTtl=i,this.size=0,this.ttl=t}clear(){return this.first=null,this.items=Object.create(null),this.last=null,this.size=0,this}delete(e){if(this.has(e)){const t=this.items[e];delete this.items[e],this.size--,t.prev!==null&&(t.prev.next=t.next),t.next!==null&&(t.next.prev=t.prev),this.first===t&&(this.first=t.next),this.last===t&&(this.last=t.prev)}return this}entries(e=this.keys()){const t=new Array(e.length);for(let i=0;i<e.length;i++){const s=e[i];t[i]=[s,this.get(s)]}return t}evict(e=!1){if(e||this.size>0){const t=this.first;delete this.items[t.key],--this.size===0?(this.first=null,this.last=null):(this.first=t.next,this.first.prev=null)}return this}expiresAt(e){let t;return this.has(e)&&(t=this.items[e].expiry),t}get(e){const t=this.items[e];if(t!==void 0){if(this.ttl>0&&t.expiry<=Date.now()){this.delete(e);return}return this.moveToEnd(t),t.value}}has(e){return e in this.items}moveToEnd(e){this.last!==e&&(e.prev!==null&&(e.prev.next=e.next),e.next!==null&&(e.next.prev=e.prev),this.first===e&&(this.first=e.next),e.prev=this.last,e.next=null,this.last!==null&&(this.last.next=e),this.last=e,this.first===null&&(this.first=e))}keys(){const e=new Array(this.size);let t=this.first,i=0;for(;t!==null;)e[i++]=t.key,t=t.next;return e}setWithEvicted(e,t,i=this.resetTtl){let s=null;if(this.has(e))this.set(e,t,!0,i);else{this.max>0&&this.size===this.max&&(s={...this.first},this.evict(!0));let r=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t};++this.size===1?this.first=r:this.last.next=r,this.last=r}return s}set(e,t,i=!1,s=this.resetTtl){let r=this.items[e];return i||r!==void 0?(r.value=t,i===!1&&s&&(r.expiry=this.ttl>0?Date.now()+this.ttl:this.ttl),this.moveToEnd(r)):(this.max>0&&this.size===this.max&&this.evict(!0),r=this.items[e]={expiry:this.ttl>0?Date.now()+this.ttl:this.ttl,key:e,prev:this.last,next:null,value:t},++this.size===1?this.first=r:this.last.next=r,this.last=r),this}values(e=this.keys()){const t=new Array(e.length);for(let i=0;i<e.length;i++)t[i]=this.get(e[i]);return t}}function Lm(n=1e3,e=0,t=!1){if(isNaN(n)||n<0)throw new TypeError("Invalid max value");if(isNaN(e)||e<0)throw new TypeError("Invalid ttl value");if(typeof t!="boolean")throw new TypeError("Invalid resetTtl value");return new zm(n,e,t)}function nc(n){return!!n.tagStyles&&Object.keys(n.tagStyles).length>0}function rc(n){return n.includes("<")}function Om(n,e){return n.clone().assign(e)}function Wm(n,e){const t=[],i=e.tagStyles;if(!nc(e)||!rc(n))return t.push({text:n,style:e}),t;const s=[e],r=[];let o="",a=0;for(;a<n.length;){const h=n[a];if(h==="<"){const l=n.indexOf(">",a);if(l===-1){o+=h,a++;continue}const c=n.slice(a+1,l);if(c.startsWith("/")){const d=c.slice(1).trim();if(r.length>0&&r[r.length-1]===d){o.length>0&&(t.push({text:o,style:s[s.length-1]}),o=""),s.pop(),r.pop(),a=l+1;continue}else{o+=n.slice(a,l+1),a=l+1;continue}}else{const d=c.trim();if(i[d]){o.length>0&&(t.push({text:o,style:s[s.length-1]}),o="");const u=s[s.length-1],p=Om(u,i[d]);s.push(p),r.push(d),a=l+1;continue}else{o+=n.slice(a,l+1),a=l+1;continue}}}else o+=h,a++}return o.length>0&&t.push({text:o,style:s[s.length-1]}),t}const Gm=[10,13],Um=new Set(Gm),Hm=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],Vm=new Set(Hm),Nm=/(\r\n|\r|\n)/,$m=/(?:\r\n|\r|\n)/;function Vr(n){return typeof n!="string"?!1:Um.has(n.charCodeAt(0))}function Wt(n,e){return typeof n!="string"?!1:Vm.has(n.charCodeAt(0))}function oc(n){return n==="normal"||n==="pre-line"}function ac(n){return n==="normal"}function Qt(n){if(typeof n!="string")return"";let e=n.length-1;for(;e>=0&&Wt(n[e]);)e--;return e<n.length-1?n.slice(0,e+1):n}function hc(n){const e=[],t=[];if(typeof n!="string")return e;for(let i=0;i<n.length;i++){const s=n[i],r=n[i+1];if(Wt(s)||Vr(s)){t.length>0&&(e.push(t.join("")),t.length=0),s==="\r"&&r===`
498
+ `?(e.push(`\r
499
+ `),i++):e.push(s);continue}t.push(s)}return t.length>0&&e.push(t.join("")),e}function lc(n,e,t,i){const s=t(n),r=[];for(let o=0;o<s.length;o++){let a=s[o],h=a,l=1;for(;s[o+l];){const c=s[o+l];if(!i(h,c,n,o,e))a+=c,h=c,l++;else break}o+=l-1,r.push(a)}return r}const Ym=/\r\n|\r|\n/g;function Xm(n,e,t,i,s,r,o,a){var B;const h=Wm(n,e);if(ac(e.whiteSpace))for(let j=0;j<h.length;j++){const k=h[j];h[j]={text:k.text.replace(Ym," "),style:k.style}}const c=[];let d=[];for(const j of h){const k=j.text.split(Nm);for(let F=0;F<k.length;F++){const ot=k[F];ot===`\r
500
+ `||ot==="\r"||ot===`
501
+ `?(c.push(d),d=[]):ot.length>0&&d.push({text:ot,style:j.style})}}(d.length>0||c.length===0)&&c.push(d);const u=t?jm(c,e,i,s,o,a):c,p=[],g=[],m=[],y=[],x=[];let S=0;const v=e._fontString,b=r(v);b.fontSize===0&&(b.fontSize=e.fontSize,b.ascent=e.fontSize);let P="",C=!!e.dropShadow;for(const j of u){let k=0,F=b.ascent,ot=b.descent,z="";for(const Y of j){const ht=Y.style._fontString,wt=r(ht);ht!==P&&(i.font=ht,P=ht);const Ct=s(Y.text,Y.style.letterSpacing,i);k+=Ct,F=Math.max(F,wt.ascent),ot=Math.max(ot,wt.descent),z+=Y.text,!C&&Y.style.dropShadow&&(C=!0)}j.length===0&&(F=b.ascent,ot=b.descent),p.push(k),g.push(F),m.push(ot),x.push(z);const Z=e.lineHeight||F+ot;y.push(Z+e.leading),S=Math.max(S,k)}const _=((B=e._stroke)==null?void 0:B.width)||0,T=(t&&e.align!=="left"&&e.align!=="justify"?Math.max(S,e.wordWrapWidth):S)+_+(e.dropShadow?e.dropShadow.distance:0);let A=0;for(let j=0;j<y.length;j++)A+=y[j];A=Math.max(A,y[0]+_);const E=A+(e.dropShadow?e.dropShadow.distance:0),D=e.lineHeight||b.fontSize;return{width:T,height:E,lines:x,lineWidths:p,lineHeight:D+e.leading,maxLineWidth:S,fontProperties:b,runsByLine:u,lineAscents:g,lineDescents:m,lineHeights:y,hasDropShadow:C}}function jm(n,e,t,i,s,r){var y;const{letterSpacing:o,whiteSpace:a,wordWrapWidth:h,breakWords:l}=e,c=oc(a),d=h+o,u={};let p="";const g=(x,S)=>{const v=`${x}|${S.styleKey}`;let b=u[v];if(b===void 0){const P=S._fontString;P!==p&&(t.font=P,p=P),b=i(x,S.letterSpacing,t)+S.letterSpacing,u[v]=b}return b},m=[];for(const x of n){const S=Zm(x),v=m.length,b=E=>{let D=0,B=E;do{const{token:j,style:k}=S[B];D+=g(j,k),B++}while(B<S.length&&S[B].continuesFromPrevious);return D},P=E=>{const D=[];let B=E;do D.push({token:S[B].token,style:S[B].style}),B++;while(B<S.length&&S[B].continuesFromPrevious);return D};let C=[],_=0,R=!c,M=null;const T=()=>{M&&M.text.length>0&&C.push(M),M=null},A=()=>{if(T(),C.length>0){const E=C[C.length-1];E.text=Qt(E.text),E.text.length===0&&C.pop()}m.push(C),C=[],_=0,R=!1};for(let E=0;E<S.length;E++){const{token:D,style:B,continuesFromPrevious:j}=S[E],k=g(D,B);if(c){const z=Wt(D),Z=(M==null?void 0:M.text[M.text.length-1])??((y=C[C.length-1])==null?void 0:y.text.slice(-1))??"",Y=Z?Wt(Z):!1;if(z&&Y)continue}const F=!j,ot=F?b(E):k;if(ot>d&&F)if(_>0&&A(),l){const z=P(E);for(let Z=0;Z<z.length;Z++){const Y=z[Z].token,ht=z[Z].style,wt=lc(Y,l,r,s);for(const Ct of wt){const Et=g(Ct,ht);Et+_>d&&A(),!M||M.style!==ht?(T(),M={text:Ct,style:ht}):M.text+=Ct,_+=Et}}E+=z.length-1}else{const z=P(E);T(),m.push(z.map(Z=>({text:Z.token,style:Z.style}))),R=!1,E+=z.length-1}else if(ot+_>d&&F){if(Wt(D)){R=!1;continue}A(),M={text:D,style:B},_=k}else if(j&&!l)!M||M.style!==B?(T(),M={text:D,style:B}):M.text+=D,_+=k;else{const z=Wt(D);if(_===0&&z&&!R)continue;!M||M.style!==B?(T(),M={text:D,style:B}):M.text+=D,_+=k}}if(T(),C.length>0){const E=C[C.length-1];E.text=Qt(E.text),E.text.length===0&&C.pop()}(C.length>0||m.length===v)&&m.push(C)}return m}function Zm(n){const e=[];let t=!1;for(const i of n){const s=hc(i.text);let r=!0;for(const o of s){const a=Wt(o)||Vr(o),h=r&&t&&!a;e.push({token:o,style:i.style,continuesFromPrevious:h}),t=!a,r=!1}}return e}const qm={willReadFrequently:!0};function Wa(n,e,t,i,s){let r=t[n];return typeof r!="number"&&(r=s(n,e,i)+e,t[n]=r),r}function Km(n,e,t,i,s,r,o){const a=t.getContext("2d",qm);a.font=e._fontString;let h=0,l="";const c=[],d=Object.create(null),{letterSpacing:u,whiteSpace:p}=e,g=oc(p),m=ac(p);let y=!g;const x=e.wordWrapWidth+u,S=hc(n);for(let b=0;b<S.length;b++){let P=S[b];if(Vr(P)){if(!m){c.push(Qt(l)),y=!g,l="",h=0;continue}P=" "}if(g){const _=Wt(P),R=Wt(l[l.length-1]);if(_&&R)continue}const C=Wa(P,u,d,a,i);if(C>x)if(l!==""&&(c.push(Qt(l)),l="",h=0),s(P,e.breakWords)){const _=lc(P,e.breakWords,o,r);for(const R of _){const M=Wa(R,u,d,a,i);M+h>x&&(c.push(Qt(l)),y=!1,l="",h=0),l+=R,h+=M}}else l.length>0&&(c.push(Qt(l)),l="",h=0),c.push(Qt(P)),y=!1,l="",h=0;else C+h>x&&(y=!1,c.push(Qt(l)),l="",h=0),(l.length>0||!Wt(P)||y)&&(l+=P,h+=C)}const v=Qt(l);return v.length>0&&c.push(v),c.join(`
502
+ `)}const Ga={willReadFrequently:!0},re=class O{static get experimentalLetterSpacingSupported(){let e=O._experimentalLetterSpacingSupported;if(e===void 0){const t=$.get().getCanvasRenderingContext2D().prototype;e=O._experimentalLetterSpacingSupported="letterSpacing"in t||"textLetterSpacing"in t}return e}constructor(e,t,i,s,r,o,a,h,l,c){this.text=e,this.style=t,this.width=i,this.height=s,this.lines=r,this.lineWidths=o,this.lineHeight=a,this.maxLineWidth=h,this.fontProperties=l,c&&(this.runsByLine=c.runsByLine,this.lineAscents=c.lineAscents,this.lineDescents=c.lineDescents,this.lineHeights=c.lineHeights,this.hasDropShadow=c.hasDropShadow)}static measureText(e=" ",t,i=O._canvas,s=t.wordWrap){var P;const r=`${e}-${t.styleKey}-wordWrap-${s}`;if(O._measurementCache.has(r))return O._measurementCache.get(r);if(nc(t)&&rc(e)){const C=Xm(e,t,s,O._context,O._measureText,O.measureFont,O.canBreakChars,O.wordWrapSplit),_=new O(e,t,C.width,C.height,C.lines,C.lineWidths,C.lineHeight,C.maxLineWidth,C.fontProperties,{runsByLine:C.runsByLine,lineAscents:C.lineAscents,lineDescents:C.lineDescents,lineHeights:C.lineHeights,hasDropShadow:C.hasDropShadow});return O._measurementCache.set(r,_),_}const a=t._fontString,h=O.measureFont(a);h.fontSize===0&&(h.fontSize=t.fontSize,h.ascent=t.fontSize,h.descent=0);const l=O._context;l.font=a;const d=(s?O._wordWrap(e,t,i):e).split($m),u=new Array(d.length);let p=0;for(let C=0;C<d.length;C++){const _=O._measureText(d[C],t.letterSpacing,l);u[C]=_,p=Math.max(p,_)}const g=((P=t._stroke)==null?void 0:P.width)??0,m=t.lineHeight||h.fontSize,y=O._getAlignWidth(p,t,s),x=O._adjustWidthForStyle(y,t),S=Math.max(m,h.fontSize+g)+(d.length-1)*(m+t.leading),v=O._adjustHeightForStyle(S,t),b=new O(e,t,x,v,d,u,m+t.leading,p,h);return O._measurementCache.set(r,b),b}static _adjustWidthForStyle(e,t){var r;const i=((r=t._stroke)==null?void 0:r.width)||0;let s=e+i;return t.dropShadow&&(s+=t.dropShadow.distance),s}static _adjustHeightForStyle(e,t){let i=e;return t.dropShadow&&(i+=t.dropShadow.distance),i}static _getAlignWidth(e,t,i){return i&&t.align!=="left"&&t.align!=="justify"?Math.max(e,t.wordWrapWidth):e}static _measureText(e,t,i){let s=!1;O.experimentalLetterSpacingSupported&&(O.experimentalLetterSpacing?(i.letterSpacing=`${t}px`,i.textLetterSpacing=`${t}px`,s=!0):(i.letterSpacing="0px",i.textLetterSpacing="0px"));const r=i.measureText(e);let o=r.width;const a=-(r.actualBoundingBoxLeft??0);let l=(r.actualBoundingBoxRight??0)-a;if(o>0)if(s)o-=t,l-=t;else{const c=(O.graphemeSegmenter(e).length-1)*t;o+=c,l+=c}return Math.max(o,l)}static _wordWrap(e,t,i=O._canvas){return Km(e,t,i,O._measureText,O.canBreakWords,O.canBreakChars,O.wordWrapSplit)}static isBreakingSpace(e,t){return Wt(e)}static canBreakWords(e,t){return t}static canBreakChars(e,t,i,s,r){return!0}static wordWrapSplit(e){return O.graphemeSegmenter(e)}static measureFont(e){if(O._fonts[e])return O._fonts[e];const t=O._context;t.font=e;const i=t.measureText(O.METRICS_STRING+O.BASELINE_SYMBOL),s=i.actualBoundingBoxAscent??0,r=i.actualBoundingBoxDescent??0,o={ascent:s,descent:r,fontSize:s+r};return O._fonts[e]=o,o}static clearMetrics(e=""){e?delete O._fonts[e]:O._fonts={}}static get _canvas(){if(!O.__canvas){let e;try{const t=new OffscreenCanvas(0,0),i=t.getContext("2d",Ga);if(i!=null&&i.measureText)return O.__canvas=t,t;e=$.get().createCanvas()}catch{e=$.get().createCanvas()}e.width=e.height=10,O.__canvas=e}return O.__canvas}static get _context(){return O.__context||(O.__context=O._canvas.getContext("2d",Ga)),O.__context}};re.METRICS_STRING="|ÉqÅ";re.BASELINE_SYMBOL="M";re.BASELINE_MULTIPLIER=1.4;re.HEIGHT_MULTIPLIER=2;re.graphemeSegmenter=n=>[...n];re.experimentalLetterSpacing=!1;re._fonts={};re._measurementCache=Lm(1e3);let oe=re;const Qm=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function ur(n){const e=typeof n.fontSize=="number"?`${n.fontSize}px`:n.fontSize;let t=n.fontFamily;Array.isArray(n.fontFamily)||(t=n.fontFamily.split(","));for(let i=t.length-1;i>=0;i--){let s=t[i].trim();!/([\"\'])[^\'\"]+\1/.test(s)&&!Qm.includes(s)&&(s=`"${s}"`),t[i]=s}return`${n.fontStyle} ${n.fontVariant} ${n.fontWeight} ${e} ${t.join(",")}`}const Ua=1e5;function cs(n,e,t,i=0,s=0,r=0){if(n.texture===G.WHITE&&!n.fill)return rt.shared.setValue(n.color).setAlpha(n.alpha??1).toHexa();if(n.fill){if(n.fill instanceof Os){const o=n.fill,a=e.createPattern(o.texture.source.resource,"repeat"),h=o.transform.copyTo(H.shared);return h.scale(o.texture.source.pixelWidth,o.texture.source.pixelHeight),a.setTransform(h),a}else if(n.fill instanceof Gt){const o=n.fill,a=o.type==="linear",h=o.textureSpace==="local";let l=1,c=1;h&&t&&(l=t.width+i,c=t.height+i);let d,u=!1;if(a){const{start:p,end:g}=o;d=e.createLinearGradient(p.x*l+s,p.y*c+r,g.x*l+s,g.y*c+r),u=Math.abs(g.x-p.x)<Math.abs((g.y-p.y)*.1)}else{const{center:p,innerRadius:g,outerCenter:m,outerRadius:y}=o;d=e.createRadialGradient(p.x*l+s,p.y*c+r,g*l,m.x*l+s,m.y*c+r,y*l)}if(u&&h&&t){const p=t.lineHeight/c;for(let g=0;g<t.lines.length;g++){const m=(g*t.lineHeight+i/2)/c;o.colorStops.forEach(y=>{let x=m+y.offset*p;x=Math.max(0,Math.min(1,x)),d.addColorStop(Math.floor(x*Ua)/Ua,rt.shared.setValue(y.color).toHex())})}}else o.colorStops.forEach(p=>{d.addColorStop(p.offset,rt.shared.setValue(p.color).toHex())});return d}}else{const o=e.createPattern(n.texture.source.resource,"repeat"),a=n.matrix.copyTo(H.shared);return a.scale(n.texture.source.pixelWidth,n.texture.source.pixelHeight),o.setTransform(a),o}return nt("FillStyle not recognised",n),"red"}const Ha=new tt;class Jm{getCanvasAndContext(e){const{text:t,style:i,resolution:s=1}=e,r=i._getFinalPadding(),o=oe.measureText(t||" ",i),a=Math.ceil(Math.ceil(Math.max(1,o.width)+r*2)*s),h=Math.ceil(Math.ceil(Math.max(1,o.height)+r*2)*s),l=dr.getOptimalCanvasAndContext(a,h);this._renderTextToCanvas(i,r,s,l,o);const c=i.trim?Bm({canvas:l.canvas,width:a,height:h,resolution:1,output:Ha}):Ha.set(0,0,a,h);return{canvasAndContext:l,frame:c}}returnCanvasAndContext(e){dr.returnCanvasAndContext(e)}_renderTextToCanvas(e,t,i,s,r){var C,_,R;if(r.runsByLine&&r.runsByLine.length>0){this._renderTaggedTextToCanvas(r,e,t,i,s);return}const{canvas:o,context:a}=s,h=ur(e),l=r.lines,c=r.lineHeight,d=r.lineWidths,u=r.maxLineWidth,p=r.fontProperties,g=o.height;if(a.resetTransform(),a.scale(i,i),a.textBaseline=e.textBaseline,(C=e._stroke)!=null&&C.width){const M=e._stroke;a.lineWidth=M.width,a.miterLimit=M.miterLimit,a.lineJoin=M.join,a.lineCap=M.cap}a.font=h;let m,y;const x=e.dropShadow?2:1,S=e.wordWrap?e.wordWrapWidth:u,b=(((_=e._stroke)==null?void 0:_.width)??0)/2;let P=(c-p.fontSize)/2;c-p.fontSize<0&&(P=0);for(let M=0;M<x;++M){const T=e.dropShadow&&M===0,A=T?Math.ceil(Math.max(1,g)+t*2):0,E=A*i;if(T)this._setupDropShadow(a,e,i,E);else{const D=e._gradientBounds,B=e._gradientOffset;if(D){const j={width:D.width,height:D.height,lineHeight:D.height,lines:r.lines};this._setFillAndStrokeStyles(a,e,j,t,b,(B==null?void 0:B.x)??0,(B==null?void 0:B.y)??0)}else B?this._setFillAndStrokeStyles(a,e,r,t,b,B.x,B.y):this._setFillAndStrokeStyles(a,e,r,t,b);a.shadowColor="black"}for(let D=0;D<l.length;D++)m=b,y=b+D*c+p.ascent+P,m+=this._getAlignmentOffset(d[D],S,e.align),(R=e._stroke)!=null&&R.width&&this._drawLetterSpacing(l[D],e,s,m+t,y+t-A,!0),e._fill!==void 0&&this._drawLetterSpacing(l[D],e,s,m+t,y+t-A)}}_renderTaggedTextToCanvas(e,t,i,s,r){var b,P;const{canvas:o,context:a}=r,{runsByLine:h,lineWidths:l,maxLineWidth:c,lineAscents:d,lineHeights:u,hasDropShadow:p}=e,g=o.height;a.resetTransform(),a.scale(s,s),a.textBaseline=t.textBaseline;const m=p?2:1,y=t.wordWrap?t.wordWrapWidth:c,S=(((b=t._stroke)==null?void 0:b.width)??0)/2,v=[];for(let C=0;C<h.length;C++){const _=h[C],R=[];for(const M of _){const T=ur(M.style);a.font=T,R.push({width:oe._measureText(M.text,M.style.letterSpacing,a),font:T})}v.push(R)}for(let C=0;C<m;++C){const _=p&&C===0,R=_?Math.ceil(Math.max(1,g)+i*2):0,M=R*s;_||(a.shadowColor="black");let T=S;for(let A=0;A<h.length;A++){const E=h[A],D=l[A],B=d[A],j=u[A],k=v[A];let F=S;F+=this._getAlignmentOffset(D,y,t.align);const ot=T+B;let z=F+i;for(let Z=0;Z<E.length;Z++){const Y=E[Z],{width:ht,font:wt}=k[Z];if(a.font=wt,a.textBaseline=Y.style.textBaseline,(P=Y.style._stroke)!=null&&P.width){const Ct=Y.style._stroke;if(a.lineWidth=Ct.width,a.miterLimit=Ct.miterLimit,a.lineJoin=Ct.join,a.lineCap=Ct.cap,_)if(Y.style.dropShadow)this._setupDropShadow(a,Y.style,s,M);else{z+=ht;continue}else{const Et=oe.measureFont(wt),Ut=Y.style.lineHeight||Et.fontSize,Yi={width:ht,height:Ut,lineHeight:Ut,lines:[Y.text]};a.strokeStyle=cs(Ct,a,Yi,i*2,z-i,T)}this._drawLetterSpacing(Y.text,Y.style,r,z,ot+i-R,!0)}z+=ht}z=F+i;for(let Z=0;Z<E.length;Z++){const Y=E[Z],{width:ht,font:wt}=k[Z];if(a.font=wt,a.textBaseline=Y.style.textBaseline,Y.style._fill!==void 0){if(_)if(Y.style.dropShadow)this._setupDropShadow(a,Y.style,s,M);else{z+=ht;continue}else{const Ct=oe.measureFont(wt),Et=Y.style.lineHeight||Ct.fontSize,Ut={width:ht,height:Et,lineHeight:Et,lines:[Y.text]};a.fillStyle=cs(Y.style._fill,a,Ut,i*2,z-i,T)}this._drawLetterSpacing(Y.text,Y.style,r,z,ot+i-R,!1)}z+=ht}T+=j}}}_setFillAndStrokeStyles(e,t,i,s,r,o=0,a=0){var h;if(e.fillStyle=t._fill?cs(t._fill,e,i,s*2,o,a):null,(h=t._stroke)!=null&&h.width){const l=r+s*2;e.strokeStyle=cs(t._stroke,e,i,l,o,a)}}_setupDropShadow(e,t,i,s){e.fillStyle="black",e.strokeStyle="black";const r=t.dropShadow,o=r.color,a=r.alpha;e.shadowColor=rt.shared.setValue(o).setAlpha(a).toRgbaString();const h=r.blur*i,l=r.distance*i;e.shadowBlur=h,e.shadowOffsetX=Math.cos(r.angle)*l,e.shadowOffsetY=Math.sin(r.angle)*l+s}_getAlignmentOffset(e,t,i){return i==="right"?t-e:i==="center"?(t-e)/2:0}_drawLetterSpacing(e,t,i,s,r,o=!1){const{context:a}=i,h=t.letterSpacing;let l=!1;if(oe.experimentalLetterSpacingSupported&&(oe.experimentalLetterSpacing?(a.letterSpacing=`${h}px`,a.textLetterSpacing=`${h}px`,l=!0):(a.letterSpacing="0px",a.textLetterSpacing="0px")),h===0||l){o?a.strokeText(e,s,r):a.fillText(e,s,r);return}let c=s;const d=oe.graphemeSegmenter(e);let u=a.measureText(e).width,p=0;for(let g=0;g<d.length;++g){const m=d[g];o?a.strokeText(m,c,r):a.fillText(m,c,r);let y="";for(let x=g+1;x<d.length;++x)y+=d[x];p=a.measureText(y).width,c+=u-p+h,u=p}}}const Xe=new Jm,Nr=class Me extends jt{constructor(e={}){super(),this.uid=dt("textStyle"),this._tick=0,this._cachedFontString=null,ty(e),e instanceof Me&&(e=e._toObject());const s={...Me.defaultTextStyle,...e};for(const r in s){const o=r;this[o]=s[r]}this._tagStyles=e.tagStyles??void 0,this.update(),this._tick=0}get align(){return this._align}set align(e){this._align!==e&&(this._align=e,this.update())}get breakWords(){return this._breakWords}set breakWords(e){this._breakWords!==e&&(this._breakWords=e,this.update())}get dropShadow(){return this._dropShadow}set dropShadow(e){this._dropShadow!==e&&(e!==null&&typeof e=="object"?this._dropShadow=this._createProxy({...Me.defaultDropShadow,...e}):this._dropShadow=e?this._createProxy({...Me.defaultDropShadow}):null,this.update())}get fontFamily(){return this._fontFamily}set fontFamily(e){this._fontFamily!==e&&(this._fontFamily=e,this.update())}get fontSize(){return this._fontSize}set fontSize(e){this._fontSize!==e&&(typeof e=="string"?this._fontSize=parseInt(e,10):this._fontSize=e,this.update())}get fontStyle(){return this._fontStyle}set fontStyle(e){this._fontStyle!==e&&(this._fontStyle=e.toLowerCase(),this.update())}get fontVariant(){return this._fontVariant}set fontVariant(e){this._fontVariant!==e&&(this._fontVariant=e,this.update())}get fontWeight(){return this._fontWeight}set fontWeight(e){this._fontWeight!==e&&(this._fontWeight=e,this.update())}get leading(){return this._leading}set leading(e){this._leading!==e&&(this._leading=e,this.update())}get letterSpacing(){return this._letterSpacing}set letterSpacing(e){this._letterSpacing!==e&&(this._letterSpacing=e,this.update())}get lineHeight(){return this._lineHeight}set lineHeight(e){this._lineHeight!==e&&(this._lineHeight=e,this.update())}get padding(){return this._padding}set padding(e){this._padding!==e&&(this._padding=e,this.update())}get filters(){return this._filters}set filters(e){this._filters!==e&&(this._filters=Object.freeze(e),this.update())}get trim(){return this._trim}set trim(e){this._trim!==e&&(this._trim=e,this.update())}get textBaseline(){return this._textBaseline}set textBaseline(e){this._textBaseline!==e&&(this._textBaseline=e,this.update())}get whiteSpace(){return this._whiteSpace}set whiteSpace(e){this._whiteSpace!==e&&(this._whiteSpace=e,this.update())}get wordWrap(){return this._wordWrap}set wordWrap(e){this._wordWrap!==e&&(this._wordWrap=e,this.update())}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(e){this._wordWrapWidth!==e&&(this._wordWrapWidth=e,this.update())}get fill(){return this._originalFill}set fill(e){e!==this._originalFill&&(this._originalFill=e,this._isFillStyle(e)&&(this._originalFill=this._createProxy({...gt.defaultFillStyle,...e},()=>{this._fill=Ae({...this._originalFill},gt.defaultFillStyle)})),this._fill=Ae(e===0?"black":e,gt.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(e){e!==this._originalStroke&&(this._originalStroke=e,this._isFillStyle(e)&&(this._originalStroke=this._createProxy({...gt.defaultStrokeStyle,...e},()=>{this._stroke=Ps({...this._originalStroke},gt.defaultStrokeStyle)})),this._stroke=Ps(e,gt.defaultStrokeStyle),this.update())}get tagStyles(){return this._tagStyles}set tagStyles(e){this._tagStyles!==e&&(this._tagStyles=e??void 0,this.update())}update(){this._tick++,this._cachedFontString=null,this.emit("update",this)}reset(){const e=Me.defaultTextStyle;for(const t in e)this[t]=e[t]}assign(e){for(const t in e){const i=t;this[i]=e[t]}return this}get styleKey(){return`${this.uid}-${this._tick}`}get _fontString(){return this._cachedFontString===null&&(this._cachedFontString=ur(this)),this._cachedFontString}_toObject(){return{align:this.align,breakWords:this.breakWords,dropShadow:this._dropShadow?{...this._dropShadow}:null,fill:this._fill?{...this._fill}:void 0,fontFamily:this.fontFamily,fontSize:this.fontSize,fontStyle:this.fontStyle,fontVariant:this.fontVariant,fontWeight:this.fontWeight,leading:this.leading,letterSpacing:this.letterSpacing,lineHeight:this.lineHeight,padding:this.padding,stroke:this._stroke?{...this._stroke}:void 0,textBaseline:this.textBaseline,trim:this.trim,whiteSpace:this.whiteSpace,wordWrap:this.wordWrap,wordWrapWidth:this.wordWrapWidth,filters:this._filters?[...this._filters]:void 0,tagStyles:this._tagStyles?{...this._tagStyles}:void 0}}clone(){return new Me(this._toObject())}_getFinalPadding(){let e=0;if(this._filters)for(let t=0;t<this._filters.length;t++)e+=this._filters[t].padding;return Math.max(this._padding,e)}destroy(e=!1){var i,s,r,o;if(this.removeAllListeners(),typeof e=="boolean"?e:e==null?void 0:e.texture){const a=typeof e=="boolean"?e:e==null?void 0:e.textureSource;(i=this._fill)!=null&&i.texture&&this._fill.texture.destroy(a),(s=this._originalFill)!=null&&s.texture&&this._originalFill.texture.destroy(a),(r=this._stroke)!=null&&r.texture&&this._stroke.texture.destroy(a),(o=this._originalStroke)!=null&&o.texture&&this._originalStroke.texture.destroy(a)}this._fill=null,this._stroke=null,this.dropShadow=null,this._originalStroke=null,this._originalFill=null}_createProxy(e,t){return new Proxy(e,{set:(i,s,r)=>(i[s]===r||(i[s]=r,t==null||t(s,r),this.update()),!0)})}_isFillStyle(e){return(e??null)!==null&&!(rt.isColorLike(e)||e instanceof Gt||e instanceof Os)}};Nr.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5};Nr.defaultTextStyle={align:"left",breakWords:!1,dropShadow:null,fill:"black",fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,padding:0,stroke:null,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let ue=Nr;function ty(n){const e=n;if(typeof e.dropShadow=="boolean"&&e.dropShadow){const t=ue.defaultDropShadow;n.dropShadow={alpha:e.dropShadowAlpha??t.alpha,angle:e.dropShadowAngle??t.angle,blur:e.dropShadowBlur??t.blur,color:e.dropShadowColor??t.color,distance:e.dropShadowDistance??t.distance}}if(e.strokeThickness!==void 0){V(Q,"strokeThickness is now a part of stroke");const t=e.stroke;let i={};if(rt.isColorLike(t))i.color=t;else if(t instanceof Gt||t instanceof Os)i.fill=t;else if(Object.hasOwnProperty.call(t,"color")||Object.hasOwnProperty.call(t,"fill"))i=t;else throw new Error("Invalid stroke value.");n.stroke={...i,width:e.strokeThickness}}if(Array.isArray(e.fillGradientStops)){if(V(Q,"gradient fill is now a fill pattern: `new FillGradient(...)`"),!Array.isArray(e.fill)||e.fill.length===0)throw new Error("Invalid fill value. Expected an array of colors for gradient fill.");e.fill.length!==e.fillGradientStops.length&&nt("The number of fill colors must match the number of fill gradient stops.");const t=new Gt({start:{x:0,y:0},end:{x:0,y:1},textureSpace:"local"}),i=e.fillGradientStops.slice(),s=e.fill.map(r=>rt.shared.setValue(r).toNumber());i.forEach((r,o)=>{t.addColorStop(r,s[o])}),n.fill={fill:t}}}function ey(n,e){const{texture:t,bounds:i}=n,s=e._style._getFinalPadding();Dh(i,e._anchor,t);const r=e._anchor._x*s*2,o=e._anchor._y*s*2;i.minX-=s-r,i.minY-=s-o,i.maxX-=s-r,i.maxY-=s-o}class iy{constructor(){this.batcherName="default",this.topology="triangle-list",this.attributeSize=4,this.indexSize=6,this.packAsQuad=!0,this.roundPixels=0,this._attributeStart=0,this._batcher=null,this._batch=null}get blendMode(){return this.renderable.groupBlendMode}get color(){return this.renderable.groupColorAlpha}reset(){this.renderable=null,this.texture=null,this._batcher=null,this._batch=null,this.bounds=null}destroy(){this.reset()}}class sy extends iy{}class cc{constructor(e){this._renderer=e,e.runners.resolutionChange.add(this),this._managedTexts=new ci({renderer:e,type:"renderable",onUnload:this.onTextUnload.bind(this),name:"canvasText"})}resolutionChange(){for(const e in this._managedTexts.items){const t=this._managedTexts.items[e];t!=null&&t._autoResolution&&t.onViewUpdate()}}validateRenderable(e){const t=this._getGpuText(e),i=e.styleKey;return t.currentKey!==i?!0:e._didTextUpdate}addRenderable(e,t){const i=this._getGpuText(e);if(e._didTextUpdate){const s=e._autoResolution?this._renderer.resolution:e.resolution;(i.currentKey!==e.styleKey||e._resolution!==s)&&this._updateGpuText(e),e._didTextUpdate=!1,ey(i,e)}this._renderer.renderPipes.batch.addToBatch(i,t)}updateRenderable(e){const t=this._getGpuText(e);t._batcher.updateElement(t)}_updateGpuText(e){const t=this._getGpuText(e);t.texture&&this._renderer.canvasText.decreaseReferenceCount(t.currentKey),e._resolution=e._autoResolution?this._renderer.resolution:e.resolution,t.texture=this._renderer.canvasText.getManagedTexture(e),t.currentKey=e.styleKey}_getGpuText(e){return e._gpuData[this._renderer.uid]||this.initGpuText(e)}initGpuText(e){const t=new sy;return t.currentKey="--",t.renderable=e,t.transform=e.groupTransform,t.bounds={minX:0,maxX:1,minY:0,maxY:0},t.roundPixels=this._renderer._roundPixels|e._roundPixels,e._gpuData[this._renderer.uid]=t,this._managedTexts.add(e),t}onTextUnload(e){const t=e._gpuData[this._renderer.uid];if(!t)return;const{canvasText:i}=this._renderer;i.getReferenceCount(t.currentKey)>0?i.decreaseReferenceCount(t.currentKey):t.texture&&i.returnTexture(t.texture)}destroy(){this._managedTexts.destroy(),this._renderer=null}}cc.extension={type:[I.WebGLPipes,I.WebGPUPipes,I.CanvasPipes],name:"text"};const ny=new Ft;function ry(n,e,t,i){const s=ny;s.minX=0,s.minY=0,s.maxX=n.width/i|0,s.maxY=n.height/i|0;const r=Ds.getOptimalTexture(s.width,s.height,i,!1);return r.source.uploadMethodId="image",r.source.resource=n,r.source.alphaMode="premultiply-alpha-on-upload",r.frame.width=e/i,r.frame.height=t/i,r.source.emit("update",r.source),r.updateUvs(),r}class dc{constructor(e,t){this._activeTextures={},this._renderer=e,this._retainCanvasContext=t}getTexture(e,t,i,s){typeof e=="string"&&(V("8.0.0","CanvasTextSystem.getTexture: Use object TextOptions instead of separate arguments"),e={text:e,style:i,resolution:t}),e.style instanceof ue||(e.style=new ue(e.style)),e.textureStyle instanceof Je||(e.textureStyle=new Je(e.textureStyle)),typeof e.text!="string"&&(e.text=e.text.toString());const{text:r,style:o,textureStyle:a}=e,h=e.resolution??this._renderer.resolution,{frame:l,canvasAndContext:c}=Xe.getCanvasAndContext({text:r,style:o,resolution:h}),d=ry(c.canvas,l.width,l.height,h);if(a&&(d.source.style=a),o.trim&&(l.pad(o.padding),d.frame.copyFrom(l),d.frame.scale(1/h),d.updateUvs()),o.filters){const u=this._applyFilters(d,o.filters);return this.returnTexture(d),Xe.returnCanvasAndContext(c),u}return this._renderer.texture.initSource(d._source),this._retainCanvasContext||Xe.returnCanvasAndContext(c),d}returnTexture(e){const t=e.source,i=t.resource;if(this._retainCanvasContext&&(i!=null&&i.getContext)){const s=i.getContext("2d");s&&Xe.returnCanvasAndContext({canvas:i,context:s})}t.resource=null,t.uploadMethodId="unknown",t.alphaMode="no-premultiply-alpha",Ds.returnTexture(e,!0)}renderTextToCanvas(){V("8.10.0","CanvasTextSystem.renderTextToCanvas: no longer supported, use CanvasTextSystem.getTexture instead")}getManagedTexture(e){e._resolution=e._autoResolution?this._renderer.resolution:e.resolution;const t=e.styleKey;if(this._activeTextures[t])return this._increaseReferenceCount(t),this._activeTextures[t].texture;const i=this.getTexture({text:e.text,style:e.style,resolution:e._resolution,textureStyle:e.textureStyle});return this._activeTextures[t]={texture:i,usageCount:1},i}decreaseReferenceCount(e){const t=this._activeTextures[e];t&&(t.usageCount--,t.usageCount===0&&(this.returnTexture(t.texture),this._activeTextures[e]=null))}getReferenceCount(e){var t;return((t=this._activeTextures[e])==null?void 0:t.usageCount)??0}_increaseReferenceCount(e){this._activeTextures[e].usageCount++}_applyFilters(e,t){const i=this._renderer.renderTarget.renderTarget,s=this._renderer.filter.generateFilteredTexture({texture:e,filters:t});return this._renderer.renderTarget.bind(i,!1),s}destroy(){this._renderer=null;for(const e in this._activeTextures)this._activeTextures[e]&&this.returnTexture(this._activeTextures[e].texture);this._activeTextures=null}}class uc extends dc{constructor(e){super(e,!0)}}uc.extension={type:[I.CanvasSystem],name:"canvasText"};class pc extends dc{constructor(e){super(e,!1)}}pc.extension={type:[I.WebGLSystem,I.WebGPUSystem],name:"canvasText"};K.add(uc);K.add(pc);K.add(cc);class Ws extends Im{constructor(...e){const t=Em(e,"Text");super(t,ue),this.renderPipeId="text",t.textureStyle&&(this.textureStyle=t.textureStyle instanceof Je?t.textureStyle:new Je(t.textureStyle))}updateBounds(){const e=this._bounds,t=this._anchor;let i=0,s=0;if(this._style.trim){const{frame:r,canvasAndContext:o}=Xe.getCanvasAndContext({text:this.text,style:this._style,resolution:1});Xe.returnCanvasAndContext(o),i=r.width,s=r.height}else{const r=oe.measureText(this._text,this._style);i=r.width,s=r.height}e.minX=-t._x*i,e.maxX=e.minX+i,e.minY=-t._y*s,e.maxY=e.minY+s}}class $r extends G{static create(e){const{dynamic:t,...i}=e;return new $r({source:new zt(i),dynamic:t??!1})}resize(e,t,i){return this.source.resize(e,t,i),this}}K.add(Td,Rd);function oy(n,e){var t=-1,i=n.length;for(e||(e=Array(i));++t<i;)e[t]=n[t];return e}function ay(n,e,t,i){var s=!t;t||(t={});for(var r=-1,o=e.length;++r<o;){var a=e[r],h=void 0;h===void 0&&(h=n[a]),s?Sh(t,a,h):vh(t,a,h)}return t}function hy(n){return Jc(function(e,t){var i=-1,s=t.length,r=s>1?t[s-1]:void 0,o=s>2?t[2]:void 0;for(r=n.length>3&&typeof r=="function"?(s--,r):void 0,o&&td(t[0],t[1],o)&&(r=s<3?void 0:r,s=1),e=Object(e);++i<s;){var a=t[i];a&&n(e,a,i,r)}return e})}function ly(n){var e=[];if(n!=null)for(var t in Object(n))e.push(t);return e}var cy=Object.prototype,dy=cy.hasOwnProperty;function uy(n){if(!De(n))return ly(n);var e=ed(n),t=[];for(var i in n)i=="constructor"&&(e||!dy.call(n,i))||t.push(i);return t}function fc(n){return bh(n)?id(n,!0):uy(n)}function py(n){var e=n==null?0:n.length;return e?sd(n):[]}function fy(n){return nd(rd(n,void 0,py),n+"")}var gy="[object Object]",my=Function.prototype,yy=Object.prototype,gc=my.toString,xy=yy.hasOwnProperty,Sy=gc.call(Object);function vy(n){if(!wr(n)||wh(n)!=gy)return!1;var e=od(n);if(e===null)return!0;var t=xy.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&gc.call(t)==Sy}var by=ld.isFinite,wy=Math.min;function Cy(n){var e=Math[n];return function(t,i){if(t=ad(t),i=i==null?0:wy(hd(i),292),i&&by(t)){var s=(ao(t)+"e").split("e"),r=e(s[0]+"e"+(+s[1]+i));return s=(ao(r)+"e").split("e"),+(s[0]+"e"+(+s[1]-i))}return e(t)}}function pr(n,e,t){(t!==void 0&&!cd(n[e],t)||t===void 0&&!(e in n))&&Sh(n,e,t)}function _y(n){return wr(n)&&bh(n)}function fr(n,e){if(!(e==="constructor"&&typeof n[e]=="function")&&e!="__proto__")return n[e]}function Py(n){return ay(n,fc(n))}function My(n,e,t,i,s,r,o){var a=fr(n,t),h=fr(e,t),l=o.get(h);if(l){pr(n,t,l);return}var c=r?r(a,h,t+"",n,e,o):void 0,d=c===void 0;if(d){var u=Hn(h),p=!u&&dd(h),g=!u&&!p&&ud(h);c=h,u||p||g?Hn(a)?c=a:_y(a)?c=oy(a):p?(d=!1,c=pd(h,!0)):g?(d=!1,c=fd(h,!0)):c=[]:vy(h)||ho(h)?(c=a,ho(a)?c=Py(a):(!De(a)||gd(a))&&(c=md(h))):d=!1}d&&(o.set(h,c),s(c,h,i,r,o),o.delete(h)),pr(n,t,c)}function mc(n,e,t,i,s){n!==e&&yd(e,function(r,o){if(s||(s=new xd),De(r))My(n,e,o,t,mc,i,s);else{var a=i?i(fr(n,o),r,o+"",n,e,s):void 0;a===void 0&&(a=r),pr(n,o,a)}},fc)}var Va=hy(function(n,e,t,i){mc(n,e,t,i)}),Ay="[object Number]";function Na(n){return typeof n=="number"||wr(n)&&wh(n)==Ay}function Ty(n,e,t,i){if(!De(n))return n;e=Ch(e,n);for(var s=-1,r=e.length,o=r-1,a=n;a!=null&&++s<r;){var h=Sd(e[s]),l=t;if(h==="__proto__"||h==="constructor"||h==="prototype")return n;if(s!=o){var c=a[h];l=void 0,l===void 0&&(l=De(c)?c:vd(e[s+1])?[]:{})}vh(a,h,l),a=a[h]}return n}function Ry(n,e,t){for(var i=-1,s=e.length,r={};++i<s;){var o=e[i],a=bd(n,o);t(a,o)&&Ty(r,Ch(o,n),a)}return r}function ky(n,e){return Ry(n,e,function(t,i){return wd(n,i)})}var Dn=fy(function(n,e){return n==null?{}:ky(n,e)}),$a=Cy("round"),Iy="Expected a function";function _t(n,e,t){var i=!0,s=!0;if(typeof n!="function")throw new TypeError(Iy);return De(t)&&(i="leading"in t?!!t.leading:i,s="trailing"in t?!!t.trailing:s),Vn(n,e,{leading:i,maxWait:e,trailing:s})}const Yr=(n,e,t)=>{if(!e)return{x:0,y:0};const i=Math.cos(t),s=Math.sin(t);return{x:(n.x*i+n.y*s)/e,y:(-n.x*s+n.y*i)/e}};function Ey(n){return n<.5?4*n*n*n:(n-1)*(2*n-2)*(2*n-2)+1}function yc(n,e=2){if(n==null)return n;if(Na(n))return $a(n,e);if(Hn(n))return Cd(n,t=>yc(t,e));if(De(n)){const t=["x","y","rotation"];return _d(n,(i,s)=>Na(i)&&t.includes(s)?$a(i,e):i)}return n}const Ya=100,xc=2*1024,Yt="__log_summary__";function Dy(n){return n.length>xc}function Fy(n){try{return JSON.stringify(n)}catch{return"[unserializable]"}}function Xa(n){return typeof n=="string"?n.length:n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:Fy(n).length}function By(n,e=3){return n.slice(0,e)}function zy(n){if(Array.isArray(n))return n.length<=Ya?n:{[Yt]:!0,type:"Array",size:n.length,byteLength:Xa(n),sample:By(n)};if(ArrayBuffer.isView(n)&&!(n instanceof DataView)){const e=n;return e.length<=Ya?n:{[Yt]:!0,type:n.constructor.name,size:e.length,byteLength:e.byteLength,sample:Array.from(n).slice(0,3)}}if(typeof n=="string")return Dy(n)?{[Yt]:!0,type:"string",size:n.length,byteLength:n.length,sample:n.slice(0,200)}:n;if(typeof n=="object"&&n!==null){const e=Xa(n);if(e<=xc)return n;const t=Object.keys(n);return{[Yt]:!0,type:"Object",size:t.length,byteLength:e,sample:t.slice(0,5).reduce((i,s)=>(i[s]=n[s],i),{})}}return n}function $i(n){return n.map(zy)}function bt(n,e){if(!(typeof n!="object"||n===null))return n[e]}function Ly(n){const e=n[0],t=bt(e,"mapHeader");return t?[{[Yt]:!0,source:"drawRasterMap",mapId:t.id,width:t.mapWidth,height:t.mapHeight,resolution:t.mapResolution,origin:{x:t.originX,y:t.originY},version:t.version??null,mapStable:t.mapStable}]:$i(n)}function Oy(n){const e=n[0];return typeof e!="object"||e===null?$i(n):[{[Yt]:!0,source:"drawMap",id:bt(e,"id"),size:bt(e,"size"),resolution:bt(e,"resolution"),origin:bt(e,"origin"),status:bt(e,"status")}]}function Wy(n){var t,i,s;const e=n[0];return typeof e!="object"||e===null?$i(n):[{[Yt]:!0,source:"parsedRasterMapData",width:bt(e,"width"),height:bt(e,"height"),totalPixels:bt(e,"totalPixels"),obstacleCount:((t=bt(e,"obstacles"))==null?void 0:t.length)??void 0,carpetCount:((i=bt(e,"carpet"))==null?void 0:i.length)??void 0,roomCount:((s=bt(e,"rooms"))==null?void 0:s.size)??void 0}]}function Xr(n){if(n.length===0)return;let e=1/0,t=1/0,i=-1/0,s=-1/0;for(const r of n){const o=bt(r,"x"),a=bt(r,"y");typeof o!="number"||typeof a!="number"||(o<e&&(e=o),a<t&&(t=a),o>i&&(i=o),a>s&&(s=a))}if(Number.isFinite(e))return{minX:e,minY:t,maxX:i,maxY:s}}function Gy(n){const e=n[0],t=bt(e,"pathHeader"),i=bt(e,"pathPoints")??[];return t?[{[Yt]:!0,source:"drawPath",pathId:t.pathId,type:t.type,direction:t.direction,pointCount:i.length,bounds:Xr(i)}]:$i(n)}function Uy(n){const e=n[0],t=bt(e,"pathPoints")??[];return[{[Yt]:!0,source:"drawFullPath",pointCount:t.length,bounds:Xr(t)}]}function Hy(n){const e=Array.isArray(n[0])?n[0]:[];return[{[Yt]:!0,source:"drawIncrementalPath",pointCount:e.length,bounds:Xr(e)}]}const Vy=[{match:"[Map] drawRasterMap",summarize:Ly},{match:"[Map] drawMap",summarize:Oy},{match:"[Map] Parsed Raster Map Data",summarize:Wy},{match:"[Path] drawPath",summarize:Gy},{match:"[Path] Draw Full Path",summarize:Uy},{match:"[Path] Draw Incremental Path",summarize:Hy}];function Ny(n,e){if(e.length===0)return e;for(const t of Vy)if(n.includes(t.match))return t.summarize(e);return $i(e)}const $y="ray-robot-map-sdk",ja=["warn","error"],ds="%c[ray-2d-laser-map-sdk]%c ",Yy="%c[ray-2d-laser-map-sdk:DEBUG]%c ",Xy="background: #2196F3; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",jy="color: #2196F3;",Zy="background: #FF9800; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",qy="color: #FF9800;",Ky="background: #F44336; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",Qy="color: #F44336;",Jy="background: #9C27B0; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",tx="color: #9C27B0;",ex="background: #4CAF50; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",ix="color: #4CAF50;";let At={},Gi=!1;function se(n){if(n)try{return n()}catch{return}}function sx(n){At={...At,...n},Gi=!1}function nx(){return{config:{...At},appLogSinkWarned:Gi}}function rx(n){At=n?{...n.config}:{},Gi=(n==null?void 0:n.appLogSinkWarned)??!1}function ox(){const n=se(At.getLoggerConfig);if(typeof(n==null?void 0:n.enabled)=="boolean")return n.enabled;const e=se(At.isEnabled);if(typeof e=="boolean")return e;const t=se(At.getLegacyEnabled);return typeof t=="boolean"?t:!1}function ax(){const n=se(At.getLoggerConfig);if(typeof(n==null?void 0:n.tag)=="string"&&n.tag.length>0)return n.tag;const e=se(At.getTag);return typeof e=="string"&&e.length>0?e:$y}function us(n,e,t){return{level:n,message:e,data:t,tag:ax(),ts:Date.now()}}function hx(n){const e=se(At.getLoggerConfig);return typeof(e==null?void 0:e.appLogEnabled)=="boolean"?e.appLogEnabled?(e.appLogLevels??ja).includes(n):!1:se(At.isAppLogEnabled)?(se(At.getAppLogLevels)??ja).includes(n):!1}function lx(){const n=se(At.getLoggerConfig);return typeof(n==null?void 0:n.appLogSummary)=="boolean"?n.appLogSummary:!0}function ps(n){if(!hx(n.level))return;const{appLogSink:e}=At;if(typeof e!="function")return;const t=lx()?{...n,data:Ny(n.message,n.data)}:n;try{e(t)}catch(i){if(Gi)return;Gi=!0,console.warn("[ray-robot-map-sdk] app logger bridge failed",i)}}function Si(n,e,t,i,s,r){ox()&&console[n](`${e}${s}`,t,i,...r)}const w={log(n,...e){const t=us("info",n,e);Si("log",ds,Xy,jy,n,e),ps(t)},warn(n,...e){const t=us("warn",n,e);Si("warn",ds,Zy,qy,n,e),ps(t)},error(n,...e){const t=us("error",n,e);Si("error",ds,Ky,Qy,n,e),ps(t)},debug(n,...e){const t=us("debug",n,e);Si("log",Yy,Jy,tx,n,e),ps(t)},success(n,...e){Si("log",ds,ex,ix,n,e)}},et=n=>n,Bt=n=>n,Sc=n=>n.map(e=>({x:Bt(e.x),y:Bt(e.y)})),Ci=(n,e)=>({x:Bt(n),y:Bt(e)}),Za=n=>{if(n.length<=1)return[...n];const e=cx(n),t=e.slice(1).map((s,r)=>({prev:e[r],current:s})),i=new Map;return t.forEach(({prev:s,current:r})=>{dx(s,r).forEach(a=>{const h=`${a.x},${a.y}`;i.has(h)||i.set(h,a)})}),Array.from(i.values())},cx=n=>{if(n.length<=1)return[...n];const e=n[0],t=n[n.length-1];return e.x===t.x&&e.y===t.y?[...n]:[...n,e]},dx=(n,e)=>{const t=[],i=Math.abs(e.x-n.x),s=Math.abs(e.y-n.y),r=n.x<e.x?1:-1,o=n.y<e.y?1:-1;let a=i-s,h=n.x,l=n.y;for(;t.push({x:h,y:l}),!(h===e.x&&l===e.y);){const c=2*a;c>-s&&(a-=s,h+=r),c<i&&(a+=i,l+=o)}return t},gr=(n,e)=>{let t=0,i=n.length-1;for(;t<=i;){const s=Math.floor((t+i)/2),r=n[s];if(r===e)return!0;r<e?t=s+1:i=s-1}return!1},ux=(n,e,t=1,i=2e3)=>{const s=[],r=e.x-n.x,o=e.y-n.y,a=Math.sqrt(r*r+o*o);if(a===0)return[n];const h=Math.min(Math.max(Math.ceil(a/t),2),i);for(let l=0;l<=h;l++){const c=l/h,d={x:n.x+c*r,y:n.y+c*o};s.push(d)}return s},qa=(n,e,t,i,s,r=8)=>{const o=(e+i)/2,a=(t+s)/2,h={x:o,y:a},l=i-e,c=s-t,d=Math.min(r,Math.min(l,c)*.2);return It(h,n)&&ki(h,n)>=d?h:px(n,h,d)},px=(n,e,t)=>{const{minX:i,minY:s,maxX:r,maxY:o}=Ts(n),a=r-i,h=o-s,l=e.x,c=e.y,d=Math.min(.5,Math.min(a,h)*.05),u=[];if(It({x:l,y:c},n)){const S=ki({x:l,y:c},n);u.push({point:{x:l,y:c},distance:S,centerDistance:0})}const p=Math.max(a,h)*.6,g=Math.PI/16;let m=0;const y=1e4;let x=!1;for(let S=d;S<=p&&!x;S+=d){const v=g*(1+S/p);for(let b=0;b<2*Math.PI;b+=v){if(m++,m>y){w.error(`[findBestInnerPoint] Iteration limit reached (${m}). Room size: ${a}x${h}`),x=!0;break}const P=l+S*Math.cos(b),C=c+S*Math.sin(b);if(P>=i&&P<=r&&C>=s&&C<=o){const _={x:P,y:C};if(It(_,n)){const R=ki(_,n),M=q({x:P,y:C},{x:l,y:c});R>=t&&u.push({point:_,distance:R,centerDistance:M})}}}if(u.length>=15)break}if(u.length>0){const S=u.map(v=>({...v,score:v.distance*1.5-v.centerDistance*.5}));return S.sort((v,b)=>b.score-v.score),S[0].point}if(u.length===0){let S={x:l,y:c},v=0;const b=d*2;let P=0;const C=5e3;let _=!1;for(let R=i;R<=r&&!_;R+=b)for(let M=s;M<=o;M+=b){if(P++,P>C){w.error(`[findBestInnerPoint] Coarse search iteration limit reached. Room size: ${a}x${h}`),_=!0;break}const T={x:R,y:M};if(It(T,n)){const A=ki(T,n);A>v&&(v=A,S=T)}}return S}return{x:l,y:c}},ki=(n,e)=>{let t=1/0;for(let i=0,s=e.length-1;i<e.length;s=i++){const r=e[s],o=e[i],a=Gs(n,r,o);t=Math.min(t,a)}return t},Ka=(n,e)=>e.length===1?q(n,e[0]):e.length===2?Gs(n,e[0],e[1]):e.length===4?It(n,e)?0:ki(n,e):(w.warn(`[Distance] Invalid geometry: expected 1, 2 or 4 points, got ${e.length}`),1/0),Gs=(n,e,t)=>{const i=(e.x-t.x)**2+(e.y-t.y)**2;if(i===0)return q(n,e);const s=Math.max(0,Math.min(1,((n.x-e.x)*(t.x-e.x)+(n.y-e.y)*(t.y-e.y))/i)),r=e.x+s*(t.x-e.x),o=e.y+s*(t.y-e.y);return q(n,{x:r,y:o})},fx=(n,e)=>{const t=n.length;if(t<=2||e<=0)return n.slice();const i=new Uint8Array(t);i[0]=1,i[t-1]=1;const s=[[0,t-1]];for(;s.length>0;){const[o,a]=s.pop();let h=0,l=-1;const c=n[o],d=n[a];for(let u=o+1;u<a;u++){const p=Gs(n[u],c,d);p>h&&(h=p,l=u)}l!==-1&&h>e&&(i[l]=1,s.push([o,l]),s.push([l,a]))}const r=[];for(let o=0;o<t;o++)i[o]&&r.push(n[o]);return r},It=(n,e,t=!1)=>{if(e.length<3)return!1;if(t&&gx(n,e))return!0;let i=!1;for(let s=0,r=e.length-1;s<e.length;r=s++){const o=e[s].x,a=e[s].y,h=e[r].x,l=e[r].y;a>n.y!=l>n.y&&n.x<(h-o)*(n.y-a)/(l-a)+o&&(i=!i)}return i},gx=(n,e)=>{if(e.length<2)return!1;for(let t=0;t<e.length;t++){const i=(t+1)%e.length;if(mx(n,e[t],e[i]))return!0}return!1},mx=(n,e,t,i=.5)=>{if(Gs(n,e,t)>i)return!1;const r=Math.min(e.x,t.x)-i,o=Math.max(e.x,t.x)+i,a=Math.min(e.y,t.y)-i,h=Math.max(e.y,t.y)+i;return n.x>=r&&n.x<=o&&n.y>=a&&n.y<=h},Ts=n=>{if(n.length===0)return{minX:0,minY:0,maxX:0,maxY:0};let e=1/0,t=1/0,i=-1/0,s=-1/0;for(const r of n)e=Math.min(e,r.x),t=Math.min(t,r.y),i=Math.max(i,r.x),s=Math.max(s,r.y);return{minX:e,minY:t,maxX:i,maxY:s}},Oe=n=>{const e=n.reduce((t,i)=>({x:t.x+i.x,y:t.y+i.y}),{x:0,y:0});return{x:e.x/n.length,y:e.y/n.length}},yx=(n,e,t)=>{if(n.length<4)return n;const[i,s,,r]=n,o=q(i,s),a=q(i,r),h=o<e||a<e,l=t!=null&&(o>t||a>t);if(!h&&!l)return n;const c=Oe(n),d=Tt(mt(i,s)),u=Tt(mt(i,r)),p=S=>{let v=S;return t!=null&&(v=Math.min(v,t)),Math.max(v,e)},g=p(o),m=p(a),y=g/2,x=m/2;return[Ci(c.x-d.x*y-u.x*x,c.y-d.y*y-u.y*x),Ci(c.x+d.x*y-u.x*x,c.y+d.y*y-u.y*x),Ci(c.x+d.x*y+u.x*x,c.y+d.y*y+u.y*x),Ci(c.x-d.x*y+u.x*x,c.y-d.y*y+u.y*x)]},xx=n=>{if(n.length!==4)return n;const e=Oe(n),t=q(n[0],n[1]),i=q(n[1],n[2]),s=Math.atan2(n[1].y-n[0].y,n[1].x-n[0].x),r=[{x:-t/2,y:-i/2},{x:t/2,y:-i/2},{x:t/2,y:i/2},{x:-t/2,y:i/2}],o=Math.cos(s),a=Math.sin(s);return r.map(h=>Ci(h.x*o-h.y*a+e.x,h.x*a+h.y*o+e.y))},fs=(n,e,t,i=Bt(10),s)=>{if(t===0)return 1;const o=(n.x*e.x+n.y*e.y)/t/t,a=i/t;if(o<=0)return a;let h=o;if(s!=null){const l=s/t;h=Math.min(h,l)}return Math.max(h,a)},q=(n,e)=>{const t=n.x-e.x,i=n.y-e.y;return Math.sqrt(t*t+i*i)},Ui=n=>Math.sqrt(n.x*n.x+n.y*n.y),mt=(n,e)=>({x:e.x-n.x,y:e.y-n.y}),Tt=n=>{const e=Ui(n);return e===0?{x:0,y:0}:{x:n.x/e,y:n.y/e}},vc=(n,e)=>{const t=mt(n,e);return Tt(t)},bc=n=>({x:-n.y,y:n.x}),wc=(n,e)=>{const t=vc(n,e);return bc(t)},Cc=(n,e)=>{const t=Tt(n),i=Tt(e),s={x:(t.x+i.x)/2,y:(t.y+i.y)/2};return Tt(s)},vs=(n,e,t=0)=>{const i=mt(n,e);let s=Math.atan2(i.y,i.x),o=(s+t)%(2*Math.PI);return o>Math.PI&&(o-=2*Math.PI),o<-Math.PI&&(o+=2*Math.PI),(o>Math.PI/2||o<-Math.PI/2)&&(s+=Math.PI),s},_c=(n,e,t)=>{const i=Oe([n,e]),s=wc(n,e);return{x:i.x+s.x*t,y:i.y+s.y*t}},Sx=(n,e,t)=>{const i=Math.cos(t),s=Math.sin(t),r=n.x-e.x,o=n.y-e.y;return{x:r*i-o*s+e.x,y:r*s+o*i+e.y}},vx=(n,e,t)=>n.map(i=>Sx(i,e,t)),bx=(n,e,t)=>{if(q(n,e)===0)return[n,n,n,n];const s=vc(n,e),r=bc(s),o={x:n.x-s.x*t,y:n.y-s.y*t},a={x:e.x+s.x*t,y:e.y+s.y*t};return[{x:o.x+r.x*t,y:o.y+r.y*t},{x:a.x+r.x*t,y:a.y+r.y*t},{x:a.x-r.x*t,y:a.y-r.y*t},{x:o.x-r.x*t,y:o.y-r.y*t}]},wx=(n,e)=>{if(n.length<3)return n;const t=[];for(let i=0;i<n.length;i++){const s=n[i],r=n[(i+1)%n.length],o=n[(i-1+n.length)%n.length],a=mt(s,r);if(Ui(a)===0){t.push(s);continue}const l=Tt(a),c={x:l.y,y:-l.x},d=mt(o,s),u=Ui(d);let p={x:0,y:0};if(u>0){const S=Tt(d);p={x:S.y,y:-S.x}}const g=Cc(p,c),m=p.x*c.x+p.y*c.y,y=1/Math.max(.1,Math.sqrt((1+m)/2)),x={x:s.x+g.x*e*y,y:s.y+g.y*e*y};t.push(x)}return t},Pc=(n,e,t)=>{if(q(n,e)===0)return[];const s=wc(n,e),r=t/2;return[n.x+s.x*r,n.y+s.y*r,e.x+s.x*r,e.y+s.y*r,e.x-s.x*r,e.y-s.y*r,n.x-s.x*r,n.y-s.y*r]},Mc=(n,e,t,i)=>{const s=mt(n,e),r=mt(n,t),o=Cc(s,r),a={x:-o.x,y:-o.y};return{x:n.x+a.x*i,y:n.y+a.y*i}},Cx=(n,e,t,i,s,r)=>{const o=new Set(n),a=_x(n,e),h=Px(a,o,e,t,i,s,r);return h||a},_x=(n,e)=>{let t=0,i=0;for(let s=0;s<n.length;s++){const r=n[s],o=r%e,a=Math.floor(r/e);t+=o,i+=a}return{x:t/n.length,y:i/n.length}},Px=(n,e,t,i,s,r,o)=>{const a={x:i-10,y:n.y},h={x:r+10,y:n.y},l={x:i,y:s},c={x:i,y:o},d={x:r,y:s},u={x:r,y:o},p=Hi(a,h,l,c),g=Hi(a,h,d,u);if(!p||!g)return null;const m=[],y=Math.max(i,Math.min(p.x,g.x)),x=Math.min(r,Math.max(p.x,g.x)),S=Math.round(n.y);for(let v=Math.round(y);v<=Math.round(x);v++){const b=S*t+v;e.has(b)&&m.push({x:v,y:S})}if(m.length>=2){const v=Mx(m),b={x:(v.min.x+v.max.x)/2,y:(v.min.y+v.max.y)/2},P=Math.round(b.y)*t+Math.round(b.x);if(e.has(P))return b}return null},Hi=(n,e,t,i)=>{const s=(n.x-t.x)*(e.y-t.y)-(n.y-t.y)*(e.x-t.x),r=(n.x-i.x)*(e.y-i.y)-(n.y-i.y)*(e.x-i.x);if(s*r>=0)return null;const o=(t.x-n.x)*(i.y-n.y)-(t.y-n.y)*(i.x-n.x),a=o+s-r;if(o*a>=0)return null;const h=o/(r-s),l=h*(e.x-n.x),c=h*(e.y-n.y);return{x:n.x+l,y:n.y+c}},Mx=n=>{if(!n||n.length===0)return{min:{x:0,y:0},max:{x:0,y:0}};let e=n[0],t=n[0];const i=s=>s.x-s.y;for(let s=1;s<n.length;s++){const r=n[s];i(r)<i(e)&&(e=r),i(r)>i(t)&&(t=r)}return{min:e,max:t}},Fn=(n,e)=>({minX:Math.min(n.minX,e.minX),minY:Math.min(n.minY,e.minY),maxX:Math.max(n.maxX,e.maxX),maxY:Math.max(n.maxY,e.maxY)}),Ax=n=>{if(n.length===0)return{x:0,y:0,width:0,height:0};let e=n[0].x,t=n[0].y,i=n[0].x+n[0].width,s=n[0].y+n[0].height;return n.forEach(r=>{e=Math.min(e,r.x),t=Math.min(t,r.y),i=Math.max(i,r.x+r.width),s=Math.max(s,r.y+r.height)}),{x:e,y:t,width:i-e,height:s-t}},Tx=(n,e,t)=>{let i=1/0,s=1/0,r=-1/0,o=-1/0;for(let a=0;a<n.obstacles.length;a++){const h=n.obstacles[a],l=h%e,c=Math.floor(h/e);i=Math.min(i,l),s=Math.min(s,c),r=Math.max(r,l),o=Math.max(o,c)}return n.rooms.forEach(a=>{for(let h=0;h<a.length;h++){const l=a[h],c=l%e,d=Math.floor(l/e);i=Math.min(i,c),s=Math.min(s,d),r=Math.max(r,c),o=Math.max(o,d)}}),i===1/0?{minX:0,minY:0,maxX:e,maxY:t}:{minX:Math.max(0,i),minY:Math.max(0,s),maxX:Math.min(e,r),maxY:Math.min(t,o)}},Rx=(n,e,t,i,s,r)=>{const o=t+s,a=i+r,h=Math.min(n.x,e.x),l=Math.max(n.x,e.x),c=Math.min(n.y,e.y),d=Math.max(n.y,e.y);if(l<t||h>o||d<i||c>a)return!1;if(Qa(n,t,i,s,r)||Qa(e,t,i,s,r))return!0;const u=[{x:t,y:i},{x:o,y:i},{x:o,y:a},{x:t,y:a}];for(let p=0;p<4;p++){const g=u[p],m=u[(p+1)%4];if(Hi(n,e,g,m))return!0}return!1},Qa=(n,e,t,i,s)=>n.x>=e&&n.x<=e+i&&n.y>=t&&n.y<=t+s,kx=(n,e,t,i)=>{const s=t/2;return i==="horizontal"?[{x:n-s,y:e},{x:n+s,y:e}]:[{x:n,y:e-s},{x:n,y:e+s}]},Ix=(n,e,t)=>{const i={x:e.x-n.x,y:e.y-n.y},s=Math.sqrt(i.x*i.x+i.y*i.y);if(s===0)return[n,e];const r={x:i.x/s,y:i.y/s},o={x:n.x-r.x*t,y:n.y-r.y*t},a={x:e.x+r.x*t,y:e.y+r.y*t};return[o,a]},Ja=(n,e,t)=>{const i=Ts(n),s=Ts(e),r=Math.max(0,Math.max(i.minX,s.minX)-Math.min(i.maxX,s.maxX)),o=Math.max(0,Math.max(i.minY,s.minY)-Math.min(i.maxY,s.maxY));if(r>t||o>t)return!1;let[a,h]=[n,e];e.length>n.length&&([a,h]=[e,n]);const l=Math.max(1,Math.floor(t)),c=new Map;for(const u of a){const p=Math.floor(u.x/l),g=Math.floor(u.y/l),m=`${p},${g}`;c.has(m)||c.set(m,[]),c.get(m).push(u)}const d=t*t;for(const u of h){const p=Math.floor(u.x/l),g=Math.floor(u.y/l);for(let m=-1;m<=1;m++)for(let y=-1;y<=1;y++){const x=`${p+m},${g+y}`,S=c.get(x);if(S)for(const v of S){const b=u.x-v.x,P=u.y-v.y;if(b*b+P*P<=d)return!0}}}return!1},th=(n,e,t,i)=>{let[s,r]=[n,e];e.length>n.length&&([s,r]=[e,n]);const o=new Set(s),a=i*i;for(let h=0;h<r.length;h++){const l=r[h],c=l%t,d=Math.floor(l/t);for(let u=-i;u<=i;u++)for(let p=-i;p<=i;p++){const g=c+u,y=(d+p)*t+g;if(o.has(y)&&u*u+p*p<=a)return!0}}return!1},eh=(n,e)=>{if(n<=1)return!0;if(e.length===0)return!1;const t=Array.from({length:n},(a,h)=>h),i=Array(n).fill(0),s=a=>(t[a]!==a&&(t[a]=s(t[a])),t[a]),r=(a,h)=>{const l=s(a),c=s(h);l!==c&&(i[l]<i[c]?t[l]=c:i[l]>i[c]?t[c]=l:(t[c]=l,i[l]++))};for(const[a,h]of e)r(a,h);const o=s(0);for(let a=1;a<n;a++)if(s(a)!==o)return!1;return!0},Ex=(n,e,t,i="priority")=>{const s=new Map;if(n.length===0)return s;if(n.length===1)return s.set(n[0].id,0),s;const r=new Map;for(let l=0;l<n.length;l++){const c=n[l];r.has(c.id)||r.set(c.id,new Set);for(let d=l+1;d<n.length;d++){const u=n[d];e(c,u)&&(r.get(c.id).add(u.id),r.has(u.id)||r.set(u.id,new Set),r.get(u.id).add(c.id))}}const o=new Array(t).fill(0),a=[...n].sort((l,c)=>{const d=(r.get(l.id)||new Set).size,u=(r.get(c.id)||new Set).size,p=n.indexOf(l),g=n.indexOf(c),m=-p*.5+d*.5;return-g*.5+u*.5-m}),h=l=>{const c=r.get(l)||new Set,d=new Map;for(const u of c){const p=s.get(u);p!==void 0&&(d.has(p)||d.set(p,[]),d.get(p).push(u))}for(const[u,p]of d){if(p.length!==1)continue;const g=p[0],m=r.get(g)||new Set,y=new Set;for(const x of m){if(x===l)continue;const S=s.get(x);S!==void 0&&y.add(S)}for(let x=0;x<t;x++)if(x!==u&&!y.has(x))return o[u]--,o[x]++,s.set(g,x),u}return-1};for(const l of a){const c=r.get(l.id)||new Set,d=new Set;for(const p of c){const g=s.get(p);g!==void 0&&d.add(g)}let u=-1;if(i==="priority"){let p=-1,g=-1/0;for(let m=0;m<t;m++)if(!d.has(m)){const y=t-m,x=o[m]*.7,S=y-x;(S>g||S===g&&m<p)&&(g=S,p=m)}if(u=p,u===-1&&(u=h(l.id)),u===-1){w.warn(`[FourColor] Room ${l.id}: recolor failed, falling back to least-conflict color`);let m=1/0;for(let y=0;y<t;y++){let x=0;for(const S of c)s.get(S)===y&&x++;(x<m||x===m&&y<u)&&(m=x,u=y)}}o[u]++}else{const p=[];for(let g=0;g<t;g++)d.has(g)||p.push(g);if(p.length===0){if(u=h(l.id),u===-1){w.warn(`[FourColor] Room ${l.id}: recolor failed, falling back to least-conflict color`);let g=1/0,m=0;for(let y=0;y<t;y++)(o[y]<g||o[y]===g&&y<m)&&(g=o[y],m=y);u=m}}else{u=p[0];let g=o[u];for(const m of p)(o[m]<g||o[m]===g&&m<u)&&(u=m,g=o[m])}o[u]++}s.set(l.id,u)}return s},Dx=Symbol(),ih=Object.getPrototypeOf,mr=new WeakMap,Fx=n=>n&&(mr.has(n)?mr.get(n):ih(n)===Object.prototype||ih(n)===Array.prototype),Bx=n=>Fx(n)&&n[Dx]||null,sh=(n,e=!0)=>{mr.set(n,e)},Rs={},jr=n=>typeof n=="object"&&n!==null,zx=n=>jr(n)&&!Zr.has(n)&&(Array.isArray(n)||!(Symbol.iterator in n))&&!(n instanceof WeakMap)&&!(n instanceof WeakSet)&&!(n instanceof Error)&&!(n instanceof Number)&&!(n instanceof Date)&&!(n instanceof String)&&!(n instanceof RegExp)&&!(n instanceof ArrayBuffer)&&!(n instanceof Promise),Ac=(n,e)=>{const t=nh.get(n);if((t==null?void 0:t[0])===e)return t[1];const i=Array.isArray(n)?[]:Object.create(Object.getPrototypeOf(n));return sh(i,!0),nh.set(n,[e,i]),Reflect.ownKeys(n).forEach(s=>{if(Object.getOwnPropertyDescriptor(i,s))return;const r=Reflect.get(n,s),{enumerable:o}=Reflect.getOwnPropertyDescriptor(n,s),a={value:r,enumerable:o,configurable:!0};if(Zr.has(r))sh(r,!1);else if(Le.has(r)){const[h,l]=Le.get(r);a.value=Ac(h,l())}Object.defineProperty(i,s,a)}),Object.preventExtensions(i)},Lx=(n,e,t,i)=>({deleteProperty(s,r){const o=Reflect.get(s,r);t(r);const a=Reflect.deleteProperty(s,r);return a&&i(["delete",[r],o]),a},set(s,r,o,a){const h=!n()&&Reflect.has(s,r),l=Reflect.get(s,r,a);if(h&&(rh(l,o)||ks.has(o)&&rh(l,ks.get(o))))return!0;t(r),jr(o)&&(o=Bx(o)||o);const c=!Le.has(o)&&Wx(o)?yr(o):o;return e(r,c),Reflect.set(s,r,c,a),i(["set",[r],o,l]),!0}}),Le=new WeakMap,Zr=new WeakSet,nh=new WeakMap,Bn=[1],ks=new WeakMap;let rh=Object.is,Ox=(n,e)=>new Proxy(n,e),Wx=zx,Gx=Ac,Ux=Lx;function yr(n={}){if(!jr(n))throw new Error("object required");const e=ks.get(n);if(e)return e;let t=Bn[0];const i=new Set,s=(y,x=++Bn[0])=>{t!==x&&(r=t=x,i.forEach(S=>S(y,x)))};let r=t;const o=(y=Bn[0])=>(r!==y&&(r=y,h.forEach(([x])=>{const S=x[1](y);S>t&&(t=S)})),t),a=y=>(x,S)=>{const v=[...x];v[1]=[y,...v[1]],s(v,S)},h=new Map,l=(y,x)=>{const S=!Zr.has(x)&&Le.get(x);if(S){if((Rs?"production":void 0)!=="production"&&h.has(y))throw new Error("prop listener already exists");if(i.size){const v=S[2](a(y));h.set(y,[S,v])}else h.set(y,[S])}},c=y=>{var x;const S=h.get(y);S&&(h.delete(y),(x=S[1])==null||x.call(S))},d=y=>(i.add(y),i.size===1&&h.forEach(([S,v],b)=>{if((Rs?"production":void 0)!=="production"&&v)throw new Error("remove already exists");const P=S[2](a(b));h.set(b,[S,P])}),()=>{i.delete(y),i.size===0&&h.forEach(([S,v],b)=>{v&&(v(),h.set(b,[S]))})});let u=!0;const p=Ux(()=>u,l,c,s),g=Ox(n,p);ks.set(n,g);const m=[n,o,d];return Le.set(g,m),Reflect.ownKeys(n).forEach(y=>{const x=Object.getOwnPropertyDescriptor(n,y);"value"in x&&x.writable&&(g[y]=n[y])}),u=!1,g}function Us(n,e,t){const i=Le.get(n);(Rs?"production":void 0)!=="production"&&!i&&console.warn("Please use proxy object");let s;const r=[],o=i[2];let a=!1;const l=o(c=>{r.push(c),s||(s=Promise.resolve().then(()=>{s=void 0,a&&e(r.splice(0))}))});return a=!0,()=>{a=!1,l()}}function Hx(n){const e=Le.get(n);(Rs?"production":void 0)!=="production"&&!e&&console.warn("Please use proxy object");const[t,i]=e;return Gx(t,i())}function W(n,e,t,i){let s=n[e];return Us(n,()=>{const r=n[e];Object.is(s,r)||t(s=r)})}class Vx extends L{constructor(t){super();f(this,"dragStart",null);f(this,"initialTouchDistance",null);f(this,"initialScale",null);f(this,"activeTouches",new Map);f(this,"firstTouchId",null);f(this,"secondTouchId",null);f(this,"taintedPointers",new Set);f(this,"zoomFactor",.8);f(this,"scaleMin",.2);f(this,"scaleMax",5);f(this,"originalPosition",{x:0,y:0});f(this,"targetPosition",{x:0,y:0});f(this,"centerPosition",{x:0,y:0});f(this,"originalScale",{x:1,y:1});f(this,"targetScale",{x:1,y:1});f(this,"defaultScale",{x:1,y:1});f(this,"transitionDuration",500);f(this,"transitionStartTime",null);f(this,"initialPinchCenter",null);f(this,"isGestureValid",!0);f(this,"lastTapTime",0);f(this,"doubleTapDelay",300);f(this,"doubleTapZoomFactor",1.5);f(this,"lastTapPosition",null);f(this,"tapDistanceThreshold",20);f(this,"tapDetectionEnabled",!0);f(this,"mapClickStartPosition",null);f(this,"mapClickStartTime",0);f(this,"mapClickTimeThreshold",300);f(this,"mapClickMoveThreshold",10);f(this,"shouldSuppressMapClick",!1);f(this,"isGestureHijacked",!1);f(this,"hijackedPointerId",null);f(this,"isHijackPaused",!1);f(this,"activeGestureSession",null);f(this,"interactionGraphics");f(this,"viewportBounds");f(this,"boundResetAnimation");f(this,"debouncedStopWheelRender");f(this,"debouncedLogWheelScale");f(this,"interactionState",{isInteracting:!1,isAnimating:!1,interactionTimer:null,renderReasons:new Set});f(this,"throttledAntiScale");f(this,"unsubscribeEnableInteraction",null);f(this,"suppressMapClick",()=>{this.shouldSuppressMapClick=!0});f(this,"handleGestureHijacked",t=>{var r,o;this.isGestureHijacked=!0,this.hijackedPointerId=t.pointerId,this.isHijackPaused=!1,this.clearTouches();const i=t.global.x-this.viewportBounds.x,s=t.global.y-this.viewportBounds.y;this.activeTouches.set(t.pointerId,{x:i,y:s}),this.firstTouchId=t.pointerId,this.dragStart={x:i,y:s},(o=(r=this.appService.events)==null?void 0:r.onGestureStart)==null||o.call(r)});this.appService=t;const i=t.getApp();this.viewportBounds=i.getViewportBounds(),this.eventMode="static",this.unsubscribeEnableInteraction=W(t.runtime,"enableInteraction",s=>{this.updateInteractionMode(s)}),this.updateInteractionMode(t.runtimeSnapshot.enableInteraction),this.interactionGraphics=new U,this.interactionGraphics.rect(0,0,this.viewportBounds.width,this.viewportBounds.height).fill({color:"#ffffff",alpha:0}),this.addChild(this.interactionGraphics),this.scaleMax=i.scaleMax,this.scaleMin=i.scaleMin,this.centerPosition={x:Math.round(this.viewportBounds.width/2),y:Math.round(this.viewportBounds.height/2)},this.originalPosition={x:Math.round(this.viewportBounds.width/2),y:Math.round(this.viewportBounds.height/2)},this.targetPosition={x:Math.round(this.viewportBounds.width/2),y:Math.round(this.viewportBounds.height/2)},this.throttledAntiScale=_t(s=>{this.appService.emitter.emit("antiScale",s)},16,{leading:!0,trailing:!0}),this.boundResetAnimation=this.resetAnimation.bind(this),this.debouncedStopWheelRender=Vn(()=>{i.stopRender("wheel")},300),this.debouncedLogWheelScale=Vn(s=>{w.debug("[Interaction] 滚轮缩放完成 - Scale:",s.toFixed(3))},500),this.setupInteraction()}updateInteractionMode(t){this.eventMode=t?"static":"none",w.debug(`[Interaction] 交互模式已更新: ${t?"启用":"禁用"}`)}setupInteraction(){this.on("pointerdown",t=>this.onPointerDown(t)),this.on("pointerup",t=>this.onPointerUp(t)),this.on("pointerupoutside",t=>this.onPointerUp(t)),this.on("pointermove",t=>this.onPointerMove(t)),this.on("wheel",t=>this.onWheel(t)),document.addEventListener("pointercancel",t=>{w.debug("[Interaction] Received global pointercancel"),this.handleGlobalCancel(t)})}handleGlobalCancel(t){const i=this.appService;if(this.isGestureHijacked){w.debug("[Interaction] 系统取消或移出视口,强制结束劫持手势");const s=i.getApp(),r=new Ia(s.renderer.events);r.pointerId=t.pointerId,this.dispatchGestureEnd(r),this.exitGestureHijacked()}this.clearTouches()}resetPan(t){const i=this.appService,s=i.getApp(),r=i.appContainer;this.transitionStartTime!==null&&(s.ticker.remove(this.boundResetAnimation),this.transitionStartTime=null);const o=this.centerPosition.x-t.x*r.scale.x,a=this.centerPosition.y-t.y*r.scale.y;this.originalPosition={x:r.x,y:r.y},this.targetPosition={x:o,y:a},this.originalScale={x:r.scale.x,y:r.scale.y},this.targetScale={x:r.scale.x,y:r.scale.y};const h=Math.sqrt((r.x-o)**2+(r.y-a)**2),c=(d=>Math.pow(Math.min(1,d/1e3),.5))(h);this.transitionDuration=500+1e3*Math.min(1,Math.pow(c,2)),this.transitionStartTime=s.ticker.lastTime,s.ticker.add(this.boundResetAnimation)}setPanZoom({targetPosition:t,targetScale:i,setCenter:s=!1,setScale:r=!1}={},o=!0){const a=this.appService,h=a.getApp(),l=a.appContainer;if(s&&t&&(this.centerPosition={x:t.x,y:t.y},w.debug("[Interaction] Set center position:",this.centerPosition)),r&&i&&(this.defaultScale={x:i.x,y:i.y},w.debug("[Interaction] Set scale:",this.defaultScale)),this.originalPosition={x:l.x,y:l.y},this.originalScale={x:l.scale.x,y:l.scale.y},t?this.targetPosition=t:this.targetPosition={x:this.centerPosition.x,y:this.centerPosition.y},i?this.targetScale=i:this.targetScale=this.defaultScale,!o){l.position.set(this.targetPosition.x,this.targetPosition.y),l.scale.set(this.targetScale.x,this.targetScale.y),this.antiScale(this.targetScale.x),this.transitionStartTime!==null&&(h.ticker.remove(this.boundResetAnimation),this.transitionStartTime=null),w.debug("[Interaction] 直接设置缩放完成 - Scale:",this.targetScale.x.toFixed(3));return}const c=Math.sqrt((l.x-this.targetPosition.x)**2+(l.y-this.targetPosition.y)**2),u=(y=>Math.pow(Math.min(1,y/1e3),.5))(c),g=((y,x)=>Math.pow(Math.min(1,Math.abs(y-x)/Math.abs(.2-1)),.5))(l.scale.x,this.targetScale.x),m=u*.8+g*.2;this.transitionDuration=500+1e3*Math.min(1,Math.pow(m,2)),this.transitionStartTime!==null&&(h.ticker.remove(this.boundResetAnimation),this.interactionState.isAnimating=!1,h.stopRender("animation")),this.interactionState.isAnimating=!0,h.requestRender("animation",!0),this.transitionStartTime=h.ticker.lastTime,h.ticker.add(this.boundResetAnimation)}clearTouches(){var s,r;const i=this.appService.getApp();this.activeTouches.clear(),this.firstTouchId=null,this.secondTouchId=null,this.dragStart=null,this.initialTouchDistance=null,this.initialScale=null,this.initialPinchCenter=null,this.isGestureValid=!0,this.taintedPointers.clear(),this.transitionStartTime!==null&&(i.ticker.remove(this.boundResetAnimation),this.transitionStartTime=null),this.interactionState.isInteracting&&(this.interactionState.isInteracting=!1,(r=(s=this.appService.events)==null?void 0:s.onGestureEnd)==null||r.call(s)),i.stopRender("interaction")}checkEventListeners(){return{wheel:this.listenerCount("wheel"),pointerdown:this.listenerCount("pointerdown"),pointerup:this.listenerCount("pointerup"),pointerupoutside:this.listenerCount("pointerupoutside"),pointermove:this.listenerCount("pointermove")}}destroy(){this.checkEventListeners(),this.interactionState.interactionTimer&&clearTimeout(this.interactionState.interactionTimer),this.interactionState.renderReasons.clear(),this.interactionState.isInteracting=!1,this.interactionState.isAnimating=!1,this.debouncedStopWheelRender.cancel(),this.debouncedLogWheelScale.cancel(),this.unsubscribeEnableInteraction&&(this.unsubscribeEnableInteraction(),this.unsubscribeEnableInteraction=null),this.releaseGestureSession(),super.destroy()}hijack(t){if(this.activeGestureSession)throw new Error("[Interaction] A gesture session is already live; hijack is exclusive");this.handleGestureHijacked(t);const i={moveCallbacks:[],endCallbacks:[],ended:!1,session:null},s={onMove:r=>{i.ended||i.moveCallbacks.push(r)},onEnd:r=>{i.ended||i.endCallbacks.push(r)},cancel:()=>{this.activeGestureSession!==i||i.ended||(this.dispatchGestureEnd(t),this.exitGestureHijacked())}};return i.session=s,this.activeGestureSession=i,s}dispatchGestureMove(t){const i=this.activeGestureSession;if(!(!i||i.ended))for(const s of i.moveCallbacks)s(t)}dispatchGestureEnd(t){const i=this.activeGestureSession;if(!i||i.ended)return;i.ended=!0;const s=i.endCallbacks;this.activeGestureSession=null;for(const r of s)r(t)}releaseGestureSession(){this.activeGestureSession&&(this.activeGestureSession.ended=!0,this.activeGestureSession=null)}exitGestureHijacked(){var i,s;const t=this.appService;this.hijackedPointerId!==null&&!this.isHijackPaused&&(this.activeTouches.delete(this.hijackedPointerId),this.firstTouchId===this.hijackedPointerId&&(this.firstTouchId=null,this.dragStart=null),this.secondTouchId===this.hijackedPointerId&&(this.secondTouchId=null)),this.isGestureHijacked=!1,this.hijackedPointerId=null,this.isHijackPaused=!1,(s=(i=t.events)==null?void 0:i.onGestureEnd)==null||s.call(i)}forceEndGesture(){if(this.isGestureHijacked){w.debug("[Interaction] 强制结束劫持手势");const t=this.appService.getApp(),i=new Ia(t.renderer.events);i.pointerId=this.hijackedPointerId,this.dispatchGestureEnd(i),this.exitGestureHijacked()}this.clearTouches()}pauseGestureHijack(){this.isHijackPaused=!0}resumeGestureHijack(){this.isHijackPaused=!1}antiScale(t){this.throttledAntiScale(t)}resetAnimation(){const t=this.appService,i=t.getApp(),s=t.appContainer;if(this.transitionStartTime===null)return;const{targetPosition:r,targetScale:o}=this,a=i.ticker.lastTime,h=Math.min(1,(a-this.transitionStartTime)/this.transitionDuration);if(h>=1)s.position.set(r.x,r.y),s.scale.set(o.x,o.y),this.antiScale(o.x),i.ticker.remove(this.boundResetAnimation),this.transitionStartTime=null,this.interactionState.isAnimating=!1,i.stopRender("animation"),w.debug("[Interaction] 动画缩放完成 - Scale:",s.scale.x.toFixed(3));else{const l=Ey(h),c=this.originalPosition.x+(r.x-this.originalPosition.x)*l,d=this.originalPosition.y+(r.y-this.originalPosition.y)*l,u=this.originalScale.x+(o.x-this.originalScale.x)*l,p=this.originalScale.y+(o.y-this.originalScale.y)*l;s.position.set(c,d),s.scale.set(u,p),this.antiScale(u)}}onWheel(t){const i=this.appService;if(this.isGestureHijacked){w.warn("⚠️ [onWheel] 被手势劫持阻止执行",{isGestureHijacked:this.isGestureHijacked,hijackedPointerId:this.hijackedPointerId,isHijackPaused:this.isHijackPaused});return}i.getApp().requestRender("wheel",!0),this.debouncedStopWheelRender();const{scaleMin:s,scaleMax:r}=this,o=i.appContainer;t.preventDefault();const a=t.global.x-this.viewportBounds.x,h=t.global.y-this.viewportBounds.y,l=(a-o.x)/o.scale.x,c=(h-o.y)/o.scale.y,d=t.deltaY>0?.95:1.05;let u=o.scale.x*d,p=o.scale.y*d;if(u=Math.max(s,Math.min(r,u)),p=Math.max(s,Math.min(r,p)),!(u!==o.scale.x||p!==o.scale.y))return;const m=a-l*u,y=h-c*p;try{o.scale.set(u,p),o.position.set(m,y),this.antiScale(u),this.debouncedLogWheelScale(u)}catch(x){w.error("❌ [onWheel] 应用缩放时发生错误:",x)}}onPointerDown(t){var l,c;const i=this.appService;w.debug("[Interaction] onPointerDown",{pointerId:t.pointerId,activeTouches:this.activeTouches.size,isInteracting:this.interactionState.isInteracting,isGestureValid:this.isGestureValid,isGestureHijacked:this.isGestureHijacked,hijackedPointerId:this.hijackedPointerId,isHijackPaused:this.isHijackPaused,taintedPointers:Array.from(this.taintedPointers),firstTouchId:this.firstTouchId,hasPinchState:this.initialTouchDistance!==null}),this.interactionState.isInteracting||(this.interactionState.isInteracting=!0,i.getApp().requestRender("interaction",!0),(c=(l=i.events)==null?void 0:l.onGestureStart)==null||c.call(l)),this.isGestureHijacked&&t.pointerId!==this.hijackedPointerId&&!this.isHijackPaused&&this.pauseGestureHijack();const s=i.getApp(),r=i.appContainer;this.transitionStartTime!==null&&(s.ticker.remove(this.boundResetAnimation),this.transitionStartTime=null),this.activeTouches.size===0&&this.taintedPointers.size>0&&(w.debug("[Interaction] 清除污染指针列表,准备新手势",Array.from(this.taintedPointers)),this.taintedPointers.clear()),this.activeTouches.size===0&&(this.isGestureValid=!0,this.initialTouchDistance=null,this.initialScale=null,this.initialPinchCenter=null,this.dragStart=null,this.firstTouchId=null,this.secondTouchId=null),this.activeTouches.has(t.pointerId)&&this.activeTouches.size===1&&(this.isGestureValid=!0);const o=t.global.x-this.viewportBounds.x,a=t.global.y-this.viewportBounds.y;this.activeTouches.set(t.pointerId,{x:o,y:a});const h=this.activeTouches.size-this.taintedPointers.size;if(this.taintedPointers.size>0){w.debug("[Interaction] 存在污染指针,阻止多点触摸手势",Array.from(this.taintedPointers)),h===1&&!this.taintedPointers.has(t.pointerId)&&(this.firstTouchId=t.pointerId,this.dragStart={x:o,y:a});return}if(this.activeTouches.size===1)this.firstTouchId=t.pointerId,this.dragStart={x:o,y:a},this.mapClickStartPosition={x:o,y:a},this.mapClickStartTime=performance.now();else if(this.activeTouches.size===2){const d=Array.from(this.activeTouches.keys());this.secondTouchId=d.find(u=>u!==this.firstTouchId)||t.pointerId,this.setInitialScaleAndDistance(r),this.tapDetectionEnabled=!1}}onPointerUp(t){var r,o;const i=this.appService;if(this.taintedPointers.has(t.pointerId)&&(w.debug("[Interaction] 移除污染指针",t.pointerId),this.taintedPointers.delete(t.pointerId)),this.isGestureHijacked)if(t.pointerId===this.hijackedPointerId){this.dispatchGestureEnd(t),this.exitGestureHijacked();return}else this.isHijackPaused;if(!this.activeTouches.has(t.pointerId))return;const s=this.initialTouchDistance!==null&&this.initialScale!==null;if(this.activeTouches.delete(t.pointerId),w.debug(`[Interaction] onPointerUp, remaining touches: ${this.activeTouches.size}`),s&&this.activeTouches.size===1){this.isGestureValid=!1;const a=Array.from(this.activeTouches.keys());setTimeout(()=>{var h,l;!this.isGestureValid&&this.activeTouches.size>0&&(w.debug("[Interaction] 100ms 缓冲结束,检测到真正的幽灵指针,标记为污染并清理",a),a.forEach(c=>{this.activeTouches.has(c)&&(this.taintedPointers.add(c),this.activeTouches.delete(c),this.firstTouchId===c&&(this.firstTouchId=null,this.dragStart=null),this.secondTouchId===c&&(this.secondTouchId=null))}),this.activeTouches.size===0&&this.interactionState.isInteracting&&(w.debug("[Interaction] 清理幽灵指针后所有触摸点已释放,结束手势"),this.interactionState.isInteracting=!1,i.getApp().stopRender("interaction"),(l=(h=i.events)==null?void 0:h.onGestureEnd)==null||l.call(h)))},100),this.initialTouchDistance=null,this.initialScale=null,this.initialPinchCenter=null}t.pointerId===this.firstTouchId?(this.firstTouchId=null,this.dragStart=null,this.activeTouches.size===0&&this.tapDetectionEnabled&&this.detectDoubleTap(t),this.activeTouches.size===0&&!s&&this.detectMapClick(t)):t.pointerId===this.secondTouchId&&(this.secondTouchId=null),this.isGestureHijacked&&this.isHijackPaused&&this.activeTouches.size===1&&Array.from(this.activeTouches.keys())[0]===this.hijackedPointerId&&this.resumeGestureHijack(),this.activeTouches.size===0&&(this.isGestureValid=!0,this.initialTouchDistance=null,this.initialScale=null,this.initialPinchCenter=null,this.firstTouchId=null,this.secondTouchId=null,this.dragStart=null,this.tapDetectionEnabled=!0,w.debug("[Interaction] onPointerUp all-released",{pointerId:t.pointerId,isInteracting:this.interactionState.isInteracting,isGestureHijacked:this.isGestureHijacked,isGestureValid:this.isGestureValid,taintedPointers:this.taintedPointers.size}),this.interactionState.isInteracting&&(this.interactionState.isInteracting=!1,i.getApp().stopRender("interaction"),(o=(r=i.events)==null?void 0:r.onGestureEnd)==null||o.call(r)))}detectDoubleTap(t){const i=this.appService,{interactionConfig:s}=i;if(!s.enableDoubleTapZoom)return;const r=performance.now(),o={x:t.global.x-this.viewportBounds.x,y:t.global.y-this.viewportBounds.y};r-this.lastTapTime<this.doubleTapDelay&&this.lastTapPosition&&q(o,this.lastTapPosition)<this.tapDistanceThreshold?(this.handleDoubleTap(o),this.lastTapTime=0,this.lastTapPosition=null):(this.lastTapTime=r,this.lastTapPosition=o)}detectMapClick(t){var h;const i=this.appService;if(!i.runtimeSnapshot.enableMapClickCapture||!((h=i.events)!=null&&h.onClickMap)||!this.mapClickStartPosition)return;const r=performance.now()-this.mapClickStartTime,o={x:t.global.x-this.viewportBounds.x,y:t.global.y-this.viewportBounds.y},a=q(this.mapClickStartPosition,o);if(r<=this.mapClickTimeThreshold&&a<=this.mapClickMoveThreshold&&!this.shouldSuppressMapClick){const l=i.appContainer,c=i.mapState,d=(o.x-l.x)/l.scale.x,u=(o.y-l.y)/l.scale.y,p={x:d-((c==null?void 0:c.origin.x)||0),y:u-((c==null?void 0:c.origin.y)||0)};w.debug("[Interaction] 地图点击捕获",{screenPosition:o,containerPosition:{x:d,y:u},origin:c==null?void 0:c.origin,mapPosition:p,clickDuration:r,moveDistance:a}),i.events.onClickMap(p)}this.mapClickStartPosition=null,this.mapClickStartTime=0,this.shouldSuppressMapClick=!1}handleDoubleTap(t){const i=this.appService,s=i.getApp(),r=i.appContainer,{scaleMin:o,scaleMax:a,doubleTapZoomFactor:h}=this,l=t.x,c=t.y,d=(l-r.x)/r.scale.x,u=(c-r.y)/r.scale.y;let p=r.scale.x*h,g=r.scale.y*h;p=Math.max(o,Math.min(a,p)),g=Math.max(o,Math.min(a,g)),this.originalPosition={x:r.x,y:r.y},this.originalScale={x:r.scale.x,y:r.scale.y};const m=l-d*p,y=c-u*g;this.targetPosition={x:m,y},this.targetScale={x:p,y:g},this.interactionState.isAnimating=!0,s.requestRender("animation",!0),this.transitionDuration=300,this.transitionStartTime=s.ticker.lastTime,s.ticker.add(this.boundResetAnimation)}onPointerMove(t){if(this.isGestureHijacked&&!this.isHijackPaused)if(t.pointerId===this.hijackedPointerId){const r=t.global.x-this.viewportBounds.x,o=t.global.y-this.viewportBounds.y;this.activeTouches.set(t.pointerId,{x:r,y:o}),this.dispatchGestureMove(t);return}else{w.debug("[Interaction] onPointerMove ignored: gesture hijacked",{pointerId:t.pointerId,hijackedPointerId:this.hijackedPointerId,isHijackPaused:this.isHijackPaused});return}if(!this.activeTouches.has(t.pointerId)||!this.isGestureValid){w.debug("[Interaction] onPointerMove ignored: not in activeTouches or invalid",{pointerId:t.pointerId,inActiveTouches:this.activeTouches.has(t.pointerId),isGestureValid:this.isGestureValid,activeTouches:this.activeTouches.size});return}if(this.taintedPointers.size>0&&(this.initialTouchDistance!==null||this.initialScale!==null)){w.debug("[Interaction] 存在污染指针,阻止多点触摸手势移动");return}const i=t.global.x-this.viewportBounds.x,s=t.global.y-this.viewportBounds.y;this.activeTouches.set(t.pointerId,{x:i,y:s}),this.activeTouches.size===2&&this.initialTouchDistance!==null&&this.initialScale!==null&&this.applyPinchZoom(),this.activeTouches.size===1&&(this.initialTouchDistance!==null||this.initialScale!==null)&&(this.initialTouchDistance=null,this.initialScale=null,this.initialPinchCenter=null,this.secondTouchId=null),this.activeTouches.size===1&&t.pointerId===this.firstTouchId&&this.dragStart!==null&&!this.taintedPointers.has(t.pointerId)?this.applyPan(t):this.activeTouches.size===1&&w.debug("[Interaction] onPointerMove single-touch pan skipped",{pointerId:t.pointerId,isFirstChild:t.pointerId===this.firstTouchId,hasDragStart:this.dragStart!==null,isTainted:this.taintedPointers.has(t.pointerId)})}applyPan(t){const i=this.appService,s=this.activeTouches.get(t.pointerId),r=i.appContainer,{x:o,y:a}=this.dragStart,h=s.x-o,l=s.y-a;r.position.set(r.x+h,r.y+l),this.dragStart={x:s.x,y:s.y},w.debug("[Interaction] applyPan",{pointerId:t.pointerId,dx:h,dy:l})}applyPinchZoom(){var m;const i=this.appService.appContainer,s=Array.from(this.activeTouches.values());if(s.length<2||!this.initialTouchDistance||!this.initialScale||!this.initialPinchCenter)return;const r=q(s[0],s[1]),o={x:(s[0].x+s[1].x)/2,y:(s[0].y+s[1].y)/2},a={x:(o.x-i.position.x)/i.scale.x,y:(o.y-i.position.y)/i.scale.y},h=(r/this.initialTouchDistance)**this.zoomFactor,l=Math.max(this.scaleMin,Math.min(this.scaleMax,this.initialScale.x*h)),c=Math.max(this.scaleMin,Math.min(this.scaleMax,this.initialScale.y*h));i.scale.set(l,c),w.debug("[Interaction] applyPinchZoom",{newScaleX:l,initialScale:(m=this.initialScale)==null?void 0:m.x,scaleRatio:h});let d=o.x-a.x*l,u=o.y-a.y*c;const p=o.x-this.initialPinchCenter.x,g=o.y-this.initialPinchCenter.y;d+=p,u+=g,i.position.set(d,u),this.antiScale(l),this.initialPinchCenter=o}setInitialScaleAndDistance(t){const i=Array.from(this.activeTouches.values());i.length<2||(this.initialTouchDistance=q(i[0],i[1]),this.initialScale={x:t.scale.x,y:t.scale.y},this.initialPinchCenter={x:(i[0].x+i[1].x)/2,y:(i[0].y+i[1].y)/2})}}function Nx(n){return{all:n=n||new Map,on:function(e,t){var i=n.get(e);i?i.push(t):n.set(e,[t])},off:function(e,t){var i=n.get(e);i&&(t?i.splice(i.indexOf(t)>>>0,1):n.set(e,[]))},emit:function(e,t){var i=n.get(e);i&&i.slice().map(function(s){s(t)}),(i=n.get("*"))&&i.slice().map(function(s){s(e,t)})}}}const $x="__ray_robot_map_debug_ring__",Tc="__ray_robot_map_late_lifecycle_markers__",Yx=200,Xx=20;function jx(){return Date.now()}function Zx(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function qr(){try{return globalThis.localStorage??null}catch{return null}}function qx(){var n;try{return((n=globalThis.document)==null?void 0:n.visibilityState)??null}catch{return null}}function Kx(n){if(!n||typeof n!="object")return null;const e=n;return typeof e.seq!="number"||typeof e.ts!="number"||typeof e.event!="string"||typeof e.sessionId!="string"?null:{seq:e.seq,ts:e.ts,event:e.event,sessionId:e.sessionId,instanceId:e.instanceId??null,visibilityState:e.visibilityState??null,rendererType:e.rendererType??null,mapId:e.mapId??null,detail:e.detail}}function oh(n,e){if(!n)return[];try{const t=n.getItem(e);if(!t)return[];const i=JSON.parse(t);return Array.isArray(i)?i.map(s=>Kx(s)).filter(s=>s!==null):[]}catch{return[]}}function Qx(n,e,t){if(n)try{n.setItem(e,JSON.stringify(t))}catch{}}function Jx(n){if(!n)return{};try{const e=n.getItem(Tc);if(!e)return{};const t=JSON.parse(e);return typeof t=="object"&&t?t:{}}catch{return{}}}function tS(n=qr()){return Jx(n)}function eS(n=qr()){if(n)try{n.removeItem(Tc)}catch{}}function iS(n={}){var g;const e=n.storage===void 0?qr():n.storage,t=n.storageKey??$x,i=n.maxEntries??Yx,s=n.previousTailSize??Xx,r=n.now??jx,o=((g=n.createSessionId)==null?void 0:g.call(n))??Zx(),a=oh(e,t),h=a.length>0?a[a.length-1].sessionId:null;let l=a.length>0?a[a.length-1].seq:0;const c=()=>oh(e,t);return{getSessionId:()=>o,hasStorage:()=>e!==null,readAll:c,readCurrentSession:()=>c().filter(m=>m.sessionId===o),readPreviousSessionTail:()=>h?c().filter(m=>m.sessionId===h).slice(-s):[],readLateLifecycleMarkers:()=>tS(e),clear:()=>{if(eS(e),!!e)try{e.removeItem(t)}catch{}},record:m=>{l+=1;const y={seq:l,ts:r(),event:m.event,sessionId:o,instanceId:m.instanceId??null,visibilityState:m.visibilityState??qx(),rendererType:m.rendererType??null,mapId:m.mapId??null,detail:m.detail},x=[...c(),y].slice(-i);return Qx(e,t,x),y}}}let zn=null;function Ln(){return zn||(zn=iS()),zn}class Rc{constructor(e){this.app=e}getApp(){return this.app}getConfig(){return this.getApp().config}getDebuggerMode(){return!1}getRoomData(e){return this.getApp().managers.roomsManager.getRoomPropertyById(e)}get coords(){return this.getApp().coords}get ticker(){return this.getApp().ticker}get mapState(){return this.getApp().mapState}get isMapDrawn(){return this.getApp().isMapDrawn}get config(){return this.getConfig()}get gloalConfig(){return this.getConfig().global}get mapConfig(){return this.getConfig().map}get roomConfig(){return this.getConfig().room}get heatMapConfig(){return this.getConfig().heatmap}get pathConfig(){return this.getConfig().path}get carpetConfig(){return this.getConfig().carpet}get robotConfig(){return this.getConfig().robot}get chargingStationConfig(){return this.getConfig().chargingStation}get interactionConfig(){return this.getConfig().interaction}get controlsConfig(){return this.getConfig().controls}get furnitureConfig(){return this.getConfig().furniture}get dividerConfig(){return this.getConfig().divider}get detectedObjectConfig(){return this.getConfig().detectedObject}get snapshotConfig(){return this.getConfig().snapshot}get appContainer(){return this.getApp().components.appContainer}get interaction(){return this.getApp().components.interaction}get gestureController(){return this.getApp().components.interaction}get viewportContainer(){return this.getApp().components.viewportContainer}get mapManager(){return this.getApp().managers.mapManager}get pathManager(){return this.getApp().managers.pathManager}get heatmapManager(){return this.getApp().managers.heatmapManager}get controlsManager(){return this.getApp().managers.controlsManager}get detectedObjectManager(){return this.getApp().managers.detectedObjectManager}get customElementsManager(){return this.getApp().managers.customElementsManager}get roomsManager(){return this.getApp().managers.roomsManager}get editControlManager(){return this.getApp().managers.editControlManager}get furnitureManager(){return this.getApp().managers.furnitureManager}get runtime(){return this.getApp().runtime}get runtimeSnapshot(){return Hx(this.getApp().runtime)}isInteractionEnabled(){return this.runtimeSnapshot.enableInteraction}fixPrecision(e,t){return yc(e,t)}get events(){return this.getApp().events}get baseScale(){return this.getApp().components.interaction.targetScale.x}get currentScale(){return this.getApp().components.appContainer.scale.x}get emitter(){return this.getApp().emitter}getChargerPosition(){const e=this.mapState;return e?this.fixPrecision({x:e.charger.x-e.origin.x,y:e.charger.y-e.origin.y}):null}getRobotPosition(){const e=this.pathManager.robot;return e?e.getCurrentPosition():null}}const sS=3.28084,On=100,ah=5;class nS{constructor(e=()=>"meter"){f(this,"cmPerPixel",null);f(this,"fallbackWarned",!1);f(this,"getDisplayUnit");this.getDisplayUnit=e}setResolution(e){if(!Number.isFinite(e)||e<=0){w.warn("[CoordinateSpace] Ignoring invalid resolution",e);return}this.cmPerPixel=e}isReady(){return this.cmPerPixel!=null}toPixels(e){const t=this.resolveResolution("toPixels");return Bt(e*(On/t))}toMeters(e){const t=this.resolveResolution("toMeters");return et(e*(t/On))}toDisplayUnit(e){switch(this.getDisplayUnit()){case"feet":return e*sS;case"centimeter":return e*On;case"meter":default:return e}}validateShape(e,t){const i=this.toPixels(t.minSize),s=t.maxSize!=null?this.toPixels(t.maxSize):void 0,r=yx(e,i,s);return xx(r)}resolveResolution(e){return this.cmPerPixel==null?(this.fallbackWarned||(this.fallbackWarned=!0,w.warn(`[CoordinateSpace] ${e} called before map resolution is ready, falling back to default ${ah}cm/pixel. This happens when the device reports an invalid map resolution (e.g. 0) or when converting before the first map draw.`)),ah):this.cmPerPixel}}let rS="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",hh=(n=21)=>{let e="",t=n|0;for(;t--;)e+=rS[Math.random()*64|0];return e};const ri=(n,e,t)=>{if(e!=null){if(typeof e!="number"||!Number.isFinite(e)||e<=n){w.warn(`[${t}] maxSize (${String(e)}) must be a finite number greater than minSize (${n}); ignoring.`);return}return e}};class oS extends L{constructor(t,i){super();f(this,"viewportBounds",{x:0,y:0,width:0,height:0});f(this,"maskGraphics",null);f(this,"containerElement",null);this.containerElement=i||window,this.calculateViewportBounds(t.global),this.position.set(this.viewportBounds.x,this.viewportBounds.y),this.createMask()}calculateViewportBounds(t){const{containerTop:i,containerLeft:s,containerWidth:r,containerHeight:o}=t,{width:a,height:h}=this.getContainerSize(),l=this.parseSize(s,a),c=this.parseSize(i,h),d=this.parseSize(r,a),u=this.parseSize(o,h);this.viewportBounds={x:l,y:c,width:d,height:u}}getContainerSize(){if(!this.containerElement)return{width:window.innerWidth,height:window.innerHeight};if(this.containerElement===window)return{width:window.innerWidth,height:window.innerHeight};const t=this.containerElement;return{width:t.clientWidth||window.innerWidth,height:t.clientHeight||window.innerHeight}}createMask(){this.maskGraphics=new U,this.maskGraphics.rect(0,0,this.viewportBounds.width,this.viewportBounds.height).fill(16777215),this.addChild(this.maskGraphics),this.mask=this.maskGraphics}parseSize(t,i){if(!isNaN(Number(t)))return Number(t);if(t=t.trim(),t.endsWith("%")){const s=parseFloat(t)/100;return i*s}if(t.endsWith("vw")){const s=parseFloat(t)/100;return window.innerWidth*s}if(t.endsWith("vh")){const s=parseFloat(t)/100;return window.innerHeight*s}if(t.endsWith("rpx")){const s=parseFloat(t),r=window.innerWidth/750;return s*r}return t.endsWith("px")||!isNaN(parseFloat(t))?parseFloat(t):(w.warn(`Cannot parse size value: ${t}`),0)}getViewportBounds(){return{...this.viewportBounds}}updateViewport(t){var i,s;this.calculateViewportBounds(t.global),this.position.set(this.viewportBounds.x,this.viewportBounds.y),(i=this.maskGraphics)==null||i.clear(),(s=this.maskGraphics)==null||s.rect(0,0,this.viewportBounds.width,this.viewportBounds.height).fill(16777215)}addContent(t){this.addChild(t)}}const aS="interaction",kc="roomFill",Ic="free",Kr="roomFloorType",Ec="carpet",Dc="obstacle",Fc="heatmap",Bc="path",Te="furniture",ce="controls",zc="roomInfo",je="detectedObject",Ii="customElement",Ei="customElementGif",Lc="chargingStation",Oc="robot",Ke="customCarpet",Ie="editControls",hS=[aS,kc,Ic,Kr,Ec,Ke,Dc,Fc,Bc,Te,zc,je,Ii,Ei,Lc,Oc,ce,Ie],lS=[ce,Ie,Ke,Ii,Ei,je,Te];class cS extends L{constructor(t){super();f(this,"layers",new Map);f(this,"mapRotation",0);f(this,"backgroundGraphics");f(this,"lastBackgroundState",null);this.appService=t;const s=this.appService.getApp().getViewportBounds();this.position.set(Math.round(s.width/2),Math.round(s.height/2)),this.pivot.set(0,0),this.backgroundGraphics=new U,this.backgroundGraphics.label="snapshotBackground",this.backgroundGraphics.visible=!1,this.addChild(this.backgroundGraphics),this.initializeLayers()}initializeLayers(){Object.values(hS).forEach(i=>{const s=new L;s.label=i,i===ce&&(s.isRenderGroup=!0),i===Ie&&(s.isRenderGroup=!0),i===Kr&&(s.eventMode="none"),this.layers.set(i,s),this.addChild(s)})}getLayer(t){return this.layers.get(t)}addToLayer(t,i,s){const r=this.layers.get(t);return r?(s!==void 0&&(i.zIndex=s),r.addChild(i),!0):(w.warn("[AppContainer Debug] Layer not found:",t),!1)}removeFromLayer(t,i){const s=this.layers.get(t);return s&&i.parent===s?(s.removeChild(i),!0):!1}clearLayer(t){const i=this.layers.get(t);return i?(i.removeChildren(),!0):!1}setLayerVisibility(t,i){const s=this.layers.get(t);return s?(s.visible=i,!0):!1}updateOriginTrackedLayers(t,i){lS.forEach(s=>{const r=this.layers.get(s);r&&r.position.set(t,i)})}getLayerVisibility(t){const i=this.layers.get(t);return i?i.visible:!1}setMapRotation(t){this.mapRotation=t*Math.PI/180,this.rotation=this.mapRotation}getMapRotation(){return this.mapRotation*180/Math.PI}getMapRotationRadians(){return this.mapRotation}getSnapshotBounds(){this.layers.forEach(s=>{});const t=this.backgroundGraphics.visible;this.backgroundGraphics.visible=!1;const i=this.getLocalBounds();return this.backgroundGraphics.visible=t,new tt(i.x,i.y,i.width,i.height)}updateBackground(t,i){if(!i){this.backgroundGraphics.visible=!1,this.lastBackgroundState=null;return}const s=this.getSnapshotBounds(),{x:r,y:o,width:a,height:h}=s;if(this.lastBackgroundState&&this.lastBackgroundState.color===t&&this.lastBackgroundState.width===a&&this.lastBackgroundState.height===h&&this.lastBackgroundState.x===r&&this.lastBackgroundState.y===o){this.backgroundGraphics.visible=!0;return}this.backgroundGraphics.clear(),this.backgroundGraphics.rect(r,o,a,h).fill(t),this.backgroundGraphics.visible=!0,this.lastBackgroundState={color:t,x:r,y:o,width:a,height:h}}}class Zt extends Xt{constructor(t,i){super(i);f(this,"throttledUpdateScale");f(this,"fixedWidth",0);f(this,"fixedHeight",0);f(this,"isFixedSizeSet",!1);f(this,"sizeFixed",!0);f(this,"baselineScale",1);f(this,"basePositionX",0);f(this,"basePositionY",0);f(this,"pixelOffset",null);this.appService=t,this.anchor.set(.5),this.visible=!1,this.throttledUpdateScale=_t(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.registerScaleListener()}setFixedSize(t,i){this.fixedWidth=t,this.fixedHeight=i,this.isFixedSizeSet=!0,this.applySize()}setSizeFixed(t){this.sizeFixed=t,this.baselineScale=1,t&&this.isFixedSizeSet?this.applySize():!t&&this.isFixedSizeSet&&this.applySize()}setBasePosition(t,i){this.basePositionX=t,this.basePositionY=i,this.pixelOffset?this.applyPixelOffset():this.position.set(t,i)}setPixelOffset(t){this.pixelOffset=t,t?this.applyPixelOffset():this.position.set(this.basePositionX,this.basePositionY)}applyPixelOffset(){if(this.destroyed||!this.pixelOffset)return;if(!this.sizeFixed){this.position.set(this.basePositionX,this.basePositionY);return}const t=this.appService.currentScale,i=this.appService.appContainer.getMapRotationRadians(),s=Yr(this.pixelOffset,t,i);this.position.set(this.basePositionX+s.x,this.basePositionY+s.y)}set width(t){if(this.isFixedSizeSet){w.warn("EnhancedSprite: 使用 setFixedSize() 方法来设置宽度");return}this.setFixedSize(t,this.fixedHeight||t)}set height(t){if(this.isFixedSizeSet){w.warn("EnhancedSprite: 使用 setFixedSize() 方法来设置高度");return}this.setFixedSize(this.fixedWidth||t,t)}get width(){return this.fixedWidth||super.width}get height(){return this.fixedHeight||super.height}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}applySize(){if(this.destroyed||!this.scale||!this.isFixedSizeSet||!this.texture||this.texture.width===0||this.texture.height===0)return;const t=this.appService,i=this.fixedWidth/this.texture.width,s=this.fixedHeight/this.texture.height;if(this.sizeFixed){const r=t.currentScale;if(r===0)return;const o=i/r,a=s/r;this.scale&&super.scale.set(o,a)}else this.scale&&super.scale.set(i/this.baselineScale,s/this.baselineScale)}updateScale(t){this.destroyed||!this.scale||this.sizeFixed&&(this.isFixedSizeSet?this.applySize():t!==0&&super.scale.set(1/t),this.applyPixelOffset())}async loadTextureAndSetSize(t,i){try{const s=this.appService,r=await N.load(t);if(this.destroyed||(this.texture=r,this.destroyed)||(i.sizeFixed!==void 0&&this.setSizeFixed(i.sizeFixed),this.setFixedSize(i.width,i.height),this.destroyed))return;s.getApp().renderOnceNextFrame()}catch(s){w.error(`Failed to load texture "${t}":`,s)}}draw(t,i){const{x:s,y:r,rotation:o=0}=t;i&&!this.visible?this.visible=i():!i&&!this.visible&&(this.visible=!0),this.rotation=o,this.position.set(s,r)}set texture(t){super.texture=t,this.isFixedSizeSet&&t&&t.width>0&&t.height>0&&this.applySize()}get texture(){return super.texture}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.throttledUpdateScale.cancel(),super.destroy(t)}}class dS extends Zt{constructor(e){super(e),this.appService=e,this.initializeSprite()}async initializeSprite(){const e=this.appService;await this.loadTextureAndSetSize("chargingStation",e.chargingStationConfig.icon)}async draw({x:e,y:t,rotation:i}){const s=this.appService;super.draw({x:e,y:t,rotation:i},()=>s.runtimeSnapshot.showChargingStation)}}class Wc extends U{constructor(t,i){super();f(this,"currentPosition",null);f(this,"config");f(this,"handleScaleChange",()=>{this.redraw()});this.appService=t,this.setupAntiScaleListener(),this.config=i.config}setupAntiScaleListener(){this.appService.emitter.on("antiScale",this.handleScaleChange)}draw(t){const i=this.appService;this.currentPosition=t;const{size:s,color:r,strokeWidth:o,strokeColor:a,strokeDashed:h,strokeDashArray:l}=this.config;this.clear();const c=i.coords.toPixels(et(s)),d=i.getApp().toFixedSize(o);this.setFillStyle({color:r}),h&&l.length>=2?this.drawDashedCircle(t,c,a,d,l):this.circle(t.x,t.y,c).fill().stroke({color:a,width:d,cap:"round",join:"round"})}drawDashedCircle(t,i,s,r,o){const a=this.appService;this.circle(t.x,t.y,i).fill();const h=a.getApp().toFixedSize(o[0]),l=a.getApp().toFixedSize(o[1]),c=2*Math.PI*i,d=h+l,u=Math.floor(c/d);if(u===0){this.circle(t.x,t.y,i).stroke({color:s,width:r,cap:"round",join:"round"});return}const p=c/u,g=p*(h/d);for(let m=0;m<u;m++){const y=m*p/i,x=(m*p+g)/i,S=Math.max(4,Math.ceil(Math.abs(x-y)*i/2)),v=(x-y)/S;for(let b=0;b<=S;b++){const P=y+v*b,C=t.x+i*Math.cos(P),_=t.y+i*Math.sin(P);b===0?this.moveTo(C,_):this.lineTo(C,_)}}this.stroke({color:s,width:r,cap:"round",join:"round"})}redraw(){this.currentPosition&&this.draw(this.currentPosition)}destroy(){this.appService.emitter.off("antiScale",this.handleScaleChange),super.destroy()}}class vt{constructor(e,t={}){f(this,"target");f(this,"isPointerDown",!1);f(this,"pointerDownPos",null);f(this,"clickThreshold");f(this,"stopPropagation");f(this,"clickCallback",null);this.target=e,this.clickThreshold=t.clickThreshold??10,this.stopPropagation=t.stopPropagation??!1,this.clickCallback=t.onClick||null,this.setup()}setup(){this.target.interactive=!0,this.target.eventMode="static",this.target.on("pointerdown",this.handlePointerDown.bind(this)),this.target.on("pointermove",this.handlePointerMove.bind(this)),this.target.on("pointerup",this.handlePointerUp.bind(this)),this.target.on("pointerupoutside",this.handlePointerUpOutside.bind(this))}handlePointerDown(e){this.stopPropagation&&e.stopPropagation(),this.isPointerDown=!0,this.pointerDownPos={x:e.globalX,y:e.globalY}}handlePointerMove(e){if(this.stopPropagation&&e.stopPropagation(),this.isPointerDown&&this.pointerDownPos){const t=e.globalX-this.pointerDownPos.x,i=e.globalY-this.pointerDownPos.y;Math.sqrt(t*t+i*i)>this.clickThreshold&&(this.isPointerDown=!1,this.pointerDownPos=null)}}handlePointerUp(e){if(this.stopPropagation&&e.stopPropagation(),this.isPointerDown&&this.pointerDownPos){const t=e.globalX-this.pointerDownPos.x,i=e.globalY-this.pointerDownPos.y;Math.sqrt(t*t+i*i)<=this.clickThreshold&&this.clickCallback&&this.clickCallback(e,this.target)}this.isPointerDown=!1,this.pointerDownPos=null}handlePointerUpOutside(){this.isPointerDown=!1,this.pointerDownPos=null}setClickCallback(e){return this.clickCallback=e,this}setClickThreshold(e){return this.clickThreshold=e,this}getTarget(){return this.target}isInteracting(){return this.isPointerDown}destroy(){this.target.off("pointerdown",this.handlePointerDown),this.target.off("pointermove",this.handlePointerMove),this.target.off("pointerup",this.handlePointerUp),this.target.off("pointerupoutside",this.handlePointerUpOutside),this.clickCallback=null}}class uS extends L{constructor(t){super();f(this,"chargingStation");f(this,"ring");f(this,"unsubscribeFns",[]);f(this,"clickHandler");this.appService=t,t.appContainer.addToLayer(Lc,this),this.ring=new Wc(this.appService,{config:this.appService.chargingStationConfig.ring}),this.ring.visible=this.appService.runtimeSnapshot.showChargingStationRing,this.addChild(this.ring),this.chargingStation=new dS(this.appService),this.addChild(this.chargingStation);const i=W(this.appService.runtime,"showChargingStationRing",s=>{w.log(`[runtime] showChargingStationRing: ${s}`),this.ring.visible=s});this.unsubscribeFns.push(i),this.initClickInteraction()}async draw({x:t,y:i,rotation:s}){if(t===0&&i===0){this.visible=!1;return}this.visible=!0,this.ring.draw({x:t,y:i}),await this.chargingStation.draw({x:t,y:i,rotation:s})}initClickInteraction(){const{enableChargingStationClick:t}=this.appService.interactionConfig;t&&(this.clickHandler||(this.clickHandler=new vt(this.chargingStation,{onClick:()=>{var i;if((i=this.appService.events)!=null&&i.onClickChargingStation){const s=this.appService.getChargerPosition()??{x:0,y:0};this.appService.events.onClickChargingStation({rotation:this.chargingStation.rotation,...s})}}})))}destroy(){this.unsubscribeFns.forEach(t=>t()),this.unsubscribeFns=[],this.ring.destroy(),this.clickHandler&&this.clickHandler.destroy(),super.destroy()}}class pS extends L{constructor(t){super({isRenderGroup:!0});f(this,"carpetSprite",null);f(this,"carpetMask",null);this.appService=t,this.appService.appContainer.addToLayer(Ec,this)}async createCarpetFromRasterData(t,i){const s=this.appService;if(!s.runtimeSnapshot.showCarpet||(this.clearCarpet(),t.length===0))return;const{src:r,opacity:o,scale:a}=s.carpetConfig,h=await N.load(r);if(!h){w.warn(`Carpet texture not found: ${r}`);return}const l=this.createCarpetGraphics(t,i),c=l.getLocalBounds();if(c.width===0||c.height===0)return;const d=new As({texture:h,width:c.width,height:c.height});d.x=c.x,d.y=c.y,d.alpha=o,d.tileScale.set(a);const u=new L;u.addChild(l),d.mask=u,this.addChild(d),this.carpetSprite=d,this.carpetMask=u,s.getApp().renderOnceNextFrame()}createCarpetGraphics(t,i){const s=new U;for(let r=0;r<t.length;r++){const o=t[r],a=o%i,h=Math.floor(o/i);s.rect(a,h,1,1)}return s.fill(16777215),s}clearCarpet(){this.carpetSprite&&(this.removeChild(this.carpetSprite),this.carpetSprite.destroy(),this.carpetSprite=null),this.carpetMask&&(this.carpetMask.destroy({children:!0,context:!0}),this.carpetMask=null)}async createCarpetFromStructuredData(t){const i=this.appService;if(!i.runtimeSnapshot.showCarpet||!t||(this.clearCarpet(),t.length===0))return;const{src:s,opacity:r,scale:o}=i.carpetConfig,a=await N.load(s);if(!a){w.warn(`Carpet texture not found: ${s}`);return}const h=this.createCarpetGraphicsFromStructuredData(t),l=h.getLocalBounds();if(l.width===0||l.height===0)return;const c=new As({texture:a,width:l.width,height:l.height});c.x=l.x,c.y=l.y,c.alpha=r,c.tileScale.set(o);const d=new L;d.addChild(h),c.mask=d,this.addChild(c),this.carpetSprite=c,this.carpetMask=d,i.getApp().renderOnceNextFrame()}createCarpetGraphicsFromStructuredData(t){const i=new U;for(const s of t){const r=s.coordinates;for(let o=0;o<r.length;o+=2){const a=r[o],h=r[o+1];i.rect(a,h,1,1)}}return i.fill(16777215),i}destroy(){this.clearCarpet(),super.destroy()}}class lh extends U{constructor(e){super(),this.appService=e,this.appService.appContainer.addToLayer(Ic,this)}draw(e){const t=this.appService;this.clear(),this.setFillStyle({color:t.mapConfig.freeColor});for(const i of e){const s=i.coordinates;for(let r=0;r<s.length;r+=2){const o=s[r],a=s[r+1];this.rect(o,a,1,1)}}this.fill()}destroy(e){super.destroy(e)}}class ch extends U{constructor(e){super(),this.appService=e,this.appService.appContainer.addToLayer(Dc,this)}draw(e){const t=this.appService;this.clear(),this.setFillStyle({color:t.mapConfig.obstacleColor});for(const i of e){const s=i.coordinates;for(let r=0;r<s.length;r+=2){const o=s[r],a=s[r+1];this.rect(o,a,1,1)}}this.fill()}drawRaster(e,t){const i=this.appService;if(this.clear(),e.length!==0){this.setFillStyle({color:i.mapConfig.obstacleColor});for(let s=0;s<e.length;s+=ae){const r=Math.min(s+ae,e.length);for(let o=s;o<r;o++){const a=e[o],h=a%t,l=Math.floor(a/t);this.rect(h,l,1,1)}this.fill(),r<e.length&&this.setFillStyle({color:i.mapConfig.obstacleColor})}}}destroy(e){super.destroy(e)}}class dh extends L{constructor(t){super({isRenderGroup:!0});f(this,"roomGraphicsMap",new Map);f(this,"roomContextMap",new Map);f(this,"roomClickHandlerMap",new Map);f(this,"unsubscribeFns",[]);f(this,"mapWidth",0);f(this,"rasterRoomDataMap",new Map);f(this,"structuredRoomGeometry",new Map);this.appService=t,this.appService.appContainer.addToLayer(kc,this);const i=Us(this.appService.config.room.colors,()=>{this.refreshRoomColors()});this.unsubscribeFns.push(i)}draw(t){const i=this.appService;this.clearRooms();const s=i.roomConfig,{selectRoomIds:r,enableRoomSelection:o}=i.runtimeSnapshot;t.forEach(a=>{const h=a.id>=255,l=new U,c=new gt,d=new gt,u=new gt;if(h)c.setFillStyle({color:a.color}),d.setFillStyle({color:a.color}),u.setFillStyle({color:a.color});else{const p=a.colorIndex??0,g=s.colors.active[p%s.colors.active.length],m=s.colors.inactive[p%s.colors.inactive.length],y=(s.colors.normal||s.colors.active)[p%(s.colors.normal||s.colors.active).length];c.setFillStyle({color:g}),d.setFillStyle({color:m}),u.setFillStyle({color:y})}if(c.poly(a.polyPoints).fill(),d.poly(a.polyPoints).fill(),u.poly(a.polyPoints).fill(),a.outlinePoints.forEach(p=>{c.rect(p.x,p.y,1,1).fill(),d.rect(p.x,p.y,1,1).fill(),u.rect(p.x,p.y,1,1).fill()}),h?l.context=c:l.context=o?r.includes(a.id)?c:d:u,!h){const p=new vt(l,{clickThreshold:10,onClick:()=>{this.handleRoomClick(a.id)}});this.roomClickHandlerMap.set(a.id,p),this.structuredRoomGeometry.set(a.id,{polyPoints:a.polyPoints,outlinePoints:a.outlinePoints,colorIndex:a.colorIndex??0})}this.roomGraphicsMap.set(a.id,l),this.roomContextMap.set(a.id,{activeContext:c,inactiveContext:d,normalContext:u}),this.addChild(l)})}drawRaster(t){const i=this.appService;if(this.clearRooms(),this.mapWidth=t.width,t.sortedRooms.length===0)return;const{selectRoomIds:s,enableRoomSelection:r}=i.runtimeSnapshot;t.sortedRooms.forEach(o=>{this.drawRasterRoom(o,r,s)})}drawRasterRoom(t,i,s){const{roomId:r,pixelIndices:o,activeColor:a,inactiveColor:h}=t,c=this.appService.roomConfig;let d=a;const u=typeof r=="number";if(u){const S=t.colorIndex??0;d=(c.colors.normal||c.colors.active)[S%(c.colors.normal||c.colors.active).length]}const p=new U,g=new gt,m=new gt,y=new gt;g.setFillStyle({color:a}),m.setFillStyle({color:h}),y.setFillStyle({color:d}),this.drawPixelPointsInBatches(g,o,ae,this.mapWidth),this.drawPixelPointsInBatches(m,o,ae,this.mapWidth),this.drawPixelPointsInBatches(y,o,ae,this.mapWidth);const x=u&&s.includes(r);if(p.context=i?u&&x?g:m:y,u){const S=new vt(p,{clickThreshold:10,onClick:()=>{this.handleRoomClick(r)}});this.roomClickHandlerMap.set(r,S)}this.roomGraphicsMap.set(r,p),this.roomContextMap.set(r,{activeContext:g,inactiveContext:m,normalContext:y}),this.rasterRoomDataMap.set(r,t),this.addChild(p)}drawPixelPointsInBatches(t,i,s,r){for(let o=0;o<i.length;o+=s){const a=Math.min(o+s,i.length);for(let h=o;h<a;h++){const l=i[h],c=l%r,d=Math.floor(l/r);t.rect(c,d,1,1)}t.fill()}}handleRoomClick(t){var s,r;const i=this.appService;(r=(s=i.events)==null?void 0:s.onClickRoom)==null||r.call(s,i.getRoomData(t)??{id:t})}setRoomStateBySelectIds(t){const i=this.appService,{enableRoomSelection:s}=i.runtimeSnapshot;this.roomGraphicsMap.forEach((r,o)=>{if(typeof o=="number"){const a=this.roomContextMap.get(o);if(a)if(s){const h=t.includes(o);r.context=h?a.activeContext:a.inactiveContext}else r.context=a.normalContext}})}setRoomState(t,i){const s=this.roomGraphicsMap.get(t),r=this.roomContextMap.get(t);if(!s||!r){w.warn(`Room ${t} not found`);return}typeof t=="number"&&(s.context=i?r.activeContext:r.inactiveContext)}setAllRoomsState(t){this.roomGraphicsMap.forEach((i,s)=>{typeof s=="number"&&this.setRoomState(s,t)})}getRoomGraphicsMap(){const t=new Map;return this.roomGraphicsMap.forEach((i,s)=>{typeof s=="number"&&t.set(s,i)}),t}getRasterRoomData(t){return this.rasterRoomDataMap.get(t)||null}getMapWidth(){return this.mapWidth}isWallIntersectsAnyRoom(t){const s=this.appService.getApp().mapState;if(!s)return w.warn("[RoomFill] Map state not available"),!1;if(!t||t.length!==2)return w.warn("[RoomFill] Invalid wall points provided"),!1;const[r,o]=t,a={x:r.x+s.origin.x,y:r.y+s.origin.y},h={x:o.x+s.origin.x,y:o.y+s.origin.y};return s.mapType==="raster"?this.isWallIntersectsAnyRoomRaster(a,h):this.isWallIntersectsAnyRoomStructured(a,h)}isZoneIntersectsAnyRoom(t){const s=this.appService.getApp().mapState;if(!s)return w.warn("[RoomFill] Map state not available"),!1;if(!t||t.length!==4)return w.warn("[RoomFill] Invalid zone points provided"),!1;const r=t.map(o=>({x:o.x+s.origin.x,y:o.y+s.origin.y}));return s.mapType==="raster"?this.isZoneIntersectsAnyRoomRaster(r):this.isZoneIntersectsAnyRoomStructured(r)}isWallIntersectsAnyRoomRaster(t,i){if(this.mapWidth===0||this.rasterRoomDataMap.size===0)return!1;const s=this.getLinePixels(t,i);for(const r of this.rasterRoomDataMap.values())for(const o of s)if(gr(r.pixelIndices,o))return!0;return!1}isWallIntersectsAnyRoomStructured(t,i){const r=this.appService.mapManager.getAllRooms();for(const o of r)if(!(!o.outlinePoints||o.outlinePoints.length<3)){if(It(t,o.outlinePoints,!0)||It(i,o.outlinePoints,!0))return!0;for(let a=0;a<o.outlinePoints.length;a++){const h=o.outlinePoints[a],l=o.outlinePoints[(a+1)%o.outlinePoints.length];if(Hi(t,i,h,l))return!0}}return!1}isZoneIntersectsAnyRoomRaster(t){if(this.mapWidth===0||this.rasterRoomDataMap.size===0)return!1;const i=[[t[0],t[1]],[t[1],t[2]],[t[2],t[3]],[t[3],t[0]]];for(const[r,o]of i)if(this.isWallIntersectsAnyRoomRaster(r,o))return!0;const s=this.rasterRoomDataMap.values().next().value;if(s&&s.pixelIndices.length>0){const r=s.pixelIndices[0],o=r%this.mapWidth,a=Math.floor(r/this.mapWidth);if(It({x:o,y:a},t,!0))return!0}return!1}isZoneIntersectsAnyRoomStructured(t){const s=this.appService.mapManager.getAllRooms(),r=[[t[0],t[1]],[t[1],t[2]],[t[2],t[3]],[t[3],t[0]]];for(const o of s)if(!(!o.outlinePoints||o.outlinePoints.length<3)){for(const a of t)if(It(a,o.outlinePoints,!0))return!0;for(const a of o.outlinePoints)if(It(a,t,!0))return!0;for(const[a,h]of r)for(let l=0;l<o.outlinePoints.length;l++){const c=o.outlinePoints[l],d=o.outlinePoints[(l+1)%o.outlinePoints.length];if(Hi(a,h,c,d))return!0}}return!1}getLinePixels(t,i){const r=this.appService.getApp().mapState;if(!r)return[];const o=r.height,a=[],h=Math.round(t.x),l=Math.round(t.y),c=Math.round(i.x),d=Math.round(i.y),u=Math.abs(c-h),p=Math.abs(d-l),g=h<c?1:-1,m=l<d?1:-1;let y=u-p,x=h,S=l;for(;;){if(x>=0&&x<this.mapWidth&&S>=0&&S<o){const b=S*this.mapWidth+x;a.push(b)}if(x===c&&S===d)break;const v=2*y;v>-p&&(y-=p,x+=g),v<u&&(y+=u,S+=m)}return a}getZonePixels(t,i,s,r){const a=this.appService.getApp().mapState;if(!a)return[];const h=a.height,l=[],c=Math.max(0,Math.floor(t)),d=Math.min(this.mapWidth-1,Math.ceil(s)),u=Math.max(0,Math.floor(i)),p=Math.min(h-1,Math.ceil(r));for(let g=u;g<=p;g++)for(let m=c;m<=d;m++){const y=g*this.mapWidth+m;l.push(y)}return l}refreshRoomColors(){const{selectRoomIds:t,enableRoomSelection:i}=this.appService.runtimeSnapshot,s=this.appService.roomConfig;this.roomGraphicsMap.forEach((r,o)=>{if(typeof o!="number")return;const a=this.roomContextMap.get(o),h=this.structuredRoomGeometry.get(o);if(a&&h){const l=h.colorIndex,c=s.colors.active[l%s.colors.active.length],d=s.colors.inactive[l%s.colors.inactive.length],u=(s.colors.normal||s.colors.active)[l%(s.colors.normal||s.colors.active).length];a.activeContext.clear(),a.activeContext.setFillStyle({color:c}),a.activeContext.poly(h.polyPoints).fill(),h.outlinePoints.forEach(p=>{a.activeContext.rect(p.x,p.y,1,1).fill()}),a.inactiveContext.clear(),a.inactiveContext.setFillStyle({color:d}),a.inactiveContext.poly(h.polyPoints).fill(),h.outlinePoints.forEach(p=>{a.inactiveContext.rect(p.x,p.y,1,1).fill()}),a.normalContext.clear(),a.normalContext.setFillStyle({color:u}),a.normalContext.poly(h.polyPoints).fill(),h.outlinePoints.forEach(p=>{a.normalContext.rect(p.x,p.y,1,1).fill()}),r.context=i?t.includes(o)?a.activeContext:a.inactiveContext:a.normalContext}else if(a){const l=this.rasterRoomDataMap.get(o);if(l){const c=l.colorIndex??0,d=s.colors.active[c%s.colors.active.length],u=s.colors.inactive[c%s.colors.inactive.length],p=(s.colors.normal||s.colors.active)[c%(s.colors.normal||s.colors.active).length];a.activeContext.clear(),a.activeContext.setFillStyle({color:d}),this.drawPixelPointsInBatches(a.activeContext,l.pixelIndices,ae,this.mapWidth),a.inactiveContext.clear(),a.inactiveContext.setFillStyle({color:u}),this.drawPixelPointsInBatches(a.inactiveContext,l.pixelIndices,ae,this.mapWidth),a.normalContext.clear(),a.normalContext.setFillStyle({color:p}),this.drawPixelPointsInBatches(a.normalContext,l.pixelIndices,ae,this.mapWidth),r.context=i?t.includes(o)?a.activeContext:a.inactiveContext:a.normalContext}}}),this.appService.getApp().renderOnceNextFrame()}clearRooms(){this.children.length===0&&this.roomGraphicsMap.size===0||(this.roomGraphicsMap.forEach(t=>{try{t.destroy()}catch(i){w.warn("Error destroying room graphics:",i)}}),this.roomGraphicsMap.clear(),this.roomContextMap.forEach(t=>{try{t.activeContext.destroy(),t.inactiveContext.destroy(),t.normalContext.destroy()}catch(i){w.warn("Error destroying graphics context:",i)}}),this.roomContextMap.clear(),this.roomClickHandlerMap.forEach(t=>{try{t.destroy()}catch(i){w.warn("Error destroying click handler:",i)}}),this.roomClickHandlerMap.clear(),this.removeChildren(),this.rasterRoomDataMap.clear(),this.structuredRoomGeometry.clear())}destroy(){this.unsubscribeFns.forEach(t=>t()),this.unsubscribeFns=[],this.clearRooms(),super.destroy()}}class fS{constructor(e){f(this,"obstacle");f(this,"free");f(this,"roomFill");f(this,"carpet");f(this,"chargingStation");f(this,"mapBounds",{minX:0,minY:0,maxX:0,maxY:0});f(this,"lastMapId",null);f(this,"lastOrigin",null);f(this,"lastSize",null);f(this,"lastStatus",null);f(this,"roomGeometryMap",new Map);f(this,"rasterRoomPixelsMap",new Map);f(this,"fourColorCache",null);f(this,"carpetData",null);f(this,"unsubscribeFns",[]);this.appService=e,this.obstacle=new ch(this.appService),this.free=new lh(this.appService),this.roomFill=new dh(this.appService),this.carpet=new pS(this.appService),this.chargingStation=new uS(this.appService),this.validateColorConfig();const t=W(e.runtime,"enableRoomSelection",o=>{if(w.log(`[runtime] enableRoomSelection: ${o}`),o){this.roomFill.setAllRoomsState(!1);const a=this.appService.runtimeSnapshot.selectRoomIds;this.roomFill.setRoomStateBySelectIds(a)}else this.roomFill.setAllRoomsState(!0)}),i=W(e.runtime,"selectRoomIds",o=>{w.log(`[runtime] selectRoomIds: ${o}`),this.roomFill.setRoomStateBySelectIds(o)}),s=W(e.runtime,"showChargingStation",o=>{w.log(`[runtime] showChargingStation: ${o}`),this.chargingStation.visible=o}),r=W(e.runtime,"showCarpet",o=>{w.log(`[runtime] showCarpet: ${o}`),o?e.getApp().managers.customCarpetManager.getCustomCarpets().length===0&&this.createCarpet():this.carpet.clearCarpet()});this.unsubscribeFns.push(t,i,s,r)}async drawMap(e){const t=this.appService,{id:i,obstacles:s,free:r,rooms:o,charger:a,carpet:h,status:l,origin:c,size:d}=e;this.clearComponents(),this.resetGeometryData();const u=this.processRoomsGeometry(o);this.roomFill.draw(u),r&&this.free.draw(r),s&&this.obstacle.draw(s),this.carpetData=h,this.createCarpet();const p=this.mergeLayerBounds();lo(p,this.mapBounds)||(w.debug("[Map] Map bounds updated:",p),this.mapBounds=p,this.shouldFitMapToView(i,l===1,{x:c[0],y:c[1]},{x:d[0],y:d[1]})&&(t.getApp().fitMapToView(this.mapBounds),this.lastMapId=i,this.lastOrigin={x:c[0],y:c[1]},this.lastSize={x:d[0],y:d[1]},this.lastStatus=l===1));const g=((e.charger.angle??0)+t.chargingStationConfig.rotationCorrection)*Math.PI/180;return await this.chargingStation.draw({x:a.coordinate[0],y:a.coordinate[1],rotation:g}),await t.roomsManager.refresh(),!0}async drawRasterMap(e,t){const i=this.appService;this.clearComponents();const{id:s,width:r,height:o,charger:a,chargerDirection:h,status:l,origin:c}=t;w.debug("[Map] Parsed Raster Map Data",e),this.obstacle.drawRaster(e.obstacles,r),this.carpetData=this.convertRasterToStructuredData(e.carpet,r),i.getApp().managers.customCarpetManager.getCustomCarpets().length===0&&this.createCarpet();const u=this.processRasterData(e);this.roomFill.drawRaster(u);const p=Tx(e,r,o);lo(p,this.mapBounds)||(w.debug("[Map] Raster map bounds updated:",p),this.mapBounds=p,this.shouldFitMapToView(s,l,c,{x:r,y:o})&&(i.getApp().fitMapToView(this.mapBounds),this.lastMapId=s,this.lastOrigin={...c},this.lastSize={x:r,y:o},this.lastStatus=l));const g=(h+i.chargingStationConfig.rotationCorrection)*Math.PI/180;return await this.chargingStation.draw({x:a.x,y:a.y,rotation:g}),this.generateRoomGeometryFromRaster(e),await i.roomsManager.refresh(),!0}resetGeometryData(){this.roomGeometryMap.clear(),this.rasterRoomPixelsMap.clear(),this.fourColorCache=null,this.mapBounds={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}shouldFitMapToView(e,t,i,s){const r=this.appService,{originChangeAutoFitThreshold:o,sizeChangeAutoFitThreshold:a}=r.getApp().config.map;if(this.lastMapId!==e)return w.debug("[Map] Map ID changed, triggering fitMapToView"),!0;if(this.lastStatus!==null&&this.lastStatus!==t)return w.debug(`[Map] Map status changed (${this.lastStatus} -> ${t}), triggering fitMapToView`),!0;if(this.lastOrigin&&i){const h=Math.abs(i.x-this.lastOrigin.x),l=Math.abs(i.y-this.lastOrigin.y);if(h>o||l>o)return w.debug(`[Map] Origin change exceeded threshold (deltaX: ${h}, deltaY: ${l}, threshold: ${o}), triggering fitMapToView`),!0}if(this.lastSize&&s){const h=Math.abs(s.x-this.lastSize.x),l=Math.abs(s.y-this.lastSize.y);if(h>a||l>a)return w.debug(`[Map] Size change exceeded threshold (deltaX: ${h}, deltaY: ${l}, threshold: ${a}), triggering fitMapToView`),!0}return!1}convertRasterToStructuredData(e,t){if(e.length===0)return[];const i=[];for(let s=0;s<e.length;s++){const r=e[s],o=r%t,a=Math.floor(r/t);i.push(o,a)}return[{coordinates:i}]}async createCarpet(){!this.appService.runtimeSnapshot.showCarpet||!this.carpetData||await this.carpet.createCarpetFromStructuredData(this.carpetData)}processRoomsGeometry(e){if(!e)return[];const t=this.appService,{active:i}=t.roomConfig.colors,s=t.roomConfig.colors[Ks.UNKNOWN_ROOM];if(Object.keys(e).length===0)return this.mapBounds={minX:0,minY:0,maxX:0,maxY:0},[];const r=Object.keys(e).sort((u,p)=>Number(u)-Number(p)),o=r.filter(u=>Number(u)<255),a=r.filter(u=>Number(u)>=255),h=[],l=[];o.forEach(u=>{const{coordinates:p}=e[u];if(p.length<4)return;const g=p.filter(A=>!isFinite(A));if(g.length>0){w.error(`[Room ${u}] Contains ${g.length} invalid coordinates (NaN/Infinity)`);return}const m=Number(u);let y=1/0,x=1/0,S=-1/0,v=-1/0;const b=[];for(let A=0;A<p.length;A+=2){const E=p[A],D=p[A+1];y=Math.min(y,E),x=Math.min(x,D),S=Math.max(S,E),v=Math.max(v,D),b.push({x:E,y:D})}const P=S-y,C=v-x;if(P===0||C===0){w.error(`[Room ${u}] Degenerate polygon (${P}x${C}). Skipping.`);return}if(P<2||C<2){w.warn(`[Room ${u}] Room too small (${P}x${C}), skipping`);return}const _=new tt(y,x,S-y+1,v-x+1),R=Za(b),M=R.flatMap(A=>[A.x+.5,A.y+.5]),T=qa(R,y,x,S,v);l.push({id:m,points:b,outlinePoints:R,polyPoints:M,centerPoint:T,boundingBox:_}),this.mapBounds.minX=Math.min(this.mapBounds.minX,y),this.mapBounds.minY=Math.min(this.mapBounds.minY,x),this.mapBounds.maxX=Math.max(this.mapBounds.maxX,S),this.mapBounds.maxY=Math.max(this.mapBounds.maxY,v)});const c=[...l].sort((u,p)=>{if(t.roomConfig.colors.sortBy==="area"){const g=u.outlinePoints.length;return p.outlinePoints.length-g}else return u.id-p.id}),d=this.assignColorsUsingFourColorAlgorithm(c,i.length,"structured");return l.forEach(u=>{const p=d.get(u.id)||0,g=i[p],m={id:u.id,color:g,colorIndex:p,boundingBox:u.boundingBox,points:u.points,outlinePoints:u.outlinePoints,polyPoints:u.polyPoints,centerPoint:u.centerPoint};this.roomGeometryMap.set(u.id,m),h.push(m)}),a.forEach(u=>{const{coordinates:p}=e[u];if(p.length<4)return;const g=Number(u);let m=1/0,y=1/0,x=-1/0,S=-1/0;const v=[];for(let A=0;A<p.length;A+=2){const E=p[A],D=p[A+1];m=Math.min(m,E),y=Math.min(y,D),x=Math.max(x,E),S=Math.max(S,D),v.push({x:E,y:D})}const b=x-m,P=S-y;if(b===0||P===0){w.error(`[Unknown Room ${u}] Degenerate polygon (${b}x${P}). Skipping.`);return}if(b<2||P<2){w.warn(`[Unknown Room ${u}] Room too small (${b}x${P}), skipping`);return}const C=new tt(m,y,x-m+1,S-y+1),_=Za(v),R=_.flatMap(A=>[A.x+.5,A.y+.5]),M=qa(_,m,y,x,S),T={id:g,color:s,boundingBox:C,points:v,outlinePoints:_,polyPoints:R,centerPoint:M};h.push(T),this.mapBounds.minX=Math.min(this.mapBounds.minX,m),this.mapBounds.minY=Math.min(this.mapBounds.minY,y),this.mapBounds.maxX=Math.max(this.mapBounds.maxX,x),this.mapBounds.maxY=Math.max(this.mapBounds.maxY,S)}),h}mergeLayerBounds(){let e={...this.mapBounds};if(this.obstacle.bounds&&(e=Fn(e,this.obstacle.bounds)),this.free.bounds&&(e=Fn(e,this.free.bounds)),this.roomFill.children.length>0){const t=this.roomFill.getLocalBounds();t.width>0&&t.height>0&&(e=Fn(e,{minX:t.x,minY:t.y,maxX:t.x+t.width,maxY:t.y+t.height}))}return e}getRoomById(e){return this.roomGeometryMap.get(e)}getAllRooms(){return Array.from(this.roomGeometryMap.values())}isWallIntersectsAnyRoom(e){return this.roomFill.isWallIntersectsAnyRoom(e)}isZoneIntersectsAnyRoom(e){return this.roomFill.isZoneIntersectsAnyRoom(e)}areRoomsAdjacent(e){const t=this.appService,i=t.mapConfig.adjacencyThreshold;if(!e||e.length===0)return w.warn("[MapManager] No room IDs provided"),!1;if(e.length===1)return!0;const s=Array.from(new Set(e));if(s.length===1)return!0;const r=t.getApp().mapState;return((r==null?void 0:r.mapType)??"structured")==="raster"?this.areRasterRoomsAdjacentInternal(s,i):this.areStructuredRoomsAdjacentInternal(s,i)}areStructuredRoomsAdjacentInternal(e,t){const i=[];for(const r of e){const o=this.getRoomById(r);if(!o)return w.warn(`[MapManager] Room ${r} not found in map`),!1;if(!o.outlinePoints||o.outlinePoints.length===0)return w.warn(`[MapManager] Room ${r} has no outline points`),!1;i.push({id:r,points:o.outlinePoints})}const s=[];for(let r=0;r<i.length;r++)for(let o=r+1;o<i.length;o++){const a=i[r],h=i[o];Ja(a.points,h.points,t)&&s.push([r,o])}return eh(i.length,s)}areRasterRoomsAdjacentInternal(e,t){const s=this.appService.getApp().mapState;if(!s)return w.warn("[MapManager] Map state not available"),!1;const r=s.width,o=[];for(const h of e){const l=this.getRasterRoomPixels(h);if(!l)return w.warn(`[MapManager] Room ${h} pixel data not found in raster map`),!1;o.push({id:h,pixels:l})}const a=[];for(let h=0;h<o.length;h++)for(let l=h+1;l<o.length;l++){const c=o[h],d=o[l];th(c.pixels,d.pixels,r,t)&&a.push([h,l])}return eh(o.length,a)}isPointInAnyRoom(e){const i=this.appService.getApp().mapState;return i?(i.mapType??"structured")==="raster"?this.isPointInAnyRoomRasterInternal(e,i):this.isPointInAnyRoomStructuredInternal(e,i):(w.warn("[MapManager] Map state not available"),null)}isPointInAnyRoomStructuredInternal(e,t){const i=e.x+t.origin.x,s=e.y+t.origin.y,r={x:i,y:s},o=this.getAllRooms();for(const a of o)if(a.outlinePoints&&a.outlinePoints.length>=3&&It(r,a.outlinePoints)){const l=this.appService.roomsManager.getRoomPropertyById(a.id);return l||(w.warn(`[MapManager] Room ${a.id} found in geometry but not in RoomManager`),null)}return null}isPointInAnyRoomRasterInternal(e,t){const i=t.width,s=t.height,r=e.x+t.origin.x,o=e.y+t.origin.y,a=Math.round(r),h=Math.round(o);if(a<0||a>=i||h<0||h>=s)return w.warn(`[MapManager] Point (${a}, ${h}) is out of map bounds (${i}x${s})`),null;const l=h*i+a,c=this.getAllRooms();for(const d of c){const u=this.getRasterRoomPixels(d.id);if(u&&u.length>0&&gr(u,l)){const g=this.appService.roomsManager.getRoomPropertyById(d.id);return g||(w.warn(`[MapManager] Room ${d.id} found in geometry but not in RoomManager`),null)}}return null}isPointInRoom(e,t){const i=this.appService.getApp().mapState;if(!i)return w.warn("[MapManager] Map state not available"),!1;const s=this.getRoomById(t);if(!s)return!1;const r=e.x+i.origin.x,o=e.y+i.origin.y;if((i.mapType??"structured")==="raster"){const h=Math.round(r),l=Math.round(o);if(h<0||h>=i.width||l<0||l>=i.height)return!1;const c=l*i.width+h,d=this.getRasterRoomPixels(t);return!!d&&d.length>0&&gr(d,c)}return!!s.outlinePoints&&s.outlinePoints.length>=3&&It({x:r,y:o},s.outlinePoints)}clearComponents(){this.obstacle.clear(),this.obstacle.destroy(),this.obstacle=new ch(this.appService),this.free.clear(),this.free.destroy(),this.free=new lh(this.appService),this.carpet.clearCarpet(),this.carpetData=null,this.roomFill.clearRooms(),this.roomFill.isRenderGroup&&(this.roomFill.isRenderGroup=!1),this.roomFill.removeChildren(),this.roomFill.destroy(),this.roomFill=new dh(this.appService)}processRasterData(e){const i=this.appService.roomConfig,s=[],r=[];e.rooms.forEach((d,u)=>{typeof u=="number"?s.push([u,d]):r.push([u,d])}),s.sort(([d],[u])=>d-u);const o=s.map(([d,u])=>({id:d,pixels:u})).sort((d,u)=>i.colors.sortBy==="area"?u.pixels.length-d.pixels.length:d.id-u.id),a=this.assignColorsUsingFourColorAlgorithm(o,i.colors.active.length,"raster"),h=s.map(([d,u])=>{const p=a.get(d)||0;return{roomId:d,pixelIndices:u,activeColor:i.colors.active[p],inactiveColor:i.colors.inactive[p%i.colors.inactive.length],colorIndex:p}}),l=r.map(([d,u])=>{let p=i.colors[d];return d===Ks.VERSION0_ROOM&&!p&&(p=i.colors[Ks.NO_ROOM_DATA]),{roomId:d,pixelIndices:u,activeColor:p,inactiveColor:p}}),c=[...h,...l];return{obstacles:e.obstacles,carpet:e.carpet,sortedRooms:c,width:e.width,height:e.height,totalPixels:e.totalPixels}}generateRoomGeometryFromRaster(e){const t=this.appService;this.roomGeometryMap.clear(),this.rasterRoomPixelsMap.clear();const{active:i}=t.roomConfig.colors,s=[];e.rooms.forEach((h,l)=>{typeof l=="number"&&s.push(l)}),s.sort((h,l)=>h-l);const r=[];s.forEach(h=>{const l=e.rooms.get(h);this.rasterRoomPixelsMap.set(h,l);let c=1/0,d=1/0,u=-1/0,p=-1/0;for(let y=0;y<l.length;y++){const x=l[y],S=x%e.width,v=Math.floor(x/e.width);c=Math.min(c,S),d=Math.min(d,v),u=Math.max(u,S),p=Math.max(p,v)}const g=Cx(l,e.width,c,d,u,p),m=new tt(c,d,u-c+1,p-d+1);r.push({id:h,pixelIndices:l,boundingBox:m,centerPoint:g})});const o=[...r].sort((h,l)=>t.roomConfig.colors.sortBy==="area"?l.pixelIndices.length-h.pixelIndices.length:h.id-l.id),a=this.assignColorsUsingFourColorAlgorithm(o,i.length,"raster");r.forEach(h=>{const l=a.get(h.id)||0,c=i[l],d={id:h.id,color:c,colorIndex:l,boundingBox:h.boundingBox,points:[],outlinePoints:[],polyPoints:[],centerPoint:h.centerPoint};this.roomGeometryMap.set(h.id,d)})}getRasterRoomPixels(e){return this.rasterRoomPixelsMap.get(e)}validateColorConfig(){const t=this.appService.roomConfig.colors,i=t.active.length,s=t.inactive.length,r=t.name.length,o=t.propertyTheme.length,a=t.selectionIndicatorBackground.length,h=t.selectionIndicatorIcon.length;i<4&&w.warn(`[FourColor] room.colors.active requires at least 4 colors for the four-color theorem, but got ${i}. Adjacent rooms may have the same color.`),s!==i&&w.warn(`[FourColor] room.colors.inactive length (${s}) does not match room.colors.active length (${i}). Using modulo for color assignment.`),r!==i&&w.warn(`[FourColor] room.colors.name length (${r}) does not match room.colors.active length (${i}). Using modulo for color assignment.`),o!==i&&w.warn(`[FourColor] room.colors.propertyTheme length (${o}) does not match room.colors.active length (${i}). Using modulo for color assignment.`),a!==i&&w.warn(`[FourColor] room.colors.selectionIndicatorBackground length (${a}) does not match room.colors.active length (${i}). Using modulo for color assignment.`),h!==i&&w.warn(`[FourColor] room.colors.selectionIndicatorIcon length (${h}) does not match room.colors.active length (${i}). Using modulo for color assignment.`)}assignColorsUsingFourColorAlgorithm(e,t,i){var d;const s=this.appService,r=((d=s.mapState)==null?void 0:d.id)??null;if(this.fourColorCache&&this.fourColorCache.mapId===r&&this.fourColorCache.colorMap.size===e.length)return w.debug("[FourColor] Using cached color map"),this.fourColorCache.colorMap;const o=s.getApp().config.map.adjacencyThreshold||3,a=s.roomConfig.colors.strategy,l=Ex(e,(u,p)=>{var g;if(i==="structured"){const m=u.outlinePoints,y=p.outlinePoints;return!m||!y?!1:Ja(m,y,o)}else{const m=u.pixels,y=p.pixels;if(!m||!y)return!1;const x=((g=s.mapState)==null?void 0:g.width)||0;return th(m,y,x,o)}},t,a);this.fourColorCache={mapId:r,colorMap:l};const c=new Array(t).fill(0);return l.forEach(u=>{c[u]++}),w.debug("[FourColor] Color distribution:",c),l}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[],this.obstacle.destroy(),this.free.destroy(),this.roomFill.destroy(),this.carpet.destroy(),this.chargingStation.destroy(),this.fourColorCache=null}}class gS extends L{constructor(t){super({isRenderGroup:!0});f(this,"commonPath");f(this,"chargePath");f(this,"transitionsPath");f(this,"mopPath");f(this,"mopPathTrack");f(this,"mopPathTrackContainer");f(this,"debugPoints");f(this,"pathData",null);f(this,"lastPointCount",0);f(this,"lastDrawnPosition",null);f(this,"isRealTimeDrawing",!1);f(this,"throttledUpdateLineWidth");f(this,"throttledHandleRobotPosition");f(this,"unsubscribeFns",[]);f(this,"handleRobotAnimationComplete",()=>{this.isRealTimeDrawing&&this.stopRealTimeDrawing()});this.appService=t,this.appService.appContainer.addToLayer(Bc,this),this.eventMode="none",this.commonPath=new U,this.chargePath=new U,this.transitionsPath=new U,this.mopPathTrackContainer=new L,this.mopPathTrackContainer.filters=[new gm],this.mopPathTrack=new U,this.mopPath=new U,this.debugPoints=new U,this.mopPathTrackContainer.addChild(this.mopPathTrack),this.addChild(this.mopPathTrackContainer),this.addChild(this.commonPath),this.addChild(this.chargePath),this.addChild(this.transitionsPath),this.addChild(this.mopPath),this.addChild(this.debugPoints),this.visible=t.runtimeSnapshot.showPath,this.commonPath.visible=t.pathConfig.commonPath.visible,this.chargePath.visible=t.pathConfig.chargePath.visible,this.transitionsPath.visible=t.pathConfig.transitionPath.visible,this.mopPathTrackContainer.visible=t.pathConfig.mopPath.trackVisible,this.mopPath.visible=t.pathConfig.mopPath.lineVisible,this.throttledUpdateLineWidth=_t(()=>{this.updateLineWidth()},50,{leading:!0,trailing:!0}),this.throttledHandleRobotPosition=_t(this.handleRobotPositionUpdate.bind(this),0),this.registerEventListeners()}registerEventListeners(){const{emitter:t}=this.appService;t.on("antiScale",this.throttledUpdateLineWidth),t.on("robotPositionUpdate",this.throttledHandleRobotPosition),t.on("robotAnimationComplete",this.handleRobotAnimationComplete);const i=Us(this.appService.config.path,()=>{this.pathData&&(this.redrawPaths(this.pathData),this.appService.getApp().renderOnceNextFrame())});this.unsubscribeFns.push(i)}handleRobotPositionUpdate(t){if(!this.isRealTimeDrawing||!this.lastDrawnPosition)return;const i=t.pathType||"common";let s=[];switch(i){case"common":s=[this.commonPath];break;case"charge":s=[this.chargePath];break;case"transitions":s=[this.transitionsPath];break;case"mop":s=[this.mopPathTrack,this.mopPath];break;default:s=[this.commonPath]}s.forEach(r=>{r.moveTo(this.lastDrawnPosition.x,this.lastDrawnPosition.y),r.lineTo(t.x,t.y),r.stroke()}),this.lastDrawnPosition={x:t.x,y:t.y}}updateLineWidth(){const t=this.appService;this.pathData&&t.pathConfig.lineWidthFixed&&this.redrawPaths(this.pathData)}redrawPaths(t){const{pathPoints:i}=t;if(this.commonPath.clear(),this.chargePath.clear(),this.transitionsPath.clear(),this.mopPathTrack.clear(),this.mopPath.clear(),this.debugPoints.clear(),!i||i.length===0)return;this.setupPathStyles(),this.drawPathSegments(this.simplifyPathPoints(i)),this.commonPath.stroke(),this.chargePath.stroke(),this.transitionsPath.stroke(),this.mopPathTrack.stroke(),this.mopPath.stroke(),this.appService.getDebuggerMode()&&this.drawDebugPoints(i)}setupPathStyles(){var r;const t=this.appService,i=t.pathConfig,s=o=>i.lineWidthFixed?t.getApp().toFixedSize(o):o;this.commonPath.setStrokeStyle({width:s(i.commonPath.width),color:i.commonPath.color,join:"round",cap:"round"}),this.chargePath.setStrokeStyle({width:s(i.chargePath.width),color:i.chargePath.color,join:"round",cap:"round"}),this.transitionsPath.setStrokeStyle({width:s(i.transitionPath.width),color:i.transitionPath.color,join:"round",cap:"round"}),this.mopPathTrack.setStrokeStyle({width:s(i.mopPath.trackWidth),color:i.mopPath.trackColor,alpha:1,join:"round",cap:"round"}),(r=this.mopPathTrackContainer.filters)!=null&&r[0]&&(this.mopPathTrackContainer.filters[0].alpha=i.mopPath.trackAlpha),this.mopPathTrackContainer.visible=i.mopPath.trackVisible,this.mopPath.setStrokeStyle({width:s(i.mopPath.lineWidth),color:i.mopPath.lineColor,join:"round",cap:"round"}),this.mopPath.visible=i.mopPath.lineVisible}drawPathSegments(t){let i=null,s=null;for(let r=0;r<t.length;r++){const o=t[r],a=o.type||"common";let h;switch(a){case"common":h=[this.commonPath];break;case"charge":h=[this.chargePath];break;case"transitions":h=[this.transitionsPath];break;case"mop":h=[this.mopPathTrack,this.mopPath];break;default:h=[this.commonPath]}r===0||a!==i?h.forEach(c=>c.moveTo(o.x,o.y)):s&&h.length===s.length&&h.every((c,d)=>c===s[d])&&h.forEach(c=>c.lineTo(o.x,o.y)),i=a,s=h}}simplifyPathPoints(t){const i=this.appService.pathConfig.simplifyTolerancePx;if(!i||i<=0||t.length<=2)return t;const s=this.appService.getApp().scaleMax||1,r=i/s,o=[];let a=0;for(let h=1;h<=t.length;h++)if(h===t.length||t[h].type!==t[a].type){const c=fx(t.slice(a,h),r);for(let d=0;d<c.length;d++)o.push(c[d]);a=h}return o}drawDebugPoints(t){const i={common:16711935,charge:65535,transitions:16776960,mop:65280},s=1;for(const r of t){const o=r.type||"common",a=i[o];this.debugPoints.rect(r.x-s/2,r.y-s/2,s,s),this.debugPoints.fill(a)}}updatePositionByOrigin(t,i){this.position.set(t,i)}drawFull(t){var i;w.debug("[Path] Draw Full Path",t),this.pathData=t,this.redrawPaths(t),this.lastPointCount=((i=t.pathPoints)==null?void 0:i.length)||0}drawIncremental(t){var o,a,h,l;const i=this.appService,s=this.lastPointCount,r=((o=t.pathPoints)==null?void 0:o.slice(s))||[];if(r.length>0)if(this.setupPathStyles(),w.debug("[Path] Draw Incremental Path",r),i.robotConfig.speed>0){if(this.isRealTimeDrawing=!0,s>0&&((a=this.pathData)!=null&&a.pathPoints)){const u=this.pathData.pathPoints[s-1];this.lastDrawnPosition={x:u.x,y:u.y}}}else this.drawNewPathSegments(r,s,t.pathPoints,(h=this.pathData)==null?void 0:h.pathPoints);this.pathData=t,this.lastPointCount=((l=t.pathPoints)==null?void 0:l.length)||0}drawNewPathSegments(t,i,s,r){if(!s||t.length===0)return;let o=null;i>0&&(r&&r[i-1]?o=r[i-1]:s[i-1]&&(o=s[i-1]));let a=null,h=null,l=!1;for(let c=0;c<t.length;c++){const d=t[c],u=d.type||"common";let p;switch(u){case"common":p=[this.commonPath];break;case"charge":p=[this.chargePath];break;case"transitions":p=[this.transitionsPath];break;case"mop":p=[this.mopPathTrack,this.mopPath];break;default:p=[this.commonPath]}u!==a||c===0?(h&&l&&h.forEach(m=>m.stroke()),a=u,h=p,l=!0,o&&c===0&&o.type===u?p.forEach(m=>{m.moveTo(o.x,o.y),m.lineTo(d.x,d.y)}):p.forEach(m=>m.moveTo(d.x,d.y))):p.forEach(m=>m.lineTo(d.x,d.y))}h&&l&&h.forEach(c=>c.stroke())}stopRealTimeDrawing(){this.isRealTimeDrawing=!1,this.lastDrawnPosition=null}clear(){this.commonPath.clear(),this.chargePath.clear(),this.transitionsPath.clear(),this.mopPathTrack.clear(),this.mopPath.clear(),this.debugPoints.clear(),this.pathData=null,this.lastPointCount=0,this.lastDrawnPosition=null,this.isRealTimeDrawing=!1}destroy(t){const{emitter:i}=this.appService;i.off("antiScale",this.throttledUpdateLineWidth),i.off("robotPositionUpdate",this.throttledHandleRobotPosition),i.off("robotAnimationComplete",this.handleRobotAnimationComplete),this.unsubscribeFns.forEach(s=>s()),this.unsubscribeFns=[],this.stopRealTimeDrawing(),super.destroy(t)}}class mS extends Zt{constructor(e){super(e),this.appService=e,this.initializeSprite()}async initializeSprite(){await this.loadTextureAndSetSize("robot",this.appService.robotConfig.icon)}async draw({x:e,y:t,rotation:i}){super.draw({x:e,y:t,rotation:i})}}const it=class it extends Ms{constructor(t,i){super(i||[]);f(this,"throttledUpdateScale");f(this,"fixedWidth",0);f(this,"fixedHeight",0);f(this,"isFixedSizeSet",!1);f(this,"sizeFixed",!0);f(this,"baselineScale",1);this.appService=t,this.anchor.set(.5),this.visible=!1,this.throttledUpdateScale=_t(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.registerScaleListener()}setFixedSize(t,i){this.fixedWidth=t,this.fixedHeight=i,this.isFixedSizeSet=!0,this.applySize()}setSizeFixed(t){this.sizeFixed=t,this.baselineScale=1,t&&this.isFixedSizeSet?this.applySize():!t&&this.isFixedSizeSet&&this.applySize()}set width(t){this.isFixedSizeSet||this.setFixedSize(t,this.fixedHeight||t)}set height(t){this.isFixedSizeSet||this.setFixedSize(this.fixedWidth||t,t)}get width(){return this.fixedWidth||super.width}get height(){return this.fixedHeight||super.height}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}applySize(){if(!this.isFixedSizeSet||!this.textures||this.textures.length===0||!this.textures[0]||this.textures[0].width===0||this.textures[0].height===0)return;const t=this.textures[0],i=this.fixedWidth/t.width,s=this.fixedHeight/t.height;if(this.sizeFixed){const r=this.appService.currentScale;if(r===0||!isFinite(r)){const h=i,l=s;super.scale.set(h,l);return}const o=i/r,a=s/r;super.scale.set(o,a)}else super.scale.set(i/this.baselineScale,s/this.baselineScale)}updateScale(t){this.sizeFixed&&(this.isFixedSizeSet?this.applySize():t!==0&&super.scale.set(1/t))}static async loadAnimationTextures(t,i,s="sleep_",r=96){try{const a=await(await fetch(t)).json();a.meta&&(a.meta.image=i),await N.load(i);const h=G.from(i),l=new Kn(h.source,a);await l.parse();const c=[];for(let d=0;d<r;d++){const u=d.toString().padStart(3,"0"),p=`${s}${u}.png`,g=l.textures[p];g?c.push(g):w.warn(`[EnhancedAnimatedSprite] Frame not found: ${p}`)}return c}catch(o){return w.error("[EnhancedAnimatedSprite] Failed to load textures:",o),[]}}setupAnimation(t){t.sizeFixed!==void 0&&this.setSizeFixed(t.sizeFixed),this.setFixedSize(t.width,t.height),this.animationSpeed=.5,this.loop=!0,w.log(`Animation setup complete, visible=${this.visible}, scale=(${this.scale.x.toFixed(3)}, ${this.scale.y.toFixed(3)})`)}draw(t,i){const{x:s,y:r}=t;i&&!this.visible?this.visible=i():!i&&!this.visible&&(this.visible=!0),this.position.set(s,r)}play(){this.textures&&this.textures.length>0&&(super.play(),it.animatedSprites.add(this),it.startAnimationTicker())}stop(){super.stop(),it.animatedSprites.delete(this),it.updateAnimationTicker()}set textures(t){super.textures=t,this.isFixedSizeSet&&t&&t.length>0&&t[0]&&t[0].width>0&&t[0].height>0&&this.applySize()}get textures(){return super.textures}static startAnimationTicker(){var t;(t=it.animationTicker)!=null&&t.started||(it.animationTicker||(it.animationTicker=new yt,it.animationTicker.maxFPS=24,it.animationTicker.add(()=>{const i=it.animatedSprites.values().next().value;i&&it.updateAnimations(i.appService)})),it.animationTicker.start(),w.log("🎬 [AnimationTicker] Started animation ticker"))}static updateAnimationTicker(){it.animatedSprites.size>0?it.startAnimationTicker():it.stopAnimationTicker()}static stopAnimationTicker(){var t;(t=it.animationTicker)!=null&&t.started&&(w.log("⏸️ [AnimationTicker] Stopped animation ticker"),it.animationTicker.stop())}static updateAnimations(t){if(it.animatedSprites.size===0)return;const i=t.getApp();i.renderer.render(i.stage)}destroy(t){it.animatedSprites.delete(this),it.updateAnimationTicker(),this.appService.emitter.off("antiScale",this.throttledUpdateScale),super.destroy(t)}};f(it,"animationTicker",null),f(it,"animatedSprites",new Set);let Is=it;class Qr extends Is{constructor(t,i){super(t,i);f(this,"unsubscribeFns",[]);f(this,"throttledUpdateOffset");f(this,"fixedOffsetX",0);f(this,"fixedOffsetY",0);this.appService=t,this.throttledUpdateOffset=_t(this.updateOffset.bind(this),30,{leading:!0,trailing:!0}),this.initializeAnimation()}static async create(t){const i=t.robotConfig,s=await Is.loadAnimationTextures(i.sleepAnimation.jsonSrc,i.sleepAnimation.imageSrc,i.sleepAnimation.framePrefix,i.sleepAnimation.frameCount);s.length===0&&(w.warn("No textures loaded for sleep animation"),s.push(G.EMPTY));const r=new Qr(t,s);return r.setupAnimation({width:i.sleepAnimation.width,height:i.sleepAnimation.height,sizeFixed:i.sleepAnimation.sizeFixed}),r}initializeAnimation(){this.visible=!1,this.fixedOffsetX=this.appService.robotConfig.sleepAnimation.offsetX,this.fixedOffsetY=this.appService.robotConfig.sleepAnimation.offsetY,this.appService.emitter.on("antiScale",this.throttledUpdateOffset);const t=W(this.appService.runtime,"showRobotSleepAnimation",i=>{w.log(`[runtime] showRobotSleepAnimation: ${i}`),this.updateVisibility()});this.unsubscribeFns.push(t)}shouldShow(){const t=this.appService.runtimeSnapshot.showRobotSleepAnimation,i=this.parent,s=i?i.visible:!1,r=i&&(i.x!==0||i.y!==0);return t&&s&&!!r}updateVisibility(){const t=this.shouldShow();t&&!this.visible?(this.visible=!0,this.textures&&this.textures.length>0&&this.play()):!t&&this.visible?(this.visible=!1,this.stop()):!t&&this.playing&&this.stop()}updateOffset(){}draw(t){const i=this.appService.getApp().toFixedSize(this.appService.robotConfig.sleepAnimation.offsetX),s=this.appService.getApp().toFixedSize(this.appService.robotConfig.sleepAnimation.offsetY),r={...t,x:t.x+i,y:t.y+s};super.draw(r,()=>this.shouldShow()),this.updateVisibility()}onRobotVisibilityChanged(){this.updateVisibility()}set visible(t){const i=super.visible;super.visible=t,t&&!i&&this.textures&&this.textures.length>0?this.play():!t&&i&&this.playing&&this.stop()}get visible(){return super.visible}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateOffset),this.unsubscribeFns.forEach(i=>i()),this.unsubscribeFns=[],this.stop(),super.destroy(t)}}class yS extends U{constructor(t){super();f(this,"currentPosition",null);f(this,"animationStartTime",0);f(this,"isAnimating",!1);f(this,"handleScaleChange",()=>{this.redraw()});f(this,"updateAnimation",()=>{if(!this.currentPosition||!this.isAnimating||!this.visible)return;const t=this.appService,i=t.robotConfig.pulseCircle,r=(Date.now()-this.animationStartTime)%i.duration/i.duration,{minScale:o,maxScale:a,minAlpha:h,maxAlpha:l}=i,c=o+(a-o)*(Math.sin(r*Math.PI*2)*.5+.5),d=l-(l-h)*(c-o)/(a-o);super.clear();const{size:u,color:p,strokeWidth:g,strokeColor:m,sizeFixed:y}=i,S=(y?t.getApp().toFixedSize(u/2):u/2)*c,v=t.getApp().toFixedSize(g);this.setFillStyle({color:p,alpha:d}),this.circle(this.currentPosition.x,this.currentPosition.y,S).fill().stroke({color:m,width:v,alpha:d,cap:"round",join:"round"})});this.appService=t,this.setupAntiScaleListener()}setupAntiScaleListener(){this.appService.emitter.on("antiScale",this.handleScaleChange)}draw(t){this.currentPosition=t,this.isAnimating||this.startAnimation(),this.redraw()}startAnimation(){const t=this.appService;this.isAnimating||(this.isAnimating=!0,this.animationStartTime=Date.now(),t.getApp().ticker.add(this.updateAnimation,this),t.getApp().requestRender("pulse-circle-animation",!0))}stopAnimation(){const t=this.appService;this.isAnimating&&(this.isAnimating=!1,t.getApp().ticker.remove(this.updateAnimation,this),t.getApp().stopRender("pulse-circle-animation"))}redraw(){this.currentPosition&&this.isAnimating&&this.updateAnimation()}clearCircle(){super.clear()}remove(){this.stopAnimation(),this.clearCircle(),this.currentPosition=null}destroy(){this.stopAnimation(),this.appService.emitter.off("antiScale",this.handleScaleChange),super.destroy()}}class xS extends L{constructor(t){super();f(this,"robot");f(this,"ring");f(this,"pulseCircle");f(this,"sleepAnimation",null);f(this,"unsubscribeFns",[]);f(this,"clickHandler");f(this,"targetPosition",null);f(this,"targetRotation",null);f(this,"isMoving",!1);f(this,"pathQueue",[]);f(this,"lastPosition",null);f(this,"currentPathType");f(this,"lastUpdateTime",0);f(this,"isCleared",!1);this.appService=t,t.appContainer.addToLayer(Oc,this),this.visible=t.runtime.showRobot,this.ring=new Wc(this.appService,{config:this.appService.robotConfig.ring}),this.ring.visible=this.appService.runtime.showRobotRing,this.addChild(this.ring),this.pulseCircle=new yS(this.appService),this.pulseCircle.visible=t.runtime.showRobotPulseCircle,this.addChild(this.pulseCircle),this.robot=new mS(this.appService),this.addChild(this.robot),this.lastUpdateTime=Date.now(),this.appService.robotConfig.speed>0&&this.appService.getApp().ticker.add(this.update,this);const s=W(this.appService.runtime,"showRobotRing",o=>{w.log(`[runtime] showRobotRing: ${o}`),this.ring.visible=o});this.unsubscribeFns.push(s);const r=W(this.appService.runtime,"showRobotPulseCircle",o=>{w.log(`[runtime] showRobotPulseCircle: ${o}`),o?(this.lastPosition&&this.pulseCircle.draw(this.lastPosition),this.pulseCircle.visible=!0):(this.pulseCircle.remove(),this.pulseCircle.visible=!1)});this.unsubscribeFns.push(r),this.initClickInteraction()}async initializeSleepAnimation(){try{this.sleepAnimation=await Qr.create(this.appService),this.addChild(this.sleepAnimation),w.log("Sleep animation added to robot")}catch(t){w.error("Failed to initialize sleep animation:",t)}}updatePositionByOrigin(t,i){this.position.set(t,i)}async draw({x:t,y:i,rotation:s}){this.isCleared&&(this.robot.visible=!0,this.ring.visible=this.appService.runtime.showRobotRing,this.pulseCircle.visible=this.appService.runtime.showRobotPulseCircle,this.sleepAnimation&&(this.sleepAnimation.visible=!0),this.isCleared=!1),this.ring.draw({x:t,y:i}),this.pulseCircle.draw({x:t,y:i}),await this.robot.draw({x:t,y:i,rotation:s}),this.sleepAnimation||await this.initializeSleepAnimation(),this.sleepAnimation.draw({x:t,y:i}),this.lastPosition={x:t,y:i},this.sleepAnimation.draw({x:t,y:i}),this.lastPosition={x:t,y:i}}initClickInteraction(){const{enableRobotClick:t}=this.appService.interactionConfig;t?this.clickHandler||(this.clickHandler=new vt(this.robot,{onClick:()=>{var s;const i=this.getCurrentPosition();i&&((s=this.appService.events)!=null&&s.onClickRobot)&&this.appService.events.onClickRobot({...i,rotation:this.robot.rotation})}})):this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=void 0,this.robot.interactive=!1,this.robot.eventMode="none")}getCurrentPosition(){return this.lastPosition?this.appService.fixPrecision({...this.lastPosition}):null}moveTo(t){this.pathQueue.push(t),this.isMoving||this.processNextPathPoint()}batchProcessQueue(t=!1){if(this.pathQueue.length===0)return;const i=[...this.pathQueue];if(t){const s=i[i.length-1];this.robot.position.set(s.x,s.y),s.rotation!==void 0&&(this.robot.rotation=s.rotation),this.lastPosition={x:s.x,y:s.y},this.pathQueue=[],this.isMoving=!1,this.targetPosition=null}else this.pathQueue.splice(0,i.length),this.pathQueue.length===0?(this.isMoving=!1,this.targetPosition=null):this.processNextPathPoint()}processNextPathPoint(){if(this.pathQueue.length===0){this.isMoving=!1,this.currentPathType=void 0,this.stopRobotAnimation(),this.appService.emitter.emit("robotAnimationComplete");return}this.isMoving||this.startRobotAnimation(),this.isMoving=!0;const t=this.pathQueue[0];this.targetPosition={x:t.x,y:t.y},this.currentPathType=t.type,t.rotation!==void 0&&(this.targetRotation=t.rotation),this.lastPosition||(this.lastPosition={x:this.robot.x,y:this.robot.y})}update(){const t=Date.now();if(this.lastUpdateTime===0){this.lastUpdateTime=t;return}let i=t-this.lastUpdateTime;if(this.lastUpdateTime=t,i>500&&(i=16.67),this.targetPosition){const s=this.targetPosition.x-this.robot.x,r=this.targetPosition.y-this.robot.y,o=Math.sqrt(s*s+r*r),a=this.appService.robotConfig.speed,h=this.appService.coords.toPixels(et(a));if(a===0){this.robot.position.set(this.targetPosition.x,this.targetPosition.y),this.targetRotation!==null&&(this.robot.rotation=this.targetRotation,this.targetRotation=null),this.targetPosition=null,this.lastPosition={x:this.robot.x,y:this.robot.y},this.pathQueue.shift(),this.processNextPathPoint();return}const l=h*(i/1e3);o<l?(this.robot.position.set(this.targetPosition.x,this.targetPosition.y),this.targetRotation!==null&&(this.robot.rotation=this.targetRotation,this.targetRotation=null),this.targetPosition=null,this.lastPosition={x:this.robot.x,y:this.robot.y},this.pathQueue.shift(),this.processNextPathPoint()):(this.robot.x+=s*(l/o),this.robot.y+=r*(l/o),this.appService.emitter.emit("robotPositionUpdate",{x:this.robot.x,y:this.robot.y,pathType:this.currentPathType}),this.lastPosition={x:this.robot.x,y:this.robot.y})}}startRobotAnimation(){this.appService.getApp().requestRender("robot-animation",!0)}set visible(t){super.visible=t,this.sleepAnimation&&this.sleepAnimation.onRobotVisibilityChanged()}get visible(){return super.visible}stopRobotAnimation(){this.appService.getApp().stopRender("robot-animation")}remove(){this.pathQueue=[],this.isMoving=!1,this.targetPosition=null,this.stopRobotAnimation()}clear(){this.remove(),this.robot.visible=!1,this.ring.visible=!1,this.pulseCircle.remove(),this.sleepAnimation&&(this.sleepAnimation.visible=!1),this.lastPosition=null,this.isCleared=!0}destroy(t){this.unsubscribeFns.forEach(s=>s()),this.unsubscribeFns=[],this.stopRobotAnimation(),this.appService.robotConfig.speed>0&&this.appService.getApp().ticker.remove(this.update,this),this.ring.destroy(),this.pulseCircle.destroy(),this.clickHandler&&this.clickHandler.destroy(),super.destroy(t)}}class SS{constructor(e){f(this,"path");f(this,"robot");f(this,"unsubscribeFns",[]);f(this,"lastDrawnPathData",null);f(this,"pointsSinceFullRedraw",0);this.appService=e,this.path=new gS(this.appService),this.robot=new xS(this.appService);const t=W(e.runtime,"showPath",s=>{w.log(`[runtime] showPath: ${s}`),this.path.visible=s}),i=W(e.runtime,"showRobot",s=>{w.log(`[runtime] showRobot: ${s}`),this.robot.visible=s});this.unsubscribeFns.push(t,i)}draw(e){var s,r,o;const t=(s=e.pathHeader)==null?void 0:s.pathId,i=(o=(r=this.lastDrawnPathData)==null?void 0:r.pathHeader)==null?void 0:o.pathId;this.lastDrawnPathData&&t!==i&&(this.path.clear(),this.lastDrawnPathData=null),this.shouldUseIncrementalDraw(e)?this.incrementalDraw(e):this.fullDraw(e),this.lastDrawnPathData=e}shouldUseIncrementalDraw(e){var l,c,d,u;if(!this.lastDrawnPathData)return!1;const t=(l=e.pathHeader)==null?void 0:l.pathId,i=(c=this.lastDrawnPathData.pathHeader)==null?void 0:c.pathId;if(t!==i)return!1;const s=((d=e.pathPoints)==null?void 0:d.length)||0,r=((u=this.lastDrawnPathData.pathPoints)==null?void 0:u.length)||0,o=s-r,a=this.appService.pathConfig.incrementalThreshold;if(o<=0||o>a)return!1;const h=this.appService.pathConfig.consolidateThreshold;return!(h>0&&this.pointsSinceFullRedraw+o>h)}fullDraw(e){if(this.path.stopRealTimeDrawing(),this.path.drawFull(e),this.pointsSinceFullRedraw=0,e.pathPoints&&e.pathPoints.length>0){const t=e.pathPoints[e.pathPoints.length-1];this.moveRobotToPoint(t,e.pathHeader.direction,!1)}else this.robot.clear()}convertToRobotPoint(e,t){const i=t+this.appService.robotConfig.rotationCorrection;return{x:e.x,y:e.y,rotation:i*Math.PI/180,type:e.type}}moveRobotToPoint(e,t,i=!0){const s=this.convertToRobotPoint(e,t);i?this.robot.moveTo(s):(this.robot.remove(),this.robot.draw(s))}incrementalDraw(e){var o;if(!this.lastDrawnPathData||!e.pathPoints)return;this.path.drawIncremental(e);const t=((o=this.lastDrawnPathData.pathPoints)==null?void 0:o.length)||0,i=e.pathPoints.slice(t);if(this.pointsSinceFullRedraw+=i.length,i.length===0)return;if(this.appService.robotConfig.speed>0)i.forEach(a=>{this.moveRobotToPoint(a,e.pathHeader.direction,!0)});else{const a=i[i.length-1];this.moveRobotToPoint(a,e.pathHeader.direction,!1)}}batchProcessRobotQueue(e=!1){this.robot.batchProcessQueue(e)}updatePositionByOrigin(e,t){this.path.updatePositionByOrigin(e,t),this.robot.updatePositionByOrigin(e,t)}clear(){this.lastDrawnPathData=null,this.pointsSinceFullRedraw=0,this.path.clear(),this.robot.clear()}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[],this.path.destroy(),this.robot.destroy()}}class vS extends L{constructor(t){super();f(this,"colorGradients",[]);f(this,"cellSize",2);this.appService=t,this.appService.appContainer.addToLayer(Fc,this);const i=this.appService.heatMapConfig;this.colorGradients=i.colorGradients.map(s=>new rt(s).toArray().slice(0,3).join(",")),this.cellSize=i.cellSize}draw(t,i=.8){this.removeChildren();const{useGradient:s}=this.appService.heatMapConfig,r=s?this.gradientDrawing(t):this.gridDrawing(t);this.croppingHeatmap(r),r.alpha=i,this.addChild(r)}croppingHeatmap(t){var a;const i=((a=this.appService.mapState)==null?void 0:a.origin)||{x:0,y:0},r=this.appService.mapManager.roomFill.children.filter(h=>h instanceof U),o=new U;for(const h of r)o.context.instructions.push(...h.context.instructions);o.context.dirty=!0,o.position.set(-i.x,-i.y),t.setMask({mask:o}),this.addChild(o)}gridDrawing(t){const i=[],s=[],r=t.length,o=t[0].length;for(let c=0;c<r;c++)for(let d=0;d<o;d++){const u=t[c][d],p=this.cellSize/2,g=u.x-p,m=u.y-p,y=u.x+p,x=u.y+p;i.push(g,m),s.push(u.signal),i.push(y,m),s.push(u.signal),i.push(y,x),s.push(u.signal),i.push(g,m),s.push(u.signal),i.push(y,x),s.push(u.signal),i.push(g,x),s.push(u.signal)}const a=new Oi({attributes:{aPosition:new Float32Array(i),aSignal:new Float32Array(s)}}),h=new Be({glProgram:new ii({vertex:`
503
+ in vec2 aPosition;
504
+ in float aSignal;
505
+ uniform mat3 uProjectionMatrix;
506
+ uniform mat3 uWorldTransformMatrix;
507
+ uniform mat3 uTransformMatrix;
508
+
509
+ out float vSignal;
510
+
511
+ void main() {
512
+ mat3 mvp = uProjectionMatrix * uWorldTransformMatrix * uTransformMatrix;
513
+ gl_Position = vec4((mvp * vec3(aPosition, 1.0)).xy, 0.0, 1.0);
514
+ vSignal = aSignal;
515
+ }
516
+ `,fragment:`
517
+ precision mediump float;
518
+
519
+ in float vSignal;
520
+
521
+ void main() {
522
+ vec3 color;
523
+
524
+ if (vSignal > 0.875) {
525
+ color = vec3(${this.colorGradients[0]});
526
+ } else if (vSignal > 0.75) {
527
+ color = vec3(${this.colorGradients[1]});
528
+ } else if (vSignal > 0.625) {
529
+ color = vec3(${this.colorGradients[2]});
530
+ } else if (vSignal > 0.5) {
531
+ color = vec3(${this.colorGradients[3]});
532
+ } else if (vSignal > 0.375) {
533
+ color = vec3(${this.colorGradients[4]});
534
+ } else if (vSignal > 0.25) {
535
+ color = vec3(${this.colorGradients[5]});
536
+ } else if (vSignal > 0.125) {
537
+ color = vec3(${this.colorGradients[6]});
538
+ } else {
539
+ color = vec3(${this.colorGradients[7]});
540
+ }
541
+ gl_FragColor = vec4(color, 1.0);
542
+ }
543
+ `}),gpuProgram:new de({vertex:{source:`
544
+ struct GlobalUniforms {
545
+ uProjectionMatrix: mat3x3<f32>,
546
+ uWorldTransformMatrix: mat3x3<f32>,
547
+ uWorldColorAlpha: vec4<f32>,
548
+ uResolution: vec2<f32>,
549
+ };
550
+
551
+ struct LocalUniforms {
552
+ uTransformMatrix: mat3x3<f32>,
553
+ uColor: vec4<f32>,
554
+ uRound: f32,
555
+ };
556
+
557
+ @group(0) @binding(0) var<uniform> globalUniforms: GlobalUniforms;
558
+ @group(1) @binding(0) var<uniform> localUniforms: LocalUniforms;
559
+
560
+ struct VSOutput {
561
+ @builtin(position) position: vec4<f32>,
562
+ @location(0) vSignal: f32,
563
+ };
564
+
565
+ @vertex
566
+ fn main(
567
+ @location(0) aPosition: vec2<f32>,
568
+ @location(1) aSignal: f32
569
+ ) -> VSOutput {
570
+ var output: VSOutput;
571
+ let mvp = globalUniforms.uProjectionMatrix * globalUniforms.uWorldTransformMatrix * localUniforms.uTransformMatrix;
572
+ output.position = vec4((mvp * vec3<f32>(aPosition, 1.0)).xy, 0.0, 1.0);
573
+ output.vSignal = aSignal;
574
+ return output;
575
+ }
576
+ `,entryPoint:"main"},fragment:{source:`
577
+ @fragment
578
+ fn main(@location(0) vSignal: f32) -> @location(0) vec4<f32> {
579
+ var color: vec3<f32>;
580
+
581
+ if (vSignal > 0.875) {
582
+ color = vec3<f32>(${this.colorGradients[0]});
583
+ } else if (vSignal > 0.75) {
584
+ color = vec3<f32>(${this.colorGradients[1]});
585
+ } else if (vSignal > 0.625) {
586
+ color = vec3<f32>(${this.colorGradients[2]});
587
+ } else if (vSignal > 0.5) {
588
+ color = vec3<f32>(${this.colorGradients[3]});
589
+ } else if (vSignal > 0.375) {
590
+ color = vec3<f32>(${this.colorGradients[4]});
591
+ } else if (vSignal > 0.25) {
592
+ color = vec3<f32>(${this.colorGradients[5]});
593
+ } else if (vSignal > 0.125) {
594
+ color = vec3<f32>(${this.colorGradients[6]});
595
+ } else {
596
+ color = vec3<f32>(${this.colorGradients[7]});
597
+ }
598
+
599
+ return vec4<f32>(color, 1.0);
600
+ }
601
+ `,entryPoint:"main"}})}),l=new Ba({geometry:a,shader:h});return l.alpha=.8,l}gradientDrawing(t){const i=[],s=[],r=t.length,o=t[0].length;for(let c=0;c<r;c++)for(let d=0;d<o;d++){const u=t[c][d],p=this.cellSize/2,g=(_,R)=>_<0||_>=r||R<0||R>=o?u.signal:t[_][R].signal,m=(g(c-1,d-1)+g(c-1,d)+g(c,d-1)+u.signal)/4,y=(g(c-1,d)+g(c-1,d+1)+u.signal+g(c,d+1))/4,x=(u.signal+g(c,d+1)+g(c+1,d)+g(c+1,d+1))/4,S=(g(c,d-1)+u.signal+g(c+1,d-1)+g(c+1,d))/4,v=u.x-p,b=u.y-p,P=u.x+p,C=u.y+p;i.push(v,b,P,b,P,C),s.push(m,y,x),i.push(v,b,P,C,v,C),s.push(m,x,S)}const a=new Oi({attributes:{aPosition:new Float32Array(i),aSignal:new Float32Array(s)}}),h=new Be({glProgram:new ii({vertex:`
602
+ in vec2 aPosition;
603
+ in float aSignal;
604
+ uniform mat3 uProjectionMatrix;
605
+ uniform mat3 uWorldTransformMatrix;
606
+ uniform mat3 uTransformMatrix;
607
+
608
+ out float vSignal;
609
+
610
+ void main() {
611
+ mat3 mvp = uProjectionMatrix * uWorldTransformMatrix * uTransformMatrix;
612
+ gl_Position = vec4((mvp * vec3(aPosition, 1.0)).xy, 0.0, 1.0);
613
+ vSignal = aSignal;
614
+ }
615
+ `,fragment:`
616
+ precision mediump float;
617
+
618
+ in float vSignal;
619
+
620
+ // 颜色插值函数
621
+ vec3 interpolateColor(vec3 color1, vec3 color2, float t) {
622
+ return mix(color1, color2, t);
623
+ }
624
+
625
+ void main() {
626
+ vec3 color;
627
+ float signal = clamp(vSignal, 0.0, 1.0);
628
+
629
+ vec3 color1 = vec3(${this.colorGradients[7]});
630
+ vec3 color2 = vec3(${this.colorGradients[6]});
631
+ vec3 color3 = vec3(${this.colorGradients[5]});
632
+ vec3 color4 = vec3(${this.colorGradients[4]});
633
+ vec3 color5 = vec3(${this.colorGradients[3]});
634
+ vec3 color6 = vec3(${this.colorGradients[2]});
635
+ vec3 color7 = vec3(${this.colorGradients[1]});
636
+ vec3 color8 = vec3(${this.colorGradients[0]});
637
+
638
+ if (signal <= 0.125) {
639
+ float t = signal / 0.125;
640
+ color = interpolateColor(color1, color2, t);
641
+ } else if (signal <= 0.25) {
642
+ float t = (signal - 0.125) / 0.125;
643
+ color = interpolateColor(color2, color3, t);
644
+ } else if (signal <= 0.375) {
645
+ float t = (signal - 0.25) / 0.125;
646
+ color = interpolateColor(color3, color4, t);
647
+ } else if (signal <= 0.5) {
648
+ float t = (signal - 0.375) / 0.125;
649
+ color = interpolateColor(color4, color5, t);
650
+ } else if (signal <= 0.625) {
651
+ float t = (signal - 0.5) / 0.125;
652
+ color = interpolateColor(color5, color6, t);
653
+ } else if (signal <= 0.75) {
654
+ float t = (signal - 0.625) / 0.125;
655
+ color = interpolateColor(color6, color7, t);
656
+ } else if (signal <= 0.875) {
657
+ float t = (signal - 0.75) / 0.125;
658
+ color = interpolateColor(color7, color8, t);
659
+ } else {
660
+ color = color8;
661
+ }
662
+
663
+ gl_FragColor = vec4(color, 1.0);
664
+ }
665
+ `}),gpuProgram:new de({vertex:{source:`
666
+ struct GlobalUniforms {
667
+ uProjectionMatrix: mat3x3<f32>,
668
+ uWorldTransformMatrix: mat3x3<f32>,
669
+ uWorldColorAlpha: vec4<f32>,
670
+ uResolution: vec2<f32>,
671
+ };
672
+
673
+ struct LocalUniforms {
674
+ uTransformMatrix: mat3x3<f32>,
675
+ uColor: vec4<f32>,
676
+ uRound: f32,
677
+ };
678
+
679
+ @group(0) @binding(0) var<uniform> globalUniforms: GlobalUniforms;
680
+ @group(1) @binding(0) var<uniform> localUniforms: LocalUniforms;
681
+
682
+ struct VSOutput {
683
+ @builtin(position) position: vec4<f32>,
684
+ @location(0) vSignal: f32,
685
+ };
686
+
687
+ @vertex
688
+ fn main(
689
+ @location(0) aPosition: vec2<f32>,
690
+ @location(1) aSignal: f32
691
+ ) -> VSOutput {
692
+ var output: VSOutput;
693
+ let mvp = globalUniforms.uProjectionMatrix * globalUniforms.uWorldTransformMatrix * localUniforms.uTransformMatrix;
694
+ output.position = vec4((mvp * vec3<f32>(aPosition, 1.0)).xy, 0.0, 1.0);
695
+ output.vSignal = aSignal;
696
+ return output;
697
+ }
698
+ `,entryPoint:"main"},fragment:{source:`
699
+ fn interpolateColor(color1: vec3<f32>, color2: vec3<f32>, t: f32) -> vec3<f32> {
700
+ return mix(color1, color2, t);
701
+ }
702
+
703
+ @fragment
704
+ fn main(@location(0) vSignal: f32) -> @location(0) vec4<f32> {
705
+ var color: vec3<f32>;
706
+ let signal = clamp(vSignal, 0.0, 1.0);
707
+
708
+ let color1 = vec3<f32>(${this.colorGradients[7]});
709
+ let color2 = vec3<f32>(${this.colorGradients[6]});
710
+ let color3 = vec3<f32>(${this.colorGradients[5]});
711
+ let color4 = vec3<f32>(${this.colorGradients[4]});
712
+ let color5 = vec3<f32>(${this.colorGradients[3]});
713
+ let color6 = vec3<f32>(${this.colorGradients[2]});
714
+ let color7 = vec3<f32>(${this.colorGradients[1]});
715
+ let color8 = vec3<f32>(${this.colorGradients[0]});
716
+
717
+ if (signal <= 0.125) {
718
+ let t = signal / 0.125;
719
+ color = interpolateColor(color1, color2, t);
720
+ } else if (signal <= 0.25) {
721
+ let t = (signal - 0.125) / 0.125;
722
+ color = interpolateColor(color2, color3, t);
723
+ } else if (signal <= 0.375) {
724
+ let t = (signal - 0.25) / 0.125;
725
+ color = interpolateColor(color3, color4, t);
726
+ } else if (signal <= 0.5) {
727
+ let t = (signal - 0.375) / 0.125;
728
+ color = interpolateColor(color4, color5, t);
729
+ } else if (signal <= 0.625) {
730
+ let t = (signal - 0.5) / 0.125;
731
+ color = interpolateColor(color5, color6, t);
732
+ } else if (signal <= 0.75) {
733
+ let t = (signal - 0.625) / 0.125;
734
+ color = interpolateColor(color6, color7, t);
735
+ } else if (signal <= 0.875) {
736
+ let t = (signal - 0.75) / 0.125;
737
+ color = interpolateColor(color7, color8, t);
738
+ } else {
739
+ color = color8;
740
+ }
741
+
742
+ return vec4<f32>(color, 1.0);
743
+ }
744
+ `,entryPoint:"main"}})}),l=new Ba({geometry:a,shader:h});return l.alpha=.8,l}updatePositionByOrigin(t,i){this.position.set(t,i)}clear(){this.removeChildren()}destroy(){this.removeChildren(),this.cacheAsTexture(!1)}}class bS{constructor(e){f(this,"heatmap");f(this,"pointsTopLeftOrigin",[]);f(this,"signalGrid",[]);f(this,"cellSize",2);f(this,"maxDistance",14);f(this,"smoothIterations",10);f(this,"heatmapAlpha",.8);f(this,"isHeatmapDrawn",!1);f(this,"loadTimer",null);f(this,"pendingPoints",null);this.appService=e,this.heatmap=new vS(e);const t=e.heatMapConfig;this.cellSize=t.cellSize,this.maxDistance=t.maxDistance,this.smoothIterations=t.smoothIterations,this.heatmapAlpha=t.heatmapAlpha}draw(e){if(e.length===0){this.clear();return}const t=this.appService;if(!t.isMapDrawn){this.pendingPoints=e;return}this.pendingPoints=null;const{minX:i,minY:s}=t.mapManager.mapBounds,r=e.map(o=>({x:+(o.x-i).toFixed(0),y:+(o.y-s).toFixed(0),signal:o.signal}));this.signalGrid=this.calculateInterpolatedSignal(r),this.heatmap.draw(this.signalGrid,this.heatmapAlpha),this.isHeatmapDrawn=!0}clear(){this.pendingPoints=null,this.pointsTopLeftOrigin=[],this.signalGrid=[],this.heatmap.clear(),this.isHeatmapDrawn=!1}onMapLoaded(){this.loadTimer||(this.pendingPoints&&this.draw(this.pendingPoints),this.loadTimer=setTimeout(()=>{this.loadTimer=null},200))}calculateInterpolatedSignal(e){var p;const t=this.appService,i=((p=t.mapState)==null?void 0:p.origin)||{x:0,y:0};let{minX:s,minY:r,maxX:o,maxY:a}=t.mapManager.mapBounds;r=r-i.y,s=s-i.x,a=a-i.y,o=o-i.x;const h=Math.ceil((a-r)/this.cellSize),l=Math.ceil((o-s)/this.cellSize),c=Array(h).fill(null).map(()=>Array(l).fill(null));for(let g=0;g<h;g++){const m=r+g*this.cellSize+this.cellSize/2,y=Math.min(this.cellSize,a-(m-this.cellSize/2));for(let x=0;x<l;x++){const S=s+x*this.cellSize+this.cellSize/2,v=Math.min(this.cellSize,o-(S-this.cellSize/2));let b=0,P=!1;for(let C=0;C<e.length;C++){const _=e[C];if(Math.abs(S-_.x)<=v/2&&Math.abs(m-_.y)<=y/2){const R=1-_.signal/7;b=Math.round(Math.max(b,R)*10)/10,P=!0}}c[g][x]={x:S,y:m,signal:b,hasPoint:P}}}const d=(g,m)=>{if(e.length===0)return 0;let y=0,x=0;for(const S of e){const v=Math.sqrt((g-S.x)**2+(m-S.y)**2);if(v<=this.maxDistance){const b=1/(1+v),P=1-S.signal/7;x+=b*P,y+=b}}return y===0?0:Math.round(x/y*1e3)/1e3},u=(g,m=1)=>{for(let y=0;y<m;y++){const x=g.map(S=>[...S]);for(let S=1;S<h-1;S++)for(let v=1;v<l-1;v++)if(!g[S][v].hasPoint){let b=0,P=0;const C=4;for(let _=-C;_<=C;_++)for(let R=-C;R<=C;R++){if(_===0&&R===0)continue;const M=S+_,T=v+R;if(M>=0&&M<h&&T>=0&&T<l){const E=1/(1+Math.sqrt(_*_+R*R)*.3);b+=g[M][T].signal*E,P+=E}}if(P>0){const _=b/P,R=.6,M=.4;x[S][v].signal=g[S][v].signal*R+_*M,x[S][v].signal>.1&&(x[S][v].signal=Math.max(x[S][v].signal,.2))}}for(let S=0;S<h;S++)for(let v=0;v<l;v++)g[S][v].signal=x[S][v].signal}};for(let g=0;g<h;g++)for(let m=0;m<l;m++){const y=c[g][m];y.hasPoint||(y.signal=d(y.x,y.y))}return u(c,this.smoothIterations),c}updatePositionByOrigin(e,t){this.heatmap.updatePositionByOrigin(e,t)}destroy(){this.heatmap.destroy()}}class Jr extends U{constructor(t,i){super();f(this,"fillOptions");f(this,"isDragging",!1);f(this,"dragStartPosition",null);f(this,"gestureSession",null);f(this,"handlePointerDown",t=>{t.stopPropagation(),this.startDragging(t)});f(this,"handleDragPointerMove",t=>{var i,s;!this.isDragging||!this.dragStartPosition||(s=(i=this.fillOptions).onDragMove)==null||s.call(i,t)});f(this,"handleDragPointerUp",()=>{var t,i;this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,(i=(t=this.fillOptions).onDragEnd)==null||i.call(t))});this.appService=t,this.fillOptions=i,this.setupInteraction(),this.draw()}setupInteraction(){this.fillOptions.enableInteraction&&(this.eventMode="static",this.on("pointerdown",this.handlePointerDown))}startDragging(t){var s,r;this.isDragging=!0;const i=this.parent.toLocal(t.global);this.dragStartPosition={x:i.x,y:i.y},(r=(s=this.fillOptions).onDragStart)==null||r.call(s,t),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}draw(){const{points:t,fillColor:i}=this.fillOptions;if(t.length<3)return;this.clear();const s=t.flatMap(r=>[r.x,r.y]);this.setFillStyle({color:i}).poly(s).fill()}getDragStartPosition(){return this.dragStartPosition}updateOptions(t){this.fillOptions={...this.fillOptions,...t},t.enableInteraction!==void 0&&(this.off("pointerdown",this.handlePointerDown),this.setupInteraction()),this.draw()}updatePoints(t){this.fillOptions.points=t,this.draw()}updateFillColor(t){this.fillOptions.fillColor=t,this.draw()}stopDragging(){var t;this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,(t=this.gestureSession)==null||t.cancel(),this.gestureSession=null)}isCurrentlyDragging(){return this.isDragging}setInteractionEnabled(t){this.fillOptions.enableInteraction=t,t?(this.eventMode="static",this.on("pointerdown",this.handlePointerDown)):(this.eventMode="auto",this.off("pointerdown",this.handlePointerDown),this.isDragging&&this.stopDragging())}destroy(){this.stopDragging(),this.gestureSession=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}class oi extends L{constructor(t,i){super();f(this,"borderOptions");f(this,"solidLine",null);f(this,"dashGraphics",null);f(this,"fillGraphics",null);f(this,"handleAntiScale",()=>{this.drawBorder()});this.appService=t,this.borderOptions={...i},this.drawBorder(),this.setupAntiScaleListener(),this.eventMode="none"}setupAntiScaleListener(){this.appService.emitter.on("antiScale",this.handleAntiScale)}drawBorder(){const{points:t=[],closePath:i=!1,style:s}=this.borderOptions;t.length<2||(this.clearBorder(),s.fillColor!==void 0&&i&&this.drawFill(t,s),s.isDashed?this.drawContinuousDashedBorder(t,i,s):this.drawSolidBorder(t,i,s))}drawFill(t,i){if(!(!i.fillColor||t.length<3)){this.fillGraphics&&(this.removeChild(this.fillGraphics),this.fillGraphics.destroy()),this.fillGraphics=new U,this.fillGraphics.setFillStyle({color:i.fillColor}),this.fillGraphics.moveTo(t[0].x,t[0].y);for(let s=1;s<t.length;s++)this.fillGraphics.lineTo(t[s].x,t[s].y);this.fillGraphics.closePath(),this.fillGraphics.fill(),this.addChild(this.fillGraphics)}}drawSolidBorder(t,i,s){const r=this.appService;this.solidLine&&(this.removeChild(this.solidLine),this.solidLine.destroy()),this.solidLine=new U;const o=r.getApp().toFixedSize(s.width);this.solidLine.setStrokeStyle({color:s.color,width:o}),this.solidLine.moveTo(t[0].x,t[0].y);for(let a=1;a<t.length;a++)this.solidLine.lineTo(t[a].x,t[a].y);i&&this.solidLine.lineTo(t[0].x,t[0].y),this.solidLine.stroke(),this.addChild(this.solidLine)}drawContinuousDashedBorder(t,i,s){if(t.length<2)return;if(!s.dashArray||s.dashArray.length!==2||s.dashArray[0]<=0||s.dashArray[1]<=0){w.warn("Invalid dashArray:",s.dashArray);return}const r=this.appService;this.dashGraphics=new U;const o=r.getApp().toFixedSize(s.width);this.dashGraphics.setStrokeStyle({color:s.color,width:o});const a=Math.max(r.getApp().toFixedSize(s.dashArray[0]),1),h=Math.max(r.getApp().toFixedSize(s.dashArray[1]),1),l=i?[...t,t[0]]:t;this.drawContinuousPathDashes(this.dashGraphics,l,a,h),this.dashGraphics.stroke(),this.addChild(this.dashGraphics)}drawContinuousPathDashes(t,i,s,r){if(i.length<2)return;if(s<=0||r<=0){w.warn("Invalid dash parameters:",{dashLength:s,gapLength:r});return}const o=this.calculatePathSegments(i),a=o.reduce((c,d)=>c+d.length,0);if(a===0)return;const h=s+r;let l=0;for(;l<a;){const c=l+s;c<=a?this.drawContinuousDashSegment(t,o,l,c):this.drawContinuousDashSegment(t,o,l,a),l+=h}}calculatePathSegments(t){const i=[];for(let s=0;s<t.length-1;s++){const r=t[s],o=t[s+1],a=o.x-r.x,h=o.y-r.y,l=Math.sqrt(a*a+h*h);i.push({start:r,end:o,length:l})}return i}drawContinuousDashSegment(t,i,s,r){if(s>=r)return;let o=0,a=!1,h=null;for(const l of i){const c=o,d=o+l.length;if(d>s&&c<r){const u=Math.max(s,c),p=Math.min(r,d),g=(u-c)/l.length,m=(p-c)/l.length,y={x:l.start.x+(l.end.x-l.start.x)*g,y:l.start.y+(l.end.y-l.start.y)*g},x={x:l.start.x+(l.end.x-l.start.x)*m,y:l.start.y+(l.end.y-l.start.y)*m};a?h&&Math.sqrt(Math.pow(y.x-h.x,2)+Math.pow(y.y-h.y,2))>.1&&t.lineTo(y.x,y.y):(t.moveTo(y.x,y.y),a=!0),t.lineTo(x.x,x.y),h=x}if(o+=l.length,o>=r)break}}clearBorder(){this.fillGraphics&&(this.removeChild(this.fillGraphics),this.fillGraphics.destroy(),this.fillGraphics=null),this.solidLine&&(this.removeChild(this.solidLine),this.solidLine.destroy(),this.solidLine=null),this.dashGraphics&&(this.removeChild(this.dashGraphics),this.dashGraphics.destroy(),this.dashGraphics=null)}updateStyle(t){this.borderOptions.style={...this.borderOptions.style,...t},this.drawBorder()}updatePoints(t){this.borderOptions.points=t,this.drawBorder()}setClosePath(t){this.borderOptions.closePath=t,this.drawBorder()}getOptions(){return{...this.borderOptions}}destroy(){this.appService.emitter.off("antiScale",this.handleAntiScale),this.clearBorder(),super.destroy()}}class Hs{constructor(e){f(this,"id",null);f(this,"layer",null);f(this,"editingState",{});f(this,"idleState",{});f(this,"host",null);f(this,"onHostDestroyed",null);f(this,"detached",!1);this.deps=e}attach(e,t){this.layer&&this.detach(),this.detached=!1,this.host=e,this.id=t.id,this.editingState=t.editingState,this.idleState=t.idleState??{},this.layer=this.deps.editControls.registerEditControl(t.id,t.layerOptions);const i=()=>this.detach();return this.onHostDestroyed=i,e.once("destroyed",i),this.layer}detach(){this.detached||(this.detached=!0,this.host&&this.onHostDestroyed&&this.host.off("destroyed",this.onHostDestroyed),this.onHostDestroyed=null,this.host=null,this.id!=null&&this.deps.editControls.unregisterEditControl(this.id),this.id=null,this.layer=null)}setEditing(e){if(this.id==null){w.warn("[EditableShape] setEditing called before attach; ignoring");return}this.deps.editControls.updateEditState(this.id,e?this.editingState:this.idleState)}applyEditState(e){if(this.id==null){w.warn("[EditableShape] applyEditState called before attach; ignoring");return}this.deps.editControls.updateEditState(this.id,e)}updatePoints(e,t=!0){var i;(i=this.layer)==null||i.updatePoints(e,t)}getLayer(){return this.layer}getMoveButton(){var e;return((e=this.layer)==null?void 0:e.getMoveButton())??null}}class Es extends Ws{constructor(t,{text:i,style:s}){super({text:i,style:s});f(this,"throttledUpdateScale");this.appService=t,this.throttledUpdateScale=_t(this.updateScale.bind(this),20,{leading:!0,trailing:!0}),this.registerScaleListener(),this.updateScale(this.appService.currentScale)}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}updateScale(t){t<=0||this.scale.set(1/t)}setBaseFontSize(t){this.style.fontSize=t}updateText(t){this.text=t}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateScale),super.destroy(t)}}class Gc extends L{constructor(t){super();f(this,"throttledUpdateScale");this.appService=t,this.throttledUpdateScale=_t(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.updateScale(this.appService.currentScale),this.registerScaleListener()}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}updateScale(t){t!==0&&this.scale.set(1/t)}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateScale),super.destroy(t)}}class Vs extends Gc{constructor(t,i){super(t);f(this,"background");f(this,"icon");f(this,"options");this.appService=t,this.options=i,this.background=new U,this.addChild(this.background),this.icon=new Zt(t),this.addChild(this.icon),this.eventMode="static",this.render(),this.setupHitArea(),this.setupEvents()}setupHitArea(){const t=this.appService,i=this.options.config||t.controlsConfig,s=8,r=i.iconWrapperWidth+s*2,o=i.iconWrapperHeight+s*2;this.hitArea=new tt(-r/2,-o/2,r,o)}async render(){this.renderBackground(),this.renderIcon()}renderBackground(){const t=this.appService,i=this.options.config||t.controlsConfig;this.background.clear(),this.background.roundRect(-i.iconWrapperWidth/2,-i.iconWrapperHeight/2,i.iconWrapperWidth,i.iconWrapperHeight,i.iconWrapperBorderRadius).fill(this.options.backgroundColor)}async renderIcon(){try{const t=this.appService,i=this.options.config||t.controlsConfig;await this.icon.loadTextureAndSetSize(this.options.iconAlias,{width:i.iconWidth,height:i.iconHeight,sizeFixed:!1}),this.icon.visible=!0}catch(t){w.error(`Failed to load icon: ${this.options.iconAlias}`,t)}}destroy(){super.destroy()}}class Uc extends Vs{constructor(t,i){super(t,i);f(this,"isMoving",!1);f(this,"dragStartPosition",null);f(this,"gestureSession",null);f(this,"handleMovePointerMove",t=>{var i,s;!this.isMoving||!this.dragStartPosition||(s=(i=this.options).onMoveMove)==null||s.call(i,t)});f(this,"handleMovePointerUp",()=>{var t,i;this.gestureSession=null,this.isMoving&&(this.isMoving=!1,this.dragStartPosition=null,(i=(t=this.options).onMoveEnd)==null||i.call(t))});this.appService=t}setupEvents(){this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(t){t.stopPropagation(),this.startMoving(t)}startMoving(t){var i,s;this.isMoving=!0,this.dragStartPosition=this.parent.toLocal(t.global),(s=(i=this.options).onMoveStart)==null||s.call(i),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleMovePointerMove),this.gestureSession.onEnd(this.handleMovePointerUp)}isCurrentlyMoving(){return this.isMoving}getDragStartPosition(){return this.dragStartPosition?{...this.dragStartPosition}:null}stopMoving(){var t,i;this.isMoving&&(this.gestureSession?this.gestureSession.cancel():(this.isMoving=!1,this.dragStartPosition=null,(i=(t=this.options).onMoveEnd)==null||i.call(t)))}destroy(){this.stopMoving(),this.gestureSession=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}class Hc extends Vs{constructor(t,i){super(t,i);f(this,"clickHandler",null);this.appService=t}setupEvents(){this.clickHandler=new vt(this,{onClick:this.options.onClick,stopPropagation:!0})}destroy(){var t;(t=this.clickHandler)==null||t.destroy(),super.destroy()}}const wS=10;class CS extends Vs{constructor(t,i){super(t,i);f(this,"isRotating",!1);f(this,"hasRotated",!1);f(this,"rotationCenter",{x:0,y:0});f(this,"downPosition",{x:0,y:0});f(this,"lastAngle",0);f(this,"clickHandler",null);f(this,"gestureSession",null);f(this,"handleRotationPointerMove",t=>{var o,a,h,l;if(!this.isRotating)return;if(!this.hasRotated){const c=t.global.x-this.downPosition.x,d=t.global.y-this.downPosition.y;if(Math.sqrt(c*c+d*d)<=wS)return;this.hasRotated=!0,(a=(o=this.options).onRotationStart)==null||a.call(o,this.rotationCenter)}const i=this.parent.toLocal(t.global),s=Math.atan2(i.y-this.rotationCenter.y,i.x-this.rotationCenter.x),r=s-this.lastAngle;(l=(h=this.options).onRotationMove)==null||l.call(h,r),this.lastAngle=s});f(this,"handleRotationPointerUp",()=>{var t,i;this.gestureSession=null,this.isRotating&&(this.isRotating=!1,this.hasRotated&&((i=(t=this.options).onRotationEnd)==null||i.call(t)),this.hasRotated=!1)});this.appService=t}setupEvents(){this.options.onClick&&(this.clickHandler=new vt(this,{onClick:()=>{var t,i;this.hasRotated||(i=(t=this.options).onClick)==null||i.call(t)},stopPropagation:!1})),this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(t){t.stopPropagation(),this.startRotation(t)}startRotation(t){this.isRotating=!0,this.hasRotated=!1,this.downPosition={x:t.global.x,y:t.global.y};const i=this.options.getTargetPoints();this.rotationCenter=Oe(i);const s=this.parent.toLocal(t.global);this.lastAngle=Math.atan2(s.y-this.rotationCenter.y,s.x-this.rotationCenter.x),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleRotationPointerMove),this.gestureSession.onEnd(this.handleRotationPointerUp)}isCurrentlyRotating(){return this.isRotating}stopRotation(){var t,i;this.isRotating&&(this.gestureSession?this.gestureSession.cancel():(this.isRotating=!1,this.hasRotated&&((i=(t=this.options).onRotationEnd)==null||i.call(t)),this.hasRotated=!1))}destroy(){var t;this.stopRotation(),this.gestureSession=null,(t=this.clickHandler)==null||t.destroy(),this.off("pointerdown",this.handlePointerDown),super.destroy()}}class bs extends Vs{constructor(t,i){super(t,i);f(this,"isScaling",!1);f(this,"initialButtonPosition",null);f(this,"dragStartPosition",null);f(this,"gestureSession",null);f(this,"handleScalePointerMove",t=>{var o,a;if(!this.isScaling||!this.initialButtonPosition||!this.dragStartPosition)return;const i=this.parent.toLocal(t.global),s=i.x-this.dragStartPosition.x,r=i.y-this.dragStartPosition.y;(a=(o=this.options).onScaleMove)==null||a.call(o,{deltaX:s,deltaY:r})});f(this,"handleScalePointerUp",()=>{var t,i;this.gestureSession=null,this.isScaling&&(this.isScaling=!1,this.initialButtonPosition=null,this.dragStartPosition=null,(i=(t=this.options).onScaleEnd)==null||i.call(t))});this.appService=t}setupEvents(){this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(t){t.stopPropagation(),this.startScaling(t)}startScaling(t){var i,s,r,o;if(this.isScaling=!0,this.dragStartPosition=this.parent.toLocal(t.global),"initialButtonPosition"in this.options)this.initialButtonPosition={x:this.position.x,y:this.position.y},(s=(i=this.options).onScaleStart)==null||s.call(i);else{const a=this.options.getTargetPoints(),h=this.options.getButtonIndex();h>=0&&h<a.length&&(this.initialButtonPosition={...a[h]}),(o=(r=this.options).onScaleStart)==null||o.call(r,h)}this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleScalePointerMove),this.gestureSession.onEnd(this.handleScalePointerUp)}isCurrentlyScaling(){return this.isScaling}stopScaling(){var t,i;this.isScaling&&(this.gestureSession?this.gestureSession.cancel():(this.isScaling=!1,this.initialButtonPosition=null,this.dragStartPosition=null,(i=(t=this.options).onScaleEnd)==null||i.call(t)))}destroy(){this.stopScaling(),this.gestureSession=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}const pt={REMOVE:0,ROTATE:1,SCALE:2,MOVE:3};class _S extends L{constructor(t,i){super();f(this,"config");f(this,"events");f(this,"zonePoints",[]);f(this,"outlinePoints");f(this,"minSize",.1);f(this,"maxSize");f(this,"sizeConstraintPerEdge");f(this,"initialZonePoints",[]);f(this,"scaleCache",null);f(this,"rotationCache",null);f(this,"outlineBorder");f(this,"moveLine");f(this,"sizeText");f(this,"controlButtons");f(this,"deleteButton",null);f(this,"rotateButton",null);f(this,"scaleButton",null);f(this,"moveButton",null);f(this,"horizontalScaleButton",null);f(this,"verticalScaleButton",null);f(this,"horizontalScaleInitialPosition",null);f(this,"verticalScaleInitialPosition",null);f(this,"clickHandler",null);f(this,"throttledUpdateOutline");this.appService=t,this.zonePoints=i.zonePoints,this.config={...i.config,showScaleButton:i.config.showScaleButton!==void 0?i.config.showScaleButton:!0,showRadialScaleButton:i.config.showRadialScaleButton!==void 0?i.config.showRadialScaleButton:!0,showDeleteButton:i.config.showDeleteButton!==void 0?i.config.showDeleteButton:!0,showMoveButton:i.config.showMoveButton!==void 0?i.config.showMoveButton:!0,showRotateButton:i.config.showRotateButton!==void 0?i.config.showRotateButton:!0,rotateMode:i.config.rotateMode??"step",scaleMode:i.config.scaleMode??"free"},this.events=i.events||{},this.minSize=i.minSize??.1,this.maxSize=i.maxSize,this.sizeConstraintPerEdge=i.sizeConstraintPerEdge,this.throttledUpdateOutline=_t(this.updateOutlineForScale.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.registerScaleListener()}initializeComponents(){this.outlinePoints=this.calculateOutlinePoints(),this.outlineBorder=this.createOutlineBorder(),this.addChild(this.outlineBorder),this.moveLine=this.createMoveLine(),this.addChild(this.moveLine),this.moveLine.visible=this.config.showMoveButton||!1,this.sizeText=this.createSizeText(),this.addChild(this.sizeText),this.controlButtons=new L,this.addChild(this.controlButtons),this.createControlButtons(),this.setupClickHandler()}createOutlineBorder(){const{outlineStrokeColor:t,outlineStrokeWidth:i,outlineDashed:s,outlineDashArray:r,outlineFillColor:o}=this.config;return new oi(this.appService,{points:this.outlinePoints,closePath:!0,style:{color:t,width:i,isDashed:s,dashArray:r,fillColor:o}})}createMoveLine(){const{outlineStrokeColor:t,outlineStrokeWidth:i,outlineDashed:s,outlineDashArray:r}=this.config,o=this.calculateMoveLinePoints();return new oi(this.appService,{points:o,closePath:!1,style:{color:t,width:i,isDashed:s,dashArray:r}})}createSizeText(){const t=this.calculateSizeText(),i=new Es(this.appService,{text:t,style:{fontSize:this.config.textFontSize,fontFamily:this.config.textFontFamily,fontWeight:this.config.textFontWeight,fill:this.config.textColor,align:"center"}});i.anchor.set(.5);const s=this.calculateSizeTextPosition();i.position.set(s.x,s.y);const r=this.calculateSizeTextRotation();return i.rotation=r,i.eventMode="none",i}createDeleteButton(){const t=new Hc(this.appService,{iconAlias:"deleteIcon",backgroundColor:this.config.deleteIconWrapperFillColor??this.config.iconWrapperFillColor,onClick:()=>{var i,s;return(s=(i=this.events).onRemove)==null?void 0:s.call(i)}});return t.position.set(this.outlinePoints[pt.REMOVE].x,this.outlinePoints[pt.REMOVE].y),t}createRotateButton(){const t=this.config.rotateMode==="step",i=new CS(this.appService,{iconAlias:"rotateIcon",backgroundColor:this.config.iconWrapperFillColor,getTargetPoints:()=>this.zonePoints,onRotationStart:s=>{var r,o;this.initializeRotationCache(s),(o=(r=this.events).onRotateStart)==null||o.call(r,s)},onRotationMove:t?void 0:s=>{var o,a;const r=this.handleInternalRotationMove(s);(a=(o=this.events).onRotateMove)==null||a.call(o,r??void 0)},onClick:t?()=>{var o,a,h,l;const s=this.config.stepRotateAngle??Math.PI/2,r=this.onClickRotateButton(s);(a=(o=this.events).onRotateMove)==null||a.call(o,r??void 0),(l=(h=this.events).onClickRotate)==null||l.call(h,r??void 0)}:void 0,onRotationEnd:()=>{var s,r;this.resetRotationState(),(r=(s=this.events).onRotateEnd)==null||r.call(s)}});return i.position.set(this.outlinePoints[pt.ROTATE].x,this.outlinePoints[pt.ROTATE].y),i}onClickRotateButton(t){this.rotationCache||this.initializeRotationCache(this.calculateRotationCenter());const i=this.handleInternalRotationMove(t);return this.resetRotationState(),i}createScaleButton(){const t=new bs(this.appService,{iconAlias:"scaleIcon",backgroundColor:this.config.iconWrapperFillColor,initialButtonPosition:this.outlinePoints[pt.SCALE],onScaleStart:()=>{var i,s;this.initializeScaleCache(),(s=(i=this.events).onScaleStart)==null||s.call(i)},onScaleMove:({deltaX:i,deltaY:s})=>{var o,a;const r=this.handleInternalScaleMove(i,s);(a=(o=this.events).onScaleMove)==null||a.call(o,r??void 0)},onScaleEnd:()=>{var i,s;this.resetScaleState(),this.initialZonePoints=[],(s=(i=this.events).onScaleEnd)==null||s.call(i)}});return t.position.set(this.outlinePoints[pt.SCALE].x,this.outlinePoints[pt.SCALE].y),t}createHorizontalScaleButton(){const[,t,i]=this.outlinePoints,s=this.getEdgeCenter(t,i),r=new bs(this.appService,{iconAlias:"horizontalScaleIcon",backgroundColor:this.config.iconWrapperFillColor,config:{iconWrapperWidth:18,iconWrapperHeight:18,iconWrapperBorderRadius:18,iconWidth:10,iconHeight:8},initialButtonPosition:s,onScaleStart:()=>{var h,l;const[,o,a]=this.zonePoints;this.horizontalScaleInitialPosition=this.getEdgeCenter(o,a),this.initializeScaleCache(),(l=(h=this.events).onScaleStart)==null||l.call(h)},onScaleMove:({deltaX:o,deltaY:a})=>{var l,c;const h=this.handleInternalHorizontalScaleMove(o,a);(c=(l=this.events).onScaleMoveHorizontal)==null||c.call(l,h??void 0)},onScaleEnd:()=>{var o,a;this.resetScaleState(),this.initialZonePoints=[],this.horizontalScaleInitialPosition=null,(a=(o=this.events).onScaleEnd)==null||a.call(o)}});return r.position.set(s.x,s.y),r}createVerticalScaleButton(){const[,,t,i]=this.outlinePoints,s=this.getEdgeCenter(t,i),r=new bs(this.appService,{iconAlias:"verticalScaleIcon",backgroundColor:this.config.iconWrapperFillColor,config:{iconWrapperWidth:18,iconWrapperHeight:18,iconWrapperBorderRadius:18,iconWidth:8,iconHeight:10},initialButtonPosition:s,onScaleStart:()=>{var h,l;const[,,o,a]=this.zonePoints;this.verticalScaleInitialPosition=this.getEdgeCenter(o,a),this.initializeScaleCache(),(l=(h=this.events).onScaleStart)==null||l.call(h)},onScaleMove:({deltaX:o,deltaY:a})=>{var l,c;const h=this.handleInternalVerticalScaleMove(o,a);(c=(l=this.events).onScaleMoveVertical)==null||c.call(l,h??void 0)},onScaleEnd:()=>{var o,a;this.resetScaleState(),this.initialZonePoints=[],this.verticalScaleInitialPosition=null,(a=(o=this.events).onScaleEnd)==null||a.call(o)}});return r.position.set(s.x,s.y),r}createMoveButton(){const t=this.calculateMoveButtonPosition(),i=new Uc(this.appService,{iconAlias:"moveIcon",backgroundColor:this.config.iconWrapperFillColor,onMoveStart:()=>{var s,r;return(r=(s=this.events).onMoveStart)==null?void 0:r.call(s)},onMoveMove:s=>{var r,o;return(o=(r=this.events).onMoveMove)==null?void 0:o.call(r,s)},onMoveEnd:()=>{var s,r;return(r=(s=this.events).onMoveEnd)==null?void 0:r.call(s)}});return i.position.set(t.x,t.y),i}createAndAddButton(t,i){return t.visible=i,this.controlButtons.addChild(t),t}createControlButtons(){this.outlinePoints.length<4||(this.deleteButton=this.createAndAddButton(this.createDeleteButton(),this.config.showDeleteButton??!1),this.moveButton=this.createAndAddButton(this.createMoveButton(),this.config.showMoveButton??!1),this.rotateButton=this.createAndAddButton(this.createRotateButton(),this.config.showRotateButton??!1),this.scaleButton=this.createAndAddButton(this.createScaleButton(),this.config.showScaleButton??!1),this.horizontalScaleButton=this.createAndAddButton(this.createHorizontalScaleButton(),this.config.showRadialScaleButton??!1),this.verticalScaleButton=this.createAndAddButton(this.createVerticalScaleButton(),this.config.showRadialScaleButton??!1))}calculateOutlinePoints(){const t=this.zonePoints;if(t.length<4)return t;const s=this.appService.getApp().toFixedSize(this.config.outlineOffset);return wx(t,s)}calculateMoveButtonPosition(){const t=this.calculateOutlinePoints();if(t.length<4)return{x:0,y:0};const s=this.appService.getApp().toFixedSize(this.config.moveButtonOffset),r=t[pt.MOVE],o=t[pt.SCALE],a=t[pt.REMOVE];return Mc(r,o,a,s)}calculateMoveLinePoints(){const t=this.calculateOutlinePoints();if(t.length<4)return[];const i=t[pt.MOVE],s=this.calculateMoveButtonPosition();return[i,s]}calculateSizeText(){const t=this.zonePoints;if(t.length<4)return"0m*0m";const[i,s,,r]=t,o=q(i,s),a=q(i,r),{coords:h}=this.appService,l=h.toMeters(Bt(o)),c=h.toMeters(Bt(a)),d=h.toDisplayUnit(l),u=h.toDisplayUnit(c),p=this.appService.runtimeSnapshot.unitLabel;return`${d.toFixed(1)}${p}*${u.toFixed(1)}${p}`}getEdgeCenter(t,i){return{x:(t.x+i.x)/2,y:(t.y+i.y)/2}}calculatePerpendicularOffset(t,i,s,r=!1){const o=Tt(mt(i,t)),a=r?{x:-o.y,y:o.x}:{x:o.y,y:-o.x};return{x:a.x*s,y:a.y*s}}calculateSizeTextPosition(){if(this.zonePoints.length<4)return{x:0,y:0};const i=this.calculateOutlinePoints(),[s,r,o,a]=i,{textPosition:h,textOffset:l}=this.config,d=this.appService.getApp().toFixedSize(l);let u,p;switch(h){case"top":u=this.getEdgeCenter(s,r),p=this.calculatePerpendicularOffset(r,s,d);break;case"right":u=this.getEdgeCenter(r,o),p=this.calculatePerpendicularOffset(r,o,d);break;case"bottom":u=this.getEdgeCenter(a,o),p=this.calculatePerpendicularOffset(a,o,d,!0);break;case"left":u=this.getEdgeCenter(s,a),p=this.calculatePerpendicularOffset(a,s,d);break;default:u=this.getEdgeCenter(s,r),p={x:0,y:d};break}return{x:u.x+p.x,y:u.y+p.y}}calculateSizeTextRotation(){const t=this.zonePoints;if(t.length<4)return 0;const[i,s,r,o]=t,{textPosition:a}=this.config;let h,l;switch(a){case"top":h=i,l=s;break;case"right":h=s,l=r;break;case"bottom":h=r,l=o;break;case"left":h=o,l=i;break;default:h=i,l=s;break}const c=this.appService.appContainer.getMapRotationRadians();return vs(h,l,c)}calculateHorizontalScaleButtonRotation(){const t=this.zonePoints;if(t.length<4)return 0;const[,i,s]=t,r=this.appService.appContainer.getMapRotationRadians();return vs(i,s,r)+Math.PI/2}calculateVerticalScaleButtonRotation(){const t=this.zonePoints;if(t.length<4)return 0;const[,,i,s]=t,r=this.appService.appContainer.getMapRotationRadians();return vs(s,i,r)}updatePoints(t,i=!0){this.zonePoints=t,this.updateOutlineBorder(),this.moveLine&&this.updateMoveLine(),this.updateControlButtonsPosition(),this.updateSizeText(i)}updateOutlineBorder(){const t=this.calculateOutlinePoints();this.outlinePoints=t,this.outlineBorder.updatePoints(t)}updateMoveLine(){if(!this.moveLine)return;const t=this.calculateMoveLinePoints();this.moveLine.updatePoints(t)}updateSizeText(t=!0){if(this.sizeText){if(t){const i=this.calculateSizeText();this.sizeText.updateText(i)}this.updateSizeTextPosition()}}updateSizeTextPosition(){if(!this.sizeText)return;const t=this.calculateSizeTextPosition();this.sizeText.position.set(t.x,t.y);const i=this.calculateSizeTextRotation();this.sizeText.rotation=i}updateControlButtonsPosition(){if(!this.deleteButton||!this.scaleButton||!this.moveButton)return;const t=this.calculateOutlinePoints();if(t.length<4)return;const i=this.calculateMoveButtonPosition(),s=[{button:this.deleteButton,point:t[pt.REMOVE]},{button:this.scaleButton,point:t[pt.SCALE]},{button:this.moveButton,point:i}];if(this.rotateButton&&s.push({button:this.rotateButton,point:t[pt.ROTATE]}),this.horizontalScaleButton){const r=t[pt.ROTATE],o=t[pt.SCALE],a=_c(r,o,0);s.push({button:this.horizontalScaleButton,point:a})}if(this.verticalScaleButton){const r=t[pt.SCALE],o=t[pt.MOVE],a=this.getEdgeCenter(r,o);s.push({button:this.verticalScaleButton,point:a})}s.forEach(({button:r,point:o})=>r.position.set(o.x,o.y)),this.horizontalScaleButton&&(this.horizontalScaleButton.rotation=this.calculateHorizontalScaleButtonRotation()),this.verticalScaleButton&&(this.verticalScaleButton.rotation=this.calculateVerticalScaleButtonRotation()),this.scaleButton&&this.scaleButton.visible&&(this.scaleButton.rotation=this.calculateVerticalScaleButtonRotation())}setupClickHandler(){this.clickHandler=new vt(this,{onClick:()=>{var t,i;(i=(t=this.events).onClick)==null||i.call(t)},stopPropagation:!1})}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateOutline),this.appService.emitter.on("mapRotationUpdate",this.throttledUpdateOutline)}updateOutlineForScale(){(this.outlineBorder.visible||this.controlButtons.visible)&&(this.updateOutlineBorder(),this.moveLine&&this.updateMoveLine(),this.updateControlButtonsPosition(),this.updateSizeTextPosition())}initializeScaleCache(){if(this.initialZonePoints.length===0&&(this.initialZonePoints=this.zonePoints.map(p=>({...p}))),this.initialZonePoints.length<4)return;const t={...this.initialZonePoints[pt.SCALE]};if(!t)return;const i=pt.REMOVE,{x:s,y:r}=this.initialZonePoints[i],[,o,,a]=this.initialZonePoints,h={x:s,y:r},l=mt(h,o),c=mt(h,a),d=Ui(l),u=Ui(c);d===0||u===0||(this.scaleCache={fixedPoint:h,edge1:l,edge2:c,edge1Len:d,edge2Len:u,initialButtonPosition:t})}sizeConstraintPixels(){const{coords:t}=this.appService,i=(r,o)=>({minSizePixels:t.toPixels(et(r)),maxSizePixels:o!=null?t.toPixels(et(o)):void 0});if(this.sizeConstraintPerEdge){const{edge1:r,edge2:o}=this.sizeConstraintPerEdge();return{edge1:i(r.min,r.max),edge2:i(o.min,o.max)}}const s=i(this.minSize,this.maxSize);return{edge1:s,edge2:s}}handleInternalScaleMove(t,i){if(this.initialZonePoints.length!==4||!this.scaleCache)return null;const{edge1:s,edge2:r}=this.sizeConstraintPixels(),{fixedPoint:o,edge1:a,edge2:h,edge1Len:l,edge2Len:c,initialButtonPosition:d}=this.scaleCache,u={x:d.x+t,y:d.y+i},p=mt(o,u);let g=fs(p,a,l,s.minSizePixels,s.maxSizePixels),m=fs(p,h,c,r.minSizePixels,r.maxSizePixels);if(this.config.scaleMode==="ratioLocked"){const y=Math.min(g,m);g=y,m=y}return this.calculatePointsFromScale(o,a,h,g,m)}resetScaleState(){this.scaleCache=null}handleInternalHorizontalScaleMove(t,i){if(this.initialZonePoints.length!==4||!this.scaleCache||!this.horizontalScaleInitialPosition)return null;const{fixedPoint:s,edge1:r,edge2:o,edge1Len:a}=this.scaleCache,{edge1:h}=this.sizeConstraintPixels(),l={x:this.horizontalScaleInitialPosition.x+t,y:this.horizontalScaleInitialPosition.y+i},c=mt(s,l),d=fs(c,r,a,h.minSizePixels,h.maxSizePixels);return this.calculatePointsFromScale(s,r,o,d,1)}handleInternalVerticalScaleMove(t,i){if(this.initialZonePoints.length!==4||!this.scaleCache||!this.verticalScaleInitialPosition)return null;const{fixedPoint:s,edge1:r,edge2:o,edge2Len:a}=this.scaleCache,{edge2:h}=this.sizeConstraintPixels(),l={x:this.verticalScaleInitialPosition.x+t,y:this.verticalScaleInitialPosition.y+i},c=mt(s,l),d=1,u=fs(c,o,a,h.minSizePixels,h.maxSizePixels);return this.calculatePointsFromScale(s,r,o,d,u)}calculatePointsFromScale(t,i,s,r,o){const{x:a,y:h}=t;return[t,{x:a+i.x*r,y:h+i.y*r},{x:a+i.x*r+s.x*o,y:h+i.y*r+s.y*o},{x:a+s.x*o,y:h+s.y*o}]}initializeRotationCache(t){this.zonePoints.length<3||(this.rotationCache={rotationCenter:t,initialPoints:this.zonePoints.map(i=>({...i})),totalAngle:0})}handleInternalRotationMove(t){if(!this.rotationCache||this.rotationCache.initialPoints.length<3)return null;const{rotationCenter:i,initialPoints:s}=this.rotationCache;return this.rotationCache.totalAngle+=t,vx(s,i,this.rotationCache.totalAngle)}resetRotationState(){this.rotationCache=null}calculateRotationCenter(){return this.zonePoints.length===0?{x:0,y:0}:Oe(this.zonePoints)}updateEditState({showRotateButton:t=!1,showScaleButton:i=!1,showRadialScaleButton:s=!1,showDeleteButton:r=!1,showMoveButton:o=!1,showBorder:a=!1,showSizeText:h=!1,borderStyle:l}){this.rotateButton&&(this.rotateButton.visible=t),this.scaleButton&&(this.scaleButton.visible=i),this.horizontalScaleButton&&(this.horizontalScaleButton.visible=s),this.verticalScaleButton&&(this.verticalScaleButton.visible=s),this.deleteButton&&(this.deleteButton.visible=r),this.moveButton&&(this.moveButton.visible=o);const c=t||i||s||r||o;this.controlButtons.visible=c,!c&&this.getOperationState().hasAnyOperation&&this.stopAllOperations(),this.outlineBorder.visible=a,this.moveLine&&(this.moveLine.visible=o),this.sizeText&&(this.sizeText.visible=h),a&&(this.updateOutlineBorder(),c&&(this.moveLine&&o&&this.updateMoveLine(),this.updateControlButtonsPosition()),h&&this.updateSizeTextPosition()),l&&this.outlineBorder.updateStyle({isDashed:l.isDashed,dashArray:l.dashArray})}getOperationState(){var r,o,a;const t=((r=this.scaleButton)==null?void 0:r.isCurrentlyScaling())||!1,i=((o=this.rotateButton)==null?void 0:o.isCurrentlyRotating())||!1,s=((a=this.moveButton)==null?void 0:a.isCurrentlyMoving())||!1;return{isDragging:!1,isScaling:t,isRotating:i,isMoving:s,hasAnyOperation:t||i||s}}stopAllOperations(){var t,i,s;(t=this.scaleButton)==null||t.stopScaling(),(i=this.rotateButton)==null||i.stopRotation(),(s=this.moveButton)==null||s.stopMoving()}getControlButtonsContainer(){return this.controlButtons}getMoveButton(){return this.moveButton}calculateEdgeMidpoint(t,i){const s=this.calculateOutlinePoints();if(s.length<4)return{x:0,y:0};const r=s[t],o=s[i];return{x:(r.x+o.x)/2,y:(r.y+o.y)/2}}destroy(){var t,i,s,r,o,a,h,l,c,d,u;this.appService.emitter.off("antiScale",this.throttledUpdateOutline),this.appService.emitter.off("mapRotationUpdate",this.throttledUpdateOutline),(t=this.clickHandler)==null||t.destroy(),this.clickHandler=null,(i=this.deleteButton)==null||i.destroy(),(s=this.rotateButton)==null||s.destroy(),(r=this.scaleButton)==null||r.destroy(),(o=this.moveButton)==null||o.destroy(),(a=this.horizontalScaleButton)==null||a.destroy(),(h=this.verticalScaleButton)==null||h.destroy(),this.deleteButton=null,this.rotateButton=null,this.scaleButton=null,this.moveButton=null,this.horizontalScaleButton=null,this.verticalScaleButton=null,(l=this.outlineBorder)==null||l.destroy(),(c=this.moveLine)==null||c.destroy(),(d=this.sizeText)==null||d.destroy(),(u=this.controlButtons)==null||u.destroy(),super.destroy()}}function PS(n,e,t){return{outlineStrokeColor:String(n.outlineStrokeColor),outlineStrokeWidth:n.outlineStrokeWidth,outlineDashed:n.outlineDashed,outlineDashArray:n.outlineDashArray,outlineFillColor:n.outlineFillColor?String(n.outlineFillColor):void 0,outlineOffset:n.outlineOffset,iconWrapperFillColor:String(n.iconWrapperFillColor),deleteIconWrapperFillColor:"deleteIconWrapperFillColor"in n&&n.deleteIconWrapperFillColor!==void 0?String(n.deleteIconWrapperFillColor):void 0,showRotateButton:(t==null?void 0:t.showRotateButton)??n.showRotateButton,showScaleButton:(t==null?void 0:t.showScaleButton)??!0,showRadialScaleButton:t==null?void 0:t.showRadialScaleButton,showDeleteButton:(t==null?void 0:t.showDeleteButton)??!0,showMoveButton:(t==null?void 0:t.showMoveButton)??!0,rotateMode:t==null?void 0:t.rotateMode,scaleMode:"free",textColor:String(n.textColor),textPosition:n.textPosition,textOffset:n.textOffset,moveButtonOffset:e.moveButtonOffset,textFontSize:e.textFontSize,textFontFamily:e.textFontFamily,textFontWeight:e.textFontWeight}}function Ns(n,e){return{coords:n.coords,editControls:n.editControlManager,getZoneConfig:t=>MS(n,t),controlsConfig:n.getConfig().controls,makeControlFill:t=>new Jr(n,t),makeBorder:t=>new oi(n,t),render:{request:t=>n.getApp().requestRender(t,!0),stop:t=>n.getApp().stopRender(t)},events:e}}function MS(n,e){var i;const t=n.getConfig();if($e(e)){const s=t.controls[e];if(s)return s}else{const s=(i=t.customZoneTypes)==null?void 0:i[e];if(s)return s}return _h.cleanZone}class $s extends L{constructor(t){super();f(this,"zoneData");f(this,"zoneType");f(this,"zoneConfig");f(this,"controlsConfig");f(this,"zoneEvents");f(this,"deps");f(this,"controlFill");f(this,"zoneBorder");f(this,"editableShape");f(this,"clickHandler",null);f(this,"initialZonePoints",[]);f(this,"dragStartPosition",null);f(this,"editing",!1);f(this,"resolvedMaxSizeCache",null);f(this,"handleDragStart",()=>{this.editing&&(this.initialZonePoints=this.zoneData.points.map(t=>({...t})),this.dragStartPosition=this.controlFill.getDragStartPosition(),this.deps.render.request("zone-drag"))});f(this,"handleDragMove",t=>{if(!this.editing||this.initialZonePoints.length===0||!this.dragStartPosition)return;const i=this.parent.toLocal(t.global),s=i.x-this.dragStartPosition.x,r=i.y-this.dragStartPosition.y;this.applyTranslation(s,r)});f(this,"handleDragEnd",()=>{var t,i;this.initialZonePoints=[],this.dragStartPosition=null,this.deps.render.stop("zone-drag"),(i=(t=this.zoneEvents).onUpdate)==null||i.call(t,this.getZoneData())});f(this,"handleRotationStart",()=>{this.deps.render.request("zone-rotate")});f(this,"handleRotationMove",t=>{t&&(this.zoneData.points=t,this.drawZone(!1))});f(this,"handleScaleStart",()=>{this.deps.render.request("zone-scale")});f(this,"handleScaleMove",t=>{t&&(this.zoneData.points=t,this.drawZone())});f(this,"handleMoveStart",()=>{this.initialZonePoints=this.zoneData.points.map(t=>({...t})),this.deps.render.request("zone-move")});f(this,"handleMove",t=>{var a;if(!this.editing||this.initialZonePoints.length===0)return;const i=this.parent.toLocal(t.global),s=(a=this.editableShape.getMoveButton())==null?void 0:a.getDragStartPosition();if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.applyTranslation(r,o)});f(this,"handleMoveEnd",()=>{var t,i;this.initialZonePoints=[],this.deps.render.stop("zone-move"),(i=(t=this.zoneEvents).onUpdate)==null||i.call(t,this.getZoneData())});f(this,"handleTransformEnd",()=>{var t,i;this.initialZonePoints=[],this.deps.render.stop("zone-rotate"),this.deps.render.stop("zone-scale"),(i=(t=this.zoneEvents).onUpdate)==null||i.call(t,this.getZoneData())});f(this,"handleDelete",()=>{var t,i;(i=(t=this.zoneEvents).onRemove)==null||i.call(t,this.zoneData.id)});f(this,"handleClick",()=>{var t,i;this.editing||(i=(t=this.zoneEvents)==null?void 0:t.onClick)==null||i.call(t,this.getZoneData())});const{deps:i,zoneData:s,zoneType:r}=t;this.deps=i,this.zoneType=r,this.zoneEvents=i.events,this.zoneConfig=i.getZoneConfig(r),this.controlsConfig=i.controlsConfig;const o=this.validateZoneShape(s.points);this.zoneData={...s,points:o},this.initializeComponents(),this.createEditControlLayer(),this.setupClickHandler(),this.applyEditing()}getResolvedMaxSize(){const t=this.zoneConfig.maxSize;if(this.resolvedMaxSizeCache&&this.resolvedMaxSizeCache.key===t)return this.resolvedMaxSizeCache.value;const i=ri(this.zoneConfig.minSize,t,this.zoneType);return this.resolvedMaxSizeCache={key:t,value:i},i}validateZoneShape(t){if(t.length<4)return t;const i=this.getResolvedMaxSize();return this.deps.coords.validateShape(Sc(t),{minSize:et(this.zoneConfig.minSize),maxSize:i!=null?et(i):void 0})}initializeComponents(){this.controlFill=this.createControlFill(),this.addChild(this.controlFill),this.zoneBorder=this.createBorder(),this.addChild(this.zoneBorder)}createControlFill(){return this.deps.makeControlFill({points:this.zoneData.points,fillColor:this.zoneConfig.fillColor,enableInteraction:this.editing,onDragStart:this.handleDragStart,onDragMove:this.handleDragMove,onDragEnd:this.handleDragEnd})}createBorder(){const t=this.editing?this.zoneConfig.editing:this.zoneConfig.normal;return this.deps.makeBorder({points:this.zoneData.points,closePath:!0,style:{color:this.zoneConfig.strokeColor,width:this.zoneConfig.strokeWidth,isDashed:t.isDashed,dashArray:t.dashArray}})}createEditControlLayer(){const t=PS(this.zoneConfig,this.controlsConfig,{showRotateButton:this.zoneConfig.showRotateButton,showRadialScaleButton:!1,rotateMode:"free"});this.editableShape=new Hs({editControls:this.deps.editControls});const i=this.getResolvedMaxSize(),s={config:t,zonePoints:this.zoneData.points,minSize:this.zoneConfig.minSize,maxSize:i??void 0,contentLayer:ce,events:{onRemove:this.handleDelete,onRotateStart:this.handleRotationStart,onRotateMove:this.handleRotationMove,onRotateEnd:this.handleTransformEnd,onScaleStart:this.handleScaleStart,onScaleMove:this.handleScaleMove,onScaleEnd:this.handleTransformEnd,onMoveStart:this.handleMoveStart,onMoveMove:this.handleMove,onMoveEnd:this.handleMoveEnd,onClick:this.handleClick}};this.editableShape.attach(this,{id:this.zoneData.id,topology:"quad",layerOptions:s,editingState:{showRotateButton:this.zoneConfig.showRotateButton,showScaleButton:!0,showRadialScaleButton:!1,showDeleteButton:!0,showMoveButton:!0,showBorder:!0,showSizeText:!0},idleState:{showRotateButton:!1,showScaleButton:!1,showRadialScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}})}applyTranslation(t,i){this.zoneData.points=this.initialZonePoints.map(s=>({x:s.x+t,y:s.y+i})),this.drawZone()}setupClickHandler(){this.interactiveChildren=!0,this.clickHandler=new vt(this,{onClick:this.handleClick,stopPropagation:!1})}drawZone(t=!0){const{points:i}=this.zoneData;i.length<4||(this.controlFill.updatePoints(i),this.zoneBorder.updatePoints(i),this.editableShape.updatePoints(i,t))}applyEditing(){this.controlFill.setInteractionEnabled(this.editing),this.updateBorderStyle(this.editing?this.zoneConfig.editing:this.zoneConfig.normal),this.editableShape.setEditing(this.editing),this.zIndex=this.editing?1e3:0}updateBorderStyle(t){this.zoneBorder.updateStyle({isDashed:t.isDashed,dashArray:t.dashArray})}setEditing(t){this.editing!==t&&(this.editing=t,this.applyEditing())}isEditing(){return this.editing}updateZoneData(t){const i=this.validateZoneShape(t.points);this.zoneData={...t,points:i},this.drawZone()}getZoneData(){return{...this.zoneData}}refreshDisplay(){this.drawZone()}destroy(){var t,i,s;this.editableShape.detach(),(t=this.clickHandler)==null||t.destroy(),this.clickHandler=null,(i=this.zoneBorder)==null||i.destroy(),(s=this.controlFill)==null||s.destroy(),super.destroy()}}class to extends $s{constructor(e,t){super({deps:Ns(e,{onRemove:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onRemoveForbiddenSweepZone)==null||r.call(s,i)},onUpdate:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onUpdateForbiddenSweepZone)==null||r.call(s,i)},onClick:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onClickForbiddenSweepZone)==null||r.call(s,i)}}),zoneData:t.zoneData,zoneType:"forbiddenSweepZone"})}static create(e,t){return new to(e,{zoneData:t})}}class eo extends $s{constructor(e,t){super({deps:Ns(e,{onRemove:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onRemoveForbiddenMopZone)==null||r.call(s,i)},onUpdate:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onUpdateForbiddenMopZone)==null||r.call(s,i)},onClick:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onClickForbiddenMopZone)==null||r.call(s,i)}}),zoneData:t.zoneData,zoneType:"forbiddenMopZone"})}static create(e,t){return new eo(e,{zoneData:t})}}class io extends $s{constructor(e,t){super({deps:Ns(e,{onRemove:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onRemoveCleanZone)==null||r.call(s,i)},onUpdate:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onUpdateCleanZone)==null||r.call(s,i)},onClick:i=>{var s,r;(r=(s=e.events)==null?void 0:s.onClickCleanZone)==null||r.call(s,i)}}),zoneData:t.zoneData,zoneType:"cleanZone"})}static create(e,t){return new io(e,{zoneData:t})}}class Ne extends U{constructor(t,i){super();f(this,"lineOptions");f(this,"strokeContext",null);f(this,"drawDashLine",()=>{const{start:t,end:i,style:s}=this.lineOptions;this.clear(),this.strokeContext&&this.strokeContext.destroy();const r=this.appService;this.strokeContext=new gt;const o=r.getApp().toFixedSize(s.width);this.strokeContext.setStrokeStyle({color:s.color,width:o}),this.drawDashedLineToContext(this.strokeContext,t.x,t.y,i.x,i.y,s.dashArray[0],s.dashArray[1]),this.strokeContext.stroke(),this.context=this.strokeContext});this.appService=t,this.lineOptions={...i},this.eventMode="static",this.drawDashLine(),this.setupAntiScaleListener()}setupAntiScaleListener(){this.appService.emitter.on("antiScale",this.drawDashLine)}drawDashedLineToContext(t,i,s,r,o,a,h){const l=r-i,c=o-s,d=Math.sqrt(l*l+c*c);if(d===0)return;const u=this.appService,p=u.getApp().toFixedSize(a),g=u.getApp().toFixedSize(h),m=p+g,y=d/m,x=Math.round(y);if(x===0){t.moveTo(i,s),t.lineTo(r,o);return}const S=d/x,v=S*(p/m),b=l/d,P=c/d;for(let C=0;C<x;C++){const _=C*S,R=_+v;if(_>=d)break;const M=Math.min(R,d),T=i+_*b,A=s+_*P,E=i+M*b,D=s+M*P;t.moveTo(T,A),t.lineTo(E,D)}}updatePoints(t,i){this.lineOptions.start=t,this.lineOptions.end=i,this.drawDashLine()}updateStyle(t){this.lineOptions.style={...this.lineOptions.style,...t},this.drawDashLine()}getOptions(){return{...this.lineOptions}}destroy(){this.appService.emitter.off("antiScale",this.drawDashLine),this.strokeContext&&this.strokeContext.destroy(),super.destroy()}}const $t=class $t extends L{constructor(t){super();f(this,"wallData");f(this,"wallConfig");f(this,"controlsConfig");f(this,"wallEvents");f(this,"appService");f(this,"wallLine");f(this,"outlineBorder");f(this,"moveLine");f(this,"lengthText");f(this,"controlButtons");f(this,"removeButton",null);f(this,"scaleButton",null);f(this,"moveButton",null);f(this,"initialWallPoints",[]);f(this,"initialButtonPosition",null);f(this,"isDragging",!1);f(this,"dragStartPosition",null);f(this,"gestureSession",null);f(this,"resolvedMaxWidthCache",null);f(this,"throttledUpdateOutline");f(this,"throttledHandleScaleChange");f(this,"wallLineClickHandler",null);f(this,"handleRemove",()=>{var t,i;(i=(t=this.wallEvents).onRemove)==null||i.call(t,this.wallData.id)});f(this,"initializeOperation",()=>{this.initialWallPoints=this.wallData.points.map(t=>({...t}))});f(this,"finalizeOperation",()=>{var t,i;this.initialWallPoints=[],(i=(t=this.wallEvents).onUpdate)==null||i.call(t,this.getWallData())});f(this,"handleScaleStart",()=>{this.initializeOperation();const t=this.calculateOutlinePoints();t.length>$t.BUTTON_INDICES.SCALE&&(this.initialButtonPosition={...t[$t.BUTTON_INDICES.SCALE]}),this.appService.getApp().requestRender("virtualwall-scale",!0)});f(this,"handleScaleMove",({deltaX:t,deltaY:i})=>{if(this.initialWallPoints.length===0||!this.initialButtonPosition)return;const s={x:this.initialButtonPosition.x+t,y:this.initialButtonPosition.y+i};this.applyScaleAndRotation(s)});f(this,"handleScaleEnd",()=>{this.finalizeOperation(),this.initialButtonPosition=null,this.appService.getApp().stopRender("virtualwall-scale")});f(this,"handleMoveStart",()=>{this.initializeOperation(),this.appService.getApp().requestRender("virtualwall-move",!0)});f(this,"handleMove",t=>{var a;if(this.initialWallPoints.length===0)return;const i=this.parent.toLocal(t.global),s=this.getDragStartPosition()||((a=this.moveButton)==null?void 0:a.getDragStartPosition());if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.applyTranslation(r,o)});f(this,"handleMoveEnd",()=>{this.finalizeOperation(),this.appService.getApp().stopRender("virtualwall-move")});f(this,"handleScaleChange",()=>{this.redrawSolidLine(),this.setupWallLineHitArea()});f(this,"handleWallLinePointerDown",t=>{this.isEditingEnabled()&&(t.stopPropagation(),this.startDragging(t))});f(this,"handleDragPointerMove",t=>{!this.isDragging||!this.dragStartPosition||this.handleMove(t)});f(this,"handleDragPointerUp",()=>{this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.appService.getApp().stopRender("virtualwall-drag"),this.finalizeOperation())});const{appService:i,wallData:s,events:r={}}=t;this.appService=i,this.wallEvents=r,this.wallConfig=this.appService.controlsConfig.virtualWall,this.controlsConfig=this.appService.controlsConfig,this.wallData={...s,points:this.validateAndCorrectWallLength(s.points)},this.throttledHandleScaleChange=_t(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.throttledUpdateOutline=_t(this.updateOutlineForScale.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.updateEditState(),this.registerScaleListener()}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateOutline),this.appService.emitter.on("antiScale",this.throttledHandleScaleChange),this.appService.emitter.on("mapRotationUpdate",this.throttledUpdateOutline)}getResolvedMaxWidth(){const t=this.wallConfig.maxWidth;if(this.resolvedMaxWidthCache&&this.resolvedMaxWidthCache.key===t)return this.resolvedMaxWidthCache.value;const i=ri(this.wallConfig.minWidth,t,"virtualWall");return this.resolvedMaxWidthCache={key:t,value:i},i}validateAndCorrectWallLength(t){if(t.length<2)return t;const[i,s]=t,{coords:r}=this.appService,o=r.toPixels(et(this.wallConfig.minWidth)),a=this.getResolvedMaxWidth(),h=a!=null?r.toPixels(et(a)):void 0,l=q(i,s),c=l<o,d=h!=null&&l>h;if(!c&&!d)return t;if(l===0)return[i,{x:i.x+o,y:i.y}];const u=Tt(mt(i,s));let p=l;return h!=null&&(p=Math.min(p,h)),p=Math.max(p,o),[i,{x:i.x+u.x*p,y:i.y+u.y*p}]}isEditingEnabled(){return this.appService.runtimeSnapshot.editingVirtualWallIds.includes(this.wallData.id)}updateOutlineForScale(){this.isEditingEnabled()&&(this.updateOutlineComponents(),this.updateControlButtonsPosition(),this.updateLengthTextPosition())}initializeComponents(){this.outlineBorder=this.createOutlineBorder(),this.addChild(this.outlineBorder),this.createWallLine(!1),this.addChild(this.wallLine),this.lengthText=this.createLengthText(),this.addChild(this.lengthText),this.moveLine=this.createMoveLine(),this.addChild(this.moveLine),this.controlButtons=new L,this.controlButtons.visible=this.isEditingEnabled(),this.addChild(this.controlButtons),this.createControlButtons()}createWallLine(t=!0){const{points:i}=this.wallData;if(i.length<2)return;const{lineWidth:s,lineColor:r,editing:o,normal:a}=this.wallConfig,l=this.isEditingEnabled()?o:a;l.isDashed?this.wallLine=new Ne(this.appService,{start:i[0],end:i[1],style:{color:r.toString(),width:s,dashArray:l.dashArray}}):this.wallLine=this.createSolidLine(i[0],i[1],s,r.toString()),t&&this.setupWallLineInteraction()}createLengthText(){const t=this.calculateWallLengthInMeters(),i=this.formatLengthText(t),s=new Es(this.appService,{text:i,style:{fontSize:this.controlsConfig.textFontSize,fontFamily:this.controlsConfig.textFontFamily,fontWeight:this.controlsConfig.textFontWeight,fill:this.wallConfig.textColor,align:"center"}});s.anchor.set(.5);const r=this.calculateTextPosition();s.position.set(r.x,r.y);const o=this.calculateTextRotation();return s.rotation=o,s.eventMode="none",s}calculateWallLengthInMeters(){const{points:t}=this.wallData;if(t.length<2)return 0;const i=q(t[0],t[1]);return this.appService.coords.toMeters(Bt(i))}formatLengthText(t){const i=this.appService.coords.toDisplayUnit(et(t)),s=this.appService.runtimeSnapshot.unitLabel;return`${i.toFixed(1)}${s}`}calculateTextPosition(){const{points:t}=this.wallData;if(t.length<2)return{x:0,y:0};const[i,s]=t,r=this.appService.getApp().toFixedSize(this.wallConfig.textOffset);return _c(i,s,r)}calculateTextRotation(){const{points:t}=this.wallData;if(t.length<2)return 0;const[i,s]=t,r=this.appService.appContainer.getMapRotationRadians();return vs(i,s,r)}getOutlineStyle(){return{color:this.wallConfig.outlineStrokeColor,width:this.wallConfig.outlineStrokeWidth,isDashed:this.wallConfig.outlineDashed,dashArray:this.wallConfig.outlineDashArray,fillColor:this.wallConfig.outlineFillColor}}createOutlineBorder(){const t=this.calculateOutlinePoints();return new oi(this.appService,{points:t,closePath:!0,style:this.getOutlineStyle()})}createMoveLine(){const t=this.calculateOutlinePoints(),i=this.calculateMoveLinePoints(t);return new oi(this.appService,{points:i,closePath:!1,style:this.getOutlineStyle()})}calculateOutlinePoints(t){const i=t||this.wallData.points;if(i.length<2)return i;const s=this.appService.getApp().toFixedSize(this.wallConfig.outlineOffset),r=bx(i[0],i[1],s);return[r[3],r[2],r[1],r[0]]}calculateMoveLinePoints(t){if(t.length<4)return[];const{MOVE:i}=$t.BUTTON_INDICES,s=t[i],r=this.calculateMoveButtonPosition();return[s,r]}calculateMoveButtonPosition(){const{moveButtonOffset:t}=this.controlsConfig,i=this.calculateOutlinePoints();if(i.length<4)return{x:0,y:0};const{MOVE:s}=$t.BUTTON_INDICES,r=i[s],o=i[(s+3)%4],a=i[(s+1)%4],h=this.appService.getApp().toFixedSize(t);return Mc(r,a,o,h)}createControlButtons(){const t=this.calculateOutlinePoints();if(t.length<4)return;const{REMOVE:i,SCALE:s}=$t.BUTTON_INDICES;this.removeButton=new Hc(this.appService,{iconAlias:"deleteIcon",backgroundColor:this.wallConfig.iconWrapperFillColor,onClick:this.handleRemove}),this.removeButton.position.set(t[i].x,t[i].y),this.scaleButton=new bs(this.appService,{iconAlias:"scaleIcon",backgroundColor:this.wallConfig.iconWrapperFillColor,getTargetPoints:()=>this.calculateOutlinePoints(),getButtonIndex:()=>s,onScaleStart:this.handleScaleStart,onScaleMove:this.handleScaleMove,onScaleEnd:this.handleScaleEnd}),this.scaleButton.position.set(t[s].x,t[s].y);const r=this.calculateMoveButtonPosition();this.moveButton=new Uc(this.appService,{iconAlias:"moveIcon",backgroundColor:this.wallConfig.iconWrapperFillColor,onMoveStart:this.handleMoveStart,onMoveMove:this.handleMove,onMoveEnd:this.handleMoveEnd}),this.moveButton.position.set(r.x,r.y),this.controlButtons.addChild(this.removeButton),this.controlButtons.addChild(this.scaleButton),this.controlButtons.addChild(this.moveButton)}applyScaleAndRotation(t){if(this.initialWallPoints.length<2)return;const[i,s]=this.initialWallPoints,r=i,o=this.calculateOutlinePoints(this.initialWallPoints);if(o.length<4)return;const a=o[$t.BUTTON_INDICES.SCALE],l=mt(s,a),c={x:t.x-l.x,y:t.y-l.y},d=mt(r,c),u=q(r,c),{coords:p}=this.appService,g=p.toPixels(et(this.wallConfig.minWidth)),m=this.getResolvedMaxWidth(),y=m!=null?p.toPixels(et(m)):void 0;let x;if(u<g)if(u===0)x={x:r.x+g,y:r.y};else{const S=Tt(d);x={x:r.x+S.x*g,y:r.y+S.y*g}}else if(y!=null&&u>y){const S=Tt(d);x={x:r.x+S.x*y,y:r.y+S.y*y}}else x=c;this.wallData.points=[r,x],this.drawVirtualWall(),this.updateControlButtonsPosition()}applyTranslation(t,i){this.wallData.points=this.initialWallPoints.map(s=>({x:s.x+t,y:s.y+i})),this.drawVirtualWall(),this.updateControlButtonsPosition()}drawVirtualWall(){this.updateWallLine(),this.updateLengthText(),this.updateOutlineComponents()}updateWallLine(){const{points:t}=this.wallData;t.length<2||(this.wallLine instanceof Ne?this.wallLine.updatePoints(t[0],t[1]):this.redrawSolidLine(),this.setupWallLineHitArea())}updateLengthText(){if(!this.lengthText)return;const t=this.calculateWallLengthInMeters(),i=this.formatLengthText(t);this.lengthText.updateText(i),this.updateLengthTextPosition()}updateLengthTextPosition(){if(!this.lengthText)return;const t=this.calculateTextPosition();this.lengthText.position.set(t.x,t.y);const i=this.calculateTextRotation();this.lengthText.rotation=i}updateOutlineComponents(){const t=this.calculateOutlinePoints();this.outlineBorder.updatePoints(t);const i=this.calculateMoveLinePoints(t);this.moveLine.updatePoints(i)}updateControlButtonsPosition(){if(!this.removeButton||!this.scaleButton||!this.moveButton)return;const t=this.calculateOutlinePoints();if(t.length<4)return;const{REMOVE:i,SCALE:s}=$t.BUTTON_INDICES,r=this.calculateMoveButtonPosition();this.removeButton.position.set(t[i].x,t[i].y),this.scaleButton.position.set(t[s].x,t[s].y),this.moveButton.position.set(r.x,r.y)}updateEditState(){const t=this.isEditingEnabled();this.controlButtons.visible=t,this.outlineBorder.visible=t,this.moveLine.visible=t,this.lengthText&&(this.lengthText.visible=t),t&&(this.updateOutlineComponents(),this.updateControlButtonsPosition(),this.updateLengthTextPosition()),this.updateWallLineStyle(),this.setupWallLineInteraction(),this.zIndex=t?1e3:0}createSolidLine(t,i,s,r){const o=new U;o.eventMode="static";const a=this.appService.getApp().toFixedSize(s);return o.moveTo(t.x,t.y),o.lineTo(i.x,i.y),o.stroke({color:r,width:a}),o}updateWallLineStyle(){const t=this.isEditingEnabled(),{editing:i,normal:s,lineWidth:r,lineColor:o}=this.wallConfig,a=t?i:s;this.wallLine instanceof Ne!==a.isDashed?(this.removeChild(this.wallLine),this.wallLine.destroy(),this.createWallLine(!1),this.addChild(this.wallLine)):this.wallLine instanceof Ne?this.wallLine.updateStyle({color:o.toString(),width:r,dashArray:a.dashArray}):this.redrawSolidLine()}redrawSolidLine(){const t=this.appService;if(!this.wallLine||this.wallLine instanceof Ne)return;const{points:i}=this.wallData;if(i.length<2)return;const{lineWidth:s,lineColor:r}=this.wallConfig,o=t.getApp().toFixedSize(s);this.wallLine.clear(),this.wallLine.setStrokeStyle({color:r.toString(),width:o}).moveTo(i[0].x,i[0].y).lineTo(i[1].x,i[1].y).stroke()}setupWallLineInteraction(){var i;if(!this.wallLine)return;this.setupWallLineHitArea();const t=this.isEditingEnabled();(i=this.wallLineClickHandler)==null||i.destroy(),this.wallLineClickHandler=null,this.wallLine.off("pointerdown",this.handleWallLinePointerDown),t?this.wallLine.on("pointerdown",this.handleWallLinePointerDown):this.wallLineClickHandler=new vt(this.wallLine,{onClick:()=>{var s,r;this.appService.gestureController.suppressMapClick(),(r=(s=this.wallEvents)==null?void 0:s.onClick)==null||r.call(s,this.getWallData())},stopPropagation:!1})}startDragging(t){const i=this.appService;this.isDragging=!0;const s=this.parent.toLocal(t.global);this.dragStartPosition={x:s.x,y:s.y},this.initializeOperation(),i.getApp().requestRender("virtualwall-drag",!0),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}getDragStartPosition(){return this.dragStartPosition}setupWallLineHitArea(){if(!this.wallLine)return;const{points:t}=this.wallData;if(t.length<2)return;const{hitAreaThickness:i}=this.wallConfig,s=this.appService.getApp().toFixedSize(i),r=Pc(t[0],t[1],s);if(r.length===0)return;const o=new ke(r);this.wallLine.hitArea=o}getWallData(){return{...this.wallData}}updateWallData(t){this.wallData={...t,points:this.validateAndCorrectWallLength(t.points)},this.drawVirtualWall(),this.updateControlButtonsPosition()}updateEditingState(){this.updateEditState()}refreshDisplay(){this.drawVirtualWall()}destroy(){var t,i,s,r,o,a,h,l,c,d;this.appService.emitter.off("antiScale",this.throttledUpdateOutline),this.appService.emitter.off("antiScale",this.throttledHandleScaleChange),this.appService.emitter.off("mapRotationUpdate",this.throttledUpdateOutline),this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null),(t=this.gestureSession)==null||t.cancel(),this.gestureSession=null,this.wallLine&&this.wallLine.off("pointerdown",this.handleWallLinePointerDown),(i=this.wallLineClickHandler)==null||i.destroy(),this.wallLineClickHandler=null,(s=this.wallLine)==null||s.destroy(),(r=this.lengthText)==null||r.destroy(),(o=this.outlineBorder)==null||o.destroy(),(a=this.moveLine)==null||a.destroy(),(h=this.controlButtons)==null||h.destroy(),(l=this.removeButton)==null||l.destroy(),(c=this.scaleButton)==null||c.destroy(),(d=this.moveButton)==null||d.destroy(),this.removeButton=null,this.scaleButton=null,this.moveButton=null,super.destroy()}};f($t,"BUTTON_INDICES",{REMOVE:0,SCALE:2,MOVE:3});let xr=$t;class AS extends L{constructor(t){super();f(this,"thresholdData");f(this,"thresholdConfig");f(this,"thresholdEvents");f(this,"appService");f(this,"band");f(this,"bandFill");f(this,"bandStripes");f(this,"bandBorder");f(this,"stripesMask");f(this,"editableShape");f(this,"bandClickHandler",null);f(this,"initialPoints",null);f(this,"isDragging",!1);f(this,"hasDragMoved",!1);f(this,"dragStartPosition",null);f(this,"gestureSession",null);f(this,"resolvedMaxLengthCache",null);f(this,"resolvedMaxHeightCache",null);f(this,"throttledRedraw");f(this,"resolveSizeConstraintPerEdge",()=>({edge1:{min:this.thresholdConfig.minLength,max:this.getResolvedMaxLength()},edge2:{min:this.thresholdConfig.minHeight,max:this.getResolvedMaxHeight()}}));f(this,"handleRemove",()=>{var t,i;(i=(t=this.thresholdEvents).onRemove)==null||i.call(t,this.thresholdData.id)});f(this,"handleRotateStart",()=>{this.appService.getApp().requestRender("threshold-rotate",!0)});f(this,"handleRotateMove",t=>{t&&(this.setFromQuad(t),this.refreshAfterGeometryChange())});f(this,"handleRotateEnd",()=>{var t,i;this.appService.getApp().stopRender("threshold-rotate"),(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())});f(this,"handleScaleStart",()=>{this.appService.getApp().requestRender("threshold-scale",!0)});f(this,"handleScaleMove",t=>{t&&(this.setFromQuad(t),this.refreshAfterGeometryChange())});f(this,"handleScaleEnd",()=>{var t,i;this.appService.getApp().stopRender("threshold-scale"),(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())});f(this,"handleMoveStart",()=>{this.initialPoints=this.clonePoints(),this.appService.getApp().requestRender("threshold-move",!0)});f(this,"handleMoveMove",t=>{var r;if(!this.initialPoints||!this.parent)return;const i=this.parent.toLocal(t.global),s=(r=this.editableShape.getMoveButton())==null?void 0:r.getDragStartPosition();s&&this.applyTranslation(i.x-s.x,i.y-s.y)});f(this,"handleMoveEnd",()=>{var t,i;this.initialPoints=null,this.appService.getApp().stopRender("threshold-move"),(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())});f(this,"handleBandPointerDown",t=>{this.isEditingEnabled()&&(t.stopPropagation(),this.startDragging(t))});f(this,"handleDragPointerMove",t=>{if(!this.isDragging||!this.dragStartPosition||!this.initialPoints)return;this.hasDragMoved=!0;const i=this.parent.toLocal(t.global);this.applyTranslation(i.x-this.dragStartPosition.x,i.y-this.dragStartPosition.y)});f(this,"handleDragPointerUp",()=>{var t,i;this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.initialPoints=null,this.appService.getApp().stopRender("threshold-drag"),this.hasDragMoved&&(this.hasDragMoved=!1,(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())))});const{appService:i,thresholdData:s,events:r={}}=t;this.appService=i,this.thresholdEvents=r,this.thresholdConfig=i.controlsConfig.threshold,this.thresholdData=this.validateAndCorrect(s),this.band=new L,this.bandFill=new U,this.bandStripes=new U,this.bandBorder=new U,this.stripesMask=new U,this.bandFill.eventMode="none",this.bandStripes.eventMode="none",this.bandBorder.eventMode="none",this.stripesMask.eventMode="none",this.bandStripes.mask=this.stripesMask,this.band.addChild(this.bandFill),this.band.addChild(this.bandStripes),this.band.addChild(this.bandBorder),this.band.addChild(this.stripesMask),this.addChild(this.band),this.drawBand(),this.eventMode="passive",this.setupBandInteraction(),this.editableShape=this.createEditControls(),this.updateEditState(),this.throttledRedraw=_t(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.appService.emitter.on("antiScale",this.throttledRedraw)}getThresholdData(){const[t,i]=this.thresholdData.points;return{...this.thresholdData,points:[{...t},{...i}]}}updateThresholdData(t){this.thresholdData=this.validateAndCorrect(t),this.refreshAfterGeometryChange()}updateEditingState(){this.updateEditState()}refreshDisplay(){this.editableShape.updatePoints(this.getQuadPoints())}isEditingEnabled(){return this.appService.runtimeSnapshot.editingThresholdIds.includes(this.thresholdData.id)}updateEditState(){this.editableShape.setEditing(this.isEditingEnabled()),this.zIndex=this.isEditingEnabled()?1e3:0}getQuadPoints(){const[t,i]=this.thresholdData.points;if(q(t,i)===0)return[];const s=Tt(mt(t,i)),r={x:-s.y,y:s.x},o=this.thresholdData.height/2;return[{x:t.x-r.x*o,y:t.y-r.y*o},{x:i.x-r.x*o,y:i.y-r.y*o},{x:i.x+r.x*o,y:i.y+r.y*o},{x:t.x+r.x*o,y:t.y+r.y*o}]}setFromQuad(t){if(t.length<4)return;const[i,s,r,o]=t;this.thresholdData={...this.thresholdData,points:[{x:(i.x+o.x)/2,y:(i.y+o.y)/2},{x:(s.x+r.x)/2,y:(s.y+r.y)/2}],height:q(i,o)}}createEditControls(){const t=this.thresholdConfig,i=this.appService.controlsConfig,s=new Hs({editControls:this.appService.editControlManager}),r={config:{outlineStrokeColor:t.outlineStrokeColor,outlineStrokeWidth:t.outlineStrokeWidth,outlineDashed:t.outlineDashed,outlineDashArray:t.outlineDashArray,outlineFillColor:t.outlineFillColor,outlineOffset:t.outlineOffset,iconWrapperFillColor:t.iconWrapperFillColor,showRotateButton:!0,showScaleButton:!0,showRadialScaleButton:!1,showDeleteButton:!0,showMoveButton:!0,rotateMode:"free",scaleMode:"free",textColor:t.textColor,textPosition:"top",textOffset:t.textOffset,moveButtonOffset:i.moveButtonOffset,textFontSize:i.textFontSize,textFontFamily:i.textFontFamily,textFontWeight:i.textFontWeight},zonePoints:this.getQuadPoints(),sizeConstraintPerEdge:this.resolveSizeConstraintPerEdge,contentLayer:ce,events:{onRemove:this.handleRemove,onRotateStart:this.handleRotateStart,onRotateMove:this.handleRotateMove,onRotateEnd:this.handleRotateEnd,onScaleStart:this.handleScaleStart,onScaleMove:this.handleScaleMove,onScaleEnd:this.handleScaleEnd,onMoveStart:this.handleMoveStart,onMoveMove:this.handleMoveMove,onMoveEnd:this.handleMoveEnd}};return s.attach(this,{id:this.thresholdData.id,topology:"quad",layerOptions:r,editingState:{showRotateButton:!0,showScaleButton:!0,showRadialScaleButton:!1,showDeleteButton:!0,showMoveButton:!0,showBorder:!0,showSizeText:!0},idleState:{showRotateButton:!1,showScaleButton:!1,showRadialScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}}),s}setupBandInteraction(){this.updateBandHitArea(),this.bandClickHandler=new vt(this.band,{onClick:()=>{var t,i;this.appService.gestureController.suppressMapClick(),(i=(t=this.thresholdEvents).onClick)==null||i.call(t,this.getThresholdData())},stopPropagation:!1}),this.band.on("pointerdown",this.handleBandPointerDown)}updateBandHitArea(){const[t,i]=this.thresholdData.points,s=q(t,i),r=this.appService.getApp().toFixedSize(this.thresholdConfig.hitAreaPadding),o=this.thresholdData.height+r*2;this.band.hitArea=new tt(0,-o/2,s,o)}startDragging(t){this.isDragging=!0,this.hasDragMoved=!1;const i=this.parent.toLocal(t.global);this.dragStartPosition={x:i.x,y:i.y},this.initialPoints=this.clonePoints(),this.appService.getApp().requestRender("threshold-drag",!0),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}applyTranslation(t,i){if(!this.initialPoints)return;const[s,r]=this.initialPoints;this.thresholdData={...this.thresholdData,points:[{x:s.x+t,y:s.y+i},{x:r.x+t,y:r.y+i}]},this.refreshAfterGeometryChange()}refreshAfterGeometryChange(){this.drawBand(),this.updateBandHitArea(),this.editableShape.updatePoints(this.getQuadPoints())}clonePoints(){const[t,i]=this.thresholdData.points;return[{...t},{...i}]}handleScaleChange(){this.drawBand(),this.updateBandHitArea()}getResolvedMaxLength(){const t=this.thresholdConfig.maxLength;if(this.resolvedMaxLengthCache&&this.resolvedMaxLengthCache.key===t)return this.resolvedMaxLengthCache.value;const i=ri(this.thresholdConfig.minLength,t,"threshold");return this.resolvedMaxLengthCache={key:t,value:i},i}getResolvedMaxHeight(){const t=this.thresholdConfig.maxHeight;if(this.resolvedMaxHeightCache&&this.resolvedMaxHeightCache.key===t)return this.resolvedMaxHeightCache.value;const i=ri(this.thresholdConfig.minHeight,t,"threshold.height");return this.resolvedMaxHeightCache={key:t,value:i},i}validateAndCorrect(t){return{...t,points:this.validateAndCorrectLength(t.points),height:this.validateAndCorrectHeight(t.height),type:t.type??"passable"}}validateAndCorrectLength(t){const[i,s]=t,{coords:r}=this.appService,o=r.toPixels(et(this.thresholdConfig.minLength)),a=this.getResolvedMaxLength(),h=a!=null?r.toPixels(et(a)):void 0,l=q(i,s),c=l<o,d=h!=null&&l>h;if(!c&&!d)return[{...i},{...s}];if(l===0)return[{...i},{x:i.x+o,y:i.y}];const u=Tt(mt(i,s));let p=l;return h!=null&&(p=Math.min(p,h)),p=Math.max(p,o),[{...i},{x:i.x+u.x*p,y:i.y+u.y*p}]}validateAndCorrectHeight(t){const{coords:i}=this.appService,s=i.toPixels(et(this.thresholdConfig.minHeight)),r=this.getResolvedMaxHeight(),o=r!=null?i.toPixels(et(r)):void 0;let a=t!=null&&Number.isFinite(t)&&t>0?t:i.toPixels(et(this.thresholdConfig.defaultHeight));return o!=null&&(a=Math.min(a,o)),Math.max(a,s)}getTypeStyle(){return this.thresholdData.type==="passable"?this.thresholdConfig.passable:this.thresholdConfig.impassable}drawBand(){const[t,i]=this.thresholdData.points,{stripeWidth:s,stripeGap:r,borderWidth:o,cornerRadius:a}=this.thresholdConfig,h=this.getTypeStyle(),l=this.appService.getApp(),c=this.thresholdData.height,d=l.toFixedSize(s),u=l.toFixedSize(r),p=l.toFixedSize(o);this.bandFill.clear(),this.bandStripes.clear(),this.bandBorder.clear(),this.stripesMask.clear();const g=q(t,i);if(g===0)return;this.band.position.set(t.x,t.y),this.band.rotation=Math.atan2(i.y-t.y,i.x-t.x);const m=c/2,y=Math.min(l.toFixedSize(a),m,g/2);this.bandFill.roundRect(0,-m,g,c,y).fill(h.fillColor),this.bandBorder.roundRect(0,-m,g,c,y).stroke({color:h.color,width:p}),this.stripesMask.roundRect(0,-m,g,c,y).fill(16777215);const x=d+u;if(x<=0)return;let S=!1;for(let v=-c;v<g;v+=x){let b=v,P=-m,C=v+c,_=m;b<0&&(P+=-b,b=0),C>g&&(_-=C-g,C=g),!(b>=C)&&(this.bandStripes.moveTo(b,P).lineTo(C,_),S=!0)}S&&this.bandStripes.stroke({color:h.color,width:d})}destroy(){var t,i;this.appService.emitter.off("antiScale",this.throttledRedraw),this.editableShape.detach(),this.isDragging&&(this.isDragging=!1,this.hasDragMoved=!1,this.dragStartPosition=null,this.initialPoints=null),(t=this.gestureSession)==null||t.cancel(),this.gestureSession=null,this.band.off("pointerdown",this.handleBandPointerDown),(i=this.bandClickHandler)==null||i.destroy(),this.bandClickHandler=null,this.bandStripes.mask=null,this.bandFill.destroy(),this.bandStripes.destroy(),this.bandBorder.destroy(),this.stripesMask.destroy(),this.band.destroy(),super.destroy()}}const TS={fontSize:12,fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:"400",color:"#5d68fe",position:"top",offset:-8,editing:{visible:!0},normal:{visible:!0}};class so extends L{constructor(t){super();f(this,"spotData");f(this,"spotConfig");f(this,"controlsConfig");f(this,"spotEvents");f(this,"appService");f(this,"controlFill");f(this,"spotBorder");f(this,"centerIcon");f(this,"sizeText");f(this,"nameText");f(this,"clickHandler",null);f(this,"initialSpotPoint",null);f(this,"dragStartMousePosition",null);f(this,"throttledUpdateScale");f(this,"unsubscribeMapRotation",null);f(this,"iconAlias");f(this,"editingIdsKey");f(this,"handleDragStart",t=>{this.isEditingEnabled()&&(this.initialSpotPoint={...this.spotData.point},this.dragStartMousePosition=this.parent.toLocal(t.global),this.appService.getApp().requestRender("spot-drag",!0))});f(this,"handleDragMove",t=>{if(!this.isEditingEnabled()||!this.initialSpotPoint||!this.dragStartMousePosition||!this.controlFill)return;const i=this.parent.toLocal(t.global),s=i.x-this.dragStartMousePosition.x,r=i.y-this.dragStartMousePosition.y;this.applyTranslation(s,r)});f(this,"handleDragEnd",()=>{var t,i;this.initialSpotPoint=null,this.dragStartMousePosition=null,this.appService.getApp().stopRender("spot-drag"),(i=(t=this.spotEvents).onUpdate)==null||i.call(t,this.getSpotData())});const{appService:i,spotData:s,events:r={},config:o,iconAlias:a,editingIdsKey:h}=t;this.appService=i,this.spotData=s,this.spotEvents=r,this.controlsConfig=this.appService.controlsConfig,this.spotConfig=o??this.appService.controlsConfig.spot,this.iconAlias=a??"spotIcon",this.editingIdsKey=h??"editingSpotIds",this.position.set(s.point.x,s.point.y),this.throttledUpdateScale=_t(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.updateEditState(),this.setupClickHandler(),this.registerScaleListener()}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}updateScale(){this.isEditingEnabled()&&this.sizeText&&this.updateSizeTextPosition(),this.nameText&&this.updateNameTextPosition()}isEditingEnabled(){return this.appService.runtimeSnapshot[this.editingIdsKey].includes(this.spotData.id)}shouldShowIcon(){return(this.isEditingEnabled()?this.spotConfig.editing:this.spotConfig.normal).showIcon}calculateRectanglePoints(){const{size:t}=this.spotConfig;if(t===0)return[{x:0,y:0},{x:0,y:0},{x:0,y:0},{x:0,y:0}];const s=this.appService.coords.toPixels(et(t))/2;return[{x:-s,y:-s},{x:s,y:-s},{x:s,y:s},{x:-s,y:s}]}initializeComponents(){const t=this.calculateRectanglePoints();this.spotConfig.size>0&&(this.controlFill=this.createControlFill(t),this.addChild(this.controlFill),this.spotBorder=this.createBorder(t),this.addChild(this.spotBorder)),this.centerIcon=this.createCenterIcon(),this.addChild(this.centerIcon),this.spotConfig.showText&&(this.sizeText=this.createSizeText(),this.addChild(this.sizeText)),this.calculateSpotNameText()&&(this.nameText=this.createNameText(),this.addChild(this.nameText)),this.drawSpot()}createControlFill(t){const i=this.isEditingEnabled();return new Jr(this.appService,{points:t,fillColor:this.spotConfig.fillColor,enableInteraction:i,onDragStart:this.handleDragStart,onDragMove:this.handleDragMove,onDragEnd:this.handleDragEnd})}createBorder(t){const s=this.isEditingEnabled()?this.spotConfig.editing:this.spotConfig.normal;return new oi(this.appService,{points:t,closePath:!0,style:{color:this.spotConfig.strokeColor,width:this.spotConfig.strokeWidth,isDashed:s.isDashed,dashArray:s.dashArray}})}createCenterIcon(){const t=new Zt(this.appService);return this.loadIconTexture(t),t.position.set(0,0),t.eventMode="static",this.setupIconDrag(t),t.visible=!1,t}async loadIconTexture(t){const{iconSize:i,iconSizeFixed:s,iconAnchor:r}=this.spotConfig;await t.loadTextureAndSetSize(this.iconAlias,{width:i,height:i,sizeFixed:s}),r&&t.anchor.set(r.x,r.y),this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation||(this.unsubscribeMapRotation=W(this.appService.runtime,"mapRotation",o=>{this.applyAntiRotation(o)})),t.visible=this.shouldShowIcon()}applyAntiRotation(t){const i=-t*Math.PI/180;this.rotation=i}setupIconDrag(t){let i=null,s=!1;const r=a=>{if(!s||!this.initialSpotPoint||!i)return;const h=this.parent.toLocal(a.global),l=h.x-i.x,c=h.y-i.y;this.applyTranslation(l,c)},o=()=>{var a,h;s&&(s=!1,this.initialSpotPoint=null,i=null,this.appService.getApp().stopRender("spot-drag"),(h=(a=this.spotEvents).onUpdate)==null||h.call(a,this.getSpotData()))};t.on("pointerdown",a=>{if(!this.isEditingEnabled())return;a.stopPropagation(),s=!0,this.initialSpotPoint={...this.spotData.point},i=this.parent.toLocal(a.global),this.appService.getApp().requestRender("spot-drag",!0);const h=this.appService.gestureController.hijack(a);h.onMove(r),h.onEnd(o)})}createSizeText(){const t=this.calculateSpotSizeText(),i=new Es(this.appService,{text:t,style:{fontSize:this.controlsConfig.textFontSize,fontFamily:this.controlsConfig.textFontFamily,fontWeight:this.controlsConfig.textFontWeight,fill:this.spotConfig.textColor,align:"center"}});i.anchor.set(.5);const s=this.calculateSizeTextPosition();return i.position.set(s.x,s.y),i.eventMode="none",i}calculateSpotSizeText(){const{size:t}=this.spotConfig,i=this.appService.coords.toDisplayUnit(et(t)),s=this.appService.runtimeSnapshot.unitLabel;return`${i.toFixed(1)}${s}*${i.toFixed(1)}${s}`}calculateSizeTextPosition(){const{textPosition:t,textOffset:i}=this.spotConfig;return this.calculateTextPosition(t,i)}calculateTextPosition(t,i){const s=this.calculateRectanglePoints();if(s.length<4)return{x:0,y:0};const[r,o,a,h]=s,l=this.appService.getApp().toFixedSize(i);let c,d;switch(t){case"top":{c={x:(r.x+o.x)/2,y:(r.y+o.y)/2},d={x:c.x,y:c.y+l};break}case"right":{c={x:(o.x+a.x)/2,y:(o.y+a.y)/2},d={x:c.x+l,y:c.y};break}case"bottom":{c={x:(h.x+a.x)/2,y:(h.y+a.y)/2},d={x:c.x,y:c.y+l};break}case"left":{c={x:(r.x+h.x)/2,y:(r.y+h.y)/2},d={x:c.x-l,y:c.y};break}default:{c={x:(r.x+o.x)/2,y:(r.y+o.y)/2},d={x:c.x,y:c.y+l};break}}return d}getNameLabelConfig(){return this.spotConfig.nameLabel??TS}createNameText(){const t=this.getNameLabelConfig(),i=new Es(this.appService,{text:this.calculateSpotNameText(),style:{fontSize:t.fontSize,fontFamily:t.fontFamily,fontWeight:t.fontWeight,fill:t.color,align:"center"}});i.anchor.set(.5);const s=this.calculateNameTextPosition();return i.position.set(s.x,s.y),i.eventMode="none",i}calculateSpotNameText(){var t;return((t=this.spotData.name)==null?void 0:t.trim())??""}calculateNameTextPosition(){const{position:t,offset:i}=this.getNameLabelConfig();return this.calculateTextPosition(t,i)}shouldShowNameText(){if(!this.calculateSpotNameText())return!1;const i=this.isEditingEnabled(),s=this.getNameLabelConfig();return(i?s.editing:s.normal).visible}applyTranslation(t,i){if(!this.initialSpotPoint)return;const s={x:this.initialSpotPoint.x+t,y:this.initialSpotPoint.y+i};this.spotData.roomId!==void 0&&!this.appService.mapManager.isPointInRoom(s,this.spotData.roomId)||(this.spotData.point=s,this.drawSpot())}setupClickHandler(){const t=this.spotConfig.size>0?this:this.centerIcon;this.clickHandler=new vt(t,{onClick:()=>{var i,s;this.isEditingEnabled()||(this.appService.gestureController.suppressMapClick(),(s=(i=this.spotEvents)==null?void 0:i.onClick)==null||s.call(i,this.getSpotData()))},stopPropagation:!1}),this.eventMode="static"}drawSpot(){const t=this.calculateRectanglePoints();this.position.set(this.spotData.point.x,this.spotData.point.y),this.spotConfig.size>0&&(this.controlFill&&this.controlFill.updatePoints(t),this.spotBorder&&this.spotBorder.updatePoints(t)),this.spotConfig.showText&&this.sizeText&&this.updateSizeText(),this.nameText&&this.updateNameText()}updateSizeText(){if(!this.sizeText)return;const t=this.calculateSpotSizeText();this.sizeText.updateText(t),this.updateSizeTextPosition()}updateSizeTextPosition(){if(!this.sizeText)return;const t=this.calculateSizeTextPosition();this.sizeText.position.set(t.x,t.y)}updateNameText(){this.nameText&&(this.nameText.updateText(this.calculateSpotNameText()),this.updateNameTextPosition())}updateNameTextPosition(){if(!this.nameText)return;const t=this.calculateNameTextPosition();this.nameText.position.set(t.x,t.y)}updateEditState(){const t=this.isEditingEnabled(),i=t?this.spotConfig.editing:this.spotConfig.normal;if(this.sizeText&&(this.sizeText.visible=t&&this.spotConfig.showText),this.nameText&&(this.nameText.visible=this.shouldShowNameText()),this.centerIcon){this.centerIcon.visible=this.shouldShowIcon();const s=this.spotConfig.iconAnchor;s&&this.centerIcon.anchor.set(s.x,s.y)}this.sizeText&&(this.sizeText.visible=this.spotConfig.showText),this.controlFill&&(this.controlFill.setInteractionEnabled(t),this.controlFill.visible=i.showFill??i.showFrame),this.spotBorder&&(this.spotBorder.updateStyle({isDashed:i.isDashed,dashArray:i.dashArray}),this.spotBorder.visible=i.showFrame),this.zIndex=t?1e3:0}updateSpotData(t){this.spotData={...t},!this.nameText&&this.calculateSpotNameText()&&(this.nameText=this.createNameText(),this.addChild(this.nameText)),this.drawSpot(),this.updateEditState()}getSpotData(){return{...this.spotData}}refreshDisplay(){this.drawSpot()}destroy(){var t,i,s,r,o,a;this.appService.emitter.off("antiScale",this.throttledUpdateScale),this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),(t=this.clickHandler)==null||t.destroy(),this.clickHandler=null,this.centerIcon&&this.spotConfig.size===0&&this.centerIcon.removeAllListeners(),(i=this.controlFill)==null||i.destroy(),(s=this.spotBorder)==null||s.destroy(),(r=this.centerIcon)==null||r.destroy(),(o=this.sizeText)==null||o.destroy(),(a=this.nameText)==null||a.destroy(),super.destroy()}static create(t,i,s){return new so({appService:t,spotData:i,config:s==null?void 0:s.config,iconAlias:s==null?void 0:s.iconAlias,editingIdsKey:s==null?void 0:s.editingIdsKey,events:(s==null?void 0:s.events)??{onUpdate:r=>{var o,a;(a=(o=t.events)==null?void 0:o.onUpdateSpot)==null||a.call(o,r)},onClick:r=>{var o,a;(a=(o=t.events)==null?void 0:o.onClickSpot)==null||a.call(o,r)}}})}}class RS extends Gc{constructor(t){const{appService:i,wayPointData:s,order:r,events:o={}}=t;super(i);f(this,"wayPointData");f(this,"order");f(this,"wayPointConfig");f(this,"controlsConfig");f(this,"wayPointEvents");f(this,"icon");f(this,"orderContainer");f(this,"orderBackground");f(this,"orderText");f(this,"clickHandler",null);f(this,"initialWayPointPoint",null);f(this,"unsubscribeMapRotation",null);this.wayPointData=s,this.order=r,this.wayPointEvents=o,this.controlsConfig=this.appService.controlsConfig,this.wayPointConfig=this.appService.controlsConfig.wayPoint,this.position.set(s.point.x,s.point.y),this.initializeComponents(),this.updateEditState(),this.setupClickHandler()}isEditingEnabled(){return(this.appService.runtimeSnapshot.editingWayPointIds||[]).includes(this.wayPointData.id)}initializeComponents(){this.icon=this.createIcon(),this.addChild(this.icon),this.wayPointConfig.showOrder&&(this.createOrderContainer(),this.addChild(this.orderContainer))}createIcon(){const t=new Zt(this.appService);return this.loadIconTexture(t),t.position.set(0,0),t.anchor.set(.5,1),t.eventMode="static",this.setupIconDrag(t),t}async loadIconTexture(t){const i=this.isEditingEnabled(),s=i?this.wayPointConfig.editing:this.wayPointConfig.normal,{iconSize:r}=s,o=i?"wayPointActive":"wayPoint";await t.loadTextureAndSetSize(o,{width:r,height:r,sizeFixed:!1}),this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation||(this.unsubscribeMapRotation=W(this.appService.runtime,"mapRotation",a=>{this.applyAntiRotation(a)})),t.visible=!0,this.orderContainer&&this.updateOrderPosition()}applyAntiRotation(t){const i=-t*Math.PI/180;this.rotation=i}createOrderContainer(){const i=this.isEditingEnabled()?this.wayPointConfig.editing:this.wayPointConfig.normal,{orderContainer:s,orderText:r}=i;this.orderContainer=new L,this.orderBackground=new U,this.orderText=new Ws({text:this.order.toString(),style:new ue({fontSize:r.fontSize,fontFamily:r.fontFamily,fontWeight:r.fontWeight,fill:r.color,align:"center",trim:!0})}),this.orderBackground.clear(),this.orderBackground.circle(0,0,s.size/2),this.orderBackground.fill({color:s.backgroundColor}),this.orderText.anchor.set(.5,.5),this.orderContainer.addChild(this.orderBackground),this.orderContainer.addChild(this.orderText),this.orderContainer.eventMode="none",this.orderContainer.visible=this.wayPointConfig.showOrder,this.updateOrderPosition()}updateOrderPosition(){if(!this.orderContainer)return;const i=this.isEditingEnabled()?this.wayPointConfig.editing:this.wayPointConfig.normal,{offsetX:s,offsetY:r}=i.orderContainer;this.orderContainer.position.set(s,-r)}setupIconDrag(t){let i=null,s=null,r=!1;const o=h=>{if(!(!r||!i||!s)&&this.parent){const l=this.parent.toLocal(h.global),c=l.x-i.x,d=l.y-i.y,u={x:s.x+c,y:s.y+d};this.wayPointData.point=u,this.position.set(u.x,u.y),this.orderContainer&&this.updateOrderPosition()}},a=()=>{var h,l;r&&(r=!1,i=null,s=null,(l=(h=this.wayPointEvents).onUpdate)==null||l.call(h,this.wayPointData))};t.on("pointerdown",h=>{if(this.isEditingEnabled()&&(h.stopPropagation(),s={...this.wayPointData.point},this.parent&&(i=this.parent.toLocal(h.global)),r=!0,this.parent)){const l=this.appService.gestureController.hijack(h);l.onMove(o),l.onEnd(a)}})}setupClickHandler(){this.clickHandler=new vt(this.icon,{stopPropagation:!1,onClick:()=>{var t,i;this.appService.gestureController.suppressMapClick(),(i=(t=this.wayPointEvents).onClick)==null||i.call(t,this.wayPointData)}})}updateWayPoint(t){this.wayPointData=t,this.drawWayPoint()}updateOrder(t){this.order=t,this.orderText&&(this.orderText.text=t.toString())}getWayPointData(){return{...this.wayPointData}}drawWayPoint(){this.position.set(this.wayPointData.point.x,this.wayPointData.point.y),this.orderContainer&&this.updateOrderPosition()}updateEditState(){if(this.loadIconTexture(this.icon),this.orderContainer&&this.orderText&&this.orderBackground){const i=this.isEditingEnabled()?this.wayPointConfig.editing:this.wayPointConfig.normal;this.orderText.style=new ue({fontSize:i.orderText.fontSize,fontFamily:i.orderText.fontFamily,fontWeight:i.orderText.fontWeight,fill:i.orderText.color,align:"center",trim:!0});const{size:s,backgroundColor:r}=i.orderContainer;this.orderBackground.clear(),this.orderBackground.circle(0,0,s/2).fill(r),this.orderContainer.visible=this.wayPointConfig.showOrder,this.updateOrderPosition()}}onEditStateChange(){this.updateEditState()}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),this.icon&&this.icon.removeAllListeners(),super.destroy()}}class uh extends U{constructor(t,i){super();f(this,"isDragging",!1);f(this,"dragStartPosition",null);f(this,"initialPosition");f(this,"gestureSession",null);f(this,"handleDragPointerMove",t=>{var a,h;if(!this.isDragging||!this.dragStartPosition)return;const i=this.parent.toLocal(t.global),s=i.x-this.dragStartPosition.x,r=i.y-this.dragStartPosition.y,o={x:this.initialPosition.x+s,y:this.initialPosition.y+r};this.position.set(o.x,o.y),(h=(a=this.options).onDragMove)==null||h.call(a,o)});f(this,"handleDragPointerUp",()=>{var i,s;if(this.gestureSession=null,!this.isDragging)return;const t=this.appService;this.isDragging=!1,this.dragStartPosition=null,t.getApp().stopRender("endpoint-drag"),(s=(i=this.options).onDragEnd)==null||s.call(i)});this.appService=t,this.options=i,this.initialPosition={...i.position},this.position.set(i.position.x,i.position.y),this.eventMode="static",this.cursor="pointer",this.setupEvents(),this.draw()}draw(){const t=this.appService,{config:i}=this.options,s=t.getApp().toFixedSize(i.endPointSize),r=t.getApp().toFixedSize(i.endPointStrokeWidth);this.clear(),this.circle(0,0,s/2),this.fill({color:i.endPointColor}),this.stroke({color:i.endPointStrokeColor,width:r}),this.setupHitArea()}setupHitArea(){const t=this.appService,{config:i}=this.options,s=Math.max(i.endPointSize/2+10,20),r=t.getApp().toFixedSize(s);this.hitArea=new zs(0,0,r)}setupEvents(){this.on("pointerdown",this.handlePointerDown.bind(this))}handlePointerDown(t){t.stopPropagation(),this.startDragging(t)}startDragging(t){var s,r;const i=this.appService;this.isDragging=!0,this.dragStartPosition=this.parent.toLocal(t.global),this.initialPosition={x:this.x,y:this.y},(r=(s=this.options).onDragStart)==null||r.call(s),i.getApp().requestRender("endpoint-drag",!0),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}updatePosition(t){this.position.set(t.x,t.y),this.initialPosition={...t}}getPosition(){return{x:this.x,y:this.y}}redraw(){this.draw()}destroy(){var t;this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null),(t=this.gestureSession)==null||t.cancel(),this.gestureSession=null,this.off("pointerdown",this.handlePointerDown),super.destroy()}}class kS extends L{constructor(t){super();f(this,"endPoints");f(this,"dividerConfig");f(this,"dividerEvents");f(this,"roomId");f(this,"appService");f(this,"roomGeometry",null);f(this,"dashLine");f(this,"solidLine",null);f(this,"startEndPoint");f(this,"endEndPoint");f(this,"solidLinePoints",null);f(this,"initialDividerPoints",[]);f(this,"isDragging",!1);f(this,"dragStartPosition",null);f(this,"gestureSession",null);f(this,"throttledHandleScaleChange");f(this,"handleEndPointDragStart",()=>{this.initialDividerPoints=this.endPoints.map(t=>({...t})),this.clearSolidLine(),this.appService.getApp().requestRender("divider-endpoint-drag",!0)});f(this,"handleEndPointDragMove",(t,i)=>{this.initialDividerPoints.length!==0&&(this.endPoints[t]=i,this.updateDashLine(),this.updateSolidLine(),this.setupDashLineHitArea())});f(this,"handleEndPointDragEnd",()=>{var t,i;this.initialDividerPoints=[],this.appService.getApp().stopRender("divider-endpoint-drag"),this.calculateAndCreateSolidLine(),this.checkAndResetIfOutOfRoom(),(i=(t=this.dividerEvents).onUpdate)==null||i.call(t,this.getDividerEndPoints())});f(this,"handleDashLinePointerDown",t=>{t.stopPropagation(),this.startDragging(t)});f(this,"handleDragPointerMove",t=>{if(!this.isDragging||!this.dragStartPosition||this.initialDividerPoints.length===0)return;const i=this.parent.toLocal(t.global),s=i.x-this.dragStartPosition.x,r=i.y-this.dragStartPosition.y;this.endPoints=this.initialDividerPoints.map(o=>({x:o.x+s,y:o.y+r})),this.updateAllComponents()});f(this,"handleDragPointerUp",()=>{var t,i;this.gestureSession=null,this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.initialDividerPoints=[],this.appService.getApp().stopRender("divider-drag"),this.calculateAndCreateSolidLine(),this.checkAndResetIfOutOfRoom(),(i=(t=this.dividerEvents).onUpdate)==null||i.call(t,this.getDividerEndPoints()))});f(this,"handleScaleChange",()=>{var t,i;(t=this.startEndPoint)==null||t.redraw(),(i=this.endEndPoint)==null||i.redraw(),this.updateSolidLine(),this.setupDashLineHitArea()});const{appService:i,endPoints:s,roomId:r,events:o={}}=t;this.appService=i,this.dividerEvents=o,this.roomId=r,this.dividerConfig=this.appService.dividerConfig,this.roomGeometry=this.appService.mapManager.getRoomById(this.roomId)||null,s?this.endPoints=this.validateDividerPoints(s):this.endPoints=this.createDefaultdividerPoints(),this.throttledHandleScaleChange=_t(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.initializeComponents(),this.calculateAndCreateSolidLine(),this.registerScaleListener()}validateDividerPoints(t){if(t.length>=2)return t.slice(0,2);const i=t[0]||{x:0,y:0},s={x:i.x+50,y:i.y};return[i,s]}createDefaultdividerPoints(){if(!this.roomGeometry)return w.warn("Room geometry not available, creating fallback divider"),[{x:0,y:0},{x:100,y:0}];const t=this.appService.getApp().mapState;if(!t)return w.warn("Map state not available, creating fallback divider"),[{x:0,y:0},{x:100,y:0}];const{boundingBox:i}=this.roomGeometry,s=this.appService.getApp().toFixedSize(this.dividerConfig.defaultExtension),r=this.dividerConfig.defaultDirection,o=i.x+i.width/2,a=i.y+i.height/2,h=r==="horizontal"?i.width+2*s:i.height+2*s;return kx(o,a,h,r).map(c=>({x:c.x-t.origin.x,y:c.y-t.origin.y}))}initializeComponents(){this.createDashLine(),this.addChild(this.dashLine),this.createEndPoints(),this.addChild(this.startEndPoint),this.addChild(this.endEndPoint),this.setupDashLineInteraction()}createDashLine(){const t=this.endPoints;if(t.length<2)return;const{dashLineWidth:i,dashLineDashArray:s,lineColor:r}=this.dividerConfig;this.dashLine=new Ne(this.appService,{start:t[0],end:t[1],style:{color:r.toString(),width:i,dashArray:s}})}createEndPoints(){const t=this.endPoints;this.startEndPoint=new uh(this.appService,{position:t[0],config:this.dividerConfig,onDragStart:this.handleEndPointDragStart,onDragMove:i=>this.handleEndPointDragMove(0,i),onDragEnd:this.handleEndPointDragEnd}),this.endEndPoint=new uh(this.appService,{position:t[1],config:this.dividerConfig,onDragStart:this.handleEndPointDragStart,onDragMove:i=>this.handleEndPointDragMove(1,i),onDragEnd:this.handleEndPointDragEnd})}setupDashLineInteraction(){this.dashLine&&(this.setupDashLineHitArea(),this.dashLine.off("pointerdown",this.handleDashLinePointerDown),this.dashLine.on("pointerdown",this.handleDashLinePointerDown))}setupDashLineHitArea(){if(!this.dashLine)return;const t=this.endPoints;if(t.length<2)return;const{hitAreaThickness:i}=this.dividerConfig,s=this.appService.getApp().toFixedSize(i),r=Pc(t[0],t[1],s);if(r.length===0)return;const o=new ke(r);this.dashLine.hitArea=o}startDragging(t){this.isDragging=!0;const i=this.parent.toLocal(t.global);this.dragStartPosition={x:i.x,y:i.y},this.initialDividerPoints=this.endPoints.map(s=>({...s})),this.clearSolidLine(),this.appService.getApp().requestRender("divider-drag",!0),this.gestureSession=this.appService.gestureController.hijack(t),this.gestureSession.onMove(this.handleDragPointerMove),this.gestureSession.onEnd(this.handleDragPointerUp)}updateAllComponents(){this.updateDashLine(),this.updateSolidLine(),this.updateEndPoints(),this.setupDashLineHitArea()}updateDashLine(){const t=this.endPoints;t.length<2||!this.dashLine||this.dashLine.updatePoints(t[0],t[1])}updateSolidLine(){if(!this.solidLine||!this.solidLinePoints)return;const{solidLineWidth:t,lineColor:i}=this.dividerConfig,s=this.appService.getApp().toFixedSize(t);this.solidLine.clear(),this.solidLine.setStrokeStyle({color:i.toString(),width:s}).moveTo(this.solidLinePoints[0].x,this.solidLinePoints[0].y).lineTo(this.solidLinePoints[1].x,this.solidLinePoints[1].y).stroke()}updateEndPoints(){const t=this.endPoints;this.startEndPoint&&this.startEndPoint.updatePosition(t[0]),this.endEndPoint&&this.endEndPoint.updatePosition(t[1])}registerScaleListener(){const{emitter:t}=this.appService;t.on("antiScale",this.throttledHandleScaleChange)}getDividerEndPoints(){return[...this.endPoints]}getEffectiveDividerPoints(){return this.solidLinePoints?[...this.solidLinePoints]:null}calculateAndCreateSolidLine(){if(this.clearSolidLine(),typeof this.roomId!="number"||!this.getRoomGraphics())return;const i=this.calculateLineRoomIntersection();i&&i.length>=2&&(this.solidLinePoints=[i[0],i[i.length-1]],this.createSolidLine())}getRoomGraphics(){const t=this.appService.mapManager.roomFill;return!t||typeof this.roomId!="number"?null:t.getRoomGraphicsMap().get(this.roomId)||null}calculateLineRoomIntersection(){const t=this.endPoints;if(t.length<2||typeof this.roomId!="number")return null;const[i,s]=t,r=this.isPointInRoomFill(i),o=this.isPointInRoomFill(s);if(r||o)return null;const a=ux(i,s),h=[];for(const p of a)this.isPointInRoomFill(p)&&h.push(p);if(h.length===0)return null;const l=h[0],c=h[h.length-1];return q(l,c)<3?null:Ix(l,c,.5)}isPointInRoomFill(t){if(typeof this.roomId!="number")return!1;const i=this.appService.getApp().mapState;if(!i)return!1;const s={x:t.x+i.origin.x,y:t.y+i.origin.y};return i.mapType==="raster"?this.isPointInRasterRoomFill(s):this.isPointInStructuredRoomFill(s)}isPointInRasterRoomFill(t){t.x-=.5,t.y-=.5;const i=this.appService.getApp().mapState,s=this.appService.mapManager.roomFill;if(!i||!s)return!1;const r=s.getRasterRoomData(this.roomId);if(!r)return!1;const o=s.getMapWidth();if(o===0)return!1;const a=Math.round(t.x),h=Math.round(t.y);if(a<0||h<0||a>=o)return!1;const l=h*o+a;for(let c=0;c<r.pixelIndices.length;c++)if(r.pixelIndices[c]===l)return!0;return!1}isPointInStructuredRoomFill(t){const i={x:Math.round(t.x),y:Math.round(t.y)},s=this.appService.getApp().mapState,r=this.appService.mapManager.getRoomById(this.roomId);return!s||!r||!r.outlinePoints?!1:It(i,r.outlinePoints,!0)}isDividerCompletelyOutOfRoom(){if(!this.roomGeometry)return!1;const{boundingBox:t}=this.roomGeometry,i=this.endPoints;if(i.length<2)return!1;const s=this.appService.getApp().mapState;if(!s)return!1;const r={x:i[0].x+s.origin.x,y:i[0].y+s.origin.y},o={x:i[1].x+s.origin.x,y:i[1].y+s.origin.y};return!Rx(r,o,t.x,t.y,t.width,t.height)}checkAndResetIfOutOfRoom(){const{resetDividerWhenOutOfRoom:t}=this.appService.dividerConfig;t&&this.isDividerCompletelyOutOfRoom()&&this.resetToDefaultState()}resetToDefaultState(){var t,i;this.endPoints=this.createDefaultdividerPoints(),this.calculateAndCreateSolidLine(),this.updateComponents(),(i=(t=this.dividerEvents).onUpdate)==null||i.call(t,this.endPoints)}updateComponents(){const t=this.endPoints;t.length>=2&&(this.dashLine.updatePoints(t[0],t[1]),this.startEndPoint.position.set(t[0].x,t[0].y),this.endEndPoint.position.set(t[1].x,t[1].y),this.setupDashLineInteraction())}createSolidLine(){if(!this.solidLinePoints)return;const{solidLineWidth:t,lineColor:i}=this.dividerConfig;this.solidLine=new U,this.solidLine.eventMode="none";const s=this.appService.getApp().toFixedSize(t);this.solidLine.setStrokeStyle({color:i.toString(),width:s}).moveTo(this.solidLinePoints[0].x,this.solidLinePoints[0].y).lineTo(this.solidLinePoints[1].x,this.solidLinePoints[1].y).stroke(),this.addChildAt(this.solidLine,0)}clearSolidLine(){this.solidLine&&(this.removeChild(this.solidLine),this.solidLine.destroy(),this.solidLine=null),this.solidLinePoints=null}updatedividerPoints(t){this.endPoints=this.validateDividerPoints(t),this.updateAllComponents(),this.calculateAndCreateSolidLine()}destroy(){var t,i,s,r;this.appService.emitter.off("antiScale",this.throttledHandleScaleChange),this.isDragging&&(this.isDragging=!1,this.dragStartPosition=null,this.initialDividerPoints=[]),(t=this.gestureSession)==null||t.cancel(),this.gestureSession=null,this.dashLine&&this.dashLine.off("pointerdown",this.handleDashLinePointerDown),this.clearSolidLine(),(i=this.dashLine)==null||i.destroy(),(s=this.startEndPoint)==null||s.destroy(),(r=this.endEndPoint)==null||r.destroy(),super.destroy()}}const Sr=["forbiddenSweepZone","forbiddenMopZone","cleanZone","virtualWall","threshold","spot","wayPoint","divider"];function IS(n){if(!n||n.length===0)return[...Sr];const e=new Set,t=[];for(const i of n)e.has(i)||(e.add(i),t.push(i));for(const i of Sr)e.has(i)||t.push(i);return t}class ES{constructor(e){f(this,"zoneMaps",new Map);f(this,"virtualWallMap",new Map);f(this,"thresholdMap",new Map);f(this,"spotMap",new Map);f(this,"roomAnchorMap",new Map);f(this,"roomAnchorsData",[]);f(this,"wayPointMap",new Map);f(this,"divider",null);f(this,"controlContainers",new Map);f(this,"unsubscribeFns",[]);f(this,"builtinZoneFactories",{forbiddenSweepZone:e=>to.create(this.appService,e),forbiddenMopZone:e=>eo.create(this.appService,e),cleanZone:e=>io.create(this.appService,e)});this.appService=e,this.initializeControlContainers();const t=W(e.runtime,"editingForbiddenSweepZoneIds",g=>{w.log(`[runtime] editingForbiddenSweepZoneIds: ${g}`);const m=this.zoneMaps.get("forbiddenSweepZone");m&&this.updateZonesEditState("forbiddenSweepZone",m)}),i=W(e.runtime,"editingForbiddenMopZoneIds",g=>{w.log(`[runtime] editingForbiddenMopZoneIds: ${g}`);const m=this.zoneMaps.get("forbiddenMopZone");m&&this.updateZonesEditState("forbiddenMopZone",m)}),s=W(e.runtime,"editingCleanZoneIds",g=>{w.log(`[runtime] editingCleanZoneIds: ${g}`);const m=this.zoneMaps.get("cleanZone");m&&this.updateZonesEditState("cleanZone",m)}),r=W(e.runtime,"editingCustomZoneIds",g=>{w.log(`[runtime] editingCustomZoneIds: ${JSON.stringify(g??{})}`);for(const[m,y]of this.zoneMaps)$e(m)||y.size&&this.updateZonesEditState(m,y)}),o=W(e.runtime,"editingVirtualWallIds",g=>{w.log(`[runtime] editingVirtualWallIds: ${g}`),this.updateVirtualWallsEditState(this.virtualWallMap)}),a=W(e.runtime,"editingThresholdIds",g=>{w.log(`[runtime] editingThresholdIds: ${g}`),this.updateThresholdsEditState(this.thresholdMap)}),h=W(e.runtime,"editingSpotIds",g=>{w.log(`[runtime] editingSpotIds: ${g}`),this.updateSpotsEditState(this.spotMap)}),l=W(e.runtime,"editingRoomAnchorIds",g=>{w.log(`[runtime] editingRoomAnchorIds: ${g}`),this.updateSpotsEditState(this.roomAnchorMap)}),c=W(e.runtime,"editingWayPointIds",g=>{w.log(`[runtime] editingWayPointIds: ${g}`),this.updateWayPointsEditState(this.wayPointMap)}),d=W(e.runtime,"dividingRoomId",g=>{w.log(`[runtime] dividingRoomId: ${g}`),this.handleDividingRoomIdChange(g)}),u=W(e.runtime,"unit",g=>{w.log(`[runtime] unit changed: ${g}`),this.handleUnitChange()}),p=W(e.runtime,"unitLabel",g=>{w.log(`[runtime] unitLabel changed: ${g}`),this.handleUnitChange()});this.unsubscribeFns.push(t,i,s,r,o,a,h,l,c,d,u,p)}updateRenderOrder(){this.applyRenderOrder()}initializeControlContainers(){const e=this.appService.appContainer.getLayer(ce);if(!e){w.warn("[ControlsManager] LAYER_CONTROLS not found during init");return}for(const t of Sr){const i=new L;i.label=`controls:${t}`,this.controlContainers.set(t,i),e.addChild(i)}this.applyRenderOrder()}applyRenderOrder(){const e=this.appService.appContainer.getLayer(ce);if(!e)return;IS(this.appService.getConfig().controls.renderOrder).forEach((i,s)=>{const r=this.controlContainers.get(i);r&&(r.zIndex=s)}),e.sortableChildren=!0,e.sortChildren()}addToControlLayer(e,t){let i=this.controlContainers.get(e);if(!i){const s=this.appService.appContainer.getLayer(ce);if(!s){w.warn("[ControlsManager] LAYER_CONTROLS not found");return}i=new L,i.label=`controls:${e}`,this.controlContainers.set(e,i),s.addChild(i),this.applyRenderOrder()}i.addChild(t)}drawForbiddenSweepZones(e){this.drawZonesByType("forbiddenSweepZone",e)}getForbiddenSweepZones(){return this.getZonesDataByType("forbiddenSweepZone")}clearAllForbiddenSweepZones(){this.clearAllZonesByType("forbiddenSweepZone")}drawForbiddenMopZones(e){this.drawZonesByType("forbiddenMopZone",e)}getForbiddenMopZones(){return this.getZonesDataByType("forbiddenMopZone")}clearAllForbiddenMopZones(){this.clearAllZonesByType("forbiddenMopZone")}drawCleanZones(e){this.drawZonesByType("cleanZone",e)}getCleanZones(){return this.getZonesDataByType("cleanZone")}clearAllCleanZones(){this.clearAllZonesByType("cleanZone")}drawVirtualWalls(e){var r;const t=this.appService,i=this.virtualWallMap,s=new Set(e.map(o=>o.id));for(const[o,a]of i)s.has(o)||((r=a.parent)==null||r.removeChild(a),a.destroy(),i.delete(o));e.forEach(o=>{const a=i.get(o.id);if(a)this.isWallDataEqual(a.getWallData(),o)||a.updateWallData(o);else{const h=new xr({appService:t,wallData:o,events:{onRemove:l=>{var c,d;(d=(c=t.events)==null?void 0:c.onRemoveVirtualWall)==null||d.call(c,l)},onUpdate:l=>{var c,d;(d=(c=t.events)==null?void 0:c.onUpdateVirtualWall)==null||d.call(c,l)},onClick:l=>{var c,d;(d=(c=t.events)==null?void 0:c.onClickVirtualWall)==null||d.call(c,l)}}});i.set(o.id,h),this.addToControlLayer("virtualWall",h)}})}getVirtualWalls(){return this.getWallsData(this.virtualWallMap)}clearAllVirtualWalls(){this.clearAllWalls(this.virtualWallMap)}drawThresholds(e){var r;const t=this.appService,i=this.thresholdMap,s=new Set(e.map(o=>o.id));for(const[o,a]of i)s.has(o)||((r=a.parent)==null||r.removeChild(a),a.destroy(),i.delete(o));e.forEach(o=>{const a=i.get(o.id);if(a)this.isThresholdDataEqual(a.getThresholdData(),o)||a.updateThresholdData(o);else{const h=new AS({appService:t,thresholdData:o,events:{onRemove:l=>{var c,d;(d=(c=t.events)==null?void 0:c.onRemoveThreshold)==null||d.call(c,l)},onUpdate:l=>{var c,d;(d=(c=t.events)==null?void 0:c.onUpdateThreshold)==null||d.call(c,l)},onClick:l=>{var c,d;(d=(c=t.events)==null?void 0:c.onClickThreshold)==null||d.call(c,l)}}});i.set(o.id,h),this.addToControlLayer("threshold",h)}})}getThresholds(){return Array.from(this.thresholdMap.values()).map(e=>e.getThresholdData())}clearAllThresholds(){var e;for(const t of this.thresholdMap.values())(e=t.parent)==null||e.removeChild(t),t.destroy();this.thresholdMap.clear()}drawSpots(e){this.drawSpotsInto(e,this.spotMap,{layer:"spot"})}getSpots(){return this.getSpotsData(this.spotMap)}clearAllSpots(){this.clearAllSpotsInternal(this.spotMap)}drawRoomAnchors(e){this.roomAnchorsData=e?[...e]:[],this.renderRoomAnchors()}getRoomAnchors(){return[...this.roomAnchorsData]}clearAllRoomAnchors(){this.roomAnchorsData=[],this.clearAllSpotsInternal(this.roomAnchorMap)}syncRoomAnchorData(e){this.roomAnchorsData.findIndex(i=>i.id===e.id)!==-1&&(this.roomAnchorsData=this.roomAnchorsData.map(i=>i.id===e.id?{...i,...e}:i))}refreshRoomAnchors(){this.clearAllSpotsInternal(this.roomAnchorMap),this.renderRoomAnchors()}renderRoomAnchors(){const e=this.appService.getConfig().controls.roomAnchor;if(!(e!=null&&e.show)){this.clearAllSpotsInternal(this.roomAnchorMap);return}this.drawSpotsInto(this.roomAnchorsData,this.roomAnchorMap,{layer:"roomAnchor",createOverrides:{config:e,iconAlias:"roomAnchorIcon",editingIdsKey:"editingRoomAnchorIds",events:{onUpdate:t=>{var s,r;const i={id:t.id,point:t.point,name:t.name,roomId:t.roomId};this.syncRoomAnchorData(i),(r=(s=this.appService.events)==null?void 0:s.onUpdateRoomAnchor)==null||r.call(s,i)},onClick:t=>{var i,s;(s=(i=this.appService.events)==null?void 0:i.onClickRoomAnchor)==null||s.call(i,{id:t.id,point:t.point,name:t.name,roomId:t.roomId})}}}})}getZoneMap(e){let t=this.zoneMaps.get(e);return t||(t=new Map,this.zoneMaps.set(e,t)),t}resolveZoneFactory(e){var s;const t=this.builtinZoneFactories[e];return t||((s=this.appService.getConfig().customZoneTypes)!=null&&s[e]?r=>new $s({deps:Ns(this.appService,{onRemove:o=>{var a,h;return(h=(a=this.appService.events)==null?void 0:a.onRemoveCustomZone)==null?void 0:h.call(a,e,o)},onUpdate:o=>{var a,h;return(h=(a=this.appService.events)==null?void 0:a.onUpdateCustomZone)==null?void 0:h.call(a,e,o)},onClick:o=>{var a,h;return(h=(a=this.appService.events)==null?void 0:a.onClickCustomZone)==null?void 0:h.call(a,e,o)}}),zoneData:r,zoneType:e}):null)}drawCustomZones(e,t){this.drawZonesByType(e,t)}getCustomZones(e){return this.getZonesDataByType(e)}clearCustomZones(e){this.clearAllZonesByType(e)}drawZonesByType(e,t){const i=this.resolveZoneFactory(e);if(!i){w.warn(`[ControlsManager] Unknown zone type: ${e}`);return}const s=this.getZoneMap(e);this.drawZonesImpl(t,s,i,e)}getZonesDataByType(e){const t=this.zoneMaps.get(e);return t?this.getZonesData(t):[]}clearAllZonesByType(e){const t=this.zoneMaps.get(e);t&&this.clearAllZones(t)}drawZonesImpl(e,t,i,s){if(!e||e.length===0){this.clearAllZones(t);return}const r=new Set(t.keys()),o=new Set(e.map(a=>a.id));for(const a of r)o.has(a)||this.removeZone(a,t);e.forEach(a=>{const h=t.get(a.id);h?this.isZoneDataEqual(h.getZoneData(),a)||h.updateZoneData(a):this.addNewZone(a,t,i,s)})}addNewZone(e,t,i,s){const r=i(e);t.set(e.id,r),this.addToControlLayer(s,r),r.setEditing(this.getEditingZoneIds(String(s)).includes(e.id))}removeZone(e,t){var s;const i=t.get(e);i&&((s=i.parent)==null||s.removeChild(i),i.destroy(),t.delete(e))}getZonesData(e){const t=[];return e.forEach(i=>{t.push(i.getZoneData())}),t}clearAllZones(e){e.forEach((t,i)=>{var r;const s=e.get(i);s&&((r=s.parent)==null||r.removeChild(s),s.destroy())}),e.clear()}getEditingZoneIds(e){var i;const t=this.appService.runtimeSnapshot;switch(e){case"forbiddenSweepZone":return t.editingForbiddenSweepZoneIds;case"forbiddenMopZone":return t.editingForbiddenMopZoneIds;case"cleanZone":return t.editingCleanZoneIds;default:return((i=t.editingCustomZoneIds)==null?void 0:i[e])??[]}}updateZonesEditState(e,t){const i=this.getEditingZoneIds(e);t.forEach((s,r)=>{s.setEditing(i.includes(r))})}updateVirtualWallsEditState(e){e.forEach(t=>{t.updateEditingState()})}updateThresholdsEditState(e){e.forEach(t=>{t.updateEditingState()})}isZoneDataEqual(e,t){if(e.id!==t.id||e.points.length!==t.points.length)return!1;for(let i=0;i<e.points.length;i++){const s=e.points[i],r=t.points[i];if(Math.abs(s.x-r.x)>.1||Math.abs(s.y-r.y)>.1)return!1}return!0}getWallsData(e){return Array.from(e.values()).map(t=>t.getWallData())}clearAllWalls(e){for(const t of e.values())t.destroy();e.clear()}isWallDataEqual(e,t){if(e.id!==t.id||e.points.length!==t.points.length)return!1;for(let i=0;i<e.points.length;i++){const s=e.points[i],r=t.points[i];if(Math.abs(s.x-r.x)>.1||Math.abs(s.y-r.y)>.1)return!1}return!0}isThresholdDataEqual(e,t){if(e.id!==t.id||(e.type??"passable")!==(t.type??"passable")||e.height==null!=(t.height==null)||e.height!=null&&t.height!=null&&Math.abs(e.height-t.height)>.1)return!1;for(let i=0;i<e.points.length;i++){const s=e.points[i],r=t.points[i];if(Math.abs(s.x-r.x)>.1||Math.abs(s.y-r.y)>.1)return!1}return!0}drawSpotsInto(e,t,i){if(!e||e.length===0){this.clearAllSpotsInternal(t);return}const s=new Set(t.keys()),r=new Set(e.map(o=>o.id));for(const o of s)r.has(o)||this.removeSpot(o,t);e.forEach(o=>{const a=t.get(o.id);a?this.isSpotDataEqual(a.getSpotData(),o)||a.updateSpotData(o):this.addNewSpot(o,t,i)})}addNewSpot(e,t,i){const s=so.create(this.appService,e,i.createOverrides);t.set(e.id,s),this.addToControlLayer(i.layer,s)}removeSpot(e,t){var s;const i=t.get(e);i&&((s=i.parent)==null||s.removeChild(i),i.destroy(),t.delete(e))}getSpotsData(e){const t=[];return e.forEach(i=>{t.push(i.getSpotData())}),t}clearAllSpotsInternal(e){e.forEach((t,i)=>{var r;const s=e.get(i);s&&((r=s.parent)==null||r.removeChild(s),s.destroy())}),e.clear()}updateSpotsEditState(e){e.forEach(t=>{t.updateEditState()})}refreshSpotsEditState(){this.updateSpotsEditState(this.spotMap)}isSpotDataEqual(e,t){if(e.id!==t.id)return!1;const i=e.point,s=t.point;return Math.abs(i.x-s.x)>.1||Math.abs(i.y-s.y)>.1||e.roomId!==t.roomId?!1:e.name===t.name}drawWayPoints(e){w.log("[ControlsManager] drawWayPoints",e);const t=Array.from(this.wayPointMap.keys()),i=e.map(r=>r.id);t.filter(r=>!i.includes(r)).forEach(r=>{this.removeWayPoint(r,this.wayPointMap)}),e.forEach((r,o)=>{const a=o+1,h=this.wayPointMap.get(r.id);h?(this.isWayPointDataEqual(h.getWayPointData(),r)||h.updateWayPoint(r),h.updateOrder(a)):this.addNewWayPoint(r,a,this.wayPointMap)})}clearAllWayPoints(){w.log("[ControlsManager] clearAllWayPoints"),this.clearAllWayPointsInternal(this.wayPointMap)}getWayPoints(){return this.getWayPointsData(this.wayPointMap)}addNewWayPoint(e,t,i){var o,a;const s=this.appService,r=new RS({appService:s,wayPointData:e,order:t,events:{onUpdate:(o=s.events)==null?void 0:o.onUpdateWayPoint,onClick:(a=s.events)==null?void 0:a.onClickWayPoint}});i.set(e.id,r),this.addToControlLayer("wayPoint",r)}removeWayPoint(e,t){var s;const i=t.get(e);i&&((s=i.parent)==null||s.removeChild(i),i.destroy(),t.delete(e))}getWayPointsData(e){const t=[];return e.forEach(i=>{t.push(i.getWayPointData())}),t}clearAllWayPointsInternal(e){e.forEach((t,i)=>{var r;const s=e.get(i);s&&((r=s.parent)==null||r.removeChild(s),s.destroy())}),e.clear()}updateWayPointsEditState(e){e.forEach(t=>{t.onEditStateChange()})}isWayPointDataEqual(e,t){if(e.id!==t.id)return!1;const i=e.point,s=t.point;return!(Math.abs(i.x-s.x)>.1||Math.abs(i.y-s.y)>.1)}handleDividingRoomIdChange(e){if(e==null||e===-1){this.clearDivider();return}if(!this.getRoomGeometry(e)){this.clearDivider();return}this.createDefaultDivider(e)}getRoomGeometry(e){return this.appService.mapManager.getRoomById(e)}createDefaultDivider(e){const t=this.appService;this.clearDivider(),this.divider=new kS({appService:this.appService,roomId:e,events:{onUpdate:i=>{var s,r;(r=(s=t.events)==null?void 0:s.onUpdateDivider)==null||r.call(s,i)}}}),this.addToControlLayer("divider",this.divider)}clearDivider(){var e;this.divider&&((e=this.divider.parent)==null||e.removeChild(this.divider),this.divider.destroy(),this.divider=null)}getDividerEndPoints(){return this.divider?this.divider.getDividerEndPoints():null}getEffectiveDividerPoints(){return this.divider?this.divider.getEffectiveDividerPoints():null}handleUnitChange(){w.debug("[ControlsManager] Unit changed, refreshing all size texts");for(const e of this.zoneMaps.values())e.forEach(t=>{t.refreshDisplay()});this.virtualWallMap.forEach(e=>{e.refreshDisplay()}),this.thresholdMap.forEach(e=>{e.refreshDisplay()}),this.spotMap.forEach(e=>{e.refreshDisplay()}),this.roomAnchorMap.forEach(e=>{e.refreshDisplay()})}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[];for(const e of this.zoneMaps.keys())this.clearAllZonesByType(e);this.clearAllVirtualWalls(),this.clearAllThresholds(),this.clearAllSpots(),this.clearAllRoomAnchors(),this.clearDivider(),this.controlContainers.forEach(e=>{e.removeFromParent(),e.destroy({children:!0})}),this.controlContainers.clear()}}class DS extends Zt{constructor(t,i){super(t);f(this,"objectData");f(this,"clickHandler",null);f(this,"unsubscribeMapRotation",null);this.appService=t,this.objectData=i}async initializeSprite(){const t=this.appService.detectedObjectConfig,i=this.objectData.width||t.width,s=this.objectData.height||t.height;await this.loadTextureAndSetSize(this.objectData.src,{width:i,height:s}),this.anchor.set(t.anchor.x,t.anchor.y),this.position.set(this.objectData.x,this.objectData.y),this.visible=!0,this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=W(this.appService.runtime,"mapRotation",r=>{this.applyAntiRotation(r)}),t.interactive?this.setupClickHandler():this.eventMode="none"}applyAntiRotation(t){const i=-t*Math.PI/180;this.rotation=i}setupClickHandler(){this.clickHandler&&this.clickHandler.destroy(),this.clickHandler=new vt(this,{onClick:()=>this.handleClick(),stopPropagation:!1})}handleClick(){var t,i;(i=(t=this.appService.events)==null?void 0:t.onClickDetectedObject)==null||i.call(t,this.getObjectData())}getObjectData(){return{...this.objectData}}async updateObjectData(t){const i=this.objectData;this.objectData=t;const s=this.appService.detectedObjectConfig;if(i.src!==t.src){const r=t.width||s.width,o=t.height||s.height;await this.loadTextureAndSetSize(t.src,{width:r,height:o})}if(i.width!==t.width||i.height!==t.height){const r=t.width||s.width,o=t.height||s.height;this.setFixedSize(r,o)}this.position.set(t.x,t.y),s.interactive?this.clickHandler||this.setupClickHandler():this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null)}isSameData(t){return this.objectData.id===t.id&&this.objectData.src===t.src&&this.objectData.x===t.x&&this.objectData.y===t.y&&this.objectData.width===t.width&&this.objectData.height===t.height}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),super.destroy()}}class FS{constructor(e){f(this,"detectedObjectMap",new Map);f(this,"unsubscribeShowDetectedObjects",null);this.appService=e,this.applyLayerVisibility(this.appService.runtime.showDetectedObjects),this.unsubscribeShowDetectedObjects=W(this.appService.runtime,"showDetectedObjects",t=>{this.applyLayerVisibility(t)})}async drawDetectedObjects(e){if(!e||e.length===0){this.clearAllDetectedObjects();return}const t=new Set(e.map(s=>s.id)),i=Array.from(this.detectedObjectMap.keys());for(const s of i)t.has(s)||this.removeDetectedObject(s);for(const s of e){const r=this.detectedObjectMap.get(s.id);r?r.isSameData(s)||await r.updateObjectData(s):await this.addNewDetectedObject(s)}}applyLayerVisibility(e){const t=this.appService.appContainer.getLayer(je);t&&(t.visible=e)}clearAllDetectedObjects(){const e=this.appService;this.detectedObjectMap.forEach(t=>{e.appContainer.removeFromLayer(je,t),t.destroy()}),this.detectedObjectMap.clear()}async addNewDetectedObject(e){const t=this.appService,i=new DS(this.appService,e);await i.initializeSprite(),this.detectedObjectMap.set(e.id,i),t.appContainer.addToLayer(je,i)}removeDetectedObject(e){const t=this.appService,i=this.detectedObjectMap.get(e);i&&(t.appContainer.removeFromLayer(je,i),i.destroy(),this.detectedObjectMap.delete(e))}destroy(){this.unsubscribeShowDetectedObjects&&(this.unsubscribeShowDetectedObjects(),this.unsubscribeShowDetectedObjects=null),this.clearAllDetectedObjects()}}var Ee={},Vc={},ne={};Object.defineProperty(ne,"__esModule",{value:!0});ne.loop=ne.conditional=ne.parse=void 0;var BS=function n(e,t){var i=arguments.length>2&&arguments[2]!==void 0?arguments[2]:{},s=arguments.length>3&&arguments[3]!==void 0?arguments[3]:i;if(Array.isArray(t))t.forEach(function(o){return n(e,o,i,s)});else if(typeof t=="function")t(e,i,s,n);else{var r=Object.keys(t)[0];Array.isArray(t[r])?(s[r]={},n(e,t[r],i,s[r])):s[r]=t[r](e,i,s,n)}return i};ne.parse=BS;var zS=function(e,t){return function(i,s,r,o){t(i,s,r)&&o(i,e,s,r)}};ne.conditional=zS;var LS=function(e,t){return function(i,s,r,o){for(var a=[],h=i.pos;t(i,s,r);){var l={};if(o(i,e,s,l),i.pos===h)break;h=i.pos,a.push(l)}return a}};ne.loop=LS;var ut={};Object.defineProperty(ut,"__esModule",{value:!0});ut.readBits=ut.readArray=ut.readUnsigned=ut.readString=ut.peekBytes=ut.readBytes=ut.peekByte=ut.readByte=ut.buildStream=void 0;var OS=function(e){return{data:e,pos:0}};ut.buildStream=OS;var Nc=function(){return function(e){return e.data[e.pos++]}};ut.readByte=Nc;var WS=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function(t){return t.data[t.pos+e]}};ut.peekByte=WS;var Ys=function(e){return function(t){return t.data.subarray(t.pos,t.pos+=e)}};ut.readBytes=Ys;var GS=function(e){return function(t){return t.data.subarray(t.pos,t.pos+e)}};ut.peekBytes=GS;var US=function(e){return function(t){return Array.from(Ys(e)(t)).map(function(i){return String.fromCharCode(i)}).join("")}};ut.readString=US;var HS=function(e){return function(t){var i=Ys(2)(t);return e?(i[1]<<8)+i[0]:(i[0]<<8)+i[1]}};ut.readUnsigned=HS;var VS=function(e,t){return function(i,s,r){for(var o=typeof t=="function"?t(i,s,r):t,a=Ys(e),h=new Array(o),l=0;l<o;l++)h[l]=a(i);return h}};ut.readArray=VS;var NS=function(e,t,i){for(var s=0,r=0;r<i;r++)s+=e[t+r]&&Math.pow(2,i-r-1);return s},$S=function(e){return function(t){for(var i=Nc()(t),s=new Array(8),r=0;r<8;r++)s[7-r]=!!(i&1<<r);return Object.keys(e).reduce(function(o,a){var h=e[a];return h.length?o[a]=NS(s,h.index,h.length):o[a]=s[h.index],o},{})}};ut.readBits=$S;(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var e=ne,t=ut,i={blocks:function(u){for(var p=0,g=[],m=u.data.length,y=0,x=(0,t.readByte)()(u);x!==p&&x;x=(0,t.readByte)()(u)){if(u.pos+x>=m){var S=m-u.pos;g.push((0,t.readBytes)(S)(u)),y+=S;break}g.push((0,t.readBytes)(x)(u)),y+=x}for(var v=new Uint8Array(y),b=0,P=0;P<g.length;P++)v.set(g[P],b),b+=g[P].length;return v}},s=(0,e.conditional)({gce:[{codes:(0,t.readBytes)(2)},{byteSize:(0,t.readByte)()},{extras:(0,t.readBits)({future:{index:0,length:3},disposal:{index:3,length:3},userInput:{index:6},transparentColorGiven:{index:7}})},{delay:(0,t.readUnsigned)(!0)},{transparentColorIndex:(0,t.readByte)()},{terminator:(0,t.readByte)()}]},function(d){var u=(0,t.peekBytes)(2)(d);return u[0]===33&&u[1]===249}),r=(0,e.conditional)({image:[{code:(0,t.readByte)()},{descriptor:[{left:(0,t.readUnsigned)(!0)},{top:(0,t.readUnsigned)(!0)},{width:(0,t.readUnsigned)(!0)},{height:(0,t.readUnsigned)(!0)},{lct:(0,t.readBits)({exists:{index:0},interlaced:{index:1},sort:{index:2},future:{index:3,length:2},size:{index:5,length:3}})}]},(0,e.conditional)({lct:(0,t.readArray)(3,function(d,u,p){return Math.pow(2,p.descriptor.lct.size+1)})},function(d,u,p){return p.descriptor.lct.exists}),{data:[{minCodeSize:(0,t.readByte)()},i]}]},function(d){return(0,t.peekByte)()(d)===44}),o=(0,e.conditional)({text:[{codes:(0,t.readBytes)(2)},{blockSize:(0,t.readByte)()},{preData:function(u,p,g){return(0,t.readBytes)(g.text.blockSize)(u)}},i]},function(d){var u=(0,t.peekBytes)(2)(d);return u[0]===33&&u[1]===1}),a=(0,e.conditional)({application:[{codes:(0,t.readBytes)(2)},{blockSize:(0,t.readByte)()},{id:function(u,p,g){return(0,t.readString)(g.blockSize)(u)}},i]},function(d){var u=(0,t.peekBytes)(2)(d);return u[0]===33&&u[1]===255}),h=(0,e.conditional)({comment:[{codes:(0,t.readBytes)(2)},i]},function(d){var u=(0,t.peekBytes)(2)(d);return u[0]===33&&u[1]===254}),l=[{header:[{signature:(0,t.readString)(3)},{version:(0,t.readString)(3)}]},{lsd:[{width:(0,t.readUnsigned)(!0)},{height:(0,t.readUnsigned)(!0)},{gct:(0,t.readBits)({exists:{index:0},resolution:{index:1,length:3},sort:{index:4},size:{index:5,length:3}})},{backgroundColorIndex:(0,t.readByte)()},{pixelAspectRatio:(0,t.readByte)()}]},(0,e.conditional)({gct:(0,t.readArray)(3,function(d,u){return Math.pow(2,u.lsd.gct.size+1)})},function(d,u){return u.lsd.gct.exists}),{frames:(0,e.loop)([s,a,h,r,o],function(d){var u=(0,t.peekByte)()(d);return u===33||u===44})}],c=l;n.default=c})(Vc);var Xs={};Object.defineProperty(Xs,"__esModule",{value:!0});Xs.deinterlace=void 0;var YS=function(e,t){for(var i=new Array(e.length),s=e.length/t,r=function(u,p){var g=e.slice(p*t,(p+1)*t);i.splice.apply(i,[u*t,t].concat(g))},o=[0,4,2,1],a=[8,8,4,2],h=0,l=0;l<4;l++)for(var c=o[l];c<s;c+=a[l])r(c,h),h++;return i};Xs.deinterlace=YS;var js={};Object.defineProperty(js,"__esModule",{value:!0});js.lzw=void 0;var XS=function(e,t,i){var s=4096,r=-1,o=i,a,h,l,c,d,u,p,C,g,m,P,y,_,R,T,M,x=new Array(i),S=new Array(s),v=new Array(s),b=new Array(s+1);for(y=e,h=1<<y,d=h+1,a=h+2,p=r,c=y+1,l=(1<<c)-1,g=0;g<h;g++)S[g]=0,v[g]=g;var P,C,_,R,M,T;for(P=C=_=R=M=T=0,m=0;m<o;){if(R===0){if(C<c){P+=t[T]<<C,C+=8,T++;continue}if(g=P&l,P>>=c,C-=c,g>a||g==d)break;if(g==h){c=y+1,l=(1<<c)-1,a=h+2,p=r;continue}if(p==r){b[R++]=v[g],p=g,_=g;continue}for(u=g,g==a&&(b[R++]=_,g=p);g>h;)b[R++]=v[g],g=S[g];_=v[g]&255,b[R++]=_,a<s&&(S[a]=p,v[a]=_,a++,!(a&l)&&a<s&&(c++,l+=a)),p=u}R--,x[M++]=b[R],m++}for(m=M;m<o;m++)x[m]=0;return x};js.lzw=XS;Object.defineProperty(Ee,"__esModule",{value:!0});var $c=Ee.decompressFrames=Ee.decompressFrame=Yc=Ee.parseGIF=void 0,jS=JS(Vc),ZS=ne,qS=ut,KS=Xs,QS=js;function JS(n){return n&&n.__esModule?n:{default:n}}var tv=function(e){var t=new Uint8Array(e);return(0,ZS.parse)((0,qS.buildStream)(t),jS.default)},Yc=Ee.parseGIF=tv,ev=function(e){for(var t=e.pixels.length,i=new Uint8ClampedArray(t*4),s=0;s<t;s++){var r=s*4,o=e.pixels[s],a=e.colorTable[o]||[0,0,0];i[r]=a[0],i[r+1]=a[1],i[r+2]=a[2],i[r+3]=o!==e.transparentIndex?255:0}return i},Xc=function(e,t,i){if(!e.image){console.warn("gif frame does not have associated image.");return}var s=e.image,r=s.descriptor.width*s.descriptor.height,o=(0,QS.lzw)(s.data.minCodeSize,s.data.blocks,r);s.descriptor.lct.interlaced&&(o=(0,KS.deinterlace)(o,s.descriptor.width));var a={pixels:o,dims:{top:e.image.descriptor.top,left:e.image.descriptor.left,width:e.image.descriptor.width,height:e.image.descriptor.height}};return s.descriptor.lct&&s.descriptor.lct.exists?a.colorTable=s.lct:a.colorTable=t,e.gce&&(a.delay=(e.gce.delay||10)*10,a.disposalType=e.gce.extras.disposal,e.gce.extras.transparentColorGiven&&(a.transparentIndex=e.gce.transparentColorIndex)),i&&(a.patch=ev(a)),a};Ee.decompressFrame=Xc;var iv=function(e,t){return e.frames.filter(function(i){return i.image}).map(function(i){return Xc(i,e.gct,t)})};$c=Ee.decompressFrames=iv;class Zs{constructor(e){if(!e||!e.length)throw new Error("Invalid frames");const[{texture:{width:t,height:i}}]=e;this.width=t,this.height=i,this.frames=e,this.textures=this.frames.map(s=>s.texture),this.totalFrames=this.frames.length,this.duration=this.frames[this.totalFrames-1].end}destroy(){for(const e of this.textures)e.destroy(!0);for(const e of this.frames)e.texture=null;this.frames.length=0,this.textures.length=0,Object.assign(this,{frames:null,textures:null,width:0,height:0,duration:0,totalFrames:0})}static from(e,t){if(!e||e.byteLength===0)throw new Error("Invalid buffer");const i=S=>{let v=null;for(const b of S.frames)v=b.gce??v,"image"in b&&!("gce"in b)&&(b.gce=v)},s=Yc(e);i(s);const r=$c(s,!0),o=[],a=s.lsd.width,h=s.lsd.height,l=$.get().createCanvas(a,h),c=l.getContext("2d",{willReadFrequently:!0}),d=$.get().createCanvas(),u=d.getContext("2d");let p=0,g=null;const{fps:m=30,...y}=t??{},x=1e3/m;for(let S=0;S<r.length;S++){const{disposalType:v=2,delay:b=x,patch:P,dims:{width:C,height:_,left:R,top:M}}=r[S];d.width=C,d.height=_,u.clearRect(0,0,C,_);const T=u.createImageData(C,_);T.data.set(P),u.putImageData(T,0,0),v===3&&(g=c.getImageData(0,0,a,h)),c.drawImage(d,R,M);const A=c.getImageData(0,0,a,h);v===2?c.clearRect(0,0,a,h):v===3&&c.putImageData(g,0,0);const E=$.get().createCanvas(A.width,A.height);E.getContext("2d").putImageData(A,0,0),o.push({start:p,end:p+b,texture:new G({source:new Ar({resource:E,...y})})}),p+=b}return l.width=l.height=0,d.width=d.height=0,new Zs(o)}}const sv={extension:I.Asset,detection:{test:async()=>!0,add:async n=>[...n,"gif"],remove:async n=>n.filter(e=>e!=="gif")},loader:{name:"gifLoader",id:"gif",test:n=>Mt.extname(n)===".gif"||n.startsWith("data:image/gif"),load:async(n,e)=>{const i=await(await $.get().fetch(n)).arrayBuffer();return Zs.from(i,e==null?void 0:e.data)},unload:async n=>{n.destroy()}}},jc=class vr extends Xt{constructor(...e){const t=e[0]instanceof Zs?{source:e[0]}:e[0],{source:i,fps:s,loop:r,animationSpeed:o,autoPlay:a,autoUpdate:h,onComplete:l,onFrameChange:c,onLoop:d,...u}=Object.assign({},vr.defaultOptions,t);super({texture:G.EMPTY,...u}),this.animationSpeed=1,this.loop=!0,this.duration=0,this.autoPlay=!0,this.dirty=!1,this._currentFrame=0,this._autoUpdate=!1,this._isConnectedToTicker=!1,this._playing=!1,this._currentTime=0,this.onRender=()=>this._updateFrame(),this.texture=i.textures[0],this.duration=i.frames[i.frames.length-1].end,this._source=i,this._playing=!1,this._currentTime=0,this._isConnectedToTicker=!1,Object.assign(this,{fps:s,loop:r,animationSpeed:o,autoPlay:a,autoUpdate:h,onComplete:l,onFrameChange:c,onLoop:d}),this.currentFrame=0,a&&this.play()}stop(){this._playing&&(this._playing=!1,this._autoUpdate&&this._isConnectedToTicker&&(yt.shared.remove(this.update,this),this._isConnectedToTicker=!1))}play(){this._playing||(this._playing=!0,this._autoUpdate&&!this._isConnectedToTicker&&(yt.shared.add(this.update,this,Fe.HIGH),this._isConnectedToTicker=!0),!this.loop&&this.currentFrame===this._source.frames.length-1&&(this._currentTime=0))}get progress(){return this._currentTime/this.duration}get playing(){return this._playing}update(e){var o,a;if(!this._playing)return;const t=this.animationSpeed*e.deltaTime/yt.targetFPMS,i=this._currentTime+t,s=i%this.duration,r=this._source.frames.findIndex(h=>h.start<=s&&h.end>s);i>=this.duration?this.loop?(this._currentTime=s,this._updateFrameIndex(r),(o=this.onLoop)==null||o.call(this)):(this._currentTime=this.duration,this._updateFrameIndex(this.totalFrames-1),(a=this.onComplete)==null||a.call(this),this.stop()):(this._currentTime=s,this._updateFrameIndex(r))}_updateFrame(){this.dirty&&(this.texture=this._source.frames[this._currentFrame].texture,this.dirty=!1)}get autoUpdate(){return this._autoUpdate}set autoUpdate(e){e!==this._autoUpdate&&(this._autoUpdate=e,!this._autoUpdate&&this._isConnectedToTicker?(yt.shared.remove(this.update,this),this._isConnectedToTicker=!1):this._autoUpdate&&!this._isConnectedToTicker&&this._playing&&(yt.shared.add(this.update,this),this._isConnectedToTicker=!0))}get currentFrame(){return this._currentFrame}set currentFrame(e){this._updateFrameIndex(e),this._currentTime=this._source.frames[e].start}get source(){return this._source}_updateFrameIndex(e){var t;if(e<0||e>=this.totalFrames)throw new Error(`Frame index out of range, expecting 0 to ${this.totalFrames}, got ${e}`);this._currentFrame!==e&&(this._currentFrame=e,this.dirty=!0,(t=this.onFrameChange)==null||t.call(this,e))}get totalFrames(){return this._source.totalFrames}destroy(e=!1){this.stop(),super.destroy(),e&&this._source.destroy();const t=null;this._source=t,this.onComplete=t,this.onFrameChange=t,this.onLoop=t}clone(){const e=new vr({source:this._source,autoUpdate:this._autoUpdate,loop:this.loop,autoPlay:this.autoPlay,animationSpeed:this.animationSpeed,onComplete:this.onComplete,onFrameChange:this.onFrameChange,onLoop:this.onLoop});return e.dirty=!0,e}};jc.defaultOptions={fps:30,loop:!0,animationSpeed:1,autoPlay:!0,autoUpdate:!0,onComplete:null,onFrameChange:null,onLoop:null};let nv=jc;K.add(sv);class no extends nv{constructor(t,i){super(i);f(this,"throttledUpdateScale");f(this,"fixedWidth",0);f(this,"fixedHeight",0);f(this,"isFixedSizeSet",!1);f(this,"sizeFixed",!0);f(this,"baselineScale",1);f(this,"basePositionX",0);f(this,"basePositionY",0);f(this,"pixelOffset",null);this.appService=t,this.anchor.set(.5),this.visible=!1,this.throttledUpdateScale=_t(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.registerScaleListener()}setFixedSize(t,i){this.fixedWidth=t,this.fixedHeight=i,this.isFixedSizeSet=!0,this.applySize()}setSizeFixed(t){this.sizeFixed=t,this.baselineScale=1,t&&this.isFixedSizeSet?this.applySize():!t&&this.isFixedSizeSet&&this.applySize()}setBasePosition(t,i){this.basePositionX=t,this.basePositionY=i,this.pixelOffset?this.applyPixelOffset():this.position.set(t,i)}setPixelOffset(t){this.pixelOffset=t,t?this.applyPixelOffset():this.position.set(this.basePositionX,this.basePositionY)}applyPixelOffset(){if(this.destroyed||!this.pixelOffset)return;if(!this.sizeFixed){this.position.set(this.basePositionX,this.basePositionY);return}const t=this.appService.currentScale,i=this.appService.appContainer.getMapRotationRadians(),s=Yr(this.pixelOffset,t,i);this.position.set(this.basePositionX+s.x,this.basePositionY+s.y)}set width(t){if(this.isFixedSizeSet){w.warn("EnhancedGifSprite: 使用 setFixedSize() 方法来设置宽度");return}this.setFixedSize(t,this.fixedHeight||t)}set height(t){if(this.isFixedSizeSet){w.warn("EnhancedGifSprite: 使用 setFixedSize() 方法来设置高度");return}this.setFixedSize(this.fixedWidth||t,t)}get width(){return this.fixedWidth||super.width}get height(){return this.fixedHeight||super.height}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}applySize(){if(!this.isFixedSizeSet||!this.texture||this.texture.width===0||this.texture.height===0)return;const t=this.fixedWidth/this.texture.width,i=this.fixedHeight/this.texture.height;if(this.sizeFixed){const s=this.appService.currentScale;if(s===0)return;const r=t/s,o=i/s;super.scale.set(r,o)}else super.scale.set(t/this.baselineScale,i/this.baselineScale)}updateScale(t){this.sizeFixed&&(this.isFixedSizeSet?this.applySize():t!==0&&super.scale.set(1/t),this.applyPixelOffset())}static async createFromSrc(t,i,s){try{const r=await N.load(i),o=new no(t,{source:r});return s.sizeFixed!==void 0&&o.setSizeFixed(s.sizeFixed),o.setFixedSize(s.width,s.height),o}catch(r){throw w.error(`Failed to load GIF "${i}":`,r),r}}draw(t,i){const{x:s,y:r,rotation:o=0}=t;i&&!this.visible?this.visible=i():!i&&!this.visible&&(this.visible=!0),this.rotation=o,this.position.set(s,r)}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateScale),super.destroy(t)}}class Ve extends no{constructor(t,i,s){super(t,{source:i});f(this,"elementData");f(this,"clickHandler",null);f(this,"unsubscribeMapRotation",null);f(this,"userRotation",0);this.elementData=s}async initialize(){this.elementData.sizeFixed!==void 0&&this.setSizeFixed(this.elementData.sizeFixed),this.setFixedSize(this.elementData.width,this.elementData.height);const t=this.elementData.anchor||{x:.5,y:.5};this.anchor.set(t.x,t.y),this.setPixelOffset(this.elementData.pixelOffset??null),this.setBasePosition(this.elementData.x,this.elementData.y),this.elementData.rotation!==void 0&&(this.userRotation=this.elementData.rotation),this.elementData.opacity!==void 0&&(this.alpha=this.elementData.opacity),this.applyRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=W(this.appService.runtime,"mapRotation",i=>{this.applyRotation(i),this.applyPixelOffset()}),this.visible=!0,this.elementData.interactive?this.setupClickHandler():this.eventMode="none"}applyRotation(t){const i=-t*Math.PI/180;this.rotation=this.userRotation+i}setupClickHandler(){this.clickHandler&&this.clickHandler.destroy(),this.clickHandler=new vt(this,{onClick:()=>this.handleClick(),stopPropagation:!1})}handleClick(){var t,i;(i=(t=this.appService.events)==null?void 0:t.onClickCustomElement)==null||i.call(t,this.getElementData())}getElementData(){return{...this.elementData}}async updateElementData(t){const i=this.elementData;if(this.elementData=t,i.src!==t.src)throw new Error("GIF source change requires recreation of instance");i.sizeFixed!==t.sizeFixed&&t.sizeFixed!==void 0&&this.setSizeFixed(t.sizeFixed),(i.width!==t.width||i.height!==t.height)&&this.setFixedSize(t.width,t.height);const s=t.anchor||{x:.5,y:.5},r=i.anchor||{x:.5,y:.5};(s.x!==r.x||s.y!==r.y)&&this.anchor.set(s.x,s.y),this.setPixelOffset(t.pixelOffset??null),this.setBasePosition(t.x,t.y),t.rotation!==void 0&&(this.userRotation=t.rotation,this.applyRotation(this.appService.runtime.mapRotation)),t.opacity!==void 0&&(this.alpha=t.opacity),t.interactive?this.clickHandler||this.setupClickHandler():(this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),this.eventMode="none")}isSameData(t){const i=this.elementData.anchor||{x:.5,y:.5},s=t.anchor||{x:.5,y:.5},r=this.elementData.pixelOffset,o=t.pixelOffset;return this.elementData.id===t.id&&this.elementData.type===t.type&&this.elementData.src===t.src&&this.elementData.x===t.x&&this.elementData.y===t.y&&this.elementData.width===t.width&&this.elementData.height===t.height&&this.elementData.rotation===t.rotation&&this.elementData.opacity===t.opacity&&this.elementData.interactive===t.interactive&&this.elementData.sizeFixed===t.sizeFixed&&i.x===s.x&&i.y===s.y&&((r==null?void 0:r.x)??0)===((o==null?void 0:o.x)??0)&&((r==null?void 0:r.y)??0)===((o==null?void 0:o.y)??0)}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),super.destroy()}}class Wn extends Zt{constructor(t,i){super(t);f(this,"elementData");f(this,"clickHandler",null);f(this,"unsubscribeMapRotation",null);f(this,"userRotation",0);this.appService=t,this.elementData=i}async initialize(){await this.loadTextureAndSetSize(this.elementData.src,{width:this.elementData.width,height:this.elementData.height,sizeFixed:this.elementData.sizeFixed});const t=this.elementData.anchor||{x:.5,y:.5};this.anchor.set(t.x,t.y),this.setPixelOffset(this.elementData.pixelOffset??null),this.setBasePosition(this.elementData.x,this.elementData.y),this.elementData.rotation!==void 0&&(this.userRotation=this.elementData.rotation),this.elementData.opacity!==void 0&&(this.alpha=this.elementData.opacity),this.applyRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=W(this.appService.runtime,"mapRotation",i=>{this.applyRotation(i),this.applyPixelOffset()}),this.visible=!0,this.elementData.interactive?this.setupClickHandler():this.eventMode="none"}applyRotation(t){const i=-t*Math.PI/180;this.rotation=this.userRotation+i}setupClickHandler(){this.clickHandler&&this.clickHandler.destroy(),this.clickHandler=new vt(this,{onClick:()=>this.handleClick(),stopPropagation:!1})}handleClick(){var t,i;(i=(t=this.appService.events)==null?void 0:t.onClickCustomElement)==null||i.call(t,this.getElementData())}getElementData(){return{...this.elementData}}async updateElementData(t){const i=this.elementData;this.elementData=t,i.src!==t.src?await this.loadTextureAndSetSize(t.src,{width:t.width,height:t.height,sizeFixed:t.sizeFixed}):(i.sizeFixed!==t.sizeFixed&&t.sizeFixed!==void 0&&this.setSizeFixed(t.sizeFixed),(i.width!==t.width||i.height!==t.height)&&this.setFixedSize(t.width,t.height));const s=t.anchor||{x:.5,y:.5},r=i.anchor||{x:.5,y:.5};(s.x!==r.x||s.y!==r.y)&&this.anchor.set(s.x,s.y),this.setPixelOffset(t.pixelOffset??null),this.setBasePosition(t.x,t.y),t.rotation!==void 0&&(this.userRotation=t.rotation,this.applyRotation(this.appService.runtime.mapRotation)),t.opacity!==void 0&&(this.alpha=t.opacity),t.interactive?this.clickHandler||this.setupClickHandler():(this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),this.eventMode="none")}isSameData(t){const i=this.elementData.anchor||{x:.5,y:.5},s=t.anchor||{x:.5,y:.5},r=this.elementData.pixelOffset,o=t.pixelOffset;return this.elementData.id===t.id&&this.elementData.type===t.type&&this.elementData.src===t.src&&this.elementData.x===t.x&&this.elementData.y===t.y&&this.elementData.width===t.width&&this.elementData.height===t.height&&this.elementData.rotation===t.rotation&&this.elementData.opacity===t.opacity&&this.elementData.interactive===t.interactive&&this.elementData.sizeFixed===t.sizeFixed&&i.x===s.x&&i.y===s.y&&((r==null?void 0:r.x)??0)===((o==null?void 0:o.x)??0)&&((r==null?void 0:r.y)??0)===((o==null?void 0:o.y)??0)}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.clickHandler&&(this.clickHandler.destroy(),this.clickHandler=null),super.destroy()}}class rv extends dm{constructor(t,i){super(i);f(this,"throttledUpdateScale");f(this,"fixedWidth",0);f(this,"fixedHeight",0);f(this,"isFixedSizeSet",!1);f(this,"userCenterX",0);f(this,"userCenterY",0);f(this,"sizeFixed",!0);f(this,"pixelOffset",null);this.appService=t,this.anchor.set(0,0),this.throttledUpdateScale=_t(this.updateScale.bind(this),30,{leading:!0,trailing:!0}),this.registerScaleListener()}setFixedSize(t,i){this.fixedWidth=t,this.fixedHeight=i,this.isFixedSizeSet=!0,this.applyFixedSize(),this.updatePositionFromCenter()}setCenterPosition(t,i){this.userCenterX=t,this.userCenterY=i,this.updatePositionFromCenter()}setPixelOffset(t){this.pixelOffset=t,this.isFixedSizeSet&&this.updatePositionFromCenter()}applyPixelOffset(){this.isFixedSizeSet&&this.updatePositionFromCenter()}setSizeFixed(t){this.sizeFixed=t,this.isFixedSizeSet&&(this.applyFixedSize(),this.updatePositionFromCenter())}getIsFixedSizeSet(){return this.isFixedSizeSet}updatePositionFromCenter(){if(!this.isFixedSizeSet){this.position.set(this.userCenterX,this.userCenterY);return}const i=this.appService.currentScale;let s,r;this.sizeFixed?(s=this.fixedWidth/2/i,r=this.fixedHeight/2/i):(s=this.fixedWidth/2,r=this.fixedHeight/2);let o=this.userCenterX,a=this.userCenterY;if(this.sizeFixed&&this.pixelOffset){const h=this.appService.appContainer.getMapRotationRadians(),l=Yr(this.pixelOffset,i,h);o+=l.x,a+=l.y}this.position.set(o-s,a-r)}registerScaleListener(){this.appService.emitter.on("antiScale",this.throttledUpdateScale)}applyFixedSize(){if(!this.isFixedSizeSet)return;const i=this.appService.currentScale;if(i!==0){if(this.sizeFixed){const s=1/i;this.scale.set(s)}else this.scale.set(1);this.element&&(this.element.style.width=`${this.fixedWidth}px`,this.element.style.height=`${this.fixedHeight}px`)}}updateScale(t){this.isFixedSizeSet&&t!==0&&(this.applyFixedSize(),this.updatePositionFromCenter())}updateTransform(t){return super.updateTransform(t)}destroy(t){this.appService.emitter.off("antiScale",this.throttledUpdateScale),super.destroy(t)}}class Di extends rv{constructor(t,i){const s=document.createElement("div");Di.setupDefaultStyles(s,i),s.innerHTML=i.htmlContent;super(t,{element:s});f(this,"elementData");f(this,"domClickHandler",null);f(this,"resizeObserver",null);f(this,"debugMarker",null);f(this,"unsubscribeMapRotation",null);f(this,"userRotation",0);this.elementData=i}async initialize(){this.alpha=0,this.elementData.width&&this.elementData.height?(this.setFixedSize(this.elementData.width,this.elementData.height),this.setCenterPosition(this.elementData.x,this.elementData.y),this.setSizeFixed(this.elementData.sizeFixed??!0),this.waitForElementInsertion()):(this.position.set(this.elementData.x,this.elementData.y),this.setupAutoSize()),this.setPixelOffset(this.elementData.pixelOffset??null),this.elementData.rotation!==void 0&&(this.userRotation=this.elementData.rotation),this.applyRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=W(this.appService.runtime,"mapRotation",t=>{this.applyRotation(t),this.applyPixelOffset()}),this.elementData.interactive?this.setupClickHandler():this.eventMode="none"}applyRotation(t){const i=-t*Math.PI/180;this.rotation=this.userRotation+i}setupAutoSize(){this.element&&(this.element.style.width="auto",this.element.style.height="auto",this.waitForElementDimensions())}waitForElementInsertion(){if(!this.element)return;const t=()=>{this.element&&(this.element.isConnected?this.showElement():requestAnimationFrame(t))};requestAnimationFrame(t)}waitForElementDimensions(){this.element&&(typeof ResizeObserver<"u"?(this.resizeObserver=new ResizeObserver(t=>{var s;const i=t[0];i&&i.contentRect.width>0&&i.contentRect.height>0&&(this.setFixedSize(i.contentRect.width,i.contentRect.height),this.setCenterPosition(this.elementData.x,this.elementData.y),this.setSizeFixed(this.elementData.sizeFixed??!0),this.alpha===0&&this.showElement(),(s=this.resizeObserver)==null||s.disconnect(),this.resizeObserver=null)}),this.resizeObserver.observe(this.element)):this.pollForElementDimensions())}pollForElementDimensions(){if(!this.element)return;const t=()=>{if(!this.element)return;if(!this.element.isConnected){requestAnimationFrame(t);return}const i=this.element.getBoundingClientRect();i.width>0&&i.height>0?(this.setFixedSize(i.width,i.height),this.setCenterPosition(this.elementData.x,this.elementData.y),this.setSizeFixed(this.elementData.sizeFixed??!0),this.alpha===0&&this.showElement()):requestAnimationFrame(t)};requestAnimationFrame(t)}showElement(){this.alpha=this.elementData.opacity??1,this.element.style.pointerEvents=this.elementData.interactive?"auto":"none",this.interactive=this.elementData.interactive??!1,this.elementData.interactive&&this.element&&(this.element.style.setProperty("-webkit-tap-highlight-color","transparent"),this.element.style.setProperty("-webkit-touch-callout","none")),this.appService.getApp().renderOnceNextFrame()}setupClickHandler(){this.element&&(this.domClickHandler=t=>{t.preventDefault(),t.stopPropagation(),this.handleClick()},this.element.addEventListener("click",this.domClickHandler))}handleClick(){var t,i;(i=(t=this.appService.events)==null?void 0:t.onClickCustomElement)==null||i.call(t,this.getElementData())}getElementData(){return{...this.elementData}}async updateElementData(t){const i=this.elementData;this.elementData=t,i.htmlContent!==t.htmlContent&&this.element&&(this.element.innerHTML=t.htmlContent,(!t.width||!t.height)&&this.waitForElementDimensions()),(i.width!==t.width||i.height!==t.height)&&(t.width&&t.height?(this.setFixedSize(t.width,t.height),this.element&&(this.element.style.width=`${t.width}px`,this.element.style.height=`${t.height}px`)):this.setupAutoSize()),this.setPixelOffset(t.pixelOffset??null),t.width&&t.height?this.setCenterPosition(t.x,t.y):this.getIsFixedSizeSet()?this.setCenterPosition(t.x,t.y):this.position.set(t.x,t.y),i.sizeFixed!==t.sizeFixed&&t.sizeFixed!==void 0&&this.setSizeFixed(t.sizeFixed),this.userRotation=t.rotation??0,this.applyRotation(this.appService.runtime.mapRotation),this.alpha=t.opacity??1,t.interactive?this.domClickHandler||this.setupClickHandler():(this.eventMode="none",this.domClickHandler&&this.element&&(this.element.removeEventListener("click",this.domClickHandler),this.domClickHandler=null))}isSameData(t){const i=this.elementData.pixelOffset,s=t.pixelOffset;return this.elementData.id===t.id&&this.elementData.type===t.type&&this.elementData.htmlContent===t.htmlContent&&this.elementData.x===t.x&&this.elementData.y===t.y&&this.elementData.width===t.width&&this.elementData.height===t.height&&this.elementData.rotation===t.rotation&&this.elementData.opacity===t.opacity&&this.elementData.interactive===t.interactive&&this.elementData.sizeFixed===t.sizeFixed&&((i==null?void 0:i.x)??0)===((s==null?void 0:s.x)??0)&&((i==null?void 0:i.y)??0)===((s==null?void 0:s.y)??0)}static setupDefaultStyles(t,i){const s={position:"relative",boxSizing:"border-box",webkitFontSmoothing:"antialiased",textRendering:"optimizeLegibility",background:"transparent",userSelect:"auto",webkitUserSelect:"auto"};i.width&&i.height?(s.width=`${i.width}px`,s.height=`${i.height}px`,s.overflow="hidden"):(s.width=i.width?`${i.width}px`:"auto",s.height=i.height?`${i.height}px`:"auto",s.overflow="visible"),Object.assign(t.style,s),t.style.setProperty("-webkit-tap-highlight-color","transparent"),t.style.setProperty("-webkit-touch-callout","none")}destroy(){this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.resizeObserver&&(this.resizeObserver.disconnect(),this.resizeObserver=null),this.domClickHandler&&this.element&&(this.element.removeEventListener("click",this.domClickHandler),this.domClickHandler=null),this.debugMarker&&(this.debugMarker.destroy(),this.debugMarker=null),super.destroy()}}class ov{constructor(e){f(this,"customElementsMap",new Map);f(this,"gifTicker",null);f(this,"gifElements",new Set);this.appService=e}async drawCustomElements(e){if(!e||e.length===0){this.clearAllCustomElements();return}const t=new Set(e.map(r=>r.id)),i=Array.from(this.customElementsMap.keys());for(const r of i)t.has(r)||this.removeCustomElement(r);const s=e.map(async r=>{const o=this.customElementsMap.get(r.id);o?this.isSameData(o,r)||(r.type==="gif"&&o.getElementData().src!==r.src?(this.removeCustomElement(r.id),await this.addNewCustomElement(r)):await this.updateElementData(o,r)):await this.addNewCustomElement(r)});await Promise.all(s),this.updateGifTicker()}clearAllCustomElements(){const e=this.appService;this.customElementsMap.forEach(t=>{t instanceof Ve?e.appContainer.removeFromLayer(Ei,t):e.appContainer.removeFromLayer(Ii,t),t.destroy()}),this.customElementsMap.clear(),this.gifElements.clear(),this.stopGifTicker()}async addNewCustomElement(e){const t=this.appService;let i;switch(e.type){case"image":i=new Wn(this.appService,e);break;case"gif":{const s=await N.load(e.src);i=new Ve(this.appService,s,e);break}case"html":i=new Di(this.appService,e);break;default:throw new Error(`Unsupported custom element type: ${e.type}`)}await i.initialize(),this.customElementsMap.set(e.id,i),i instanceof Ve?(t.appContainer.addToLayer(Ei,i),this.gifElements.add(i)):t.appContainer.addToLayer(Ii,i)}removeCustomElement(e){const t=this.appService,i=this.customElementsMap.get(e);i&&(i instanceof Ve?(this.gifElements.delete(i),t.appContainer.removeFromLayer(Ei,i)):t.appContainer.removeFromLayer(Ii,i),i.destroy(),this.customElementsMap.delete(e))}isSameData(e,t){return e.getElementData().type!==t.type?!1:t.type==="image"&&e instanceof Wn||t.type==="gif"&&e instanceof Ve||t.type==="html"&&e instanceof Di?e.isSameData(t):!1}async updateElementData(e,t){if(t.type==="image"&&e instanceof Wn)await e.updateElementData(t);else if(t.type==="gif"&&e instanceof Ve)await e.updateElementData(t);else if(t.type==="html"&&e instanceof Di)await e.updateElementData(t);else throw new Error("Element type mismatch during update")}updateGifTicker(){this.gifElements.size>0?this.startGifTicker():this.stopGifTicker()}startGifTicker(){var e;(e=this.gifTicker)!=null&&e.started||(this.gifTicker?this.gifTicker.maxFPS=1:(this.gifTicker=new yt,this.gifTicker.maxFPS=1,this.gifTicker.add(()=>{this.renderGifContainer()})),this.gifTicker.start())}stopGifTicker(){var e;(e=this.gifTicker)!=null&&e.started&&(w.log("⏸️ [GifTicker] 停止 GIF 专用渲染"),this.gifTicker.stop())}renderGifContainer(){const e=this.appService;if(this.gifElements.size===0)return;const t=e.getApp();t.renderer.render(t.stage)}destroy(){this.stopGifTicker(),this.gifTicker&&(this.gifTicker.destroy(),this.gifTicker=null),this.clearAllCustomElements()}}class av extends L{constructor(t,i){super();f(this,"roomId");f(this,"roomIndex");f(this,"appService");f(this,"nameText");f(this,"iconSprite",null);f(this,"iconWrapper",null);f(this,"iconBg",null);this.appService=t,this.roomId=i.id,this.roomIndex=i.index;const{nameLabel:s,type:r}=t.roomConfig,{showRoomType:o}=t.runtime,a=i.colorIndex??i.index,h=this.getRoomNameColor(a),l=new ue({fontSize:s.fontSize,fontFamily:s.fontFamily,fontWeight:s.fontWeight,fill:h,align:"center"}),c=i.name||"Unknown";this.nameText=new Ws({text:c,style:l}),this.nameText.anchor.set(.5),o&&i.type!=null&&(r!=null&&r.assets)&&r.assets[i.type]&&this.createIcon(i.type,h),this.addChild(this.nameText),this.layout()}createIcon(t,i){const{type:s}=this.appService.roomConfig,r=s.iconSize||14;this.iconWrapper||(this.iconWrapper=new L,this.addChild(this.iconWrapper)),s.container.visible?(this.iconBg||(this.iconBg=new U,this.iconWrapper.addChild(this.iconBg)),this.drawIconBg(i)):this.iconBg&&(this.iconBg.destroy(),this.iconBg=null),this.iconSprite||(this.iconSprite=new Zt(this.appService),this.iconSprite.anchor.set(.5),this.iconWrapper.addChild(this.iconSprite)),this.iconSprite.visible=!0,this.iconSprite.tint=s.container.visible?"#ffffff":i,this.iconSprite.setFixedSize(r,r),this.iconSprite.loadTextureAndSetSize(s.assets[t],{width:r,height:r,sizeFixed:!1}).then(()=>{this.iconSprite&&(this.iconSprite.visible=this.appService.runtime.showRoomType,this.layout())}),s.container&&this.iconSprite.position.set(0,0)}drawIconBg(t){const{type:i}=this.appService.roomConfig;if(!this.iconBg||!i.container.visible)return;const{size:s,borderRadius:r}=i.container;this.iconBg.clear().roundRect(-s/2,-s/2,s,s,r).fill(t)}layout(){if(!this.iconWrapper||!this.iconWrapper.visible){this.nameText.position.set(0,0);return}if(!(this.iconSprite&&this.iconSprite.visible||this.iconBg&&this.iconBg.visible)){this.nameText.position.set(0,0);return}const{gap:i=4,position:s="left"}=this.appService.roomConfig.type,r=this.nameText.width,o=this.iconWrapper.width,h=-(o+i+r)/2;s==="left"?(this.iconWrapper.x=h+o/2,this.nameText.x=h+o+i+r/2):(this.nameText.x=h+r/2,this.iconWrapper.x=h+r+i+o/2),this.iconWrapper.y=0,this.nameText.y=0}updateName(t){this.nameText.text=t,this.layout()}refreshColor(t){const{type:i}=this.appService.roomConfig,s=this.appService.getRoomData(this.roomId),r=(s==null?void 0:s.colorIndex)??this.roomIndex,o=this.getRoomNameColor(r,t);this.nameText.style.fill=o,this.iconBg&&this.drawIconBg(o),this.iconSprite&&(this.iconSprite.tint=i.container.visible?"#ffffff":o)}getRoomNameColor(t,i){const{colors:s}=this.appService.roomConfig,{enableRoomSelection:r,selectRoomIds:o}=this.appService.runtime;if(i)return i;if(r)return!o.includes(this.roomId)&&s.nameInactive?s.nameInactive[t%s.nameInactive.length]:s.name[t%s.name.length];const a=s.nameNormal||s.name;return a[t%a.length]}async updateRoomType(t){const{type:i}=this.appService.roomConfig;if(!this.appService.runtime.showRoomType||t==null||!(i!=null&&i.assets)||!i.assets[t])this.iconWrapper&&(this.iconWrapper.visible=!1);else{const r=this.appService.getRoomData(this.roomId),o=(r==null?void 0:r.colorIndex)??this.roomIndex,a=this.getRoomNameColor(o);this.createIcon(t,a),this.iconWrapper&&(this.iconWrapper.visible=!0)}this.layout()}updateRoomTypeVisibility(t){if(this.iconWrapper)this.iconWrapper.visible=t,this.layout();else if(t){const i=this.appService.getRoomData(this.roomId);i&&this.updateRoomType(i.type??null)}}destroy(t){this.iconBg&&(this.iconBg.destroy(),this.iconBg=null),this.iconSprite&&(this.iconSprite.destroy(),this.iconSprite=null),this.iconWrapper&&(this.iconWrapper.destroy(),this.iconWrapper=null),this.nameText.destroy({texture:!0,textureSource:!0}),super.destroy(t)}}class hv extends L{constructor(t,i){super();f(this,"background");f(this,"foldedIndicator");f(this,"propertyIcons",new Map);f(this,"orderContainer");f(this,"orderBackground");f(this,"orderText");f(this,"isFolded",!1);f(this,"roomId");f(this,"roomIndex");f(this,"isDestroyed",!1);this.appService=t;const s=this.appService.roomConfig;this.roomId=i.id,this.roomIndex=i.index,this.background=new U,this.foldedIndicator=new U,this.foldedIndicator.visible=!1;const{property:r}=s,o=i.colorIndex??i.index,a=this.getIconColor(o);this.initializePropertyIcons(r.displayOrders,a);const h=r.cleanOrder.color==="auto"?s.colors.active[o%s.colors.active.length]:r.cleanOrder.color;this.orderContainer=new L,this.orderBackground=new U,this.orderText=new Ws({text:"",style:new ue({fontSize:r.cleanOrder.fontSize,fontFamily:r.cleanOrder.fontFamily,fontWeight:r.cleanOrder.fontWeight,fill:h,align:"center",trim:!0})}),this.orderText.anchor.set(.5,.5),this.orderContainer.addChild(this.orderBackground),this.orderContainer.addChild(this.orderText),this.addChild(this.background),this.addChild(this.foldedIndicator),this.propertyIcons.forEach(({sprite:l})=>{this.addChild(l)}),this.addChild(this.orderContainer),this.visible=this.appService.runtimeSnapshot.showRoomProperty}initializePropertyIcons(t,i){const s=["cleanMode","suction","cistern","cleanTimes"];t.forEach(r=>{const o=s.includes(r),a=new Zt(this.appService);a.tint=i,a.anchor.set(0,0),this.propertyIcons.set(r,{fieldName:r,sprite:a,isBuiltin:o})})}async updateProperty(t){this.isDestroyed||this.destroyed||(await this.updateIcons(t),!(this.isDestroyed||this.destroyed)&&this.updateBackground())}getFieldValue(t,i){if(["cleanMode","suction","cistern","cleanTimes"].includes(i))return t[i]??null;if(t.customData&&i in t.customData){const r=t.customData[i];return typeof r=="number"?r:null}return null}getAssetAlias(t,i){const s={cleanMode:r=>`cleanMode_${r}`,suction:r=>`fan_${r}`,cistern:r=>`water_${r}`,cleanTimes:r=>`cleanTimes${r}`};return t in s?s[t](i):`custom_${t}_${i}`}shouldShowField(t,i,s){const{showRoomProperty:r}=this.appService.runtimeSnapshot;return!(s===null||!r||i==="cleanTimes"&&s<=0)}getDisplayElements(t){const{displayOrders:i}=this.appService.roomConfig.property,{showRoomOrder:s}=this.appService.runtimeSnapshot,r=t.order||0,o=s&&r>0,a=[];return o&&a.push({element:this.orderContainer,show:!0,isOrder:!0,fieldName:"order"}),i.forEach(h=>{const l=this.propertyIcons.get(h);if(!l||!l.sprite)return;const c=this.getFieldValue(t,h);this.shouldShowField(t,h,c)&&c!==null&&a.push({element:l.sprite,show:!0,isOrder:!1,fieldName:h,value:c})}),{elementsToShow:a,orderValue:r}}async updateIcons(t){if(this.isDestroyed||this.destroyed||this.isFolded)return;const{iconWidth:i,iconHeight:s,container:r,cleanOrder:o,iconGap:a}=this.appService.roomConfig.property,{paddingHorizontal:h,paddingVertical:l}=r,{elementsToShow:c,orderValue:d}=this.getDisplayElements(t);this.orderContainer.visible=!1,this.propertyIcons.forEach(({sprite:g})=>{g.visible=!1});const u=[];if(c.forEach(g=>{if(g.isOrder){this.orderContainer.visible=!0,this.orderText.text=d.toString();const m=t.colorIndex??this.roomIndex,y=this.getIconColor(m);this.orderBackground.clear(),this.orderBackground.setFillStyle({color:y}),this.orderBackground.circle(i/2,s/2,i/2).fill();const x=this.resolveOrderTextColor(m);this.orderText.style.fill=x,this.orderText.position.set(i/2,s/2)}else{const m=this.propertyIcons.get(g.fieldName);if(m&&m.sprite){m.sprite.visible=!0;const y=this.getAssetAlias(g.fieldName,g.value);u.push(m.sprite.loadTextureAndSetSize(y,{width:i,height:s,sizeFixed:!1}))}}}),await Promise.all(u),this.isDestroyed||this.destroyed)return;let p=h;c.forEach((g,m)=>{const{element:y,isOrder:x}=g;!y||!y.position||(y.position.set(p,l),p+=i,m<c.length-1&&(x?p+=o.gapRight:p+=a))})}updateBackground(){if(this.isDestroyed||this.destroyed)return;const t=this.appService.roomConfig,{container:i,foldable:s}=t.property,{borderRadius:r,tailHeight:o,tailWidth:a,backgroundColor:h}=i,l=this.calculateContentWidth(),c=this.calculateContentHeight(),d=Math.min(r,l/2,c/2),u=d*.8,p=Math.max(l-u*2,a*.5),g=Math.min(a,l/2,p);if(this.background.clear(),this.background.setFillStyle({color:h}),s){const m=(l-g)/2,y=c+o;this.background.moveTo(d,0),this.background.lineTo(l-d,0),this.background.arcTo(l,0,l,d,d),this.background.lineTo(l,c-d),this.background.arcTo(l,c,l-d,c,d),this.background.lineTo(m+g,c),this.background.lineTo(m+g/2,y),this.background.lineTo(m,c),this.background.lineTo(d,c),this.background.arcTo(0,c,0,c-d,d),this.background.lineTo(0,d),this.background.arcTo(0,0,d,0,d),this.background.closePath()}else this.background.roundRect(0,0,l,c,d);this.background.fill()}calculateContentWidth(){const{iconWidth:t,container:i,cleanOrder:s,iconGap:r}=this.appService.roomConfig.property,{paddingHorizontal:o}=i,a=this.appService.getRoomData(this.roomId);if(!a)return o*2;const{elementsToShow:h}=this.getDisplayElements(a);let l=o;return h.forEach((c,d)=>{const{isOrder:u}=c;l+=t,d<h.length-1&&(u?l+=s.gapRight:l+=r)}),l+=o,l}calculateContentHeight(){const t=this.appService.roomConfig,{iconHeight:i,container:s}=t.property;return s.paddingVertical+i+s.paddingVertical}getTotalHeight(){const{foldable:t,container:i}=this.appService.roomConfig.property,{tailHeight:s}=i;return this.isFolded?s:this.calculateContentHeight()+(t?s:0)}getTotalWidth(){if(this.isFolded){const{tailWidth:i}=this.appService.roomConfig.property.container,s=this.calculateContentWidth();return Math.min(i,s/2)}return this.calculateContentWidth()}async setFolded(t){const{foldable:i}=this.appService.roomConfig.property;if(i)if(this.isFolded=t,t)this.background.visible=!1,this.orderContainer.visible=!1,this.propertyIcons.forEach(({sprite:s})=>{s.visible=!1}),this.foldedIndicator.visible=!0,this.updateFoldedIndicator();else{this.background.visible=!0,this.foldedIndicator.visible=!1,this.foldedIndicator.position.set(0,0),this.updateBackground();const s=this.appService.getRoomData(this.roomId);s&&await this.updateIcons(s)}}isFoldedState(){const{foldable:t}=this.appService.roomConfig.property;return t?this.isFolded:!1}updateFoldedIndicator(){const t=this.appService.roomConfig,{tailHeight:i,tailWidth:s,backgroundColor:r}=t.property.container,o=this.calculateContentWidth(),a=Math.min(s,o/2);this.foldedIndicator.clear(),this.foldedIndicator.setFillStyle({color:r}),this.foldedIndicator.poly([0,i,a,i,a/2,0]).fill(),this.foldedIndicator.position.set(0,0)}resolveOrderTextColor(t){const{property:i,colors:s}=this.appService.roomConfig,{enableRoomSelection:r}=this.appService.runtime;if(i.cleanOrder.color==="auto"){const o=r?s.active:s.normal||s.active;return o[t%o.length]}return i.cleanOrder.color}getIconColor(t){const{colors:i}=this.appService.roomConfig,{propertyTheme:s,propertyThemeInactive:r,propertyThemeNormal:o}=i,{enableRoomSelection:a,selectRoomIds:h}=this.appService.runtime;if(a)return!h.includes(this.roomId)&&r?r[t%r.length]:s[t%s.length];const l=o||s;return l[t%l.length]}refreshColor(){const t=this.appService.getRoomData(this.roomId),i=(t==null?void 0:t.colorIndex)??this.roomIndex,s=this.getIconColor(i);if(this.propertyIcons.forEach(({sprite:r})=>{r.tint=s}),this.orderBackground&&this.orderBackground.visible){const{property:r}=this.appService.roomConfig,o=r.iconWidth,a=r.iconHeight;this.orderBackground.clear(),this.orderBackground.setFillStyle({color:s}),this.orderBackground.circle(o/2,a/2,o/2).fill();const h=this.resolveOrderTextColor(i);this.orderText.style.fill=h}}destroy(){this.isDestroyed||(this.isDestroyed=!0,this.propertyIcons.forEach(({sprite:t})=>{t.destroy()}),this.propertyIcons.clear(),super.destroy({children:!0,context:!0}))}}class lv extends L{constructor(t,i){super();f(this,"background");f(this,"checkmarkIcon");f(this,"bubble");f(this,"roomIndex");f(this,"roomId");this.appService=t;const s=this.appService.roomConfig;this.roomId=i.id,this.roomIndex=i.index,this.background=new U,this.bubble=new U;const{colors:{selectionIndicatorIcon:r}}=s;this.checkmarkIcon=new Zt(this.appService);const o=i.colorIndex??i.index;this.checkmarkIcon.tint=r[o%r.length],this.checkmarkIcon.anchor.set(0,0),this.addChild(this.background),this.addChild(this.bubble),this.addChild(this.checkmarkIcon)}async updateIndicator(t){const{roomSelectionMode:i,enableRoomSelection:s,selectRoomIds:r}=this.appService.runtimeSnapshot;if(!s||i!=="checkmark"){this.visible=!1;return}const o=r.includes(t.id);await this.showCheckmarkMode(o),this.updateBackground()}async showCheckmarkMode(t){const{selectionIndicator:i}=this.appService.roomConfig,{iconWidth:s,iconHeight:r}=i;if(t){this.visible=!0,this.checkmarkIcon.visible=!0,await this.checkmarkIcon.loadTextureAndSetSize("checkmark",{width:s,height:r,sizeFixed:!1});const o=i.containerWidth/2,a=i.containerHeight/2;this.checkmarkIcon.position.set(o-s/2,a-r/2)}else this.visible=!1}updateBackground(){const{selectionIndicator:t,colors:i}=this.appService.roomConfig,{containerWidth:s,containerHeight:r,strokeWidth:o,strokeColor:a,borderRadius:h,tailHeight:l,tailWidth:c}=t,d=this.appService.getRoomData(this.roomId),u=(d==null?void 0:d.colorIndex)??this.roomIndex,p=i.selectionIndicatorBackground[u%i.selectionIndicatorBackground.length],g=a==="auto"?p:a;if(this.checkmarkIcon.tint=i.selectionIndicatorIcon[u%i.selectionIndicatorIcon.length],this.background.clear(),this.bubble.clear(),this.background.setFillStyle({color:p}).roundRect(0,0,s,r,h).fill().setStrokeStyle({color:g,width:o,alignment:0}).stroke(),l>0&&c>0){const m=(s-c)/2;this.bubble.setFillStyle({color:g});const y=r+o;this.bubble.poly([m,y-1,m+c,y-1,m+c/2,y+l]).fill()}}getTotalHeight(){const{selectionIndicator:t}=this.appService.roomConfig,{containerHeight:i,tailHeight:s,strokeWidth:r}=t;return i+r+(s>0?s:0)}getTotalWidth(){const{selectionIndicator:t}=this.appService.roomConfig;return t.containerWidth}async refreshColor(){const t=this.appService.getRoomData(this.roomId);t&&await this.updateIndicator(t)}destroy(){var t;(t=this.checkmarkIcon)==null||t.destroy(),super.destroy({children:!0,context:!0})}}class cv extends L{constructor(t,i){super();f(this,"roomId");f(this,"roomName");f(this,"roomProperty",null);f(this,"roomSelectionIndicator",null);f(this,"clickHandler",null);f(this,"unsubscribeMapRotation",null);f(this,"targetElasticScale",1);f(this,"currentElasticScale",1);f(this,"isAnimatingScale",!1);f(this,"scaleAnimationBound",null);f(this,"updateScaleBound",null);this.appService=t,this.enableRenderGroup(),this.roomId=i.id,this.initializeElasticScale(t.currentScale),this.updateScaleBound=s=>this.updateScale(s),this.appService.emitter.on("antiScale",this.updateScaleBound),this.updateScale(this.appService.currentScale),i.centerPoint&&this.position.set(i.centerPoint.x,i.centerPoint.y),this.roomName=new av(this.appService,i),this.roomName.visible=this.appService.runtimeSnapshot.showRoomName,this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=W(this.appService.runtime,"mapRotation",s=>{this.applyAntiRotation(s)}),this.clickHandler=new vt(this,{onClick:()=>{var s,r;(r=(s=this.appService.events)==null?void 0:s.onClickRoomProperties)==null||r.call(s,i)}})}async initialize(t){await this.createRoomProperty(t),await this.createRoomSelectionIndicator(t),this.updateLayout()}applyAntiRotation(t){const i=-t*Math.PI/180;this.rotation=i}initializeElasticScale(t){const{enableElasticScale:i,elasticMinScale:s,elasticMaxScale:r}=this.appService.roomConfig;if(!i)return;const o=1,a=5;let h;t<=o?h=s:t>=a?h=r:h=1,this.targetElasticScale=h,this.currentElasticScale=h}updateScale(t){const{enableElasticScale:i,elasticMinScale:s,elasticMaxScale:r}=this.appService.roomConfig;if(!i){t!==0&&this.scale.set(1/t);return}if(t===0)return;const o=1,a=5;let h;t<=o?h=s:t>=a?h=r:h=1;const c=1/t*h;Math.abs(this.targetElasticScale-h)>.01?(this.targetElasticScale=h,this.startScaleAnimation()):this.scale.set(c)}startScaleAnimation(){this.scaleAnimationBound||(this.scaleAnimationBound=this.animateScale.bind(this)),this.isAnimatingScale||(this.isAnimatingScale=!0,this.appService.getApp().ticker.add(this.scaleAnimationBound))}animateScale(){this.currentElasticScale+=(this.targetElasticScale-this.currentElasticScale)*.3;const r=1/this.appService.currentScale*this.currentElasticScale;this.scale.set(r),Math.abs(this.currentElasticScale-this.targetElasticScale)<.001&&(this.currentElasticScale=this.targetElasticScale,this.isAnimatingScale=!1,this.scaleAnimationBound&&this.appService.getApp().ticker.remove(this.scaleAnimationBound))}shouldShowRoomProperty(){const{showRoomOrder:t,showRoomProperty:i,selectRoomIds:s,enableRoomSelection:r,roomSelectionMode:o}=this.appService.runtimeSnapshot,a=this.appService.getRoomData(this.roomId);if(!a||r&&o==="checkmark"&&s.includes(this.roomId))return!1;const h=t&&(a.order||0)>0;let l=!1;if(i){const{displayOrders:c}=this.appService.roomConfig.property;l=c.some(d=>!!(d==="suction"&&a.suction!=null||d==="cistern"&&a.cistern!=null||d==="cleanMode"&&a.cleanMode!=null||d==="cleanTimes"&&a.cleanTimes>0||a.customData&&d in a.customData&&typeof a.customData[d]=="number"&&a.customData[d]!=null))}return h||l}shouldShowRoomSelectionIndicator(){const{enableRoomSelection:t,roomSelectionMode:i}=this.appService.runtimeSnapshot;return t&&i==="checkmark"}async updateRoomPropertyVisibility(){if(!this.roomProperty)return;if(!this.shouldShowRoomProperty())this.roomProperty.visible=!1;else{this.roomProperty.visible=!0;const i=this.appService.runtimeSnapshot.roomPropertyFoldIds.includes(this.roomId);await this.roomProperty.setFolded(i);const s=this.appService.getRoomData(this.roomId);s&&await this.roomProperty.updateProperty(s)}this.updateLayout()}async updateRoomSelectionIndicatorVisibility(){if(!this.roomSelectionIndicator)return;if(this.shouldShowRoomSelectionIndicator()){const i=this.appService.getRoomData(this.roomId);i&&await this.roomSelectionIndicator.updateIndicator(i)}else this.roomSelectionIndicator.visible=!1;this.updateLayout()}async createRoomProperty(t){this.roomProperty&&(this.removeChild(this.roomProperty),this.roomProperty.destroy()),this.roomProperty=new hv(this.appService,t),await this.roomProperty.updateProperty(t),this.addChild(this.roomProperty),this.addChild(this.roomName),await this.updateRoomPropertyVisibility(),this.updateLayout()}async createRoomSelectionIndicator(t){this.roomSelectionIndicator&&(this.removeChild(this.roomSelectionIndicator),this.roomSelectionIndicator.destroy()),this.roomSelectionIndicator=new lv(this.appService,t),await this.updateRoomSelectionIndicatorVisibility(),this.addChild(this.roomSelectionIndicator)}updateLayout(){var l,c,d,u,p,g;if(this.destroyed)return;const{property:{offsetY:t,offsetX:i},selectionIndicator:{offsetY:s,offsetX:r}}=this.appService.roomConfig,o=((l=this.roomProperty)==null?void 0:l.visible)||!1,a=((c=this.roomName)==null?void 0:c.visible)||!1,h=((d=this.roomSelectionIndicator)==null?void 0:d.visible)||!1;if(o&&this.roomProperty){const m=this.roomProperty.getTotalHeight(),y=this.roomProperty.getTotalWidth();if(this.roomProperty.isFoldedState()){const S=-y/2+i,v=-m/2-t;this.roomProperty.position.set(S,v)}else a&&((u=this.roomName)!=null&&u.position)?(this.roomProperty.position.set(-y/2+i,-t-m),this.roomName.position.set(0,0)):this.roomProperty.position.set(-y/2+i,-m/2-t)}if(h&&this.roomSelectionIndicator){const m=this.roomSelectionIndicator.getTotalHeight(),y=this.roomSelectionIndicator.getTotalWidth();a&&((p=this.roomName)!=null&&p.position)?(this.roomSelectionIndicator.position.set(-y/2+r,-s-m),this.roomName.position.set(0,0)):this.roomSelectionIndicator.position.set(-y/2+r,-m/2-s)}a&&!o&&!h&&((g=this.roomName)!=null&&g.position)&&this.roomName.position.set(0,0)}updateName(t){this.roomName.updateName(t)}async updateRoomType(t){await this.roomName.updateRoomType(t),this.updateLayout()}updateRoomNameVisibility(t){this.roomName.visible=t,this.updateLayout()}updateRoomTypeVisibility(t){this.roomName.updateRoomTypeVisibility(t),this.updateLayout()}updatePosition(t){this.position.set(t.x,t.y)}async refreshColor(){this.roomName&&this.roomName.refreshColor(),this.roomProperty&&this.roomProperty.refreshColor(),this.roomSelectionIndicator&&await this.roomSelectionIndicator.refreshColor()}destroy(){var t,i,s,r;(t=this.clickHandler)==null||t.destroy(),this.clickHandler=null,this.unsubscribeMapRotation&&(this.unsubscribeMapRotation(),this.unsubscribeMapRotation=null),this.isAnimatingScale&&this.scaleAnimationBound&&(this.appService.getApp().ticker.remove(this.scaleAnimationBound),this.isAnimatingScale=!1),this.scaleAnimationBound=null,this.updateScaleBound&&(this.appService.emitter.off("antiScale",this.updateScaleBound),this.updateScaleBound=null),(i=this.roomProperty)==null||i.destroy(),this.roomProperty=null,(s=this.roomSelectionIndicator)==null||s.destroy(),this.roomSelectionIndicator=null,(r=this.roomName)==null||r.destroy(),this.isRenderGroup&&(this.isRenderGroup=!1),super.destroy()}}class dv extends L{constructor(t){super({isRenderGroup:!0});f(this,"floorTypeMap",new Map);f(this,"floorTypeMasks",new Map);f(this,"floorTypeContexts",new Map);f(this,"floorTypeToRooms",new Map);this.appService=t,this.appService.appContainer.addToLayer(Kr,this)}async createFloorTypes(t){if(!this.appService.runtimeSnapshot.showRoomFloorType)return;this.clearFloorTypes();const s=this.groupRoomsByFloorType(t),r=[];for(const[o,a]of s)r.push(this.createMergedFloorType(o,a));await Promise.all(r)}groupRoomsByFloorType(t){const i=new Map,s=this.appService;return t.forEach((r,o)=>{const a=s.getRoomData(o),h=(a==null?void 0:a.floorType)||0;h>=0&&(i.has(h)||i.set(h,[]),i.get(h).push({roomId:o,graphics:r}))}),i}async createMergedFloorType(t,i){const s=this.appService,{assets:r,opacity:o,scale:a}=s.roomConfig.floorType,h=t%r.length,l=`floorType${h}`;if(!r[h]){w.warn(`No texture asset configured for floorType: ${t}`);return}const c=await N.load(l);if(!c){w.warn(`Floor material texture not found: ${l}`);return}const d=i.map(({graphics:y})=>y.getLocalBounds()),u=Ax(d),p=new As({texture:c,width:u.width,height:u.height});p.x=u.x,p.y=u.y,p.alpha=o,p.tileScale.set(a);const{maskContainer:g,contexts:m}=this.createMergedMask(i.map(({graphics:y})=>y));p.mask=g,this.addChild(p),this.floorTypeMap.set(t,p),this.floorTypeMasks.set(t,g),this.floorTypeContexts.set(t,m),this.floorTypeToRooms.set(t,new Set(i.map(({roomId:y})=>y)))}createMergedMask(t){const i=new L,s=[];return t.forEach(r=>{const o=new U,a=r.context.clone();o.context=a,s.push(a),i.addChild(o)}),{maskContainer:i,contexts:s}}clearFloorTypes(){this.floorTypeMasks.forEach(t=>{try{t.destroy({children:!0})}catch(i){w.warn("Error destroying floor mask:",i)}}),this.floorTypeMasks.clear(),this.floorTypeContexts.forEach(t=>{try{t.forEach(i=>{try{i.destroy()}catch(s){w.warn("Error destroying cloned graphics context:",s)}})}catch(i){w.warn("Error destroying graphics contexts:",i)}}),this.floorTypeContexts.clear(),this.floorTypeMap.forEach(t=>{try{this.removeChild(t),t.destroy()}catch(i){w.warn("Error destroying floor material:",i)}}),this.floorTypeMap.clear(),this.floorTypeToRooms.clear()}destroy(){this.clearFloorTypes(),super.destroy()}}const Gn=(n,e)=>n&&e?{x:n.x-e.x,y:n.y-e.y}:null;class uv{constructor(e){f(this,"unsubscribeFns",[]);f(this,"roomInfoContainer",new L);f(this,"roomInfoMap",new Map);f(this,"roomDisplayMap",new Map);f(this,"roomFloorType");this.appService=e,this.roomFloorType=new dv(e),e.appContainer.addToLayer(zc,this.roomInfoContainer);const t=W(e.runtime,"showRoomFloorType",d=>{w.log(`[runtime] showRoomFloorType: ${d}`),d?this.updateFloorTypes():this.roomFloorType.clearFloorTypes()}),i=W(e.runtime,"showRoomProperty",d=>{w.log(`[runtime] showRoomProperty: ${d}`),this.updateAllRoomPropertyVisibility()}),s=W(e.runtime,"showRoomOrder",d=>{w.log(`[runtime] showRoomOrder: ${d}`),this.updateAllRoomPropertyVisibility()}),r=W(e.runtime,"roomPropertyFoldIds",d=>{w.log(`[runtime] roomPropertyFoldIds: ${d}`),this.updateAllRoomPropertyVisibility()}),o=W(e.runtime,"showRoomName",d=>{w.log(`[runtime] showRoomName: ${d}`),this.updateAllRoomNameVisibility(d)}),a=W(e.runtime,"showRoomType",d=>{w.log(`[runtime] showRoomType: ${d}`),this.updateAllRoomTypeVisibility(d)}),h=W(e.runtime,"enableRoomSelection",d=>{w.log(`[runtime] enableRoomSelection: ${d}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()}),l=W(e.runtime,"selectRoomIds",d=>{w.log(`[runtime] selectRoomIds: ${d}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()}),c=W(e.runtime,"roomSelectionMode",d=>{w.log(`[runtime] roomSelectionMode: ${d}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()});this.unsubscribeFns.push(t,i,s,r,o,a,h,l,c)}async drawRoomProperty(e){var s;const t=this.appService;this.roomDisplayMap.clear();const i=((s=t.getApp().mapState)==null?void 0:s.origin)??null;return e.forEach((r,o)=>{const a=t.mapManager.getRoomById(r.id),h=(a==null?void 0:a.centerPoint)||null,l={...r,centerPoint:h,relativeCenterPoint:Gn(h,i),index:o,colorIndex:a==null?void 0:a.colorIndex};this.roomDisplayMap.set(r.id,l)}),await this.updateRoomInfoDisplay(),await this.updateFloorTypes(),!0}async updateRoomInfoDisplay(){if(this.roomDisplayMap.size===0){this.appService.mapManager.getAllRooms().length===0&&this.clearRoomInfos();return}const e=Array.from(this.roomDisplayMap.values()).filter(t=>t.centerPoint!==null);this.clearRoomInfos(),await Promise.all(e.map(t=>this.createRoomInfo(t)))}async createRoomInfo(e){const t=new cv(this.appService,e);this.roomInfoContainer.addChild(t),this.roomInfoMap.set(e.id,t),await t.initialize(e)}updateRoomName(e,t){const i=this.roomInfoMap.get(e);i&&i.updateName(t)}async updateRoomType(e,t){const i=this.roomDisplayMap.get(e);i&&(i.type=t);const s=this.roomInfoMap.get(e);s&&await s.updateRoomType(t)}updateRoomPosition(e,t){var r;const i=this.roomDisplayMap.get(e);if(i){i.centerPoint=t;const o=((r=this.appService.getApp().mapState)==null?void 0:r.origin)??null;i.relativeCenterPoint=Gn(t,o)}const s=this.roomInfoMap.get(e);s&&s.updatePosition(t)}clearRoomInfos(){if(this.roomInfoMap.size===0)return;const e=Array.from(this.roomInfoMap.values());this.roomInfoContainer.removeChildren(),e.forEach(t=>{try{t.destroy()}catch(i){w.warn(`[RoomManager] Error destroying RoomInfo for room ${t.roomId}:`,i)}}),this.roomInfoMap.clear()}getRoomPropertyById(e){return this.roomDisplayMap.get(e)}async refresh(){var i;const e=this.appService;this.roomFloorType.clearFloorTypes();const t=((i=e.getApp().mapState)==null?void 0:i.origin)??null;this.roomDisplayMap.forEach((s,r)=>{const o=e.mapManager.getRoomById(r),a=(o==null?void 0:o.centerPoint)||null;if(s.centerPoint!==a){s.centerPoint=a,s.relativeCenterPoint=Gn(a,t);const l=this.roomInfoMap.get(r);l&&a&&l.updatePosition(a)}const h=o==null?void 0:o.colorIndex;if(s.colorIndex!==h&&h!==void 0){s.colorIndex=h;const l=this.roomInfoMap.get(r);l&&l.refreshColor()}}),await this.updateRoomInfoDisplay(),await this.updateFloorTypes()}async updateAllRoomPropertyVisibility(){this.roomInfoMap.size!==0&&await Promise.all(Array.from(this.roomInfoMap.values()).map(async e=>{try{await e.updateRoomPropertyVisibility()}catch(t){console.warn(`[RoomManager] Failed to update room property visibility for room ${e.roomId}`,t)}}))}updateAllRoomNameVisibility(e){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(t=>{t.updateRoomNameVisibility(e)})}updateAllRoomTypeVisibility(e){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(t=>{t.updateRoomTypeVisibility(e)})}updateAllRoomSelectionIndicatorVisibility(){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(e=>{e.updateRoomSelectionIndicatorVisibility()})}refreshAllRoomColors(){this.roomInfoMap.size!==0&&this.roomInfoMap.forEach(e=>{e.refreshColor()})}async updateFloorTypes(){const e=this.appService,t=e.mapManager.roomFill.getRoomGraphicsMap();t.size>0?(await this.roomFloorType.createFloorTypes(t),e.getApp().renderOnceNextFrame()):e.mapManager.getAllRooms().length===0&&this.roomFloorType.clearFloorTypes()}clear(){this.clearRoomInfos(),this.roomInfoContainer.removeChildren(),this.roomInfoMap.clear(),this.roomDisplayMap.clear(),this.roomFloorType.clearFloorTypes()}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[],this.clearRoomInfos(),this.roomInfoContainer.destroy(),this.roomFloorType.destroy()}}var mh,yh;(mh=navigator==null?void 0:navigator.userAgent)!=null&&mh.includes("tuya-ark-ide")||((yh=navigator==null?void 0:navigator.userAgent)==null||yh.includes("miniProgram"));const pv=()=>{var i,s;if(!Fu.any)return!0;const n=navigator.userAgent.toLowerCase(),e=()=>{const r=navigator.deviceMemory;return r?r>=4:!0};let t=!1;if(/iphone|ipad|ipod/.test(n)){const r=(i=n.match(/os (\d+)_/))==null?void 0:i[1];t=(r?parseInt(r):0)>=12}else if(/android/.test(n)){const r=(s=n.match(/android (\d+)/))==null?void 0:s[1];t=(r?parseInt(r):0)>=10}return t&&e()};class fv extends L{constructor(t,i,s){super();f(this,"graphics");f(this,"sprite",null);f(this,"viewportBounds");f(this,"lastConfig",null);f(this,"onImageLoaded");this.label="background",this.viewportBounds=i,this.onImageLoaded=s,this.graphics=new U,this.graphics.label="backgroundGraphics",this.addChild(this.graphics),this.render(t)}async render(t){if(this.lastConfig=t,this.clear(),t.backgroundImage){await this.renderImage(t.backgroundImage,t.backgroundAlpha);return}if(t.backgroundGradient){this.renderGradient(t.backgroundGradient);return}if(t.backgroundColor!==void 0){this.renderSolidColor(t.backgroundColor,t.backgroundAlpha);return}w.warn("[Background] No background configuration provided")}clear(){this.graphics.clear(),this.sprite&&(this.removeChild(this.sprite),this.sprite.destroy(),this.sprite=null)}renderSolidColor(t,i){this.graphics.clear(),this.graphics.rect(0,0,this.viewportBounds.width,this.viewportBounds.height).fill({color:t,alpha:i}),w.debug("[Background] Rendered solid color background",{color:t,alpha:i})}renderGradient(t){const{width:i,height:s}=this.viewportBounds;if(this.graphics.clear(),t.type==="linear"){const r=t.x0??0,o=t.y0??0,a=t.x1??1,h=t.y1??1,l=new Gt({type:"linear",start:{x:r,y:o},end:{x:a,y:h},colorStops:t.colorStops});this.graphics.rect(0,0,i,s).fill(l),w.debug("[Background] Rendered linear gradient background",{x0:r,y0:o,x1:a,y1:h,colorStops:t.colorStops.length})}else if(t.type==="radial"){const r=t.cx??.5,o=t.cy??.5,a=t.r??.5,h=new Gt({type:"radial",center:{x:r,y:o},innerRadius:0,outerCenter:{x:r,y:o},outerRadius:a,colorStops:t.colorStops});this.graphics.rect(0,0,i,s).fill(h),w.debug("[Background] Rendered radial gradient background",{cx:r,cy:o,r:a,colorStops:t.colorStops.length})}}async renderImage(t,i){var s,r,o,a;try{const h=await N.load(t.src);if(!h){w.error("[Background] Failed to load image:",t.src),(s=this.lastConfig)!=null&&s.backgroundColor&&this.renderSolidColor(this.lastConfig.backgroundColor,i);return}this.sprite=new Xt(h),this.sprite.label="backgroundSprite",this.sprite.alpha=i;const{width:l,height:c}=this.viewportBounds,d=t.fit||"cover",u=((r=t.position)==null?void 0:r.x)??.5,p=((o=t.position)==null?void 0:o.y)??.5,g=h.width,m=h.height,y=g/m,x=l/c;switch(d){case"fill":this.sprite.width=l,this.sprite.height=c,this.sprite.x=0,this.sprite.y=0;break;case"contain":y>x?(this.sprite.width=l,this.sprite.height=l/y):(this.sprite.height=c,this.sprite.width=c*y),this.sprite.x=(l-this.sprite.width)*u,this.sprite.y=(c-this.sprite.height)*p;break;case"cover":y>x?(this.sprite.height=c,this.sprite.width=c*y):(this.sprite.width=l,this.sprite.height=l/y),this.sprite.x=(l-this.sprite.width)*u,this.sprite.y=(c-this.sprite.height)*p;break;case"none":this.sprite.width=g,this.sprite.height=m,this.sprite.x=(l-g)*u,this.sprite.y=(c-m)*p;break}t.repeat&&w.warn("[Background] Repeat mode not yet implemented"),this.addChild(this.sprite),w.debug("[Background] Rendered image background",{src:t.src,fit:d,position:{x:u,y:p},spriteSize:{width:this.sprite.width,height:this.sprite.height}}),this.onImageLoaded&&this.onImageLoaded()}catch(h){w.error("[Background] Error loading background image:",h),(a=this.lastConfig)!=null&&a.backgroundColor&&this.renderSolidColor(this.lastConfig.backgroundColor,i)}}async update(t){await this.render(t)}async updateViewportBounds(t){this.viewportBounds=t,this.lastConfig&&await this.render(this.lastConfig)}destroy(){this.clear(),super.destroy()}}class gv extends L{constructor(t){super();f(this,"carpetData");f(this,"carpetConfig");f(this,"controlsConfig");f(this,"carpetEvents");f(this,"appService");f(this,"controlFill");f(this,"editableShape");f(this,"clickHandler",null);f(this,"maskContainer",null);f(this,"maskGraphics",null);f(this,"texture",null);f(this,"textureMap",new Map);f(this,"tilingSprite",null);f(this,"initialZonePoints",[]);f(this,"unsubscribeFns",[]);f(this,"resolvedMaxSizeCache",null);f(this,"handleDragStart",()=>{this.isEditingEnabled()&&(this.carpetData.points&&this.carpetData.points.length>0?this.initialZonePoints=this.carpetData.points.map(t=>({...t})):this.initialZonePoints=[],this.appService.getApp().requestRender("zone-drag",!0))});f(this,"handleDragMove",t=>{if(!this.isEditingEnabled()||this.initialZonePoints.length===0||this.carpetData.shape==="custom")return;const i=this.parent.toLocal(t.global),s=this.controlFill.getDragStartPosition();if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.applyTranslation(r,o)});f(this,"handleDragEnd",()=>{var t,i;this.initialZonePoints=[],this.appService.getApp().stopRender("zone-drag"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});f(this,"handleMoveStart",()=>{this.carpetData.points&&this.carpetData.points.length>0?this.initialZonePoints=this.carpetData.points.map(t=>({...t})):this.initialZonePoints=[],this.appService.getApp().requestRender("zone-move",!0)});f(this,"handleMove",t=>{var a,h;if(!this.isEditingEnabled()||this.initialZonePoints.length===0)return;const i=this.parent.toLocal(t.global),s=(h=(a=this.editableShape)==null?void 0:a.getMoveButton())==null?void 0:h.getDragStartPosition();if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.applyTranslation(r,o)});f(this,"handleMoveEnd",()=>{var t,i;this.initialZonePoints=[],this.appService.getApp().stopRender("zone-move"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});f(this,"handleRotationStart",()=>{this.appService.getApp().requestRender("zone-rotate",!0)});f(this,"handleRotationMove",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});f(this,"handleRotationEnd",()=>{var t,i;this.appService.getApp().stopRender("zone-rotate"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});f(this,"handleClickRotate",t=>{var i,s;t&&(this.carpetData.points=t,this.drawCarpet()),this.appService.getApp().renderOnce(),(s=(i=this.carpetEvents).onUpdate)==null||s.call(i,this.getCarpetData())});f(this,"handleScaleStart",()=>{this.appService.getApp().requestRender("zone-scale",!0)});f(this,"handleScaleMove",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});f(this,"handleScaleMoveHorizontal",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});f(this,"handleScaleMoveVertical",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});f(this,"handleScaleEnd",()=>{var t,i;this.appService.getApp().stopRender("zone-scale"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});f(this,"handleDelete",()=>{var t,i;(i=(t=this.carpetEvents).onRemove)==null||i.call(t,this.carpetData.id)});f(this,"handleClick",()=>{var t,i;this.isEditingEnabled()||(i=(t=this.carpetEvents)==null?void 0:t.onClick)==null||i.call(t,this.getCarpetData())});f(this,"handlePointsUpdate",t=>{this.carpetData.points=t,this.drawCarpet()});const{appService:i,carpetData:s,events:r={},textureMap:o}=t;this.appService=i,this.textureMap=o,this.carpetEvents=r,this.controlsConfig=this.getControlsConfig(),this.carpetConfig=this.controlsConfig.carpet,this.processCarpetData(s),this.initializeComponents(),this.createEditControlLayer(),this.setupClickHandler(),this.setupEnableRoomSelectionListener(),this.updateEditState(),this.loadTexture()}getResolvedMaxSize(){const t=this.carpetConfig.maxSize;if(this.resolvedMaxSizeCache&&this.resolvedMaxSizeCache.key===t)return this.resolvedMaxSizeCache.value;const i=ri(this.carpetConfig.minSize,t,"carpet");return this.resolvedMaxSizeCache={key:t,value:i},i}validateCarpetShape(t){const i=this.getResolvedMaxSize();return this.appService.coords.validateShape(Sc(t),{minSize:et(this.carpetConfig.minSize),maxSize:i!=null?et(i):void 0})}processCarpetData(t){if(t.points&&t.points.length>=2)if(t.shape==="custom")this.carpetData={...t,points:t.points};else{const s=this.validateCarpetShape(t.points);this.carpetData={...t,points:s}}else this.carpetData={...t,points:[],shape:t.shape||"rectangle"}}getControlsConfig(){const{controls:t}=this.appService.getConfig();return t}isEditingEnabled(){return this.appService.runtimeSnapshot.editingCarpetIds.includes(this.carpetData.id)}isSelected(){return this.appService.runtimeSnapshot.selectedCarpetIds.includes(this.carpetData.id)}shouldShowEditControl(){return this.isEditingEnabled()||this.isSelected()}initializeComponents(){this.maskContainer=this.createMaskContainer(),this.controlFill=this.createControlFill(),this.addChild(this.maskContainer),this.addChild(this.controlFill),this.drawCarpet()}createMaskContainer(){const t=new L;return this.maskGraphics=new U,this.updateMaskShape(),t.addChild(this.maskGraphics),t.mask=this.maskGraphics,t}createControlFill(){const t=this.isEditingEnabled();return new Jr(this.appService,{points:this.carpetData.points||[],fillColor:this.carpetConfig.fillColor,enableInteraction:t,onDragStart:this.handleDragStart,onDragMove:this.handleDragMove,onDragEnd:this.handleDragEnd})}createEditControlLayer(){const t=this.isEditingEnabled(),i=this.carpetData.shape==="custom",s=!!t&&!i&&this.carpetConfig.scaleMode==="ratioLocked",r={...Dn(this.carpetConfig,["outlineStrokeWidth","outlineDashed","outlineDashArray","outlineFillColor","outlineOffset","outlineStrokeColor"]),...Dn(this.carpetConfig,["textColor","textPosition","textOffset"]),...Dn(this.controlsConfig,["textFontSize","textFontFamily","textFontWeight"]),showRotateButton:!!t&&!i&&this.carpetConfig.showRotateButton,showScaleButton:!!t&&!i,showDeleteButton:!!t,showMoveButton:!!t&&!i,showRadialScaleButton:s,iconWrapperFillColor:this.carpetConfig.iconWrapperFillColor,deleteIconWrapperFillColor:this.carpetConfig.deleteIconWrapperFillColor,rotateMode:this.carpetConfig.rotateMode,scaleMode:this.carpetConfig.scaleMode,moveButtonOffset:this.controlsConfig.moveButtonOffset},o=i?this.calculateBoundingRectanglePoints():this.carpetData.points||[];this.editableShape=new Hs({editControls:this.appService.editControlManager});const a=this.getResolvedMaxSize();this.editableShape.attach(this,{id:this.carpetData.id,topology:"quad",layerOptions:{config:r,zonePoints:o,minSize:this.carpetConfig.minSize,maxSize:a??void 0,contentLayer:Ke,events:{onRemove:this.handleDelete,onRotateStart:this.handleRotationStart,onRotateMove:this.handleRotationMove,onClickRotate:this.handleClickRotate,onRotateEnd:this.handleRotationEnd,onScaleStart:this.handleScaleStart,onScaleMove:this.handleScaleMove,onScaleMoveHorizontal:this.handleScaleMoveHorizontal,onScaleMoveVertical:this.handleScaleMoveVertical,onScaleEnd:this.handleScaleEnd,onMoveStart:this.handleMoveStart,onMoveMove:this.handleMove,onMoveEnd:this.handleMoveEnd,onClick:this.handleClick,onPointsUpdate:this.handlePointsUpdate}},editingState:{showRotateButton:!i&&this.carpetConfig.showRotateButton,showScaleButton:!i,showDeleteButton:!0,showMoveButton:!i,showBorder:!0,showSizeText:!0,borderStyle:this.carpetConfig.editing,showRadialScaleButton:!i&&this.carpetConfig.scaleMode==="ratioLocked"},idleState:{showRotateButton:!1,showScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}})}setupClickHandler(){this.interactiveChildren=!0,this.clickHandler=new vt(this,{onClick:()=>{var t,i;this.isEditingEnabled()||(i=(t=this.carpetEvents)==null?void 0:t.onClick)==null||i.call(t,this.getCarpetData())},stopPropagation:!1})}setupEnableRoomSelectionListener(){const t=W(this.appService.runtime,"enableRoomSelection",s=>{this.updateClickHandlerState(s)});this.unsubscribeFns.push(t);const i=this.appService.runtimeSnapshot.enableRoomSelection;this.updateClickHandlerState(i)}isRoomSelectionEnabled(){return this.appService.runtimeSnapshot.enableRoomSelection}updateClickHandlerState(t){if(t){if(this.eventMode="none",this.clickHandler){const i=this.clickHandler.getTarget();i.eventMode="none"}}else if(this.eventMode="static",this.clickHandler){const i=this.clickHandler.getTarget();i.eventMode="static"}}calculateBounds(){const{points:t}=this.carpetData;let i=1/0,s=1/0,r=-1/0,o=-1/0;if(t&&t.length>0)for(const a of t)i=Math.min(i,a.x),s=Math.min(s,a.y),r=Math.max(r,a.x),o=Math.max(o,a.y);return{minX:i,minY:s,maxX:r,maxY:o}}calculateBoundingRectanglePoints(){const{points:t}=this.carpetData;if(!t||t.length===0)return[];const{minX:i,minY:s,maxX:r,maxY:o}=Ts(t);return[{x:i,y:s},{x:r,y:s},{x:r,y:o},{x:i,y:o}]}updateMaskShape(){if(!this.maskGraphics)return;this.maskGraphics.clear();const{points:t,shape:i}=this.carpetData;if(!(!t||!Array.isArray(t)||t.length<2)){if(i==="round"){if(t.length<4)return;const r=Oe(t),[o,a,,h]=t,l=q(o,a),c=q(o,h),d=Math.atan2(a.y-o.y,a.x-o.x);this.maskGraphics.position.set(r.x,r.y),this.maskGraphics.rotation=d,this.maskGraphics.ellipse(0,0,l/2,c/2)}else{const r=t.flatMap(o=>[o.x,o.y]);this.maskGraphics.poly(r),this.maskGraphics.position.set(0,0),this.maskGraphics.rotation=0}this.maskGraphics.fill(16777215)}}loadTexture(){const{opacity:t,scale:i}=this.appService.carpetConfig,{type:s}=this.carpetData;try{this.texture=this.textureMap.get(s)||this.textureMap.get(-1)||null,this.texture&&this.maskContainer&&(this.tilingSprite&&(this.maskContainer.removeChild(this.tilingSprite),this.tilingSprite.destroy(),this.tilingSprite=null),this.createTilingSprite(i,t),this.appService.getApp().renderOnce())}catch(r){console.warn("Failed to load carpet texture:",r)}}createTilingSprite(t,i){if(!this.texture||!this.maskContainer)return;const s=this.calculateBounds();this.tilingSprite=new As({texture:this.texture,width:s.maxX-s.minX+100,height:s.maxY-s.minY+100}),this.tilingSprite.position.set(s.minX-50,s.minY-50),this.tilingSprite.tileScale.set(t),this.tilingSprite.alpha=i,this.maskContainer.addChild(this.tilingSprite)}updateTilingSprite(){if(!this.tilingSprite)return;const t=this.calculateBounds();this.tilingSprite.position.set(t.minX-50,t.minY-50),this.tilingSprite.width=t.maxX-t.minX+100,this.tilingSprite.height=t.maxY-t.minY+100}applyTranslation(t,i){this.carpetData.points=this.initialZonePoints.map(s=>({x:s.x+t,y:s.y+i})),this.drawCarpet()}drawCarpet(){const{points:t}=this.carpetData;if(!(!t||t.length<2)&&(this.updateMaskShape(),this.updateTilingSprite(),this.controlFill.updatePoints(t),this.editableShape)){const r=this.carpetData.shape==="custom"?this.calculateBoundingRectanglePoints():t;this.editableShape.updatePoints(r)}}updateEditState(){const t=this.isEditingEnabled(),i=this.isSelected(),s=this.shouldShowEditControl();this.controlFill.setInteractionEnabled(t),this.editableShape&&(i&&!t?this.editableShape.applyEditState({showRotateButton:!1,showScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!0,showSizeText:!1,borderStyle:this.carpetConfig.normal}):this.editableShape.setEditing(t)),this.zIndex=s?1e3:0}refreshConfig(){this.controlsConfig=this.getControlsConfig(),this.carpetConfig=this.controlsConfig.carpet,this.resolvedMaxSizeCache=null,this.controlFill.updateFillColor(this.carpetConfig.fillColor),this.editableShape.detach(),this.createEditControlLayer(),this.drawCarpet(),this.updateEditState()}updateCarpetData(t){const s=this.carpetData.type;if(t.points&&t.points.length>=2)if(t.shape==="custom")this.carpetData={...t,points:t.points};else{const r=this.validateCarpetShape(t.points);this.carpetData={...t,points:r}}else this.carpetData={...t,points:t.points||[]};s!==this.carpetData.type&&this.loadTexture(),this.drawCarpet(),this.updateEditState()}getCarpetData(){return{...this.carpetData}}refreshDisplay(){this.drawCarpet()}destroy(){var t,i,s,r,o;this.editableShape.detach(),this.unsubscribeFns.forEach(a=>a()),this.unsubscribeFns=[],(t=this.tilingSprite)==null||t.destroy(),(i=this.maskGraphics)==null||i.destroy(),(s=this.maskContainer)==null||s.destroy(),this.tilingSprite=null,this.maskGraphics=null,this.maskContainer=null,this.texture=null,(r=this.controlFill)==null||r.destroy(),(o=this.clickHandler)==null||o.destroy(),super.destroy()}}class mv{constructor(e){f(this,"customCarpetMap",new Map);f(this,"unsubscribeFns",[]);f(this,"textureMap",new Map);f(this,"texturesLoaded",!1);f(this,"texturesLoadingPromise",null);this.appService=e,this.applyLayerVisibility(e.runtime.showCustomCarpets);const t=W(e.runtime,"editingCarpetIds",r=>{w.log(`[runtime] editingCarpetIds: ${r}`),this.updateCarpetsEditState()}),i=W(e.runtime,"selectedCarpetIds",r=>{w.log(`[runtime] selectedCarpetIds: ${r}`),this.updateCarpetsEditState()}),s=W(e.runtime,"showCustomCarpets",r=>{w.log(`[runtime] showCustomCarpets: ${r}`),this.applyLayerVisibility(r)});this.unsubscribeFns.push(t,i,s)}async loadTextures(){if(!this.texturesLoaded){if(this.texturesLoadingPromise)return this.texturesLoadingPromise;this.texturesLoadingPromise=this._loadTextures(),await this.texturesLoadingPromise,this.texturesLoaded=!0,this.texturesLoadingPromise=null}}async _loadTextures(){const e=this.appService,{material:t,src:i}=e.carpetConfig;if(t)for(const s of t){const r=await N.load(s.src);this.textureMap.set(s.type,r)}if(i){const s=await N.load(i);this.textureMap.set(-1,s)}}async drawCustomCarpets(e){if(await this.loadTextures(),!e||e.length===0){this.clearAllCustomCarpets();return}const t=new Set(this.customCarpetMap.keys()),i=new Set(e.map(s=>s.id));for(const s of t)i.has(s)||this.removeCustomCarpet(s);e.forEach(s=>{const r=this.customCarpetMap.get(s.id.toString());r?this.isCarpetDataEqual(r.getCarpetData(),s)||r.updateCarpetData(s):this.addNewCustomCarpet(s)})}getCustomCarpets(){const e=[];return this.customCarpetMap.forEach(t=>{e.push(t.getCarpetData())}),e}getCustomCarpetById(e){return this.customCarpetMap.get(e)}clearAllCustomCarpets(){this.customCarpetMap.forEach((e,t)=>{var s;const i=this.customCarpetMap.get(t);i&&((s=i.parent)==null||s.removeChild(i),i.destroy())}),this.customCarpetMap.clear()}addNewCustomCarpet(e){const t=this.appService,i=new gv({appService:t,carpetData:e,textureMap:this.textureMap,events:{onRemove:s=>{var r,o;(o=(r=t.events)==null?void 0:r.onDeleteCustomCarpet)==null||o.call(r,{id:s})},onUpdate:s=>{var r,o;(o=(r=t.events)==null?void 0:r.onUpdateCustomCarpet)==null||o.call(r,s)},onClick:s=>{var r,o;(o=(r=t.events)==null?void 0:r.onClickCarpet)==null||o.call(r,{id:s.id})}}});this.customCarpetMap.set(e.id.toString(),i),t.appContainer.addToLayer(Ke,i)}removeCustomCarpet(e){const t=this.appService,i=this.customCarpetMap.get(e);i&&(t.appContainer.removeFromLayer(Ke,i),i.destroy(),this.customCarpetMap.delete(e))}updateCarpetsEditState(){this.customCarpetMap.forEach(e=>{e.updateEditState()})}applyLayerVisibility(e){const t=this.appService.appContainer.getLayer(Ke);t&&(t.visible=e)}isCarpetDataEqual(e,t){if(e.id!==t.id||e.type!==t.type||e.shape!==t.shape)return!1;const i=e.points||[],s=t.points||[];if(i.length!==s.length)return!1;for(let r=0;r<i.length;r++){const o=i[r],a=s[r];if(Math.abs(o.x-a.x)>.1||Math.abs(o.y-a.y)>.1)return!1}return!0}refreshDisplay(){this.customCarpetMap.forEach(e=>{e.refreshDisplay()})}refreshConfig(){this.customCarpetMap.forEach(e=>{e.refreshConfig()})}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[],this.clearAllCustomCarpets()}}function yv(n,e){return{coords:n.coords,editControls:n.editControlManager,furnitureConfig:n.furnitureConfig,controlsConfig:n.controlsConfig,gestures:n.gestureController,render:{request:t=>n.getApp().requestRender(t,!0),stop:t=>n.getApp().stopRender(t),once:t=>n.getApp().requestRender(t,!1)},events:e}}const ph="furniture-drag",fh="furniture-scale",gh="furniture-move",Un="furniture-rotate";class xv extends L{constructor(t){super();f(this,"deps");f(this,"config");f(this,"controlsConfig");f(this,"furnitureEvents");f(this,"data");f(this,"textureAlias");f(this,"sprite");f(this,"editableShape");f(this,"editing",!1);f(this,"clickHandler",null);f(this,"dragStartPosition",null);f(this,"initialPoints",[]);f(this,"isDragging",!1);f(this,"gestureSession",null);f(this,"originalSizeMeters",null);f(this,"resolveSizeConstraintPerEdge",()=>{var o,a;const{minScaleRatio:t,maxScaleRatio:i}=this.config,s=i===1/0||i==null?void 0:i,r=h=>{if(!h||h<=0)return{min:.1,max:void 0};const l=h*(t||0);return{min:l>0?l:.1,max:s!=null?h*s:void 0}};return{edge1:r((o=this.originalSizeMeters)==null?void 0:o.width),edge2:r((a=this.originalSizeMeters)==null?void 0:a.height)}});f(this,"onDragStart",t=>{if(!this.editing||!this.parent||t.target!==this&&t.target!==this.sprite)return;t.stopPropagation();const i=this.parent.toLocal(t.global);this.dragStartPosition={x:i.x,y:i.y},this.initialPoints=this.data.points.map(s=>({...s})),this.isDragging=!1,this.gestureSession=this.deps.gestures.hijack(t),this.gestureSession.onMove(this.onDragMove),this.gestureSession.onEnd(this.onDragEnd)});f(this,"onDragMove",t=>{if(!this.dragStartPosition||!this.parent)return;const i=this.parent.toLocal(t.global),s=i.x-this.dragStartPosition.x,r=i.y-this.dragStartPosition.y;!this.isDragging&&Math.abs(s)+Math.abs(r)<3||(this.isDragging||(this.isDragging=!0,this.deps.render.request(ph)),this.data.points=this.initialPoints.map(o=>({x:o.x+s,y:o.y+r})),this.redraw())});f(this,"onDragEnd",()=>{var t,i;this.gestureSession=null,this.dragStartPosition&&(this.isDragging&&((i=(t=this.furnitureEvents).onUpdate)==null||i.call(t,this.getData()),this.deps.render.stop(ph)),this.dragStartPosition=null,this.initialPoints=[],this.isDragging=!1)});f(this,"handleRotateStart",()=>{this.deps.render.request(Un)});f(this,"handleRotateMove",t=>{t&&(this.data.points=t,this.redraw())});f(this,"handleTapRotate",t=>{var i,s;t&&(this.data.points=t,this.redraw()),this.captureOriginalSize(),this.deps.render.once(Un),(s=(i=this.furnitureEvents).onUpdate)==null||s.call(i,this.getData())});f(this,"handleScaleStart",()=>{this.deps.render.request(fh)});f(this,"handleScaleMove",t=>{t&&(this.data.points=t,this.redraw())});f(this,"handleMoveStart",()=>{this.initialPoints=this.data.points.map(t=>({...t})),this.deps.render.request(gh)});f(this,"handleMove",t=>{var a;if(!this.editing||this.initialPoints.length===0||!this.parent)return;const i=this.parent.toLocal(t.global),s=(a=this.editableShape.getMoveButton())==null?void 0:a.getDragStartPosition();if(!s)return;const r=i.x-s.x,o=i.y-s.y;this.data.points=this.initialPoints.map(h=>({x:h.x+r,y:h.y+o})),this.redraw()});f(this,"handleMoveEnd",()=>{var t,i;this.initialPoints=[],this.deps.render.stop(gh),(i=(t=this.furnitureEvents).onUpdate)==null||i.call(t,this.getData())});f(this,"handleTransformEnd",()=>{var t,i;this.deps.render.stop(Un),this.deps.render.stop(fh),(i=(t=this.furnitureEvents).onUpdate)==null||i.call(t,this.getData())});f(this,"handleDelete",()=>{var t,i;(i=(t=this.furnitureEvents).onRemove)==null||i.call(t,this.data.id)});f(this,"handleClick",()=>{var t,i;this.editing||(i=(t=this.furnitureEvents).onClick)==null||i.call(t,this.getData())});const{deps:i,data:s,textureAlias:r}=t;this.deps=i,this.config=i.furnitureConfig,this.controlsConfig=i.controlsConfig,this.furnitureEvents=i.events,this.data={...s,points:s.points.map(o=>({...o}))},this.textureAlias=r,this.captureOriginalSize(),this.createSprite(),this.updateSpriteTransform(),this.createEditControlLayer(),this.eventMode="static",this.cursor="pointer",this.setupInteraction(),this.applyEditing()}captureOriginalSize(){const t=this.data.points;if(t.length<4){this.originalSizeMeters=null;return}const i=q(t[0],t[1]),s=q(t[1],t[2]);this.originalSizeMeters={width:this.deps.coords.toMeters(Bt(i)),height:this.deps.coords.toMeters(Bt(s))}}createSprite(){const t=N.get(this.textureAlias);this.sprite=new Xt(t),this.sprite.anchor.set(.5),this.sprite.alpha=this.config.opacity,this.sprite.eventMode="passive",this.addChild(this.sprite)}updateSpriteTransform(){const t=this.data.points;if(t.length<4)return;const i=Oe(t),s=t[1].x-t[0].x,r=t[1].y-t[0].y,o=Math.atan2(r,s),a=q(t[0],t[1]),h=q(t[1],t[2]);this.sprite.position.set(i.x,i.y),this.sprite.rotation=o,this.sprite.width=a,this.sprite.height=h}createEditControlLayer(){const t={outlineStrokeColor:String(this.config.outlineStrokeColor),outlineStrokeWidth:this.config.outlineStrokeWidth,outlineDashed:this.config.outlineDashed,outlineDashArray:this.config.outlineDashArray,outlineFillColor:this.config.outlineFillColor?String(this.config.outlineFillColor):void 0,outlineOffset:this.config.outlineOffset,iconWrapperFillColor:String(this.config.iconWrapperFillColor),showRotateButton:!0,showScaleButton:!0,showRadialScaleButton:!1,showDeleteButton:!0,showMoveButton:!0,rotateMode:"step",stepRotateAngle:this.config.rotateDirection==="ccw"?-Math.PI/2:Math.PI/2,scaleMode:this.config.lockAspectRatio?"ratioLocked":"free",textColor:String(this.config.textColor),textPosition:this.config.textPosition,textOffset:this.config.textOffset,moveButtonOffset:this.controlsConfig.moveButtonOffset,textFontSize:this.controlsConfig.textFontSize,textFontFamily:this.controlsConfig.textFontFamily,textFontWeight:this.controlsConfig.textFontWeight};this.editableShape=new Hs({editControls:this.deps.editControls});const i={config:t,zonePoints:this.data.points,sizeConstraintPerEdge:this.resolveSizeConstraintPerEdge,contentLayer:Te,events:{onRemove:this.handleDelete,onRotateStart:this.handleRotateStart,onRotateMove:this.handleRotateMove,onClickRotate:this.handleTapRotate,onRotateEnd:this.handleTransformEnd,onScaleStart:this.handleScaleStart,onScaleMove:this.handleScaleMove,onScaleEnd:this.handleTransformEnd,onMoveStart:this.handleMoveStart,onMoveMove:this.handleMove,onMoveEnd:this.handleMoveEnd,onClick:this.handleClick}};this.editableShape.attach(this,{id:this.data.id,topology:"quad",layerOptions:i,editingState:{showRotateButton:!0,showScaleButton:!0,showRadialScaleButton:!1,showDeleteButton:!0,showMoveButton:!0,showBorder:!0,showSizeText:this.config.showSizeText},idleState:{showRotateButton:!1,showScaleButton:!1,showRadialScaleButton:!1,showDeleteButton:!1,showMoveButton:!1,showBorder:!1,showSizeText:!1}})}setupInteraction(){this.clickHandler=new vt(this,{onClick:t=>{!this.isDragging&&((t==null?void 0:t.target)===this||(t==null?void 0:t.target)===this.sprite)&&this.handleClick()}}),this.on("pointerdown",this.onDragStart,this)}redraw(){this.data.points.length<4||(this.updateSpriteTransform(),this.editableShape.updatePoints(this.data.points))}applyEditing(){this.editableShape.setEditing(this.editing),this.zIndex=this.editing?1e3:0}updateEditState(t){this.editing!==t&&(this.editing=t,this.applyEditing())}isEditing(){return this.editing}getData(){return{id:this.data.id,furnitureType:this.data.furnitureType,points:this.data.points.map(t=>({...t}))}}updateData(t){this.data={...t,points:t.points.map(i=>({...i}))},this.captureOriginalSize(),this.data.points.length>=4&&(this.updateSpriteTransform(),this.editableShape.updatePoints(this.data.points))}destroy(){var t,i,s;(t=this.editableShape)==null||t.detach(),(i=this.gestureSession)==null||i.cancel(),this.gestureSession=null,(s=this.clickHandler)==null||s.destroy(),this.clickHandler=null,super.destroy({children:!0})}}class Sv{constructor(e){f(this,"furnitureMap",new Map);f(this,"unsubscribeFns",[]);this.appService=e,this.applyLayerVisibility(e.runtime.showFurnitures);const t=W(e.runtime,"editingFurnitureIds",s=>{w.log(`[runtime] editingFurnitureIds: ${s}`),this.updateEditState()}),i=W(e.runtime,"showFurnitures",s=>{w.log(`[runtime] showFurnitures: ${s}`),this.applyLayerVisibility(s)});this.unsubscribeFns.push(t,i)}async drawFurnitures(e){if(!e||e.length===0){this.clearAll();return}const t=new Set(this.furnitureMap.keys()),i=new Set(e.map(r=>r.id));for(const r of t)i.has(r)||this.removeFurniture(r);const s=[];for(const r of e){const o=this.furnitureMap.get(r.id);o?this.isDataEqual(o.getData(),r)||o.updateData(r):s.push(this.addFurniture(r))}await Promise.all(s)}async addFurniture(e){const t=this.appService;if(!t.furnitureConfig.assets.find(l=>l.type===e.furnitureType)){w.warn(`[FurnitureManager] No asset found for furnitureType: ${e.furnitureType}`);return}const r=`furniture_${e.furnitureType}`;await N.load(r);const o=yv(t,{onRemove:l=>{var c,d;(d=(c=t.events)==null?void 0:c.onRemoveFurniture)==null||d.call(c,l)},onUpdate:l=>{var c,d;(d=(c=t.events)==null?void 0:c.onUpdateFurniture)==null||d.call(c,l)},onClick:l=>{var c,d;(d=(c=t.events)==null?void 0:c.onClickFurniture)==null||d.call(c,l)}}),a=new xv({deps:o,data:e,textureAlias:r});this.furnitureMap.set(e.id,a),t.appContainer.addToLayer(Te,a),t.runtime.editingFurnitureIds.includes(e.id)&&(a.updateEditState(!0),this.moveToEditLayer(a))}removeFurniture(e){var i;const t=this.furnitureMap.get(e);t&&((i=t.parent)==null||i.removeChild(t),t.destroy(),this.furnitureMap.delete(e))}clearAll(){var e;for(const[,t]of this.furnitureMap)(e=t.parent)==null||e.removeChild(t),t.destroy();this.furnitureMap.clear()}applyLayerVisibility(e){const t=this.appService.appContainer.getLayer(Te);t&&(t.visible=e),this.furnitureMap.forEach(i=>{i.visible=e})}updateEditState(){const e=this.appService.runtime.editingFurnitureIds,{appContainer:t}=this.appService,i=t.getLayer(Te);this.furnitureMap.forEach((s,r)=>{const o=e.includes(r);s.updateEditState(o),o?this.moveToEditLayer(s):s.parent!==i&&this.moveToFurnitureLayer(s)})}moveToEditLayer(e){var t;(t=e.parent)==null||t.removeChild(e),this.appService.appContainer.addToLayer(Ie,e)}moveToFurnitureLayer(e){var t;(t=e.parent)==null||t.removeChild(e),this.appService.appContainer.addToLayer(Te,e)}getFurnitures(){const e=[];return this.furnitureMap.forEach(t=>{e.push(t.getData())}),e}isDataEqual(e,t){if(e.id!==t.id||e.furnitureType!==t.furnitureType||e.points.length!==t.points.length)return!1;for(let i=0;i<e.points.length;i++)if(Math.abs(e.points[i].x-t.points[i].x)>.1||Math.abs(e.points[i].y-t.points[i].y)>.1)return!1;return!0}destroy(){this.unsubscribeFns.forEach(e=>e()),this.unsubscribeFns=[],this.clearAll()}}class vv{constructor(e){f(this,"editControlLayers",new Map);this.appService=e}registerEditControl(e,t){const i=this.appService;this.editControlLayers.has(e)&&this.unregisterEditControl(e);const s=new _S(i,t);if(!i.appContainer.addToLayer(Ie,s))throw w.warn(`[EditControlManager] Failed to add edit control layer for id: ${e}`),s.destroy(),new Error(`Failed to register edit control for id: ${e}`);if(this.editControlLayers.set(e,s),t.contentLayer){const o=i.appContainer.getLayer(Ie),a=i.appContainer.getLayer(t.contentLayer);o&&a&&(o.position.x!==a.position.x||o.position.y!==a.position.y)&&w.warn(`[EditControlManager] Edit layer position does not match content layer "${t.contentLayer}" position — edit controls will appear misaligned. Ensure "${t.contentLayer}" is in ORIGIN_TRACKED_LAYERS.`,{edit:o.position,content:a.position})}return s}unregisterEditControl(e){const t=this.editControlLayers.get(e);if(!t)return;this.appService.appContainer.removeFromLayer(Ie,t),t.destroy(),this.editControlLayers.delete(e)}getEditControl(e){return this.editControlLayers.get(e)}updateEditState(e,t){const i=this.editControlLayers.get(e);i&&i.updateEditState(t)}clearAll(){Array.from(this.editControlLayers.keys()).forEach(t=>this.unregisterEditControl(t))}getAllEditControls(){return Array.from(this.editControlLayers.values())}hasEditControl(e){return this.editControlLayers.has(e)}}function gs(n){return n.charAt(0).toUpperCase()+n.slice(1)}const Fi=class Fi extends bl{constructor(t=uo){super();f(this,"mapState",null);f(this,"components",{});f(this,"managers",{});f(this,"config",co);f(this,"runtime");f(this,"appService");f(this,"coords");f(this,"scaleMin",.5);f(this,"scaleMax",5);f(this,"events",{});f(this,"instanceKey");f(this,"debugInstanceId");f(this,"previousLoggerRuntimeState",null);f(this,"isDestroying",!1);f(this,"hasActiveContextLoss",!1);f(this,"createdAtMs",Date.now());f(this,"lastMapDataAtMs",null);f(this,"lastMapDrawAtMs",null);f(this,"lastPathDataAtMs",null);f(this,"lastVisibilityChangeAtMs",null);f(this,"containerElement");f(this,"onWebGLContextLost",t=>{var r;const i=t;if((r=i.preventDefault)==null||r.call(i),this.hasActiveContextLoss)return;this.hasActiveContextLoss=!0;const s=this.getContextLossDiagnostics(t);w.error("[Pixi] WebGL context lost",s.summary),w.error("[Pixi] WebGL context lost tail",s.recentLifecycleTail),this.recordDebugLifecycleEvent("webglcontextlost",{eventType:t.type,statusMessage:i.statusMessage??null})});f(this,"onWebGLContextRestored",t=>{this.hasActiveContextLoss=!1,w.warn("[Pixi] WebGL context restored, scheduling render",this.getRendererDiagnostics({eventType:t.type})),this.recordDebugLifecycleEvent("webglcontextrestored",{eventType:t.type}),this.renderOnceNextFrame()});f(this,"emitter",Nx());f(this,"tickerState",{renderReasons:new Set,renderTimer:null,lastRequestReason:null,lastStopReason:null});f(this,"customCarpetResolvedMaxSizeCache",null);f(this,"pendingAsyncRender",!1);f(this,"isFirstMapDraw",!0);f(this,"isMapDrawn",!1);f(this,"onVisibilityChange",()=>{var i;this.lastVisibilityChangeAtMs=Date.now(),document.visibilityState==="visible"||(i=this.components.interaction)==null||i.clearTouches()});f(this,"onRendererResize",()=>{var t,i;this.isDestroying||((t=this.components.viewportContainer)==null||t.updateViewport(this.config),(i=this.components.background)==null||i.updateViewportBounds(this.getViewportBounds()),this.renderOnceNextFrame())});this.instanceKey=t,this.debugInstanceId=hh(),this.coords=new nS(()=>{var i;return((i=this.runtime)==null?void 0:i.unit)??"meter"}),this.appService=new Rc(this),globalThis.__PIXI_APP__=this,this.recordDebugLifecycleEvent("app:create",{instanceKey:t})}getRendererDiagnostics(t={}){var r,o,a,h,l,c,d,u,p,g,m;const i=this.containerElement&&"getBoundingClientRect"in this.containerElement&&typeof this.containerElement.getBoundingClientRect=="function"?this.containerElement.getBoundingClientRect():null,s=((r=this.renderer)==null?void 0:r.type)===te.WEBGPU?"webgpu":((o=this.renderer)==null?void 0:o.type)===te.WEBGL?"webgl":"unknown";return{sessionId:Ln().getSessionId(),instanceId:this.debugInstanceId,requestedPreference:this.config.global.rendererPreference,rendererType:s,rendererWidth:((a=this.renderer)==null?void 0:a.width)??null,rendererHeight:((h=this.renderer)==null?void 0:h.height)??null,canvasWidth:((l=this.canvas)==null?void 0:l.width)??null,canvasHeight:((c=this.canvas)==null?void 0:c.height)??null,canvasClientWidth:((d=this.canvas)==null?void 0:d.clientWidth)??null,canvasClientHeight:((u=this.canvas)==null?void 0:u.clientHeight)??null,containerWidth:(i==null?void 0:i.width)??null,containerHeight:(i==null?void 0:i.height)??null,mapId:((p=this.mapState)==null?void 0:p.id)??null,mapWidth:((g=this.mapState)==null?void 0:g.width)??null,mapHeight:((m=this.mapState)==null?void 0:m.height)??null,isMapDrawn:this.isMapDrawn,visibilityState:document.visibilityState,...t}}getElapsedMsSince(t){return typeof t=="number"?Math.max(0,Date.now()-t):null}getDeviceDiagnostics(){const t=globalThis.navigator;return{devicePixelRatio:globalThis.devicePixelRatio??null,userAgent:(t==null?void 0:t.userAgent)??null,hardwareConcurrency:(t==null?void 0:t.hardwareConcurrency)??null,deviceMemory:(t==null?void 0:t.deviceMemory)??null,documentWasDiscarded:"wasDiscarded"in document?document.wasDiscarded:null}}getWebGLDiagnostics(){var r;const t=(r=this.renderer)==null?void 0:r.gl;if(!t)return{contextAttributes:null,isContextLost:null,drawingBufferWidth:null,drawingBufferHeight:null,vendor:null,renderer:null,version:null,shadingLanguageVersion:null,maxTextureSize:null,maxRenderbufferSize:null};const i=o=>{if(typeof o!="number"||typeof t.getParameter!="function")return null;try{return t.getParameter(o)??null}catch{return null}},s=typeof t.getExtension=="function"?t.getExtension("WEBGL_debug_renderer_info"):null;return{contextAttributes:typeof t.getContextAttributes=="function"?t.getContextAttributes()??null:null,isContextLost:typeof t.isContextLost=="function"?t.isContextLost():null,drawingBufferWidth:t.drawingBufferWidth??null,drawingBufferHeight:t.drawingBufferHeight??null,vendor:s&&typeof s.UNMASKED_VENDOR_WEBGL=="number"?i(s.UNMASKED_VENDOR_WEBGL):null,renderer:s&&typeof s.UNMASKED_RENDERER_WEBGL=="number"?i(s.UNMASKED_RENDERER_WEBGL):null,version:i(t.VERSION),shadingLanguageVersion:i(t.SHADING_LANGUAGE_VERSION),maxTextureSize:i(t.MAX_TEXTURE_SIZE),maxRenderbufferSize:i(t.MAX_RENDERBUFFER_SIZE)}}getRecentLifecycleTail(){return Ln().readCurrentSession().slice(-Fi.CONTEXT_LOSS_TAIL_SIZE).map(t=>({seq:t.seq,ts:t.ts,event:t.event,sessionId:t.sessionId,instanceId:t.instanceId??null,visibilityState:t.visibilityState??null,rendererType:t.rendererType??null,mapId:t.mapId??null,detail:t.detail}))}getContextLossDiagnostics(t){const i=t;return{summary:this.getRendererDiagnostics({eventType:t.type,statusMessage:i.statusMessage??null,uptimeMs:this.getElapsedMsSince(this.createdAtMs),timeSinceLastMapDataMs:this.getElapsedMsSince(this.lastMapDataAtMs),timeSinceLastMapDrawMs:this.getElapsedMsSince(this.lastMapDrawAtMs),timeSinceLastPathDataMs:this.getElapsedMsSince(this.lastPathDataAtMs),timeSinceLastVisibilityChangeMs:this.getElapsedMsSince(this.lastVisibilityChangeAtMs),device:this.getDeviceDiagnostics(),webgl:this.getWebGLDiagnostics()}),recentLifecycleTail:this.getRecentLifecycleTail()}}attachRendererDiagnostics(){var t,i;if(((t=this.renderer)==null?void 0:t.type)!==te.WEBGL||typeof((i=this.canvas)==null?void 0:i.addEventListener)!="function"){w.debug("[Pixi] Renderer diagnostics initialized",this.getRendererDiagnostics({contextListeners:!1}));return}this.canvas.addEventListener("webglcontextlost",this.onWebGLContextLost),this.canvas.addEventListener("webglcontextrestored",this.onWebGLContextRestored),w.debug("[Pixi] Renderer diagnostics initialized",this.getRendererDiagnostics({contextListeners:!0}))}detachRendererDiagnostics(){var t;typeof((t=this.canvas)==null?void 0:t.removeEventListener)=="function"&&(this.canvas.removeEventListener("webglcontextlost",this.onWebGLContextLost),this.canvas.removeEventListener("webglcontextrestored",this.onWebGLContextRestored))}getDebugRendererType(){var t,i;return((t=this.renderer)==null?void 0:t.type)===te.WEBGPU?"webgpu":((i=this.renderer)==null?void 0:i.type)===te.WEBGL?"webgl":"unknown"}recordDebugLifecycleEvent(t,i){var s;Ln().record({event:t,instanceId:this.debugInstanceId,visibilityState:typeof document<"u"?document.visibilityState:null,rendererType:this.getDebugRendererType(),mapId:((s=this.mapState)==null?void 0:s.id)??null,detail:i})}async initialize(t){const{resizeTo:i,events:s,config:r,runtime:o={},...a}=t;this.config=yr(Va({},co,r??{},(g,m)=>{if(Array.isArray(m))return m})),this.validateCustomZoneTypes(this.config),this.previousLoggerRuntimeState=nx(),sx({getLoggerConfig:()=>this.config.logger,getLegacyEnabled:()=>this.config.global.enableLogger}),w.log("Applying config",this.config,r),this.runtime=yr(Object.assign({},Pd,o));const h=this.instanceKey===uo;this.containerElement=i;const l=h&&this.config.interaction.enable,c=this.config.global.performanceMode||!h,d={gcActive:!1,autoStart:!1,sharedTicker:c,eventFeatures:{move:l,globalMove:!1,click:l,wheel:l}},u={resizeTo:h?i:void 0,resolution:this.config.global.resolution,antialias:c?!1:pv(),depth:!c,autoDensity:!0,backgroundColor:0,backgroundAlpha:0,...d,...a},p=this.config.global.rendererPreference;if(p==="webgpu")try{await this.init({...u,preference:"webgpu"})}catch(g){w.warn("[Pixi] WebGPU initialization failed, falling back to WebGL:",g),await this.init({...u,preference:"webgl"})}else await this.init({...u,preference:p});this.attachRendererDiagnostics(),this.recordDebugLifecycleEvent("app:initialized",{isMainInstance:h,isPerformanceMode:c,requestedPreference:p}),w.debug("[Pixi] Renderer initialized",this.getRendererDiagnostics({isMainInstance:h,isPerformanceMode:c})),this.preloadAssets(),this.scaleMax=this.config.interaction.zoomRange.max,this.scaleMin=this.config.interaction.zoomRange.min,this.events=s,this.initializeViewportContainer(),this.initializeInteraction(),this.initializeAppContainer(),this.renderer.on("resize",this.onRendererResize),this.managers.mapManager=new fS(this.appService),this.managers.heatmapManager=new bS(this.appService),this.managers.pathManager=new SS(this.appService),this.managers.controlsManager=new ES(this.appService),this.managers.detectedObjectManager=new FS(this.appService),this.managers.customElementsManager=new ov(this.appService),this.managers.roomsManager=new uv(this.appService),this.managers.customCarpetManager=new mv(this.appService),this.managers.furnitureManager=new Sv(this.appService),this.managers.editControlManager=new vv(this.appService),this.setupMapRotationListener(),document.addEventListener("visibilitychange",this.onVisibilityChange)}async drawMap(t){var a,h,l,c,d,u,p;this.lastMapDataAtMs=Date.now(),this.isMapDrawn=!1,w.log("[Map] drawMap",t);const{size:i,resolution:s,origin:r,id:o}=t;((a=this.mapState)==null?void 0:a.id)!==void 0&&this.mapState.id!==o&&this.managers.pathManager.clear(),(r[0]!==((h=this.mapState)==null?void 0:h.origin.x)||r[1]!==((l=this.mapState)==null?void 0:l.origin.y))&&(this.appService.appContainer.updateOriginTrackedLayers(...r),this.managers.pathManager.updatePositionByOrigin(...r),this.managers.heatmapManager.updatePositionByOrigin(...r)),this.mapState={id:t.id,status:t.status===1,origin:{x:r[0],y:r[1]},charger:{x:t.charger.coordinate[0],y:t.charger.coordinate[1]},chargerDirection:t.charger.angle??0,resolution:s,width:i[0],height:i[1],mapType:"structured"},this.coords.setResolution(s),w.debug("[Map] Structured map state updated",{mapId:o,mapWidth:i[0],mapHeight:i[1],mapResolution:s,mapStatus:t.status===1,originX:r[0],originY:r[1]}),this.isFirstMapDraw&&(this.isFirstMapDraw=!1,(d=(c=this.events)==null?void 0:c.onMapFirstDrawed)==null||d.call(c,this.mapState)),(p=(u=this.events)==null?void 0:u.onMapDrawed)==null||p.call(u,this.mapState),this.emitter.emit("mapStateUpdate",this.mapState),await this.managers.mapManager.drawMap(t),i[0]===0||i[1]===0?(w.warn("[Map] Structured map cleared by incoming data",this.getRendererDiagnostics({mapId:o,mapWidth:i[0],mapHeight:i[1],mapResolution:s,mapStatus:t.status===1,originX:r[0],originY:r[1]})),this.managers.pathManager.clear(),this.managers.roomsManager.clear(),this.isMapDrawn=!1):(this.isMapDrawn=!0,this.lastMapDrawAtMs=Date.now(),this.managers.heatmapManager.onMapLoaded()),this.emitRoomsDrawed(),this.renderOnce()}async drawRasterMap(t){var a,h,l,c,d,u;this.lastMapDataAtMs=Date.now(),this.isMapDrawn=!1,w.log("[Map] drawRasterMap",t);const{mapHeader:i,mapData:s}=t,{originX:r,originY:o}=i;(r!==((a=this.mapState)==null?void 0:a.origin.x)||o!==((h=this.mapState)==null?void 0:h.origin.y))&&(this.appService.appContainer.updateOriginTrackedLayers(r,o),this.managers.pathManager.updatePositionByOrigin(r,o),this.managers.heatmapManager.updatePositionByOrigin(r,o)),this.mapState={id:i.id,status:i.mapStable,origin:{x:r,y:o},charger:{x:i.chargeX,y:i.chargeY},chargerDirection:i.chargeDirection??0,resolution:i.mapResolution*100,width:i.mapWidth,height:i.mapHeight,version:i.version,mapType:"raster"},this.coords.setResolution(i.mapResolution*100),w.debug("[Map] Raster map state updated",{mapId:i.id,mapWidth:i.mapWidth,mapHeight:i.mapHeight,mapResolution:i.mapResolution*100,mapStatus:i.mapStable,originX:r,originY:o,version:i.version??null}),this.isFirstMapDraw&&(this.isFirstMapDraw=!1,(c=(l=this.events)==null?void 0:l.onMapFirstDrawed)==null||c.call(l,this.mapState)),(u=(d=this.events)==null?void 0:d.onMapDrawed)==null||u.call(d,this.mapState),this.emitter.emit("mapStateUpdate",this.mapState),await this.managers.mapManager.drawRasterMap(s.parsed,this.mapState),i.mapWidth===0||i.mapHeight===0?(w.warn("[Map] Raster map cleared by incoming data",this.getRendererDiagnostics({mapId:i.id,mapWidth:i.mapWidth,mapHeight:i.mapHeight,mapResolution:i.mapResolution*100,mapStatus:i.mapStable,originX:r,originY:o,version:i.version??null})),this.managers.pathManager.clear(),this.managers.roomsManager.clear(),this.isMapDrawn=!1):(this.isMapDrawn=!0,this.lastMapDrawAtMs=Date.now(),this.managers.heatmapManager.onMapLoaded()),this.emitRoomsDrawed(),this.renderOnce()}emitRoomsDrawed(){var t,i;(i=(t=this.events)==null?void 0:t.onRoomsDrawed)==null||i.call(t,this.getRoomCenters())}getRoomCenters(){var i;const t=((i=this.mapState)==null?void 0:i.origin)??{x:0,y:0};return this.managers.mapManager.getAllRooms().map(s=>({id:s.id,centerPoint:s.centerPoint,relativeCenterPoint:{x:s.centerPoint.x-t.x,y:s.centerPoint.y-t.y}}))}drawPath(t){var i,s;this.lastPathDataAtMs=Date.now(),w.log("[Path] drawPath",t),(s=(i=this.events)==null?void 0:i.onPathDrawed)==null||s.call(i,{id:t.pathHeader.pathId,type:t.pathHeader.type,direction:t.pathHeader.direction,count:t.pathHeader.count,initFlag:t.pathHeader.initFlag,robotPosition:t.pathPoints[t.pathPoints.length-1]??null}),this.managers.pathManager.draw(t),this.renderOnce()}async drawRoomProperty(t){var i,s;w.log("[Room] drawRoomProperty",t),(s=(i=this.events)==null?void 0:i.onRoomPropertiesDrawed)==null||s.call(i,t),await this.managers.roomsManager.drawRoomProperty(t),this.renderOnceNextFrame()}async drawCustomCarpets(t){w.log("[CustomCarpets] drawCustomCarpets",t),await this.managers.customCarpetManager.drawCustomCarpets(t),this.renderOnceNextFrame()}async drawFurnitures(t){w.log("[Furniture] drawFurnitures",t),await this.managers.furnitureManager.drawFurnitures(t),this.renderOnceNextFrame()}drawHeatmap(t){w.log("[Heatmap] drawHeatmap",t),this.managers.heatmapManager.draw(t),this.renderOnce()}drawForbiddenSweepZones(t){w.log("[Controls] drawForbiddenSweepZones",t),this.managers.controlsManager.drawForbiddenSweepZones(t),this.renderOnceNextFrame()}drawForbiddenMopZones(t){w.log("[Controls] drawForbiddenMopZones",t),this.managers.controlsManager.drawForbiddenMopZones(t),this.renderOnceNextFrame()}drawCleanZones(t){w.log("[Controls] drawCleanZones",t),this.managers.controlsManager.drawCleanZones(t),this.renderOnceNextFrame()}drawCustomZones(t,i){if($e(t)){w.warn(`[MapApplication] drawCustomZones: '${t}' is a built-in type; use draw${gs(t)}s() instead`);return}w.log("[Controls] drawCustomZones",t,i),this.managers.controlsManager.drawCustomZones(t,i),this.renderOnceNextFrame()}getCustomZones(t){return $e(t)?(w.warn(`[MapApplication] getCustomZones: '${t}' is a built-in type; use get${gs(t)}s() instead`),[]):this.managers.controlsManager.getCustomZones(t)}clearCustomZones(t){if($e(t)){w.warn(`[MapApplication] clearCustomZones: '${t}' is a built-in type; use clearAll${gs(t)}s() instead`);return}w.log("[Controls] clearCustomZones",t),this.managers.controlsManager.clearCustomZones(t),this.renderOnceNextFrame()}setEditingCustomZones(t,i){if($e(t)){w.warn(`[MapApplication] setEditingCustomZones: '${t}' is a built-in type; use runtime.editing${gs(t)}Ids instead`);return}this.runtime.editingCustomZoneIds={...this.runtime.editingCustomZoneIds??{},[t]:[...i]}}drawVirtualWalls(t){w.log("[Controls] drawVirtualWalls",t),this.managers.controlsManager.drawVirtualWalls(t),this.renderOnceNextFrame()}drawThresholds(t){w.log("[Controls] drawThresholds",t),this.managers.controlsManager.drawThresholds(t),this.renderOnceNextFrame()}drawSpots(t){w.log("[Controls] drawSpots",t),this.managers.controlsManager.drawSpots(t),this.renderOnceNextFrame()}drawRoomAnchors(t){w.log("[Controls] drawRoomAnchors",t),this.managers.controlsManager.drawRoomAnchors(t),this.renderOnceNextFrame()}getRoomAnchors(){return this.managers.controlsManager.getRoomAnchors()}clearAllRoomAnchors(){this.managers.controlsManager.clearAllRoomAnchors(),this.renderOnceNextFrame()}drawWayPoints(t){w.log("[Controls] drawWayPoints",t),this.managers.controlsManager.drawWayPoints(t),this.renderOnceNextFrame()}async drawDetectedObjects(t){w.log("[DetectedObject] drawDetectedObjects",t),await this.managers.detectedObjectManager.drawDetectedObjects(t),this.renderOnceNextFrame()}drawCustomCarpet(t){w.log("[CustomCarpet] drawCustomCarpet",t),this.managers.customCarpetManager.drawCustomCarpets(t),this.renderOnceNextFrame()}async drawCustomElements(t){w.log("[CustomElements] drawCustomElements",t),await this.managers.customElementsManager.drawCustomElements(t),this.renderOnceNextFrame()}getForbiddenSweepZones(){return this.managers.controlsManager.getForbiddenSweepZones()}getForbiddenMopZones(){return this.managers.controlsManager.getForbiddenMopZones()}getCleanZones(){return this.managers.controlsManager.getCleanZones()}getVirtualWalls(){return this.managers.controlsManager.getVirtualWalls()}getThresholds(){return this.managers.controlsManager.getThresholds()}getSpots(){return this.managers.controlsManager.getSpots()}getWayPoints(){return this.managers.controlsManager.getWayPoints()}getEffectiveDividerPoints(){return this.managers.controlsManager.getEffectiveDividerPoints()}getCustomCarpets(){return this.managers.customCarpetManager.getCustomCarpets()}getFurnitures(){return this.managers.furnitureManager.getFurnitures()}getDividerEndPoints(){return this.managers.controlsManager.getDividerEndPoints()}resetPanZoom(){this.components.interaction.setPanZoom()}forceEndGesture(){w.log("[Map] forceEndGesture"),this.components.interaction.forceEndGesture()}fitMapToView(t,i=!1){if(!t||t.minX===t.maxX||t.minY===t.maxY)return;const s=this.config.map.autoPaddingVerticalPercent,r=this.config.map.autoPaddingHorizontalPercent,o=this.getViewportBounds(),a=this.components.appContainer.getMapRotationRadians(),h=this.calculateRotatedBounds(t,a),l=h.maxX-h.minX,c=h.maxY-h.minY,d=o.width,u=o.height,p=d*(1-r*2),g=u*(1-s*2),m=p/l,y=g/c,x=Math.min(m,y),S=this.config.interaction.fitMinScale,v=this.config.interaction.fitMaxScale,b=Math.max(S,Math.min(v,x));this.setScaleBounds(this.config.interaction.zoomRange.min,this.config.interaction.zoomRange.max),b<this.scaleMin&&(this.setScaleBounds(b,this.scaleMax),w.debug("[MapApplication] scaleMin lowered for fit:",{configured:this.config.interaction.zoomRange.min,adjusted:b})),b>this.scaleMax&&(this.setScaleBounds(this.scaleMin,b),w.debug("[MapApplication] scaleMax raised for fit:",{configured:this.config.interaction.zoomRange.max,adjusted:b}));const P=t.minX+(t.maxX-t.minX)/2,C=t.minY+(t.maxY-t.minY)/2,_=this.config.map.autoFitOffset||{x:0,y:0},R=d/2+(_.x||0),M=u/2+(_.y||0),T=Math.cos(a),A=Math.sin(a),E=P*T-C*A,D=P*A+C*T,B=R-E*b,j=M-D*b;w.debug("[MapApplication] fitMapToView calculated:",{rotation:this.components.appContainer.getMapRotation(),originalBounds:t,rotatedBounds:h,finalScale:b,position:{x:B,y:j}}),this.components.interaction.setPanZoom({targetPosition:{x:B,y:j},targetScale:{x:b,y:b},setCenter:!0,setScale:!0},i)}setScaleBounds(t,i){this.scaleMin=t,this.scaleMax=i,this.components.interaction.scaleMin=t,this.components.interaction.scaleMax=i}validateCustomZoneTypes(t){const i=["minSize","strokeColor","strokeWidth","fillColor","outlineOffset","outlineStrokeColor","outlineStrokeWidth","outlineDashed","outlineDashArray","outlineFillColor","iconWrapperFillColor","textColor","textPosition","textOffset","showRotateButton","editing","normal"],s=t.customZoneTypes??{},r=_h.cleanZone;for(const[,o]of Object.entries(s))for(const a of i)o[a]===void 0&&(o[a]=r[a])}calculateRotatedBounds(t,i){if(i===0)return t;const s=(t.minX+t.maxX)/2,r=(t.minY+t.maxY)/2,o=[{x:t.minX-s,y:t.minY-r},{x:t.maxX-s,y:t.minY-r},{x:t.maxX-s,y:t.maxY-r},{x:t.minX-s,y:t.maxY-r}],a=Math.cos(i),h=Math.sin(i),l=o.map(g=>({x:g.x*a-g.y*h,y:g.x*h+g.y*a}));let c=1/0,d=1/0,u=-1/0,p=-1/0;return l.forEach(g=>{c=Math.min(c,g.x),d=Math.min(d,g.y),u=Math.max(u,g.x),p=Math.max(p,g.y)}),{minX:c+s,minY:d+r,maxX:u+s,maxY:p+r}}getViewportBounds(){var t;return((t=this.components.viewportContainer)==null?void 0:t.getViewportBounds())||{x:0,y:0,width:this.renderer.width,height:this.renderer.height}}updateRuntime(t){Object.assign(this.runtime,t),w.log("[runtime] runtime updated",t),this.renderOnceNextFrame()}updateConfig(t){var s,r,o,a,h,l,c;Va(this.config,t,(d,u)=>{if(Array.isArray(u))return u}),t.customZoneTypes&&this.validateCustomZoneTypes(this.config),(s=this.managers.controlsManager)==null||s.updateRenderOrder(),((r=t.controls)==null?void 0:r.spot)!==void 0&&((o=this.managers.controlsManager)==null||o.refreshSpotsEditState()),((a=t.controls)==null?void 0:a.roomAnchor)!==void 0&&((h=this.managers.controlsManager)==null||h.refreshRoomAnchors()),((l=t.controls)==null?void 0:l.carpet)!==void 0&&((c=this.managers.customCarpetManager)==null||c.refreshConfig()),w.log("[Config] Configuration updated",t),this.renderOnceNextFrame()}metersToPixels(t){return this.coords.toPixels(et(t))}pixelsToMeters(t){return this.coords.toMeters(Bt(t))}toFixedSize(t,i){const s=i??this.components.appContainer.scale.x;return t/s}fromFixedSize(t,i){const s=i??this.components.appContainer.scale.x;return t*s}getViewportCenterPoint(){if(!this.mapState)return w.warn("Map state not available, cannot calculate center point"),null;const t=this.getViewportBounds(),i=t.x+t.width/2,s=t.y+t.height/2,r=this.components.appContainer,o=r.scale.x,a=r.getMapRotationRadians(),h=i-r.x,l=s-r.y,c=h/o,d=l/o,u=Math.cos(a),p=Math.sin(a),g=c*u+d*p,m=-c*p+d*u,y=g-this.mapState.origin.x,x=m-this.mapState.origin.y;return{x:y,y:x}}getMapCenterPoint(){if(!this.mapState)return w.warn("Map state not available, cannot calculate map center point"),null;const t=this.managers.mapManager.mapBounds;if(t.minX===1/0||t.minY===1/0||t.maxX===-1/0||t.maxY===-1/0)return w.warn("Invalid map bounds, cannot calculate map center point"),null;const i=(t.minX+t.maxX)/2,s=(t.minY+t.maxY)/2,r=i-this.mapState.origin.x,o=s-this.mapState.origin.y;return{x:r,y:o}}getWallPointsByViewportCenter(t){var g;const{width:i=this.config.controls.virtualWall.minWidth,direction:s="horizontal",offsetX:r=0,offsetY:o=0}=t||{},a=this.getViewportCenterPoint()||{x:0,y:0},l=this.coords.toPixels(et(i))/2,c=((g=this.components.appContainer)==null?void 0:g.getMapRotationRadians())||0,d=Math.cos(c),u=Math.sin(c);let p;return s==="horizontal"?p=[{vx:-l+r,vy:o},{vx:l+r,vy:o}]:p=[{vx:r,vy:-l+o},{vx:r,vy:l+o}],p.map(m=>({x:a.x+m.vx*d+m.vy*u,y:a.y-m.vx*u+m.vy*d}))}getForbiddenSweepZonePointsByViewportCenter(t){const i=this.config.controls.forbiddenSweepZone,{size:s=i.minSize,offsetX:r=0,offsetY:o=0}=t||{};return this.generateZonePoints(s,r,o)}getForbiddenMopZonePointsByViewportCenter(t){const i=this.config.controls.forbiddenMopZone,{size:s=i.minSize,offsetX:r=0,offsetY:o=0}=t||{};return this.generateZonePoints(s,r,o)}getCleanZonePointsByViewportCenter(t){const i=this.config.controls.cleanZone,{size:s=i.minSize,offsetX:r=0,offsetY:o=0}=t||{};return this.generateZonePoints(s,r,o)}getSpotPointByViewportCenter(t){const{offsetX:i=0,offsetY:s=0}=t||{},r=this.getViewportCenterPoint()||{x:0,y:0},o=r.x+i,a=r.y+s;return{x:o,y:a}}getFurniturePointsByViewportCenter(t){const{furnitureType:i=1,offsetX:s=0,offsetY:r=0}=t||{},o=this.config.furniture.assets.find(h=>h.type===i),a=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:a,widthMeters:(o==null?void 0:o.width)??1.8,heightMeters:(o==null?void 0:o.height)??2,applyMapRotation:!0,visualOffsetX:s,visualOffsetY:r})}getResolvedCustomCarpetMaxSize(){const t=this.config.controls.carpet.maxSize;if(this.customCarpetResolvedMaxSizeCache&&this.customCarpetResolvedMaxSizeCache.key===t)return this.customCarpetResolvedMaxSizeCache.value;const i=ri(this.config.controls.carpet.minSize,t,"carpet");return this.customCarpetResolvedMaxSizeCache={key:t,value:i},i}getCustomCarpetPointsByViewportCenter(t){const s=this.config.controls.carpet.minSize,r=this.getResolvedCustomCarpetMaxSize(),{offsetX:o=0,offsetY:a=0}=t||{},h=(g,m)=>{const y=typeof g=="number"&&Number.isFinite(g)?g:m;return r!=null?Math.min(Math.max(y,s),r):Math.max(y,s)},l=(t==null?void 0:t.width)??(t==null?void 0:t.height),c=(t==null?void 0:t.height)??(t==null?void 0:t.width),d=h(l,s),u=h(c,s),p=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:p,widthMeters:d,heightMeters:u,applyMapRotation:!0,visualOffsetX:o,visualOffsetY:a})}getRectPointsByCenter(t){const{center:i,width:s,height:r,applyMapRotation:o=!0}=t;return this.buildRectPoints({center:i,widthMeters:s,heightMeters:r,applyMapRotation:o})}areRoomsAdjacent(t){return!t||t.length===0?(w.warn("[Room] No room IDs provided"),!1):this.managers.mapManager.areRoomsAdjacent(t)}isPointInAnyRoom(t){return!t||typeof t.x!="number"||typeof t.y!="number"?(w.warn("[Room] Invalid point provided"),null):this.mapState?this.managers.mapManager.isPointInAnyRoom(t):(w.warn("[Room] Map state not available"),null)}isPointInRoom(t,i){return!t||typeof t.x!="number"||typeof t.y!="number"?(w.warn("[Room] Invalid point provided"),!1):this.mapState?this.managers.mapManager.isPointInRoom(t,i):(w.warn("[Room] Map state not available"),!1)}isWallIntersectsAnyRoom(t){return!t||t.length!==2||!t[0]||!t[1]||typeof t[0].x!="number"||typeof t[0].y!="number"||typeof t[1].x!="number"||typeof t[1].y!="number"?(w.warn("[Room] Invalid wall points provided"),!1):this.mapState?this.managers.mapManager.isWallIntersectsAnyRoom(t):(w.warn("[Room] Map state not available"),!1)}isZoneIntersectsAnyRoom(t){return!t||t.length!==4||!t[0]||!t[1]||!t[2]||!t[3]||typeof t[0].x!="number"||typeof t[0].y!="number"||typeof t[1].x!="number"||typeof t[1].y!="number"||typeof t[2].x!="number"||typeof t[2].y!="number"||typeof t[3].x!="number"||typeof t[3].y!="number"?(w.warn("[Room] Invalid zone points provided"),!1):this.mapState?this.managers.mapManager.isZoneIntersectsAnyRoom(t):(w.warn("[Room] Map state not available"),!1)}isNearChargerOrRobot(t,i,s){var h,l;if(!t||t.length<1)return w.warn("[Distance] Invalid points array: must have at least 1 point"),!1;if(t.length!==1&&t.length!==2&&t.length!==4)return w.warn("[Distance] Invalid points array: must have exactly 1 (point), 2 (wall) or 4 (zone) points"),!1;if(i<=0)return w.warn("[Distance] Invalid threshold: must be greater than 0"),!1;if(!this.mapState)return w.warn("[Distance] Map state not available"),!1;const{checkCharger:r=!0,checkRobot:o=!1}=s||{};if(!r&&!o)return w.warn("[Distance] At least one of checkCharger or checkRobot must be true"),!1;const a=this.coords.toPixels(et(i));if(r){const c=this.appService.getChargerPosition();if(c){const d=(h=this.mapState)==null?void 0:h.charger.x,u=(l=this.mapState)==null?void 0:l.charger.y;if(d===0&&u===0)return w.warn("[Distance] Charger position not available"),!1;const p=Ka(c,t);if(p<=a)return w.log(`[Distance] Too close to charger: ${p.toFixed(2)} pixels (threshold: ${a.toFixed(2)} pixels)`),!0}else w.warn("[Distance] Charger position not available")}if(o){const c=this.appService.getRobotPosition();if(c){const d=Ka(c,t);if(d<=a)return w.log(`[Distance] Too close to robot: ${d.toFixed(2)} pixels (threshold: ${a.toFixed(2)} pixels)`),!0}else w.warn("[Distance] Robot position not available")}return!1}async snapshot(t){this.render();const{snapshot:i,global:s}=this.config,r=(t==null?void 0:t.backgroundColor)??s.backgroundColor,o=this.components.appContainer,a=o.getSnapshotBounds(),h=Math.floor(a.x),l=Math.floor(a.y),c=Math.ceil(a.x+a.width)-h,d=Math.ceil(a.y+a.height)-l;if(c<=0||d<=0)return w.error("[MapApplication] Snapshot failed: invalid bounds",a),"";const u=i.resolution||window.devicePixelRatio||2,p=$r.create({width:c,height:d,resolution:u}),g=new U;g.rect(0,0,c,d).fill(r);const m=new H;m.translate(-h,-l);try{return this.renderer.render({container:g,target:p}),this.renderer.render({container:o,target:p,transform:m,clear:!1}),await this.renderer.extract.base64({target:p,format:i.format,quality:i.quality,antialias:i.antialias})}catch(y){return w.error("[MapApplication] Snapshot failed:",y),""}finally{g.destroy(),p.destroy(!0)}}async snapshotByData({map:t,path:i,roomProperties:s,customElements:r,forbiddenSweepZones:o,forbiddenMopZones:a,virtualWalls:h,detectedObjects:l,furnitures:c,carpets:d},u={},p){const g=`SNAPSHOT_${hh()}`;w.log(`[MapApplication] ${g} snapshot start`);const m=new Fi(g);try{if(await m.initialize({config:this.config,runtime:u}),!t)throw new Error("Map data is required");if(t.startsWith("7b22")){const x=Md(t);await m.drawMap(x)}else{const x=Ad(t,{pointsStructured:!0});if(x)await m.drawRasterMap(x);else throw new Error("Failed to decode raster map data")}if(i){const{decodePath:x}=await Re(async()=>{const{decodePath:v}=await import("./theme.BwMYfKet.js").then(b=>b.f);return{decodePath:v}},__vite__mapDeps([4,2])),S=x(i);m.drawPath(S)}s&&s.length>0&&await m.drawRoomProperty(s),o&&o.length>0&&m.drawForbiddenSweepZones(o),a&&a.length>0&&m.drawForbiddenMopZones(a),h&&h.length>0&&m.drawVirtualWalls(h),d&&d.length>0&&await m.drawCustomCarpets(d),c&&c.length>0&&await m.drawFurnitures(c),l&&l.length>0&&await m.drawDetectedObjects(l),r&&r.length>0&&await m.drawCustomElements(r);const y=await m.snapshot(p);return w.log(`[MapApplication] ${g} snapshot completed successfully`),y}catch(y){throw w.error(`[MapApplication] ${g} snapshot other map failed:`,y),y}finally{w.log(`[MapApplication] ${g} destroy`),m.destroy()}}renderOnce(){w.debug("[Pixi] renderOnce");try{this.render()}catch(t){w.error("[Pixi] renderOnce failed",this.getRendererDiagnostics({error:t}))}}renderOnceNextFrame(){this.pendingAsyncRender||(this.pendingAsyncRender=!0,requestAnimationFrame(()=>{w.debug("[Pixi] renderOnceNextFrame");try{this.render()}catch(t){w.error("[Pixi] renderOnceNextFrame failed",this.getRendererDiagnostics({error:t}))}finally{this.pendingAsyncRender=!1}}))}requestRender(t,i=!1){var r;if(this.tickerState.lastRequestReason=t,!i){this.renderOnceNextFrame(),this.emitRenderStateUpdate();return}const s=this.tickerState.renderTimer!==null;this.tickerState.renderReasons.add(t),w.debug("[Ticker] requestRender(continuous)",{reason:t,hadPendingStop:s,reasonsAfterAdd:[...this.tickerState.renderReasons],tickerStarted:(r=this.ticker)==null?void 0:r.started}),this.ticker.started||(w.debug(`🎬 [Ticker] START: ${t}`),this.ticker.start()),this.emitRenderStateUpdate()}stopRender(t){var i;this.tickerState.lastStopReason=t,this.tickerState.renderReasons.delete(t),w.debug("[Ticker] stopRender",{reason:t,reasonsAfterDelete:[...this.tickerState.renderReasons],tickerStarted:(i=this.ticker)==null?void 0:i.started}),this.tickerState.renderReasons.size===0&&this.scheduleStopRender("final",100),this.emitRenderStateUpdate()}getRenderState(){var i;const t=!!((i=this.ticker)!=null&&i.started);return{continuous:t,fps:t?Math.round(this.ticker.FPS):0,lastRequestReason:this.tickerState.lastRequestReason,lastStopReason:this.tickerState.lastStopReason,activeReasons:[...this.tickerState.renderReasons]}}emitRenderStateUpdate(){this.emitter.emit("renderStateUpdate",this.getRenderState())}destroy(){var t,i,s,r,o,a,h,l,c,d,u,p,g;if(!this.isDestroying){this.isDestroying=!0,w.log("[MapApplication] destroy"),this.recordDebugLifecycleEvent("destroy:start");try{this.tickerState.renderTimer&&(clearTimeout(this.tickerState.renderTimer),this.tickerState.renderTimer=null),this.tickerState.renderReasons.clear(),this.emitter.all.clear(),(t=this.renderer)==null||t.off("resize",this.onRendererResize),document.removeEventListener("visibilitychange",this.onVisibilityChange),(i=this.managers.pathManager)==null||i.destroy(),(s=this.managers.mapManager)==null||s.destroy(),(r=this.managers.controlsManager)==null||r.destroy(),(o=this.managers.furnitureManager)==null||o.destroy(),(a=this.managers.detectedObjectManager)==null||a.destroy(),(h=this.managers.customElementsManager)==null||h.destroy(),(l=this.managers.roomsManager)==null||l.destroy(),(c=this.components.interaction)==null||c.destroy(),(d=this.components.background)==null||d.destroy(),(u=this.components.viewportContainer)==null||u.destroy(),(p=this.components.appContainer)==null||p.destroy(),(g=this.managers.heatmapManager)==null||g.destroy(),this.detachRendererDiagnostics(),rx(this.previousLoggerRuntimeState),this.previousLoggerRuntimeState=null,globalThis.__PIXI_APP__===this&&delete globalThis.__PIXI_APP__,super.destroy({removeView:!0},{children:!0,texture:!0,textureSource:!0,context:!0})}finally{globalThis.__PIXI_APP__===this&&delete globalThis.__PIXI_APP__,this.recordDebugLifecycleEvent("destroy:end")}}}initializeViewportContainer(){this.components.viewportContainer=new oS(this.config,this.containerElement),this.stage.addChild(this.components.viewportContainer);const t=this.getViewportBounds();this.components.background=new fv(this.config.global,t,()=>{this.renderOnceNextFrame()}),this.components.viewportContainer.addChild(this.components.background),this.components.viewportContainer.setChildIndex(this.components.background,0),Us(this.config.global,()=>{var i;(i=this.components.background)==null||i.update(this.config.global)})}initializeAppContainer(){this.components.appContainer=new cS(this.appService),this.components.interaction.addChild(this.components.appContainer)}initializeInteraction(){this.components.interaction=new Vx(this.appService),this.components.viewportContainer.addChild(this.components.interaction)}scheduleStopRender(t,i){this.tickerState.renderTimer&&clearTimeout(this.tickerState.renderTimer),w.debug("[Ticker] scheduleStopRender(set)",{reason:t,delay:i,reasonsNow:[...this.tickerState.renderReasons]}),this.tickerState.renderTimer=setTimeout(()=>{this.tickerState.renderTimer=null,this.tickerState.renderReasons.delete(t),this.tickerState.renderReasons.size===0?(w.debug("⏸️ [Ticker] STOP"),this.ticker&&(this.ticker.stop(),this.emitRenderStateUpdate())):w.debug("[Ticker] stop-timer fired but reasons remain",{reasons:[...this.tickerState.renderReasons]})},i)}generateZonePoints(t,i,s){const r=this.getViewportCenterPoint()||{x:0,y:0};return this.buildRectPoints({center:r,widthMeters:t,heightMeters:t,applyMapRotation:!0,visualOffsetX:i,visualOffsetY:s})}buildRectPoints(t){var m;const{center:i,widthMeters:s,heightMeters:r,applyMapRotation:o,visualOffsetX:a=0,visualOffsetY:h=0}=t,l=this.coords.toPixels(et(s))/2,c=this.coords.toPixels(et(r))/2,d=o&&((m=this.components.appContainer)==null?void 0:m.getMapRotationRadians())||0,u=Math.cos(d),p=Math.sin(d);return[{vx:-l+a,vy:-c+h},{vx:l+a,vy:-c+h},{vx:l+a,vy:c+h},{vx:-l+a,vy:c+h}].map(y=>({x:i.x+y.vx*u+y.vy*p,y:i.y-y.vx*p+y.vy*u}))}preloadAssets(){var o;const t=this.config.robot.icon.src,i=this.config.chargingStation.icon.src,s=[];N.add({alias:"robot",src:t}),s.push("robot"),N.add({alias:"chargingStation",src:i}),s.push("chargingStation"),N.add({alias:"deleteIcon",src:this.config.controls.deleteIconSrc}),s.push("deleteIcon"),N.add({alias:"rotateIcon",src:this.config.controls.rotateIconSrc}),s.push("rotateIcon"),N.add({alias:"scaleIcon",src:this.config.controls.scaleIconSrc}),s.push("scaleIcon"),N.add({alias:"moveIcon",src:this.config.controls.moveIconSrc}),s.push("moveIcon"),N.add({alias:"checkmark",src:this.config.room.selectionIndicator.iconSrc}),s.push("checkmark"),N.add({alias:"spotIcon",src:this.config.controls.spot.iconSrc}),s.push("spotIcon");const r=(o=this.config.controls.roomAnchor)==null?void 0:o.iconSrc;r&&(N.add({alias:"roomAnchorIcon",src:r}),s.push("roomAnchorIcon")),N.add({alias:"wayPoint",src:this.config.controls.wayPoint.normal.iconSrc}),s.push("wayPoint"),N.add({alias:"wayPointActive",src:this.config.controls.wayPoint.editing.iconSrc}),s.push("wayPointActive"),N.add({alias:"horizontalScaleIcon",src:this.config.controls.horizontalScaleIconSrc}),s.push("horizontalScaleIcon"),N.add({alias:"verticalScaleIcon",src:this.config.controls.verticalScaleIconSrc}),s.push("verticalScaleIcon"),this.config.room.property.cleanMode.assets.forEach((a,h)=>{const l=`cleanMode_${h}`;N.add({alias:l,src:a}),s.push(l)}),this.config.room.property.suction.assets.forEach((a,h)=>{const l=`fan_${h}`;N.add({alias:l,src:a}),s.push(l)}),this.config.room.property.cistern.assets.forEach((a,h)=>{const l=`water_${h}`;N.add({alias:l,src:a}),s.push(l)}),this.config.room.property.cleanTimes.assets.forEach((a,h)=>{const l=`cleanTimes${h+1}`;N.add({alias:l,src:a}),s.push(l)}),this.config.room.floorType.assets.forEach((a,h)=>{if(!a)return;const l=`floorType${h}`;N.add({alias:l,src:a}),s.push(l)}),this.config.room.property.customAssets&&Object.entries(this.config.room.property.customAssets).forEach(([a,h])=>{h.forEach((l,c)=>{const d=`custom_${a}_${c}`;N.add({alias:d,src:l}),s.push(d)})}),this.config.furniture.assets.forEach(a=>{const h=`furniture_${a.type}`;N.add({alias:h,src:a.src}),s.push(h)}),N.backgroundLoad(s)}setupMapRotationListener(){this.applyMapRotation(this.runtime.mapRotation),W(this.runtime,"mapRotation",t=>{this.applyMapRotation(t)})}applyMapRotation(t){const i=(t%360+360)%360;w.log(`[MapApplication] Applying map rotation: ${i}°`),this.components.appContainer.setMapRotation(i);const s=this.managers.mapManager.mapBounds;s&&s.minX!==1/0&&s.maxX!==-1/0&&this.fitMapToView(s,!1),this.emitter.emit("mapRotationUpdate",i),this.renderOnce()}};f(Fi,"CONTEXT_LOSS_TAIL_SIZE",8);let br=Fi;const Tv=Object.freeze(Object.defineProperty({__proto__:null,AppService:Rc,MapApplication:br},Symbol.toStringTag,{value:"Module"}));export{ta as $,Pi as A,le as B,oe as C,Pr as D,jt as E,Tr as F,U as G,bm as H,ei as I,lg as J,Ls as K,tg as L,H as M,Gt as N,Os as O,J as P,Ar as Q,tt as R,uf as S,G as T,Fe as U,$ as V,gl as W,te as X,Ni as Y,lf as Z,ci as _,Je as a,Ai as a0,Rr as a1,ul as a2,zt as a3,si as a4,kl as a5,Wf as a6,Vf as a7,Av as a8,El as a9,Oi as aA,gf as aB,Il as aC,Gf as aD,$f as aE,wm as aF,Dl as aG,Yf as aH,pm as aI,Tv as aJ,Be as aa,ys as ab,Ju as ac,Wd as ad,de as ae,ii as af,Xf as ag,Rt as ah,Lh as ai,Ft as aj,Ds as ak,Mo as al,Xt as am,iy as an,mu as ao,To as ap,an as aq,Ro as ar,xu as as,Wh as at,$r as au,Ur as av,ml as aw,Vi as ax,_p as ay,Sp as az,dr as b,rt as c,V as d,ue as e,ur as f,cs as g,xt as h,X as i,Vu as j,ft as k,Lm as l,dt as m,Fu as n,Iu as o,I as p,yt as q,Jd as r,um as s,Ia as t,ep as u,Q as v,nt as w,K as x,L as y,st as z};