@ray-js/robot-map-sdk 0.0.16 → 0.0.17-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.d.ts +86 -0
- package/dist/index.rjs.js +1 -1
- package/dist-app/assets/index-BK1e_Ra7.js +1 -0
- package/dist-app/index.html +1 -1
- package/dist-docs/404.html +2 -2
- package/dist-docs/adr/0001-threshold-mirrors-virtual-wall.html +3 -3
- package/dist-docs/adr/0002-threshold-edit-surface-quad-family.html +3 -3
- package/dist-docs/adr/0003-beautify-derived-presentation-geometry.html +25 -0
- package/dist-docs/adr/0004-beautify-shells-enclose-never-subtract.html +25 -0
- package/dist-docs/agents/domain.html +3 -3
- package/dist-docs/agents/issue-tracker.html +3 -3
- package/dist-docs/agents/triage-labels.html +3 -3
- package/dist-docs/assets/adr_0003-beautify-derived-presentation-geometry.md.BIaPCTDJ.js +1 -0
- package/dist-docs/assets/adr_0003-beautify-derived-presentation-geometry.md.BIaPCTDJ.lean.js +1 -0
- package/dist-docs/assets/adr_0004-beautify-shells-enclose-never-subtract.md.PRaaUF5r.js +1 -0
- package/dist-docs/assets/adr_0004-beautify-shells-enclose-never-subtract.md.PRaaUF5r.lean.js +1 -0
- package/dist-docs/assets/{app.Cd1m9LaA.js → app.BKcB-q3l.js} +1 -1
- package/dist-docs/assets/chunks/@localSearchIndexroot.BiQ_oQbs.js +1 -0
- package/dist-docs/assets/chunks/{BitmapFont.COctfnp7.js → BitmapFont.BVQlrRID.js} +1 -1
- package/dist-docs/assets/chunks/{BufferResource.BCDLxIzj.js → BufferResource.ccuOZM7p.js} +1 -1
- package/dist-docs/assets/chunks/{CanvasRenderer.Bssy09MS.js → CanvasRenderer.BjafRf72.js} +1 -1
- package/dist-docs/assets/chunks/{RenderTargetSystem.CjYHTdeo.js → RenderTargetSystem.CNtSJQIT.js} +1 -1
- package/dist-docs/assets/chunks/{VPLocalSearchBox.D8CmmPQy.js → VPLocalSearchBox.BraJ5EBN.js} +1 -1
- package/dist-docs/assets/chunks/{WebGLRenderer.Ddc_zq8h.js → WebGLRenderer.IUUQ0Lkd.js} +1 -1
- package/dist-docs/assets/chunks/{WebGPURenderer.CiQbGJ6S.js → WebGPURenderer.CLtb2XY4.js} +1 -1
- package/dist-docs/assets/chunks/{browserAll.DDmHIbps.js → browserAll.BeYySQdg.js} +1 -1
- package/dist-docs/assets/chunks/index.vn3lfis1.js +744 -0
- package/dist-docs/assets/chunks/theme.CAU4HwNY.js +4 -0
- package/dist-docs/assets/chunks/{webworkerAll.wMItuqKH.js → webworkerAll.Dyo1xVCt.js} +1 -1
- package/dist-docs/assets/{guide_getting-started.md.BKeG0DkW.js → guide_getting-started.md.ItwGZAsG.js} +1 -1
- package/dist-docs/assets/{reference_config.md.DpjGhNQS.js → reference_config.md.CXZBV81d.js} +3 -3
- package/dist-docs/assets/{reference_config.md.DpjGhNQS.lean.js → reference_config.md.CXZBV81d.lean.js} +1 -1
- package/dist-docs/assets/reference_runtime.md.BfmrB9c5.js +20 -0
- package/dist-docs/assets/reference_runtime.md.BfmrB9c5.lean.js +1 -0
- package/dist-docs/guide/advanced-usage.html +3 -3
- package/dist-docs/guide/concepts.html +3 -3
- package/dist-docs/guide/getting-started.html +5 -5
- package/dist-docs/guide/mcp.html +3 -3
- package/dist-docs/guide/spot-room-binding.html +3 -3
- package/dist-docs/hashmap.json +1 -1
- package/dist-docs/index.html +3 -3
- package/dist-docs/plans/2026-03-04-detected-objects-visibility-design.html +3 -3
- package/dist-docs/plans/2026-03-04-show-detected-objects-implementation-plan.html +3 -3
- package/dist-docs/plans/2026-03-10-simulator-debug-design.html +3 -3
- package/dist-docs/plans/2026-03-10-simulator-events-console-design.html +3 -3
- package/dist-docs/plans/2026-03-10-simulator-events-console-implementation-plan.html +3 -3
- package/dist-docs/plans/2026-03-10-simulator-runtime-controls-design.html +3 -3
- package/dist-docs/plans/2026-03-10-simulator-runtime-controls-implementation-plan.html +3 -3
- package/dist-docs/plans/2026-03-10-testing-rollout-next-steps-plan.html +3 -3
- package/dist-docs/plans/2026-03-11-simulator-logger-dump-implementation-plan.html +3 -3
- package/dist-docs/reference/callbacks.html +3 -3
- package/dist-docs/reference/config.html +6 -6
- package/dist-docs/reference/data.html +3 -3
- package/dist-docs/reference/methods.html +3 -3
- package/dist-docs/reference/runtime.html +5 -5
- package/dist-docs/reference/types.html +3 -3
- package/dist-docs/reference/utils.html +3 -3
- package/dist-docs/simulator/index.html +3 -3
- package/package.json +1 -1
- package/dist-app/assets/index-awQy0VC0.js +0 -1
- package/dist-docs/assets/chunks/@localSearchIndexroot.Ctil7hF1.js +0 -1
- package/dist-docs/assets/chunks/index.010EeCxe.js +0 -744
- package/dist-docs/assets/chunks/theme.CUoWj-PI.js +0 -4
- package/dist-docs/assets/reference_runtime.md.CE2QTAiD.js +0 -20
- package/dist-docs/assets/reference_runtime.md.CE2QTAiD.lean.js +0 -1
- /package/dist-docs/assets/{guide_getting-started.md.BKeG0DkW.lean.js → guide_getting-started.md.ItwGZAsG.lean.js} +0 -0
|
@@ -0,0 +1,744 @@
|
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/chunks/browserAll.BeYySQdg.js","assets/chunks/webworkerAll.Dyo1xVCt.js","assets/chunks/framework.CBLqO2Q1.js","assets/chunks/mapValues.D2X8cRgC.js","assets/chunks/theme.CAU4HwNY.js","assets/chunks/WebGPURenderer.CLtb2XY4.js","assets/chunks/BufferResource.ccuOZM7p.js","assets/chunks/RenderTargetSystem.CNtSJQIT.js","assets/chunks/WebGLRenderer.IUUQ0Lkd.js","assets/chunks/CanvasRenderer.BjafRf72.js","assets/chunks/BitmapFont.BVQlrRID.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
var jd=Object.defineProperty;var Zd=(n,e,t)=>e in n?jd(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t;var y=(n,e,t)=>Zd(n,typeof e!="symbol"?e+"":e,t);import{V as ze}from"./framework.CBLqO2Q1.js";import{L as cl,u as dl,m as ul,G as qd,E as Kd,d as Ue,y as Qd,Q as Jd,v as pl,H as tu,R as eu,T as iu,i as jr,U as fl,V as su,W as nu,I as ru,X as ou,K as zo,Y as au,e as hu,w as lu,l as dr,f as cu,a as du,x as Oo,Z as uu,h as pu,_ as fu,j as gu,$ as gl,a0 as mu,a1 as yu,C as xu,a2 as Su,N as ur,O as bu,P as vu,M as Wo}from"./mapValues.D2X8cRgC.js";import{a as me,N as fn,i as ei,D as ml,b as Go,M as Uo,d as wu,H as Cu,e as _u}from"./theme.CAU4HwNY.js";var F=(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))(F||{});const pr=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},as=(n,e)=>pr(n).priority??e,Q={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...n){return n.map(pr).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(pr).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)=>as(o.value,t)-as(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)=>as(r,t)-as(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))}},Mu={extension:{type:F.Environment,name:"browser",priority:-1},test:()=>!0,load:async()=>{await ze(()=>import("./browserAll.BeYySQdg.js"),__vite__mapDeps([0,1,2,3,4]))}},Pu={extension:{type:F.Environment,name:"webworker",priority:0},test:()=>typeof self<"u"&&self.WorkerGlobalScope!==void 0,load:async()=>{await ze(()=>import("./webworkerAll.Dyo1xVCt.js"),__vite__mapDeps([1,2,3,4]))}};class dt{constructor(e,t,i){this._x=t||0,this._y=i||0,this._observer=e}clone(e){return new dt(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 yl={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),f=t?t+l:l;return h._events[f]?h._events[f].fn?h._events[f]=[h._events[f],p]:h._events[f].push(p):(h._events[f]=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,f=new Array(p);u<p;u++)f[u]=d[u].fn;return f},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,f){var g=t?t+l:l;if(!this._events[g])return!1;var m=this._events[g],x=arguments.length,S,b;if(m.fn){switch(m.once&&this.removeListener(l,m.fn,void 0,!0),x){case 1:return m.fn.call(m.context),!0;case 2:return m.fn.call(m.context,c),!0;case 3:return m.fn.call(m.context,c,d),!0;case 4:return m.fn.call(m.context,c,d,u),!0;case 5:return m.fn.call(m.context,c,d,u,p),!0;case 6:return m.fn.call(m.context,c,d,u,p,f),!0}for(b=1,S=new Array(x-1);b<x;b++)S[b-1]=arguments[b];m.fn.apply(m.context,S)}else{var v=m.length,M;for(b=0;b<v;b++)switch(m[b].once&&this.removeListener(l,m[b].fn,void 0,!0),x){case 1:m[b].fn.call(m[b].context);break;case 2:m[b].fn.call(m[b].context,c);break;case 3:m[b].fn.call(m[b].context,c,d);break;case 4:m[b].fn.call(m[b].context,c,d,u);break;default:if(!S)for(M=1,S=new Array(x-1);M<x;M++)S[M-1]=arguments[M];m[b].fn.apply(m[b].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 f=this._events[p];if(f.fn)f.fn===c&&(!u||f.once)&&(!d||f.context===d)&&o(this,p);else{for(var g=0,m=[],x=f.length;g<x;g++)(f[g].fn!==c||u&&!f[g].once||d&&f[g].context!==d)&&m.push(f[g]);m.length?this._events[p]=m.length===1?m[0]:m: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})(yl);var Au=yl.exports;const Jt=cl(Au),Tu=Math.PI*2,Ru=180/Math.PI,ku=Math.PI/180;class tt{constructor(e=0,t=0){this.x=0,this.y=0,this.x=e,this.y=t}clone(){return new tt(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 gn.x=0,gn.y=0,gn}}const gn=new tt;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 tt;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 tt;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(Tu-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 Iu.identity()}static get shared(){return Eu.identity()}}const Eu=new H,Iu=new H,Te=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],Re=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],ke=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],Ee=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],fr=[],xl=[],hs=Math.sign;function Du(){for(let n=0;n<16;n++){const e=[];fr.push(e);for(let t=0;t<16;t++){const i=hs(Te[n]*Te[t]+ke[n]*Re[t]),s=hs(Re[n]*Te[t]+Ee[n]*Re[t]),r=hs(Te[n]*ke[t]+ke[n]*Ee[t]),o=hs(Re[n]*ke[t]+Ee[n]*Ee[t]);for(let a=0;a<16;a++)if(Te[a]===i&&Re[a]===s&&ke[a]===r&&Ee[a]===o){e.push(a);break}}}for(let n=0;n<16;n++){const e=new H;e.set(Te[n],Re[n],ke[n],Ee[n],0,0),xl.push(e)}}Du();const Z={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=>Te[n],uY:n=>Re[n],vX:n=>ke[n],vY:n=>Ee[n],inv:n=>n&8?n&15:-n&7,add:(n,e)=>fr[n][e],sub:(n,e)=>fr[n][Z.inv(e)],rotate180:n=>n^4,isVertical:n=>(n&3)===2,byDirection:(n,e)=>Math.abs(n)*2<=Math.abs(e)?e>=0?Z.S:Z.N:Math.abs(e)*2<=Math.abs(n)?n>0?Z.E:Z.W:e>0?n>0?Z.SE:Z.SW:n>0?Z.NE:Z.NW,matrixAppendRotationInv:(n,e,t=0,i=0,s=0,r=0)=>{const o=xl[Z.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,f=n.b,g=n.c,m=n.d;n.a=a*p+h*g,n.b=a*f+h*m,n.c=l*p+c*g,n.d=l*f+c*m,n.tx=d*p+u*g+n.tx,n.ty=d*f+u*m+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===Z.E?(i.set(s+h,r+l,o,a),i):t===Z.S?i.set(c-r-a+h,s+l,a,o):t===Z.W?i.set(c-s-o+h,d-r-a+l,o,a):t===Z.N?i.set(r+h,d-s-o+l,a,o):i.set(s+h,r+l,o,a)}},ls=[new tt,new tt,new tt,new tt];class et{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 et(0,0,0,0)}clone(){return new et(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,f=h+o+l,g=a+c,m=a+r-c,x=h+c,S=h+o-c;return e>=d&&e<=u&&t>=p&&t<=f&&!(e>g&&e<m&&t>x&&t<S)}intersects(e,t){if(!t){const P=this.x<e.x?e.x:this.x;if((this.right>e.right?e.right:this.right)<=P)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=ls[0].set(e.left,e.top),h=ls[1].set(e.left,e.bottom),l=ls[2].set(e.right,e.top),c=ls[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),f=u*i+p*r,g=u*s+p*r,m=u*i+p*o,x=u*s+p*o;if(Math.max(f,g,m,x)<=u*a.x+p*a.y||Math.min(f,g,m,x)>=u*c.x+p*c.y)return!1;const S=d*(a.y-l.y),b=d*(l.x-a.x),v=S*i+b*r,M=S*s+b*r,_=S*i+b*o,w=S*s+b*o;return!(Math.max(v,M,_,w)<=S*a.x+b*a.y||Math.min(v,M,_,w)>=S*c.x+b*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 et),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 mn={default:-1};function ut(n="default"){return mn[n]===void 0&&(mn[n]=-1),++mn[n]}const Ho=new Set,J="8.0.0",Fu="8.3.4",ii={quiet:!1,noColor:!1},V=(n,e,t=3)=>{if(ii.quiet||Ho.has(e))return;let i=new Error().stack;const s=`${e}
|
|
3
|
+
Deprecated since v${n}`,r=typeof console.groupCollapsed=="function"&&!ii.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))),Ho.add(e)};Object.defineProperties(V,{quiet:{get:()=>ii.quiet,set:n=>{ii.quiet=n},enumerable:!0,configurable:!1},noColor:{get:()=>ii.noColor,set:n=>{ii.noColor=n},enumerable:!0,configurable:!1}});const Sl=()=>{};function li(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 No(n){return!(n&n-1)&&!!n}function bl(n){const e={};for(const t in n)n[t]!==void 0&&(e[t]=n[t]);return e}const Vo=Object.create(null);function Bu(n){const e=Vo[n];return e===void 0&&(Vo[n]=ut("resource")),e}const vl=class wl extends Jt{constructor(e={}){super(),this._resourceType="textureSampler",this._touched=0,this._maxAnisotropy=1,this.destroyed=!1,e={...wl.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(J,"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=Bu(e),this._resourceId}destroy(){this.destroyed=!0,this.emit("destroy",this),this.emit("change",this),this.removeAllListeners()}};vl.defaultOptions={addressMode:"clamp-to-edge",scaleMode:"linear"};let ci=vl;const Cl=class _l extends Jt{constructor(e={}){super(),this.options=e,this._gpuData=Object.create(null),this._gcLastUsed=-1,this.uid=ut("textureSource"),this._resourceType="textureSource",this._resourceId=ut("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={..._l.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 ci(bl(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=ut("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=ut("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=No(this.pixelWidth)&&No(this.pixelHeight)}static test(e){throw new Error("Unimplemented")}};Cl.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 Gt=Cl;class Zr extends Gt{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}}Zr.extension=F.TextureSource;const $o=new H;class Lu{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&&($o.set(i.width/s.width,0,0,i.height/s.height,-s.x/s.width,-s.y/s.height),this.mapCoord.append($o));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 U 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=ut("texture"),this.uvs={x0:0,y0:0,x1:0,y1:0,x2:0,y2:0,x3:0,y3:0},this.frame=new et,this.noFrame=!1,this.dynamic=!1,this.isTexture=!0,this.label=t,this.source=(e==null?void 0:e.source)??new Gt,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 Lu(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=Z.add(l,Z.NW),e.x0=u+c*Z.uX(l),e.y0=p+d*Z.uY(l),l=Z.add(l,2),e.x1=u+c*Z.uX(l),e.y1=p+d*Z.uY(l),l=Z.add(l,2),e.x2=u+c*Z.uX(l),e.y2=p+d*Z.uY(l),l=Z.add(l,2),e.x3=u+c*Z.uX(l),e.y3=p+d*Z.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(J,"Texture.baseTexture is now Texture.source"),this._source}}U.EMPTY=new U({label:"EMPTY",source:new Gt({label:"EMPTY"})});U.EMPTY.destroy=Sl;U.WHITE=new U({source:new Zr({resource:new Uint8Array([255,255,255,255]),width:1,height:1,alphaMode:"premultiply-alpha-on-upload",label:"WHITE"}),label:"WHITE"});U.WHITE.destroy=Sl;function Ml(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 Ot{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 et);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,f=this.maxX,g=this.maxY,m=o*e+h*t+c,x=a*e+l*t+d;m<u&&(u=m),x<p&&(p=x),m>f&&(f=m),x>g&&(g=x),m=o*i+h*t+c,x=a*i+l*t+d,m<u&&(u=m),x<p&&(p=x),m>f&&(f=m),x>g&&(g=x),m=o*e+h*s+c,x=a*e+l*s+d,m<u&&(u=m),x<p&&(p=x),m>f&&(f=m),x>g&&(g=x),m=o*i+h*s+c,x=a*i+l*s+d,m<u&&(u=m),x<p&&(p=x),m>f&&(f=m),x>g&&(g=x),this.minX=u,this.minY=p,this.maxX=f,this.maxY=g}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 Ot(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,f=s.ty;for(let g=t;g<i;g+=2){const m=e[g],x=e[g+1],S=l*m+d*x+p,b=c*m+u*x+f;r=S<r?S:r,o=b<o?b:o,a=S>a?S:a,h=b>h?b: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 zu={grad:.9,turn:360,rad:360/(2*Math.PI)},se=function(n){return typeof n=="string"?n.length>0:typeof n=="number"},Ct=function(n,e,t){return e===void 0&&(e=0),t===void 0&&(t=Math.pow(10,e)),Math.round(t*n)/t+0},zt=function(n,e,t){return e===void 0&&(e=0),t===void 0&&(t=1),n>t?t:n>e?n:e},Pl=function(n){return(n=isFinite(n)?n%360:0)>0?n:n+360},Xo=function(n){return{r:zt(n.r,0,255),g:zt(n.g,0,255),b:zt(n.b,0,255),a:zt(n.a)}},yn=function(n){return{r:Ct(n.r),g:Ct(n.g),b:Ct(n.b),a:Ct(n.a,3)}},Ou=/^#([0-9a-f]{3,8})$/i,cs=function(n){var e=n.toString(16);return e.length<2?"0"+e:e},Al=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}},Tl=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}},jo=function(n){return{h:Pl(n.h),s:zt(n.s,0,100),l:zt(n.l,0,100),a:zt(n.a)}},Zo=function(n){return{h:Ct(n.h),s:Ct(n.s),l:Ct(n.l),a:Ct(n.a,3)}},qo=function(n){return Tl((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},Oi=function(n){return{h:(e=Al(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},Wu=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Gu=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Uu=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Hu=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,gr={string:[[function(n){var e=Ou.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?Ct(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?Ct(parseInt(n.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(n){var e=Uu.exec(n)||Hu.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=Wu.exec(n)||Gu.exec(n);if(!e)return null;var t,i,s=jo({h:(t=e[1],i=e[2],i===void 0&&(i="deg"),Number(t)*(zu[i]||1)),s:Number(e[3]),l:Number(e[4]),a:e[5]===void 0?1:Number(e[5])/(e[6]?100:1)});return qo(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 se(e)&&se(t)&&se(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(!se(e)||!se(t)||!se(i))return null;var o=jo({h:Number(e),s:Number(t),l:Number(i),a:Number(r)});return qo(o)},"hsl"],[function(n){var e=n.h,t=n.s,i=n.v,s=n.a,r=s===void 0?1:s;if(!se(e)||!se(t)||!se(i))return null;var o=function(a){return{h:Pl(a.h),s:zt(a.s,0,100),v:zt(a.v,0,100),a:zt(a.a)}}({h:Number(e),s:Number(t),v:Number(i),a:Number(r)});return Tl(o)},"hsv"]]},Ko=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]},Nu=function(n){return typeof n=="string"?Ko(n.trim(),gr.string):typeof n=="object"&&n!==null?Ko(n,gr.object):[null,void 0]},xn=function(n,e){var t=Oi(n);return{h:t.h,s:zt(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},Qo=function(n,e){var t=Oi(n);return{h:t.h,s:t.s,l:zt(t.l+100*e,0,100),a:t.a}},mr=function(){function n(e){this.parsed=Nu(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 Ct(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=yn(this.rgba),t=e.r,i=e.g,s=e.b,o=(r=e.a)<1?cs(Ct(255*r)):"","#"+cs(t)+cs(i)+cs(s)+o;var e,t,i,s,r,o},n.prototype.toRgb=function(){return yn(this.rgba)},n.prototype.toRgbString=function(){return e=yn(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 Zo(Oi(this.rgba))},n.prototype.toHslString=function(){return e=Zo(Oi(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=Al(this.rgba),{h:Ct(e.h),s:Ct(e.s),v:Ct(e.v),a:Ct(e.a,3)};var e},n.prototype.invert=function(){return jt({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),jt(xn(this.rgba,e))},n.prototype.desaturate=function(e){return e===void 0&&(e=.1),jt(xn(this.rgba,-e))},n.prototype.grayscale=function(){return jt(xn(this.rgba,-1))},n.prototype.lighten=function(e){return e===void 0&&(e=.1),jt(Qo(this.rgba,e))},n.prototype.darken=function(e){return e===void 0&&(e=.1),jt(Qo(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"?jt({r:(t=this.rgba).r,g:t.g,b:t.b,a:e}):Ct(this.rgba.a,3);var t},n.prototype.hue=function(e){var t=Oi(this.rgba);return typeof e=="number"?jt({h:e,s:t.s,l:t.l,a:t.a}):Ct(t.h)},n.prototype.isEqual=function(e){return this.toHex()===jt(e).toHex()},n}(),jt=function(n){return n instanceof mr?n:new mr(n)},Jo=[],Vu=function(n){n.forEach(function(e){Jo.indexOf(e)<0&&(e(mr,gr),Jo.push(e))})};function $u(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 f in t){var g=(a=c,h=r[f],Math.pow(a.r-h.r,2)+Math.pow(a.g-h.g,2)+Math.pow(a.b-h.b,2));g<d&&(d=g,u=f)}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"])}Vu([$u]);const di=class Fi{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 Fi)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]=Fi._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=Fi.HEX_PATTERN.exec(e);a&&(e=`#${a[2]}`)}const o=jt(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 Fi||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}};di.shared=new di;di._temp=new di;di.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let ht=di;const Yu={cullArea:null,cullable:!1,cullableChildren:!0};let bn=0;const ta=500;function at(...n){bn!==ta&&(bn++,bn===ta?console.warn("PixiJS Warning: too many warnings, no more warnings will be reported to the console by PixiJS."):console.warn("PixiJS Warning: ",...n))}const ns={_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 Xu{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 ju{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 Xu(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 Ft=new ju;ns.register(Ft);const Zu={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 qu(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 Ku={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)}qu(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(J,"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)}},Qu={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 ea{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 Ju{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 Ft.get(i.maskClass,e)}return e}returnMaskEffect(e){Ft.return(e)}}const yr=new Ju;Q.handleByList(F.MaskEffect,yr._effectClasses);const tp={_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),yr.returnMaskEffect(e),this._maskEffect=null),n!=null&&(this._maskEffect=yr.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 ea);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 ea),this._filterEffect.filterArea=n},get filterArea(){var n;return(n=this._filterEffect)==null?void 0:n.filterArea}},ep={label:null,get name(){return V(J,"Container.name property has been removed, use Container.label instead"),this.label},set name(n){V(J,"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}},At=Ft.getPool(H),le=Ft.getPool(Ot),ip=new H,sp={getFastGlobalBounds(n,e){e||(e=new Ot),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=le.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(ip).invert()),e.addBounds(i),le.return(i)}else this.renderGroup&&(e.addBounds(i,this.relativeGroupTransform),le.return(i))}};function Rl(n,e,t){t.clear();let i,s;return n.parent?e?i=n.parent.worldTransform:(s=At.get().identity(),i=qr(n,s)):i=H.IDENTITY,kl(n,t,i,e),s&&At.return(s),t.isValid||t.set(0,0,0,0),t}function kl(n,e,t,i){var a,h;if(!n.visible||!n.measurable)return;let s;i?s=n.worldTransform:(n.updateLocalTransform(),s=At.get(),s.appendFrom(n.localTransform,t));const r=e,o=!!n.effects.length;if(o&&(e=le.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++)kl(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),le.return(e)}i||At.return(s)}function qr(n,e){const t=n.parent;return t&&(qr(t,e),t.updateLocalTransform(),e.append(t.localTransform)),e}function Kr(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 ia=16777215;function sa(n,e){return n===ia?e:e===ia?n:Kr(n,e)}function Wi(n){return((n&255)<<16)+(n&65280)+(n>>16&255)}const np={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=qr(this,At.get().identity());return n.appendFrom(this.localTransform,t),At.return(t),n},getGlobalTint(n){if(n)return this.renderGroup?Wi(this.renderGroup.worldColor):this.parentRenderGroup?Wi(sa(this.localColor,this.parentRenderGroup.worldColor)):this.tint;let e=this.localColor,t=this.parent;for(;t;)e=sa(e,t.localColor),t=t.parent;return Wi(e)}};function El(n,e,t){return e.clear(),t||(t=H.IDENTITY),Il(n,e,t,n,!0),e.isValid||e.set(0,0,0,0),e}function Il(n,e,t,i,s){var h,l;let r;if(s)r=At.get(),r=t.copyTo(r);else{if(!n.visible||!n.measurable)return;n.updateLocalTransform();const c=n.localTransform;r=At.get(),r.appendFrom(c,t)}const o=e,a=!!n.effects.length;if(a&&(e=le.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++)Il(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),le.return(e)}At.return(r)}function Dl(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&&Dl(s,e)}return e.didChange}const rp=new H,op={_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 Ot});const n=this._localBoundsCacheData;return n.index=1,n.didChange=!1,n.data[0]!==this._didViewChangeTick&&(n.didChange=!0,n.data[0]=this._didViewChangeTick),Dl(this,n),n.didChange&&El(this,n.localBounds,rp),n.localBounds},getBounds(n,e){return Rl(this,n,e||new Ot)}},ap={_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}},hp={_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(lp))}};function lp(n,e){return n._zIndex-e._zIndex}const cp={getGlobalPosition(n=new tt,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(At.get(),t);return e=i.apply(n,e),At.return(i),e},toLocal(n,e,t,i){e&&(n=e.toGlobal(n,t,i));const s=this.getGlobalTransform(At.get(),i);return t=s.applyInverse(n,t),At.return(s),t}};class Qr{constructor(){this.uid=ut("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 dp=0;class up{constructor(e){this._poolKeyHash=Object.create(null),this._texturePool={},this.textureOptions=e||{},this.enableFullScreen=!1,this.textureStyle=new ci(this.textureOptions)}createTexture(e,t,i){const s=new Gt({...this.textureOptions,width:e,height:t,resolution:1,antialias:i,autoGarbageCollect:!1});return new U({source:s,label:`texturePool_${dp++}`})}getOptimalTexture(e,t,i=1,s){let r=Math.ceil(e*i-1e-6),o=Math.ceil(t*i-1e-6);r=li(r),o=li(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 qs=new up;ns.register(qs);class pp{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 Qr,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&&(qs.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 fp(n,e,t={}){for(const i in e)!t[i]&&e[i]!==void 0&&(n[i]=e[i])}const vn=new dt(null),ds=new dt(null),wn=new dt(null,1,1),us=new dt(null),na=1,gp=2,Cn=4;class W extends Jt{constructor(e={}){var t,i;super(),this.uid=ut("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 dt(this,0,0),this._scale=wn,this._pivot=ds,this._origin=us,this._skew=vn,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=[],fp(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."),Q.mixin(W,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(J,"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=Ft.get(pp,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),Ft.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*Ru}set angle(e){this.rotation=e*ku}get pivot(){return this._pivot===ds&&(this._pivot=new dt(this,0,0)),this._pivot}set pivot(e){this._pivot===ds&&(this._pivot=new dt(this,0,0),this._origin!==us&&at("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===vn&&(this._skew=new dt(this,0,0)),this._skew}set skew(e){this._skew===vn&&(this._skew=new dt(this,0,0)),this._skew.copyFrom(e)}get scale(){return this._scale===wn&&(this._scale=new dt(this,1,1)),this._scale}set scale(e){this._scale===wn&&(this._scale=new dt(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===us&&(this._origin=new dt(this,0,0)),this._origin}set origin(e){this._origin===us&&(this._origin=new dt(this,0,0),this._pivot!==ds&&at("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|=na,this._onUpdate())}get alpha(){return this.localAlpha}set tint(e){const i=ht.shared.setValue(e??16777215).toBgrNumber();i!==this.localColor&&(this.localColor=i,this._updateFlags|=na,this._onUpdate())}get tint(){return Wi(this.localColor)}set blendMode(e){this.localBlendMode!==e&&(this.parentRenderGroup&&(this.parentRenderGroup.structureDidChange=!0),this._updateFlags|=gp,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|=Cn,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|=Cn,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|=Cn,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}}Q.mixin(W,Ku,sp,cp,ap,op,tp,ep,hp,Yu,Zu,np,Qu);class xi extends W{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 Ot(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 Qt extends xi{constructor(e=U.EMPTY){e instanceof U&&(e={texture:e});const{texture:t=U.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 dt({_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 U?new Qt(e):new Qt(U.from(e,t))}set texture(e){e||(e=U.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 Ml(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 mp=new Ot;function Fl(n,e,t){const i=mp;n.measurable=!0,Rl(n,t,i),e.addBoundsMask(i),n.measurable=!1}function Bl(n,e,t){const i=le.get();n.measurable=!0;const s=At.get().identity(),r=Ll(n,t,s);El(n,i,r),n.measurable=!1,e.addBoundsMask(i),At.return(s),le.return(i)}function Ll(n,e,t){return n?(n!==e&&(Ll(n.parent,e,t),n.updateLocalTransform(),t.append(n.localTransform)),t):(at("Mask bounds, renderable is not inside the root container"),t)}class zl{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 Qt),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||Fl(this.mask,e,t)}addLocalBounds(e,t){Bl(this.mask,e,t)}containsPoint(e,t){const i=this.mask;return t(i,e)}destroy(){this.reset()}static test(e){return e instanceof Qt}}zl.extension=F.MaskEffect;class Ol{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"}}Ol.extension=F.MaskEffect;class Wl{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){Fl(this.mask,e,t)}addLocalBounds(e,t){Bl(this.mask,e,t)}containsPoint(e,t){const i=this.mask;return t(i,e)}destroy(){this.reset()}static test(e){return e instanceof W}}Wl.extension=F.MaskEffect;const yp={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 ra=yp;const j={get(){return ra},set(n){ra=n}};class Jr extends Gt{constructor(e){e.resource||(e.resource=j.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"))}}Jr.extension=F.TextureSource;class ui extends Gt{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}}ui.extension=F.TextureSource;var He=(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))(He||{});class _n{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 Gl=class Bt{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 _n(null,null,1/0),this.deltaMS=1/Bt.targetFPMS,this.elapsedMS=1/Bt.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=He.NORMAL){return this._addListener(new _n(e,t,i))}addOnce(e,t,i=He.NORMAL){return this._addListener(new _n(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*Bt.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,Bt.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(!Bt._shared){const e=Bt._shared=new Bt;e.autoStart=!0,e._protected=!0}return Bt._shared}static get system(){if(!Bt._system){const e=Bt._system=new Bt;e.autoStart=!0,e._protected=!0}return Bt._system}};Gl.targetFPMS=.06;let xt=Gl,Mn;async function Ul(){return Mn??(Mn=(async()=>{var o;const e=j.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"})()),Mn}const Ks=class Hl extends Gt{constructor(e){super(e),this.isReady=!1,this.uploadMethodId="video",e={...Hl.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=xt.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 Ul(),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&&(xt.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||(xt.shared.add(this.updateFrame,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(this._videoFrameRequestCallbackHandle!==null&&(this.resource.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(xt.shared.remove(this.updateFrame,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement}};Ks.extension=F.TextureSource;Ks.defaultOptions={...Gt.defaultOptions,autoLoad:!0,autoPlay:!0,updateFPS:0,crossorigin:!0,loop:!1,muted:!0,playsinline:!0,preload:!1};Ks.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Gi=Ks;const Ht=(n,e,t=!1)=>(Array.isArray(n)||(n=[n]),e?n.map(i=>typeof i=="string"||t?e(i):i):n);class xp{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||at(`[Assets] Asset id ${e} was not found in the Cache`),t}set(e,t){const i=Ht(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&&at("[Cache] already has key:",h),this._cache.set(h,r.get(h))})}remove(e){if(!this._cacheMap.has(e)){at(`[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 St=new xp,xr=[];Q.handleByList(F.TextureSource,xr);function Nl(n={}){const e=n&&n.resource,t=e?n.resource:n,i=e?n:{resource:n};for(let s=0;s<xr.length;s++){const r=xr[s];if(r.test(t))return new r(i)}throw new Error(`Could not find a source type for resource: ${i.resource}`)}function Sp(n={},e=!1){const t=n&&n.resource,i=t?n.resource:n,s=t?n:{resource:n};if(!e&&St.has(i))return St.get(i);const r=new U({source:Nl(s)});return r.on("destroy",()=>{St.has(i)&&St.remove(i)}),e||St.set(i,r),r}function bp(n,e=!1){return typeof n=="string"?St.get(n):n instanceof Gt?new U({source:n}):Sp(n,e)}U.from=bp;Gt.from=Nl;Q.add(zl,Ol,Wl,Gi,ui,Jr,Zr);var _e=(n=>(n[n.Low=0]="Low",n[n.Normal=1]="Normal",n[n.High=2]="High",n))(_e||{});function Ut(n){if(typeof n!="string")throw new TypeError(`Path must be a string. Received ${JSON.stringify(n)}`)}function _i(n){return n.split("?")[0].split("#")[0]}function vp(n){return n.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function wp(n,e,t){return n.replace(new RegExp(vp(e),"g"),t)}function Cp(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 Et={toPosix(n){return wp(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){Ut(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(Ut(n),this.isDataUrl(n)||this.isBlobUrl(n))return n;const i=_i(this.toPosix(e??j.get().getBaseUrl())),s=_i(this.toPosix(t??this.rootname(i)));return n=this.toPosix(n),n.startsWith("/")?Et.join(s,n.slice(1)):this.isAbsolute(n)?n:this.join(i,n)},normalize(n){if(Ut(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=Cp(n),n.length>0&&i&&(n+="/"),t?`/${n}`:e+n},isAbsolute(n){return Ut(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(Ut(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(Ut(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){Ut(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){Ut(n),e&&Ut(e),n=_i(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){Ut(n),n=_i(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){Ut(n);const e={root:"",dir:"",base:"",ext:"",name:""};if(n.length===0)return e;n=_i(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 Vl(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?Vl(n.replace(i[t],a),e,t+1,i,s):s.push(n.replace(i[t],a))}}function _p(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)}),Vl(n,s,0,t,i)}else i.push(n);return i}const Os=n=>!Array.isArray(n);class Si{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 Ht(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&&at("[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)&&at(`[Resolver] already has key: ${r} overwriting`)},Ht(t).forEach(r=>{const{src:o}=r;let{data:a,format:h,loadParser:l,parser:c}=r;const d=Ht(o).map(g=>typeof g=="string"?_p(g):Array.isArray(g)?g:[g]),u=this.getAlias(r);Array.isArray(u)?u.forEach(i):i(u);const p=[],f=g=>{const m=this._parsers.find(x=>x.test(g));return{src:g,...m==null?void 0:m.parse(g)}};d.forEach(g=>{g.forEach(m=>{let x={};if(typeof m!="object"?x=f(m):(a=m.data??a,h=m.format??h,(m.loadParser||m.parser)&&(l=m.loadParser??l,c=m.parser??c),x={...f(m.src),...m}),!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(g=>{this._assetMap[g]=p})})}resolveBundle(e){const t=Os(e);e=Ht(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=Os(e);e=Ht(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=Et.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??Mp(e.src),h!==void 0&&(e.progressSize=h),e}}Si.RETINA_PREFIX=/@([0-9\.]+)x/;function Mp(n){return n.split(".").pop().split("?").shift().split("#").shift()}const Sr=(n,e)=>{const t=e.split("?")[1];return t&&(n+=`?${t}`),n},$l=class Bi{constructor(e,t){this.linkedSheets=[];let i=e;(e==null?void 0:e.source)instanceof Gt&&(i={texture:e,data:t});const{texture:s,data:r,cachePrefix:o=""}=i;this.cachePrefix=o,this._texture=s instanceof U?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 et(0,0,Math.floor(c.w)/this.resolution,Math.floor(c.h)/this.resolution);o.rotated?h=new et(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 et(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 et(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 U({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=[]}};$l.BATCH_SIZE=1e3;let br=$l;const Pp=["jpg","png","jpeg","avif","webp","basis","etc2","bc7","bc6h","bc5","bc4","bc3","bc2","bc1","eac","astc"];function Yl(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=Et.dirname(n[0]);e.linkedSheets.forEach((r,o)=>{const a=Yl([`${s}/${e.data.meta.related_multi_packs[o]}`],r,!0);Object.assign(i,a)})}return i}const Ap={extension:F.Asset,cache:{test:n=>n instanceof br,getCacheableAssets:(n,e)=>Yl(n,e,!1)},resolver:{extension:{type:F.ResolveParser,name:"resolveSpritesheet"},test:n=>{const t=n.split("?")[0].split("."),i=t.pop(),s=t.pop();return i==="json"&&Pp.includes(s)},parse:n=>{var t;const e=n.split(".");return{resolution:parseFloat(((t=Si.RETINA_PREFIX.exec(n))==null?void 0:t[1])??"1"),format:e[e.length-2],src:n}}},loader:{name:"spritesheetLoader",id:"spritesheet",extension:{type:F.LoadParser,priority:_e.Normal,name:"spritesheetLoader"},async testParse(n,e){return Et.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=Et.dirname(e.src);a&&a.lastIndexOf("/")!==a.length-1&&(a+="/");let h;if(i instanceof U)h=i;else{const p=Sr(a+(s??n.meta.image),e.src);h=(await t.load([{src:p,data:r}]))[p]}const l=new br({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 g of c){if(typeof g!="string")continue;let m=a+g;(u=e.data)!=null&&u.ignoreMultiPack||(m=Sr(m,e.src),p.push(t.load({src:m,data:{textureOptions:r,ignoreMultiPack:!0}})))}const f=await Promise.all(p);l.linkedSheets=f,f.forEach(g=>{g.linkedSheets=[l].concat(l.linkedSheets.filter(m=>m!==g))})}return l},async unload(n,e,t){await t.unload(n.textureSource._sourceOrigin),n.destroy(!1)}}};Q.add(Ap);class Tp{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||xt.shared.add(this.updateTranslation,this,He.HIGH)}destroy(){this._observer?(this._observer.disconnect(),this._observer=null):this._tickerAttached&&xt.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 to{constructor(e){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=to.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new tt,this.page=new tt,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 Pn=/iPhone/i,oa=/iPod/i,aa=/iPad/i,ha=/\biOS-universal(?:.+)Mac\b/i,An=/\bAndroid(?:.+)Mobile\b/i,la=/Android/i,Ze=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,ps=/Silk/i,ne=/Windows Phone/i,ca=/\bWindows(?:.+)ARM\b/i,da=/BlackBerry/i,ua=/BB10/i,pa=/Opera Mini/i,fa=/\b(CriOS|Chrome)(?:.+)Mobile/i,ga=/Mobile(?:.+)Firefox\b/i,ma=function(n){return typeof n<"u"&&n.platform==="MacIntel"&&typeof n.maxTouchPoints=="number"&&n.maxTouchPoints>1&&typeof MSStream>"u"};function Rp(n){return function(e){return e.test(n)}}function ya(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=Rp(t),r={apple:{phone:s(Pn)&&!s(ne),ipod:s(oa),tablet:!s(Pn)&&(s(aa)||ma(e))&&!s(ne),universal:s(ha),device:(s(Pn)||s(oa)||s(aa)||s(ha)||ma(e))&&!s(ne)},amazon:{phone:s(Ze),tablet:!s(Ze)&&s(ps),device:s(Ze)||s(ps)},android:{phone:!s(ne)&&s(Ze)||!s(ne)&&s(An),tablet:!s(ne)&&!s(Ze)&&!s(An)&&(s(ps)||s(la)),device:!s(ne)&&(s(Ze)||s(ps)||s(An)||s(la))||s(/\bokhttp\b/i)},windows:{phone:s(ne),tablet:s(ca),device:s(ne)||s(ca)},other:{blackberry:s(da),blackberry10:s(ua),opera:s(pa),firefox:s(ga),chrome:s(fa),device:s(da)||s(ua)||s(pa)||s(ga)||s(fa)},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 kp=ya.default??ya,Ep=kp(globalThis.navigator),Tn=Object.create(null),xa=Object.create(null);function eo(n,e){let t=xa[n];return t===void 0&&(Tn[e]===void 0&&(Tn[e]=1),xa[n]=t=Tn[e]++),t}let qe;function Xl(){return(!qe||qe!=null&&qe.isContextLost())&&(qe=j.get().createCanvas().getContext("webgl",{})),qe}let fs;function Ip(){if(!fs){fs="mediump";const n=Xl();n&&n.getShaderPrecisionFormat&&(fs=n.getShaderPrecisionFormat(n.FRAGMENT_SHADER,n.HIGH_FLOAT).precision?"highp":"mediump")}return fs}function Dp(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 Fp(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 Bp(n,e){return e?`#version 300 es
|
|
22
|
+
${n}`:n}const Lp={},zp={};function Op(n,{name:e="pixi-program"},t=!0){e=e.replace(/\s+/g,"-"),e+=t?"-fragment":"-vertex";const i=t?Lp:zp;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 Wp(n,e){return e?n.replace("#version 300 es",""):n}const Rn={stripVersion:Wp,ensurePrecision:Fp,addProgramDefines:Dp,setProgramName:Op,insertVersion:Bp},Mi=Object.create(null),jl=class vr{constructor(e){e={...vr.defaultOptions,...e};const t=e.fragment.indexOf("#version 300 es")!==-1,i={stripVersion:t,ensurePrecision:{requestedFragmentPrecision:e.preferredFragmentPrecision,requestedVertexPrecision:e.preferredVertexPrecision,maxSupportedVertexPrecision:"highp",maxSupportedFragmentPrecision:Ip()},setProgramName:{name:e.name},addProgramDefines:t,insertVersion:t};let s=e.fragment,r=e.vertex;Object.keys(Rn).forEach(o=>{const a=i[o];s=Rn[o](s,a,!0),r=Rn[o](r,a,!1)}),this.fragment=s,this.vertex=r,this.transformFeedbackVaryings=e.transformFeedbackVaryings,this._key=eo(`${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,Mi[this._cacheKey]=null}static from(e){const t=`${e.vertex}:${e.fragment}`;return Mi[t]||(Mi[t]=new vr(e),Mi[t]._cacheKey=t),Mi[t]}};jl.defaultOptions={preferredVertexPrecision:"highp",preferredFragmentPrecision:"mediump"};let pi=jl;const Sa={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 Gp(n){return Sa[n]??Sa.float32}const Up={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"},ba=/@location\((\d+)\)\s+([a-zA-Z0-9_]+)\s*:\s*([a-zA-Z0-9_<>]+)(?:,|\s|\)|$)/g;function va(n,e){let t;for(;(t=ba.exec(n))!==null;){const i=Up[t[3]]??"float32";e[t[2]]={location:parseInt(t[1],10),format:i,stride:Gp(i).stride,offset:0,instance:!1,start:0}}ba.lastIndex=0}function Hp(n){return n.replace(/\/\/.*$/gm,"").replace(/\/\*[\s\S]*?\*\//g,"")}function Np({source:n,entryPoint:e}){const t={},i=Hp(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(va(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&&va(c[1],t)}}return t}function kn(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 f=p.match(h)[1],g=p.match(a).reduce((m,x)=>{const[S,b]=x.split(":");return m[S.trim()]=b.trim(),m},{});return g?{name:f,members:g}:null}).filter(({name:p})=>l.some(f=>f.type===p||f.type.includes(`<${p}>`))))??[];return{groups:l,structs:c}}var Ie=(n=>(n[n.VERTEX=1]="VERTEX",n[n.FRAGMENT=2]="FRAGMENT",n[n.COMPUTE=4]="COMPUTE",n))(Ie||{});function Vp({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:Ie.VERTEX|Ie.FRAGMENT,buffer:{type:"uniform"}}):i.type==="sampler"?e[i.group].push({binding:i.binding,visibility:Ie.FRAGMENT,sampler:{type:"filtering"}}):i.type==="texture_2d"||i.type.startsWith("texture_2d<")?e[i.group].push({binding:i.binding,visibility:Ie.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:Ie.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:Ie.FRAGMENT,texture:{sampleType:"float",viewDimension:"cube",multisampled:!1}})}for(let t=0;t<e.length;t++)e[t]||(e[t]=[]);return e}function $p({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 Yp(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 be{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=kn(t.source);this.structsAndGroups=l}else{const l=kn(i.source),c=kn(t.source);this.structsAndGroups=Yp(l,c)}this.layout=s??$p(this.structsAndGroups),this.gpuLayout=r??Vp(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=eo(i,"program")}get attributeData(){return this._attributeData??(this._attributeData=Np(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 be(e),Pi[t]._cacheKey=t),Pi[t]}}const Zl=["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>"],Xp=Zl.reduce((n,e)=>(n[e]=!0,n),{});function jp(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 ql=class Kl{constructor(e,t){this._touched=0,this.uid=ut("uniform"),this._resourceType="uniformGroup",this._resourceId=ut("resource"),this.isUniformGroup=!0,this._dirtyId=0,this.destroyed=!1,t={...Kl.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,!Xp[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: ${Zl.join(", ")}`)}r.value??(r.value=jp(r.type,r.size)),i[s]=r.value}this.uniforms=i,this._dirtyId=1,this.ubo=t.ubo,this.isStatic=t.isStatic,this._signature=eo(Object.keys(i).map(s=>`${s}-${e[s].type}`).join("-"),"uniform-group")}update(){this._dirtyId++}};ql.defaultOptions={ubo:!1,isStatic:!1};let fi=ql;class Ui{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 he=(n=>(n[n.WEBGL=1]="WEBGL",n[n.WEBGPU=2]="WEBGPU",n[n.CANVAS=4]="CANVAS",n[n.BOTH=3]="BOTH",n))(he||{});class Ne extends Jt{constructor(e){super(),this.uid=ut("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|=he.WEBGPU),i&&(o|=he.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 Ui,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 fi(u));const p=h[d];p&&(s[p.group]||(s[p.group]=new Ui,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 Ui,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=be.from(t)),i&&(o=pi.from(i)),new Ne({gpuProgram:r,glProgram:o,...s})}}const Zp={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},En=0,In=1,Dn=2,Fn=3,Bn=4,Ln=5,wr=class Ql{constructor(){this.data=0,this.blendMode="normal",this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(this.data&1<<En)}set blend(e){!!(this.data&1<<En)!==e&&(this.data^=1<<En)}get offsets(){return!!(this.data&1<<In)}set offsets(e){!!(this.data&1<<In)!==e&&(this.data^=1<<In)}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<<Dn)}set culling(e){!!(this.data&1<<Dn)!==e&&(this.data^=1<<Dn)}get depthTest(){return!!(this.data&1<<Fn)}set depthTest(e){!!(this.data&1<<Fn)!==e&&(this.data^=1<<Fn)}get depthMask(){return!!(this.data&1<<Ln)}set depthMask(e){!!(this.data&1<<Ln)!==e&&(this.data^=1<<Ln)}get clockwiseFrontFace(){return!!(this.data&1<<Bn)}set clockwiseFrontFace(e){!!(this.data&1<<Bn)!==e&&(this.data^=1<<Bn)}get blendMode(){return this._blendMode}set blendMode(e){this.blend=e!=="none",this._blendMode=e,this._blendModeId=Zp[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 Ql;return e.depthTest=!1,e.blend=!0,e}};wr.default2d=wr.for2d();let rs=wr;const Jl=class Cr extends Ne{constructor(e){e={...Cr.defaultOptions,...e},super(e),this.enabled=!0,this._state=rs.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=be.from(t)),i&&(o=pi.from(i)),new Cr({gpuProgram:r,glProgram:o,...s})}};Jl.defaultOptions={blendMode:"normal",resolution:1,padding:0,antialias:"off",blendRequired:!1,clipToViewport:!0};let qp=Jl;const _r=[];Q.handleByNamedList(F.Environment,_r);async function Kp(n){if(!n)for(let e=0;e<_r.length;e++){const t=_r[e];if(t.value.test()){await t.value.load();return}}}let Ai;function Qp(){if(typeof Ai=="boolean")return Ai;try{Ai=new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")===!0}catch{Ai=!1}return Ai}function wa(n,e,t=2){const i=e&&e.length,s=i?e[0]*t:n.length;let r=tc(n,0,s,t,!0);const o=[];if(!r||r.next===r.prev)return o;let a,h,l;if(i&&(r=nf(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],f=n[u+1];p<a&&(a=p),f<h&&(h=f),p>c&&(c=p),f>d&&(d=f)}l=Math.max(c-a,d-h),l=l!==0?32767/l:0}return Zi(r,o,t,a,h,l,0),o}function tc(n,e,t,i,s){let r;if(s===gf(n,e,t,i)>0)for(let o=e;o<t;o+=i)r=Ca(o/i|0,n[o],n[o+1],r);else for(let o=t-i;o>=e;o-=i)r=Ca(o/i|0,n[o],n[o+1],r);return r&&gi(r,r.next)&&(Ki(r),r=r.next),r}function Ve(n,e){if(!n)return n;e||(e=n);let t=n,i;do if(i=!1,!t.steiner&&(gi(t,t.next)||lt(t.prev,t,t.next)===0)){if(Ki(t),t=e=t.prev,t===t.next)break;i=!0}else t=t.next;while(i||t!==e);return e}function Zi(n,e,t,i,s,r,o){if(!n)return;!o&&r&&lf(n,i,s,r);let a=n;for(;n.prev!==n.next;){const h=n.prev,l=n.next;if(r?tf(n,i,s,r):Jp(n)){e.push(h.i,n.i,l.i),Ki(n),n=l.next,a=l.next;continue}if(n=l,n===a){o?o===1?(n=ef(Ve(n),e),Zi(n,e,t,i,s,r,2)):o===2&&sf(n,e,t,i,s,r):Zi(Ve(n),e,t,i,s,r,1);break}}}function Jp(n){const e=n.prev,t=n,i=n.next;if(lt(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 f=i.next;for(;f!==e;){if(f.x>=c&&f.x<=u&&f.y>=d&&f.y<=p&&Li(s,a,r,h,o,l,f.x,f.y)&<(f.prev,f,f.next)>=0)return!1;f=f.next}return!0}function tf(n,e,t,i){const s=n.prev,r=n,o=n.next;if(lt(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),f=Math.min(c,d,u),g=Math.max(a,h,l),m=Math.max(c,d,u),x=Mr(p,f,e,t,i),S=Mr(g,m,e,t,i);let b=n.prevZ,v=n.nextZ;for(;b&&b.z>=x&&v&&v.z<=S;){if(b.x>=p&&b.x<=g&&b.y>=f&&b.y<=m&&b!==s&&b!==o&&Li(a,c,h,d,l,u,b.x,b.y)&<(b.prev,b,b.next)>=0||(b=b.prevZ,v.x>=p&&v.x<=g&&v.y>=f&&v.y<=m&&v!==s&&v!==o&&Li(a,c,h,d,l,u,v.x,v.y)&<(v.prev,v,v.next)>=0))return!1;v=v.nextZ}for(;b&&b.z>=x;){if(b.x>=p&&b.x<=g&&b.y>=f&&b.y<=m&&b!==s&&b!==o&&Li(a,c,h,d,l,u,b.x,b.y)&<(b.prev,b,b.next)>=0)return!1;b=b.prevZ}for(;v&&v.z<=S;){if(v.x>=p&&v.x<=g&&v.y>=f&&v.y<=m&&v!==s&&v!==o&&Li(a,c,h,d,l,u,v.x,v.y)&<(v.prev,v,v.next)>=0)return!1;v=v.nextZ}return!0}function ef(n,e){let t=n;do{const i=t.prev,s=t.next.next;!gi(i,s)&&ic(i,t,t.next,s)&&qi(i,s)&&qi(s,i)&&(e.push(i.i,t.i,s.i),Ki(t),Ki(t.next),t=n=s),t=t.next}while(t!==n);return Ve(t)}function sf(n,e,t,i,s,r){let o=n;do{let a=o.next.next;for(;a!==o.prev;){if(o.i!==a.i&&uf(o,a)){let h=sc(o,a);o=Ve(o,o.next),h=Ve(h,h.next),Zi(o,e,t,i,s,r,0),Zi(h,e,t,i,s,r,0);return}a=a.next}o=o.next}while(o!==n)}function nf(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=tc(n,a,h,i,!1);l===l.next&&(l.steiner=!0),s.push(df(l))}s.sort(rf);for(let r=0;r<s.length;r++)t=of(s[r],t);return t}function rf(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 of(n,e){const t=af(n,e);if(!t)return e;const i=sc(t,n);return Ve(i,i.next),Ve(t,t.next)}function af(n,e){let t=e;const i=n.x,s=n.y;let r=-1/0,o;if(gi(n,t))return t;do{if(gi(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&&ec(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);qi(t,n)&&(d<c||d===c&&(t.x>o.x||t.x===o.x&&hf(o,t)))&&(o=t,c=d)}t=t.next}while(t!==a);return o}function hf(n,e){return lt(n.prev,n,e.prev)<0&<(e.next,n,n.next)<0}function lf(n,e,t,i){let s=n;do s.z===0&&(s.z=Mr(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,cf(s)}function cf(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 Mr(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 df(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 ec(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 Li(n,e,t,i,s,r,o,a){return!(n===o&&e===a)&&ec(n,e,t,i,s,r,o,a)}function uf(n,e){return n.next.i!==e.i&&n.prev.i!==e.i&&!pf(n,e)&&(qi(n,e)&&qi(e,n)&&ff(n,e)&&(lt(n.prev,n,e.prev)||lt(n,e.prev,e))||gi(n,e)&<(n.prev,n,n.next)>0&<(e.prev,e,e.next)>0)}function lt(n,e,t){return(e.y-n.y)*(t.x-e.x)-(e.x-n.x)*(t.y-e.y)}function gi(n,e){return n.x===e.x&&n.y===e.y}function ic(n,e,t,i){const s=ms(lt(n,e,t)),r=ms(lt(n,e,i)),o=ms(lt(t,i,n)),a=ms(lt(t,i,e));return!!(s!==r&&o!==a||s===0&&gs(n,t,e)||r===0&&gs(n,i,e)||o===0&&gs(t,n,i)||a===0&&gs(t,e,i))}function gs(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 ms(n){return n>0?1:n<0?-1:0}function pf(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&&ic(t,t.next,n,e))return!0;t=t.next}while(t!==n);return!1}function qi(n,e){return lt(n.prev,n,n.next)<0?lt(n,e,n.next)>=0&<(n,n.prev,e)>=0:lt(n,e,n.prev)<0||lt(n,n.next,e)<0}function ff(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 sc(n,e){const t=Pr(n.i,n.x,n.y),i=Pr(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 Ca(n,e,t,i){const s=Pr(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 Ki(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 Pr(n,e,t){return{i:n,x:e,y:t,prev:null,next:null,z:0,prevZ:null,nextZ:null,steiner:!1}}function gf(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 mf=wa.default||wa;var nc=(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))(nc||{});class yf{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 xf=["init","destroy","contextChange","resolutionChange","resetState","renderEnd","renderStart","render","update","postrender","prerender"],rc=class oc extends Jt{constructor(e){super(),this.tick=0,this.uid=ut("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=[...xf,...this.config.runners??[]];this._addRunners(...t),this._unsafeEvalCheck()}async init(e={}){const t=e.skipExtensionImports===!0?!0:e.manageImports===!1;await Kp(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={...oc.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 W&&(i={container:i},t&&(V(J,"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:ht.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=nc.ALL);const{clear:i,clearColor:s,target:r,mipLevel:o,layer:a}=e;ht.shared.setValue(s??this.background.colorRgba),t.renderTarget.clear(r,i,ht.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 yf(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)&&ns.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(!Qp())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()}};rc.defaultOptions={resolution:1,failIfMajorPerformanceCaveat:!1,roundPixels:!1};let ac=rc,ys;function Sf(n){return ys!==void 0||(ys=(()=>{var t;const e={stencil:!0,failIfMajorPerformanceCaveat:n??ac.defaultOptions.failIfMajorPerformanceCaveat};try{if(!j.get().getWebGLRenderingContext())return!1;let s=j.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}})()),ys}let xs;async function bf(n={}){return xs!==void 0||(xs=await(async()=>{const e=j.get().getNavigator().gpu;if(!e)return!1;try{return await(await e.requestAdapter(n)).requestDevice(),!0}catch{return!1}})()),xs}const _a=["webgl","webgpu","canvas"];async function vf(n){let e=[];n.preference?(e.push(n.preference),_a.forEach(r=>{r!==n.preference&&e.push(r)})):e=_a.slice();let t,i={};for(let r=0;r<e.length;r++){const o=e[r];if(o==="webgpu"&&await bf()){const{WebGPURenderer:a}=await ze(async()=>{const{WebGPURenderer:h}=await import("./WebGPURenderer.CLtb2XY4.js");return{WebGPURenderer:h}},__vite__mapDeps([5,6,7,2,3,4]));t=a,i={...n,...n.webgpu};break}else if(o==="webgl"&&Sf(n.failIfMajorPerformanceCaveat??ac.defaultOptions.failIfMajorPerformanceCaveat)){const{WebGLRenderer:a}=await ze(async()=>{const{WebGLRenderer:h}=await import("./WebGLRenderer.IUUQ0Lkd.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 ze(async()=>{const{CanvasRenderer:h}=await import("./CanvasRenderer.BjafRf72.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 hc="8.16.0";class lc{static init(){var e;(e=globalThis.__PIXI_APP_INIT__)==null||e.call(globalThis,this,hc)}static destroy(){}}lc.extension=F.Application;class wf{constructor(e){this._renderer=e}init(){var e;(e=globalThis.__PIXI_RENDERER_INIT__)==null||e.call(globalThis,this._renderer,hc)}destroy(){this._renderer=null}}wf.extension={type:[F.WebGLSystem,F.WebGPUSystem],name:"initHook",priority:-10};class cc{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}}cc.extension=F.Application;class dc{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,He.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=e.sharedTicker?xt.shared:new xt,e.autoStart&&this.start()}static destroy(){if(this._ticker){const e=this._ticker;this.ticker=null,e.destroy()}}}dc.extension=F.Application;Q.add(cc);Q.add(dc);const uc=class Ar{constructor(...e){this.stage=new W,e[0]!==void 0&&V(J,"Application constructor options are deprecated, please use Application.init() instead.")}async init(e){e={...e},this.stage||(this.stage=new W),this.renderer=await vf(e),Ar._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(J,"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=Ar._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}};uc._plugins=[];let pc=uc;Q.handleByList(F.Application,pc._plugins);Q.add(lc);const zn={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),f={};for(const g in p){const m=p[g].split("="),x=m[0],S=m[1].replace(/"/gm,""),b=parseFloat(S),v=isNaN(b)?S:b;f[x]=v}t[u].push(f)}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 f=u.letter??u.char??String.fromCharCode(p);f==="space"&&(f=" "),h[p]=f,i.chars[f]={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),f=parseInt(c[d].amount,10);i.chars[h[p]].kerning[h[u]]=f}return i}},Ma={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}},Pa={test(n){return typeof n=="string"&&n.match(/<font(\s|>)/)?Ma.test(j.get().parseXML(n)):!1},parse(n){return Ma.parse(j.get().parseXML(n))}},Cf=[".xml",".fnt"],_f={extension:{type:F.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}},Mf={extension:{type:F.LoadParser,priority:_e.Normal},name:"loadBitmapFont",id:"bitmap-font",test(n){return Cf.includes(Et.extname(n).toLowerCase())},async testParse(n){return zn.test(n)||Pa.test(n)},async parse(n,e,t){const i=zn.test(n)?zn.parse(n):Pa.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 f=Et.join(Et.dirname(s),p);f=Sr(f,s),o.push({src:f,data:a})}const[h,{BitmapFont:l}]=await Promise.all([t.load(o),ze(()=>import("./BitmapFont.BVQlrRID.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 j.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 Pf{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 Af={extension:{type:F.CacheParser,name:"cacheTextureArray"},test:n=>Array.isArray(n)&&n.every(e=>e instanceof U),getCacheableAssets:(n,e)=>{const t={};return n.forEach(i=>{e.forEach((s,r)=>{t[i+(r===0?"":r+1)]=s})}),t}};async function fc(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 Tf={extension:{type:F.DetectionParser,priority:1},test:async()=>fc("data:image/avif;base64,AAAAIGZ0eXBhdmlmAAAAAGF2aWZtaWYxbWlhZk1BMUIAAADybWV0YQAAAAAAAAAoaGRscgAAAAAAAAAAcGljdAAAAAAAAAAAAAAAAGxpYmF2aWYAAAAADnBpdG0AAAAAAAEAAAAeaWxvYwAAAABEAAABAAEAAAABAAABGgAAAB0AAAAoaWluZgAAAAAAAQAAABppbmZlAgAAAAABAABhdjAxQ29sb3IAAAAAamlwcnAAAABLaXBjbwAAABRpc3BlAAAAAAAAAAIAAAACAAAAEHBpeGkAAAAAAwgICAAAAAxhdjFDgQ0MAAAAABNjb2xybmNseAACAAIAAYAAAAAXaXBtYQAAAAAAAAABAAEEAQKDBAAAACVtZGF0EgAKCBgANogQEAwgMg8f8D///8WfhwB8+ErK42A="),add:async n=>[...n,"avif"],remove:async n=>n.filter(e=>e!=="avif")},Aa=["png","jpg","jpeg"],Rf={extension:{type:F.DetectionParser,priority:-1},test:()=>Promise.resolve(!0),add:async n=>[...n,...Aa],remove:async n=>n.filter(e=>!Aa.includes(e))},kf="WorkerGlobalScope"in globalThis&&globalThis instanceof globalThis.WorkerGlobalScope;function Qs(n){return kf?!1:document.createElement("video").canPlayType(n)!==""}const Ef={extension:{type:F.DetectionParser,priority:0},test:async()=>Qs("video/mp4"),add:async n=>[...n,"mp4","m4v"],remove:async n=>n.filter(e=>e!=="mp4"&&e!=="m4v")},If={extension:{type:F.DetectionParser,priority:0},test:async()=>Qs("video/ogg"),add:async n=>[...n,"ogv"],remove:async n=>n.filter(e=>e!=="ogv")},Df={extension:{type:F.DetectionParser,priority:0},test:async()=>Qs("video/webm"),add:async n=>[...n,"webm"],remove:async n=>n.filter(e=>e!=="webm")},Ff={extension:{type:F.DetectionParser,priority:0},test:async()=>fc("data:image/webp;base64,UklGRh4AAABXRUJQVlA4TBEAAAAvAAAAAAfQ//73v/+BiOh/AAA="),add:async n=>[...n,"webp"],remove:async n=>n.filter(e=>e!=="webp")},gc=class ks{constructor(){this.loadOptions={...ks.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&&at(`[Assets] "loadParser" is deprecated, use "parser" instead for ${e}`),r||at(`[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 at(`[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"?{...ks.defaultOptions,...this.loadOptions,onProgress:t}:{...ks.defaultOptions,...this.loadOptions,...t||{}},{onProgress:s,onError:r,strategy:o,retryCount:a,retryDelay:h}=i;let l=0;const c={},d=Os(e),u=Ht(e,g=>({alias:[g],src:g,data:{}})),p=u.reduce((g,m)=>g+(m.progressSize||1),0),f=u.map(async g=>{const m=Et.toAbsolute(g.src);c[g.src]||(await this._loadAssetWithRetry(m,g,{onProgress:s,onError:r,strategy:o,retryCount:a,retryDelay:h},c),l+=g.progressSize||1,s&&s(l/p))});return await Promise.all(f),d?c[u[0].src]:c}async unload(e){const i=Ht(e,s=>({alias:[s],src:s})).map(async s=>{var a,h;const r=Et.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?at("[Assets] parser should have an id"):(e[t.name]||e[t.id])&&at(`[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}}};gc.defaultOptions={onProgress:void 0,onError:void 0,strategy:"throw",retryCount:3,retryDelay:250};let Bf=gc;function Me(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 bi(n,e){const t=n.split("?")[0],i=Et.extname(t).toLowerCase();return Array.isArray(e)?e.includes(i):i===e}const Lf=".json",zf="application/json",Of={extension:{type:F.LoadParser,priority:_e.Low},name:"loadJson",id:"json",test(n){return Me(n,zf)||bi(n,Lf)},async load(n){return await(await j.get().fetch(n)).json()}},Wf=".txt",Gf="text/plain",Uf={name:"loadTxt",id:"text",extension:{type:F.LoadParser,priority:_e.Low,name:"loadTxt"},test(n){return Me(n,Gf)||bi(n,Wf)},async load(n){return await(await j.get().fetch(n)).text()}},Hf=["normal","bold","100","200","300","400","500","600","700","800","900"],Nf=[".ttf",".otf",".woff",".woff2"],Vf=["font/ttf","font/otf","font/woff","font/woff2"],$f=/^(--|-?[A-Z_])[0-9A-Z_-]*$/i;function Yf(n){const e=Et.extname(n),s=Et.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($f)){r=!1;break}let o=s.join(" ");return r||(o=`"${o.replace(/[\\"]/g,"\\$&")}"`),o}const Xf=/^[0-9A-Za-z%:/?#\[\]@!\$&'()\*\+,;=\-._~]*$/;function jf(n){return Xf.test(n)?n:encodeURI(n)}const Zf={extension:{type:F.LoadParser,priority:_e.Low},name:"loadWebFont",id:"web-font",test(n){return Me(n,Vf)||bi(n,Nf)},async load(n,e){var i,s,r;const t=j.get().getFontFaceSet();if(t){const o=[],a=((i=e.data)==null?void 0:i.family)??Yf(n),h=((r=(s=e.data)==null?void 0:s.weights)==null?void 0:r.filter(c=>Hf.includes(c)))??["normal"],l=e.data??{};for(let c=0;c<h.length;c++){const d=h[c],u=new FontFace(a,`url(${jf(n)})`,{...l,weight:d});await u.load(),t.add(u),o.push(u)}return St.has(`${a}-and-url`)?St.get(`${a}-and-url`).entries.push({url:n,faces:o}):St.set(`${a}-and-url`,{entries:[{url:n,faces:o}]}),o.length===1?o[0]:o}return at("[loadWebFont] FontFace API is not supported. Skipping loading font"),null},unload(n){const e=Array.isArray(n)?n:[n],t=e[0].family,i=St.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=>{j.get().getFontFaceSet().delete(r)}),i.entries.length===0&&St.remove(`${t}-and-url`)}};var qf=Qf,On={a:7,c:6,h:1,l:2,m:2,q:4,s:4,t:2,v:1,z:0},Kf=/([astvzqmhlc])([^astvzqmhlc]*)/ig;function Qf(n){var e=[];return n.replace(Kf,function(t,i,s){var r=i.toLowerCase();for(s=tg(s),r=="m"&&s.length>2&&(e.push([i].concat(s.splice(0,2))),r="l",i=i=="m"?"l":"L");;){if(s.length==On[r])return s.unshift(i),e.push(s);if(s.length<On[r])throw new Error("malformed path data");e.push([i].concat(s.splice(0,On[r])))}}),e}var Jf=/-?[0-9]*\.?[0-9]+(?:e[-+]?\d+)?/ig;function tg(n){var e=n.match(Jf);return e?e.map(Number):[]}const eg=cl(qf);function ig(n,e){const t=eg(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:at(`Unknown SVG path command: ${l}`)}l!=="Z"&&l!=="z"&&s===null&&(s={startX:r,startY:o},i.push(s))}return e}class Js{constructor(e=0,t=0,i=0){this.type="circle",this.x=e,this.y=t,this.radius=i}clone(){return new Js(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 et),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 io{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 io(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,f=t-this.y,g=p*p/(l*l)+f*f/(c*c),m=p*p/(d*d)+f*f/(u*u);return g>1&&m<=1}getBounds(e){return e||(e=new et),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 sg(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,f;u<0?(p=t,f=i):u>1?(p=s,f=r):(p=t+u*h,f=i+u*l);const g=n-p,m=e-f;return g*g+m*m}let ng,rg;class Oe{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(ng),i=e.getBounds(rg);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 Oe(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],f=h[(c+3)%h.length],g=sg(e,t,d,u,p,f),m=Math.sign((p-d)*(t-u)-(f-u)*(e-d));if(g<=(m<0?a:o))return!0}return!1}getBounds(e){e||(e=new et);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 Ss=(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 so{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 et),e.x=this.x,e.y=this.y,e.width=this.width,e.height=this.height,e}clone(){return new so(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,f=a-l*2,g=h-l*2,m=r+a,x=o+h;return(e>=r-c&&e<=r+d||e>=m-d&&e<=m+c)&&t>=p&&t<=p+g||(t>=o-c&&t<=o+d||t>=x-d&&t<=x+c)&&e>=u&&e<=u+f?!0:e<u&&t<p&&Ss(e,t,u,p,l,d,c)||e>m-l&&t<p&&Ss(e,t,m-l,p,l,d,c)||e>m-l&&t>x-l&&Ss(e,t,m-l,x-l,l,d,c)||e<u&&t>x-l&&Ss(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 mc={};function og(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 mc[i]||ag(n,e,i,t)}function ag(n,e,t,i){const s={};let r=0;for(let a=0;a<i;a++){const h=a<e?n[a]:U.EMPTY.source;s[r++]=h.source,s[r++]=h.style}const o=new Ui(s);return mc[t]=o,o}class Ta{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 Ra(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 hg={normal:"normal-npm",add:"add-npm",screen:"screen-npm"};var lg=(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))(lg||{});function Ws(n,e){return e.alphaMode==="no-premultiply-alpha"&&hg[n]||n}const cg=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join(`
|
|
25
|
+
`);function dg(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 ug(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=cg.replace(/%forloop%/gi,dg(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 Ke=null;function pg(){var e;if(Ke)return Ke;const n=Xl();return Ke=n.getParameter(n.MAX_TEXTURE_IMAGE_UNITS),Ke=ug(Ke,n),(e=n.getExtension("WEBGL_lose_context"))==null||e.loseContext(),Ke}class fg{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 gg{constructor(){this.renderPipeId="batch",this.action="startBatch",this.start=0,this.size=0,this.textures=new fg,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 Hi=[];let Gs=0;ns.register({clear:()=>{if(Hi.length>0)for(const n of Hi)n&&n.destroy();Hi.length=0,Gs=0}});function ka(){return Gs>0?Hi[--Gs]:new gg}function Ea(n){n.elements=null,Hi[Gs++]=n}let Ti=0;const yc=class xc{constructor(e){this.uid=ut("batcher"),this.dirty=!0,this.batchIndex=0,this.batches=[],this._elements=[],e={...xc.defaultOptions,...e},e.maxTextures||(V("v8.8.0","maxTextures is a required option for Batcher now, please pass it in the options"),e.maxTextures=pg());const{maxTextures:t,attributesInitialSize:i,indicesInitialSize:s}=e;this.attributeBuffer=new Ta(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++)Ea(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=ka(),s=i.textures;s.clear();const r=t[this.elementStart];let o=Ws(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",f=[];const g=this.maxTextures;for(let m=this.elementStart;m<this.elementSize;++m){const x=t[m];t[m]=null;const b=x.texture._source,v=Ws(x.blendMode,b),M=o!==v||a!==x.topology;if(b._batchTick===Ti&&!M){x._textureId=b._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,f.push(x);continue}b._batchTick=Ti,(s.count>=g||M)&&(this._finishBatch(i,u,d-u,s,o,a,e,p,f),p="renderBatch",u=d,o=v,a=x.topology,i=ka(),s=i.textures,s.clear(),f=[],++Ti),x._textureId=b._textureBindLocation=s.count,s.ids[b.uid]=s.count,s.textures[s.count++]=b,x._batch=i,f.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,f),u=d,++Ti),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,++Ti,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 Ta(t);Ra(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 Ra(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++)Ea(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}}};yc.defaultOptions={maxTextures:null,attributesInitialSize:4,indicesInitialSize:6};let mg=yc;var gt=(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))(gt||{});class xe 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=ut("buffer"),this._resourceType="buffer",this._resourceId=ut("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>.STATIC)}set static(e){e?this.descriptor.usage|=gt.STATIC:this.descriptor.usage&=~gt.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=ut("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 Sc(n,e){if(!(n instanceof xe)){let t=e?gt.INDEX:gt.VERTEX;n instanceof Array&&(e?(n=new Uint32Array(n),t=gt.INDEX|gt.COPY_DST):(n=new Float32Array(n),t=gt.VERTEX|gt.COPY_DST)),n=new xe({data:n,label:e?"index-mesh-buffer":"vertex-mesh-buffer",usage:t})}return n}function yg(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],f=s[u+1];p>a&&(a=p),f>h&&(h=f),p<r&&(r=p),f<o&&(o=f)}return t.minX=r,t.minY=o,t.maxX=a,t.maxY=h,t}function xg(n){return(n instanceof xe||Array.isArray(n)||n.BYTES_PER_ELEMENT)&&(n={buffer:n}),n.buffer=Sc(n.buffer,!1),n}class Qi extends Jt{constructor(e={}){super(),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=ut("geometry"),this._layoutKey=0,this.instanceCount=1,this._bounds=new Ot,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=xg(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=Sc(e,!0),this.buffers.push(this.indexBuffer)}get bounds(){return this._boundsDirty?(this._boundsDirty=!1,yg(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 Sg=new Float32Array(1),bg=new Uint32Array(1);class vg extends Qi{constructor(){const t=new xe({data:Sg,label:"attribute-batch-buffer",usage:gt.VERTEX|gt.COPY_DST,shrinkToFit:!1}),i=new xe({data:bg,label:"index-batch-buffer",usage:gt.INDEX|gt.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 Ia(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 at(`${i} placement hook does not exist in shader`)}}const wg=/\{\{(.*?)\}\}/g;function Da(n){var i;const e={};return(((i=n.match(wg))==null?void 0:i.map(s=>s.replace(/[{()}]/g,"")))??[]).forEach(s=>{e[s]=[]}),e}function Fa(n,e){let t;const i=/@in\s+([^;]+);/g;for(;(t=i.exec(n))!==null;)e.push(t[1])}function Ba(n,e,t=!1){const i=[];Fa(e,i),n.forEach(a=>{a.header&&Fa(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 La(n,e){let t;const i=/@out\s+([^;]+);/g;for(;(t=i.exec(n))!==null;)e.push(t[1])}function Cg(n){const t=/\b(\w+)\s*:/g.exec(n);return t?t[1]:""}function _g(n){const e=/@.*?\s+/g;return n.replace(e,"")}function Mg(n,e){const t=[];La(e,t),n.forEach(h=>{h.header&&La(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 ${_g(h)};`).join(`
|
|
31
|
+
`),o=`return VSOutput(
|
|
32
|
+
${t.sort().map(h=>` ${Cg(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 za(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 ye=Object.create(null),Wn=new Map;let Pg=0;function Ag({template:n,bits:e}){const t=bc(n,e);if(ye[t])return ye[t];const{vertex:i,fragment:s}=Rg(n,e);return ye[t]=vc(i,s,e),ye[t]}function Tg({template:n,bits:e}){const t=bc(n,e);return ye[t]||(ye[t]=vc(n.vertex,n.fragment,e)),ye[t]}function Rg(n,e){const t=e.map(o=>o.vertex).filter(o=>!!o),i=e.map(o=>o.fragment).filter(o=>!!o);let s=Ba(t,n.vertex,!0);s=Mg(t,s);const r=Ba(i,n.fragment,!0);return{vertex:s,fragment:r}}function bc(n,e){return e.map(t=>(Wn.has(t)||Wn.set(t,Pg++),Wn.get(t))).sort((t,i)=>t-i).join("-")+n.vertex+n.fragment}function vc(n,e,t){const i=Da(n),s=Da(e);return t.forEach(r=>{Ia(r.vertex,i,r.name),Ia(r.fragment,s,r.name)}),{vertex:za(n,i),fragment:za(e,s)}}const kg=`
|
|
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
|
+
`,Eg=`
|
|
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
|
+
`,Ig=`
|
|
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
|
+
`,Dg=`
|
|
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
|
+
`,Fg={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
|
+
`}},Bg={name:"global-uniforms-bit",vertex:{header:`
|
|
177
|
+
uniform mat3 uProjectionMatrix;
|
|
178
|
+
uniform mat3 uWorldTransformMatrix;
|
|
179
|
+
uniform vec4 uWorldColorAlpha;
|
|
180
|
+
uniform vec2 uResolution;
|
|
181
|
+
`}};function wc({bits:n,name:e}){const t=Ag({template:{fragment:Eg,vertex:kg},bits:[Fg,...n]});return be.from({name:e,vertex:{source:t.vertex,entryPoint:"main"},fragment:{source:t.fragment,entryPoint:"main"}})}function Cc({bits:n,name:e}){return new pi({name:e,...Tg({template:{vertex:Ig,fragment:Dg},bits:[Bg,...n]})})}const Lg={name:"color-bit",vertex:{header:`
|
|
182
|
+
@in aColor: vec4<f32>;
|
|
183
|
+
`,main:`
|
|
184
|
+
vColor *= vec4<f32>(aColor.rgb * aColor.a, aColor.a);
|
|
185
|
+
`}},zg={name:"color-bit",vertex:{header:`
|
|
186
|
+
in vec4 aColor;
|
|
187
|
+
`,main:`
|
|
188
|
+
vColor *= vec4(aColor.rgb * aColor.a, aColor.a);
|
|
189
|
+
`}},Gn={};function Og(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 Wg(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 Gg(n){return Gn[n]||(Gn[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
|
+
${Og(n)}
|
|
205
|
+
`,main:`
|
|
206
|
+
var uvDx = dpdx(vUV);
|
|
207
|
+
var uvDy = dpdy(vUV);
|
|
208
|
+
|
|
209
|
+
${Wg(n)}
|
|
210
|
+
`}}),Gn[n]}const Un={};function Ug(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 Hg(n){return Un[n]||(Un[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
|
+
${Ug(n)}
|
|
230
|
+
`}}),Un[n]}const _c={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
|
+
`}},Mc={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
|
+
`}},Oa={};function Ng(n){let e=Oa[n];if(e)return e;const t=new Int32Array(n);for(let i=0;i<n;i++)t[i]=i;return e=Oa[n]=new fi({uTextures:{value:t,type:"i32",size:n}},{isStatic:!0}),e}class Wa extends Ne{constructor(e){const t=Cc({name:"batch",bits:[zg,Hg(e),Mc]}),i=wc({name:"batch",bits:[Lg,Gg(e),_c]});super({glProgram:t,gpuProgram:i,resources:{batchSamplers:Ng(e)}}),this.maxTextures=e}}let Ri=null;const Pc=class Ac extends mg{constructor(e){super(e),this.geometry=new vg,this.name=Ac.extension.name,this.vertexSize=6,Ri??(Ri=new Wa(e.maxTextures)),this.shader=Ri}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:f,uvs:g}=e,m=e.color,x=e.attributeOffset,S=x+e.attributeSize;for(let b=x;b<S;b++){const v=b*2,M=f[v],_=f[v+1];t[s++]=h*M+c*_+u,t[s++]=d*_+l*M+p,t[s++]=g[v],t[s++]=g[v+1],i[s++]=m,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,f=e.bounds,g=f.maxX,m=f.minX,x=f.maxY,S=f.minY,b=o.uvs,v=e.color,M=r<<16|e.roundPixels&65535;t[s+0]=h*m+c*S+u,t[s+1]=d*S+l*m+p,t[s+2]=b.x0,t[s+3]=b.y0,i[s+4]=v,i[s+5]=M,t[s+6]=h*g+c*S+u,t[s+7]=d*S+l*g+p,t[s+8]=b.x1,t[s+9]=b.y1,i[s+10]=v,i[s+11]=M,t[s+12]=h*g+c*x+u,t[s+13]=d*x+l*g+p,t[s+14]=b.x2,t[s+15]=b.y2,i[s+16]=v,i[s+17]=M,t[s+18]=h*m+c*x+u,t[s+19]=d*x+l*m+p,t[s+20]=b.x3,t[s+21]=b.y3,i[s+22]=v,i[s+23]=M}_updateMaxTextures(e){this.shader.maxTextures!==e&&(Ri=new Wa(e),this.shader=Ri)}destroy(){this.shader=null,super.destroy()}};Pc.extension={type:[F.Batcher],name:"default"};let Vg=Pc;class vi{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 $g(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,f=a.ty;for(;h<o;){const g=n[t],m=n[t+1];i[s]=l*g+d*m+p,i[s+1]=c*g+u*m+f,s+=r,t+=e,h++}}function Yg(n,e,t,i){let s=0;for(e*=t;s<i;)n[e]=0,n[e+1]=0,e+=t,s++}function Tc(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],f=n[d+1];n[d]=r*p+a*f+l,n[d+1]=o*p+h*f+c,d+=i}}const Xg=new H;class no{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?Kr(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)||Xg}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 Ji={extension:{type:F.ShapeBuilder,name:"circle"},build(n,e){let t,i,s,r,o,a;if(n.type==="circle"){const v=n;if(o=a=v.radius,o<=0)return!1;t=v.x,i=v.y,s=r=0}else if(n.type==="ellipse"){const v=n;if(o=v.halfWidth,a=v.halfHeight,o<=0||a<=0)return!1;t=v.x,i=v.y,s=r=0}else{const v=n,M=v.width/2,_=v.height/2;t=v.x+M,i=v.y+_,o=a=Math.max(0,Math.min(v.radius,Math.min(M,_))),s=M-o,r=_-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,f=s+o,g=r,m=t+f,x=t-f,S=i+g;if(e[c++]=m,e[c++]=S,e[--d]=S,e[--d]=x,r){const v=i-g;e[u++]=x,e[u++]=v,e[--p]=v,e[--p]=m}for(let v=1;v<h;v++){const M=Math.PI/2*(v/h),_=s+Math.cos(M)*o,w=r+Math.sin(M)*a,P=t+_,A=t-_,T=i+w,R=i-w;e[c++]=P,e[c++]=T,e[--d]=T,e[--d]=A,e[u++]=A,e[u++]=R,e[--p]=R,e[--p]=P}f=s,g=r+a,m=t+f,x=t-f,S=i+g;const b=i-g;return e[c++]=m,e[c++]=S,e[--p]=b,e[--p]=m,s&&(e[c++]=x,e[c++]=S,e[--p]=b,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}},jg={...Ji,extension:{...Ji.extension,name:"ellipse"}},Zg={...Ji,extension:{...Ji.extension,name:"roundedRectangle"}},Rc=1e-4,Ga=1e-4;function qg(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 f=h+u,g=l+p,m=c+u,x=d+p;return a.push(f,g),a.push(m,x),2}function Pe(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,f=Math.abs(p),g=Math.sqrt(h*h+l*l),m=(15*f*Math.sqrt(g)/Math.PI>>0)+1,x=p/m;if(u+=x,a){o.push(n,e),o.push(t,i);for(let S=1,b=u;S<m;S++,b+=x)o.push(n,e),o.push(n+Math.sin(b)*g,e+Math.cos(b)*g);o.push(n,e),o.push(s,r)}else{o.push(t,i),o.push(n,e);for(let S=1,b=u;S<m;S++,b+=x)o.push(n+Math.sin(b)*g,e+Math.cos(b)*g),o.push(n,e);o.push(s,r),o.push(n,e)}return m*2}function Kg(n,e,t,i,s,r){const o=Rc;if(n.length===0)return;const a=e;let h=a.alignment;if(e.alignment!==.5){let L=qg(n);h=(h-.5)*L+.5}const l=new tt(n[0],n[1]),c=new tt(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 L=(l.x+c.x)*.5,Y=(c.y+l.y)*.5;n.unshift(L,Y),n.push(L,Y)}const p=s,f=n.length/2;let g=n.length;const m=p.length/2,x=a.width/2,S=x*x,b=a.miterLimit*a.miterLimit;let v=n[0],M=n[1],_=n[2],w=n[3],P=0,A=0,T=-(M-w),R=v-_,k=0,I=0,B=Math.sqrt(T*T+R*R);T/=B,R/=B,T*=x,R*=x;const N=h,E=(1-N)*2,D=N*2;d||(a.cap==="round"?g+=Pe(v-T*(E-D)*.5,M-R*(E-D)*.5,v-T*E,M-R*E,v+T*D,M+R*D,p,!0)+2:a.cap==="square"&&(g+=Ua(v,M,T,R,E,D,!0,p))),p.push(v-T*E,M-R*E),p.push(v+T*D,M+R*D);for(let L=1;L<f-1;++L){v=n[(L-1)*2],M=n[(L-1)*2+1],_=n[L*2],w=n[L*2+1],P=n[(L+1)*2],A=n[(L+1)*2+1],T=-(M-w),R=v-_,B=Math.sqrt(T*T+R*R),T/=B,R/=B,T*=x,R*=x,k=-(w-A),I=_-P,B=Math.sqrt(k*k+I*I),k/=B,I/=B,k*=x,I*=x;const Y=_-v,$=M-w,st=_-P,vt=A-w,mt=Y*st+$*vt,_t=$*st-vt*Y,Tt=_t<0;if(Math.abs(_t)<.001*Math.abs(mt)){p.push(_-T*E,w-R*E),p.push(_+T*D,w+R*D),mt>=0&&(a.join==="round"?g+=Pe(_,w,_-T*E,w-R*E,_-k*E,w-I*E,p,!1)+4:g+=2,p.push(_-k*D,w-I*D),p.push(_+k*E,w+I*E));continue}const fe=(-T+v)*(-R+w)-(-T+_)*(-R+M),Xe=(-k+P)*(-I+w)-(-k+_)*(-I+A),wt=(Y*Xe-st*fe)/_t,ee=(vt*fe-$*Xe)/_t,je=(wt-_)*(wt-_)+(ee-w)*(ee-w),$t=_+(wt-_)*E,Lt=w+(ee-w)*E,ie=_-(wt-_)*D,Yt=w-(ee-w)*D,Ci=Math.min(Y*Y+$*$,st*st+vt*vt),Lo=Tt?E:D,Xd=Ci+Lo*Lo*S;je<=Xd?a.join==="bevel"||je/S>b?(Tt?(p.push($t,Lt),p.push(_+T*D,w+R*D),p.push($t,Lt),p.push(_+k*D,w+I*D)):(p.push(_-T*E,w-R*E),p.push(ie,Yt),p.push(_-k*E,w-I*E),p.push(ie,Yt)),g+=2):a.join==="round"?Tt?(p.push($t,Lt),p.push(_+T*D,w+R*D),g+=Pe(_,w,_+T*D,w+R*D,_+k*D,w+I*D,p,!0)+4,p.push($t,Lt),p.push(_+k*D,w+I*D)):(p.push(_-T*E,w-R*E),p.push(ie,Yt),g+=Pe(_,w,_-T*E,w-R*E,_-k*E,w-I*E,p,!1)+4,p.push(_-k*E,w-I*E),p.push(ie,Yt)):(p.push($t,Lt),p.push(ie,Yt)):(p.push(_-T*E,w-R*E),p.push(_+T*D,w+R*D),a.join==="round"?Tt?g+=Pe(_,w,_+T*D,w+R*D,_+k*D,w+I*D,p,!0)+2:g+=Pe(_,w,_-T*E,w-R*E,_-k*E,w-I*E,p,!1)+2:a.join==="miter"&&je/S<=b&&(Tt?(p.push(ie,Yt),p.push(ie,Yt)):(p.push($t,Lt),p.push($t,Lt)),g+=2),p.push(_-k*E,w-I*E),p.push(_+k*D,w+I*D),g+=2)}v=n[(f-2)*2],M=n[(f-2)*2+1],_=n[(f-1)*2],w=n[(f-1)*2+1],T=-(M-w),R=v-_,B=Math.sqrt(T*T+R*R),T/=B,R/=B,T*=x,R*=x,p.push(_-T*E,w-R*E),p.push(_+T*D,w+R*D),d||(a.cap==="round"?g+=Pe(_-T*(E-D)*.5,w-R*(E-D)*.5,_-T*E,w-R*E,_+T*D,w+R*D,p,!1)+2:a.cap==="square"&&(g+=Ua(_,w,T,R,E,D,!1,p)));const q=Ga*Ga;for(let L=m;L<g+m-2;++L)v=p[L*2],M=p[L*2+1],_=p[(L+1)*2],w=p[(L+1)*2+1],P=p[(L+2)*2],A=p[(L+2)*2+1],!(Math.abs(v*(w-A)+_*(A-M)+P*(M-w))<q)&&r.push(L,L+1,L+2)}function Qg(n,e,t,i){const s=Rc;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 kc(n,e,t,i,s,r,o){const a=mf(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 Jg=[],tm={extension:{type:F.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){kc(n,Jg,e,t,i,s,r)}},em={extension:{type:F.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}},im={extension:{type:F.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}},Ha=[{offset:0,color:"white"},{offset:1,color:"black"}],ro=class Tr{constructor(...e){this.uid=ut("fillGradient"),this._tick=0,this.type="linear",this.colorStops=[];let t=sm(e);t={...t.type==="radial"?Tr.defaultRadialOptions:Tr.defaultLinearOptions,...bl(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:ht.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 m=e;e=i,i=m,r*=-1}if(o<0){const m=t;t=s,s=m,o*=-1}}const h=this.colorStops.length?this.colorStops:Ha,l=this._textureSize,{canvas:c,context:d}=Va(l,1),u=a?d.createLinearGradient(this._textureSize,0,0,0):d.createLinearGradient(0,0,this._textureSize,0);Na(u,h),d.fillStyle=u,d.fillRect(0,0,l,1),this.texture=new U({source:new ui({resource:c,addressMode:this._wrapMode})});const p=Math.sqrt(r*r+o*o),f=Math.atan2(o,r),g=new H;g.scale(p/l,1),g.rotate(f),g.translate(e,t),this.textureSpace==="local"&&g.scale(l,l),this.transform=g}buildGradient(){this.texture||this._tick++,this.type==="linear"?this.buildLinearGradient():this.buildRadialGradient()}buildRadialGradient(){if(this.texture)return;const e=this.colorStops.length?this.colorStops:Ha,t=this._textureSize,{canvas:i,context:s}=Va(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),f=(r-d)*p,g=(o-u)*p,m=s.createRadialGradient(f,g,l*p,(a-d)*p,(h-u)*p,c*p);Na(m,e),s.fillStyle=e[e.length-1].color,s.fillRect(0,0,t,t),s.fillStyle=m,s.translate(f,g),s.rotate(this.rotation),s.scale(1,this.scale),s.translate(-f,-g),s.fillRect(0,0,t,t),this.texture=new U({source:new ui({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}`}};ro.defaultLinearOptions={start:{x:0,y:0},end:{x:0,y:1},colorStops:[],textureSpace:"local",type:"linear",textureSize:256,wrapMode:"clamp-to-edge"};ro.defaultRadialOptions={center:{x:.5,y:.5},innerRadius:0,outerRadius:.5,colorStops:[],scale:1,textureSpace:"local",type:"radial",textureSize:256,wrapMode:"clamp-to-edge"};let Vt=ro;function Na(n,e){for(let t=0;t<e.length;t++){const i=e[t];n.addColorStop(i.offset,i.color)}}function Va(n,e){const t=j.get().createCanvas(n,e),i=t.getContext("2d");return{canvas:t,context:i}}function sm(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]??Vt.defaultLinearOptions.textureSize}),e}const nm=new H,rm=new et;function om(n,e,t,i){const s=e.matrix?n.copyFrom(e.matrix).invert():n.identity();if(e.textureSpace==="local"){const o=t.getBounds(rm);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,f=s.b,g=s.c,m=s.d;s.a*=l,s.b*=l,s.c*=c,s.d*=c,s.tx=d*p+u*g+s.tx,s.ty=d*f+u*m+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 Vt)&&r.addressMode==="clamp-to-edge"&&(r.addressMode="repeat",r.update()),i&&s.append(nm.copyFrom(i).invert()),s}const tn={};Q.handleByMap(F.ShapeBuilder,tn);Q.add(em,tm,im,Ji,jg,Zg);const am=new et,hm=new H;function lm(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")cm(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&&$a(l.shapePath,h,!0,i,t),l&&(a.shapePrimitives[a.shapePrimitives.length-1].holes=l.shapePath.shapePrimitives),$a(a,h,o,i,t)}}}function cm(n,e,t){const i=[],s=tn.rectangle,r=am;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&&Tc(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 f=Ft.get(no);f.indexOffset=c,f.indexSize=l.length-c,f.attributeOffset=d,f.attributeSize=a.length/2-d,f.baseColor=n.style,f.alpha=n.alpha,f.texture=u,f.geometryData=t,e.push(f)}function $a(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=tn[h.type];if(!u.build(h,d))return;const p=a.length,f=r.length/2;let g="triangle-list";if(l&&Tc(d,l),t){const b=h.closePath??!0,v=e;v.pixelLine?(Qg(d,b,r,a),g="line-list"):Kg(d,v,!1,b,r,a)}else if(c){const b=[],v=d.slice();dm(c).forEach(_=>{b.push(v.length/2),v.push(..._)}),kc(v,b,r,2,f,a,p)}else u.triangulate(d,r,2,f,a,p);const m=o.length/2,x=e.texture;if(x!==U.WHITE){const b=om(hm,e,h,l);$g(r,2,f,o,m,2,r.length/2-f,b)}else Yg(o,m,2,r.length/2-f);const S=Ft.get(no);S.indexOffset=p,S.indexSize=a.length-p,S.attributeOffset=f,S.attributeSize=r.length/2-f,S.baseColor=e.color,S.alpha=e.alpha,S.texture=x,S.geometryData=s,S.topology=g,i.push(S)})}function dm(n){const e=[];for(let t=0;t<n.length;t++){const i=n[t].shape,s=[];tn[i.type].build(i,s)&&e.push(s)}return e}class um{constructor(){this.batches=[],this.geometryData={vertices:[],uvs:[],indices:[]}}reset(){this.batches&&this.batches.forEach(e=>{Ft.return(e)}),this.graphicsData&&Ft.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 pm{constructor(){this.instructions=new Qr}init(e){const t=e.maxTextures;this.batcher?this.batcher._updateMaxTextures(t):this.batcher=new Vg({maxTextures:t}),this.instructions.reset()}get geometry(){return V(Fu,"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 oo=class Rr{constructor(e){this._renderer=e,this._managedContexts=new vi({renderer:e,type:"resource",name:"graphicsContext"})}init(e){Rr.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??Rr.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(),lm(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=Ft.get(pm,{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=og(u.textures.textures,u.textures.count,this._renderer.limits.maxBatchableTextures)}return t}_initContext(e){const t=new um;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};oo.extension={type:[F.WebGLSystem,F.WebGPUSystem],name:"graphicsContext"};oo.defaultOptions={bezierSmoothness:.5};let ao=oo;const fm=8,bs=11920929e-14,gm=1;function Ec(n,e,t,i,s,r,o,a,h,l){const d=Math.min(.99,Math.max(0,l??ao.defaultOptions.bezierSmoothness));let u=(gm-d)/1;return u*=u,mm(e,t,i,s,r,o,a,h,n,u),n}function mm(n,e,t,i,s,r,o,a,h,l){kr(n,e,t,i,s,r,o,a,h,l,0),h.push(o,a)}function kr(n,e,t,i,s,r,o,a,h,l,c){if(c>fm)return;const d=(n+t)/2,u=(e+i)/2,p=(t+s)/2,f=(i+r)/2,g=(s+o)/2,m=(r+a)/2,x=(d+p)/2,S=(u+f)/2,b=(p+g)/2,v=(f+m)/2,M=(x+b)/2,_=(S+v)/2;if(c>0){let w=o-n,P=a-e;const A=Math.abs((t-o)*P-(i-a)*w),T=Math.abs((s-o)*P-(r-a)*w);if(A>bs&&T>bs){if((A+T)*(A+T)<=l*(w*w+P*P)){h.push(M,_);return}}else if(A>bs){if(A*A<=l*(w*w+P*P)){h.push(M,_);return}}else if(T>bs){if(T*T<=l*(w*w+P*P)){h.push(M,_);return}}else if(w=M-(n+o)/2,P=_-(e+a)/2,w*w+P*P<=l){h.push(M,_);return}}kr(n,e,d,u,x,S,M,_,h,l,c+1),kr(M,_,b,v,g,m,o,a,h,l,c+1)}const ym=8,xm=11920929e-14,Sm=1;function bm(n,e,t,i,s,r,o,a){const l=Math.min(.99,Math.max(0,a??ao.defaultOptions.bezierSmoothness));let c=(Sm-l)/1;return c*=c,vm(e,t,i,s,r,o,n,c),n}function vm(n,e,t,i,s,r,o,a){Er(o,n,e,t,i,s,r,a,0),o.push(s,r)}function Er(n,e,t,i,s,r,o,a,h){if(h>ym)return;const l=(e+i)/2,c=(t+s)/2,d=(i+r)/2,u=(s+o)/2,p=(l+d)/2,f=(c+u)/2;let g=r-e,m=o-t;const x=Math.abs((i-r)*m-(s-o)*g);if(x>xm){if(x*x<=a*(g*g+m*m)){n.push(p,f);return}}else if(g=p-(e+r)/2,m=f-(t+o)/2,g*g+m*m<=a){n.push(p,f);return}Er(n,e,t,l,c,p,f,a,h+1),Er(n,p,f,d,u,r,o,a,h+1)}function Ic(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),f=e+u*i,g=t+p*i;n.push(f,g),c+=l}}function wm(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,f=c*c+d*d,g=h*c+l*d,m=r*Math.sqrt(p)/u,x=r*Math.sqrt(f)/u,S=m*g/p,b=x*g/f,v=m*d+x*l,M=m*c+x*h,_=l*(x+S),w=h*(x+S),P=d*(m+b),A=c*(m+b),T=Math.atan2(w-M,_-v),R=Math.atan2(A-M,P-v);Ic(n,v+e,M+t,r,T,R,l*c>d*h)}const Ni=Math.PI*2,Hn={centerX:0,centerY:0,ang1:0,ang2:0},Nn=({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 Cm(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)},_m=(n,e,t,i,s,r,o,a,h,l,c,d,u)=>{const p=Math.pow(s,2),f=Math.pow(r,2),g=Math.pow(c,2),m=Math.pow(d,2);let x=p*f-p*m-f*g;x<0&&(x=0),x/=p*m+f*g,x=Math.sqrt(x)*(o===a?-1:1);const S=x*s/r*d,b=x*-r/s*c,v=l*S-h*b+(n+t)/2,M=h*S+l*b+(e+i)/2,_=(c-S)/s,w=(d-b)/r,P=(-c-S)/s,A=(-d-b)/r,T=Ya(1,0,_,w);let R=Ya(_,w,P,A);a===0&&R>0&&(R-=Ni),a===1&&R<0&&(R+=Ni),u.centerX=v,u.centerY=M,u.ang1=T,u.ang2=R};function Mm(n,e,t,i,s,r,o,a=0,h=0,l=0){if(r===0||o===0)return;const c=Math.sin(a*Ni/360),d=Math.cos(a*Ni/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 f=Math.pow(u,2)/Math.pow(r,2)+Math.pow(p,2)/Math.pow(o,2);f>1&&(r*=Math.sqrt(f),o*=Math.sqrt(f)),_m(e,t,i,s,r,o,h,l,c,d,u,p,Hn);let{ang1:g,ang2:m}=Hn;const{centerX:x,centerY:S}=Hn;let b=Math.abs(m)/(Ni/4);Math.abs(1-b)<1e-7&&(b=1);const v=Math.max(Math.ceil(b),1);m/=v;let M=n[n.length-2],_=n[n.length-1];const w={x:0,y:0};for(let P=0;P<v;P++){const A=Cm(g,m),{x:T,y:R}=Nn(A[0],r,o,d,c,x,S,w),{x:k,y:I}=Nn(A[1],r,o,d,c,x,S,w),{x:B,y:N}=Nn(A[2],r,o,d,c,x,S,w);Ec(n,M,_,T,R,k,I,B,N),M=B,_=N,g+=m}}function Pm(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,f=!1;c.nx*d.nx-c.ny*-d.ny<0?u<0?u=Math.PI+u:(u=Math.PI-u,p=-1,f=!0):u>0&&(p=-1,f=!0);const g=u/2;let m,x=Math.abs(Math.cos(g)*h/Math.sin(g));x>Math.min(c.len/2,d.len/2)?(x=Math.min(c.len/2,d.len/2),m=Math.abs(x*Math.sin(g)/Math.cos(g))):m=h;const S=a.x+d.nx*x+-d.ny*m*p,b=a.y+d.ny*x+d.nx*m*p,v=Math.atan2(c.ny,c.nx)+Math.PI/2*p,M=Math.atan2(d.ny,d.nx)-Math.PI/2*p;o===0&&n.moveTo(S+Math.cos(v)*m,b+Math.sin(v)*m),n.arc(S,b,m,v,M,f),r=a}}function Am(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 m=Math.min(u/2,l);p=r(h,c,m/u)}const f=s(d,h);let g;if(f<1e-4)g=h;else{const m=Math.min(f/2,l);g=r(h,d,m/f)}a===0?n.moveTo(p.x,p.y):n.lineTo(p.x,p.y),n.quadraticCurveTo(h.x,h.y,g.x,g.y,i)}}const Tm=new et;class Rm{constructor(e){this.shapePrimitives=[],this._currentPoly=null,this._bounds=new Ot,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 Ic(a,e,t,i,s,r,o),this}arcTo(e,t,i,s,r){this._ensurePoly();const o=this._currentPoly.points;return wm(o,e,t,i,s,r),this}arcToSvg(e,t,i,s,r,o,a){const h=this._currentPoly.points;return Mm(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 Ec(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 bm(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 et(e,t,i,s),r),this}circle(e,t,i,s){return this.drawShape(new Js(e,t,i),s),this}poly(e,t,i){const s=new Oe(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,f=e+i*Math.cos(p),g=t+i*Math.sin(p),m=p+Math.PI+d,x=p-Math.PI-d,S=f+r*Math.cos(m),b=g+r*Math.sin(m),v=f+r*Math.cos(x),M=g+r*Math.sin(x);u===0?this.moveTo(S,b):this.lineTo(S,b),this.quadraticCurveTo(f,g,v,M,a)}return this.closePath()}roundShape(e,t,i=!1,s){return e.length<3?this:(i?Am(this,e,t,s):Pm(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 io(e,t,i,s),r),this}roundRect(e,t,i,s,r,o){return this.drawShape(new so(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 Oe,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 Oe,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(Tm);s.transform?e.addRect(r,s.transform):e.addRect(r)}return e}}class ce{constructor(e,t=!1){this.instructions=[],this.uid=ut("graphicsPath"),this._dirty=!0,this.checkForHoles=t,typeof e=="string"?ig(e,this):this.instructions=(e==null?void 0:e.slice())??[]}get shapePath(){return this._shapePath||(this._shapePath=new Rm(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(tt.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(tt.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,f=u*c+h;d.push(e+p*Math.cos(f),t+p*Math.sin(f))}return this.poly(d,!0,a),this}clone(e=!1){const t=new ce;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,f=0,g=0;for(let m=0;m<this.instructions.length;m++){const x=this.instructions[m],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],f=S[0],g=S[1],S[0]=t*f+s*g,S[1]=i*f+r*g,S[5]=t*h+s*l+o,S[6]=i*h+r*l+a;break;case"circle":S[4]=ki(S[3],e);break;case"rect":S[4]=ki(S[4],e);break;case"ellipse":S[8]=ki(S[8],e);break;case"roundRect":S[5]=ki(S[5],e);break;case"addPath":S[0].transform(e);break;case"poly":S[2]=ki(S[2],e);break;default:at("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 ki(n,e){return n?n.prepend(e):e.clone()}function ct(n,e,t){const i=n.getAttribute(e);return i?Number(i):t}function km(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]=Em(o);break;case"radialgradient":e.defs[o.id]=Im();break}}}}function Em(n){const e=ct(n,"x1",0),t=ct(n,"y1",0),i=ct(n,"x2",1),s=ct(n,"y2",0),r=n.getAttribute("gradientUnits")||"objectBoundingBox",o=new Vt(e,t,i,s,r==="objectBoundingBox"?"local":"global");for(let a=0;a<n.children.length;a++){const h=n.children[a],l=ct(h,"offset",0),c=ht.shared.setValue(h.getAttribute("stop-color")).toNumber();o.addColorStop(l,c)}return o}function Im(n){return at("[SVG Parser] Radial gradients are not yet supported"),new Vt(0,0,1,0)}function Xa(n){const e=n.match(/url\s*\(\s*['"]?\s*#([^'"\s)]+)\s*['"]?\s*\)/i);return e?e[1]:""}const ja={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 Dc(n,e){const t=n.getAttribute("style"),i={},s={},r={strokeStyle:i,fillStyle:s,useFill:!1,useStroke:!1};for(const o in ja){const a=n.getAttribute(o);a&&Za(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(":");ja[l]&&Za(e,r,l,c.trim())}}return{strokeStyle:r.useStroke?i:null,fillStyle:r.useFill?s:null,useFill:r.useFill,useStroke:r.useStroke}}function Za(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=ht.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=ht.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 Dm(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 Fm(n){return n.split(/(?=[Mm])/).filter(i=>i.trim().length>0)}function Bm(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 qa(n,e){const t=new ce(n,!1);for(const i of t.instructions)e.instructions.push(i)}function Lm(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 ce};km(n,t);const i=n.children,{fillStyle:s,strokeStyle:r}=Dc(n,t);for(let o=0;o<i.length;o++){const a=i[o];a.nodeName.toLowerCase()!=="defs"&&Fc(a,t,s,r)}return e}function Fc(n,e,t,i){const s=n.children,{fillStyle:r,strokeStyle:o}=Dc(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,f,g,m,x,S,b,v,M,_,w,P;switch(n.nodeName.toLowerCase()){case"path":{M=n.getAttribute("d");const A=n.getAttribute("fill-rule"),T=Fm(M),R=A==="evenodd",k=T.length>1;if(R&&k){const B=T.map(E=>({path:E,area:Bm(E)}));if(B.sort((E,D)=>D.area-E.area),T.length>3||!Dm(B))for(let E=0;E<B.length;E++){const D=B[E],q=E===0;e.context.beginPath();const L=new ce(void 0,!0);qa(D.path,L),e.context.path(L),q?(t&&e.context.fill(t),i&&e.context.stroke(i)):e.context.cut()}else for(let E=0;E<B.length;E++){const D=B[E],q=E%2===1;e.context.beginPath();const L=new ce(void 0,!0);qa(D.path,L),e.context.path(L),q?e.context.cut():(t&&e.context.fill(t),i&&e.context.stroke(i))}}else{const B=A?A==="evenodd":!0;_=new ce(M,B),e.context.path(_),t&&e.context.fill(t),i&&e.context.stroke(i)}break}case"circle":f=ct(n,"cx",0),g=ct(n,"cy",0),m=ct(n,"r",0),e.context.ellipse(f,g,m,m),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"rect":h=ct(n,"x",0),l=ct(n,"y",0),w=ct(n,"width",0),P=ct(n,"height",0),x=ct(n,"rx",0),S=ct(n,"ry",0),x||S?e.context.roundRect(h,l,w,P,x||S):e.context.rect(h,l,w,P),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"ellipse":f=ct(n,"cx",0),g=ct(n,"cy",0),x=ct(n,"rx",0),S=ct(n,"ry",0),e.context.beginPath(),e.context.ellipse(f,g,x,S),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"line":c=ct(n,"x1",0),d=ct(n,"y1",0),u=ct(n,"x2",0),p=ct(n,"y2",0),e.context.beginPath(),e.context.moveTo(c,d),e.context.lineTo(u,p),i&&e.context.stroke(i);break;case"polygon":v=n.getAttribute("points"),b=v.match(/-?\d+/g).map(A=>parseInt(A,10)),e.context.poly(b,!0),t&&e.context.fill(t),i&&e.context.stroke(i);break;case"polyline":v=n.getAttribute("points"),b=v.match(/-?\d+/g).map(A=>parseInt(A,10)),e.context.poly(b,!1),i&&e.context.stroke(i);break;case"g":case"svg":break;default:{at(`[SVG parser] <${n.nodeName}> elements unsupported`);break}}a&&(t=null);for(let A=0;A<s.length;A++)Fc(s[A],e,t,i)}const Ka={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 en{constructor(e,t){this.uid=ut("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=Ka[t].addressModeU,e.source.style.addressModeV=Ka[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 zm(n){return ht.isColorLike(n)}function Qa(n){return n instanceof en}function Ja(n){return n instanceof Vt}function Om(n){return n instanceof U}function Wm(n,e,t){const i=ht.shared.setValue(e??0);return n.color=i.toNumber(),n.alpha=i.alpha===1?t.alpha:i.alpha,n.texture=U.WHITE,{...t,...n}}function Gm(n,e,t){return n.texture=e,{...t,...n}}function th(n,e,t){return n.fill=e,n.color=16777215,n.texture=e.texture,n.matrix=e.transform,{...t,...n}}function eh(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 Um(n,e){const t={...e,...n},i=ht.shared.setValue(t.color);return t.alpha*=i.alpha,t.color=i.toNumber(),t}function Be(n,e){if(n==null)return null;const t={},i=n;return zm(n)?Wm(t,n,e):Om(n)?Gm(t,n,e):Qa(n)?th(t,n,e):Ja(n)?eh(t,n,e):i.fill&&Qa(i.fill)?th(i,i.fill,e):i.fill&&Ja(i.fill)?eh(i,i.fill,e):Um(i,e)}function Us(n,e){const{width:t,alignment:i,miterLimit:s,cap:r,join:o,pixelLine:a,...h}=e,l=Be(n,h);return l?{width:t,alignment:i,miterLimit:s,cap:r,join:o,pixelLine:a,...l}:null}const Hm=new tt,ih=new H,ho=class Zt extends Jt{constructor(){super(...arguments),this._gpuData=Object.create(null),this.autoGarbageCollect=!0,this._gcLastUsed=-1,this.uid=ut("graphicsContext"),this.dirty=!0,this.batchMode="auto",this.instructions=[],this.destroyed=!1,this._activePath=new ce,this._transform=new H,this._fillStyle={...Zt.defaultFillStyle},this._strokeStyle={...Zt.defaultStrokeStyle},this._stateStack=[],this._tick=0,this._bounds=new Ot,this._boundsDirty=!0}clone(){const e=new Zt;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=Be(e,Zt.defaultFillStyle)}get strokeStyle(){return this._strokeStyle}set strokeStyle(e){this._strokeStyle=Us(e,Zt.defaultStrokeStyle)}setFillStyle(e){return this._fillStyle=Be(e,Zt.defaultFillStyle),this}setStrokeStyle(e){return this._strokeStyle=Be(e,Zt.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?ht.shared.setValue(t).toNumber():16777215}}),this.onUpdate(),this}beginPath(){return this._activePath=new ce,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(J,"GraphicsContext.fill(color, alpha) is deprecated, use GraphicsContext.fill({ color, alpha }) instead"),e={color:e,alpha:t}),this._fillStyle=Be(e,Zt.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(tt.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=Us(e,Zt.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++,Lm(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):(ih.set(e,t,i,s,r,o),this._transform.append(ih),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,f=p?p.applyInverse(e,Hm):e;if(o.action==="fill")i=u.contains(f.x,f.y);else{const m=l;i=u.strokeContains(f.x,f.y,m.width,m.alignment)}const g=a.hole;if(g){const m=(s=g.shapePath)==null?void 0:s.shapePrimitives;if(m)for(let x=0;x<m.length;x++)m[x].shape.contains(f.x,f.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}};ho.defaultFillStyle={color:16777215,alpha:1,texture:U.WHITE,matrix:null,fill:null,textureSpace:"local"};ho.defaultStrokeStyle={width:1,color:16777215,alpha:1,alignment:.5,miterLimit:10,cap:"butt",join:"miter",texture:U.WHITE,matrix:null,fill:null,textureSpace:"local",pixelLine:!1};let nt=ho;function lo(n,e=1){var i;const t=(i=Si.RETINA_PREFIX)==null?void 0:i.exec(n);return t?parseFloat(t[1]):e}function co(n,e,t){n.label=t,n._sourceOrigin=t;const i=new U({source:n,label:t}),s=()=>{delete e.promiseCache[t],St.has(t)&&St.remove(t)};return i.source.once("destroy",()=>{e.promiseCache[t]&&(at("[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||(at("[Assets] A Texture managed by Assets was destroyed instead of unloaded! Use Assets.unload() instead of destroying the Texture."),s())}),i}const Nm=".svg",uo="image/svg+xml",Vm={extension:{type:F.LoadParser,priority:_e.Low,name:"loadSVG"},name:"loadSVG",id:"svg",config:{crossOrigin:"anonymous",parseAsGraphicsContext:!1},test(n){return Me(n,uo)||bi(n,Nm)},async load(n,e,t){var i;return((i=e.data)==null?void 0:i.parseAsGraphicsContext)??this.config.parseAsGraphicsContext?Xm(n):$m(n,e,t,this.config.crossOrigin)},unload(n){n.destroy(!0)}};async function $m(n,e,t,i){var m,x,S;const s=Me(n,uo),r=j.get().createImage();r.crossOrigin=i,r.src=n,await new Promise((b,v)=>{r.complete?b(r):(r.onload=()=>b(r),r.onerror=v)}),await r.decode();const o=((m=e.data)==null?void 0:m.width)??r.width,a=((x=e.data)==null?void 0:x.height)??r.height,h=((S=e.data)==null?void 0:S.resolution)||lo(n),l=Math.ceil(o*h),c=Math.ceil(a*h),d=j.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,...f}=e.data??{},g=new ui({resource:d,alphaMode:"premultiply-alpha-on-upload",resolution:h,...f});return co(g,t,n)}function Ym(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 Xm(n){const e=Me(n,uo);let t;if(e)if(n.includes(";base64,")){const s=n.split(";base64,")[1];t=Ym(s)}else{const s=n.split(",")[1];t=decodeURIComponent(s)}else t=await(await j.get().fetch(n)).text();const i=new nt;return i.svg(t),i}const jm=`(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 oi=null,Ir=class{constructor(){oi||(oi=URL.createObjectURL(new Blob([jm],{type:"application/javascript"}))),this.worker=new Worker(oi)}};Ir.revokeObjectURL=function(){oi&&(URL.revokeObjectURL(oi),oi=null)};const Zm=`(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 ai=null;class Bc{constructor(){ai||(ai=URL.createObjectURL(new Blob([Zm],{type:"application/javascript"}))),this.worker=new Worker(ai)}}Bc.revokeObjectURL=function(){ai&&(URL.revokeObjectURL(ai),ai=null)};let sh=0,Vn;class qm{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 Ir;t.addEventListener("message",i=>{t.terminate(),Ir.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(){Vn===void 0&&(Vn=navigator.hardwareConcurrency||4);let e=this._workerPool.pop();return!e&&this._createdWorkers<Vn&&(this._createdWorkers++,e=new Bc().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[sh]={resolve:t.resolve,reject:t.reject},e.postMessage({data:t.arguments,uuid:sh++,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 nh=new qm,Km=[".jpeg",".jpg",".png",".webp",".avif"],Qm=["image/jpeg","image/png","image/webp","image/avif"];async function Jm(n,e){var s;const t=await j.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 Lc={name:"loadTextures",id:"texture",extension:{type:F.LoadParser,priority:_e.High,name:"loadTextures"},config:{preferWorkers:!0,preferCreateImageBitmap:!0,crossOrigin:"anonymous"},test(n){return Me(n,Qm)||bi(n,Km)},async load(n,e,t){var r;let i=null;globalThis.createImageBitmap&&this.config.preferCreateImageBitmap?this.config.preferWorkers&&await nh.isImageBitmapSupported()?i=await nh.loadImageBitmap(n,e):i=await Jm(n,e):i=await new Promise((o,a)=>{i=j.get().createImage(),i.crossOrigin=this.config.crossOrigin,i.src=n,i.complete?o(i):(i.onload=()=>{o(i)},i.onerror=a)});const s=new ui({resource:i,alphaMode:"premultiply-alpha-on-upload",resolution:((r=e.data)==null?void 0:r.resolution)||lo(n),...e.data});return co(s,t,n)},unload(n){n.destroy(!0)}},ty=[".mp4",".m4v",".webm",".ogg",".ogv",".h264",".avi",".mov"];let $n,Yn;function ey(n,e,t){t===void 0&&!e.startsWith("data:")?n.crossOrigin=sy(e):t!==!1&&(n.crossOrigin=typeof t=="string"?t:"anonymous")}function iy(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 sy(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 ny(){const n=[],e=[];for(const t of ty){const i=Gi.MIME_TYPES[t.substring(1)]||`video/${t.substring(1)}`;Qs(i)&&(n.push(t),e.includes(i)||e.push(i))}return{validVideoExtensions:n,validVideoMime:e}}const ry={name:"loadVideo",id:"video",extension:{type:F.LoadParser,name:"loadVideo"},test(n){if(!$n||!Yn){const{validVideoExtensions:i,validVideoMime:s}=ny();$n=i,Yn=s}const e=Me(n,Yn),t=bi(n,$n);return e||t},async load(n,e,t){var h,l;const i={...Gi.defaultOptions,resolution:((h=e.data)==null?void 0:h.resolution)||lo(n),alphaMode:((l=e.data)==null?void 0:l.alphaMode)||await Ul(),...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),ey(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=Gi.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 g=new Gi({...i,resource:s});f(),e.data.preload&&await iy(s),c(co(g,t,n))}function p(g){f(),d(g)}function f(){s.removeEventListener("canplay",u),s.removeEventListener("error",p),o.removeEventListener("error",p)}})},unload(n){n.destroy(!0)}},zc={extension:{type:F.ResolveParser,name:"resolveTexture"},test:Lc.test,parse:n=>{var e;return{resolution:parseFloat(((e=Si.RETINA_PREFIX.exec(n))==null?void 0:e[1])??"1"),format:n.split(".").pop(),src:n}}},oy={extension:{type:F.ResolveParser,priority:-2,name:"resolveJson"},test:n=>Si.RETINA_PREFIX.test(n)&&n.endsWith(".json"),parse:zc.parse};class ay{constructor(){this._detections=[],this._initialized=!1,this.resolver=new Si,this.loader=new Bf,this.cache=St,this._backgroundLoader=new Pf(this.loader),this._backgroundLoader.active=!0,this.reset()}async init(e={}){var r,o;if(this._initialized){at("[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=Os(e),s=Ht(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],f=Object.values(p),m=[...new Set(f.flat())].reduce((x,S)=>x+(S.progressSize||1),0);return h.push(0),a+=m,this._mapLoadToResolve(p,x=>{h[u]=x*m,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 St.get(e);const t={};for(let i=0;i<e.length;i++)t[i]=St.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}),St.set(h,a)}),r}async unload(e){this._initialized||await this.init();const t=Ht(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=Ht(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=>{St.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 X=new ay;Q.handleByList(F.LoadParser,X.loader.parsers).handleByList(F.ResolveParser,X.resolver.parsers).handleByList(F.CacheParser,X.cache.parsers).handleByList(F.DetectionParser,X.detections);Q.add(Af,Rf,Tf,Ff,Ef,If,Df,Of,Uf,Zf,Vm,Lc,ry,Mf,_f,zc,oy);const rh={loader:F.LoadParser,resolver:F.ResolveParser,cache:F.CacheParser,detection:F.DetectionParser};Q.handle(F.Asset,n=>{const e=n.ref;Object.entries(rh).filter(([t])=>!!e[t]).forEach(([t,i])=>Q.add(Object.assign(e[t],{extension:e[t].extension??i})))},n=>{const e=n.ref;Object.keys(rh).filter(t=>!!e[t]).forEach(t=>Q.remove(e[t]))});class Oc{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 Tp({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}}Oc.extension={type:[F.WebGLPipes,F.WebGPUPipes,F.CanvasPipes],name:"dom"};Q.add(Oc);class hy extends xi{constructor(e={}){const{element:t,anchor:i,...s}=e;super({label:"DOMContainer",...s}),this.renderPipeId="dom",this.batched=!1,this._anchor=new tt(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 ly extends to{constructor(){super(...arguments),this.client=new tt,this.movement=new tt,this.offset=new tt,this.global=new tt,this.screen=new tt}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,f,g){throw new Error("Method not implemented.")}}class oh extends ly{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 cy=`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
|
+
`,dy=`
|
|
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
|
+
`,ah=`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 Wc=class Gc extends qp{constructor(e){e={...Gc.defaultOptions,...e};const t=be.from({vertex:{source:ah,entryPoint:"mainVertex"},fragment:{source:ah,entryPoint:"mainFragment"}}),i=pi.from({vertex:cy,fragment:dy,name:"alpha-filter"}),{alpha:s,...r}=e,o=new fi({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}};Wc.defaultOptions={alpha:1};let uy=Wc;function hh(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,f=h*h+l*l,g=h*c+l*d,m=h*u+l*p,x=c*c+d*d,S=c*u+d*p,b=1/(f*x-g*g),v=(x*m-g*S)*b,M=(f*S-g*m)*b;return v>=0&&M>=0&&v+M<1}class py{constructor(){this.isBatchable=!1}reset(){this.isBatchable=!1,this.context=null,this.graphicsData&&(this.graphicsData.destroy(),this.graphicsData=null)}destroy(){this.reset()}}class fy{constructor(){this.instructions=new Qr}init(){this.instructions.reset()}destroy(){this.instructions.destroy(),this.instructions=null}}const po=class Dr{constructor(e){this._renderer=e,this._managedContexts=new vi({renderer:e,type:"resource",name:"graphicsContext"})}init(e){Dr.defaultOptions.bezierSmoothness=(e==null?void 0:e.bezierSmoothness)??Dr.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 fy,i=this.getGpuContext(e);return i.graphicsData=t,t.init(),t}_initContext(e){const t=new py;return t.context=e,e._gpuData[this._renderer.uid]=t,this._managedContexts.add(e),t}destroy(){this._managedContexts.destroy(),this._renderer=null}};po.extension={type:[F.CanvasSystem],name:"graphicsContext"};po.defaultOptions={bezierSmoothness:.5};let gy=po;class Uc{constructor(e,t){this.state=rs.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new vi({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}}Uc.extension={type:[F.CanvasPipes],name:"graphics"};function fo(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 my{constructor(){this.batches=[],this.batched=!1}destroy(){this.batches.forEach(e=>{Ft.return(e)}),this.batches.length=0}}class Hc{constructor(e,t){this.state=rs.for2d(),this.renderer=e,this._adaptor=t,this.renderer.runners.contextChange.add(this),this._managedGraphics=new vi({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,fo(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 my;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=Ft.get(no);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}}Hc.extension={type:[F.WebGLPipes,F.WebGPUPipes],name:"graphics"};Q.add(Uc);Q.add(Hc);Q.add(gy);Q.add(ao);class O extends xi{constructor(e){e instanceof nt&&(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 nt,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 O(this._context.clone()):(this._ownedContext=null,new O(this._context))}lineStyle(e,t,i){V(J,"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(J,"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(J,"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!==nt.defaultStrokeStyle.width||e.color!==nt.defaultStrokeStyle.color||e.alpha!==nt.defaultStrokeStyle.alpha)&&this.context.stroke(),this}drawCircle(...e){return V(J,"Graphics#drawCircle has been renamed to Graphics#circle"),this._callContextMethod("circle",e)}drawEllipse(...e){return V(J,"Graphics#drawEllipse has been renamed to Graphics#ellipse"),this._callContextMethod("ellipse",e)}drawPolygon(...e){return V(J,"Graphics#drawPolygon has been renamed to Graphics#poly"),this._callContextMethod("poly",e)}drawRect(...e){return V(J,"Graphics#drawRect has been renamed to Graphics#rect"),this._callContextMethod("rect",e)}drawRoundedRect(...e){return V(J,"Graphics#drawRoundedRect has been renamed to Graphics#roundRect"),this._callContextMethod("roundRect",e)}drawStar(...e){return V(J,"Graphics#drawStar has been renamed to Graphics#star"),this._callContextMethod("star",e)}}const Nc=class Vc extends Qi{constructor(...e){let t=e[0]??{};t instanceof Float32Array&&(V(J,"use new MeshGeometry({ positions, uvs, indices }) instead"),t={positions:t,uvs:e[1],indices:e[2]}),t={...Vc.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 xe({data:i,label:"attribute-mesh-positions",shrinkToFit:o,usage:gt.VERTEX|gt.COPY_DST}),h=new xe({data:s,label:"attribute-mesh-uvs",shrinkToFit:o,usage:gt.VERTEX|gt.COPY_DST}),l=new xe({data:r,label:"index-mesh-buffer",shrinkToFit:o,usage:gt.INDEX|gt.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}};Nc.defaultOptions={topology:"triangle-list",shrinkBuffersToFit:!1};let go=Nc;class $c{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 lh{destroy(){}}class Yc{constructor(e,t){this.localUniforms=new fi({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 Ui({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=Ws(e.groupBlendMode,e.texture._source);const t=this.localUniforms;t.uniforms.uTransformMatrix=e.groupTransform,t.uniforms.uRound=this.renderer._roundPixels|e._roundPixels,t.update(),fo(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 lh),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 lh),e._gpuData[this.renderer.uid].batchableMesh||this._initBatchableMesh(e)}_initBatchableMesh(e){const t=new $c;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}}Yc.extension={type:[F.WebGLPipes,F.WebGPUPipes],name:"mesh"};Q.add(Yc);class ch extends xi{constructor(...e){let t=e[0];t instanceof Qi&&(V(J,"Mesh: use new Mesh({ geometry, shader }) instead"),t={geometry:t,shader:e[1]},e[3]&&(V(J,"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)??U.WHITE,this.state=a??rs.for2d(),this._geometry=i,this._geometry.on("update",this.onViewUpdate,this),this.roundPixels=o??!1}get material(){return V(J,"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=U.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 go?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(hh(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(hh(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 Hs extends Qt{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 U?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&&(xt.shared.remove(this.update,this),this._isConnectedToTicker=!1))}play(){this._playing||(this._playing=!0,this._autoUpdate&&!this._isConnectedToTicker&&(xt.shared.add(this.update,this,He.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(U.from(e[i]));return new Hs(t)}static fromImages(e){const t=[];for(let i=0;i<e.length;++i)t.push(U.from(e[i]));return new Hs(t)}get totalFrames(){return this._textures.length}get textures(){return this._textures}set textures(e){if(e[0]instanceof U)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?(xt.shared.remove(this.update,this),this._isConnectedToTicker=!1):this._autoUpdate&&!this._isConnectedToTicker&&this._playing&&(xt.shared.add(this.update,this),this._isConnectedToTicker=!0))}}class yy{constructor({matrix:e,observer:t}={}){this.dirty=!0,this._matrix=e??new H,this.observer=t,this.position=new dt(this,0,0),this.scale=new dt(this,1,1),this.pivot=new dt(this,0,0),this.skew=new dt(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 Qe;function dh(n){const e=j.get().createCanvas(6,1),t=e.getContext("2d");return t.fillStyle=n,t.fillRect(0,0,6,1),e}function xy(){if(Qe!==void 0)return Qe;try{const n=dh("#ff00ff"),e=dh("#ffff00"),i=j.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)Qe=!1;else{const r=s.data;Qe=r[0]===255&&r[1]===0&&r[2]===0}}catch{Qe=!1}return Qe}const ot={canvas:null,convertTintToImage:!1,cacheStepsPerColorChannel:8,canUseMultiply:xy(),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=ot._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=ot._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const h=j.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),ot._canvasSourceCache.set(e,{canvas:h,resourceId:e._resourceId}),h}if(i){const a=j.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),ot._unpremultipliedCache.set(e,{canvas:a,resourceId:e._resourceId}),a}if(o){const a=ot._canvasSourceCache.get(e);if((a==null?void 0:a.resourceId)===e._resourceId)return a.canvas;const h=j.get().createCanvas(e.pixelWidth,e.pixelHeight),l=h.getContext("2d");return h.width=e.pixelWidth,h.height=e.pixelHeight,l.drawImage(t,0,0),ot._canvasSourceCache.set(e,{canvas:h,resourceId:e._resourceId}),h}return t},getTintedCanvas:(n,e)=>{const t=n.texture,i=ht.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:j.get().createCanvas();return ot.tintMethod(t,e,a),a.tintId=o,s[i]=a,s[i]},getTintedPattern:(n,e)=>{const t=ht.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||(ot.canvas||(ot.canvas=j.get().createCanvas()),ot.tintMethod(n,e,ot.canvas),r=ot.canvas.getContext("2d").createPattern(ot.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=Z.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=ht.shared.setValue(e).toHex(),i.fillRect(0,0,h,l),i.globalCompositeOperation="multiply";const c=ot.getCanvasSource(n);if(!c){i.restore();return}o&&ot._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=Z.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=ht.shared.setValue(e).toHex(),i.fillRect(0,0,h,l),i.globalCompositeOperation="destination-atop";const c=ot.getCanvasSource(n);if(!c){i.restore();return}o&&ot._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=Z.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=ot.getCanvasSource(n);if(!c){i.restore();return}o&&ot._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,f=i.getImageData(0,0,h,l),g=f.data;for(let m=0;m<g.length;m+=4)g[m]=g[m]*d/255,g[m+1]=g[m+1]*u/255,g[m+2]=g[m+2]*p/255;i.putImageData(f,0,0)},_applyInverseRotation:(n,e,t,i)=>{const s=Z.inv(e),r=Z.uX(s),o=Z.uY(s),a=Z.vX(s),h=Z.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)}};ot.tintMethod=ot.canUseMultiply?ot.tintWithMultiply:ot.tintWithPerPixel;const vs=new H,Ei=new H,Xt=[new tt,new tt,new tt,new tt];class Xc{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 w,P;const t=this._renderer,i=t.canvasContext,s=i.activeContext;s.save(),i.setBlendMode(e.groupBlendMode);const r=((w=t.globalUniforms.globalUniformData)==null?void 0:w.worldColor)??4294967295,o=e.groupColorAlpha,a=(r>>>24&255)/255,h=(o>>>24&255)/255,l=((P=t.filter)==null?void 0:P.alphaMultiplier)??1,c=a*h*l;if(c<=0){s.restore();return}s.globalAlpha=c;const d=r&16777215,u=o&16777215,p=Wi(Kr(u,d)),f=e.texture,g=ot.getTintedPattern(f,p),m=e.width,x=e.height,S=e.groupTransform,b=f.source._resolution??f.source.resolution??1;Ei.copyFrom(e._tileTransform.matrix),e.applyAnchorToTexture||Ei.translate(-e.anchor.x*m,-e.anchor.y*x),Ei.scale(1/b,1/b),vs.identity(),vs.prepend(Ei),vs.prepend(S);const v=t._roundPixels|e._roundPixels;i.setContextTransform(vs,v===1),s.fillStyle=g;const M=e.anchor.x*-m,_=e.anchor.y*-x;Xt[0].set(M,_),Xt[1].set(M+m,_),Xt[2].set(M+m,_+x),Xt[3].set(M,_+x);for(let A=0;A<4;A++)Ei.applyInverse(Xt[A],Xt[A]);s.beginPath(),s.moveTo(Xt[0].x,Xt[0].y);for(let A=1;A<4;A++)s.lineTo(Xt[A].x,Xt[A].y);s.closePath(),s.fill(),s.restore()}destroy(){this._renderer=null}}Xc.extension={type:[F.CanvasPipes],name:"tilingSprite"};const Es={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
|
+
`}},w0={...Es,vertex:{...Es.vertex,header:Es.vertex.header.replace("group(1)","group(2)")}},Sy={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
|
+
`}},by={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
|
+
`}},vy={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 Xn,jn;class wy extends Ne{constructor(){Xn??(Xn=wc({name:"tiling-sprite-shader",bits:[Es,by,_c]})),jn??(jn=Cc({name:"tiling-sprite-shader",bits:[Sy,vy,Mc]}));const e=new fi({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:jn,gpuProgram:Xn,resources:{localUniforms:new fi({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:U.EMPTY.source,uSampler:U.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 Cy extends go{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 _y(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 My(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 Py(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),My(e,2,0,a)}const Is=new Cy;class Ay{constructor(){this.canBatch=!0,this.geometry=new go({indices:Is.indices.slice(),positions:Is.positions.slice(),uvs:Is.uvs.slice()})}destroy(){var e;this.geometry.destroy(),(e=this.shader)==null||e.destroy()}}class jc{constructor(e){this._state=rs.default2d,this._renderer=e,this._managedTilingSprites=new vi({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 $c);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 wy),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,fo(e.groupColorAlpha,s.uColor,0),this._state.blendMode=Ws(e.groupBlendMode,e.texture._source),t.encoder.draw({geometry:Is,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 Ay;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()),Py(e,i.uvs),_y(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===he.WEBGL&&(s=this._renderer.context.supports.nonPowOf2wrapping),t.canBatch=i.textureMatrix.isSimple&&(s||i.source.isPowerOfTwo),t.canBatch}}jc.extension={type:[F.WebGLPipes,F.WebGPUPipes],name:"tilingSprite"};Q.add(Xc);Q.add(jc);const Zc=class Ds extends xi{constructor(...e){let t=e[0]||{};t instanceof U&&(t={texture:t}),e.length>1&&(V(J,"use new TilingSprite({ texture, width:100, height:100 }) instead"),t.width=e[1],t.height=e[2]),t={...Ds.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 dt({_onUpdate:()=>{this.onViewUpdate()}}),this.applyAnchorToTexture=c,this.texture=i,this._width=h??i.width,this._height=l??i.height,this._tileTransform=new yy({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 Ds({texture:St.get(e),...t}):new Ds({texture:e,...t})}get uvRespectAnchor(){return V(J,"uvRespectAnchor is deprecated, please use applyAnchorToTexture instead"),this.applyAnchorToTexture}set uvRespectAnchor(e){V(J,"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=U.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}};Zc.defaultOptions={texture:U.EMPTY,anchor:{x:0,y:0},tilePosition:{x:0,y:0},tileScale:{x:1,y:1},tileRotation:0,applyAnchorToTexture:!1};let Ns=Zc;class Ty extends xi{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 dt({_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 Ry(n,e){let t=n[0]??{};return(typeof t=="string"||n[1])&&(V(J,`use new ${e}({ text: "hi!", style }) instead`),t={text:t,style:n[1]}),t}class ky{constructor(e){this._canvasPool=Object.create(null),this.canvasOptions=e||{},this.enableFullScreen=!1}_createCanvasAndContext(e,t){const i=j.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=li(e),t=li(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 Fr=new ky;ns.register(Fr);let Ae=null,oe=null;function Ey(n,e){Ae||(Ae=j.get().createCanvas(256,128),oe=Ae.getContext("2d",{willReadFrequently:!0}),oe.globalCompositeOperation="copy",oe.globalAlpha=1),(Ae.width<n||Ae.height<e)&&(Ae.width=li(n),Ae.height=li(e))}function uh(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 ph(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 Iy(...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(Ey(s,r),!oe)throw new TypeError("Failed to get canvas 2D context");oe.drawImage(t,0,0,s,r,0,0,s*i,r*i);const h=oe.getImageData(0,0,s,r).data;let l=0,c=0,d=s-1,u=r-1;for(;c<r&&uh(h,s,c);)++c;if(c===r)return et.EMPTY;for(;uh(h,s,u);)--u;for(;ph(h,s,l,c,u);)++l;for(;ph(h,s,d,c,u);)--d;return++d,++u,oe.globalCompositeOperation="source-over",oe.strokeRect(l,c,d-l,u-c),oe.globalCompositeOperation="copy",o??(o=new et),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 Dy{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 Fy(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 Dy(n,e,t)}function qc(n){return!!n.tagStyles&&Object.keys(n.tagStyles).length>0}function Kc(n){return n.includes("<")}function By(n,e){return n.clone().assign(e)}function Ly(n,e){const t=[],i=e.tagStyles;if(!qc(e)||!Kc(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=By(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 zy=[10,13],Oy=new Set(zy),Wy=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288],Gy=new Set(Wy),Uy=/(\r\n|\r|\n)/,Hy=/(?:\r\n|\r|\n)/;function mo(n){return typeof n!="string"?!1:Oy.has(n.charCodeAt(0))}function Nt(n,e){return typeof n!="string"?!1:Gy.has(n.charCodeAt(0))}function Qc(n){return n==="normal"||n==="pre-line"}function Jc(n){return n==="normal"}function re(n){if(typeof n!="string")return"";let e=n.length-1;for(;e>=0&&Nt(n[e]);)e--;return e<n.length-1?n.slice(0,e+1):n}function td(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(Nt(s)||mo(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 ed(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 Ny=/\r\n|\r|\n/g;function Vy(n,e,t,i,s,r,o,a){var B;const h=Ly(n,e);if(Jc(e.whiteSpace))for(let N=0;N<h.length;N++){const E=h[N];h[N]={text:E.text.replace(Ny," "),style:E.style}}const c=[];let d=[];for(const N of h){const E=N.text.split(Uy);for(let D=0;D<E.length;D++){const q=E[D];q===`\r
|
|
500
|
+
`||q==="\r"||q===`
|
|
501
|
+
`?(c.push(d),d=[]):q.length>0&&d.push({text:q,style:N.style})}}(d.length>0||c.length===0)&&c.push(d);const u=t?$y(c,e,i,s,o,a):c,p=[],f=[],g=[],m=[],x=[];let S=0;const b=e._fontString,v=r(b);v.fontSize===0&&(v.fontSize=e.fontSize,v.ascent=e.fontSize);let M="",_=!!e.dropShadow;for(const N of u){let E=0,D=v.ascent,q=v.descent,L="";for(const $ of N){const st=$.style._fontString,vt=r(st);st!==M&&(i.font=st,M=st);const mt=s($.text,$.style.letterSpacing,i);E+=mt,D=Math.max(D,vt.ascent),q=Math.max(q,vt.descent),L+=$.text,!_&&$.style.dropShadow&&(_=!0)}N.length===0&&(D=v.ascent,q=v.descent),p.push(E),f.push(D),g.push(q),x.push(L);const Y=e.lineHeight||D+q;m.push(Y+e.leading),S=Math.max(S,E)}const w=((B=e._stroke)==null?void 0:B.width)||0,T=(t&&e.align!=="left"&&e.align!=="justify"?Math.max(S,e.wordWrapWidth):S)+w+(e.dropShadow?e.dropShadow.distance:0);let R=0;for(let N=0;N<m.length;N++)R+=m[N];R=Math.max(R,m[0]+w);const k=R+(e.dropShadow?e.dropShadow.distance:0),I=e.lineHeight||v.fontSize;return{width:T,height:k,lines:x,lineWidths:p,lineHeight:I+e.leading,maxLineWidth:S,fontProperties:v,runsByLine:u,lineAscents:f,lineDescents:g,lineHeights:m,hasDropShadow:_}}function $y(n,e,t,i,s,r){var m;const{letterSpacing:o,whiteSpace:a,wordWrapWidth:h,breakWords:l}=e,c=Qc(a),d=h+o,u={};let p="";const f=(x,S)=>{const b=`${x}|${S.styleKey}`;let v=u[b];if(v===void 0){const M=S._fontString;M!==p&&(t.font=M,p=M),v=i(x,S.letterSpacing,t)+S.letterSpacing,u[b]=v}return v},g=[];for(const x of n){const S=Yy(x),b=g.length,v=k=>{let I=0,B=k;do{const{token:N,style:E}=S[B];I+=f(N,E),B++}while(B<S.length&&S[B].continuesFromPrevious);return I},M=k=>{const I=[];let B=k;do I.push({token:S[B].token,style:S[B].style}),B++;while(B<S.length&&S[B].continuesFromPrevious);return I};let _=[],w=0,P=!c,A=null;const T=()=>{A&&A.text.length>0&&_.push(A),A=null},R=()=>{if(T(),_.length>0){const k=_[_.length-1];k.text=re(k.text),k.text.length===0&&_.pop()}g.push(_),_=[],w=0,P=!1};for(let k=0;k<S.length;k++){const{token:I,style:B,continuesFromPrevious:N}=S[k],E=f(I,B);if(c){const L=Nt(I),Y=(A==null?void 0:A.text[A.text.length-1])??((m=_[_.length-1])==null?void 0:m.text.slice(-1))??"",$=Y?Nt(Y):!1;if(L&&$)continue}const D=!N,q=D?v(k):E;if(q>d&&D)if(w>0&&R(),l){const L=M(k);for(let Y=0;Y<L.length;Y++){const $=L[Y].token,st=L[Y].style,vt=ed($,l,r,s);for(const mt of vt){const _t=f(mt,st);_t+w>d&&R(),!A||A.style!==st?(T(),A={text:mt,style:st}):A.text+=mt,w+=_t}}k+=L.length-1}else{const L=M(k);T(),g.push(L.map(Y=>({text:Y.token,style:Y.style}))),P=!1,k+=L.length-1}else if(q+w>d&&D){if(Nt(I)){P=!1;continue}R(),A={text:I,style:B},w=E}else if(N&&!l)!A||A.style!==B?(T(),A={text:I,style:B}):A.text+=I,w+=E;else{const L=Nt(I);if(w===0&&L&&!P)continue;!A||A.style!==B?(T(),A={text:I,style:B}):A.text+=I,w+=E}}if(T(),_.length>0){const k=_[_.length-1];k.text=re(k.text),k.text.length===0&&_.pop()}(_.length>0||g.length===b)&&g.push(_)}return g}function Yy(n){const e=[];let t=!1;for(const i of n){const s=td(i.text);let r=!0;for(const o of s){const a=Nt(o)||mo(o),h=r&&t&&!a;e.push({token:o,style:i.style,continuesFromPrevious:h}),t=!a,r=!1}}return e}const Xy={willReadFrequently:!0};function fh(n,e,t,i,s){let r=t[n];return typeof r!="number"&&(r=s(n,e,i)+e,t[n]=r),r}function jy(n,e,t,i,s,r,o){const a=t.getContext("2d",Xy);a.font=e._fontString;let h=0,l="";const c=[],d=Object.create(null),{letterSpacing:u,whiteSpace:p}=e,f=Qc(p),g=Jc(p);let m=!f;const x=e.wordWrapWidth+u,S=td(n);for(let v=0;v<S.length;v++){let M=S[v];if(mo(M)){if(!g){c.push(re(l)),m=!f,l="",h=0;continue}M=" "}if(f){const w=Nt(M),P=Nt(l[l.length-1]);if(w&&P)continue}const _=fh(M,u,d,a,i);if(_>x)if(l!==""&&(c.push(re(l)),l="",h=0),s(M,e.breakWords)){const w=ed(M,e.breakWords,o,r);for(const P of w){const A=fh(P,u,d,a,i);A+h>x&&(c.push(re(l)),m=!1,l="",h=0),l+=P,h+=A}}else l.length>0&&(c.push(re(l)),l="",h=0),c.push(re(M)),m=!1,l="",h=0;else _+h>x&&(m=!1,c.push(re(l)),l="",h=0),(l.length>0||!Nt(M)||m)&&(l+=M,h+=_)}const b=re(l);return b.length>0&&c.push(b),c.join(`
|
|
502
|
+
`)}const gh={willReadFrequently:!0},pe=class G{static get experimentalLetterSpacingSupported(){let e=G._experimentalLetterSpacingSupported;if(e===void 0){const t=j.get().getCanvasRenderingContext2D().prototype;e=G._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=G._canvas,s=t.wordWrap){var M;const r=`${e}-${t.styleKey}-wordWrap-${s}`;if(G._measurementCache.has(r))return G._measurementCache.get(r);if(qc(t)&&Kc(e)){const _=Vy(e,t,s,G._context,G._measureText,G.measureFont,G.canBreakChars,G.wordWrapSplit),w=new G(e,t,_.width,_.height,_.lines,_.lineWidths,_.lineHeight,_.maxLineWidth,_.fontProperties,{runsByLine:_.runsByLine,lineAscents:_.lineAscents,lineDescents:_.lineDescents,lineHeights:_.lineHeights,hasDropShadow:_.hasDropShadow});return G._measurementCache.set(r,w),w}const a=t._fontString,h=G.measureFont(a);h.fontSize===0&&(h.fontSize=t.fontSize,h.ascent=t.fontSize,h.descent=0);const l=G._context;l.font=a;const d=(s?G._wordWrap(e,t,i):e).split(Hy),u=new Array(d.length);let p=0;for(let _=0;_<d.length;_++){const w=G._measureText(d[_],t.letterSpacing,l);u[_]=w,p=Math.max(p,w)}const f=((M=t._stroke)==null?void 0:M.width)??0,g=t.lineHeight||h.fontSize,m=G._getAlignWidth(p,t,s),x=G._adjustWidthForStyle(m,t),S=Math.max(g,h.fontSize+f)+(d.length-1)*(g+t.leading),b=G._adjustHeightForStyle(S,t),v=new G(e,t,x,b,d,u,g+t.leading,p,h);return G._measurementCache.set(r,v),v}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;G.experimentalLetterSpacingSupported&&(G.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=(G.graphemeSegmenter(e).length-1)*t;o+=c,l+=c}return Math.max(o,l)}static _wordWrap(e,t,i=G._canvas){return jy(e,t,i,G._measureText,G.canBreakWords,G.canBreakChars,G.wordWrapSplit)}static isBreakingSpace(e,t){return Nt(e)}static canBreakWords(e,t){return t}static canBreakChars(e,t,i,s,r){return!0}static wordWrapSplit(e){return G.graphemeSegmenter(e)}static measureFont(e){if(G._fonts[e])return G._fonts[e];const t=G._context;t.font=e;const i=t.measureText(G.METRICS_STRING+G.BASELINE_SYMBOL),s=i.actualBoundingBoxAscent??0,r=i.actualBoundingBoxDescent??0,o={ascent:s,descent:r,fontSize:s+r};return G._fonts[e]=o,o}static clearMetrics(e=""){e?delete G._fonts[e]:G._fonts={}}static get _canvas(){if(!G.__canvas){let e;try{const t=new OffscreenCanvas(0,0),i=t.getContext("2d",gh);if(i!=null&&i.measureText)return G.__canvas=t,t;e=j.get().createCanvas()}catch{e=j.get().createCanvas()}e.width=e.height=10,G.__canvas=e}return G.__canvas}static get _context(){return G.__context||(G.__context=G._canvas.getContext("2d",gh)),G.__context}};pe.METRICS_STRING="|ÉqÅ";pe.BASELINE_SYMBOL="M";pe.BASELINE_MULTIPLIER=1.4;pe.HEIGHT_MULTIPLIER=2;pe.graphemeSegmenter=n=>[...n];pe.experimentalLetterSpacing=!1;pe._fonts={};pe._measurementCache=Fy(1e3);let ge=pe;const Zy=["serif","sans-serif","monospace","cursive","fantasy","system-ui"];function Br(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)&&!Zy.includes(s)&&(s=`"${s}"`),t[i]=s}return`${n.fontStyle} ${n.fontVariant} ${n.fontWeight} ${e} ${t.join(",")}`}const mh=1e5;function ws(n,e,t,i=0,s=0,r=0){if(n.texture===U.WHITE&&!n.fill)return ht.shared.setValue(n.color).setAlpha(n.alpha??1).toHexa();if(n.fill){if(n.fill instanceof en){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 Vt){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:f}=o;d=e.createLinearGradient(p.x*l+s,p.y*c+r,f.x*l+s,f.y*c+r),u=Math.abs(f.x-p.x)<Math.abs((f.y-p.y)*.1)}else{const{center:p,innerRadius:f,outerCenter:g,outerRadius:m}=o;d=e.createRadialGradient(p.x*l+s,p.y*c+r,f*l,g.x*l+s,g.y*c+r,m*l)}if(u&&h&&t){const p=t.lineHeight/c;for(let f=0;f<t.lines.length;f++){const g=(f*t.lineHeight+i/2)/c;o.colorStops.forEach(m=>{let x=g+m.offset*p;x=Math.max(0,Math.min(1,x)),d.addColorStop(Math.floor(x*mh)/mh,ht.shared.setValue(m.color).toHex())})}}else o.colorStops.forEach(p=>{d.addColorStop(p.offset,ht.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 at("FillStyle not recognised",n),"red"}const yh=new et;class qy{getCanvasAndContext(e){const{text:t,style:i,resolution:s=1}=e,r=i._getFinalPadding(),o=ge.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=Fr.getOptimalCanvasAndContext(a,h);this._renderTextToCanvas(i,r,s,l,o);const c=i.trim?Iy({canvas:l.canvas,width:a,height:h,resolution:1,output:yh}):yh.set(0,0,a,h);return{canvasAndContext:l,frame:c}}returnCanvasAndContext(e){Fr.returnCanvasAndContext(e)}_renderTextToCanvas(e,t,i,s,r){var _,w,P;if(r.runsByLine&&r.runsByLine.length>0){this._renderTaggedTextToCanvas(r,e,t,i,s);return}const{canvas:o,context:a}=s,h=Br(e),l=r.lines,c=r.lineHeight,d=r.lineWidths,u=r.maxLineWidth,p=r.fontProperties,f=o.height;if(a.resetTransform(),a.scale(i,i),a.textBaseline=e.textBaseline,(_=e._stroke)!=null&&_.width){const A=e._stroke;a.lineWidth=A.width,a.miterLimit=A.miterLimit,a.lineJoin=A.join,a.lineCap=A.cap}a.font=h;let g,m;const x=e.dropShadow?2:1,S=e.wordWrap?e.wordWrapWidth:u,v=(((w=e._stroke)==null?void 0:w.width)??0)/2;let M=(c-p.fontSize)/2;c-p.fontSize<0&&(M=0);for(let A=0;A<x;++A){const T=e.dropShadow&&A===0,R=T?Math.ceil(Math.max(1,f)+t*2):0,k=R*i;if(T)this._setupDropShadow(a,e,i,k);else{const I=e._gradientBounds,B=e._gradientOffset;if(I){const N={width:I.width,height:I.height,lineHeight:I.height,lines:r.lines};this._setFillAndStrokeStyles(a,e,N,t,v,(B==null?void 0:B.x)??0,(B==null?void 0:B.y)??0)}else B?this._setFillAndStrokeStyles(a,e,r,t,v,B.x,B.y):this._setFillAndStrokeStyles(a,e,r,t,v);a.shadowColor="black"}for(let I=0;I<l.length;I++)g=v,m=v+I*c+p.ascent+M,g+=this._getAlignmentOffset(d[I],S,e.align),(P=e._stroke)!=null&&P.width&&this._drawLetterSpacing(l[I],e,s,g+t,m+t-R,!0),e._fill!==void 0&&this._drawLetterSpacing(l[I],e,s,g+t,m+t-R)}}_renderTaggedTextToCanvas(e,t,i,s,r){var v,M;const{canvas:o,context:a}=r,{runsByLine:h,lineWidths:l,maxLineWidth:c,lineAscents:d,lineHeights:u,hasDropShadow:p}=e,f=o.height;a.resetTransform(),a.scale(s,s),a.textBaseline=t.textBaseline;const g=p?2:1,m=t.wordWrap?t.wordWrapWidth:c,S=(((v=t._stroke)==null?void 0:v.width)??0)/2,b=[];for(let _=0;_<h.length;_++){const w=h[_],P=[];for(const A of w){const T=Br(A.style);a.font=T,P.push({width:ge._measureText(A.text,A.style.letterSpacing,a),font:T})}b.push(P)}for(let _=0;_<g;++_){const w=p&&_===0,P=w?Math.ceil(Math.max(1,f)+i*2):0,A=P*s;w||(a.shadowColor="black");let T=S;for(let R=0;R<h.length;R++){const k=h[R],I=l[R],B=d[R],N=u[R],E=b[R];let D=S;D+=this._getAlignmentOffset(I,m,t.align);const q=T+B;let L=D+i;for(let Y=0;Y<k.length;Y++){const $=k[Y],{width:st,font:vt}=E[Y];if(a.font=vt,a.textBaseline=$.style.textBaseline,(M=$.style._stroke)!=null&&M.width){const mt=$.style._stroke;if(a.lineWidth=mt.width,a.miterLimit=mt.miterLimit,a.lineJoin=mt.join,a.lineCap=mt.cap,w)if($.style.dropShadow)this._setupDropShadow(a,$.style,s,A);else{L+=st;continue}else{const _t=ge.measureFont(vt),Tt=$.style.lineHeight||_t.fontSize,fe={width:st,height:Tt,lineHeight:Tt,lines:[$.text]};a.strokeStyle=ws(mt,a,fe,i*2,L-i,T)}this._drawLetterSpacing($.text,$.style,r,L,q+i-P,!0)}L+=st}L=D+i;for(let Y=0;Y<k.length;Y++){const $=k[Y],{width:st,font:vt}=E[Y];if(a.font=vt,a.textBaseline=$.style.textBaseline,$.style._fill!==void 0){if(w)if($.style.dropShadow)this._setupDropShadow(a,$.style,s,A);else{L+=st;continue}else{const mt=ge.measureFont(vt),_t=$.style.lineHeight||mt.fontSize,Tt={width:st,height:_t,lineHeight:_t,lines:[$.text]};a.fillStyle=ws($.style._fill,a,Tt,i*2,L-i,T)}this._drawLetterSpacing($.text,$.style,r,L,q+i-P,!1)}L+=st}T+=N}}}_setFillAndStrokeStyles(e,t,i,s,r,o=0,a=0){var h;if(e.fillStyle=t._fill?ws(t._fill,e,i,s*2,o,a):null,(h=t._stroke)!=null&&h.width){const l=r+s*2;e.strokeStyle=ws(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=ht.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(ge.experimentalLetterSpacingSupported&&(ge.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=ge.graphemeSegmenter(e);let u=a.measureText(e).width,p=0;for(let f=0;f<d.length;++f){const g=d[f];o?a.strokeText(g,c,r):a.fillText(g,c,r);let m="";for(let x=f+1;x<d.length;++x)m+=d[x];p=a.measureText(m).width,c+=u-p+h,u=p}}}const si=new qy,yo=class De extends Jt{constructor(e={}){super(),this.uid=ut("textStyle"),this._tick=0,this._cachedFontString=null,Ky(e),e instanceof De&&(e=e._toObject());const s={...De.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({...De.defaultDropShadow,...e}):this._dropShadow=e?this._createProxy({...De.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({...nt.defaultFillStyle,...e},()=>{this._fill=Be({...this._originalFill},nt.defaultFillStyle)})),this._fill=Be(e===0?"black":e,nt.defaultFillStyle),this.update())}get stroke(){return this._originalStroke}set stroke(e){e!==this._originalStroke&&(this._originalStroke=e,this._isFillStyle(e)&&(this._originalStroke=this._createProxy({...nt.defaultStrokeStyle,...e},()=>{this._stroke=Us({...this._originalStroke},nt.defaultStrokeStyle)})),this._stroke=Us(e,nt.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=De.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=Br(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 De(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&&!(ht.isColorLike(e)||e instanceof Vt||e instanceof en)}};yo.defaultDropShadow={alpha:1,angle:Math.PI/6,blur:0,color:"black",distance:5};yo.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 ve=yo;function Ky(n){const e=n;if(typeof e.dropShadow=="boolean"&&e.dropShadow){const t=ve.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(J,"strokeThickness is now a part of stroke");const t=e.stroke;let i={};if(ht.isColorLike(t))i.color=t;else if(t instanceof Vt||t instanceof en)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(J,"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&&at("The number of fill colors must match the number of fill gradient stops.");const t=new Vt({start:{x:0,y:0},end:{x:0,y:1},textureSpace:"local"}),i=e.fillGradientStops.slice(),s=e.fill.map(r=>ht.shared.setValue(r).toNumber());i.forEach((r,o)=>{t.addColorStop(r,s[o])}),n.fill={fill:t}}}function Qy(n,e){const{texture:t,bounds:i}=n,s=e._style._getFinalPadding();Ml(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 Jy{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 tx extends Jy{}class id{constructor(e){this._renderer=e,e.runners.resolutionChange.add(this),this._managedTexts=new vi({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,Qy(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 tx;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}}id.extension={type:[F.WebGLPipes,F.WebGPUPipes,F.CanvasPipes],name:"text"};const ex=new Ot;function ix(n,e,t,i){const s=ex;s.minX=0,s.minY=0,s.maxX=n.width/i|0,s.maxY=n.height/i|0;const r=qs.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 sd{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 ve||(e.style=new ve(e.style)),e.textureStyle instanceof ci||(e.textureStyle=new ci(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}=si.getCanvasAndContext({text:r,style:o,resolution:h}),d=ix(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),si.returnCanvasAndContext(c),u}return this._renderer.texture.initSource(d._source),this._retainCanvasContext||si.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&&si.returnCanvasAndContext({canvas:i,context:s})}t.resource=null,t.uploadMethodId="unknown",t.alphaMode="no-premultiply-alpha",qs.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 nd extends sd{constructor(e){super(e,!0)}}nd.extension={type:[F.CanvasSystem],name:"canvasText"};class rd extends sd{constructor(e){super(e,!1)}}rd.extension={type:[F.WebGLSystem,F.WebGPUSystem],name:"canvasText"};Q.add(nd);Q.add(rd);Q.add(id);class sn extends Ty{constructor(...e){const t=Ry(e,"Text");super(t,ve),this.renderPipeId="text",t.textureStyle&&(this.textureStyle=t.textureStyle instanceof ci?t.textureStyle:new ci(t.textureStyle))}updateBounds(){const e=this._bounds,t=this._anchor;let i=0,s=0;if(this._style.trim){const{frame:r,canvasAndContext:o}=si.getCanvasAndContext({text:this.text,style:this._style,resolution:1});si.returnCanvasAndContext(o),i=r.width,s=r.height}else{const r=ge.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 xo extends U{static create(e){const{dynamic:t,...i}=e;return new xo({source:new Gt(i),dynamic:t??!1})}resize(e,t,i){return this.source.resize(e,t,i),this}}Q.add(Mu,Pu);function sx(n,e){var t=-1,i=n.length;for(e||(e=Array(i));++t<i;)e[t]=n[t];return e}function nx(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?dl(t,a,h):ul(t,a,h)}return t}function rx(n){return qd(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&&Kd(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 ox(n){var e=[];if(n!=null)for(var t in Object(n))e.push(t);return e}var ax=Object.prototype,hx=ax.hasOwnProperty;function lx(n){if(!Ue(n))return ox(n);var e=Qd(n),t=[];for(var i in n)i=="constructor"&&(e||!hx.call(n,i))||t.push(i);return t}function od(n){return pl(n)?Jd(n,!0):lx(n)}function cx(n){var e=n==null?0:n.length;return e?tu(n):[]}function dx(n){return eu(iu(n,void 0,cx),n+"")}var ux="[object Object]",px=Function.prototype,fx=Object.prototype,ad=px.toString,gx=fx.hasOwnProperty,mx=ad.call(Object);function yx(n){if(!jr(n)||fl(n)!=ux)return!1;var e=su(n);if(e===null)return!0;var t=gx.call(e,"constructor")&&e.constructor;return typeof t=="function"&&t instanceof t&&ad.call(t)==mx}var xx=ou.isFinite,Sx=Math.min;function bx(n){var e=Math[n];return function(t,i){if(t=nu(t),i=i==null?0:Sx(ru(i),292),i&&xx(t)){var s=(zo(t)+"e").split("e"),r=e(s[0]+"e"+(+s[1]+i));return s=(zo(r)+"e").split("e"),+(s[0]+"e"+(+s[1]-i))}return e(t)}}function Lr(n,e,t){(t!==void 0&&!au(n[e],t)||t===void 0&&!(e in n))&&dl(n,e,t)}function vx(n){return jr(n)&&pl(n)}function zr(n,e){if(!(e==="constructor"&&typeof n[e]=="function")&&e!="__proto__")return n[e]}function wx(n){return nx(n,od(n))}function Cx(n,e,t,i,s,r,o){var a=zr(n,t),h=zr(e,t),l=o.get(h);if(l){Lr(n,t,l);return}var c=r?r(a,h,t+"",n,e,o):void 0,d=c===void 0;if(d){var u=dr(h),p=!u&&hu(h),f=!u&&!p&&lu(h);c=h,u||p||f?dr(a)?c=a:vx(a)?c=sx(a):p?(d=!1,c=cu(h,!0)):f?(d=!1,c=du(h,!0)):c=[]:yx(h)||Oo(h)?(c=a,Oo(a)?c=wx(a):(!Ue(a)||uu(a))&&(c=pu(h))):d=!1}d&&(o.set(h,c),s(c,h,i,r,o),o.delete(h)),Lr(n,t,c)}function hd(n,e,t,i,s){n!==e&&fu(e,function(r,o){if(s||(s=new gu),Ue(r))Cx(n,e,o,t,hd,i,s);else{var a=i?i(zr(n,o),r,o+"",n,e,s):void 0;a===void 0&&(a=r),Lr(n,o,a)}},od)}var xh=rx(function(n,e,t,i){hd(n,e,t,i)}),_x="[object Number]";function Sh(n){return typeof n=="number"||jr(n)&&fl(n)==_x}function Mx(n,e,t,i){if(!Ue(n))return n;e=gl(e,n);for(var s=-1,r=e.length,o=r-1,a=n;a!=null&&++s<r;){var h=mu(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=Ue(c)?c:yu(e[s+1])?[]:{})}ul(a,h,l),a=a[h]}return n}function Px(n,e,t){for(var i=-1,s=e.length,r={};++i<s;){var o=e[i],a=xu(n,o);t(a,o)&&Mx(r,gl(o,n),a)}return r}function Ax(n,e){return Px(n,e,function(t,i){return Su(n,i)})}var Zn=dx(function(n,e){return n==null?{}:Ax(n,e)}),bh=bx("round"),Tx="Expected a function";function Pt(n,e,t){var i=!0,s=!0;if(typeof n!="function")throw new TypeError(Tx);return Ue(t)&&(i="leading"in t?!!t.leading:i,s="trailing"in t?!!t.trailing:s),ur(n,e,{leading:i,maxWait:e,trailing:s})}const So=(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 Rx(n){return n<.5?4*n*n*n:(n-1)*(2*n-2)*(2*n-2)+1}function ld(n,e=2){if(n==null)return n;if(Sh(n))return bh(n,e);if(dr(n))return bu(n,t=>ld(t,e));if(Ue(n)){const t=["x","y","rotation"];return vu(n,(i,s)=>Sh(i)&&t.includes(s)?bh(i,e):i)}return n}const vh=100,cd=2*1024,Kt="__log_summary__";function kx(n){return n.length>cd}function Ex(n){try{return JSON.stringify(n)}catch{return"[unserializable]"}}function wh(n){return typeof n=="string"?n.length:n instanceof ArrayBuffer||ArrayBuffer.isView(n)?n.byteLength:Ex(n).length}function Ix(n,e=3){return n.slice(0,e)}function Dx(n){if(Array.isArray(n))return n.length<=vh?n:{[Kt]:!0,type:"Array",size:n.length,byteLength:wh(n),sample:Ix(n)};if(ArrayBuffer.isView(n)&&!(n instanceof DataView)){const e=n;return e.length<=vh?n:{[Kt]:!0,type:n.constructor.name,size:e.length,byteLength:e.byteLength,sample:Array.from(n).slice(0,3)}}if(typeof n=="string")return kx(n)?{[Kt]:!0,type:"string",size:n.length,byteLength:n.length,sample:n.slice(0,200)}:n;if(typeof n=="object"&&n!==null){const e=wh(n);if(e<=cd)return n;const t=Object.keys(n);return{[Kt]:!0,type:"Object",size:t.length,byteLength:e,sample:t.slice(0,5).reduce((i,s)=>(i[s]=n[s],i),{})}}return n}function os(n){return n.map(Dx)}function Mt(n,e){if(!(typeof n!="object"||n===null))return n[e]}function Fx(n){const e=n[0],t=Mt(e,"mapHeader");return t?[{[Kt]:!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}]:os(n)}function Bx(n){const e=n[0];return typeof e!="object"||e===null?os(n):[{[Kt]:!0,source:"drawMap",id:Mt(e,"id"),size:Mt(e,"size"),resolution:Mt(e,"resolution"),origin:Mt(e,"origin"),status:Mt(e,"status")}]}function Lx(n){var t,i,s;const e=n[0];return typeof e!="object"||e===null?os(n):[{[Kt]:!0,source:"parsedRasterMapData",width:Mt(e,"width"),height:Mt(e,"height"),totalPixels:Mt(e,"totalPixels"),obstacleCount:((t=Mt(e,"obstacles"))==null?void 0:t.length)??void 0,carpetCount:((i=Mt(e,"carpet"))==null?void 0:i.length)??void 0,roomCount:((s=Mt(e,"rooms"))==null?void 0:s.size)??void 0}]}function bo(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=Mt(r,"x"),a=Mt(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 zx(n){const e=n[0],t=Mt(e,"pathHeader"),i=Mt(e,"pathPoints")??[];return t?[{[Kt]:!0,source:"drawPath",pathId:t.pathId,type:t.type,direction:t.direction,pointCount:i.length,bounds:bo(i)}]:os(n)}function Ox(n){const e=n[0],t=Mt(e,"pathPoints")??[];return[{[Kt]:!0,source:"drawFullPath",pointCount:t.length,bounds:bo(t)}]}function Wx(n){const e=Array.isArray(n[0])?n[0]:[];return[{[Kt]:!0,source:"drawIncrementalPath",pointCount:e.length,bounds:bo(e)}]}const Gx=[{match:"[Map] drawRasterMap",summarize:Fx},{match:"[Map] drawMap",summarize:Bx},{match:"[Map] Parsed Raster Map Data",summarize:Lx},{match:"[Path] drawPath",summarize:zx},{match:"[Path] Draw Full Path",summarize:Ox},{match:"[Path] Draw Incremental Path",summarize:Wx}];function Ux(n,e){if(e.length===0)return e;for(const t of Gx)if(n.includes(t.match))return t.summarize(e);return os(e)}const Hx="ray-robot-map-sdk",Ch=["warn","error"],Cs="%c[ray-2d-laser-map-sdk]%c ",Nx="%c[ray-2d-laser-map-sdk:DEBUG]%c ",Vx="background: #2196F3; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",$x="color: #2196F3;",Yx="background: #FF9800; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",Xx="color: #FF9800;",jx="background: #F44336; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",Zx="color: #F44336;",qx="background: #9C27B0; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",Kx="color: #9C27B0;",Qx="background: #4CAF50; color: white; padding: 2px 4px; border-radius: 3px; font-weight: bold;",Jx="color: #4CAF50;";let It={},ts=!1;function de(n){if(n)try{return n()}catch{return}}function tS(n){It={...It,...n},ts=!1}function eS(){return{config:{...It},appLogSinkWarned:ts}}function iS(n){It=n?{...n.config}:{},ts=(n==null?void 0:n.appLogSinkWarned)??!1}function sS(){const n=de(It.getLoggerConfig);if(typeof(n==null?void 0:n.enabled)=="boolean")return n.enabled;const e=de(It.isEnabled);if(typeof e=="boolean")return e;const t=de(It.getLegacyEnabled);return typeof t=="boolean"?t:!1}function nS(){const n=de(It.getLoggerConfig);if(typeof(n==null?void 0:n.tag)=="string"&&n.tag.length>0)return n.tag;const e=de(It.getTag);return typeof e=="string"&&e.length>0?e:Hx}function _s(n,e,t){return{level:n,message:e,data:t,tag:nS(),ts:Date.now()}}function rS(n){const e=de(It.getLoggerConfig);return typeof(e==null?void 0:e.appLogEnabled)=="boolean"?e.appLogEnabled?(e.appLogLevels??Ch).includes(n):!1:de(It.isAppLogEnabled)?(de(It.getAppLogLevels)??Ch).includes(n):!1}function oS(){const n=de(It.getLoggerConfig);return typeof(n==null?void 0:n.appLogSummary)=="boolean"?n.appLogSummary:!0}function Ms(n){if(!rS(n.level))return;const{appLogSink:e}=It;if(typeof e!="function")return;const t=oS()?{...n,data:Ux(n.message,n.data)}:n;try{e(t)}catch(i){if(ts)return;ts=!0,console.warn("[ray-robot-map-sdk] app logger bridge failed",i)}}function Ii(n,e,t,i,s,r){sS()&&console[n](`${e}${s}`,t,i,...r)}const C={log(n,...e){const t=_s("info",n,e);Ii("log",Cs,Vx,$x,n,e),Ms(t)},warn(n,...e){const t=_s("warn",n,e);Ii("warn",Cs,Yx,Xx,n,e),Ms(t)},error(n,...e){const t=_s("error",n,e);Ii("error",Cs,jx,Zx,n,e),Ms(t)},debug(n,...e){const t=_s("debug",n,e);Ii("log",Nx,qx,Kx,n,e),Ms(t)},success(n,...e){Ii("log",Cs,Qx,Jx,n,e)}},it=n=>n,Wt=n=>n,dd=n=>n.map(e=>({x:Wt(e.x),y:Wt(e.y)})),zi=(n,e)=>({x:Wt(n),y:Wt(e)}),_h=n=>{if(n.length<=1)return[...n];const e=aS(n),t=e.slice(1).map((s,r)=>({prev:e[r],current:s})),i=new Map;return t.forEach(({prev:s,current:r})=>{hS(s,r).forEach(a=>{const h=`${a.x},${a.y}`;i.has(h)||i.set(h,a)})}),Array.from(i.values())},aS=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]},hS=(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},Or=(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},lS=(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},qn=(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 kt(h,n)&&Vi(h,n)>=d?h:cS(n,h,d)},cS=(n,e,t)=>{const{minX:i,minY:s,maxX:r,maxY:o}=Vs(n),a=r-i,h=o-s,l=e.x,c=e.y,d=Math.min(.5,Math.min(a,h)*.05),u=[];if(kt({x:l,y:c},n)){const S=Vi({x:l,y:c},n);u.push({point:{x:l,y:c},distance:S,centerDistance:0})}const p=Math.max(a,h)*.6,f=Math.PI/16;let g=0;const m=1e4;let x=!1;for(let S=d;S<=p&&!x;S+=d){const b=f*(1+S/p);for(let v=0;v<2*Math.PI;v+=b){if(g++,g>m){C.error(`[findBestInnerPoint] Iteration limit reached (${g}). Room size: ${a}x${h}`),x=!0;break}const M=l+S*Math.cos(v),_=c+S*Math.sin(v);if(M>=i&&M<=r&&_>=s&&_<=o){const w={x:M,y:_};if(kt(w,n)){const P=Vi(w,n),A=K({x:M,y:_},{x:l,y:c});P>=t&&u.push({point:w,distance:P,centerDistance:A})}}}if(u.length>=15)break}if(u.length>0){const S=u.map(b=>({...b,score:b.distance*1.5-b.centerDistance*.5}));return S.sort((b,v)=>v.score-b.score),S[0].point}if(u.length===0){let S={x:l,y:c},b=0;const v=d*2;let M=0;const _=5e3;let w=!1;for(let P=i;P<=r&&!w;P+=v)for(let A=s;A<=o;A+=v){if(M++,M>_){C.error(`[findBestInnerPoint] Coarse search iteration limit reached. Room size: ${a}x${h}`),w=!0;break}const T={x:P,y:A};if(kt(T,n)){const R=Vi(T,n);R>b&&(b=R,S=T)}}return S}return{x:l,y:c}},Vi=(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=wi(n,r,o);t=Math.min(t,a)}return t},Mh=(n,e)=>e.length===1?K(n,e[0]):e.length===2?wi(n,e[0],e[1]):e.length===4?kt(n,e)?0:Vi(n,e):(C.warn(`[Distance] Invalid geometry: expected 1, 2 or 4 points, got ${e.length}`),1/0),wi=(n,e,t)=>{const i=(e.x-t.x)**2+(e.y-t.y)**2;if(i===0)return K(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 K(n,{x:r,y:o})},ud=(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=wi(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},kt=(n,e,t=!1)=>{if(e.length<3)return!1;if(t&&dS(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},dS=(n,e)=>{if(e.length<2)return!1;for(let t=0;t<e.length;t++){const i=(t+1)%e.length;if(uS(n,e[t],e[i]))return!0}return!1},uS=(n,e,t,i=.5)=>{if(wi(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},Vs=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}},Ye=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}},pS=(n,e,t)=>{if(n.length<4)return n;const[i,s,,r]=n,o=K(i,s),a=K(i,r),h=o<e||a<e,l=t!=null&&(o>t||a>t);if(!h&&!l)return n;const c=Ye(n),d=Dt(yt(i,s)),u=Dt(yt(i,r)),p=S=>{let b=S;return t!=null&&(b=Math.min(b,t)),Math.max(b,e)},f=p(o),g=p(a),m=f/2,x=g/2;return[zi(c.x-d.x*m-u.x*x,c.y-d.y*m-u.y*x),zi(c.x+d.x*m-u.x*x,c.y+d.y*m-u.y*x),zi(c.x+d.x*m+u.x*x,c.y+d.y*m+u.y*x),zi(c.x-d.x*m+u.x*x,c.y-d.y*m+u.y*x)]},fS=n=>{if(n.length!==4)return n;const e=Ye(n),t=K(n[0],n[1]),i=K(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=>zi(h.x*o-h.y*a+e.x,h.x*a+h.y*o+e.y))},Ps=(n,e,t,i=Wt(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)},K=(n,e)=>{const t=n.x-e.x,i=n.y-e.y;return Math.sqrt(t*t+i*i)},es=n=>Math.sqrt(n.x*n.x+n.y*n.y),yt=(n,e)=>({x:e.x-n.x,y:e.y-n.y}),Dt=n=>{const e=es(n);return e===0?{x:0,y:0}:{x:n.x/e,y:n.y/e}},pd=(n,e)=>{const t=yt(n,e);return Dt(t)},fd=n=>({x:-n.y,y:n.x}),gd=(n,e)=>{const t=pd(n,e);return fd(t)},md=(n,e)=>{const t=Dt(n),i=Dt(e),s={x:(t.x+i.x)/2,y:(t.y+i.y)/2};return Dt(s)},Fs=(n,e,t=0)=>{const i=yt(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},yd=(n,e,t)=>{const i=Ye([n,e]),s=gd(n,e);return{x:i.x+s.x*t,y:i.y+s.y*t}},gS=(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}},mS=(n,e,t)=>n.map(i=>gS(i,e,t)),yS=(n,e,t)=>{if(K(n,e)===0)return[n,n,n,n];const s=pd(n,e),r=fd(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}]},xS=(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=yt(s,r);if(es(a)===0){t.push(s);continue}const l=Dt(a),c={x:l.y,y:-l.x},d=yt(o,s),u=es(d);let p={x:0,y:0};if(u>0){const S=Dt(d);p={x:S.y,y:-S.x}}const f=md(p,c),g=p.x*c.x+p.y*c.y,m=1/Math.max(.1,Math.sqrt((1+g)/2)),x={x:s.x+f.x*e*m,y:s.y+f.y*e*m};t.push(x)}return t},xd=(n,e,t)=>{if(K(n,e)===0)return[];const s=gd(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]},Sd=(n,e,t,i)=>{const s=yt(n,e),r=yt(n,t),o=md(s,r),a={x:-o.x,y:-o.y};return{x:n.x+a.x*i,y:n.y+a.y*i}},SS=(n,e,t,i,s,r)=>{const o=new Set(n),a=bS(n,e),h=vS(a,o,e,t,i,s,r);return h||a},bS=(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}},vS=(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=is(a,h,l,c),f=is(a,h,d,u);if(!p||!f)return null;const g=[],m=Math.max(i,Math.min(p.x,f.x)),x=Math.min(r,Math.max(p.x,f.x)),S=Math.round(n.y);for(let b=Math.round(m);b<=Math.round(x);b++){const v=S*t+b;e.has(v)&&g.push({x:b,y:S})}if(g.length>=2){const b=wS(g),v={x:(b.min.x+b.max.x)/2,y:(b.min.y+b.max.y)/2},M=Math.round(v.y)*t+Math.round(v.x);if(e.has(M))return v}return null},is=(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}},wS=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}},Kn=(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)}),CS=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}},_S=(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)}},MS=(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(Ph(n,t,i,s,r)||Ph(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 f=u[p],g=u[(p+1)%4];if(is(n,e,f,g))return!0}return!1},Ph=(n,e,t,i,s)=>n.x>=e&&n.x<=e+i&&n.y>=t&&n.y<=t+s,PS=(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}]},AS=(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]},TS=255,Bs=n=>n>=TS,Wr=(n,e,t)=>{const i=Vs(n),s=Vs(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),f=Math.floor(u.y/l),g=`${p},${f}`;c.has(g)||c.set(g,[]),c.get(g).push(u)}const d=t*t;for(const u of h){const p=Math.floor(u.x/l),f=Math.floor(u.y/l);for(let g=-1;g<=1;g++)for(let m=-1;m<=1;m++){const x=`${p+g},${f+m}`,S=c.get(x);if(S)for(const b of S){const v=u.x-b.x,M=u.y-b.y;if(v*v+M*M<=d)return!0}}}return!1},Qn=(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 f=c+u,m=(d+p)*t+f;if(o.has(m)&&u*u+p*p<=a)return!0}}return!1},Ah=(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},RS=(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),f=n.indexOf(c),g=-p*.5+d*.5;return-f*.5+u*.5-g}),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 f=p[0],g=r.get(f)||new Set,m=new Set;for(const x of g){if(x===l)continue;const S=s.get(x);S!==void 0&&m.add(S)}for(let x=0;x<t;x++)if(x!==u&&!m.has(x))return o[u]--,o[x]++,s.set(f,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 f=s.get(p);f!==void 0&&d.add(f)}let u=-1;if(i==="priority"){let p=-1,f=-1/0;for(let g=0;g<t;g++)if(!d.has(g)){const m=t-g,x=o[g]*.7,S=m-x;(S>f||S===f&&g<p)&&(f=S,p=g)}if(u=p,u===-1&&(u=h(l.id)),u===-1){C.warn(`[FourColor] Room ${l.id}: recolor failed, falling back to least-conflict color`);let g=1/0;for(let m=0;m<t;m++){let x=0;for(const S of c)s.get(S)===m&&x++;(x<g||x===g&&m<u)&&(g=x,u=m)}}o[u]++}else{const p=[];for(let f=0;f<t;f++)d.has(f)||p.push(f);if(p.length===0){if(u=h(l.id),u===-1){C.warn(`[FourColor] Room ${l.id}: recolor failed, falling back to least-conflict color`);let f=1/0,g=0;for(let m=0;m<t;m++)(o[m]<f||o[m]===f&&m<g)&&(f=o[m],g=m);u=g}}else{u=p[0];let f=o[u];for(const g of p)(o[g]<f||o[g]===f&&g<u)&&(u=g,f=o[g])}o[u]++}s.set(l.id,u)}return s},kS=Symbol(),Th=Object.getPrototypeOf,Gr=new WeakMap,ES=n=>n&&(Gr.has(n)?Gr.get(n):Th(n)===Object.prototype||Th(n)===Array.prototype),IS=n=>ES(n)&&n[kS]||null,Rh=(n,e=!0)=>{Gr.set(n,e)},$s={},vo=n=>typeof n=="object"&&n!==null,DS=n=>vo(n)&&!wo.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),bd=(n,e)=>{const t=kh.get(n);if((t==null?void 0:t[0])===e)return t[1];const i=Array.isArray(n)?[]:Object.create(Object.getPrototypeOf(n));return Rh(i,!0),kh.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(wo.has(r))Rh(r,!1);else if($e.has(r)){const[h,l]=$e.get(r);a.value=bd(h,l())}Object.defineProperty(i,s,a)}),Object.preventExtensions(i)},FS=(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&&(Eh(l,o)||Ys.has(o)&&Eh(l,Ys.get(o))))return!0;t(r),vo(o)&&(o=IS(o)||o);const c=!$e.has(o)&&LS(o)?Ur(o):o;return e(r,c),Reflect.set(s,r,c,a),i(["set",[r],o,l]),!0}}),$e=new WeakMap,wo=new WeakSet,kh=new WeakMap,Jn=[1],Ys=new WeakMap;let Eh=Object.is,BS=(n,e)=>new Proxy(n,e),LS=DS,zS=bd,OS=FS;function Ur(n={}){if(!vo(n))throw new Error("object required");const e=Ys.get(n);if(e)return e;let t=Jn[0];const i=new Set,s=(m,x=++Jn[0])=>{t!==x&&(r=t=x,i.forEach(S=>S(m,x)))};let r=t;const o=(m=Jn[0])=>(r!==m&&(r=m,h.forEach(([x])=>{const S=x[1](m);S>t&&(t=S)})),t),a=m=>(x,S)=>{const b=[...x];b[1]=[m,...b[1]],s(b,S)},h=new Map,l=(m,x)=>{const S=!wo.has(x)&&$e.get(x);if(S){if(($s?"production":void 0)!=="production"&&h.has(m))throw new Error("prop listener already exists");if(i.size){const b=S[2](a(m));h.set(m,[S,b])}else h.set(m,[S])}},c=m=>{var x;const S=h.get(m);S&&(h.delete(m),(x=S[1])==null||x.call(S))},d=m=>(i.add(m),i.size===1&&h.forEach(([S,b],v)=>{if(($s?"production":void 0)!=="production"&&b)throw new Error("remove already exists");const M=S[2](a(v));h.set(v,[S,M])}),()=>{i.delete(m),i.size===0&&h.forEach(([S,b],v)=>{b&&(b(),h.set(v,[S]))})});let u=!0;const p=OS(()=>u,l,c,s),f=BS(n,p);Ys.set(n,f);const g=[n,o,d];return $e.set(f,g),Reflect.ownKeys(n).forEach(m=>{const x=Object.getOwnPropertyDescriptor(n,m);"value"in x&&x.writable&&(f[m]=n[m])}),u=!1,f}function nn(n,e,t){const i=$e.get(n);($s?"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 WS(n){const e=$e.get(n);($s?"production":void 0)!=="production"&&!e&&console.warn("Please use proxy object");const[t,i]=e;return zS(t,i())}function z(n,e,t,i){let s=n[e];return nn(n,()=>{const r=n[e];Object.is(s,r)||t(s=r)})}class GS extends W{constructor(t){super();y(this,"dragStart",null);y(this,"initialTouchDistance",null);y(this,"initialScale",null);y(this,"activeTouches",new Map);y(this,"firstTouchId",null);y(this,"secondTouchId",null);y(this,"taintedPointers",new Set);y(this,"zoomFactor",.8);y(this,"scaleMin",.2);y(this,"scaleMax",5);y(this,"originalPosition",{x:0,y:0});y(this,"targetPosition",{x:0,y:0});y(this,"centerPosition",{x:0,y:0});y(this,"originalScale",{x:1,y:1});y(this,"targetScale",{x:1,y:1});y(this,"defaultScale",{x:1,y:1});y(this,"transitionDuration",500);y(this,"transitionStartTime",null);y(this,"initialPinchCenter",null);y(this,"isGestureValid",!0);y(this,"lastTapTime",0);y(this,"doubleTapDelay",300);y(this,"doubleTapZoomFactor",1.5);y(this,"lastTapPosition",null);y(this,"tapDistanceThreshold",20);y(this,"tapDetectionEnabled",!0);y(this,"mapClickStartPosition",null);y(this,"mapClickStartTime",0);y(this,"mapClickTimeThreshold",300);y(this,"mapClickMoveThreshold",10);y(this,"shouldSuppressMapClick",!1);y(this,"isGestureHijacked",!1);y(this,"hijackedPointerId",null);y(this,"isHijackPaused",!1);y(this,"activeGestureSession",null);y(this,"interactionGraphics");y(this,"viewportBounds");y(this,"boundResetAnimation");y(this,"debouncedStopWheelRender");y(this,"debouncedLogWheelScale");y(this,"interactionState",{isInteracting:!1,isAnimating:!1,interactionTimer:null,renderReasons:new Set});y(this,"throttledAntiScale");y(this,"unsubscribeEnableInteraction",null);y(this,"suppressMapClick",()=>{this.shouldSuppressMapClick=!0});y(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=z(t.runtime,"enableInteraction",s=>{this.updateInteractionMode(s)}),this.updateInteractionMode(t.runtimeSnapshot.enableInteraction),this.interactionGraphics=new O,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=Pt(s=>{this.appService.emitter.emit("antiScale",s)},16,{leading:!0,trailing:!0}),this.boundResetAnimation=this.resetAnimation.bind(this),this.debouncedStopWheelRender=ur(()=>{i.stopRender("wheel")},300),this.debouncedLogWheelScale=ur(s=>{C.debug("[Interaction] 滚轮缩放完成 - Scale:",s.toFixed(3))},500),this.setupInteraction()}updateInteractionMode(t){this.eventMode=t?"static":"none",C.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=>{C.debug("[Interaction] Received global pointercancel"),this.handleGlobalCancel(t)})}handleGlobalCancel(t){const i=this.appService;if(this.isGestureHijacked){C.debug("[Interaction] 系统取消或移出视口,强制结束劫持手势");const s=i.getApp(),r=new oh(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},C.debug("[Interaction] Set center position:",this.centerPosition)),r&&i&&(this.defaultScale={x:i.x,y:i.y},C.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),C.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=(m=>Math.pow(Math.min(1,m/1e3),.5))(c),f=((m,x)=>Math.pow(Math.min(1,Math.abs(m-x)/Math.abs(.2-1)),.5))(l.scale.x,this.targetScale.x),g=u*.8+f*.2;this.transitionDuration=500+1e3*Math.min(1,Math.pow(g,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){C.debug("[Interaction] 强制结束劫持手势");const t=this.appService.getApp(),i=new oh(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"),C.debug("[Interaction] 动画缩放完成 - Scale:",s.scale.x.toFixed(3));else{const l=Rx(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){C.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 g=a-l*u,m=h-c*p;try{o.scale.set(u,p),o.position.set(g,m),this.antiScale(u),this.debouncedLogWheelScale(u)}catch(x){C.error("❌ [onWheel] 应用缩放时发生错误:",x)}}onPointerDown(t){var l,c;const i=this.appService;C.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&&(C.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){C.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)&&(C.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),C.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&&(C.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&&(C.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,C.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&&K(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=K(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)};C.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,f=r.scale.y*h;p=Math.max(o,Math.min(a,p)),f=Math.max(o,Math.min(a,f)),this.originalPosition={x:r.x,y:r.y},this.originalScale={x:r.scale.x,y:r.scale.y};const g=l-d*p,m=c-u*f;this.targetPosition={x:g,y:m},this.targetScale={x:p,y:f},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 return;if(!this.activeTouches.has(t.pointerId)||!this.isGestureValid||this.taintedPointers.size>0&&(this.initialTouchDistance!==null||this.initialScale!==null))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)}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},C.debug("[Interaction] applyPan",{pointerId:t.pointerId,dx:h,dy:l})}applyPinchZoom(){var g;const i=this.appService.appContainer,s=Array.from(this.activeTouches.values());if(s.length<2||!this.initialTouchDistance||!this.initialScale||!this.initialPinchCenter)return;const r=K(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),C.debug("[Interaction] applyPinchZoom",{newScaleX:l,initialScale:(g=this.initialScale)==null?void 0:g.x,scaleRatio:h});let d=o.x-a.x*l,u=o.y-a.y*c;const p=o.x-this.initialPinchCenter.x,f=o.y-this.initialPinchCenter.y;d+=p,u+=f,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=K(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 US(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 HS="__ray_robot_map_debug_ring__",vd="__ray_robot_map_late_lifecycle_markers__",NS=200,VS=20;function $S(){return Date.now()}function YS(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,10)}`}function Co(){try{return globalThis.localStorage??null}catch{return null}}function XS(){var n;try{return((n=globalThis.document)==null?void 0:n.visibilityState)??null}catch{return null}}function jS(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 Ih(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=>jS(s)).filter(s=>s!==null):[]}catch{return[]}}function ZS(n,e,t){if(n)try{n.setItem(e,JSON.stringify(t))}catch{}}function qS(n){if(!n)return{};try{const e=n.getItem(vd);if(!e)return{};const t=JSON.parse(e);return typeof t=="object"&&t?t:{}}catch{return{}}}function KS(n=Co()){return qS(n)}function QS(n=Co()){if(n)try{n.removeItem(vd)}catch{}}function JS(n={}){var f;const e=n.storage===void 0?Co():n.storage,t=n.storageKey??HS,i=n.maxEntries??NS,s=n.previousTailSize??VS,r=n.now??$S,o=((f=n.createSessionId)==null?void 0:f.call(n))??YS(),a=Ih(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=()=>Ih(e,t);return{getSessionId:()=>o,hasStorage:()=>e!==null,readAll:c,readCurrentSession:()=>c().filter(g=>g.sessionId===o),readPreviousSessionTail:()=>h?c().filter(g=>g.sessionId===h).slice(-s):[],readLateLifecycleMarkers:()=>KS(e),clear:()=>{if(QS(e),!!e)try{e.removeItem(t)}catch{}},record:g=>{l+=1;const m={seq:l,ts:r(),event:g.event,sessionId:o,instanceId:g.instanceId??null,visibilityState:g.visibilityState??XS(),rendererType:g.rendererType??null,mapId:g.mapId??null,detail:g.detail},x=[...c(),m].slice(-i);return ZS(e,t,x),m}}}let tr=null;function er(){return tr||(tr=JS()),tr}class wd{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 WS(this.getApp().runtime)}isInteractionEnabled(){return this.runtimeSnapshot.enableInteraction}fixPrecision(e,t){return ld(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 tb=3.28084,ir=100,Dh=5;class eb{constructor(e=()=>"meter"){y(this,"cmPerPixel",null);y(this,"fallbackWarned",!1);y(this,"getDisplayUnit");this.getDisplayUnit=e}setResolution(e){if(!Number.isFinite(e)||e<=0){C.warn("[CoordinateSpace] Ignoring invalid resolution",e);return}this.cmPerPixel=e}isReady(){return this.cmPerPixel!=null}toPixels(e){const t=this.resolveResolution("toPixels");return Wt(e*(ir/t))}toMeters(e){const t=this.resolveResolution("toMeters");return it(e*(t/ir))}toDisplayUnit(e){switch(this.getDisplayUnit()){case"feet":return e*tb;case"centimeter":return e*ir;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=pS(e,i,s);return fS(r)}resolveResolution(e){return this.cmPerPixel==null?(this.fallbackWarned||(this.fallbackWarned=!0,C.warn(`[CoordinateSpace] ${e} called before map resolution is ready, falling back to default ${Dh}cm/pixel. This happens when the device reports an invalid map resolution (e.g. 0) or when converting before the first map draw.`)),Dh):this.cmPerPixel}}let ib="useandom-26T198340PX75pxJACKVERYMINDBUSHWOLF_GQZbfghjklqvwyzrict",Fh=(n=21)=>{let e="",t=n|0;for(;t--;)e+=ib[Math.random()*64|0];return e};const mi=(n,e,t)=>{if(e!=null){if(typeof e!="number"||!Number.isFinite(e)||e<=n){C.warn(`[${t}] maxSize (${String(e)}) must be a finite number greater than minSize (${n}); ignoring.`);return}return e}};class sb extends W{constructor(t,i){super();y(this,"viewportBounds",{x:0,y:0,width:0,height:0});y(this,"maskGraphics",null);y(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 O,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):(C.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 nb="interaction",Cd="roomFill",_d="free",_o="roomFloorType",Md="carpet",Pd="obstacle",Ad="heatmap",Td="path",Le="furniture",Se="controls",Rd="roomInfo",ni="detectedObject",$i="customElement",Yi="customElementGif",kd="chargingStation",Ed="robot",hi="customCarpet",We="editControls",rb=[nb,Cd,_d,_o,Md,hi,Pd,Ad,Td,Le,Rd,ni,$i,Yi,kd,Ed,Se,We],ob=[Se,We,hi,$i,Yi,ni,Le];class ab extends W{constructor(t){super();y(this,"layers",new Map);y(this,"mapRotation",0);y(this,"backgroundGraphics");y(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 O,this.backgroundGraphics.label="snapshotBackground",this.backgroundGraphics.visible=!1,this.addChild(this.backgroundGraphics),this.initializeLayers()}initializeLayers(){Object.values(rb).forEach(i=>{const s=new W;s.label=i,i===Se&&(s.isRenderGroup=!0),i===We&&(s.isRenderGroup=!0),i===_o&&(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):(C.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){ob.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 et(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 te extends Qt{constructor(t,i){super(i);y(this,"throttledUpdateScale");y(this,"fixedWidth",0);y(this,"fixedHeight",0);y(this,"isFixedSizeSet",!1);y(this,"sizeFixed",!0);y(this,"baselineScale",1);y(this,"basePositionX",0);y(this,"basePositionY",0);y(this,"pixelOffset",null);this.appService=t,this.anchor.set(.5),this.visible=!1,this.throttledUpdateScale=Pt(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=So(this.pixelOffset,t,i);this.position.set(this.basePositionX+s.x,this.basePositionY+s.y)}set width(t){if(this.isFixedSizeSet){C.warn("EnhancedSprite: 使用 setFixedSize() 方法来设置宽度");return}this.setFixedSize(t,this.fixedHeight||t)}set height(t){if(this.isFixedSizeSet){C.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 X.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){C.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 hb extends te{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 Id extends O{constructor(t,i){super();y(this,"currentPosition",null);y(this,"config");y(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(it(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,f=p*(h/d);for(let g=0;g<u;g++){const m=g*p/i,x=(g*p+f)/i,S=Math.max(4,Math.ceil(Math.abs(x-m)*i/2)),b=(x-m)/S;for(let v=0;v<=S;v++){const M=m+b*v,_=t.x+i*Math.cos(M),w=t.y+i*Math.sin(M);v===0?this.moveTo(_,w):this.lineTo(_,w)}}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 bt{constructor(e,t={}){y(this,"target");y(this,"isPointerDown",!1);y(this,"pointerDownPos",null);y(this,"clickThreshold");y(this,"stopPropagation");y(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 lb extends W{constructor(t){super();y(this,"chargingStation");y(this,"ring");y(this,"unsubscribeFns",[]);y(this,"clickHandler");this.appService=t,t.appContainer.addToLayer(kd,this),this.ring=new Id(this.appService,{config:this.appService.chargingStationConfig.ring}),this.ring.visible=this.appService.runtimeSnapshot.showChargingStationRing,this.addChild(this.ring),this.chargingStation=new hb(this.appService),this.addChild(this.chargingStation);const i=z(this.appService.runtime,"showChargingStationRing",s=>{C.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 bt(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 cb extends W{constructor(t){super({isRenderGroup:!0});y(this,"carpetSprite",null);y(this,"carpetMask",null);this.appService=t,this.appService.appContainer.addToLayer(Md,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 X.load(r);if(!h){C.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 Ns({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 W;u.addChild(l),d.mask=u,this.addChild(d),this.carpetSprite=d,this.carpetMask=u,s.getApp().renderOnceNextFrame()}createCarpetGraphics(t,i){const s=new O;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 X.load(s);if(!a){C.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 Ns({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 W;d.addChild(h),c.mask=d,this.addChild(c),this.carpetSprite=c,this.carpetMask=d,i.getApp().renderOnceNextFrame()}createCarpetGraphicsFromStructuredData(t){const i=new O;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 Bh extends O{constructor(e){super(),this.appService=e,this.appService.appContainer.addToLayer(_d,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 Lh extends O{constructor(e){super(),this.appService=e,this.appService.appContainer.addToLayer(Pd,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+=me){const r=Math.min(s+me,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 we extends W{constructor(t,i){super();y(this,"borderOptions");y(this,"solidLine",null);y(this,"dashGraphics",null);y(this,"fillGraphics",null);y(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 O,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 O;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){C.warn("Invalid dashArray:",s.dashArray);return}const r=this.appService;this.dashGraphics=new O;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){C.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),f=(u-c)/l.length,g=(p-c)/l.length,m={x:l.start.x+(l.end.x-l.start.x)*f,y:l.start.y+(l.end.y-l.start.y)*f},x={x:l.start.x+(l.end.x-l.start.x)*g,y:l.start.y+(l.end.y-l.start.y)*g};a?h&&Math.sqrt(Math.pow(m.x-h.x,2)+Math.pow(m.y-h.y,2))>.1&&t.lineTo(m.x,m.y):(t.moveTo(m.x,m.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()}}const Ce=n=>{const e=n.length;if(e<3)return 0;let t=0;for(let i=0;i<e;i++){const s=n[i],r=n[(i+1)%e];t+=s.x*r.y-r.x*s.y}return t/2},zh=n=>Math.abs(Ce(n)),db=(n,e)=>{const t=zh(e);return t===0?1/0:(zh(n)-t)/t},Oh=(n,e)=>{if(e.length<3||n.length<2)return 0;let t=0;const i=s=>{if(!kt(s,e,!1))return;let r=1/0;for(let o=0;o<e.length;o++)r=Math.min(r,wi(s,e[o],e[(o+1)%e.length]));t=Math.max(t,r)};for(let s=0;s<n.length;s++){const r=n[s],o=n[(s+1)%n.length];i(r),i({x:(r.x+o.x)/2,y:(r.y+o.y)/2})}return t},Wh=(n,e)=>{const t=n.length,i=c=>e?c.x:c.y;let s=1/0,r=-1/0;for(const c of n){const d=i(c);d<s&&(s=d),d>r&&(r=d)}const o=Math.max(1,t),a=Math.max(1e-9,(r-s)/o),h=Array.from({length:o},()=>[]),l=c=>Math.min(o-1,Math.max(0,Math.floor((c-s)/a)));for(let c=0;c<t;c++){const d=i(n[c]),u=i(n[(c+1)%t]),p=l(Math.min(d,u)),f=l(Math.max(d,u));for(let g=p;g<=f;g++)h[g].push(c)}return{min:s,width:a,buckets:h}},ub=n=>({points:n,x:Wh(n,!0),y:Wh(n,!1)}),pb=(n,e,t)=>{const{points:i}=n,s=e?n.x:n.y,{min:r,width:o,buckets:a}=s,h=Math.min(a.length-1,Math.max(0,Math.floor((t-r)/o))),l=[];for(const c of a[h]){const d=i[c],u=i[(c+1)%i.length],p=e?d.x:d.y,f=e?u.x:u.y;if(p<=t&&f>t||f<=t&&p>t){const g=(t-p)/(f-p);l.push(e?d.y+g*(u.y-d.y):d.x+g*(u.x-d.x))}}return l},Gh=new WeakMap,rn=(n,e,t)=>{let i=Gh.get(n);return i||(i=ub(n),Gh.set(n,i)),pb(i,e,t)},Mo=.5,ss=n=>{const e=n.length;let t=1/0,i=-1/0;for(const u of n)u.y<t&&(t=u.y),u.y>i&&(i=u.y);const s=Math.max(1,e),r=Math.max(1e-9,(i-t)/s),o=u=>Math.min(s-1,Math.max(0,Math.floor((u-t)/r))),a=new Uint32Array(s+1);for(let u=0;u<e;u++){const p=n[u].y,f=n[(u+1)%e].y,g=o(Math.min(p,f)),m=o(Math.max(p,f));for(let x=g;x<=m;x++)a[x+1]++}for(let u=0;u<s;u++)a[u+1]+=a[u];const h=new Uint32Array(a[s]),l=a.slice(0,s);for(let u=0;u<e;u++){const p=n[u].y,f=n[(u+1)%e].y,g=o(Math.min(p,f)),m=o(Math.max(p,f));for(let x=g;x<=m;x++)h[l[x]++]=u}const c=u=>{const p=o(u.y);let f=0;for(let g=a[p];g<a[p+1];g++){const m=h[g],x=n[m],S=n[(m+1)%e];if(x.y<=u.y&&S.y>u.y||S.y<=u.y&&x.y>u.y){const b=(u.y-x.y)/(S.y-x.y);u.x<x.x+b*(S.x-x.x)&&f++}}return f%2===1},d=(u,p)=>{const f=o(u.y-p),g=o(u.y+p);for(let m=f;m<=g;m++)for(let x=a[m];x<a[m+1];x++){const S=h[x];if(wi(u,n[S],n[(S+1)%e])<=p)return!1}return!0};return{isInsideByCrossings:c,distanceToBoundaryExceeds:d,contains:u=>e>=3&&(!d(u,Mo)||c(u))}},Hr=(n,e,t)=>{if(e.length<3)return!0;const i=ss(e),s=Math.max(Mo,t);for(const r of n)if(!i.isInsideByCrossings(r)&&i.distanceToBoundaryExceeds(r,s))return!0;return!1},fb=(n,e,t,i)=>{if(e.length<3)return!0;const s=Math.max(Mo,t),r=i.minX-s,o=i.maxX+s,a=i.minY-s,h=i.maxY+s;let l=null;for(const c of n)if(!(c.x<r||c.x>o||c.y<a||c.y>h)&&(l||(l=ss(e)),!l.isInsideByCrossings(c)&&l.distanceToBoundaryExceeds(c,s)))return!0;return!1},Uh=1e-9,Ls=1e-6,gb=n=>{const e=n.length,t=[];for(let d=0;d<e;d++){const u=n[d],p=n[(d+1)%e],f=p.x-u.x,g=p.y-u.y;if(Math.hypot(f,g)<Uh)continue;const m=Math.abs(f)>=Math.abs(g),x=m?f:g;t.push({horizontal:m,dir:x>=0?1:-1,perpA:m?u.y:u.x,perpB:m?p.y:p.x,start:u})}const i=t.length;if(i<3)return null;const s=Ce(n);if(Math.abs(s)<Uh)return null;const r=s>0?1:-1;let o=-1;for(let d=0;d<i;d++){const u=t[(d-1+i)%i];if(t[d].horizontal!==u.horizontal||t[d].dir!==u.dir){o=d;break}}if(o===-1)return null;const a=[];let h=0;for(;h<i;){const d=t[(o+h)%i];let u=1/0,p=-1/0,f=h;for(;f<i;){const g=t[(o+f)%i];if(g.horizontal!==d.horizontal||g.dir!==d.dir)break;u=Math.min(u,g.perpA,g.perpB),p=Math.max(p,g.perpA,g.perpB),f++}a.push({horizontal:d.horizontal,dir:d.dir,perpMin:u,perpMax:p,entry:d.start}),h=f}const l=[],c=d=>{const u=d.horizontal?-r*d.dir:r*d.dir;l.push({horizontal:d.horizontal,rep:u>0?d.perpMax:d.perpMin})};return a.forEach((d,u)=>{u>0&&a[u-1].horizontal===d.horizontal&&l.push({horizontal:!d.horizontal,rep:d.horizontal?d.entry.x:d.entry.y}),c(d)}),a.length>1&&a[a.length-1].horizontal===a[0].horizontal&&l.push({horizontal:!a[0].horizontal,rep:a[0].horizontal?a[0].entry.x:a[0].entry.y}),l},mb=(n,e)=>{const t=n.length,i=n[(e-1+t)%t],s=n[(e+1)%t];return Math.abs(s.rep-i.rep)},yi=n=>{const e=n.length,t=[];for(let i=0;i<e;i++){const s=n[(i-1+e)%e],r=n[i];r.horizontal?t.push({x:s.rep,y:r.rep}):t.push({x:r.rep,y:s.rep})}return t},Dd=(n,e,t)=>{const i=n.length,s=(e-1+i)%i,r=(e+1)%i,o={horizontal:n[s].horizontal,rep:t},a=[];for(let h=0;h<i;h++)h===e||h===r||a.push(h===s?o:n[h]);return a},Fd=(n,e)=>{const t=n.length,i=(e-1+t)%t,s=(e+1)%t,r=Math.min(n[(e-2+t)%t].rep,n[e].rep,n[(e+2)%t].rep),o=Math.max(n[(e-2+t)%t].rep,n[e].rep,n[(e+2)%t].rep),a=Math.min(n[i].rep,n[s].rep),h=Math.max(n[i].rep,n[s].rep);return n[i].horizontal?{minX:r,maxX:o,minY:a,maxY:h}:{minX:a,maxX:h,minY:r,maxY:o}},Bd=(n,e)=>{const t=n.length,i=n[(e-1+t)%t].rep,s=n[(e+1)%t].rep;return i===s?[i]:[i,s]},yb=(n,e)=>{for(let i=0;i<16;i++){const s=yi(n),r=n.length,o=Ce(s)>0?1:-1,a=n.map((d,u)=>{const p=s[u],f=s[(u+1)%r];if(d.horizontal){const m=f.x-p.x>=0?1:-1;return{lo:Math.min(p.x,f.x),hi:Math.max(p.x,f.x),outward:-o*m}}const g=f.y-p.y>=0?1:-1;return{lo:Math.min(p.y,f.y),hi:Math.max(p.y,f.y),outward:o*g}}),h=ss(s),l=new Map;let c=!1;for(const d of e){if(h.contains(d))continue;c=!0;let u=-1,p=1/0;for(let m=0;m<r;m++){const x=a[m],S=n[m].horizontal?d.x:d.y,v=((n[m].horizontal?d.y:d.x)-n[m].rep)*x.outward;if(v<=0)continue;const M=Math.max(0,x.lo-S,S-x.hi),_=Math.hypot(M,v);_<p&&(p=_,u=m)}if(u===-1)continue;const f=n[u].horizontal?d.y:d.x,g=l.get(u);(g===void 0||(f-g)*a[u].outward>0)&&l.set(u,f)}if(!c||l.size===0)return;l.forEach((d,u)=>{n[u].rep=d})}},xb=(n,e,t)=>{let i=n;const s=new Set;let r=!Hr(t,yi(i),Ls);for(;i.length>4;){const o=i.length;let a=-1,h=1/0;for(let u=0;u<o;u++){if(s.has(i[u]))continue;const p=mb(i,u);p<h&&(h=p,a=u)}if(a===-1||h>=e)break;const l=Bd(i,a),c=Fd(i,a);let d=null;for(const u of l){const p=Dd(i,a,u),f=yi(p);if(r?fb(t,f,Ls,c):Hr(t,f,Ls))continue;const m=Math.abs(Ce(f));(!d||m<d.area)&&(d={runs:p,area:m})}d?(i=d.runs,r=!0,s.clear()):s.add(i[a])}return i},Sb=n=>{let e=1/0,t=-1/0,i=1/0,s=-1/0;return n.forEach(r=>{r.horizontal?(r.rep<i&&(i=r.rep),r.rep>s&&(s=r.rep)):(r.rep<e&&(e=r.rep),r.rep>t&&(t=r.rep))}),{minX:e,maxX:t,minY:i,maxY:s}},Hh=(n,e)=>n.x>=e.minX&&n.x<=e.maxX&&n.y>=e.minY&&n.y<=e.maxY,bb=(n,e,t,i)=>{let s=n;const r=Sb(s),o=i.neighborPoints.filter(a=>Hh(a,r));for(;s.length>4&&s.length>i.targetEdges;){const a=yi(s),h=Math.abs(Ce(a)),l=o.length?ss(a):null,c=s.length;let d=null;for(let u=0;u<c;u++){const p=Fd(s,u),f=o.filter(g=>Hh(g,p));for(const g of Bd(s,u)){const m=Dd(s,u,g);if(m.length<4)continue;const x=yi(m);if(Hr(e,x,Ls))continue;const S=Math.abs(Ce(x)),b=m.length===4?i.rectangleInflation??i.maxInflation:i.maxInflation;if((S-t)/t>b)continue;if(f.length>0&&l){const M=ss(x);if(f.some(w=>M.contains(w)&&!l.contains(w)))continue}const v=S-h;(!d||v<d.added)&&(d={runs:m,added:v})}}if(!d)break;s=d.runs}return s},vb=(n,e,t,i)=>{const s=gb(n);if(!s||s.length<4)return null;yb(s,e);const r=xb(s,t,e),o=i?bb(r,e,Math.abs(Ce(n))||1,i):r;if(o.length<4)return null;const a=yi(o);return a.length<4?null:a},Rt=1e-6,Po=1e-6,wb=1,ri=.25,Cb=64,Ld=1,Nh=n=>{const e=n.length,t=Ce(n)>0?1:-1,i=[];for(let s=0;s<e;s++){const r=(s+1)%e,o=n[s],a=n[r],h=a.x-o.x,l=a.y-o.y;if(Math.abs(h)<Rt&&Math.abs(l)>=Rt){const c=l>=0?1:-1;i.push({i:s,j:r,horizontal:!1,pos:(o.x+a.x)/2,lo:Math.min(o.y,a.y),hi:Math.max(o.y,a.y),outward:t*c})}else if(Math.abs(l)<Rt&&Math.abs(h)>=Rt){const c=h>=0?1:-1;i.push({i:s,j:r,horizontal:!0,pos:(o.y+a.y)/2,lo:Math.min(o.x,a.x),hi:Math.max(o.x,a.x),outward:-t*c})}}return i},As=(n,e,t,i)=>n.some(s=>s.horizontal===e.horizontal&&Math.abs(s.pos-e.pos)<=Po&&Math.min(s.hi,i)-Math.max(s.lo,t)>Rt),_b=(n,e,t,i,s,r)=>{const o=(u,p)=>u.filter(f=>f.horizontal===p.horizontal&&Math.abs(f.pos-p.pos)<=Po&&Math.min(f.hi,e)-Math.max(f.lo,n)>Rt).map(f=>[Math.max(f.lo,n),Math.min(f.hi,e)]),a=[...o(t,i),...o(s,r)].sort((u,p)=>u[0]-p[0]);let h=0,l=-1/0,c=n;const d=(u,p)=>{const f=l-h;p-u>Math.max(f,Ld)&&(h=u,l=p)};for(const[u,p]of a)d(c,u),c=Math.max(c,p);return d(c,e),l>h?[h,l]:null},Vh=(n,e,t,i,s,r)=>{const o=rn(n,e,t);if(o.length<2)return null;o.sort((h,l)=>h-l);let a=null;for(let h=0;h+1<o.length;h+=2){const l=o[h],c=o[h+1];c<=i||l>=s||(r>0?a=a===null?c:Math.max(a,c):a=a===null?l:Math.min(a,l))}return a},zd=(n,e,t,i,s,r,o)=>{let a=r,h=o;const l=(c,d)=>{c!==null&&(d>0?a=Math.max(a,c):h=Math.min(h,c))};if(l(Vh(n,t.horizontal,s,r,o,t.outward),t.outward),l(Vh(e,i.horizontal,s,r,o,i.outward),i.outward),a>h){const c=Math.min(o,Math.max(r,(a+h)/2));return{strictLo:a,strictHi:h,slackLo:Math.max(r,c-ri),slackHi:Math.min(o,c+ri)}}return{strictLo:a,strictHi:h,slackLo:Math.max(r,a-ri),slackHi:Math.min(o,h+ri)}},Xs=(n,e,t)=>Math.min(t,Math.max(e,n)),Nr=.25,$h=(n,e,t,i)=>{const s=[];for(const r of n){const o=e?r.x:r.y,a=o-Nr,h=o+Nr;a>t&&a<i&&s.push(a),h>t&&h<i&&s.push(h)}return s},Ao=(n,e,t,i,s)=>{const r=[],o=Math.max(1,Math.round((s-i)/wb)),a=(s-i)/o;for(let l=0;l<o;l++)r.push(i+(l+.5)*a);r.push(...$h(n,t,i,s)),r.push(...$h(e,t,i,s)),r.sort((l,c)=>l-c);const h=[];for(const l of r)(h.length===0||l-h[h.length-1]>Nr/4)&&h.push(l);return h},Mb=(n,e,t,i,s,r,o)=>{const a=Math.min(t.lo,i.lo),h=Math.max(t.hi,i.hi);let l=s,c=r,d=s,u=r;for(const p of Ao(n,e,t.horizontal,a,h)){const f=zd(n,e,t,i,p,s,r);if(l=Math.max(l,f.strictLo),c=Math.min(c,f.strictHi),d=Math.max(d,f.slackLo),u=Math.min(u,f.slackHi),d>u)return null}return l<=c?Xs(o,l,c):Xs(o,d,u)},Pb=(n,e,t,i,s,r,o,a,h)=>{const l=Ao(n,e,t.horizontal,s,r),c=l.map(v=>zd(n,e,t,i,v,o,a)),d=c.length,u=v=>v<=0?s:v>=d?r:(l[v-1]+l[v])/2,p=[];let f=0,g=c[0].strictLo,m=c[0].strictHi,x=c[0].slackLo,S=c[0].slackHi;const b=v=>{const M=g<=m?Xs(h,g,m):Xs(h,x,S);p.push({from:u(f),to:u(v),pos:M})};for(let v=1;v<d;v++){const M=Math.max(x,c[v].slackLo),_=Math.min(S,c[v].slackHi);M>_?(b(v),f=v,g=c[v].strictLo,m=c[v].strictHi,x=c[v].slackLo,S=c[v].slackHi):(x=M,S=_,g=Math.max(g,c[v].strictLo),m=Math.min(m,c[v].strictHi))}return b(d),p},Yh=(n,e,t,i,s,r)=>{if(!n)return!1;for(const o of Ao(n,n,e,i,s)){const a=rn(n,e,o);if(!(a.length<2)){a.sort((h,l)=>h-l);for(let h=0;h+1<a.length;h+=2)if(t>0&&a[h+1]>r+ri||t<0&&a[h]<r-ri)return!1}}return!0},sr=(n,e,t,i,s)=>{const r=[];if(t-n.lo>Rt){const o=e[0].pos,a=(o-n.pos)*n.outward<0&&Yh(s,n.horizontal,n.outward,n.lo,t,o);r.push({from:n.lo,to:t,pos:a?o:n.pos})}if(r.push(...e),n.hi-i>Rt){const o=e[e.length-1].pos,a=(o-n.pos)*n.outward<0&&Yh(s,n.horizontal,n.outward,i,n.hi,o);r.push({from:i,to:n.hi,pos:a?o:n.pos})}return Ab(r)},Ab=n=>{const e=[];for(const t of n){const i=e[e.length-1];i&&Math.abs(i.pos-t.pos)<=Po?i.to=t.to:e.push({...t})}return e},Tb=n=>{let e=n;for(let t=0;t<8;t++){const i=e.length;if(i<=4)return e;const s=[];for(let r=0;r<i;r++){const o=e[(r-1+i)%i],a=e[r],h=e[(r+1)%i];if(Math.abs(a.x-o.x)<=Rt&&Math.abs(a.y-o.y)<=Rt)continue;const l=Math.abs(o.x-a.x)<=Rt&&Math.abs(a.x-h.x)<=Rt,c=Math.abs(o.y-a.y)<=Rt&&Math.abs(a.y-h.y)<=Rt;l||c||s.push(a)}if(s.length===e.length)return s;e=s}return e},Di=(n,e,t)=>{e.horizontal?(n[e.i]={x:n[e.i].x,y:t},n[e.j]={x:n[e.j].x,y:t}):(n[e.i]={x:t,y:n[e.i].y},n[e.j]={x:t,y:n[e.j].y})},nr=(n,e,t)=>{const i=l=>e.horizontal?l.x:l.y,s=(l,c)=>e.horizontal?{x:l,y:c}:{x:c,y:l},r=i(n[e.i])<=i(n[e.j]),o=r?t:[...t].reverse(),a=[];o.forEach((l,c)=>{const d=r?l.from:l.to;c===0||a.push(s(d,o[c-1].pos)),a.push(s(d,l.pos))});const h=o[o.length-1];a.push(s(r?h.to:h.from,h.pos)),e.j===e.i+1?n.splice(e.i,2,...a):(n[e.i]=a[0],n[e.j]=a[a.length-1],n.push(...a.slice(1,-1)))},Rb=(n,e,t,i,s)=>{const r={};if(Object.keys(n).forEach(u=>{r[Number(u)]=n[Number(u)]}),t<=0||e.length===0)return r;const o=new Set;e.forEach(([u,p])=>{o.add(u),o.add(p)});const a=new Map,h=new Map,l=new Map;o.forEach(u=>{const p=n[u];if(!p)return;a.set(u,p.map(g=>({x:g.x,y:g.y}))),l.set(u,[]);const f=s==null?void 0:s[u];f&&f.length>=3&&h.set(u,f)});const c=new Set;return[...e].sort((u,p)=>u[0]-p[0]||u[1]-p[1]).forEach(([u,p])=>{const f=a.get(u),g=a.get(p);if(!f||!g)return;const m=(i==null?void 0:i[`${Math.min(u,p)}-${Math.max(u,p)}`])??t,x=l.get(u),S=l.get(p);for(let b=0;b<Cb;b++){const v=Nh(f),M=Nh(g);let _=!1;for(const w of v){for(const P of M){if(w.horizontal!==P.horizontal||w.outward===P.outward)continue;const A=Math.max(w.lo,P.lo),T=Math.min(w.hi,P.hi);if(T-A<=Ld)continue;const k=(P.pos-w.pos)*w.outward<0?m:t;if(Math.abs(w.pos-P.pos)>k)continue;const I=_b(A,T,x,w,S,P),B=Math.min(w.pos,P.pos),N=Math.max(w.pos,P.pos),E=(w.pos+P.pos)/2;if(!I){const wt=As(x,w,A,T),ee=As(S,P,A,T);if(wt&&ee)continue;const je=wt?w.pos:P.pos,$t=wt?g:f,Lt=wt?P:w,ie=wt?S:x,Yt=wt?p:u,Ci=sr(Lt,[{from:A,to:T,pos:je}],A,T,h.get(Yt));Ci.length===1?Di($t,Lt,Ci[0].pos):nr($t,Lt,Ci),ie.push({horizontal:Lt.horizontal,pos:je,lo:A,hi:T}),c.add(Yt),_=!0;break}const[D,q]=I,L=h.get(u),Y=h.get(p),$=As(x,w,w.lo,w.hi),st=As(S,P,P.lo,P.hi),vt=$||st,mt=$?w.pos:st?P.pos:E,_t=vt?null:L&&Y?Mb(L,Y,w,P,B,N,E):E;if(_t!==null){Di(f,w,_t),Di(g,P,_t);const wt={horizontal:w.horizontal,pos:_t,lo:D,hi:q};x.push(wt),S.push({...wt}),c.add(u),c.add(p),_=!0;break}const Tt=L&&Y?Pb(L,Y,w,P,D,q,B,N,mt):[{from:D,to:q,pos:mt}],fe=sr(w,Tt,D,q,L),Xe=sr(P,Tt,D,q,Y);fe.length===1?Di(f,w,fe[0].pos):nr(f,w,fe),Xe.length===1?Di(g,P,Xe[0].pos):nr(g,P,Xe),Tt.forEach(wt=>{const ee={horizontal:w.horizontal,pos:wt.pos,lo:wt.from,hi:wt.to};x.push(ee),S.push({...ee})}),c.add(u),c.add(p),_=!0;break}if(_)break}if(!_)break}}),c.forEach(u=>{r[u]=Tb(a.get(u))}),r},Fe=1e-6,kb=2,To=1,Eb=2,Ib=3,Db=14,Xh=8,jh=14,Zh=n=>{const e=n.length,t=[];for(let r=0;r<e;r++){const o=n[r],a=n[(r+1)%e],h=a.x-o.x,l=a.y-o.y;Math.abs(h)<Fe&&Math.abs(l)>=Fe?t.push({horizontal:!1,pos:(o.x+a.x)/2,lo:Math.min(o.y,a.y),hi:Math.max(o.y,a.y)}):Math.abs(l)<Fe&&Math.abs(h)>=Fe&&t.push({horizontal:!0,pos:(o.y+a.y)/2,lo:Math.min(o.x,a.x),hi:Math.max(o.x,a.x)})}const i=(r,o)=>r.horizontal===o.horizontal&&Math.abs(r.pos-o.pos)<Fe&&Math.max(r.lo,o.lo)<=Math.min(r.hi,o.hi)+Fe,s=[];for(const r of t){const o=s[s.length-1];o&&i(o,r)?(o.lo=Math.min(o.lo,r.lo),o.hi=Math.max(o.hi,r.hi)):s.push({...r})}if(s.length>1){const r=s[0],o=s[s.length-1];i(r,o)&&(r.lo=Math.min(r.lo,o.lo),r.hi=Math.max(r.hi,o.hi),s.pop())}return s},qh=(n,e)=>rn(n,!1,e),Kh=(n,e)=>rn(n,!0,e),Ts=(n,e)=>{let t,i=1/0;for(const s of n){const r=Math.abs(s-e);r<i&&(i=r,t=s)}return t},Qh=2.5*To,Jh=2,Fb=(n,e,t,i,s,r)=>{const o=[],a=[];let h=-1,l=-1;for(let f=s;f<=r+Fe;f+=To){let g,m;if(t?(g=Ts(Kh(n,f),i),m=Ts(Kh(e,f),i)):(g=Ts(qh(n,f),i),m=Ts(qh(e,f),i)),o.push(f),g===void 0||m===void 0){a.push("other");continue}if(Math.abs(g-i)>jh||Math.abs(m-i)>jh){a.push("other");continue}h<0&&(h=o.length-1),l=o.length-1;const x=Math.abs(g-m);x<=Eb?a.push("open"):x>=Ib&&x<=Db?a.push("wall"):a.push("other")}const c=h>=0?o[h]:s,d=l>=0?o[l]:r,u=[];let p=-1;for(let f=0;f<=a.length;f++){const g=f<a.length&&a[f]==="open";if(g&&p<0)p=f;else if(!g&&p>=0){const m=o[p],x=o[f-1];u.push({start:m,end:x,wallBefore:a.slice(0,p).includes("wall"),wallAfter:a.slice(f).includes("wall"),touchesLo:m-c<=Qh,touchesHi:d-x<=Qh}),p=-1}}return{runs:u,lo:c,hi:d}},rr=n=>n.touchesLo&&n.wallAfter,or=n=>n.touchesHi&&n.wallBefore,ar=n=>n.end-n.start,Bb=(n,e,t)=>{const i={};if(t.length===0)return i;const s=new Map,r=new Map,o=h=>{if(s.has(h))return!0;const l=n[h],c=e[h];return!l||!c||c.length<3?!1:(s.set(h,l),r.set(h,c),!0)},a=(h,l)=>{i[h]||(i[h]=[]),i[h].push(l)};return t.forEach(([h,l])=>{if(!o(h)||!o(l))return;const c=Zh(s.get(h)),d=Zh(s.get(l)),u=r.get(h),p=r.get(l),f=[];c.forEach(g=>{d.forEach(m=>{if(g.horizontal!==m.horizontal||Math.abs(g.pos-m.pos)>kb)return;const x=Math.max(g.lo,m.lo),S=Math.min(g.hi,m.hi);if(S-x<To)return;const b=(g.pos+m.pos)/2,v=Fb(u,p,g.horizontal,b,x,S);v.runs.forEach(M=>{const _=M.wallBefore&&M.wallAfter,w=rr(M)||or(M);f.push({horizontal:g.horizontal,posA:g.pos,posB:m.pos,lo:v.lo,hi:v.hi,run:M,ok:(_||w)&&ar(M)>=Xh})})})});for(const g of f)if(!g.horizontal)for(const m of f){if(!m.horizontal)continue;const x=[];rr(g.run)&&x.push(g.lo),or(g.run)&&x.push(g.hi);const S=[];rr(m.run)&&S.push(m.lo),or(m.run)&&S.push(m.hi),x.some(v=>S.some(M=>Math.abs((g.posA+g.posB)/2-M)<=Jh&&Math.abs((m.posA+m.posB)/2-v)<=Jh))&&ar(g.run)+ar(m.run)>=Xh&&(g.ok=!0,m.ok=!0)}f.forEach(g=>{if(!g.ok)return;const{run:m}=g,x=m.touchesLo?g.lo:m.start,S=m.touchesHi?g.hi:m.end;a(h,tl(g.horizontal,g.posA,x,S)),a(l,tl(g.horizontal,g.posB,x,S))})}),i},tl=(n,e,t,i)=>({start:n?{x:t,y:e}:{x:e,y:t},end:n?{x:i,y:e}:{x:e,y:i}}),ae=.01,Lb=(n,e)=>{const t=n.length;if(t<2)return[];const i=new Array(t+1);i[0]=0;for(let d=0;d<t;d++){const u=n[d],p=n[(d+1)%t];i[d+1]=i[d]+Math.hypot(p.x-u.x,p.y-u.y)}const s=i[t];if(s===0)return[];const r=[];if(e.forEach(d=>{for(let u=0;u<t;u++){const p=n[u],f=n[(u+1)%t],g=f.x-p.x,m=f.y-p.y,x=Math.hypot(g,m);if(x===0)continue;const S=g/x,b=m/x,v=el(d.start,p,S,b,x),M=el(d.end,p,S,b,x);if(v===void 0||M===void 0)continue;const _=i[u]+Math.min(v,M),w=i[u]+Math.max(v,M);w-_>ae&&r.push([_,w]);break}}),r.length===0)return[[...n,n[0]]];r.sort((d,u)=>d[0]-u[0]);const o=[];for(const d of r){const u=o[o.length-1];u&&d[0]<=u[1]+ae?u[1]=Math.max(u[1],d[1]):o.push([d[0],d[1]])}const a=[];let h=0;for(const[d,u]of o)d-h>ae&&a.push([h,d]),h=u;s-h>ae&&a.push([h,s]);const l=d=>{let u=0;for(;u<t&&i[u+1]<d;)u++;u>=t&&(u=t-1);const p=n[u],f=n[(u+1)%t],g=i[u+1]-i[u],m=g===0?0:(d-i[u])/g;return{x:p.x+(f.x-p.x)*m,y:p.y+(f.y-p.y)*m}},c=[];for(const[d,u]of a){const p=[l(d)];for(let f=1;f<=t;f++)i[f]>d+ae&&i[f]<u-ae&&p.push(n[f%t]);p.push(l(u)),p.length>=2&&c.push(p)}return c},el=(n,e,t,i,s)=>{const r=n.x-e.x,o=n.y-e.y,a=r*t+o*i;if(!(Math.abs(r*i-o*t)>ae)&&!(a<-ae||a>s+ae))return Math.max(0,Math.min(s,a))},zb=n=>{if(typeof n=="number")return{r:n>>16&255,g:n>>8&255,b:n&255};if(typeof n!="string")return null;let e=n.trim().replace(/^#/,"");if(e.length===3&&(e=e.split("").map(i=>i+i).join("")),!/^[0-9a-fA-F]{6}$/.test(e))return null;const t=Number.parseInt(e,16);return{r:t>>16&255,g:t>>8&255,b:t&255}},Ob=(n,e)=>{const t=zb(n);if(!t)return C.warn(`[Beautify] Unsupported shell base color: ${String(n)}`),16777215;const i=Math.min(1,Math.max(0,e)),s=r=>Math.round(r+(255-r)*i);return s(t.r)<<16|s(t.g)<<8|s(t.b)},Wb=.8,Gb=4e6,Ub=(n,e,t)=>{if(e<=0||t<=0||n.length===0)return new Uint32Array(0);const i=e*t,s=new Uint8Array(i);for(let o=0;o<n.length;o++){const a=n[o];a<i&&(s[a]=1)}const r=[];for(let o=0;o<n.length;o++){const a=n[o];if(a>=i||s[a]!==1)continue;s[a]=2;const h=a%e,l=Math.floor(a/e);(h===0||h===e-1||l===0||l===t-1||s[a-1]===0||s[a+1]===0||s[a-e]===0||s[a+e]===0)&&r.push(a)}return Uint32Array.from(r)},Hb=(n,e,t)=>{if(e<=0||t<=0||n.length===0)return null;const i=t+1,s=(w,P)=>w*i+P,r=w=>Math.floor(w/i),o=w=>w%i,a=e*t,h=new Uint8Array(a);let l=0;for(let w=0;w<n.length;w++){const P=n[w];P<a&&h[P]===0&&(h[P]=1,l++)}if(l===0)return null;const c=(w,P)=>w<0||P<0||w>=e||P>=t?!1:h[P*e+w]!==0,d=new Map,u=(w,P,A,T)=>{const R=s(w,P),k=s(A,T),I=d.get(R);I?I.push(k):d.set(R,[k])};for(let w=0;w<n.length;w++){const P=n[w];if(P>=a||h[P]!==1)continue;h[P]=2;const A=P%e,T=Math.floor(P/e);c(A,T-1)||u(A,T,A+1,T),c(A+1,T)||u(A+1,T,A+1,T+1),c(A,T+1)||u(A+1,T+1,A,T+1),c(A-1,T)||u(A,T+1,A,T)}const p=(w,P)=>{const A=Math.sign(r(P)-r(w)),T=Math.sign(o(P)-o(w));return A===1?0:T===1?1:A===-1?2:3},f=(w,P)=>w*4+p(w,P),g=new Set,m=[];d.forEach((w,P)=>{for(const A of w){if(g.has(f(P,A)))continue;const T=[P];let R=P,k=A,I=0;for(;k!==void 0&&I++<Gb&&(g.add(f(R,k)),T.push(k),k!==P);){const B=d.get(k);if(!B||B.length===0)break;const N=p(R,k),E=[(N+3)%4,N,(N+1)%4,(N+2)%4];let D;for(const q of E){for(const L of B)if(!g.has(f(k,L))&&p(k,L)===q){D=L;break}if(D!==void 0)break}R=k,k=D}m.push(T)}});const x=w=>{const P=w.map(R=>({x:r(R),y:o(R)}));P.length>1&&P[0].x===P[P.length-1].x&&P[0].y===P[P.length-1].y&&P.pop();const A=[],T=P.length;for(let R=0;R<T;R++){const k=P[(R-1+T)%T],I=P[R],B=P[(R+1)%T];(I.x-k.x)*(B.y-I.y)-(I.y-k.y)*(B.x-I.x)===0||A.push(I)}return A},S=w=>{let P=0;for(let A=0;A<w.length;A++){const T=w[A],R=w[(A+1)%w.length];P+=T.x*R.y-R.x*T.y}return P/2};let b=null,v=0,M=0;for(const w of m){const P=x(w);if(P.length<3)continue;const A=S(P);A<=0||(M+=A,A>v&&(v=A,b=P))}if(!b||M<=0||v/M<Wb)return null;const _=[];for(const w of b)_.push(w.x,w.y);return _},Nb=2,Vb=6,$b=.8,Yb=4,Xb=.8,jb=1.5,Zb=1.5,qb=7,Kb=3,Qb=n=>{const e=[];for(let t=0;t+1<n.length;t+=2)e.push({x:n[t],y:n[t+1]});return e},Jb=n=>n.some(e=>!isFinite(e.x)||!isFinite(e.y)),tv=(n,e)=>{const t=[...n,n[0]],i=ud(t,e);return i.pop(),i},ev=(n,e,t)=>{const i=[];return e.forEach(s=>{if(s===t)return;const r=n[s];if(r)for(let o=0;o<r.length;o++)i.push(r[o])}),i},iv=n=>n.length>=3&&!Jb(n),sv=(n,e,t,i)=>{const s=Object.keys(n).map(Number).filter(o=>{var a;return(a=e[o])==null?void 0:a.shell}),r=[];for(let o=0;o<s.length;o++)for(let a=o+1;a<s.length;a++){const h=s[o],l=s[a];(i?i(h,l):Wr(n[h]??[],n[l]??[],t))&&r.push([h,l])}return r},nv=.5,rv=2,ov=(n,e,t)=>{if(t<=0)return{pairs:e,pairTolerances:{}};const i=Object.keys(n).map(Number).filter(h=>{var l;return(l=n[h])==null?void 0:l.shell}),s=(h,l)=>`${Math.min(h,l)}-${Math.max(h,l)}`,r=new Set(e.map(([h,l])=>s(h,l))),o=[...e],a={};for(let h=0;h<i.length;h++)for(let l=h+1;l<i.length;l++){const c=i[h],d=i[l],u=n[c].shell,p=n[d].shell,f=Math.max(Oh(u,p),Oh(p,u));if(f<=nv)continue;const g=s(c,d);r.has(g)||o.push([c,d]);const m=f+rv;m>t&&(a[g]=m)}return{pairs:o,pairTolerances:a}},av=(n,e,t)=>{const{wallSnapTolerance:i,outlines:s}=t;if(i<=0)return;const{pairs:r,pairTolerances:o}=e;if(r.length===0)return;const a={};r.forEach(([l,c])=>{var d,u;(d=n[l])!=null&&d.shell&&(a[l]=n[l].shell),(u=n[c])!=null&&u.shell&&(a[c]=n[c].shell)});const h=Rb(a,r,i,o,s);Object.keys(a).map(Number).forEach(l=>{h[l]!==a[l]&&(n[l]={...n[l],shell:h[l]})})},hv=(n,e,t)=>{if(t.length===0)return;const i={},s={};t.forEach(([o,a])=>{[o,a].forEach(h=>{var l;(l=e[h])!=null&&l.shell&&!i[h]&&(i[h]=e[h].shell,s[h]=n[h]??[])})});const r=Bb(i,s,t);Object.keys(r).forEach(o=>{const a=Number(o);r[a].length>0&&(e[a]={...e[a],doorways:r[a]})})},il=(n,e,t)=>{const i=e.wallSnapTolerance??qb,s=e.adjacencyThreshold??Kb,r=e.level==="boxy",o=r?Zb:$b,a=Object.keys(n).map(Number),h={};a.forEach(u=>{var p;h[u]=Qb(((p=n[String(u)])==null?void 0:p.coordinates)??[])});const l={};a.forEach(u=>{const p=h[u];if(!iv(p)){l[u]={shell:null,footprint:null,fellBack:!0};return}const f=tv(p,Nb);if(f.length<3){l[u]={shell:null,footprint:null,fellBack:!0};return}const g=p,m=vb(f,p,Vb,r?{maxInflation:Xb,rectangleInflation:jb,targetEdges:Yb,neighborPoints:ev(h,a,u)}:void 0);if(m&&m.length>=4&&db(m,f)<=o){l[u]={shell:m,footprint:g,fellBack:!1};return}l[u]={shell:null,footprint:null,fellBack:!0}});const c=sv(h,l,s,t),d=ov(l,c,i);return av(l,d,{wallSnapTolerance:i,outlines:h}),hv(h,l,d.pairs),l};class sl extends W{constructor(t){super({isRenderGroup:!0});y(this,"roomGraphicsMap",new Map);y(this,"roomContextMap",new Map);y(this,"roomClickHandlerMap",new Map);y(this,"unsubscribeFns",[]);y(this,"mapWidth",0);y(this,"rasterRoomDataMap",new Map);y(this,"structuredRoomGeometry",new Map);y(this,"shellBorderMap",new Map);y(this,"footprintGraphicsMap",new Map);y(this,"footprintContextMap",new Map);this.appService=t,this.appService.appContainer.addToLayer(Cd,this);const i=nn(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=Bs(a.id),l=new O,c=new nt,d=new nt,u=new nt;let p,f,g;const m=a.colorIndex??0;h?(p=a.color,f=a.color,g=a.color):(p=s.colors.active[m%s.colors.active.length],f=s.colors.inactive[m%s.colors.inactive.length],g=(s.colors.normal||s.colors.active)[m%(s.colors.normal||s.colors.active).length]);const x=a.shell?a.shell.map(_=>({x:_.x+.5,y:_.y+.5})):void 0,S=x==null?void 0:x.flatMap(_=>[_.x,_.y]),b=S&&a.footprint?a.footprint.flatMap(_=>[_.x+.5,_.y+.5]):void 0,v={polyPoints:a.polyPoints,outlinePoints:a.outlinePoints,shellPolyPoints:S};this.fillStructuredContext(c,p,v,m),this.fillStructuredContext(d,f,v,m),this.fillStructuredContext(u,g,v,m);const M=h?"activeContext":o?r.includes(a.id)?"activeContext":"inactiveContext":"normalContext";if(l.context=M==="activeContext"?c:M==="inactiveContext"?d:u,this.roomGraphicsMap.set(a.id,l),this.roomContextMap.set(a.id,{activeContext:c,inactiveContext:d,normalContext:u}),this.addChild(l),S&&b&&(this.createFootprintLayer(a.id,b,{activeColor:p,inactiveColor:f,normalColor:g}),this.applyFootprintState(a.id,M)),x){const _=a.doorways&&a.doorways.length>0?a.doorways.map(w=>({start:{x:w.start.x+.5,y:w.start.y+.5},end:{x:w.end.x+.5,y:w.end.y+.5}})):void 0;this.createShellBorder(a.id,x,_)}if(!h){const _=new bt(l,{clickThreshold:10,onClick:()=>{this.handleRoomClick(a.id)}});this.roomClickHandlerMap.set(a.id,_),this.structuredRoomGeometry.set(a.id,{polyPoints:a.polyPoints,outlinePoints:a.outlinePoints,colorIndex:m,shellPolyPoints:S,footprintPolyPoints:b})}})}fillStructuredContext(t,i,s,r){if(s.shellPolyPoints){t.setFillStyle({color:this.resolveShellColor(i,r)}),t.poly(s.shellPolyPoints).fill();return}t.setFillStyle({color:i}),t.poly(s.polyPoints).fill(),s.outlinePoints.forEach(o=>{t.rect(o.x,o.y,1,1).fill()})}resolveShellColor(t,i){const s=this.appService.roomConfig.colors.shell;return s&&s.length>0?s[i%s.length]:Ob(t,this.appService.mapConfig.beautify.shellLightenRatio)}createFootprintLayer(t,i,s){const r=new O,o=new nt,a=new nt,h=new nt;this.fillFootprintContext(o,s.activeColor,i),this.fillFootprintContext(a,s.inactiveColor,i),this.fillFootprintContext(h,s.normalColor,i),r.context=h,r.eventMode="none",this.footprintGraphicsMap.set(t,r),this.footprintContextMap.set(t,{activeContext:o,inactiveContext:a,normalContext:h}),this.addChild(r)}fillFootprintContext(t,i,s){t.setFillStyle({color:i}),t.poly(s).fill()}applyFootprintState(t,i){const s=this.footprintGraphicsMap.get(t),r=this.footprintContextMap.get(t);s&&r&&(s.context=r[i])}createShellBorder(t,i,s){const r=this.appService.mapConfig,o={color:r.obstacleColor,width:r.beautify.borderWidth,isDashed:!1,dashArray:[4,2]};if(!s||s.length===0){const l=new we(this.appService,{points:i,closePath:!0,style:o});this.shellBorderMap.set(t,[l]),this.addChild(l);return}const a=Lb(i,s),h=[];a.forEach(l=>{if(l.length<2)return;const c=new we(this.appService,{points:l,closePath:!1,style:o});h.push(c),this.addChild(c)}),this.shellBorderMap.set(t,h)}drawRaster(t,i){const s=this.appService;if(this.clearRooms(),this.mapWidth=t.width,t.sortedRooms.length===0)return;const{selectRoomIds:r,enableRoomSelection:o}=s.runtimeSnapshot;t.sortedRooms.forEach(a=>{const h=typeof a.roomId=="number"?i==null?void 0:i.get(a.roomId):void 0;h?this.drawBeautifiedRasterRoom(a,h,o,r):this.drawRasterRoom(a,o,r)})}drawBeautifiedRasterRoom(t,i,s,r){const{roomId:o,activeColor:a,inactiveColor:h}=t;if(typeof o!="number")return;const l=this.appService.roomConfig,c=t.colorIndex??0,d=(l.colors.normal||l.colors.active)[c%(l.colors.normal||l.colors.active).length],u=i.shell.flatMap(M=>[M.x,M.y]),p=i.footprint.flatMap(M=>[M.x,M.y]),f={polyPoints:[],outlinePoints:[],shellPolyPoints:u},g=new O,m=new nt,x=new nt,S=new nt;this.fillStructuredContext(m,a,f,c),this.fillStructuredContext(x,h,f,c),this.fillStructuredContext(S,d,f,c);const b=s?r.includes(o)?"activeContext":"inactiveContext":"normalContext";g.context=b==="activeContext"?m:b==="inactiveContext"?x:S,this.addChild(g),this.createFootprintLayer(o,p,{activeColor:a,inactiveColor:h,normalColor:d}),this.applyFootprintState(o,b),this.createShellBorder(o,i.shell,i.doorways);const v=new bt(g,{clickThreshold:10,onClick:()=>{this.handleRoomClick(o)}});this.roomClickHandlerMap.set(o,v),this.roomGraphicsMap.set(o,g),this.roomContextMap.set(o,{activeContext:m,inactiveContext:x,normalContext:S}),this.rasterRoomDataMap.set(o,t),this.structuredRoomGeometry.set(o,{polyPoints:[],outlinePoints:[],colorIndex:c,shellPolyPoints:u,footprintPolyPoints:p})}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 O,f=new nt,g=new nt,m=new nt;f.setFillStyle({color:a}),g.setFillStyle({color:h}),m.setFillStyle({color:d}),this.drawPixelPointsInBatches(f,o,me,this.mapWidth),this.drawPixelPointsInBatches(g,o,me,this.mapWidth),this.drawPixelPointsInBatches(m,o,me,this.mapWidth);const x=u&&s.includes(r);if(p.context=i?u&&x?f:g:m,u){const S=new bt(p,{clickThreshold:10,onClick:()=>{this.handleRoomClick(r)}});this.roomClickHandlerMap.set(r,S)}this.roomGraphicsMap.set(r,p),this.roomContextMap.set(r,{activeContext:f,inactiveContext:g,normalContext:m}),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){const h=s?t.includes(o)?"activeContext":"inactiveContext":"normalContext";r.context=a[h],this.applyFootprintState(o,h)}}})}setRoomState(t,i){const s=this.roomGraphicsMap.get(t),r=this.roomContextMap.get(t);if(!s||!r){C.warn(`Room ${t} not found`);return}if(typeof t!="number")return;const o=i?"activeContext":"inactiveContext";s.context=r[o],this.applyFootprintState(t,o)}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 C.warn("[RoomFill] Map state not available"),!1;if(!t||t.length!==2)return C.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 C.warn("[RoomFill] Map state not available"),!1;if(!t||t.length!==4)return C.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(Or(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(kt(t,o.outlinePoints,!0)||kt(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(is(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(kt({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(kt(a,o.outlinePoints,!0))return!0;for(const a of o.outlinePoints)if(kt(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(is(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),f=h<c?1:-1,g=l<d?1:-1;let m=u-p,x=h,S=l;for(;;){if(x>=0&&x<this.mapWidth&&S>=0&&S<o){const v=S*this.mapWidth+x;a.push(v)}if(x===c&&S===d)break;const b=2*m;b>-p&&(m-=p,x+=f),b<u&&(m+=u,S+=g)}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 f=u;f<=p;f++)for(let g=c;g<=d;g++){const m=f*this.mapWidth+g;l.push(m)}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(),this.fillStructuredContext(a.activeContext,c,h,l),a.inactiveContext.clear(),this.fillStructuredContext(a.inactiveContext,d,h,l),a.normalContext.clear(),this.fillStructuredContext(a.normalContext,u,h,l);const p=this.footprintContextMap.get(o);p&&h.footprintPolyPoints&&(p.activeContext.clear(),this.fillFootprintContext(p.activeContext,c,h.footprintPolyPoints),p.inactiveContext.clear(),this.fillFootprintContext(p.inactiveContext,d,h.footprintPolyPoints),p.normalContext.clear(),this.fillFootprintContext(p.normalContext,u,h.footprintPolyPoints));const f=i?t.includes(o)?"activeContext":"inactiveContext":"normalContext";r.context=a[f],this.applyFootprintState(o,f)}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,me,this.mapWidth),a.inactiveContext.clear(),a.inactiveContext.setFillStyle({color:u}),this.drawPixelPointsInBatches(a.inactiveContext,l.pixelIndices,me,this.mapWidth),a.normalContext.clear(),a.normalContext.setFillStyle({color:p}),this.drawPixelPointsInBatches(a.normalContext,l.pixelIndices,me,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){C.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){C.warn("Error destroying graphics context:",i)}}),this.roomContextMap.clear(),this.roomClickHandlerMap.forEach(t=>{try{t.destroy()}catch(i){C.warn("Error destroying click handler:",i)}}),this.roomClickHandlerMap.clear(),this.footprintGraphicsMap.forEach(t=>{try{t.destroy()}catch(i){C.warn("Error destroying footprint graphics:",i)}}),this.footprintGraphicsMap.clear(),this.footprintContextMap.forEach(t=>{try{t.activeContext.destroy(),t.inactiveContext.destroy(),t.normalContext.destroy()}catch(i){C.warn("Error destroying footprint context:",i)}}),this.footprintContextMap.clear(),this.shellBorderMap.forEach(t=>{t.forEach(i=>{try{i.destroy()}catch(s){C.warn("Error destroying shell border:",s)}})}),this.shellBorderMap.clear(),this.removeChildren(),this.rasterRoomDataMap.clear(),this.structuredRoomGeometry.clear())}destroy(){this.unsubscribeFns.forEach(t=>t()),this.unsubscribeFns=[],this.clearRooms(),super.destroy()}}class lv{constructor(e){y(this,"obstacle");y(this,"free");y(this,"roomFill");y(this,"carpet");y(this,"chargingStation");y(this,"mapBounds",{minX:0,minY:0,maxX:0,maxY:0});y(this,"lastMapId",null);y(this,"lastOrigin",null);y(this,"lastSize",null);y(this,"lastStatus",null);y(this,"roomGeometryMap",new Map);y(this,"shellCenterMap",new Map);y(this,"rasterRoomPixelsMap",new Map);y(this,"fourColorCache",null);y(this,"carpetData",null);y(this,"structuredMapData",null);y(this,"rasterMapData",null);y(this,"unsubscribeFns",[]);this.appService=e,this.obstacle=new Lh(this.appService),this.free=new Bh(this.appService),this.roomFill=new sl(this.appService),this.carpet=new cb(this.appService),this.chargingStation=new lb(this.appService),this.validateColorConfig();const t=z(e.runtime,"enableRoomSelection",a=>{if(C.log(`[runtime] enableRoomSelection: ${a}`),a){this.roomFill.setAllRoomsState(!1);const h=this.appService.runtimeSnapshot.selectRoomIds;this.roomFill.setRoomStateBySelectIds(h)}else this.roomFill.setAllRoomsState(!0)}),i=z(e.runtime,"selectRoomIds",a=>{C.log(`[runtime] selectRoomIds: ${a}`),this.roomFill.setRoomStateBySelectIds(a)}),s=z(e.runtime,"showChargingStation",a=>{C.log(`[runtime] showChargingStation: ${a}`),this.chargingStation.visible=a}),r=z(e.runtime,"showCarpet",a=>{C.log(`[runtime] showCarpet: ${a}`),a?e.getApp().managers.customCarpetManager.getCustomCarpets().length===0&&this.createCarpet():this.carpet.clearCarpet()}),o=z(e.runtime,"enableBeautify",a=>{C.log(`[runtime] enableBeautify: ${a}`),this.reprocessStructuredMap(),this.reprocessRasterMap()});this.unsubscribeFns.push(t,i,s,r,o)}reprocessStructuredMap(){this.structuredMapData&&this.drawMap(this.structuredMapData).catch(e=>{C.error("[Beautify] Redraw after config change failed:",e)})}reprocessRasterMap(){if(!this.rasterMapData)return;const{rasterData:e,mapState:t}=this.rasterMapData;this.drawRasterMap(e,t).catch(i=>{C.error("[Beautify] Raster redraw after config change failed:",i)})}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.structuredMapData=e,this.rasterMapData=null,this.clearComponents(),this.resetGeometryData();const u=this.processRoomsGeometry(o),p=t.runtimeSnapshot.enableBeautify;this.roomFill.draw(p?this.applyBeautifyShells(o,u):u),r&&!p&&this.free.draw(r),s&&!p&&this.obstacle.draw(s),this.carpetData=h,this.createCarpet();const f=this.mergeLayerBounds();Wo(f,this.mapBounds)||(C.debug("[Map] Map bounds updated:",f),this.mapBounds=f,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.structuredMapData=null,this.rasterMapData={rasterData:e,mapState:t},this.clearComponents();const{id:s,width:r,height:o,charger:a,chargerDirection:h,status:l,origin:c}=t;C.debug("[Map] Parsed Raster Map Data",e);const d=i.runtimeSnapshot.enableBeautify;d||this.obstacle.drawRaster(e.obstacles,r),this.carpetData=this.convertRasterToStructuredData(e.carpet,r),i.getApp().managers.customCarpetManager.getCustomCarpets().length===0&&this.createCarpet();const p=this.processRasterData(e),f=d?this.applyRasterBeautifyShells(e):null;this.roomFill.drawRaster(p,f??void 0);const g=_S(e,r,o);Wo(g,this.mapBounds)||(C.debug("[Map] Raster map bounds updated:",g),this.mapBounds=g,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 m=(h+i.chargingStationConfig.rotationCorrection)*Math.PI/180;return await this.chargingStation.draw({x:a.x,y:a.y,rotation:m}),this.generateRoomGeometryFromRaster(e),f&&f.forEach((x,S)=>{this.shellCenterMap.set(S,this.computeShellCenter(x.shell))}),await i.roomsManager.refresh(),!0}resetGeometryData(){this.roomGeometryMap.clear(),this.shellCenterMap.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 C.debug("[Map] Map ID changed, triggering fitMapToView"),!0;if(this.lastStatus!==null&&this.lastStatus!==t)return C.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 C.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 C.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[fn.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=>!Bs(Number(u))),a=r.filter(u=>Bs(Number(u))),h=[],l=[];o.forEach(u=>{const{coordinates:p}=e[u];if(p.length<4)return;const f=p.filter(R=>!isFinite(R));if(f.length>0){C.error(`[Room ${u}] Contains ${f.length} invalid coordinates (NaN/Infinity)`);return}const g=Number(u);let m=1/0,x=1/0,S=-1/0,b=-1/0;const v=[];for(let R=0;R<p.length;R+=2){const k=p[R],I=p[R+1];m=Math.min(m,k),x=Math.min(x,I),S=Math.max(S,k),b=Math.max(b,I),v.push({x:k,y:I})}const M=S-m,_=b-x;if(M===0||_===0){C.error(`[Room ${u}] Degenerate polygon (${M}x${_}). Skipping.`);return}if(M<2||_<2){C.warn(`[Room ${u}] Room too small (${M}x${_}), skipping`);return}const w=new et(m,x,S-m+1,b-x+1),P=_h(v),A=P.flatMap(R=>[R.x+.5,R.y+.5]),T=qn(P,m,x,S,b);l.push({id:g,points:v,outlinePoints:P,polyPoints:A,centerPoint:T,boundingBox:w}),this.mapBounds.minX=Math.min(this.mapBounds.minX,m),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,b)});const c=[...l].sort((u,p)=>{if(t.roomConfig.colors.sortBy==="area"){const f=u.outlinePoints.length;return p.outlinePoints.length-f}else return u.id-p.id}),d=this.assignColorsUsingFourColorAlgorithm(c,i.length,"structured");return l.forEach(u=>{const p=d.get(u.id)||0,f=i[p],g={id:u.id,color:f,colorIndex:p,boundingBox:u.boundingBox,points:u.points,outlinePoints:u.outlinePoints,polyPoints:u.polyPoints,centerPoint:u.centerPoint};this.roomGeometryMap.set(u.id,g),h.push(g)}),a.forEach(u=>{const{coordinates:p}=e[u];if(p.length<4)return;const f=Number(u);let g=1/0,m=1/0,x=-1/0,S=-1/0;const b=[];for(let R=0;R<p.length;R+=2){const k=p[R],I=p[R+1];g=Math.min(g,k),m=Math.min(m,I),x=Math.max(x,k),S=Math.max(S,I),b.push({x:k,y:I})}const v=x-g,M=S-m;if(v===0||M===0){C.error(`[Unknown Room ${u}] Degenerate polygon (${v}x${M}). Skipping.`);return}if(v<2||M<2){C.warn(`[Unknown Room ${u}] Room too small (${v}x${M}), skipping`);return}const _=new et(g,m,x-g+1,S-m+1),w=_h(b),P=w.flatMap(R=>[R.x+.5,R.y+.5]),A=qn(w,g,m,x,S),T={id:f,color:s,boundingBox:_,points:b,outlinePoints:w,polyPoints:P,centerPoint:A};h.push(T),this.mapBounds.minX=Math.min(this.mapBounds.minX,g),this.mapBounds.minY=Math.min(this.mapBounds.minY,m),this.mapBounds.maxX=Math.max(this.mapBounds.maxX,x),this.mapBounds.maxY=Math.max(this.mapBounds.maxY,S)}),h}applyBeautifyShells(e,t){if(!e)return t;const i={};Object.keys(e).forEach(c=>{Bs(Number(c))||(i[c]=e[c])});const s=this.appService.mapConfig.beautify,r=Date.now(),o=il(i,{level:s.level,wallSnapTolerance:s.wallSnapTolerance,adjacencyThreshold:this.appService.mapConfig.adjacencyThreshold}),a=Object.keys(i),h=a.reduce((c,d)=>{var u,p;return c+(((p=(u=i[d])==null?void 0:u.coordinates)==null?void 0:p.length)??0)/2},0),l=a.filter(c=>{var d;return(d=o[Number(c)])==null?void 0:d.shell}).length;return C.log(`[Beautify] pipeline ${Date.now()-r}ms rooms=${a.length} shells=${l} fellBack=${a.length-l} points=${h}`),t.map(c=>{const d=o[c.id];return!d||!d.shell?c:(this.shellCenterMap.set(c.id,this.computeShellCenter(d.shell)),{...c,shell:d.shell,...d.footprint?{footprint:d.footprint}:{},...d.doorways&&d.doorways.length>0?{doorways:d.doorways}:{}})})}applyRasterBeautifyShells(e){const{width:t,height:i}=e,s=new Map;if(e.rooms.forEach((g,m)=>{typeof m=="number"&&g.length>0&&s.set(m,g)}),s.size===0)return null;const r=Date.now(),o={};let a=0;s.forEach((g,m)=>{a+=g.length;const x=Hb(g,t,i);x&&(o[String(m)]={coordinates:x})});const h=this.appService.mapConfig.adjacencyThreshold,l=new Map,c=new Map;s.forEach((g,m)=>{const x=Ub(g,t,i);l.set(m,x);let S=1/0,b=1/0,v=-1/0,M=-1/0;for(let _=0;_<x.length;_++){const w=x[_]%t,P=Math.floor(x[_]/t);w<S&&(S=w),P<b&&(b=P),w>v&&(v=w),P>M&&(M=P)}c.set(m,{minX:S,minY:b,maxX:v,maxY:M})});const d=(g,m)=>{const x=c.get(g),S=c.get(m),b=l.get(g),v=l.get(m);return!x||!S||!b||!v||x.minX>S.maxX+h||S.minX>x.maxX+h||x.minY>S.maxY+h||S.minY>x.maxY+h?!1:Qn(b,v,t,h)},u=this.appService.mapConfig.beautify,p=il(o,{level:u.level,wallSnapTolerance:u.wallSnapTolerance,adjacencyThreshold:h},d),f=new Map;return Object.keys(o).forEach(g=>{const m=Number(g),x=p[m];x!=null&&x.shell&&x.footprint&&f.set(m,{shell:x.shell,footprint:x.footprint,...x.doorways&&x.doorways.length>0?{doorways:x.doorways}:{}})}),C.log(`[Beautify] raster pipeline ${Date.now()-r}ms rooms=${s.size} shells=${f.size} fellBack=${s.size-f.size} pixels=${a}`),f}computeShellCenter(e){let t=1/0,i=1/0,s=-1/0,r=-1/0;return e.forEach(o=>{t=Math.min(t,o.x),i=Math.min(i,o.y),s=Math.max(s,o.x),r=Math.max(r,o.y)}),qn(e,t,i,s,r)}getRoomLabelAnchor(e){var t;return this.shellCenterMap.get(e)??((t=this.getRoomById(e))==null?void 0:t.centerPoint)}mergeLayerBounds(){let e={...this.mapBounds};if(this.obstacle.bounds&&(e=Kn(e,this.obstacle.bounds)),this.free.bounds&&(e=Kn(e,this.free.bounds)),this.roomFill.children.length>0){const t=this.roomFill.getLocalBounds();t.width>0&&t.height>0&&(e=Kn(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 C.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 C.warn(`[MapManager] Room ${r} not found in map`),!1;if(!o.outlinePoints||o.outlinePoints.length===0)return C.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];Wr(a.points,h.points,t)&&s.push([r,o])}return Ah(i.length,s)}areRasterRoomsAdjacentInternal(e,t){const s=this.appService.getApp().mapState;if(!s)return C.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 C.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];Qn(c.pixels,d.pixels,r,t)&&a.push([h,l])}return Ah(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):(C.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&&kt(r,a.outlinePoints)){const l=this.appService.roomsManager.getRoomPropertyById(a.id);return l||(C.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 C.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&&Or(u,l)){const f=this.appService.roomsManager.getRoomPropertyById(d.id);return f||(C.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 C.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&&Or(d,c)}return!!s.outlinePoints&&s.outlinePoints.length>=3&&kt({x:r,y:o},s.outlinePoints)}clearComponents(){this.obstacle.clear(),this.obstacle.destroy(),this.obstacle=new Lh(this.appService),this.free.clear(),this.free.destroy(),this.free=new Bh(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 sl(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===fn.VERSION0_ROOM&&!p&&(p=i.colors[fn.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.shellCenterMap.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 m=0;m<l.length;m++){const x=l[m],S=x%e.width,b=Math.floor(x/e.width);c=Math.min(c,S),d=Math.min(d,b),u=Math.max(u,S),p=Math.max(p,b)}const f=SS(l,e.width,c,d,u,p),g=new et(c,d,u-c+1,p-d+1);r.push({id:h,pixelIndices:l,boundingBox:g,centerPoint:f})});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&&C.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&&C.warn(`[FourColor] room.colors.inactive length (${s}) does not match room.colors.active length (${i}). Using modulo for color assignment.`),r!==i&&C.warn(`[FourColor] room.colors.name length (${r}) does not match room.colors.active length (${i}). Using modulo for color assignment.`),o!==i&&C.warn(`[FourColor] room.colors.propertyTheme length (${o}) does not match room.colors.active length (${i}). Using modulo for color assignment.`),a!==i&&C.warn(`[FourColor] room.colors.selectionIndicatorBackground length (${a}) does not match room.colors.active length (${i}). Using modulo for color assignment.`),h!==i&&C.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 C.debug("[FourColor] Using cached color map"),this.fourColorCache.colorMap;const o=s.getApp().config.map.adjacencyThreshold||3,a=s.roomConfig.colors.strategy,l=RS(e,(u,p)=>{var f;if(i==="structured"){const g=u.outlinePoints,m=p.outlinePoints;return!g||!m?!1:Wr(g,m,o)}else{const g=u.pixels,m=p.pixels;if(!g||!m)return!1;const x=((f=s.mapState)==null?void 0:f.width)||0;return Qn(g,m,x,o)}},t,a);this.fourColorCache={mapId:r,colorMap:l};const c=new Array(t).fill(0);return l.forEach(u=>{c[u]++}),C.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,this.structuredMapData=null,this.rasterMapData=null,this.shellCenterMap.clear()}}class cv extends W{constructor(t){super({isRenderGroup:!0});y(this,"commonPath");y(this,"chargePath");y(this,"transitionsPath");y(this,"mopPath");y(this,"mopPathTrack");y(this,"mopPathTrackContainer");y(this,"debugPoints");y(this,"pathData",null);y(this,"lastPointCount",0);y(this,"lastDrawnPosition",null);y(this,"isRealTimeDrawing",!1);y(this,"throttledUpdateLineWidth");y(this,"throttledHandleRobotPosition");y(this,"unsubscribeFns",[]);y(this,"handleRobotAnimationComplete",()=>{this.isRealTimeDrawing&&this.stopRealTimeDrawing()});this.appService=t,this.appService.appContainer.addToLayer(Td,this),this.eventMode="none",this.commonPath=new O,this.chargePath=new O,this.transitionsPath=new O,this.mopPathTrackContainer=new W,this.mopPathTrackContainer.filters=[new uy],this.mopPathTrack=new O,this.mopPath=new O,this.debugPoints=new O,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=Pt(()=>{this.updateLineWidth()},50,{leading:!0,trailing:!0}),this.throttledHandleRobotPosition=Pt(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=nn(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=ud(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;C.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(),C.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(g=>g.stroke()),a=u,h=p,l=!0,o&&c===0&&o.type===u?p.forEach(g=>{g.moveTo(o.x,o.y),g.lineTo(d.x,d.y)}):p.forEach(g=>g.moveTo(d.x,d.y))):p.forEach(g=>g.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 dv extends te{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 rt=class rt extends Hs{constructor(t,i){super(i||[]);y(this,"throttledUpdateScale");y(this,"fixedWidth",0);y(this,"fixedHeight",0);y(this,"isFixedSizeSet",!1);y(this,"sizeFixed",!0);y(this,"baselineScale",1);this.appService=t,this.anchor.set(.5),this.visible=!1,this.throttledUpdateScale=Pt(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 X.load(i);const h=U.from(i),l=new br(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`,f=l.textures[p];f?c.push(f):C.warn(`[EnhancedAnimatedSprite] Frame not found: ${p}`)}return c}catch(o){return C.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,C.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(),rt.animatedSprites.add(this),rt.startAnimationTicker())}stop(){super.stop(),rt.animatedSprites.delete(this),rt.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=rt.animationTicker)!=null&&t.started||(rt.animationTicker||(rt.animationTicker=new xt,rt.animationTicker.maxFPS=24,rt.animationTicker.add(()=>{const i=rt.animatedSprites.values().next().value;i&&rt.updateAnimations(i.appService)})),rt.animationTicker.start(),C.log("🎬 [AnimationTicker] Started animation ticker"))}static updateAnimationTicker(){rt.animatedSprites.size>0?rt.startAnimationTicker():rt.stopAnimationTicker()}static stopAnimationTicker(){var t;(t=rt.animationTicker)!=null&&t.started&&(C.log("⏸️ [AnimationTicker] Stopped animation ticker"),rt.animationTicker.stop())}static updateAnimations(t){if(rt.animatedSprites.size===0)return;const i=t.getApp();i.renderer.render(i.stage)}destroy(t){rt.animatedSprites.delete(this),rt.updateAnimationTicker(),this.appService.emitter.off("antiScale",this.throttledUpdateScale),super.destroy(t)}};y(rt,"animationTicker",null),y(rt,"animatedSprites",new Set);let js=rt;class Ro extends js{constructor(t,i){super(t,i);y(this,"unsubscribeFns",[]);y(this,"throttledUpdateOffset");y(this,"fixedOffsetX",0);y(this,"fixedOffsetY",0);this.appService=t,this.throttledUpdateOffset=Pt(this.updateOffset.bind(this),30,{leading:!0,trailing:!0}),this.initializeAnimation()}static async create(t){const i=t.robotConfig,s=await js.loadAnimationTextures(i.sleepAnimation.jsonSrc,i.sleepAnimation.imageSrc,i.sleepAnimation.framePrefix,i.sleepAnimation.frameCount);s.length===0&&(C.warn("No textures loaded for sleep animation"),s.push(U.EMPTY));const r=new Ro(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=z(this.appService.runtime,"showRobotSleepAnimation",i=>{C.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 uv extends O{constructor(t){super();y(this,"currentPosition",null);y(this,"animationStartTime",0);y(this,"isAnimating",!1);y(this,"handleScaleChange",()=>{this.redraw()});y(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:f,strokeColor:g,sizeFixed:m}=i,S=(m?t.getApp().toFixedSize(u/2):u/2)*c,b=t.getApp().toFixedSize(f);this.setFillStyle({color:p,alpha:d}),this.circle(this.currentPosition.x,this.currentPosition.y,S).fill().stroke({color:g,width:b,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 pv extends W{constructor(t){super();y(this,"robot");y(this,"ring");y(this,"pulseCircle");y(this,"sleepAnimation",null);y(this,"unsubscribeFns",[]);y(this,"clickHandler");y(this,"targetPosition",null);y(this,"targetRotation",null);y(this,"isMoving",!1);y(this,"pathQueue",[]);y(this,"lastPosition",null);y(this,"currentPathType");y(this,"lastUpdateTime",0);y(this,"isCleared",!1);this.appService=t,t.appContainer.addToLayer(Ed,this),this.visible=t.runtime.showRobot,this.ring=new Id(this.appService,{config:this.appService.robotConfig.ring}),this.ring.visible=this.appService.runtime.showRobotRing,this.addChild(this.ring),this.pulseCircle=new uv(this.appService),this.pulseCircle.visible=t.runtime.showRobotPulseCircle,this.addChild(this.pulseCircle),this.robot=new dv(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=z(this.appService.runtime,"showRobotRing",o=>{C.log(`[runtime] showRobotRing: ${o}`),this.ring.visible=o});this.unsubscribeFns.push(s);const r=z(this.appService.runtime,"showRobotPulseCircle",o=>{C.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 Ro.create(this.appService),this.addChild(this.sleepAnimation),C.log("Sleep animation added to robot")}catch(t){C.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 bt(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(it(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 fv{constructor(e){y(this,"path");y(this,"robot");y(this,"unsubscribeFns",[]);y(this,"lastDrawnPathData",null);y(this,"pointsSinceFullRedraw",0);this.appService=e,this.path=new cv(this.appService),this.robot=new pv(this.appService);const t=z(e.runtime,"showPath",s=>{C.log(`[runtime] showPath: ${s}`),this.path.visible=s}),i=z(e.runtime,"showRobot",s=>{C.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 gv extends W{constructor(t){super();y(this,"colorGradients",[]);y(this,"cellSize",2);this.appService=t,this.appService.appContainer.addToLayer(Ad,this);const i=this.appService.heatMapConfig;this.colorGradients=i.colorGradients.map(s=>new ht(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 O),o=new O;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,f=u.x-p,g=u.y-p,m=u.x+p,x=u.y+p;i.push(f,g),s.push(u.signal),i.push(m,g),s.push(u.signal),i.push(m,x),s.push(u.signal),i.push(f,g),s.push(u.signal),i.push(m,x),s.push(u.signal),i.push(f,x),s.push(u.signal)}const a=new Qi({attributes:{aPosition:new Float32Array(i),aSignal:new Float32Array(s)}}),h=new Ne({glProgram:new pi({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 be({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 ch({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,f=(w,P)=>w<0||w>=r||P<0||P>=o?u.signal:t[w][P].signal,g=(f(c-1,d-1)+f(c-1,d)+f(c,d-1)+u.signal)/4,m=(f(c-1,d)+f(c-1,d+1)+u.signal+f(c,d+1))/4,x=(u.signal+f(c,d+1)+f(c+1,d)+f(c+1,d+1))/4,S=(f(c,d-1)+u.signal+f(c+1,d-1)+f(c+1,d))/4,b=u.x-p,v=u.y-p,M=u.x+p,_=u.y+p;i.push(b,v,M,v,M,_),s.push(g,m,x),i.push(b,v,M,_,b,_),s.push(g,x,S)}const a=new Qi({attributes:{aPosition:new Float32Array(i),aSignal:new Float32Array(s)}}),h=new Ne({glProgram:new pi({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 be({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 ch({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 mv{constructor(e){y(this,"heatmap");y(this,"pointsTopLeftOrigin",[]);y(this,"signalGrid",[]);y(this,"cellSize",2);y(this,"maxDistance",14);y(this,"smoothIterations",10);y(this,"heatmapAlpha",.8);y(this,"isHeatmapDrawn",!1);y(this,"loadTimer",null);y(this,"pendingPoints",null);this.appService=e,this.heatmap=new gv(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 f=0;f<h;f++){const g=r+f*this.cellSize+this.cellSize/2,m=Math.min(this.cellSize,a-(g-this.cellSize/2));for(let x=0;x<l;x++){const S=s+x*this.cellSize+this.cellSize/2,b=Math.min(this.cellSize,o-(S-this.cellSize/2));let v=0,M=!1;for(let _=0;_<e.length;_++){const w=e[_];if(Math.abs(S-w.x)<=b/2&&Math.abs(g-w.y)<=m/2){const P=1-w.signal/7;v=Math.round(Math.max(v,P)*10)/10,M=!0}}c[f][x]={x:S,y:g,signal:v,hasPoint:M}}}const d=(f,g)=>{if(e.length===0)return 0;let m=0,x=0;for(const S of e){const b=Math.sqrt((f-S.x)**2+(g-S.y)**2);if(b<=this.maxDistance){const v=1/(1+b),M=1-S.signal/7;x+=v*M,m+=v}}return m===0?0:Math.round(x/m*1e3)/1e3},u=(f,g=1)=>{for(let m=0;m<g;m++){const x=f.map(S=>[...S]);for(let S=1;S<h-1;S++)for(let b=1;b<l-1;b++)if(!f[S][b].hasPoint){let v=0,M=0;const _=4;for(let w=-_;w<=_;w++)for(let P=-_;P<=_;P++){if(w===0&&P===0)continue;const A=S+w,T=b+P;if(A>=0&&A<h&&T>=0&&T<l){const k=1/(1+Math.sqrt(w*w+P*P)*.3);v+=f[A][T].signal*k,M+=k}}if(M>0){const w=v/M,P=.6,A=.4;x[S][b].signal=f[S][b].signal*P+w*A,x[S][b].signal>.1&&(x[S][b].signal=Math.max(x[S][b].signal,.2))}}for(let S=0;S<h;S++)for(let b=0;b<l;b++)f[S][b].signal=x[S][b].signal}};for(let f=0;f<h;f++)for(let g=0;g<l;g++){const m=c[f][g];m.hasPoint||(m.signal=d(m.x,m.y))}return u(c,this.smoothIterations),c}updatePositionByOrigin(e,t){this.heatmap.updatePositionByOrigin(e,t)}destroy(){this.heatmap.destroy()}}class ko extends O{constructor(t,i){super();y(this,"fillOptions");y(this,"isDragging",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"handlePointerDown",t=>{t.stopPropagation(),this.startDragging(t)});y(this,"handleDragPointerMove",t=>{var i,s;!this.isDragging||!this.dragStartPosition||(s=(i=this.fillOptions).onDragMove)==null||s.call(i,t)});y(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 on{constructor(e){y(this,"id",null);y(this,"layer",null);y(this,"editingState",{});y(this,"idleState",{});y(this,"host",null);y(this,"onHostDestroyed",null);y(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){C.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){C.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 Zs extends sn{constructor(t,{text:i,style:s}){super({text:i,style:s});y(this,"throttledUpdateScale");this.appService=t,this.throttledUpdateScale=Pt(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 Od extends W{constructor(t){super();y(this,"throttledUpdateScale");this.appService=t,this.throttledUpdateScale=Pt(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 an extends Od{constructor(t,i){super(t);y(this,"background");y(this,"icon");y(this,"options");this.appService=t,this.options=i,this.background=new O,this.addChild(this.background),this.icon=new te(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 et(-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){C.error(`Failed to load icon: ${this.options.iconAlias}`,t)}}destroy(){super.destroy()}}class Wd extends an{constructor(t,i){super(t,i);y(this,"isMoving",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"handleMovePointerMove",t=>{var i,s;!this.isMoving||!this.dragStartPosition||(s=(i=this.options).onMoveMove)==null||s.call(i,t)});y(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 Gd extends an{constructor(t,i){super(t,i);y(this,"clickHandler",null);this.appService=t}setupEvents(){this.clickHandler=new bt(this,{onClick:this.options.onClick,stopPropagation:!0})}destroy(){var t;(t=this.clickHandler)==null||t.destroy(),super.destroy()}}const yv=10;class xv extends an{constructor(t,i){super(t,i);y(this,"isRotating",!1);y(this,"hasRotated",!1);y(this,"rotationCenter",{x:0,y:0});y(this,"downPosition",{x:0,y:0});y(this,"lastAngle",0);y(this,"clickHandler",null);y(this,"gestureSession",null);y(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)<=yv)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});y(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 bt(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=Ye(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 zs extends an{constructor(t,i){super(t,i);y(this,"isScaling",!1);y(this,"initialButtonPosition",null);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(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})});y(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 ft={REMOVE:0,ROTATE:1,SCALE:2,MOVE:3};class Sv extends W{constructor(t,i){super();y(this,"config");y(this,"events");y(this,"zonePoints",[]);y(this,"outlinePoints");y(this,"minSize",.1);y(this,"maxSize");y(this,"sizeConstraintPerEdge");y(this,"initialZonePoints",[]);y(this,"scaleCache",null);y(this,"rotationCache",null);y(this,"outlineBorder");y(this,"moveLine");y(this,"sizeText");y(this,"controlButtons");y(this,"deleteButton",null);y(this,"rotateButton",null);y(this,"scaleButton",null);y(this,"moveButton",null);y(this,"horizontalScaleButton",null);y(this,"verticalScaleButton",null);y(this,"horizontalScaleInitialPosition",null);y(this,"verticalScaleInitialPosition",null);y(this,"clickHandler",null);y(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=Pt(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 W,this.addChild(this.controlButtons),this.createControlButtons(),this.setupClickHandler()}createOutlineBorder(){const{outlineStrokeColor:t,outlineStrokeWidth:i,outlineDashed:s,outlineDashArray:r,outlineFillColor:o}=this.config;return new we(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 we(this.appService,{points:o,closePath:!1,style:{color:t,width:i,isDashed:s,dashArray:r}})}createSizeText(){const t=this.calculateSizeText(),i=new Zs(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 Gd(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[ft.REMOVE].x,this.outlinePoints[ft.REMOVE].y),t}createRotateButton(){const t=this.config.rotateMode==="step",i=new xv(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[ft.ROTATE].x,this.outlinePoints[ft.ROTATE].y),i}onClickRotateButton(t){this.rotationCache||this.initializeRotationCache(this.calculateRotationCenter());const i=this.handleInternalRotationMove(t);return this.resetRotationState(),i}createScaleButton(){const t=new zs(this.appService,{iconAlias:"scaleIcon",backgroundColor:this.config.iconWrapperFillColor,initialButtonPosition:this.outlinePoints[ft.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[ft.SCALE].x,this.outlinePoints[ft.SCALE].y),t}createHorizontalScaleButton(){const[,t,i]=this.outlinePoints,s=this.getEdgeCenter(t,i),r=new zs(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 zs(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 Wd(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 xS(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[ft.MOVE],o=t[ft.SCALE],a=t[ft.REMOVE];return Sd(r,o,a,s)}calculateMoveLinePoints(){const t=this.calculateOutlinePoints();if(t.length<4)return[];const i=t[ft.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=K(i,s),a=K(i,r),{coords:h}=this.appService,l=h.toMeters(Wt(o)),c=h.toMeters(Wt(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=Dt(yt(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 Fs(h,l,c)}calculateHorizontalScaleButtonRotation(){const t=this.zonePoints;if(t.length<4)return 0;const[,i,s]=t,r=this.appService.appContainer.getMapRotationRadians();return Fs(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 Fs(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[ft.REMOVE]},{button:this.scaleButton,point:t[ft.SCALE]},{button:this.moveButton,point:i}];if(this.rotateButton&&s.push({button:this.rotateButton,point:t[ft.ROTATE]}),this.horizontalScaleButton){const r=t[ft.ROTATE],o=t[ft.SCALE],a=yd(r,o,0);s.push({button:this.horizontalScaleButton,point:a})}if(this.verticalScaleButton){const r=t[ft.SCALE],o=t[ft.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 bt(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[ft.SCALE]};if(!t)return;const i=ft.REMOVE,{x:s,y:r}=this.initialZonePoints[i],[,o,,a]=this.initialZonePoints,h={x:s,y:r},l=yt(h,o),c=yt(h,a),d=es(l),u=es(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(it(r)),maxSizePixels:o!=null?t.toPixels(it(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=yt(o,u);let f=Ps(p,a,l,s.minSizePixels,s.maxSizePixels),g=Ps(p,h,c,r.minSizePixels,r.maxSizePixels);if(this.config.scaleMode==="ratioLocked"){const m=Math.min(f,g);f=m,g=m}return this.calculatePointsFromScale(o,a,h,f,g)}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=yt(s,l),d=Ps(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=yt(s,l),d=1,u=Ps(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,mS(s,i,this.rotationCache.totalAngle)}resetRotationState(){this.rotationCache=null}calculateRotationCenter(){return this.zonePoints.length===0?{x:0,y:0}:Ye(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 bv(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 hn(n,e){return{coords:n.coords,editControls:n.editControlManager,getZoneConfig:t=>vv(n,t),controlsConfig:n.getConfig().controls,makeControlFill:t=>new ko(n,t),makeBorder:t=>new we(n,t),render:{request:t=>n.getApp().requestRender(t,!0),stop:t=>n.getApp().stopRender(t)},events:e}}function vv(n,e){var i;const t=n.getConfig();if(ei(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 ml.cleanZone}class ln extends W{constructor(t){super();y(this,"zoneData");y(this,"zoneType");y(this,"zoneConfig");y(this,"controlsConfig");y(this,"zoneEvents");y(this,"deps");y(this,"controlFill");y(this,"zoneBorder");y(this,"editableShape");y(this,"clickHandler",null);y(this,"initialZonePoints",[]);y(this,"dragStartPosition",null);y(this,"editing",!1);y(this,"resolvedMaxSizeCache",null);y(this,"handleDragStart",()=>{this.editing&&(this.initialZonePoints=this.zoneData.points.map(t=>({...t})),this.dragStartPosition=this.controlFill.getDragStartPosition(),this.deps.render.request("zone-drag"))});y(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)});y(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())});y(this,"handleRotationStart",()=>{this.deps.render.request("zone-rotate")});y(this,"handleRotationMove",t=>{t&&(this.zoneData.points=t,this.drawZone(!1))});y(this,"handleScaleStart",()=>{this.deps.render.request("zone-scale")});y(this,"handleScaleMove",t=>{t&&(this.zoneData.points=t,this.drawZone())});y(this,"handleMoveStart",()=>{this.initialZonePoints=this.zoneData.points.map(t=>({...t})),this.deps.render.request("zone-move")});y(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)});y(this,"handleMoveEnd",()=>{var t,i;this.initialZonePoints=[],this.deps.render.stop("zone-move"),(i=(t=this.zoneEvents).onUpdate)==null||i.call(t,this.getZoneData())});y(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())});y(this,"handleDelete",()=>{var t,i;(i=(t=this.zoneEvents).onRemove)==null||i.call(t,this.zoneData.id)});y(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=mi(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(dd(t),{minSize:it(this.zoneConfig.minSize),maxSize:i!=null?it(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=bv(this.zoneConfig,this.controlsConfig,{showRotateButton:this.zoneConfig.showRotateButton,showRadialScaleButton:!1,rotateMode:"free"});this.editableShape=new on({editControls:this.deps.editControls});const i=this.getResolvedMaxSize(),s={config:t,zonePoints:this.zoneData.points,minSize:this.zoneConfig.minSize,maxSize:i??void 0,contentLayer:Se,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 bt(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 Eo extends ln{constructor(e,t){super({deps:hn(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 Eo(e,{zoneData:t})}}class Io extends ln{constructor(e,t){super({deps:hn(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 Io(e,{zoneData:t})}}class Do extends ln{constructor(e,t){super({deps:hn(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 Do(e,{zoneData:t})}}class ti extends O{constructor(t,i){super();y(this,"lineOptions");y(this,"strokeContext",null);y(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 nt;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),f=u.getApp().toFixedSize(h),g=p+f,m=d/g,x=Math.round(m);if(x===0){t.moveTo(i,s),t.lineTo(r,o);return}const S=d/x,b=S*(p/g),v=l/d,M=c/d;for(let _=0;_<x;_++){const w=_*S,P=w+b;if(w>=d)break;const A=Math.min(P,d),T=i+w*v,R=s+w*M,k=i+A*v,I=s+A*M;t.moveTo(T,R),t.lineTo(k,I)}}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 qt=class qt extends W{constructor(t){super();y(this,"wallData");y(this,"wallConfig");y(this,"controlsConfig");y(this,"wallEvents");y(this,"appService");y(this,"wallLine");y(this,"outlineBorder");y(this,"moveLine");y(this,"lengthText");y(this,"controlButtons");y(this,"removeButton",null);y(this,"scaleButton",null);y(this,"moveButton",null);y(this,"initialWallPoints",[]);y(this,"initialButtonPosition",null);y(this,"isDragging",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"resolvedMaxWidthCache",null);y(this,"throttledUpdateOutline");y(this,"throttledHandleScaleChange");y(this,"wallLineClickHandler",null);y(this,"handleRemove",()=>{var t,i;(i=(t=this.wallEvents).onRemove)==null||i.call(t,this.wallData.id)});y(this,"initializeOperation",()=>{this.initialWallPoints=this.wallData.points.map(t=>({...t}))});y(this,"finalizeOperation",()=>{var t,i;this.initialWallPoints=[],(i=(t=this.wallEvents).onUpdate)==null||i.call(t,this.getWallData())});y(this,"handleScaleStart",()=>{this.initializeOperation();const t=this.calculateOutlinePoints();t.length>qt.BUTTON_INDICES.SCALE&&(this.initialButtonPosition={...t[qt.BUTTON_INDICES.SCALE]}),this.appService.getApp().requestRender("virtualwall-scale",!0)});y(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)});y(this,"handleScaleEnd",()=>{this.finalizeOperation(),this.initialButtonPosition=null,this.appService.getApp().stopRender("virtualwall-scale")});y(this,"handleMoveStart",()=>{this.initializeOperation(),this.appService.getApp().requestRender("virtualwall-move",!0)});y(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)});y(this,"handleMoveEnd",()=>{this.finalizeOperation(),this.appService.getApp().stopRender("virtualwall-move")});y(this,"handleScaleChange",()=>{this.redrawSolidLine(),this.setupWallLineHitArea()});y(this,"handleWallLinePointerDown",t=>{this.isEditingEnabled()&&(t.stopPropagation(),this.startDragging(t))});y(this,"handleDragPointerMove",t=>{!this.isDragging||!this.dragStartPosition||this.handleMove(t)});y(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=Pt(this.handleScaleChange.bind(this),30,{leading:!0,trailing:!0}),this.throttledUpdateOutline=Pt(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=mi(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(it(this.wallConfig.minWidth)),a=this.getResolvedMaxWidth(),h=a!=null?r.toPixels(it(a)):void 0,l=K(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=Dt(yt(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 W,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 ti(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 Zs(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=K(t[0],t[1]);return this.appService.coords.toMeters(Wt(i))}formatLengthText(t){const i=this.appService.coords.toDisplayUnit(it(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 yd(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 Fs(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 we(this.appService,{points:t,closePath:!0,style:this.getOutlineStyle()})}createMoveLine(){const t=this.calculateOutlinePoints(),i=this.calculateMoveLinePoints(t);return new we(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=yS(i[0],i[1],s);return[r[3],r[2],r[1],r[0]]}calculateMoveLinePoints(t){if(t.length<4)return[];const{MOVE:i}=qt.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}=qt.BUTTON_INDICES,r=i[s],o=i[(s+3)%4],a=i[(s+1)%4],h=this.appService.getApp().toFixedSize(t);return Sd(r,a,o,h)}createControlButtons(){const t=this.calculateOutlinePoints();if(t.length<4)return;const{REMOVE:i,SCALE:s}=qt.BUTTON_INDICES;this.removeButton=new Gd(this.appService,{iconAlias:"deleteIcon",backgroundColor:this.wallConfig.iconWrapperFillColor,onClick:this.handleRemove}),this.removeButton.position.set(t[i].x,t[i].y),this.scaleButton=new zs(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 Wd(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[qt.BUTTON_INDICES.SCALE],l=yt(s,a),c={x:t.x-l.x,y:t.y-l.y},d=yt(r,c),u=K(r,c),{coords:p}=this.appService,f=p.toPixels(it(this.wallConfig.minWidth)),g=this.getResolvedMaxWidth(),m=g!=null?p.toPixels(it(g)):void 0;let x;if(u<f)if(u===0)x={x:r.x+f,y:r.y};else{const S=Dt(d);x={x:r.x+S.x*f,y:r.y+S.y*f}}else if(m!=null&&u>m){const S=Dt(d);x={x:r.x+S.x*m,y:r.y+S.y*m}}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 ti?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}=qt.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 O;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 ti!==a.isDashed?(this.removeChild(this.wallLine),this.wallLine.destroy(),this.createWallLine(!1),this.addChild(this.wallLine)):this.wallLine instanceof ti?this.wallLine.updateStyle({color:o.toString(),width:r,dashArray:a.dashArray}):this.redrawSolidLine()}redrawSolidLine(){const t=this.appService;if(!this.wallLine||this.wallLine instanceof ti)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 bt(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=xd(t[0],t[1],s);if(r.length===0)return;const o=new Oe(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()}};y(qt,"BUTTON_INDICES",{REMOVE:0,SCALE:2,MOVE:3});let Vr=qt;class wv extends W{constructor(t){super();y(this,"thresholdData");y(this,"thresholdConfig");y(this,"thresholdEvents");y(this,"appService");y(this,"band");y(this,"bandFill");y(this,"bandStripes");y(this,"bandBorder");y(this,"stripesMask");y(this,"editableShape");y(this,"bandClickHandler",null);y(this,"initialPoints",null);y(this,"isDragging",!1);y(this,"hasDragMoved",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"resolvedMaxLengthCache",null);y(this,"resolvedMaxHeightCache",null);y(this,"throttledRedraw");y(this,"resolveSizeConstraintPerEdge",()=>({edge1:{min:this.thresholdConfig.minLength,max:this.getResolvedMaxLength()},edge2:{min:this.thresholdConfig.minHeight,max:this.getResolvedMaxHeight()}}));y(this,"handleRemove",()=>{var t,i;(i=(t=this.thresholdEvents).onRemove)==null||i.call(t,this.thresholdData.id)});y(this,"handleRotateStart",()=>{this.appService.getApp().requestRender("threshold-rotate",!0)});y(this,"handleRotateMove",t=>{t&&(this.setFromQuad(t),this.refreshAfterGeometryChange())});y(this,"handleRotateEnd",()=>{var t,i;this.appService.getApp().stopRender("threshold-rotate"),(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())});y(this,"handleScaleStart",()=>{this.appService.getApp().requestRender("threshold-scale",!0)});y(this,"handleScaleMove",t=>{t&&(this.setFromQuad(t),this.refreshAfterGeometryChange())});y(this,"handleScaleEnd",()=>{var t,i;this.appService.getApp().stopRender("threshold-scale"),(i=(t=this.thresholdEvents).onUpdate)==null||i.call(t,this.getThresholdData())});y(this,"handleMoveStart",()=>{this.initialPoints=this.clonePoints(),this.appService.getApp().requestRender("threshold-move",!0)});y(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)});y(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())});y(this,"handleBandPointerDown",t=>{this.isEditingEnabled()&&(t.stopPropagation(),this.startDragging(t))});y(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)});y(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 W,this.bandFill=new O,this.bandStripes=new O,this.bandBorder=new O,this.stripesMask=new O,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=Pt(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(K(t,i)===0)return[];const s=Dt(yt(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:K(i,o)}}createEditControls(){const t=this.thresholdConfig,i=this.appService.controlsConfig,s=new on({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:Se,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 bt(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=K(t,i),r=this.appService.getApp().toFixedSize(this.thresholdConfig.hitAreaPadding),o=this.thresholdData.height+r*2;this.band.hitArea=new et(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=mi(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=mi(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(it(this.thresholdConfig.minLength)),a=this.getResolvedMaxLength(),h=a!=null?r.toPixels(it(a)):void 0,l=K(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=Dt(yt(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(it(this.thresholdConfig.minHeight)),r=this.getResolvedMaxHeight(),o=r!=null?i.toPixels(it(r)):void 0;let a=t!=null&&Number.isFinite(t)&&t>0?t:i.toPixels(it(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 f=K(t,i);if(f===0)return;this.band.position.set(t.x,t.y),this.band.rotation=Math.atan2(i.y-t.y,i.x-t.x);const g=c/2,m=Math.min(l.toFixedSize(a),g,f/2);this.bandFill.roundRect(0,-g,f,c,m).fill(h.fillColor),this.bandBorder.roundRect(0,-g,f,c,m).stroke({color:h.color,width:p}),this.stripesMask.roundRect(0,-g,f,c,m).fill(16777215);const x=d+u;if(x<=0)return;let S=!1;for(let b=-c;b<f;b+=x){let v=b,M=-g,_=b+c,w=g;v<0&&(M+=-v,v=0),_>f&&(w-=_-f,_=f),!(v>=_)&&(this.bandStripes.moveTo(v,M).lineTo(_,w),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 Cv={fontSize:12,fontFamily:"system-ui, -apple-system, sans-serif",fontWeight:"400",color:"#5d68fe",position:"top",offset:-8,editing:{visible:!0},normal:{visible:!0}};class Fo extends W{constructor(t){super();y(this,"spotData");y(this,"spotConfig");y(this,"controlsConfig");y(this,"spotEvents");y(this,"appService");y(this,"controlFill");y(this,"spotBorder");y(this,"centerIcon");y(this,"sizeText");y(this,"nameText");y(this,"clickHandler",null);y(this,"initialSpotPoint",null);y(this,"dragStartMousePosition",null);y(this,"throttledUpdateScale");y(this,"unsubscribeMapRotation",null);y(this,"iconAlias");y(this,"editingIdsKey");y(this,"handleDragStart",t=>{this.isEditingEnabled()&&(this.initialSpotPoint={...this.spotData.point},this.dragStartMousePosition=this.parent.toLocal(t.global),this.appService.getApp().requestRender("spot-drag",!0))});y(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)});y(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=Pt(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(it(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 ko(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 we(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 te(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=z(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 Zs(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(it(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??Cv}createNameText(){const t=this.getNameLabelConfig(),i=new Zs(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 bt(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 Fo({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 _v extends Od{constructor(t){const{appService:i,wayPointData:s,order:r,events:o={}}=t;super(i);y(this,"wayPointData");y(this,"order");y(this,"wayPointConfig");y(this,"controlsConfig");y(this,"wayPointEvents");y(this,"icon");y(this,"orderContainer");y(this,"orderBackground");y(this,"orderText");y(this,"clickHandler",null);y(this,"initialWayPointPoint",null);y(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 te(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=z(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 W,this.orderBackground=new O,this.orderText=new sn({text:this.order.toString(),style:new ve({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 bt(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 ve({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 nl extends O{constructor(t,i){super();y(this,"isDragging",!1);y(this,"dragStartPosition",null);y(this,"initialPosition");y(this,"gestureSession",null);y(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)});y(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 Js(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 Mv extends W{constructor(t){super();y(this,"endPoints");y(this,"dividerConfig");y(this,"dividerEvents");y(this,"roomId");y(this,"appService");y(this,"roomGeometry",null);y(this,"dashLine");y(this,"solidLine",null);y(this,"startEndPoint");y(this,"endEndPoint");y(this,"solidLinePoints",null);y(this,"initialDividerPoints",[]);y(this,"isDragging",!1);y(this,"dragStartPosition",null);y(this,"gestureSession",null);y(this,"throttledHandleScaleChange");y(this,"handleEndPointDragStart",()=>{this.initialDividerPoints=this.endPoints.map(t=>({...t})),this.clearSolidLine(),this.appService.getApp().requestRender("divider-endpoint-drag",!0)});y(this,"handleEndPointDragMove",(t,i)=>{this.initialDividerPoints.length!==0&&(this.endPoints[t]=i,this.updateDashLine(),this.updateSolidLine(),this.setupDashLineHitArea())});y(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())});y(this,"handleDashLinePointerDown",t=>{t.stopPropagation(),this.startDragging(t)});y(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()});y(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()))});y(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=Pt(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 C.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 C.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 PS(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 ti(this.appService,{start:t[0],end:t[1],style:{color:r.toString(),width:i,dashArray:s}})}createEndPoints(){const t=this.endPoints;this.startEndPoint=new nl(this.appService,{position:t[0],config:this.dividerConfig,onDragStart:this.handleEndPointDragStart,onDragMove:i=>this.handleEndPointDragMove(0,i),onDragEnd:this.handleEndPointDragEnd}),this.endEndPoint=new nl(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=xd(t[0],t[1],s);if(r.length===0)return;const o=new Oe(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=lS(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 K(l,c)<3?null:AS(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:kt(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!MS(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 O,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 $r=["forbiddenSweepZone","forbiddenMopZone","cleanZone","virtualWall","threshold","spot","wayPoint","divider"];function Pv(n){if(!n||n.length===0)return[...$r];const e=new Set,t=[];for(const i of n)e.has(i)||(e.add(i),t.push(i));for(const i of $r)e.has(i)||t.push(i);return t}class Av{constructor(e){y(this,"zoneMaps",new Map);y(this,"virtualWallMap",new Map);y(this,"thresholdMap",new Map);y(this,"spotMap",new Map);y(this,"roomAnchorMap",new Map);y(this,"roomAnchorsData",[]);y(this,"wayPointMap",new Map);y(this,"divider",null);y(this,"controlContainers",new Map);y(this,"unsubscribeFns",[]);y(this,"builtinZoneFactories",{forbiddenSweepZone:e=>Eo.create(this.appService,e),forbiddenMopZone:e=>Io.create(this.appService,e),cleanZone:e=>Do.create(this.appService,e)});this.appService=e,this.initializeControlContainers();const t=z(e.runtime,"editingForbiddenSweepZoneIds",f=>{C.log(`[runtime] editingForbiddenSweepZoneIds: ${f}`);const g=this.zoneMaps.get("forbiddenSweepZone");g&&this.updateZonesEditState("forbiddenSweepZone",g)}),i=z(e.runtime,"editingForbiddenMopZoneIds",f=>{C.log(`[runtime] editingForbiddenMopZoneIds: ${f}`);const g=this.zoneMaps.get("forbiddenMopZone");g&&this.updateZonesEditState("forbiddenMopZone",g)}),s=z(e.runtime,"editingCleanZoneIds",f=>{C.log(`[runtime] editingCleanZoneIds: ${f}`);const g=this.zoneMaps.get("cleanZone");g&&this.updateZonesEditState("cleanZone",g)}),r=z(e.runtime,"editingCustomZoneIds",f=>{C.log(`[runtime] editingCustomZoneIds: ${JSON.stringify(f??{})}`);for(const[g,m]of this.zoneMaps)ei(g)||m.size&&this.updateZonesEditState(g,m)}),o=z(e.runtime,"editingVirtualWallIds",f=>{C.log(`[runtime] editingVirtualWallIds: ${f}`),this.updateVirtualWallsEditState(this.virtualWallMap)}),a=z(e.runtime,"editingThresholdIds",f=>{C.log(`[runtime] editingThresholdIds: ${f}`),this.updateThresholdsEditState(this.thresholdMap)}),h=z(e.runtime,"editingSpotIds",f=>{C.log(`[runtime] editingSpotIds: ${f}`),this.updateSpotsEditState(this.spotMap)}),l=z(e.runtime,"editingRoomAnchorIds",f=>{C.log(`[runtime] editingRoomAnchorIds: ${f}`),this.updateSpotsEditState(this.roomAnchorMap)}),c=z(e.runtime,"editingWayPointIds",f=>{C.log(`[runtime] editingWayPointIds: ${f}`),this.updateWayPointsEditState(this.wayPointMap)}),d=z(e.runtime,"dividingRoomId",f=>{C.log(`[runtime] dividingRoomId: ${f}`),this.handleDividingRoomIdChange(f)}),u=z(e.runtime,"unit",f=>{C.log(`[runtime] unit changed: ${f}`),this.handleUnitChange()}),p=z(e.runtime,"unitLabel",f=>{C.log(`[runtime] unitLabel changed: ${f}`),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(Se);if(!e){C.warn("[ControlsManager] LAYER_CONTROLS not found during init");return}for(const t of $r){const i=new W;i.label=`controls:${t}`,this.controlContainers.set(t,i),e.addChild(i)}this.applyRenderOrder()}applyRenderOrder(){const e=this.appService.appContainer.getLayer(Se);if(!e)return;Pv(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(Se);if(!s){C.warn("[ControlsManager] LAYER_CONTROLS not found");return}i=new W,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 Vr({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 wv({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 ln({deps:hn(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){C.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)}refreshZonesConfig(){for(const[e,t]of this.zoneMaps){if(t.size===0)continue;const i=this.resolveZoneFactory(e);if(!i)continue;const s=this.getZonesData(t);this.clearAllZones(t),this.drawZonesImpl(s,t,i,e)}}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=Fo.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){C.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(){C.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 _v({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 Mv({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(){C.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 Tv extends te{constructor(t,i){super(t);y(this,"objectData");y(this,"clickHandler",null);y(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=z(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 bt(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 Rv{constructor(e){y(this,"detectedObjectMap",new Map);y(this,"unsubscribeShowDetectedObjects",null);this.appService=e,this.applyLayerVisibility(this.appService.runtime.showDetectedObjects),this.unsubscribeShowDetectedObjects=z(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(ni);t&&(t.visible=e)}clearAllDetectedObjects(){const e=this.appService;this.detectedObjectMap.forEach(t=>{e.appContainer.removeFromLayer(ni,t),t.destroy()}),this.detectedObjectMap.clear()}async addNewDetectedObject(e){const t=this.appService,i=new Tv(this.appService,e);await i.initializeSprite(),this.detectedObjectMap.set(e.id,i),t.appContainer.addToLayer(ni,i)}removeDetectedObject(e){const t=this.appService,i=this.detectedObjectMap.get(e);i&&(t.appContainer.removeFromLayer(ni,i),i.destroy(),this.detectedObjectMap.delete(e))}destroy(){this.unsubscribeShowDetectedObjects&&(this.unsubscribeShowDetectedObjects(),this.unsubscribeShowDetectedObjects=null),this.clearAllDetectedObjects()}}var Ge={},Ud={},ue={};Object.defineProperty(ue,"__esModule",{value:!0});ue.loop=ue.conditional=ue.parse=void 0;var kv=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};ue.parse=kv;var Ev=function(e,t){return function(i,s,r,o){t(i,s,r)&&o(i,e,s,r)}};ue.conditional=Ev;var Iv=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}};ue.loop=Iv;var pt={};Object.defineProperty(pt,"__esModule",{value:!0});pt.readBits=pt.readArray=pt.readUnsigned=pt.readString=pt.peekBytes=pt.readBytes=pt.peekByte=pt.readByte=pt.buildStream=void 0;var Dv=function(e){return{data:e,pos:0}};pt.buildStream=Dv;var Hd=function(){return function(e){return e.data[e.pos++]}};pt.readByte=Hd;var Fv=function(){var e=arguments.length>0&&arguments[0]!==void 0?arguments[0]:0;return function(t){return t.data[t.pos+e]}};pt.peekByte=Fv;var cn=function(e){return function(t){return t.data.subarray(t.pos,t.pos+=e)}};pt.readBytes=cn;var Bv=function(e){return function(t){return t.data.subarray(t.pos,t.pos+e)}};pt.peekBytes=Bv;var Lv=function(e){return function(t){return Array.from(cn(e)(t)).map(function(i){return String.fromCharCode(i)}).join("")}};pt.readString=Lv;var zv=function(e){return function(t){var i=cn(2)(t);return e?(i[1]<<8)+i[0]:(i[0]<<8)+i[1]}};pt.readUnsigned=zv;var Ov=function(e,t){return function(i,s,r){for(var o=typeof t=="function"?t(i,s,r):t,a=cn(e),h=new Array(o),l=0;l<o;l++)h[l]=a(i);return h}};pt.readArray=Ov;var Wv=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},Gv=function(e){return function(t){for(var i=Hd()(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]=Wv(s,h.index,h.length):o[a]=s[h.index],o},{})}};pt.readBits=Gv;(function(n){Object.defineProperty(n,"__esModule",{value:!0}),n.default=void 0;var e=ue,t=pt,i={blocks:function(u){for(var p=0,f=[],g=u.data.length,m=0,x=(0,t.readByte)()(u);x!==p&&x;x=(0,t.readByte)()(u)){if(u.pos+x>=g){var S=g-u.pos;f.push((0,t.readBytes)(S)(u)),m+=S;break}f.push((0,t.readBytes)(x)(u)),m+=x}for(var b=new Uint8Array(m),v=0,M=0;M<f.length;M++)b.set(f[M],v),v+=f[M].length;return b}},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,f){return(0,t.readBytes)(f.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,f){return(0,t.readString)(f.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})(Ud);var dn={};Object.defineProperty(dn,"__esModule",{value:!0});dn.deinterlace=void 0;var Uv=function(e,t){for(var i=new Array(e.length),s=e.length/t,r=function(u,p){var f=e.slice(p*t,(p+1)*t);i.splice.apply(i,[u*t,t].concat(f))},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};dn.deinterlace=Uv;var un={};Object.defineProperty(un,"__esModule",{value:!0});un.lzw=void 0;var Hv=function(e,t,i){var s=4096,r=-1,o=i,a,h,l,c,d,u,p,_,f,g,M,m,w,P,T,A,x=new Array(i),S=new Array(s),b=new Array(s),v=new Array(s+1);for(m=e,h=1<<m,d=h+1,a=h+2,p=r,c=m+1,l=(1<<c)-1,f=0;f<h;f++)S[f]=0,b[f]=f;var M,_,w,P,A,T;for(M=_=w=P=A=T=0,g=0;g<o;){if(P===0){if(_<c){M+=t[T]<<_,_+=8,T++;continue}if(f=M&l,M>>=c,_-=c,f>a||f==d)break;if(f==h){c=m+1,l=(1<<c)-1,a=h+2,p=r;continue}if(p==r){v[P++]=b[f],p=f,w=f;continue}for(u=f,f==a&&(v[P++]=w,f=p);f>h;)v[P++]=b[f],f=S[f];w=b[f]&255,v[P++]=w,a<s&&(S[a]=p,b[a]=w,a++,!(a&l)&&a<s&&(c++,l+=a)),p=u}P--,x[A++]=v[P],g++}for(g=A;g<o;g++)x[g]=0;return x};un.lzw=Hv;Object.defineProperty(Ge,"__esModule",{value:!0});var Nd=Ge.decompressFrames=Ge.decompressFrame=Vd=Ge.parseGIF=void 0,Nv=jv(Ud),Vv=ue,$v=pt,Yv=dn,Xv=un;function jv(n){return n&&n.__esModule?n:{default:n}}var Zv=function(e){var t=new Uint8Array(e);return(0,Vv.parse)((0,$v.buildStream)(t),Nv.default)},Vd=Ge.parseGIF=Zv,qv=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},$d=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,Xv.lzw)(s.data.minCodeSize,s.data.blocks,r);s.descriptor.lct.interlaced&&(o=(0,Yv.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=qv(a)),a};Ge.decompressFrame=$d;var Kv=function(e,t){return e.frames.filter(function(i){return i.image}).map(function(i){return $d(i,e.gct,t)})};Nd=Ge.decompressFrames=Kv;class pn{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 b=null;for(const v of S.frames)b=v.gce??b,"image"in v&&!("gce"in v)&&(v.gce=b)},s=Vd(e);i(s);const r=Nd(s,!0),o=[],a=s.lsd.width,h=s.lsd.height,l=j.get().createCanvas(a,h),c=l.getContext("2d",{willReadFrequently:!0}),d=j.get().createCanvas(),u=d.getContext("2d");let p=0,f=null;const{fps:g=30,...m}=t??{},x=1e3/g;for(let S=0;S<r.length;S++){const{disposalType:b=2,delay:v=x,patch:M,dims:{width:_,height:w,left:P,top:A}}=r[S];d.width=_,d.height=w,u.clearRect(0,0,_,w);const T=u.createImageData(_,w);T.data.set(M),u.putImageData(T,0,0),b===3&&(f=c.getImageData(0,0,a,h)),c.drawImage(d,P,A);const R=c.getImageData(0,0,a,h);b===2?c.clearRect(0,0,a,h):b===3&&c.putImageData(f,0,0);const k=j.get().createCanvas(R.width,R.height);k.getContext("2d").putImageData(R,0,0),o.push({start:p,end:p+v,texture:new U({source:new Jr({resource:k,...m})})}),p+=v}return l.width=l.height=0,d.width=d.height=0,new pn(o)}}const Qv={extension:F.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=>Et.extname(n)===".gif"||n.startsWith("data:image/gif"),load:async(n,e)=>{const i=await(await j.get().fetch(n)).arrayBuffer();return pn.from(i,e==null?void 0:e.data)},unload:async n=>{n.destroy()}}},Yd=class Yr extends Qt{constructor(...e){const t=e[0]instanceof pn?{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({},Yr.defaultOptions,t);super({texture:U.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&&(xt.shared.remove(this.update,this),this._isConnectedToTicker=!1))}play(){this._playing||(this._playing=!0,this._autoUpdate&&!this._isConnectedToTicker&&(xt.shared.add(this.update,this,He.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/xt.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?(xt.shared.remove(this.update,this),this._isConnectedToTicker=!1):this._autoUpdate&&!this._isConnectedToTicker&&this._playing&&(xt.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 Yr({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}};Yd.defaultOptions={fps:30,loop:!0,animationSpeed:1,autoPlay:!0,autoUpdate:!0,onComplete:null,onFrameChange:null,onLoop:null};let Jv=Yd;Q.add(Qv);class Bo extends Jv{constructor(t,i){super(i);y(this,"throttledUpdateScale");y(this,"fixedWidth",0);y(this,"fixedHeight",0);y(this,"isFixedSizeSet",!1);y(this,"sizeFixed",!0);y(this,"baselineScale",1);y(this,"basePositionX",0);y(this,"basePositionY",0);y(this,"pixelOffset",null);this.appService=t,this.anchor.set(.5),this.visible=!1,this.throttledUpdateScale=Pt(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=So(this.pixelOffset,t,i);this.position.set(this.basePositionX+s.x,this.basePositionY+s.y)}set width(t){if(this.isFixedSizeSet){C.warn("EnhancedGifSprite: 使用 setFixedSize() 方法来设置宽度");return}this.setFixedSize(t,this.fixedHeight||t)}set height(t){if(this.isFixedSizeSet){C.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 X.load(i),o=new Bo(t,{source:r});return s.sizeFixed!==void 0&&o.setSizeFixed(s.sizeFixed),o.setFixedSize(s.width,s.height),o}catch(r){throw C.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 Je extends Bo{constructor(t,i,s){super(t,{source:i});y(this,"elementData");y(this,"clickHandler",null);y(this,"unsubscribeMapRotation",null);y(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=z(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 bt(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 hr extends te{constructor(t,i){super(t);y(this,"elementData");y(this,"clickHandler",null);y(this,"unsubscribeMapRotation",null);y(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=z(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 bt(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 t0 extends hy{constructor(t,i){super(i);y(this,"throttledUpdateScale");y(this,"fixedWidth",0);y(this,"fixedHeight",0);y(this,"isFixedSizeSet",!1);y(this,"userCenterX",0);y(this,"userCenterY",0);y(this,"sizeFixed",!0);y(this,"pixelOffset",null);this.appService=t,this.anchor.set(0,0),this.throttledUpdateScale=Pt(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=So(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 Xi extends t0{constructor(t,i){const s=document.createElement("div");Xi.setupDefaultStyles(s,i),s.innerHTML=i.htmlContent;super(t,{element:s});y(this,"elementData");y(this,"domClickHandler",null);y(this,"resizeObserver",null);y(this,"debugMarker",null);y(this,"unsubscribeMapRotation",null);y(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=z(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 e0{constructor(e){y(this,"customElementsMap",new Map);y(this,"gifTicker",null);y(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 Je?e.appContainer.removeFromLayer(Yi,t):e.appContainer.removeFromLayer($i,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 hr(this.appService,e);break;case"gif":{const s=await X.load(e.src);i=new Je(this.appService,s,e);break}case"html":i=new Xi(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 Je?(t.appContainer.addToLayer(Yi,i),this.gifElements.add(i)):t.appContainer.addToLayer($i,i)}removeCustomElement(e){const t=this.appService,i=this.customElementsMap.get(e);i&&(i instanceof Je?(this.gifElements.delete(i),t.appContainer.removeFromLayer(Yi,i)):t.appContainer.removeFromLayer($i,i),i.destroy(),this.customElementsMap.delete(e))}isSameData(e,t){return e.getElementData().type!==t.type?!1:t.type==="image"&&e instanceof hr||t.type==="gif"&&e instanceof Je||t.type==="html"&&e instanceof Xi?e.isSameData(t):!1}async updateElementData(e,t){if(t.type==="image"&&e instanceof hr)await e.updateElementData(t);else if(t.type==="gif"&&e instanceof Je)await e.updateElementData(t);else if(t.type==="html"&&e instanceof Xi)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 xt,this.gifTicker.maxFPS=1,this.gifTicker.add(()=>{this.renderGifContainer()})),this.gifTicker.start())}stopGifTicker(){var e;(e=this.gifTicker)!=null&&e.started&&(C.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 i0 extends W{constructor(t,i){super();y(this,"roomId");y(this,"roomIndex");y(this,"appService");y(this,"nameText");y(this,"iconSprite",null);y(this,"iconWrapper",null);y(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 ve({fontSize:s.fontSize,fontFamily:s.fontFamily,fontWeight:s.fontWeight,fill:h,align:"center"}),c=i.name||"Unknown";this.nameText=new sn({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 W,this.addChild(this.iconWrapper)),s.container.visible?(this.iconBg||(this.iconBg=new O,this.iconWrapper.addChild(this.iconBg)),this.drawIconBg(i)):this.iconBg&&(this.iconBg.destroy(),this.iconBg=null),this.iconSprite||(this.iconSprite=new te(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 s0 extends W{constructor(t,i){super();y(this,"background");y(this,"foldedIndicator");y(this,"propertyIcons",new Map);y(this,"orderContainer");y(this,"orderBackground");y(this,"orderText");y(this,"isFolded",!1);y(this,"roomId");y(this,"roomIndex");y(this,"isDestroyed",!1);this.appService=t;const s=this.appService.roomConfig;this.roomId=i.id,this.roomIndex=i.index,this.background=new O,this.foldedIndicator=new O,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 W,this.orderBackground=new O,this.orderText=new sn({text:"",style:new ve({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 te(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:f})=>{f.visible=!1});const u=[];if(c.forEach(f=>{if(f.isOrder){this.orderContainer.visible=!0,this.orderText.text=d.toString();const g=t.colorIndex??this.roomIndex,m=this.getIconColor(g);this.orderBackground.clear(),this.orderBackground.setFillStyle({color:m}),this.orderBackground.circle(i/2,s/2,i/2).fill();const x=this.resolveOrderTextColor(g);this.orderText.style.fill=x,this.orderText.position.set(i/2,s/2)}else{const g=this.propertyIcons.get(f.fieldName);if(g&&g.sprite){g.sprite.visible=!0;const m=this.getAssetAlias(f.fieldName,f.value);u.push(g.sprite.loadTextureAndSetSize(m,{width:i,height:s,sizeFixed:!1}))}}}),await Promise.all(u),this.isDestroyed||this.destroyed)return;let p=h;c.forEach((f,g)=>{const{element:m,isOrder:x}=f;!m||!m.position||(m.position.set(p,l),p+=i,g<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),f=Math.min(a,l/2,p);if(this.background.clear(),this.background.setFillStyle({color:h}),s){const g=(l-f)/2,m=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(g+f,c),this.background.lineTo(g+f/2,m),this.background.lineTo(g,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 n0 extends W{constructor(t,i){super();y(this,"background");y(this,"checkmarkIcon");y(this,"bubble");y(this,"roomIndex");y(this,"roomId");this.appService=t;const s=this.appService.roomConfig;this.roomId=i.id,this.roomIndex=i.index,this.background=new O,this.bubble=new O;const{colors:{selectionIndicatorIcon:r}}=s;this.checkmarkIcon=new te(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],f=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:f,width:o,alignment:0}).stroke(),l>0&&c>0){const g=(s-c)/2;this.bubble.setFillStyle({color:f});const m=r+o;this.bubble.poly([g,m-1,g+c,m-1,g+c/2,m+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 r0 extends W{constructor(t,i){super();y(this,"roomId");y(this,"roomName");y(this,"roomProperty",null);y(this,"roomSelectionIndicator",null);y(this,"clickHandler",null);y(this,"unsubscribeMapRotation",null);y(this,"targetElasticScale",1);y(this,"currentElasticScale",1);y(this,"isAnimatingScale",!1);y(this,"scaleAnimationBound",null);y(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 i0(this.appService,i),this.roomName.visible=this.appService.runtimeSnapshot.showRoomName,this.applyAntiRotation(this.appService.runtime.mapRotation),this.unsubscribeMapRotation=z(this.appService.runtime,"mapRotation",s=>{this.applyAntiRotation(s)}),this.clickHandler=new bt(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 s0(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 n0(this.appService,t),await this.updateRoomSelectionIndicatorVisibility(),this.addChild(this.roomSelectionIndicator)}updateLayout(){var l,c,d,u,p,f;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 g=this.roomProperty.getTotalHeight(),m=this.roomProperty.getTotalWidth();if(this.roomProperty.isFoldedState()){const S=-m/2+i,b=-g/2-t;this.roomProperty.position.set(S,b)}else a&&((u=this.roomName)!=null&&u.position)?(this.roomProperty.position.set(-m/2+i,-t-g),this.roomName.position.set(0,0)):this.roomProperty.position.set(-m/2+i,-g/2-t)}if(h&&this.roomSelectionIndicator){const g=this.roomSelectionIndicator.getTotalHeight(),m=this.roomSelectionIndicator.getTotalWidth();a&&((p=this.roomName)!=null&&p.position)?(this.roomSelectionIndicator.position.set(-m/2+r,-s-g),this.roomName.position.set(0,0)):this.roomSelectionIndicator.position.set(-m/2+r,-g/2-s)}a&&!o&&!h&&((f=this.roomName)!=null&&f.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 o0 extends W{constructor(t){super({isRenderGroup:!0});y(this,"floorTypeMap",new Map);y(this,"floorTypeMasks",new Map);y(this,"floorTypeContexts",new Map);y(this,"floorTypeToRooms",new Map);this.appService=t,this.appService.appContainer.addToLayer(_o,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]){C.warn(`No texture asset configured for floorType: ${t}`);return}const c=await X.load(l);if(!c){C.warn(`Floor material texture not found: ${l}`);return}const d=i.map(({graphics:m})=>m.getLocalBounds()),u=CS(d),p=new Ns({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:f,contexts:g}=this.createMergedMask(i.map(({graphics:m})=>m));p.mask=f,this.addChild(p),this.floorTypeMap.set(t,p),this.floorTypeMasks.set(t,f),this.floorTypeContexts.set(t,g),this.floorTypeToRooms.set(t,new Set(i.map(({roomId:m})=>m)))}createMergedMask(t){const i=new W,s=[];return t.forEach(r=>{const o=new O,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){C.warn("Error destroying floor mask:",i)}}),this.floorTypeMasks.clear(),this.floorTypeContexts.forEach(t=>{try{t.forEach(i=>{try{i.destroy()}catch(s){C.warn("Error destroying cloned graphics context:",s)}})}catch(i){C.warn("Error destroying graphics contexts:",i)}}),this.floorTypeContexts.clear(),this.floorTypeMap.forEach(t=>{try{this.removeChild(t),t.destroy()}catch(i){C.warn("Error destroying floor material:",i)}}),this.floorTypeMap.clear(),this.floorTypeToRooms.clear()}destroy(){this.clearFloorTypes(),super.destroy()}}const lr=(n,e)=>n&&e?{x:n.x-e.x,y:n.y-e.y}:null;class a0{constructor(e){y(this,"unsubscribeFns",[]);y(this,"roomInfoContainer",new W);y(this,"roomInfoMap",new Map);y(this,"roomDisplayMap",new Map);y(this,"roomFloorType");this.appService=e,this.roomFloorType=new o0(e),e.appContainer.addToLayer(Rd,this.roomInfoContainer);const t=z(e.runtime,"showRoomFloorType",d=>{C.log(`[runtime] showRoomFloorType: ${d}`),d?this.updateFloorTypes():this.roomFloorType.clearFloorTypes()}),i=z(e.runtime,"showRoomProperty",d=>{C.log(`[runtime] showRoomProperty: ${d}`),this.updateAllRoomPropertyVisibility()}),s=z(e.runtime,"showRoomOrder",d=>{C.log(`[runtime] showRoomOrder: ${d}`),this.updateAllRoomPropertyVisibility()}),r=z(e.runtime,"roomPropertyFoldIds",d=>{C.log(`[runtime] roomPropertyFoldIds: ${d}`),this.updateAllRoomPropertyVisibility()}),o=z(e.runtime,"showRoomName",d=>{C.log(`[runtime] showRoomName: ${d}`),this.updateAllRoomNameVisibility(d)}),a=z(e.runtime,"showRoomType",d=>{C.log(`[runtime] showRoomType: ${d}`),this.updateAllRoomTypeVisibility(d)}),h=z(e.runtime,"enableRoomSelection",d=>{C.log(`[runtime] enableRoomSelection: ${d}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()}),l=z(e.runtime,"selectRoomIds",d=>{C.log(`[runtime] selectRoomIds: ${d}`),this.updateAllRoomPropertyVisibility(),this.updateAllRoomSelectionIndicatorVisibility(),this.refreshAllRoomColors()}),c=z(e.runtime,"roomSelectionMode",d=>{C.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:lr(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){var s,r;const t=new r0(this.appService,e);this.roomInfoContainer.addChild(t),this.roomInfoMap.set(e.id,t);const i=(r=(s=this.appService.mapManager).getRoomLabelAnchor)==null?void 0:r.call(s,e.id);i&&e.centerPoint&&(i.x!==e.centerPoint.x||i.y!==e.centerPoint.y)&&t.updatePosition(i),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=lr(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){C.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=lr(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 hl,ll;(hl=navigator==null?void 0:navigator.userAgent)!=null&&hl.includes("tuya-ark-ide")||((ll=navigator==null?void 0:navigator.userAgent)==null||ll.includes("miniProgram"));const h0=()=>{var i,s;if(!Ep.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 l0 extends W{constructor(t,i,s){super();y(this,"graphics");y(this,"sprite",null);y(this,"viewportBounds");y(this,"lastConfig",null);y(this,"onImageLoaded");this.label="background",this.viewportBounds=i,this.onImageLoaded=s,this.graphics=new O,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}C.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}),C.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 Vt({type:"linear",start:{x:r,y:o},end:{x:a,y:h},colorStops:t.colorStops});this.graphics.rect(0,0,i,s).fill(l),C.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 Vt({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),C.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 X.load(t.src);if(!h){C.error("[Background] Failed to load image:",t.src),(s=this.lastConfig)!=null&&s.backgroundColor&&this.renderSolidColor(this.lastConfig.backgroundColor,i);return}this.sprite=new Qt(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,f=h.width,g=h.height,m=f/g,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":m>x?(this.sprite.width=l,this.sprite.height=l/m):(this.sprite.height=c,this.sprite.width=c*m),this.sprite.x=(l-this.sprite.width)*u,this.sprite.y=(c-this.sprite.height)*p;break;case"cover":m>x?(this.sprite.height=c,this.sprite.width=c*m):(this.sprite.width=l,this.sprite.height=l/m),this.sprite.x=(l-this.sprite.width)*u,this.sprite.y=(c-this.sprite.height)*p;break;case"none":this.sprite.width=f,this.sprite.height=g,this.sprite.x=(l-f)*u,this.sprite.y=(c-g)*p;break}t.repeat&&C.warn("[Background] Repeat mode not yet implemented"),this.addChild(this.sprite),C.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){C.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 c0 extends W{constructor(t){super();y(this,"carpetData");y(this,"carpetConfig");y(this,"controlsConfig");y(this,"carpetEvents");y(this,"appService");y(this,"controlFill");y(this,"editableShape");y(this,"clickHandler",null);y(this,"maskContainer",null);y(this,"maskGraphics",null);y(this,"texture",null);y(this,"textureMap",new Map);y(this,"tilingSprite",null);y(this,"initialZonePoints",[]);y(this,"unsubscribeFns",[]);y(this,"resolvedMaxSizeCache",null);y(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))});y(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)});y(this,"handleDragEnd",()=>{var t,i;this.initialZonePoints=[],this.appService.getApp().stopRender("zone-drag"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});y(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)});y(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)});y(this,"handleMoveEnd",()=>{var t,i;this.initialZonePoints=[],this.appService.getApp().stopRender("zone-move"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});y(this,"handleRotationStart",()=>{this.appService.getApp().requestRender("zone-rotate",!0)});y(this,"handleRotationMove",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});y(this,"handleRotationEnd",()=>{var t,i;this.appService.getApp().stopRender("zone-rotate"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});y(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())});y(this,"handleScaleStart",()=>{this.appService.getApp().requestRender("zone-scale",!0)});y(this,"handleScaleMove",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});y(this,"handleScaleMoveHorizontal",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});y(this,"handleScaleMoveVertical",t=>{t&&(this.carpetData.points=t,this.drawCarpet())});y(this,"handleScaleEnd",()=>{var t,i;this.appService.getApp().stopRender("zone-scale"),(i=(t=this.carpetEvents).onUpdate)==null||i.call(t,this.getCarpetData())});y(this,"handleDelete",()=>{var t,i;(i=(t=this.carpetEvents).onRemove)==null||i.call(t,this.carpetData.id)});y(this,"handleClick",()=>{var t,i;this.isEditingEnabled()||(i=(t=this.carpetEvents)==null?void 0:t.onClick)==null||i.call(t,this.getCarpetData())});y(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=mi(this.carpetConfig.minSize,t,"carpet");return this.resolvedMaxSizeCache={key:t,value:i},i}validateCarpetShape(t){const i=this.getResolvedMaxSize();return this.appService.coords.validateShape(dd(t),{minSize:it(this.carpetConfig.minSize),maxSize:i!=null?it(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 W;return this.maskGraphics=new O,this.updateMaskShape(),t.addChild(this.maskGraphics),t.mask=this.maskGraphics,t}createControlFill(){const t=this.isEditingEnabled();return new ko(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={...Zn(this.carpetConfig,["outlineStrokeWidth","outlineDashed","outlineDashArray","outlineFillColor","outlineOffset","outlineStrokeColor"]),...Zn(this.carpetConfig,["textColor","textPosition","textOffset"]),...Zn(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 on({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:hi,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 bt(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=z(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}=Vs(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=Ye(t),[o,a,,h]=t,l=K(o,a),c=K(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 Ns({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 d0{constructor(e){y(this,"customCarpetMap",new Map);y(this,"unsubscribeFns",[]);y(this,"textureMap",new Map);y(this,"texturesLoaded",!1);y(this,"texturesLoadingPromise",null);this.appService=e,this.applyLayerVisibility(e.runtime.showCustomCarpets);const t=z(e.runtime,"editingCarpetIds",r=>{C.log(`[runtime] editingCarpetIds: ${r}`),this.updateCarpetsEditState()}),i=z(e.runtime,"selectedCarpetIds",r=>{C.log(`[runtime] selectedCarpetIds: ${r}`),this.updateCarpetsEditState()}),s=z(e.runtime,"showCustomCarpets",r=>{C.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 X.load(s.src);this.textureMap.set(s.type,r)}if(i){const s=await X.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 c0({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(hi,i)}removeCustomCarpet(e){const t=this.appService,i=this.customCarpetMap.get(e);i&&(t.appContainer.removeFromLayer(hi,i),i.destroy(),this.customCarpetMap.delete(e))}updateCarpetsEditState(){this.customCarpetMap.forEach(e=>{e.updateEditState()})}applyLayerVisibility(e){const t=this.appService.appContainer.getLayer(hi);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 u0(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 rl="furniture-drag",ol="furniture-scale",al="furniture-move",cr="furniture-rotate";class p0 extends W{constructor(t){super();y(this,"deps");y(this,"config");y(this,"controlsConfig");y(this,"furnitureEvents");y(this,"data");y(this,"textureAlias");y(this,"sprite");y(this,"editableShape");y(this,"editing",!1);y(this,"clickHandler",null);y(this,"dragStartPosition",null);y(this,"initialPoints",[]);y(this,"isDragging",!1);y(this,"gestureSession",null);y(this,"originalSizeMeters",null);y(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)}});y(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)});y(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(rl)),this.data.points=this.initialPoints.map(o=>({x:o.x+s,y:o.y+r})),this.redraw())});y(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(rl)),this.dragStartPosition=null,this.initialPoints=[],this.isDragging=!1)});y(this,"handleRotateStart",()=>{this.deps.render.request(cr)});y(this,"handleRotateMove",t=>{t&&(this.data.points=t,this.redraw())});y(this,"handleTapRotate",t=>{var i,s;t&&(this.data.points=t,this.redraw()),this.captureOriginalSize(),this.deps.render.once(cr),(s=(i=this.furnitureEvents).onUpdate)==null||s.call(i,this.getData())});y(this,"handleScaleStart",()=>{this.deps.render.request(ol)});y(this,"handleScaleMove",t=>{t&&(this.data.points=t,this.redraw())});y(this,"handleMoveStart",()=>{this.initialPoints=this.data.points.map(t=>({...t})),this.deps.render.request(al)});y(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()});y(this,"handleMoveEnd",()=>{var t,i;this.initialPoints=[],this.deps.render.stop(al),(i=(t=this.furnitureEvents).onUpdate)==null||i.call(t,this.getData())});y(this,"handleTransformEnd",()=>{var t,i;this.deps.render.stop(cr),this.deps.render.stop(ol),(i=(t=this.furnitureEvents).onUpdate)==null||i.call(t,this.getData())});y(this,"handleDelete",()=>{var t,i;(i=(t=this.furnitureEvents).onRemove)==null||i.call(t,this.data.id)});y(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=K(t[0],t[1]),s=K(t[1],t[2]);this.originalSizeMeters={width:this.deps.coords.toMeters(Wt(i)),height:this.deps.coords.toMeters(Wt(s))}}createSprite(){const t=X.get(this.textureAlias);this.sprite=new Qt(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=Ye(t),s=t[1].x-t[0].x,r=t[1].y-t[0].y,o=Math.atan2(r,s),a=K(t[0],t[1]),h=K(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 on({editControls:this.deps.editControls});const i={config:t,zonePoints:this.data.points,sizeConstraintPerEdge:this.resolveSizeConstraintPerEdge,contentLayer:Le,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 bt(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 f0{constructor(e){y(this,"furnitureMap",new Map);y(this,"unsubscribeFns",[]);this.appService=e,this.applyLayerVisibility(e.runtime.showFurnitures);const t=z(e.runtime,"editingFurnitureIds",s=>{C.log(`[runtime] editingFurnitureIds: ${s}`),this.updateEditState()}),i=z(e.runtime,"showFurnitures",s=>{C.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)){C.warn(`[FurnitureManager] No asset found for furnitureType: ${e.furnitureType}`);return}const r=`furniture_${e.furnitureType}`;await X.load(r);const o=u0(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 p0({deps:o,data:e,textureAlias:r});this.furnitureMap.set(e.id,a),t.appContainer.addToLayer(Le,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(Le);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(Le);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(We,e)}moveToFurnitureLayer(e){var t;(t=e.parent)==null||t.removeChild(e),this.appService.appContainer.addToLayer(Le,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 g0{constructor(e){y(this,"editControlLayers",new Map);this.appService=e}registerEditControl(e,t){const i=this.appService;this.editControlLayers.has(e)&&this.unregisterEditControl(e);const s=new Sv(i,t);if(!i.appContainer.addToLayer(We,s))throw C.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(We),a=i.appContainer.getLayer(t.contentLayer);o&&a&&(o.position.x!==a.position.x||o.position.y!==a.position.y)&&C.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(We,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 Rs(n){return n.charAt(0).toUpperCase()+n.slice(1)}const ji=class ji extends pc{constructor(t=Uo){super();y(this,"mapState",null);y(this,"components",{});y(this,"managers",{});y(this,"config",Go);y(this,"runtime");y(this,"appService");y(this,"coords");y(this,"scaleMin",.5);y(this,"scaleMax",5);y(this,"events",{});y(this,"instanceKey");y(this,"debugInstanceId");y(this,"previousLoggerRuntimeState",null);y(this,"isDestroying",!1);y(this,"hasActiveContextLoss",!1);y(this,"createdAtMs",Date.now());y(this,"lastMapDataAtMs",null);y(this,"lastMapDrawAtMs",null);y(this,"lastPathDataAtMs",null);y(this,"lastVisibilityChangeAtMs",null);y(this,"containerElement");y(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);C.error("[Pixi] WebGL context lost",s.summary),C.error("[Pixi] WebGL context lost tail",s.recentLifecycleTail),this.recordDebugLifecycleEvent("webglcontextlost",{eventType:t.type,statusMessage:i.statusMessage??null})});y(this,"onWebGLContextRestored",t=>{this.hasActiveContextLoss=!1,C.warn("[Pixi] WebGL context restored, scheduling render",this.getRendererDiagnostics({eventType:t.type})),this.recordDebugLifecycleEvent("webglcontextrestored",{eventType:t.type}),this.renderOnceNextFrame()});y(this,"emitter",US());y(this,"tickerState",{renderReasons:new Set,renderTimer:null,lastRequestReason:null,lastStopReason:null});y(this,"customCarpetResolvedMaxSizeCache",null);y(this,"pendingAsyncRender",!1);y(this,"isFirstMapDraw",!0);y(this,"isMapDrawn",!1);y(this,"onVisibilityChange",()=>{var i;this.lastVisibilityChangeAtMs=Date.now(),document.visibilityState==="visible"||(i=this.components.interaction)==null||i.clearTouches()});y(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=Fh(),this.coords=new eb(()=>{var i;return((i=this.runtime)==null?void 0:i.unit)??"meter"}),this.appService=new wd(this),globalThis.__PIXI_APP__=this,this.recordDebugLifecycleEvent("app:create",{instanceKey:t})}getRendererDiagnostics(t={}){var r,o,a,h,l,c,d,u,p,f,g;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)===he.WEBGPU?"webgpu":((o=this.renderer)==null?void 0:o.type)===he.WEBGL?"webgl":"unknown";return{sessionId:er().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:((f=this.mapState)==null?void 0:f.width)??null,mapHeight:((g=this.mapState)==null?void 0:g.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 er().readCurrentSession().slice(-ji.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)!==he.WEBGL||typeof((i=this.canvas)==null?void 0:i.addEventListener)!="function"){C.debug("[Pixi] Renderer diagnostics initialized",this.getRendererDiagnostics({contextListeners:!1}));return}this.canvas.addEventListener("webglcontextlost",this.onWebGLContextLost),this.canvas.addEventListener("webglcontextrestored",this.onWebGLContextRestored),C.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)===he.WEBGPU?"webgpu":((i=this.renderer)==null?void 0:i.type)===he.WEBGL?"webgl":"unknown"}recordDebugLifecycleEvent(t,i){var s;er().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=Ur(xh({},Go,r??{},(f,g)=>{if(Array.isArray(g))return g})),this.validateCustomZoneTypes(this.config),this.previousLoggerRuntimeState=eS(),tS({getLoggerConfig:()=>this.config.logger,getLegacyEnabled:()=>this.config.global.enableLogger}),C.log("Applying config",this.config,r),this.runtime=Ur(Object.assign({},wu,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:h0(),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(f){C.warn("[Pixi] WebGPU initialization failed, falling back to WebGL:",f),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}),C.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 lv(this.appService),this.managers.heatmapManager=new mv(this.appService),this.managers.pathManager=new fv(this.appService),this.managers.controlsManager=new Av(this.appService),this.managers.detectedObjectManager=new Rv(this.appService),this.managers.customElementsManager=new e0(this.appService),this.managers.roomsManager=new a0(this.appService),this.managers.customCarpetManager=new d0(this.appService),this.managers.furnitureManager=new f0(this.appService),this.managers.editControlManager=new g0(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,C.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),C.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?(C.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,C.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),C.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?(C.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(),C.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;C.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){C.log("[CustomCarpets] drawCustomCarpets",t),await this.managers.customCarpetManager.drawCustomCarpets(t),this.renderOnceNextFrame()}async drawFurnitures(t){C.log("[Furniture] drawFurnitures",t),await this.managers.furnitureManager.drawFurnitures(t),this.renderOnceNextFrame()}drawHeatmap(t){C.log("[Heatmap] drawHeatmap",t),this.managers.heatmapManager.draw(t),this.renderOnce()}drawForbiddenSweepZones(t){C.log("[Controls] drawForbiddenSweepZones",t),this.managers.controlsManager.drawForbiddenSweepZones(t),this.renderOnceNextFrame()}drawForbiddenMopZones(t){C.log("[Controls] drawForbiddenMopZones",t),this.managers.controlsManager.drawForbiddenMopZones(t),this.renderOnceNextFrame()}drawCleanZones(t){C.log("[Controls] drawCleanZones",t),this.managers.controlsManager.drawCleanZones(t),this.renderOnceNextFrame()}drawCustomZones(t,i){if(ei(t)){C.warn(`[MapApplication] drawCustomZones: '${t}' is a built-in type; use draw${Rs(t)}s() instead`);return}C.log("[Controls] drawCustomZones",t,i),this.managers.controlsManager.drawCustomZones(t,i),this.renderOnceNextFrame()}getCustomZones(t){return ei(t)?(C.warn(`[MapApplication] getCustomZones: '${t}' is a built-in type; use get${Rs(t)}s() instead`),[]):this.managers.controlsManager.getCustomZones(t)}clearCustomZones(t){if(ei(t)){C.warn(`[MapApplication] clearCustomZones: '${t}' is a built-in type; use clearAll${Rs(t)}s() instead`);return}C.log("[Controls] clearCustomZones",t),this.managers.controlsManager.clearCustomZones(t),this.renderOnceNextFrame()}setEditingCustomZones(t,i){if(ei(t)){C.warn(`[MapApplication] setEditingCustomZones: '${t}' is a built-in type; use runtime.editing${Rs(t)}Ids instead`);return}this.runtime.editingCustomZoneIds={...this.runtime.editingCustomZoneIds??{},[t]:[...i]}}drawVirtualWalls(t){C.log("[Controls] drawVirtualWalls",t),this.managers.controlsManager.drawVirtualWalls(t),this.renderOnceNextFrame()}drawThresholds(t){C.log("[Controls] drawThresholds",t),this.managers.controlsManager.drawThresholds(t),this.renderOnceNextFrame()}drawSpots(t){C.log("[Controls] drawSpots",t),this.managers.controlsManager.drawSpots(t),this.renderOnceNextFrame()}drawRoomAnchors(t){C.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){C.log("[Controls] drawWayPoints",t),this.managers.controlsManager.drawWayPoints(t),this.renderOnceNextFrame()}async drawDetectedObjects(t){C.log("[DetectedObject] drawDetectedObjects",t),await this.managers.detectedObjectManager.drawDetectedObjects(t),this.renderOnceNextFrame()}drawCustomCarpet(t){C.log("[CustomCarpet] drawCustomCarpet",t),this.managers.customCarpetManager.drawCustomCarpets(t),this.renderOnceNextFrame()}async drawCustomElements(t){C.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(){C.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),f=u*(1-s*2),g=p/l,m=f/c,x=Math.min(g,m),S=this.config.interaction.fitMinScale,b=this.config.interaction.fitMaxScale,v=Math.max(S,Math.min(b,x));this.setScaleBounds(this.config.interaction.zoomRange.min,this.config.interaction.zoomRange.max),v<this.scaleMin&&(this.setScaleBounds(v,this.scaleMax),C.debug("[MapApplication] scaleMin lowered for fit:",{configured:this.config.interaction.zoomRange.min,adjusted:v})),v>this.scaleMax&&(this.setScaleBounds(this.scaleMin,v),C.debug("[MapApplication] scaleMax raised for fit:",{configured:this.config.interaction.zoomRange.max,adjusted:v}));const M=t.minX+(t.maxX-t.minX)/2,_=t.minY+(t.maxY-t.minY)/2,w=this.config.map.autoFitOffset||{x:0,y:0},P=d/2+(w.x||0),A=u/2+(w.y||0),T=Math.cos(a),R=Math.sin(a),k=M*T-_*R,I=M*R+_*T,B=P-k*v,N=A-I*v;C.debug("[MapApplication] fitMapToView calculated:",{rotation:this.components.appContainer.getMapRotation(),originalBounds:t,rotatedBounds:h,finalScale:v,position:{x:B,y:N}}),this.components.interaction.setPanZoom({targetPosition:{x:B,y:N},targetScale:{x:v,y:v},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=ml.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(f=>({x:f.x*a-f.y*h,y:f.x*h+f.y*a}));let c=1/0,d=1/0,u=-1/0,p=-1/0;return l.forEach(f=>{c=Math.min(c,f.x),d=Math.min(d,f.y),u=Math.max(u,f.x),p=Math.max(p,f.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),C.log("[runtime] runtime updated",t),this.renderOnceNextFrame()}updateConfig(t){var o,a,h,l,c,d,u,p,f,g,m;xh(this.config,t,(x,S)=>{if(Array.isArray(S))return S}),t.customZoneTypes&&this.validateCustomZoneTypes(this.config),(o=this.managers.controlsManager)==null||o.updateRenderOrder(),((a=t.controls)==null?void 0:a.spot)!==void 0&&((h=this.managers.controlsManager)==null||h.refreshSpotsEditState()),((l=t.controls)==null?void 0:l.roomAnchor)!==void 0&&((c=this.managers.controlsManager)==null||c.refreshRoomAnchors()),((d=t.controls)==null?void 0:d.carpet)!==void 0&&((u=this.managers.customCarpetManager)==null||u.refreshConfig());const s=t.controls;((s==null?void 0:s.forbiddenSweepZone)!==void 0||(s==null?void 0:s.forbiddenMopZone)!==void 0||(s==null?void 0:s.cleanZone)!==void 0||t.customZoneTypes!==void 0)&&((p=this.managers.controlsManager)==null||p.refreshZonesConfig()),((f=t.map)==null?void 0:f.beautify)!==void 0&&this.runtime.enableBeautify&&((g=this.managers.mapManager)==null||g.reprocessStructuredMap(),(m=this.managers.mapManager)==null||m.reprocessRasterMap()),C.log("[Config] Configuration updated",t),this.renderOnceNextFrame()}metersToPixels(t){return this.coords.toPixels(it(t))}pixelsToMeters(t){return this.coords.toMeters(Wt(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 C.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),f=c*u+d*p,g=-c*p+d*u,m=f-this.mapState.origin.x,x=g-this.mapState.origin.y;return{x:m,y:x}}getMapCenterPoint(){if(!this.mapState)return C.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 C.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 f;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(it(i))/2,c=((f=this.components.appContainer)==null?void 0:f.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(g=>({x:a.x+g.vx*d+g.vy*u,y:a.y-g.vx*u+g.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=mi(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=(f,g)=>{const m=typeof f=="number"&&Number.isFinite(f)?f:g;return r!=null?Math.min(Math.max(m,s),r):Math.max(m,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?(C.warn("[Room] No room IDs provided"),!1):this.managers.mapManager.areRoomsAdjacent(t)}isPointInAnyRoom(t){return!t||typeof t.x!="number"||typeof t.y!="number"?(C.warn("[Room] Invalid point provided"),null):this.mapState?this.managers.mapManager.isPointInAnyRoom(t):(C.warn("[Room] Map state not available"),null)}isPointInRoom(t,i){return!t||typeof t.x!="number"||typeof t.y!="number"?(C.warn("[Room] Invalid point provided"),!1):this.mapState?this.managers.mapManager.isPointInRoom(t,i):(C.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"?(C.warn("[Room] Invalid wall points provided"),!1):this.mapState?this.managers.mapManager.isWallIntersectsAnyRoom(t):(C.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"?(C.warn("[Room] Invalid zone points provided"),!1):this.mapState?this.managers.mapManager.isZoneIntersectsAnyRoom(t):(C.warn("[Room] Map state not available"),!1)}isNearChargerOrRobot(t,i,s){var h,l;if(!t||t.length<1)return C.warn("[Distance] Invalid points array: must have at least 1 point"),!1;if(t.length!==1&&t.length!==2&&t.length!==4)return C.warn("[Distance] Invalid points array: must have exactly 1 (point), 2 (wall) or 4 (zone) points"),!1;if(i<=0)return C.warn("[Distance] Invalid threshold: must be greater than 0"),!1;if(!this.mapState)return C.warn("[Distance] Map state not available"),!1;const{checkCharger:r=!0,checkRobot:o=!1}=s||{};if(!r&&!o)return C.warn("[Distance] At least one of checkCharger or checkRobot must be true"),!1;const a=this.coords.toPixels(it(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 C.warn("[Distance] Charger position not available"),!1;const p=Mh(c,t);if(p<=a)return C.log(`[Distance] Too close to charger: ${p.toFixed(2)} pixels (threshold: ${a.toFixed(2)} pixels)`),!0}else C.warn("[Distance] Charger position not available")}if(o){const c=this.appService.getRobotPosition();if(c){const d=Mh(c,t);if(d<=a)return C.log(`[Distance] Too close to robot: ${d.toFixed(2)} pixels (threshold: ${a.toFixed(2)} pixels)`),!0}else C.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 C.error("[MapApplication] Snapshot failed: invalid bounds",a),"";const u=i.resolution||window.devicePixelRatio||2,p=xo.create({width:c,height:d,resolution:u}),f=new O;f.rect(0,0,c,d).fill(r);const g=new H;g.translate(-h,-l);try{return this.renderer.render({container:f,target:p}),this.renderer.render({container:o,target:p,transform:g,clear:!1}),await this.renderer.extract.base64({target:p,format:i.format,quality:i.quality,antialias:i.antialias})}catch(m){return C.error("[MapApplication] Snapshot failed:",m),""}finally{f.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 f=`SNAPSHOT_${Fh()}`;C.log(`[MapApplication] ${f} snapshot start`);const g=new ji(f);try{if(await g.initialize({config:this.config,runtime:u}),!t)throw new Error("Map data is required");if(t.startsWith("7b22")){const x=Cu(t);await g.drawMap(x)}else{const x=_u(t,{pointsStructured:!0});if(x)await g.drawRasterMap(x);else throw new Error("Failed to decode raster map data")}if(i){const{decodePath:x}=await ze(async()=>{const{decodePath:b}=await import("./theme.CAU4HwNY.js").then(v=>v.f);return{decodePath:b}},__vite__mapDeps([4,2])),S=x(i);g.drawPath(S)}s&&s.length>0&&await g.drawRoomProperty(s),o&&o.length>0&&g.drawForbiddenSweepZones(o),a&&a.length>0&&g.drawForbiddenMopZones(a),h&&h.length>0&&g.drawVirtualWalls(h),d&&d.length>0&&await g.drawCustomCarpets(d),c&&c.length>0&&await g.drawFurnitures(c),l&&l.length>0&&await g.drawDetectedObjects(l),r&&r.length>0&&await g.drawCustomElements(r);const m=await g.snapshot(p);return C.log(`[MapApplication] ${f} snapshot completed successfully`),m}catch(m){throw C.error(`[MapApplication] ${f} snapshot other map failed:`,m),m}finally{C.log(`[MapApplication] ${f} destroy`),g.destroy()}}renderOnce(){C.debug("[Pixi] renderOnce");try{this.render()}catch(t){C.error("[Pixi] renderOnce failed",this.getRendererDiagnostics({error:t}))}}renderOnceNextFrame(){this.pendingAsyncRender||(this.pendingAsyncRender=!0,requestAnimationFrame(()=>{C.debug("[Pixi] renderOnceNextFrame");try{this.render()}catch(t){C.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),C.debug("[Ticker] requestRender(continuous)",{reason:t,hadPendingStop:s,reasonsAfterAdd:[...this.tickerState.renderReasons],tickerStarted:(r=this.ticker)==null?void 0:r.started}),this.ticker.started||(C.debug(`🎬 [Ticker] START: ${t}`),this.ticker.start()),this.emitRenderStateUpdate()}stopRender(t){var i;this.tickerState.lastStopReason=t,this.tickerState.renderReasons.delete(t),C.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,f;if(!this.isDestroying){this.isDestroying=!0,C.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(),(f=this.managers.heatmapManager)==null||f.destroy(),this.detachRendererDiagnostics(),iS(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 sb(this.config,this.containerElement),this.stage.addChild(this.components.viewportContainer);const t=this.getViewportBounds();this.components.background=new l0(this.config.global,t,()=>{this.renderOnceNextFrame()}),this.components.viewportContainer.addChild(this.components.background),this.components.viewportContainer.setChildIndex(this.components.background,0),nn(this.config.global,()=>{var i;(i=this.components.background)==null||i.update(this.config.global)})}initializeAppContainer(){this.components.appContainer=new ab(this.appService),this.components.interaction.addChild(this.components.appContainer)}initializeInteraction(){this.components.interaction=new GS(this.appService),this.components.viewportContainer.addChild(this.components.interaction)}scheduleStopRender(t,i){this.tickerState.renderTimer&&clearTimeout(this.tickerState.renderTimer),C.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?(C.debug("⏸️ [Ticker] STOP"),this.ticker&&(this.ticker.stop(),this.emitRenderStateUpdate())):C.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 g;const{center:i,widthMeters:s,heightMeters:r,applyMapRotation:o,visualOffsetX:a=0,visualOffsetY:h=0}=t,l=this.coords.toPixels(it(s))/2,c=this.coords.toPixels(it(r))/2,d=o&&((g=this.components.appContainer)==null?void 0:g.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(m=>({x:i.x+m.vx*u+m.vy*p,y:i.y-m.vx*p+m.vy*u}))}preloadAssets(){var o;const t=this.config.robot.icon.src,i=this.config.chargingStation.icon.src,s=[];X.add({alias:"robot",src:t}),s.push("robot"),X.add({alias:"chargingStation",src:i}),s.push("chargingStation"),X.add({alias:"deleteIcon",src:this.config.controls.deleteIconSrc}),s.push("deleteIcon"),X.add({alias:"rotateIcon",src:this.config.controls.rotateIconSrc}),s.push("rotateIcon"),X.add({alias:"scaleIcon",src:this.config.controls.scaleIconSrc}),s.push("scaleIcon"),X.add({alias:"moveIcon",src:this.config.controls.moveIconSrc}),s.push("moveIcon"),X.add({alias:"checkmark",src:this.config.room.selectionIndicator.iconSrc}),s.push("checkmark"),X.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&&(X.add({alias:"roomAnchorIcon",src:r}),s.push("roomAnchorIcon")),X.add({alias:"wayPoint",src:this.config.controls.wayPoint.normal.iconSrc}),s.push("wayPoint"),X.add({alias:"wayPointActive",src:this.config.controls.wayPoint.editing.iconSrc}),s.push("wayPointActive"),X.add({alias:"horizontalScaleIcon",src:this.config.controls.horizontalScaleIconSrc}),s.push("horizontalScaleIcon"),X.add({alias:"verticalScaleIcon",src:this.config.controls.verticalScaleIconSrc}),s.push("verticalScaleIcon"),this.config.room.property.cleanMode.assets.forEach((a,h)=>{const l=`cleanMode_${h}`;X.add({alias:l,src:a}),s.push(l)}),this.config.room.property.suction.assets.forEach((a,h)=>{const l=`fan_${h}`;X.add({alias:l,src:a}),s.push(l)}),this.config.room.property.cistern.assets.forEach((a,h)=>{const l=`water_${h}`;X.add({alias:l,src:a}),s.push(l)}),this.config.room.property.cleanTimes.assets.forEach((a,h)=>{const l=`cleanTimes${h+1}`;X.add({alias:l,src:a}),s.push(l)}),this.config.room.floorType.assets.forEach((a,h)=>{if(!a)return;const l=`floorType${h}`;X.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}`;X.add({alias:d,src:l}),s.push(d)})}),this.config.furniture.assets.forEach(a=>{const h=`furniture_${a.type}`;X.add({alias:h,src:a.src}),s.push(h)}),X.backgroundLoad(s)}setupMapRotationListener(){this.applyMapRotation(this.runtime.mapRotation),z(this.runtime,"mapRotation",t=>{this.applyMapRotation(t)})}applyMapRotation(t){const i=(t%360+360)%360;C.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()}};y(ji,"CONTEXT_LOSS_TAIL_SIZE",8);let Xr=ji;const C0=Object.freeze(Object.defineProperty({__proto__:null,AppService:wd,MapApplication:Xr},Symbol.toStringTag,{value:"Module"}));export{Ra as $,Wi as A,xe as B,ge as C,Kr as D,Jt as E,to as F,O as G,xy as H,ui as I,om as J,tn as K,Kg as L,H as M,Vt as N,en as O,tt as P,Jr as Q,et as R,lg as S,U as T,He as U,j as V,ac as W,he as X,rs as Y,og as Z,vi as _,ci as a,Ui as a0,eo as a1,nc as a2,Gt as a3,fi as a4,wc as a5,Lg as a6,Gg as a7,w0 as a8,_c as a9,Qi as aA,ug as aB,Cc as aC,zg as aD,Hg as aE,Sy as aF,Mc as aG,Ng as aH,cy as aI,C0 as aJ,Ne as aa,Es as ab,qp as ac,Lu as ad,be as ae,pi as af,Vg as ag,Ft as ah,Rl as ai,Ot as aj,qs as ak,ea as al,Qt as am,Jy as an,pp as ao,sa as ap,Cn as aq,na as ar,gp as as,El as at,xo as au,fo as av,hc as aw,ns as ax,wf as ay,yf as az,Fr as b,ht as c,V as d,ve as e,Br as f,ws as g,St as h,Z as i,Gp as j,gt as k,Fy as l,ut as m,Ep as n,Tp as o,F as p,xt as q,qu as r,ly as s,oh as t,Qp as u,J as v,at as w,Q as x,W as y,ot as z};
|