@archilogic/floor-plan-sdk 5.1.15 → 5.1.16

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/fpe.js CHANGED
@@ -1 +1 @@
1
- const t=3.28084,e=(t,e=1/64)=>{const i=1/e;return Math.round(t*i)/i};function i(t){return Math.sign(t)*Math.floor(Math.abs(t))}function s(t,e){return typeof t<"u"&&null!==t&&Number.isFinite(t)&&t>=-e&&t<=e}const r=" ",n="m",o="′",a="″",l="m²",h="ft²";function u(t,e=.5,i=1/64){return!(t%e)||e<=i?[t/e,1/e]:u(t,e/2)}const c=(s=0,l="metric",h=3)=>{if("imperial"===l){const{feet:n,inches:l,fraction:h,isNegative:c}=function(s){const r=s*t,n=Math.abs(r),o=e(n%1*12);return{feet:i(n),inches:i(o),fraction:e(o%1),isNegative:Math.sign(s)<0}}(s);let d="";if(h>0){const[t,i]=u(e(h));d=`${r}${t}/${i}`}return`${c?"-":""}${n}${o}${r}${l}${d}${a}`}const c=Math.pow(10,h);return`${Math.round(s*c)/c}${r}${n}`},d=(e=0,i="metric",s=0,n=!0)=>{let o="",a="";const u=Math.pow(10,s);if("imperial"===i){const i=function(e){return e*t*t}(e);o=""+Math.round(i*u)/u,a=`${r}${h}`}else o=""+Math.round(e*u)/u,a=`${r}${l}`;return n&&(o+=a),o};["US","USA","United States","U.S","U.S.A","England","UK","U.K","United Kingdom","Liberia","Myanmar"].map(t=>t.toLowerCase());const p=(t,e)=>{const i=`.${e}`;return(t=>t.replace(/[/\\]/g,"_"))((t=>t.replace(/[.,\s]/g,"_"))(t.endsWith(i)?t.split(i)[0]:t))+i};function f(t){const e=function(t){return"#"===t.slice(0,1)&&(t=t.slice(1)),t}(t);return 3===e.length?`#${e.split("").map(t=>t+t).join("")}`:t}function m(t){return t>=0&&t<=255}function g(t){const e=f(t),i={r:parseInt(e.substring(1,3),16),g:parseInt(e.substring(3,5),16),b:parseInt(e.substring(5,7),16)};if(function({r:t,g:e,b:i}){return m(t)&&m(e)&&m(i)}(i))return i;throw"invalid hex color input"}function y(t){return JSON.parse(JSON.stringify(t))}function v(...t){let e={};for(const i of t)if(i instanceof Array)e instanceof Array||(e=[]),e=[...e,...i];else if(i instanceof Object)for(const t of Object.entries(i)){const i=t[0];let s=t[1];s instanceof Object&&i in e&&(s=v(e[i],s)),e={...e,[i]:s}}return e}function x(){return typeof window<"u"&&typeof navigator<"u"&&typeof document<"u"}!x()||window.self===window.top||window.location.ancestorOrigins&&window.location.ancestorOrigins[0]||document.referrer,x()&&navigator.platform.toUpperCase().indexOf("MAC");var b={exports:{}};function _(){}_.prototype={on:function(t,e,i){var s=this.e||(this.e={});return(s[t]||(s[t]=[])).push({fn:e,ctx:i}),this},once:function(t,e,i){var s=this;function r(){s.off(t,r),e.apply(i,arguments)}return r._=e,this.on(t,r,i)},emit:function(t){for(var e=[].slice.call(arguments,1),i=((this.e||(this.e={}))[t]||[]).slice(),s=0,r=i.length;s<r;s++)i[s].fn.apply(i[s].ctx,e);return this},off:function(t,e){var i=this.e||(this.e={}),s=i[t],r=[];if(s&&e)for(var n=0,o=s.length;n<o;n++)s[n].fn!==e&&s[n].fn._!==e&&r.push(s[n]);return r.length?i[t]=r:delete i[t],this}},b.exports=_;var w=b.exports.TinyEmitter=_;const P=["info","warnings","errors"];class E extends w{constructor(t){super(),this.levels=P.slice(),this.info=this.log,t&&this.setLevels(t),this.levelStack=[]}setLevels(t){const e=this.levels.slice();if("string"==typeof t)switch(t){case"none":this.levels=[];break;case"all":this.levels=["debug","info","warnings","errors"];break;case"debug":this.levels=["debug"];break;case"info":this.levels=["info"];break;case"warnings":this.levels=["warnings"];break;case"errors":this.levels=["errors"];break;default:console.error(`Unknown setting '${t}'.`)}else this.levels=t.slice();return e}push(){this.levelStack.push(this.levels)}pushAndSetLevels(t){return this.push(),this.setLevels(t)}pop(){if(this.levelStack.length>0){const t=this.levelStack.pop();this.setLevels(t)}}debug(...t){this.levels.includes("debug")&&(console.debug(...t),this.emit("debug",...t))}log(...t){this.levels.includes("info")&&(console.log(...t),this.emit("info",...t))}warn(...t){this.levels.includes("warnings")&&(console.warn(...t),this.emit("warning",...t))}error(...t){this.levels.includes("errors")&&(console.error(...t),this.emit("error",...t))}}for(var T,A=[],I=0;I<256;++I)A.push((I+256).toString(16).slice(1));var S=new Uint8Array(16);function C(){if(!T&&!(T="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return T(S)}const M={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function O(t,e,i){if(M.randomUUID&&!t)return M.randomUUID();var s=(t=t||{}).random||(t.rng||C)();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,function(t,e=0){return(A[t[e+0]]+A[t[e+1]]+A[t[e+2]]+A[t[e+3]]+"-"+A[t[e+4]]+A[t[e+5]]+"-"+A[t[e+6]]+A[t[e+7]]+"-"+A[t[e+8]]+A[t[e+9]]+"-"+A[t[e+10]]+A[t[e+11]]+A[t[e+12]]+A[t[e+13]]+A[t[e+14]]+A[t[e+15]]).toLowerCase()}(s)}const N=t=>{const e=[];for(const[i,s]of Object.entries(t))void 0!==s&&e.push(`${i}=${String(s)}`);return e.length?`?${e.join("&")}`:""};class L extends Error{code;data;constructor(t,e,i){super(t||"There was a problem. Please check your internet connection and try again."),this.name="SpaceApiError",this.stack=(new Error).stack,this.code=e,this.data=i}}let R="https://api.archilogic.com";function k(t){let e;if(t.secretAccessToken)e={type:"secret",secretAccessToken:t.secretAccessToken};else if(t.temporaryAccessToken||t.temporaryAccessTokenFunction)e={type:"temporary",temporaryAccessToken:t.temporaryAccessToken};else{if(!t.publishableAccessToken)throw new L("Programming error: token is not provided.",void 0,void 0);e={type:"publishable",publishableAccessToken:t.publishableAccessToken}}return t.sdkVersion&&(e.sdkVersion=t.sdkVersion),e}function B(t){return t.status>=200&&t.status<400?t:t.json().then(e=>{const i=e?.message||e?.error||e;switch(typeof i){case"string":return Promise.reject(new L(i,t.status,void 0));case"object":return Promise.reject(new L(i.message,t.status,i.data));default:return Promise.reject(new L(null,null,e))}})}async function F(t,e,i={},s){const r=new URL(R+e),n=function(t){const e=new Headers;switch(t.type){case"secret":e.set("authorization",`AL-Secret-Token ${t.secretAccessToken}`);break;case"temporary":e.set("authorization",`${t.temporaryAccessToken?.authorization}`)}return t.sdkVersion&&e.set("x-sdk-version",t.sdkVersion),e}(s);let o=!1;switch("publishable"===s.type&&r.searchParams.set("pubtoken",s.publishableAccessToken),t){case"GET":i&&"object"==typeof i&&Object.entries(i).forEach(([t,e])=>{void 0!==e&&r.searchParams.set(t,e.toString())});break;case"POST":case"PUT":case"PATCH":n.set("content-type","application/json"),o=!0;break;case"DELETE":break;default:return Promise.reject(new L("Programming error, unsupported method: "+t,void 0,void 0))}return fetch(r.toString(),{method:t,headers:n,body:o?JSON.stringify(i):void 0}).then(B,t=>{throw t}).then(t=>t.json()).catch(t=>Promise.reject(t))}class D{config;temporaryAccessTokenFunction;tempScopes=[{resource:"floor",action:"readPublic"},{resource:"floor",action:"readPrivate"},{resource:"floor",action:"queryPublic"},{resource:"floor",action:"queryPrivate"},{resource:"floor",action:"archive"},{resource:"customFields",action:"readPublic"},{resource:"customFields",action:"readPrivate"},{resource:"customFields",action:"write"}];temporaryAccessToken;temporaryAccessTokenPromise;durationSeconds=3600;constructor(t){this.config=k(t),(t.temporaryAccessToken||t.temporaryAccessTokenFunction)&&(this.temporaryAccessTokenFunction=t.temporaryAccessTokenFunction,this.temporaryAccessToken=t.temporaryAccessToken),t.temporaryAccessTokenScopes&&(this.tempScopes=t.temporaryAccessTokenScopes)}get isAccessTokenActive(){const t=/* @__PURE__ */(new Date).getTime()/1e3;return!!this.temporaryAccessToken&&this.temporaryAccessToken.expiresAt>t}async getTemporaryAccessToken(){if(this.isAccessTokenActive&&this.temporaryAccessToken)return this.temporaryAccessToken;this.temporaryAccessTokenPromise||(this.temporaryAccessTokenPromise=new Promise(async(t,e)=>{if(this.temporaryAccessTokenFunction&&(this.temporaryAccessToken=await this.temporaryAccessTokenFunction({scopes:this.tempScopes,durationSeconds:this.durationSeconds}),this.isAccessTokenActive&&t(this.temporaryAccessToken)),this.temporaryAccessToken){const t=/* @__PURE__ */new Date;t.setTime(1e3*this.temporaryAccessToken.expiresAt),e(new L(`Temporary access token expired at ${t.toString()}`,void 0,void 0))}else e(new L("Temporary access token not defined",void 0,void 0))}));try{return await this.temporaryAccessTokenPromise}catch(t){throw this.temporaryAccessTokenPromise=void 0,t}finally{this.isAccessTokenActive&&(this.temporaryAccessTokenPromise=void 0)}}async callSpaceAPI(t,e,i={},s=this.config){switch(s.type){case"secret":case"publishable":return F(t,e,i,s);case"temporary":{const r=await this.getTemporaryAccessToken();return F(t,e,i,{...s,temporaryAccessToken:r})}}}}class U{connection;constructor(t,e={}){this.connection=new D(t);for(const[i,s]of Object.entries(e))this[i]=s}async getTemporaryAccessToken(){return this.connection.getTemporaryAccessToken()}async createFloor(t){return this.connection.callSpaceAPI("POST","/v2/floor",t)}async duplicateFloor(t,e){const i=e.revisionId?`?revisionId=${e.revisionId}`:"";return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/duplicate${i}`)}async updateFloor(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/floor/${t}`,e)}async archiveFloor(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/archive`)}async unarchiveFloor(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/unarchive`)}async searchFloorsBasic(t){const{name:e,id:i,paginationInput:s,teamId:r}=t,n=((t,e,i,s)=>{const r={};return t&&(r.name={contains:`${t}`}),e&&(r.ids=[e]),s&&(r.team={id:{eq:s}}),{query:"query ($floorFilter: FloorFilter!, $paginationInput: PaginationInput) { getFloors(where: $floorFilter, paginationInput: $paginationInput) { floors { id name area createdAt updatedAt labels { name color } }, paginationInfo { currentPage limit offset totalCount totalPageCount} } }",variables:{floorFilter:r,paginationInput:i}}})(e,i,s,r);return this.connection.callSpaceAPI("POST","/graphql",n)}async searchFloorsAdvanced(t,e){const i=((t,e)=>({query:t,variables:{paginationInput:e}}))(t,e);return this.connection.callSpaceAPI("POST","/graphql",i)}async getFloorById(t,e=!1,i=!0,s=!1,r,n=!1){const o=N({includeAddress:s,includeRelations:i,includeCustomAttributes:n}),a=await this.connection.callSpaceAPI("GET",`/v2/floor/${t}${e?"/geo-json":""}${o}`);let l={};if(a.properties?.defaultLayoutId){const{layout:t,id:e,lastRevision:i,categories:s}=await this.getLayout(a.properties.defaultLayoutId,r);l={layout:{id:e,layout:t,lastRevision:i,categories:s}}}return{...a,...l}}async getFloorGeoJson(t,e){const i=N(e??{}),s=await this.connection.callSpaceAPI("GET",`/v2/floor/${t}/geo-json${i}`);let r;if(e?.includeAllElements){const t=s.features.find(t=>"Floor"===t.properties.resourceType);r=t?.properties.defaultLayoutId}else{r=s.properties.defaultLayoutId}if(r){const{layout:t,id:e,lastRevision:i,categories:n}=await this.getLayout(r);return{...s,layout:{id:e,layout:t,lastRevision:i,categories:n}}}return s}getFloorStatistics(t){return this.connection.callSpaceAPI("GET",`/v2/floor/${t}/statistics`)}queryFloors(t){return this.connection.callSpaceAPI("GET","/v2/floor",t)}async getAllFloors(t=!1,e=!1,i=!1,s,r){const n=t||i?1e3:1e4,o=await this.queryFloors({geometry:t,includeArchived:e,includeRelations:i,includeCustomAttributes:r,teamId:s,limit:n});let a=o.features||[];if(a.length<n)return o;for(;a?.length;)a=(await this.queryFloors({geometry:t,includeArchived:e,includeRelations:i,includeCustomAttributes:r,teamId:s,offset:o.features.length,limit:n})).features||[],o.features.push(...a);return o}getFloorplanImage(t,e){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/2d-image`,e)}getSceneStructure(t,e=!1){return this.connection.callSpaceAPI("GET",`/v2/floor/${t}/scene-structure`,{includeMetadata:e})}assignLabel(t,e){return this.connection.callSpaceAPI("PUT",`/v2/floor/${t}/label/${e}`)}removeLabel(t,e){return this.connection.callSpaceAPI("DELETE",`/v2/floor/${t}/label/${e}`)}getSpaceById(t,e=!1,i=!0){const s=`?includeRelations=${i}`;return this.connection.callSpaceAPI("GET",`/v2/space/${t}/${e?"geo-json":""}${s}`)}querySpaces(t){return this.connection.callSpaceAPI("GET","/v2/space",t)}async getAllSpacesByFloorId(t,e=!1,i,s){const r=1e3,n=await this.querySpaces({floorId:t,geometry:e,includeRelations:i,includeCustomAttributes:s,limit:r});let o=n.features||[];if(o.length<r)return n;for(;o?.length;)o=(await this.querySpaces({floorId:t,geometry:e,includeRelations:i,includeCustomAttributes:s,offset:n.features.length,limit:r})).features||[],n.features.push(...o);return n}getAssetById(t,e=!1,i=!0,s=!1){const r=N({includeRelations:i,includeCustomAttributes:s});return this.connection.callSpaceAPI("GET",`/v2/asset/${t}/${e?"geo-json":""}${r}`)}queryAssets(t){return this.connection.callSpaceAPI("GET","/v2/asset",t)}async getAllAssets(t){const{limit:e=1e4,...i}=t,s=await this.queryAssets({...i,limit:e});let r=s.features||[];if(r.length<e)return s;for(;r?.length;)r=(await this.queryAssets({...t,offset:(t.offset||0)+s.features.length,limit:e})).features||[],s.features.push(...r);return s}getAllAssetsByFloorId(t,e=!1,i,s){return this.getAllAssets({floorId:t,geometry:e,includeRelations:i,includeCustomAttributes:s})}getAllAssetsBySpaceId(t,e=!1,i,s){return this.getAllAssets({spaceId:t,geometry:e,includeRelations:i,includeCustomAttributes:s})}getCustomField(t,e,i){return this.connection.callSpaceAPI("GET",`/v2/${t}/${e}/custom-field/${i}`)}getAllCustomFields(t,e){return this.connection.callSpaceAPI("GET",`/v2/${t}/${e}/custom-field`)}setCustomField(t,e,i,s){return this.connection.callSpaceAPI("PUT",`/v2/${t}/${e}/custom-field/${i}`,s)}deleteCustomField(t,e,i){return this.connection.callSpaceAPI("DELETE",`/v2/${t}/${e}/custom-field/${i}`)}getLabel(t){return this.connection.callSpaceAPI("GET",`/v2/label/${t}`)}listLabels(){return this.connection.callSpaceAPI("GET","/v2/label/")}createOrUpdateLabel(t,e){return this.connection.callSpaceAPI("PUT",`/v2/label/${t}`,e)}deleteLabel(t){return this.connection.callSpaceAPI("DELETE",`/v2/label/${t}`)}getCustomAttributes(){return this.connection.callSpaceAPI("GET","/v2/custom-attributes")}getCustomAttribute(t,e){return this.connection.callSpaceAPI("GET",`/v2/${t.toLowerCase()}/custom-attributes/${e}`)}getCustomAttributesForResourceType(t){return this.connection.callSpaceAPI("GET",`/v2/${t.toLowerCase()}/custom-attributes`)}createCustomAttribute(t){const{resourceType:e,...i}=t;return this.connection.callSpaceAPI("POST",`/v2/${e.toLowerCase()}/custom-attributes`,i)}updateCustomAttribute(t){const{apiFieldName:e,resourceType:i,...s}=t;return this.connection.callSpaceAPI("PATCH",`/v2/${i.toLowerCase()}/custom-attributes/${e}`,s)}deleteCustomAttribute(t,e){return this.connection.callSpaceAPI("DELETE",`/v2/${t.toLowerCase()}/custom-attributes/${e}`)}getCustomAttributeValues(t,e){return this.connection.callSpaceAPI("GET",`/v2/${t.toLowerCase()}/${e}/custom-attributes`)}createCustomAttributeValue(t){const{apiFieldName:e,resourceId:i,resourceType:s,...r}=t;return this.connection.callSpaceAPI("POST",`/v2/${s.toLowerCase()}/${i}/custom-attributes/${e}`,r)}updateCustomAttributeValue(t){const{apiFieldName:e,resourceId:i,resourceType:s,...r}=t;return this.connection.callSpaceAPI("PATCH",`/v2/${s.toLowerCase()}/${i}/custom-attributes/${e}`,r)}deleteCustomAttributeValue(t,e,i){return this.connection.callSpaceAPI("DELETE",`/v2/${e.toLowerCase()}/${t}/custom-attributes/${i}`)}createLayout(t,e,i){return this.connection.callSpaceAPI("POST","/v2/layout",{floorId:t,layout:e,isDefault:i})}duplicateLayout(t,e){const i=N({revisionId:e});return this.connection.callSpaceAPI("POST",`/v2/layout/${t}/duplicate${i}`,{layoutId:t,revisionId:e})}getLayout(t,e){const i=N(e?{filter:e}:{});return this.connection.callSpaceAPI("GET",`/v2/layout/${t}${i}`)}getLayouts(t,e){const i=N({floorId:t,isDefault:e});return this.connection.callSpaceAPI("GET",`/v2/layout/${i}`)}updateLayout(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/layout/${t}`,e)}deleteLayout(t){return this.connection.callSpaceAPI("DELETE",`/v2/layout/${t}`)}createLayoutRevision(t,e){return this.connection.callSpaceAPI("POST",`/v2/layout/${t}/revisions`,e)}updateLayoutRevision(t,e,i){return this.connection.callSpaceAPI("PATCH",`/v2/layout/${t}/revisions/${e}`,i)}getLayoutRevisions(t,e){const i=N(e?{filter:e}:{});return this.connection.callSpaceAPI("GET",`/v2/layout/${t}/revisions${i}`)}getLayoutRevision(t,e){return this.connection.callSpaceAPI("GET",`/v2/layout/${t}/revisions/${e}`)}convertLanguageToQuery(t){return this.connection.callSpaceAPI("POST","/v2/language/graphql",t)}convertLanguageToAgentResponse(t){return this.connection.callSpaceAPI("POST","/v2/language/query-floors",t)}getDxf(t){return this.connection.callSpaceAPI("GET",`/v2/floor/${t}/dxf`)}getIfc(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/ifc`)}getGltf(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/gltf`)}getImdf(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/imdf`)}getImdfs(t){return this.connection.callSpaceAPI("POST","/v2/floor/imdf",t)}listExtensions(t){return this.connection.callSpaceAPI("GET","/v2/extensions",t)}createExtension(t){return this.connection.callSpaceAPI("POST","/v2/extensions",t)}updateExtension(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/extensions/${t}`,e)}deleteExtension(t){return this.connection.callSpaceAPI("DELETE",`/v2/extensions/${t}`)}listExtensionAccess(t){return this.connection.callSpaceAPI("GET",`/v2/extensions/${t}/access`)}grantExtensionAccess(t,e){return this.connection.callSpaceAPI("PUT",`/v2/extensions/${t}/access/${e}`)}revokeExtensionAccess(t,e){return this.connection.callSpaceAPI("DELETE",`/v2/extensions/${t}/access/${e}`)}listBuildings(){return this.connection.callSpaceAPI("GET","/v2/buildings")}createBuilding(t){return this.connection.callSpaceAPI("POST","/v2/buildings",t)}getBuildingById(t){return this.connection.callSpaceAPI("GET",`/v2/buildings/${t}`)}updateBuilding(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/buildings/${t}`,e)}deleteBuilding(t){return this.connection.callSpaceAPI("DELETE",`/v2/buildings/${t}`)}}var G;(t=>{t.version="6.4.2.3",t.use_lines=!0;class e{m_Parent=null;m_polygon=[];m_Index=0;m_jointype=0;m_endtype=0;m_Children=[];IsOpen=!1;IsHoleNode(){for(var t=!0,e=this.m_Parent;null!==e;)t=!t,e=e.m_Parent;return t}ChildCount(){return this.m_Children.length}Contour(){return this.m_polygon}AddChild(t){var e=this.m_Children.length;this.m_Children.push(t),t.m_Parent=this,t.m_Index=e}GetNext(){return this.m_Children.length>0?this.m_Children[0]:this.GetNextSiblingUp()}GetNextSiblingUp(){return null===this.m_Parent?null:this.m_Index===this.m_Parent.m_Children.length-1?this.m_Parent.GetNextSiblingUp():this.m_Parent.m_Children[this.m_Index+1]}Children(){return this.m_Children}Parent(){return this.m_Parent}IsHole(){return this.IsHoleNode()}}t.PolyNode=e;t.PolyTree=class extends e{m_AllPolys=[];constructor(){super()}Clear(){for(var t=0,e=this.m_AllPolys.length;t<e;t++)this.m_AllPolys[t]=null;this.m_AllPolys.length=0,this.m_Children.length=0}GetFirst(){return this.m_Children.length>0?this.m_Children[0]:null}Total(){var t=this.m_AllPolys.length;return t>0&&this.m_Children[0]!==this.m_AllPolys[0]&&t--,t}},t.Clear=function(t){t.length=0},t.PI=3.141592653589793,t.PI2=6.283185307179586;t.FPoint=class{X=0;Y=0;constructor(...e){var i=e,s=e.length;if(this.X=0,this.Y=0,2===s)this.X=i[0],this.Y=i[1];else if(1===s)if(i[0]instanceof t.FPoint){var r=i[0];this.X=r.X,this.Y=r.Y}else{var n=i[0];this.X=n.X,this.Y=n.Y}else this.X=0,this.Y=0}static op_Equality(t,e){return t.X===e.X&&t.Y===e.Y}static op_Inequality(t,e){return t.X!==e.X||t.Y!==e.Y}};var i,s,r,n,o,a,l,h;t.FRect=class{left;top;right;bottom;constructor(...t){var e=t,i=t.length;if(4===i)this.left=e[0],this.top=e[1],this.right=e[2],this.bottom=e[3];else if(1===i){var s=e[0];this.left=s.left,this.top=s.top,this.right=s.right,this.bottom=s.bottom}else this.left=0,this.top=0,this.right=0,this.bottom=0}},(i=t.ClipType||(t.ClipType={}))[i.ctIntersection=0]="ctIntersection",i[i.ctUnion=1]="ctUnion",i[i.ctDifference=2]="ctDifference",i[i.ctXor=3]="ctXor",(s=t.PolyType||(t.PolyType={}))[s.ptSubject=0]="ptSubject",s[s.ptClip=1]="ptClip",(r=t.PolyFillType||(t.PolyFillType={}))[r.pftEvenOdd=0]="pftEvenOdd",r[r.pftNonZero=1]="pftNonZero",r[r.pftPositive=2]="pftPositive",r[r.pftNegative=3]="pftNegative",(n=t.JoinType||(t.JoinType={}))[n.jtSquare=0]="jtSquare",n[n.jtRound=1]="jtRound",n[n.jtMiter=2]="jtMiter",(o=t.EndType||(t.EndType={}))[o.etOpenSquare=0]="etOpenSquare",o[o.etOpenRound=1]="etOpenRound",o[o.etOpenButt=2]="etOpenButt",o[o.etClosedLine=3]="etClosedLine",o[o.etClosedPolygon=4]="etClosedPolygon",(a=t.EdgeSide||(t.EdgeSide={}))[a.esLeft=0]="esLeft",a[a.esRight=1]="esRight",(l=t.Direction||(t.Direction={}))[l.dRightToLeft=0]="dRightToLeft",l[l.dLeftToRight=1]="dLeftToRight",(h=t.NodeType||(t.NodeType={}))[h.ntAny=0]="ntAny",h[h.ntOpen=1]="ntOpen",h[h.ntClosed=2]="ntClosed";t.TEdge=class{Bot=new t.FPoint;Curr=new t.FPoint;Top=new t.FPoint;Delta=new t.FPoint;Dx=0;PolyTyp=0;Side=0;WindDelta=0;WindCnt=0;WindCnt2=0;OutIdx=0;Next=null;Prev=null;NextInLML=null;NextInAEL=null;PrevInAEL=null;NextInSEL=null;PrevInSEL=null};t.IntersectNode=class{Edge1=null;Edge2=null;Pt=new t.FPoint},t.Compare=function(t,e){var i=e.Pt.Y-t.Pt.Y;return i>0?1:i<0?-1:0};t.LocalMinima=class{Y=0;LeftBound=null;RightBound=null;Next=null};t.Scanbeam=class{Y=0;Next=null};t.Maxima=class{X=0;Next=null;Prev=null};t.OutRec=class{Idx=0;IsHole=!1;IsOpen=!1;FirstLeft=null;Pts=null;BottomPt=null;PolyNode=null};t.OutPt=class{Idx=0;Pt=new t.FPoint;Next=null;Prev=null};t.Join=class{OutPt1=null;OutPt2=null;OffPt=new t.FPoint};class u{m_MinimaList=null;m_CurrentLM=null;m_edges=new Array;m_HasOpenPaths=!1;PreserveCollinear=!1;m_Scanbeam=null;m_PolyOuts=null;m_ActiveEdges=null;static horizontal=-34e37;static Skip=-2;static Unassigned=-1;static tolerance=1e-20;static maxValue=Math.sqrt(Number.MAX_VALUE);static minValue=Math.sqrt(Number.MIN_VALUE);static near_zero(e){return e>-t.ClipperBase.tolerance&&e<t.ClipperBase.tolerance}static IsHorizontal(t){return 0===t.Delta.Y}PointIsVertex(e,i){var s=i;do{if(t.FPoint.op_Equality(s.Pt,e))return!0;s=s.Next}while(s!==i);return!1}PointOnLineSegment(t,e,i){return t.X===e.X&&t.Y===e.Y||t.X===i.X&&t.Y===i.Y||t.X>e.X==t.X<i.X&&t.Y>e.Y==t.Y<i.Y&&(t.X-e.X)*(i.Y-e.Y)===(i.X-e.X)*(t.Y-e.Y)}PointOnPolygon(t,e){for(var i=e;;){if(this.PointOnLineSegment(t,i.Pt,i.Next.Pt))return!0;if((i=i.Next)===e)break}return!1}static SlopesEqual(){var t,e,i,s,r,n,o=arguments,a=o.length;return 2===a?(e=o[1],(t=o[0]).Delta.Y*e.Delta.X===t.Delta.X*e.Delta.Y):3===a?(s=o[1],r=o[2],((i=o[0]).Y-s.Y)*(s.X-r.X)-(i.X-s.X)*(s.Y-r.Y)===0):(s=o[1],r=o[2],n=o[3],((i=o[0]).Y-s.Y)*(r.X-n.X)-(i.X-s.X)*(r.Y-n.Y)===0)}static SlopesEqual3(t,e){return t.Delta.Y*e.Delta.X===t.Delta.X*e.Delta.Y}static SlopesEqual4(t,e,i){return(t.Y-e.Y)*(e.X-i.X)-(t.X-e.X)*(e.Y-i.Y)===0}static SlopesEqual5(t,e,i,s){return(t.Y-e.Y)*(i.X-s.X)-(t.X-e.X)*(i.Y-s.Y)===0}Clear(){this.DisposeLocalMinimaList();for(var e=0,i=this.m_edges.length;e<i;++e){for(var s=0,r=this.m_edges[e].length;s<r;++s)this.m_edges[e][s]=null;t.Clear(this.m_edges[e])}t.Clear(this.m_edges),this.m_HasOpenPaths=!1}DisposeLocalMinimaList(){for(;null!==this.m_MinimaList;){var t=this.m_MinimaList.Next;this.m_MinimaList=null,this.m_MinimaList=t}this.m_CurrentLM=null}RangeTest(e){(e.X>t.ClipperBase.maxValue||e.X<-t.ClipperBase.maxValue||e.Y>t.ClipperBase.maxValue||e.Y<-t.ClipperBase.maxValue||e.X>0&&e.X<t.ClipperBase.minValue||e.Y>0&&e.Y<t.ClipperBase.minValue||e.X<0&&e.X>-t.ClipperBase.minValue||e.Y<0&&e.Y>-t.ClipperBase.minValue)&&t.Error("Coordinate outside allowed range in RangeTest().")}InitEdge(t,e,i,s){t.Next=e,t.Prev=i,t.Curr.X=s.X,t.Curr.Y=s.Y,t.OutIdx=-1}InitEdge2(t,e){t.Curr.Y>=t.Next.Curr.Y?(t.Bot.X=t.Curr.X,t.Bot.Y=t.Curr.Y,t.Top.X=t.Next.Curr.X,t.Top.Y=t.Next.Curr.Y):(t.Top.X=t.Curr.X,t.Top.Y=t.Curr.Y,t.Bot.X=t.Next.Curr.X,t.Bot.Y=t.Next.Curr.Y),this.SetDx(t),t.PolyTyp=e}FindNextLocMin(e){for(var i;;){for(;t.FPoint.op_Inequality(e.Bot,e.Prev.Bot)||t.FPoint.op_Equality(e.Curr,e.Top);)e=e.Next;if(e.Dx!==t.ClipperBase.horizontal&&e.Prev.Dx!==t.ClipperBase.horizontal)break;for(;e.Prev.Dx===t.ClipperBase.horizontal;)e=e.Prev;for(i=e;e.Dx===t.ClipperBase.horizontal;)e=e.Next;if(e.Top.Y!==e.Prev.Bot.Y){i.Prev.Bot.X<e.Bot.X&&(e=i);break}}return e}ProcessBound(e,i){var s,r,n=e;if(n.OutIdx===t.ClipperBase.Skip){if(e=n,i){for(;e.Top.Y===e.Next.Bot.Y;)e=e.Next;for(;e!==n&&e.Dx===t.ClipperBase.horizontal;)e=e.Prev}else{for(;e.Top.Y===e.Prev.Bot.Y;)e=e.Prev;for(;e!==n&&e.Dx===t.ClipperBase.horizontal;)e=e.Next}if(e===n)n=i?e.Next:e.Prev;else{e=i?n.Next:n.Prev;var o=new t.LocalMinima;o.Next=null,o.Y=e.Bot.Y,o.LeftBound=null,o.RightBound=e,e.WindDelta=0,n=this.ProcessBound(e,i),this.InsertLocalMinima(o)}return n}if(e.Dx===t.ClipperBase.horizontal&&((s=i?e.Prev:e.Next).Dx===t.ClipperBase.horizontal?s.Bot.X!==e.Bot.X&&s.Top.X!==e.Bot.X&&this.ReverseHorizontal(e):s.Bot.X!==e.Bot.X&&this.ReverseHorizontal(e)),s=e,i){for(;n.Top.Y===n.Next.Bot.Y&&n.Next.OutIdx!==t.ClipperBase.Skip;)n=n.Next;if(n.Dx===t.ClipperBase.horizontal&&n.Next.OutIdx!==t.ClipperBase.Skip){for(r=n;r.Prev.Dx===t.ClipperBase.horizontal;)r=r.Prev;r.Prev.Top.X>n.Next.Top.X&&(n=r.Prev)}for(;e!==n;)e.NextInLML=e.Next,e.Dx===t.ClipperBase.horizontal&&e!==s&&e.Bot.X!==e.Prev.Top.X&&this.ReverseHorizontal(e),e=e.Next;e.Dx===t.ClipperBase.horizontal&&e!==s&&e.Bot.X!==e.Prev.Top.X&&this.ReverseHorizontal(e),n=n.Next}else{for(;n.Top.Y===n.Prev.Bot.Y&&n.Prev.OutIdx!==t.ClipperBase.Skip;)n=n.Prev;if(n.Dx===t.ClipperBase.horizontal&&n.Prev.OutIdx!==t.ClipperBase.Skip){for(r=n;r.Next.Dx===t.ClipperBase.horizontal;)r=r.Next;(r.Next.Top.X===n.Prev.Top.X||r.Next.Top.X>n.Prev.Top.X)&&(n=r.Next)}for(;e!==n;)e.NextInLML=e.Prev,e.Dx===t.ClipperBase.horizontal&&e!==s&&e.Bot.X!==e.Next.Top.X&&this.ReverseHorizontal(e),e=e.Prev;e.Dx===t.ClipperBase.horizontal&&e!==s&&e.Bot.X!==e.Next.Top.X&&this.ReverseHorizontal(e),n=n.Prev}return n}AddPath(e,i,s){t.use_lines?s||1!==i||t.Error("AddPath: Open paths must be subject."):s||t.Error("AddPath: Open paths have been disabled.");var r=e.length-1;if(s)for(;r>0&&t.FPoint.op_Equality(e[r],e[0]);)--r;for(;r>0&&t.FPoint.op_Equality(e[r],e[r-1]);)--r;if(s&&r<2||!s&&r<1)return!1;for(var n=new Array,o=0;o<=r;o++)n.push(new t.TEdge);var a=!0;n[1].Curr.X=e[1].X,n[1].Curr.Y=e[1].Y,this.RangeTest(e[0]),this.RangeTest(e[r]),this.InitEdge(n[0],n[1],n[r],e[0]),this.InitEdge(n[r],n[0],n[r-1],e[r]);for(o=r-1;o>=1;--o)this.RangeTest(e[o]),this.InitEdge(n[o],n[o+1],n[o-1],e[o]);for(var l,h=n[0],u=h,c=h;;)if(u.Curr!==u.Next.Curr||!s&&u.Next===h){if(u.Prev===u.Next)break;if(!s||!t.ClipperBase.SlopesEqual4(u.Prev.Curr,u.Curr,u.Next.Curr)||this.PreserveCollinear&&this.Pt2IsBetweenPt1AndPt3(u.Prev.Curr,u.Curr,u.Next.Curr)){if((u=u.Next)===c||!s&&u.Next===h)break}else u===h&&(h=u.Next),c=u=(u=this.RemoveEdge(u)).Prev}else{if(u===u.Next)break;u===h&&(h=u.Next),c=u=this.RemoveEdge(u)}if(!s&&u===u.Next||s&&u.Prev===u.Next)return!1;s||(this.m_HasOpenPaths=!0,h.Prev.OutIdx=t.ClipperBase.Skip),u=h;do{this.InitEdge2(u,i),u=u.Next,a&&u.Curr.Y!==h.Curr.Y&&(a=!1)}while(u!==h);if(a){if(s)return!1;for(u.Prev.OutIdx=t.ClipperBase.Skip,(p=new t.LocalMinima).Next=null,p.Y=u.Bot.Y,p.LeftBound=null,p.RightBound=u,p.RightBound.Side=1,p.RightBound.WindDelta=0;u.Bot.X!==u.Prev.Top.X&&this.ReverseHorizontal(u),u.Next.OutIdx!==t.ClipperBase.Skip;)u.NextInLML=u.Next,u=u.Next;return this.InsertLocalMinima(p),this.m_edges.push(n),!0}this.m_edges.push(n);var d=null;for(t.FPoint.op_Equality(u.Prev.Bot,u.Prev.Top)&&(u=u.Next);(u=this.FindNextLocMin(u))!==d;){var p;null===d&&(d=u),(p=new t.LocalMinima).Next=null,p.Y=u.Bot.Y,u.Dx<u.Prev.Dx?(p.LeftBound=u.Prev,p.RightBound=u,l=!1):(p.LeftBound=u,p.RightBound=u.Prev,l=!0),p.LeftBound.Side=0,p.RightBound.Side=1,s?p.LeftBound.Next===p.RightBound?p.LeftBound.WindDelta=-1:p.LeftBound.WindDelta=1:p.LeftBound.WindDelta=0,p.RightBound.WindDelta=-p.LeftBound.WindDelta,(u=this.ProcessBound(p.LeftBound,l)).OutIdx===t.ClipperBase.Skip&&(u=this.ProcessBound(u,l));var f=this.ProcessBound(p.RightBound,!l);f.OutIdx===t.ClipperBase.Skip&&(f=this.ProcessBound(f,!l)),p.LeftBound.OutIdx===t.ClipperBase.Skip?p.LeftBound=null:p.RightBound.OutIdx===t.ClipperBase.Skip&&(p.RightBound=null),this.InsertLocalMinima(p),l||(u=f)}return!0}AddPaths(t,e,i){for(var s=!1,r=0,n=t.length;r<n;++r)this.AddPath(t[r],e,i)&&(s=!0);return s}Pt2IsBetweenPt1AndPt3(e,i,s){return!(t.FPoint.op_Equality(e,s)||t.FPoint.op_Equality(e,i)||t.FPoint.op_Equality(s,i))&&(e.X!==s.X?i.X>e.X==i.X<s.X:i.Y>e.Y==i.Y<s.Y)}RemoveEdge(t){t.Prev.Next=t.Next,t.Next.Prev=t.Prev;var e=t.Next;return t.Prev=null,e}SetDx(e){e.Delta.X=e.Top.X-e.Bot.X,e.Delta.Y=e.Top.Y-e.Bot.Y,0===e.Delta.Y?e.Dx=t.ClipperBase.horizontal:e.Dx=e.Delta.X/e.Delta.Y}InsertLocalMinima(t){if(null===this.m_MinimaList)this.m_MinimaList=t;else if(t.Y>=this.m_MinimaList.Y)t.Next=this.m_MinimaList,this.m_MinimaList=t;else{for(var e=this.m_MinimaList;null!==e.Next&&t.Y<e.Next.Y;)e=e.Next;t.Next=e.Next,e.Next=t}}PopLocalMinima(t,e){return e.v=this.m_CurrentLM,null!==this.m_CurrentLM&&this.m_CurrentLM.Y===t&&(this.m_CurrentLM=this.m_CurrentLM.Next,!0)}ReverseHorizontal(t){var e=t.Top.X;t.Top.X=t.Bot.X,t.Bot.X=e}Reset(){if(this.m_CurrentLM=this.m_MinimaList,null!==this.m_CurrentLM){this.m_Scanbeam=null;for(var e=this.m_MinimaList;null!==e;){this.InsertScanbeam(e.Y);var i=e.LeftBound;null!==i&&(i.Curr.X=i.Bot.X,i.Curr.Y=i.Bot.Y,i.OutIdx=t.ClipperBase.Unassigned),null!==(i=e.RightBound)&&(i.Curr.X=i.Bot.X,i.Curr.Y=i.Bot.Y,i.OutIdx=t.ClipperBase.Unassigned),e=e.Next}this.m_ActiveEdges=null}}InsertScanbeam(e){if(null===this.m_Scanbeam)this.m_Scanbeam=new t.Scanbeam,this.m_Scanbeam.Next=null,this.m_Scanbeam.Y=e;else if(e>this.m_Scanbeam.Y){var i=new t.Scanbeam;i.Y=e,i.Next=this.m_Scanbeam,this.m_Scanbeam=i}else{for(var s=this.m_Scanbeam;null!==s.Next&&e<=s.Next.Y;)s=s.Next;if(e===s.Y)return;var r=new t.Scanbeam;r.Y=e,r.Next=s.Next,s.Next=r}}PopScanbeam(t){return null===this.m_Scanbeam?(t.v=0,!1):(t.v=this.m_Scanbeam.Y,this.m_Scanbeam=this.m_Scanbeam.Next,!0)}LocalMinimaPending(){return null!==this.m_CurrentLM}CreateOutRec(){var e=new t.OutRec;return e.Idx=t.ClipperBase.Unassigned,e.IsHole=!1,e.IsOpen=!1,e.FirstLeft=null,e.Pts=null,e.BottomPt=null,e.PolyNode=null,this.m_PolyOuts.push(e),e.Idx=this.m_PolyOuts.length-1,e}DisposeOutRec(t){var e=this.m_PolyOuts[t];e.Pts=null,e=null,this.m_PolyOuts[t]=null}UpdateEdgeIntoAEL(e){null===e.NextInLML&&t.Error("UpdateEdgeIntoAEL: invalid call");var i=e.PrevInAEL,s=e.NextInAEL;return e.NextInLML.OutIdx=e.OutIdx,null!==i?i.NextInAEL=e.NextInLML:this.m_ActiveEdges=e.NextInLML,null!==s&&(s.PrevInAEL=e.NextInLML),e.NextInLML.Side=e.Side,e.NextInLML.WindDelta=e.WindDelta,e.NextInLML.WindCnt=e.WindCnt,e.NextInLML.WindCnt2=e.WindCnt2,(e=e.NextInLML).Curr.X=e.Bot.X,e.Curr.Y=e.Bot.Y,e.PrevInAEL=i,e.NextInAEL=s,t.ClipperBase.IsHorizontal(e)||this.InsertScanbeam(e.Top.Y),e}SwapPositionsInAEL(t,e){if(t.NextInAEL!==t.PrevInAEL&&e.NextInAEL!==e.PrevInAEL){if(t.NextInAEL===e){var i=e.NextInAEL;null!==i&&(i.PrevInAEL=t);var s=t.PrevInAEL;null!==s&&(s.NextInAEL=e),e.PrevInAEL=s,e.NextInAEL=t,t.PrevInAEL=e,t.NextInAEL=i}else if(e.NextInAEL===t){var r=t.NextInAEL;null!==r&&(r.PrevInAEL=e);var n=e.PrevInAEL;null!==n&&(n.NextInAEL=t),t.PrevInAEL=n,t.NextInAEL=e,e.PrevInAEL=t,e.NextInAEL=r}else{var o=t.NextInAEL,a=t.PrevInAEL;t.NextInAEL=e.NextInAEL,null!==t.NextInAEL&&(t.NextInAEL.PrevInAEL=t),t.PrevInAEL=e.PrevInAEL,null!==t.PrevInAEL&&(t.PrevInAEL.NextInAEL=t),e.NextInAEL=o,null!==e.NextInAEL&&(e.NextInAEL.PrevInAEL=e),e.PrevInAEL=a,null!==e.PrevInAEL&&(e.PrevInAEL.NextInAEL=e)}null===t.PrevInAEL?this.m_ActiveEdges=t:null===e.PrevInAEL&&(this.m_ActiveEdges=e)}}DeleteFromAEL(t){var e=t.PrevInAEL,i=t.NextInAEL;null===e&&null===i&&t!==this.m_ActiveEdges||(null!==e?e.NextInAEL=i:this.m_ActiveEdges=i,null!==i&&(i.PrevInAEL=e),t.NextInAEL=null,t.PrevInAEL=null)}}t.ClipperBase=u;t.Clipper=class extends u{m_SortedEdges=null;m_IntersectList=null;m_IntersectNodeComparer=null;m_ExecuteLocked=!1;m_ClipFillType=0;m_SubjFillType=0;m_Joins=null;m_GhostJoins=null;m_UsingPolyTree=!1;ReverseSolution=!1;StrictlySimple=!1;m_ClipType=0;m_Maxima=null;ZFillFunction;constructor(e){super(),void 0===e&&(e=0),this.m_PolyOuts=null,this.m_Scanbeam=null,this.m_ActiveEdges=null,this.m_Scanbeam=null,this.m_Maxima=null,this.m_ActiveEdges=null,this.m_SortedEdges=null,this.m_IntersectList=new Array,this.m_IntersectNodeComparer=t.Compare,this.m_ExecuteLocked=!1,this.m_UsingPolyTree=!1,this.m_PolyOuts=new Array,this.m_Joins=new Array,this.m_GhostJoins=new Array,this.ReverseSolution=!!(1&e),this.StrictlySimple=!!(2&e),this.PreserveCollinear=!!(4&e)}static ioReverseSolution=1;static ioStrictlySimple=2;static ioPreserveCollinear=4;Clear(){0!==this.m_edges.length&&(this.DisposeAllPolyPts(),super.Clear())}InsertMaxima(e){var i=new t.Maxima;if(i.X=e,null===this.m_Maxima)this.m_Maxima=i,this.m_Maxima.Next=null,this.m_Maxima.Prev=null;else if(e<this.m_Maxima.X)i.Next=this.m_Maxima,i.Prev=null,this.m_Maxima=i;else{for(var s=this.m_Maxima;null!==s.Next&&e>=s.Next.X;)s=s.Next;if(e===s.X)return;i.Next=s.Next,i.Prev=s,null!==s.Next&&(s.Next.Prev=i),s.Next=i}}Execute(...e){var i=e,s=i.length,r=i[1]instanceof t.PolyTree;if(4===s&&!r){var n=i[0],o=i[1],a=i[2],l=i[3];if(this.m_ExecuteLocked)return!1;this.m_HasOpenPaths&&t.Error("Error: PolyTree struct is needed for open path clipping."),this.m_ExecuteLocked=!0,t.Clear(o),this.m_SubjFillType=a,this.m_ClipFillType=l,this.m_ClipType=n,this.m_UsingPolyTree=!1;try{(u=this.ExecuteInternal())&&this.BuildResult(o)}finally{this.DisposeAllPolyPts(),this.m_ExecuteLocked=!1}return u}if(4===s&&r){n=i[0];var h=i[1];a=i[2],l=i[3];if(this.m_ExecuteLocked)return!1;this.m_ExecuteLocked=!0,this.m_SubjFillType=a,this.m_ClipFillType=l,this.m_ClipType=n,this.m_UsingPolyTree=!0;try{var u;(u=this.ExecuteInternal())&&this.BuildResult2(h)}finally{this.DisposeAllPolyPts(),this.m_ExecuteLocked=!1}return u}if(2===s&&!r){n=i[0],o=i[1];return this.Execute(n,o,0,0)}if(2===s&&r){n=i[0],h=i[1];return this.Execute(n,h,0,0)}}FixHoleLinkage(t){if(null!==t.FirstLeft&&(t.IsHole===t.FirstLeft.IsHole||null===t.FirstLeft.Pts)){for(var e=t.FirstLeft;null!==e&&(e.IsHole===t.IsHole||null===e.Pts);)e=e.FirstLeft;t.FirstLeft=e}}ExecuteInternal(){try{this.Reset(),this.m_SortedEdges=null,this.m_Maxima=null;var t,e,i,s={},r={};if(!this.PopScanbeam(s))return!1;for(this.InsertLocalMinimaIntoAEL(s.v);this.PopScanbeam(r)||this.LocalMinimaPending();){if(this.ProcessHorizontals(),this.m_GhostJoins.length=0,!this.ProcessIntersections(r.v))return!1;this.ProcessEdgesAtTopOfScanbeam(r.v),s.v=r.v,this.InsertLocalMinimaIntoAEL(s.v)}for(e=0,i=this.m_PolyOuts.length;e<i;e++)null===(t=this.m_PolyOuts[e]).Pts||t.IsOpen||(t.IsHole^this.ReverseSolution)==this.Area$1(t)>0&&this.ReversePolyPtLinks(t.Pts);for(this.JoinCommonEdges(),e=0,i=this.m_PolyOuts.length;e<i;e++)null!==(t=this.m_PolyOuts[e]).Pts&&(t.IsOpen?this.FixupOutPolyline(t):this.FixupOutPolygon(t));return this.StrictlySimple&&this.DoSimplePolygons(),!0}finally{this.m_Joins.length=0,this.m_GhostJoins.length=0}}DisposeAllPolyPts(){for(var e=0,i=this.m_PolyOuts.length;e<i;++e)this.DisposeOutRec(e);t.Clear(this.m_PolyOuts)}AddJoin(e,i,s){var r=new t.Join;r.OutPt1=e,r.OutPt2=i,r.OffPt.X=s.X,r.OffPt.Y=s.Y,this.m_Joins.push(r)}AddGhostJoin(e,i){var s=new t.Join;s.OutPt1=e,s.OffPt.X=i.X,s.OffPt.Y=i.Y,this.m_GhostJoins.push(s)}InsertLocalMinimaIntoAEL(e){for(var i,s,r={};this.PopLocalMinima(e,r);){i=r.v.LeftBound,s=r.v.RightBound;var n=null;if(null===i?(this.InsertEdgeIntoAEL(s,null),this.SetWindingCount(s),this.IsContributing(s)&&(n=this.AddOutPt(s,s.Bot))):null===s?(this.InsertEdgeIntoAEL(i,null),this.SetWindingCount(i),this.IsContributing(i)&&(n=this.AddOutPt(i,i.Bot)),this.InsertScanbeam(i.Top.Y)):(this.InsertEdgeIntoAEL(i,null),this.InsertEdgeIntoAEL(s,i),this.SetWindingCount(i),s.WindCnt=i.WindCnt,s.WindCnt2=i.WindCnt2,this.IsContributing(i)&&(n=this.AddLocalMinPoly(i,s,i.Bot)),this.InsertScanbeam(i.Top.Y)),null!==s&&(t.ClipperBase.IsHorizontal(s)?(null!==s.NextInLML&&this.InsertScanbeam(s.NextInLML.Top.Y),this.AddEdgeToSEL(s)):this.InsertScanbeam(s.Top.Y)),null!==i&&null!==s){if(null!==n&&t.ClipperBase.IsHorizontal(s)&&this.m_GhostJoins.length>0&&0!==s.WindDelta)for(var o=0,a=this.m_GhostJoins.length;o<a;o++){var l=this.m_GhostJoins[o];this.HorzSegmentsOverlap(l.OutPt1.Pt.X,l.OffPt.X,s.Bot.X,s.Top.X)&&this.AddJoin(l.OutPt1,n,l.OffPt)}if(i.OutIdx>=0&&null!==i.PrevInAEL&&i.PrevInAEL.Curr.X===i.Bot.X&&i.PrevInAEL.OutIdx>=0&&t.ClipperBase.SlopesEqual5(i.PrevInAEL.Curr,i.PrevInAEL.Top,i.Curr,i.Top)&&0!==i.WindDelta&&0!==i.PrevInAEL.WindDelta){var h=this.AddOutPt(i.PrevInAEL,i.Bot);this.AddJoin(n,h,i.Top)}if(i.NextInAEL!==s){if(s.OutIdx>=0&&s.PrevInAEL.OutIdx>=0&&t.ClipperBase.SlopesEqual5(s.PrevInAEL.Curr,s.PrevInAEL.Top,s.Curr,s.Top)&&0!==s.WindDelta&&0!==s.PrevInAEL.WindDelta){h=this.AddOutPt(s.PrevInAEL,s.Bot);this.AddJoin(n,h,s.Top)}var u=i.NextInAEL;if(null!==u)for(;u!==s;)this.IntersectEdges(s,u,i.Curr),u=u.NextInAEL}}}}InsertEdgeIntoAEL(t,e){if(null===this.m_ActiveEdges)t.PrevInAEL=null,t.NextInAEL=null,this.m_ActiveEdges=t;else if(null===e&&this.E2InsertsBeforeE1(this.m_ActiveEdges,t))t.PrevInAEL=null,t.NextInAEL=this.m_ActiveEdges,this.m_ActiveEdges.PrevInAEL=t,this.m_ActiveEdges=t;else{for(null===e&&(e=this.m_ActiveEdges);null!==e.NextInAEL&&!this.E2InsertsBeforeE1(e.NextInAEL,t);)e=e.NextInAEL;t.NextInAEL=e.NextInAEL,null!==e.NextInAEL&&(e.NextInAEL.PrevInAEL=t),t.PrevInAEL=e,e.NextInAEL=t}}E2InsertsBeforeE1(e,i){return i.Curr.X===e.Curr.X?i.Top.Y>e.Top.Y?i.Top.X<t.Clipper.TopX(e,i.Top.Y):e.Top.X>t.Clipper.TopX(i,e.Top.Y):i.Curr.X<e.Curr.X}IsEvenOddFillType(t){return 0===t.PolyTyp?0===this.m_SubjFillType:0===this.m_ClipFillType}IsEvenOddAltFillType(t){return 0===t.PolyTyp?0===this.m_ClipFillType:0===this.m_SubjFillType}IsContributing(t){var e,i;switch(0===t.PolyTyp?(e=this.m_SubjFillType,i=this.m_ClipFillType):(e=this.m_ClipFillType,i=this.m_SubjFillType),e){case 0:if(0===t.WindDelta&&1!==t.WindCnt)return!1;break;case 1:if(1!==Math.abs(t.WindCnt))return!1;break;case 2:if(1!==t.WindCnt)return!1;break;default:if(-1!==t.WindCnt)return!1}switch(this.m_ClipType){case 0:switch(i){case 0:case 1:return 0!==t.WindCnt2;case 2:return t.WindCnt2>0;default:return t.WindCnt2<0}case 1:switch(i){case 0:case 1:return 0===t.WindCnt2;case 2:return t.WindCnt2<=0;default:return t.WindCnt2>=0}case 2:if(0===t.PolyTyp)switch(i){case 0:case 1:return 0===t.WindCnt2;case 2:return t.WindCnt2<=0;default:return t.WindCnt2>=0}else switch(i){case 0:case 1:return 0!==t.WindCnt2;case 2:return t.WindCnt2>0;default:return t.WindCnt2<0}case 3:if(0!==t.WindDelta)return!0;switch(i){case 0:case 1:return 0===t.WindCnt2;case 2:return t.WindCnt2<=0;default:return t.WindCnt2>=0}}return!0}SetWindingCount(t){for(var e=t.PrevInAEL;null!==e&&(e.PolyTyp!==t.PolyTyp||0===e.WindDelta);)e=e.PrevInAEL;if(null===e){var i=0===t.PolyTyp?this.m_SubjFillType:this.m_ClipFillType;0===t.WindDelta?t.WindCnt=3===i?-1:1:t.WindCnt=t.WindDelta,t.WindCnt2=0,e=this.m_ActiveEdges}else if(0===t.WindDelta&&1!==this.m_ClipType)t.WindCnt=1,t.WindCnt2=e.WindCnt2,e=e.NextInAEL;else if(this.IsEvenOddFillType(t)){if(0===t.WindDelta){for(var s=!0,r=e.PrevInAEL;null!==r;)r.PolyTyp===e.PolyTyp&&0!==r.WindDelta&&(s=!s),r=r.PrevInAEL;t.WindCnt=s?0:1}else t.WindCnt=t.WindDelta;t.WindCnt2=e.WindCnt2,e=e.NextInAEL}else e.WindCnt*e.WindDelta<0?Math.abs(e.WindCnt)>1?e.WindDelta*t.WindDelta<0?t.WindCnt=e.WindCnt:t.WindCnt=e.WindCnt+t.WindDelta:t.WindCnt=0===t.WindDelta?1:t.WindDelta:0===t.WindDelta?t.WindCnt=e.WindCnt<0?e.WindCnt-1:e.WindCnt+1:e.WindDelta*t.WindDelta<0?t.WindCnt=e.WindCnt:t.WindCnt=e.WindCnt+t.WindDelta,t.WindCnt2=e.WindCnt2,e=e.NextInAEL;if(this.IsEvenOddAltFillType(t))for(;e!==t;)0!==e.WindDelta&&(t.WindCnt2=0===t.WindCnt2?1:0),e=e.NextInAEL;else for(;e!==t;)t.WindCnt2+=e.WindDelta,e=e.NextInAEL}AddEdgeToSEL(t){null===this.m_SortedEdges?(this.m_SortedEdges=t,t.PrevInSEL=null,t.NextInSEL=null):(t.NextInSEL=this.m_SortedEdges,t.PrevInSEL=null,this.m_SortedEdges.PrevInSEL=t,this.m_SortedEdges=t)}PopEdgeFromSEL(t){if(t.v=this.m_SortedEdges,null===t.v)return!1;var e=t.v;return this.m_SortedEdges=t.v.NextInSEL,null!==this.m_SortedEdges&&(this.m_SortedEdges.PrevInSEL=null),e.NextInSEL=null,e.PrevInSEL=null,!0}CopyAELToSEL(){var t=this.m_ActiveEdges;for(this.m_SortedEdges=t;null!==t;)t.PrevInSEL=t.PrevInAEL,t.NextInSEL=t.NextInAEL,t=t.NextInAEL}SwapPositionsInSEL(t,e){if(!(null===t.NextInSEL&&null===t.PrevInSEL||null===e.NextInSEL&&null===e.PrevInSEL)){if(t.NextInSEL===e)null!==(i=e.NextInSEL)&&(i.PrevInSEL=t),null!==(s=t.PrevInSEL)&&(s.NextInSEL=e),e.PrevInSEL=s,e.NextInSEL=t,t.PrevInSEL=e,t.NextInSEL=i;else if(e.NextInSEL===t){null!==(i=t.NextInSEL)&&(i.PrevInSEL=e),null!==(s=e.PrevInSEL)&&(s.NextInSEL=t),t.PrevInSEL=s,t.NextInSEL=e,e.PrevInSEL=t,e.NextInSEL=i}else{var i=t.NextInSEL,s=t.PrevInSEL;t.NextInSEL=e.NextInSEL,null!==t.NextInSEL&&(t.NextInSEL.PrevInSEL=t),t.PrevInSEL=e.PrevInSEL,null!==t.PrevInSEL&&(t.PrevInSEL.NextInSEL=t),e.NextInSEL=i,null!==e.NextInSEL&&(e.NextInSEL.PrevInSEL=e),e.PrevInSEL=s,null!==e.PrevInSEL&&(e.PrevInSEL.NextInSEL=e)}null===t.PrevInSEL?this.m_SortedEdges=t:null===e.PrevInSEL&&(this.m_SortedEdges=e)}}AddLocalMaxPoly(t,e,i){this.AddOutPt(t,i),0===e.WindDelta&&this.AddOutPt(e,i),t.OutIdx===e.OutIdx?(t.OutIdx=-1,e.OutIdx=-1):t.OutIdx<e.OutIdx?this.AppendPolygon(t,e):this.AppendPolygon(e,t)}AddLocalMinPoly(e,i,s){var r,n,o;if(t.ClipperBase.IsHorizontal(i)||e.Dx>i.Dx?(r=this.AddOutPt(e,s),i.OutIdx=e.OutIdx,e.Side=0,i.Side=1,o=(n=e).PrevInAEL===i?i.PrevInAEL:n.PrevInAEL):(r=this.AddOutPt(i,s),e.OutIdx=i.OutIdx,e.Side=1,i.Side=0,o=(n=i).PrevInAEL===e?e.PrevInAEL:n.PrevInAEL),null!==o&&o.OutIdx>=0&&o.Top.Y<s.Y&&n.Top.Y<s.Y){var a=t.Clipper.TopX(o,s.Y),l=t.Clipper.TopX(n,s.Y);if(a===l&&0!==n.WindDelta&&0!==o.WindDelta&&t.ClipperBase.SlopesEqual5(new t.FPoint(a,s.Y),o.Top,new t.FPoint(l,s.Y),n.Top)){var h=this.AddOutPt(o,s);this.AddJoin(r,h,n.Top)}}return r}AddOutPt(e,i){if(e.OutIdx<0){let r=this.CreateOutRec();r.IsOpen=0===e.WindDelta;var s=new t.OutPt;return r.Pts=s,s.Idx=r.Idx,s.Pt.X=i.X,s.Pt.Y=i.Y,s.Next=s,s.Prev=s,r.IsOpen||this.SetHoleState(e,r),e.OutIdx=r.Idx,s}{let o=this.m_PolyOuts[e.OutIdx];var r=o.Pts,n=0===e.Side;return n&&t.FPoint.op_Equality(i,r.Pt)?r:!n&&t.FPoint.op_Equality(i,r.Prev.Pt)?r.Prev:((s=new t.OutPt).Idx=o.Idx,s.Pt.X=i.X,s.Pt.Y=i.Y,s.Next=r,s.Prev=r.Prev,s.Prev.Next=s,r.Prev=s,n&&(o.Pts=s),s)}}GetLastOutPt(t){var e=this.m_PolyOuts[t.OutIdx];return 0===t.Side?e.Pts:e.Pts.Prev}SwapPoints(e,i){var s=new t.FPoint(e.Value);e.Value.X=i.Value.X,e.Value.Y=i.Value.Y,i.Value.X=s.X,i.Value.Y=s.Y}HorzSegmentsOverlap(t,e,i,s){var r;return t>e&&(r=t,t=e,e=r),i>s&&(r=i,i=s,s=r),t<s&&i<e}SetHoleState(t,e){for(var i=t.PrevInAEL,s=null;null!==i;)i.OutIdx>=0&&0!==i.WindDelta&&(null===s?s=i:s.OutIdx===i.OutIdx&&(s=null)),i=i.PrevInAEL;null===s?(e.FirstLeft=null,e.IsHole=!1):(e.FirstLeft=this.m_PolyOuts[s.OutIdx],e.IsHole=!e.FirstLeft.IsHole)}GetDx(e,i){return e.Y===i.Y?t.ClipperBase.horizontal:(i.X-e.X)/(i.Y-e.Y)}FirstIsBottomPt(e,i){for(var s=e.Prev;t.FPoint.op_Equality(s.Pt,e.Pt)&&s!==e;)s=s.Prev;var r=Math.abs(this.GetDx(e.Pt,s.Pt));for(s=e.Next;t.FPoint.op_Equality(s.Pt,e.Pt)&&s!==e;)s=s.Next;var n=Math.abs(this.GetDx(e.Pt,s.Pt));for(s=i.Prev;t.FPoint.op_Equality(s.Pt,i.Pt)&&s!==i;)s=s.Prev;var o=Math.abs(this.GetDx(i.Pt,s.Pt));for(s=i.Next;t.FPoint.op_Equality(s.Pt,i.Pt)&&s!==i;)s=s.Next;var a=Math.abs(this.GetDx(i.Pt,s.Pt));return Math.max(r,n)===Math.max(o,a)&&Math.min(r,n)===Math.min(o,a)?this.Area(e)>0:r>=o&&r>=a||n>=o&&n>=a}GetBottomPt(e){for(var i=null,s=e.Next;s!==e;)s.Pt.Y>e.Pt.Y?(e=s,i=null):s.Pt.Y===e.Pt.Y&&s.Pt.X<=e.Pt.X&&(s.Pt.X<e.Pt.X?(i=null,e=s):s.Next!==e&&s.Prev!==e&&(i=s)),s=s.Next;if(null!==i)for(;i!==s;)for(this.FirstIsBottomPt(s,i)||(e=i),i=i.Next;t.FPoint.op_Inequality(i.Pt,e.Pt);)i=i.Next;return e}GetLowermostRec(t,e){null===t.BottomPt&&(t.BottomPt=this.GetBottomPt(t.Pts)),null===e.BottomPt&&(e.BottomPt=this.GetBottomPt(e.Pts));var i=t.BottomPt,s=e.BottomPt;return i.Pt.Y>s.Pt.Y?t:i.Pt.Y<s.Pt.Y?e:i.Pt.X<s.Pt.X?t:i.Pt.X>s.Pt.X||i.Next===i?e:s.Next===s||this.FirstIsBottomPt(i,s)?t:e}OutRec1RightOfOutRec2(t,e){do{if((t=t.FirstLeft)===e)return!0}while(null!==t);return!1}GetOutRec(t){for(var e=this.m_PolyOuts[t];e!==this.m_PolyOuts[e.Idx];)e=this.m_PolyOuts[e.Idx];return e}AppendPolygon(t,e){var i,s=this.m_PolyOuts[t.OutIdx],r=this.m_PolyOuts[e.OutIdx];i=this.OutRec1RightOfOutRec2(s,r)?r:this.OutRec1RightOfOutRec2(r,s)?s:this.GetLowermostRec(s,r);var n=s.Pts,o=n.Prev,a=r.Pts,l=a.Prev;0===t.Side?0===e.Side?(this.ReversePolyPtLinks(a),a.Next=n,n.Prev=a,o.Next=l,l.Prev=o,s.Pts=l):(l.Next=n,n.Prev=l,a.Prev=o,o.Next=a,s.Pts=a):1===e.Side?(this.ReversePolyPtLinks(a),o.Next=l,l.Prev=o,a.Next=n,n.Prev=a):(o.Next=a,a.Prev=o,n.Prev=l,l.Next=n),s.BottomPt=null,i===r&&(r.FirstLeft!==s&&(s.FirstLeft=r.FirstLeft),s.IsHole=r.IsHole),r.Pts=null,r.BottomPt=null,r.FirstLeft=s;var h=t.OutIdx,u=e.OutIdx;t.OutIdx=-1,e.OutIdx=-1;for(var c=this.m_ActiveEdges;null!==c;){if(c.OutIdx===u){c.OutIdx=h,c.Side=t.Side;break}c=c.NextInAEL}r.Idx=s.Idx}ReversePolyPtLinks(t){if(null!==t){var e,i;e=t;do{i=e.Next,e.Next=e.Prev,e.Prev=i,e=i}while(e!==t)}}static SwapSides(t,e){var i=t.Side;t.Side=e.Side,e.Side=i}static SwapPolyIndexes(t,e){var i=t.OutIdx;t.OutIdx=e.OutIdx,e.OutIdx=i}IntersectEdges(e,i,s){var r=e.OutIdx>=0,n=i.OutIdx>=0;if(!t.use_lines||0!==e.WindDelta&&0!==i.WindDelta){if(e.PolyTyp===i.PolyTyp)if(this.IsEvenOddFillType(e)){var o=e.WindCnt;e.WindCnt=i.WindCnt,i.WindCnt=o}else e.WindCnt+i.WindDelta===0?e.WindCnt=-e.WindCnt:e.WindCnt+=i.WindDelta,i.WindCnt-e.WindDelta===0?i.WindCnt=-i.WindCnt:i.WindCnt-=e.WindDelta;else this.IsEvenOddFillType(i)?e.WindCnt2=0===e.WindCnt2?1:0:e.WindCnt2+=i.WindDelta,this.IsEvenOddFillType(e)?i.WindCnt2=0===i.WindCnt2?1:0:i.WindCnt2-=e.WindDelta;var a,l,h,u,c,d;switch(0===e.PolyTyp?(a=this.m_SubjFillType,h=this.m_ClipFillType):(a=this.m_ClipFillType,h=this.m_SubjFillType),0===i.PolyTyp?(l=this.m_SubjFillType,u=this.m_ClipFillType):(l=this.m_ClipFillType,u=this.m_SubjFillType),a){case 2:c=e.WindCnt;break;case 3:c=-e.WindCnt;break;default:c=Math.abs(e.WindCnt)}switch(l){case 2:d=i.WindCnt;break;case 3:d=-i.WindCnt;break;default:d=Math.abs(i.WindCnt)}if(r&&n)0!==c&&1!==c||0!==d&&1!==d||e.PolyTyp!==i.PolyTyp&&3!==this.m_ClipType?this.AddLocalMaxPoly(e,i,s):(this.AddOutPt(e,s),this.AddOutPt(i,s),t.Clipper.SwapSides(e,i),t.Clipper.SwapPolyIndexes(e,i));else if(r)0!==d&&1!==d||(this.AddOutPt(e,s),t.Clipper.SwapSides(e,i),t.Clipper.SwapPolyIndexes(e,i));else if(n)0!==c&&1!==c||(this.AddOutPt(i,s),t.Clipper.SwapSides(e,i),t.Clipper.SwapPolyIndexes(e,i));else if(!(0!==c&&1!==c||0!==d&&1!==d)){var p,f;switch(h){case 2:p=e.WindCnt2;break;case 3:p=-e.WindCnt2;break;default:p=Math.abs(e.WindCnt2)}switch(u){case 2:f=i.WindCnt2;break;case 3:f=-i.WindCnt2;break;default:f=Math.abs(i.WindCnt2)}if(e.PolyTyp!==i.PolyTyp)this.AddLocalMinPoly(e,i,s);else if(1===c&&1===d)switch(this.m_ClipType){case 0:p>0&&f>0&&this.AddLocalMinPoly(e,i,s);break;case 1:p<=0&&f<=0&&this.AddLocalMinPoly(e,i,s);break;case 2:(1===e.PolyTyp&&p>0&&f>0||0===e.PolyTyp&&p<=0&&f<=0)&&this.AddLocalMinPoly(e,i,s);break;case 3:this.AddLocalMinPoly(e,i,s)}else t.Clipper.SwapSides(e,i)}}else{if(0===e.WindDelta&&0===i.WindDelta)return;e.PolyTyp===i.PolyTyp&&e.WindDelta!==i.WindDelta&&1===this.m_ClipType?0===e.WindDelta?n&&(this.AddOutPt(e,s),r&&(e.OutIdx=-1)):r&&(this.AddOutPt(i,s),n&&(i.OutIdx=-1)):e.PolyTyp!==i.PolyTyp&&(0!==e.WindDelta||1!==Math.abs(i.WindCnt)||1===this.m_ClipType&&0!==i.WindCnt2?0!==i.WindDelta||1!==Math.abs(e.WindCnt)||1===this.m_ClipType&&0!==e.WindCnt2||(this.AddOutPt(i,s),n&&(i.OutIdx=-1)):(this.AddOutPt(e,s),r&&(e.OutIdx=-1)))}}DeleteFromSEL(t){var e=t.PrevInSEL,i=t.NextInSEL;null===e&&null===i&&t!==this.m_SortedEdges||(null!==e?e.NextInSEL=i:this.m_SortedEdges=i,null!==i&&(i.PrevInSEL=e),t.NextInSEL=null,t.PrevInSEL=null)}ProcessHorizontals(){for(var t={};this.PopEdgeFromSEL(t);)this.ProcessHorizontal(t.v)}GetHorzDirection(t,e){t.Bot.X<t.Top.X?(e.Left=t.Bot.X,e.Right=t.Top.X,e.Dir=1):(e.Left=t.Top.X,e.Right=t.Bot.X,e.Dir=0)}ProcessHorizontal(e){var i={Dir:null,Left:null,Right:null};this.GetHorzDirection(e,i);for(var s=i.Dir,r=i.Left,n=i.Right,o=0===e.WindDelta,a=e,l=null;null!==a.NextInLML&&t.ClipperBase.IsHorizontal(a.NextInLML);)a=a.NextInLML;null===a.NextInLML&&(l=this.GetMaximaPair(a));var h=this.m_Maxima;if(null!==h)if(1===s){for(;null!==h&&h.X<=e.Bot.X;)h=h.Next;null!==h&&h.X>=a.Top.X&&(h=null)}else{for(;null!==h.Next&&h.Next.X<e.Bot.X;)h=h.Next;h.X<=a.Top.X&&(h=null)}for(var u=null;;){for(var c=e===a,d=this.GetNextInAEL(e,s);null!==d;){if(null!==h)if(1===s)for(;null!==h&&h.X<d.Curr.X;)e.OutIdx>=0&&!o&&this.AddOutPt(e,new t.FPoint(h.X,e.Bot.Y)),h=h.Next;else for(;null!==h&&h.X>d.Curr.X;)e.OutIdx>=0&&!o&&this.AddOutPt(e,new t.FPoint(h.X,e.Bot.Y)),h=h.Prev;if(1===s&&d.Curr.X>n||0===s&&d.Curr.X<r)break;if(d.Curr.X===e.Top.X&&null!==e.NextInLML&&d.Dx<e.NextInLML.Dx)break;if(e.OutIdx>=0&&!o){u=this.AddOutPt(e,d.Curr);for(var p=this.m_SortedEdges;null!==p;){if(p.OutIdx>=0&&this.HorzSegmentsOverlap(e.Bot.X,e.Top.X,p.Bot.X,p.Top.X)){var f=this.GetLastOutPt(p);this.AddJoin(f,u,p.Top)}p=p.NextInSEL}this.AddGhostJoin(u,e.Bot)}if(d===l&&c)return e.OutIdx>=0&&this.AddLocalMaxPoly(e,l,e.Top),this.DeleteFromAEL(e),void this.DeleteFromAEL(l);if(1===s){var m=new t.FPoint(d.Curr.X,e.Curr.Y);this.IntersectEdges(e,d,m)}else{m=new t.FPoint(d.Curr.X,e.Curr.Y);this.IntersectEdges(d,e,m)}var g=this.GetNextInAEL(d,s);this.SwapPositionsInAEL(e,d),d=g}if(null===e.NextInLML||!t.ClipperBase.IsHorizontal(e.NextInLML))break;(e=this.UpdateEdgeIntoAEL(e)).OutIdx>=0&&this.AddOutPt(e,e.Bot),i={Dir:s,Left:r,Right:n},this.GetHorzDirection(e,i),s=i.Dir,r=i.Left,n=i.Right}if(e.OutIdx>=0&&null===u){u=this.GetLastOutPt(e);for(p=this.m_SortedEdges;null!==p;){if(p.OutIdx>=0&&this.HorzSegmentsOverlap(e.Bot.X,e.Top.X,p.Bot.X,p.Top.X)){f=this.GetLastOutPt(p);this.AddJoin(f,u,p.Top)}p=p.NextInSEL}this.AddGhostJoin(u,e.Top)}if(null!==e.NextInLML)if(e.OutIdx>=0){if(u=this.AddOutPt(e,e.Top),0===(e=this.UpdateEdgeIntoAEL(e)).WindDelta)return;var y=e.PrevInAEL;g=e.NextInAEL;if(null!==y&&y.Curr.X===e.Bot.X&&y.Curr.Y===e.Bot.Y&&0===y.WindDelta&&y.OutIdx>=0&&y.Curr.Y>y.Top.Y&&t.ClipperBase.SlopesEqual3(e,y)){let t=this.AddOutPt(y,e.Bot);this.AddJoin(u,t,e.Top)}else if(null!==g&&g.Curr.X===e.Bot.X&&g.Curr.Y===e.Bot.Y&&0!==g.WindDelta&&g.OutIdx>=0&&g.Curr.Y>g.Top.Y&&t.ClipperBase.SlopesEqual3(e,g)){let t=this.AddOutPt(g,e.Bot);this.AddJoin(u,t,e.Top)}}else e=this.UpdateEdgeIntoAEL(e);else e.OutIdx>=0&&this.AddOutPt(e,e.Top),this.DeleteFromAEL(e)}GetNextInAEL(t,e){return 1===e?t.NextInAEL:t.PrevInAEL}IsMinima(t){return null!==t&&t.Prev.NextInLML!==t&&t.Next.NextInLML!==t}IsMaxima(t,e){return null!==t&&t.Top.Y===e&&null===t.NextInLML}IsIntermediate(t,e){return t.Top.Y===e&&null!==t.NextInLML}GetMaximaPair(e){return t.FPoint.op_Equality(e.Next.Top,e.Top)&&null===e.Next.NextInLML?e.Next:t.FPoint.op_Equality(e.Prev.Top,e.Top)&&null===e.Prev.NextInLML?e.Prev:null}GetMaximaPairEx(e){var i=this.GetMaximaPair(e);return null===i||i.OutIdx===t.ClipperBase.Skip||i.NextInAEL===i.PrevInAEL&&!t.ClipperBase.IsHorizontal(i)?null:i}ProcessIntersections(e){if(null===this.m_ActiveEdges)return!0;try{if(this.BuildIntersectList(e),0===this.m_IntersectList.length)return!0;if(1!==this.m_IntersectList.length&&!this.FixupIntersectionOrder())return!1;this.ProcessIntersectList()}catch(i){this.m_SortedEdges=null,this.m_IntersectList.length=0,t.Error("ProcessIntersections error")}return this.m_SortedEdges=null,!0}BuildIntersectList(e){if(null!==this.m_ActiveEdges){var i=this.m_ActiveEdges;for(this.m_SortedEdges=i;null!==i;)i.PrevInSEL=i.PrevInAEL,i.NextInSEL=i.NextInAEL,i.Curr.X=t.Clipper.TopX(i,e),i=i.NextInAEL;for(var s=!0;s&&null!==this.m_SortedEdges;){for(s=!1,i=this.m_SortedEdges;null!==i.NextInSEL;){var r=i.NextInSEL,n=new t.FPoint;if(i.Curr.X>r.Curr.X){this.IntersectPoint(i,r,n),n.Y<e&&(n=new t.FPoint(t.Clipper.TopX(i,e),e));var o=new t.IntersectNode;o.Edge1=i,o.Edge2=r,o.Pt.X=n.X,o.Pt.Y=n.Y,this.m_IntersectList.push(o),this.SwapPositionsInSEL(i,r),s=!0}else i=r}if(null===i.PrevInSEL)break;i.PrevInSEL.NextInSEL=null}this.m_SortedEdges=null}}EdgesAdjacent(t){return t.Edge1.NextInSEL===t.Edge2||t.Edge1.PrevInSEL===t.Edge2}static IntersectNodeSort(t,e){return e.Pt.Y-t.Pt.Y}FixupIntersectionOrder(){this.m_IntersectList.sort(this.m_IntersectNodeComparer),this.CopyAELToSEL();for(var t=this.m_IntersectList.length,e=0;e<t;e++){if(!this.EdgesAdjacent(this.m_IntersectList[e])){for(var i=e+1;i<t&&!this.EdgesAdjacent(this.m_IntersectList[i]);)i++;if(i===t)return!1;var s=this.m_IntersectList[e];this.m_IntersectList[e]=this.m_IntersectList[i],this.m_IntersectList[i]=s}this.SwapPositionsInSEL(this.m_IntersectList[e].Edge1,this.m_IntersectList[e].Edge2)}return!0}ProcessIntersectList(){for(var t=0,e=this.m_IntersectList.length;t<e;t++){var i=this.m_IntersectList[t];this.IntersectEdges(i.Edge1,i.Edge2,i.Pt),this.SwapPositionsInAEL(i.Edge1,i.Edge2)}this.m_IntersectList.length=0}static TopX(t,e){return e===t.Top.Y?t.Top.X:t.Bot.X+t.Dx*(e-t.Bot.Y)}IntersectPoint(e,i,s){var r,n;if(s.X=0,s.Y=0,e.Dx===i.Dx)return s.Y=e.Curr.Y,void(s.X=t.Clipper.TopX(e,s.Y));if(0===e.Delta.X)s.X=e.Bot.X,t.ClipperBase.IsHorizontal(i)?s.Y=i.Bot.Y:(n=i.Bot.Y-i.Bot.X/i.Dx,s.Y=s.X/i.Dx+n);else if(0===i.Delta.X)s.X=i.Bot.X,t.ClipperBase.IsHorizontal(e)?s.Y=e.Bot.Y:(r=e.Bot.Y-e.Bot.X/e.Dx,s.Y=s.X/e.Dx+r);else{r=e.Bot.X-e.Bot.Y*e.Dx;var o=((n=i.Bot.X-i.Bot.Y*i.Dx)-r)/(e.Dx-i.Dx);s.Y=o,Math.abs(e.Dx)<Math.abs(i.Dx)?s.X=e.Dx*o+r:s.X=i.Dx*o+n}if(s.Y<e.Top.Y||s.Y<i.Top.Y){if(e.Top.Y>i.Top.Y)return s.Y=e.Top.Y,s.X=t.Clipper.TopX(i,e.Top.Y),s.X<e.Top.X;s.Y=i.Top.Y,Math.abs(e.Dx)<Math.abs(i.Dx)?s.X=t.Clipper.TopX(e,s.Y):s.X=t.Clipper.TopX(i,s.Y)}s.Y>e.Curr.Y&&(s.Y=e.Curr.Y,Math.abs(e.Dx)>Math.abs(i.Dx)?s.X=t.Clipper.TopX(i,s.Y):s.X=t.Clipper.TopX(e,s.Y))}ProcessEdgesAtTopOfScanbeam(e){for(var i=this.m_ActiveEdges;null!==i;){var s=this.IsMaxima(i,e);if(s){var r=this.GetMaximaPairEx(i);s=null===r||!t.ClipperBase.IsHorizontal(r)}if(s){this.StrictlySimple&&this.InsertMaxima(i.Top.X);var n=i.PrevInAEL;this.DoMaxima(i),i=null===n?this.m_ActiveEdges:n.NextInAEL}else{if(this.IsIntermediate(i,e)&&t.ClipperBase.IsHorizontal(i.NextInLML)?((i=this.UpdateEdgeIntoAEL(i)).OutIdx>=0&&this.AddOutPt(i,i.Bot),this.AddEdgeToSEL(i)):(i.Curr.X=t.Clipper.TopX(i,e),i.Curr.Y=e),this.StrictlySimple){n=i.PrevInAEL;if(i.OutIdx>=0&&0!==i.WindDelta&&null!==n&&n.OutIdx>=0&&n.Curr.X===i.Curr.X&&0!==n.WindDelta){var o=new t.FPoint(i.Curr),a=this.AddOutPt(n,o),l=this.AddOutPt(i,o);this.AddJoin(a,l,o)}}i=i.NextInAEL}}for(this.ProcessHorizontals(),this.m_Maxima=null,i=this.m_ActiveEdges;null!==i;){if(this.IsIntermediate(i,e)){a=null;i.OutIdx>=0&&(a=this.AddOutPt(i,i.Top));n=(i=this.UpdateEdgeIntoAEL(i)).PrevInAEL;var h=i.NextInAEL;if(null!==n&&n.Curr.X===i.Bot.X&&n.Curr.Y===i.Bot.Y&&null!==a&&n.OutIdx>=0&&n.Curr.Y===n.Top.Y&&t.ClipperBase.SlopesEqual5(i.Curr,i.Top,n.Curr,n.Top)&&0!==i.WindDelta&&0!==n.WindDelta){l=this.AddOutPt(n,i.Bot);this.AddJoin(a,l,i.Top)}else if(null!==h&&h.Curr.X===i.Bot.X&&h.Curr.Y===i.Bot.Y&&null!==a&&h.OutIdx>=0&&h.Curr.Y===h.Top.Y&&t.ClipperBase.SlopesEqual5(i.Curr,i.Top,h.Curr,h.Top)&&0!==i.WindDelta&&0!==h.WindDelta){l=this.AddOutPt(h,i.Bot);this.AddJoin(a,l,i.Top)}}i=i.NextInAEL}}DoMaxima(e){var i=this.GetMaximaPairEx(e);if(null===i)return e.OutIdx>=0&&this.AddOutPt(e,e.Top),void this.DeleteFromAEL(e);for(var s=e.NextInAEL;null!==s&&s!==i;)this.IntersectEdges(e,s,e.Top),this.SwapPositionsInAEL(e,s),s=e.NextInAEL;-1===e.OutIdx&&-1===i.OutIdx?(this.DeleteFromAEL(e),this.DeleteFromAEL(i)):e.OutIdx>=0&&i.OutIdx>=0?(e.OutIdx>=0&&this.AddLocalMaxPoly(e,i,e.Top),this.DeleteFromAEL(e),this.DeleteFromAEL(i)):t.use_lines&&0===e.WindDelta?(e.OutIdx>=0&&(this.AddOutPt(e,e.Top),e.OutIdx=t.ClipperBase.Unassigned),this.DeleteFromAEL(e),i.OutIdx>=0&&(this.AddOutPt(i,e.Top),i.OutIdx=t.ClipperBase.Unassigned),this.DeleteFromAEL(i)):t.Error("DoMaxima error")}static ReversePaths(t){for(var e=0,i=t.length;e<i;e++)t[e].reverse()}static Orientation(e){return t.Clipper.Area(e)>=0}PointCount(t){if(null===t)return 0;var e=0,i=t;do{e++,i=i.Next}while(i!==t);return e}BuildResult(e){t.Clear(e);for(var i=0,s=this.m_PolyOuts.length;i<s;i++){var r=this.m_PolyOuts[i];if(null!==r.Pts){var n=r.Pts.Prev,o=this.PointCount(n);if(!(o<2)){for(var a=new Array(o),l=0;l<o;l++)a[l]=n.Pt,n=n.Prev;e.push(a)}}}}BuildResult2(e){e.Clear();for(var i=0,s=this.m_PolyOuts.length;i<s;i++){var r=this.m_PolyOuts[i],n=this.PointCount(r.Pts);if(!(r.IsOpen&&n<2||!r.IsOpen&&n<3)){this.FixHoleLinkage(r);var o=new t.PolyNode;e.m_AllPolys.push(o),r.PolyNode=o,o.m_polygon.length=n;for(var a=r.Pts.Prev,l=0;l<n;l++)o.m_polygon[l]=a.Pt,a=a.Prev}}for(i=0,s=this.m_PolyOuts.length;i<s;i++){null!==(r=this.m_PolyOuts[i]).PolyNode&&(r.IsOpen?(r.PolyNode.IsOpen=!0,e.AddChild(r.PolyNode)):null!==r.FirstLeft&&null!==r.FirstLeft.PolyNode?r.FirstLeft.PolyNode.AddChild(r.PolyNode):e.AddChild(r.PolyNode))}}FixupOutPolyline(e){for(var i=e.Pts,s=i.Prev;i!==s;)if(i=i.Next,t.FPoint.op_Equality(i.Pt,i.Prev.Pt)){i===s&&(s=i.Prev);var r=i.Prev;r.Next=i.Next,i.Next.Prev=r,i=r}i===i.Prev&&(e.Pts=null)}FixupOutPolygon(e){var i=null;e.BottomPt=null;for(var s=e.Pts,r=this.PreserveCollinear||this.StrictlySimple;;){if(s.Prev===s||s.Prev===s.Next)return void(e.Pts=null);if(t.FPoint.op_Equality(s.Pt,s.Next.Pt)||t.FPoint.op_Equality(s.Pt,s.Prev.Pt)||t.ClipperBase.SlopesEqual4(s.Prev.Pt,s.Pt,s.Next.Pt)&&(!r||!this.Pt2IsBetweenPt1AndPt3(s.Prev.Pt,s.Pt,s.Next.Pt)))i=null,s.Prev.Next=s.Next,s.Next.Prev=s.Prev,s=s.Prev;else{if(s===i)break;null===i&&(i=s),s=s.Next}}e.Pts=s}DupOutPt(e,i){var s=new t.OutPt;return s.Pt.X=e.Pt.X,s.Pt.Y=e.Pt.Y,s.Idx=e.Idx,i?(s.Next=e.Next,s.Prev=e,e.Next.Prev=s,e.Next=s):(s.Prev=e.Prev,s.Next=e,e.Prev.Next=s,e.Prev=s),s}GetOverlap(t,e,i,s,r){return t<e?i<s?(r.Left=Math.max(t,i),r.Right=Math.min(e,s)):(r.Left=Math.max(t,s),r.Right=Math.min(e,i)):i<s?(r.Left=Math.max(e,i),r.Right=Math.min(t,s)):(r.Left=Math.max(e,s),r.Right=Math.min(t,i)),r.Left<r.Right}JoinHorz(e,i,s,r,n,o){var a=e.Pt.X>i.Pt.X?0:1,l=s.Pt.X>r.Pt.X?0:1;if(a===l)return!1;if(1===a){for(;e.Next.Pt.X<=n.X&&e.Next.Pt.X>=e.Pt.X&&e.Next.Pt.Y===n.Y;)e=e.Next;o&&e.Pt.X!==n.X&&(e=e.Next),i=this.DupOutPt(e,!o),t.FPoint.op_Inequality(i.Pt,n)&&((e=i).Pt.X=n.X,e.Pt.Y=n.Y,i=this.DupOutPt(e,!o))}else{for(;e.Next.Pt.X>=n.X&&e.Next.Pt.X<=e.Pt.X&&e.Next.Pt.Y===n.Y;)e=e.Next;o||e.Pt.X===n.X||(e=e.Next),i=this.DupOutPt(e,o),t.FPoint.op_Inequality(i.Pt,n)&&((e=i).Pt.X=n.X,e.Pt.Y=n.Y,i=this.DupOutPt(e,o))}if(1===l){for(;s.Next.Pt.X<=n.X&&s.Next.Pt.X>=s.Pt.X&&s.Next.Pt.Y===n.Y;)s=s.Next;o&&s.Pt.X!==n.X&&(s=s.Next),r=this.DupOutPt(s,!o),t.FPoint.op_Inequality(r.Pt,n)&&((s=r).Pt.X=n.X,s.Pt.Y=n.Y,r=this.DupOutPt(s,!o))}else{for(;s.Next.Pt.X>=n.X&&s.Next.Pt.X<=s.Pt.X&&s.Next.Pt.Y===n.Y;)s=s.Next;o||s.Pt.X===n.X||(s=s.Next),r=this.DupOutPt(s,o),t.FPoint.op_Inequality(r.Pt,n)&&((s=r).Pt.X=n.X,s.Pt.Y=n.Y,r=this.DupOutPt(s,o))}return 1===a===o?(e.Prev=s,s.Next=e,i.Next=r,r.Prev=i):(e.Next=s,s.Prev=e,i.Prev=r,r.Next=i),!0}JoinPoints(e,i,s){var r=e.OutPt1,n=new t.OutPt,o=e.OutPt2,a=new t.OutPt,l=e.OutPt1.Pt.Y===e.OffPt.Y;if(l&&t.FPoint.op_Equality(e.OffPt,e.OutPt1.Pt)&&t.FPoint.op_Equality(e.OffPt,e.OutPt2.Pt)){if(i!==s)return!1;for(n=e.OutPt1.Next;n!==r&&t.FPoint.op_Equality(n.Pt,e.OffPt);)n=n.Next;var h=n.Pt.Y>e.OffPt.Y;for(a=e.OutPt2.Next;a!==o&&t.FPoint.op_Equality(a.Pt,e.OffPt);)a=a.Next;return h!==a.Pt.Y>e.OffPt.Y&&(h?(n=this.DupOutPt(r,!1),a=this.DupOutPt(o,!0),r.Prev=o,o.Next=r,n.Next=a,a.Prev=n,e.OutPt1=r,e.OutPt2=n,!0):(n=this.DupOutPt(r,!0),a=this.DupOutPt(o,!1),r.Next=o,o.Prev=r,n.Prev=a,a.Next=n,e.OutPt1=r,e.OutPt2=n,!0))}if(l){for(n=r;r.Prev.Pt.Y===r.Pt.Y&&r.Prev!==n&&r.Prev!==o;)r=r.Prev;for(;n.Next.Pt.Y===n.Pt.Y&&n.Next!==r&&n.Next!==o;)n=n.Next;if(n.Next===r||n.Next===o)return!1;for(a=o;o.Prev.Pt.Y===o.Pt.Y&&o.Prev!==a&&o.Prev!==n;)o=o.Prev;for(;a.Next.Pt.Y===a.Pt.Y&&a.Next!==o&&a.Next!==r;)a=a.Next;if(a.Next===o||a.Next===r)return!1;var u={Left:null,Right:null};if(!this.GetOverlap(r.Pt.X,n.Pt.X,o.Pt.X,a.Pt.X,u))return!1;var c,d=u.Left,p=u.Right,f=new t.FPoint;return r.Pt.X>=d&&r.Pt.X<=p?(f.X=r.Pt.X,f.Y=r.Pt.Y,c=r.Pt.X>n.Pt.X):o.Pt.X>=d&&o.Pt.X<=p?(f.X=o.Pt.X,f.Y=o.Pt.Y,c=o.Pt.X>a.Pt.X):n.Pt.X>=d&&n.Pt.X<=p?(f.X=n.Pt.X,f.Y=n.Pt.Y,c=n.Pt.X>r.Pt.X):(f.X=a.Pt.X,f.Y=a.Pt.Y,c=a.Pt.X>o.Pt.X),e.OutPt1=r,e.OutPt2=o,this.JoinHorz(r,n,o,a,f,c)}for(n=r.Next;t.FPoint.op_Equality(n.Pt,r.Pt)&&n!==r;)n=n.Next;var m=n.Pt.Y>r.Pt.Y||!t.ClipperBase.SlopesEqual4(r.Pt,n.Pt,e.OffPt);if(m){for(n=r.Prev;t.FPoint.op_Equality(n.Pt,r.Pt)&&n!==r;)n=n.Prev;if(n.Pt.Y>r.Pt.Y||!t.ClipperBase.SlopesEqual4(r.Pt,n.Pt,e.OffPt))return!1}for(a=o.Next;t.FPoint.op_Equality(a.Pt,o.Pt)&&a!==o;)a=a.Next;var g=a.Pt.Y>o.Pt.Y||!t.ClipperBase.SlopesEqual4(o.Pt,a.Pt,e.OffPt);if(g){for(a=o.Prev;t.FPoint.op_Equality(a.Pt,o.Pt)&&a!==o;)a=a.Prev;if(a.Pt.Y>o.Pt.Y||!t.ClipperBase.SlopesEqual4(o.Pt,a.Pt,e.OffPt))return!1}return n!==r&&a!==o&&n!==a&&(i!==s||m!==g)&&(m?(n=this.DupOutPt(r,!1),a=this.DupOutPt(o,!0),r.Prev=o,o.Next=r,n.Next=a,a.Prev=n,e.OutPt1=r,e.OutPt2=n,!0):(n=this.DupOutPt(r,!0),a=this.DupOutPt(o,!1),r.Next=o,o.Prev=r,n.Prev=a,a.Next=n,e.OutPt1=r,e.OutPt2=n,!0))}static GetBounds(e){for(var i=0,s=e.length;i<s&&0===e[i].length;)i++;if(i===s)return new t.FRect(0,0,0,0);var r=new t.FRect;for(r.left=e[i][0].X,r.right=r.left,r.top=e[i][0].Y,r.bottom=r.top;i<s;i++)for(var n=0,o=e[i].length;n<o;n++)e[i][n].X<r.left?r.left=e[i][n].X:e[i][n].X>r.right&&(r.right=e[i][n].X),e[i][n].Y<r.top?r.top=e[i][n].Y:e[i][n].Y>r.bottom&&(r.bottom=e[i][n].Y);return r}GetBounds2(e){var i=e,s=new t.FRect;for(s.left=e.Pt.X,s.right=e.Pt.X,s.top=e.Pt.Y,s.bottom=e.Pt.Y,e=e.Next;e!==i;)e.Pt.X<s.left&&(s.left=e.Pt.X),e.Pt.X>s.right&&(s.right=e.Pt.X),e.Pt.Y<s.top&&(s.top=e.Pt.Y),e.Pt.Y>s.bottom&&(s.bottom=e.Pt.Y),e=e.Next;return s}static PointInPolygon(t,e){var i=0,s=e.length;if(s<3)return 0;for(var r=e[0],n=1;n<=s;++n){var o=n===s?e[0]:e[n];if(o.Y===t.Y&&(o.X===t.X||r.Y===t.Y&&o.X>t.X==r.X<t.X))return-1;if(r.Y<t.Y!=o.Y<t.Y)if(r.X>=t.X)if(o.X>t.X)i=1-i;else{if(0===(a=(r.X-t.X)*(o.Y-t.Y)-(o.X-t.X)*(r.Y-t.Y)))return-1;a>0==o.Y>r.Y&&(i=1-i)}else if(o.X>t.X){var a;if(0===(a=(r.X-t.X)*(o.Y-t.Y)-(o.X-t.X)*(r.Y-t.Y)))return-1;a>0==o.Y>r.Y&&(i=1-i)}r=o}return i}PointInPolygon(t,e){var i=0,s=e,r=t.X,n=t.Y,o=e.Pt.X,a=e.Pt.Y;do{var l=(e=e.Next).Pt.X,h=e.Pt.Y;if(h===n&&(l===r||a===n&&l>r==o<r))return-1;if(a<n!=h<n)if(o>=r)if(l>r)i=1-i;else{if(0===(u=(o-r)*(h-n)-(l-r)*(a-n)))return-1;u>0==h>a&&(i=1-i)}else if(l>r){var u;if(0===(u=(o-r)*(h-n)-(l-r)*(a-n)))return-1;u>0==h>a&&(i=1-i)}o=l,a=h}while(s!==e);return i}Poly2ContainsPoly1(t,e){var i=t;do{var s=this.PointInPolygon(i.Pt,e);if(s>=0)return s>0;i=i.Next}while(i!==t);return!0}FixupFirstLefts1(e,i){for(var s,r,n=0,o=this.m_PolyOuts.length;n<o;n++)s=this.m_PolyOuts[n],r=t.Clipper.ParseFirstLeft(s.FirstLeft),null!==s.Pts&&r===e&&this.Poly2ContainsPoly1(s.Pts,i.Pts)&&(s.FirstLeft=i)}FixupFirstLefts2(e,i){for(var s,r,n=i.FirstLeft,o=0,a=this.m_PolyOuts.length;o<a;o++)null!==(s=this.m_PolyOuts[o]).Pts&&s!==i&&s!==e&&((r=t.Clipper.ParseFirstLeft(s.FirstLeft))!==n&&r!==e&&r!==i||(this.Poly2ContainsPoly1(s.Pts,e.Pts)?s.FirstLeft=e:this.Poly2ContainsPoly1(s.Pts,i.Pts)?s.FirstLeft=i:s.FirstLeft!==e&&s.FirstLeft!==i||(s.FirstLeft=n)))}FixupFirstLefts3(e,i){for(var s,r,n=0,o=this.m_PolyOuts.length;n<o;n++)s=this.m_PolyOuts[n],r=t.Clipper.ParseFirstLeft(s.FirstLeft),null!==s.Pts&&r===e&&(s.FirstLeft=i)}static ParseFirstLeft(t){for(;null!==t&&null===t.Pts;)t=t.FirstLeft;return t}JoinCommonEdges(){for(var t=0,e=this.m_Joins.length;t<e;t++){var i,s=this.m_Joins[t],r=this.GetOutRec(s.OutPt1.Idx),n=this.GetOutRec(s.OutPt2.Idx);if(null!==r.Pts&&null!==n.Pts)if(!r.IsOpen&&!n.IsOpen)i=r===n?r:this.OutRec1RightOfOutRec2(r,n)?n:this.OutRec1RightOfOutRec2(n,r)?r:this.GetLowermostRec(r,n),this.JoinPoints(s,r,n)&&(r===n?(r.Pts=s.OutPt1,r.BottomPt=null,(n=this.CreateOutRec()).Pts=s.OutPt2,this.UpdateOutPtIdxs(n),this.Poly2ContainsPoly1(n.Pts,r.Pts)?(n.IsHole=!r.IsHole,n.FirstLeft=r,this.m_UsingPolyTree&&this.FixupFirstLefts2(n,r),(n.IsHole^this.ReverseSolution)==this.Area$1(n)>0&&this.ReversePolyPtLinks(n.Pts)):this.Poly2ContainsPoly1(r.Pts,n.Pts)?(n.IsHole=r.IsHole,r.IsHole=!n.IsHole,n.FirstLeft=r.FirstLeft,r.FirstLeft=n,this.m_UsingPolyTree&&this.FixupFirstLefts2(r,n),(r.IsHole^this.ReverseSolution)==this.Area$1(r)>0&&this.ReversePolyPtLinks(r.Pts)):(n.IsHole=r.IsHole,n.FirstLeft=r.FirstLeft,this.m_UsingPolyTree&&this.FixupFirstLefts1(r,n))):(n.Pts=null,n.BottomPt=null,n.Idx=r.Idx,r.IsHole=i.IsHole,i===n&&(r.FirstLeft=n.FirstLeft),n.FirstLeft=r,this.m_UsingPolyTree&&this.FixupFirstLefts3(n,r)))}}UpdateOutPtIdxs(t){var e=t.Pts;do{e.Idx=t.Idx,e=e.Prev}while(e!==t.Pts)}DoSimplePolygons(){for(var e=0;e<this.m_PolyOuts.length;){var i=this.m_PolyOuts[e++],s=i.Pts;if(null!==s&&!i.IsOpen)do{for(var r=s.Next;r!==i.Pts;){if(t.FPoint.op_Equality(s.Pt,r.Pt)&&r.Next!==s&&r.Prev!==s){var n=s.Prev,o=r.Prev;s.Prev=o,o.Next=s,r.Prev=n,n.Next=r,i.Pts=s;var a=this.CreateOutRec();a.Pts=r,this.UpdateOutPtIdxs(a),this.Poly2ContainsPoly1(a.Pts,i.Pts)?(a.IsHole=!i.IsHole,a.FirstLeft=i,this.m_UsingPolyTree&&this.FixupFirstLefts2(a,i)):this.Poly2ContainsPoly1(i.Pts,a.Pts)?(a.IsHole=i.IsHole,i.IsHole=!a.IsHole,a.FirstLeft=i.FirstLeft,i.FirstLeft=a,this.m_UsingPolyTree&&this.FixupFirstLefts2(i,a)):(a.IsHole=i.IsHole,a.FirstLeft=i.FirstLeft,this.m_UsingPolyTree&&this.FixupFirstLefts1(i,a)),r=s}r=r.Next}s=s.Next}while(s!==i.Pts)}}static Area(t){if(!Array.isArray(t))return 0;var e=t.length;if(e<3)return 0;for(var i=0,s=0,r=e-1;s<e;++s)i+=(t[r].X+t[s].X)*(t[r].Y-t[s].Y),r=s;return.5*-i}Area(t){var e=t;if(null===t)return 0;var i=0;do{i+=(t.Prev.Pt.X+t.Pt.X)*(t.Prev.Pt.Y-t.Pt.Y),t=t.Next}while(t!==e);return.5*i}Area$1(t){return this.Area(t.Pts)}static SimplifyPolygon(e,i){var s=new Array,r=new t.Clipper(0);return r.StrictlySimple=!0,r.AddPath(e,0,!0),r.Execute(1,s,i,i),s}static SimplifyPolygons(e,i){void 0===i&&(i=0);var s=new Array,r=new t.Clipper(0);return r.StrictlySimple=!0,r.AddPaths(e,0,!0),r.Execute(1,s,i,i),s}static DistanceSqrd(t,e){var i=t.X-e.X,s=t.Y-e.Y;return i*i+s*s}static DistanceFromLineSqrd(t,e,i){var s=e.Y-i.Y,r=i.X-e.X,n=s*e.X+r*e.Y;return(n=s*t.X+r*t.Y-n)*n/(s*s+r*r)}static SlopesNearCollinear(e,i,s,r){return Math.abs(e.X-i.X)>Math.abs(e.Y-i.Y)?e.X>i.X==e.X<s.X?t.Clipper.DistanceFromLineSqrd(e,i,s)<r:i.X>e.X==i.X<s.X?t.Clipper.DistanceFromLineSqrd(i,e,s)<r:t.Clipper.DistanceFromLineSqrd(s,e,i)<r:e.Y>i.Y==e.Y<s.Y?t.Clipper.DistanceFromLineSqrd(e,i,s)<r:i.Y>e.Y==i.Y<s.Y?t.Clipper.DistanceFromLineSqrd(i,e,s)<r:t.Clipper.DistanceFromLineSqrd(s,e,i)<r}static PointsAreClose(t,e,i){var s=t.X-e.X,r=t.Y-e.Y;return s*s+r*r<=i}static ExcludeOp(t){var e=t.Prev;return e.Next=t.Next,t.Next.Prev=e,e.Idx=0,e}static CleanPolygon(e,i){void 0===i&&(i=1.415);var s=e.length;if(0===s)return new Array;for(var r=new Array(s),n=0;n<s;++n)r[n]=new t.OutPt;for(n=0;n<s;++n)r[n].Pt=e[n],r[n].Next=r[(n+1)%s],r[n].Next.Prev=r[n],r[n].Idx=0;for(var o=i*i,a=r[0];0===a.Idx&&a.Next!==a.Prev;)t.Clipper.PointsAreClose(a.Pt,a.Prev.Pt,o)?(a=t.Clipper.ExcludeOp(a),s--):t.Clipper.PointsAreClose(a.Prev.Pt,a.Next.Pt,o)?(t.Clipper.ExcludeOp(a.Next),a=t.Clipper.ExcludeOp(a),s-=2):t.Clipper.SlopesNearCollinear(a.Prev.Pt,a.Pt,a.Next.Pt,o)?(a=t.Clipper.ExcludeOp(a),s--):(a.Idx=1,a=a.Next);s<3&&(s=0);var l=new Array(s);for(n=0;n<s;++n)l[n]=new t.FPoint(a.Pt),a=a.Next;return r=null,l}static CleanPolygons(e,i){for(var s=new Array(e.length),r=0,n=e.length;r<n;r++)s[r]=t.Clipper.CleanPolygon(e[r],i);return s}static Minkowski(e,i,s,r){var n=r?1:0,o=e.length,a=i.length,l=new Array;if(s)for(var h=0;h<a;h++){for(var u=new Array(o),c=0,d=e.length,p=e[c];c<d;p=e[++c])u[c]=new t.FPoint(i[h].X+p.X,i[h].Y+p.Y);l.push(u)}else for(h=0;h<a;h++){for(u=new Array(o),c=0,d=e.length,p=e[c];c<d;p=e[++c])u[c]=new t.FPoint(i[h].X-p.X,i[h].Y-p.Y);l.push(u)}var f=new Array;for(h=0;h<a-1+n;h++)for(c=0;c<o;c++){var m=new Array;m.push(l[h%a][c%o]),m.push(l[(h+1)%a][c%o]),m.push(l[(h+1)%a][(c+1)%o]),m.push(l[h%a][(c+1)%o]),t.Clipper.Orientation(m)||m.reverse(),f.push(m)}return f}static MinkowskiSum(e,i,s){if(i[0]instanceof Array){let l=i;for(var r=[],n=(a=new t.Clipper,0);n<l.length;++n){var o=t.Clipper.Minkowski(e,l[n],!0,s);if(a.AddPaths(o,0,!0),s){let i=t.Clipper.TranslatePath(l[n],e[0]);a.AddPath(i,1,!0)}}return a.Execute(1,r,1,1),r}{let r=i,n=t.Clipper.Minkowski(e,r,!0,s);var a;return(a=new t.Clipper).AddPaths(n,0,!0),a.Execute(1,n,1,1),n}}static TranslatePath(e,i){for(var s=[],r=0;r<e.length;r++)s.push(new t.FPoint(e[r].X+i.X,e[r].Y+i.Y));return s}static MinkowskiDiff(e,i){var s=t.Clipper.Minkowski(e,i,!1,!0),r=new t.Clipper;return r.AddPaths(s,0,!0),r.Execute(1,s,1,1),s}static PolyTreeToPaths(e){var i=new Array;return t.Clipper.AddPolyNodeToPaths(e,0,i),i}static AddPolyNodeToPaths(e,i,s){var r=!0;switch(i){case 1:return;case 2:r=!e.IsOpen}e.m_polygon.length>0&&r&&s.push(e.m_polygon);for(var n=0,o=e.Children(),a=o.length,l=o[n];n<a;l=o[++n])t.Clipper.AddPolyNodeToPaths(l,i,s)}static OpenPathsFromPolyTree(t){for(var e=[],i=0,s=t.ChildCount();i<s;i++)t.Children()[i].IsOpen&&e.push(t.Children()[i].m_polygon);return e}static ClosedPathsFromPolyTree(e){var i=[];return t.Clipper.AddPolyNodeToPaths(e,2,i),i}};t.ClipperOffset=class{m_destPolys=[];m_srcPoly=[];m_destPoly=[];m_normals=new Array;m_delta=0;m_sinA=0;m_sin=0;m_cos=0;m_miterLim=0;m_StepsPerRad=0;m_lowest=new t.FPoint;m_polyNodes=new t.PolyNode;MiterLimit;ArcTolerance;constructor(e,i){void 0===e&&(e=2),void 0===i&&(i=t.ClipperOffset.def_arc_tolerance),this.MiterLimit=e,this.ArcTolerance=i,this.m_lowest.X=-1}static two_pi=6.28318530717959;static def_arc_tolerance=.25;Clear(){t.Clear(this.m_polyNodes.Children()),this.m_lowest.X=-1}AddPath(e,i,s){var r=e.length-1;if(!(r<0)){var n=new t.PolyNode;if(n.m_jointype=i,n.m_endtype=s,3===s||4===s)for(;r>0&&t.FPoint.op_Equality(e[0],e[r]);)r--;n.m_polygon.push(e[0]);for(var o=0,a=0,l=1;l<=r;l++)t.FPoint.op_Inequality(n.m_polygon[o],e[l])&&(o++,n.m_polygon.push(e[l]),(e[l].Y>n.m_polygon[a].Y||e[l].Y===n.m_polygon[a].Y&&e[l].X<n.m_polygon[a].X)&&(a=o));if(!(4===s&&o<2)&&(this.m_polyNodes.AddChild(n),4===s))if(this.m_lowest.X<0)this.m_lowest=new t.FPoint(this.m_polyNodes.ChildCount()-1,a);else{var h=this.m_polyNodes.Children()[this.m_lowest.X].m_polygon[this.m_lowest.Y];(n.m_polygon[a].Y>h.Y||n.m_polygon[a].Y===h.Y&&n.m_polygon[a].X<h.X)&&(this.m_lowest=new t.FPoint(this.m_polyNodes.ChildCount()-1,a))}}}AddPaths(t,e,i){for(var s=0,r=t.length;s<r;s++)this.AddPath(t[s],e,i)}FixOrientations(){if(this.m_lowest.X>=0&&!t.Clipper.Orientation(this.m_polyNodes.Children()[this.m_lowest.X].m_polygon))for(var e=0;e<this.m_polyNodes.ChildCount();e++){(4===(i=this.m_polyNodes.Children()[e]).m_endtype||3===i.m_endtype&&t.Clipper.Orientation(i.m_polygon))&&i.m_polygon.reverse()}else for(e=0;e<this.m_polyNodes.ChildCount();e++){var i;3!==(i=this.m_polyNodes.Children()[e]).m_endtype||t.Clipper.Orientation(i.m_polygon)||i.m_polygon.reverse()}}static GetUnitNormal(e,i){var s=i.X-e.X,r=i.Y-e.Y;if(0===s&&0===r)return new t.FPoint(0,0);var n=1/Math.sqrt(s*s+r*r);return s*=n,r*=n,new t.FPoint(r,-s)}DoOffset(e){if(this.m_destPolys=new Array,this.m_delta=e,t.ClipperBase.near_zero(e))for(var i=0;i<this.m_polyNodes.ChildCount();i++){4===(n=this.m_polyNodes.Children()[i]).m_endtype&&this.m_destPolys.push(n.m_polygon)}else{var s;this.MiterLimit>2?this.m_miterLim=2/(this.MiterLimit*this.MiterLimit):this.m_miterLim=.5,s=this.ArcTolerance<=0?t.ClipperOffset.def_arc_tolerance:this.ArcTolerance>Math.abs(e)*t.ClipperOffset.def_arc_tolerance?Math.abs(e)*t.ClipperOffset.def_arc_tolerance:this.ArcTolerance;var r=3.14159265358979/Math.acos(1-s/Math.abs(e));this.m_sin=Math.sin(t.ClipperOffset.two_pi/r),this.m_cos=Math.cos(t.ClipperOffset.two_pi/r),this.m_StepsPerRad=r/t.ClipperOffset.two_pi,e<0&&(this.m_sin=-this.m_sin);for(i=0;i<this.m_polyNodes.ChildCount();i++){var n=this.m_polyNodes.Children()[i];this.m_srcPoly=n.m_polygon;var o=this.m_srcPoly.length;if(!(0===o||e<=0&&(o<3||4!==n.m_endtype)))if(this.m_destPoly=new Array,1!==o){this.m_normals.length=0;for(d=0;d<o-1;d++)this.m_normals.push(t.ClipperOffset.GetUnitNormal(this.m_srcPoly[d],this.m_srcPoly[d+1]));if(3===n.m_endtype||4===n.m_endtype?this.m_normals.push(t.ClipperOffset.GetUnitNormal(this.m_srcPoly[o-1],this.m_srcPoly[0])):this.m_normals.push(new t.FPoint(this.m_normals[o-2])),4===n.m_endtype){var a=o-1;for(d=0;d<o;d++)a=this.OffsetPoint(d,a,n.m_jointype);this.m_destPolys.push(this.m_destPoly)}else if(3===n.m_endtype){for(a=o-1,d=0;d<o;d++)a=this.OffsetPoint(d,a,n.m_jointype);this.m_destPolys.push(this.m_destPoly),this.m_destPoly=new Array;var l=this.m_normals[o-1];for(d=o-1;d>0;d--)this.m_normals[d]=new t.FPoint(-this.m_normals[d-1].X,-this.m_normals[d-1].Y);this.m_normals[0]=new t.FPoint(-l.X,-l.Y),a=0;for(d=o-1;d>=0;d--)a=this.OffsetPoint(d,a,n.m_jointype);this.m_destPolys.push(this.m_destPoly)}else{var h;for(a=0,d=1;d<o-1;++d)a=this.OffsetPoint(d,a,n.m_jointype);if(2===n.m_endtype){d=o-1;h=new t.FPoint(this.m_srcPoly[d].X+this.m_normals[d].X*e,this.m_srcPoly[d].Y+this.m_normals[d].Y*e),this.m_destPoly.push(h),h=new t.FPoint(this.m_srcPoly[d].X-this.m_normals[d].X*e,this.m_srcPoly[d].Y-this.m_normals[d].Y*e),this.m_destPoly.push(h)}else{d=o-1;a=o-2,this.m_sinA=0,this.m_normals[d]=new t.FPoint(-this.m_normals[d].X,-this.m_normals[d].Y),0===n.m_endtype?this.DoSquare(d,a):this.DoRound(d,a)}for(d=o-1;d>0;d--)this.m_normals[d]=new t.FPoint(-this.m_normals[d-1].X,-this.m_normals[d-1].Y);this.m_normals[0]=new t.FPoint(-this.m_normals[1].X,-this.m_normals[1].Y);for(d=(a=o-1)-1;d>0;--d)a=this.OffsetPoint(d,a,n.m_jointype);2===n.m_endtype?(h=new t.FPoint(this.m_srcPoly[0].X-this.m_normals[0].X*e,this.m_srcPoly[0].Y-this.m_normals[0].Y*e),this.m_destPoly.push(h),h=new t.FPoint(this.m_srcPoly[0].X+this.m_normals[0].X*e,this.m_srcPoly[0].Y+this.m_normals[0].Y*e),this.m_destPoly.push(h)):(a=1,this.m_sinA=0,0===n.m_endtype?this.DoSquare(0,1):this.DoRound(0,1)),this.m_destPolys.push(this.m_destPoly)}}else{if(1===n.m_jointype)for(var u=1,c=0,d=1;d<=r;d++){this.m_destPoly.push(new t.FPoint(this.m_srcPoly[0].X+u*e,this.m_srcPoly[0].Y+c*e));var p=u;u=u*this.m_cos-this.m_sin*c,c=p*this.m_sin+c*this.m_cos}else{u=-1,c=-1;for(var d=0;d<4;++d)this.m_destPoly.push(new t.FPoint(this.m_srcPoly[0].X+u*e,this.m_srcPoly[0].Y+c*e)),u<0?u=1:c<0?c=1:u=-1}this.m_destPolys.push(this.m_destPoly)}}}}Execute(...e){var i=e;if(i[0]instanceof t.PolyTree){o=i[0],a=i[1];if(o.Clear(),this.FixOrientations(),this.DoOffset(a),(n=new t.Clipper(0)).AddPaths(this.m_destPolys,0,!0),a>0)n.Execute(1,o,2,2);else{h=t.Clipper.GetBounds(this.m_destPolys);if((l=[]).push(new t.FPoint(h.left-10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.top-10)),l.push(new t.FPoint(h.left-10,h.top-10)),n.AddPath(l,0,!0),n.ReverseSolution=!0,n.Execute(1,o,3,3),1===o.ChildCount()&&o.Children()[0].ChildCount()>0){var s=o.Children()[0];o.Children()[0]=s.Children()[0],o.Children()[0].m_Parent=o;for(var r=1;r<s.ChildCount();r++)o.AddChild(s.Children()[r])}else o.Clear()}}else{var n,o=i[0],a=i[1];if(t.Clear(o),this.FixOrientations(),this.DoOffset(a),(n=new t.Clipper(0)).AddPaths(this.m_destPolys,0,!0),a>0)n.Execute(1,o,2,2);else{var l,h=t.Clipper.GetBounds(this.m_destPolys);(l=[]).push(new t.FPoint(h.left-10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.top-10)),l.push(new t.FPoint(h.left-10,h.top-10)),n.AddPath(l,0,!0),n.ReverseSolution=!0,n.Execute(1,o,3,3),o.length>0&&o.splice(0,1)}}}OffsetPoint(e,i,s){if(this.m_sinA=this.m_normals[i].X*this.m_normals[e].Y-this.m_normals[e].X*this.m_normals[i].Y,0===this.m_sinA)return i;if(this.m_sinA>1?this.m_sinA=1:this.m_sinA<-1&&(this.m_sinA=-1),this.m_sinA*this.m_delta<0)this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_normals[i].X*this.m_delta,this.m_srcPoly[e].Y+this.m_normals[i].Y*this.m_delta)),this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e])),this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_normals[e].X*this.m_delta,this.m_srcPoly[e].Y+this.m_normals[e].Y*this.m_delta));else switch(s){case 2:var r=this.m_normals[e].X*this.m_normals[i].X+this.m_normals[e].Y*this.m_normals[i].Y+1;r>=this.m_miterLim?this.DoMiter(e,i,r):this.DoSquare(e,i);break;case 0:this.DoSquare(e,i);break;case 1:this.DoRound(e,i)}return i=e}DoSquare(e,i){var s=Math.tan(Math.atan2(this.m_sinA,this.m_normals[i].X*this.m_normals[e].X+this.m_normals[i].Y*this.m_normals[e].Y)/4);this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_delta*(this.m_normals[i].X-this.m_normals[i].Y*s),this.m_srcPoly[e].Y+this.m_delta*(this.m_normals[i].Y+this.m_normals[i].X*s))),this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_delta*(this.m_normals[e].X+this.m_normals[e].Y*s),this.m_srcPoly[e].Y+this.m_delta*(this.m_normals[e].Y-this.m_normals[e].X*s)))}DoMiter(e,i,s){var r=this.m_delta/s;this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+(this.m_normals[i].X+this.m_normals[e].X)*r,this.m_srcPoly[e].Y+(this.m_normals[i].Y+this.m_normals[e].Y)*r))}DoRound(e,i){for(var s,r=Math.atan2(this.m_sinA,this.m_normals[i].X*this.m_normals[e].X+this.m_normals[i].Y*this.m_normals[e].Y),n=Math.max(Math.round(this.m_StepsPerRad*Math.abs(r)),1),o=this.m_normals[i].X,a=this.m_normals[i].Y,l=0;l<n;++l)this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+o*this.m_delta,this.m_srcPoly[e].Y+a*this.m_delta)),s=o,o=o*this.m_cos-this.m_sin*a,a=s*this.m_sin+a*this.m_cos;this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_normals[e].X*this.m_delta,this.m_srcPoly[e].Y+this.m_normals[e].Y*this.m_delta))}},t.Error=function(e){throw new t.Error(e)}})(G||(G={}));const X=G;function W(t){let e=et(t),i=X.Clipper.GetBounds(e);return{min:[i.left,-i.bottom],max:[i.right,-i.top]}}function Y(t){if(!t.length)return[];let e=t.filter(t=>t&&t.length>0);if(!e.length)return[];if(1===e.length)return[e[0]];let i=et(e);if(!i.length)return[];let s=[i[0]],r=i.slice(1),n=new X.Clipper;n.AddPaths(s,X.PolyType.ptSubject,!0),n.AddPaths(r,X.PolyType.ptClip,!0);let o=[];return n.Execute(X.ClipType.ctUnion,o,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),it(o)}function H(t,e=0,i=[],s=[],r=[]){for(let n of t.m_Children){if(!n.m_polygon.length)continue;let t=e%2!=0,o=it([n.m_polygon])[0],a={polygon:o,children:[]};i.push(a),t?r.push(o):(r=[o],s.push(r)),H(n,e+1,a.children,s,r)}return s.sort((t,e)=>K(t[0])>K(e[0])?-1:1),{polyTree:i,polygons:s}}function $(t,e=.1,i,s){if(!t.length||!t[0])return[];void 0===i&&(i=X.EndType.etClosedPolygon),e=e&&"number"==typeof e?e:.1;let r=et(t=s?t:Q(t)),n=new X.ClipperOffset(2),o=[];return n.AddPaths(r,X.JoinType.jtMiter,i),n.Execute(o,e),it(o)}function j(t,e=.1,i=X.EndType.etClosedPolygon){if(!t.length||!t[0])return{polygons:[],polyTree:[]};let s=[];for(let o of t)s.push(...et(o));let r=new X.ClipperOffset(2);r.AddPaths(s,X.JoinType.jtMiter,i);let n=new X.PolyTree;return r.Execute(n,e),H(n)}function z(t,e,i){if(!t.length||!t[0])return[];if(!e.length)return t;let s=et(t),r=et(e),n=new X.Clipper;n.AddPaths(s,X.PolyType.ptSubject,!0),n.AddPaths(r,X.PolyType.ptClip,!0);let o=[];return new X.PolyTree,n.Execute(X.ClipType.ctDifference,o,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),it(o)}function V(t,e){if(!t.length||!t[0])return{polygons:[],polyTree:[]};if(!e.length){let e=t.map(t=>[...t]),i=e.map(t=>({polygon:t[0],children:[]}));return{polygons:e,polyTree:i}}let i=[];for(let o=0;o<t.length;o++)i.push(...et(t[o]));let s=[];for(let o=0;o<e.length;o++)s.push(...et(e[o]));let r=new X.Clipper;r.AddPaths(i,X.PolyType.ptSubject,!0),r.AddPaths(s,X.PolyType.ptClip,!0);let n=new X.PolyTree;return r.Execute(X.ClipType.ctDifference,n,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),H(n)}function q(t,e,i=[]){let s=new X.FPoint(t[0],-t[1]),r=et([e])[0],n=X.Clipper.PointInPolygon(s,r);for(let o of i){let e=q(t,o);1===e?n=0:-1===e&&(n=-1)}return n}function J(t){let e=et([t]);return X.Clipper.Area(e[0])}function K(t){return Math.abs(J(t))}function Z(t){let e=Math.abs(J(t[0]));for(let i of t.slice(1))e-=Math.abs(J(i));return e}function Q(t,e=.01){let i=et(t);return it(X.Clipper.CleanPolygons(i,e))}function tt(t,e=.01){return Q([t],e)[0]}function et(t=[]){let e=[],i=0;for(let s=0;s<t.length;s++){let r=t[s];if(!r?.length)continue;let n=new Array(r.length);for(let t=0;t<r.length;t++){let e=r[t];n[t]={X:e[0],Y:-e[1]}}e[i]=n,i++}return e}function it(t){let e=new Array(t.length);for(let i=0;i<t.length;i++){let s=t[i]||[],r=new Array(s.length);for(let t=0;t<s.length;t++){let e=s[t];r[t]=[e.X,-e.Y]}e[i]=r}return e}var st=1e-6,rt="undefined"!=typeof Float32Array?Float32Array:Array;function nt(){var t=new rt(16);return rt!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function ot(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function at(t,e){if(t===e){var i=e[1],s=e[2],r=e[3],n=e[6],o=e[7],a=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=i,t[6]=e[9],t[7]=e[13],t[8]=s,t[9]=n,t[11]=e[14],t[12]=r,t[13]=o,t[14]=a}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}function lt(t,e){var i=e[0],s=e[1],r=e[2],n=e[3],o=e[4],a=e[5],l=e[6],h=e[7],u=e[8],c=e[9],d=e[10],p=e[11],f=e[12],m=e[13],g=e[14],y=e[15],v=i*a-s*o,x=i*l-r*o,b=i*h-n*o,_=s*l-r*a,w=s*h-n*a,P=r*h-n*l,E=u*m-c*f,T=u*g-d*f,A=u*y-p*f,I=c*g-d*m,S=c*y-p*m,C=d*y-p*g,M=v*C-x*S+b*I+_*A-w*T+P*E;return M?(M=1/M,t[0]=(a*C-l*S+h*I)*M,t[1]=(r*S-s*C-n*I)*M,t[2]=(m*P-g*w+y*_)*M,t[3]=(d*w-c*P-p*_)*M,t[4]=(l*A-o*C-h*T)*M,t[5]=(i*C-r*A+n*T)*M,t[6]=(g*b-f*P-y*x)*M,t[7]=(u*P-d*b+p*x)*M,t[8]=(o*S-a*A+h*E)*M,t[9]=(s*A-i*S-n*E)*M,t[10]=(f*w-m*b+y*v)*M,t[11]=(c*b-u*w-p*v)*M,t[12]=(a*T-o*I-l*E)*M,t[13]=(i*I-s*T+r*E)*M,t[14]=(m*x-f*_-g*v)*M,t[15]=(u*_-c*x+d*v)*M,t):null}function ht(t,e,i){var s=e[0],r=e[1],n=e[2],o=e[3],a=e[4],l=e[5],h=e[6],u=e[7],c=e[8],d=e[9],p=e[10],f=e[11],m=e[12],g=e[13],y=e[14],v=e[15],x=i[0],b=i[1],_=i[2],w=i[3];return t[0]=x*s+b*a+_*c+w*m,t[1]=x*r+b*l+_*d+w*g,t[2]=x*n+b*h+_*p+w*y,t[3]=x*o+b*u+_*f+w*v,x=i[4],b=i[5],_=i[6],w=i[7],t[4]=x*s+b*a+_*c+w*m,t[5]=x*r+b*l+_*d+w*g,t[6]=x*n+b*h+_*p+w*y,t[7]=x*o+b*u+_*f+w*v,x=i[8],b=i[9],_=i[10],w=i[11],t[8]=x*s+b*a+_*c+w*m,t[9]=x*r+b*l+_*d+w*g,t[10]=x*n+b*h+_*p+w*y,t[11]=x*o+b*u+_*f+w*v,x=i[12],b=i[13],_=i[14],w=i[15],t[12]=x*s+b*a+_*c+w*m,t[13]=x*r+b*l+_*d+w*g,t[14]=x*n+b*h+_*p+w*y,t[15]=x*o+b*u+_*f+w*v,t}function ut(t,e){return t[0]=e[12],t[1]=e[13],t[2]=e[14],t}function ct(t,e){var i=new rt(3);!function(t,e){var i=e[0],s=e[1],r=e[2],n=e[4],o=e[5],a=e[6],l=e[8],h=e[9],u=e[10];t[0]=Math.sqrt(i*i+s*s+r*r),t[1]=Math.sqrt(n*n+o*o+a*a),t[2]=Math.sqrt(l*l+h*h+u*u)}(i,e);var s=1/i[0],r=1/i[1],n=1/i[2],o=e[0]*s,a=e[1]*r,l=e[2]*n,h=e[4]*s,u=e[5]*r,c=e[6]*n,d=e[8]*s,p=e[9]*r,f=e[10]*n,m=o+u+f,g=0;return m>0?(g=2*Math.sqrt(m+1),t[3]=.25*g,t[0]=(c-p)/g,t[1]=(d-l)/g,t[2]=(a-h)/g):o>u&&o>f?(g=2*Math.sqrt(1+o-u-f),t[3]=(c-p)/g,t[0]=.25*g,t[1]=(a+h)/g,t[2]=(d+l)/g):u>f?(g=2*Math.sqrt(1+u-o-f),t[3]=(d-l)/g,t[0]=(a+h)/g,t[1]=.25*g,t[2]=(c+p)/g):(g=2*Math.sqrt(1+f-o-u),t[3]=(a-h)/g,t[0]=(d+l)/g,t[1]=(c+p)/g,t[2]=.25*g),t}function dt(){var t=new rt(3);return rt!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function pt(t){var e=new rt(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function ft(t,e,i){var s=new rt(3);return s[0]=t,s[1]=e,s[2]=i,s}function mt(t,e,i,s){return t[0]=e,t[1]=i,t[2]=s,t}function gt(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t[2]=e[2]+i[2],t}function yt(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t[2]=e[2]-i[2],t}function vt(t,e){var i=e[0],s=e[1],r=e[2],n=i*i+s*s+r*r;return n>0&&(n=1/Math.sqrt(n)),t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t}function xt(t,e,i){var s=e[0],r=e[1],n=e[2],o=i[0],a=i[1],l=i[2];return t[0]=r*l-n*a,t[1]=n*o-s*l,t[2]=s*a-r*o,t}function bt(t,e,i){var s=e[0],r=e[1],n=e[2],o=i[3]*s+i[7]*r+i[11]*n+i[15];return o=o||1,t[0]=(i[0]*s+i[4]*r+i[8]*n+i[12])/o,t[1]=(i[1]*s+i[5]*r+i[9]*n+i[13])/o,t[2]=(i[2]*s+i[6]*r+i[10]*n+i[14])/o,t}var _t=yt;function wt(){var t=new rt(4);return rt!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t[3]=1,t}function Pt(t,e,i){i*=.5;var s=Math.sin(i);return t[0]=s*e[0],t[1]=s*e[1],t[2]=s*e[2],t[3]=Math.cos(i),t}dt(),function(){var t,e=(t=new rt(4),rt!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0),t)}();var Et;function Tt(){var t=new rt(2);return rt!=Float32Array&&(t[0]=0,t[1]=0),t}dt(),ft(1,0,0),ft(0,1,0),wt(),wt(),Et=new rt(9),rt!=Float32Array&&(Et[1]=0,Et[2]=0,Et[3]=0,Et[5]=0,Et[6]=0,Et[7]=0),Et[0]=1,Et[4]=1,Et[8]=1,function(){var t=Tt()}();var At="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function It(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function St(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if("function"==typeof e){var i=function t(){var i=!1;try{i=this instanceof t}catch{}return i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};i.prototype=e.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(t).forEach(function(e){var s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(i,e,s.get?s:{enumerable:!0,get:function(){return t[e]}})}),i}var Ct,Mt={exports:{}};var Ot=function(){if(Ct)return Mt.exports;function t(t,i,r){r=r||2;var n,o,a,u,c,p,f,m=i&&i.length,g=m?i[0]*r:t.length,y=e(t,0,g,r,!0),v=[];if(!y||y.next===y.prev)return v;if(m&&(y=function(t,i,s,r){var n,o,a,u=[];for(n=0,o=i.length;n<o;n++)(a=e(t,i[n]*r,n<o-1?i[n+1]*r:t.length,r,!1))===a.next&&(a.steiner=!0),u.push(d(a));for(u.sort(l),n=0;n<u.length;n++)s=h(u[n],s);return s}(t,i,y,r)),t.length>80*r){n=a=t[0],o=u=t[1];for(var x=r;x<g;x+=r)(c=t[x])<n&&(n=c),(p=t[x+1])<o&&(o=p),c>a&&(a=c),p>u&&(u=p);f=0!==(f=Math.max(a-n,u-o))?32767/f:0}return s(y,v,r,n,o,f,0),v}function e(t,e,i,s,r){var n,o;if(r===T(t,e,i,s)>0)for(n=e;n<i;n+=s)o=w(n,t[n],t[n+1],o);else for(n=i-s;n>=e;n-=s)o=w(n,t[n],t[n+1],o);return o&&g(o,o.next)&&(P(o),o=o.next),o}function i(t,e){if(!t)return t;e||(e=t);var i,s=t;do{if(i=!1,s.steiner||!g(s,s.next)&&0!==m(s.prev,s,s.next))s=s.next;else{if(P(s),(s=e=s.prev)===s.next)break;i=!0}}while(i||s!==e);return e}function s(t,e,l,h,u,d,p){if(t){!p&&d&&function(t,e,i,s){var r=t;do{0===r.z&&(r.z=c(r.x,r.y,e,i,s)),r.prevZ=r.prev,r.nextZ=r.next,r=r.next}while(r!==t);r.prevZ.nextZ=null,r.prevZ=null,function(t){var e,i,s,r,n,o,a,l,h=1;do{for(i=t,t=null,n=null,o=0;i;){for(o++,s=i,a=0,e=0;e<h&&(a++,s=s.nextZ);e++);for(l=h;a>0||l>0&&s;)0!==a&&(0===l||!s||i.z<=s.z)?(r=i,i=i.nextZ,a--):(r=s,s=s.nextZ,l--),n?n.nextZ=r:t=r,r.prevZ=n,n=r;i=s}n.nextZ=null,h*=2}while(o>1)}(r)}(t,h,u,d);for(var f,m,g=t;t.prev!==t.next;)if(f=t.prev,m=t.next,d?n(t,h,u,d):r(t))e.push(f.i/l|0),e.push(t.i/l|0),e.push(m.i/l|0),P(t),t=m.next,g=m.next;else if((t=m)===g){p?1===p?s(t=o(i(t),e,l),e,l,h,u,d,2):2===p&&a(t,e,l,h,u,d):s(i(t),e,l,h,u,d,1);break}}}function r(t){var e=t.prev,i=t,s=t.next;if(m(e,i,s)>=0)return!1;for(var r=e.x,n=i.x,o=s.x,a=e.y,l=i.y,h=s.y,u=r<n?r<o?r:o:n<o?n:o,c=a<l?a<h?a:h:l<h?l:h,d=r>n?r>o?r:o:n>o?n:o,f=a>l?a>h?a:h:l>h?l:h,g=s.next;g!==e;){if(g.x>=u&&g.x<=d&&g.y>=c&&g.y<=f&&p(r,a,n,l,o,h,g.x,g.y)&&m(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function n(t,e,i,s){var r=t.prev,n=t,o=t.next;if(m(r,n,o)>=0)return!1;for(var a=r.x,l=n.x,h=o.x,u=r.y,d=n.y,f=o.y,g=a<l?a<h?a:h:l<h?l:h,y=u<d?u<f?u:f:d<f?d:f,v=a>l?a>h?a:h:l>h?l:h,x=u>d?u>f?u:f:d>f?d:f,b=c(g,y,e,i,s),_=c(v,x,e,i,s),w=t.prevZ,P=t.nextZ;w&&w.z>=b&&P&&P.z<=_;){if(w.x>=g&&w.x<=v&&w.y>=y&&w.y<=x&&w!==r&&w!==o&&p(a,u,l,d,h,f,w.x,w.y)&&m(w.prev,w,w.next)>=0)return!1;if(w=w.prevZ,P.x>=g&&P.x<=v&&P.y>=y&&P.y<=x&&P!==r&&P!==o&&p(a,u,l,d,h,f,P.x,P.y)&&m(P.prev,P,P.next)>=0)return!1;P=P.nextZ}for(;w&&w.z>=b;){if(w.x>=g&&w.x<=v&&w.y>=y&&w.y<=x&&w!==r&&w!==o&&p(a,u,l,d,h,f,w.x,w.y)&&m(w.prev,w,w.next)>=0)return!1;w=w.prevZ}for(;P&&P.z<=_;){if(P.x>=g&&P.x<=v&&P.y>=y&&P.y<=x&&P!==r&&P!==o&&p(a,u,l,d,h,f,P.x,P.y)&&m(P.prev,P,P.next)>=0)return!1;P=P.nextZ}return!0}function o(t,e,s){var r=t;do{var n=r.prev,o=r.next.next;!g(n,o)&&y(n,r,r.next,o)&&b(n,o)&&b(o,n)&&(e.push(n.i/s|0),e.push(r.i/s|0),e.push(o.i/s|0),P(r),P(r.next),r=t=o),r=r.next}while(r!==t);return i(r)}function a(t,e,r,n,o,a){var l=t;do{for(var h=l.next.next;h!==l.prev;){if(l.i!==h.i&&f(l,h)){var u=_(l,h);return l=i(l,l.next),u=i(u,u.next),s(l,e,r,n,o,a,0),void s(u,e,r,n,o,a,0)}h=h.next}l=l.next}while(l!==t)}function l(t,e){return t.x-e.x}function h(t,e){var s=function(t,e){var i,s=e,r=t.x,n=t.y,o=-1/0;do{if(n<=s.y&&n>=s.next.y&&s.next.y!==s.y){var a=s.x+(n-s.y)*(s.next.x-s.x)/(s.next.y-s.y);if(a<=r&&a>o&&(o=a,i=s.x<s.next.x?s:s.next,a===r))return i}s=s.next}while(s!==e);if(!i)return null;var l,h=i,c=i.x,d=i.y,f=1/0;s=i;do{r>=s.x&&s.x>=c&&r!==s.x&&p(n<d?r:o,n,c,d,n<d?o:r,n,s.x,s.y)&&(l=Math.abs(n-s.y)/(r-s.x),b(s,t)&&(l<f||l===f&&(s.x>i.x||s.x===i.x&&u(i,s)))&&(i=s,f=l)),s=s.next}while(s!==h);return i}(t,e);if(!s)return e;var r=_(s,t);return i(r,r.next),i(s,s.next)}function u(t,e){return m(t.prev,t,e.prev)<0&&m(e.next,t,t.next)<0}function c(t,e,i,s,r){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*r|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-s)*r|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function d(t){var e=t,i=t;do{(e.x<i.x||e.x===i.x&&e.y<i.y)&&(i=e),e=e.next}while(e!==t);return i}function p(t,e,i,s,r,n,o,a){return(r-o)*(e-a)>=(t-o)*(n-a)&&(t-o)*(s-a)>=(i-o)*(e-a)&&(i-o)*(n-a)>=(r-o)*(s-a)}function f(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&y(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(b(t,e)&&b(e,t)&&function(t,e){var i=t,s=!1,r=(t.x+e.x)/2,n=(t.y+e.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&r<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(s=!s),i=i.next}while(i!==t);return s}(t,e)&&(m(t.prev,t,e.prev)||m(t,e.prev,e))||g(t,e)&&m(t.prev,t,t.next)>0&&m(e.prev,e,e.next)>0)}function m(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function g(t,e){return t.x===e.x&&t.y===e.y}function y(t,e,i,s){var r=x(m(t,e,i)),n=x(m(t,e,s)),o=x(m(i,s,t)),a=x(m(i,s,e));return r!==n&&o!==a||(!(0!==r||!v(t,i,e))||(!(0!==n||!v(t,s,e))||(!(0!==o||!v(i,t,s))||!(0!==a||!v(i,e,s)))))}function v(t,e,i){return e.x<=Math.max(t.x,i.x)&&e.x>=Math.min(t.x,i.x)&&e.y<=Math.max(t.y,i.y)&&e.y>=Math.min(t.y,i.y)}function x(t){return t>0?1:t<0?-1:0}function b(t,e){return m(t.prev,t,t.next)<0?m(t,e,t.next)>=0&&m(t,t.prev,e)>=0:m(t,e,t.prev)<0||m(t,t.next,e)<0}function _(t,e){var i=new E(t.i,t.x,t.y),s=new E(e.i,e.x,e.y),r=t.next,n=e.prev;return t.next=e,e.prev=t,i.next=r,r.prev=i,s.next=i,i.prev=s,n.next=s,s.prev=n,s}function w(t,e,i,s){var r=new E(t,e,i);return s?(r.next=s.next,r.prev=s,s.next.prev=r,s.next=r):(r.prev=r,r.next=r),r}function P(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function E(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function T(t,e,i,s){for(var r=0,n=e,o=i-s;n<i;n+=s)r+=(t[o]-t[n])*(t[n+1]+t[o+1]),o=n;return r}return Ct=1,Mt.exports=t,Mt.exports.default=t,t.deviation=function(t,e,i,s){var r=e&&e.length,n=r?e[0]*i:t.length,o=Math.abs(T(t,0,n,i));if(r)for(var a=0,l=e.length;a<l;a++){var h=e[a]*i,u=a<l-1?e[a+1]*i:t.length;o-=Math.abs(T(t,h,u,i))}var c=0;for(a=0;a<s.length;a+=3){var d=s[a]*i,p=s[a+1]*i,f=s[a+2]*i;c+=Math.abs((t[d]-t[f])*(t[p+1]-t[d+1])-(t[d]-t[p])*(t[f+1]-t[d+1]))}return 0===o&&0===c?0:Math.abs((c-o)/o)},t.flatten=function(t){for(var e=t[0][0].length,i={vertices:[],holes:[],dimensions:e},s=0,r=0;r<t.length;r++){for(var n=0;n<t[r].length;n++)for(var o=0;o<e;o++)i.vertices.push(t[r][n][o]);r>0&&(s+=t[r-1].length,i.holes.push(s))}return i},Mt.exports}();const Nt=/* @__PURE__ */It(Ot);for(var Lt,Rt=[],kt=0;kt<256;++kt)Rt.push((kt+256).toString(16).slice(1));var Bt=new Uint8Array(16);function Ft(){if(!Lt&&!(Lt="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Lt(Bt)}const Dt={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Ut(t,e,i){if(Dt.randomUUID&&!t)return Dt.randomUUID();var s=(t=t||{}).random||(t.rng||Ft)();return s[6]=15&s[6]|64,s[8]=63&s[8]|128,function(t,e=0){return(Rt[t[e+0]]+Rt[t[e+1]]+Rt[t[e+2]]+Rt[t[e+3]]+"-"+Rt[t[e+4]]+Rt[t[e+5]]+"-"+Rt[t[e+6]]+Rt[t[e+7]]+"-"+Rt[t[e+8]]+Rt[t[e+9]]+"-"+Rt[t[e+10]]+Rt[t[e+11]]+Rt[t[e+12]]+Rt[t[e+13]]+Rt[t[e+14]]+Rt[t[e+15]]).toLowerCase()}(s)}function Gt(t,e,i,s,r){Xt(t,e,i||0,s||t.length-1,r||Yt)}function Xt(t,e,i,s,r){for(;s>i;){if(s-i>600){var n=s-i+1,o=e-i+1,a=Math.log(n),l=.5*Math.exp(2*a/3),h=.5*Math.sqrt(a*l*(n-l)/n)*(o-n/2<0?-1:1);Xt(t,e,Math.max(i,Math.floor(e-o*l/n+h)),Math.min(s,Math.floor(e+(n-o)*l/n+h)),r)}var u=t[e],c=i,d=s;for(Wt(t,i,e),r(t[s],u)>0&&Wt(t,i,s);c<d;){for(Wt(t,c,d),c++,d--;r(t[c],u)<0;)c++;for(;r(t[d],u)>0;)d--}0===r(t[i],u)?Wt(t,i,d):Wt(t,++d,s),d<=e&&(i=d+1),e<=d&&(s=d-1)}}function Wt(t,e,i){var s=t[e];t[e]=t[i],t[i]=s}function Yt(t,e){return t<e?-1:t>e?1:0}class Ht{constructor(t=9){this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(t){let e=this.data;const i=[];if(!ie(t,e))return i;const s=this.toBBox,r=[];for(;e;){for(let n=0;n<e.children.length;n++){const o=e.children[n],a=e.leaf?s(o):o;ie(t,a)&&(e.leaf?i.push(o):ee(t,a)?this._all(o,i):r.push(o))}e=r.pop()}return i}collides(t){let e=this.data;if(!ie(t,e))return!1;const i=[];for(;e;){for(let s=0;s<e.children.length;s++){const r=e.children[s],n=e.leaf?this.toBBox(r):r;if(ie(t,n)){if(e.leaf||ee(t,n))return!0;i.push(r)}}e=i.pop()}return!1}load(t){if(!t||!t.length)return this;if(t.length<this._minEntries){for(let e=0;e<t.length;e++)this.insert(t[e]);return this}let e=this._build(t.slice(),0,t.length-1,0);if(this.data.children.length)if(this.data.height===e.height)this._splitRoot(this.data,e);else{if(this.data.height<e.height){const t=this.data;this.data=e,e=t}this._insert(e,this.data.height-e.height-1,!0)}else this.data=e;return this}insert(t){return t&&this._insert(t,this.data.height-1),this}clear(){return this.data=se([]),this}remove(t,e){if(!t)return this;let i=this.data;const s=this.toBBox(t),r=[],n=[];let o,a,l;for(;i||r.length;){if(i||(i=r.pop(),a=r[r.length-1],o=n.pop(),l=!0),i.leaf){const s=$t(t,i.children,e);if(-1!==s)return i.children.splice(s,1),r.push(i),this._condense(r),this}l||i.leaf||!ee(i,s)?a?(o++,i=a.children[o],l=!1):i=null:(r.push(i),n.push(o),o=0,a=i,i=i.children[0])}return this}toBBox(t){return t}compareMinX(t,e){return t.minX-e.minX}compareMinY(t,e){return t.minY-e.minY}toJSON(){return this.data}fromJSON(t){return this.data=t,this}_all(t,e){const i=[];for(;t;)t.leaf?e.push(...t.children):i.push(...t.children),t=i.pop();return e}_build(t,e,i,s){const r=i-e+1;let n,o=this._maxEntries;if(r<=o)return n=se(t.slice(e,i+1)),jt(n,this.toBBox),n;s||(s=Math.ceil(Math.log(r)/Math.log(o)),o=Math.ceil(r/Math.pow(o,s-1))),n=se([]),n.leaf=!1,n.height=s;const a=Math.ceil(r/o),l=a*Math.ceil(Math.sqrt(o));re(t,e,i,l,this.compareMinX);for(let h=e;h<=i;h+=l){const e=Math.min(h+l-1,i);re(t,h,e,a,this.compareMinY);for(let i=h;i<=e;i+=a){const r=Math.min(i+a-1,e);n.children.push(this._build(t,i,r,s-1))}}return jt(n,this.toBBox),n}_chooseSubtree(t,e,i,s){for(;s.push(e),!e.leaf&&s.length-1!==i;){let i,s=1/0,r=1/0;for(let n=0;n<e.children.length;n++){const o=e.children[n],a=Kt(o),l=Qt(t,o)-a;l<r?(r=l,s=a<s?a:s,i=o):l===r&&a<s&&(s=a,i=o)}e=i||e.children[0]}return e}_insert(t,e,i){const s=i?t:this.toBBox(t),r=[],n=this._chooseSubtree(s,this.data,e,r);for(n.children.push(t),Vt(n,s);e>=0&&r[e].children.length>this._maxEntries;)this._split(r,e),e--;this._adjustParentBBoxes(s,r,e)}_split(t,e){const i=t[e],s=i.children.length,r=this._minEntries;this._chooseSplitAxis(i,r,s);const n=this._chooseSplitIndex(i,r,s),o=se(i.children.splice(n,i.children.length-n));o.height=i.height,o.leaf=i.leaf,jt(i,this.toBBox),jt(o,this.toBBox),e?t[e-1].children.push(o):this._splitRoot(i,o)}_splitRoot(t,e){this.data=se([t,e]),this.data.height=t.height+1,this.data.leaf=!1,jt(this.data,this.toBBox)}_chooseSplitIndex(t,e,i){let s,r=1/0,n=1/0;for(let o=e;o<=i-e;o++){const e=zt(t,0,o,this.toBBox),a=zt(t,o,i,this.toBBox),l=te(e,a),h=Kt(e)+Kt(a);l<r?(r=l,s=o,n=h<n?h:n):l===r&&h<n&&(n=h,s=o)}return s||i-e}_chooseSplitAxis(t,e,i){const s=t.leaf?this.compareMinX:qt,r=t.leaf?this.compareMinY:Jt;this._allDistMargin(t,e,i,s)<this._allDistMargin(t,e,i,r)&&t.children.sort(s)}_allDistMargin(t,e,i,s){t.children.sort(s);const r=this.toBBox,n=zt(t,0,e,r),o=zt(t,i-e,i,r);let a=Zt(n)+Zt(o);for(let l=e;l<i-e;l++){const e=t.children[l];Vt(n,t.leaf?r(e):e),a+=Zt(n)}for(let l=i-e-1;l>=e;l--){const e=t.children[l];Vt(o,t.leaf?r(e):e),a+=Zt(o)}return a}_adjustParentBBoxes(t,e,i){for(let s=i;s>=0;s--)Vt(e[s],t)}_condense(t){for(let e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children,e.splice(e.indexOf(t[i]),1)):this.clear():jt(t[i],this.toBBox)}}function $t(t,e,i){if(!i)return e.indexOf(t);for(let s=0;s<e.length;s++)if(i(t,e[s]))return s;return-1}function jt(t,e){zt(t,0,t.children.length,e,t)}function zt(t,e,i,s,r){r||(r=se(null)),r.minX=1/0,r.minY=1/0,r.maxX=-1/0,r.maxY=-1/0;for(let n=e;n<i;n++){const e=t.children[n];Vt(r,t.leaf?s(e):e)}return r}function Vt(t,e){return t.minX=Math.min(t.minX,e.minX),t.minY=Math.min(t.minY,e.minY),t.maxX=Math.max(t.maxX,e.maxX),t.maxY=Math.max(t.maxY,e.maxY),t}function qt(t,e){return t.minX-e.minX}function Jt(t,e){return t.minY-e.minY}function Kt(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function Zt(t){return t.maxX-t.minX+(t.maxY-t.minY)}function Qt(t,e){return(Math.max(e.maxX,t.maxX)-Math.min(e.minX,t.minX))*(Math.max(e.maxY,t.maxY)-Math.min(e.minY,t.minY))}function te(t,e){const i=Math.max(t.minX,e.minX),s=Math.max(t.minY,e.minY),r=Math.min(t.maxX,e.maxX),n=Math.min(t.maxY,e.maxY);return Math.max(0,r-i)*Math.max(0,n-s)}function ee(t,e){return t.minX<=e.minX&&t.minY<=e.minY&&e.maxX<=t.maxX&&e.maxY<=t.maxY}function ie(t,e){return e.minX<=t.maxX&&e.minY<=t.maxY&&e.maxX>=t.minX&&e.maxY>=t.minY}function se(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function re(t,e,i,s,r){const n=[e,i];for(;n.length;){if((i=n.pop())-(e=n.pop())<=s)continue;const o=e+Math.ceil((i-e)/s/2)*s;Gt(t,o,e,i,r),n.push(e,o,o,i)}}var ne,oe={exports:{}};var ae,le,he,ue,ce,de,pe=function(){if(ne)return oe.exports;function t(){}return ne=1,t.prototype={on:function(t,e,i){var s=this.e||(this.e={});return(s[t]||(s[t]=[])).push({fn:e,ctx:i}),this},once:function(t,e,i){var s=this;function r(){s.off(t,r),e.apply(i,arguments)}return r._=e,this.on(t,r,i)},emit:function(t){for(var e=[].slice.call(arguments,1),i=((this.e||(this.e={}))[t]||[]).slice(),s=0,r=i.length;s<r;s++)i[s].fn.apply(i[s].ctx,e);return this},off:function(t,e){var i=this.e||(this.e={}),s=i[t],r=[];if(s&&e)for(var n=0,o=s.length;n<o;n++)s[n].fn!==e&&s[n].fn._!==e&&r.push(s[n]);return r.length?i[t]=r:delete i[t],this}},oe.exports=t,oe.exports.TinyEmitter=t,oe.exports}(),fe=t=>{throw TypeError(t)},me=(t,e,i)=>e.has(t)||fe("Cannot "+i),ge=(t,e,i)=>(me(t,e,"read from private field"),i?i.call(t):e.get(t)),ye=(t,e,i)=>e.has(t)?fe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),ve=(t,e,i,s)=>(me(t,e,"write to private field"),e.set(t,i),i),xe=(t,e,i)=>(me(t,e,"access private method"),i);let be=new class extends E{error(...t){this.levels.includes("errors")&&(t.length>0&&(t[0]="Internal error: "+t[0]),console.error(...t),this.emit("error",...t))}}(["info","warnings","errors"]);class _e{constructor(t){this.spaceGraph=null,this.type=t}}class we extends _e{constructor(t,e){super(e),this.name="",this.customId="",this.id=t}copyForClone(t){this.name=t.name,this.customId=t.customId}setName(t){this.name=t,this.emit("node-property-change",this,"name")}setCustomId(t){this.customId=t,this.emit("node-property-change",this,"customId")}emit(t,...e){this.spaceGraph&&this.spaceGraph.emit(t,...e)}toJSON(){return{type:this.type,id:this.id,name:""===this.name?void 0:this.name,customId:""===this.customId?void 0:this.customId}}}const Pe="material:color";class Ee extends we{constructor(t,e=[1,1,1],i=1){super(t,Pe),this.color=[...e],this.opacity=i}toJSON(){let t;return t=1===this.opacity?[...this.color]:[this.color[0],this.color[1],this.color[2],this.opacity],{...super.toJSON(),value:t}}}const Te="material:standard";class Ae extends we{constructor(t,e){super(t,Te),this.reference=e}toJSON(){return{...super.toJSON(),reference:this.reference}}}const Ie="material:embedded";class Se extends we{constructor(t,e,i){super(t,Ce),this.reference=e,this.format=i}toJSON(){return be.warn("Embedded material not supported in materials section."),{...super.toJSON(),type:"material:color",value:[1,1,1,1]}}}const Ce="material:basic";class Me extends we{constructor(t){super(t,Ce),this.colorDiffuse=[1,1,1],this.colorSpecular=[1,1,1],this.specularCoefficient=1,this.opacity=1}copyForClone(t){super.copyForClone(t),this.colorDiffuse=[...t.colorDiffuse],this.colorSpecular=[...t.colorSpecular],this.specularCoefficient=t.specularCoefficient,this.opacity=t.opacity}toJSON(){return{...super.toJSON(),colorDiffuse:[...this.colorDiffuse],colorSpecular:[...this.colorSpecular],specularCoefficient:this.specularCoefficient,opacity:this.opacity}}}const Oe="default",Ne=[1,1,1],Le=[1,1,1],Re=[...Ne,1];function ke(t,e){return Number.isFinite(t)?!(t<0||t>1)||(be.warn(`Value out of range (0 to 1) in color literal: '${e}'.`),!1):(be.warn(`Invalid float value in color literal: '${e}'.`),!1)}function Be(t,e){return Number.isInteger(t)?!(t<0||t>255)||(be.warn(`Value out of range (0 to 255) in color literal: '${e}'.`),!1):(be.warn(`Invalid byte value in color literal: '${e}'.`),!1)}function Fe(t){if(t.length<3||t.length>4)return be.warn(`Invalid number of components in color literal: '${t}'.`),Re;let e=t.toString(),i=[0,0,0,0];for(let s=0;s<t.length;s++){let r=t[s];if(!ke(r,e))return Re;i[s]=r}return 3===t.length&&(i[3]=Re[3]),i}function De(t){let e,i,s,r,n=t.substring(1),o=parseInt(n,16);if(isNaN(o))return be.warn(`Invalid hexadecimal color literal: '${t}'.`),Re;if(3===n.length?o=o<<4|15:6===n.length&&(o=o<<8|255),3===n.length||4===n.length)e=(o>>12&15)/15,i=(o>>8&15)/15,s=(o>>4&15)/15,r=(15&o)/15;else{if(6!==n.length&&8!==n.length)return be.warn(`Invalid hexademical color literal length: '${t}'.`),Re;e=(o>>24&255)/255,i=(o>>16&255)/255,s=(o>>8&255)/255,r=(255&o)/255}return[e,i,s,r]}function Ue(t,e){if(!t.endsWith(")"))return be.warn(`Missing closing parenthesis: '${t}'.`),Re;let i=e?5:4,s=t.substring(i,t.length-1).split(",");if(s.length<3||s.length>4||3===s.length&&e||4===s.length&&!e)return be.warn(`Invalid number of components in color literal: '${t}'.`),Re;let r=[0,0,0,0];for(let n=0;n<3;n++){let e=s[n],i=parseFloat(e);if(!Be(i,t))return Re;r[n]=i/255}if(4===s.length){let e=parseFloat(s[3]);if(!ke(e,t))return Re;r[3]=e}else r[3]=Re[3];return r}function Ge([t,e,i]){return"#"+Math.round(255*t).toString(16).padStart(2,"0")+Math.round(255*e).toString(16).padStart(2,"0")+Math.round(255*i).toString(16).padStart(2,"0")}function Xe({name:t=Oe,color:e=Ne,specularColor:i=Le,specularCoefficient:s=1,opacity:r=1,reference:n}={}){return n?{name:t,reference:n}:{name:t,color:[...e],specularColor:[...i],specularCoefficient:s,opacity:r}}function We(t,e={}){if(Array.isArray(t)){let[e,i,s,r]=Fe(t);return Xe({name:t.toString(),color:[e,i,s],opacity:r})}if("string"==typeof t){let i,s,r,n;if(""===t)return be.warn("Empty string not a valid color value."),Xe({name:t});if(t===Oe)return Xe();if("#"===t.charAt(0))[i,s,r,n]=De(t);else if(t.startsWith("rgb("))[i,s,r,n]=Ue(t,!1);else{if(!t.startsWith("rgba(")){if(t.startsWith("asm:")){let e=t.substring(4,t.length);return Xe({name:t,reference:e})}if(t.startsWith("data3d:")){let e=t.substring(7,t.length);return Xe({name:t,reference:e})}{let i=e[t];if(void 0===i)return be.warn(`Unknown material: '${t}'.`),Xe();{let e;switch(i.type){case Pe:e=Xe({name:t,color:i.color,specularColor:i.color});break;case Te:e=Xe({name:t,reference:i.reference});break;case Ie:be.warn("Embedded material not supported in materials section."),e=Xe();break;case Ce:e=Xe({name:t,color:i.colorDiffuse,specularColor:i.colorSpecular,specularCoefficient:i.specularCoefficient,opacity:i.opacity});break;default:be.warn(`Unknown material type ${i.type}.`),e=Xe()}return e}}}[i,s,r,n]=Ue(t,!0)}return Xe({name:t,color:[i,s,r],opacity:n})}return be.warn(`Material can only be an array or a string: '${t}'.`),Xe()}const Ye="default";function He(t,e){return new Array(e-t).fill(void 0).map((e,i)=>t+i)}function $e(t,e){let i=new Array(3*e.length),s=0;for(let r=0;r<e.length;r++){let n=3*e[r];i[s++]=t[n],i[s++]=t[n+1],i[s++]=t[n+2]}return i}function je(t,e,i){let s=3*e,r=new Array(s*i.length),n=0;for(let o=0;o<i.length;o++){let e=s*i[o];for(let i=0;i<s;i++)r[n++]=t[e++]}return r}function ze(t,e,i){let s=[],r=e.faces,{surfaces:n,materials:o}=function(t){let e=t.surfaces??{[Ye]:"all"},i=t.materials??{[Ye]:"default"};if(e&&0===Object.keys(e).length)be.warn("Empty 'surfaces' field not allowed.");else if(i&&0===Object.keys(i).length)be.warn("Empty 'materials' field not allowed.");else if(t.material)t.materials?be.warn("Cannot use 'material' and 'materials' at the same time."):i={[Ye]:t.material};else if(i[Ye])Object.keys(i).length>1&&be.warn("Extraneous material assignments ignored.");else{let t=Object.keys(e);for(let e of t)i[e]||be.warn(`Surface '${e}' not assigned a material, using default.`);let s=Object.keys(i);for(let i of s)e[i]||be.warn(`Surface '${i}' not found.`)}return{surfaces:e,materials:i}}(t);for(let[a,l]of Object.entries(n)){if("all"!==l&&!Array.isArray(l)&&"object"!=typeof l){be.warn(`Unknown face indices type, skipping surface '${a}'.`);continue}let n=[];if("geometry:mesh"===t.type)if("all"===l){let t=e.indices.length/3;n.push(...He(0,t))}else if(Array.isArray(l))n.push(...l);else{let{start:t,end:e}=l;n.push(...He(t,e))}else if("all"===l)for(let t of r){let{index:e,count:i}=t;n.push(...He(e,e+i))}else if(Array.isArray(l))for(let t=0;t<l.length;t++){let e=r[l[t]],{index:i,count:s}=e;n.push(...He(i,i+s))}else{let{start:t,end:e}=l;for(let i=t;i<e;i++){let t=r[i],{index:e,count:s}=t;n.push(...He(e,e+s))}}let h,{vertices:u,indices:c,normals:d,uvs:p}=e;h=o[Ye]?o[Ye]:o[a]??"default";let f=We(h,i),m={name:a,vertices:u,indices:$e(c,n),material:f};d&&(m.normals=je(d,3,n)),p&&(m.uvs=je(p,2,n)),s.push(m)}return s}function Ve(t,e){let i=function(t){if(Array.isArray(t))return[t];if("vector3:list"===t.type)return t.list;if("vector3:range"===t.type){let{start:e,step:i,count:s}=t.range;return function(t,e,i){let s=[];for(let r=0;r<i;r++){let i=t[0]+r*e[0],n=t[1]+r*e[1],o=t[2]+r*e[2];s.push([i,n,o])}return s}(e,i,s)}return be.warn(`Unknown position type: ${t}`),[[0,0,0]]}(t),s=function(t){if("number"==typeof t)return[t];if("number:list"===t.type)return t.list;if("number:range"===t.type){let{start:e,step:i,count:s}=t.range;return function(t,e,i){let s=[];for(let r=0;r<i;r++){let i=t+r*e;s.push(i)}return s}(e,i,s)}return be.warn(`Unknown rotation type: ${t}`),[0]}(e),r=Math.max(i.length,s.length),n=[];for(let o=0;o<r;o++){let t=i[Math.min(o,i.length-1)],e=s[Math.min(o,s.length-1)];void 0!==t&&void 0!==e&&n.push({position:t,rotation:e})}return n}function qe(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Je(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if("function"==typeof e){var i=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};i.prototype=e.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(t).forEach(function(e){var s=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(i,e,s.get?s:{enumerable:!0,get:function(){return t[e]}})}),i}var Ke={exports:{}};function Ze(t,e){return t<e?-1:t>e?1:0}const Qe=/* @__PURE__ */Je(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:class{constructor(t=[],e=Ze){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(t){this.data.push(t),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:i}=this,s=e[t];for(;t>0;){const r=t-1>>1,n=e[r];if(i(s,n)>=0)break;e[t]=n,t=r}e[t]=s}_down(t){const{data:e,compare:i}=this,s=this.length>>1,r=e[t];for(;t<s;){let s=1+(t<<1),n=e[s];const o=s+1;if(o<this.length&&i(e[o],n)<0&&(s=o,n=e[o]),i(n,r)>=0)break;e[t]=n,t=s}e[t]=r}}},Symbol.toStringTag,{value:"Module"})));var ti;const ei=/* @__PURE__ */qe(function(){if(ti)return Ke.exports;ti=1;var t=Qe;function e(e,r,n){var o,a,l,h;r=r||1;for(var u=0;u<e[0].length;u++){var c=e[0][u];(!u||c[0]<o)&&(o=c[0]),(!u||c[1]<a)&&(a=c[1]),(!u||c[0]>l)&&(l=c[0]),(!u||c[1]>h)&&(h=c[1])}var d=l-o,p=h-a,f=Math.min(d,p),m=f/2;if(0===f){var g=[o,a];return g.distance=0,g}for(var y=new t(void 0,i),v=o;v<l;v+=f)for(var x=a;x<h;x+=f)y.push(new s(v+m,x+m,m,e));var b=function(t){for(var e=0,i=0,r=0,n=t[0],o=0,a=n.length,l=a-1;o<a;l=o++){var h=n[o],u=n[l],c=h[0]*u[1]-u[0]*h[1];i+=(h[0]+u[0])*c,r+=(h[1]+u[1])*c,e+=3*c}return 0===e?new s(n[0][0],n[0][1],0,t):new s(i/e,r/e,0,t)}(e),_=new s(o+d/2,a+p/2,0,e);_.d>b.d&&(b=_);for(var w=y.length;y.length;){var P=y.pop();P.d>b.d&&(b=P,n&&console.log("found best %d after %d probes",Math.round(1e4*P.d)/1e4,w)),P.max-b.d<=r||(m=P.h/2,y.push(new s(P.x-m,P.y-m,m,e)),y.push(new s(P.x+m,P.y-m,m,e)),y.push(new s(P.x-m,P.y+m,m,e)),y.push(new s(P.x+m,P.y+m,m,e)),w+=4)}n&&(console.log("num probes: "+w),console.log("best distance: "+b.d));var E=[b.x,b.y];return E.distance=b.d,E}function i(t,e){return e.max-t.max}function s(t,e,i,s){this.x=t,this.y=e,this.h=i,this.d=function(t,e,i){for(var s=!1,n=1/0,o=0;o<i.length;o++)for(var a=i[o],l=0,h=a.length,u=h-1;l<h;u=l++){var c=a[l],d=a[u];c[1]>e!=d[1]>e&&t<(d[0]-c[0])*(e-c[1])/(d[1]-c[1])+c[0]&&(s=!s),n=Math.min(n,r(t,e,c,d))}return 0===n?0:(s?1:-1)*Math.sqrt(n)}(t,e,s),this.max=this.d+this.h*Math.SQRT2}function r(t,e,i,s){var r=i[0],n=i[1],o=s[0]-r,a=s[1]-n;if(0!==o||0!==a){var l=((t-r)*o+(e-n)*a)/(o*o+a*a);l>1?(r=s[0],n=s[1]):l>0&&(r+=o*l,n+=a*l)}return(o=t-r)*o+(a=e-n)*a}return t.default&&(t=t.default),Ke.exports=e,Ke.exports.default=e,Ke.exports}());function ii(t,e){return[t[0]+e[0],t[1]+e[1]]}function si(t){let e;return 0===t[0]?e=t[1]>0?Math.PI/2:t[1]<0?3*Math.PI/2:0:(e=Math.atan2(t[1],t[0]),e<0&&(e+=2*Math.PI)),e}function ri(t,e){return t[0]*e[1]-t[1]*e[0]}function ni(t,e,i){return Math.abs(t[0]-e[0])<i&&Math.abs(t[1]-e[1])<i}function oi(t){return Math.sqrt(function(t){return t[0]*t[0]+t[1]*t[1]}(t))}function ai(t,e){return oi(di(e,t))}function li(t,e,i){return[t[0]+i*(e[0]-t[0]),t[1]+i*(e[1]-t[1])]}function hi(t){let e=oi(t);return[t[0]/e,t[1]/e]}function ui(t){return[-t[1],t[0]]}function ci(t,e){return[t[0]*e,t[1]*e]}function di(t,e){return[t[0]-e[0],t[1]-e[1]]}function pi(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}function fi(t,e){return[t[0]-e[0],t[1]-e[1],t[2]-e[2]]}function mi(t,e,i){return[t[0]+i*(e[0]-t[0]),t[1]+i*(e[1]-t[1]),t[2]+i*(e[2]-t[2])]}function gi(t,e,i){let s=ri(di(e,t),di(i,t));return s>1e-7?1:s<-1e-7?-1:0}function yi(t,e){return si([e[0]-t[0],e[1]-t[1]])}function vi(t,e,i,s){let r=di(e,t),n=di(s,i),o=function(t,e){return t[0]*e[0]+t[1]*e[1]}(r,n),a=ri(r,n);return Math.atan2(Math.abs(a),o)}function xi(t,e){let i=!1;const s=t[0],r=t[1];for(let n=0;n<e.length;n++){const t=e[n],o=n===e.length-1?e[0]:e[n+1];if(t[1]<r&&o[1]>=r||o[1]<r&&t[1]>=r){const e=o[0]-t[0],n=o[1]-t[1];Math.abs(n)>=1e-9&&t[0]+(r-t[1])/n*e<s&&(i=!i)}}return i}function bi(t,e){if(!xi(t,e[0]))return!1;for(let i=1;i<e.length;i++){if(xi(t,e[i]))return!1}return!0}function _i(t,e,i){return function(t,e,i){const s=di(i,e),r=s[0]*s[0]+s[1]*s[1];let n;if(r<1e-9)n=e;else{const o=((t[0]-e[0])*s[0]+(t[1]-e[1])*s[1])/r;n=o<0?e:o>1?i:li(e,i,o)}const o=di(n,t);return o[0]*o[0]+o[1]*o[1]}(t,e,i)**.5}function wi(t){let e=0;for(let i=0;i<t.length;i++){let s=i,r=i<t.length-1?i+1:0,n=t[s],o=t[r];e+=n[0]*o[1]-o[0]*n[1]}return.5*e}function Pi(t){return Math.abs(wi(t))}function Ei(t,e=.1){let i;if(function(t){if(0===t.length)return 0;let e=Pi(t[0]);for(let i=1;i<t.length;i++)e-=Pi(t[i]);return e}(t)<.1)i=function(t){const{min:e,max:i}=W([t]);return[e[0]+(i[0]-e[0])/2,e[1]+(i[1]-e[1])/2]}(t[0]);else{const s=ei(t,e);i=[s[0],s[1]]}return i}function Ti(t){return wi(t)>0}function Ai(t,e,i){if(0!==t[0]||0!==t[1]||0!==t[2]||0!==e){let s=nt(),r=ft(t[0],t[1],t[2]),n=function(t=0,e=[0,1,0]){let i=t*Math.PI/180,s=wt();return Pt(s,e,i),s}(e,i);return function(t,e,i){var s=e[0],r=e[1],n=e[2],o=e[3],a=s+s,l=r+r,h=n+n,u=s*a,c=s*l,d=s*h,p=r*l,f=r*h,m=n*h,g=o*a,y=o*l,v=o*h;t[0]=1-(p+m),t[1]=c+v,t[2]=d-y,t[3]=0,t[4]=c-v,t[5]=1-(u+m),t[6]=f+g,t[7]=0,t[8]=d+y,t[9]=f-g,t[10]=1-(u+p),t[11]=0,t[12]=i[0],t[13]=i[1],t[14]=i[2],t[15]=1}(s,n,r),s}return nt()}function Ii(t){let e=dt(),i=wt();ut(e,t),ct(i,t);let s=dt(),r=(n=s,o=i,a=2*Math.acos(o[3]),(l=Math.sin(a/2))>st?(n[0]=o[0]/l,n[1]=o[1]/l,n[2]=o[2]/l):(n[0]=1,n[1]=0,n[2]=0),a);var n,o,a,l;return 0===r&&(s=[0,1,0]),{position:[e[0],e[1],e[2]],rotation:180*r/Math.PI,rotationAxis:[s[0],s[1],s[2]]}}function Si(t,e){let i=dt();for(let s=0;s<t.length;s+=3)i[0]=t[s],i[1]=t[s+1],i[2]=t[s+2],bt(i,i,e),t[s]=i[0],t[s+1]=i[1],t[s+2]=i[2]}function Ci(t){let e=function(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=e[0],t[5]=e[1],t}(function(){var t=new rt(6);return rt!=Float32Array&&(t[1]=0,t[2]=0,t[4]=0,t[5]=0),t[0]=1,t[3]=1,t}(),t.position);return function(t,e,i){var s=e[0],r=e[1],n=e[2],o=e[3],a=e[4],l=e[5],h=Math.sin(i),u=Math.cos(i);t[0]=s*u+n*h,t[1]=r*u+o*h,t[2]=s*-h+n*u,t[3]=r*-h+o*u,t[4]=a,t[5]=l}(e,e,-t.rotation*Math.PI/180),e}function Mi(t,e){return function(t,e){let i=function(t,e,i){var s=e[0],r=e[1];return t[0]=i[0]*s+i[2]*r+i[4],t[1]=i[1]*s+i[3]*r+i[5],t}(Tt(),t.position,e),s=t.rotation+Math.atan2(-e[1],e[0])*(180/Math.PI);return{position:[i[0],i[1]],rotation:(r=s,n=360,(r%n+n)%n)};var r,n}(t,Ci(e))}function Oi(t,e){return t.map(t=>{let{position:i}=Mi({position:t,rotation:0},e);return i})}function Ni({position:t=[0,0,0],rotation:e=0,rotationAxis:i=[0,1,0],name:s,vertices:r,indices:n,normals:o,uvs:a,material:l}){let h=Ve(t,e),u=[],c=[],d=[],p=[],f=nt();for(let g=0;g<h.length;g++){let t=h[g],{position:e,rotation:s}=t,l=Ai(e,s,i),m=r.slice();Si(m,l);let y=u.length/3;for(const i of m)u.push(i);for(const i of n)c.push(y+i);if(Array.isArray(o)){ot(f,l),f[12]=0,f[13]=0,f[14]=0,at(f,f),lt(f,f);let t=o.slice();Si(t,f),d.push(...t)}Array.isArray(a)&&p.push(...a)}let m={name:s,vertices:u,indices:c,material:l};return Array.isArray(o)&&(m.normals=d),Array.isArray(a)&&(m.uvs=p),m}class Li{constructor(){this.polygons=[]}clone(){const t=new Li;for(const e of this.polygons)t.polygons.push(e.clone());return t}toPolygons(){return this.polygons}union(t){var e=new Li.Node(this.clone().polygons),i=new Li.Node(t.clone().polygons);return e.clipTo(i),i.clipTo(e),i.invert(),i.clipTo(e),i.invert(),e.build(i.allPolygons()),Li.fromPolygons(e.allPolygons())}subtract(t){var e=new Li.Node(this.polygons),i=new Li.Node(t.polygons);return e.invert(),e.clipTo(i),i.clipTo(e),i.invert(),i.clipTo(e),i.invert(),e.build(i.allPolygons()),e.invert(),Li.fromPolygons(e.allPolygons())}intersect(t){var e=new Li.Node(this.clone().polygons),i=new Li.Node(t.clone().polygons);return e.invert(),i.clipTo(e),i.invert(),e.clipTo(i),i.clipTo(e),e.build(i.allPolygons()),e.invert(),Li.fromPolygons(e.allPolygons())}inverse(){var t=this.clone();return t.polygons.forEach(function(t){t.flip()}),t}}(t=>{function e(t){return[-t[0],-t[1],-t[2]]}function i(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function s(t){const e=function(t){return Math.sqrt(i(t,t))}(t);return[t[0]/e,t[1]/e,t[2]/e]}t.fromPolygons=function(e){var i=new t;return i.polygons=e,i};t.Vertex=class{constructor(t,e){this.pos=t,this.normal=e}clone(){return new t.Vertex([...this.pos],this.normal?[...this.normal]:void 0)}flip(){this.normal&&(this.normal=e(this.normal))}interpolate(e,i){return new t.Vertex(mi(this.pos,e.pos,i),this.normal&&e.normal?mi(this.normal,e.normal,i):void 0)}};const r=class{constructor(t,e){this.normal=t,this.w=e}clone(){return new t.Plane([...this.normal],this.w)}flip(){this.normal=e(this.normal),this.w=-this.w}splitPolygon(e,s,r,n,o){for(var a=0,l=[],h=0;h<e.vertices.length;h++){var u=(v=i(this.normal,e.vertices[h].pos)-this.w)<-t.Plane.EPSILON?2:v>t.Plane.EPSILON?1:0;a|=u,l.push(u)}switch(a){case 0:(i(this.normal,e.plane.normal)>0?s:r).push(e);break;case 1:n.push(e);break;case 2:o.push(e);break;case 3:var c=[],d=[];for(h=0;h<e.vertices.length;h++){var p=(h+1)%e.vertices.length,f=l[h],m=l[p],g=e.vertices[h],y=e.vertices[p];if(2!=f&&c.push(g),1!=f&&d.push(2!=f?g.clone():g),3==(f|m)){var v=(this.w-i(this.normal,g.pos))/i(this.normal,fi(y.pos,g.pos)),x=g.interpolate(y,v);c.push(x),d.push(x.clone())}}c.length>=3&&n.push(new t.Polygon(c,e.shared)),d.length>=3&&o.push(new t.Polygon(d,e.shared))}}};r.EPSILON=1e-5,r.fromPoints=function(e,r,n){var o,a,l=s((o=fi(r,e),a=fi(n,e),[o[1]*a[2]-o[2]*a[1],o[2]*a[0]-o[0]*a[2],o[0]*a[1]-o[1]*a[0]]));return new t.Plane(l,i(l,e))};let n=r;t.Plane=n;t.Polygon=class{constructor(e,i){this.vertices=e,this.shared=i,this.plane=t.Plane.fromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=[];for(const t of this.vertices)e.push(t.clone());return new t.Polygon(e,this.shared)}flip(){this.vertices.reverse();for(const t of this.vertices)t.flip();this.plane.flip()}};t.Node=class{constructor(t){this.plane=null,this.front=null,this.back=null,this.polygons=[],t&&this.build(t)}clone(){var e=new t.Node;e.plane=this.plane&&this.plane.clone(),e.front=this.front&&this.front.clone(),e.back=this.back&&this.back.clone();for(const t of this.polygons)e.polygons.push(t.clone());return e}invert(){var t;for(let i=0;i<this.polygons.length;i++)this.polygons[i].flip();null==(t=this.plane)||t.flip(),this.front&&this.front.invert(),this.back&&this.back.invert();const e=this.front;this.front=this.back,this.back=e}clipPolygons(t){if(!this.plane)return t.slice();for(var e=[],i=[],s=0;s<t.length;s++)this.plane.splitPolygon(t[s],e,i,e,i);this.front&&(e=this.front.clipPolygons(e)),i=this.back?this.back.clipPolygons(i):[];const r=new Array(e.length+i.length);for(let n=0;n<e.length;n++)r[n]=e[n];for(let n=0;n<i.length;n++)r[e.length+n]=i[n];return r}clipTo(t){this.polygons=t.clipPolygons(this.polygons),this.front&&this.front.clipTo(t),this.back&&this.back.clipTo(t)}allPolygons(t=!0){var e=t?this.polygons.slice():this.polygons;return this.front&&(e=e.concat(this.front.allPolygons(!1))),this.back&&(e=e.concat(this.back.allPolygons(!1))),e}build(e){if(e.length){this.plane||(this.plane=e[0].plane.clone());for(var i=[],s=[],r=0;r<e.length;r++)this.plane.splitPolygon(e[r],this.polygons,this.polygons,i,s);i.length&&(this.front||(this.front=new t.Node),this.front.build(i)),s.length&&(this.back||(this.back=new t.Node),this.back.build(s))}}}})(Li||(Li={}));const Ri=Li;function ki(t,e,i){let s=.5*i,r=[[-s,-s,0],[s,-s,0],[s,s,0],[-s,s,0]],{u:n,v:o,n:a}=function(t){const e=1/Math.sqrt(2);let i=[0,0,0],s=[0,0,0],r=[0,0,0];return vt(r,t),xt(i,Math.abs(r[1])<e?ft(0,1,0):ft(1,0,0),t),xt(s,t,i),vt(i,i),vt(s,s),{u:i,v:s,n:r}}(e),l=t,h=function(t,e,i,s,r,n,o,a,l,h,u,c,d,p,f,m){var g=new rt(16);return g[0]=t,g[1]=e,g[2]=i,g[3]=s,g[4]=r,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=u,g[11]=c,g[12]=d,g[13]=p,g[14]=f,g[15]=m,g}(n[0],n[1],n[2],0,o[0],o[1],o[2],0,a[0],a[1],a[2],0,l[0],l[1],l[2],1);for(let u of r)bt(u,u,h);return r}function Bi(t,e){const i=[],s=t.nextId++,{name:r,vertices:n,indices:o,material:a}=e;for(let l=0;l<o.length;l+=3){const t=3*o[l],e=3*o[l+1],h=3*o[l+2],u=[n[t],n[t+1],n[t+2]],c=[n[e],n[e+1],n[e+2]],d=[n[h],n[h+1],n[h+2]],p=[new Ri.Vertex(u),new Ri.Vertex(c),new Ri.Vertex(d)];i.push(new Ri.Polygon(p,{id:s,name:r,material:a}))}return i}function Fi(){let t=Math.random(),e=Math.random(),i=Math.random();return Xe({name:Ge([t,e,i]),color:[t,e,i],opacity:1})}function Di(t,e){const i=[],s=[],r={};for(let n=0;n<e.length;n++){const o=3*e[n],a=t[o],l=t[o+1],h=t[o+2],u=73856093*a^19349663*l^83492791*h;let c=r[u];void 0===c&&(c=i.push(a,l,h)/3-1,r[u]=c),s.push(c)}return{vertices:i,indices:s}}function Ui(t,e){const i=[];for(const s of e){const e=Bi(t,s);for(const t of e)i.push(t)}return Ri.fromPolygons(i)}function Gi(t,{debugMode:e=!1,sharedVertices:i=!0}={}){const s={},{polygons:r}=t;for(let n=0;n<r.length;n++){const t=r[n],i=t.vertices.length;if(i<3){be.warn(`Skipping CSG polygon with '${i}' '${1===i?"vertex":"vertices"}.`);continue}const o=[];o.length=3*i;for(let e=0;e<i;e++){const i=t.vertices[e];o[3*e]=i.pos[0],o[3*e+1]=i.pos[1],o[3*e+2]=i.pos[2]}let a;if(3===i)a=[0,1,2];else{a=[];for(let t=1;t<i-1;t++)a.push(0,t,t+1)}if(e){const t=Fi();s[n]={name:t.name,vertices:o,indices:a,material:t}}else{const{id:e,name:i,material:r}=t.shared,n=s[e];if(n){const t=n.vertices.length;n.vertices.length=t+o.length;for(let s=0;s<o.length;s++)n.vertices[t+s]=o[s];const e=n.indices.length;n.indices.length=e+a.length;const i=t/3;for(let s=0;s<a.length;s++)n.indices[e+s]=a[s]+i}else s[e]={name:i,vertices:o,indices:a,material:r}}}if(i)for(const n of Object.values(s)){const{vertices:t,indices:e}=n,i=Di(t,e);n.vertices=i.vertices,n.indices=i.indices}return Object.values(s)}function Xi(t,e,i,s){let r,n,o,a,l;if("string"==typeof t){if(r=t,l=e[r],!l)return be.warn(`Geometry '${r}' not found.`),[];n=[0,0,0],o=0,a=[0,1,0]}else{let i=t;if("string"==typeof i.geometry){if(r=i.geometry,l=e[r],!l)return be.warn(`Geometry '${r}' not found.`),[]}else l=i.geometry;n=i.position??[0,0,0],o=i.rotation??0,a=i.rotationAxis??[0,1,0]}if(s.indexOf(l)>-1)return be.warn(`Cycle detected while resolving geometry '${l.id}'.`),[];let h=as(l,e,i,s);"string"!=typeof t&&"csg:clip"!==t.type&&function(t,e,i,s){let r;if(t.material?t.materials?be.warn("Cannot use 'material' and 'materials' at the same time."):r={[Ye]:t.material}:t.materials&&(0===Object.keys(t.materials).length?be.warn("Empty 'materials' field not allowed."):r=t.materials),r)if(r[Ye]){let t=We(r[Ye],i);for(let i of e)i.material=t;Object.keys(r).length>1&&be.warn(`Extraneous material assignments to '${s}' ignored.`)}else for(let[n,o]of Object.entries(r)){let t=e.find(t=>t.name===n);if(t){let e=We(o,i);t.material=e}else be.warn(`Surface '${n}' not found in geometry '${s}', skipping material assignment.`)}}(t,h,i,l.id);let u=[];for(let c of h){let{name:t,vertices:e,indices:i,normals:s,uvs:r,material:l}=c,h=Ni({position:n,rotation:o,rotationAxis:a,name:t,vertices:e,indices:i,normals:s,uvs:r,material:l});u.push(h)}return u}function Wi(t,e,i,s,r){return[...t,...Xi(e,i,s,r)]}function Yi(t,e,i,s){let{plane:r,material:n}=i,o=Ui(t,e);{let e=function(t,e,i,s,r=100){let n=t.nextId++,{position:o,normal:a}=e,l=We(i,s),h=[0,0,0],u=[0,0,0];vt(h,a),function(t,e,i,s){t[0]=e[0]+i[0]*s,t[1]=e[1]+i[1]*s,t[2]=e[2]+i[2]*s}(u,o,h,r);let c=ki(o,h,r),d=ki(u,h,r),p=c.concat(d),f=[[0,1,2,3],[4,5,6,7],[0,4,5,1],[1,5,6,2],[2,6,7,3],[3,7,4,0]],m=[];for(let g of f){let t=[];for(let i of g)t.push(new Ri.Vertex(p[i]));let e=new Ri.Polygon(t,{id:n,name:"",material:l});m.push(e)}return Ri.fromPolygons(m)}(t,r,n,s);o.polygons.length>0&&(o=o.subtract(e))}return Gi(o,{debugMode:!1})}function Hi(t,e,i,s,r,n){const o=Xi(i,s,r,n),a=Ui(t,e),l=Ui(t,o);let h=[];if(a.polygons.length&&l.polygons.length){let t;switch(i.type){case"csg:subtract":t=a.subtract(l);break;case"csg:union":t=a.union(l);break;case"csg:intersect":t=a.intersect(l);break;default:t=a}h=Gi(t,{debugMode:!1})}return h}function $i(t,e,i){e[0]=t[i+0],e[1]=t[i+1],e[2]=t[i+2]}function ji(t,e,i){t[i+0]=e[0],t[i+1]=e[1],t[i+2]=e[2]}function zi(t,e){let i=new Array(3*e.length),s=dt(),r=dt(),n=dt(),o=dt(),a=dt(),l=dt(),h=0;for(let u=0;u<e.length;u+=3){let c=e[u],d=e[u+1],p=e[u+2];$i(t,s,3*c),$i(t,r,3*d),$i(t,n,3*p),_t(o,r,s),_t(a,n,s),xt(l,o,a),vt(l,l),ji(i,l,h+0),ji(i,l,h+3),ji(i,l,h+6),h+=9}return i}function Vi(t,e){let i=new Array(3*e.length),s=dt(),r=dt(),n=dt(),o=dt(),a=dt(),l=dt(),h=e.length/3,u=new Array(h),c=0;for(let f=0;f<e.length;f+=3){let i=e[f],h=e[f+1],d=e[f+2];$i(t,s,3*i),$i(t,r,3*h),$i(t,n,3*d),_t(o,r,s),_t(a,n,s),xt(l,o,a),vt(l,l),u[c++]={index1:i,index2:h,index3:d,normal1:pt(l),normal2:pt(l),normal3:pt(l)}}let d=[];for(let f=0;f<t.length;f++)d[f]={normals:[],normal:dt()};for(let f=0;f<u.length;f++){let t=u[f],{index1:e,index2:i,index3:s}=t;d[e].normals.push(t.normal1),d[i].normals.push(t.normal2),d[s].normals.push(t.normal3)}for(let f=0;f<d.length;f++){let t=d[f],e=t.normals.length;if(e>0){let i=t.normal;mt(i,0,0,0);for(let s=0;s<e;s++)gt(i,i,t.normals[s]);vt(i,i)}}let p=0;for(let f=0;f<e.length;f+=3){let t=e[f],s=e[f+1],r=e[f+2],n=d[t].normal,o=d[s].normal,a=d[r].normal;ji(i,n,p+0),ji(i,o,p+3),ji(i,a,p+6),p+=9}return i}function qi(t,e,i){e[0]=t[i+0],e[1]=t[i+1],e[2]=t[i+2]}function Ji(t,e){let i=new Array(2*e.length),s=dt(),r=dt(),n=dt(),o=dt(),a=dt(),l=dt(),h=0;for(let u=0;u<e.length;u+=3){let c,d,p=e[u],f=e[u+1],m=e[u+2];qi(t,s,3*p),qi(t,r,3*f),qi(t,n,3*m),_t(o,r,s),_t(a,n,s),xt(l,o,a),vt(l,l),l[0]=Math.abs(l[0]),l[1]=Math.abs(l[1]),l[2]=Math.abs(l[2]),l[0]>=l[1]&&l[0]>=l[2]?(c=2,d=1):l[1]>=l[0]&&l[1]>=l[2]?(c=0,d=2):(c=0,d=1),i[h++]=s[c],i[h++]=s[d],i[h++]=r[c],i[h++]=r[d],i[h++]=n[c],i[h++]=n[d]}return i}function Ki(t,e){let i=new Array(2*e.length),s=0;for(let r=0;r<e.length;r++){let n=3*e[r],o=t[n],a=t[n+1],l=t[n+2],h=.5+Math.atan2(o,l)/(2*Math.PI),u=.5+Math.asin(a)/Math.PI;i[s++]=h,i[s++]=u}return i}function Zi(t,e,i){let s=Math.cos(e),r=Math.sin(e);return[t*r*Math.cos(i),t*s,t*r*Math.sin(i)]}const Qi=48,ts=12;function es(t,e){return[e*Math.cos(t),-e*Math.sin(t)]}function is(t,e,i,s=!0){let r=[],n=e-t,o=function(t,e){let i=Math.ceil(Qi/(2*Math.PI)*t*e);const s=Math.ceil(ts/(2*Math.PI)*t);return Math.max(s,i)}(Math.abs(n),i),a=n/o;for(let l=0;l<o;l++){let e=es(t+l*a,i);r.push(e)}if(s){let t=es(e,i);r.push(t)}return r}function ss(t){let e=[];switch(t.type){case"curve:line":e.push(t.start,t.end);break;case"curve:arc":e=is(Math.PI*t.startAngle/180,Math.PI*t.endAngle/180,t.radius);break;case"curve:polyline":e=t.points}return e}function rs(t){let e=[],i=[],s=[];switch(t.type){case"curve:circle":e=is(0,2*Math.PI,t.radius,!1),i.push({index:0,count:e.length});break;case"curve:polygon":e=t.points;for(let t=0;t<e.length;t++)i.push({index:t,count:1});break;case"curve:polygonWithHoles":e=t.polygons[0];for(let t=0;t<e.length;t++)i.push({index:t,count:1});const r=t.polygons.slice(1);if(r.length>=1){const t=r.length>1?Y(r):r;for(let e of t)s.push(rs({type:"curve:polygon",points:e}))}break;case"curve:rectangle":let{dimensions:n}=t,o=n[0],a=n[1];e=[[0,0],[0,a],[o,a],[o,0]];for(let t=0;t<e.length;t++)i.push({index:t,count:1});break;case"curve:composite":const l=1e-7;let h,u,c=t.segments;for(let t=0;t<c.length;t++){let s=ss(c[t]),r=s[0],n=s[s.length-1];0===t||ni(r,u,l)||be.warn(`Composite curve segments ${t} and ${t+1} are not continuous.`),0===t&&(h=r),u=n,i.push({index:e.length,count:s.length-1}),e.push(...s.slice(0,s.length-1))}c.length>0&&!ni(u,h,l)&&be.warn("Composite curve not closed.")}return{points:e,segmentRanges:i,holes:s}}function ns(t,e,i){let s,r=i.holes??[],n=i.y??0,o=i.flipSide??!1,a=t,l=[];if(8===a.length&&0===r.length){s=(e?o:!o)?[3,0,1,1,2,3]:[1,0,3,3,2,1]}else{if(r.length>0){let t=new Array(r.length);for(let e=0;e<r.length;e++)t[e]=a.length/2,a=a.concat(r[e]);s=Nt(a,t)}else s=Nt(a);if(!o)for(let t=0;t<s.length;t+=3){let e=s[t];s[t]=s[t+2],s[t+2]=e}}let h=0;for(let u=0;u<a.length;u+=2)l[h++]=a[u],l[h++]=n,l[h++]=a[u+1];return{vertices:l,indices:s}}function os(t,e,i=0,s=!1){let r=new Array(2*t*3),n=0;for(let o=0;o<t;o++){o===t-1?s?(r[n++]=o+i,r[n++]=i,r[n++]=e+i,r[n++]=o+i,r[n++]=e+i,r[n++]=o+e+i):(r[n++]=e+i,r[n++]=i,r[n++]=o+i,r[n++]=o+e+i,r[n++]=e+i,r[n++]=o+i):s?(r[n++]=o+i,r[n++]=o+1+i,r[n++]=o+e+1+i,r[n++]=o+i,r[n++]=o+e+1+i,r[n++]=o+e+i):(r[n++]=o+e+1+i,r[n++]=o+1+i,r[n++]=o+i,r[n++]=o+e+i,r[n++]=o+e+1+i,r[n++]=o+i)}return r}function as(t,e,i,s=[]){var r;let n,o=[];switch(t.type){case"geometry:plane":n=function(t){let{normal:e,size:i,doubleSided:s}=t,r=ki([0,0,0],e,i).flat(),n=[0,1,2,0,2,3],o=[{index:0,count:2}];return s&&(n=n.concat([0,2,1,0,3,2]),o.push({index:2,count:2})),{vertices:r,indices:n,faces:o}}(t);break;case"geometry:cuboid":n=function(t){let{dimensions:e}=t,i=e[0],s=e[1],r=e[2],n=[0,s,r,i,s,r,i,s,0,0,s,0,0,0,r,i,0,r,i,0,0,0,0,0],o=[];for(let a=0;a<6;a++)o.push({index:2*a,count:2});return{vertices:n,indices:[0,1,2,0,2,3,4,7,6,4,6,5,0,4,5,0,5,1,1,5,6,1,6,2,2,6,7,2,7,3,3,7,4,3,4,0],faces:o}}(t);break;case"geometry:sphere":n=function(t){const e=16,i=16;let s,r,n=t.radius,o=[],a=[],l="generator"===t.uvs?[]:void 0;o.push(0,n,0);for(let u=1;u<i;u++){let t=Math.PI*u/i;for(let i=0;i<e;i++){let s=Zi(n,t,2*Math.PI*i/e);o.push(s[0],s[1],s[2])}}let h=o.push(0,-n,0)/3-1;s=1,r=.9375;for(let u=0;u<e;u++){let t=1+u,i=1+(u+1)%e;if(a.push(0,i,t),l){let t=1-u/e,i=1-(u+1)/e,n=.5*(t+i);l.push(n,s,i,r,t,r)}}for(let u=0;u<14;u++)for(let t=0;t<e;t++){let s=1+u*e+t,r=1+u*e+(t+1)%e,n=1+(u+1)*e+(t+1)%e,o=1+(u+1)*e+t;if(a.push(s,r,n),a.push(s,n,o),l){let s=1-t/e,r=1-(u+1)/i,n=1-(t+1)/e,o=1-(u+2)/i;l.push(s,r,n,r,n,o),l.push(s,r,n,o,s,o)}}s=.0625,r=0;for(let u=0;u<e;u++){let t=225+u,i=225+(u+1)%e;if(a.push(t,i,h),l){let t=1-u/e,i=1-(u+1)/e,n=.5*(t+i);l.push(t,s,i,s,n,r)}}return{vertices:o,indices:a,uvs:l,faces:[{index:0,count:a.length/3}]}}(t);break;case"geometry:extrusion":n=function(t){let{profile:e,height:i}=t,s=rs(e),{points:r,segmentRanges:n,holes:o}=s,a=r.flat(),l=[],h=r.length,u=[{points:r,segmentRanges:n}];for(let w of o)l.push(w.points.flat()),u.push(w),h+=w.points.length;let c=Ti(r),d=ns(a,c,{y:i,flipSide:!1,holes:l}),p=ns(a,c,{y:0,flipSide:!0,holes:l}),f=[];f.push(...d.vertices),f.push(...p.vertices);let m=d.indices,g=p.indices.map(t=>t+h),y=[];y.push(...m),y.push(...g);let v=m.length/3,x=[];x[0]={index:0,count:v},x[1]={index:v,count:v};let b=2*v,_=0;for(let w=0;w<u.length;w++){let{points:t,segmentRanges:e}=u[w],i=0===w?Ti(t):!Ti(t),s=os(t.length,d.vertices.length/3,_,i);_=t.length,y.push(...s);for(let r of e){let t=b+2*r.index,e=2*r.count;x.push({index:t,count:e})}b+=2*t.length}return{vertices:f,indices:y,faces:x}}(t);break;case"geometry:mesh":n=function(t){let{vertices:e,indices:i,normals:s,uvs:r}=t,n={vertices:e,indices:i,faces:[]};return Array.isArray(s)&&(n.normals=s),Array.isArray(r)&&(n.uvs=r),n}(t);break;default:return be.warn(`Invalid geometry type ${t.type}.`),o}o=ze(t,n,i),"geometry:plane"!==t.type&&"geometry:cuboid"!==t.type&&"geometry:sphere"!==t.type&&"geometry:extrusion"!==t.type||(null==(r=t.geometries)?void 0:r.length)&&(s.push(t),o=function(t,e,i,s,r){let n={nextId:0},o=t.geometries??[];for(let a of o)e="string"==typeof a||"reference:geometry"===a.type?Wi(e,a,i,s,r):"csg:clip"===a.type?Yi(n,e,a,s):Hi(n,e,a,i,s,r);return e}(t,o,e,i,s),s.pop());let a=[];for(let u of o){let{name:e,vertices:i,indices:s,normals:r,uvs:n,material:o}=u,{position:l,rotation:h,rotationAxis:c}=t,d=Ni({position:l,rotation:h,rotationAxis:c,name:e,vertices:i,indices:s,normals:r,uvs:n,material:o});a.push(d)}o=a;let l=t.normals??"flat";if("flat"===l||"smooth"===l)for(let u of o){let{vertices:t,indices:e}=u;u.normals="flat"===l?zi(t,e):Vi(t,e)}let h=t.uvs??"automatic";if("automatic"==h||"spherical"===h)for(let u of o){let{vertices:t,indices:e}=u;u.uvs="automatic"===h?Ji(t,e):Ki(t,e)}return o}function ls(t){let e,i,s,r={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]};for(let n=0;n<t.length;n+=3)e=t[n],i=t[n+1],s=t[n+2],r.min[0]=Math.min(r.min[0],e),r.max[0]=Math.max(r.max[0],e),r.min[1]=Math.min(r.min[1],i),r.max[1]=Math.max(r.max[1],i),r.min[2]=Math.min(r.min[2],s),r.max[2]=Math.max(r.max[2],s);return r}class hs{constructor(){this.vertices=[],this.edges=[],this.geometryProfile=[]}toJSON(){return{edges:this.edges.map(t=>t.id)}}}function us(t,e){return"integer"===e.type?"number"==typeof t&&Number.isInteger(t):typeof t===e.type&&(!("enum"in e)||e.enum.includes(t))}const cs={"spatialStructure:layout":"layout","layout:space":"space","product:static":"product","product:component":"product","spatialStructure:building":"building","spatialStructure:floor":"floor","element:asset":"element","element:beam":"element","element:casework":"element","element:column":"element","element:door":"element","element:kitchen":"element","element:railing":"element","element:ramp":"element","element:roof":"element","element:slab":"element","element:stairs":"element","element:stairFlight":"element","element:window":"element","element:generic":"element","element:floor":"element","element:ceiling":"element","element:boundaryWall":"element","element:curtainWall":"element","element:opening":"element","element:spaceDivider":"element","element:wall":"element"},ds=(t,e)=>{const i=cs[e];return i||be.error(`Missing custom attribute resource type for node type: "${e}"`),`${t}:${i}`};function ps(t,e){if("boolean"===e.type&&"string"==typeof t){if("true"===t.toLowerCase())return!0;if("false"===t.toLowerCase())return!1}if("number"===e.type&&"string"==typeof t){const e=Number(t);if(!isNaN(e))return e}return null}class fs extends we{constructor(t,e){super(t,"customAttribute:definition"),this.attributes={resourceType:"space",schema:{type:"string"}},e&&this.setAttributes(e)}getInputType(){return function(t){switch(t.type){case"integer":return"Integer";case"boolean":return"Boolean";case"number":return"Number";case"string":return"enum"in t?"Select":"Text"}}(this.attributes.schema)}setAttributes(t){let e=this.attributes;e.resourceType=t.resourceType??e.resourceType,e.updatedAt=t.updatedAt??e.updatedAt,e.description=t.description??e.description,e.schema=function(t){return t.schema?JSON.parse(JSON.stringify(t.schema)):"Text"===t.valueType?{type:"string"}:"Number"===t.valueType?{type:"number"}:"Boolean"===t.valueType?{type:"boolean"}:void 0}(t)}copyForClone(t){super.copyForClone(t),this.attributes=JSON.parse(JSON.stringify(t.attributes))}toJSON(){const t=super.toJSON();let e={resourceType:this.attributes.resourceType,schema:JSON.parse(JSON.stringify(this.attributes.schema))};return void 0!==this.attributes.updatedAt&&(e.updatedAt=this.attributes.updatedAt),void 0!==this.attributes.description&&(e.description=this.attributes.description),t.attributes=e,t}}const ms={"customAttribute:definition":fs};class gs extends we{constructor(t,e){super(t,e),this.customAttributes={}}setCustomAttributes(t,e){let i=null,s=!1;if(null===t&&(this.customAttributes={},s=!0),t&&e)for(const r in t){let n=t[r];if(null===n){delete this.customAttributes[r],s=!0;continue}const o=ds(r,this.type),a=e[o];if(a){if(!us(n,a.attributes.schema)){let t=ps(n,a.attributes.schema);if(null===t){be.error(`Value type mismatch for custom attribute. Received value: "${n}". Expected type: ${a.attributes.schema.type}`),i=`Value type mismatch for custom attribute. Received value: "${n}". Expected type: ${a.attributes.schema.type}`;continue}n=t}this.customAttributes[r]!==n&&(this.customAttributes[r]=n,s=!0)}else i=`Missing custom attribute definition for node key: "${r}", node type: "${this.type}" and definition id: ${o}`}s&&this.emit("node-custom-attributes-change",this),i&&be.error(i)}toJSON(){const t=super.toJSON();return Object.keys(this.customAttributes).length>0&&(t.customAttributes=JSON.parse(JSON.stringify(this.customAttributes))),t}copyForClone(t){super.copyForClone(t),this.customAttributes=JSON.parse(JSON.stringify(t.customAttributes))}}class ys extends gs{constructor(t,e){super(t,e),this.layout=null}}class vs extends ys{constructor(){super(...arguments),this.axisAlignedBoundingBox=null,this.objectAlignedBoundingBox=null,this.boundingBoxContour=null,this.transform=null,this.worldTransform=null}calculateTransform(){return{position:[0,0,0],rotation:0,rotationAxis:[0,1,0]}}getTransform(){return this.transform||(this.transform=this.calculateTransform()),this.transform}calculateWorldTransform(){return this.getTransform()}getWorldTransform(){return this.worldTransform||(this.worldTransform=this.calculateWorldTransform()),this.worldTransform}resetTransform(t=!1){var e;this.transform=null,this.worldTransform=null,this.axisAlignedBoundingBox=null,this.boundingBoxContour=null,t&&(null==(e=this.layout)||e.spatialIndex.addNode(this))}resetBoundingBox(t=!1){var e;this.objectAlignedBoundingBox=null,this.axisAlignedBoundingBox=null,this.boundingBoxContour=null,t&&(null==(e=this.layout)||e.spatialIndex.addNode(this))}resetSpatialIndexing(){this.resetTransform(),this.resetBoundingBox(!0)}calculateBoundingBox(){return{min:[0,0,0],max:[0,0,0]}}getBoundingBox(t=!1){this.objectAlignedBoundingBox||(this.objectAlignedBoundingBox=this.calculateBoundingBox());const{min:e,max:i}=this.objectAlignedBoundingBox;return{min:e,max:i,transform:t?this.getTransform():this.getWorldTransform()}}getAxisAlignedBoundingBox(){return this.axisAlignedBoundingBox||(this.axisAlignedBoundingBox=function({min:t,max:e,transform:i}){if(0===i.rotation)return{min:pi(t,i.position),max:pi(e,i.position)};{let s=Ai(i.position,i.rotation,i.rotationAxis);const r=[[...t],[...e],[t[0],t[1],e[2]],[e[0],e[1],t[2]]];for(const t of r)bt(t,t,s);return ls(r.flat())}}(this.getBoundingBox())),this.axisAlignedBoundingBox}calculateBoundingBoxContour(t=!1){const{min:[e,,i],max:[s,,r],transform:n}=this.getBoundingBox(t),{position:[o,,a],rotation:l}=n;let h=[[e,i],[s,i],[s,r],[e,r]];return(o||a||l)&&(h=Oi(h,{position:[o,a],rotation:l})),h}getBoundingBoxContour(){return this.boundingBoxContour||(this.boundingBoxContour=this.calculateBoundingBoxContour()),this.boundingBoxContour}}class xs extends vs{}class bs extends xs{constructor(t,e,i){super(t,"spatialGraph:vertex"),this.position=[0,0],this.edges=[],this.position[0]=e,this.position[1]=i}sortVertexEdges(){let t=[];for(let e of this.edges){let i=this===e.vertices[0]?e.vertices[1]:e.vertices[0],s=si([i.position[0]-this.position[0],i.position[1]-this.position[1]]);t.push({edge:e,edgeAngle:s})}t.sort((t,e)=>t.edgeAngle-e.edgeAngle),this.edges=t.map(t=>t.edge)}calculateTransform(){return{position:[this.position[0],0,this.position[1]],rotation:0,rotationAxis:[0,1,0]}}addEdge(t){this.edges.push(t),this.sortVertexEdges(),this.emit("vertex-add-edge",this,t)}removeEdge(t){let e=this.edges.indexOf(t);if(e>-1){let t=this.edges.splice(e,1)[0];this.emit("vertex-remove-edge",this,t)}else be.error(`Vertex does not reference edge ${t.id}.`)}setPosition(t,e){this.position[0]=t,this.position[1]=e,this.edges.length>0&&(this.layout.spatialGraph.graphChanged=!0),this.resetSpatialIndexing(),this.emit("vertex-set-position",this)}resetSpatialIndexing(){super.resetSpatialIndexing();const t=/* @__PURE__ */new Set;for(const e of this.edges){e.resetSpatialIndexing();for(const i of e.spaces)i&&t.add(i)}for(const e of t)e.resetSpatialIndexing()}toJSON(){return{...super.toJSON(),position:[...this.position]}}}function _s(t,e,i,s,r=!1){if(e.layout)return be.warn(`${s} ${e.id} already part of layout ${e.layout.id}.`),!1;if(i[e.id])return be.error(`${s} ${e.id} already registered in layout.`),!1;let n=t.spaceGraph;if(n&&n.nodesById[e.id])return be.error(`${s} ${e.id} already registered in space graph.`),!1;if(e.type.startsWith("space:")){let t=e;if(t.slabs.length>0)return be.warn(`Detached space ${t.id} references boundary slab elements.`),!1}else if(e.type.startsWith("element:")){let n=e;if(r&&n.parent)return be.warn(`${s} ${n.id} already a child of ${s} ${n.parent.id}.`),!1;for(let e of n.elements)if(!_s(t,e,i,s,!1))return!1}return!0}function ws(t,e){if(e.layout=t,t.elementsById[e.id])return void be.error(`Element ${e.id} already registered.`);t.elementsById[e.id]=e;const i=t.elementsByType[e.type];i||(be.warn(`unrecognized layout element type: ${e.type}`),t.elementsByType[e.type]=[]),i.push(e);let s=t.spaceGraph;s&&("element:asset"===e.type&&e.product&&!s.productsById[e.product.id]&&s.insertProduct(e.product),s.registerNode(e),s.emit("element-create",e));for(let r of e.elements)ws(t,r)}function Ps(t,e,i){for(let o of e.elements)Ps(t,o,e);if(t.elementsById[e.id]!==e)return void be.error(`Entry ${e.id} in 'elements stored by ID' record does not contain this object.`);delete t.elementsById[e.id];const s=t.elementsByType[e.type],r=null==s?void 0:s.indexOf(e);if(!s||-1===r)return void be.error(`element ${e.id} not found in 'elements stored by type' record.`);s.splice(r,1);let n=t.spaceGraph;n&&(n.unregisterNode(e),n.emit("element-delete",e,i)),e.layout=null}function Es(t){return"object"==typeof t&&null!==t}function Ts(t){return Es(t)&&!function(t){return Array.isArray(t)||ArrayBuffer.isView(t)}(t)}function As(t,e,i,s){Ts(t)&&Ts(e)||be.error("Both arguments must be objects.");let{onNewKeys:r,copyScopes:n,cloneObjects:o}=s,a=Object.keys(e);for(let l of a){if(r){let{allow:e,excludedScopes:s}=r;if(e===(!!s&&s.includes(i))&&!(l in t)){be.warn(`Key '${l}' not found in scope ${i}, skipped.`);continue}}let a=e[l],h=t[l];if(Es(a)){let e=`${i}.${l}`;!(null==n?void 0:n.includes(e))&&Ts(h)?As(h,a,e,s):t[l]=o?JSON.parse(JSON.stringify(a)):a}else t[l]=a}}function Is(t,e,i={onNewKeys:{allow:!1,excludedScopes:[]},copyScopes:[],cloneObjects:!0}){let s;i.onNewKeys?(s=i.onNewKeys,s.allow=i.onNewKeys.allow??!1,s.excludedScopes=i.onNewKeys.excludedScopes??[]):s={allow:!1,excludedScopes:[]},As(t,e,"",{onNewKeys:s,copyScopes:i.copyScopes??[],cloneObjects:i.cloneObjects??!0})}function Ss(t,e){t.name=e.name??t.name,t.customId=e.customId??t.customId}function Cs(t,e,i){t.setCustomAttributes(e.customAttributes,i)}function Ms(t){let e=t.getEdges();return 1===e.length?e[0].id:e.map(t=>t.id)}function Os(t){let e;switch(t.type){case"element:ceiling":case"element:floor":e=function(t){let e=[];for(let i of t.boundaries){let t=i.toJSON();e.push(t)}return{id:t.id,type:t.type,boundaries:e,parameters:{height:t.parameters.height,elevation:t.parameters.elevation,materials:{...t.parameters.materials}}}}(t);break;case"element:boundaryWall":e=function(t){let e=[];for(let s of t.boundaries){let t=s.toJSON();e.push(t)}let i=JSON.parse(JSON.stringify(t.parameters.surfaces));return{id:t.id,type:t.type,boundaries:e,parameters:{height:t.parameters.height,elevation:t.parameters.elevation,surfaces:i,materials:{...t.parameters.materials}}}}(t);break;case"element:curtainWall":e={id:(n=t).id,type:n.type,edge:Ms(n)};break;case"element:spaceDivider":e={id:(r=t).id,type:r.type,edge:Ms(r)};break;case"element:wall":e=function(t){let{width:e,height:i,offset:s,elevation:r,materials:n}=t.parameters;return{id:t.id,type:t.type,parameters:{width:e,height:i,offset:s,elevation:r,materials:{...n}},edge:Ms(t)}}(t);break;case"element:opening":e=function(t){let{position:e,dimensions:i,materials:s}=t.parameters;return{id:t.id,type:t.type,parameters:{position:[...e],dimensions:[...i],materials:{...s}}}}(t);break;case"element:asset":e={id:(i=t).id,type:i.type,position:[...i.position],rotation:i.rotation,rotationAxis:i.rotationAxis,product:null==(s=i.product)?void 0:s.id,geometries:JSON.parse(JSON.stringify(i.geometries))};break;case"element:beam":case"element:casework":case"element:column":case"element:door":case"element:generic":case"element:kitchen":case"element:railing":case"element:ramp":case"element:roof":case"element:slab":case"element:stairs":case"element:stairFlight":case"element:window":e=function(t){let e={id:t.id,type:t.type,position:[...t.position],parameters:JSON.parse(JSON.stringify(t.parameters)),rotation:t.rotation,rotationAxis:t.rotationAxis};return"element:generic"!==t.type&&"element:asset"!==t.type||(e.geometries=JSON.parse(JSON.stringify(t.geometries))),e}(t);break;default:return void be.warn(`Unknown element type '${t.type}, skipping element.`)}var i,s,r,n,o,a;if(o=e,""!==(a=t).name&&(o.name=a.name),""!==a.customId&&(o.customId=a.customId),function(t,e){e.customAttributes===Object(e.customAttributes)&&Object.keys(e.customAttributes).length>0&&(t.customAttributes=e.customAttributes)}(e,t),t.elements.length){e.elements=[];for(let i of t.elements){let t=Os(i);t&&e.elements.push(t)}}return e}class Ns extends vs{constructor(){super(...arguments),this.parent=null,this.elements=[],this.geometries=[]}insertElement(t){let e=this.layout;e&&!_s(e,t,e.elementsById,"Element",!0)||(t.parent=this,this.elements.push(t),e&&ws(e,t))}get isExternal(){if(this.parent)return this.parent.isExternal;const t=this.getSpaces().flatMap(t=>t?[t]:[]);return!t.length||t[0].isExternal}resetTransform(t=!1){super.resetTransform(t);for(const e of this.elements)e.resetTransform(t)}resetBoundingBox(t=!1){super.resetBoundingBox(t);for(const e of this.elements)e.resetBoundingBox(t)}removeElement(t){if(t.parent!==this)return void be.warn(`Element ${t.id} not a child of element ${this.id}.`);let e=this.elements.indexOf(t);if(-1===e)return void be.error(`Element ${t.id} not found in parent ${this.id}.`);let i=t.parent;t.parent=null,this.elements.splice(e,1),t.layout&&Ps(t.layout,t,i)}copyForClone(t){super.copyForClone(t),this.parameters=JSON.parse(JSON.stringify(t.parameters)),this.geometries=JSON.parse(JSON.stringify(t.geometries))}setParameters(t){Is(this.parameters,t,{onNewKeys:{allow:!1},cloneObjects:!0}),this.resetBoundingBox(),this.emit("element-parameters-change",this)}getSpaces(){return this.parent?this.parent.getSpaces():[]}toJSON(){return Os(this)}}function Ls(t,e,i){let s=t.getAxisLength(),r=[];for(let n of t.elements)if("element:opening"===n.type){let t=n.parameters.position[0],o=t/s,a=(t+n.parameters.dimensions[0])/s;i?e>=o&&e<a&&r.push(n):e>o&&e<a&&r.push(n)}return r}class Rs extends Ns{constructor(t,e,i){super(t,e),ye(this,ae),this.edges=[],this.vertices=[],this.boundingBoxTransform=null,this.edgesChanged=!1,this.setEdges(i)}setEdges(t){var e,i;if(!t.length)return this.edges=[],this.vertices=[],void xe(this,ae,le).call(this);if(1===t.length)return this.edges=[t[0]],this.vertices=[t[0].vertices[0],t[0].vertices[1]],void xe(this,ae,le).call(this);const s=function(t){var e;const i=/* @__PURE__ */new Map;for(const s of t)for(const t of s.vertices)i.has(t)||i.set(t,[]),null==(e=i.get(t))||e.push(s);return i}(t),r=[];let n,o;for(const[h,u]of s.entries())if(1===u.length){n=u[0];const t=n.vertices.find(t=>t!==h);if(2!==(null==(e=s.get(t))?void 0:e.length))return void be.error("Edge sequence is not continuous");r.push(h,t),o=t;break}if(!n||!o)return void be.error("Unable to find start of edge sequence");const a=[n];let l=n;for(;a.length<t.length;){const t=o&&(null==(i=s.get(o))?void 0:i.find(t=>t!==l));if(!t)return void be.error("Edge sequence is not continuous");if(a.includes(t))return void be.error("Duplicate Edge in sequence",t.id,l.id);const e=t.vertices.find(t=>t!==o);r.push(e),a.push(t),o=e,l=t}this.edges=a,this.vertices=r,xe(this,ae,le).call(this)}getEdges(){return[...this.edges]}getVertices(){return xe(this,ae,he).call(this),[...this.vertices]}getStartVertex(){return xe(this,ae,he).call(this),this.vertices.at(0)}getEndVertex(){return xe(this,ae,he).call(this),this.vertices.at(-1)}getAxisPoints(){const t=this.getStartVertex(),e=this.getEndVertex();return t&&e?[t.position,e.position]:[]}getAxisLength(){const[t,e]=this.getAxisPoints();return t&&e?oi(di(t,e)):0}getEdgeAtLinearPosition(t){if(t<0||t>1)return;if(1===this.edges.length)return this.edges[0];let e=this.getAxisLength();if(!e)return;let i=this.vertices[0].position;for(let s=0;s<this.vertices.length-1;s++){if(ai(i,this.vertices[s+1].position)/e>=t)return this.edges[s]}}getEdgesAtLinearSegment(t,e){if(t>e)return[];if(1===this.edges.length)return[this.edges[0]];let i=this.getAxisLength();if(!i)return[];let s=[],r=this.vertices[0].position,n=r;for(let o=0;o<this.vertices.length-1;o++){let a=this.vertices[o+1].position,l=ai(r,n)/i,h=ai(r,a)/i;(t<=l&&e>=h||t>=l&&t<h||e>l&&e<=h)&&s.push(this.edges[o]),n=a}return s}resetTransform(){this.boundingBoxTransform=null,this.objectAlignedBoundingBox=null,super.resetTransform()}getBoundingBox(){this.objectAlignedBoundingBox||(this.objectAlignedBoundingBox=this.calculateBoundingBox());const{min:t,max:e}=this.objectAlignedBoundingBox;return this.boundingBoxTransform||(this.boundingBoxTransform=this.calculateBoundingBoxTransform()),{min:t,max:e,transform:this.boundingBoxTransform}}calculateBoundingBoxTransform(){const[t,e]=this.getAxisPoints();if(!t||!e)return super.calculateTransform();const i={rotation:-(yi(t,e)/Math.PI*180)};return{position:[t[0],0,t[1]],rotation:i.rotation,rotationAxis:[0,1,0]}}get edge(){return be.warn("Use getEdges() instead of edge"),this.edges[0]||null}getAdjacentElementsByVertex(){let t=[[],[]];for(let e=0;e<this.vertices.length;e++){let i=this.vertices[e].edges.filter(t=>t.element&&t.element.id!==this.id).map(t=>t.element);t[e]=i}return t}getAdjacentSpacesBySide(){let t=[[],[]];for(let e=0;e<2;e++){let i=this.edges.filter(t=>t.spaces[e]).map(t=>t.spaces[e]);t[e]=i}return t}getSpaces(){let t=[];for(let e of this.edges)e.spaces[0]&&t.push(e.spaces[0]),e.spaces[1]&&t.push(e.spaces[1]);return t}getElementsAtLinearPosition(t){return Ls(this,t,!0)}get isExternal(){let t=0,e=0;for(const i of this.getEdges())i.isExternal?t+=i.getLength():e+=i.getLength();return t>=e}}function ks(t){for(let e of t.elements)if("element:door"===e.type){let t=e.parameters;t.hingeSide="right"===t.hingeSide?"left":"right",t.doorSide="side1"===t.doorSide?"side2":"side1"}}ae=/* @__PURE__ */new WeakSet,le=function(){this.edgesChanged=!1,this.resetSpatialIndexing(),this.emit("element-edges-change",this)},he=function(){this.edgesChanged&&this.edges.length&&this.setEdges(this.edges)};class Bs extends xs{constructor(t,e,i){super(t,"spatialGraph:edge"),this.spaces=[void 0,void 0],this.boundaryWalls=[null,null],this.element=null,this.vertices=[e,i]}getPoints(){return[this.vertices[0].position,this.vertices[1].position]}getLength(){return ai(...this.getPoints())}get isExternal(){return this.spaces.some(t=>!t||t.isExternal)}setVertices(t,e){if(t===e)return void be.warn("Cannot set both edge vertices to the same vertex.");let i,s,r=this.vertices[0],n=this.vertices[1];this.vertices[0]=t,this.vertices[1]=e,r!==t?(r.removeEdge(this),t.addEdge(this),i=!0):i=!1,n!==e?(n.removeEdge(this),e.addEdge(this),s=!0):s=!1,this.layout.spatialGraph.graphChanged=!0,this.element&&(this.element.edgesChanged=!0),this.resetSpatialIndexing(),(i||s)&&this.emit("edge-set-vertices",this,{previousVertices:[r,n]})}resetSpatialIndexing(){super.resetSpatialIndexing(),this.element&&this.element.resetSpatialIndexing()}calculateBoundingBox(){const[t,e]=this.getPoints();return{min:[Math.min(t[0],e[0]),0,Math.min(t[1],e[1])],max:[Math.max(t[0],e[0]),0,Math.max(t[1],e[1])]}}setVerticesByIds(t,e){let i=this.layout.spatialGraph,s=i.verticesById[t];if(!s)return void be.error(`Cannot find vertex ${t}.`);let r=i.verticesById[e];r?this.setVertices(s,r):be.error(`Cannot find vertex ${e}.`)}canSplit(t,e={}){let{minimumLength:i}=e;if(void 0!==i){if(t<0||t>1)return!1;let[e,s]=this.getPoints(),r=li(e,s,t),n=oi(di(r,e)),o=oi(di(r,s));if(n<i||o<i)return!1}else if(t<=0||t>=1)return!1;if(this.element){let[e,i]=this.getPoints(),s=li(e,i,t),[r]=this.element.getAxisPoints();if(!r)return!1;let n=this.element.getAxisLength(),o=ai(r,s)/n;return 0===Ls(this.element,o,!1).length}return!0}split(t,e={},i=!1){var s,r,n;let o=this.layout.spatialGraph,a=this.vertices[0],l=this.vertices[1],h=null==(s=this.element)?void 0:s.getAxisLength(),u=null==(n=null==(r=this.element)?void 0:r.getStartVertex())?void 0:n.position,[c,d]=this.getPoints(),p=li(c,d,t),f=e.vertexId??(this.layout.debugIds?o.debugVertexCount.toString():Ut()),m=o.verticesById[f]??o.createVertex(f,p[0],p[1]);this.setVertices(a,m);let g=e.edgeId??o.getEdgeId(),y=o.createEdge(g,m,l);if(y.spaces[0]=this.spaces[0],y.spaces[1]=this.spaces[1],y.boundaryWalls[0]=this.boundaryWalls[0],y.boundaryWalls[1]=this.boundaryWalls[1],this.element&&e.elementId&&h&&u){let i=ai(u,p)/h,s=this.element.getEdges(),r=s.indexOf(this)+1,n=[y,...s.splice(r)];this.element.setEdges(s);let o=e.elementId??this.layout.getElementId(this.element),a=this.layout.createElement(this.element.type,o,n);a.parameters=JSON.parse(JSON.stringify(this.element.parameters));let l=ai(u,p),c=[...this.element.elements];for(let e of c)if("element:opening"===e.type){let s=e.parameters.position[0],r=s/h,n=(s+e.parameters.dimensions[0])/h;i<=r?(e.parameters.position[0]=r*h-l,this.element.removeElement(e),a.insertElement(e)):t<n&&be.warn(`Opening ${e.id} overlaps split position.`)}}else if(this.element){const t=this.element.getEdges();this.element.setEdges([...t,y]),y.element=this.element}if(i)for(let v of y.spaces){if(!v)continue;let{boundary:t}=v.getBoundaryFromEdge(this);if(t){let e,i=t.vertices.indexOf(a),s=t.vertices.indexOf(l);e=0===i&&s===t.vertices.length-1?s:0===s&&i===t.vertices.length-1||i<s?i:s,t.vertices.splice(e+1,0,m),t.edges=[];for(let r=0;r<t.vertices.length;r++){let e=r,i=r<t.vertices.length-1?r+1:0,s=t.vertices[e],n=t.vertices[i],a=o.getEdgeFromVertices(s,n);a?t.edges.push(a):be.error(`Cannot find edge with vertices ${s.id} and ${n.id}.`)}}else be.error(`Edge ${this.id} not found in space boundary.`)}for(let v of y.boundaryWalls){if(!v)continue;let t,e=v.boundaries[0],i=e.vertices.indexOf(a),s=e.vertices.indexOf(l);t=0===i&&s===e.vertices.length-1?s:0===s&&i===e.vertices.length-1||i<s?i:s,e.vertices.splice(t+1,0,m),e.edges=[];for(let r=0;r<e.vertices.length;r++){let t=r,i=r<e.vertices.length-1?r+1:0,s=e.vertices[t],n=e.vertices[i],a=o.getEdgeFromVertices(s,n);a?e.edges.push(a):be.error(`Cannot find edge with vertices ${s.id} and ${n.id}.`)}}return{vertex:m,edge:y,element:undefined}}canMerge(t){if(this.element&&!t.element||!this.element&&t.element)return!1;let e,i=this.vertices[0],s=this.vertices[1],r=t.vertices[0],n=t.vertices[1];if(i===r)e=[s,i,n];else if(i===n)e=[s,i,r];else if(s===r)e=[i,s,n];else{if(s!==n)return!1;e=[i,s,r]}if(0!==gi(e[0].position,e[1].position,e[2].position))return!1;let o=e[1];return!(!o.edges.includes(this)||!o.edges.includes(t))}merge(t,e=!1){var i;if(this.element&&!t.element||!this.element&&t.element)return void be.warn("Either none or both edges must have an element, cannot merge.");let s,r,n=this.layout.spatialGraph,o=this.vertices[0],a=this.vertices[1],l=t.vertices[0],h=t.vertices[1];if(o===l)s=[h,o,a],r=!0;else if(o===h)s=[l,o,a],r=!1;else if(a===l)s=[o,a,h],r=!1;else{if(a!==h)return void be.warn(`Edge ${this.id} does not share a vertex with edge ${t.id}, cannot merge.`);s=[o,a,l],r=!0}let u=s[0].position,c=s[1].position;if(0!==gi(u,c,s[2].position))return void be.warn(`Edges ${this.id} and ${t.id} are not collinear, cannot merge.`);let d=s[1];if(d.edges.includes(this)&&d.edges.includes(t)||be.error(`Common vertex ${d.id} edge list does not contain either one or both edges, cannot merge.`),t.element&&r&&function(t){let e=t.getAxisLength();for(let i of t.elements){if("element:opening"!==i.type)continue;let t=i.parameters;t.position[0]=e-(t.position[0]+t.dimensions[0]),ks(i)}}(t.element),this.setVertices(s[0],s[2]),this.element&&this.element===t.element){const e=this.element.getEdges(),i=e.indexOf(t);e.splice(i,1),this.element.setEdges(e),t.element=null}else if(this.element&&t.element){const e=t.element.getEdges(),s=e.indexOf(t);e.splice(s,1);let r=[...this.element.getEdges(),...e];this.element.setEdges(r),t.element.setEdges([t]);for(const t of r)t.element=this.element;let n=null==(i=this.element.getStartVertex())?void 0:i.position;if(!n)return;let o=ai(c,n),a=[...t.element.elements];for(let i of a){if("element:opening"!==i.type)continue;t.element.removeElement(i),this.element.insertElement(i),i.parameters.position[0]+=o}}if(e)for(let p of t.spaces){if(!p)continue;let{boundary:e,edgeIndex:i}=p.getBoundaryFromEdge(t);if(e){e.edges.splice(i,1);let t=e.vertices.indexOf(s[1]);t>-1?e.vertices.splice(t,1):be.error(`Cannot find vertex ${s[1].id} in space ${p.id}`)}else be.error(`Cannot find edge ${t.id} in space ${p.id}.`)}for(let p of t.boundaryWalls){if(!p)continue;let e=p.boundaries[0],i=e.edges.indexOf(t);if(i>-1){e.edges.splice(i,1);let t=e.vertices.indexOf(s[1]);t>-1?e.vertices.splice(t,1):be.error(`Cannot find vertex ${s[1].id} in boundary wall ${p.id}`)}else be.error(`Cannot find edge ${t.id} in boundary wall ${p.id}.`)}t.spaces[0]=null,t.spaces[1]=null,t.boundaryWalls[0]=null,t.boundaryWalls[1]=null,n.removeEdge(t),0===d.edges.length&&n.removeVertex(d)}toJSON(){const t=this.vertices[0],e=this.vertices[1];return{...super.toJSON(),vertices:[t.id,e.id]}}}const Fs={usage:"generic",program:"none"};function Ds(t,e){const i=e.parent,s=i.getAxisLength(),{position:r,dimensions:n}=e.parameters,o=r[0]/s,a=(r[0]+n[0])/s;return i.getEdgesAtLinearSegment(o,a).some(e=>e.spaces[0]===t||e.spaces[1]===t)}class Us extends vs{constructor(t,e){super(t,"layout:space"),ye(this,ue),ve(this,ue,null),this.boundaries=[],this.slabs=[],this.attributes={...Fs},this.boundaries=e,this.geometry={polygons:[]}}copyForClone(t){super.copyForClone(t),this.attributes=JSON.parse(JSON.stringify(t.attributes)),this.geometry=JSON.parse(JSON.stringify(t.geometry))}setId(t){if(t===this.id)return;let e=this.layout;if((null==e?void 0:e.spacesById[t])||(null==e?void 0:e.elementsById[t])||(null==e?void 0:e.annotationsById[t]))return void be.error(`ID ${t} already in use in layout ${e.id}.`);if(e&&e.spacesById[this.id]!==this)return void be.error(`Entry ${this.id} in 'spaces stored by ID' record does not contain space ${this.id}.`);let i=this.spaceGraph;if(null==i?void 0:i.nodesById[t])return void be.error(`ID ${t} already in use in space graph object.`);if(i&&i.nodesById[this.id]!==this)return void be.error(`Entry ${this.id} in 'nodes stored by ID' record does not contain space ${this.id}.`);let s=this.id;this.id=t,e&&(delete e.spacesById[s],e.spacesById[this.id]=this),i&&(delete i.nodesById[s],i.nodesById[this.id]=this),this.emit("node-id-change",this,s)}setAttributes(t){this.attributes.usage=t.usage??this.attributes.usage,this.attributes.program=t.program??this.attributes.program,this.emit("space-attributes-change",this)}get isExternal(){return["balcony","terrace","buildingOpening"].includes(this.attributes.usage)}calculateArea(){let t=this.geometry.polygons;if(0===t.length)return be.error(`Geometry has not been computed for space ${this.id}.`),0;let e=Pi(t[0]);for(let i=1;i<t.length;i++){e-=Pi(t[i])}return e}getArea(){return null===ge(this,ue)&&ve(this,ue,this.calculateArea()),ge(this,ue)}getAdjacentSpaces(t,{connectivity:e}={}){var i;let s=null==(i=t.nodeMap.get(this))?void 0:i.get("graph:adjacentTo");if(!s)return[];if(void 0===e)return Array.from(s);{let i=0===e?2:2*e;return Array.from(s).filter(s=>{let r=t.findShortestPath("graph:connectedTo",s,this,{depthLimit:i});return!!(null==r?void 0:r.length)&&(0!==e||"element:spaceDivider"===r[1].type)})}}getElements(t){let e=t&&(Array.isArray(t)?t:[t]),i=[],s=this.layout.getElementList();for(let r of s){if(e&&!e.includes(r.type))continue;let t;switch(r.type){case"element:ceiling":case"element:floor":t=r.space===this;break;case"element:boundaryWall":break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":t=r.getEdges().some(t=>t.spaces[0]===this||t.spaces[1]===this);break;case"element:opening":t=Ds(this,r);break;case"element:door":case"element:window":t=Ds(this,r.parent);break;default:{let e,i=r;if(i.parent){let t=i.parent;for(;t.parent;)t=t.parent;e=t.getTransform().position}else e=i.position;t=bi([e[0],e[2]],this.geometry.polygons);break}}t&&i.push(r)}return i}getBoundaryFromVertex(t){for(let e of this.boundaries){let i=e.vertices.indexOf(t);if(i>-1)return{boundary:e,itemIndex:i}}return{boundary:void 0,itemIndex:-1}}getBoundaryFromEdge(t){for(let e of this.boundaries){let i=e.edges.indexOf(t);if(i>-1)return{boundary:e,edgeIndex:i}}return{boundary:void 0,edgeIndex:-1}}calculateBoundingBox(){var t;const e=W([null==(t=this.boundaries[0])?void 0:t.geometryProfile]);let i=0,s=0;for(const r of this.slabs)"element:floor"===r.type&&(i=r.parameters.elevation),"element:ceiling"===r.type&&(s=r.parameters.elevation);return{min:[e.min[0],i,e.min[1]],max:[e.max[0],s,e.max[1]]}}getAxisAlignedBoundingBox(){const{min:t,max:e}=this.getBoundingBox();return{min:t,max:e}}resetBoundingBox(t){super.resetBoundingBox(t),ve(this,ue,null)}resetSpatialIndexing(){super.resetSpatialIndexing();for(const t of this.slabs)t.resetSpatialIndexing()}attachSlab(t){if(null!==t.space)return void be.warn(`Boundary slab ${t.id} already attached to space ${t.space.id}.`);this.slabs.indexOf(t)>-1?be.warn(`Boundary slab ${t.id} already referenced by space ${this.id}.`):(t.boundaries=this.boundaries,t.space=this,this.slabs.push(t),this.resetBoundingBox())}detachSlab(t){if(t.space!==this)return void be.warn(`Boundary slab ${t.id} not attached to space ${this.id}.`);let e=this.slabs.indexOf(t);-1!==e?(t.space=null,t.boundaries=pr(this.boundaries),this.slabs.splice(e,1),this.resetBoundingBox()):be.warn(`Boundary slab ${t.id} not referenced by space ${this.id}.`)}toJSON(){const{program:t,usage:e}=this.attributes,i={...super.toJSON(),boundaries:[],attributes:{program:t,usage:e}};for(const s of this.boundaries)i.boundaries.push(s.toJSON());return i}}ue=/* @__PURE__ */new WeakMap;class Gs extends Ns{constructor(t,e,i){super(t,e),this.boundaries=pr(i)}calculateBoundingBox(){const t=[0,0,0],e=[0,0,0],i=W([this.boundaries[0].geometryProfile]);return t[0]=i.min[0],e[0]=i.max[0],t[2]=i.min[1],e[2]=i.max[1],"element:floor"===this.type?(t[1]=this.parameters.elevation-this.parameters.height,e[1]=this.parameters.elevation):(t[1]=this.parameters.elevation,e[1]=this.parameters.elevation+this.parameters.height),{min:t,max:e}}}const Xs={top:"#202020",bottom:"#000000",side1:"asm:basic-wall",side2:"asm:basic-wall",join1:"asm:basic-wall",join2:"asm:basic-wall"},Ws={width:.15,height:3,offset:0,elevation:0,materials:{...Xs}};class Ys extends Rs{constructor(t,e){super(t,"element:wall",e);for(const i of e)i.element=this;this.parameters=JSON.parse(JSON.stringify(Ws)),this.geometryProfile={valid:!0,skipped:!1,selfIntersecting:!1,sidePoints1:[],sidePoints2:[],joinPoints1:[],joinPoints2:[],points:[]}}copyForClone(t){super.copyForClone(t),this.geometryProfile=JSON.parse(JSON.stringify(t.geometryProfile))}setParameters(t){super.setParameters(t)}calculateBoundingBox(){const t=[0,0,0],e=[0,0,0],[i,s]=this.getAxisPoints();if(!i||!s)return super.calculateBoundingBox();const r=ai(i,s),{width:n,offset:o}=this.parameters,a=-.5*n+o,l=a+n,h=W([[[0,a],[r,a],[r,l],[0,l]]]);return t[0]=h.min[0],e[0]=h.max[0],t[2]=h.min[1],e[2]=h.max[1],t[1]=this.parameters.elevation,e[1]=this.parameters.elevation+this.parameters.height,{min:t,max:e}}}const Hs={"element:ceiling":{height:.2,elevation:Ws.elevation+Ws.height,materials:{top:"#808080",bottom:"asm:basic-ceiling",sides:"asm:basic-wall"}},"element:floor":{height:.2,elevation:0,materials:{top:"asm:basic-floor",bottom:"#808080",sides:"asm:basic-wall"}}};class $s extends Gs{constructor(t,e,i){super(t,e,i);let s=Hs[this.type];this.parameters=JSON.parse(JSON.stringify(s)),this.space=null}setParameters(t){super.setParameters(t)}getSpaces(){return null===this.space?[]:[this.space]}}function js(t,e){var i;let s,r=t.vertices.map(t=>t.position),n=[];for(let o of t.edges){if("element:wall"!==(null==(i=o.element)?void 0:i.type))continue;let t=o.element.geometryProfile.points;n.push(t)}if(0===n.length)s=[r];else if(e){s=z([r],Y(n))}else s=Y([r,...n]);return s=s.filter(t=>K(t)>1e-7),0===s.length?(be.warn("No valid polygons, returning boundary polygon."),r):(s=Q(s,.001),s=s.filter(t=>t.length>0),0===s.length?(be.warn("No valid polygons after filtering, returning boundary polygon."),r):(s.length>1&&(be.warn(`Result has ${s.length} polygons, returning largest one.`),s=s.sort((t,e)=>K(e)-K(t))),s[0]))}function zs(t,e){var i;let s=[js(e.boundaries[0],!0)];for(let o=1;o<e.boundaries.length;o++){s=z(s,[js(e.boundaries[o],!1)])}let{edges:r}=t.spatialGraph,n=[];for(let o of r){if(o.spaces[0]!==e||o.spaces[1]!==e||"element:wall"!==(null==(i=o.element)?void 0:i.type))continue;let[t,r]=o.getPoints();if(bi(li(t,r,.5),s)){let t=o.element.geometryProfile.points;n.push(t)}}n.length>0&&(s=z(s,n)),s.sort((t,e)=>{let i=K(t);return K(e)-i}),e.geometry.polygons=s}function Vs(t,e){return new Array(e-t).fill(void 0).map((e,i)=>t+i)}function qs(t){return`${t.type.split(":")[1]}Geometry-${t.id.substring(0,8)}`}function Js(t){let e;switch(t.type){case"curve:rectangle":e=4;break;case"curve:polygon":e=t.points.length;break;case"curve:polygonWithHoles":e=t.polygons.reduce((t,e)=>t+Js({type:"curve:polygon",points:e}),0);break;case"curve:composite":e=t.segments.reduce((t,e)=>t+Js(e),0);break;case"curve:polyline":e=t.points.length-1;break;case"curve:circle":case"curve:arc":case"curve:line":e=1}return e}function Ks(){return Ge([Math.random(),Math.random(),Math.random()])}function Zs(t,e=!1){let{materials:i,height:s,elevation:r}=t.parameters,n="element:floor"===t.type?-s:0,o=[];for(let d=1;d<t.boundaries.length;d++){let e=t.boundaries[d].geometryProfile.slice();o.push(e)}o=Y(o);let a=t.boundaries[0].geometryProfile.slice(),l=r+n,h={id:`boundarySlabGeometry-${t.id}-boundary`,type:"geometry:extrusion",position:[0,l,0],height:s,profile:{type:"curve:polygonWithHoles",polygons:[a,...o]},geometries:[]},u={top:[0],bottom:[1],sides:Vs(2,2+a.length)},c={top:e?Ks():i.top,bottom:i.bottom,sides:i.sides};h.surfaces=u,h.materials=c,t.geometries=[{type:"reference:geometry",geometry:h}],t.emit("geometry-update",t)}function Qs(t){for(let e=0;e<t.boundaries.length;e++){const i=t.boundaries[e];for(const s of i.edges){const r=s.vertices[0],n=s.vertices[1],o=i.vertices.indexOf(r),a=i.vertices.indexOf(n);let l,h;if(l=0===o?1===a:o===i.vertices.length-1?0===a:a-o===1,h=0===e?l?1:0:l?0:1,null===s.spaces[h])s.spaces[h]=t;else{const t=0===h?"left":"right";be.error(`Edge ${s.id} already references a space on its ${t} side.`)}}}}function tr(t){for(const e of t.boundaries)for(const i of e.edges)i.spaces[0]||null!==i.boundaryWalls[0]?i.spaces[1]||null!==i.boundaryWalls[1]?be.error(`Edge ${i.id} referenced by more than two adjacent nodes.`):i.boundaryWalls[1]=t:i.boundaryWalls[0]=t}function er(t,e){let i=t.spatialGraph;for(let s=0;s<e.edges.length;s++){let t=e.edges[s],r=i.edgesById[t.id];r?e.edges[s]=r:i.insertEdge(t)}lr(e)}function ir(t,e){if(0!==e.boundaries.length){for(let i of e.boundaries)er(t,i);switch(e.type){case"element:boundaryWall":tr(e);break;case"element:ceiling":case"element:floor":{let i=function(t,e){for(const i of t.spaces){if(i.boundaries.length!==e.length)continue;let t=0;for(;t<i.boundaries.length;){if(!hr(i.boundaries[t],e[t]))break;t++}if(t===i.boundaries.length)return cr(i,[{boundaries:e}])?i:void 0}return}(t,e.boundaries);i?i.attachSlab(e):be.warn(`Matching space not found for boundary slab element ${e.id}.`);break}}}else be.warn(`Boundary slab element ${e.id} does not specify boundaries.`)}function sr(t,e){let i=t.spatialGraph;const s=e.getEdges(),r=new Set(s);let n=!1;for(let o of s){let t=i.edgesById[o.id];t?(n=!0,r.delete(o),r.add(t)):i.insertEdge(o)}n&&e.setEdges(Array.from(r)),function(t){for(const e of t.getEdges())null===e.element?e.element=t:e.element!==t&&be.error(`Edge ${e.id} referenced by more than one edge element.`)}(e)}function rr(t){var e;switch(t.type){case"element:boundaryWall":case"element:ceiling":case"element:floor":!function(t){switch(t.type){case"element:boundaryWall":for(let e of t.boundaries)for(let i of e.edges)i.boundaryWalls[0]===t&&(i.boundaryWalls[0]=null),i.boundaryWalls[1]===t&&(i.boundaryWalls[1]=null);break;case"element:ceiling":case"element:floor":{let e=t.space;e?e.detachSlab(t):be.warn(`Boundary slab element ${t.id} not attached to a space.`);break}}}(t);break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":!function(t){for(const e of t.getEdges())e.element=null}(t);break;case"element:asset":null==(e=t.product)||e.instances.delete(t)}}function nr(t){const e=[];for(const i of t.boundaries){const t=[];for(const e of i.vertices)t.push(e.position);e.push(t)}return e}function or(t){let e=[];if(0===t.length)return e;if(1===t.length){let i=t[0];return e.push(i.vertices[0]),e.push(i.vertices[1]),e}for(let i=0;i<t.length;i++){let s=t[i],r=t[(i+1)%t.length],n=s.vertices[0],o=s.vertices[1],a=r.vertices[0],l=r.vertices[1];if(n===a||n===l)e.push(o);else{if(o!==a&&o!==l)return void be.warn(`Could not add edge ${s.id} to current path.`);e.push(n)}}return e}function ar(t){let e=[];for(let i=0;i<t.length-1;i++){let s=t[i],r=t[i+1];for(let t of s.edges)if(r.edges.indexOf(t)>-1){e.push(t);break}}return e}function lr(t){let e=or(t.edges);if(!e)return!1;if(t.vertices=e,t.geometryProfile=t.vertices.map(t=>t.position),!Ti(t.geometryProfile)){let{vertices:e,edges:i,geometryProfile:s}=t;e.reverse(),s.reverse();{i.reverse();let t=e[e.length-1],s=i[0];s.vertices[0]!==t&&s.vertices[1]!==t||(e.pop(),e.unshift(t))}}return!0}function hr(t,e,i){if(t.edges.length!==e.edges.length)return!1;const s=function(t,e){let i=0;for(const s of t.edges)for(const t of e.edges)if(s.id===t.id){i++;break}return i}(t,e);let r;return r=s===t.edges.length,r}function ur(t,e,i){if(t.length!==e.length)return!1;for(let s=0;s<t.length;s++){if(!hr(t[s],e[s]))return!1}return!0}function cr(t,e,i=!1){const s=.01;if(!i){const i=t.boundaries.map(t=>t.geometryProfile),r=e.map(t=>t.boundaries.map(t=>t.geometryProfile)),n=Z(i),o=r.map(t=>Z(t)).reduce((t,e)=>t+e,0);if(Math.abs(n-o)>s)return!1}const r=e.map(t=>[t.boundaries[0].geometryProfile]),{polygons:n}=j(r,.01),{polygons:o}=j(n,-.01);if(0===o.length)return be.warn(`No union polygon, cannot match space ${t.id}.`),!1;if(o.length>1)return be.warn(` Disjoint union area, cannot match space ${t.id}.`),!1;const a=o[0][0],l=t.boundaries[0].geometryProfile,h=V([[l]],[[a]]).polygons,u=V([[a]],[[l]]).polygons,c=h.length?Z(h[0]):0,d=u.length?Z(u[0]):0;return c<s&&d<s}function dr(t){let e=new hs;return e.vertices=[...t.vertices],e.edges=[...t.edges],e.geometryProfile=JSON.parse(JSON.stringify(t.geometryProfile)),e}function pr(t){let e=[];for(let i of t){let t=dr(i);e.push(t)}return e}function fr(t,e,i){for(let s of t.edges)s.spaces[0]===e?s.spaces[0]=i:s.spaces[1]===e?s.spaces[1]=i:be.warn(`Edge ${s.id} not in space ${e.id} boundary.`)}function mr(t,e,i,s){let r=function(t,e,i,s){let r=t.vertices,n=Math.min(e,i),o=Math.max(e,i),a=o-n+1,l=r.length-a+2;if(a<3||l<3)return be.warn("Cannot split boundary, both fragments should have three or more vertices."),[];let h=r.slice(0,n+1),u=r.slice(n,o+1),c=r.slice(o,r.length).concat(h),d=u,p=ar(c).concat(s),f=ar(d).concat(s),m=c.map(t=>t.position),g=d.map(t=>t.position),y=new hs;y.vertices=c,y.edges=p,y.geometryProfile=m;let v=new hs;return v.vertices=d,v.edges=f,v.geometryProfile=g,[y,v]}(t.boundaries[0],e,i,s);if(!r)return void be.warn(`Could not split outer boundary of space ${t.id}.`);let n=[r[0]],o=[r[1]];for(let f=1;f<t.boundaries.length;f++){let e=t.boundaries[f],i=e.vertices[0].position;if(xi(i,r[0].geometryProfile))n.push(e);else{if(!xi(i,r[1].geometryProfile)){be.warn("Inner boundary is not contained by either of the two split boundaries.");continue}o.push(e)}}let a,l,h=t.layout;(null==h?void 0:h.debugIds)?(a=h.getSpaceId(),l=h.getSpaceId()):(a=Ut(),l=Ut());let u=new Us(a,n),c=new Us(l,o);for(let f of n)fr(f,t,u);for(let f of o)fr(f,t,c);for(let f of n)u.geometry.polygons.push(f.geometryProfile);for(let f of o)c.geometry.polygons.push(f.geometryProfile);zs(h,u),zs(h,c);let d=[],p=[];for(let f=0;f<t.slabs.length;f++){let e,i,s=t.slabs[f];if(null==h?void 0:h.debugIds){let t="element:ceiling"===s.type?"ceiling":"floor";e=`${t}-${f+1}-in-${a}`,i=`${t}-${f+1}-in-${l}`}else e=Ut(),i=Ut();let r=new $s(e,s.type,n),u=new $s(i,s.type,o);Zs(r,!0),Zs(u,!0),d.push(r),p.push(u)}return{spaces:[u,c],slabs:[d,p]}}function gr(t,e){let{position:i,rotation:s,rotationAxis:r}=t.getTransform(),n=Ai(i,s,r);return e&&ht(n,e,n),n}function yr(t){let e;return t.parent&&(e=yr(t.parent)),gr(t,e)}function vr(t,e){switch(e.type){case"annotation:floorPlanDxf":case"annotation:floorPlanImage":return{name:"annotation",nodes:t.annotations,nodesById:t.annotationsById,nodesByType:t.annotationsByType};case"view:2d":case"view:3d":return{name:"view",nodes:t.views,nodesById:t.viewsById,nodesByType:t.viewsByType}}}class xr{constructor(t){this.vertices=[],this.verticesById={},this.edges=[],this.edgesById={},this.graphChanged=!1,this.debugVertexCount=0,this.debugEdgeCount=0,this.layout=t}emit(t,...e){let i=this.layout.spaceGraph;i&&i.emit(t,...e)}copyForClone(t){this.debugVertexCount=t.debugVertexCount,this.debugEdgeCount=t.debugEdgeCount}deleteVertexAtIndex(t,e){let i=this.vertices[t];if(e){let t=i.edges.slice();for(let s of t){let t=s.vertices[0],r=s.vertices[1];t!==i&&r!==i||this.removeEdge(s,e)}}if(this.vertices.splice(t,1),this.verticesById[i.id]===i)return delete this.verticesById[i.id],i;be.error(`Entry ${i.id} in 'vertices by ID' record does not contain this object.`)}deleteEdgeAtIndex(t,e){let i=this.edges[t];if(i.element&&this.layout.removeElement(i.element),i.vertices[0].removeEdge(i),i.vertices[1].removeEdge(i),e){if(i.spaces[0]!==i.spaces[1]){if(i.spaces[0]){let t=i.spaces[0].slabs;for(let e of t)this.layout.removeElement(e);this.layout.removeSpace(i.spaces[0])}if(i.spaces[1]){let t=i.spaces[1].slabs;for(let e of t)this.layout.removeElement(e);this.layout.removeSpace(i.spaces[1])}}i.boundaryWalls[0]&&this.layout.removeElement(i.boundaryWalls[0]),i.boundaryWalls[1]&&this.layout.removeElement(i.boundaryWalls[1])}if(this.edges.splice(t,1),this.edgesById[i.id]===i)return delete this.edgesById[i.id],this.graphChanged=!0,i;be.error(`Entry ${i.id} in 'edges by id' record does not contain this object.`)}insertVertex(t){if(!_s(this.layout,t,this.edgesById,"Edge"))return;t.layout=this.layout,this.vertices.push(t),this.verticesById[t.id]=t;let e=this.layout.spaceGraph;e&&(e.registerNode(t),e.emit("vertex-create",t))}removeVertex(t,e=!1){let i=this.vertices.indexOf(t);if(-1===i)return void be.warn(`Vertex ${t.id} not found.`);this.deleteVertexAtIndex(i,e);let s=this.layout.spaceGraph;return s&&(s.unregisterNode(t),s.emit("vertex-delete",t)),t.layout=null,t}removeVertexAtIndex(t,e=!1){let i=this.vertices[t];if(!i)return void be.warn(`Vertex not found at index ${t}.`);this.deleteVertexAtIndex(t,e);let s=this.layout.spaceGraph;return s&&(s.unregisterNode(i),s.emit("vertex-delete",i)),i.layout=null,i}removeVertexById(t,e=!1){let i=this.verticesById[t];if(i&&i.id===t)return this.removeVertex(i,e);be.error(`Entry ${t} in 'vertices by id' record does not contain this object.`)}insertEdge(t,e=!1){if(!_s(this.layout,t,this.edgesById,"Edge"))return;let i=this.verticesById[t.vertices[0].id],s=this.verticesById[t.vertices[1].id];i?t.vertices[0]=i:this.insertVertex(t.vertices[0]),s?t.vertices[1]=s:this.insertVertex(t.vertices[1]),t.layout=this.layout,this.edges.push(t),this.edgesById[t.id]=t,t.vertices[0].addEdge(t),t.vertices[1].addEdge(t);let r=this.layout.spaceGraph;r&&(r.registerNode(t),r.emit("edge-create",t)),e&&function(t){let e=t.layout,i=t.vertices[0],s=t.vertices[1];for(let r of e.spaces){let n=r.boundaries[0],o=n.vertices.indexOf(i),a=n.vertices.indexOf(s);if(o>-1&&a>-1){t.spaces[0]=r,t.spaces[1]=r;let i=mr(r,o,a,t);if(i){let s=r.slabs.slice();for(let t of s)e.removeElement(t);e.removeSpace(r);let[n,o]=i.spaces,[a,l]=i.slabs;e.insertSpace(n);for(let t of a)e.insertElement(t);e.insertSpace(o);for(let t of l)e.insertElement(t);t.emit("space-split",r,[n,o]),n.emit("geometry-profile-update",n),o.emit("geometry-profile-update",o);for(let t of n.slabs)t.emit("geometry-profile-update",t);for(let t of o.slabs)t.emit("geometry-profile-update",t)}else be.warn(`Failed to split space ${r.id}.`);break}}}(t),this.graphChanged=!0}removeEdge(t,e=!1){let i=this.edges.indexOf(t);if(-1===i)return void be.warn(`Edge ${t.id} not found.`);this.deleteEdgeAtIndex(i,e);let s=this.layout.spaceGraph;return s&&(s.unregisterNode(t),s.emit("edge-delete",t)),t.layout=null,t}removeEdgeAtIndex(t,e=!1){let i=this.edges[t];if(!i)return void be.warn(`Edge not found at index ${t}.`);this.deleteEdgeAtIndex(t,e);let s=this.layout.spaceGraph;return s&&(s.unregisterNode(i),s.emit("edge-delete",i)),i.layout=null,i}removeEdgeById(t,e=!1){let i=this.edgesById[t];if(i&&i.id===t)return this.removeEdge(i,e);be.error(`Entry ${t} in 'edges by id' record does not contain this object.`)}getEdgeFromVertices(t,e){let i=t.edges,s=e.edges;for(let r of i)for(let t of s)if(r===t)return r}getVertexId(t){return this.layout.debugIds?(t??"vertex-")+this.debugVertexCount:Ut()}getEdgeId(t){return this.layout.debugIds?(t??"edge-")+this.debugEdgeCount:Ut()}createVertex(t,e,i){let s=new bs(t,e,i);return this.insertVertex(s),s}createEdge(t,e,i,s=!1){let r=new Bs(t,e,i);return this.insertEdge(r,s),r}createEdgeByVertexIds(t,e,i,s=!1){let r=this.verticesById[e],n=this.verticesById[i];return this.createEdge(t,r,n,s)}toJSON(){let t=[];for(let i of this.vertices){let e=i.toJSON();t.push(e)}let e=[];for(let i of this.edges){let t=i.toJSON();e.push(t)}return{vertices:t,edges:e}}}const br={height:3,elevation:0,surfaces:{top:[0],bottom:[1],sides:"..."},materials:{top:"#202020",bottom:"#000000",sides:"asm:basic-wall"}};class _r extends Gs{constructor(t,e){super(t,"element:boundaryWall",e),this.parameters=JSON.parse(JSON.stringify(br))}setParameters(t){super.setParameters(t)}}const wr={materials:{}};class Pr extends Rs{constructor(t,e){super(t,"element:curtainWall",e);for(const i of e)i.element=this;this.parameters=JSON.parse(JSON.stringify(wr))}setParameters(t){super.setParameters(t)}}const Er={materials:{}};class Tr extends Rs{constructor(t,e){super(t,"element:spaceDivider",e);for(const i of e)i.element=this;this.parameters=JSON.parse(JSON.stringify(Er))}setParameters(t){super.setParameters(t)}calculateBoundingBox(){const[t,e]=this.getAxisPoints();if(!t||!e)return super.calculateBoundingBox();return{min:[0,0,-.01],max:[ai(t,e),0,.01]}}}class Ar extends Ns{constructor(t,e){super(t,e)}}function Ir(t,e,i=0){let{width:s,offset:r,elevation:n}=t.parameters,[o,a]=t.getAxisPoints();if(!o||!a)return{position:[0,0,0],rotation:0};let l=di(a,o),h=oi(l),u=li(o,a,e.parameters.position[0]/h);u=ii(u,ci(ui(hi(l)),-.5*s+r-i));let c=e.parameters.position[1]+n;return{position:[u[0],c,u[1]],rotation:180*-si(di(a,o))/Math.PI}}function Sr(t,e,i,s){const r=.001;let n=s.parameters.dimensions[0],o=s.parameters.dimensions[1],{width:a,elevation:l}=e.parameters,{position:[h,u,c],rotation:d}=Ir(e,s,r),p=s.parameters.materials,f={id:i,type:"geometry:cuboid",position:[h,u-r-l,c],rotation:d,dimensions:[n,o+r,a+.002],surfaces:{top:[0],bottom:[1],frontBack:[2,4],sides:[3,5]}},m={top:p.top,bottom:p.bottom,frontBack:"#FFFFFF",sides:p.sides};f.materials=m;let g=e.geometries[0].geometry;g.geometries??(g.geometries=[]),g.geometries.push({type:"csg:subtract",geometry:f}),s.emit("geometry-update",s)}function Cr(t,e){let i,s={},r=Vs(0,e);for(let[n,o]of Object.entries(t))if("string"==typeof o)"..."===o?i=n:be.warn("Invalid surface definition string.");else if(Array.isArray(o)){s[n]=[];for(let t of o){if(t<0||t>=e){be.warn(`Face index ${t} out of range when defining surface ${n}.`);continue}let i=r.indexOf(t);-1!==i?(s[n].push(t),r.splice(i,1)):be.warn(`Face index ${t} already assigned when defining surface ${n}.`)}}else be.warn("Invalid surface definition.");return i&&r.length>0&&(s[i]=r),s}function Mr(t){let e,{surfaces:i,materials:s}=t.parameters;for(let r=0;r<t.boundaries.length;r++){let n=t.boundaries[r],o=t.parameters.elevation,a=or(n.edges);if(!a)return void be.warn(`Could not create geometry for boundary wall ${t.id}.`);let l=a.map(t=>t.position),h=0===r?"boundary":"hole-"+r,u={id:`boundaryWallGeometry-${t.id}-${h}`,type:"geometry:extrusion",position:[0,o,0],height:t.parameters.height,profile:{type:"curve:polygon",points:l},geometries:[]};u.surfaces=Cr(i,2+l.length),u.materials=JSON.parse(JSON.stringify(s)),0===r?(e=u,t.geometries=[{type:"reference:geometry",geometry:u}]):e.geometries.push({type:"csg:subtract",geometry:u})}t.emit("geometry-update",t)}function Or(t){let{length:e,height:i,frameThickness:s,frameDepth:r,doorAngle:n,hingeSide:o,doorSide:a,doorType:l,materials:h}=t.parameters,u="right"===o,c=[e/2,r/2],d=qs(t),p=.05,f=[],m=(180-Math.min(180,Math.max(0,n)))/180,g=(r-p)/2,y=e-2*s,v=i-s;switch(l){case"singleSwing":u?f.push({position:[s-c[0],0,-c[1]],rotation:n,dimensions:[y,v,p]}):f.push({position:[c[0]-s,0,-c[1]],dimensions:[p,v,y],rotation:270-n});break;case"doubleSwing":y=e/2-s,f.push({position:[s-c[0],0,-c[1]],rotation:n,dimensions:[y,v,p]}),f.push({position:[c[0]-s,0,-c[1]],rotation:270-n,dimensions:[p,v,y]});break;case"slidingDoor":y=(e-2*s)*m;let t=u?s-c[0]:c[0]-y-s;f.push({position:[t,0,-c[1]+g],rotation:0,dimensions:[y,v,p]});break;case"garageDoor":f.push({position:[s-c[0],v*(1-m),-c[1]+g],rotation:0,dimensions:[y,v*m,p]});break;case"elevatorDoor":y=(e-2*s)/2-.005,f.push({position:[s-c[0],0,-c[1]+g],rotation:0,dimensions:[y,v,p]}),f.push({position:[0,0,-c[1]+g],rotation:0,dimensions:[y,v,p]})}let x=[];for(let b=0;b<f.length;b++){let{position:t,rotation:e,dimensions:i}=f[b],s={id:d+"-leaf-"+b,type:"geometry:cuboid",position:t,rotation:e,dimensions:i,material:h.leaf};x.push({type:"reference:geometry",position:[c[0],0,c[1]],rotation:"side2"===a?180:0,geometry:s})}return x}function Nr(t,e,i){let s=qs(t),{stepCount:r,stepHeight:n,angle:o,radius:a,width:l,circulation:h}=i,u=a-l,c=a-l/2,d=Math.PI*o/180*c/r/(u+l/2),p=[0,n,0],f=180/Math.PI*d,m=0;"right"===h&&(f=-f,m=180);let g=function(t,e,i){let{stepThickness:s,stepHeight:r,angle:n,width:o,stepCount:a,radius:l,circulation:h}=i,u=l-o/2,c=l-o,d=Math.PI*n/180*u/a/(c+o/2),p="right"===h,f=r,m=c,g=(p?-1:1)*Math.sin(d)*c,y=r-s,v=Math.cos(d)*c,x=-s,b=c+o,_=(p?-1:1)*Math.sin(d)*(c+o),w=Math.cos(d)*(c+o),P=[0,f,m,0,0,m,g,y,v,g,f,v,0,x,m,0,f,b,0,0,b,_,y,w,_,f,w,0,x,b],E=[0,8,3,0,5,8,0,3,2,0,2,1,1,2,4,0,6,5,0,1,6,5,7,8,5,6,7,6,9,7,2,7,4,4,7,9,8,7,3,7,2,3];if(p)for(let T=0;T<E.length;T+=3){let t=E[T+1];E[T+1]=E[T+2],E[T+2]=t}return{id:t,type:"geometry:mesh",vertices:P,indices:E,rotation:0,surfaces:{top:[0,1],base:[2,3,4,5,6,7,8,9,10,11,12,13]},materials:{top:e.tread,base:e.steps}}}(s,e,i);return{type:"reference:geometry",position:{type:"vector3:range",range:{start:[0,0,0],step:p,count:r}},rotation:{type:"number:range",range:{start:m,step:f,count:r}},geometry:g}}function Lr(t){let{width:e,height:i,materials:s}=t.parameters;const r=Math.max(1,Math.round(i/.17)),n={height:i,width:e,stepCount:r,stepHeight:i/r,stepThickness:.1};let o;if("straight"===t.parameters.stairFlightType){let{length:e}=t.parameters;o=function(t,e,i){let{stepCount:s,width:r,stepHeight:n,length:o,stepThickness:a}=i,l=o/s,h=[l,n,0],u=function(t,e,i){let{riser:s,tread:r,width:n,thickness:o}=i;return{id:t,type:"geometry:extrusion",rotation:90,rotationAxis:[1,0,0],height:n,profile:{type:"curve:polygon",points:[[0,0],[0,o],[r,o-s],[r,-s],[0,-s]]},surfaces:{top:[5],base:[0,1,2,3,4,6]},materials:{top:e.tread,base:e.steps}}}(qs(t),e,{tread:l,riser:n,width:r,thickness:a});return{type:"reference:geometry",position:{type:"vector3:range",range:{start:[0,0,0],step:h,count:s}},geometry:u}}(t,s,{...n,length:e})}else{let{radius:e,angle:i,circulation:r}=t.parameters;o=Nr(t,s,{...n,radius:e,angle:i,circulation:r})}t.geometries=[o],t.emit("geometry-update",t)}function Rr(t,e=!1){let{sidePoints1:i,sidePoints2:s,joinPoints1:r,joinPoints2:n,points:o}=t.geometryProfile;if(0===o.length)return;let a="wallGeometry-"+t.id,l={id:a,type:"geometry:extrusion",position:[0,t.parameters.elevation,0],height:t.parameters.height,profile:{type:"curve:composite",segments:[{type:"curve:polyline",points:i},{type:"curve:polyline",points:r},{type:"curve:polyline",points:s},{type:"curve:polyline",points:n}]}},h=t.parameters.materials,u={top:[0],bottom:[1],side1:[2],side2:[4]},c={top:e?Ks():h.top??Xs.top,bottom:h.bottom??Xs.bottom,side1:h.side1??Xs.side1,side2:h.side2??Xs.side2},[d,p]=function(t){let e=[!1,!1],i=[t.getStartVertex(),t.getEndVertex()];for(let s=0;s<i.length;s++){let t=i[s];t&&(t.edges.filter(t=>{var e;return"element:wall"===(null==(e=t.element)?void 0:e.type)}).map(t=>t.element).length>0?e[s]=!0:be.error(`Vertex ${t.id} not referencing edge that references it.`))}return e}(t);d&&(u.join1=[3],c.join1=h.join1??Xs.join1),p&&(u.join2=[5],c.join2=h.join2??Xs.join2),l.surfaces=u,l.materials=c,t.geometries=[{type:"reference:geometry",geometry:l}];for(let f=0;f<t.elements.length;f++){let e=t.elements[f];if("element:opening"!==e.type)continue;let i=a+"-opening-"+(f+1);Sr(t.layout,t,i,e)}t.emit("geometry-update",t)}function kr(t){switch(t.type){case"element:asset":case"element:beam":case"element:curtainWall":case"element:opening":case"element:ramp":case"element:roof":case"element:spaceDivider":case"element:stairs":break;case"element:casework":!function(t){let{length:e,width:i,height:s,counterHeight:r,materials:n}=t.parameters,o=Math.min(.6,e),a=Math.floor(e/o),l=e%o,h=i-.02,u=s-r,c=.02,d=qs(t),p=[],f=t.elements;for(let y of f)if("product"in y&&y.product){let{min:t,max:e}=y.product.attributes.boundingBox,i=fi(t,[0,.01,0]),s=fi(e,i),r=pi(i,y.position);p.push({id:d+"-subtraction-"+y.id.substring(0,8),type:"geometry:cuboid",position:[...r],dimensions:s})}let m=[];r>0&&m.push({id:d+"-counter",type:"geometry:cuboid",position:[0,u,0],dimensions:[e,r,i],material:n.counter}),m.push({id:d+"-doors",type:"geometry:cuboid",position:{type:"vector3:range",range:{start:[c,c,h],step:[o,0,0],count:a}},dimensions:[o-.04,u-.04,c],material:n.cabinetDoors}),l>.04&&m.push({id:d+"-doors+2",type:"geometry:cuboid",position:[a*o+c,c,h],dimensions:[l-.04,u-.04,c],material:n.cabinet});let g={id:d+"-cabinet",type:"geometry:cuboid",position:[0,0,0],dimensions:[e,u,h],geometries:[...m.map(t=>({type:"reference:geometry",geometry:t})),...p.map(t=>({type:"csg:subtract",geometry:t}))],material:n.cabinet};t.geometries=[{type:"reference:geometry",geometry:g}],t.emit("geometry-update",t)}(t);break;case"element:column":!function(t){let{profile:e,height:i,materials:s}=t.parameters,r=qs(t),n=[0,0,0];"curve:rectangle"===e.type&&(n=[-e.dimensions[0]/2,0,-e.dimensions[1]/2]);let o={id:r,type:"geometry:extrusion",position:n,profile:e,height:i},a=Js(e);o.surfaces={top:[0],bottom:[1],sides:Vs(2,2+a)},o.materials={top:s.top,bottom:s.bottom,sides:s.sides},t.geometries=[{type:"reference:geometry",geometry:o}],t.emit("geometry-update",t)}(t);break;case"element:ceiling":case"element:floor":Zs(t);break;case"element:boundaryWall":Mr(t);break;case"element:door":!function(t){let{height:e,length:i,frameThickness:s,frameDepth:r,materials:n}=t.parameters,o=qs(t),a={id:o+"-frame-top",type:"geometry:cuboid",position:[0,e-s,0],rotation:0,dimensions:[i,s,r],material:n.frame},l={id:o+"-frame-side",type:"geometry:cuboid",position:{type:"vector3:list",list:[[0,0,0],[i-s,0,0]]},rotation:0,dimensions:[s,e-s,r],material:n.frame};t.geometries=[{type:"reference:geometry",geometry:a},{type:"reference:geometry",geometry:l},...Or(t)],t.emit("geometry-update",t)}(t);break;case"element:generic":!function(t){let{profile:e,height:i,materials:s}=t.parameters;if("none"===e)return;let r=Js(e),n={id:qs(t),type:"geometry:extrusion",position:[0,0,0],profile:e,height:i,surfaces:{top:[0],bottom:[1],sides:Vs(2,2+r)},materials:{top:s.top,bottom:s.bottom,sides:s.sides}};t.geometries=[{type:"reference:geometry",geometry:n}],t.emit("geometry-update",t)}(t);break;case"element:railing":!function(t){let e,{height:i,length:s,width:r,segmentCount:n,segmentLength:o,materials:a}=t.parameters,l=.01;e=o&&o>0?Math.max(Math.round(s/o),1):n&&n>0?n:Math.max(Math.round(s/.12),1);let h=(s-l)/e,u=qs(t),c={id:u+"-horizontal",type:"geometry:cuboid",position:{type:"vector3:list",list:[[0,i-l,-r/2],[0,0,-r/2]]},rotation:0,dimensions:[s,l,r],material:a.surface},d={id:u+"-vertical",type:"geometry:cuboid",position:{type:"vector3:range",range:{start:[0,l,-r/2],step:[h,0,0],count:e+1}},rotation:0,dimensions:[l,i-.02,r],material:a.surface};t.geometries=[{type:"reference:geometry",geometry:c},{type:"reference:geometry",geometry:d}],t.emit("geometry-update",t)}(t);break;case"element:slab":!function(t){let{profile:e,height:i,materials:s}=t.parameters,r={id:qs(t),type:"geometry:extrusion",position:[0,0,0],profile:e,height:i},n=Js(e);r.surfaces={top:[0],bottom:[1],sides:Vs(2,2+n)},r.materials={top:s.top,bottom:s.bottom,sides:s.sides},t.geometries=[{type:"reference:geometry",geometry:r}],t.emit("geometry-update",t)}(t);break;case"element:stairFlight":Lr(t);break;case"element:wall":Rr(t);break;case"element:window":!function(t){let{panelCount:e,panelLength:i,height:s,length:r,frameThickness:n,frameDepth:o,materials:a}=t.parameters,l=qs(t),h={id:l,type:"geometry:cuboid",position:{type:"vector3:list",list:[[0,s-n,0],[0,0,0]]},rotation:0,dimensions:[r,n,o],material:a.frame},u=[[0,n,0]],c=r-n;if(e&&(i=c/e),i&&i>n){let t=i;for(;t<c;)u.push([t,n,0]),t+=i}u.push([r-n,n,0]);let d={id:l+"-vertical",type:"geometry:cuboid",position:{type:"vector3:list",list:u},rotation:0,dimensions:[n,s-2*n,o],material:a.frame},p={id:l+"-glass",type:"geometry:extrusion",position:[n,n,o/2],rotation:0,height:s-2*n,profile:{type:"curve:rectangle",dimensions:[r-2*n,.01]},material:a.panel};t.geometries=[{type:"reference:geometry",geometry:h},{type:"reference:geometry",geometry:d},{type:"reference:geometry",geometry:p}],t.emit("geometry-update",t)}(t)}for(let e of t.elements)kr(e)}const Br={position:[0,0],dimensions:[1,2],materials:{top:"#FFFFFF",bottom:"#FFFFFF",sides:"#FFFFFF"}};class Fr extends Ar{constructor(t){super(t,"element:opening"),this.parameters=JSON.parse(JSON.stringify(Br))}getTransform(){var t;if("element:wall"!==(null==(t=this.parent)?void 0:t.type)){const t=this.parent?`Parent of element ${this.id} is not a wall.`:`Element ${this.id} does not have a parent.`;return be.error(t),{position:[0,0,0],rotation:0,rotationAxis:[0,1,0]}}let{position:e,rotation:i}=Ir(this.parent,this);return{position:e,rotation:i,rotationAxis:[0,1,0]}}get position(){return this.getTransform().position}get rotation(){return this.getTransform().rotation}setParameters(t){let e=!!t.position,i=!!t.dimensions;if(super.setParameters(t),this.emit("element-parameters-change",this),e||i){let t=this.parent;if(t&&kr(t),i)for(let e of this.elements)kr(e);this.resetSpatialIndexing()}}getBoundingBox(t=!1){const{dimensions:e}=this.parameters,i=this.parent,s=(null==i?void 0:i.parameters.width)||0;return{min:[0,0,0],max:[e[0],e[1],s],transform:t?this.getTransform():this.getWorldTransform()}}getSpaces(){if(this.parent){return this.parent.getSpaces().filter(t=>Ds(t,this))}return be.error(`Element ${this.id} does not have a parent.`),[]}get isExternal(){const t=this.parent;if(!t)return super.isExternal;const[e]=t.getAxisPoints();if(!e)return super.isExternal;const i=t.getAxisLength(),{position:s,dimensions:r}=this.parameters,n=s[0]/i,o=(s[0]+r[0])/i,a=t.getEdgesAtLinearSegment(n,o);if(1===a.length)return a[0].isExternal;let l=0,h=0;for(const u of a){const[t,s]=u.getPoints().map(t=>ai(e,t)/i).sort((t,e)=>t-e),r=(o>s?s:o)-(n>t?n:t);u.isExternal?l+=r:h+=r}return l>=h}}class Dr extends Ns{constructor(t,e){super(t,e),this.position=[0,0,0],this.rotation=0,this.rotationAxis=[0,1,0]}copyForClone(t){super.copyForClone(t),this.position=[...t.position],this.rotation=t.rotation,this.rotationAxis=[...t.rotationAxis]}setPosition(t){this.position=[...t],this.resetTransform(!0),this.emit("element-transform-change",this)}setRotation(t,e){this.rotation=t,e&&(this.rotationAxis=[...e]),this.resetTransform(!0),this.emit("element-transform-change",this)}setTransform(t,e,i){this.position=[...t],this.rotation=e,i&&(this.rotationAxis=[...i]),this.resetTransform(!0),this.emit("element-transform-change",this)}getSpaces(){if(this.parent)return this.parent.getSpaces();let t=[this.position[0],this.position[2]];for(let e of this.layout.spaces)if(bi(t,e.geometry.polygons))return[e];return[]}calculateTransform(){return{position:[...this.position],rotation:this.rotation,rotationAxis:[...this.rotationAxis]}}calculateWorldTransform(){if(!this.parent)return this.getTransform();let t=yr(this),{position:e,rotation:i,rotationAxis:s}=Ii(t);return 0===s[0]&&s[1]<0&&0===s[2]&&(s=[0,1,0],i=-i),{position:e,rotation:i,rotationAxis:s}}calculateBoundingBox(){const t=[0,0,0],e=[0,0,0];if("length"in this.parameters&&(e[0]=this.parameters.length),"height"in this.parameters&&(e[1]=this.parameters.height),"width"in this.parameters?e[2]=this.parameters.width:"frameDepth"in this.parameters&&(e[2]=this.parameters.frameDepth),"radius"in this.parameters&&(t[0]=t[2]=-this.parameters.radius,e[0]=e[2]=this.parameters.radius),"profile"in this.parameters&&"none"!==this.parameters.profile)switch(this.parameters.profile.type){case"curve:rectangle":{let[i,s]=this.parameters.profile.dimensions;e[0]=i,e[2]=s,"element:column"===this.type&&(t[0]=-i/2,e[0]=i/2,t[2]=-s/2,e[2]=s/2);break}case"curve:circle":t[0]=t[2]=-this.parameters.profile.radius,e[0]=e[2]=this.parameters.profile.radius;break;case"curve:polygon":let i=W([this.parameters.profile.points]);t[0]=i.min[0],e[0]=i.max[0],t[2]=i.min[1],e[2]=i.max[1]}return{min:t,max:e}}setParameters(t){super.setParameters(t),kr(this)}}const Ur={materials:{}};class Gr extends Dr{constructor(t){super(t,"element:asset"),this.product=null,this.parameters=JSON.parse(JSON.stringify(Ur))}get isComponentInstance(){var t;return"product:component"===(null==(t=this.product)?void 0:t.type)}get isComponentInstanceChild(){var t;return"element:asset"===(null==(t=this.parent)?void 0:t.type)&&this.parent.isComponentInstance}setParameters(t){super.setParameters(t)}setProduct(t){this.product=t,this.product.instances.add(this),this.resetBoundingBox(),this.emit("node-property-change",this,"product"),this.emit("geometry-update",this)}calculateBoundingBox(){if(!this.product)return super.calculateBoundingBox();const{min:t,max:e}=this.product.attributes.boundingBox;return{min:t,max:e}}}const Xr={length:2,width:.1,height:.2,materials:{top:"#202020",bottom:"#000000",sides:"asm:basic-wall"}};class Wr extends Dr{constructor(t){super(t,"element:beam"),this.parameters=JSON.parse(JSON.stringify(Xr))}setParameters(t){super.setParameters(t)}}const Yr={length:2,height:.7,width:.6,counterHeight:.03,materials:{cabinet:"asm:cabinet_paint_white",cabinetDoors:"asm:cabinet_paint_white",counter:"asm:cabinet_paint_white"}};class Hr extends Dr{constructor(t){super(t,"element:casework"),this.parameters=JSON.parse(JSON.stringify(Yr))}setParameters(t){super.setParameters(t)}}const $r={type:"curve:circle",radius:.1},jr={"curve:circle":{...$r},"curve:rectangle":{type:"curve:rectangle",dimensions:[.1,.1]},"curve:polygon":{type:"curve:polygon",points:[[0,0],[.1,0],[.1,.1],[0,.1]]},"curve:polygonWithHoles":{type:"curve:polygonWithHoles",polygons:[[[0,0],[.1,0],[.1,.1],[0,.1]],[[.02,.02],[.02,.08],[.08,.08],[.08,.02]]]}},zr={profile:{...$r},height:3,materials:{top:"#202020",bottom:"#000000",sides:"asm:basic-wall"}};class Vr extends Dr{constructor(t){super(t,"element:column"),this.parameters=JSON.parse(JSON.stringify(zr))}setParameters(t){var e;(null==(e=t.profile)?void 0:e.type)&&t.profile.type!==this.parameters.profile.type&&(this.parameters.profile=JSON.parse(JSON.stringify(jr[t.profile.type]))),super.setParameters(t)}}const qr={length:1,height:2,frameThickness:.05,frameDepth:.1,doorType:"singleSwing",doorAngle:90,hardware:!0,hingeSide:"right",doorSide:"side1",materials:{frame:"asm:doorLeaf-flush-white",leaf:"asm:doorLeaf-flush-white"}};class Jr extends Dr{constructor(t){super(t,"element:door"),this.parameters=JSON.parse(JSON.stringify(qr))}setParameters(t){super.setParameters(t)}calculateBoundingBox(){const t=super.calculateBoundingBox(),{doorType:e,frameThickness:i,frameDepth:s,doorSide:r,length:n}=this.parameters;if("singleSwing"===e||"doubleSwing"===e){const o="singleSwing"===e?n-2*i:n/2-i;"side1"===r?t.min[2]=-o:t.max[2]=s+o}return t}}const Kr={"curve:circle":{type:"curve:circle",radius:.5},"curve:rectangle":{type:"curve:rectangle",dimensions:[1,1]},"curve:polygon":{type:"curve:polygon",points:[[0,0],[1,0],[1,1],[0,1]]},"curve:polygonWithHoles":{type:"curve:polygonWithHoles",polygons:[[[0,0],[1,0],[1,1],[0,1]],[[.25,.25],[.25,.75],[.75,.75],[.75,.25]]]}},Zr={profile:"none",height:0,materials:{top:"#F0F0F0",bottom:"#F0F0F0",sides:"#F0F0F0"}};class Qr extends Dr{constructor(t){super(t,"element:generic"),this.parameters=JSON.parse(JSON.stringify(Zr))}setParameters(t){t.profile&&"none"!==t.profile&&t.profile.type&&"none"!==this.parameters.profile&&this.parameters.profile.type!==t.profile.type&&(this.parameters.profile=JSON.parse(JSON.stringify(Kr[t.profile.type]))),super.setParameters(t)}}const tn="product:static",en={manufacturer:"",categories:[],subCategories:[],thumbnail:"",boundingBox:{min:[0,0,0],max:[0,0,0]},seatCapacity:0,updatedAt:""};class sn extends gs{constructor(t,e){super(t,e),ye(this,ce),this.instances=/* @__PURE__ */new Set,this.attributes=JSON.parse(JSON.stringify(en))}copyForClone(t){super.copyForClone(t),this.attributes=JSON.parse(JSON.stringify(t.attributes))}setAttributes(t){var e,i;let s=this.attributes;s.manufacturer=t.manufacturer??s.manufacturer,s.categories=(null==(e=t.categories)?void 0:e.slice())??s.categories,s.subCategories=(null==(i=t.subCategories)?void 0:i.slice())??s.subCategories,s.thumbnail=t.thumbnail??s.thumbnail,t.boundingBox&&(s.boundingBox.min=[...t.boundingBox.min],s.boundingBox.max=[...t.boundingBox.max]),s.seatCapacity=t.seatCapacity??s.seatCapacity,s.updatedAt=t.updatedAt??s.updatedAt}getBoundingBox(){return this.attributes.boundingBox}toJSON(){const t=super.toJSON();return t.attributes=xe(this,ce,de).call(this),t}}ce=/* @__PURE__ */new WeakSet,de=function(){const t={},e=this.attributes;""!==e.manufacturer&&(t.manufacturer=e.manufacturer),e.categories.length>0&&(t.categories=[...e.categories]),e.subCategories.length>0&&(t.subCategories=[...e.subCategories]),""!==e.thumbnail&&(t.thumbnail=e.thumbnail);let{min:i,max:s}=e.boundingBox;return 1!==i[0]&&-1!==s[0]&&(t.boundingBox={min:[...e.boundingBox.min],max:[...e.boundingBox.max]}),e.seatCapacity>0&&(t.seatCapacity=e.seatCapacity),void 0!==e.updatedAt&&(t.updatedAt=e.updatedAt),t};class rn extends sn{constructor(t){super(t,tn),this.geometries=[]}copyForClone(t){super.copyForClone(t),this.geometries=JSON.parse(JSON.stringify(t.geometries))}toJSON(){return{...super.toJSON(),type:tn,geometries:JSON.parse(JSON.stringify(this.geometries))}}}const nn="product:component";class on extends sn{constructor(t){super(t,nn),this.products=[],this.geometries=[],this.attributes=JSON.parse(JSON.stringify(en))}copyForClone(t){super.copyForClone(t),this.products=JSON.parse(JSON.stringify(t.products))}toJSON(){return{...super.toJSON(),type:nn,products:JSON.parse(JSON.stringify(this.products)),geometries:[]}}setProducts(t){this.products=JSON.parse(JSON.stringify(t))}setInstances(){var t;for(const e of this.instances){if(this.products.length===e.elements.length&&this.products.every((t,i)=>{var s;const r=e.elements[i];return"element:asset"===(null==r?void 0:r.type)&&t.product===(null==(s=r.product)?void 0:s.id)}))for(let i=0;i<this.products.length;i++){const s=this.products[i];if("type"in s.position)continue;if("number"!=typeof s.rotation)continue;const r=e.elements[i];"element:asset"===r.type&&(null==(t=r.product)?void 0:t.id)===s.product&&r.setTransform(s.position,s.rotation)}else{for(let t=e.elements.length-1;t>=0;t--)e.removeElement(e.elements[t]);for(const t of this.products){const i=new Gr(Ut()),s=this.spaceGraph.productsById[t.product];s||be.error(`Product ${t.product} is missing`),i.setProduct(s),"type"in t.position||"number"==typeof t.rotation&&(i.setTransform(t.position,t.rotation),e.insertElement(i))}}}}}function an(t){for(let e=t.elements.length-1;e>=0;e--)t.removeElement(t.elements[e])}function ln(t,e,i){let s=t.elements.filter(t=>t.type===e);for(let r=s.length-1;r>=i;r--)t.removeElement(s[r]);for(let r=0;r<i;r++)if(!s[r]){let i=Ut();s[r]="element:casework"===e?new Hr(i):new Gr(i),t.insertElement(s[r])}return s}function hn(t){let{length:e,width:i,height:s,wallCabinet:r,leftHighCabinetCount:n,rightHighCabinetCount:o,sinkElementSlot:a,materials:l}=t.parameters,h=Math.min(.6,e),u=s-1.5,c=Math.min(e,h*Math.max(n,0)),d=e>c?h*o:0,p=Math.max(e-c-d,0);d=Math.max(e-c-p,0);let f=0;p>0&&(f++,r&&f++),c>0&&f++,d>0&&f++;let m=p>0&&a*h>=c&&a*h<=c+p,g=ln(t,"element:casework",f),y={cabinet:l.cabinet,cabinetDoors:l.cabinetDoors,counter:l.counter};if(p>0){let e=g.shift();if(e){let s=ln(e,"element:asset",m?1:0);if(m){let e=s[0],r=function(t){const e="7f24bd1c-1ebc-4724-8cd4-ca78c7d4a1e5";if(null==t?void 0:t.productsById[e])return null==t?void 0:t.productsById[e];let i=new rn(e);return i.setAttributes({categories:["appliances"],subCategories:["kitchen"],boundingBox:{max:[.54,.21,0],min:[0,-.17,-.47]}}),i.geometries=[{type:"reference:geometry",geometry:{id:"sinkGeometry",type:"geometry:uri",format:"data3d",uri:"015f8f8e-e588-4f51-a342-2930559834ee/201208-0355-60hukz/bf4e4a56-ed95-4b58-a214-4b1a0a84ae0e.gz.data3d.buffer"}}],i}(t.spaceGraph),{min:n,max:o}=r.attributes.boundingBox,l=pi(n,(v=fi(o,n),x=.5,[v[0]*x,v[1]*x,v[2]*x]));l[1]=0;let u=pi([a*h-c,.9,0],[h/2,0,i/2]);r&&(e.setProduct(r),e.setPosition(fi(u,l)))}e.setParameters({length:p,width:i,height:.9,counterHeight:.03,materials:{...y}}),e.setTransform([c,0,0],0)}let s=r&&g.shift();s&&(an(s),s.setParameters({length:p,width:.45,height:u,counterHeight:0,materials:{...y}}),s.setTransform([c,1.5,0],0))}var v,x;let b=c>0&&g.shift();b&&(an(b),b.setParameters({length:c,width:i,height:s,counterHeight:0,materials:{...y}}),b.setTransform([0,0,0],0));let _=d>0&&g.shift();_&&(an(_),_.setParameters({length:d,width:i,height:s,counterHeight:0,materials:{...y}}),_.setTransform([c+p,0,0],0))}const un={length:3,width:.6,height:2.2,wallCabinet:!0,leftHighCabinetCount:1,rightHighCabinetCount:0,sinkElementSlot:-1,cooktopElementSlot:-1,ovenElementSlot:-1,materials:{cabinet:"asm:cabinet_paint_white",cabinetDoors:"asm:cabinet_paint_white",counter:"asm:cabinet_paint_white"}};class cn extends Dr{constructor(t){super(t,"element:kitchen"),this.parameters=JSON.parse(JSON.stringify(un))}setParameters(t,e=!1){super.setParameters(t),e||hn(this),this.emit("element-parameters-change",this)}}const dn={length:2,width:.05,height:1,segmentCount:0,segmentLength:.12,materials:{surface:"#CCCCCC"}};class pn extends Dr{constructor(t){super(t,"element:railing"),this.parameters=JSON.parse(JSON.stringify(dn))}setParameters(t){super.setParameters(t)}}const fn={length:2,width:1,height:.5,materials:{top:"asm:basic-floor",bottom:"asm:basic-wall",sides:"asm:basic-wall"}};class mn extends Dr{constructor(t){super(t,"element:ramp"),this.parameters=JSON.parse(JSON.stringify(fn))}}const gn={materials:{}};class yn extends Dr{constructor(t){super(t,"element:roof"),this.parameters=JSON.parse(JSON.stringify(gn))}}const vn={type:"curve:rectangle",dimensions:[1,1]},xn={"curve:circle":{type:"curve:circle",radius:1},"curve:rectangle":{...vn},"curve:polygon":{type:"curve:polygon",points:[[0,0],[1,0],[1,1],[0,1]]},"curve:polygonWithHoles":{type:"curve:polygonWithHoles",polygons:[[[0,0],[1,0],[1,1],[0,1]],[[.25,.25],[.25,.75],[.75,.75],[.75,.25]]]}},bn={profile:{...vn},height:.1,materials:{top:"asm:basic-floor",bottom:"asm:basic-floor",sides:"asm:basic-wall"}};class _n extends Dr{constructor(t){super(t,"element:slab"),this.parameters=JSON.parse(JSON.stringify(bn))}setParameters(t){var e;(null==(e=t.profile)?void 0:e.type)&&t.profile.type!==this.parameters.profile.type&&(this.parameters.profile=JSON.parse(JSON.stringify(xn[t.profile.type]))),super.setParameters(t)}}const wn={height:3,width:1.2,materials:{steps:"asm:basic-wall",tread:"asm:basic-floor"}},Pn={straight:{stairFlightType:"straight",length:3,...wn},spiral:{stairFlightType:"spiral",angle:270,radius:1.5,circulation:"right",...wn}};class En extends Dr{constructor(t){super(t,"element:stairFlight"),this.parameters=JSON.parse(JSON.stringify(Pn.straight))}setParameters(t){if(t.stairFlightType&&this.parameters.stairFlightType!==t.stairFlightType){let{height:e,materials:i,width:s}=this.parameters;this.parameters={...JSON.parse(JSON.stringify(Pn[t.stairFlightType])),height:e,materials:i,width:s}}super.setParameters(t)}}function Tn(t,e,i){let s=t.elements.filter(t=>t.type===e);for(let r=s.length-1;r>=i;r--)t.removeElement(s[r]);for(let r=0;r<i;r++)if(!s[r]){let i=Ut();s[r]="element:stairFlight"===e?new En(i):new _n(i),t.insertElement(s[r])}return s}const An=.1;const In={height:3,railing:"right",materials:{steps:"asm:basic-wall",tread:"asm:basic-floor",railing:"#CCCCCC"}},Sn={straight:{stairsType:"straight",length:4,width:1.2,...In},straightLanding:{stairsType:"straightLanding",length:4,width:1.2,...In},halfLanding:{stairsType:"halfLanding",length:4,width:2.5,stepWidth:1.2,circulation:"right",...In},quarterLanding:{stairsType:"quarterLanding",length:4,width:2.5,stepWidth:1.2,circulation:"right",...In},twoQuarterLanding:{stairsType:"twoQuarterLanding",length:3,width:4,stepWidth:1.2,circulation:"right",...In},winder:{stairsType:"winder",length:4,width:2.5,stepWidth:1.2,circulation:"right",...In},doubleWinder:{stairsType:"doubleWinder",length:4,width:2.5,stepWidth:1.2,circulation:"right",...In},spiral:{stairsType:"spiral",radius:1.5,angle:270,stepWidth:1.2,circulation:"right",...In},custom:{stairsType:"custom",stepWidth:1.2,...In}},Cn=Sn.straight;class Mn extends Dr{constructor(t){super(t,"element:stairs"),this.parameters=JSON.parse(JSON.stringify(Cn))}setParameters(t,e=!1){if(t.stairsType&&this.parameters.stairsType!==t.stairsType){let{height:e,railing:i,materials:s}=this.parameters;this.parameters={...JSON.parse(JSON.stringify(Sn[t.stairsType])),height:e,railing:i,materials:s}}super.setParameters(t),e||function(t){switch(t.parameters.stairsType){case"straight":{let{length:e,width:i,height:s,materials:r}=t.parameters,[n]=Tn(t,"element:stairFlight",1);Tn(t,"element:slab",0),n.setParameters({stairFlightType:"straight",length:e,width:i,height:s,materials:{steps:r.steps,tread:r.tread}}),n.setTransform([0,0,0],0);break}case"straightLanding":{let{length:e,width:i,height:s,materials:r}=t.parameters,n=(e-i)/2,[o,a]=Tn(t,"element:stairFlight",2),[l]=Tn(t,"element:slab",1);o.setParameters({stairFlightType:"straight",length:n,width:i,height:s/2,materials:{steps:r.steps,tread:r.tread}}),o.setTransform([0,0,0],0),l.setParameters({profile:{type:"curve:rectangle",dimensions:[i,i]},height:An,materials:{top:r.tread,bottom:r.steps,sides:r.steps}}),l.setTransform([n,s/2-An,0],0),a.setParameters({stairFlightType:"straight",length:n,width:i,height:s/2}),a.setTransform([e-n,s/2,0],0);break}case"halfLanding":{let{length:e,width:i,height:s,stepWidth:r,circulation:n,materials:o}=t.parameters,a="right"===n,[l,h]=Tn(t,"element:stairFlight",2),[u]=Tn(t,"element:slab",1);l.setParameters({stairFlightType:"straight",length:e-r,width:r,height:s/2,materials:{steps:o.steps,tread:o.tread}}),l.setTransform([0,0,a?0:-r],0),u.setParameters({profile:{type:"curve:rectangle",dimensions:[r,i]},height:An,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),u.setPosition([e-r,s/2-An,a?0:-i]),h.setParameters({stairFlightType:"straight",length:e-r,width:r,height:s/2,materials:{steps:o.steps,tread:o.tread}}),h.setTransform([e-r,s/2,a?i:-i+r],-180);break}case"quarterLanding":{let{length:e,width:i,height:s,stepWidth:r,circulation:n,materials:o}=t.parameters,a="right"===n,l=e-r,h=i-r,u=l/(l+h)*s,c=h/(l+h)*s,[d,p]=Tn(t,"element:stairFlight",2),[f]=Tn(t,"element:slab",1);d.setParameters({stairFlightType:"straight",length:l,width:r,height:u,materials:{steps:o.steps,tread:o.tread}}),d.setTransform([0,0,a?0:-r],0),f.setParameters({profile:{type:"curve:rectangle",dimensions:[r,r]},height:An,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),f.setPosition([e-r,u-An,a?0:-r]),p.setParameters({stairFlightType:"straight",length:h,width:r,height:c,materials:{steps:o.steps,tread:o.tread}}),a?p.setTransform([e,u,r],-90):p.setTransform([e-r,u,-r],90);break}case"twoQuarterLanding":{let{length:e,width:i,height:s,stepWidth:r,circulation:n,materials:o}=t.parameters,a="right"===n,l=e-r,h=i-2*r,u=l/(2*l+h)*s,c=h/(2*l+h)*s,[d,p,f]=Tn(t,"element:stairFlight",3),[m,g]=Tn(t,"element:slab",2);d.setParameters({stairFlightType:"straight",length:l,width:r,height:u,materials:{steps:o.steps,tread:o.tread}}),d.setTransform([0,0,a?0:-r],0),m.setParameters({profile:{type:"curve:rectangle",dimensions:[r,r]},height:An,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),m.setPosition([e-r,u-An,a?0:-r]),p.setParameters({stairFlightType:"straight",length:h,width:r,height:c,materials:{steps:o.steps,tread:o.tread}}),a?p.setTransform([e,u,r],-90):p.setTransform([e-r,u,-r],90),g.setParameters({profile:{type:"curve:rectangle",dimensions:[r,r]},height:An,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),g.setPosition([e-r,u+c-An,a?i-r:-i]),f.setParameters({stairFlightType:"straight",length:l,width:r,height:u,materials:{steps:o.steps,tread:o.tread}}),f.setTransform([e-r,u+c,a?i:-i+r],-180);break}case"spiral":{let{radius:e,angle:i,height:s,stepWidth:r,circulation:n,materials:o}=t.parameters,a="right"===n,[l]=Tn(t,"element:stairFlight",1);Tn(t,"element:slab",0),l.setParameters({stairFlightType:"spiral",radius:e,angle:i,height:s,width:r,circulation:n,materials:{steps:o.steps,tread:o.tread}}),l.setTransform([0,0,a?e:-e],0);break}}}(this),this.emit("element-parameters-change",this)}calculateBoundingBox(){const t=super.calculateBoundingBox();return"radius"in this.parameters&&(t.min[2]=0,t.max[2]=2*this.parameters.radius,t.min[0]=-this.parameters.radius,t.max[0]=this.parameters.radius),"circulation"in this.parameters&&"left"===this.parameters.circulation&&(t.min[2]=-t.max[2],t.max[2]=0),t}}const On={length:1,height:1.2,frameThickness:.05,frameDepth:.1,panelLength:0,panelCount:1,materials:{frame:"#CCCCCC",panel:"asm:glass"}};class Nn extends Dr{constructor(t){super(t,"element:window"),this.parameters=JSON.parse(JSON.stringify(On))}setParameters(t){super.setParameters(t)}}class Ln extends ys{constructor(){super(...arguments),this.position=[0,0,0],this.rotation=0}copyForClone(t){super.copyForClone(t),this.position=[...t.position],this.rotation=t.rotation,this.parameters=JSON.parse(JSON.stringify(t.parameters))}setTransform(t,e){this.position=[...t],this.rotation=e,this.emit("annotation-transform-change",this)}setParameters(t){Is(this.parameters,t,{onNewKeys:{allow:!1},cloneObjects:!0}),this.emit("annotation-parameters-change",this)}toJSON(){return{...super.toJSON(),position:[...this.position],parameters:JSON.parse(JSON.stringify(this.parameters)),rotation:this.rotation}}}const Rn={uri:"",drawingOrigin:[0,0],drawingUnits:"unitLess",hiddenLayers:[]};class kn extends Ln{constructor(t){super(t,"annotation:floorPlanDxf"),this.parameters=JSON.parse(JSON.stringify(Rn))}setParameters(t){super.setParameters(t)}}class Bn extends ys{copyForClone(t){super.copyForClone(t),this.parameters=JSON.parse(JSON.stringify(t.parameters))}setParameters(t){Is(this.parameters,t,{onNewKeys:{allow:!1},cloneObjects:!0}),this.emit("view-parameters-change",this)}toJSON(){return{...super.toJSON(),parameters:JSON.parse(JSON.stringify(this.parameters))}}}const Fn={style:{background:{fill:"#f7f8fa"},units:"metric",byId:{},byType:{},byAttribute:{program:{},usage:{}}},hidden:[]};class Dn extends Bn{constructor(t){super(t,"view:2d"),this.parameters=JSON.parse(JSON.stringify(Fn))}setParameters(t){var e,i;let{style:s}=t;void 0===(null==s?void 0:s.byId)&&(this.parameters.style.byId={}),void 0===(null==s?void 0:s.byType)&&(this.parameters.style.byType={}),void 0===(null==(e=null==s?void 0:s.byAttribute)?void 0:e.program)&&(this.parameters.style.byAttribute.program={}),void 0===(null==(i=null==s?void 0:s.byAttribute)?void 0:i.usage)&&(this.parameters.style.byAttribute.usage={}),Is(this.parameters,t,{onNewKeys:{allow:!1},copyScopes:[".style.byId",".style.byType",".style.byAttribute.program",".style.byAttribute.usage"],cloneObjects:!0}),this.emit("view-parameters-change",this)}}const Un={position:[0,0,0],normal:[0,0,1],fov:"default",scale:1,lensShiftX:0,lensShiftY:0,projection:"perspective"};class Gn extends Bn{constructor(t){super(t,"view:3d"),this.parameters=JSON.parse(JSON.stringify(Un))}setParameters(t){super.setParameters(t)}}const Xn="relation:group";class Wn extends we{constructor(t){super(t,Xn),this.elements=/* @__PURE__ */new Set}insertElements(t){for(let e of t)this.elements.add(e)}removeElements(t){for(let e of t)this.elements.delete(e)}copyForClone(t){super.copyForClone(t)}toJSON(){const t=super.toJSON();return t.elements=Array.from(this.elements).map(t=>t.id),t}}class Yn extends gs{constructor(t,e){super(t,e)}}function Hn(t,e){e.registerNode(t),function(t,e){let{vertices:i,edges:s}=t.spatialGraph;for(let r of i)e.registerNode(r),e.emit("vertex-create",r);for(let r of s)e.registerNode(r),e.emit("edge-create",r)}(t,e);for(let s of t.spaces)e.registerNode(s);let i=t.getElementList();for(let s of i)e.registerNode(s);for(let s of t.annotations)e.registerNode(s);for(let s of t.views)e.registerNode(s);e.emit("spatial-structure-create",t)}function $n(t,e){e.unregisterNode(t),function(t,e){let{vertices:i,edges:s}=t.spatialGraph;for(let r of i)e.unregisterNode(r),e.emit("vertex-delete",r);for(let r of s)e.unregisterNode(r),e.emit("edge-delete",r)}(t,e);for(let s of t.spaces)e.unregisterNode(s);let i=t.getElementList();for(let s of i)e.unregisterNode(s);for(let s of t.annotations)e.unregisterNode(s);e.emit("spatial-structure-delete",t)}function jn(t,e){e.registerNode(t);for(let i of t.layouts)Hn(i,e);e.emit("spatial-structure-create",t)}function zn(t,e){e.unregisterNode(t);for(let i of t.layouts)$n(i,e);e.emit("spatial-structure-delete",t)}function Vn(t,e,...i){let s;switch(t){case"element:ceiling":case"element:floor":s=new $s(e,t,i[0]);break;case"element:boundaryWall":s=new _r(e,i[0]);break;case"element:curtainWall":s=new Pr(e,i[0]);break;case"element:spaceDivider":s=new Tr(e,i[0]);break;case"element:wall":s=new Ys(e,i[0]);break;case"element:opening":s=new Fr(e);break;case"element:asset":s=new Gr(e);break;case"element:beam":s=new Wr(e);break;case"element:casework":s=new Hr(e);break;case"element:column":s=new Vr(e);break;case"element:door":s=new Jr(e);break;case"element:generic":s=new Qr(e);break;case"element:kitchen":s=new cn(e);break;case"element:ramp":s=new mn(e);break;case"element:roof":s=new yn(e);break;case"element:railing":s=new pn(e);break;case"element:slab":s=new _n(e);break;case"element:stairs":s=new Mn(e);break;case"element:stairFlight":s=new En(e);break;case"element:window":s=new Nn(e)}return s}const qn={uri:"",length:1,width:1};class Jn extends Ln{constructor(t){super(t,"annotation:floorPlanImage"),this.parameters=JSON.parse(JSON.stringify(qn))}setParameters(t){super.setParameters(t)}}function Kn(t,e){let i;switch(t){case"annotation:floorPlanDxf":i=new kn(e);break;case"annotation:floorPlanImage":i=new Jn(e)}return i}function Zn(t,e){let i;switch(t){case"view:2d":i=new Dn(e);break;case"view:3d":i=new Gn(e)}return i}class Qn{constructor(){this.nodeMap=/* @__PURE__ */new Map}addNode(t){return this.nodeMap.has(t)||this.nodeMap.set(t,/* @__PURE__ */new Map),this.nodeMap.get(t)}addEdge(t,e,i){var s,r;let n=this.addNode(e),o=this.addNode(i);n.has(t)||n.set(t,/* @__PURE__ */new Set),o.has(t)||o.set(t,/* @__PURE__ */new Set),null==(s=n.get(t))||s.add(i),null==(r=o.get(t))||r.add(e)}removeNode(t){if(this.nodeMap.has(t)){for(let e of this.nodeMap.get(t))for(let i of e[1])this.removeEdge(e[0],t,i);this.nodeMap.delete(t)}}removeEdge(t,e,i){var s,r,n,o;null==(r=null==(s=this.nodeMap.get(e))?void 0:s.get(t))||r.delete(i),null==(o=null==(n=this.nodeMap.get(i))?void 0:n.get(t))||o.delete(e)}findShortestPath(t,e,i,s={}){var r;let n=[[e]],o=/* @__PURE__ */new Set;for(;n.length>0;){let e=n.shift();if(!e)return null;if(s.depthLimit&&e.length-1>s.depthLimit)return null;let a=e[e.length-1];if(a===i)return e;if(!o.has(a)&&this.nodeMap.has(a)&&(null==(r=this.nodeMap.get(a))?void 0:r.has(t))){o.add(a);for(let i of this.nodeMap.get(a).get(t))n.push([...e,i])}}return null}toJSON(){const t=[],e=[];for(const[i,s]of this.nodeMap.entries()){t.push({id:i.id,type:i.type});for(const[t,r]of s.entries())for(const s of r)i.id<s.id&&e.push({type:String(t),nodes:[i.id,s.id]})}return{nodes:t,edges:e}}}const to=t=>{const e={};for(const i in t)e[i]=[];return e},eo={"element:ceiling":$s,"element:floor":$s,"element:boundaryWall":_r,"element:curtainWall":Pr,"element:spaceDivider":Tr,"element:wall":Ys,"element:opening":Fr,"element:asset":Gr,"element:beam":Wr,"element:casework":Hr,"element:column":Vr,"element:door":Jr,"element:generic":Qr,"element:kitchen":cn,"element:railing":pn,"element:ramp":mn,"element:roof":yn,"element:slab":_n,"element:stairs":Mn,"element:stairFlight":En,"element:window":Nn},io={"annotation:floorPlanDxf":kn,"annotation:floorPlanImage":Jn},so={"view:2d":Dn,"view:3d":Gn};const ro=t=>{const{min:e,max:i}=t.getAxisAlignedBoundingBox();return{id:t.id,type:t.type,minX:e[0],minY:e[2],maxX:i[0],maxY:i[2]}};class no extends Ht{constructor(t){super(),this.nodeIds=/* @__PURE__ */new Set,this.layout=t}find({min:t,max:e,margin:i,types:s}){i??(i=0),e??(e=t);const r={minX:t[0]-i,maxX:e[0]+i,minY:t[1]-i,maxY:e[1]+i},n=this.search(r),o=[];for(const a of n)(null==s?void 0:s.length)&&!(null==s?void 0:s.includes(a.type))||(this.layout.spaceGraph.nodesById[a.id]?o.push(this.layout.spaceGraph.nodesById[a.id]):be.warn(`Indexed node ${a.id} is not part of the layout anymore`));return o}addNode(t){const e=ro(t);this.nodeIds.has(t.id)&&this.remove(e),this.insert(e),this.nodeIds.add(t.id)}removeNode(t){const e=ro(t);this.nodeIds.has(t.id)&&this.remove(e)}remove(t){return this.nodeIds.delete(t.id),super.remove(t,(t,e)=>t.id===e.id),this}}const oo={...eo,"spatialGraph:edge":Bs,"spatialGraph:vertex":bs,"layout:space":Us,"view:2d":Dn,"view:3d":Gn,"annotation:floorPlanDxf":kn,"annotation:floorPlanImage":Jn};class ao extends we{constructor(t,e){super(t,e),this.position=[0,0,0],this.rotation=0,this.rotationAxis=[0,1,0],this.surfaces={},this.materials={},this.boundingBox={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}}class lo extends ao{constructor(t,e){super(t,e),this.normals="generator",this.uvs="generator",this.geometries=[]}}const ho={"geometry:plane":class extends lo{constructor(t){super(t,"geometry:plane"),this.normal=[0,1,0],this.size=1,this.doubleSided=!1}},"geometry:cuboid":class extends lo{constructor(t){super(t,"geometry:cuboid"),this.dimensions=[1,1,1]}},"geometry:sphere":class extends lo{constructor(t){super(t,"geometry:sphere"),this.radius=1}},"geometry:extrusion":class extends lo{constructor(t,e){super(t,"geometry:extrusion"),this.height=1,this.profile=e}},"geometry:mesh":class extends ao{constructor(t){super(t,"geometry:mesh"),this.vertices=[],this.indices=[],this.normals=[],this.uvs=[]}},"geometry:uri":class extends ao{constructor(t){super(t,"geometry:uri"),this.format="data3d",this.uri="",this.normals="smooth"}}},uo={"material:embedded":Se,"material:basic":Me,"material:color":Ee,"material:standard":Ae},co={"product:static":rn,"product:component":on},po={"relation:group":Wn},fo={...oo,...ho,...uo,...co,...po,"spatialStructure:building":null,"spatialStructure:floor":null,"spatialStructure:layout":null};function mo(t,e){t.name=e.name??t.name,t.customId=e.customId??t.customId}function go(t,e){let i;return t.type===nn?(i=new on(t.id),i.products=JSON.parse(JSON.stringify(t.products))):(i=new rn(t.id),i.geometries=JSON.parse(JSON.stringify(t.geometries))),t.attributes&&i.setAttributes(t.attributes),t.customAttributes&&i.setCustomAttributes(t.customAttributes,e),mo(i,t),i}function yo(t){return JSON.parse(JSON.stringify(t))}function vo(t){let e;if(Array.isArray(t)||"string"==typeof t)be.warn("Color literal or standard material reference not allowed in shared resources section.");else if("object"==typeof t)switch(t.type){case Pe:let[i,s,r,n]=function(t){let[e,i,s,r]=[1,1,1,1];return Array.isArray(t)?[e,i,s,r]=Fe(t):"string"==typeof t&&([e,i,s,r]=[1,1,1,1],""===t?be.warn("Empty string not a valid color literal."):t.startsWith("#")?[e,i,s,r]=De(t):t.startsWith("rgb(")?[e,i,s,r]=Ue(t,!1):t.startsWith("rgba(")?[e,i,s,r]=Ue(t,!0):be.warn(`String ${t} not a valid color literal.`)),[e,i,s,r]}(t.value);e=new Ee(t.id,[i,s,r],n);break;case Te:e=new Ae(t.id,t.reference);break;case Ce:e=new Me(t.id),mo(e,t),e.colorDiffuse=[...t.colorDiffuse],t.colorSpecular&&(e.colorSpecular=[...t.colorSpecular]),e.specularCoefficient=t.specularCoefficient??e.specularCoefficient,e.opacity=t.opacity??e.opacity;break;default:e=new Ee(t.id,[1,1,1],1),be.warn(`Unknown material type ${t.type}, creating default material.`)}else be.warn("Material not an array, string or object.");return e}function xo(t,e){let i;if(e.type===Xn){i=new Wn(e.id);let s=[];for(let r of e.elements)t.nodesById[r]?s.push(t.nodesById[r]):be.error(`Element ${r} not found, referenced by relation ${i.id}.`);i.insertElements(s)}return mo(i,e),i}function bo(t){const e=function(t){const{id:e,attributes:{resourceType:i}}=t;return e.endsWith(`:${i}`)?e:`${e}:${i}`}(t),i=new fs(e,t.attributes);return mo(i,t),i}function _o(t,e){!function(t,e){for(let i of e){let e=bo(i);e&&t.insertCustomAttribute(e)}}(t,e.customAttributes||[]),function(t,e){for(let i of e){let e=go(i,t.customAttributesById);t.insertProduct(e)}}(t,e.products),function(t,e){for(let i of e){let e=yo(i);t.insertGeometry(e)}}(t,e.geometries),function(t,e){for(let i of e){let e=vo(i);e&&t.insertMaterial(e)}}(t,e.materials)}function wo(t,e){let i=function(t,e){let i;switch(e.type){case Ho:i=$o.fromJSON(e,{spaceGraph:t,skipInsert:!0});break;case Wo:i=Yo.fromJSON(e,{spaceGraph:t,skipInsert:!0});break;case Go:i=Xo.fromJSON(e,{spaceGraph:t,skipInsert:!0})}return i}(t,e);t.insertSpatialStructure(i)}function Po(t,e){_o(t,e.sharedResources),wo(t,e.spatialStructure),function(t,e){for(let i of e){let e=xo(t,i);e&&t.insertRelation(e)}}(t,e.sharedResources.relations||[])}class Eo{constructor(t){this.products=[],this.productsById={},this.productsByType=to(co),this.customAttributes=[],this.customAttributesById={},this.customAttributesByType=to(ms),this.geometries=[],this.geometriesById={},this.geometriesByType=to(ho),this.materials=[],this.materialsById={},this.materialsByType=to(uo),this.relations=[],this.relationsById={},this.relationsByType=to(po),this.nodes=[],this.nodesById={},this.nodesByType=to(fo),this.spatialStructure=null,this.emitter=new pe.TinyEmitter,this.sourceSchemaVersion=t}getEvents(){return this.emitter.e??{}}copyEvents(t){let e=t.getEvents();for(let[i,s]of Object.entries(e))this.emitter.on(i,s)}deleteNodeAtIndex(t,e,i,s){let r=e[t];if(e.splice(t,1),i[r.id]!==r)return void be.error(`Entry ${r.id} in 'nodes stored by ID' record does not contain this object.`);delete i[r.id];let n=s[r.type];if(!n)return void be.error(`Node ${r.id} not found in 'nodes stored by type' record.`);let o=n.indexOf(r);if(-1!==o)return n.splice(o,1),r;be.error(`Node ${r.id} not found in 'nodes stored by type' record.`)}insertNode(t,e,i,s){i[t.id]?be.error(`Node ${t.id} already registered.`):(e.push(t),i[t.id]=t,s[t.type]||(s[t.type]=[]),s[t.type].push(t))}removeNode(t,e,i,s){let r=e.indexOf(t);if(-1!==r)return this.deleteNodeAtIndex(r,e,i,s),t;be.warn(`Node ${t.id} not found.`)}registerNode(t){var e,i;t.spaceGraph=this;let{nodes:s,nodesById:r,nodesByType:n}=this;this.insertNode(t,s,r,n),"getBoundingBox"in t&&"layout"in t&&(null==(e=t.layout)?void 0:e.spatialIndex)&&(null==(i=t.layout)||i.spatialIndex.addNode(t))}unregisterNode(t){var e,i;t.spaceGraph=null;let{nodes:s,nodesById:r,nodesByType:n}=this;this.removeNode(t,s,r,n),"getBoundingBox"in t&&"layout"in t&&(null==(e=t.layout)?void 0:e.spatialIndex)&&(null==(i=t.layout)||i.spatialIndex.removeNode(t))}insertSpatialStructure(t){if(this.spatialStructure)be.warn(`Space graph object already has spatial structure ${this.spatialStructure.id} attached.`);else if(t.spaceGraph)be.warn(`Spatial structure ${t.id} already part of a space graph object.`);else{switch(t.spaceGraph=this,this.spatialStructure=t,t.type){case"spatialStructure:building":!function(t,e){e.registerNode(t);for(let i of t.floors)jn(i,e);e.emit("spatial-structure-create",t)}(t,this);break;case"spatialStructure:floor":jn(t,this);break;case"spatialStructure:layout":Hn(t,this)}this.emit("spatial-structure-create",t)}}removeSpatialStructure(){let t=this.spatialStructure;if(t){switch(t.spaceGraph=null,this.spatialStructure=null,t.type){case"spatialStructure:building":!function(t,e){e.unregisterNode(t);for(let i of t.floors)zn(i,e);e.emit("spatial-structure-delete",t)}(t,this);break;case"spatialStructure:floor":zn(t,this);break;case"spatialStructure:layout":$n(t,this)}return this.emit("spatial-structure-delete",t),t}be.warn("No spatial structure attached to space graph object.")}insertProduct(t){t.spaceGraph?be.warn(`Product ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.products,this.productsById,this.productsByType),this.registerNode(t),this.emit("product-create",t))}removeProduct(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.products,this.productsById,this.productsByType),this.unregisterNode(t),this.emit("product-delete",t)):be.warn(`Product ${t.id} already in a detached state.`)}createProduct(t,e){let i;return i=e===nn?new on(t):new rn(t),this.insertProduct(i),i}insertGeometry(t){let{geometries:e,geometriesById:i,geometriesByType:s}=this;e.push(t),i[t.id]=t,s[t.type].push(t)}removeGeometry(t){let{geometries:e,geometriesById:i,geometriesByType:s}=this,r=e.indexOf(t);if(-1===r)return void be.warn(`Geometry ${t.id} not found.`);if(e.splice(r,1),i[t.id]!==t)return void be.error(`Entry ${t.id} in 'geometries stored by ID' record does not contain this object.`);delete this.geometriesById[t.id];let n=s[t.type];if(!n)return void be.error(`Geometry ${t.id} not found in 'geometries stored by type' record.`);let o=n.indexOf(t);-1!==o?n.splice(o,1):be.error(`Node ${t.id} not found in 'nodes stored by type' record.`)}insertMaterial(t){t.spaceGraph?be.warn(`Material ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.materials,this.materialsById,this.materialsByType),this.registerNode(t),this.emit("material-create",t))}removeMaterial(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.materials,this.materialsById,this.materialsByType),this.unregisterNode(t),this.emit("material-delete",t)):be.warn(`Material ${t.id} already in a detached state.`)}createMaterial(t,e,...i){let s;switch(t){case Pe:s=new Ee(e,i[0],i[1]);break;case Te:s=new Ae(e,i[0]);break;case Ie:s=new Se(e,i[0],i[1]);break;case Ce:s=new Me(e)}return this.insertMaterial(s),s}insertRelation(t){t.spaceGraph?be.warn(`Relation ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.relations,this.relationsById,this.relationsByType),this.registerNode(t),this.emit("relation-create",t))}removeRelation(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.relations,this.relationsById,this.relationsByType),this.unregisterNode(t),this.emit("relation-delete",t)):be.warn(`Relation ${t.id} already in a detached state.`)}createRelation(t,e){let i;if(t===Xn)i=new Wn(e);return this.insertRelation(i),i}insertCustomAttribute(t){t.spaceGraph?be.warn(`Custom attribute ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.customAttributes,this.customAttributesById,this.customAttributesByType),this.registerNode(t),this.emit("custom-attribute-create",t))}removeCustomAttribute(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.customAttributes,this.customAttributesById,this.customAttributesByType),this.unregisterNode(t),this.emit("custom-attribute-delete",t)):be.warn(`Custom attribute ${t.id} already in a detached state.`)}getId(){return Ut()}emit(t,...e){this.emitter.emit(t,...e)}on(t,e,i){this.emitter.on(t,e,i)}once(t,e,i){this.emitter.once(t,e,i)}off(t,e){this.emitter.off(t,e)}toJSON(){let t=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.products),e=function(t){let e=[];for(let i of t){let t=y(i);e.push(t)}return e}(this.geometries),i=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.materials),s=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.relations),r=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.customAttributes);return{schemaVersion:"0.24.2",spatialStructure:this.spatialStructure.toJSON(),sharedResources:{products:t,geometries:e,materials:i,relations:s,customAttributes:r}}}static fromJSON(t){const e=new Eo(t.schemaVersion);return Po(e,t),e}}function To(t,e){let i=t.spatialGraph,s=new hs;for(let r of e.edges){let t=i.edgesById[r];if(!t)return void be.warn(`Edge ${r} not found, skipping boundary.`);s.edges.push(t)}if(lr(s))return s}function Ao(t,e){let i=[];for(let s of e){let e=To(t,s);if(!e)return;i.push(e)}return i}function Io(t,e){let{id:i,position:s}=e,r=new bs(i,s[0],s[1]);return Ss(r,e),r}function So(t,e){let i=t.spatialGraph,s=e.vertices[0],r=e.vertices[1];if(s===r)return void be.warn(`Same vertex referenced twice, skipping edge ${e.id}.`);let n=i.verticesById[s],o=i.verticesById[r];if(!n||!o)return void be.warn(`One or both vertices not found, skipping edge ${e.id}.`);let a=new Bs(e.id,n,o);return Ss(a,e),a}function Co(t,e,i){i??(i=t.spaceGraph.customAttributesById);let s=Ao(t,e.boundaries);if(!s)return void be.warn(`Invalid boundaries, skipping space ${e.id}.`);let r=new Us(e.id,s);return Ss(r,e),Cs(r,e,i),e.attributes&&r.setAttributes(e.attributes),r}function Mo(t,e){let i=Kn(e.type,e.id);return Ss(i,e),i.setTransform(e.position,e.rotation??0),e.parameters&&i.setParameters(e.parameters),i}function Oo(t,e){let i=Zn(e.type,e.id);return Ss(i,e),e.parameters&&i.setParameters(e.parameters),i}const No={};function Lo(t,e,i){return No[t]||(No[t]={}),No[t][e]=i,i}const Ro={.15:t=>{if(("layout:space"===t.type||"element:floor"===t.type||"element:ceiling"===t.type)&&t.id.includes(":")){const e=JSON.parse(JSON.stringify(t));return e.id=Ut(),e}return t},.16:t=>{if("element:window"===t.type&&t.parameters&&"framePosition"in t.parameters){const e=JSON.parse(JSON.stringify(t));return delete e.parameters.framePosition,e}return t},"0.20.3":t=>{if("layout:space"===t.type||!t.parameters)return t;let e=!1;const i=JSON.parse(JSON.stringify(t.parameters));if("height"in i&&i.height<.01&&(i.height=.01,e=!0),"width"in i&&i.width<.01&&(i.width=.01,e=!0),"length"in i&&i.length<.01&&(i.length=.01,e=!0),e){const e=JSON.parse(JSON.stringify(t));return e.parameters=i,e}return t}};function ko(t,e){return!e||function(t,e){var i;if(void 0!==(null==(i=No[t])?void 0:i[e]))return No[t][e];const s=t.split(".").map(t=>parseInt(t)),r=e.split(".").map(t=>parseInt(t));for(let n=0;n<Math.max(s.length,r.length);n++){const i=s[n]||0,o=r[n]||0;if(i>o)return Lo(t,e,1);if(i<o)return Lo(t,e,-1)}return Lo(t,e,0)}(e,t)<0}function Bo(t,e){let i=t;for(const s in Ro)ko(s,e)&&(i=Ro[s](i));return i}function Fo(t,e){var i;let{position:s,rotation:r,rotationAxis:n}=e;if(t.setTransform(s??[0,0,0],r??0,n),e.parameters){let s=!!(null==(i=e.elements)?void 0:i.length);!function(t,e,i=!1){switch(t.type){case"element:ceiling":case"element:floor":case"element:boundaryWall":case"element:curtainWall":case"element:spaceDivider":case"element:wall":case"element:opening":case"element:asset":case"element:beam":case"element:casework":case"element:column":case"element:door":case"element:generic":case"element:ramp":case"element:roof":case"element:railing":case"element:slab":case"element:stairFlight":case"element:window":t.setParameters(e);break;case"element:kitchen":case"element:stairs":t.setParameters(e,i)}}(t,e.parameters,s)}"element:generic"!==e.type&&"element:asset"!==e.type||(t.geometries=e.geometries?JSON.parse(JSON.stringify(e.geometries)):[])}function Do(t,e,i){i??(i=t.spaceGraph);let s,r=Bo(e,null==i?void 0:i.sourceSchemaVersion);switch(r.type){case"element:boundaryWall":case"element:ceiling":case"element:floor":s=function(t,e){let i=Ao(t,e.boundaries);if(!i)return void be.warn(`Invalid boundaries, skipping boundary wall ${e.id}.`);let s=Vn(e.type,e.id,i);return e.parameters&&s.setParameters(e.parameters),s}(t,r);break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":s=function(t,e){let i=[];if(i=Array.isArray(e.edge)?e.edge:[e.edge],!i.length)return void be.warn(`Element ${e.id} references no edges and is skipped.`);let s=[];for(let n of i){let i=t.spatialGraph.edgesById[n];if(!i)return void be.warn(`Edge ${e.edge} not found, skipping edge element ${e.id}.`);s.push(i)}let r=Vn(e.type,e.id,s);return e.parameters&&r.setParameters(e.parameters),r}(t,r);break;case"element:opening":s=function(t,e){let i=Vn("element:opening",e.id);return e.parameters&&i.setParameters(e.parameters),i}(0,r);break;case"element:asset":s=function(t,e,i){let s=Vn(e.type,e.id);if(Fo(s,e),!e.product)return e.geometries||be.warn(`Element ${s.id} does not specify a 'geometries' field and does not reference a product.`),s;let r=t.spaceGraph??i;if(r){let t=r.nodesById[e.product];if(!t)return void be.warn(`Product ${e.product} not found, skipping element ${e.id}.`);s.setProduct(t)}else be.warn(`Layout not attached and space graph not passed as an argument, cannot find product ${e.product}.`);return s}(t,r,i);break;case"element:beam":case"element:casework":case"element:column":case"element:door":case"element:generic":case"element:kitchen":case"element:railing":case"element:ramp":case"element:roof":case"element:slab":case"element:stairFlight":case"element:stairs":case"element:window":s=function(t,e){let i=Vn(e.type,e.id);return Fo(i,e),i}(0,r);break;default:return void be.warn(`Unknown element type '${r.type}', skipping element.`)}if(!s)return;Ss(s,r),Cs(s,r,null==i?void 0:i.customAttributesById);let n=r.elements??[];for(let o of n){let e=Do(t,o,i);e&&s.insertElement(e)}return s}function Uo(t,e,i){Cs(t,e,i.customAttributesById),Ss(t,e),function(t,e){let i=t.spatialGraph,s=e.spatialGraph;for(let r of s.vertices){let t=Io(0,r);i.insertVertex(t)}for(let r of s.edges){let e=So(t,r);e&&i.insertEdge(e)}}(t,e),function(t,e,i){for(let s of e.spaces){let e=Co(t,Bo(s),i.customAttributesById);e&&t.insertSpace(e)}}(t,e,i),function(t,e,i){for(let s of e.elements){let e=Do(t,s,i);e&&t.insertElement(e)}}(t,e,i),function(t,e){let i=e.annotations??[];for(let s of i){let e=Mo(0,s);t.insertAnnotation(e)}}(t,e),function(t,e){let i=e.views??[];for(let s of i){let e=Oo(0,s);t.insertView(e)}}(t,e),function(t){const e=t.spatialGraph.edges;for(const s of e)s.spaces=[null,null],s.boundaryWalls=[null,null];const i=[];for(const s of t.spaces)Qs(s),i.push(nr(s));for(const s of e){if(null!==s.spaces[0]||null!==s.spaces[1])continue;const[e,r]=s.getPoints(),n=li(e,r,.5);for(let o=0;o<t.spaces.length;o++)if(bi(n,i[o])){s.spaces[0]=t.spaces[o],s.spaces[1]=t.spaces[o];break}}for(const s of t.elements)"element:boundaryWall"===s.type&&tr(s)}(t)}const Go="spatialStructure:layout";class Xo extends Yn{constructor(t){super(t,Go),this.parent=null,this.spaces=[],this.spacesById={},this.elements=[],this.elementsById={},this.elementsByType=to(eo),this.annotations=[],this.annotationsById={},this.annotationsByType=to(io),this.views=[],this.viewsById={},this.viewsByType=to(so),this.debugIds=!1,this.suggestedIds={},this.spatialGraph=new xr(this),this.spatialIndex=new no(this)}copyForClone(t){super.copyForClone(t),this.debugIds=t.debugIds,this.suggestedIds={...t.suggestedIds}}insertSpace(t){_s(this,t,this.spacesById,"Space")&&(!function(t,e){for(let i of t.elements)"element:ceiling"!==i.type&&"element:floor"!==i.type||ur(e.boundaries,i.boundaries)&&e.attachSlab(i)}(this,t),t.layout=this,this.spaces.push(t),this.spacesById[t.id]=t,t.boundaries.length&&(this.spatialGraph.graphChanged=!0),this.spaceGraph&&(this.spaceGraph.registerNode(t),this.spaceGraph.emit("space-create",t)))}removeSpace(t){let e=this.spaces.indexOf(t);if(-1!==e){if(function(t){let e=t.slabs.slice();for(let i of e)t.detachSlab(i);for(let i of t.boundaries)for(let e of i.edges)e.spaces[0]===t&&(e.spaces[0]=null),e.spaces[1]===t&&(e.spaces[1]=null)}(t),this.spaces.splice(e,1),this.spacesById[t.id]===t)return delete this.spacesById[t.id],this.spaceGraph&&(this.spaceGraph.unregisterNode(t),this.spaceGraph.emit("space-delete",t)),t.layout=null,t;be.error(`Entry ${t.id} in 'spaces stored by ID' record does not contain this object.`)}else be.warn(`Space ${t.id} not found.`)}createSpace(t,e){let i=new Us(t,e);return this.insertSpace(i),i}insertElement(t){_s(this,t,this.elementsById,"Element",!0)&&(!function(t,e){switch(e.type){case"element:boundaryWall":case"element:ceiling":case"element:floor":ir(t,e);break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":sr(t,e)}}(this,t),this.elements.push(t),ws(this,t))}removeElement(t){if(t.layout!==this)return void be.warn(`Element ${t.id} not part of layout ${this.id}.`);if(t.parent)return void be.warn(`Element ${t.id} not a root element, cannot remove from layout.`);rr(t);let e=this.elements.indexOf(t);if(-1!==e)return this.elements.splice(e,1),Ps(this,t,null),t;be.warn(`Element ${t.id} not found.`)}createElement(t,e,...i){let s=Vn(t,e,...i);return this.insertElement(s),s}insertNode(t){let{nodes:e,nodesById:i,nodesByType:s}=vr(this,t);t.layout=this,e.push(t),i[t.id]=t,s[t.type]||(s[t.type]=[]),s[t.type].push(t)}removeNode(t){let{name:e,nodes:i,nodesById:s,nodesByType:r}=vr(this,t),n=i.indexOf(t);if(-1===n)return void be.warn(`Node ${t.id} not found in '${e}' list.`);if(i.splice(n,1),s[t.id]!==t)return void be.error(`Entry ${t.id} in '${e} stored by ID' record does not contain this object.`);delete s[t.id];let o=r[t.type],a=null==o?void 0:o.indexOf(t);o&&-1!==a?r[t.type].splice(a,1):be.error(`Node ${t.id} not found in '${e} stored by type' record.`)}insertAnnotation(t){_s(this,t,this.annotationsById,"Annotation")&&(this.insertNode(t),this.spaceGraph&&(this.spaceGraph.registerNode(t),this.spaceGraph.emit("annotation-create",t)))}removeAnnotation(t){return this.removeNode(t),this.spaceGraph&&(this.spaceGraph.unregisterNode(t),this.spaceGraph.emit("annotation-delete",t)),t.layout=null,t}createAnnotation(t,e){let i=Kn(t,e);return this.insertAnnotation(i),i}insertView(t){_s(this,t,this.viewsById,"View")&&(this.insertNode(t),this.spaceGraph&&(this.spaceGraph.registerNode(t),this.spaceGraph.emit("view-create",t)))}removeView(t){return this.removeNode(t),this.spaceGraph&&(this.spaceGraph.unregisterNode(t),this.spaceGraph.emit("view-delete",t)),t.layout=null,t}createView(t,e){let i=Zn(t,e);return this.insertView(i),i}clearSpaces(){let t=[...this.spaces];for(let e of t)this.removeSpace(e)}getElementList(){return Object.values(this.elementsById)}getArea(t={program:{exclude:["void"]}}){var e,i;let s=(null==(e=null==t?void 0:t.program)?void 0:e.include)??[],r=(null==(i=null==t?void 0:t.program)?void 0:i.exclude)??[];if(s.length&&r.length)return be.warn("Cannot use 'include' and 'exclude' filters at the same time, skipping area calculation."),0;let n=0;for(let o of this.spaces){let t=!1;s.length&&(t=s.includes(o.attributes.program)),r.length&&(t=r.includes(o.attributes.program)),t||(n+=o.getArea())}return n}getLayoutGraph(){var t;let e=new Qn,i=this.elementsByType["element:spaceDivider"].slice();for(let s of this.elementsByType["element:opening"])"element:window"!==(null==(t=s.elements[0])?void 0:t.type)&&i.push(s);for(let s of i)for(let t of s.getSpaces())t&&e.addEdge("graph:connectedTo",t,s);for(let s of this.spatialGraph.edges)s.spaces[0]&&s.spaces[1]&&e.addEdge("graph:adjacentTo",s.spaces[0],s.spaces[1]);return e}getUniqueId(t,e){let i=0,s=t+i++;for(;this.suggestedIds[s]||e[s];)s=t+i++;return this.suggestedIds[s]=!0,s}getSpaceId(t){let e;return t=t??"space-",e=this.debugIds?this.getUniqueId(t,this.spacesById):Ut(),e}getElementId(t,e){let i;return e=e??t.type.split(":")[1]+"-",i=this.debugIds?this.getUniqueId(e,this.elementsById):Ut(),i}getBoundingBox(){const t={position:[0,0,0],rotation:0,rotationAxis:[0,1,0]};if(0===this.spaces.length)return{min:[0,0,0],max:[0,0,0],transform:t};const e=[];for(const r of this.spaces){const{min:t,max:i}=r.getAxisAlignedBoundingBox();e.push(t,i)}for(const r of this.getElementList()){const{min:t,max:i}=r.getAxisAlignedBoundingBox();e.push(t,i)}const{min:i,max:s}=ls(e.flat());return{min:i,max:s,transform:t}}toJSON(){let t=this.spatialGraph.toJSON(),e=function(t){let e=[];for(let i of t.spaces){let t=i.toJSON();e.push(t)}return e}(this),i=function(t){let e=[];for(let i of t.elements){let t=i.toJSON();t&&e.push(t)}return e}(this),s=function(t){let e=[];for(let i of t.annotations){let t=i.toJSON();e.push(t)}return e}(this),r=function(t){let e=[];for(let i of t.views){let t=i.toJSON();e.push(t)}return e}(this);return{...super.toJSON(),spatialGraph:t,spaces:e,elements:i,annotations:s,views:r}}static fromJSON(t,e){const i=(null==e?void 0:e.spaceGraph)??new Eo,s=new Xo(t.id);return Uo(s,t,i),(null==e?void 0:e.skipInsert)||i.insertSpatialStructure(s),s}}const Wo="spatialStructure:floor";class Yo extends Yn{constructor(t){super(t,Wo),this.parent=null,this.position=[0,0,0],this.rotation=0,this.layouts=[]}copyForClone(t){super.copyForClone(t),this.position=[...t.position],this.rotation=t.rotation}insertLayout(t){t.parent?be.warn(`SpaceGraphLayout ${t.id} already part of floor ${t.parent.id}.`):(t.parent=this,this.layouts.push(t),this.spaceGraph&&Hn(t,this.spaceGraph))}removeLayout(t){-1!==this.layouts.indexOf(t)?(this.spaceGraph&&$n(t,this.spaceGraph),t.parent=null):be.warn(`Floor ${t.id} not found.`)}createLayout(t){let e=new Xo(t);return this.insertLayout(e),e}toJSON(){const t={...super.toJSON(),position:[...this.position],rotation:this.rotation,layouts:[]};for(let e of this.layouts){let i=e.toJSON();t.layouts.push(i)}return t}static fromJSON(t,e){const i=(null==e?void 0:e.spaceGraph)??new Eo,s=new Yo(t.id);mo(s,t),Cs(s,t,i.customAttributesById),s.position=[...t.position],s.rotation=t.rotation;for(const r of t.layouts){const t=Xo.fromJSON(r,{spaceGraph:i,skipInsert:!0});s.insertLayout(t)}return(null==e?void 0:e.skipInsert)||i.insertSpatialStructure(s),s}}const Ho="spatialStructure:building";class $o extends Yn{constructor(t){super(t,Ho),this.floors=[],this.location={latLong:[0,0],rotation:0}}copyForClone(t){super.copyForClone(t),this.location=JSON.parse(JSON.stringify(t.location))}insertFloor(t){t.parent?be.warn(`Floor ${t.id} already part of building ${t.parent.id}.`):(t.parent=this,this.floors.push(t),this.spaceGraph&&jn(t,this.spaceGraph))}removeFloor(t){-1!==this.floors.indexOf(t)?(this.spaceGraph&&zn(t,this.spaceGraph),t.parent=null):be.warn(`Floor ${t.id} not found.`)}createFloor(t){let e=new Yo(t);return this.insertFloor(e),e}toJSON(){let t={...super.toJSON(),floors:[]},e=this.location;e.latLong[0]&&e.latLong[1]&&e.rotation&&(t.location={latLong:[...e.latLong],rotation:e.rotation});for(let i of this.floors){let e=i.toJSON();t.floors.push(e)}return t}static fromJSON(t,e){const i=e.spaceGraph??new Eo,s=new $o(t.id);mo(s,t),Cs(s,t,i.customAttributesById),t.location&&(s.location=JSON.parse(JSON.stringify(s.location)));for(const r of t.floors){const t=Yo.fromJSON(r,{spaceGraph:i,skipInsert:!0});s.insertFloor(t)}return e.skipInsert||i.insertSpatialStructure(s),s}}function jo(t,e,i,s){const r=1e-7*1e-7;let n=[e[0]-t[0],e[1]-t[1]],o=[s[0]-i[0],s[1]-i[1]],a=i[0]-t[0],l=i[1]-t[1],h=n[0]*o[1]-n[1]*o[0],u=h*h,c=n[0]*n[0]+n[1]*n[1];if(u>r*c*(o[0]*o[0]+o[1]*o[1])){let e=(a*o[1]-l*o[0])/h,i=(a*n[1]-l*n[0])/h;return{tag:2,intersect:!0,p:[t[0]+e*n[0],t[1]+e*n[1]],u:e,v:i}}return h=a*n[1]-l*n[0],u=h*h,u>r*c*(a*a+l*l)?{tag:0,intersect:!1}:{tag:1,intersect:!0}}function zo(t,e,i,s){const r=[e[0]-t[0],e[1]-t[1]],n=[s[0]-i[0],s[1]-i[1]],o=i[0]-t[0],a=i[1]-t[1];let l=r[0]*n[1]-r[1]*n[0],h=l*l;const u=r[0]*r[0]+r[1]*r[1];let c,d,p,f;if(h>1e-14*u*(n[0]*n[0]+n[1]*n[1])){const e=(o*n[1]-a*n[0])/l;if(e<0||e>1)return{tag:0,intersect:!1};{const i=(o*r[1]-a*r[0])/l;return i<0||i>1?{tag:0,intersect:!1}:(c=t[0]+e*r[0],d=t[1]+e*r[1],{tag:1,intersect:!0,p:[c,d],u:e,v:i})}}if(l=o*r[1]-a*r[0],h=l*l,h>1e-14*u*(o*o+a*a))return{tag:2,intersect:!1};{const e=(r[0]*o+r[1]*a)/u,i=e+(r[0]*n[0]+r[1]*n[1])/u;let s,l;e<i?(s=e,l=i):(s=i,l=e);const h=function(t,e,i,s){if(e<i||t>s)return{tag:0,intersect:!1};if(t===i&&e===s)return{tag:1,intersect:!0};if(e>i)return e<s?{tag:3,intersect:!0,w0:t<i?i:t,w1:e>s?s:e}:{tag:2,intersect:!0,w:t};return{tag:2,intersect:!0,w:e}}(0,1,s,l);switch(h.tag){case 0:return{tag:3,intersect:!1};case 1:return{tag:4,intersect:!0};case 2:{const e=h.w;return c=t[0]+e*r[0],d=t[1]+e*r[1],{tag:5,intersect:!0,p:[c,d],u:e}}case 3:{const e=h.w0,i=h.w1;return c=t[0]+e*r[0],d=t[1]+e*r[1],p=t[0]+i*r[0],f=t[1]+i*r[1],{tag:6,intersect:!0,p:[c,d],q:[p,f],u0:e,u1:i}}default:throw new Error("Unknown tag value.")}}}function Vo(...t){}function qo(t,e,i,s){let r=t[0],n=t[1];for(let o=1;o<e.length-1;o++){let a=e[o];if(_i(a,r,n)<1e-7)return i?t[0]=a:t[1]=a,void(s?e.splice(0,o):e.splice(o+1))}}function Jo(t){let e=0;for(;e<t.length-2;){let i=t[e],s=t[e+2];_i(t[e+1],i,s)<1e-7?t.splice(e+1,1):e++}}function Ko(t){if(t.length<3)return!1;let e=t.slice();e.push(t[0]);for(let i=0;i<e.length-2;i++){let t=e[i],s=e[i+1];for(let r=i+1;r<e.length-1;r++){const i=1e-7;let n=zo(t,s,e[r],e[r+1]);if(1===n.tag&&n.u>i&&n.u<1-i)return!0}}return!1}function Zo(t,e){return{position:[t,e],edges:[],geometry:{parameters:{joinStyle:{type:"miter",parameters:{distance:.05}}}}}}function Qo(t,e){let i={indices:[t,e],faces:[-1,-1],geometry:{tangible:!0,skipped:!1,parameters:{width:.15,height:2.5,offset:0},fragments:[],computed:{valid:!0,skipped:!1,selfIntersecting:!1,sidePoints1:[],sidePoints2:[],joinPoints1:[],joinPoints2:[],points:[]}},openings:[]};return i.geometry.fragments=[{edge:i,angle:0,points:[],joinPoints:[],sidePoints:[]},{edge:i,angle:0,points:[],joinPoints:[],sidePoints:[]}],i}const ta="intersectCap",ea="intersectCap";function ia(...t){}function sa(t){let e=t.toFixed(3),i=parseFloat(e);return e+=t>i?"+":t<i?"-":" ",t>=0&&(e=" "+e),e}function ra(t){if(t.length>0)for(let e=0;e<t.length;e++){let i=t[e];ia((i[0],i[1]))}}function na(t,e){for(let i of e)if(t.length>0){let e=t[0],s=t[t.length-1],r=oi(di(i,e)),n=oi(di(i,s));r>1e-7&&n>1e-7&&t.push(i)}else t.push(i)}function oa(t,e,i,s,r){0===t.joinPoints.length?(na(t.joinPoints,[...s,i]),na(t.sidePoints[0],r)):(na(t.joinPoints,s),na(t.sidePoints[1],r.slice().reverse())),ra(t.joinPoints),ra(t.sidePoints[0]),ra(t.sidePoints[1])}function aa(t,e,i,s,r){oa(t,0,i,[s],[s]),oa(e,0,i,[r],[r]),t.edge.geometry.computed.skipped=!0,e.edge.geometry.computed.skipped=!0}function la(t,e,i,s){oa(t,0,i,[s],[s]),oa(e,0,i,[s],[s])}function ha(t,e,i,s,r){oa(t,0,i,[s],[s]),oa(e,0,i,[r],[r])}function ua(t,e,i,s,r,n,o,a,l,h,u){if("ignore"===u)aa(t,e,i,r,a);else{let u;if(u=h?jo(s,r,l,a):jo(n,r,o,a),2!==u.tag)return be.warn("Edge side line does not intersect edge cap line, ignoring result."),void aa(t,e,i,r,a);let c=u.p;h?(oa(t,0,i,[c],[c]),oa(e,0,i,[a,c],[a])):(oa(t,0,i,[r,c],[r]),oa(e,0,i,[c],[c]))}}function ca(t,e,i,s,r,n,o,a,l,h,u,c){t.edge.id,e.edge.id;let d=jo(s,r,a,l);if(2!==d.tag)return be.warn("Edge side lines do not intersect, ignoring result.",d),void aa(t,e,i,r,l);let p=oi(di(r,s)),f=oi(di(l,a)),m=Math.max(0,1-.2/p),g=Math.max(0,1-.2/f),{p:y,u:v,v:x}=d,b="",_="";if(v>=.9999999)if(o)if(x>=.9999999){const s=1;if(oi(di(y,i))>s){let s,n=jo(y,i,r,l);2!==n.tag?(be.warn("Bevel construction failed, using center point.",n),s=li(r,l,.5)):s=n.p,oa(t,0,i,[s],[r,s]),oa(e,0,i,[s],[l,s])}else la(t,e,i,y)}else if(x>=g)la(t,e,i,y);else{let c=o&&u?ta:"ignore";ua(t,e,i,s,r,n,a,l,h,!0,c),_="ignore"===c?"* (ignore)":"* (intersectCap)"}else aa(t,e,i,r,l);else if(x>=.9999999)if(u)if(v>=m)la(t,e,i,y);else{let c=o&&u?ta:"ignore";ua(t,e,i,s,r,n,a,l,h,!1,c),b="ignore"===c?"* (ignore)":"* (intersectCap)"}else aa(t,e,i,r,l);else be.warn("Edge side line segments cross, ignoring result."),aa(t,e,i,r,l);sa(v),m.toFixed(3),sa(x),g.toFixed(3)}function da(t,e,i,s,r,n,o,a,l,h,u,c){t.edge.id,e.edge.id;let d=jo(s,r,a,l);if(2!==d.tag)return be.warn("Edge side lines do not intersect, ignoring result.",d),void aa(t,e,i,r,l);let p=oi(di(r,s)),f=oi(di(l,a)),m=Math.max(0,1-1/p),g=Math.max(0,1-1/f),{p:y,u:v,v:x}=d,b="",_="";if(v>=0&&v<=1+1e-7&&x>=0&&x<=1+1e-7)la(t,e,i,y);else if(v>1&&x>1)be.warn("Edge side line segments do not cross, ignoring result."),aa(t,e,i,r,l);else if(v>1)if(x>=g)la(t,e,i,y);else{let c=o&&u?ea:"ignore";ua(t,e,i,s,r,n,a,l,h,!1,c),_="ignore"===c?"* (ignore)":"* (intersectCap)"}else if(x>1)if(v>=m)la(t,e,i,y);else{let c=o&&u?ea:"ignore";ua(t,e,i,s,r,n,a,l,h,!0,c),b="ignore"===c?"* (ignore)":"* (intersectCap)"}else aa(t,e,i,r,l);sa(v),m.toFixed(3),sa(x),g.toFixed(3)}function pa(t,e){let i,s,r,n=e[0];n.indices[0]===t?(i=n.geometry.fragments[0],s=i.points[0],r=i.points[1]):(i=n.geometry.fragments[1],s=i.points[1],r=i.points[0]),i.joinPoints.push(s,r),i.sidePoints[0].push(s),i.sidePoints[1].push(r)}function fa(t,e,i){for(let s=0;s<e.length;s++){let r,n,o,a,l,h,u,c,d,p,f,m,g=e[s],y=s<e.length-1?e[s+1]:e[0],v=!g.geometry.skipped&&0!==g.geometry.parameters.width,x=!y.geometry.skipped&&0!==y.geometry.parameters.width;if(!v&&!x)continue;g.indices[0]===t?(r=g.geometry.fragments[0],n=g.geometry.fragments[1],o=n.points[0],a=r.points[0],l=r.points[1],h=i[g.indices[1]].position):(r=g.geometry.fragments[1],n=g.geometry.fragments[0],o=n.points[1],a=r.points[1],l=r.points[0],h=i[g.indices[0]].position),y.indices[0]===t?(u=y.geometry.fragments[0],c=y.geometry.fragments[1],d=c.points[1],p=u.points[1],f=u.points[0],m=i[y.indices[1]].position):(u=y.geometry.fragments[1],c=y.geometry.fragments[0],d=c.points[0],p=u.points[0],f=u.points[1],m=i[y.indices[0]].position);let b=i[t].position;const _=.01;let w=vi(o,a,d,p);if(w<_||w>Math.PI-_)ha(r,u,b,a,p);else{1===gi(h,b,m)?ca(r,u,b,o,a,l,v,d,p,f,x):da(r,u,b,o,a,l,v,d,p,f,x)}}}function ma(t){let e=t.geometry;e.fragments[0].joinPoints=[],e.fragments[0].sidePoints[0]=[],e.fragments[0].sidePoints[1]=[],e.fragments[1].joinPoints=[],e.fragments[1].sidePoints[0]=[],e.fragments[1].sidePoints[1]=[],e.computed={valid:!0,skipped:!1,selfIntersecting:!1,sidePoints1:[],sidePoints2:[],joinPoints1:[],joinPoints2:[],points:[]}}function ga(t,e){let i=function(t){let e={};for(let i of t){let t=i.indices[0],s=i.indices[1],r=Math.min(t,s),n=Math.max(t,s);e[r.toString()+"_"+n.toString()]=i}return e}(e),s=[];for(let n of e){if(!n.geometry.tangible||n.geometry.skipped)continue;let t=n.indices[0],e=n.indices[1];s[t]=!0,s[e]=!0,ma(n)}let{vertices:r}=t;for(let n=0;n<r.length;n++){if(!s[n])continue;let t=[],e=r[n];for(let s of e.edges){if(!s.geometry.tangible||s.geometry.skipped)continue;let e=s.indices[0],r=s.indices[1],n=Math.min(e,r),o=Math.max(e,r);i[n.toString()+"_"+o.toString()]&&t.push(s)}ia(t.length),1===t.length?pa(n,t):fa(n,t,r)}}function ya(t,e){let i=e.element;if(i?t.geometry.tangible="element:spaceDivider"!==i.type:e.boundaryWalls[0]||e.boundaryWalls[1]?t.geometry.tangible=!0:t.geometry.tangible=!1,i&&"element:wall"===i.type){let{width:e,height:s,offset:r}=i.parameters;t.geometry.parameters={width:e,height:s,offset:r}}else t.geometry.parameters={width:0,height:0,offset:0}}function va(t,e){let i=[],s={};for(let a of e)for(let t of a.vertices)if(void 0===s[t.id]){let e=Zo(t.position[0],t.position[1]);e.reference=t,s[t.id]=i.push(e)-1}let r=[],n={};for(let a of e){let t=a.vertices[0],e=a.vertices[1],i=Qo(s[t.id],s[e.id]);ya(i,a),i.id=a.id,i.reference=a,r.push(i),n[a.id]=!0}let o=function(t,e){return{vertices:t,edges:e,cycles:[],faces:[]}}(i,r);return function(t){let{vertices:e,edges:i}=t;for(let s of e)s.edges=[];for(let s of i){let t=s.indices[0],i=s.indices[1];e[t].edges.push(s),e[i].edges.push(s)}}(o),function(t){let{vertices:e}=t;for(let i=0;i<e.length;i++){let t=e[i],s=t.edges,r=[];for(let n of s){let s=e[i===n.indices[0]?n.indices[1]:n.indices[0]],o={edge:n,angle:si([s.position[0]-t.position[0],s.position[1]-t.position[1]]),points:[],joinPoints:[],sidePoints:[[],[]]},a={edge:n,fragment:o};i===n.indices[0]?n.geometry.fragments[0]=o:n.geometry.fragments[1]=o,r.push(a)}r.sort((t,e)=>t.fragment.angle-e.fragment.angle),t.edges=r.map(t=>t.edge)}}(o),o}function xa(t){const e=t.map(t=>t.geometry.computed),i=function(t){var e;if(0===t.length)return[];const i={};for(const l of t)for(const t of l.indices)i[t]??(i[t]=[]),i[t].push(l);let s=(null==(e=Object.entries(i).find(([,t])=>1===t.length))?void 0:e[0])||Object.keys(i)[0];const r=[],n=/* @__PURE__ */new Set;let o=parseInt(s),a=i[o][0];for(;r.length<t.length;){if(n.has(a)){if(a=t.find(t=>!n.has(t)),!a)break;o=a.indices[0];continue}const e=a.indices[0]!==o;r.push({edge:a,reverse:e}),n.add(a);const s=e?a.indices[0]:a.indices[1],l=i[s].find(t=>!n.has(t));if(l)o=s,a=l;else{if(a=t.find(t=>!n.has(t)),!a)break;o=a.indices[0]}}return r}(t),s=t[0].geometry.computed;let r=s.valid;const n=i[0].reverse,o=i[0].edge.geometry.computed,a=i[i.length-1].reverse,l=i[i.length-1].edge.geometry.computed,h=n?o.joinPoints2:o.joinPoints1,u=a?l.joinPoints1:l.joinPoints2,c=[],d=[];for(const{edge:m,reverse:g}of i){const{computed:t}=m.geometry;g?(c.unshift(...t.sidePoints2),d.push(...t.sidePoints1)):(c.unshift(...t.sidePoints1),d.push(...t.sidePoints2))}const p=Y(e.map(t=>t.points));let f=[];if(1===p.length)f=p[0];else if(p.length>1){const t=$(p,.001,void 0,!0);t.length>0&&(f=t[0])}return 0===f.length&&(be.warn(`Empty wall geometry after merging edge profiles: ${t.map(t=>t.id).join(", ")}`),r=!1),{valid:r,skipped:s.skipped,selfIntersecting:s.selfIntersecting,sidePoints1:c.slice(),sidePoints2:d.slice(),joinPoints1:h.slice(),joinPoints2:u.slice(),points:f}}function ba(t,e){zs(t,e),e.emit("geometry-profile-update",e);for(let i of e.slabs)i.emit("geometry-profile-update",i)}function _a(t){let e=function(t){let e=/* @__PURE__ */new Map;for(let i of t)for(let t of i.boundaryWalls)t&&e.set(t.id,t);return[...e.values()]}(t);for(let i of e)Mr(i)}function wa(t){let e=t.spatialGraph.edges,i=va(0,e);!function(t){let{vertices:e,edges:i}=t;for(let s of i){let{geometry:t}=s,i=s.indices[0],r=s.indices[1],n=t.parameters.width,o=t.parameters.offset,a=e[i].position,l=e[r].position,h=di(l,a);if(t.skipped=oi(h)<1e-7,!t.skipped){let e=ui(hi(h)),i=ci(e,.5*n+o),s=ci(e,-.5*n+o),r=ii(a,i),u=ii(a,s),c=ii(l,i),d=ii(l,s);t.fragments[0].points=[r,u],t.fragments[1].points=[c,d]}}}(i),ga(i,i.edges),function(t,e){for(let i of e){let{geometry:t}=i;if(!t.tangible||t.skipped||0===t.parameters.width)continue;let e=t.fragments[0],s=t.fragments[1],r=[...e.joinPoints],n=[...s.joinPoints],o=[...e.sidePoints[0]],a=[...e.sidePoints[1]],l=[...s.sidePoints[0]],h=[...s.sidePoints[1]],u=jo(r[0],n[n.length-1],r[r.length-1],n[0]);2===u.tag&&u.u>0&&u.u<1&&u.v>0&&u.v<1&&(n.reverse(),l.reverse(),h.reverse(),[l,h]=[h,l]);let c=h.concat(o),d=a.concat(l);2===c.length&&2===d.length&&(qo(c,r,!1,!0),qo(c,n,!0,!1),qo(d,r,!0,!1),qo(d,n,!1,!0)),Jo(c),Jo(r),Jo(d),Jo(n),1===gi(c[0],c[c.length-1],d[0])&&(c.reverse(),d.reverse(),r.reverse(),n.reverse(),[c,d]=[d,c]);let p=c.slice(0,c.length-1),f=r.slice(0,r.length-1),m=d.slice(0,d.length-1),g=n.slice(0,n.length-1),y=tt(p.concat(f).concat(m).concat(g),.001),v=i.geometry.computed;v.sidePoints1=c,v.sidePoints2=d,v.joinPoints1=r,v.joinPoints2=n,v.points=y,v.selfIntersecting=Ko(v.points),v.valid=v.points.length>=3&&!v.skipped&&!v.selfIntersecting,Vo(i.id),Vo(v.valid),Vo(v.skipped),Vo(v.selfIntersecting)}}(0,i.edges),function(t){var e;let i={};for(let s of t.edges){let t=s.reference.element;if("element:wall"===(null==t?void 0:t.type)){let r=s.geometry.computed;1===t.getEdges().length?(t.geometryProfile={valid:r.valid,skipped:r.skipped,selfIntersecting:r.selfIntersecting,sidePoints1:r.sidePoints1.slice(),sidePoints2:r.sidePoints2.slice(),joinPoints1:r.joinPoints1.slice(),joinPoints2:r.joinPoints2.slice(),points:r.points.slice()},t.emit("geometry-profile-update",t)):(i[e=t.id]??(i[e]=[]),i[t.id].push(s),i[t.id].length===t.getEdges().length&&(t.geometryProfile=xa(i[t.id]),t.emit("geometry-profile-update",t)))}}}(i),function(t){var e;for(let i of t)"element:wall"===(null==(e=i.element)?void 0:e.type)&&Rr(i.element)}(e),_a(e)}function Pa(t){wa(t),function(t){let e=t.spaces;for(let i of e){ba(t,i);for(let t of i.slabs)Zs(t)}}(t)}function Ea(t){return new Promise((e,i)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>i(t.error)})}function Ta(t,e){let i;return(s,r)=>(()=>{if(i)return i;const s=indexedDB.open(t);return s.onupgradeneeded=()=>s.result.createObjectStore(e),i=Ea(s),i.then(t=>{t.onclose=()=>i=void 0},()=>{}),i})().then(t=>r(t.transaction(e,s).objectStore(e)))}let Aa;function Ia(){return Aa||(Aa=Ta("keyval-store","keyval")),Aa}for(var Sa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ca="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Ma=0;Ma<64;Ma++)Ca[Sa.charCodeAt(Ma)]=Ma;var Oa={exports:{}};function Na(t,e){return t<e?-1:t>e?1:0}const La=/* @__PURE__ */St(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:class{constructor(t=[],e=Na){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(t){this.data.push(t),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:i}=this,s=e[t];for(;t>0;){const r=t-1>>1,n=e[r];if(i(s,n)>=0)break;e[t]=n,t=r}e[t]=s}_down(t){const{data:e,compare:i}=this,s=this.length>>1,r=e[t];for(;t<s;){let s=1+(t<<1),n=e[s];const o=s+1;if(o<this.length&&i(e[o],n)<0&&(s=o,n=e[o]),i(n,r)>=0)break;e[t]=n,t=s}e[t]=r}}},Symbol.toStringTag,{value:"Module"})));var Ra;!function(){if(Ra)return Oa.exports;Ra=1;var t=La;function e(e,r,n){var o,a,l,h;r=r||1;for(var u=0;u<e[0].length;u++){var c=e[0][u];(!u||c[0]<o)&&(o=c[0]),(!u||c[1]<a)&&(a=c[1]),(!u||c[0]>l)&&(l=c[0]),(!u||c[1]>h)&&(h=c[1])}var d=l-o,p=h-a,f=Math.min(d,p),m=f/2;if(0===f){var g=[o,a];return g.distance=0,g}for(var y=new t(void 0,i),v=o;v<l;v+=f)for(var x=a;x<h;x+=f)y.push(new s(v+m,x+m,m,e));var b=function(t){for(var e=0,i=0,r=0,n=t[0],o=0,a=n.length,l=a-1;o<a;l=o++){var h=n[o],u=n[l],c=h[0]*u[1]-u[0]*h[1];i+=(h[0]+u[0])*c,r+=(h[1]+u[1])*c,e+=3*c}return 0===e?new s(n[0][0],n[0][1],0,t):new s(i/e,r/e,0,t)}(e),_=new s(o+d/2,a+p/2,0,e);_.d>b.d&&(b=_);for(var w=y.length;y.length;){var P=y.pop();P.d>b.d&&(b=P,n&&console.log("found best %d after %d probes",Math.round(1e4*P.d)/1e4,w)),P.max-b.d<=r||(m=P.h/2,y.push(new s(P.x-m,P.y-m,m,e)),y.push(new s(P.x+m,P.y-m,m,e)),y.push(new s(P.x-m,P.y+m,m,e)),y.push(new s(P.x+m,P.y+m,m,e)),w+=4)}n&&(console.log("num probes: "+w),console.log("best distance: "+b.d));var E=[b.x,b.y];return E.distance=b.d,E}function i(t,e){return e.max-t.max}function s(t,e,i,s){this.x=t,this.y=e,this.h=i,this.d=function(t,e,i){for(var s=!1,n=1/0,o=0;o<i.length;o++)for(var a=i[o],l=0,h=a.length,u=h-1;l<h;u=l++){var c=a[l],d=a[u];c[1]>e!=d[1]>e&&t<(d[0]-c[0])*(e-c[1])/(d[1]-c[1])+c[0]&&(s=!s),n=Math.min(n,r(t,e,c,d))}return 0===n?0:(s?1:-1)*Math.sqrt(n)}(t,e,s),this.max=this.d+this.h*Math.SQRT2}function r(t,e,i,s){var r=i[0],n=i[1],o=s[0]-r,a=s[1]-n;if(0!==o||0!==a){var l=((t-r)*o+(e-n)*a)/(o*o+a*a);l>1?(r=s[0],n=s[1]):l>0&&(r+=o*l,n+=a*l)}return(o=t-r)*o+(a=e-n)*a}t.default&&(t=t.default),Oa.exports=e,Oa.exports.default=e,Oa.exports}();var ka,Ba={exports:{}};var Fa,Da,Ua=(ka||(ka=1,Fa=Ba,Da=function(){var t={},e=Math.PI/180,i=180/Math.PI,s=6378137,r=20037508.342789244;function n(t){return Number(t)===t&&t%1!=0}function o(e){if(e=e||{},this.size=e.size||256,this.expansion=!0===e.antimeridian?2:1,!t[this.size]){var i=this.size,s=t[this.size]={};s.Bc=[],s.Cc=[],s.zc=[],s.Ac=[];for(var r=0;r<30;r++)s.Bc.push(i/360),s.Cc.push(i/(2*Math.PI)),s.zc.push(i/2),s.Ac.push(i),i*=2}this.Bc=t[this.size].Bc,this.Cc=t[this.size].Cc,this.zc=t[this.size].zc,this.Ac=t[this.size].Ac}return o.prototype.px=function(t,i){if(n(i)){var s=this.size*Math.pow(2,i),r=s/2,o=s/360,a=s/(2*Math.PI),l=s,h=Math.min(Math.max(Math.sin(e*t[1]),-.9999),.9999),u=r+t[0]*o,c=r+.5*Math.log((1+h)/(1-h))*-a;return u>l*this.expansion&&(u=l*this.expansion),c>l&&(c=l),[u,c]}return r=this.zc[i],h=Math.min(Math.max(Math.sin(e*t[1]),-.9999),.9999),u=Math.round(r+t[0]*this.Bc[i]),c=Math.round(r+.5*Math.log((1+h)/(1-h))*-this.Cc[i]),u>this.Ac[i]*this.expansion&&(u=this.Ac[i]*this.expansion),c>this.Ac[i]&&(c=this.Ac[i]),[u,c]},o.prototype.ll=function(t,e){if(n(e)){var s=this.size*Math.pow(2,e),r=s/360,o=s/(2*Math.PI),a=s/2,l=(t[1]-a)/-o;return[(t[0]-a)/r,i*(2*Math.atan(Math.exp(l))-.5*Math.PI)]}return l=(t[1]-this.zc[e])/-this.Cc[e],[(t[0]-this.zc[e])/this.Bc[e],i*(2*Math.atan(Math.exp(l))-.5*Math.PI)]},o.prototype.bbox=function(t,e,i,s,r){s&&(e=Math.pow(2,i)-1-e);var n=[t*this.size,(+e+1)*this.size],o=[(+t+1)*this.size,e*this.size],a=this.ll(n,i).concat(this.ll(o,i));return"900913"===r?this.convert(a,"900913"):a},o.prototype.xyz=function(t,e,i,s){"900913"===s&&(t=this.convert(t,"WGS84"));var r=[t[0],t[1]],n=[t[2],t[3]],o=this.px(r,e),a=this.px(n,e),l=[Math.floor(o[0]/this.size),Math.floor((a[0]-1)/this.size)],h=[Math.floor(a[1]/this.size),Math.floor((o[1]-1)/this.size)],u={minX:Math.min.apply(Math,l)<0?0:Math.min.apply(Math,l),minY:Math.min.apply(Math,h)<0?0:Math.min.apply(Math,h),maxX:Math.max.apply(Math,l),maxY:Math.max.apply(Math,h)};if(i){var c={minY:Math.pow(2,e)-1-u.maxY,maxY:Math.pow(2,e)-1-u.minY};u.minY=c.minY,u.maxY=c.maxY}return u},o.prototype.convert=function(t,e){return"900913"===e?this.forward(t.slice(0,2)).concat(this.forward(t.slice(2,4))):this.inverse(t.slice(0,2)).concat(this.inverse(t.slice(2,4)))},o.prototype.forward=function(t){var i=[s*t[0]*e,s*Math.log(Math.tan(.25*Math.PI+.5*t[1]*e))];return i[0]>r&&(i[0]=r),i[0]<-r&&(i[0]=-r),i[1]>r&&(i[1]=r),i[1]<-r&&(i[1]=-r),i},o.prototype.inverse=function(t){return[t[0]*i/s,(.5*Math.PI-2*Math.atan(Math.exp(-t[1]/s)))*i]},o}(),Fa.exports=Da),Ba.exports);const Ga=/* @__PURE__ */It(Ua),Xa={work:{name:"Work",isHidden:!0,description:"space for individual head-down work",spaceUsage:{privateOffice:{name:"Private office",category:["office"]},focusRoom:{name:"Focus room",category:["office"]},openWorkspace:{name:"Open workspace",category:["office"]},enclosedWorkspace:{name:"Enclosed workspace",category:["office"]},closedWorkspace:{name:"Closed workspace",isDeprecated:!0,category:["office"]},executiveOffice:{name:"Executive office",isDeprecated:!0,category:["office"]}}},meet:{name:"Meet",isHidden:!0,spaceUsage:{meetingRoom:{name:"Meeting room",category:["office"]},hub:{name:"Hub",category:["office"]},assembly:{name:"Assembly",category:["office"]},boardRoom:{name:"Board room",category:["office"]},trainingRoom:{name:"Training room",category:["office"]},collaboration:{name:"Collaboration",isDeprecated:!0,category:["office"]}}},live:{name:"live",isHidden:!0,spaceUsage:{living:{name:"Living",category:["residential"]},dining:{name:"Dining",category:["residential"]},dining_living:{name:"Living & Dining",category:["residential"]},homeOffice:{name:"Home office",category:["residential"]},bedroom:{name:"Bedroom",category:["residential"]}}},socialize:{name:"Socialize",isHidden:!0,spaceUsage:{lobby:{name:"Lobby",category:["office","residential"]},reception:{name:"Reception",category:["office"]},lounge:{name:"Lounge",category:["office"]},cafe:{name:"Cafe",category:["office"]},canteen:{name:"Canteen",category:["office"]},pantry:{name:"Pantry",category:["office"]},terrace:{name:"Terrace",isOutdoor:!0,category:["office","residential"]},balcony:{name:"Balcony",isOutdoor:!0,category:["office","residential"]},rooftop:{name:"Rooftop",isOutdoor:!0,category:["office","residential"]},courtyard:{name:"Courtyard",isOutdoor:!0,category:["office","residential"]},garden:{name:"Garden",isOutdoor:!0,category:["residential"]},common:{name:"Common",isDeprecated:!0,category:["office"]}}},support:{name:"Support",isHidden:!0,spaceUsage:{serviceKitchen:{name:"Service kitchen",category:["office"]},printStation:{name:"Print station",category:["office"]},storage:{name:"Storage",category:["lightIndustrial","residential","office","parking"]},mailRoom:{name:"Mail room",category:["office"]},operationalRoom:{name:"Operational room",category:["lightIndustrial","office","parking"]},serviceRoom:{name:"Service room",category:["office"]},laundryRoom:{name:"Laundry room",category:["residential"]},loadingDock:{name:"Loading dock",category:["lightIndustrial"]},operate:{name:"Operate",isDeprecated:!0,category:["office"]},services:{name:"Services",isDeprecated:!0,category:["office","residential"]}}},care:{name:"Care",isHidden:!0,spaceUsage:{kitchen:{name:"Kitchen",category:["residential"]},wellnessRoom:{name:"Wellness room",category:["lightIndustrial","office"]},restroom:{name:"Restroom",category:["lightIndustrial","office","parking"]},bathroom:{name:"Bathroom",category:["residential"]},shower:{name:"Shower",category:["lightIndustrial","office","residential"]},toilet:{name:"Toilet",category:["residential"]}}},circulate:{name:"Circulate",isHidden:!0,spaceUsage:{corridor:{name:"Corridor",category:["lightIndustrial","residential","office","parking"]},foyer:{name:"Foyer",category:["lightIndustrial","residential","office","parking"]},staircase:{name:"Staircase",isVertical:!0,category:["lightIndustrial","residential","office","parking"]},elevator:{name:"Elevator",isVertical:!0,category:["lightIndustrial","residential","office","parking"]}}},drive:{name:"Drive",isHidden:!0,spaceUsage:{parkingSpot:{name:"Parking spot",category:["parking"]},driveway:{name:"Driveway",category:["parking"]},garage:{name:"Garage",category:["residential"]}}},produce:{name:"Produce",isHidden:!0,spaceUsage:{productionArea:{name:"Production area",category:["lightIndustrial"]}}},void:{isHidden:!0,name:"Void",spaceUsage:{shaft:{name:"Shaft",isVertical:!0,category:["lightIndustrial","residential","office","parking"]},buildingOpening:{name:"Building opening",isVertical:!0,category:["lightIndustrial","residential","office","parking"]},floorOpening:{name:"Floor opening",isVertical:!0,category:["lightIndustrial","residential","office","parking"]}}},undefined:{isHidden:!0,spaceUsage:{undefined:{name:"Undefined",category:["residential","office"],isHidden:!0}}}},Wa={};function Ya(t,e,i){let s=ft(...t),r=ft(...e),n=ft(...i),o=dt(),a=dt(),l=dt();return yt(o,s,n),yt(a,r,n),xt(l,o,a),vt(l,l),[...l]}function Ha(t){let{indices:e,vertices:i}=t,s=[],r=[],n=[],o=ls(i);for(let u=0;u<i.length;u+=3){let t=i[u],e=i[u+1],n=i[u+2];s.push([t,e,n]),r.push([t,n])}for(let u=0;u<e.length;u+=3){let t=e[u],i=e[u+1],o=e[u+2];Ya(s[t],s[i],s[o])[1]<.01||n.push([r[t],r[i],r[o]])}let a=[],l=[[]];if(!n.length)return{outlines:a,holes:l,boundingBox:o};let h=Q(Y(n),.0015);h=h.filter(t=>t&&t.length&&K(t)>5e-4);for(let u of h)Ti(u)?l[0].push(u):a.push(u);return{outlines:a,holes:l,boundingBox:o}}function $a(t,e={}){let i=function(t,e=nt(),i=/* @__PURE__ */new Map,s=!0){let r=[],n=t.spaceGraph;if("geometries"in t&&t.geometries)for(let o of t.geometries){let t,a,l,h;if("string"==typeof o){if(t=n.geometriesById[o],!t){be.warn(`Geometry ${o} not found.`);continue}a=[0,0,0],l=0,h=[0,1,0]}else{if("reference:geometry"!==o.type){be.warn(`Operation ${o.type} not supported.`);continue}let e=o.geometry;if("string"==typeof e){if(t=n.geometriesById[e],!t){be.warn(`Geometry ${e} not found.`);continue}}else t=e;a=o.position??[0,0,0],l=o.rotation??0,h=o.rotationAxis??[0,1,0]}let u=Ve(a,l);for(let o of u){let a=Ai(o.position,o.rotation,h);s&&(a=ht(nt(),e,a));let l=[];if("geometry:uri"===t.type&&"data3d"===t.format){let e=i.get(t.uri),s=(null==e?void 0:e.meshGeometries)||{};for(let t in s){let e=s[t];l.push(...as(e,n.geometriesById,n.materialsById,[]))}}else l=as(t,n.geometriesById,n.materialsById,[]);let u=wt(),c=dt();ct(u,a),ut(c,a);for(let t of l)Si(t.vertices,a);r.push({meshes:l,rotation:u,position:c})}}return r}(t,e.applyElementMatrix?gr(t,e.parentMatrix):void 0,e.resources),s=[];for(let r of i)for(let t of r.meshes)s.push(Ha(t));return s}Object.keys(Xa).forEach(t=>{const e=Xa[t];Wa[t]={name:e.name,type:"program",category:[]},e.isHidden&&(Wa[t].isHidden=e.isHidden);const i={};Object.keys(Xa[t].spaceUsage).forEach(e=>{const s=Xa[t].spaceUsage[e];Wa[e]={...s,type:"space",program:t},s.category.forEach(t=>{i[t]=!0})}),Wa[t].category=Object.keys(i)}),new Ga({size:256});const ja=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function za(t){return"string"==typeof t&&ja.test(t)}const Va={programs:{care:[{name:"bathroom",tags:[],categories:["residential"]},{name:"kitchen",tags:[],categories:["residential"]},{name:"restroom",tags:[],categories:["lightIndustrial","office","parking","laboratory"]},{name:"shower",tags:[],categories:["lightIndustrial","office","residential","laboratory"]},{name:"toilet",tags:[],categories:["residential"]},{name:"wellnessRoom",tags:[],categories:["lightIndustrial","office","laboratory"]}],circulate:[{name:"corridor",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"elevator",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"foyer",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"staircase",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]}],drive:[{name:"driveway",tags:[],categories:["parking"]},{name:"garage",tags:[],categories:["residential"]},{name:"parkingSpot",tags:[],categories:["parking"]}],live:[{name:"bedroom",tags:[],categories:["residential"]},{name:"dining",tags:[],categories:["residential"]},{name:"dining_living",tags:[],categories:["residential"]},{name:"homeOffice",tags:[],categories:["residential"]},{name:"living",tags:[],categories:["residential"]}],meet:[{name:"assembly",tags:[],categories:["office"]},{name:"boardRoom",tags:[],categories:["office"]},{name:"hub",tags:[],categories:["office"]},{name:"meetingRoom",tags:[],categories:["office"]},{name:"trainingRoom",tags:[],categories:["office"]}],none:[{name:"generic",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]}],produce:[{name:"productionArea",tags:[],categories:["lightIndustrial"]}],research:[{name:"lab",tags:[],categories:["lightIndustrial","laboratory"]}],socialize:[{name:"balcony",tags:["outdoor"],categories:["office","residential"]},{name:"cafe",tags:[],categories:["office","laboratory"]},{name:"canteen",tags:[],categories:["office"]},{name:"courtyard",tags:["outdoor"],categories:["office","residential"]},{name:"garden",tags:["outdoor"],categories:["residential"]},{name:"lobby",tags:[],categories:["office","residential","laboratory"]},{name:"lounge",tags:[],categories:["office","laboratory"]},{name:"pantry",tags:[],categories:["office"]},{name:"reception",tags:[],categories:["office","laboratory"]},{name:"rooftop",tags:["outdoor"],categories:["office","residential"]},{name:"terrace",tags:["outdoor"],categories:["office","residential"]}],support:[{name:"chemicalStore",tags:[],categories:["laboratory"]},{name:"cleanRoom",tags:[],categories:["laboratory"]},{name:"coldRoom",tags:[],categories:["laboratory"]},{name:"laundryRoom",tags:[],categories:["residential"]},{name:"loadingDock",tags:[],categories:["lightIndustrial"]},{name:"mailRoom",tags:[],categories:["office"]},{name:"operationalRoom",tags:[],categories:["lightIndustrial","office","parking","laboratory"]},{name:"printStation",tags:[],categories:["office"]},{name:"serviceKitchen",tags:[],categories:["office"]},{name:"serviceRoom",tags:[],categories:["office"]},{name:"storage",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]}],void:[{name:"buildingOpening",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"floorOpening",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"shaft",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]}],work:[{name:"enclosedWorkspace",tags:[],categories:["office"]},{name:"focusRoom",tags:[],categories:["office"]},{name:"openWorkspace",tags:[],categories:["office"]},{name:"privateOffice",tags:[],categories:["office"]}]}},qa="#ffffff",Ja="#0c1829",Ka="#4d586b",Za="#929baa",Qa="#72849e",tl="#f1f2f3",el="#cfd5de",il="#e8ebef",sl="#f7f8fa",rl="#bdd7ff",nl="#3355ff",ol="#dfecff",al="#ab220a",ll={api:{productDataCacheAge:864e5,productContourCacheAge:864e6},hideElements:[],panZoom:!0,preserveViewbox:"center-center",roomStampSize:null,showCeilingLamps:!1,destroyOnDomRemove:!1,ui:{scale:!0,coordinates:!1},spaceLabelMapping:{},theme:{fontFamily:"Inter, Avenir, Verdana, sans-serif",background:{color:sl,showGrid:!1},wallContours:!1,showAssetTextures:!1,elements:{floorPlan:{grayscale:!1},roomStamp:{}}},units:{system:"metric",areaDecimals:0,lengthDecimals:3,roomDimensions:"area"},zoomRange:[3,300]};let hl="archilogic/product",ul="https://storage.archilogic.com";const cl=({apiStorageUrl:t,spaceApiUrl:e,apiProductDataPath:i}={})=>{"string"==typeof t&&(ul=t),"string"==typeof i&&(hl=i),"string"==typeof e&&(R=e)};let dl=new E(["info","warnings","errors"]);function pl(t,e){let i,s=e.product.geometries[0];const r="product:component"===e.product?.type;if("string"==typeof s){let t=s;i=e.spaceGraph.geometriesById[t]}else"reference:geometry"===s?.type&&"string"!=typeof s.geometry&&(i=s.geometry);if(!r&&!("geometry:uri"===i?.type))return Promise.reject("Unsupported product geometry: "+e.product.id);const n=r?["productJson"]:["productJson","productContour"];return t.loadResources(e.product.id,e,n).catch(t=>dl.error(t))}const fl=t=>{const e=[];return t.layout.elementsByType["element:asset"].forEach(t=>{"product"in t&&"product:static"===t.product?.type&&e.push(t)}),Promise.allSettled(e.map(e=>pl(t.loader,e)))};function ml(t){return fetch(`${ul}/${hl}/outline/${t}.json`).then(t=>{if(t.ok)return t.json();throw Error(t.statusText)})}const gl="undefined"==typeof window||"undefined"!=typeof process;let yl;try{yl=!gl&&Ta("al-kvs","al-keyval")}catch(b_){dl.warn("indexedDb initialization failed")}async function vl(t,e,i){if(!yl)return Promise.resolve();i=i||2592e6;try{const s={timeStamp:/* @__PURE__ */(new Date).getTime(),content:e,maxAge:i};return await function(t,e,i=Ia()){return i("readwrite",i=>(i.put(e,t),Ea(i.transaction)))}(t,s,yl),t}catch(s){return}}async function xl(t,e){if(!yl)return Promise.resolve();const i=e||2592e6,s=/* @__PURE__ */(new Date).getTime();let r;try{r=await function(t,e=Ia()){return e("readonly",e=>Ea(e.get(t)))}(t,yl);const e=s-r.timeStamp;if(e>Math.min(r.maxAge,i))return;if(r.content)return r.content}catch(n){return}}const bl="fpe-dc2-";var _l=/* @__PURE__ */(t=>(t[t.None=0]="None",t[t.Default=1]="Default",t[t.Grayscale=2]="Grayscale",t))(_l||{});class wl extends pe.TinyEmitter{constructor(t){super(),this.promiseCache=/* @__PURE__ */new Map,this.loadStages={product:!0,productContour:!0,productTexture:!1},this.queue={productJson:/* @__PURE__ */new Map,productContour:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this.resources={nodes:/* @__PURE__ */new Map,productJson:/* @__PURE__ */new Map,productContour:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this.initialLoading=!0,this._requestCounter=0,this._loadCounter=0;const{settings:e}=t;this.floorPlan=t,this.productContourCacheAge=e.api?.productContourCacheAge,this.productDataCacheAge=e.api?.productDataCacheAge,this.loadStages.productTexture=!!e.theme?.showAssetTextures&&!1!==e.loadTextures,this.on("resource-loaded",this.loadStatus,this)}loadStatus(){const t=this._requestCounter;this._loadCounter++,this.emit("loading-status",{totalCount:t,doneCount:this._loadCounter}),t===this._loadCounter&&this.emit("loading-done",{totalCount:t})}loadResources(t,e,i){return Promise.all(i.map(i=>this.loadResource(t,e,i)))}loadResource(t,e,i){if(this.resources.nodes.has(t)||this.resources.nodes.set(t,/* @__PURE__ */new Set),this.resources.nodes.get(t).add(e),this.queue[i].has(t))return this.queue[i].get(t);let s;switch(this._requestCounter++,i){case"productJson":s=Pl(t,this,e.product);break;case"productContour":this.loadStages.productTexture&&this._requestCounter++,s=El(t,this).then(()=>{if(this.loadStages.productTexture&&!this.resources.texture.has(t)){if(!this.resources.productJson.has(t))return void dl.warn("texture loading failed, no product info yet");const e=`${ul}/${hl}/thumb/${t}.png`;this.resources.texture.set(t,{textureUrl:e,applyFilter:1}),this.emit("product-load-texture",{resourceId:t})}})}return this.queue[i].set(t,s),s}reset(){this.resources={nodes:/* @__PURE__ */new Map,productContour:/* @__PURE__ */new Map,productJson:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this.queue={productContour:/* @__PURE__ */new Map,productJson:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this._loadCounter=0,this._requestCounter=0,this.promiseCache=/* @__PURE__ */new Map,this.initialLoading=!0}}const Pl=(t,e,i)=>{const s=e.floorPlan.spaceGraph;t!==i?.id||s.productsById[t]||s.insertProduct(i);const r=JSON.parse(JSON.stringify(i?.attributes||{}));return Number.isFinite(r.boundingBox?.min[0])||(dl.warn("invalid product bounding box"),delete r.boundingBox),e.resources.productJson.set(t,r),Promise.resolve().then(()=>{e.emit("resource-loaded",{resourceId:t})})},El=async(t,e)=>{const i=bl+t,s=e.promiseCache.get(i);if(s)return s;const r=function(t,e){const i=e.productContourCacheAge,s=i||864e6;if(!t)return Promise.reject("product id missing");const r=bl+t,n=e.promiseCache.get(r);if(n)return n;const o=xl(r,i).then(e=>e||ml(t).then(t=>(vl(r,t,s),t))).catch(t=>{dl.warn(t)});return e.promiseCache.set(r,o),o}(t,e).then(i=>{const s=i,r=e.resources.productJson.get(t);if(!r.boundingBox){dl.warn("product boundingbox missing - creating from contour");let t=W(s);r.boundingBox={min:[t.min[0],0,t.min[1]],max:[t.max[0],0,t.max[1]]}}e.resources.productContour.set(t,s),e.emit("resource-loaded",{resourceId:t})}).catch(()=>{});return e.promiseCache.set(i,r),r};function Tl(t){return t.max.map((e,i)=>e-t.min[i])}function Al(t,e=[0,0]){const{dimensions:i}=t.parameters,s=t.parent;let r=[];if("element:wall"===s?.type){let t=s.parameters.width;r=[[-e[0],-e[1]],[i[0]+e[0],-e[1]],[i[0]+e[0],t+e[1]],[-e[0],t+e[1]]]}return[{type:"curve:polygon",points:r}]}function Il(t,e){const i=t.elements[0]||t,s=e?.[i?.type];return void 0===s||("boolean"==typeof s?s:i.isExternal?s.external:s.internal)}function Sl(t,e={clip:{"element:door":!0,"element:window":!0}}){const i=.01,s=t.elementsByType["element:wall"],r=t.elementsByType["element:boundaryWall"],n=t.elementsByType["element:column"],o=t.elementsByType["element:opening"],a=[];for(const c of o){if(!Il(c,e.clip))continue;const t=Al(c,[0,i]),{position:s,rotation:r}=c,n={position:[s[0],s[2]],rotation:r},o=Oi(t[0].points,n);a.push([o])}const l=[];for(const c of s){let{points:t}=c.geometryProfile;t=$([t],i)[0],l.push([t])}for(const c of n){const{profile:t}=c.parameters;let{points:e}=rs(t);if("curve:rectangle"===t.type){const[i,s]=t.dimensions;e=[[-i/2,-s/2],[i/2,-s/2],[i/2,s/2],[-i/2,s/2]]}e=Oi(e,{position:[c.position[0],c.position[2]],rotation:c.rotation}),e=$([e],i)[0],l.push([e])}for(const c of r){let t=c.boundaries[0].geometryProfile;t=$([t],i)[0],l.push([t])}let{polygons:h}=function(t){if(!t.length||!t[0])return{polygons:[],polyTree:[]};let e=et(t[0]),i=[];for(let n=1;n<t.length;n++)i.push(...et(t[n]));let s=new X.Clipper;s.AddPaths(e,X.PolyType.ptSubject,!0),s.AddPaths(i,X.PolyType.ptClip,!0);let r=new X.PolyTree;return s.Execute(X.ClipType.ctUnion,r,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),H(r)}(l);h=j(h,-.01).polygons,a.length&&(h=V(h,a).polygons);const u=[];for(const c of h){const t=[];for(const e of c){let i=tt(e,.001);i.length&&t.push(i)}t.length&&u.push(t)}return u}const Cl=class t{constructor({options:t={}}={}){this.settings=y(ll),this.fpeId="fpe-"+Math.random().toString(36).replace(/[^a-z]+/g,"").substr(0,3),this.computed={wallContours:[],snapPoints:[],snapMargin:0},this.isBrowser="object"!=typeof process&&"undefined"!=typeof window,this.location={latitude:0,longitude:0,bearing:0},this._emitter=new pe.TinyEmitter,be.setLevels("errors"),this.set(t),this.loader=new wl(this)}on(t,e,i){return this._emitter.on(t,e,i),this}once(t,e,i){return this._emitter.once(t,e,i),this}off(t,e){return this._emitter.off(t,e),this}emit(t,...e){return this._emitter.emit(t,...e),this}loadLayout(t,{skipGeometryCompute:e=!1}={}){this.loadSpaceGraph(t.spaceGraph,{skipGeometryCompute:e,layoutId:t.id})}loadSpaceGraph(t,{skipGeometryCompute:e=!1,layoutId:i}={}){this.loader.initialLoading||this.loader.reset(),this.spaceGraph=t,this.layout=i?t.nodesById[i]:t.nodesByType["spatialStructure:layout"][0],this.layout&&"spatialStructure:layout"===this.layout.type?(e||(Pa(this.layout),function(t){for(let e of t.elements)kr(e)}(this.layout)),this.settings.theme.wallContours&&(this.computed.wallContours=Sl(this.layout)),setTimeout(()=>{this.loader.emit("spaces-loaded")},0),fl(this).then(()=>{const t=this.settings.hideElements.includes("element:asset"),e=0===Object.keys(this.spaceGraph.products).length;this.loader.emit("assets-loaded",!0),(t||e)&&this.loader.emit("loading-done",{totalCount:0})}).catch(t=>dl.warn(t)),this.loader.initialLoading=!1):dl.warn("No layout to load")}loadSpaceGraphJson(t){this.loadSpaceGraph(function(t){return Eo.fromJSON(t)}(t))}async loadFloorById(e,i=this.settings.api){return new Promise(async(r,n)=>{e&&"string"==typeof e||n(`Expected non-empty string floorId parameter; instead got: "${e}"`);try{const n=k({...i,sdkVersion:t.version}),a=new U(n);this.loader.once("assets-loaded",r);const l=await a.getFloorById(e,!1,!1,!0),h=l.properties?.address;if(o=h?.latitude,s(o,90)&&(this.location.latitude=h.latitude),function(t){return s(t,180)}(h?.longitude)&&(this.location.longitude=h.longitude),function(t){return s(t,180)}(h?.bearing)&&(this.location.bearing=h.bearing),!l.layout?.layout)throw new Error(`The floor ${e} has no space graph layout`);this.emit("space-api-floor-loaded",e),this.loadSpaceGraphJson(l.layout.layout)}catch(b_){n(b_)}var o}).catch(t=>{throw this.emit("space-api-floor-error",e,t),t})}set(t={}){const e=this.settings.hideElements?.includes("element:asset");let i=y(t);i.theme&&(i.theme=v(ll.theme,i.theme)),i.ui&&(i.ui={...ll.ui,...i.ui}),i.api&&(i.api={...ll.api,...i.api}),i.units&&(i.units={...ll.units,...i.units});const s=!i.hideElements?.includes("element:asset");for(let r in i)this.settings[r]=i[r];if(this.settings.theme?.elements?.["layout:space"]?.program){const t=this.settings.theme.elements["layout:space"].program,e={wash:"care",operate:"support",common:"socialize"};Object.keys(t).forEach(i=>{Object.keys(e).includes(i)&&(t[e[i]]=t[i],delete t[i])})}this.layout&&(e&&s&&fl(this),i.theme?.wallContours&&!this.computed.wallContours?.length?this.computed.wallContours=Sl(this.layout):!i.theme?.wallContours&&this.computed.wallContours?.length&&(this.computed.wallContours=[])),this.emit("update-settings",this.settings)}getBoundingBox(t=0){const{min:[e,,i],max:[s,,r]}=this.layout.getBoundingBox();return{min:[e-t,i-t],max:[s+t,r+t]}}getResourcesFromPosition(t){const e=this.layout?.spaces?.filter(e=>bi(t,e.geometry.polygons))||[],i=[];return e.forEach(e=>{const s=e.getElements("element:asset").filter(e=>{if(e.product.attributes.subCategories.includes("ceilingLight")&&!this.settings.showCeilingLamps)return;const i=e.getBoundingBoxContour();return i?.length?q(t,i):void 0});i.push(...s)}),{spaces:e,assets:i}}destroy(){delete this.layout,delete this.settings,delete this.utils}};Cl.version="5.1.19";let Ml=Cl;function Ol(t){let{length:e,hingeSide:i,doorSide:s,doorAngle:r,doorType:n,frameThickness:o,frameDepth:a}=t.parameters,l=[],h="right"===i,u="side1"===s,c=u?0:a,d=!1,p=0,f=0;if(r<5&&r>-5){r=20;const t=r/180*Math.PI;p=Math.sin(t),f=Math.cos(t),d=!0}if("singleSwing"===n){let t,i,s,n,a=e-2*o;u?h?(t=0,i=r,s=[o,c],n=[s[0]+f*a,s[1]-p*a]):(t=180-r,i=180,s=[e-o,c],n=[s[0]-f*a,s[1]-p*a]):h?(t=-180,i=-180+r,s=[e-o,c],n=[s[0]-f*a,s[1]+p*a]):(t=360-r,i=360,s=[o,c],n=[s[0]+f*a,s[1]+p*a]),l.push({type:"curve:arc",radius:a,position:s,startAngle:t,endAngle:i}),d&&l.push({type:"curve:line",start:s,end:n})}else if("doubleSwing"===n){let t,i,s,n,a,h,m,g,y=e/2-o;u?(t=0,i=r,s=[o,c],m=[e-o,c],a=180-r,h=180,n=[s[0]+f*y,s[1]-p*y],g=[m[0]-f*y,m[1]-p*y]):(t=360-r,i=360,s=[o,c],m=[e-o,c],a=180,h=180+r,n=[s[0]+f*y,s[1]+p*y],g=[m[0]-f*y,m[1]+p*y]),l.push({type:"curve:arc",radius:y,position:s,startAngle:t,endAngle:i}),l.push({type:"curve:arc",radius:y,position:m,startAngle:a,endAngle:h}),d&&(l.push({type:"curve:line",start:s,end:n}),l.push({type:"curve:line",start:m,end:g}))}return l}function Nl(t){let e=[];switch(t.type){case"element:door":e=Ol(t);break;case"element:stairFlight":e=function(t){let e=t.parent?.elements.find(t=>"element:stairFlight"===t.type);if(e?.id!==t.id||"spiral"===t.parameters.stairFlightType)return[];let{width:i,length:s,height:r}=t.parameters,n=s/Math.round(r/.17);return[{type:"curve:polyline",points:[[n/2-.06,i/2+.12],[n/2+.06,i/2],[n/2-.06,i/2-.12]]}]}(t)}return e}function Ll(t){for(const e of Object.keys(Va.programs)){if(Va.programs[e].find(e=>e.name===t))return e}return""}function Rl(t,e=0){return({"element:door":45,"element:window":45,"element:opening":40,"element:spaceDivider":35,"spatialGraph:edge":35,"element:column":30,"element:wall":30,"element:boundaryWall":30,"element:casework":20,"element:kitchen":20,"element:railing":20,"element:generic":11,"element:asset":10,"element:stairs":5,"element:stairFlight":5,"element:slab":5,"layout:space":1,"annotation:floorPlanDxf":0,"annotation:floorPlanImage":0}[t]||0)+e}const kl={default:{fill:qa,stroke:Za,strokeWidth:"native",fillOpacity:1},selected:{fill:ol,stroke:Za,strokeWidth:1}},Bl=t=>{const e=t.toString(16);return 1===e.length?"0"+e:e},Fl=t=>Number(parseInt(t.slice(1),16));function Dl(t){return"number"==typeof t?t:"string"==typeof t&&t.startsWith("#")?Fl(t):Array.isArray(t)?Fl(((t,e,i)=>"#"+[t,e,i].map(Bl).join(""))(...t)):void 0}const Ul=({settings:t,element:e,elementType:i})=>{const s=t?.theme?.elements;if(!s)return{};let r=s.byId?.[e?.id]||s[i]||s[e?.type]||null;if(e){const t=s["layout:space"];if("layout:space"===e.type){const i=Ll(e.attributes.usage);t?.usage?.[e.attributes.usage]?r=t.usage[e.attributes.usage]:t?.program?.[i]&&(r=t.program[i])}else"element:stairs"!==e.type||r||(t?.usage?.staircase?r=t.usage.staircase:t?.program?.circulate&&(r=t.program.circulate))}return(t=>{const{fill:e,fillOpacity:i,stroke:s,strokeWidth:r,strokeOpacity:n}=t,o={};return e&&(o.fill=Dl(e)),s&&(o.stroke=Dl(s)),"number"==typeof i&&Number.isFinite(i)&&(o.fillOpacity=Math.max(Math.min(i,1),0)),"number"==typeof n&&Number.isFinite(n)&&(o.strokeOpacity=Math.max(Math.min(n,1),0)),"string"==typeof r?"native"===r&&(o.strokeWidth=r):Number.isFinite(r)&&r>=0&&(o.strokeWidth=r),o})(r||{})},Gl=t=>{if(t?.layout?.debugIds){let i=/\d+/.exec(t.id)?.[0]||"0",s=(e=parseInt(i),function(){let t=e+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296});return{fill:Math.round(5*s()*16777215)%16777215,fillOpacity:.5}}var e;return{}},Xl=({style:t,settings:e,element:i,elementType:s})=>{const r="selected"===t?"selected":"default",n=function({element:t,settings:e,elementType:i,state:s="default"}){const r=e?.theme?.showAssetTextures,n={"element:wall":{default:{fill:Ka,stroke:Ka},selected:{fill:Qa,stroke:nl,strokeWidth:"native"}},"element:boundaryWall":{default:{fill:Ka,stroke:Ja},selected:{fill:Qa,stroke:nl}},"element:curtainWall":{default:{fill:tl},selected:{strokeWidth:"native"}},"element:column":{default:{fill:Ka,stroke:Ka},selected:{fill:Qa,stroke:nl,strokeWidth:"native"}},"element:asset":{default:{fill:r?null:tl},selected:{fill:ol,stroke:nl,strokeWidth:.5,alignment:0}},"element:stairs":{default:{fill:sl},selected:{strokeWidth:"native"}},"element:stairFlight":{default:{fill:sl}},"element:slab":{default:{fill:sl}},"layout:space":(()=>{const e={default:{fill:qa,stroke:el},selected:{fill:ol,stroke:el,strokeWidth:"native"}};if(t&&"layout:space"===t.type){const i="kitchen"!==t.attributes.usage&&Ll(t.attributes.usage),s={care:el,circulate:sl};i&&s[i]&&(e.default.fill=s[i]),"void"===i&&(e.default.fillOpacity=.05)}return e})(),"spatialGraph:edge":{default:{fill:el,stroke:Ja,strokeOpacity:.8,strokeWidth:.5},selected:{stroke:nl,strokeWidth:.5}},"element:spaceDivider":{default:{fill:el,stroke:Ja,strokeOpacity:.8,strokeWidth:.5},selected:{stroke:nl,strokeWidth:.5}}}[i]||kl,o=Ul({settings:e,element:t,elementType:i});return"selected"===s?{...kl.default,...n.default,...o,...kl.selected,...n.selected}:{...kl.default,...n.default,...o}}({element:i,elementType:s||i?.type,settings:e,state:r});return{...n,...t?{}:Gl(i),..."object"==typeof t?t:{}}};function Wl(t,e,i=.5){let s=[e[0]-t[0],e[1]-t[1]];return[t[0]+s[0]*i,t[1]+s[1]*i]}function Yl(t,e,i,s=5){const r=[];let n,o,a,l=0;for(let h=0;h<=s;++h)l=h/s,n=Wl(t,e,l),o=Wl(e,i,l),a=Wl(n,o,l),r.push(a);return r}const Hl=(t,e)=>{const i=Math.ceil(48/(2*Math.PI)*t*e),s=Math.ceil(12/(2*Math.PI)*t);return Math.min(100,Math.max(s,i))},$l=t=>{const e={type:"curve:polyline",points:[]};switch(t.type){case"curve:line":e.points=[t.start,t.end];break;case"curve:arc":const i=t.startAngle/180*Math.PI,s=t.endAngle/180*Math.PI-i,r=t.radius,n=Hl(Math.abs(s),r),o=t.position,a=s/n;let l=i;for(let t=0;t<n+1;t++)e.points.push([r*Math.cos(l)+o[0],-r*Math.sin(l)+o[1]]),l+=a;break;case"curve:polyline":e.points=t.points;break;case"curve:quadraticBezier":e.points.push(t.points[0]);for(let h=0;h<=t.points.length-3;h++){let i=t.points[h],s=t.points[h+1],r=t.points[h+2],n=Yl(0===h?i:Wl(i,s),s,h===t.points.length-3?r:Wl(s,r));e.points.push(...n.slice(1))}}return e},jl=(t,e,i=.15)=>{let s,r,n;for(const o of e)if(s=Math.abs(t[0]-o[0]),!(s>i)&&(r=Math.abs(t[1]-o[1]),s<i&&r<i)){n=o;break}return n};function zl(t){const e={10:["ceilingLight","wallLight"],9:["modularMeetingRoom","phoneBooth"],8:["floorLamp","tableLamp","deskDivider","cushion","plant","officeSupply","tableware","decoration","laundry","electronics","kitchen","car"],7:["shelf","cabinet","wardrobe","storageCombination","outdoor","bicycle","people","sink"],6:["highTable","diningTable","conferenceTable","desk"],5:["sofa","armchair","loungeChair","ottoman","sideboard","pedestal"],4:["taskChair","diningChair","conferenceChair","stool","barStool","bench"],3:["shower"],2:["singleBed","doubleBed","daybed","toilet","bathtub"],1:["sideTable","coffeeTable","radiator","nightstand"],0:["rug"]};let i=0;return t.subCategories.forEach(t=>{Object.keys(e).forEach(s=>{let r=parseInt(s);e[s].includes(t)&&r>i&&(i=r)})}),1===i&&t.categories.includes("tables")&&t.boundingBox.max[1]-t.boundingBox.min[1]>.6&&(i=6),i}var Vl=/* @__PURE__ */(t=>(t[t.WEBGL_LEGACY=0]="WEBGL_LEGACY",t[t.WEBGL=1]="WEBGL",t[t.WEBGL2=2]="WEBGL2",t))(Vl||{}),ql=/* @__PURE__ */(t=>(t[t.UNKNOWN=0]="UNKNOWN",t[t.WEBGL=1]="WEBGL",t[t.CANVAS=2]="CANVAS",t))(ql||{}),Jl=/* @__PURE__ */(t=>(t[t.COLOR=16384]="COLOR",t[t.DEPTH=256]="DEPTH",t[t.STENCIL=1024]="STENCIL",t))(Jl||{}),Kl=/* @__PURE__ */(t=>(t[t.NORMAL=0]="NORMAL",t[t.ADD=1]="ADD",t[t.MULTIPLY=2]="MULTIPLY",t[t.SCREEN=3]="SCREEN",t[t.OVERLAY=4]="OVERLAY",t[t.DARKEN=5]="DARKEN",t[t.LIGHTEN=6]="LIGHTEN",t[t.COLOR_DODGE=7]="COLOR_DODGE",t[t.COLOR_BURN=8]="COLOR_BURN",t[t.HARD_LIGHT=9]="HARD_LIGHT",t[t.SOFT_LIGHT=10]="SOFT_LIGHT",t[t.DIFFERENCE=11]="DIFFERENCE",t[t.EXCLUSION=12]="EXCLUSION",t[t.HUE=13]="HUE",t[t.SATURATION=14]="SATURATION",t[t.COLOR=15]="COLOR",t[t.LUMINOSITY=16]="LUMINOSITY",t[t.NORMAL_NPM=17]="NORMAL_NPM",t[t.ADD_NPM=18]="ADD_NPM",t[t.SCREEN_NPM=19]="SCREEN_NPM",t[t.NONE=20]="NONE",t[t.SRC_OVER=0]="SRC_OVER",t[t.SRC_IN=21]="SRC_IN",t[t.SRC_OUT=22]="SRC_OUT",t[t.SRC_ATOP=23]="SRC_ATOP",t[t.DST_OVER=24]="DST_OVER",t[t.DST_IN=25]="DST_IN",t[t.DST_OUT=26]="DST_OUT",t[t.DST_ATOP=27]="DST_ATOP",t[t.ERASE=26]="ERASE",t[t.SUBTRACT=28]="SUBTRACT",t[t.XOR=29]="XOR",t))(Kl||{}),Zl=/* @__PURE__ */(t=>(t[t.POINTS=0]="POINTS",t[t.LINES=1]="LINES",t[t.LINE_LOOP=2]="LINE_LOOP",t[t.LINE_STRIP=3]="LINE_STRIP",t[t.TRIANGLES=4]="TRIANGLES",t[t.TRIANGLE_STRIP=5]="TRIANGLE_STRIP",t[t.TRIANGLE_FAN=6]="TRIANGLE_FAN",t))(Zl||{}),Ql=/* @__PURE__ */(t=>(t[t.RGBA=6408]="RGBA",t[t.RGB=6407]="RGB",t[t.RG=33319]="RG",t[t.RED=6403]="RED",t[t.RGBA_INTEGER=36249]="RGBA_INTEGER",t[t.RGB_INTEGER=36248]="RGB_INTEGER",t[t.RG_INTEGER=33320]="RG_INTEGER",t[t.RED_INTEGER=36244]="RED_INTEGER",t[t.ALPHA=6406]="ALPHA",t[t.LUMINANCE=6409]="LUMINANCE",t[t.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",t[t.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",t[t.DEPTH_STENCIL=34041]="DEPTH_STENCIL",t))(Ql||{}),th=/* @__PURE__ */(t=>(t[t.TEXTURE_2D=3553]="TEXTURE_2D",t[t.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",t[t.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",t[t.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",t[t.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",t[t.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",t[t.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",t))(th||{}),eh=/* @__PURE__ */(t=>(t[t.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",t[t.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",t[t.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",t[t.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",t[t.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",t[t.UNSIGNED_INT=5125]="UNSIGNED_INT",t[t.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",t[t.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",t[t.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",t[t.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",t[t.BYTE=5120]="BYTE",t[t.SHORT=5122]="SHORT",t[t.INT=5124]="INT",t[t.FLOAT=5126]="FLOAT",t[t.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",t[t.HALF_FLOAT=36193]="HALF_FLOAT",t))(eh||{}),ih=/* @__PURE__ */(t=>(t[t.FLOAT=0]="FLOAT",t[t.INT=1]="INT",t[t.UINT=2]="UINT",t))(ih||{}),sh=/* @__PURE__ */(t=>(t[t.NEAREST=0]="NEAREST",t[t.LINEAR=1]="LINEAR",t))(sh||{}),rh=/* @__PURE__ */(t=>(t[t.CLAMP=33071]="CLAMP",t[t.REPEAT=10497]="REPEAT",t[t.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",t))(rh||{}),nh=/* @__PURE__ */(t=>(t[t.OFF=0]="OFF",t[t.POW2=1]="POW2",t[t.ON=2]="ON",t[t.ON_MANUAL=3]="ON_MANUAL",t))(nh||{}),oh=/* @__PURE__ */(t=>(t[t.NPM=0]="NPM",t[t.UNPACK=1]="UNPACK",t[t.PMA=2]="PMA",t[t.NO_PREMULTIPLIED_ALPHA=0]="NO_PREMULTIPLIED_ALPHA",t[t.PREMULTIPLY_ON_UPLOAD=1]="PREMULTIPLY_ON_UPLOAD",t[t.PREMULTIPLIED_ALPHA=2]="PREMULTIPLIED_ALPHA",t))(oh||{}),ah=/* @__PURE__ */(t=>(t[t.NO=0]="NO",t[t.YES=1]="YES",t[t.AUTO=2]="AUTO",t[t.BLEND=0]="BLEND",t[t.CLEAR=1]="CLEAR",t[t.BLIT=2]="BLIT",t))(ah||{}),lh=/* @__PURE__ */(t=>(t[t.AUTO=0]="AUTO",t[t.MANUAL=1]="MANUAL",t))(lh||{}),hh=/* @__PURE__ */(t=>(t.LOW="lowp",t.MEDIUM="mediump",t.HIGH="highp",t))(hh||{}),uh=/* @__PURE__ */(t=>(t[t.NONE=0]="NONE",t[t.SCISSOR=1]="SCISSOR",t[t.STENCIL=2]="STENCIL",t[t.SPRITE=3]="SPRITE",t[t.COLOR=4]="COLOR",t))(uh||{}),ch=/* @__PURE__ */(t=>(t[t.NONE=0]="NONE",t[t.LOW=2]="LOW",t[t.MEDIUM=4]="MEDIUM",t[t.HIGH=8]="HIGH",t))(ch||{}),dh=/* @__PURE__ */(t=>(t[t.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",t[t.ARRAY_BUFFER=34962]="ARRAY_BUFFER",t[t.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",t))(dh||{});const ph={ADAPTER:{createCanvas:(t,e)=>{const i=document.createElement("canvas");return i.width=t,i.height=e,i},getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(t,e)=>fetch(t,e),parseXML:t=>(new DOMParser).parseFromString(t,"text/xml")},RESOLUTION:1,CREATE_IMAGE_BITMAP:!1,ROUND_PIXELS:!1};var fh=/iPhone/i,mh=/iPod/i,gh=/iPad/i,yh=/\biOS-universal(?:.+)Mac\b/i,vh=/\bAndroid(?:.+)Mobile\b/i,xh=/Android/i,bh=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,_h=/Silk/i,wh=/Windows Phone/i,Ph=/\bWindows(?:.+)ARM\b/i,Eh=/BlackBerry/i,Th=/BB10/i,Ah=/Opera Mini/i,Ih=/\b(CriOS|Chrome)(?:.+)Mobile/i,Sh=/Mobile(?:.+)Firefox\b/i,Ch=function(t){return void 0!==t&&"MacIntel"===t.platform&&"number"==typeof t.maxTouchPoints&&t.maxTouchPoints>1&&"undefined"==typeof MSStream};function Mh(t){var e={userAgent:"",platform:"",maxTouchPoints:0};t||"undefined"==typeof navigator?"string"==typeof t?e.userAgent=t:t&&t.userAgent&&(e={userAgent:t.userAgent,platform:t.platform,maxTouchPoints:t.maxTouchPoints||0}):e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0};var i=e.userAgent,s=i.split("[FBAN");void 0!==s[1]&&(i=s[0]),void 0!==(s=i.split("Twitter"))[1]&&(i=s[0]);var r=function(t){return function(e){return e.test(t)}}(i),n={apple:{phone:r(fh)&&!r(wh),ipod:r(mh),tablet:!r(fh)&&(r(gh)||Ch(e))&&!r(wh),universal:r(yh),device:(r(fh)||r(mh)||r(gh)||r(yh)||Ch(e))&&!r(wh)},amazon:{phone:r(bh),tablet:!r(bh)&&r(_h),device:r(bh)||r(_h)},android:{phone:!r(wh)&&r(bh)||!r(wh)&&r(vh),tablet:!r(wh)&&!r(bh)&&!r(vh)&&(r(_h)||r(xh)),device:!r(wh)&&(r(bh)||r(_h)||r(vh)||r(xh))||r(/\bokhttp\b/i)},windows:{phone:r(wh),tablet:r(Ph),device:r(wh)||r(Ph)},other:{blackberry:r(Eh),blackberry10:r(Th),opera:r(Ah),firefox:r(Sh),chrome:r(Ih),device:r(Eh)||r(Th)||r(Ah)||r(Sh)||r(Ih)},any:!1,phone:!1,tablet:!1};return n.any=n.apple.device||n.android.device||n.windows.device||n.other.device,n.phone=n.apple.phone||n.android.phone||n.windows.phone,n.tablet=n.apple.tablet||n.android.tablet||n.windows.tablet,n}const Oh=(Mh.default??Mh)(globalThis.navigator);ph.RETINA_PREFIX=/@([0-9\.]+)x/,ph.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT=!1;var Nh,Lh={exports:{}};var Rh=(Nh||(Nh=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function s(){}function r(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function n(t,e,s,n,o){if("function"!=typeof s)throw new TypeError("The listener must be a function");var a=new r(s,n||t,o),l=i?i+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],a]:t._events[l].push(a):(t._events[l]=a,t._eventsCount++),t}function o(t,e){0===--t._eventsCount?t._events=new s:delete t._events[e]}function a(){this._events=new s,this._eventsCount=0}Object.create&&(s.prototype=/* @__PURE__ */Object.create(null),(new s).__proto__||(i=!1)),a.prototype.eventNames=function(){var t,s,r=[];if(0===this._eventsCount)return r;for(s in t=this._events)e.call(t,s)&&r.push(i?s.slice(1):s);return Object.getOwnPropertySymbols?r.concat(Object.getOwnPropertySymbols(t)):r},a.prototype.listeners=function(t){var e=i?i+t:t,s=this._events[e];if(!s)return[];if(s.fn)return[s.fn];for(var r=0,n=s.length,o=new Array(n);r<n;r++)o[r]=s[r].fn;return o},a.prototype.listenerCount=function(t){var e=i?i+t:t,s=this._events[e];return s?s.fn?1:s.length:0},a.prototype.emit=function(t,e,s,r,n,o){var a=i?i+t:t;if(!this._events[a])return!1;var l,h,u=this._events[a],c=arguments.length;if(u.fn){switch(u.once&&this.removeListener(t,u.fn,void 0,!0),c){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,e),!0;case 3:return u.fn.call(u.context,e,s),!0;case 4:return u.fn.call(u.context,e,s,r),!0;case 5:return u.fn.call(u.context,e,s,r,n),!0;case 6:return u.fn.call(u.context,e,s,r,n,o),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];u.fn.apply(u.context,l)}else{var d,p=u.length;for(h=0;h<p;h++)switch(u[h].once&&this.removeListener(t,u[h].fn,void 0,!0),c){case 1:u[h].fn.call(u[h].context);break;case 2:u[h].fn.call(u[h].context,e);break;case 3:u[h].fn.call(u[h].context,e,s);break;case 4:u[h].fn.call(u[h].context,e,s,r);break;default:if(!l)for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];u[h].fn.apply(u[h].context,l)}}return!0},a.prototype.on=function(t,e,i){return n(this,t,e,i,!1)},a.prototype.once=function(t,e,i){return n(this,t,e,i,!0)},a.prototype.removeListener=function(t,e,s,r){var n=i?i+t:t;if(!this._events[n])return this;if(!e)return o(this,n),this;var a=this._events[n];if(a.fn)a.fn!==e||r&&!a.once||s&&a.context!==s||o(this,n);else{for(var l=0,h=[],u=a.length;l<u;l++)(a[l].fn!==e||r&&!a[l].once||s&&a[l].context!==s)&&h.push(a[l]);h.length?this._events[n]=1===h.length?h[0]:h:o(this,n)}return this},a.prototype.removeAllListeners=function(t){var e;return t?(e=i?i+t:t,this._events[e]&&o(this,e)):(this._events=new s,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,t.exports=a}(Lh)),Lh.exports);const kh=/* @__PURE__ */It(Rh);var Bh,Fh,Dh,Uh={},Gh={exports:{}},Xh=Gh.exports;function Wh(){return Dh?Fh:(Dh=1,Fh=TypeError)}const Yh=/* @__PURE__ */St(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var Hh,$h,jh,zh,Vh,qh,Jh,Kh,Zh,Qh,tu,eu,iu,su,ru,nu,ou,au,lu,hu,uu,cu,du,pu,fu,mu,gu,yu,vu,xu,bu,_u,wu,Pu,Eu,Tu,Au,Iu,Su,Cu,Mu,Ou,Nu,Lu,Ru,ku,Bu,Fu,Du,Uu,Gu,Xu,Wu,Yu,Hu,$u,ju,zu,Vu,qu,Ju,Ku,Zu,Qu,tc,ec,ic,sc,rc,nc,oc,ac,lc,hc,uc,cc,dc,pc,fc,mc,gc,yc,vc,xc,bc,_c,wc,Pc,Ec;function Tc(){if($h)return Hh;$h=1;var t="function"==typeof Map&&Map.prototype,e=Object.getOwnPropertyDescriptor&&t?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,i=t&&e&&"function"==typeof e.get?e.get:null,s=t&&Map.prototype.forEach,r="function"==typeof Set&&Set.prototype,n=Object.getOwnPropertyDescriptor&&r?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,o=r&&n&&"function"==typeof n.get?n.get:null,a=r&&Set.prototype.forEach,l="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,h="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,u="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,c=Boolean.prototype.valueOf,d=Object.prototype.toString,p=Function.prototype.toString,f=String.prototype.match,m=String.prototype.slice,g=String.prototype.replace,y=String.prototype.toUpperCase,v=String.prototype.toLowerCase,x=RegExp.prototype.test,b=Array.prototype.concat,_=Array.prototype.join,w=Array.prototype.slice,P=Math.floor,E="function"==typeof BigInt?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,A="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,I="function"==typeof Symbol&&"object"==typeof Symbol.iterator,S="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===I||"symbol")?Symbol.toStringTag:null,C=Object.prototype.propertyIsEnumerable,M=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function O(t,e){if(t===1/0||t===-1/0||t!=t||t&&t>-1e3&&t<1e3||x.call(/e/,e))return e;var i=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof t){var s=t<0?-P(-t):P(t);if(s!==t){var r=String(s),n=m.call(e,r.length+1);return g.call(r,i,"$&_")+"."+g.call(g.call(n,/([0-9]{3})/g,"$&_"),/_$/,"")}}return g.call(e,i,"$&_")}var N=Yh,L=N.custom,R=W(L)?L:null,k={__proto__:null,double:'"',single:"'"},B={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};function F(t,e,i){var s=i.quoteStyle||e,r=k[s];return r+t+r}function D(t){return g.call(String(t),/"/g,"&quot;")}function U(t){return!S||!("object"==typeof t&&(S in t||void 0!==t[S]))}function G(t){return"[object Array]"===$(t)&&U(t)}function X(t){return"[object RegExp]"===$(t)&&U(t)}function W(t){if(I)return t&&"object"==typeof t&&t instanceof Symbol;if("symbol"==typeof t)return!0;if(!t||"object"!=typeof t||!A)return!1;try{return A.call(t),!0}catch(e){}return!1}Hh=function t(e,r,n,d){var y=r||{};if(H(y,"quoteStyle")&&!H(k,y.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(H(y,"maxStringLength")&&("number"==typeof y.maxStringLength?y.maxStringLength<0&&y.maxStringLength!==1/0:null!==y.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var x=!H(y,"customInspect")||y.customInspect;if("boolean"!=typeof x&&"symbol"!==x)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(H(y,"indent")&&null!==y.indent&&"\t"!==y.indent&&!(parseInt(y.indent,10)===y.indent&&y.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(H(y,"numericSeparator")&&"boolean"!=typeof y.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var P=y.numericSeparator;if(void 0===e)return"undefined";if(null===e)return"null";if("boolean"==typeof e)return e?"true":"false";if("string"==typeof e)return z(e,y);if("number"==typeof e){if(0===e)return 1/0/e>0?"0":"-0";var T=String(e);return P?O(e,T):T}if("bigint"==typeof e){var L=String(e)+"n";return P?O(e,L):L}var B=void 0===y.depth?5:y.depth;if(void 0===n&&(n=0),n>=B&&B>0&&"object"==typeof e)return G(e)?"[Array]":"[Object]";var Y=function(t,e){var i;if("\t"===t.indent)i="\t";else{if(!("number"==typeof t.indent&&t.indent>0))return null;i=_.call(Array(t.indent+1)," ")}return{base:i,prev:_.call(Array(e+1),i)}}(y,n);if(void 0===d)d=[];else if(j(d,e)>=0)return"[Circular]";function V(e,i,s){if(i&&(d=w.call(d)).push(i),s){var r={depth:y.depth};return H(y,"quoteStyle")&&(r.quoteStyle=y.quoteStyle),t(e,r,n+1,d)}return t(e,y,n+1,d)}if("function"==typeof e&&!X(e)){var tt=function(t){if(t.name)return t.name;var e=f.call(p.call(t),/^function\s*([\w$]+)/);if(e)return e[1];return null}(e),et=Q(e,V);return"[Function"+(tt?": "+tt:" (anonymous)")+"]"+(et.length>0?" { "+_.call(et,", ")+" }":"")}if(W(e)){var it=I?g.call(String(e),/^(Symbol\(.*\))_[^)]*$/,"$1"):A.call(e);return"object"!=typeof e||I?it:q(it)}if(function(t){if(!t||"object"!=typeof t)return!1;if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement)return!0;return"string"==typeof t.nodeName&&"function"==typeof t.getAttribute}(e)){for(var st="<"+v.call(String(e.nodeName)),rt=e.attributes||[],nt=0;nt<rt.length;nt++)st+=" "+rt[nt].name+"="+F(D(rt[nt].value),"double",y);return st+=">",e.childNodes&&e.childNodes.length&&(st+="..."),st+="</"+v.call(String(e.nodeName))+">"}if(G(e)){if(0===e.length)return"[]";var ot=Q(e,V);return Y&&!function(t){for(var e=0;e<t.length;e++)if(j(t[e],"\n")>=0)return!1;return!0}(ot)?"["+Z(ot,Y)+"]":"[ "+_.call(ot,", ")+" ]"}if(function(t){return"[object Error]"===$(t)&&U(t)}(e)){var at=Q(e,V);return"cause"in Error.prototype||!("cause"in e)||C.call(e,"cause")?0===at.length?"["+String(e)+"]":"{ ["+String(e)+"] "+_.call(at,", ")+" }":"{ ["+String(e)+"] "+_.call(b.call("[cause]: "+V(e.cause),at),", ")+" }"}if("object"==typeof e&&x){if(R&&"function"==typeof e[R]&&N)return N(e,{depth:B-n});if("symbol"!==x&&"function"==typeof e.inspect)return e.inspect()}if(function(t){if(!i||!t||"object"!=typeof t)return!1;try{i.call(t);try{o.call(t)}catch(st){return!0}return t instanceof Map}catch(e){}return!1}(e)){var lt=[];return s&&s.call(e,function(t,i){lt.push(V(i,e,!0)+" => "+V(t,e))}),K("Map",i.call(e),lt,Y)}if(function(t){if(!o||!t||"object"!=typeof t)return!1;try{o.call(t);try{i.call(t)}catch(e){return!0}return t instanceof Set}catch(s){}return!1}(e)){var ht=[];return a&&a.call(e,function(t){ht.push(V(t,e))}),K("Set",o.call(e),ht,Y)}if(function(t){if(!l||!t||"object"!=typeof t)return!1;try{l.call(t,l);try{h.call(t,h)}catch(st){return!0}return t instanceof WeakMap}catch(e){}return!1}(e))return J("WeakMap");if(function(t){if(!h||!t||"object"!=typeof t)return!1;try{h.call(t,h);try{l.call(t,l)}catch(st){return!0}return t instanceof WeakSet}catch(e){}return!1}(e))return J("WeakSet");if(function(t){if(!u||!t||"object"!=typeof t)return!1;try{return u.call(t),!0}catch(e){}return!1}(e))return J("WeakRef");if(function(t){return"[object Number]"===$(t)&&U(t)}(e))return q(V(Number(e)));if(function(t){if(!t||"object"!=typeof t||!E)return!1;try{return E.call(t),!0}catch(e){}return!1}(e))return q(V(E.call(e)));if(function(t){return"[object Boolean]"===$(t)&&U(t)}(e))return q(c.call(e));if(function(t){return"[object String]"===$(t)&&U(t)}(e))return q(V(String(e)));if("undefined"!=typeof window&&e===window)return"{ [object Window] }";if("undefined"!=typeof globalThis&&e===globalThis||void 0!==At&&e===At)return"{ [object globalThis] }";if(!function(t){return"[object Date]"===$(t)&&U(t)}(e)&&!X(e)){var ut=Q(e,V),ct=M?M(e)===Object.prototype:e instanceof Object||e.constructor===Object,dt=e instanceof Object?"":"null prototype",pt=!ct&&S&&Object(e)===e&&S in e?m.call($(e),8,-1):dt?"Object":"",ft=(ct||"function"!=typeof e.constructor?"":e.constructor.name?e.constructor.name+" ":"")+(pt||dt?"["+_.call(b.call([],pt||[],dt||[]),": ")+"] ":"");return 0===ut.length?ft+"{}":Y?ft+"{"+Z(ut,Y)+"}":ft+"{ "+_.call(ut,", ")+" }"}return String(e)};var Y=Object.prototype.hasOwnProperty||function(t){return t in this};function H(t,e){return Y.call(t,e)}function $(t){return d.call(t)}function j(t,e){if(t.indexOf)return t.indexOf(e);for(var i=0,s=t.length;i<s;i++)if(t[i]===e)return i;return-1}function z(t,e){if(t.length>e.maxStringLength){var i=t.length-e.maxStringLength,s="... "+i+" more character"+(i>1?"s":"");return z(m.call(t,0,e.maxStringLength),e)+s}var r=B[e.quoteStyle||"single"];return r.lastIndex=0,F(g.call(g.call(t,r,"\\$1"),/[\x00-\x1f]/g,V),"single",e)}function V(t){var e=t.charCodeAt(0),i={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return i?"\\"+i:"\\x"+(e<16?"0":"")+y.call(e.toString(16))}function q(t){return"Object("+t+")"}function J(t){return t+" { ? }"}function K(t,e,i,s){return t+" ("+e+") {"+(s?Z(i,s):_.call(i,", "))+"}"}function Z(t,e){if(0===t.length)return"";var i="\n"+e.prev+e.base;return i+_.call(t,","+i)+"\n"+e.prev}function Q(t,e){var i=G(t),s=[];if(i){s.length=t.length;for(var r=0;r<t.length;r++)s[r]=H(t,r)?e(t[r],t):""}var n,o="function"==typeof T?T(t):[];if(I){n={};for(var a=0;a<o.length;a++)n["$"+o[a]]=o[a]}for(var l in t)H(t,l)&&(i&&String(Number(l))===l&&l<t.length||I&&n["$"+l]instanceof Symbol||(x.call(/[^\w$]/,l)?s.push(e(l,t)+": "+e(t[l],t)):s.push(l+": "+e(t[l],t))));if("function"==typeof T)for(var h=0;h<o.length;h++)C.call(t,o[h])&&s.push("["+e(o[h])+"]: "+e(t[o[h]],t));return s}return Hh}function Ac(){if(zh)return jh;zh=1;var t=/* @__PURE__ */Tc(),e=/* @__PURE__ */Wh(),i=function(t,e,i){for(var s,r=t;null!=(s=r.next);r=s)if(s.key===e)return r.next=s.next,i||(s.next=t.next,t.next=s),s};return jh=function(){var s,r={assert:function(i){if(!r.has(i))throw new e("Side channel does not contain "+t(i))},delete:function(t){var e=s&&s.next,r=function(t,e){if(t)return i(t,e,!0)}(s,t);return r&&e&&e===r&&(s=void 0),!!r},get:function(t){return function(t,e){if(t){var s=i(t,e);return s&&s.value}}(s,t)},has:function(t){return function(t,e){return!!t&&!!i(t,e)}(s,t)},set:function(t,e){s||(s={next:void 0}),function(t,e,s){var r=i(t,e);r?r.value=s:t.next={key:e,next:t.next,value:s}}(s,t,e)}};return r}}function Ic(){return qh?Vh:(qh=1,Vh=Object)}function Sc(){return Kh?Jh:(Kh=1,Jh=Error)}function Cc(){return Qh?Zh:(Qh=1,Zh=EvalError)}function Mc(){return eu?tu:(eu=1,tu=RangeError)}function Oc(){return su?iu:(su=1,iu=ReferenceError)}function Nc(){return nu?ru:(nu=1,ru=SyntaxError)}function Lc(){return au?ou:(au=1,ou=URIError)}function Rc(){return hu?lu:(hu=1,lu=Math.abs)}function kc(){return cu?uu:(cu=1,uu=Math.floor)}function Bc(){return pu?du:(pu=1,du=Math.max)}function Fc(){return mu?fu:(mu=1,fu=Math.min)}function Dc(){return yu?gu:(yu=1,gu=Math.pow)}function Uc(){return xu?vu:(xu=1,vu=Math.round)}function Gc(){return _u?bu:(_u=1,bu=Number.isNaN||function(t){return t!=t})}function Xc(){if(Pu)return wu;Pu=1;var t=/* @__PURE__ */Gc();return wu=function(e){return t(e)||0===e?e:e<0?-1:1}}function Wc(){return Tu?Eu:(Tu=1,Eu=Object.getOwnPropertyDescriptor)}function Yc(){if(Iu)return Au;Iu=1;var t=/* @__PURE__ */Wc();if(t)try{t([],"length")}catch(e){t=null}return Au=t}function Hc(){if(Cu)return Su;Cu=1;var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch(e){t=!1}return Su=t}function $c(){if(Lu)return Nu;Lu=1;var t="undefined"!=typeof Symbol&&Symbol,e=Ou?Mu:(Ou=1,Mu=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var t={},e=/* @__PURE__ */Symbol("test"),i=Object(e);if("string"==typeof e)return!1;if("[object Symbol]"!==Object.prototype.toString.call(e))return!1;if("[object Symbol]"!==Object.prototype.toString.call(i))return!1;for(var s in t[e]=42,t)return!1;if("function"==typeof Object.keys&&0!==Object.keys(t).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(t).length)return!1;var r=Object.getOwnPropertySymbols(t);if(1!==r.length||r[0]!==e)return!1;if(!Object.prototype.propertyIsEnumerable.call(t,e))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var n=Object.getOwnPropertyDescriptor(t,e);if(42!==n.value||!0!==n.enumerable)return!1}return!0});return Nu=function(){return"function"==typeof t&&("function"==typeof Symbol&&("symbol"==typeof t("foo")&&("symbol"==typeof/* @__PURE__ */Symbol("bar")&&e())))}}function jc(){return ku?Ru:(ku=1,Ru="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function zc(){return Fu?Bu:(Fu=1,Bu=/* @__PURE__ */Ic().getPrototypeOf||null)}function Vc(){if(Xu)return Gu;Xu=1;var t=function(){if(Uu)return Du;Uu=1;var t=Object.prototype.toString,e=Math.max,i=function(t,e){for(var i=[],s=0;s<t.length;s+=1)i[s]=t[s];for(var r=0;r<e.length;r+=1)i[r+t.length]=e[r];return i};return Du=function(s){var r=this;if("function"!=typeof r||"[object Function]"!==t.apply(r))throw new TypeError("Function.prototype.bind called on incompatible "+r);for(var n,o=function(t){for(var e=[],i=1,s=0;i<t.length;i+=1,s+=1)e[s]=t[i];return e}(arguments),a=e(0,r.length-o.length),l=[],h=0;h<a;h++)l[h]="$"+h;if(n=Function("binder","return function ("+function(t,e){for(var i="",s=0;s<t.length;s+=1)i+=t[s],s+1<t.length&&(i+=e);return i}(l,",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof n){var t=r.apply(this,i(o,arguments));return Object(t)===t?t:this}return r.apply(s,i(o,arguments))}),r.prototype){var u=function(){};u.prototype=r.prototype,n.prototype=new u,u.prototype=null}return n},Du}();return Gu=Function.prototype.bind||t}function qc(){return Yu?Wu:(Yu=1,Wu=Function.prototype.call)}function Jc(){return $u?Hu:($u=1,Hu=Function.prototype.apply)}function Kc(){if(qu)return Vu;qu=1;var t=Vc(),e=Jc(),i=qc(),s=zu?ju:(zu=1,ju="undefined"!=typeof Reflect&&Reflect&&Reflect.apply);return Vu=s||t.call(i,e)}function Zc(){if(Ku)return Ju;Ku=1;var t=Vc(),e=/* @__PURE__ */Wh(),i=qc(),s=Kc();return Ju=function(r){if(r.length<1||"function"!=typeof r[0])throw new e("a function is required");return s(t,i,r)}}function Qc(){if(Qu)return Zu;Qu=1;var t,e=Zc(),i=/* @__PURE__ */Yc();try{t=[].__proto__===Array.prototype}catch(o){if(!o||"object"!=typeof o||!("code"in o)||"ERR_PROTO_ACCESS"!==o.code)throw o}var s=!!t&&i&&i(Object.prototype,"__proto__"),r=Object,n=r.getPrototypeOf;return Zu=s&&"function"==typeof s.get?e([s.get]):"function"==typeof n&&function(t){return n(null==t?t:r(t))}}function td(){if(sc)return ic;sc=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,i=Vc();return ic=i.call(t,e)}function ed(){if(nc)return rc;var t;nc=1;var e=/* @__PURE__ */Ic(),i=/* @__PURE__ */Sc(),s=/* @__PURE__ */Cc(),r=/* @__PURE__ */Mc(),n=/* @__PURE__ */Oc(),o=/* @__PURE__ */Nc(),a=/* @__PURE__ */Wh(),l=/* @__PURE__ */Lc(),h=/* @__PURE__ */Rc(),u=/* @__PURE__ */kc(),c=/* @__PURE__ */Bc(),d=/* @__PURE__ */Fc(),p=/* @__PURE__ */Dc(),f=/* @__PURE__ */Uc(),m=/* @__PURE__ */Xc(),g=Function,y=function(t){try{return g('"use strict"; return ('+t+").constructor;")()}catch(e){}},v=/* @__PURE__ */Yc(),x=/* @__PURE__ */Hc(),b=function(){throw new a},_=v?function(){try{return b}catch(t){try{return v(arguments,"callee").get}catch(e){return b}}}():b,w=$c()(),P=function(){if(ec)return tc;ec=1;var t=jc(),e=zc(),i=/* @__PURE__ */Qc();return tc=t?function(e){return t(e)}:e?function(t){if(!t||"object"!=typeof t&&"function"!=typeof t)throw new TypeError("getProto: not an object");return e(t)}:i?function(t){return i(t)}:null}(),E=zc(),T=jc(),A=Jc(),I=qc(),S={},C="undefined"!=typeof Uint8Array&&P?P(Uint8Array):t,M={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?t:ArrayBuffer,"%ArrayIteratorPrototype%":w&&P?P([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":S,"%AsyncGenerator%":S,"%AsyncGeneratorFunction%":S,"%AsyncIteratorPrototype%":S,"%Atomics%":"undefined"==typeof Atomics?t:Atomics,"%BigInt%":"undefined"==typeof BigInt?t:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?t:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":s,"%Float16Array%":"undefined"==typeof Float16Array?t:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?t:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?t:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?t:FinalizationRegistry,"%Function%":g,"%GeneratorFunction%":S,"%Int8Array%":"undefined"==typeof Int8Array?t:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?t:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":w&&P?P(P([][Symbol.iterator]())):t,"%JSON%":"object"==typeof JSON?JSON:t,"%Map%":"undefined"==typeof Map?t:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&w&&P?P(/* @__PURE__ */(new Map)[Symbol.iterator]()):t,"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":v,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?t:Promise,"%Proxy%":"undefined"==typeof Proxy?t:Proxy,"%RangeError%":r,"%ReferenceError%":n,"%Reflect%":"undefined"==typeof Reflect?t:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?t:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&w&&P?P(/* @__PURE__ */(new Set)[Symbol.iterator]()):t,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":w&&P?P(""[Symbol.iterator]()):t,"%Symbol%":w?Symbol:t,"%SyntaxError%":o,"%ThrowTypeError%":_,"%TypedArray%":C,"%TypeError%":a,"%Uint8Array%":"undefined"==typeof Uint8Array?t:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?t:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?t:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?t:Uint32Array,"%URIError%":l,"%WeakMap%":"undefined"==typeof WeakMap?t:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?t:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?t:WeakSet,"%Function.prototype.call%":I,"%Function.prototype.apply%":A,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":E,"%Math.abs%":h,"%Math.floor%":u,"%Math.max%":c,"%Math.min%":d,"%Math.pow%":p,"%Math.round%":f,"%Math.sign%":m,"%Reflect.getPrototypeOf%":T};if(P)try{null.error}catch(H){var O=P(P(H));M["%Error.prototype%"]=O}var N=function t(e){var i;if("%AsyncFunction%"===e)i=y("async function () {}");else if("%GeneratorFunction%"===e)i=y("function* () {}");else if("%AsyncGeneratorFunction%"===e)i=y("async function* () {}");else if("%AsyncGenerator%"===e){var s=t("%AsyncGeneratorFunction%");s&&(i=s.prototype)}else if("%AsyncIteratorPrototype%"===e){var r=t("%AsyncGenerator%");r&&P&&(i=P(r.prototype))}return M[e]=i,i},L={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},R=Vc(),k=/* @__PURE__ */td(),B=R.call(I,Array.prototype.concat),F=R.call(A,Array.prototype.splice),D=R.call(I,String.prototype.replace),U=R.call(I,String.prototype.slice),G=R.call(I,RegExp.prototype.exec),X=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,W=/\\(\\)?/g,Y=function(t,e){var i,s=t;if(k(L,s)&&(s="%"+(i=L[s])[0]+"%"),k(M,s)){var r=M[s];if(r===S&&(r=N(s)),void 0===r&&!e)throw new a("intrinsic "+t+" exists, but is not available. Please file an issue!");return{alias:i,name:s,value:r}}throw new o("intrinsic "+t+" does not exist!")};return rc=function(t,e){if("string"!=typeof t||0===t.length)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof e)throw new a('"allowMissing" argument must be a boolean');if(null===G(/^%?[^%]*%?$/,t))throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var i=function(t){var e=U(t,0,1),i=U(t,-1);if("%"===e&&"%"!==i)throw new o("invalid intrinsic syntax, expected closing `%`");if("%"===i&&"%"!==e)throw new o("invalid intrinsic syntax, expected opening `%`");var s=[];return D(t,X,function(t,e,i,r){s[s.length]=i?D(r,W,"$1"):e||t}),s}(t),s=i.length>0?i[0]:"",r=Y("%"+s+"%",e),n=r.name,l=r.value,h=!1,u=r.alias;u&&(s=u[0],F(i,B([0,1],u)));for(var c=1,d=!0;c<i.length;c+=1){var p=i[c],f=U(p,0,1),m=U(p,-1);if(('"'===f||"'"===f||"`"===f||'"'===m||"'"===m||"`"===m)&&f!==m)throw new o("property names with quotes must have matching quotes");if("constructor"!==p&&d||(h=!0),k(M,n="%"+(s+="."+p)+"%"))l=M[n];else if(null!=l){if(!(p in l)){if(!e)throw new a("base intrinsic for "+t+" exists, but the property is not available.");return}if(v&&c+1>=i.length){var g=v(l,p);l=(d=!!g)&&"get"in g&&!("originalValue"in g.get)?g.get:l[p]}else d=k(l,p),l=l[p];d&&!h&&(M[n]=l)}}return l},rc}function id(){if(ac)return oc;ac=1;var t=/* @__PURE__ */ed(),e=Zc(),i=e([t("%String.prototype.indexOf%")]);return oc=function(s,r){var n=t(s,!!r);return"function"==typeof n&&i(s,".prototype.")>-1?e([n]):n}}function sd(){if(hc)return lc;hc=1;var t=/* @__PURE__ */ed(),e=/* @__PURE__ */id(),i=/* @__PURE__ */Tc(),s=/* @__PURE__ */Wh(),r=t("%Map%",!0),n=e("Map.prototype.get",!0),o=e("Map.prototype.set",!0),a=e("Map.prototype.has",!0),l=e("Map.prototype.delete",!0),h=e("Map.prototype.size",!0);return lc=!!r&&function(){var t,e={assert:function(t){if(!e.has(t))throw new s("Side channel does not contain "+i(t))},delete:function(e){if(t){var i=l(t,e);return 0===h(t)&&(t=void 0),i}return!1},get:function(e){if(t)return n(t,e)},has:function(e){return!!t&&a(t,e)},set:function(e,i){t||(t=new r),o(t,e,i)}};return e}}function rd(){if(pc)return dc;pc=1;var t=/* @__PURE__ */Wh(),e=/* @__PURE__ */Tc(),i=Ac(),s=sd(),r=function(){if(cc)return uc;cc=1;var t=/* @__PURE__ */ed(),e=/* @__PURE__ */id(),i=/* @__PURE__ */Tc(),s=sd(),r=/* @__PURE__ */Wh(),n=t("%WeakMap%",!0),o=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),h=e("WeakMap.prototype.delete",!0);return uc=n?function(){var t,e,u={assert:function(t){if(!u.has(t))throw new r("Side channel does not contain "+i(t))},delete:function(i){if(n&&i&&("object"==typeof i||"function"==typeof i)){if(t)return h(t,i)}else if(s&&e)return e.delete(i);return!1},get:function(i){return n&&i&&("object"==typeof i||"function"==typeof i)&&t?o(t,i):e&&e.get(i)},has:function(i){return n&&i&&("object"==typeof i||"function"==typeof i)&&t?l(t,i):!!e&&e.has(i)},set:function(i,r){n&&i&&("object"==typeof i||"function"==typeof i)?(t||(t=new n),a(t,i,r)):s&&(e||(e=s()),e.set(i,r))}};return u}:s}(),n=r||s||i;return dc=function(){var i,s={assert:function(i){if(!s.has(i))throw new t("Side channel does not contain "+e(i))},delete:function(t){return!!i&&i.delete(t)},get:function(t){return i&&i.get(t)},has:function(t){return!!i&&i.has(t)},set:function(t,e){i||(i=n()),i.set(t,e)}};return s}}function nd(){if(mc)return fc;mc=1;var t=String.prototype.replace,e=/%20/g,i="RFC3986";return fc={default:i,formatters:{RFC1738:function(i){return t.call(i,e,"+")},RFC3986:function(t){return String(t)}},RFC1738:"RFC1738",RFC3986:i}}function od(){if(yc)return gc;yc=1;var t=/* @__PURE__ */nd(),e=Object.prototype.hasOwnProperty,i=Array.isArray,s=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}(),r=function(t,e){for(var i=e&&e.plainObjects?{__proto__:null}:{},s=0;s<t.length;++s)void 0!==t[s]&&(i[s]=t[s]);return i},n=1024;return gc={arrayToObject:r,assign:function(t,e){return Object.keys(e).reduce(function(t,i){return t[i]=e[i],t},t)},combine:function(t,e){return[].concat(t,e)},compact:function(t){for(var e=[{obj:{o:t},prop:"o"}],s=[],r=0;r<e.length;++r)for(var n=e[r],o=n.obj[n.prop],a=Object.keys(o),l=0;l<a.length;++l){var h=a[l],u=o[h];"object"==typeof u&&null!==u&&-1===s.indexOf(u)&&(e.push({obj:o,prop:h}),s.push(u))}return function(t){for(;t.length>1;){var e=t.pop(),s=e.obj[e.prop];if(i(s)){for(var r=[],n=0;n<s.length;++n)void 0!==s[n]&&r.push(s[n]);e.obj[e.prop]=r}}}(e),t},decode:function(t,e,i){var s=t.replace(/\+/g," ");if("iso-8859-1"===i)return s.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(s)}catch(r){return s}},encode:function(e,i,r,o,a){if(0===e.length)return e;var l=e;if("symbol"==typeof e?l=Symbol.prototype.toString.call(e):"string"!=typeof e&&(l=String(e)),"iso-8859-1"===r)return escape(l).replace(/%u[0-9a-f]{4}/gi,function(t){return"%26%23"+parseInt(t.slice(2),16)+"%3B"});for(var h="",u=0;u<l.length;u+=n){for(var c=l.length>=n?l.slice(u,u+n):l,d=[],p=0;p<c.length;++p){var f=c.charCodeAt(p);45===f||46===f||95===f||126===f||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||a===t.RFC1738&&(40===f||41===f)?d[d.length]=c.charAt(p):f<128?d[d.length]=s[f]:f<2048?d[d.length]=s[192|f>>6]+s[128|63&f]:f<55296||f>=57344?d[d.length]=s[224|f>>12]+s[128|f>>6&63]+s[128|63&f]:(p+=1,f=65536+((1023&f)<<10|1023&c.charCodeAt(p)),d[d.length]=s[240|f>>18]+s[128|f>>12&63]+s[128|f>>6&63]+s[128|63&f])}h+=d.join("")}return h},isBuffer:function(t){return!(!t||"object"!=typeof t)&&!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))},isRegExp:function(t){return"[object RegExp]"===Object.prototype.toString.call(t)},maybeMap:function(t,e){if(i(t)){for(var s=[],r=0;r<t.length;r+=1)s.push(e(t[r]));return s}return e(t)},merge:function t(s,n,o){if(!n)return s;if("object"!=typeof n&&"function"!=typeof n){if(i(s))s.push(n);else{if(!s||"object"!=typeof s)return[s,n];(o&&(o.plainObjects||o.allowPrototypes)||!e.call(Object.prototype,n))&&(s[n]=!0)}return s}if(!s||"object"!=typeof s)return[s].concat(n);var a=s;return i(s)&&!i(n)&&(a=r(s,o)),i(s)&&i(n)?(n.forEach(function(i,r){if(e.call(s,r)){var n=s[r];n&&"object"==typeof n&&i&&"object"==typeof i?s[r]=t(n,i,o):s.push(i)}else s[r]=i}),s):Object.keys(n).reduce(function(i,s){var r=n[s];return e.call(i,s)?i[s]=t(i[s],r,o):i[s]=r,i},a)}},gc}function ad(){if(xc)return vc;xc=1;var t=rd(),e=/* @__PURE__ */od(),i=/* @__PURE__ */nd(),s=Object.prototype.hasOwnProperty,r={brackets:function(t){return t+"[]"},comma:"comma",indices:function(t,e){return t+"["+e+"]"},repeat:function(t){return t}},n=Array.isArray,o=Array.prototype.push,a=function(t,e){o.apply(t,n(e)?e:[e])},l=Date.prototype.toISOString,h=i.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,commaRoundTrip:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,filter:void 0,format:h,formatter:i.formatters[h],indices:!1,serializeDate:function(t){return l.call(t)},skipNulls:!1,strictNullHandling:!1},c={},d=function i(s,r,o,l,h,d,p,f,m,g,y,v,x,b,_,w,P,E){for(var T,A=s,I=E,S=0,C=!1;void 0!==(I=I.get(c))&&!C;){var M=I.get(s);if(S+=1,void 0!==M){if(M===S)throw new RangeError("Cyclic object value");C=!0}void 0===I.get(c)&&(S=0)}if("function"==typeof g?A=g(r,A):A instanceof Date?A=x(A):"comma"===o&&n(A)&&(A=e.maybeMap(A,function(t){return t instanceof Date?x(t):t})),null===A){if(d)return m&&!w?m(r,u.encoder,P,"key",b):r;A=""}if("string"==typeof(T=A)||"number"==typeof T||"boolean"==typeof T||"symbol"==typeof T||"bigint"==typeof T||e.isBuffer(A))return m?[_(w?r:m(r,u.encoder,P,"key",b))+"="+_(m(A,u.encoder,P,"value",b))]:[_(r)+"="+_(String(A))];var O,N=[];if(void 0===A)return N;if("comma"===o&&n(A))w&&m&&(A=e.maybeMap(A,m)),O=[{value:A.length>0?A.join(",")||null:void 0}];else if(n(g))O=g;else{var L=Object.keys(A);O=y?L.sort(y):L}var R=f?String(r).replace(/\./g,"%2E"):String(r),k=l&&n(A)&&1===A.length?R+"[]":R;if(h&&n(A)&&0===A.length)return k+"[]";for(var B=0;B<O.length;++B){var F=O[B],D="object"==typeof F&&F&&void 0!==F.value?F.value:A[F];if(!p||null!==D){var U=v&&f?String(F).replace(/\./g,"%2E"):String(F),G=n(A)?"function"==typeof o?o(k,U):k:k+(v?"."+U:"["+U+"]");E.set(s,S);var X=t();X.set(c,E),a(N,i(D,G,o,l,h,d,p,f,"comma"===o&&w&&n(A)?null:m,g,y,v,x,b,_,w,P,X))}}return N};return vc=function(e,o){var l,h=e,c=function(t){if(!t)return u;if(void 0!==t.allowEmptyArrays&&"boolean"!=typeof t.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==t.encodeDotInKeys&&"boolean"!=typeof t.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==t.encoder&&void 0!==t.encoder&&"function"!=typeof t.encoder)throw new TypeError("Encoder has to be a function.");var e=t.charset||u.charset;if(void 0!==t.charset&&"utf-8"!==t.charset&&"iso-8859-1"!==t.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var o=i.default;if(void 0!==t.format){if(!s.call(i.formatters,t.format))throw new TypeError("Unknown format option provided.");o=t.format}var a,l=i.formatters[o],h=u.filter;if(("function"==typeof t.filter||n(t.filter))&&(h=t.filter),a=t.arrayFormat in r?t.arrayFormat:"indices"in t?t.indices?"indices":"repeat":u.arrayFormat,"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var c=void 0===t.allowDots?!0===t.encodeDotInKeys||u.allowDots:!!t.allowDots;return{addQueryPrefix:"boolean"==typeof t.addQueryPrefix?t.addQueryPrefix:u.addQueryPrefix,allowDots:c,allowEmptyArrays:"boolean"==typeof t.allowEmptyArrays?!!t.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:"boolean"==typeof t.charsetSentinel?t.charsetSentinel:u.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:void 0===t.delimiter?u.delimiter:t.delimiter,encode:"boolean"==typeof t.encode?t.encode:u.encode,encodeDotInKeys:"boolean"==typeof t.encodeDotInKeys?t.encodeDotInKeys:u.encodeDotInKeys,encoder:"function"==typeof t.encoder?t.encoder:u.encoder,encodeValuesOnly:"boolean"==typeof t.encodeValuesOnly?t.encodeValuesOnly:u.encodeValuesOnly,filter:h,format:o,formatter:l,serializeDate:"function"==typeof t.serializeDate?t.serializeDate:u.serializeDate,skipNulls:"boolean"==typeof t.skipNulls?t.skipNulls:u.skipNulls,sort:"function"==typeof t.sort?t.sort:null,strictNullHandling:"boolean"==typeof t.strictNullHandling?t.strictNullHandling:u.strictNullHandling}}(o);"function"==typeof c.filter?h=(0,c.filter)("",h):n(c.filter)&&(l=c.filter);var p=[];if("object"!=typeof h||null===h)return"";var f=r[c.arrayFormat],m="comma"===f&&c.commaRoundTrip;l||(l=Object.keys(h)),c.sort&&l.sort(c.sort);for(var g=t(),y=0;y<l.length;++y){var v=l[y],x=h[v];c.skipNulls&&null===x||a(p,d(x,v,f,m,c.allowEmptyArrays,c.strictNullHandling,c.skipNulls,c.encodeDotInKeys,c.encode?c.encoder:null,c.filter,c.sort,c.allowDots,c.serializeDate,c.format,c.formatter,c.encodeValuesOnly,c.charset,g))}var b=p.join(c.delimiter),_=!0===c.addQueryPrefix?"?":"";return c.charsetSentinel&&("iso-8859-1"===c.charset?_+="utf8=%26%2310003%3B&":_+="utf8=%E2%9C%93&"),b.length>0?_+b:""}}function ld(){if(_c)return bc;_c=1;var t=/* @__PURE__ */od(),e=Object.prototype.hasOwnProperty,i=Array.isArray,s={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:t.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1,throwOnLimitExceeded:!1},r=function(t){return t.replace(/&#(\d+);/g,function(t,e){return String.fromCharCode(parseInt(e,10))})},n=function(t,e,i){if(t&&"string"==typeof t&&e.comma&&t.indexOf(",")>-1)return t.split(",");if(e.throwOnLimitExceeded&&i>=e.arrayLimit)throw new RangeError("Array limit exceeded. Only "+e.arrayLimit+" element"+(1===e.arrayLimit?"":"s")+" allowed in an array.");return t},o=function(i,s,r,o){if(i){var a=r.allowDots?i.replace(/\.([^.[]+)/g,"[$1]"):i,l=/(\[[^[\]]*])/g,h=r.depth>0&&/(\[[^[\]]*])/.exec(a),u=h?a.slice(0,h.index):a,c=[];if(u){if(!r.plainObjects&&e.call(Object.prototype,u)&&!r.allowPrototypes)return;c.push(u)}for(var d=0;r.depth>0&&null!==(h=l.exec(a))&&d<r.depth;){if(d+=1,!r.plainObjects&&e.call(Object.prototype,h[1].slice(1,-1))&&!r.allowPrototypes)return;c.push(h[1])}if(h){if(!0===r.strictDepth)throw new RangeError("Input depth exceeded depth option of "+r.depth+" and strictDepth is true");c.push("["+a.slice(h.index)+"]")}return function(e,i,s,r){var o=0;if(e.length>0&&"[]"===e[e.length-1]){var a=e.slice(0,-1).join("");o=Array.isArray(i)&&i[a]?i[a].length:0}for(var l=r?i:n(i,s,o),h=e.length-1;h>=0;--h){var u,c=e[h];if("[]"===c&&s.parseArrays)u=s.allowEmptyArrays&&(""===l||s.strictNullHandling&&null===l)?[]:t.combine([],l);else{u=s.plainObjects?{__proto__:null}:{};var d="["===c.charAt(0)&&"]"===c.charAt(c.length-1)?c.slice(1,-1):c,p=s.decodeDotInKeys?d.replace(/%2E/g,"."):d,f=parseInt(p,10);s.parseArrays||""!==p?!isNaN(f)&&c!==p&&String(f)===p&&f>=0&&s.parseArrays&&f<=s.arrayLimit?(u=[])[f]=l:"__proto__"!==p&&(u[p]=l):u={0:l}}l=u}return l}(c,s,r,o)}};return bc=function(a,l){var h=function(e){if(!e)return s;if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.decodeDotInKeys&&"boolean"!=typeof e.decodeDotInKeys)throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");if(void 0!==e.throwOnLimitExceeded&&"boolean"!=typeof e.throwOnLimitExceeded)throw new TypeError("`throwOnLimitExceeded` option must be a boolean");var i=void 0===e.charset?s.charset:e.charset,r=void 0===e.duplicates?s.duplicates:e.duplicates;if("combine"!==r&&"first"!==r&&"last"!==r)throw new TypeError("The duplicates option must be either combine, first, or last");return{allowDots:void 0===e.allowDots?!0===e.decodeDotInKeys||s.allowDots:!!e.allowDots,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:s.allowEmptyArrays,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:s.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:s.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:s.arrayLimit,charset:i,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:s.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:s.comma,decodeDotInKeys:"boolean"==typeof e.decodeDotInKeys?e.decodeDotInKeys:s.decodeDotInKeys,decoder:"function"==typeof e.decoder?e.decoder:s.decoder,delimiter:"string"==typeof e.delimiter||t.isRegExp(e.delimiter)?e.delimiter:s.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:s.depth,duplicates:r,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:s.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:s.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:s.plainObjects,strictDepth:"boolean"==typeof e.strictDepth?!!e.strictDepth:s.strictDepth,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:s.strictNullHandling,throwOnLimitExceeded:"boolean"==typeof e.throwOnLimitExceeded&&e.throwOnLimitExceeded}}(l);if(""===a||null==a)return h.plainObjects?{__proto__:null}:{};for(var u="string"==typeof a?function(o,a){var l={__proto__:null},h=a.ignoreQueryPrefix?o.replace(/^\?/,""):o;h=h.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var u=a.parameterLimit===1/0?void 0:a.parameterLimit,c=h.split(a.delimiter,a.throwOnLimitExceeded?u+1:u);if(a.throwOnLimitExceeded&&c.length>u)throw new RangeError("Parameter limit exceeded. Only "+u+" parameter"+(1===u?"":"s")+" allowed.");var d,p=-1,f=a.charset;if(a.charsetSentinel)for(d=0;d<c.length;++d)0===c[d].indexOf("utf8=")&&("utf8=%E2%9C%93"===c[d]?f="utf-8":"utf8=%26%2310003%3B"===c[d]&&(f="iso-8859-1"),p=d,d=c.length);for(d=0;d<c.length;++d)if(d!==p){var m,g,y=c[d],v=y.indexOf("]="),x=-1===v?y.indexOf("="):v+1;-1===x?(m=a.decoder(y,s.decoder,f,"key"),g=a.strictNullHandling?null:""):(m=a.decoder(y.slice(0,x),s.decoder,f,"key"),g=t.maybeMap(n(y.slice(x+1),a,i(l[m])?l[m].length:0),function(t){return a.decoder(t,s.decoder,f,"value")})),g&&a.interpretNumericEntities&&"iso-8859-1"===f&&(g=r(String(g))),y.indexOf("[]=")>-1&&(g=i(g)?[g]:g);var b=e.call(l,m);b&&"combine"===a.duplicates?l[m]=t.combine(l[m],g):b&&"last"!==a.duplicates||(l[m]=g)}return l}(a,h):a,c=h.plainObjects?{__proto__:null}:{},d=Object.keys(u),p=0;p<d.length;++p){var f=d[p],m=o(f,u[f],h,"string"==typeof a);c=t.merge(c,m,h)}return!0===h.allowSparse?c:t.compact(c)}}function hd(){if(Pc)return wc;Pc=1;var t=/* @__PURE__ */ad(),e=/* @__PURE__ */ld();return wc={formats:/* @__PURE__ */nd(),parse:e,stringify:t}}var ud=function(){if(Ec)return Uh;Ec=1;var t=(Bh||(Bh=1,function(t,e){!function(i){var s=e&&!e.nodeType&&e,r=t&&!t.nodeType&&t,n="object"==typeof At&&At;n.global!==n&&n.window!==n&&n.self!==n||(i=n);var o,a,l=2147483647,h=36,u=/^xn--/,c=/[^\x20-\x7E]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=Math.floor,m=String.fromCharCode;function g(t){throw new RangeError(p[t])}function y(t,e){for(var i=t.length,s=[];i--;)s[i]=e(t[i]);return s}function v(t,e){var i=t.split("@"),s="";return i.length>1&&(s=i[0]+"@",t=i[1]),s+y((t=t.replace(d,".")).split("."),e).join(".")}function x(t){for(var e,i,s=[],r=0,n=t.length;r<n;)(e=t.charCodeAt(r++))>=55296&&e<=56319&&r<n?56320==(64512&(i=t.charCodeAt(r++)))?s.push(((1023&e)<<10)+(1023&i)+65536):(s.push(e),r--):s.push(e);return s}function b(t){return y(t,function(t){var e="";return t>65535&&(e+=m((t-=65536)>>>10&1023|55296),t=56320|1023&t),e+m(t)}).join("")}function _(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:h}function w(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function P(t,e,i){var s=0;for(t=i?f(t/700):t>>1,t+=f(t/e);t>455;s+=h)t=f(t/35);return f(s+36*t/(t+38))}function E(t){var e,i,s,r,n,o,a,u,c,d,p=[],m=t.length,y=0,v=128,x=72;for((i=t.lastIndexOf("-"))<0&&(i=0),s=0;s<i;++s)t.charCodeAt(s)>=128&&g("not-basic"),p.push(t.charCodeAt(s));for(r=i>0?i+1:0;r<m;){for(n=y,o=1,a=h;r>=m&&g("invalid-input"),((u=_(t.charCodeAt(r++)))>=h||u>f((l-y)/o))&&g("overflow"),y+=u*o,!(u<(c=a<=x?1:a>=x+26?26:a-x));a+=h)o>f(l/(d=h-c))&&g("overflow"),o*=d;x=P(y-n,e=p.length+1,0==n),f(y/e)>l-v&&g("overflow"),v+=f(y/e),y%=e,p.splice(y++,0,v)}return b(p)}function T(t){var e,i,s,r,n,o,a,u,c,d,p,y,v,b,_,E=[];for(y=(t=x(t)).length,e=128,i=0,n=72,o=0;o<y;++o)(p=t[o])<128&&E.push(m(p));for(s=r=E.length,r&&E.push("-");s<y;){for(a=l,o=0;o<y;++o)(p=t[o])>=e&&p<a&&(a=p);for(a-e>f((l-i)/(v=s+1))&&g("overflow"),i+=(a-e)*v,e=a,o=0;o<y;++o)if((p=t[o])<e&&++i>l&&g("overflow"),p==e){for(u=i,c=h;!(u<(d=c<=n?1:c>=n+26?26:c-n));c+=h)_=u-d,b=h-d,E.push(m(w(d+_%b,0))),u=f(_/b);E.push(m(w(u,0))),n=P(i,v,s==r),i=0,++s}++i,++e}return E.join("")}if(o={version:"1.4.1",ucs2:{decode:x,encode:b},decode:E,encode:T,toASCII:function(t){return v(t,function(t){return c.test(t)?"xn--"+T(t):t})},toUnicode:function(t){return v(t,function(t){return u.test(t)?E(t.slice(4).toLowerCase()):t})}},s&&r)if(t.exports==s)r.exports=o;else for(a in o)o.hasOwnProperty(a)&&(s[a]=o[a]);else i.punycode=o}(Xh)}(Gh,Gh.exports)),Gh.exports);function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var i=/^([a-z0-9.+-]+:)/i,s=/:[0-9]*$/,r=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),o=["'"].concat(n),a=["%","/","?",";","#"].concat(o),l=["/","?","#"],h=/^[+a-z0-9A-Z_-]{0,63}$/,u=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,c={javascript:!0,"javascript:":!0},d={javascript:!0,"javascript:":!0},p={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},f=/* @__PURE__ */hd();function m(t,i,s){if(t&&"object"==typeof t&&t instanceof e)return t;var r=new e;return r.parse(t,i,s),r}return e.prototype.parse=function(e,s,n){if("string"!=typeof e)throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var m=e.indexOf("?"),g=-1!==m&&m<e.indexOf("#")?"?":"#",y=e.split(g);y[0]=y[0].replace(/\\/g,"/");var v=e=y.join(g);if(v=v.trim(),!n&&1===e.split("#").length){var x=r.exec(v);if(x)return this.path=v,this.href=v,this.pathname=x[1],x[2]?(this.search=x[2],this.query=s?f.parse(this.search.substr(1)):this.search.substr(1)):s&&(this.search="",this.query={}),this}var b=i.exec(v);if(b){var _=(b=b[0]).toLowerCase();this.protocol=_,v=v.substr(b.length)}if(n||b||v.match(/^\/\/[^@/]+@[^@/]+/)){var w="//"===v.substr(0,2);!w||b&&d[b]||(v=v.substr(2),this.slashes=!0)}if(!d[b]&&(w||b&&!p[b])){for(var P,E,T=-1,A=0;A<l.length;A++){-1!==(I=v.indexOf(l[A]))&&(-1===T||I<T)&&(T=I)}-1!==(E=-1===T?v.lastIndexOf("@"):v.lastIndexOf("@",T))&&(P=v.slice(0,E),v=v.slice(E+1),this.auth=decodeURIComponent(P)),T=-1;for(A=0;A<a.length;A++){var I;-1!==(I=v.indexOf(a[A]))&&(-1===T||I<T)&&(T=I)}-1===T&&(T=v.length),this.host=v.slice(0,T),v=v.slice(T),this.parseHost(),this.hostname=this.hostname||"";var S="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!S)for(var C=this.hostname.split(/\./),M=(A=0,C.length);A<M;A++){var O=C[A];if(O&&!O.match(h)){for(var N="",L=0,R=O.length;L<R;L++)O.charCodeAt(L)>127?N+="x":N+=O[L];if(!N.match(h)){var k=C.slice(0,A),B=C.slice(A+1),F=O.match(u);F&&(k.push(F[1]),B.unshift(F[2])),B.length&&(v="/"+B.join(".")+v),this.hostname=k.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),S||(this.hostname=t.toASCII(this.hostname));var D=this.port?":"+this.port:"",U=this.hostname||"";this.host=U+D,this.href+=this.host,S&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==v[0]&&(v="/"+v))}if(!c[_])for(A=0,M=o.length;A<M;A++){var G=o[A];if(-1!==v.indexOf(G)){var X=encodeURIComponent(G);X===G&&(X=escape(G)),v=v.split(G).join(X)}}var W=v.indexOf("#");-1!==W&&(this.hash=v.substr(W),v=v.slice(0,W));var Y=v.indexOf("?");if(-1!==Y?(this.search=v.substr(Y),this.query=v.substr(Y+1),s&&(this.query=f.parse(this.query)),v=v.slice(0,Y)):s&&(this.search="",this.query={}),v&&(this.pathname=v),p[_]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){D=this.pathname||"";var H=this.search||"";this.path=D+H}return this.href=this.format(),this},e.prototype.format=function(){var t=this.auth||"";t&&(t=(t=encodeURIComponent(t)).replace(/%3A/i,":"),t+="@");var e=this.protocol||"",i=this.pathname||"",s=this.hash||"",r=!1,n="";this.host?r=t+this.host:this.hostname&&(r=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(r+=":"+this.port)),this.query&&"object"==typeof this.query&&Object.keys(this.query).length&&(n=f.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var o=this.search||n&&"?"+n||"";return e&&":"!==e.substr(-1)&&(e+=":"),this.slashes||(!e||p[e])&&!1!==r?(r="//"+(r||""),i&&"/"!==i.charAt(0)&&(i="/"+i)):r||(r=""),s&&"#"!==s.charAt(0)&&(s="#"+s),o&&"?"!==o.charAt(0)&&(o="?"+o),e+r+(i=i.replace(/[?#]/g,function(t){return encodeURIComponent(t)}))+(o=o.replace("#","%23"))+s},e.prototype.resolve=function(t){return this.resolveObject(m(t,!1,!0)).format()},e.prototype.resolveObject=function(t){if("string"==typeof t){var i=new e;i.parse(t,!1,!0),t=i}for(var s=new e,r=Object.keys(this),n=0;n<r.length;n++){var o=r[n];s[o]=this[o]}if(s.hash=t.hash,""===t.href)return s.href=s.format(),s;if(t.slashes&&!t.protocol){for(var a=Object.keys(t),l=0;l<a.length;l++){var h=a[l];"protocol"!==h&&(s[h]=t[h])}return p[s.protocol]&&s.hostname&&!s.pathname&&(s.pathname="/",s.path=s.pathname),s.href=s.format(),s}if(t.protocol&&t.protocol!==s.protocol){if(!p[t.protocol]){for(var u=Object.keys(t),c=0;c<u.length;c++){var f=u[c];s[f]=t[f]}return s.href=s.format(),s}if(s.protocol=t.protocol,t.host||d[t.protocol])s.pathname=t.pathname;else{for(var m=(t.pathname||"").split("/");m.length&&!(t.host=m.shift()););t.host||(t.host=""),t.hostname||(t.hostname=""),""!==m[0]&&m.unshift(""),m.length<2&&m.unshift(""),s.pathname=m.join("/")}if(s.search=t.search,s.query=t.query,s.host=t.host||"",s.auth=t.auth,s.hostname=t.hostname||t.host,s.port=t.port,s.pathname||s.search){var g=s.pathname||"",y=s.search||"";s.path=g+y}return s.slashes=s.slashes||t.slashes,s.href=s.format(),s}var v=s.pathname&&"/"===s.pathname.charAt(0),x=t.host||t.pathname&&"/"===t.pathname.charAt(0),b=x||v||s.host&&t.pathname,_=b,w=s.pathname&&s.pathname.split("/")||[],P=(m=t.pathname&&t.pathname.split("/")||[],s.protocol&&!p[s.protocol]);if(P&&(s.hostname="",s.port=null,s.host&&(""===w[0]?w[0]=s.host:w.unshift(s.host)),s.host="",t.protocol&&(t.hostname=null,t.port=null,t.host&&(""===m[0]?m[0]=t.host:m.unshift(t.host)),t.host=null),b=b&&(""===m[0]||""===w[0])),x)s.host=t.host||""===t.host?t.host:s.host,s.hostname=t.hostname||""===t.hostname?t.hostname:s.hostname,s.search=t.search,s.query=t.query,w=m;else if(m.length)w||(w=[]),w.pop(),w=w.concat(m),s.search=t.search,s.query=t.query;else if(null!=t.search){if(P)s.host=w.shift(),s.hostname=s.host,(S=!!(s.host&&s.host.indexOf("@")>0)&&s.host.split("@"))&&(s.auth=S.shift(),s.hostname=S.shift(),s.host=s.hostname);return s.search=t.search,s.query=t.query,null===s.pathname&&null===s.search||(s.path=(s.pathname?s.pathname:"")+(s.search?s.search:"")),s.href=s.format(),s}if(!w.length)return s.pathname=null,s.search?s.path="/"+s.search:s.path=null,s.href=s.format(),s;for(var E=w.slice(-1)[0],T=(s.host||t.host||w.length>1)&&("."===E||".."===E)||""===E,A=0,I=w.length;I>=0;I--)"."===(E=w[I])?w.splice(I,1):".."===E?(w.splice(I,1),A++):A&&(w.splice(I,1),A--);if(!b&&!_)for(;A--;A)w.unshift("..");!b||""===w[0]||w[0]&&"/"===w[0].charAt(0)||w.unshift(""),T&&"/"!==w.join("/").substr(-1)&&w.push("");var S,C=""===w[0]||w[0]&&"/"===w[0].charAt(0);P&&(s.hostname=C?"":w.length?w.shift():"",s.host=s.hostname,(S=!!(s.host&&s.host.indexOf("@")>0)&&s.host.split("@"))&&(s.auth=S.shift(),s.hostname=S.shift(),s.host=s.hostname));return(b=b||s.host&&w.length)&&!C&&w.unshift(""),w.length>0?s.pathname=w.join("/"):(s.pathname=null,s.path=null),null===s.pathname&&null===s.search||(s.path=(s.pathname?s.pathname:"")+(s.search?s.search:"")),s.auth=t.auth||s.auth,s.slashes=s.slashes||t.slashes,s.href=s.format(),s},e.prototype.parseHost=function(){var t=this.host,e=s.exec(t);e&&(":"!==(e=e[0])&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)},Uh.parse=m,Uh.resolve=function(t,e){return m(t,!1,!0).resolve(e)},Uh.resolveObject=function(t,e){return t?m(t,!1,!0).resolveObject(e):e},Uh.format=function(t){return"string"==typeof t&&(t=m(t)),t instanceof e?t.format():e.prototype.format.call(t)},Uh.Url=e,Uh}();const cd={};function dd(t,e,i=3){if(cd[e])return;let s=(new Error).stack;typeof s>"u"?console.warn("PixiJS Deprecation Warning: ",`${e}\nDeprecated since v${t}`):(s=s.split("\n").splice(i).join("\n"),console.groupCollapsed?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",`${e}\nDeprecated since v${t}`),console.warn(s),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",`${e}\nDeprecated since v${t}`),console.warn(s))),cd[e]=!0}const pd={get parse(){return dd("7.3.0","utils.url.parse is deprecated, use native URL API instead."),ud.parse},get format(){return dd("7.3.0","utils.url.format is deprecated, use native URL API instead."),ud.format},get resolve(){return dd("7.3.0","utils.url.resolve is deprecated, use native URL API instead."),ud.resolve}};function fd(t){if("string"!=typeof t)throw new TypeError(`Path must be a string. Received ${JSON.stringify(t)}`)}function md(t){return t.split("?")[0].split("#")[0]}const gd={toPosix(t){return e="\\",i="/",t.replace(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),i);var e,i},isUrl(t){return/^https?:/.test(this.toPosix(t))},isDataUrl:t=>/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(t),isBlobUrl:t=>t.startsWith("blob:"),hasProtocol(t){return/^[^/:]+:/.test(this.toPosix(t))},getProtocol(t){fd(t),t=this.toPosix(t);const e=/^file:\/\/\//.exec(t);if(e)return e[0];const i=/^[^/:]+:\/{0,2}/.exec(t);return i?i[0]:""},toAbsolute(t,e,i){if(fd(t),this.isDataUrl(t)||this.isBlobUrl(t))return t;const s=md(this.toPosix(e??ph.ADAPTER.getBaseUrl())),r=md(this.toPosix(i??this.rootname(s)));return(t=this.toPosix(t)).startsWith("/")?gd.join(r,t.slice(1)):this.isAbsolute(t)?t:this.join(s,t)},normalize(t){if(fd(t),0===t.length)return".";if(this.isDataUrl(t)||this.isBlobUrl(t))return t;let e="";const i=(t=this.toPosix(t)).startsWith("/");this.hasProtocol(t)&&(e=this.rootname(t),t=t.slice(e.length));const s=t.endsWith("/");return(t=function(t){let e="",i=0,s=-1,r=0,n=-1;for(let o=0;o<=t.length;++o){if(o<t.length)n=t.charCodeAt(o);else{if(47===n)break;n=47}if(47===n){if(s!==o-1&&1!==r)if(s!==o-1&&2===r){if(e.length<2||2!==i||46!==e.charCodeAt(e.length-1)||46!==e.charCodeAt(e.length-2))if(e.length>2){const t=e.lastIndexOf("/");if(t!==e.length-1){-1===t?(e="",i=0):(e=e.slice(0,t),i=e.length-1-e.lastIndexOf("/")),s=o,r=0;continue}}else if(2===e.length||1===e.length){e="",i=0,s=o,r=0;continue}}else e.length>0?e+=`/${t.slice(s+1,o)}`:e=t.slice(s+1,o),i=o-s-1;s=o,r=0}else 46===n&&-1!==r?++r:r=-1}return e}(t)).length>0&&s&&(t+="/"),i?`/${t}`:e+t},isAbsolute(t){return fd(t),t=this.toPosix(t),!!this.hasProtocol(t)||t.startsWith("/")},join(...t){if(0===t.length)return".";let e;for(let i=0;i<t.length;++i){const s=t[i];if(fd(s),s.length>0)if(void 0===e)e=s;else{const r=t[i-1]??"";this.joinExtensions.includes(this.extname(r).toLowerCase())?e+=`/../${s}`:e+=`/${s}`}}return void 0===e?".":this.normalize(e)},dirname(t){if(fd(t),0===t.length)return".";let e=(t=this.toPosix(t)).charCodeAt(0);const i=47===e;let s=-1,r=!0;const n=this.getProtocol(t),o=t;for(let a=(t=t.slice(n.length)).length-1;a>=1;--a)if(e=t.charCodeAt(a),47===e){if(!r){s=a;break}}else r=!1;return-1===s?i?"/":this.isUrl(o)?n+t:n:i&&1===s?"//":n+t.slice(0,s)},rootname(t){fd(t);let e="";if(e=(t=this.toPosix(t)).startsWith("/")?"/":this.getProtocol(t),this.isUrl(t)){const i=t.indexOf("/",e.length);e=-1!==i?t.slice(0,i):t,e.endsWith("/")||(e+="/")}return e},basename(t,e){fd(t),e&&fd(e),t=md(this.toPosix(t));let i,s=0,r=-1,n=!0;if(void 0!==e&&e.length>0&&e.length<=t.length){if(e.length===t.length&&e===t)return"";let o=e.length-1,a=-1;for(i=t.length-1;i>=0;--i){const l=t.charCodeAt(i);if(47===l){if(!n){s=i+1;break}}else-1===a&&(n=!1,a=i+1),o>=0&&(l===e.charCodeAt(o)?-1===--o&&(r=i):(o=-1,r=a))}return s===r?r=a:-1===r&&(r=t.length),t.slice(s,r)}for(i=t.length-1;i>=0;--i)if(47===t.charCodeAt(i)){if(!n){s=i+1;break}}else-1===r&&(n=!1,r=i+1);return-1===r?"":t.slice(s,r)},extname(t){fd(t);let e=-1,i=0,s=-1,r=!0,n=0;for(let o=(t=md(this.toPosix(t))).length-1;o>=0;--o){const a=t.charCodeAt(o);if(47!==a)-1===s&&(r=!1,s=o+1),46===a?-1===e?e=o:1!==n&&(n=1):-1!==e&&(n=-1);else if(!r){i=o+1;break}}return-1===e||-1===s||0===n||1===n&&e===s-1&&e===i+1?"":t.slice(e,s)},parse(t){fd(t);const e={root:"",dir:"",base:"",ext:"",name:""};if(0===t.length)return e;let i=(t=md(this.toPosix(t))).charCodeAt(0);const s=this.isAbsolute(t);let r;e.root=this.rootname(t),r=s||this.hasProtocol(t)?1:0;let n=-1,o=0,a=-1,l=!0,h=t.length-1,u=0;for(;h>=r;--h)if(i=t.charCodeAt(h),47!==i)-1===a&&(l=!1,a=h+1),46===i?-1===n?n=h:1!==u&&(u=1):-1!==n&&(u=-1);else if(!l){o=h+1;break}return-1===n||-1===a||0===u||1===u&&n===a-1&&n===o+1?-1!==a&&(e.base=e.name=0===o&&s?t.slice(1,a):t.slice(o,a)):(0===o&&s?(e.name=t.slice(1,n),e.base=t.slice(1,a)):(e.name=t.slice(o,n),e.base=t.slice(o,a)),e.ext=t.slice(n,a)),e.dir=this.dirname(t),e},sep:"/",delimiter:":",joinExtensions:[".html"]};let yd,vd;function xd(){return typeof vd>"u"&&(vd=function(){const t={stencil:!0,failIfMajorPerformanceCaveat:ph.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT};try{if(!ph.ADAPTER.getWebGLRenderingContext())return!1;const e=ph.ADAPTER.createCanvas();let i=e.getContext("webgl",t)||e.getContext("experimental-webgl",t);const s=!!i?.getContextAttributes()?.stencil;if(i){const t=i.getExtension("WEBGL_lose_context");t&&t.loseContext()}return i=null,s}catch{return!1}}()),vd}var bd,_d={grad:.9,turn:360,rad:360/(2*Math.PI)},wd=function(t){return"string"==typeof t?t.length>0:"number"==typeof t},Pd=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=Math.pow(10,e)),Math.round(i*t)/i+0},Ed=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=1),t>i?i:t>e?t:e},Td=function(t){return(t=isFinite(t)?t%360:0)>0?t:t+360},Ad=function(t){return{r:Ed(t.r,0,255),g:Ed(t.g,0,255),b:Ed(t.b,0,255),a:Ed(t.a)}},Id=function(t){return{r:Pd(t.r),g:Pd(t.g),b:Pd(t.b),a:Pd(t.a,3)}},Sd=/^#([0-9a-f]{3,8})$/i,Cd=function(t){var e=t.toString(16);return e.length<2?"0"+e:e},Md=function(t){var e=t.r,i=t.g,s=t.b,r=t.a,n=Math.max(e,i,s),o=n-Math.min(e,i,s),a=o?n===e?(i-s)/o:n===i?2+(s-e)/o:4+(e-i)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},Od=function(t){var e=t.h,i=t.s,s=t.v,r=t.a;e=e/360*6,i/=100,s/=100;var n=Math.floor(e),o=s*(1-i),a=s*(1-(e-n)*i),l=s*(1-(1-e+n)*i),h=n%6;return{r:255*[s,a,o,o,l,s][h],g:255*[l,s,s,a,o,o][h],b:255*[o,o,l,s,s,a][h],a:r}},Nd=function(t){return{h:Td(t.h),s:Ed(t.s,0,100),l:Ed(t.l,0,100),a:Ed(t.a)}},Ld=function(t){return{h:Pd(t.h),s:Pd(t.s),l:Pd(t.l),a:Pd(t.a,3)}},Rd=function(t){return Od((i=(e=t).s,{h:e.h,s:(i*=((s=e.l)<50?s:100-s)/100)>0?2*i/(s+i)*100:0,v:s+i,a:e.a}));var e,i,s},kd=function(t){return{h:(e=Md(t)).h,s:(r=(200-(i=e.s))*(s=e.v)/100)>0&&r<200?i*s/100/(r<=100?r:200-r)*100:0,l:r/2,a:e.a};var e,i,s,r},Bd=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Fd=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Dd=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Ud=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Gd={string:[[function(t){var e=Sd.exec(t);return e?(t=e[1]).length<=4?{r:parseInt(t[0]+t[0],16),g:parseInt(t[1]+t[1],16),b:parseInt(t[2]+t[2],16),a:4===t.length?Pd(parseInt(t[3]+t[3],16)/255,2):1}:6===t.length||8===t.length?{r:parseInt(t.substr(0,2),16),g:parseInt(t.substr(2,2),16),b:parseInt(t.substr(4,2),16),a:8===t.length?Pd(parseInt(t.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(t){var e=Dd.exec(t)||Ud.exec(t);return e?e[2]!==e[4]||e[4]!==e[6]?null:Ad({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:void 0===e[7]?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(t){var e=Bd.exec(t)||Fd.exec(t);if(!e)return null;var i,s,r=Nd({h:(i=e[1],s=e[2],void 0===s&&(s="deg"),Number(i)*(_d[s]||1)),s:Number(e[3]),l:Number(e[4]),a:void 0===e[5]?1:Number(e[5])/(e[6]?100:1)});return Rd(r)},"hsl"]],object:[[function(t){var e=t.r,i=t.g,s=t.b,r=t.a,n=void 0===r?1:r;return wd(e)&&wd(i)&&wd(s)?Ad({r:Number(e),g:Number(i),b:Number(s),a:Number(n)}):null},"rgb"],[function(t){var e=t.h,i=t.s,s=t.l,r=t.a,n=void 0===r?1:r;if(!wd(e)||!wd(i)||!wd(s))return null;var o=Nd({h:Number(e),s:Number(i),l:Number(s),a:Number(n)});return Rd(o)},"hsl"],[function(t){var e=t.h,i=t.s,s=t.v,r=t.a,n=void 0===r?1:r;if(!wd(e)||!wd(i)||!wd(s))return null;var o,a=(o={h:Number(e),s:Number(i),v:Number(s),a:Number(n)},{h:Td(o.h),s:Ed(o.s,0,100),v:Ed(o.v,0,100),a:Ed(o.a)});return Od(a)},"hsv"]]},Xd=function(t,e){for(var i=0;i<e.length;i++){var s=e[i][0](t);if(s)return[s,e[i][1]]}return[null,void 0]},Wd=function(t,e){var i=kd(t);return{h:i.h,s:Ed(i.s+100*e,0,100),l:i.l,a:i.a}},Yd=function(t){return(299*t.r+587*t.g+114*t.b)/1e3/255},Hd=function(t,e){var i=kd(t);return{h:i.h,s:i.s,l:Ed(i.l+100*e,0,100),a:i.a}},$d=function(){function t(t){this.parsed=function(t){return"string"==typeof t?Xd(t.trim(),Gd.string):"object"==typeof t&&null!==t?Xd(t,Gd.object):[null,void 0]}(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return t.prototype.isValid=function(){return null!==this.parsed},t.prototype.brightness=function(){return Pd(Yd(this.rgba),2)},t.prototype.isDark=function(){return Yd(this.rgba)<.5},t.prototype.isLight=function(){return Yd(this.rgba)>=.5},t.prototype.toHex=function(){return e=(t=Id(this.rgba)).r,i=t.g,s=t.b,n=(r=t.a)<1?Cd(Pd(255*r)):"","#"+Cd(e)+Cd(i)+Cd(s)+n;var t,e,i,s,r,n},t.prototype.toRgb=function(){return Id(this.rgba)},t.prototype.toRgbString=function(){return e=(t=Id(this.rgba)).r,i=t.g,s=t.b,(r=t.a)<1?"rgba("+e+", "+i+", "+s+", "+r+")":"rgb("+e+", "+i+", "+s+")";var t,e,i,s,r},t.prototype.toHsl=function(){return Ld(kd(this.rgba))},t.prototype.toHslString=function(){return e=(t=Ld(kd(this.rgba))).h,i=t.s,s=t.l,(r=t.a)<1?"hsla("+e+", "+i+"%, "+s+"%, "+r+")":"hsl("+e+", "+i+"%, "+s+"%)";var t,e,i,s,r},t.prototype.toHsv=function(){return t=Md(this.rgba),{h:Pd(t.h),s:Pd(t.s),v:Pd(t.v),a:Pd(t.a,3)};var t},t.prototype.invert=function(){return jd({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},t.prototype.saturate=function(t){return void 0===t&&(t=.1),jd(Wd(this.rgba,t))},t.prototype.desaturate=function(t){return void 0===t&&(t=.1),jd(Wd(this.rgba,-t))},t.prototype.grayscale=function(){return jd(Wd(this.rgba,-1))},t.prototype.lighten=function(t){return void 0===t&&(t=.1),jd(Hd(this.rgba,t))},t.prototype.darken=function(t){return void 0===t&&(t=.1),jd(Hd(this.rgba,-t))},t.prototype.rotate=function(t){return void 0===t&&(t=15),this.hue(this.hue()+t)},t.prototype.alpha=function(t){return"number"==typeof t?jd({r:(e=this.rgba).r,g:e.g,b:e.b,a:t}):Pd(this.rgba.a,3);var e},t.prototype.hue=function(t){var e=kd(this.rgba);return"number"==typeof t?jd({h:t,s:e.s,l:e.l,a:e.a}):Pd(e.h)},t.prototype.isEqual=function(t){return this.toHex()===jd(t).toHex()},t}(),jd=function(t){return t instanceof $d?t:new $d(t)},zd=[];bd=[function(t,e){var i={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"},s={};for(var r in i)s[i[r]]=r;var n={};t.prototype.toName=function(e){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var r,o,a=s[this.toHex()];if(a)return a;if(null==e?void 0:e.closest){var l=this.toRgb(),h=1/0,u="black";if(!n.length)for(var c in i)n[c]=new t(i[c]).toRgb();for(var d in i){var p=(r=l,o=n[d],Math.pow(r.r-o.r,2)+Math.pow(r.g-o.g,2)+Math.pow(r.b-o.b,2));p<h&&(h=p,u=d)}return u}},e.string.push([function(e){var s=e.toLowerCase(),r="transparent"===s?"#0000":i[s];return r?new t(r).toRgb():null},"name"])}],bd.forEach(function(t){zd.indexOf(t)<0&&(t($d,Gd),zd.push(t))});const Vd=class t{constructor(t=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=t}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(t){return this.value=t,this}set value(e){if(e instanceof t)this._value=this.cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(null===e)throw new Error("Cannot set PIXI.Color#value to null");(null===this._value||!this.isSourceEqual(this._value,e))&&(this.normalize(e),this._value=this.cloneSource(e))}}get value(){return this._value}cloneSource(t){return"string"==typeof t||"number"==typeof t||t instanceof Number||null===t?t:Array.isArray(t)||ArrayBuffer.isView(t)?t.slice(0):"object"==typeof t&&null!==t?{...t}:t}isSourceEqual(t,e){const i=typeof t;if(i!==typeof e)return!1;if("number"===i||"string"===i||t instanceof Number)return t===e;if(Array.isArray(t)&&Array.isArray(e)||ArrayBuffer.isView(t)&&ArrayBuffer.isView(e))return t.length===e.length&&t.every((t,i)=>t===e[i]);if(null!==t&&null!==e){const i=Object.keys(t),s=Object.keys(e);return i.length===s.length&&i.every(i=>t[i]===e[i])}return t===e}toRgba(){const[t,e,i,s]=this._components;return{r:t,g:e,b:i,a:s}}toRgb(){const[t,e,i]=this._components;return{r:t,g:e,b:i}}toRgbaString(){const[t,e,i]=this.toUint8RgbArray();return`rgba(${t},${e},${i},${this.alpha})`}toUint8RgbArray(t){const[e,i,s]=this._components;return(t=t??[])[0]=Math.round(255*e),t[1]=Math.round(255*i),t[2]=Math.round(255*s),t}toRgbArray(t){t=t??[];const[e,i,s]=this._components;return t[0]=e,t[1]=i,t[2]=s,t}toNumber(){return this._int}toLittleEndianNumber(){const t=this._int;return(t>>16)+(65280&t)+((255&t)<<16)}multiply(e){const[i,s,r,n]=t.temp.setValue(e)._components;return this._components[0]*=i,this._components[1]*=s,this._components[2]*=r,this._components[3]*=n,this.refreshInt(),this._value=null,this}premultiply(t,e=!0){return e&&(this._components[0]*=t,this._components[1]*=t,this._components[2]*=t),this._components[3]=t,this.refreshInt(),this._value=null,this}toPremultiplied(t,e=!0){if(1===t)return(255<<24)+this._int;if(0===t)return e?0:this._int;let i=this._int>>16&255,s=this._int>>8&255,r=255&this._int;return e&&(i=i*t+.5|0,s=s*t+.5|0,r=r*t+.5|0),(255*t<<24)+(i<<16)+(s<<8)+r}toHex(){const t=this._int.toString(16);return`#${"000000".substring(0,6-t.length)+t}`}toHexa(){const t=Math.round(255*this._components[3]).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(t){return this._components[3]=this._clamp(t),this}round(t){const[e,i,s]=this._components;return this._components[0]=Math.round(e*t)/t,this._components[1]=Math.round(i*t)/t,this._components[2]=Math.round(s*t)/t,this.refreshInt(),this._value=null,this}toArray(t){t=t??[];const[e,i,s,r]=this._components;return t[0]=e,t[1]=i,t[2]=s,t[3]=r,t}normalize(e){let i,s,r,n;if(("number"==typeof e||e instanceof Number)&&e>=0&&e<=16777215){i=(e>>16&255)/255,s=(e>>8&255)/255,r=(255&e)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[i,s,r,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[i,s,r,n=255]=e,i/=255,s/=255,r/=255,n/=255;else if("string"==typeof e||"object"==typeof e){if("string"==typeof e){const i=t.HEX_PATTERN.exec(e);i&&(e=`#${i[2]}`)}const o=jd(e);o.isValid()&&(({r:i,g:s,b:r,a:n}=o.rgba),i/=255,s/=255,r/=255)}if(void 0===i)throw new Error(`Unable to convert color ${e}`);this._components[0]=i,this._components[1]=s,this._components[2]=r,this._components[3]=n,this.refreshInt()}refreshInt(){this._clamp(this._components);const[t,e,i]=this._components;this._int=(255*t<<16)+(255*e<<8)+(255*i|0)}_clamp(t,e=0,i=1){return"number"==typeof t?Math.min(Math.max(t,e),i):(t.forEach((s,r)=>{t[r]=Math.min(Math.max(s,e),i)}),t)}};Vd.shared=new Vd,Vd.temp=new Vd,Vd.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let qd=Vd;const Jd=function(){const t=[],e=[];for(let s=0;s<32;s++)t[s]=s,e[s]=s;t[Kl.NORMAL_NPM]=Kl.NORMAL,t[Kl.ADD_NPM]=Kl.ADD,t[Kl.SCREEN_NPM]=Kl.SCREEN,e[Kl.NORMAL]=Kl.NORMAL_NPM,e[Kl.ADD]=Kl.ADD_NPM,e[Kl.SCREEN]=Kl.SCREEN_NPM;const i=[];return i.push(e),i.push(t),i}();const Kd=/^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i;function Zd(t){if(4===t.BYTES_PER_ELEMENT)return t instanceof Float32Array?"Float32Array":t instanceof Uint32Array?"Uint32Array":"Int32Array";if(2===t.BYTES_PER_ELEMENT){if(t instanceof Uint16Array)return"Uint16Array"}else if(1===t.BYTES_PER_ELEMENT&&t instanceof Uint8Array)return"Uint8Array";return null}const Qd={Float32Array:Float32Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Uint8Array:Uint8Array};function tp(t){return t+=0===t?1:0,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1}function ep(t){return!(t&t-1||!t)}function ip(t){let e=(t>65535?1:0)<<4,i=((t>>>=e)>255?1:0)<<3;return e|=i,i=((t>>>=i)>15?1:0)<<2,e|=i,i=((t>>>=i)>3?1:0)<<1,e|=i,e|(t>>>=i)>>1}function sp(t,e,i){const s=t.length;let r;if(e>=s||0===i)return;const n=s-(i=e+i>s?s-e:i);for(r=e;r<n;++r)t[r]=t[r+i];t.length=n}function rp(t){return 0===t?0:t<0?-1:1}let np=0;function op(){return++np}const ap=class{constructor(t,e,i,s){this.left=t,this.top=e,this.right=i,this.bottom=s}get width(){return this.right-this.left}get height(){return this.bottom-this.top}isEmpty(){return this.left===this.right||this.top===this.bottom}};ap.EMPTY=new ap(0,0,0,0);let lp=ap;const hp={},up=/* @__PURE__ */Object.create(null),cp=/* @__PURE__ */Object.create(null);function dp(){let t;for(t in up)delete up[t];for(t in cp)delete cp[t]}class pp{constructor(t,e,i){this._canvas=ph.ADAPTER.createCanvas(),this._context=this._canvas.getContext("2d"),this.resolution=i||ph.RESOLUTION,this.resize(t,e)}clear(){this._checkDestroyed(),this._context.setTransform(1,0,0,1,0,0),this._context.clearRect(0,0,this._canvas.width,this._canvas.height)}resize(t,e){this._checkDestroyed(),this._canvas.width=Math.round(t*this.resolution),this._canvas.height=Math.round(e*this.resolution)}destroy(){this._context=null,this._canvas=null}get width(){return this._checkDestroyed(),this._canvas.width}set width(t){this._checkDestroyed(),this._canvas.width=Math.round(t)}get height(){return this._checkDestroyed(),this._canvas.height}set height(t){this._checkDestroyed(),this._canvas.height=Math.round(t)}get canvas(){return this._checkDestroyed(),this._canvas}get context(){return this._checkDestroyed(),this._context}_checkDestroyed(){if(null===this._canvas)throw new TypeError("The CanvasRenderTarget has already been destroyed")}}function fp(t,e,i){for(let s=0,r=4*i*e;s<e;++s,r+=4)if(0!==t[r+3])return!1;return!0}function mp(t,e,i,s,r){const n=4*e;for(let o=s,a=s*n+4*i;o<=r;++o,a+=n)if(0!==t[a+3])return!1;return!0}function gp(t){const{width:e,height:i}=t,s=t.getContext("2d",{willReadFrequently:!0});if(null===s)throw new TypeError("Failed to get canvas 2D context");const r=s.getImageData(0,0,e,i).data;let n=0,o=0,a=e-1,l=i-1;for(;o<i&&fp(r,e,o);)++o;if(o===i)return lp.EMPTY;for(;fp(r,e,l);)--l;for(;mp(r,e,n,o,l);)++n;for(;mp(r,e,a,o,l);)--a;return++a,++l,new lp(n,o,a,l)}function yp(t){const e=gp(t),{width:i,height:s}=e;let r=null;if(!e.isEmpty()){const n=t.getContext("2d");if(null===n)throw new TypeError("Failed to get canvas 2D context");r=n.getImageData(e.left,e.top,i,s)}return{width:i,height:s,data:r}}function vp(t,e=globalThis.location){if(t.startsWith("data:"))return"";e=e||globalThis.location;const i=new URL(t,document.baseURI);return i.hostname!==e.hostname||i.port!==e.port||i.protocol!==e.protocol?"anonymous":""}function xp(t,e=1){const i=ph.RETINA_PREFIX?.exec(t);return i?parseFloat(i[1]):e}const bp=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,BaseTextureCache:cp,BoundingBox:lp,CanvasRenderTarget:pp,DATA_URI:Kd,EventEmitter:kh,ProgramCache:hp,TextureCache:up,clearTextureCache:dp,correctBlendMode:function(t,e){return Jd[e?1:0][t]},createIndicesForQuads:function(t,e=null){const i=6*t;if((e=e||new Uint16Array(i)).length!==i)throw new Error(`Out buffer length is incorrect, got ${e.length} and expected ${i}`);for(let s=0,r=0;s<i;s+=6,r+=4)e[s+0]=r+0,e[s+1]=r+1,e[s+2]=r+2,e[s+3]=r+0,e[s+4]=r+2,e[s+5]=r+3;return e},decomposeDataUri:function(t){const e=Kd.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,charset:e[3]?e[3].toLowerCase():void 0,encoding:e[4]?e[4].toLowerCase():void 0,data:e[5]}},deprecation:dd,destroyTextureCache:function(){let t;for(t in up)up[t].destroy();for(t in cp)cp[t].destroy()},detectVideoAlphaMode:async function(){return yd??(yd=(async()=>{const t=document.createElement("canvas").getContext("webgl");if(!t)return oh.UNPACK;const e=await new Promise(t=>{const e=document.createElement("video");e.onloadeddata=()=>t(e),e.onerror=()=>t(null),e.autoplay=!1,e.crossOrigin="anonymous",e.preload="auto",e.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",e.load()});if(!e)return oh.UNPACK;const i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i);const s=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,s),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.NONE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e);const r=new Uint8Array(4);return t.readPixels(0,0,1,1,t.RGBA,t.UNSIGNED_BYTE,r),t.deleteFramebuffer(s),t.deleteTexture(i),t.getExtension("WEBGL_lose_context")?.loseContext(),r[0]<=r[3]?oh.PMA:oh.UNPACK})()),yd},determineCrossOrigin:vp,earcut:Nt,getBufferType:Zd,getCanvasBoundingBox:gp,getResolutionOfUrl:xp,hex2rgb:function(t,e=[]){return dd("7.2.0","utils.hex2rgb is deprecated, use Color#toRgbArray instead"),qd.shared.setValue(t).toRgbArray(e)},hex2string:function(t){return dd("7.2.0","utils.hex2string is deprecated, use Color#toHex instead"),qd.shared.setValue(t).toHex()},interleaveTypedArrays:function(t,e){let i=0,s=0;const r={};for(let l=0;l<t.length;l++)s+=e[l],i+=t[l].length;const n=new ArrayBuffer(4*i);let o=null,a=0;for(let l=0;l<t.length;l++){const i=e[l],h=t[l],u=Zd(h);r[u]||(r[u]=new Qd[u](n)),o=r[u];for(let t=0;t<h.length;t++){o[(t/i|0)*s+a+t%i]=h[t]}a+=i}return new Float32Array(n)},isMobile:Oh,isPow2:ep,isWebGLSupported:xd,log2:ip,nextPow2:tp,path:gd,premultiplyBlendMode:Jd,premultiplyRgba:function(t,e,i,s=!0){return dd("7.2.0","utils.premultiplyRgba has moved to Color.premultiply"),qd.shared.setValue(t).premultiply(e,s).toArray(i??new Float32Array(4))},premultiplyTint:function(t,e){return dd("7.2.0","utils.premultiplyTint has moved to Color.toPremultiplied"),qd.shared.setValue(t).toPremultiplied(e)},premultiplyTintToRgba:function(t,e,i,s=!0){return dd("7.2.0","utils.premultiplyTintToRgba has moved to Color.premultiply"),qd.shared.setValue(t).premultiply(e,s).toArray(i??new Float32Array(4))},removeItems:sp,rgb2hex:function(t){return dd("7.2.0","utils.rgb2hex is deprecated, use Color#toNumber instead"),qd.shared.setValue(t).toNumber()},sayHello:function(){dd("7.0.0",'sayHello is deprecated, please use Renderer\'s "hello" option')},sign:rp,skipHello:function(){dd("7.0.0","skipHello is deprecated, please use settings.RENDER_OPTIONS.hello")},string2hex:function(t){return dd("7.2.0","utils.string2hex is deprecated, use Color#toNumber instead"),qd.shared.setValue(t).toNumber()},trimCanvas:yp,uid:op,url:pd},Symbol.toStringTag,{value:"Module"}));var _p=/* @__PURE__ */(t=>(t.Renderer="renderer",t.Application="application",t.RendererSystem="renderer-webgl-system",t.RendererPlugin="renderer-webgl-plugin",t.CanvasRendererSystem="renderer-canvas-system",t.CanvasRendererPlugin="renderer-canvas-plugin",t.Asset="asset",t.LoadParser="load-parser",t.ResolveParser="resolve-parser",t.CacheParser="cache-parser",t.DetectionParser="detection-parser",t))(_p||{});const wp=t=>{if("function"==typeof t||"object"==typeof t&&t.extension){if(!t.extension)throw new Error("Extension class must have an extension object");t={..."object"!=typeof t.extension?{type:t.extension}:t.extension,ref:t}}if("object"!=typeof t)throw new Error("Invalid extension type");return"string"==typeof(t={...t}).type&&(t.type=[t.type]),t},Pp=(t,e)=>wp(t).priority??e,Ep={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...t){return t.map(wp).forEach(t=>{t.type.forEach(e=>this._removeHandlers[e]?.(t))}),this},add(...t){return t.map(wp).forEach(t=>{t.type.forEach(e=>{const i=this._addHandlers,s=this._queue;i[e]?i[e]?.(t):(s[e]=s[e]||[],s[e]?.push(t))})}),this},handle(t,e,i){const s=this._addHandlers,r=this._removeHandlers;if(s[t]||r[t])throw new Error(`Extension type ${t} already has a handler`);s[t]=e,r[t]=i;const n=this._queue;return n[t]&&(n[t]?.forEach(t=>e(t)),delete n[t]),this},handleByMap(t,e){return this.handle(t,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByList(t,e,i=-1){return this.handle(t,t=>{e.includes(t.ref)||(e.push(t.ref),e.sort((t,e)=>Pp(e,i)-Pp(t,i)))},t=>{const i=e.indexOf(t.ref);-1!==i&&e.splice(i,1)})}};class Tp{constructor(t){"number"==typeof t?this.rawBinaryData=new ArrayBuffer(t):t instanceof Uint8Array?this.rawBinaryData=t.buffer:this.rawBinaryData=t,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData)}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 uint16View(){return this._uint16View||(this._uint16View=new Uint16Array(this.rawBinaryData)),this._uint16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}view(t){return this[`${t}View`]}destroy(){this.rawBinaryData=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._uint16View=null,this._int32View=null,this.uint32View=null,this.float32View=null}static sizeOf(t){switch(t){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${t} isn't a valid view type`)}}}const Ap=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join("\n");function Ip(t){let e="";for(let i=0;i<t;++i)i>0&&(e+="\nelse "),i<t-1&&(e+=`if(test == ${i}.0){}`);return e}class Sp{constructor(){this.data=0,this.blendMode=Kl.NORMAL,this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(1&this.data)}set blend(t){!!(1&this.data)!==t&&(this.data^=1)}get offsets(){return!!(2&this.data)}set offsets(t){!!(2&this.data)!==t&&(this.data^=2)}get culling(){return!!(4&this.data)}set culling(t){!!(4&this.data)!==t&&(this.data^=4)}get depthTest(){return!!(8&this.data)}set depthTest(t){!!(8&this.data)!==t&&(this.data^=8)}get depthMask(){return!!(32&this.data)}set depthMask(t){!!(32&this.data)!==t&&(this.data^=32)}get clockwiseFrontFace(){return!!(16&this.data)}set clockwiseFrontFace(t){!!(16&this.data)!==t&&(this.data^=16)}get blendMode(){return this._blendMode}set blendMode(t){this.blend=t!==Kl.NONE,this._blendMode=t}get polygonOffset(){return this._polygonOffset}set polygonOffset(t){this.offsets=!!t,this._polygonOffset=t}static for2d(){const t=new Sp;return t.depthTest=!1,t.blend=!0,t}}Sp.prototype.toString=function(){return`[@pixi/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`};const Cp=[];function Mp(t,e){if(!t)return null;let i="";if("string"==typeof t){const e=/\.(\w{3,4})(?:$|\?|#)/i.exec(t);e&&(i=e[1].toLowerCase())}for(let s=Cp.length-1;s>=0;--s){const r=Cp[s];if(r.test&&r.test(t,i))return new r(t,e)}throw new Error("Unrecognized source type to auto-detect Resource")}class Op{constructor(t){this.items=[],this._name=t,this._aliasCount=0}emit(t,e,i,s,r,n,o,a){if(arguments.length>8)throw new Error("max arguments reached");const{name:l,items:h}=this;this._aliasCount++;for(let u=0,c=h.length;u<c;u++)h[u][l](t,e,i,s,r,n,o,a);return h===this.items&&this._aliasCount--,this}ensureNonAliasedItems(){this._aliasCount>0&&this.items.length>1&&(this._aliasCount=0,this.items=this.items.slice(0))}add(t){return t[this._name]&&(this.ensureNonAliasedItems(),this.remove(t),this.items.push(t)),this}remove(t){const e=this.items.indexOf(t);return-1!==e&&(this.ensureNonAliasedItems(),this.items.splice(e,1)),this}contains(t){return this.items.includes(t)}removeAll(){return this.ensureNonAliasedItems(),this.items.length=0,this}destroy(){this.removeAll(),this.items.length=0,this._name=""}get empty(){return 0===this.items.length}get name(){return this._name}}Object.defineProperties(Op.prototype,{dispatch:{value:Op.prototype.emit},run:{value:Op.prototype.emit}});class Np{constructor(t=0,e=0){this._width=t,this._height=e,this.destroyed=!1,this.internal=!1,this.onResize=new Op("setRealSize"),this.onUpdate=new Op("update"),this.onError=new Op("onError")}bind(t){this.onResize.add(t),this.onUpdate.add(t),this.onError.add(t),(this._width||this._height)&&this.onResize.emit(this._width,this._height)}unbind(t){this.onResize.remove(t),this.onUpdate.remove(t),this.onError.remove(t)}resize(t,e){(t!==this._width||e!==this._height)&&(this._width=t,this._height=e,this.onResize.emit(t,e))}get valid(){return!!this._width&&!!this._height}update(){this.destroyed||this.onUpdate.emit()}load(){return Promise.resolve(this)}get width(){return this._width}get height(){return this._height}style(t,e,i){return!1}dispose(){}destroy(){this.destroyed||(this.destroyed=!0,this.dispose(),this.onError.removeAll(),this.onError=null,this.onResize.removeAll(),this.onResize=null,this.onUpdate.removeAll(),this.onUpdate=null)}static test(t,e){return!1}}class Lp extends Np{constructor(t,e){const{width:i,height:s}=e||{};if(!i||!s)throw new Error("BufferResource width or height invalid");super(i,s),this.data=t,this.unpackAlignment=e.unpackAlignment??4}upload(t,e,i){const s=t.gl;s.pixelStorei(s.UNPACK_ALIGNMENT,this.unpackAlignment),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.alphaMode===oh.UNPACK);const r=e.realWidth,n=e.realHeight;return i.width===r&&i.height===n?s.texSubImage2D(e.target,0,0,0,r,n,e.format,i.type,this.data):(i.width=r,i.height=n,s.texImage2D(e.target,0,i.internalFormat,r,n,0,e.format,i.type,this.data)),!0}dispose(){this.data=null}static test(t){return null===t||t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array}}const Rp={scaleMode:sh.NEAREST,alphaMode:oh.NPM},kp=class t extends kh{constructor(e=null,i=null){super(),i=Object.assign({},t.defaultOptions,i);const{alphaMode:s,mipmap:r,anisotropicLevel:n,scaleMode:o,width:a,height:l,wrapMode:h,format:u,type:c,target:d,resolution:p,resourceOptions:f}=i;e&&!(e instanceof Np)&&((e=Mp(e,f)).internal=!0),this.resolution=p||ph.RESOLUTION,this.width=Math.round((a||0)*this.resolution)/this.resolution,this.height=Math.round((l||0)*this.resolution)/this.resolution,this._mipmap=r,this.anisotropicLevel=n,this._wrapMode=h,this._scaleMode=o,this.format=u,this.type=c,this.target=d,this.alphaMode=s,this.uid=op(),this.touched=0,this.isPowerOfTwo=!1,this._refreshPOT(),this._glTextures={},this.dirtyId=0,this.dirtyStyleId=0,this.cacheId=null,this.valid=a>0&&l>0,this.textureCacheIds=[],this.destroyed=!1,this.resource=null,this._batchEnabled=0,this._batchLocation=0,this.parentTextureArray=null,this.setResource(e)}get realWidth(){return Math.round(this.width*this.resolution)}get realHeight(){return Math.round(this.height*this.resolution)}get mipmap(){return this._mipmap}set mipmap(t){this._mipmap!==t&&(this._mipmap=t,this.dirtyStyleId++)}get scaleMode(){return this._scaleMode}set scaleMode(t){this._scaleMode!==t&&(this._scaleMode=t,this.dirtyStyleId++)}get wrapMode(){return this._wrapMode}set wrapMode(t){this._wrapMode!==t&&(this._wrapMode=t,this.dirtyStyleId++)}setStyle(t,e){let i;return void 0!==t&&t!==this.scaleMode&&(this.scaleMode=t,i=!0),void 0!==e&&e!==this.mipmap&&(this.mipmap=e,i=!0),i&&this.dirtyStyleId++,this}setSize(t,e,i){return i=i||this.resolution,this.setRealSize(t*i,e*i,i)}setRealSize(t,e,i){return this.resolution=i||this.resolution,this.width=Math.round(t)/this.resolution,this.height=Math.round(e)/this.resolution,this._refreshPOT(),this.update(),this}_refreshPOT(){this.isPowerOfTwo=ep(this.realWidth)&&ep(this.realHeight)}setResolution(t){const e=this.resolution;return e===t||(this.resolution=t,this.valid&&(this.width=Math.round(this.width*e)/t,this.height=Math.round(this.height*e)/t,this.emit("update",this)),this._refreshPOT()),this}setResource(t){if(this.resource===t)return this;if(this.resource)throw new Error("Resource can be set only once");return t.bind(this),this.resource=t,this}update(){this.valid?(this.dirtyId++,this.dirtyStyleId++,this.emit("update",this)):this.width>0&&this.height>0&&(this.valid=!0,this.emit("loaded",this),this.emit("update",this))}onError(t){this.emit("error",this,t)}destroy(){this.resource&&(this.resource.unbind(this),this.resource.internal&&this.resource.destroy(),this.resource=null),this.cacheId&&(delete cp[this.cacheId],delete up[this.cacheId],this.cacheId=null),this.valid=!1,this.dispose(),t.removeFromCache(this),this.textureCacheIds=null,this.destroyed=!0,this.emit("destroyed",this),this.removeAllListeners()}dispose(){this.emit("dispose",this)}castToBaseTexture(){return this}static from(e,i,s=ph.STRICT_TEXTURE_CACHE){const r="string"==typeof e;let n=null;if(r)n=e;else{if(!e._pixiId){const t=i?.pixiIdPrefix||"pixiid";e._pixiId=`${t}_${op()}`}n=e._pixiId}let o=cp[n];if(r&&s&&!o)throw new Error(`The cacheId "${n}" does not exist in BaseTextureCache.`);return o||(o=new t(e,i),o.cacheId=n,t.addToCache(o,n)),o}static fromBuffer(e,i,s,r){e=e||new Float32Array(i*s*4);const n=new Lp(e,{width:i,height:s,...r?.resourceOptions});let o,a;return e instanceof Float32Array?(o=Ql.RGBA,a=eh.FLOAT):e instanceof Int32Array?(o=Ql.RGBA_INTEGER,a=eh.INT):e instanceof Uint32Array?(o=Ql.RGBA_INTEGER,a=eh.UNSIGNED_INT):e instanceof Int16Array?(o=Ql.RGBA_INTEGER,a=eh.SHORT):e instanceof Uint16Array?(o=Ql.RGBA_INTEGER,a=eh.UNSIGNED_SHORT):e instanceof Int8Array?(o=Ql.RGBA,a=eh.BYTE):(o=Ql.RGBA,a=eh.UNSIGNED_BYTE),n.internal=!0,new t(n,Object.assign({},Rp,{type:a,format:o},r))}static addToCache(t,e){e&&(t.textureCacheIds.includes(e)||t.textureCacheIds.push(e),cp[e]&&cp[e]!==t&&console.warn(`BaseTexture added to the cache with an id [${e}] that already had an entry`),cp[e]=t)}static removeFromCache(t){if("string"==typeof t){const e=cp[t];if(e){const i=e.textureCacheIds.indexOf(t);return i>-1&&e.textureCacheIds.splice(i,1),delete cp[t],e}}else if(t?.textureCacheIds){for(let e=0;e<t.textureCacheIds.length;++e)delete cp[t.textureCacheIds[e]];return t.textureCacheIds.length=0,t}return null}};kp.defaultOptions={mipmap:nh.POW2,anisotropicLevel:0,scaleMode:sh.LINEAR,wrapMode:rh.CLAMP,alphaMode:oh.UNPACK,target:th.TEXTURE_2D,format:Ql.RGBA,type:eh.UNSIGNED_BYTE},kp._globalBatch=0;let Bp=kp;class Fp{constructor(){this.texArray=null,this.blend=0,this.type=Zl.TRIANGLES,this.start=0,this.size=0,this.data=null}}let Dp=0;class Up{constructor(t,e=!0,i=!1){this.data=t||new Float32Array(1),this._glBuffers={},this._updateID=0,this.index=i,this.static=e,this.id=Dp++,this.disposeRunner=new Op("disposeBuffer")}update(t){t instanceof Array&&(t=new Float32Array(t)),this.data=t||this.data,this._updateID++}dispose(){this.disposeRunner.emit(this,!1)}destroy(){this.dispose(),this.data=null}set index(t){this.type=t?dh.ELEMENT_ARRAY_BUFFER:dh.ARRAY_BUFFER}get index(){return this.type===dh.ELEMENT_ARRAY_BUFFER}static from(t){return t instanceof Array&&(t=new Float32Array(t)),new Up(t)}}class Gp{constructor(t,e=0,i=!1,s=eh.FLOAT,r,n,o,a=1){this.buffer=t,this.size=e,this.normalized=i,this.type=s,this.stride=r,this.start=n,this.instance=o,this.divisor=a}destroy(){this.buffer=null}static from(t,e,i,s,r){return new Gp(t,e,i,s,r)}}const Xp={Float32Array:Float32Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Uint8Array:Uint8Array};const Wp={5126:4,5123:2,5121:1};let Yp=0;const Hp={Float32Array:Float32Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Uint8Array:Uint8Array,Uint16Array:Uint16Array};class $p{constructor(t=[],e={}){this.buffers=t,this.indexBuffer=null,this.attributes=e,this.glVertexArrayObjects={},this.id=Yp++,this.instanced=!1,this.instanceCount=1,this.disposeRunner=new Op("disposeGeometry"),this.refCount=0}addAttribute(t,e,i=0,s=!1,r,n,o,a=!1){if(!e)throw new Error("You must pass a buffer when creating an attribute");e instanceof Up||(e instanceof Array&&(e=new Float32Array(e)),e=new Up(e));const l=t.split("|");if(l.length>1){for(let t=0;t<l.length;t++)this.addAttribute(l[t],e,i,s,r);return this}let h=this.buffers.indexOf(e);return-1===h&&(this.buffers.push(e),h=this.buffers.length-1),this.attributes[t]=new Gp(h,i,s,r,n,o,a),this.instanced=this.instanced||a,this}getAttribute(t){return this.attributes[t]}getBuffer(t){return this.buffers[this.getAttribute(t).buffer]}addIndex(t){return t instanceof Up||(t instanceof Array&&(t=new Uint16Array(t)),t=new Up(t)),t.type=dh.ELEMENT_ARRAY_BUFFER,this.indexBuffer=t,this.buffers.includes(t)||this.buffers.push(t),this}getIndex(){return this.indexBuffer}interleave(){if(1===this.buffers.length||2===this.buffers.length&&this.indexBuffer)return this;const t=[],e=[],i=new Up;let s;for(s in this.attributes){const i=this.attributes[s],r=this.buffers[i.buffer];t.push(r.data),e.push(i.size*Wp[i.type]/4),i.buffer=0}for(i.data=function(t,e){let i=0,s=0;const r={};for(let l=0;l<t.length;l++)s+=e[l],i+=t[l].length;const n=new ArrayBuffer(4*i);let o=null,a=0;for(let l=0;l<t.length;l++){const i=e[l],h=t[l],u=Zd(h);r[u]||(r[u]=new Xp[u](n)),o=r[u];for(let t=0;t<h.length;t++)o[(t/i|0)*s+a+t%i]=h[t];a+=i}return new Float32Array(n)}(t,e),s=0;s<this.buffers.length;s++)this.buffers[s]!==this.indexBuffer&&this.buffers[s].destroy();return this.buffers=[i],this.indexBuffer&&this.buffers.push(this.indexBuffer),this}getSize(){for(const t in this.attributes){const e=this.attributes[t];return this.buffers[e.buffer].data.length/(e.stride/4||e.size)}return 0}dispose(){this.disposeRunner.emit(this,!1)}destroy(){this.dispose(),this.buffers=null,this.indexBuffer=null,this.attributes=null}clone(){const t=new $p;for(let e=0;e<this.buffers.length;e++)t.buffers[e]=new Up(this.buffers[e].data.slice(0));for(const e in this.attributes){const i=this.attributes[e];t.attributes[e]=new Gp(i.buffer,i.size,i.normalized,i.type,i.stride,i.start,i.instance)}return this.indexBuffer&&(t.indexBuffer=t.buffers[this.buffers.indexOf(this.indexBuffer)],t.indexBuffer.type=dh.ELEMENT_ARRAY_BUFFER),t}static merge(t){const e=new $p,i=[],s=[],r=[];let n;for(let o=0;o<t.length;o++){n=t[o];for(let t=0;t<n.buffers.length;t++)s[t]=s[t]||0,s[t]+=n.buffers[t].data.length,r[t]=0}for(let o=0;o<n.buffers.length;o++)i[o]=new(Hp[Zd(n.buffers[o].data)])(s[o]),e.buffers[o]=new Up(i[o]);for(let o=0;o<t.length;o++){n=t[o];for(let t=0;t<n.buffers.length;t++)i[t].set(n.buffers[t].data,r[t]),r[t]+=n.buffers[t].data.length}if(e.attributes=n.attributes,n.indexBuffer){e.indexBuffer=e.buffers[n.buffers.indexOf(n.indexBuffer)],e.indexBuffer.type=dh.ELEMENT_ARRAY_BUFFER;let i=0,s=0,r=0,o=0;for(let t=0;t<n.buffers.length;t++)if(n.buffers[t]!==n.indexBuffer){o=t;break}for(const t in n.attributes){const e=n.attributes[t];(0|e.buffer)===o&&(s+=e.size*Wp[e.type]/4)}for(let n=0;n<t.length;n++){const a=t[n].indexBuffer.data;for(let t=0;t<a.length;t++)e.indexBuffer.data[t+r]+=i;i+=t[n].buffers[o].data.length/s,r+=a.length}}return e}}class jp extends $p{constructor(t=!1){super(),this._buffer=new Up(null,t,!1),this._indexBuffer=new Up(null,t,!0),this.addAttribute("aVertexPosition",this._buffer,2,!1,eh.FLOAT).addAttribute("aTextureCoord",this._buffer,2,!1,eh.FLOAT).addAttribute("aColor",this._buffer,4,!0,eh.UNSIGNED_BYTE).addAttribute("aTextureId",this._buffer,1,!0,eh.FLOAT).addIndex(this._indexBuffer)}}const zp=2*Math.PI,Vp=180/Math.PI,qp=Math.PI/180;var Jp=/* @__PURE__ */(t=>(t[t.POLY=0]="POLY",t[t.RECT=1]="RECT",t[t.CIRC=2]="CIRC",t[t.ELIP=3]="ELIP",t[t.RREC=4]="RREC",t))(Jp||{});class Kp{constructor(t=0,e=0){this.x=0,this.y=0,this.x=t,this.y=e}clone(){return new Kp(this.x,this.y)}copyFrom(t){return this.set(t.x,t.y),this}copyTo(t){return t.set(this.x,this.y),t}equals(t){return t.x===this.x&&t.y===this.y}set(t=0,e=t){return this.x=t,this.y=e,this}}Kp.prototype.toString=function(){return`[@pixi/math:Point x=${this.x} y=${this.y}]`};const Zp=[new Kp,new Kp,new Kp,new Kp];class Qp{constructor(t=0,e=0,i=0,s=0){this.x=Number(t),this.y=Number(e),this.width=Number(i),this.height=Number(s),this.type=Jp.RECT}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}static get EMPTY(){return new Qp(0,0,0,0)}clone(){return new Qp(this.x,this.y,this.width,this.height)}copyFrom(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this}copyTo(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t}contains(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t<this.x+this.width&&e>=this.y&&e<this.y+this.height)}intersects(t,e){if(!e){const e=this.x<t.x?t.x:this.x;if((this.right>t.right?t.right:this.right)<=e)return!1;const i=this.y<t.y?t.y:this.y;return(this.bottom>t.bottom?t.bottom:this.bottom)>i}const i=this.left,s=this.right,r=this.top,n=this.bottom;if(s<=i||n<=r)return!1;const o=Zp[0].set(t.left,t.top),a=Zp[1].set(t.left,t.bottom),l=Zp[2].set(t.right,t.top),h=Zp[3].set(t.right,t.bottom);if(l.x<=o.x||a.y<=o.y)return!1;const u=Math.sign(e.a*e.d-e.b*e.c);if(0===u||(e.apply(o,o),e.apply(a,a),e.apply(l,l),e.apply(h,h),Math.max(o.x,a.x,l.x,h.x)<=i||Math.min(o.x,a.x,l.x,h.x)>=s||Math.max(o.y,a.y,l.y,h.y)<=r||Math.min(o.y,a.y,l.y,h.y)>=n))return!1;const c=u*(a.y-o.y),d=u*(o.x-a.x),p=c*i+d*r,f=c*s+d*r,m=c*i+d*n,g=c*s+d*n;if(Math.max(p,f,m,g)<=c*o.x+d*o.y||Math.min(p,f,m,g)>=c*h.x+d*h.y)return!1;const y=u*(o.y-l.y),v=u*(l.x-o.x),x=y*i+v*r,b=y*s+v*r,_=y*i+v*n,w=y*s+v*n;return!(Math.max(x,b,_,w)<=y*o.x+v*o.y||Math.min(x,b,_,w)>=y*h.x+v*h.y)}pad(t=0,e=t){return this.x-=t,this.y-=e,this.width+=2*t,this.height+=2*e,this}fit(t){const e=Math.max(this.x,t.x),i=Math.min(this.x+this.width,t.x+t.width),s=Math.max(this.y,t.y),r=Math.min(this.y+this.height,t.y+t.height);return this.x=e,this.width=Math.max(i-e,0),this.y=s,this.height=Math.max(r-s,0),this}ceil(t=1,e=.001){const i=Math.ceil((this.x+this.width-e)*t)/t,s=Math.ceil((this.y+this.height-e)*t)/t;return this.x=Math.floor((this.x+e)*t)/t,this.y=Math.floor((this.y+e)*t)/t,this.width=i-this.x,this.height=s-this.y,this}enlarge(t){const e=Math.min(this.x,t.x),i=Math.max(this.x+this.width,t.x+t.width),s=Math.min(this.y,t.y),r=Math.max(this.y+this.height,t.y+t.height);return this.x=e,this.width=i-e,this.y=s,this.height=r-s,this}}Qp.prototype.toString=function(){return`[@pixi/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`};class tf{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.radius=i,this.type=Jp.CIRC}clone(){return new tf(this.x,this.y,this.radius)}contains(t,e){if(this.radius<=0)return!1;const i=this.radius*this.radius;let s=this.x-t,r=this.y-e;return s*=s,r*=r,s+r<=i}getBounds(){return new Qp(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}}tf.prototype.toString=function(){return`[@pixi/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`};class ef{constructor(t=0,e=0,i=0,s=0){this.x=t,this.y=e,this.width=i,this.height=s,this.type=Jp.ELIP}clone(){return new ef(this.x,this.y,this.width,this.height)}contains(t,e){if(this.width<=0||this.height<=0)return!1;let i=(t-this.x)/this.width,s=(e-this.y)/this.height;return i*=i,s*=s,i+s<=1}getBounds(){return new Qp(this.x-this.width,this.y-this.height,this.width,this.height)}}ef.prototype.toString=function(){return`[@pixi/math:Ellipse x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`};class sf{constructor(...t){let e=Array.isArray(t[0])?t[0]:t;if("number"!=typeof e[0]){const t=[];for(let i=0,s=e.length;i<s;i++)t.push(e[i].x,e[i].y);e=t}this.points=e,this.type=Jp.POLY,this.closeStroke=!0}clone(){const t=this.points.slice(),e=new sf(t);return e.closeStroke=this.closeStroke,e}contains(t,e){let i=!1;const s=this.points.length/2;for(let r=0,n=s-1;r<s;n=r++){const s=this.points[2*r],o=this.points[2*r+1],a=this.points[2*n],l=this.points[2*n+1];o>e!=l>e&&t<(e-o)/(l-o)*(a-s)+s&&(i=!i)}return i}}sf.prototype.toString=function(){return`[@pixi/math:PolygoncloseStroke=${this.closeStroke}points=${this.points.reduce((t,e)=>`${t}, ${e}`,"")}]`};class rf{constructor(t=0,e=0,i=0,s=0,r=20){this.x=t,this.y=e,this.width=i,this.height=s,this.radius=r,this.type=Jp.RREC}clone(){return new rf(this.x,this.y,this.width,this.height,this.radius)}contains(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){const i=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(e>=this.y+i&&e<=this.y+this.height-i||t>=this.x+i&&t<=this.x+this.width-i)return!0;let s=t-(this.x+i),r=e-(this.y+i);const n=i*i;if(s*s+r*r<=n||(s=t-(this.x+this.width-i),s*s+r*r<=n)||(r=e-(this.y+this.height-i),s*s+r*r<=n)||(s=t-(this.x+i),s*s+r*r<=n))return!0}return!1}}rf.prototype.toString=function(){return`[@pixi/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`};class nf{constructor(t=1,e=0,i=0,s=1,r=0,n=0){this.array=null,this.a=t,this.b=e,this.c=i,this.d=s,this.tx=r,this.ty=n}fromArray(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]}set(t,e,i,s,r,n){return this.a=t,this.b=e,this.c=i,this.d=s,this.tx=r,this.ty=n,this}toArray(t,e){this.array||(this.array=new Float32Array(9));const i=e||this.array;return t?(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(t,e){e=e||new Kp;const i=t.x,s=t.y;return e.x=this.a*i+this.c*s+this.tx,e.y=this.b*i+this.d*s+this.ty,e}applyInverse(t,e){e=e||new Kp;const i=1/(this.a*this.d+this.c*-this.b),s=t.x,r=t.y;return e.x=this.d*i*s+-this.c*i*r+(this.ty*this.c-this.tx*this.d)*i,e.y=this.a*i*r+-this.b*i*s+(-this.ty*this.a+this.tx*this.b)*i,e}translate(t,e){return this.tx+=t,this.ty+=e,this}scale(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this}rotate(t){const e=Math.cos(t),i=Math.sin(t),s=this.a,r=this.c,n=this.tx;return this.a=s*e-this.b*i,this.b=s*i+this.b*e,this.c=r*e-this.d*i,this.d=r*i+this.d*e,this.tx=n*e-this.ty*i,this.ty=n*i+this.ty*e,this}append(t){const e=this.a,i=this.b,s=this.c,r=this.d;return this.a=t.a*e+t.b*s,this.b=t.a*i+t.b*r,this.c=t.c*e+t.d*s,this.d=t.c*i+t.d*r,this.tx=t.tx*e+t.ty*s+this.tx,this.ty=t.tx*i+t.ty*r+this.ty,this}setTransform(t,e,i,s,r,n,o,a,l){return this.a=Math.cos(o+l)*r,this.b=Math.sin(o+l)*r,this.c=-Math.sin(o-a)*n,this.d=Math.cos(o-a)*n,this.tx=t-(i*this.a+s*this.c),this.ty=e-(i*this.b+s*this.d),this}prepend(t){const e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){const e=this.a,i=this.c;this.a=e*t.a+this.b*t.c,this.b=e*t.b+this.b*t.d,this.c=i*t.a+this.d*t.c,this.d=i*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this}decompose(t){const e=this.a,i=this.b,s=this.c,r=this.d,n=t.pivot,o=-Math.atan2(-s,r),a=Math.atan2(i,e),l=Math.abs(o+a);return l<1e-5||Math.abs(zp-l)<1e-5?(t.rotation=a,t.skew.x=t.skew.y=0):(t.rotation=0,t.skew.x=o,t.skew.y=a),t.scale.x=Math.sqrt(e*e+i*i),t.scale.y=Math.sqrt(s*s+r*r),t.position.x=this.tx+(n.x*e+n.y*s),t.position.y=this.ty+(n.x*i+n.y*r),t}invert(){const t=this.a,e=this.b,i=this.c,s=this.d,r=this.tx,n=t*s-e*i;return this.a=s/n,this.b=-e/n,this.c=-i/n,this.d=t/n,this.tx=(i*this.ty-s*r)/n,this.ty=-(t*this.ty-e*r)/n,this}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const t=new nf;return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyTo(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyFrom(t){return this.a=t.a,this.b=t.b,this.c=t.c,this.d=t.d,this.tx=t.tx,this.ty=t.ty,this}static get IDENTITY(){return new nf}static get TEMP_MATRIX(){return new nf}}nf.prototype.toString=function(){return`[@pixi/math:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`};const of=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],af=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],lf=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],hf=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],uf=[],cf=[],df=Math.sign;!function(){for(let t=0;t<16;t++){const e=[];uf.push(e);for(let i=0;i<16;i++){const s=df(of[t]*of[i]+lf[t]*af[i]),r=df(af[t]*of[i]+hf[t]*af[i]),n=df(of[t]*lf[i]+lf[t]*hf[i]),o=df(af[t]*lf[i]+hf[t]*hf[i]);for(let t=0;t<16;t++)if(of[t]===s&&af[t]===r&&lf[t]===n&&hf[t]===o){e.push(t);break}}}for(let t=0;t<16;t++){const e=new nf;e.set(of[t],af[t],lf[t],hf[t],0,0),cf.push(e)}}();const pf={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:t=>of[t],uY:t=>af[t],vX:t=>lf[t],vY:t=>hf[t],inv:t=>8&t?15&t:7&-t,add:(t,e)=>uf[t][e],sub:(t,e)=>uf[t][pf.inv(e)],rotate180:t=>4^t,isVertical:t=>2==(3&t),byDirection:(t,e)=>2*Math.abs(t)<=Math.abs(e)?e>=0?pf.S:pf.N:2*Math.abs(e)<=Math.abs(t)?t>0?pf.E:pf.W:e>0?t>0?pf.SE:pf.SW:t>0?pf.NE:pf.NW,matrixAppendRotationInv:(t,e,i=0,s=0)=>{const r=cf[pf.inv(e)];r.tx=i,r.ty=s,t.append(r)}};class ff{constructor(t,e,i=0,s=0){this._x=i,this._y=s,this.cb=t,this.scope=e}clone(t=this.cb,e=this.scope){return new ff(t,e,this._x,this._y)}set(t=0,e=t){return(this._x!==t||this._y!==e)&&(this._x=t,this._y=e,this.cb.call(this.scope)),this}copyFrom(t){return(this._x!==t.x||this._y!==t.y)&&(this._x=t.x,this._y=t.y,this.cb.call(this.scope)),this}copyTo(t){return t.set(this._x,this._y),t}equals(t){return t.x===this._x&&t.y===this._y}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}ff.prototype.toString=function(){return`[@pixi/math:ObservablePoint x=${this.x} y=${this.y} scope=${this.scope}]`};const mf=class{constructor(){this.worldTransform=new nf,this.localTransform=new nf,this.position=new ff(this.onChange,this,0,0),this.scale=new ff(this.onChange,this,1,1),this.pivot=new ff(this.onChange,this,0,0),this.skew=new ff(this.updateSkew,this,0,0),this._rotation=0,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._localID=0,this._currentLocalID=0,this._worldID=0,this._parentID=0}onChange(){this._localID++}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._localID++}updateLocalTransform(){const t=this.localTransform;this._localID!==this._currentLocalID&&(t.a=this._cx*this.scale.x,t.b=this._sx*this.scale.x,t.c=this._cy*this.scale.y,t.d=this._sy*this.scale.y,t.tx=this.position.x-(this.pivot.x*t.a+this.pivot.y*t.c),t.ty=this.position.y-(this.pivot.x*t.b+this.pivot.y*t.d),this._currentLocalID=this._localID,this._parentID=-1)}updateTransform(t){const e=this.localTransform;if(this._localID!==this._currentLocalID&&(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._currentLocalID=this._localID,this._parentID=-1),this._parentID!==t._worldID){const i=t.worldTransform,s=this.worldTransform;s.a=e.a*i.a+e.b*i.c,s.b=e.a*i.b+e.b*i.d,s.c=e.c*i.a+e.d*i.c,s.d=e.c*i.b+e.d*i.d,s.tx=e.tx*i.a+e.ty*i.c+i.tx,s.ty=e.tx*i.b+e.ty*i.d+i.ty,this._parentID=t._worldID,this._worldID++}}setFromMatrix(t){t.decompose(this),this._localID++}get rotation(){return this._rotation}set rotation(t){this._rotation!==t&&(this._rotation=t,this.updateSkew())}};mf.IDENTITY=new mf;let gf=mf;gf.prototype.toString=function(){return`[@pixi/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}) ]`};function yf(t,e,i){const s=t.createShader(e);return t.shaderSource(s,i),t.compileShader(s),s}function vf(t){const e=new Array(t);for(let i=0;i<e.length;i++)e[i]=!1;return e}function xf(t,e){switch(t){case"float":case"int":case"uint":case"sampler2D":case"sampler2DArray":return 0;case"vec2":return new Float32Array(2*e);case"vec3":return new Float32Array(3*e);case"vec4":return new Float32Array(4*e);case"ivec2":return new Int32Array(2*e);case"ivec3":return new Int32Array(3*e);case"ivec4":return new Int32Array(4*e);case"uvec2":return new Uint32Array(2*e);case"uvec3":return new Uint32Array(3*e);case"uvec4":return new Uint32Array(4*e);case"bool":return!1;case"bvec2":return vf(2*e);case"bvec3":return vf(3*e);case"bvec4":return vf(4*e);case"mat2":return new Float32Array([1,0,0,1]);case"mat3":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const bf=[{test:t=>"float"===t.type&&1===t.size&&!t.isArray,code:t=>`\n if(uv["${t}"] !== ud["${t}"].value)\n {\n ud["${t}"].value = uv["${t}"]\n gl.uniform1f(ud["${t}"].location, uv["${t}"])\n }\n `},{test:(t,e)=>!("sampler2D"!==t.type&&"samplerCube"!==t.type&&"sampler2DArray"!==t.type||1!==t.size||t.isArray||null!=e&&void 0===e.castToBaseTexture),code:t=>`t = syncData.textureCount++;\n\n renderer.texture.bind(uv["${t}"], t);\n\n if(ud["${t}"].value !== t)\n {\n ud["${t}"].value = t;\n gl.uniform1i(ud["${t}"].location, t);\n; // eslint-disable-line max-len\n }`},{test:(t,e)=>"mat3"===t.type&&1===t.size&&!t.isArray&&void 0!==e.a,code:t=>`\n gl.uniformMatrix3fv(ud["${t}"].location, false, uv["${t}"].toArray(true));\n `,codeUbo:t=>`\n var ${t}_matrix = uv.${t}.toArray(true);\n\n data[offset] = ${t}_matrix[0];\n data[offset+1] = ${t}_matrix[1];\n data[offset+2] = ${t}_matrix[2];\n \n data[offset + 4] = ${t}_matrix[3];\n data[offset + 5] = ${t}_matrix[4];\n data[offset + 6] = ${t}_matrix[5];\n \n data[offset + 8] = ${t}_matrix[6];\n data[offset + 9] = ${t}_matrix[7];\n data[offset + 10] = ${t}_matrix[8];\n `},{test:(t,e)=>"vec2"===t.type&&1===t.size&&!t.isArray&&void 0!==e.x,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.x || cv[1] !== v.y)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n gl.uniform2f(ud["${t}"].location, v.x, v.y);\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n `},{test:t=>"vec2"===t.type&&1===t.size&&!t.isArray,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(ud["${t}"].location, v[0], v[1]);\n }\n `},{test:(t,e)=>"vec4"===t.type&&1===t.size&&!t.isArray&&void 0!==e.width,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n cv[2] = v.width;\n cv[3] = v.height;\n gl.uniform4f(ud["${t}"].location, v.x, v.y, v.width, v.height)\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n data[offset+2] = v.width;\n data[offset+3] = v.height;\n `},{test:(t,e)=>"vec4"===t.type&&1===t.size&&!t.isArray&&void 0!==e.red,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.alpha)\n {\n cv[0] = v.red;\n cv[1] = v.green;\n cv[2] = v.blue;\n cv[3] = v.alpha;\n gl.uniform4f(ud["${t}"].location, v.red, v.green, v.blue, v.alpha)\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.red;\n data[offset+1] = v.green;\n data[offset+2] = v.blue;\n data[offset+3] = v.alpha;\n `},{test:(t,e)=>"vec3"===t.type&&1===t.size&&!t.isArray&&void 0!==e.red,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.a)\n {\n cv[0] = v.red;\n cv[1] = v.green;\n cv[2] = v.blue;\n \n gl.uniform3f(ud["${t}"].location, v.red, v.green, v.blue)\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.red;\n data[offset+1] = v.green;\n data[offset+2] = v.blue;\n `},{test:t=>"vec4"===t.type&&1===t.size&&!t.isArray,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(ud["${t}"].location, v[0], v[1], v[2], v[3])\n }`}],_f={float:"\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1f(location, v);\n }",vec2:"\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2f(location, v[0], v[1])\n }",vec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3f(location, v[0], v[1], v[2])\n }",vec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(location, v[0], v[1], v[2], v[3]);\n }",int:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",ivec2:"\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }",ivec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }",ivec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }",uint:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1ui(location, v);\n }",uvec2:"\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2ui(location, v[0], v[1]);\n }",uvec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3ui(location, v[0], v[1], v[2]);\n }",uvec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4ui(location, v[0], v[1], v[2], v[3]);\n }",bool:"\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1i(location, v);\n }",bvec2:"\n if (cv[0] != v[0] || cv[1] != v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }",bvec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }",bvec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }",mat2:"gl.uniformMatrix2fv(location, false, v)",mat3:"gl.uniformMatrix3fv(location, false, v)",mat4:"gl.uniformMatrix4fv(location, false, v)",sampler2D:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",samplerCube:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",sampler2DArray:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }"},wf={float:"gl.uniform1fv(location, v)",vec2:"gl.uniform2fv(location, v)",vec3:"gl.uniform3fv(location, v)",vec4:"gl.uniform4fv(location, v)",mat4:"gl.uniformMatrix4fv(location, false, v)",mat3:"gl.uniformMatrix3fv(location, false, v)",mat2:"gl.uniformMatrix2fv(location, false, v)",int:"gl.uniform1iv(location, v)",ivec2:"gl.uniform2iv(location, v)",ivec3:"gl.uniform3iv(location, v)",ivec4:"gl.uniform4iv(location, v)",uint:"gl.uniform1uiv(location, v)",uvec2:"gl.uniform2uiv(location, v)",uvec3:"gl.uniform3uiv(location, v)",uvec4:"gl.uniform4uiv(location, v)",bool:"gl.uniform1iv(location, v)",bvec2:"gl.uniform2iv(location, v)",bvec3:"gl.uniform3iv(location, v)",bvec4:"gl.uniform4iv(location, v)",sampler2D:"gl.uniform1iv(location, v)",samplerCube:"gl.uniform1iv(location, v)",sampler2DArray:"gl.uniform1iv(location, v)"};const Pf={};let Ef,Tf=Pf;function Af(){if(!Ef){Ef=hh.MEDIUM;const t=function(){if(Tf===Pf||Tf?.isContextLost()){const t=ph.ADAPTER.createCanvas();let e;ph.PREFER_ENV>=Vl.WEBGL2&&(e=t.getContext("webgl2",{})),e||(e=t.getContext("webgl",{})||t.getContext("experimental-webgl",{}),e?e.getExtension("WEBGL_draw_buffers"):e=null),Tf=e}return Tf}();if(t&&t.getShaderPrecisionFormat){const e=t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT);e&&(Ef=e.precision?hh.HIGH:hh.MEDIUM)}}return Ef}function If(t,e){const i=t.getShaderSource(e).split("\n").map((t,e)=>`${e}: ${t}`),s=t.getShaderInfoLog(e),r=s.split("\n"),n={},o=r.map(t=>parseFloat(t.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(t=>!(!t||n[t])&&(n[t]=!0,!0)),a=[""];o.forEach(t=>{i[t-1]=`%c${i[t-1]}%c`,a.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")});const l=i.join("\n");a[0]=l,console.error(s),console.groupCollapsed("click to view full shader code"),console.warn(...a),console.groupEnd()}const Sf={float:1,vec2:2,vec3:3,vec4:4,int:1,ivec2:2,ivec3:3,ivec4:4,uint:1,uvec2:2,uvec3:3,uvec4:4,bool:1,bvec2:2,bvec3:3,bvec4:4,mat2:4,mat3:9,mat4:16,sampler2D:1};function Cf(t){return Sf[t]}let Mf=null;const Of={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",UNSIGNED_INT:"uint",UNSIGNED_INT_VEC2:"uvec2",UNSIGNED_INT_VEC3:"uvec3",UNSIGNED_INT_VEC4:"uvec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",INT_SAMPLER_2D:"sampler2D",UNSIGNED_INT_SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray"};function Nf(t,e){if(!Mf){const e=Object.keys(Of);Mf={};for(let i=0;i<e.length;++i){const s=e[i];Mf[t[s]]=Of[s]}}return Mf[e]}function Lf(t,e,i){if("precision"!==t.substring(0,9)){let s=e;return e===hh.HIGH&&i!==hh.HIGH&&(s=hh.MEDIUM),`precision ${s} float;\n${t}`}return i!==hh.HIGH&&"precision highp"===t.substring(0,15)?t.replace("precision highp","precision mediump"):t}let Rf;let kf=0;const Bf={},Ff=class t{constructor(e,i,s="pixi-shader",r={}){this.extra={},this.id=kf++,this.vertexSrc=e||t.defaultVertexSrc,this.fragmentSrc=i||t.defaultFragmentSrc,this.vertexSrc=this.vertexSrc.trim(),this.fragmentSrc=this.fragmentSrc.trim(),this.extra=r,"#version"!==this.vertexSrc.substring(0,8)&&(s=s.replace(/\s+/g,"-"),Bf[s]?(Bf[s]++,s+=`-${Bf[s]}`):Bf[s]=1,this.vertexSrc=`#define SHADER_NAME ${s}\n${this.vertexSrc}`,this.fragmentSrc=`#define SHADER_NAME ${s}\n${this.fragmentSrc}`,this.vertexSrc=Lf(this.vertexSrc,t.defaultVertexPrecision,hh.HIGH),this.fragmentSrc=Lf(this.fragmentSrc,t.defaultFragmentPrecision,Af())),this.glPrograms={},this.syncUniforms=null}static get defaultVertexSrc(){return"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n"}static get defaultFragmentSrc(){return"varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}"}static from(e,i,s){const r=e+i;let n=hp[r];return n||(hp[r]=n=new t(e,i,s)),n}};Ff.defaultVertexPrecision=hh.HIGH,Ff.defaultFragmentPrecision=Oh.apple.device?hh.HIGH:hh.MEDIUM;let Df=Ff,Uf=0;class Gf{constructor(t,e,i){this.group=!0,this.syncUniforms={},this.dirtyId=0,this.id=Uf++,this.static=!!e,this.ubo=!!i,t instanceof Up?(this.buffer=t,this.buffer.type=dh.UNIFORM_BUFFER,this.autoManage=!1,this.ubo=!0):(this.uniforms=t,this.ubo&&(this.buffer=new Up(new Float32Array(1)),this.buffer.type=dh.UNIFORM_BUFFER,this.autoManage=!0))}update(){this.dirtyId++,!this.autoManage&&this.buffer&&this.buffer.update()}add(t,e,i){if(this.ubo)throw new Error("[UniformGroup] uniform groups in ubo mode cannot be modified, or have uniform groups nested in them");this.uniforms[t]=new Gf(e,i)}static from(t,e,i){return new Gf(t,e,i)}static uboFrom(t,e){return new Gf(t,e??!0,!0)}}class Xf{constructor(t,e){this.uniformBindCount=0,this.program=t,this.uniformGroup=e?e instanceof Gf?e:new Gf(e):new Gf({}),this.disposeRunner=new Op("disposeShader")}checkUniformExists(t,e){if(e.uniforms[t])return!0;for(const i in e.uniforms){const s=e.uniforms[i];if(!0===s.group&&this.checkUniformExists(t,s))return!0}return!1}destroy(){this.uniformGroup=null,this.disposeRunner.emit(this),this.disposeRunner.destroy()}get uniforms(){return this.uniformGroup.uniforms}static from(t,e,i){const s=Df.from(t,e);return new Xf(s,i)}}class Wf{constructor(t,e){if(this.vertexSrc=t,this.fragTemplate=e,this.programCache={},this.defaultGroupCache={},!e.includes("%count%"))throw new Error('Fragment template must contain "%count%".');if(!e.includes("%forloop%"))throw new Error('Fragment template must contain "%forloop%".')}generateShader(t){if(!this.programCache[t]){const e=new Int32Array(t);for(let s=0;s<t;s++)e[s]=s;this.defaultGroupCache[t]=Gf.from({uSamplers:e},!0);let i=this.fragTemplate;i=i.replace(/%count%/gi,`${t}`),i=i.replace(/%forloop%/gi,this.generateSampleSrc(t)),this.programCache[t]=new Df(this.vertexSrc,i)}const e={tint:new Float32Array([1,1,1,1]),translationMatrix:new nf,default:this.defaultGroupCache[t]};return new Xf(this.programCache[t],e)}generateSampleSrc(t){let e="";e+="\n",e+="\n";for(let i=0;i<t;i++)i>0&&(e+="\nelse "),i<t-1&&(e+=`if(vTextureId < ${i}.5)`),e+="\n{",e+=`\n\tcolor = texture2D(uSamplers[${i}], vTextureCoord);`,e+="\n}";return e+="\n",e+="\n",e}}class Yf{constructor(){this.elements=[],this.ids=[],this.count=0}clear(){for(let t=0;t<this.count;t++)this.elements[t]=null;this.count=0}}class Hf{constructor(t){this.renderer=t}flush(){}destroy(){this.renderer=null}start(){}stop(){this.flush()}render(t){}}const $f=class t extends Hf{constructor(e){super(e),this.setShaderGenerator(),this.geometryClass=jp,this.vertexSize=6,this.state=Sp.for2d(),this.size=4*t.defaultBatchSize,this._vertexCount=0,this._indexCount=0,this._bufferedElements=[],this._bufferedTextures=[],this._bufferSize=0,this._shader=null,this._packedGeometries=[],this._packedGeometryPoolSize=2,this._flushId=0,this._aBuffers={},this._iBuffers={},this.maxTextures=1,this.renderer.on("prerender",this.onPrerender,this),e.runners.contextChange.add(this),this._dcIndex=0,this._aIndex=0,this._iIndex=0,this._attributeBuffer=null,this._indexBuffer=null,this._tempBoundTextures=[]}static get defaultMaxTextures(){return this._defaultMaxTextures=this._defaultMaxTextures??function(t){let e=!0;const i=ph.ADAPTER.getNavigator();if(Oh.tablet||Oh.phone){if(Oh.apple.device){const t=i.userAgent.match(/OS (\d+)_(\d+)?/);t&&parseInt(t[1],10)<11&&(e=!1)}if(Oh.android.device){const t=i.userAgent.match(/Android\s([0-9.]*)/);t&&parseInt(t[1],10)<7&&(e=!1)}}return e?t:4}(32),this._defaultMaxTextures}static set defaultMaxTextures(t){this._defaultMaxTextures=t}static get canUploadSameBuffer(){return this._canUploadSameBuffer=this._canUploadSameBuffer??!Oh.apple.device,this._canUploadSameBuffer}static set canUploadSameBuffer(t){this._canUploadSameBuffer=t}get MAX_TEXTURES(){return dd("7.1.0","BatchRenderer#MAX_TEXTURES renamed to BatchRenderer#maxTextures"),this.maxTextures}static get defaultVertexSrc(){return"precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n"}static get defaultFragmentTemplate(){return"varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n"}setShaderGenerator({vertex:e=t.defaultVertexSrc,fragment:i=t.defaultFragmentTemplate}={}){this.shaderGenerator=new Wf(e,i)}contextChange(){const e=this.renderer.gl;ph.PREFER_ENV===Vl.WEBGL_LEGACY?this.maxTextures=1:(this.maxTextures=Math.min(e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),t.defaultMaxTextures),this.maxTextures=function(t,e){if(0===t)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const i=e.createShader(e.FRAGMENT_SHADER);for(;;){const s=Ap.replace(/%forloop%/gi,Ip(t));if(e.shaderSource(i,s),e.compileShader(i),e.getShaderParameter(i,e.COMPILE_STATUS))break;t=t/2|0}return t}(this.maxTextures,e)),this._shader=this.shaderGenerator.generateShader(this.maxTextures);for(let t=0;t<this._packedGeometryPoolSize;t++)this._packedGeometries[t]=new this.geometryClass;this.initFlushBuffers()}initFlushBuffers(){const{_drawCallPool:e,_textureArrayPool:i}=t,s=this.size/4,r=Math.floor(s/this.maxTextures)+1;for(;e.length<s;)e.push(new Fp);for(;i.length<r;)i.push(new Yf);for(let t=0;t<this.maxTextures;t++)this._tempBoundTextures[t]=null}onPrerender(){this._flushId=0}render(t){t._texture.valid&&(this._vertexCount+t.vertexData.length/2>this.size&&this.flush(),this._vertexCount+=t.vertexData.length/2,this._indexCount+=t.indices.length,this._bufferedTextures[this._bufferSize]=t._texture.baseTexture,this._bufferedElements[this._bufferSize++]=t)}buildTexturesAndDrawCalls(){const{_bufferedTextures:e,maxTextures:i}=this,s=t._textureArrayPool,r=this.renderer.batch,n=this._tempBoundTextures,o=this.renderer.textureGC.count;let a=++Bp._globalBatch,l=0,h=s[0],u=0;r.copyBoundTextures(n,i);for(let t=0;t<this._bufferSize;++t){const c=e[t];e[t]=null,c._batchEnabled!==a&&(h.count>=i&&(r.boundArray(h,n,a,i),this.buildDrawCalls(h,u,t),u=t,h=s[++l],++a),c._batchEnabled=a,c.touched=o,h.elements[h.count++]=c)}h.count>0&&(r.boundArray(h,n,a,i),this.buildDrawCalls(h,u,this._bufferSize),++l,++a);for(let t=0;t<n.length;t++)n[t]=null;Bp._globalBatch=a}buildDrawCalls(e,i,s){const{_bufferedElements:r,_attributeBuffer:n,_indexBuffer:o,vertexSize:a}=this,l=t._drawCallPool;let h=this._dcIndex,u=this._aIndex,c=this._iIndex,d=l[h];d.start=this._iIndex,d.texArray=e;for(let t=i;t<s;++t){const s=r[t],p=s._texture.baseTexture,f=Jd[p.alphaMode?1:0][s.blendMode];r[t]=null,i<t&&d.blend!==f&&(d.size=c-d.start,i=t,d=l[++h],d.texArray=e,d.start=c),this.packInterleavedGeometry(s,n,o,u,c),u+=s.vertexData.length/2*a,c+=s.indices.length,d.blend=f}i<s&&(d.size=c-d.start,++h),this._dcIndex=h,this._aIndex=u,this._iIndex=c}bindAndClearTexArray(t){const e=this.renderer.texture;for(let i=0;i<t.count;i++)e.bind(t.elements[i],t.ids[i]),t.elements[i]=null;t.count=0}updateGeometry(){const{_packedGeometries:e,_attributeBuffer:i,_indexBuffer:s}=this;t.canUploadSameBuffer?(e[this._flushId]._buffer.update(i.rawBinaryData),e[this._flushId]._indexBuffer.update(s),this.renderer.geometry.updateBuffers()):(this._packedGeometryPoolSize<=this._flushId&&(this._packedGeometryPoolSize++,e[this._flushId]=new this.geometryClass),e[this._flushId]._buffer.update(i.rawBinaryData),e[this._flushId]._indexBuffer.update(s),this.renderer.geometry.bind(e[this._flushId]),this.renderer.geometry.updateBuffers(),this._flushId++)}drawBatches(){const e=this._dcIndex,{gl:i,state:s}=this.renderer,r=t._drawCallPool;let n=null;for(let t=0;t<e;t++){const{texArray:e,type:o,size:a,start:l,blend:h}=r[t];n!==e&&(n=e,this.bindAndClearTexArray(e)),this.state.blendMode=h,s.set(this.state),i.drawElements(o,a,i.UNSIGNED_SHORT,2*l)}}flush(){0!==this._vertexCount&&(this._attributeBuffer=this.getAttributeBuffer(this._vertexCount),this._indexBuffer=this.getIndexBuffer(this._indexCount),this._aIndex=0,this._iIndex=0,this._dcIndex=0,this.buildTexturesAndDrawCalls(),this.updateGeometry(),this.drawBatches(),this._bufferSize=0,this._vertexCount=0,this._indexCount=0)}start(){this.renderer.state.set(this.state),this.renderer.texture.ensureSamplerType(this.maxTextures),this.renderer.shader.bind(this._shader),t.canUploadSameBuffer&&this.renderer.geometry.bind(this._packedGeometries[this._flushId])}stop(){this.flush()}destroy(){for(let t=0;t<this._packedGeometryPoolSize;t++)this._packedGeometries[t]&&this._packedGeometries[t].destroy();this.renderer.off("prerender",this.onPrerender,this),this._aBuffers=null,this._iBuffers=null,this._packedGeometries=null,this._attributeBuffer=null,this._indexBuffer=null,this._shader&&(this._shader.destroy(),this._shader=null),super.destroy()}getAttributeBuffer(t){const e=tp(Math.ceil(t/8)),i=ip(e),s=8*e;this._aBuffers.length<=i&&(this._iBuffers.length=i+1);let r=this._aBuffers[s];return r||(this._aBuffers[s]=r=new Tp(s*this.vertexSize*4)),r}getIndexBuffer(t){const e=tp(Math.ceil(t/12)),i=ip(e),s=12*e;this._iBuffers.length<=i&&(this._iBuffers.length=i+1);let r=this._iBuffers[i];return r||(this._iBuffers[i]=r=new Uint16Array(s)),r}packInterleavedGeometry(t,e,i,s,r){const{uint32View:n,float32View:o}=e,a=s/this.vertexSize,l=t.uvs,h=t.indices,u=t.vertexData,c=t._texture.baseTexture._batchLocation,d=Math.min(t.worldAlpha,1),p=qd.shared.setValue(t._tintRGB).toPremultiplied(d,t._texture.baseTexture.alphaMode>0);for(let f=0;f<u.length;f+=2)o[s++]=u[f],o[s++]=u[f+1],o[s++]=l[f],o[s++]=l[f+1],n[s++]=p,o[s++]=c;for(let f=0;f<h.length;f++)i[r++]=a+h[f]}};$f.defaultBatchSize=4096,$f.extension={name:"batch",type:_p.RendererPlugin},$f._drawCallPool=[],$f._textureArrayPool=[];let jf=$f;Ep.add(jf);const zf=class t extends Xf{constructor(e,i,s){super(Df.from(e||t.defaultVertexSrc,i||t.defaultFragmentSrc),s),this.padding=0,this.resolution=t.defaultResolution,this.multisample=t.defaultMultisample,this.enabled=!0,this.autoFit=!0,this.state=new Sp}apply(t,e,i,s,r){t.applyFilter(this,e,i,s)}get blendMode(){return this.state.blendMode}set blendMode(t){this.state.blendMode=t}get resolution(){return this._resolution}set resolution(t){this._resolution=t}static get defaultVertexSrc(){return"attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"}static get defaultFragmentSrc(){return"varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"}};zf.defaultResolution=1,zf.defaultMultisample=ch.NONE;let Vf=zf;class qf{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new qd(0),this.alpha=1}init(t){this.clearBeforeRender=t.clearBeforeRender;const{backgroundColor:e,background:i,backgroundAlpha:s}=t,r=i??e;void 0!==r&&(this.color=r),this.alpha=s}get color(){return this._backgroundColor.value}set color(t){this._backgroundColor.setValue(t)}get alpha(){return this._backgroundColor.alpha}set alpha(t){this._backgroundColor.setAlpha(t)}get backgroundColor(){return this._backgroundColor}destroy(){}}qf.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0},qf.extension={type:[_p.RendererSystem,_p.CanvasRendererSystem],name:"background"},Ep.add(qf);class Jf{constructor(t){this.renderer=t,this.emptyRenderer=new Hf(t),this.currentRenderer=this.emptyRenderer}setObjectRenderer(t){this.currentRenderer!==t&&(this.currentRenderer.stop(),this.currentRenderer=t,this.currentRenderer.start())}flush(){this.setObjectRenderer(this.emptyRenderer)}reset(){this.setObjectRenderer(this.emptyRenderer)}copyBoundTextures(t,e){const{boundTextures:i}=this.renderer.texture;for(let s=e-1;s>=0;--s)t[s]=i[s]||null,t[s]&&(t[s]._batchLocation=s)}boundArray(t,e,i,s){const{elements:r,ids:n,count:o}=t;let a=0;for(let l=0;l<o;l++){const t=r[l],o=t._batchLocation;if(o>=0&&o<s&&e[o]===t)n[l]=o;else for(;a<s;){const s=e[a];if(!s||s._batchEnabled!==i||s._batchLocation!==a){n[l]=a,t._batchLocation=a,e[a]=t;break}a++}}}destroy(){this.renderer=null}}Jf.extension={type:_p.RendererSystem,name:"batch"},Ep.add(Jf);let Kf=0;class Zf{constructor(t){this.renderer=t,this.webGLVersion=1,this.extensions={},this.supports={uint32Indices:!1},this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(t){this.gl=t,this.renderer.gl=t,this.renderer.CONTEXT_UID=Kf++}init(t){if(t.context)this.initFromContext(t.context);else{const e=this.renderer.background.alpha<1,i=t.premultipliedAlpha;this.preserveDrawingBuffer=t.preserveDrawingBuffer,this.useContextAlpha=t.useContextAlpha,this.powerPreference=t.powerPreference,this.initFromOptions({alpha:e,premultipliedAlpha:i,antialias:t.antialias,stencil:!0,preserveDrawingBuffer:t.preserveDrawingBuffer,powerPreference:t.powerPreference})}}initFromContext(t){this.gl=t,this.validateContext(t),this.renderer.gl=t,this.renderer.CONTEXT_UID=Kf++,this.renderer.runners.contextChange.emit(t);const e=this.renderer.view;void 0!==e.addEventListener&&(e.addEventListener("webglcontextlost",this.handleContextLost,!1),e.addEventListener("webglcontextrestored",this.handleContextRestored,!1))}initFromOptions(t){const e=this.createContext(this.renderer.view,t);this.initFromContext(e)}createContext(t,e){let i;if(ph.PREFER_ENV>=Vl.WEBGL2&&(i=t.getContext("webgl2",e)),i)this.webGLVersion=2;else if(this.webGLVersion=1,i=t.getContext("webgl",e)||t.getContext("experimental-webgl",e),!i)throw new Error("This browser does not support WebGL. Try using the canvas renderer");return this.gl=i,this.getExtensions(),this.gl}getExtensions(){const{gl:t}=this,e={loseContext:t.getExtension("WEBGL_lose_context"),anisotropicFiltering:t.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),s3tc:t.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:t.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:t.getExtension("WEBGL_compressed_texture_etc"),etc1:t.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:t.getExtension("WEBGL_compressed_texture_atc"),astc:t.getExtension("WEBGL_compressed_texture_astc"),bptc:t.getExtension("EXT_texture_compression_bptc")};1===this.webGLVersion?Object.assign(this.extensions,e,{drawBuffers:t.getExtension("WEBGL_draw_buffers"),depthTexture:t.getExtension("WEBGL_depth_texture"),vertexArrayObject:t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:t.getExtension("OES_element_index_uint"),floatTexture:t.getExtension("OES_texture_float"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),textureHalfFloat:t.getExtension("OES_texture_half_float"),textureHalfFloatLinear:t.getExtension("OES_texture_half_float_linear")}):2===this.webGLVersion&&Object.assign(this.extensions,e,{colorBufferFloat:t.getExtension("EXT_color_buffer_float")})}handleContextLost(t){t.preventDefault(),setTimeout(()=>{this.gl.isContextLost()&&this.extensions.loseContext&&this.extensions.loseContext.restoreContext()},0)}handleContextRestored(){this.renderer.runners.contextChange.emit(this.gl)}destroy(){const t=this.renderer.view;this.renderer=null,void 0!==t.removeEventListener&&(t.removeEventListener("webglcontextlost",this.handleContextLost),t.removeEventListener("webglcontextrestored",this.handleContextRestored)),this.gl.useProgram(null),this.extensions.loseContext&&this.extensions.loseContext.loseContext()}postrender(){this.renderer.objectRenderer.renderingToScreen&&this.gl.flush()}validateContext(t){const e=t.getContextAttributes(),i="WebGL2RenderingContext"in globalThis&&t instanceof globalThis.WebGL2RenderingContext;i&&(this.webGLVersion=2),e&&!e.stencil&&console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const s=i||!!t.getExtension("OES_element_index_uint");this.supports.uint32Indices=s,s||console.warn("Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly")}}Zf.defaultOptions={context:null,antialias:!1,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:"default"},Zf.extension={type:_p.RendererSystem,name:"context"},Ep.add(Zf);class Qf{constructor(t,e){if(this.width=Math.round(t),this.height=Math.round(e),!this.width||!this.height)throw new Error("Framebuffer width or height is zero");this.stencil=!1,this.depth=!1,this.dirtyId=0,this.dirtyFormat=0,this.dirtySize=0,this.depthTexture=null,this.colorTextures=[],this.glFramebuffers={},this.disposeRunner=new Op("disposeFramebuffer"),this.multisample=ch.NONE}get colorTexture(){return this.colorTextures[0]}addColorTexture(t=0,e){return this.colorTextures[t]=e||new Bp(null,{scaleMode:sh.NEAREST,resolution:1,mipmap:nh.OFF,width:this.width,height:this.height}),this.dirtyId++,this.dirtyFormat++,this}addDepthTexture(t){return this.depthTexture=t||new Bp(null,{scaleMode:sh.NEAREST,resolution:1,width:this.width,height:this.height,mipmap:nh.OFF,format:Ql.DEPTH_COMPONENT,type:eh.UNSIGNED_SHORT}),this.dirtyId++,this.dirtyFormat++,this}enableDepth(){return this.depth=!0,this.dirtyId++,this.dirtyFormat++,this}enableStencil(){return this.stencil=!0,this.dirtyId++,this.dirtyFormat++,this}resize(t,e){if(t=Math.round(t),e=Math.round(e),!t||!e)throw new Error("Framebuffer width and height must not be zero");if(t!==this.width||e!==this.height){this.width=t,this.height=e,this.dirtyId++,this.dirtySize++;for(let i=0;i<this.colorTextures.length;i++){const s=this.colorTextures[i],r=s.resolution;s.setSize(t/r,e/r)}if(this.depthTexture){const i=this.depthTexture.resolution;this.depthTexture.setSize(t/i,e/i)}}}dispose(){this.disposeRunner.emit(this,!1)}destroyDepthTexture(){this.depthTexture&&(this.depthTexture.destroy(),this.depthTexture=null,++this.dirtyId,++this.dirtyFormat)}}class tm extends Bp{constructor(t={}){if("number"==typeof t){t={width:arguments[0],height:arguments[1],scaleMode:arguments[2],resolution:arguments[3]}}t.width=t.width??100,t.height=t.height??100,t.multisample??(t.multisample=ch.NONE),super(null,t),this.mipmap=nh.OFF,this.valid=!0,this._clear=new qd([0,0,0,0]),this.framebuffer=new Qf(this.realWidth,this.realHeight).addColorTexture(0,this),this.framebuffer.multisample=t.multisample,this.maskStack=[],this.filterStack=[{}]}set clearColor(t){this._clear.setValue(t)}get clearColor(){return this._clear.value}get clear(){return this._clear}get multisample(){return this.framebuffer.multisample}set multisample(t){this.framebuffer.multisample=t}resize(t,e){this.framebuffer.resize(t*this.resolution,e*this.resolution),this.setRealSize(this.framebuffer.width,this.framebuffer.height)}dispose(){this.framebuffer.dispose(),super.dispose()}destroy(){super.destroy(),this.framebuffer.destroyDepthTexture(),this.framebuffer=null}}class em extends Np{constructor(t){const e=t;super(e.naturalWidth||e.videoWidth||e.displayWidth||e.width,e.naturalHeight||e.videoHeight||e.displayHeight||e.height),this.source=t,this.noSubImage=!1}static crossOrigin(t,e,i){void 0!==i||e.startsWith("data:")?!1!==i&&(t.crossOrigin="string"==typeof i?i:"anonymous"):t.crossOrigin=vp(e)}upload(t,e,i,s){const r=t.gl,n=e.realWidth,o=e.realHeight;if(s=s||this.source,typeof HTMLImageElement<"u"&&s instanceof HTMLImageElement){if(!s.complete||0===s.naturalWidth)return!1}else if(typeof HTMLVideoElement<"u"&&s instanceof HTMLVideoElement&&s.readyState<=1)return!1;return r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.alphaMode===oh.UNPACK),this.noSubImage||e.target!==r.TEXTURE_2D||i.width!==n||i.height!==o?(i.width=n,i.height=o,r.texImage2D(e.target,0,i.internalFormat,e.format,i.type,s)):r.texSubImage2D(r.TEXTURE_2D,0,0,0,e.format,i.type,s),!0}update(){if(this.destroyed)return;const t=this.source,e=t.naturalWidth||t.videoWidth||t.width,i=t.naturalHeight||t.videoHeight||t.height;this.resize(e,i),super.update()}dispose(){this.source=null}}class im extends em{constructor(t,e){if(e=e||{},"string"==typeof t){const i=new Image;em.crossOrigin(i,t,e.crossorigin),i.src=t,t=i}super(t),!t.complete&&this._width&&this._height&&(this._width=0,this._height=0),this.url=t.src,this._process=null,this.preserveBitmap=!1,this.createBitmap=(e.createBitmap??ph.CREATE_IMAGE_BITMAP)&&!!globalThis.createImageBitmap,this.alphaMode="number"==typeof e.alphaMode?e.alphaMode:null,this.bitmap=null,this._load=null,!1!==e.autoLoad&&this.load()}load(t){return this._load||(void 0!==t&&(this.createBitmap=t),this._load=new Promise((t,e)=>{const i=this.source;this.url=i.src;const s=()=>{this.destroyed||(i.onload=null,i.onerror=null,this.update(),this._load=null,this.createBitmap?t(this.process()):t(this))};i.complete&&i.src?s():(i.onload=s,i.onerror=t=>{e(t),this.onError.emit(t)})})),this._load}process(){const t=this.source;if(null!==this._process)return this._process;if(null!==this.bitmap||!globalThis.createImageBitmap)return Promise.resolve(this);const e=globalThis.createImageBitmap,i=!t.crossOrigin||"anonymous"===t.crossOrigin;return this._process=fetch(t.src,{mode:i?"cors":"no-cors"}).then(t=>t.blob()).then(i=>e(i,0,0,t.width,t.height,{premultiplyAlpha:null===this.alphaMode||this.alphaMode===oh.UNPACK?"premultiply":"none"})).then(t=>this.destroyed?Promise.reject():(this.bitmap=t,this.update(),this._process=null,Promise.resolve(this))),this._process}upload(t,e,i){if("number"==typeof this.alphaMode&&(e.alphaMode=this.alphaMode),!this.createBitmap)return super.upload(t,e,i);if(!this.bitmap&&(this.process(),!this.bitmap))return!1;if(super.upload(t,e,i,this.bitmap),!this.preserveBitmap){let t=!0;const s=e._glTextures;for(const r in s){const n=s[r];if(n!==i&&n.dirtyId!==e.dirtyId){t=!1;break}}t&&(this.bitmap.close&&this.bitmap.close(),this.bitmap=null)}return!0}dispose(){this.source.onload=null,this.source.onerror=null,super.dispose(),this.bitmap&&(this.bitmap.close(),this.bitmap=null),this._process=null,this._load=null}static test(t){return typeof HTMLImageElement<"u"&&("string"==typeof t||t instanceof HTMLImageElement)}}class sm{constructor(){this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsFloat32=new Float32Array(8)}set(t,e,i){const s=e.width,r=e.height;if(i){const e=t.width/2/s,n=t.height/2/r,o=t.x/s+e,a=t.y/r+n;i=pf.add(i,pf.NW),this.x0=o+e*pf.uX(i),this.y0=a+n*pf.uY(i),i=pf.add(i,2),this.x1=o+e*pf.uX(i),this.y1=a+n*pf.uY(i),i=pf.add(i,2),this.x2=o+e*pf.uX(i),this.y2=a+n*pf.uY(i),i=pf.add(i,2),this.x3=o+e*pf.uX(i),this.y3=a+n*pf.uY(i)}else this.x0=t.x/s,this.y0=t.y/r,this.x1=(t.x+t.width)/s,this.y1=t.y/r,this.x2=(t.x+t.width)/s,this.y2=(t.y+t.height)/r,this.x3=t.x/s,this.y3=(t.y+t.height)/r;this.uvsFloat32[0]=this.x0,this.uvsFloat32[1]=this.y0,this.uvsFloat32[2]=this.x1,this.uvsFloat32[3]=this.y1,this.uvsFloat32[4]=this.x2,this.uvsFloat32[5]=this.y2,this.uvsFloat32[6]=this.x3,this.uvsFloat32[7]=this.y3}}sm.prototype.toString=function(){return`[@pixi/core:TextureUvs x0=${this.x0} y0=${this.y0} x1=${this.x1} y1=${this.y1} x2=${this.x2} y2=${this.y2} x3=${this.x3} y3=${this.y3}]`};const rm=new sm;function nm(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}class om extends kh{constructor(t,e,i,s,r,n,o){if(super(),this.noFrame=!1,e||(this.noFrame=!0,e=new Qp(0,0,1,1)),t instanceof om&&(t=t.baseTexture),this.baseTexture=t,this._frame=e,this.trim=s,this.valid=!1,this.destroyed=!1,this._uvs=rm,this.uvMatrix=null,this.orig=i||e,this._rotate=Number(r||0),!0===r)this._rotate=2;else if(this._rotate%2!=0)throw new Error("attempt to use diamond-shaped UVs. If you are sure, set rotation manually");this.defaultAnchor=n?new Kp(n.x,n.y):new Kp(0,0),this.defaultBorders=o,this._updateID=0,this.textureCacheIds=[],t.valid?this.noFrame?t.valid&&this.onBaseTextureUpdated(t):this.frame=e:t.once("loaded",this.onBaseTextureUpdated,this),this.noFrame&&t.on("update",this.onBaseTextureUpdated,this)}update(){this.baseTexture.resource&&this.baseTexture.resource.update()}onBaseTextureUpdated(t){if(this.noFrame){if(!this.baseTexture.valid)return;this._frame.width=t.width,this._frame.height=t.height,this.valid=!0,this.updateUvs()}else this.frame=this._frame;this.emit("update",this)}destroy(t){if(this.baseTexture){if(t){const{resource:t}=this.baseTexture;t?.url&&up[t.url]&&om.removeFromCache(t.url),this.baseTexture.destroy()}this.baseTexture.off("loaded",this.onBaseTextureUpdated,this),this.baseTexture.off("update",this.onBaseTextureUpdated,this),this.baseTexture=null}this._frame=null,this._uvs=null,this.trim=null,this.orig=null,this.valid=!1,om.removeFromCache(this),this.textureCacheIds=null,this.destroyed=!0,this.emit("destroyed",this),this.removeAllListeners()}clone(){const t=this._frame.clone(),e=this._frame===this.orig?t:this.orig.clone(),i=new om(this.baseTexture,!this.noFrame&&t,e,this.trim?.clone(),this.rotate,this.defaultAnchor,this.defaultBorders);return this.noFrame&&(i._frame=t),i}updateUvs(){this._uvs===rm&&(this._uvs=new sm),this._uvs.set(this._frame,this.baseTexture,this.rotate),this._updateID++}static from(t,e={},i=ph.STRICT_TEXTURE_CACHE){const s="string"==typeof t;let r=null;if(s)r=t;else if(t instanceof Bp){if(!t.cacheId){const i=e?.pixiIdPrefix||"pixiid";t.cacheId=`${i}-${op()}`,Bp.addToCache(t,t.cacheId)}r=t.cacheId}else{if(!t._pixiId){const i=e?.pixiIdPrefix||"pixiid";t._pixiId=`${i}_${op()}`}r=t._pixiId}let n=up[r];if(s&&i&&!n)throw new Error(`The cacheId "${r}" does not exist in TextureCache.`);return n||t instanceof Bp?!n&&t instanceof Bp&&(n=new om(t),om.addToCache(n,r)):(e.resolution||(e.resolution=xp(t)),n=new om(new Bp(t,e)),n.baseTexture.cacheId=r,Bp.addToCache(n.baseTexture,r),om.addToCache(n,r)),n}static fromURL(t,e){const i=Object.assign({autoLoad:!1},e?.resourceOptions),s=om.from(t,Object.assign({resourceOptions:i},e),!1),r=s.baseTexture.resource;return s.baseTexture.valid?Promise.resolve(s):r.load().then(()=>Promise.resolve(s))}static fromBuffer(t,e,i,s){return new om(Bp.fromBuffer(t,e,i,s))}static fromLoader(t,e,i,s){const r=new Bp(t,Object.assign({scaleMode:Bp.defaultOptions.scaleMode,resolution:xp(e)},s)),{resource:n}=r;n instanceof im&&(n.url=e);const o=new om(r);return i||(i=e),Bp.addToCache(o.baseTexture,i),om.addToCache(o,i),i!==e&&(Bp.addToCache(o.baseTexture,e),om.addToCache(o,e)),o.baseTexture.valid?Promise.resolve(o):new Promise(t=>{o.baseTexture.once("loaded",()=>t(o))})}static addToCache(t,e){e&&(t.textureCacheIds.includes(e)||t.textureCacheIds.push(e),up[e]&&up[e]!==t&&console.warn(`Texture added to the cache with an id [${e}] that already had an entry`),up[e]=t)}static removeFromCache(t){if("string"==typeof t){const e=up[t];if(e){const i=e.textureCacheIds.indexOf(t);return i>-1&&e.textureCacheIds.splice(i,1),delete up[t],e}}else if(t?.textureCacheIds){for(let e=0;e<t.textureCacheIds.length;++e)up[t.textureCacheIds[e]]===t&&delete up[t.textureCacheIds[e]];return t.textureCacheIds.length=0,t}return null}get resolution(){return this.baseTexture.resolution}get frame(){return this._frame}set frame(t){this._frame=t,this.noFrame=!1;const{x:e,y:i,width:s,height:r}=t,n=e+s>this.baseTexture.width,o=i+r>this.baseTexture.height;if(n||o){const t=n&&o?"and":"or",a=`X: ${e} + ${s} = ${e+s} > ${this.baseTexture.width}`,l=`Y: ${i} + ${r} = ${i+r} > ${this.baseTexture.height}`;throw new Error(`Texture Error: frame does not fit inside the base Texture dimensions: ${a} ${t} ${l}`)}this.valid=s&&r&&this.baseTexture.valid,!this.trim&&!this.rotate&&(this.orig=t),this.valid&&this.updateUvs()}get rotate(){return this._rotate}set rotate(t){this._rotate=t,this.valid&&this.updateUvs()}get width(){return this.orig.width}get height(){return this.orig.height}castToBaseTexture(){return this.baseTexture}static get EMPTY(){return om._EMPTY||(om._EMPTY=new om(new Bp),nm(om._EMPTY),nm(om._EMPTY.baseTexture)),om._EMPTY}static get WHITE(){if(!om._WHITE){const t=ph.ADAPTER.createCanvas(16,16),e=t.getContext("2d");t.width=16,t.height=16,e.fillStyle="white",e.fillRect(0,0,16,16),om._WHITE=new om(Bp.from(t)),nm(om._WHITE),nm(om._WHITE.baseTexture)}return om._WHITE}}class am extends om{constructor(t,e){super(t,e),this.valid=!0,this.filterFrame=null,this.filterPoolKey=null,this.updateUvs()}get framebuffer(){return this.baseTexture.framebuffer}get multisample(){return this.framebuffer.multisample}set multisample(t){this.framebuffer.multisample=t}resize(t,e,i=!0){const s=this.baseTexture.resolution,r=Math.round(t*s)/s,n=Math.round(e*s)/s;this.valid=r>0&&n>0,this._frame.width=this.orig.width=r,this._frame.height=this.orig.height=n,i&&this.baseTexture.resize(r,n),this.updateUvs()}setResolution(t){const{baseTexture:e}=this;e.resolution!==t&&(e.setResolution(t),this.resize(e.width,e.height,!1))}static create(t){return new am(new tm(t))}}class lm{constructor(t){this.texturePool={},this.textureOptions=t||{},this.enableFullScreen=!1,this._pixelsWidth=0,this._pixelsHeight=0}createTexture(t,e,i=ch.NONE){const s=new tm(Object.assign({width:t,height:e,resolution:1,multisample:i},this.textureOptions));return new am(s)}getOptimalTexture(t,e,i=1,s=ch.NONE){let r;t=Math.max(Math.ceil(t*i-1e-6),1),e=Math.max(Math.ceil(e*i-1e-6),1),this.enableFullScreen&&t===this._pixelsWidth&&e===this._pixelsHeight?r=s>1?-s:-1:(r=((65535&(t=tp(t)))<<16|65535&(e=tp(e)))>>>0,s>1&&(r+=4294967296*s)),this.texturePool[r]||(this.texturePool[r]=[]);let n=this.texturePool[r].pop();return n||(n=this.createTexture(t,e,s)),n.filterPoolKey=r,n.setResolution(i),n}getFilterTexture(t,e,i){const s=this.getOptimalTexture(t.width,t.height,e||t.resolution,i||ch.NONE);return s.filterFrame=t.filterFrame,s}returnTexture(t){const e=t.filterPoolKey;t.filterFrame=null,this.texturePool[e].push(t)}returnFilterTexture(t){this.returnTexture(t)}clear(t){if(t=!1!==t)for(const e in this.texturePool){const t=this.texturePool[e];if(t)for(let e=0;e<t.length;e++)t[e].destroy(!0)}this.texturePool={}}setScreenSize(t){if(t.width!==this._pixelsWidth||t.height!==this._pixelsHeight){this.enableFullScreen=t.width>0&&t.height>0;for(const t in this.texturePool){if(!(Number(t)<0))continue;const e=this.texturePool[t];if(e)for(let t=0;t<e.length;t++)e[t].destroy(!0);this.texturePool[t]=[]}this._pixelsWidth=t.width,this._pixelsHeight=t.height}}}lm.SCREEN_KEY=-1;class hm extends $p{constructor(){super(),this.addAttribute("aVertexPosition",new Float32Array([0,0,1,0,1,1,0,1])).addIndex([0,1,3,2])}}class um extends $p{constructor(){super(),this.vertices=new Float32Array([-1,-1,1,-1,1,1,-1,1]),this.uvs=new Float32Array([0,0,1,0,1,1,0,1]),this.vertexBuffer=new Up(this.vertices),this.uvBuffer=new Up(this.uvs),this.addAttribute("aVertexPosition",this.vertexBuffer).addAttribute("aTextureCoord",this.uvBuffer).addIndex([0,1,2,0,2,3])}map(t,e){let i=0,s=0;return this.uvs[0]=i,this.uvs[1]=s,this.uvs[2]=i+e.width/t.width,this.uvs[3]=s,this.uvs[4]=i+e.width/t.width,this.uvs[5]=s+e.height/t.height,this.uvs[6]=i,this.uvs[7]=s+e.height/t.height,i=e.x,s=e.y,this.vertices[0]=i,this.vertices[1]=s,this.vertices[2]=i+e.width,this.vertices[3]=s,this.vertices[4]=i+e.width,this.vertices[5]=s+e.height,this.vertices[6]=i,this.vertices[7]=s+e.height,this.invalidate(),this}invalidate(){return this.vertexBuffer._updateID++,this.uvBuffer._updateID++,this}}class cm{constructor(){this.renderTexture=null,this.target=null,this.legacy=!1,this.resolution=1,this.multisample=ch.NONE,this.sourceFrame=new Qp,this.destinationFrame=new Qp,this.bindingSourceFrame=new Qp,this.bindingDestinationFrame=new Qp,this.filters=[],this.transform=null}clear(){this.target=null,this.filters=null,this.renderTexture=null}}const dm=[new Kp,new Kp,new Kp,new Kp],pm=new nf;class fm{constructor(t){this.renderer=t,this.defaultFilterStack=[{}],this.texturePool=new lm,this.statePool=[],this.quad=new hm,this.quadUv=new um,this.tempRect=new Qp,this.activeState={},this.globalUniforms=new Gf({outputFrame:new Qp,inputSize:new Float32Array(4),inputPixel:new Float32Array(4),inputClamp:new Float32Array(4),resolution:1,filterArea:new Float32Array(4),filterClamp:new Float32Array(4)},!0),this.forceClear=!1,this.useMaxPadding=!1}init(){this.texturePool.setScreenSize(this.renderer.view)}push(t,e){const i=this.renderer,s=this.defaultFilterStack,r=this.statePool.pop()||new cm,n=i.renderTexture;let o,a;if(n.current){const t=n.current;o=t.resolution,a=t.multisample}else o=i.resolution,a=i.multisample;let l=e[0].resolution||o,h=e[0].multisample??a,u=e[0].padding,c=e[0].autoFit,d=e[0].legacy??!0;for(let m=1;m<e.length;m++){const t=e[m];l=Math.min(l,t.resolution||o),h=Math.min(h,t.multisample??a),u=this.useMaxPadding?Math.max(u,t.padding):u+t.padding,c=c&&t.autoFit,d=d||(t.legacy??!0)}1===s.length&&(this.defaultFilterStack[0].renderTexture=n.current),s.push(r),r.resolution=l,r.multisample=h,r.legacy=d,r.target=t,r.sourceFrame.copyFrom(t.filterArea||t.getBounds(!0)),r.sourceFrame.pad(u);const p=this.tempRect.copyFrom(n.sourceFrame);i.projection.transform&&this.transformAABB(pm.copyFrom(i.projection.transform).invert(),p),c?(r.sourceFrame.fit(p),(r.sourceFrame.width<=0||r.sourceFrame.height<=0)&&(r.sourceFrame.width=0,r.sourceFrame.height=0)):r.sourceFrame.intersects(p)||(r.sourceFrame.width=0,r.sourceFrame.height=0),this.roundFrame(r.sourceFrame,n.current?n.current.resolution:i.resolution,n.sourceFrame,n.destinationFrame,i.projection.transform),r.renderTexture=this.getOptimalFilterTexture(r.sourceFrame.width,r.sourceFrame.height,l,h),r.filters=e,r.destinationFrame.width=r.renderTexture.width,r.destinationFrame.height=r.renderTexture.height;const f=this.tempRect;f.x=0,f.y=0,f.width=r.sourceFrame.width,f.height=r.sourceFrame.height,r.renderTexture.filterFrame=r.sourceFrame,r.bindingSourceFrame.copyFrom(n.sourceFrame),r.bindingDestinationFrame.copyFrom(n.destinationFrame),r.transform=i.projection.transform,i.projection.transform=null,n.bind(r.renderTexture,r.sourceFrame,f),i.framebuffer.clear(0,0,0,0)}pop(){const t=this.defaultFilterStack,e=t.pop(),i=e.filters;this.activeState=e;const s=this.globalUniforms.uniforms;s.outputFrame=e.sourceFrame,s.resolution=e.resolution;const r=s.inputSize,n=s.inputPixel,o=s.inputClamp;if(r[0]=e.destinationFrame.width,r[1]=e.destinationFrame.height,r[2]=1/r[0],r[3]=1/r[1],n[0]=Math.round(r[0]*e.resolution),n[1]=Math.round(r[1]*e.resolution),n[2]=1/n[0],n[3]=1/n[1],o[0]=.5*n[2],o[1]=.5*n[3],o[2]=e.sourceFrame.width*r[2]-.5*n[2],o[3]=e.sourceFrame.height*r[3]-.5*n[3],e.legacy){const t=s.filterArea;t[0]=e.destinationFrame.width,t[1]=e.destinationFrame.height,t[2]=e.sourceFrame.x,t[3]=e.sourceFrame.y,s.filterClamp=s.inputClamp}this.globalUniforms.update();const a=t[t.length-1];if(this.renderer.framebuffer.blit(),1===i.length)i[0].apply(this,e.renderTexture,a.renderTexture,ah.BLEND,e),this.returnFilterTexture(e.renderTexture);else{let t=e.renderTexture,s=this.getOptimalFilterTexture(t.width,t.height,e.resolution);s.filterFrame=t.filterFrame;let r=0;for(r=0;r<i.length-1;++r){1===r&&e.multisample>1&&(s=this.getOptimalFilterTexture(t.width,t.height,e.resolution),s.filterFrame=t.filterFrame),i[r].apply(this,t,s,ah.CLEAR,e);const n=t;t=s,s=n}i[r].apply(this,t,a.renderTexture,ah.BLEND,e),r>1&&e.multisample>1&&this.returnFilterTexture(e.renderTexture),this.returnFilterTexture(t),this.returnFilterTexture(s)}e.clear(),this.statePool.push(e)}bindAndClear(t,e=ah.CLEAR){const{renderTexture:i,state:s}=this.renderer;if(t===this.defaultFilterStack[this.defaultFilterStack.length-1].renderTexture?this.renderer.projection.transform=this.activeState.transform:this.renderer.projection.transform=null,t?.filterFrame){const e=this.tempRect;e.x=0,e.y=0,e.width=t.filterFrame.width,e.height=t.filterFrame.height,i.bind(t,t.filterFrame,e)}else t!==this.defaultFilterStack[this.defaultFilterStack.length-1].renderTexture?i.bind(t):this.renderer.renderTexture.bind(t,this.activeState.bindingSourceFrame,this.activeState.bindingDestinationFrame);const r=1&s.stateId||this.forceClear;(e===ah.CLEAR||e===ah.BLIT&&r)&&this.renderer.framebuffer.clear(0,0,0,0)}applyFilter(t,e,i,s){const r=this.renderer;r.state.set(t.state),this.bindAndClear(i,s),t.uniforms.uSampler=e,t.uniforms.filterGlobals=this.globalUniforms,r.shader.bind(t),t.legacy=!!t.program.attributeData.aTextureCoord,t.legacy?(this.quadUv.map(e._frame,e.filterFrame),r.geometry.bind(this.quadUv),r.geometry.draw(Zl.TRIANGLES)):(r.geometry.bind(this.quad),r.geometry.draw(Zl.TRIANGLE_STRIP))}calculateSpriteMatrix(t,e){const{sourceFrame:i,destinationFrame:s}=this.activeState,{orig:r}=e._texture,n=t.set(s.width,0,0,s.height,i.x,i.y),o=e.worldTransform.copyTo(nf.TEMP_MATRIX);return o.invert(),n.prepend(o),n.scale(1/r.width,1/r.height),n.translate(e.anchor.x,e.anchor.y),n}destroy(){this.renderer=null,this.texturePool.clear(!1)}getOptimalFilterTexture(t,e,i=1,s=ch.NONE){return this.texturePool.getOptimalTexture(t,e,i,s)}getFilterTexture(t,e,i){if("number"==typeof t){const i=t;t=e,e=i}t=t||this.activeState.renderTexture;const s=this.texturePool.getOptimalTexture(t.width,t.height,e||t.resolution,i||ch.NONE);return s.filterFrame=t.filterFrame,s}returnFilterTexture(t){this.texturePool.returnTexture(t)}emptyPool(){this.texturePool.clear(!0)}resize(){this.texturePool.setScreenSize(this.renderer.view)}transformAABB(t,e){const i=dm[0],s=dm[1],r=dm[2],n=dm[3];i.set(e.left,e.top),s.set(e.left,e.bottom),r.set(e.right,e.top),n.set(e.right,e.bottom),t.apply(i,i),t.apply(s,s),t.apply(r,r),t.apply(n,n);const o=Math.min(i.x,s.x,r.x,n.x),a=Math.min(i.y,s.y,r.y,n.y),l=Math.max(i.x,s.x,r.x,n.x),h=Math.max(i.y,s.y,r.y,n.y);e.x=o,e.y=a,e.width=l-o,e.height=h-a}roundFrame(t,e,i,s,r){if(!(t.width<=0||t.height<=0||i.width<=0||i.height<=0)){if(r){const{a:t,b:e,c:i,d:s}=r;if((Math.abs(e)>1e-4||Math.abs(i)>1e-4)&&(Math.abs(t)>1e-4||Math.abs(s)>1e-4))return}(r=r?pm.copyFrom(r):pm.identity()).translate(-i.x,-i.y).scale(s.width/i.width,s.height/i.height).translate(s.x,s.y),this.transformAABB(r,t),t.ceil(e),this.transformAABB(r.invert(),t)}}}fm.extension={type:_p.RendererSystem,name:"filter"},Ep.add(fm);class mm{constructor(t){this.framebuffer=t,this.stencil=null,this.dirtyId=-1,this.dirtyFormat=-1,this.dirtySize=-1,this.multisample=ch.NONE,this.msaaBuffer=null,this.blitFramebuffer=null,this.mipLevel=0}}const gm=new Qp;class ym{constructor(t){this.renderer=t,this.managedFramebuffers=[],this.unknownFramebuffer=new Qf(10,10),this.msaaSamples=null}contextChange(){this.disposeAll(!0);const t=this.gl=this.renderer.gl;if(this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.current=this.unknownFramebuffer,this.viewport=new Qp,this.hasMRT=!0,this.writeDepthTexture=!0,1===this.renderer.context.webGLVersion){let e=this.renderer.context.extensions.drawBuffers,i=this.renderer.context.extensions.depthTexture;ph.PREFER_ENV===Vl.WEBGL_LEGACY&&(e=null,i=null),e?t.drawBuffers=t=>e.drawBuffersWEBGL(t):(this.hasMRT=!1,t.drawBuffers=()=>{}),i||(this.writeDepthTexture=!1)}else this.msaaSamples=t.getInternalformatParameter(t.RENDERBUFFER,t.RGBA8,t.SAMPLES)}bind(t,e,i=0){const{gl:s}=this;if(t){const r=t.glFramebuffers[this.CONTEXT_UID]||this.initFramebuffer(t);this.current!==t&&(this.current=t,s.bindFramebuffer(s.FRAMEBUFFER,r.framebuffer)),r.mipLevel!==i&&(t.dirtyId++,t.dirtyFormat++,r.mipLevel=i),r.dirtyId!==t.dirtyId&&(r.dirtyId=t.dirtyId,r.dirtyFormat!==t.dirtyFormat?(r.dirtyFormat=t.dirtyFormat,r.dirtySize=t.dirtySize,this.updateFramebuffer(t,i)):r.dirtySize!==t.dirtySize&&(r.dirtySize=t.dirtySize,this.resizeFramebuffer(t)));for(let e=0;e<t.colorTextures.length;e++){const i=t.colorTextures[e];this.renderer.texture.unbind(i.parentTextureArray||i)}if(t.depthTexture&&this.renderer.texture.unbind(t.depthTexture),e){const t=e.width>>i,s=e.height>>i,r=t/e.width;this.setViewport(e.x*r,e.y*r,t,s)}else{const e=t.width>>i,s=t.height>>i;this.setViewport(0,0,e,s)}}else this.current&&(this.current=null,s.bindFramebuffer(s.FRAMEBUFFER,null)),e?this.setViewport(e.x,e.y,e.width,e.height):this.setViewport(0,0,this.renderer.width,this.renderer.height)}setViewport(t,e,i,s){const r=this.viewport;t=Math.round(t),e=Math.round(e),i=Math.round(i),s=Math.round(s),(r.width!==i||r.height!==s||r.x!==t||r.y!==e)&&(r.x=t,r.y=e,r.width=i,r.height=s,this.gl.viewport(t,e,i,s))}get size(){return this.current?{x:0,y:0,width:this.current.width,height:this.current.height}:{x:0,y:0,width:this.renderer.width,height:this.renderer.height}}clear(t,e,i,s,r=Jl.COLOR|Jl.DEPTH){const{gl:n}=this;n.clearColor(t,e,i,s),n.clear(r)}initFramebuffer(t){const{gl:e}=this,i=new mm(e.createFramebuffer());return i.multisample=this.detectSamples(t.multisample),t.glFramebuffers[this.CONTEXT_UID]=i,this.managedFramebuffers.push(t),t.disposeRunner.add(this),i}resizeFramebuffer(t){const{gl:e}=this,i=t.glFramebuffers[this.CONTEXT_UID];if(i.stencil){let s;e.bindRenderbuffer(e.RENDERBUFFER,i.stencil),s=1===this.renderer.context.webGLVersion?e.DEPTH_STENCIL:t.depth&&t.stencil?e.DEPTH24_STENCIL8:t.depth?e.DEPTH_COMPONENT24:e.STENCIL_INDEX8,i.msaaBuffer?e.renderbufferStorageMultisample(e.RENDERBUFFER,i.multisample,s,t.width,t.height):e.renderbufferStorage(e.RENDERBUFFER,s,t.width,t.height)}const s=t.colorTextures;let r=s.length;e.drawBuffers||(r=Math.min(r,1));for(let n=0;n<r;n++){const r=s[n],o=r.parentTextureArray||r;this.renderer.texture.bind(o,0),0===n&&i.msaaBuffer&&(e.bindRenderbuffer(e.RENDERBUFFER,i.msaaBuffer),e.renderbufferStorageMultisample(e.RENDERBUFFER,i.multisample,o._glTextures[this.CONTEXT_UID].internalFormat,t.width,t.height))}t.depthTexture&&this.writeDepthTexture&&this.renderer.texture.bind(t.depthTexture,0)}updateFramebuffer(t,e){const{gl:i}=this,s=t.glFramebuffers[this.CONTEXT_UID],r=t.colorTextures;let n=r.length;i.drawBuffers||(n=Math.min(n,1)),s.multisample>1&&this.canMultisampleFramebuffer(t)?s.msaaBuffer=s.msaaBuffer||i.createRenderbuffer():s.msaaBuffer&&(i.deleteRenderbuffer(s.msaaBuffer),s.msaaBuffer=null,s.blitFramebuffer&&(s.blitFramebuffer.dispose(),s.blitFramebuffer=null));const o=[];for(let a=0;a<n;a++){const n=r[a],l=n.parentTextureArray||n;this.renderer.texture.bind(l,0),0===a&&s.msaaBuffer?(i.bindRenderbuffer(i.RENDERBUFFER,s.msaaBuffer),i.renderbufferStorageMultisample(i.RENDERBUFFER,s.multisample,l._glTextures[this.CONTEXT_UID].internalFormat,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,s.msaaBuffer)):(i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+a,n.target,l._glTextures[this.CONTEXT_UID].texture,e),o.push(i.COLOR_ATTACHMENT0+a))}if(o.length>1&&i.drawBuffers(o),t.depthTexture&&this.writeDepthTexture){const s=t.depthTexture;this.renderer.texture.bind(s,0),i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,s._glTextures[this.CONTEXT_UID].texture,e)}if(!t.stencil&&!t.depth||t.depthTexture&&this.writeDepthTexture)s.stencil&&(i.deleteRenderbuffer(s.stencil),s.stencil=null);else{let e,r;s.stencil=s.stencil||i.createRenderbuffer(),1===this.renderer.context.webGLVersion?(e=i.DEPTH_STENCIL_ATTACHMENT,r=i.DEPTH_STENCIL):t.depth&&t.stencil?(e=i.DEPTH_STENCIL_ATTACHMENT,r=i.DEPTH24_STENCIL8):t.depth?(e=i.DEPTH_ATTACHMENT,r=i.DEPTH_COMPONENT24):(e=i.STENCIL_ATTACHMENT,r=i.STENCIL_INDEX8),i.bindRenderbuffer(i.RENDERBUFFER,s.stencil),s.msaaBuffer?i.renderbufferStorageMultisample(i.RENDERBUFFER,s.multisample,r,t.width,t.height):i.renderbufferStorage(i.RENDERBUFFER,r,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,e,i.RENDERBUFFER,s.stencil)}}canMultisampleFramebuffer(t){return 1!==this.renderer.context.webGLVersion&&t.colorTextures.length<=1&&!t.depthTexture}detectSamples(t){const{msaaSamples:e}=this;let i=ch.NONE;if(t<=1||null===e)return i;for(let s=0;s<e.length;s++)if(e[s]<=t){i=e[s];break}return 1===i&&(i=ch.NONE),i}blit(t,e,i){const{current:s,renderer:r,gl:n,CONTEXT_UID:o}=this;if(2!==r.context.webGLVersion||!s)return;const a=s.glFramebuffers[o];if(!a)return;if(!t){if(!a.msaaBuffer)return;const e=s.colorTextures[0];if(!e)return;a.blitFramebuffer||(a.blitFramebuffer=new Qf(s.width,s.height),a.blitFramebuffer.addColorTexture(0,e)),(t=a.blitFramebuffer).colorTextures[0]!==e&&(t.colorTextures[0]=e,t.dirtyId++,t.dirtyFormat++),(t.width!==s.width||t.height!==s.height)&&(t.width=s.width,t.height=s.height,t.dirtyId++,t.dirtySize++)}e||((e=gm).width=s.width,e.height=s.height),i||(i=e);const l=e.width===i.width&&e.height===i.height;this.bind(t),n.bindFramebuffer(n.READ_FRAMEBUFFER,a.framebuffer),n.blitFramebuffer(e.left,e.top,e.right,e.bottom,i.left,i.top,i.right,i.bottom,n.COLOR_BUFFER_BIT,l?n.NEAREST:n.LINEAR),n.bindFramebuffer(n.READ_FRAMEBUFFER,t.glFramebuffers[this.CONTEXT_UID].framebuffer)}disposeFramebuffer(t,e){const i=t.glFramebuffers[this.CONTEXT_UID],s=this.gl;if(!i)return;delete t.glFramebuffers[this.CONTEXT_UID];const r=this.managedFramebuffers.indexOf(t);r>=0&&this.managedFramebuffers.splice(r,1),t.disposeRunner.remove(this),e||(s.deleteFramebuffer(i.framebuffer),i.msaaBuffer&&s.deleteRenderbuffer(i.msaaBuffer),i.stencil&&s.deleteRenderbuffer(i.stencil)),i.blitFramebuffer&&this.disposeFramebuffer(i.blitFramebuffer,e)}disposeAll(t){const e=this.managedFramebuffers;this.managedFramebuffers=[];for(let i=0;i<e.length;i++)this.disposeFramebuffer(e[i],t)}forceStencil(){const t=this.current;if(!t)return;const e=t.glFramebuffers[this.CONTEXT_UID];if(!e||e.stencil&&t.stencil)return;t.stencil=!0;const i=t.width,s=t.height,r=this.gl,n=e.stencil=r.createRenderbuffer();let o,a;r.bindRenderbuffer(r.RENDERBUFFER,n),1===this.renderer.context.webGLVersion?(o=r.DEPTH_STENCIL_ATTACHMENT,a=r.DEPTH_STENCIL):t.depth?(o=r.DEPTH_STENCIL_ATTACHMENT,a=r.DEPTH24_STENCIL8):(o=r.STENCIL_ATTACHMENT,a=r.STENCIL_INDEX8),e.msaaBuffer?r.renderbufferStorageMultisample(r.RENDERBUFFER,e.multisample,a,i,s):r.renderbufferStorage(r.RENDERBUFFER,a,i,s),r.framebufferRenderbuffer(r.FRAMEBUFFER,o,r.RENDERBUFFER,n)}reset(){this.current=this.unknownFramebuffer,this.viewport=new Qp}destroy(){this.renderer=null}}ym.extension={type:_p.RendererSystem,name:"framebuffer"},Ep.add(ym);const vm={5126:4,5123:2,5121:1};class xm{constructor(t){this.renderer=t,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this.canUseUInt32ElementIndex=!1,this.managedGeometries={}}contextChange(){this.disposeAll(!0);const t=this.gl=this.renderer.gl,e=this.renderer.context;if(this.CONTEXT_UID=this.renderer.CONTEXT_UID,2!==e.webGLVersion){let e=this.renderer.context.extensions.vertexArrayObject;ph.PREFER_ENV===Vl.WEBGL_LEGACY&&(e=null),e?(t.createVertexArray=()=>e.createVertexArrayOES(),t.bindVertexArray=t=>e.bindVertexArrayOES(t),t.deleteVertexArray=t=>e.deleteVertexArrayOES(t)):(this.hasVao=!1,t.createVertexArray=()=>null,t.bindVertexArray=()=>null,t.deleteVertexArray=()=>null)}if(2!==e.webGLVersion){const e=t.getExtension("ANGLE_instanced_arrays");e?(t.vertexAttribDivisor=(t,i)=>e.vertexAttribDivisorANGLE(t,i),t.drawElementsInstanced=(t,i,s,r,n)=>e.drawElementsInstancedANGLE(t,i,s,r,n),t.drawArraysInstanced=(t,i,s,r)=>e.drawArraysInstancedANGLE(t,i,s,r)):this.hasInstance=!1}this.canUseUInt32ElementIndex=2===e.webGLVersion||!!e.extensions.uint32ElementIndex}bind(t,e){e=e||this.renderer.shader.shader;const{gl:i}=this;let s=t.glVertexArrayObjects[this.CONTEXT_UID],r=!1;s||(this.managedGeometries[t.id]=t,t.disposeRunner.add(this),t.glVertexArrayObjects[this.CONTEXT_UID]=s={},r=!0);const n=s[e.program.id]||this.initGeometryVao(t,e,r);this._activeGeometry=t,this._activeVao!==n&&(this._activeVao=n,this.hasVao?i.bindVertexArray(n):this.activateVao(t,e.program)),this.updateBuffers()}reset(){this.unbind()}updateBuffers(){const t=this._activeGeometry,e=this.renderer.buffer;for(let i=0;i<t.buffers.length;i++){const s=t.buffers[i];e.update(s)}}checkCompatibility(t,e){const i=t.attributes,s=e.attributeData;for(const r in s)if(!i[r])throw new Error(`shader and geometry incompatible, geometry missing the "${r}" attribute`)}getSignature(t,e){const i=t.attributes,s=e.attributeData,r=["g",t.id];for(const n in i)s[n]&&r.push(n,s[n].location);return r.join("-")}initGeometryVao(t,e,i=!0){const s=this.gl,r=this.CONTEXT_UID,n=this.renderer.buffer,o=e.program;o.glPrograms[r]||this.renderer.shader.generateProgram(e),this.checkCompatibility(t,o);const a=this.getSignature(t,o),l=t.glVertexArrayObjects[this.CONTEXT_UID];let h=l[a];if(h)return l[o.id]=h,h;const u=t.buffers,c=t.attributes,d={},p={};for(const f in u)d[f]=0,p[f]=0;for(const f in c)!c[f].size&&o.attributeData[f]?c[f].size=o.attributeData[f].size:c[f].size||console.warn(`PIXI Geometry attribute '${f}' size cannot be determined (likely the bound shader does not have the attribute)`),d[c[f].buffer]+=c[f].size*vm[c[f].type];for(const f in c){const t=c[f],e=t.size;void 0===t.stride&&(d[t.buffer]===e*vm[t.type]?t.stride=0:t.stride=d[t.buffer]),void 0===t.start&&(t.start=p[t.buffer],p[t.buffer]+=e*vm[t.type])}h=s.createVertexArray(),s.bindVertexArray(h);for(let f=0;f<u.length;f++){const t=u[f];n.bind(t),i&&t._glBuffers[r].refCount++}return this.activateVao(t,o),l[o.id]=h,l[a]=h,s.bindVertexArray(null),n.unbind(dh.ARRAY_BUFFER),h}disposeGeometry(t,e){if(!this.managedGeometries[t.id])return;delete this.managedGeometries[t.id];const i=t.glVertexArrayObjects[this.CONTEXT_UID],s=this.gl,r=t.buffers,n=this.renderer?.buffer;if(t.disposeRunner.remove(this),i){if(n)for(let t=0;t<r.length;t++){const i=r[t]._glBuffers[this.CONTEXT_UID];i&&(i.refCount--,0===i.refCount&&!e&&n.dispose(r[t],e))}if(!e)for(const t in i)if("g"===t[0]){const e=i[t];this._activeVao===e&&this.unbind(),s.deleteVertexArray(e)}delete t.glVertexArrayObjects[this.CONTEXT_UID]}}disposeAll(t){const e=Object.keys(this.managedGeometries);for(let i=0;i<e.length;i++)this.disposeGeometry(this.managedGeometries[e[i]],t)}activateVao(t,e){const i=this.gl,s=this.CONTEXT_UID,r=this.renderer.buffer,n=t.buffers,o=t.attributes;t.indexBuffer&&r.bind(t.indexBuffer);let a=null;for(const l in o){const t=o[l],h=n[t.buffer],u=h._glBuffers[s];if(e.attributeData[l]){a!==u&&(r.bind(h),a=u);const s=e.attributeData[l].location;if(i.enableVertexAttribArray(s),i.vertexAttribPointer(s,t.size,t.type||i.FLOAT,t.normalized,t.stride,t.start),t.instance){if(!this.hasInstance)throw new Error("geometry error, GPU Instancing is not supported on this device");i.vertexAttribDivisor(s,t.divisor)}}}}draw(t,e,i,s){const{gl:r}=this,n=this._activeGeometry;if(n.indexBuffer){const o=n.indexBuffer.data.BYTES_PER_ELEMENT,a=2===o?r.UNSIGNED_SHORT:r.UNSIGNED_INT;2===o||4===o&&this.canUseUInt32ElementIndex?n.instanced?r.drawElementsInstanced(t,e||n.indexBuffer.data.length,a,(i||0)*o,s||1):r.drawElements(t,e||n.indexBuffer.data.length,a,(i||0)*o):console.warn("unsupported index buffer type: uint32")}else n.instanced?r.drawArraysInstanced(t,i,e||n.getSize(),s||1):r.drawArrays(t,i,e||n.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this.renderer=null}}xm.extension={type:_p.RendererSystem,name:"geometry"},Ep.add(xm);const bm=new nf;class _m{constructor(t,e){this._texture=t,this.mapCoord=new nf,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,this.clampMargin=typeof e>"u"?.5:e,this.isSimple=!1}get texture(){return this._texture}set texture(t){this._texture=t,this._textureID=-1}multiplyUvs(t,e){void 0===e&&(e=t);const i=this.mapCoord;for(let s=0;s<t.length;s+=2){const r=t[s],n=t[s+1];e[s]=r*i.a+n*i.c+i.tx,e[s+1]=r*i.b+n*i.d+i.ty}return e}update(t){const e=this._texture;if(!e||!e.valid||!t&&this._textureID===e._updateID)return!1;this._textureID=e._updateID,this._updateID++;const i=e._uvs;this.mapCoord.set(i.x1-i.x0,i.y1-i.y0,i.x3-i.x0,i.y3-i.y0,i.x0,i.y0);const s=e.orig,r=e.trim;r&&(bm.set(s.width/r.width,0,0,s.height/r.height,-r.x/r.width,-r.y/r.height),this.mapCoord.append(bm));const n=e.baseTexture,o=this.uClampFrame,a=this.clampMargin/n.resolution,l=this.clampOffset;return o[0]=(e._frame.x+a+l)/n.width,o[1]=(e._frame.y+a+l)/n.height,o[2]=(e._frame.x+e._frame.width-a+l)/n.width,o[3]=(e._frame.y+e._frame.height-a+l)/n.height,this.uClampOffset[0]=l/n.realWidth,this.uClampOffset[1]=l/n.realHeight,this.isSimple=e._frame.width===n.width&&e._frame.height===n.height&&0===e.rotate,!0}}class wm extends Vf{constructor(t,e,i){let s=null;"string"!=typeof t&&void 0===e&&void 0===i&&(s=t,t=void 0,e=void 0,i=void 0),super(t||"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n",e||"varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n",i),this.maskSprite=s,this.maskMatrix=new nf}get maskSprite(){return this._maskSprite}set maskSprite(t){this._maskSprite=t,this._maskSprite&&(this._maskSprite.renderable=!1)}apply(t,e,i,s){const r=this._maskSprite,n=r._texture;n.valid&&(n.uvMatrix||(n.uvMatrix=new _m(n,0)),n.uvMatrix.update(),this.uniforms.npmAlpha=n.baseTexture.alphaMode?0:1,this.uniforms.mask=n,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,r).prepend(n.uvMatrix.mapCoord),this.uniforms.alpha=r.worldAlpha,this.uniforms.maskClamp=n.uvMatrix.uClampFrame,t.applyFilter(this,e,i,s))}}class Pm{constructor(t=null){this.type=uh.NONE,this.autoDetect=!0,this.maskObject=t||null,this.pooled=!1,this.isMaskData=!0,this.resolution=null,this.multisample=Vf.defaultMultisample,this.enabled=!0,this.colorMask=15,this._filters=null,this._stencilCounter=0,this._scissorCounter=0,this._scissorRect=null,this._scissorRectLocal=null,this._colorMask=15,this._target=null}get filter(){return this._filters?this._filters[0]:null}set filter(t){t?this._filters?this._filters[0]=t:this._filters=[t]:this._filters=null}reset(){this.pooled&&(this.maskObject=null,this.type=uh.NONE,this.autoDetect=!0),this._target=null,this._scissorRectLocal=null}copyCountersOrReset(t){t?(this._stencilCounter=t._stencilCounter,this._scissorCounter=t._scissorCounter,this._scissorRect=t._scissorRect):(this._stencilCounter=0,this._scissorCounter=0,this._scissorRect=null)}}class Em{constructor(t){this.renderer=t,this.enableScissor=!0,this.alphaMaskPool=[],this.maskDataPool=[],this.maskStack=[],this.alphaMaskIndex=0}setMaskStack(t){this.maskStack=t,this.renderer.scissor.setMaskStack(t),this.renderer.stencil.setMaskStack(t)}push(t,e){let i=e;if(!i.isMaskData){const t=this.maskDataPool.pop()||new Pm;t.pooled=!0,t.maskObject=e,i=t}const s=0!==this.maskStack.length?this.maskStack[this.maskStack.length-1]:null;if(i.copyCountersOrReset(s),i._colorMask=s?s._colorMask:15,i.autoDetect&&this.detect(i),i._target=t,i.type!==uh.SPRITE&&this.maskStack.push(i),i.enabled)switch(i.type){case uh.SCISSOR:this.renderer.scissor.push(i);break;case uh.STENCIL:this.renderer.stencil.push(i);break;case uh.SPRITE:i.copyCountersOrReset(null),this.pushSpriteMask(i);break;case uh.COLOR:this.pushColorMask(i)}i.type===uh.SPRITE&&this.maskStack.push(i)}pop(t){const e=this.maskStack.pop();if(e&&e._target===t){if(e.enabled)switch(e.type){case uh.SCISSOR:this.renderer.scissor.pop(e);break;case uh.STENCIL:this.renderer.stencil.pop(e.maskObject);break;case uh.SPRITE:this.popSpriteMask(e);break;case uh.COLOR:this.popColorMask(e)}if(e.reset(),e.pooled&&this.maskDataPool.push(e),0!==this.maskStack.length){const t=this.maskStack[this.maskStack.length-1];t.type===uh.SPRITE&&t._filters&&(t._filters[0].maskSprite=t.maskObject)}}}detect(t){const e=t.maskObject;e?e.isSprite?t.type=uh.SPRITE:this.enableScissor&&this.renderer.scissor.testScissor(t)?t.type=uh.SCISSOR:t.type=uh.STENCIL:t.type=uh.COLOR}pushSpriteMask(t){const{maskObject:e}=t,i=t._target;let s=t._filters;s||(s=this.alphaMaskPool[this.alphaMaskIndex],s||(s=this.alphaMaskPool[this.alphaMaskIndex]=[new wm])),s[0].resolution=t.resolution,s[0].multisample=t.multisample,s[0].maskSprite=e;const r=i.filterArea;i.filterArea=e.getBounds(!0),this.renderer.filter.push(i,s),i.filterArea=r,t._filters||this.alphaMaskIndex++}popSpriteMask(t){this.renderer.filter.pop(),t._filters?t._filters[0].maskSprite=null:(this.alphaMaskIndex--,this.alphaMaskPool[this.alphaMaskIndex][0].maskSprite=null)}pushColorMask(t){const e=t._colorMask,i=t._colorMask=e&t.colorMask;i!==e&&this.renderer.gl.colorMask(!!(1&i),!!(2&i),!!(4&i),!!(8&i))}popColorMask(t){const e=t._colorMask,i=this.maskStack.length>0?this.maskStack[this.maskStack.length-1]._colorMask:15;i!==e&&this.renderer.gl.colorMask(!!(1&i),!!(2&i),!!(4&i),!!(8&i))}destroy(){this.renderer=null}}Em.extension={type:_p.RendererSystem,name:"mask"},Ep.add(Em);class Tm{constructor(t){this.renderer=t,this.maskStack=[],this.glConst=0}getStackLength(){return this.maskStack.length}setMaskStack(t){const{gl:e}=this.renderer,i=this.getStackLength();this.maskStack=t;const s=this.getStackLength();s!==i&&(0===s?e.disable(this.glConst):(e.enable(this.glConst),this._useCurrent()))}_useCurrent(){}destroy(){this.renderer=null,this.maskStack=null}}const Am=new nf,Im=[],Sm=class t extends Tm{constructor(t){super(t),this.glConst=ph.ADAPTER.getWebGLRenderingContext().SCISSOR_TEST}getStackLength(){const t=this.maskStack[this.maskStack.length-1];return t?t._scissorCounter:0}calcScissorRect(t){if(t._scissorRectLocal)return;const e=t._scissorRect,{maskObject:i}=t,{renderer:s}=this,r=s.renderTexture,n=i.getBounds(!0,Im.pop()??new Qp);this.roundFrameToPixels(n,r.current?r.current.resolution:s.resolution,r.sourceFrame,r.destinationFrame,s.projection.transform),e&&n.fit(e),t._scissorRectLocal=n}static isMatrixRotated(t){if(!t)return!1;const{a:e,b:i,c:s,d:r}=t;return(Math.abs(i)>1e-4||Math.abs(s)>1e-4)&&(Math.abs(e)>1e-4||Math.abs(r)>1e-4)}testScissor(e){const{maskObject:i}=e;if(!i.isFastRect||!i.isFastRect()||t.isMatrixRotated(i.worldTransform)||t.isMatrixRotated(this.renderer.projection.transform))return!1;this.calcScissorRect(e);const s=e._scissorRectLocal;return s.width>0&&s.height>0}roundFrameToPixels(e,i,s,r,n){t.isMatrixRotated(n)||((n=n?Am.copyFrom(n):Am.identity()).translate(-s.x,-s.y).scale(r.width/s.width,r.height/s.height).translate(r.x,r.y),this.renderer.filter.transformAABB(n,e),e.fit(r),e.x=Math.round(e.x*i),e.y=Math.round(e.y*i),e.width=Math.round(e.width*i),e.height=Math.round(e.height*i))}push(t){t._scissorRectLocal||this.calcScissorRect(t);const{gl:e}=this.renderer;t._scissorRect||e.enable(e.SCISSOR_TEST),t._scissorCounter++,t._scissorRect=t._scissorRectLocal,this._useCurrent()}pop(t){const{gl:e}=this.renderer;t&&Im.push(t._scissorRectLocal),this.getStackLength()>0?this._useCurrent():e.disable(e.SCISSOR_TEST)}_useCurrent(){const t=this.maskStack[this.maskStack.length-1]._scissorRect;let e;e=this.renderer.renderTexture.current?t.y:this.renderer.height-t.height-t.y,this.renderer.gl.scissor(t.x,e,t.width,t.height)}};Sm.extension={type:_p.RendererSystem,name:"scissor"};let Cm=Sm;Ep.add(Cm);class Mm extends Tm{constructor(t){super(t),this.glConst=ph.ADAPTER.getWebGLRenderingContext().STENCIL_TEST}getStackLength(){const t=this.maskStack[this.maskStack.length-1];return t?t._stencilCounter:0}push(t){const e=t.maskObject,{gl:i}=this.renderer,s=t._stencilCounter;0===s&&(this.renderer.framebuffer.forceStencil(),i.clearStencil(0),i.clear(i.STENCIL_BUFFER_BIT),i.enable(i.STENCIL_TEST)),t._stencilCounter++;const r=t._colorMask;0!==r&&(t._colorMask=0,i.colorMask(!1,!1,!1,!1)),i.stencilFunc(i.EQUAL,s,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.INCR),e.renderable=!0,e.render(this.renderer),this.renderer.batch.flush(),e.renderable=!1,0!==r&&(t._colorMask=r,i.colorMask(!!(1&r),!!(2&r),!!(4&r),!!(8&r))),this._useCurrent()}pop(t){const e=this.renderer.gl;if(0===this.getStackLength())e.disable(e.STENCIL_TEST);else{const i=0!==this.maskStack.length?this.maskStack[this.maskStack.length-1]:null,s=i?i._colorMask:15;0!==s&&(i._colorMask=0,e.colorMask(!1,!1,!1,!1)),e.stencilOp(e.KEEP,e.KEEP,e.DECR),t.renderable=!0,t.render(this.renderer),this.renderer.batch.flush(),t.renderable=!1,0!==s&&(i._colorMask=s,e.colorMask(!!(1&s),!!(2&s),!!(4&s),!!(8&s))),this._useCurrent()}}_useCurrent(){const t=this.renderer.gl;t.stencilFunc(t.EQUAL,this.getStackLength(),4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP)}}Mm.extension={type:_p.RendererSystem,name:"stencil"},Ep.add(Mm);class Om{constructor(t){this.renderer=t,this.plugins={},Object.defineProperties(this.plugins,{extract:{enumerable:!1,get:()=>(dd("7.0.0","renderer.plugins.extract has moved to renderer.extract"),t.extract)},prepare:{enumerable:!1,get:()=>(dd("7.0.0","renderer.plugins.prepare has moved to renderer.prepare"),t.prepare)},interaction:{enumerable:!1,get:()=>(dd("7.0.0","renderer.plugins.interaction has been deprecated, use renderer.events"),t.events)}})}init(){const t=this.rendererPlugins;for(const e in t)this.plugins[e]=new t[e](this.renderer)}destroy(){for(const t in this.plugins)this.plugins[t].destroy(),this.plugins[t]=null}}Om.extension={type:[_p.RendererSystem,_p.CanvasRendererSystem],name:"_plugin"},Ep.add(Om);class Nm{constructor(t){this.renderer=t,this.destinationFrame=null,this.sourceFrame=null,this.defaultFrame=null,this.projectionMatrix=new nf,this.transform=null}update(t,e,i,s){this.destinationFrame=t||this.destinationFrame||this.defaultFrame,this.sourceFrame=e||this.sourceFrame||t,this.calculateProjection(this.destinationFrame,this.sourceFrame,i,s),this.transform&&this.projectionMatrix.append(this.transform);const r=this.renderer;r.globalUniforms.uniforms.projectionMatrix=this.projectionMatrix,r.globalUniforms.update(),r.shader.shader&&r.shader.syncUniformGroup(r.shader.shader.uniforms.globals)}calculateProjection(t,e,i,s){const r=this.projectionMatrix,n=s?-1:1;r.identity(),r.a=1/e.width*2,r.d=n*(1/e.height*2),r.tx=-1-e.x*r.a,r.ty=-n-e.y*r.d}setTransform(t){}destroy(){this.renderer=null}}Nm.extension={type:_p.RendererSystem,name:"projection"},Ep.add(Nm);const Lm=new gf,Rm=new Qp;class km{constructor(t){this.renderer=t,this._tempMatrix=new nf}generateTexture(t,e){const{region:i,...s}=e||{},r=i?.copyTo(Rm)||t.getLocalBounds(Rm,!0),n=s.resolution||this.renderer.resolution;r.width=Math.max(r.width,1/n),r.height=Math.max(r.height,1/n),s.width=r.width,s.height=r.height,s.resolution=n,s.multisample??(s.multisample=this.renderer.multisample);const o=am.create(s);this._tempMatrix.tx=-r.x,this._tempMatrix.ty=-r.y;const a=t.transform;return t.transform=Lm,this.renderer.render(t,{renderTexture:o,transform:this._tempMatrix,skipUpdateTransform:!!t.parent,blit:!0}),t.transform=a,o}destroy(){}}km.extension={type:[_p.RendererSystem,_p.CanvasRendererSystem],name:"textureGenerator"},Ep.add(km);const Bm=new Qp,Fm=new Qp;class Dm{constructor(t){this.renderer=t,this.defaultMaskStack=[],this.current=null,this.sourceFrame=new Qp,this.destinationFrame=new Qp,this.viewportFrame=new Qp}contextChange(){const t=this.renderer?.gl.getContextAttributes();this._rendererPremultipliedAlpha=!!(t&&t.alpha&&t.premultipliedAlpha)}bind(t=null,e,i){const s=this.renderer;let r,n,o;this.current=t,t?(r=t.baseTexture,o=r.resolution,e||(Bm.width=t.frame.width,Bm.height=t.frame.height,e=Bm),i||(Fm.x=t.frame.x,Fm.y=t.frame.y,Fm.width=e.width,Fm.height=e.height,i=Fm),n=r.framebuffer):(o=s.resolution,e||(Bm.width=s._view.screen.width,Bm.height=s._view.screen.height,e=Bm),i||((i=Bm).width=e.width,i.height=e.height));const a=this.viewportFrame;a.x=i.x*o,a.y=i.y*o,a.width=i.width*o,a.height=i.height*o,t||(a.y=s.view.height-(a.y+a.height)),a.ceil(),this.renderer.framebuffer.bind(n,a),this.renderer.projection.update(i,e,o,!n),t?this.renderer.mask.setMaskStack(r.maskStack):this.renderer.mask.setMaskStack(this.defaultMaskStack),this.sourceFrame.copyFrom(e),this.destinationFrame.copyFrom(i)}clear(t,e){const i=this.current?this.current.baseTexture.clear:this.renderer.background.backgroundColor,s=qd.shared.setValue(t||i);(this.current&&this.current.baseTexture.alphaMode>0||!this.current&&this._rendererPremultipliedAlpha)&&s.premultiply(s.alpha);const r=this.destinationFrame,n=this.current?this.current.baseTexture:this.renderer._view.screen,o=r.width!==n.width||r.height!==n.height;if(o){let{x:t,y:e,width:i,height:s}=this.viewportFrame;t=Math.round(t),e=Math.round(e),i=Math.round(i),s=Math.round(s),this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST),this.renderer.gl.scissor(t,e,i,s)}this.renderer.framebuffer.clear(s.red,s.green,s.blue,s.alpha,e),o&&this.renderer.scissor.pop()}resize(){this.bind(null)}reset(){this.bind(null)}destroy(){this.renderer=null}}Dm.extension={type:_p.RendererSystem,name:"renderTexture"},Ep.add(Dm);class Um{constructor(t,e){this.program=t,this.uniformData=e,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBufferBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBufferBindings=null,this.program=null}}function Gm(t,e){const i=yf(t,t.VERTEX_SHADER,e.vertexSrc),s=yf(t,t.FRAGMENT_SHADER,e.fragmentSrc),r=t.createProgram();t.attachShader(r,i),t.attachShader(r,s);const n=e.extra?.transformFeedbackVaryings;if(n&&("function"!=typeof t.transformFeedbackVaryings?console.warn("TransformFeedback is not supported but TransformFeedbackVaryings are given."):t.transformFeedbackVaryings(r,n.names,"separate"===n.bufferMode?t.SEPARATE_ATTRIBS:t.INTERLEAVED_ATTRIBS)),t.linkProgram(r),t.getProgramParameter(r,t.LINK_STATUS)||function(t,e,i,s){t.getProgramParameter(e,t.LINK_STATUS)||(t.getShaderParameter(i,t.COMPILE_STATUS)||If(t,i),t.getShaderParameter(s,t.COMPILE_STATUS)||If(t,s),console.error("PixiJS Error: Could not initialize shader."),""!==t.getProgramInfoLog(e)&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",t.getProgramInfoLog(e)))}(t,r,i,s),e.attributeData=function(t,e){const i={},s=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let r=0;r<s;r++){const s=e.getActiveAttrib(t,r);if(s.name.startsWith("gl_"))continue;const n=Nf(e,s.type),o={type:n,name:s.name,size:Cf(n),location:e.getAttribLocation(t,s.name)};i[s.name]=o}return i}(r,t),e.uniformData=function(t,e){const i={},s=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let r=0;r<s;r++){const s=e.getActiveUniform(t,r),n=s.name.replace(/\[.*?\]$/,""),o=!!s.name.match(/\[.*?\]$/),a=Nf(e,s.type);i[n]={name:n,index:r,type:a,size:s.size,isArray:o,value:xf(a,s.size)}}return i}(r,t),!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(e.vertexSrc)){const i=Object.keys(e.attributeData);i.sort((t,e)=>t>e?1:-1);for(let s=0;s<i.length;s++)e.attributeData[i[s]].location=s,t.bindAttribLocation(r,s,i[s]);t.linkProgram(r)}t.deleteShader(i),t.deleteShader(s);const o={};for(const a in e.uniformData){const i=e.uniformData[a];o[a]={location:t.getUniformLocation(r,a),value:xf(i.type,i.size)}}return new Um(r,o)}function Xm(t,e,i,s,r){i.buffer.update(r)}const Wm={float:"\n data[offset] = v;\n ",vec2:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n ",vec3:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n ",vec4:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n data[offset+3] = v[3];\n ",mat2:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n\n data[offset+4] = v[2];\n data[offset+5] = v[3];\n ",mat3:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n data[offset + 4] = v[3];\n data[offset + 5] = v[4];\n data[offset + 6] = v[5];\n\n data[offset + 8] = v[6];\n data[offset + 9] = v[7];\n data[offset + 10] = v[8];\n ",mat4:"\n for(var i = 0; i < 16; i++)\n {\n data[offset + i] = v[i];\n }\n "},Ym={float:4,vec2:8,vec3:12,vec4:16,int:4,ivec2:8,ivec3:12,ivec4:16,uint:4,uvec2:8,uvec3:12,uvec4:16,bool:4,bvec2:8,bvec3:12,bvec4:16,mat2:32,mat3:48,mat4:64};function Hm(t,e){if(!t.autoManage)return{size:0,syncFunc:Xm};const i=function(t,e){const i=[];for(const s in t)e[s]&&i.push(e[s]);return i.sort((t,e)=>t.index-e.index),i}(t.uniforms,e),{uboElements:s,size:r}=function(t){const e=t.map(t=>({data:t,offset:0,dataLen:0,dirty:0}));let i=0,s=0,r=0;for(let n=0;n<e.length;n++){const t=e[n];if(i=Ym[t.data.type],t.data.size>1&&(i=Math.max(i,16)*t.data.size),t.dataLen=i,s%i!==0&&s<16){const t=s%i%16;s+=t,r+=t}s+i>16?(r=16*Math.ceil(r/16),t.offset=r,r+=i,s=i):(t.offset=r,s+=i,r+=i)}return r=16*Math.ceil(r/16),{uboElements:e,size:r}}(i),n=["\n var v = null;\n var v2 = null;\n var cv = null;\n var t = 0;\n var gl = renderer.gl\n var index = 0;\n var data = buffer.data;\n "];for(let o=0;o<s.length;o++){const e=s[o],i=t.uniforms[e.data.name],r=e.data.name;let a=!1;for(let t=0;t<bf.length;t++){const s=bf[t];if(s.codeUbo&&s.test(e.data,i)){n.push(`offset = ${e.offset/4};`,bf[t].codeUbo(e.data.name,i)),a=!0;break}}if(!a)if(e.data.size>1){const t=Cf(e.data.type),i=Math.max(Ym[e.data.type]/16,1),s=t/i,o=(4-s%4)%4;n.push(`\n cv = ud.${r}.value;\n v = uv.${r};\n offset = ${e.offset/4};\n\n t = 0;\n\n for(var i=0; i < ${e.data.size*i}; i++)\n {\n for(var j = 0; j < ${s}; j++)\n {\n data[offset++] = v[t++];\n }\n offset += ${o};\n }\n\n `)}else{const t=Wm[e.data.type];n.push(`\n cv = ud.${r}.value;\n v = uv.${r};\n offset = ${e.offset/4};\n ${t};\n `)}}return n.push("\n renderer.buffer.update(buffer);\n "),{size:r,syncFunc:new Function("ud","uv","renderer","syncData","buffer",n.join("\n"))}}let $m=0;const jm={textureCount:0,uboCount:0};class zm{constructor(t){this.destroyed=!1,this.renderer=t,this.systemCheck(),this.gl=null,this.shader=null,this.program=null,this.cache={},this._uboCache={},this.id=$m++}systemCheck(){if(!function(){if("boolean"==typeof Rf)return Rf;try{Rf=!0===new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")}catch{Rf=!1}return Rf}())throw new Error("Current environment does not allow unsafe-eval, please use @pixi/unsafe-eval module to enable support.")}contextChange(t){this.gl=t,this.reset()}bind(t,e){t.disposeRunner.add(this),t.uniforms.globals=this.renderer.globalUniforms;const i=t.program,s=i.glPrograms[this.renderer.CONTEXT_UID]||this.generateProgram(t);return this.shader=t,this.program!==i&&(this.program=i,this.gl.useProgram(s.program)),e||(jm.textureCount=0,jm.uboCount=0,this.syncUniformGroup(t.uniformGroup,jm)),s}setUniforms(t){const e=this.shader.program,i=e.glPrograms[this.renderer.CONTEXT_UID];e.syncUniforms(i.uniformData,t,this.renderer)}syncUniformGroup(t,e){const i=this.getGlProgram();(!t.static||t.dirtyId!==i.uniformDirtyGroups[t.id])&&(i.uniformDirtyGroups[t.id]=t.dirtyId,this.syncUniforms(t,i,e))}syncUniforms(t,e,i){(t.syncUniforms[this.shader.program.id]||this.createSyncGroups(t))(e.uniformData,t.uniforms,this.renderer,i)}createSyncGroups(t){const e=this.getSignature(t,this.shader.program.uniformData,"u");return this.cache[e]||(this.cache[e]=function(t,e){const i=["\n var v = null;\n var cv = null;\n var cu = null;\n var t = 0;\n var gl = renderer.gl;\n "];for(const s in t.uniforms){const r=e[s];if(!r){!0===t.uniforms[s]?.group&&(t.uniforms[s].ubo?i.push(`\n renderer.shader.syncUniformBufferGroup(uv.${s}, '${s}');\n `):i.push(`\n renderer.shader.syncUniformGroup(uv.${s}, syncData);\n `));continue}const n=t.uniforms[s];let o=!1;for(let t=0;t<bf.length;t++)if(bf[t].test(r,n)){i.push(bf[t].code(s,n)),o=!0;break}if(!o){const t=(1!==r.size||r.isArray?wf:_f)[r.type].replace("location",`ud["${s}"].location`);i.push(`\n cu = ud["${s}"];\n cv = cu.value;\n v = uv["${s}"];\n ${t};`)}}return new Function("ud","uv","renderer","syncData",i.join("\n"))}(t,this.shader.program.uniformData)),t.syncUniforms[this.shader.program.id]=this.cache[e],t.syncUniforms[this.shader.program.id]}syncUniformBufferGroup(t,e){const i=this.getGlProgram();if(!t.static||0!==t.dirtyId||!i.uniformGroups[t.id]){t.dirtyId=0;const s=i.uniformGroups[t.id]||this.createSyncBufferGroup(t,i,e);t.buffer.update(),s(i.uniformData,t.uniforms,this.renderer,jm,t.buffer)}this.renderer.buffer.bindBufferBase(t.buffer,i.uniformBufferBindings[e])}createSyncBufferGroup(t,e,i){const{gl:s}=this.renderer;this.renderer.buffer.bind(t.buffer);const r=this.gl.getUniformBlockIndex(e.program,i);e.uniformBufferBindings[i]=this.shader.uniformBindCount,s.uniformBlockBinding(e.program,r,this.shader.uniformBindCount),this.shader.uniformBindCount++;const n=this.getSignature(t,this.shader.program.uniformData,"ubo");let o=this._uboCache[n];if(o||(o=this._uboCache[n]=Hm(t,this.shader.program.uniformData)),t.autoManage){const e=new Float32Array(o.size/4);t.buffer.update(e)}return e.uniformGroups[t.id]=o.syncFunc,e.uniformGroups[t.id]}getSignature(t,e,i){const s=t.uniforms,r=[`${i}-`];for(const n in s)r.push(n),e[n]&&r.push(e[n].type);return r.join("-")}getGlProgram(){return this.shader?this.shader.program.glPrograms[this.renderer.CONTEXT_UID]:null}generateProgram(t){const e=this.gl,i=t.program,s=Gm(e,i);return i.glPrograms[this.renderer.CONTEXT_UID]=s,s}reset(){this.program=null,this.shader=null}disposeShader(t){this.shader===t&&(this.shader=null)}destroy(){this.renderer=null,this.destroyed=!0}}zm.extension={type:_p.RendererSystem,name:"shader"},Ep.add(zm);class Vm{constructor(t){this.renderer=t}run(t){const{renderer:e}=this;e.runners.init.emit(e.options),t.hello&&console.log(`PixiJS 7.4.2 - ${e.rendererLogId} - https://pixijs.com`),e.resize(e.screen.width,e.screen.height)}destroy(){}}Vm.defaultOptions={hello:!1},Vm.extension={type:[_p.RendererSystem,_p.CanvasRendererSystem],name:"startup"},Ep.add(Vm);const qm=class t{constructor(){this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode=Kl.NONE,this._blendEq=!1,this.map=[],this.map[0]=this.setBlend,this.map[1]=this.setOffset,this.map[2]=this.setCullFace,this.map[3]=this.setDepthTest,this.map[4]=this.setFrontFace,this.map[5]=this.setDepthMask,this.checks=[],this.defaultState=new Sp,this.defaultState.blend=!0}contextChange(t){this.gl=t,this.blendModes=function(t,e=[]){return e[Kl.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.ADD]=[t.ONE,t.ONE],e[Kl.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.NONE]=[0,0],e[Kl.NORMAL_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.ADD_NPM]=[t.SRC_ALPHA,t.ONE,t.ONE,t.ONE],e[Kl.SCREEN_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.SRC_IN]=[t.DST_ALPHA,t.ZERO],e[Kl.SRC_OUT]=[t.ONE_MINUS_DST_ALPHA,t.ZERO],e[Kl.SRC_ATOP]=[t.DST_ALPHA,t.ONE_MINUS_SRC_ALPHA],e[Kl.DST_OVER]=[t.ONE_MINUS_DST_ALPHA,t.ONE],e[Kl.DST_IN]=[t.ZERO,t.SRC_ALPHA],e[Kl.DST_OUT]=[t.ZERO,t.ONE_MINUS_SRC_ALPHA],e[Kl.DST_ATOP]=[t.ONE_MINUS_DST_ALPHA,t.SRC_ALPHA],e[Kl.XOR]=[t.ONE_MINUS_DST_ALPHA,t.ONE_MINUS_SRC_ALPHA],e[Kl.SUBTRACT]=[t.ONE,t.ONE,t.ONE,t.ONE,t.FUNC_REVERSE_SUBTRACT,t.FUNC_ADD],e}(t),this.set(this.defaultState),this.reset()}set(t){if(t=t||this.defaultState,this.stateId!==t.data){let e=this.stateId^t.data,i=0;for(;e;)1&e&&this.map[i].call(this,!!(t.data&1<<i)),e>>=1,i++;this.stateId=t.data}for(let e=0;e<this.checks.length;e++)this.checks[e](this,t)}forceState(t){t=t||this.defaultState;for(let e=0;e<this.map.length;e++)this.map[e].call(this,!!(t.data&1<<e));for(let e=0;e<this.checks.length;e++)this.checks[e](this,t);this.stateId=t.data}setBlend(e){this.updateCheck(t.checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this.updateCheck(t.checkPolygonOffset,e),this.gl[e?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(t){this.gl[t?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(t){this.gl.depthMask(t)}setCullFace(t){this.gl[t?"enable":"disable"](this.gl.CULL_FACE)}setFrontFace(t){this.gl.frontFace(this.gl[t?"CW":"CCW"])}setBlendMode(t){if(t===this.blendMode)return;this.blendMode=t;const e=this.blendModes[t],i=this.gl;2===e.length?i.blendFunc(e[0],e[1]):i.blendFuncSeparate(e[0],e[1],e[2],e[3]),6===e.length?(this._blendEq=!0,i.blendEquationSeparate(e[4],e[5])):this._blendEq&&(this._blendEq=!1,i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD))}setPolygonOffset(t,e){this.gl.polygonOffset(t,e)}reset(){this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode=-1,this.setBlendMode(0)}updateCheck(t,e){const i=this.checks.indexOf(t);e&&-1===i?this.checks.push(t):!e&&-1!==i&&this.checks.splice(i,1)}static checkBlendMode(t,e){t.setBlendMode(e.blendMode)}static checkPolygonOffset(t,e){t.setPolygonOffset(1,e.polygonOffset)}destroy(){this.gl=null}};qm.extension={type:_p.RendererSystem,name:"state"};let Jm=qm;Ep.add(Jm);class Km extends kh{constructor(){super(...arguments),this.runners={},this._systemsHash={}}setup(t){this.addRunners(...t.runners);const e=(t.priority??[]).filter(e=>t.systems[e]),i=[...e,...Object.keys(t.systems).filter(t=>!e.includes(t))];for(const s of i)this.addSystem(t.systems[s],s)}addRunners(...t){t.forEach(t=>{this.runners[t]=new Op(t)})}addSystem(t,e){const i=new t(this);if(this[e])throw new Error(`Whoops! The name "${e}" is already in use`);this[e]=i,this._systemsHash[e]=i;for(const s in this.runners)this.runners[s].add(i);return this}emitWithCustomOptions(t,e){const i=Object.keys(this._systemsHash);t.items.forEach(s=>{const r=i.find(t=>this._systemsHash[t]===s);s[t.name](e[r])})}destroy(){Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash={}}}const Zm=class t{constructor(e){this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=t.defaultMaxIdle,this.checkCountMax=t.defaultCheckCountMax,this.mode=t.defaultMode}postrender(){this.renderer.objectRenderer.renderingToScreen&&(this.count++,this.mode!==lh.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run())))}run(){const t=this.renderer.texture,e=t.managedTextures;let i=!1;for(let s=0;s<e.length;s++){const r=e[s];r.resource&&this.count-r.touched>this.maxIdle&&(t.destroyTexture(r,!0),e[s]=null,i=!0)}if(i){let t=0;for(let i=0;i<e.length;i++)null!==e[i]&&(e[t++]=e[i]);e.length=t}}unload(t){const e=this.renderer.texture,i=t._texture;i&&!i.framebuffer&&e.destroyTexture(i);for(let s=t.children.length-1;s>=0;s--)this.unload(t.children[s])}destroy(){this.renderer=null}};Zm.defaultMode=lh.AUTO,Zm.defaultMaxIdle=3600,Zm.defaultCheckCountMax=600,Zm.extension={type:_p.RendererSystem,name:"textureGC"};let Qm=Zm;Ep.add(Qm);class tg{constructor(t){this.texture=t,this.width=-1,this.height=-1,this.dirtyId=-1,this.dirtyStyleId=-1,this.mipmap=!1,this.wrapMode=33071,this.type=eh.UNSIGNED_BYTE,this.internalFormat=Ql.RGBA,this.samplerType=0}}class eg{constructor(t){this.renderer=t,this.boundTextures=[],this.currentLocation=-1,this.managedTextures=[],this._unknownBoundTextures=!1,this.unknownTexture=new Bp,this.hasIntegerTextures=!1}contextChange(){const t=this.gl=this.renderer.gl;this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.webGLVersion=this.renderer.context.webGLVersion,this.internalFormats=function(t){let e;return e="WebGL2RenderingContext"in globalThis&&t instanceof globalThis.WebGL2RenderingContext?{[eh.UNSIGNED_BYTE]:{[Ql.RGBA]:t.RGBA8,[Ql.RGB]:t.RGB8,[Ql.RG]:t.RG8,[Ql.RED]:t.R8,[Ql.RGBA_INTEGER]:t.RGBA8UI,[Ql.RGB_INTEGER]:t.RGB8UI,[Ql.RG_INTEGER]:t.RG8UI,[Ql.RED_INTEGER]:t.R8UI,[Ql.ALPHA]:t.ALPHA,[Ql.LUMINANCE]:t.LUMINANCE,[Ql.LUMINANCE_ALPHA]:t.LUMINANCE_ALPHA},[eh.BYTE]:{[Ql.RGBA]:t.RGBA8_SNORM,[Ql.RGB]:t.RGB8_SNORM,[Ql.RG]:t.RG8_SNORM,[Ql.RED]:t.R8_SNORM,[Ql.RGBA_INTEGER]:t.RGBA8I,[Ql.RGB_INTEGER]:t.RGB8I,[Ql.RG_INTEGER]:t.RG8I,[Ql.RED_INTEGER]:t.R8I},[eh.UNSIGNED_SHORT]:{[Ql.RGBA_INTEGER]:t.RGBA16UI,[Ql.RGB_INTEGER]:t.RGB16UI,[Ql.RG_INTEGER]:t.RG16UI,[Ql.RED_INTEGER]:t.R16UI,[Ql.DEPTH_COMPONENT]:t.DEPTH_COMPONENT16},[eh.SHORT]:{[Ql.RGBA_INTEGER]:t.RGBA16I,[Ql.RGB_INTEGER]:t.RGB16I,[Ql.RG_INTEGER]:t.RG16I,[Ql.RED_INTEGER]:t.R16I},[eh.UNSIGNED_INT]:{[Ql.RGBA_INTEGER]:t.RGBA32UI,[Ql.RGB_INTEGER]:t.RGB32UI,[Ql.RG_INTEGER]:t.RG32UI,[Ql.RED_INTEGER]:t.R32UI,[Ql.DEPTH_COMPONENT]:t.DEPTH_COMPONENT24},[eh.INT]:{[Ql.RGBA_INTEGER]:t.RGBA32I,[Ql.RGB_INTEGER]:t.RGB32I,[Ql.RG_INTEGER]:t.RG32I,[Ql.RED_INTEGER]:t.R32I},[eh.FLOAT]:{[Ql.RGBA]:t.RGBA32F,[Ql.RGB]:t.RGB32F,[Ql.RG]:t.RG32F,[Ql.RED]:t.R32F,[Ql.DEPTH_COMPONENT]:t.DEPTH_COMPONENT32F},[eh.HALF_FLOAT]:{[Ql.RGBA]:t.RGBA16F,[Ql.RGB]:t.RGB16F,[Ql.RG]:t.RG16F,[Ql.RED]:t.R16F},[eh.UNSIGNED_SHORT_5_6_5]:{[Ql.RGB]:t.RGB565},[eh.UNSIGNED_SHORT_4_4_4_4]:{[Ql.RGBA]:t.RGBA4},[eh.UNSIGNED_SHORT_5_5_5_1]:{[Ql.RGBA]:t.RGB5_A1},[eh.UNSIGNED_INT_2_10_10_10_REV]:{[Ql.RGBA]:t.RGB10_A2,[Ql.RGBA_INTEGER]:t.RGB10_A2UI},[eh.UNSIGNED_INT_10F_11F_11F_REV]:{[Ql.RGB]:t.R11F_G11F_B10F},[eh.UNSIGNED_INT_5_9_9_9_REV]:{[Ql.RGB]:t.RGB9_E5},[eh.UNSIGNED_INT_24_8]:{[Ql.DEPTH_STENCIL]:t.DEPTH24_STENCIL8},[eh.FLOAT_32_UNSIGNED_INT_24_8_REV]:{[Ql.DEPTH_STENCIL]:t.DEPTH32F_STENCIL8}}:{[eh.UNSIGNED_BYTE]:{[Ql.RGBA]:t.RGBA,[Ql.RGB]:t.RGB,[Ql.ALPHA]:t.ALPHA,[Ql.LUMINANCE]:t.LUMINANCE,[Ql.LUMINANCE_ALPHA]:t.LUMINANCE_ALPHA},[eh.UNSIGNED_SHORT_5_6_5]:{[Ql.RGB]:t.RGB},[eh.UNSIGNED_SHORT_4_4_4_4]:{[Ql.RGBA]:t.RGBA},[eh.UNSIGNED_SHORT_5_5_5_1]:{[Ql.RGBA]:t.RGBA}},e}(t),this.samplerTypes=function(t){let e;return e="WebGL2RenderingContext"in globalThis&&t instanceof globalThis.WebGL2RenderingContext?{[t.RGB]:ih.FLOAT,[t.RGBA]:ih.FLOAT,[t.ALPHA]:ih.FLOAT,[t.LUMINANCE]:ih.FLOAT,[t.LUMINANCE_ALPHA]:ih.FLOAT,[t.R8]:ih.FLOAT,[t.R8_SNORM]:ih.FLOAT,[t.RG8]:ih.FLOAT,[t.RG8_SNORM]:ih.FLOAT,[t.RGB8]:ih.FLOAT,[t.RGB8_SNORM]:ih.FLOAT,[t.RGB565]:ih.FLOAT,[t.RGBA4]:ih.FLOAT,[t.RGB5_A1]:ih.FLOAT,[t.RGBA8]:ih.FLOAT,[t.RGBA8_SNORM]:ih.FLOAT,[t.RGB10_A2]:ih.FLOAT,[t.RGB10_A2UI]:ih.FLOAT,[t.SRGB8]:ih.FLOAT,[t.SRGB8_ALPHA8]:ih.FLOAT,[t.R16F]:ih.FLOAT,[t.RG16F]:ih.FLOAT,[t.RGB16F]:ih.FLOAT,[t.RGBA16F]:ih.FLOAT,[t.R32F]:ih.FLOAT,[t.RG32F]:ih.FLOAT,[t.RGB32F]:ih.FLOAT,[t.RGBA32F]:ih.FLOAT,[t.R11F_G11F_B10F]:ih.FLOAT,[t.RGB9_E5]:ih.FLOAT,[t.R8I]:ih.INT,[t.R8UI]:ih.UINT,[t.R16I]:ih.INT,[t.R16UI]:ih.UINT,[t.R32I]:ih.INT,[t.R32UI]:ih.UINT,[t.RG8I]:ih.INT,[t.RG8UI]:ih.UINT,[t.RG16I]:ih.INT,[t.RG16UI]:ih.UINT,[t.RG32I]:ih.INT,[t.RG32UI]:ih.UINT,[t.RGB8I]:ih.INT,[t.RGB8UI]:ih.UINT,[t.RGB16I]:ih.INT,[t.RGB16UI]:ih.UINT,[t.RGB32I]:ih.INT,[t.RGB32UI]:ih.UINT,[t.RGBA8I]:ih.INT,[t.RGBA8UI]:ih.UINT,[t.RGBA16I]:ih.INT,[t.RGBA16UI]:ih.UINT,[t.RGBA32I]:ih.INT,[t.RGBA32UI]:ih.UINT,[t.DEPTH_COMPONENT16]:ih.FLOAT,[t.DEPTH_COMPONENT24]:ih.FLOAT,[t.DEPTH_COMPONENT32F]:ih.FLOAT,[t.DEPTH_STENCIL]:ih.FLOAT,[t.DEPTH24_STENCIL8]:ih.FLOAT,[t.DEPTH32F_STENCIL8]:ih.FLOAT}:{[t.RGB]:ih.FLOAT,[t.RGBA]:ih.FLOAT,[t.ALPHA]:ih.FLOAT,[t.LUMINANCE]:ih.FLOAT,[t.LUMINANCE_ALPHA]:ih.FLOAT,[t.DEPTH_STENCIL]:ih.FLOAT},e}(t);const e=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);this.boundTextures.length=e;for(let s=0;s<e;s++)this.boundTextures[s]=null;this.emptyTextures={};const i=new tg(t.createTexture());t.bindTexture(t.TEXTURE_2D,i.texture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array(4)),this.emptyTextures[t.TEXTURE_2D]=i,this.emptyTextures[t.TEXTURE_CUBE_MAP]=new tg(t.createTexture()),t.bindTexture(t.TEXTURE_CUBE_MAP,this.emptyTextures[t.TEXTURE_CUBE_MAP].texture);for(let s=0;s<6;s++)t.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+s,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,null);t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_MIN_FILTER,t.LINEAR);for(let s=0;s<this.boundTextures.length;s++)this.bind(null,s)}bind(t,e=0){const{gl:i}=this;if(t=t?.castToBaseTexture(),t?.valid&&!t.parentTextureArray){t.touched=this.renderer.textureGC.count;const s=t._glTextures[this.CONTEXT_UID]||this.initTexture(t);this.boundTextures[e]!==t&&(this.currentLocation!==e&&(this.currentLocation=e,i.activeTexture(i.TEXTURE0+e)),i.bindTexture(t.target,s.texture)),s.dirtyId!==t.dirtyId?(this.currentLocation!==e&&(this.currentLocation=e,i.activeTexture(i.TEXTURE0+e)),this.updateTexture(t)):s.dirtyStyleId!==t.dirtyStyleId&&this.updateTextureStyle(t),this.boundTextures[e]=t}else this.currentLocation!==e&&(this.currentLocation=e,i.activeTexture(i.TEXTURE0+e)),i.bindTexture(i.TEXTURE_2D,this.emptyTextures[i.TEXTURE_2D].texture),this.boundTextures[e]=null}reset(){this._unknownBoundTextures=!0,this.hasIntegerTextures=!1,this.currentLocation=-1;for(let t=0;t<this.boundTextures.length;t++)this.boundTextures[t]=this.unknownTexture}unbind(t){const{gl:e,boundTextures:i}=this;if(this._unknownBoundTextures){this._unknownBoundTextures=!1;for(let t=0;t<i.length;t++)i[t]===this.unknownTexture&&this.bind(null,t)}for(let s=0;s<i.length;s++)i[s]===t&&(this.currentLocation!==s&&(e.activeTexture(e.TEXTURE0+s),this.currentLocation=s),e.bindTexture(t.target,this.emptyTextures[t.target].texture),i[s]=null)}ensureSamplerType(t){const{boundTextures:e,hasIntegerTextures:i,CONTEXT_UID:s}=this;if(i)for(let r=t-1;r>=0;--r){const t=e[r];t&&t._glTextures[s].samplerType!==ih.FLOAT&&this.renderer.texture.unbind(t)}}initTexture(t){const e=new tg(this.gl.createTexture());return e.dirtyId=-1,t._glTextures[this.CONTEXT_UID]=e,this.managedTextures.push(t),t.on("dispose",this.destroyTexture,this),e}initTextureType(t,e){e.internalFormat=this.internalFormats[t.type]?.[t.format]??t.format,e.samplerType=this.samplerTypes[e.internalFormat]??ih.FLOAT,2===this.webGLVersion&&t.type===eh.HALF_FLOAT?e.type=this.gl.HALF_FLOAT:e.type=t.type}updateTexture(t){const e=t._glTextures[this.CONTEXT_UID];if(!e)return;const i=this.renderer;if(this.initTextureType(t,e),t.resource?.upload(i,t,e))e.samplerType!==ih.FLOAT&&(this.hasIntegerTextures=!0);else{const s=t.realWidth,r=t.realHeight,n=i.gl;(e.width!==s||e.height!==r||e.dirtyId<0)&&(e.width=s,e.height=r,n.texImage2D(t.target,0,e.internalFormat,s,r,0,t.format,e.type,null))}t.dirtyStyleId!==e.dirtyStyleId&&this.updateTextureStyle(t),e.dirtyId=t.dirtyId}destroyTexture(t,e){const{gl:i}=this;if((t=t.castToBaseTexture())._glTextures[this.CONTEXT_UID]&&(this.unbind(t),i.deleteTexture(t._glTextures[this.CONTEXT_UID].texture),t.off("dispose",this.destroyTexture,this),delete t._glTextures[this.CONTEXT_UID],!e)){const e=this.managedTextures.indexOf(t);-1!==e&&sp(this.managedTextures,e,1)}}updateTextureStyle(t){const e=t._glTextures[this.CONTEXT_UID];e&&(t.mipmap!==nh.POW2&&2===this.webGLVersion||t.isPowerOfTwo?e.mipmap=t.mipmap>=1:e.mipmap=!1,2===this.webGLVersion||t.isPowerOfTwo?e.wrapMode=t.wrapMode:e.wrapMode=rh.CLAMP,t.resource?.style(this.renderer,t,e)||this.setStyle(t,e),e.dirtyStyleId=t.dirtyStyleId)}setStyle(t,e){const i=this.gl;if(e.mipmap&&t.mipmap!==nh.ON_MANUAL&&i.generateMipmap(t.target),i.texParameteri(t.target,i.TEXTURE_WRAP_S,e.wrapMode),i.texParameteri(t.target,i.TEXTURE_WRAP_T,e.wrapMode),e.mipmap){i.texParameteri(t.target,i.TEXTURE_MIN_FILTER,t.scaleMode===sh.LINEAR?i.LINEAR_MIPMAP_LINEAR:i.NEAREST_MIPMAP_NEAREST);const e=this.renderer.context.extensions.anisotropicFiltering;if(e&&t.anisotropicLevel>0&&t.scaleMode===sh.LINEAR){const s=Math.min(t.anisotropicLevel,i.getParameter(e.MAX_TEXTURE_MAX_ANISOTROPY_EXT));i.texParameterf(t.target,e.TEXTURE_MAX_ANISOTROPY_EXT,s)}}else i.texParameteri(t.target,i.TEXTURE_MIN_FILTER,t.scaleMode===sh.LINEAR?i.LINEAR:i.NEAREST);i.texParameteri(t.target,i.TEXTURE_MAG_FILTER,t.scaleMode===sh.LINEAR?i.LINEAR:i.NEAREST)}destroy(){this.renderer=null}}eg.extension={type:_p.RendererSystem,name:"texture"},Ep.add(eg);class ig{constructor(t){this.renderer=t}contextChange(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID}bind(t){const{gl:e,CONTEXT_UID:i}=this,s=t._glTransformFeedbacks[i]||this.createGLTransformFeedback(t);e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,s)}unbind(){const{gl:t}=this;t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null)}beginTransformFeedback(t,e){const{gl:i,renderer:s}=this;e&&s.shader.bind(e),i.beginTransformFeedback(t)}endTransformFeedback(){const{gl:t}=this;t.endTransformFeedback()}createGLTransformFeedback(t){const{gl:e,renderer:i,CONTEXT_UID:s}=this,r=e.createTransformFeedback();t._glTransformFeedbacks[s]=r,e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,r);for(let n=0;n<t.buffers.length;n++){const r=t.buffers[n];r&&(i.buffer.update(r),r._glBuffers[s].refCount++,e.bindBufferBase(e.TRANSFORM_FEEDBACK_BUFFER,n,r._glBuffers[s].buffer||null))}return e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,null),t.disposeRunner.add(this),r}disposeTransformFeedback(t,e){const i=t._glTransformFeedbacks[this.CONTEXT_UID],s=this.gl;t.disposeRunner.remove(this);const r=this.renderer.buffer;if(r)for(let n=0;n<t.buffers.length;n++){const i=t.buffers[n];if(!i)continue;const s=i._glBuffers[this.CONTEXT_UID];s&&(s.refCount--,0===s.refCount&&!e&&r.dispose(i,e))}i&&(e||s.deleteTransformFeedback(i),delete t._glTransformFeedbacks[this.CONTEXT_UID])}destroy(){this.renderer=null}}ig.extension={type:_p.RendererSystem,name:"transformFeedback"},Ep.add(ig);class sg{constructor(t){this.renderer=t}init(t){this.screen=new Qp(0,0,t.width,t.height),this.element=t.view||ph.ADAPTER.createCanvas(),this.resolution=t.resolution||ph.RESOLUTION,this.autoDensity=!!t.autoDensity}resizeView(t,e){this.element.width=Math.round(t*this.resolution),this.element.height=Math.round(e*this.resolution);const i=this.element.width/this.resolution,s=this.element.height/this.resolution;this.screen.width=i,this.screen.height=s,this.autoDensity&&(this.element.style.width=`${i}px`,this.element.style.height=`${s}px`),this.renderer.emit("resize",i,s),this.renderer.runners.resize.emit(this.screen.width,this.screen.height)}destroy(t){t&&this.element.parentNode?.removeChild(this.element),this.renderer=null,this.element=null,this.screen=null}}sg.defaultOptions={width:800,height:600,resolution:void 0,autoDensity:!1},sg.extension={type:[_p.RendererSystem,_p.CanvasRendererSystem],name:"_view"},Ep.add(sg),ph.PREFER_ENV=Vl.WEBGL2,ph.STRICT_TEXTURE_CACHE=!1,ph.RENDER_OPTIONS={...Zf.defaultOptions,...qf.defaultOptions,...sg.defaultOptions,...Vm.defaultOptions},Object.defineProperties(ph,{WRAP_MODE:{get:()=>Bp.defaultOptions.wrapMode,set(t){dd("7.1.0","settings.WRAP_MODE is deprecated, use BaseTexture.defaultOptions.wrapMode"),Bp.defaultOptions.wrapMode=t}},SCALE_MODE:{get:()=>Bp.defaultOptions.scaleMode,set(t){dd("7.1.0","settings.SCALE_MODE is deprecated, use BaseTexture.defaultOptions.scaleMode"),Bp.defaultOptions.scaleMode=t}},MIPMAP_TEXTURES:{get:()=>Bp.defaultOptions.mipmap,set(t){dd("7.1.0","settings.MIPMAP_TEXTURES is deprecated, use BaseTexture.defaultOptions.mipmap"),Bp.defaultOptions.mipmap=t}},ANISOTROPIC_LEVEL:{get:()=>Bp.defaultOptions.anisotropicLevel,set(t){dd("7.1.0","settings.ANISOTROPIC_LEVEL is deprecated, use BaseTexture.defaultOptions.anisotropicLevel"),Bp.defaultOptions.anisotropicLevel=t}},FILTER_RESOLUTION:{get:()=>(dd("7.1.0","settings.FILTER_RESOLUTION is deprecated, use Filter.defaultResolution"),Vf.defaultResolution),set(t){Vf.defaultResolution=t}},FILTER_MULTISAMPLE:{get:()=>(dd("7.1.0","settings.FILTER_MULTISAMPLE is deprecated, use Filter.defaultMultisample"),Vf.defaultMultisample),set(t){Vf.defaultMultisample=t}},SPRITE_MAX_TEXTURES:{get:()=>jf.defaultMaxTextures,set(t){dd("7.1.0","settings.SPRITE_MAX_TEXTURES is deprecated, use BatchRenderer.defaultMaxTextures"),jf.defaultMaxTextures=t}},SPRITE_BATCH_SIZE:{get:()=>jf.defaultBatchSize,set(t){dd("7.1.0","settings.SPRITE_BATCH_SIZE is deprecated, use BatchRenderer.defaultBatchSize"),jf.defaultBatchSize=t}},CAN_UPLOAD_SAME_BUFFER:{get:()=>jf.canUploadSameBuffer,set(t){dd("7.1.0","settings.CAN_UPLOAD_SAME_BUFFER is deprecated, use BatchRenderer.canUploadSameBuffer"),jf.canUploadSameBuffer=t}},GC_MODE:{get:()=>Qm.defaultMode,set(t){dd("7.1.0","settings.GC_MODE is deprecated, use TextureGCSystem.defaultMode"),Qm.defaultMode=t}},GC_MAX_IDLE:{get:()=>Qm.defaultMaxIdle,set(t){dd("7.1.0","settings.GC_MAX_IDLE is deprecated, use TextureGCSystem.defaultMaxIdle"),Qm.defaultMaxIdle=t}},GC_MAX_CHECK_COUNT:{get:()=>Qm.defaultCheckCountMax,set(t){dd("7.1.0","settings.GC_MAX_CHECK_COUNT is deprecated, use TextureGCSystem.defaultCheckCountMax"),Qm.defaultCheckCountMax=t}},PRECISION_VERTEX:{get:()=>Df.defaultVertexPrecision,set(t){dd("7.1.0","settings.PRECISION_VERTEX is deprecated, use Program.defaultVertexPrecision"),Df.defaultVertexPrecision=t}},PRECISION_FRAGMENT:{get:()=>Df.defaultFragmentPrecision,set(t){dd("7.1.0","settings.PRECISION_FRAGMENT is deprecated, use Program.defaultFragmentPrecision"),Df.defaultFragmentPrecision=t}}});var rg=/* @__PURE__ */(t=>(t[t.INTERACTION=50]="INTERACTION",t[t.HIGH=25]="HIGH",t[t.NORMAL=0]="NORMAL",t[t.LOW=-25]="LOW",t[t.UTILITY=-50]="UTILITY",t))(rg||{});class ng{constructor(t,e=null,i=0,s=!1){this.next=null,this.previous=null,this._destroyed=!1,this.fn=t,this.context=e,this.priority=i,this.once=s}match(t,e=null){return this.fn===t&&this.context===e}emit(t){this.fn&&(this.context?this.fn.call(this.context,t):this.fn(t));const e=this.next;return this.once&&this.destroy(!0),this._destroyed&&(this.next=null),e}connect(t){this.previous=t,t.next&&(t.next.previous=this),this.next=t.next,t.next=this}destroy(t=!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 e=this.next;return this.next=t?null:e,this.previous=null,e}}const og=class t{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 ng(null,null,1/0),this.deltaMS=1/t.targetFPMS,this.elapsedMS=1/t.targetFPMS,this._tick=t=>{this._requestId=null,this.started&&(this.update(t),this.started&&null===this._requestId&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){null===this._requestId&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){null!==this._requestId&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(t,e,i=rg.NORMAL){return this._addListener(new ng(t,e,i))}addOnce(t,e,i=rg.NORMAL){return this._addListener(new ng(t,e,i,!0))}_addListener(t){let e=this._head.next,i=this._head;if(e){for(;e;){if(t.priority>e.priority){t.connect(i);break}i=e,e=e.next}t.previous||t.connect(i)}else t.connect(i);return this._startIfPossible(),this}remove(t,e){let i=this._head.next;for(;i;)i=i.match(t,e)?i.destroy():i.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let t=0,e=this._head;for(;e=e.next;)t++;return t}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let t=this._head.next;for(;t;)t=t.destroy(!0);this._head.destroy(),this._head=null}}update(e=performance.now()){let i;if(e>this.lastTime){if(i=this.elapsedMS=e-this.lastTime,i>this._maxElapsedMS&&(i=this._maxElapsedMS),i*=this.speed,this._minElapsedMS){const t=e-this._lastFrame|0;if(t<this._minElapsedMS)return;this._lastFrame=e-t%this._minElapsedMS}this.deltaMS=i,this.deltaTime=this.deltaMS*t.targetFPMS;const s=this._head;let r=s.next;for(;r;)r=r.emit(this.deltaTime);s.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 i=Math.min(this.maxFPS,e),s=Math.min(Math.max(0,i)/1e3,t.targetFPMS);this._maxElapsedMS=1/s}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(t){if(0===t)this._minElapsedMS=0;else{const e=Math.max(this.minFPS,t);this._minElapsedMS=1/(e/1e3)}}static get shared(){if(!t._shared){const e=t._shared=new t;e.autoStart=!0,e._protected=!0}return t._shared}static get system(){if(!t._system){const e=t._system=new t;e.autoStart=!0,e._protected=!0}return t._system}};og.targetFPMS=.06;let ag=og;Object.defineProperties(ph,{TARGET_FPMS:{get:()=>ag.targetFPMS,set(t){dd("7.1.0","settings.TARGET_FPMS is deprecated, use Ticker.targetFPMS"),ag.targetFPMS=t}}});class lg{static init(t){t=Object.assign({autoStart:!0,sharedTicker:!1},t),Object.defineProperty(this,"ticker",{set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,rg.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=t.sharedTicker?ag.shared:new ag,t.autoStart&&this.start()}static destroy(){if(this._ticker){const t=this._ticker;this.ticker=null,t.destroy()}}}lg.extension=_p.Application,Ep.add(lg);const hg=[];Ep.handleByList(_p.Renderer,hg);class ug{constructor(t){this.renderer=t}contextChange(t){let e;if(1===this.renderer.context.webGLVersion){const i=t.getParameter(t.FRAMEBUFFER_BINDING);t.bindFramebuffer(t.FRAMEBUFFER,null),e=t.getParameter(t.SAMPLES),t.bindFramebuffer(t.FRAMEBUFFER,i)}else{const i=t.getParameter(t.DRAW_FRAMEBUFFER_BINDING);t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),e=t.getParameter(t.SAMPLES),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,i)}e>=ch.HIGH?this.multisample=ch.HIGH:e>=ch.MEDIUM?this.multisample=ch.MEDIUM:e>=ch.LOW?this.multisample=ch.LOW:this.multisample=ch.NONE}destroy(){}}ug.extension={type:_p.RendererSystem,name:"_multisample"},Ep.add(ug);class cg{constructor(t){this.buffer=t||null,this.updateID=-1,this.byteLength=-1,this.refCount=0}}class dg{constructor(t){this.renderer=t,this.managedBuffers={},this.boundBufferBases={}}destroy(){this.renderer=null}contextChange(){this.disposeAll(!0),this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID}bind(t){const{gl:e,CONTEXT_UID:i}=this,s=t._glBuffers[i]||this.createGLBuffer(t);e.bindBuffer(t.type,s.buffer)}unbind(t){const{gl:e}=this;e.bindBuffer(t,null)}bindBufferBase(t,e){const{gl:i,CONTEXT_UID:s}=this;if(this.boundBufferBases[e]!==t){const r=t._glBuffers[s]||this.createGLBuffer(t);this.boundBufferBases[e]=t,i.bindBufferBase(i.UNIFORM_BUFFER,e,r.buffer)}}bindBufferRange(t,e,i){const{gl:s,CONTEXT_UID:r}=this;i=i||0;const n=t._glBuffers[r]||this.createGLBuffer(t);s.bindBufferRange(s.UNIFORM_BUFFER,e||0,n.buffer,256*i,256)}update(t){const{gl:e,CONTEXT_UID:i}=this,s=t._glBuffers[i]||this.createGLBuffer(t);if(t._updateID!==s.updateID)if(s.updateID=t._updateID,e.bindBuffer(t.type,s.buffer),s.byteLength>=t.data.byteLength)e.bufferSubData(t.type,0,t.data);else{const i=t.static?e.STATIC_DRAW:e.DYNAMIC_DRAW;s.byteLength=t.data.byteLength,e.bufferData(t.type,t.data,i)}}dispose(t,e){if(!this.managedBuffers[t.id])return;delete this.managedBuffers[t.id];const i=t._glBuffers[this.CONTEXT_UID],s=this.gl;t.disposeRunner.remove(this),i&&(e||s.deleteBuffer(i.buffer),delete t._glBuffers[this.CONTEXT_UID])}disposeAll(t){const e=Object.keys(this.managedBuffers);for(let i=0;i<e.length;i++)this.dispose(this.managedBuffers[e[i]],t)}createGLBuffer(t){const{CONTEXT_UID:e,gl:i}=this;return t._glBuffers[e]=new cg(i.createBuffer()),this.managedBuffers[t.id]=t,t.disposeRunner.add(this),t._glBuffers[e]}}dg.extension={type:_p.RendererSystem,name:"buffer"},Ep.add(dg);class pg{constructor(t){this.renderer=t}render(t,e){const i=this.renderer;let s,r,n,o;if(e&&(s=e.renderTexture,r=e.clear,n=e.transform,o=e.skipUpdateTransform),this.renderingToScreen=!s,i.runners.prerender.emit(),i.emit("prerender"),i.projection.transform=n,!i.context.isLost){if(s||(this.lastObjectRendered=t),!o){const e=t.enableTempParent();t.updateTransform(),t.disableTempParent(e)}i.renderTexture.bind(s),i.batch.currentRenderer.start(),(r??i.background.clearBeforeRender)&&i.renderTexture.clear(),t.render(i),i.batch.currentRenderer.flush(),s&&(e.blit&&i.framebuffer.blit(),s.baseTexture.update()),i.runners.postrender.emit(),i.projection.transform=null,i.emit("postrender")}}destroy(){this.renderer=null,this.lastObjectRendered=null}}pg.extension={type:_p.RendererSystem,name:"objectRenderer"},Ep.add(pg);const fg=class t extends Km{constructor(e){super(),this.type=ql.WEBGL,e=Object.assign({},ph.RENDER_OPTIONS,e),this.gl=null,this.CONTEXT_UID=0,this.globalUniforms=new Gf({projectionMatrix:new nf},!0);const i={runners:["init","destroy","contextChange","resolutionChange","reset","update","postrender","prerender","resize"],systems:t.__systems,priority:["_view","textureGenerator","background","_plugin","startup","context","state","texture","buffer","geometry","framebuffer","transformFeedback","mask","scissor","stencil","projection","textureGC","filter","renderTexture","batch","objectRenderer","_multisample"]};this.setup(i),"useContextAlpha"in e&&(dd("7.0.0","options.useContextAlpha is deprecated, use options.premultipliedAlpha and options.backgroundAlpha instead"),e.premultipliedAlpha=e.useContextAlpha&&"notMultiplied"!==e.useContextAlpha,e.backgroundAlpha=!1===e.useContextAlpha?1:e.backgroundAlpha),this._plugin.rendererPlugins=t.__plugins,this.options=e,this.startup.run(this.options)}static test(t){return!t?.forceCanvas&&xd()}render(t,e){this.objectRenderer.render(t,e)}resize(t,e){this._view.resizeView(t,e)}reset(){return this.runners.reset.emit(),this}clear(){this.renderTexture.bind(),this.renderTexture.clear()}destroy(t=!1){this.runners.destroy.items.reverse(),this.emitWithCustomOptions(this.runners.destroy,{_view:t}),super.destroy()}get plugins(){return this._plugin.plugins}get multisample(){return this._multisample.multisample}get width(){return this._view.element.width}get height(){return this._view.element.height}get resolution(){return this._view.resolution}set resolution(t){this._view.resolution=t,this.runners.resolutionChange.emit(t)}get autoDensity(){return this._view.autoDensity}get view(){return this._view.element}get screen(){return this._view.screen}get lastObjectRendered(){return this.objectRenderer.lastObjectRendered}get renderingToScreen(){return this.objectRenderer.renderingToScreen}get rendererLogId(){return`WebGL ${this.context.webGLVersion}`}get clearBeforeRender(){return dd("7.0.0","renderer.clearBeforeRender has been deprecated, please use renderer.background.clearBeforeRender instead."),this.background.clearBeforeRender}get useContextAlpha(){return dd("7.0.0","renderer.useContextAlpha has been deprecated, please use renderer.context.premultipliedAlpha instead."),this.context.useContextAlpha}get preserveDrawingBuffer(){return dd("7.0.0","renderer.preserveDrawingBuffer has been deprecated, we cannot truly know this unless pixi created the context"),this.context.preserveDrawingBuffer}get backgroundColor(){return dd("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color}set backgroundColor(t){dd("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color=t}get backgroundAlpha(){return dd("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha}set backgroundAlpha(t){dd("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha=t}get powerPreference(){return dd("7.0.0","renderer.powerPreference has been deprecated, we can only know this if pixi creates the context"),this.context.powerPreference}generateTexture(t,e){return this.textureGenerator.generateTexture(t,e)}};fg.extension={type:_p.Renderer,priority:1},fg.__plugins={},fg.__systems={};let mg=fg;Ep.handleByMap(_p.RendererPlugin,mg.__plugins),Ep.handleByMap(_p.RendererSystem,mg.__systems),Ep.add(mg);class gg extends Np{constructor(t,e){const{width:i,height:s}=e||{};super(i,s),this.items=[],this.itemDirtyIds=[];for(let r=0;r<t;r++){const t=new Bp;this.items.push(t),this.itemDirtyIds.push(-2)}this.length=t,this._load=null,this.baseTexture=null}initFromArray(t,e){for(let i=0;i<this.length;i++)t[i]&&(t[i].castToBaseTexture?this.addBaseTextureAt(t[i].castToBaseTexture(),i):t[i]instanceof Np?this.addResourceAt(t[i],i):this.addResourceAt(Mp(t[i],e),i))}dispose(){for(let t=0,e=this.length;t<e;t++)this.items[t].destroy();this.items=null,this.itemDirtyIds=null,this._load=null}addResourceAt(t,e){if(!this.items[e])throw new Error(`Index ${e} is out of bounds`);return t.valid&&!this.valid&&this.resize(t.width,t.height),this.items[e].setResource(t),this}bind(t){if(null!==this.baseTexture)throw new Error("Only one base texture per TextureArray is allowed");super.bind(t);for(let e=0;e<this.length;e++)this.items[e].parentTextureArray=t,this.items[e].on("update",t.update,t)}unbind(t){super.unbind(t);for(let e=0;e<this.length;e++)this.items[e].parentTextureArray=null,this.items[e].off("update",t.update,t)}load(){if(this._load)return this._load;const t=this.items.map(t=>t.resource).filter(t=>t).map(t=>t.load());return this._load=Promise.all(t).then(()=>{const{realWidth:t,realHeight:e}=this.items[0];return this.resize(t,e),this.update(),Promise.resolve(this)}),this._load}}class yg extends em{constructor(t){super(t)}static test(t){const{OffscreenCanvas:e}=globalThis;return!!(e&&t instanceof e)||globalThis.HTMLCanvasElement&&t instanceof HTMLCanvasElement}}const vg=class t extends gg{constructor(e,i){const{width:s,height:r,autoLoad:n,linkBaseTexture:o}=i||{};if(e&&e.length!==t.SIDES)throw new Error(`Invalid length. Got ${e.length}, expected 6`);super(6,{width:s,height:r});for(let a=0;a<t.SIDES;a++)this.items[a].target=th.TEXTURE_CUBE_MAP_POSITIVE_X+a;this.linkBaseTexture=!1!==o,e&&this.initFromArray(e,i),!1!==n&&this.load()}bind(t){super.bind(t),t.target=th.TEXTURE_CUBE_MAP}addBaseTextureAt(t,e,i){if(void 0===i&&(i=this.linkBaseTexture),!this.items[e])throw new Error(`Index ${e} is out of bounds`);if(!this.linkBaseTexture||t.parentTextureArray||Object.keys(t._glTextures).length>0){if(!t.resource)throw new Error("CubeResource does not support copying of renderTexture.");this.addResourceAt(t.resource,e)}else t.target=th.TEXTURE_CUBE_MAP_POSITIVE_X+e,t.parentTextureArray=this.baseTexture,this.items[e]=t;return t.valid&&!this.valid&&this.resize(t.realWidth,t.realHeight),this.items[e]=t,this}upload(e,i,s){const r=this.itemDirtyIds;for(let n=0;n<t.SIDES;n++){const t=this.items[n];(r[n]<t.dirtyId||s.dirtyId<i.dirtyId)&&(t.valid&&t.resource?(t.resource.upload(e,t,s),r[n]=t.dirtyId):r[n]<-1&&(e.gl.texImage2D(t.target,0,s.internalFormat,i.realWidth,i.realHeight,0,i.format,s.type,null),r[n]=-1))}return!0}static test(e){return Array.isArray(e)&&e.length===t.SIDES}};vg.SIDES=6;let xg=vg;class bg extends em{constructor(t,e){let i,s,r;e=e||{},"string"==typeof t?(i=bg.EMPTY,s=t,r=!0):(i=t,s=null,r=!1),super(i),this.url=s,this.crossOrigin=e.crossOrigin??!0,this.alphaMode="number"==typeof e.alphaMode?e.alphaMode:null,this.ownsImageBitmap=e.ownsImageBitmap??r,this._load=null,!1!==e.autoLoad&&this.load()}load(){return this._load||(this._load=new Promise(async(t,e)=>{if(null!==this.url)try{const e=await ph.ADAPTER.fetch(this.url,{mode:this.crossOrigin?"cors":"no-cors"});if(this.destroyed)return;const i=await e.blob();if(this.destroyed)return;const s=await createImageBitmap(i,{premultiplyAlpha:null===this.alphaMode||this.alphaMode===oh.UNPACK?"premultiply":"none"});if(this.destroyed)return void s.close();this.source=s,this.update(),t(this)}catch(i){if(this.destroyed)return;e(i),this.onError.emit(i)}else t(this)})),this._load}upload(t,e,i){return this.source instanceof ImageBitmap?("number"==typeof this.alphaMode&&(e.alphaMode=this.alphaMode),super.upload(t,e,i)):(this.load(),!1)}dispose(){this.ownsImageBitmap&&this.source instanceof ImageBitmap&&this.source.close(),super.dispose(),this._load=null}static test(t){return!!globalThis.createImageBitmap&&typeof ImageBitmap<"u"&&("string"==typeof t||t instanceof ImageBitmap)}static get EMPTY(){return bg._EMPTY=bg._EMPTY??ph.ADAPTER.createCanvas(0,0),bg._EMPTY}}const _g=class t extends em{constructor(t,e){e=e||{},super(ph.ADAPTER.createCanvas()),this._width=0,this._height=0,this.svg=t,this.scale=e.scale||1,this._overrideWidth=e.width,this._overrideHeight=e.height,this._resolve=null,this._crossorigin=e.crossorigin,this._load=null,!1!==e.autoLoad&&this.load()}load(){return this._load||(this._load=new Promise(e=>{if(this._resolve=()=>{this.update(),e(this)},t.SVG_XML.test(this.svg.trim())){if(!btoa)throw new Error("Your browser doesn't support base64 conversions.");this.svg=`data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(this.svg)))}`}this._loadSvg()})),this._load}_loadSvg(){const t=new Image;em.crossOrigin(t,this.svg,this._crossorigin),t.src=this.svg,t.onerror=e=>{this._resolve&&(t.onerror=null,this.onError.emit(e))},t.onload=()=>{if(!this._resolve)return;const e=t.width,i=t.height;if(!e||!i)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");let s=e*this.scale,r=i*this.scale;(this._overrideWidth||this._overrideHeight)&&(s=this._overrideWidth||this._overrideHeight/i*e,r=this._overrideHeight||this._overrideWidth/e*i),s=Math.round(s),r=Math.round(r);const n=this.source;n.width=s,n.height=r,n._pixiId=`canvas_${op()}`,n.getContext("2d").drawImage(t,0,0,e,i,0,0,s,r),this._resolve(),this._resolve=null}}static getSize(e){const i=t.SVG_SIZE.exec(e),s={};return i&&(s[i[1]]=Math.round(parseFloat(i[3])),s[i[5]]=Math.round(parseFloat(i[7]))),s}dispose(){super.dispose(),this._resolve=null,this._crossorigin=null}static test(e,i){return"svg"===i||"string"==typeof e&&e.startsWith("data:image/svg+xml")||"string"==typeof e&&t.SVG_XML.test(e)}};_g.SVG_XML=/^(<\?xml[^?]+\?>)?\s*(<!--[^(-->)]*-->)?\s*\<svg/m,_g.SVG_SIZE=/<svg[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i;let wg=_g;const Pg=class t extends em{constructor(e,i){if(i=i||{},!(e instanceof HTMLVideoElement)){const s=document.createElement("video");!1!==i.autoLoad&&s.setAttribute("preload","auto"),!1!==i.playsinline&&(s.setAttribute("webkit-playsinline",""),s.setAttribute("playsinline","")),!0===i.muted&&(s.setAttribute("muted",""),s.muted=!0),!0===i.loop&&s.setAttribute("loop",""),!1!==i.autoPlay&&s.setAttribute("autoplay",""),"string"==typeof e&&(e=[e]);const r=e[0].src||e[0];em.crossOrigin(s,r,i.crossorigin);for(let i=0;i<e.length;++i){const r=document.createElement("source");let{src:n,mime:o}=e[i];if(n=n||e[i],n.startsWith("data:"))o=n.slice(5,n.indexOf(";"));else if(!n.startsWith("blob:")){const e=n.split("?").shift().toLowerCase(),i=e.slice(e.lastIndexOf(".")+1);o=o||t.MIME_TYPES[i]||`video/${i}`}r.src=n,o&&(r.type=o),s.appendChild(r)}e=s}super(e),this.noSubImage=!0,this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=i.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=!1!==i.autoPlay,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._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),!1!==i.autoLoad&&this.load()}update(t=0){if(!this.destroyed){if(this._updateFPS){const t=ag.shared.elapsedMS*this.source.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-t)}(!this._updateFPS||this._msToNextUpdate<=0)&&(super.update(),this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0)}}_videoFrameRequestCallback(){this.update(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.source.requestVideoFrameCallback(this._videoFrameRequestCallback)}load(){if(this._load)return this._load;const t=this.source;return(t.readyState===t.HAVE_ENOUGH_DATA||t.readyState===t.HAVE_FUTURE_DATA)&&t.width&&t.height&&(t.complete=!0),t.addEventListener("play",this._onPlayStart),t.addEventListener("pause",this._onPlayStop),t.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._onCanPlay():(t.addEventListener("canplay",this._onCanPlay),t.addEventListener("canplaythrough",this._onCanPlay),t.addEventListener("error",this._onError,!0)),this._load=new Promise((e,i)=>{this.valid?e(this):(this._resolve=e,this._reject=i,t.load())}),this._load}_onError(t){this.source.removeEventListener("error",this._onError,!0),this.onError.emit(t),this._reject&&(this._reject(t),this._reject=null,this._resolve=null)}_isSourcePlaying(){const t=this.source;return!t.paused&&!t.ended}_isSourceReady(){return this.source.readyState>2}_onPlayStart(){this.valid||this._onCanPlay(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.update(),this._msToNextUpdate=0)}_onCanPlay(){const t=this.source;t.removeEventListener("canplay",this._onCanPlay),t.removeEventListener("canplaythrough",this._onCanPlay);const e=this.valid;this._msToNextUpdate=0,this.update(),this._msToNextUpdate=0,!e&&this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&t.play()}dispose(){this._configureAutoUpdate();const t=this.source;t&&(t.removeEventListener("play",this._onPlayStart),t.removeEventListener("pause",this._onPlayStop),t.removeEventListener("seeked",this._onSeeked),t.removeEventListener("canplay",this._onCanPlay),t.removeEventListener("canplaythrough",this._onCanPlay),t.removeEventListener("error",this._onError,!0),t.pause(),t.src="",t.load()),super.dispose()}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){t!==this._autoUpdate&&(this._autoUpdate=t,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(t){t!==this._updateFPS&&(this._updateFPS=t,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.source.requestVideoFrameCallback?(this._isConnectedToTicker&&(ag.shared.remove(this.update,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),null===this._videoFrameRequestCallbackHandle&&(this._videoFrameRequestCallbackHandle=this.source.requestVideoFrameCallback(this._videoFrameRequestCallback))):(null!==this._videoFrameRequestCallbackHandle&&(this.source.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(ag.shared.add(this.update,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(null!==this._videoFrameRequestCallbackHandle&&(this.source.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(ag.shared.remove(this.update,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e,i){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement||t.TYPES.includes(i)}};Pg.TYPES=["mp4","m4v","webm","ogg","ogv","h264","avi","mov"],Pg.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Eg=Pg;Cp.push(bg,im,yg,Eg,class extends em{constructor(t){super(t)}static test(t){return!!globalThis.VideoFrame&&t instanceof globalThis.VideoFrame}},wg,Lp,xg,class extends gg{constructor(t,e){const{width:i,height:s}=e||{};let r,n;Array.isArray(t)?(r=t,n=t.length):n=t,super(n,{width:i,height:s}),r&&this.initFromArray(r,e)}addBaseTextureAt(t,e){if(!t.resource)throw new Error("ArrayResource does not support RenderTexture");return this.addResourceAt(t.resource,e),this}bind(t){super.bind(t),t.target=th.TEXTURE_2D_ARRAY}upload(t,e,i){const{length:s,itemDirtyIds:r,items:n}=this,{gl:o}=t;i.dirtyId<0&&o.texImage3D(o.TEXTURE_2D_ARRAY,0,i.internalFormat,this._width,this._height,s,0,e.format,i.type,null);for(let a=0;a<s;a++){const t=n[a];r[a]<t.dirtyId&&(r[a]=t.dirtyId,t.valid&&o.texSubImage3D(o.TEXTURE_2D_ARRAY,0,0,0,a,t.resource.width,t.resource.height,1,e.format,i.type,t.resource.source))}return!0}});class Tg{constructor(){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.rect=null,this.updateID=-1}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}clear(){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0}getRectangle(t){return this.minX>this.maxX||this.minY>this.maxY?Qp.EMPTY:((t=t||new Qp(0,0,1,1)).x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)}addPoint(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)}addPointMatrix(t,e){const{a:i,b:s,c:r,d:n,tx:o,ty:a}=t,l=i*e.x+r*e.y+o,h=s*e.x+n*e.y+a;this.minX=Math.min(this.minX,l),this.maxX=Math.max(this.maxX,l),this.minY=Math.min(this.minY,h),this.maxY=Math.max(this.maxY,h)}addQuad(t){let e=this.minX,i=this.minY,s=this.maxX,r=this.maxY,n=t[0],o=t[1];e=n<e?n:e,i=o<i?o:i,s=n>s?n:s,r=o>r?o:r,n=t[2],o=t[3],e=n<e?n:e,i=o<i?o:i,s=n>s?n:s,r=o>r?o:r,n=t[4],o=t[5],e=n<e?n:e,i=o<i?o:i,s=n>s?n:s,r=o>r?o:r,n=t[6],o=t[7],e=n<e?n:e,i=o<i?o:i,s=n>s?n:s,r=o>r?o:r,this.minX=e,this.minY=i,this.maxX=s,this.maxY=r}addFrame(t,e,i,s,r){this.addFrameMatrix(t.worldTransform,e,i,s,r)}addFrameMatrix(t,e,i,s,r){const n=t.a,o=t.b,a=t.c,l=t.d,h=t.tx,u=t.ty;let c=this.minX,d=this.minY,p=this.maxX,f=this.maxY,m=n*e+a*i+h,g=o*e+l*i+u;c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,m=n*s+a*i+h,g=o*s+l*i+u,c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,m=n*e+a*r+h,g=o*e+l*r+u,c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,m=n*s+a*r+h,g=o*s+l*r+u,c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,this.minX=c,this.minY=d,this.maxX=p,this.maxY=f}addVertexData(t,e,i){let s=this.minX,r=this.minY,n=this.maxX,o=this.maxY;for(let a=e;a<i;a+=2){const e=t[a],i=t[a+1];s=e<s?e:s,r=i<r?i:r,n=e>n?e:n,o=i>o?i:o}this.minX=s,this.minY=r,this.maxX=n,this.maxY=o}addVertices(t,e,i,s){this.addVerticesMatrix(t.worldTransform,e,i,s)}addVerticesMatrix(t,e,i,s,r=0,n=r){const o=t.a,a=t.b,l=t.c,h=t.d,u=t.tx,c=t.ty;let d=this.minX,p=this.minY,f=this.maxX,m=this.maxY;for(let g=i;g<s;g+=2){const t=e[g],i=e[g+1],s=o*t+l*i+u,y=h*i+a*t+c;d=Math.min(d,s-r),f=Math.max(f,s+r),p=Math.min(p,y-n),m=Math.max(m,y+n)}this.minX=d,this.minY=p,this.maxX=f,this.maxY=m}addBounds(t){const e=this.minX,i=this.minY,s=this.maxX,r=this.maxY;this.minX=t.minX<e?t.minX:e,this.minY=t.minY<i?t.minY:i,this.maxX=t.maxX>s?t.maxX:s,this.maxY=t.maxY>r?t.maxY:r}addBoundsMask(t,e){const i=t.minX>e.minX?t.minX:e.minX,s=t.minY>e.minY?t.minY:e.minY,r=t.maxX<e.maxX?t.maxX:e.maxX,n=t.maxY<e.maxY?t.maxY:e.maxY;if(i<=r&&s<=n){const t=this.minX,e=this.minY,o=this.maxX,a=this.maxY;this.minX=i<t?i:t,this.minY=s<e?s:e,this.maxX=r>o?r:o,this.maxY=n>a?n:a}}addBoundsMatrix(t,e){this.addFrameMatrix(e,t.minX,t.minY,t.maxX,t.maxY)}addBoundsArea(t,e){const i=t.minX>e.x?t.minX:e.x,s=t.minY>e.y?t.minY:e.y,r=t.maxX<e.x+e.width?t.maxX:e.x+e.width,n=t.maxY<e.y+e.height?t.maxY:e.y+e.height;if(i<=r&&s<=n){const t=this.minX,e=this.minY,o=this.maxX,a=this.maxY;this.minX=i<t?i:t,this.minY=s<e?s:e,this.maxX=r>o?r:o,this.maxY=n>a?n:a}}pad(t=0,e=t){this.isEmpty()||(this.minX-=t,this.maxX+=t,this.minY-=e,this.maxY+=e)}addFramePad(t,e,i,s,r,n){t-=r,e-=n,i+=r,s+=n,this.minX=this.minX<t?this.minX:t,this.maxX=this.maxX>i?this.maxX:i,this.minY=this.minY<e?this.minY:e,this.maxY=this.maxY>s?this.maxY:s}}class Ag extends kh{constructor(){super(),this.tempDisplayObjectParent=null,this.transform=new gf,this.alpha=1,this.visible=!0,this.renderable=!0,this.cullable=!1,this.cullArea=null,this.parent=null,this.worldAlpha=1,this._lastSortedIndex=0,this._zIndex=0,this.filterArea=null,this.filters=null,this._enabledFilters=null,this._bounds=new Tg,this._localBounds=null,this._boundsID=0,this._boundsRect=null,this._localBoundsRect=null,this._mask=null,this._maskRefCount=0,this._destroyed=!1,this.isSprite=!1,this.isMask=!1}static mixin(t){const e=Object.keys(t);for(let i=0;i<e.length;++i){const s=e[i];Object.defineProperty(Ag.prototype,s,Object.getOwnPropertyDescriptor(t,s))}}get destroyed(){return this._destroyed}_recursivePostUpdateTransform(){this.parent?(this.parent._recursivePostUpdateTransform(),this.transform.updateTransform(this.parent.transform)):this.transform.updateTransform(this._tempDisplayObjectParent.transform)}updateTransform(){this._boundsID++,this.transform.updateTransform(this.parent.transform),this.worldAlpha=this.alpha*this.parent.worldAlpha}getBounds(t,e){return t||(this.parent?(this._recursivePostUpdateTransform(),this.updateTransform()):(this.parent=this._tempDisplayObjectParent,this.updateTransform(),this.parent=null)),this._bounds.updateID!==this._boundsID&&(this.calculateBounds(),this._bounds.updateID=this._boundsID),e||(this._boundsRect||(this._boundsRect=new Qp),e=this._boundsRect),this._bounds.getRectangle(e)}getLocalBounds(t){t||(this._localBoundsRect||(this._localBoundsRect=new Qp),t=this._localBoundsRect),this._localBounds||(this._localBounds=new Tg);const e=this.transform,i=this.parent;this.parent=null,this._tempDisplayObjectParent.worldAlpha=i?.worldAlpha??1,this.transform=this._tempDisplayObjectParent.transform;const s=this._bounds,r=this._boundsID;this._bounds=this._localBounds;const n=this.getBounds(!1,t);return this.parent=i,this.transform=e,this._bounds=s,this._bounds.updateID+=this._boundsID-r,n}toGlobal(t,e,i=!1){return i||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)}toLocal(t,e,i,s){return e&&(t=e.toGlobal(t,i,s)),s||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,i)}setParent(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t}removeFromParent(){this.parent?.removeChild(this)}setTransform(t=0,e=0,i=1,s=1,r=0,n=0,o=0,a=0,l=0){return this.position.x=t,this.position.y=e,this.scale.x=i||1,this.scale.y=s||1,this.rotation=r,this.skew.x=n,this.skew.y=o,this.pivot.x=a,this.pivot.y=l,this}destroy(t){this.removeFromParent(),this._destroyed=!0,this.transform=null,this.parent=null,this._bounds=null,this.mask=null,this.cullArea=null,this.filters=null,this.filterArea=null,this.hitArea=null,this.eventMode="auto",this.interactiveChildren=!1,this.emit("destroyed"),this.removeAllListeners()}get _tempDisplayObjectParent(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new Ig),this.tempDisplayObjectParent}enableTempParent(){const t=this.parent;return this.parent=this._tempDisplayObjectParent,t}disableTempParent(t){this.parent=t}get x(){return this.position.x}set x(t){this.transform.position.x=t}get y(){return this.position.y}set y(t){this.transform.position.y=t}get worldTransform(){return this.transform.worldTransform}get localTransform(){return this.transform.localTransform}get position(){return this.transform.position}set position(t){this.transform.position.copyFrom(t)}get scale(){return this.transform.scale}set scale(t){this.transform.scale.copyFrom(t)}get pivot(){return this.transform.pivot}set pivot(t){this.transform.pivot.copyFrom(t)}get skew(){return this.transform.skew}set skew(t){this.transform.skew.copyFrom(t)}get rotation(){return this.transform.rotation}set rotation(t){this.transform.rotation=t}get angle(){return this.transform.rotation*Vp}set angle(t){this.transform.rotation=t*qp}get zIndex(){return this._zIndex}set zIndex(t){this._zIndex!==t&&(this._zIndex=t,this.parent&&(this.parent.sortDirty=!0))}get worldVisible(){let t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}get mask(){return this._mask}set mask(t){if(this._mask!==t){if(this._mask){const t=this._mask.isMaskData?this._mask.maskObject:this._mask;t&&(t._maskRefCount--,0===t._maskRefCount&&(t.renderable=!0,t.isMask=!1))}if(this._mask=t,this._mask){const t=this._mask.isMaskData?this._mask.maskObject:this._mask;t&&(0===t._maskRefCount&&(t.renderable=!1,t.isMask=!0),t._maskRefCount++)}}}}class Ig extends Ag{constructor(){super(...arguments),this.sortDirty=null}}Ag.prototype.displayObjectUpdateTransform=Ag.prototype.updateTransform;const Sg=new nf;function Cg(t,e){return t.zIndex===e.zIndex?t._lastSortedIndex-e._lastSortedIndex:t.zIndex-e.zIndex}const Mg=class t extends Ag{constructor(){super(),this.children=[],this.sortableChildren=t.defaultSortableChildren,this.sortDirty=!1}onChildrenChange(t){}addChild(...t){if(t.length>1)for(let e=0;e<t.length;e++)this.addChild(t[e]);else{const e=t[0];e.parent&&e.parent.removeChild(e),e.parent=this,this.sortDirty=!0,e.transform._parentID=-1,this.children.push(e),this._boundsID++,this.onChildrenChange(this.children.length-1),this.emit("childAdded",e,this,this.children.length-1),e.emit("added",this)}return t[0]}addChildAt(t,e){if(e<0||e>this.children.length)throw new Error(`${t}addChildAt: The index ${e} supplied is out of bounds ${this.children.length}`);return t.parent&&t.parent.removeChild(t),t.parent=this,this.sortDirty=!0,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),this.emit("childAdded",t,this,e),t}swapChildren(t,e){if(t===e)return;const i=this.getChildIndex(t),s=this.getChildIndex(e);this.children[i]=e,this.children[s]=t,this.onChildrenChange(i<s?i:s)}getChildIndex(t){const e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e}setChildIndex(t,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);const i=this.getChildIndex(t);sp(this.children,i,1),this.children.splice(e,0,t),this.onChildrenChange(e)}getChildAt(t){if(t<0||t>=this.children.length)throw new Error(`getChildAt: Index (${t}) does not exist.`);return this.children[t]}removeChild(...t){if(t.length>1)for(let e=0;e<t.length;e++)this.removeChild(t[e]);else{const e=t[0],i=this.children.indexOf(e);if(-1===i)return null;e.parent=null,e.transform._parentID=-1,sp(this.children,i,1),this._boundsID++,this.onChildrenChange(i),e.emit("removed",this),this.emit("childRemoved",e,this,i)}return t[0]}removeChildAt(t){const e=this.getChildAt(t);return e.parent=null,e.transform._parentID=-1,sp(this.children,t,1),this._boundsID++,this.onChildrenChange(t),e.emit("removed",this),this.emit("childRemoved",e,this,t),e}removeChildren(t=0,e=this.children.length){const i=t,s=e-i;let r;if(s>0&&s<=e){r=this.children.splice(i,s);for(let t=0;t<r.length;++t)r[t].parent=null,r[t].transform&&(r[t].transform._parentID=-1);this._boundsID++,this.onChildrenChange(t);for(let t=0;t<r.length;++t)r[t].emit("removed",this),this.emit("childRemoved",r[t],this,t);return r}if(0===s&&0===this.children.length)return[];throw new RangeError("removeChildren: numeric values are outside the acceptable range.")}sortChildren(){let t=!1;for(let e=0,i=this.children.length;e<i;++e){const i=this.children[e];i._lastSortedIndex=e,!t&&0!==i.zIndex&&(t=!0)}t&&this.children.length>1&&this.children.sort(Cg),this.sortDirty=!1}updateTransform(){this.sortableChildren&&this.sortDirty&&this.sortChildren(),this._boundsID++,this.transform.updateTransform(this.parent.transform),this.worldAlpha=this.alpha*this.parent.worldAlpha;for(let t=0,e=this.children.length;t<e;++t){const e=this.children[t];e.visible&&e.updateTransform()}}calculateBounds(){this._bounds.clear(),this._calculateBounds();for(let t=0;t<this.children.length;t++){const e=this.children[t];if(e.visible&&e.renderable)if(e.calculateBounds(),e._mask){const t=e._mask.isMaskData?e._mask.maskObject:e._mask;t?(t.calculateBounds(),this._bounds.addBoundsMask(e._bounds,t._bounds)):this._bounds.addBounds(e._bounds)}else e.filterArea?this._bounds.addBoundsArea(e._bounds,e.filterArea):this._bounds.addBounds(e._bounds)}this._bounds.updateID=this._boundsID}getLocalBounds(t,e=!1){const i=super.getLocalBounds(t);if(!e)for(let s=0,r=this.children.length;s<r;++s){const t=this.children[s];t.visible&&t.updateTransform()}return i}_calculateBounds(){}_renderWithCulling(e){const i=e.renderTexture.sourceFrame;if(!(i.width>0&&i.height>0))return;let s,r;this.cullArea?(s=this.cullArea,r=this.worldTransform):this._render!==t.prototype._render&&(s=this.getBounds(!0));const n=e.projection.transform;if(n&&(r?(r=Sg.copyFrom(r),r.prepend(n)):r=n),s&&i.intersects(s,r))this._render(e);else if(this.cullArea)return;for(let t=0,o=this.children.length;t<o;++t){const i=this.children[t],s=i.cullable;i.cullable=s||!this.cullArea,i.render(e),i.cullable=s}}render(t){if(this.visible&&!(this.worldAlpha<=0)&&this.renderable)if(this._mask||this.filters?.length)this.renderAdvanced(t);else if(this.cullable)this._renderWithCulling(t);else{this._render(t);for(let e=0,i=this.children.length;e<i;++e)this.children[e].render(t)}}renderAdvanced(t){const e=this.filters,i=this._mask;if(e){this._enabledFilters||(this._enabledFilters=[]),this._enabledFilters.length=0;for(let t=0;t<e.length;t++)e[t].enabled&&this._enabledFilters.push(e[t])}const s=e&&this._enabledFilters?.length||i&&(!i.isMaskData||i.enabled&&(i.autoDetect||i.type!==uh.NONE));if(s&&t.batch.flush(),e&&this._enabledFilters?.length&&t.filter.push(this,this._enabledFilters),i&&t.mask.push(this,this._mask),this.cullable)this._renderWithCulling(t);else{this._render(t);for(let e=0,i=this.children.length;e<i;++e)this.children[e].render(t)}s&&t.batch.flush(),i&&t.mask.pop(this),e&&this._enabledFilters?.length&&t.filter.pop()}_render(t){}destroy(t){super.destroy(),this.sortDirty=!1;const e="boolean"==typeof t?t:t?.children,i=this.removeChildren(0,this.children.length);if(e)for(let s=0;s<i.length;++s)i[s].destroy(t)}get width(){return this.scale.x*this.getLocalBounds().width}set width(t){const e=this.getLocalBounds().width;this.scale.x=0!==e?t/e:1,this._width=t}get height(){return this.scale.y*this.getLocalBounds().height}set height(t){const e=this.getLocalBounds().height;this.scale.y=0!==e?t/e:1,this._height=t}};Mg.defaultSortableChildren=!1;let Og=Mg;Og.prototype.containerUpdateTransform=Og.prototype.updateTransform,Object.defineProperties(ph,{SORTABLE_CHILDREN:{get:()=>Og.defaultSortableChildren,set(t){dd("7.1.0","settings.SORTABLE_CHILDREN is deprecated, use Container.defaultSortableChildren"),Og.defaultSortableChildren=t}}});const Ng=new Kp,Lg=new Uint16Array([0,1,2,0,2,3]);class Rg extends Og{constructor(t){super(),this._anchor=new ff(this._onAnchorUpdate,this,t?t.defaultAnchor.x:0,t?t.defaultAnchor.y:0),this._texture=null,this._width=0,this._height=0,this._tintColor=new qd(16777215),this._tintRGB=null,this.tint=16777215,this.blendMode=Kl.NORMAL,this._cachedTint=16777215,this.uvs=null,this.texture=t||om.EMPTY,this.vertexData=new Float32Array(8),this.vertexTrimmedData=null,this._transformID=-1,this._textureID=-1,this._transformTrimmedID=-1,this._textureTrimmedID=-1,this.indices=Lg,this.pluginName="batch",this.isSprite=!0,this._roundPixels=ph.ROUND_PIXELS}_onTextureUpdate(){this._textureID=-1,this._textureTrimmedID=-1,this._cachedTint=16777215,this._width&&(this.scale.x=rp(this.scale.x)*this._width/this._texture.orig.width),this._height&&(this.scale.y=rp(this.scale.y)*this._height/this._texture.orig.height)}_onAnchorUpdate(){this._transformID=-1,this._transformTrimmedID=-1}calculateVertices(){const t=this._texture;if(this._transformID===this.transform._worldID&&this._textureID===t._updateID)return;this._textureID!==t._updateID&&(this.uvs=this._texture._uvs.uvsFloat32),this._transformID=this.transform._worldID,this._textureID=t._updateID;const e=this.transform.worldTransform,i=e.a,s=e.b,r=e.c,n=e.d,o=e.tx,a=e.ty,l=this.vertexData,h=t.trim,u=t.orig,c=this._anchor;let d=0,p=0,f=0,m=0;if(h?(p=h.x-c._x*u.width,d=p+h.width,m=h.y-c._y*u.height,f=m+h.height):(p=-c._x*u.width,d=p+u.width,m=-c._y*u.height,f=m+u.height),l[0]=i*p+r*m+o,l[1]=n*m+s*p+a,l[2]=i*d+r*m+o,l[3]=n*m+s*d+a,l[4]=i*d+r*f+o,l[5]=n*f+s*d+a,l[6]=i*p+r*f+o,l[7]=n*f+s*p+a,this._roundPixels){const t=ph.RESOLUTION;for(let e=0;e<l.length;++e)l[e]=Math.round(l[e]*t)/t}}calculateTrimmedVertices(){if(this.vertexTrimmedData){if(this._transformTrimmedID===this.transform._worldID&&this._textureTrimmedID===this._texture._updateID)return}else this.vertexTrimmedData=new Float32Array(8);this._transformTrimmedID=this.transform._worldID,this._textureTrimmedID=this._texture._updateID;const t=this._texture,e=this.vertexTrimmedData,i=t.orig,s=this._anchor,r=this.transform.worldTransform,n=r.a,o=r.b,a=r.c,l=r.d,h=r.tx,u=r.ty,c=-s._x*i.width,d=c+i.width,p=-s._y*i.height,f=p+i.height;if(e[0]=n*c+a*p+h,e[1]=l*p+o*c+u,e[2]=n*d+a*p+h,e[3]=l*p+o*d+u,e[4]=n*d+a*f+h,e[5]=l*f+o*d+u,e[6]=n*c+a*f+h,e[7]=l*f+o*c+u,this._roundPixels){const t=ph.RESOLUTION;for(let i=0;i<e.length;++i)e[i]=Math.round(e[i]*t)/t}}_render(t){this.calculateVertices(),t.batch.setObjectRenderer(t.plugins[this.pluginName]),t.plugins[this.pluginName].render(this)}_calculateBounds(){const t=this._texture.trim,e=this._texture.orig;!t||t.width===e.width&&t.height===e.height?(this.calculateVertices(),this._bounds.addQuad(this.vertexData)):(this.calculateTrimmedVertices(),this._bounds.addQuad(this.vertexTrimmedData))}getLocalBounds(t){return 0===this.children.length?(this._localBounds||(this._localBounds=new Tg),this._localBounds.minX=this._texture.orig.width*-this._anchor._x,this._localBounds.minY=this._texture.orig.height*-this._anchor._y,this._localBounds.maxX=this._texture.orig.width*(1-this._anchor._x),this._localBounds.maxY=this._texture.orig.height*(1-this._anchor._y),t||(this._localBoundsRect||(this._localBoundsRect=new Qp),t=this._localBoundsRect),this._localBounds.getRectangle(t)):super.getLocalBounds.call(this,t)}containsPoint(t){this.worldTransform.applyInverse(t,Ng);const e=this._texture.orig.width,i=this._texture.orig.height,s=-e*this.anchor.x;let r=0;return Ng.x>=s&&Ng.x<s+e&&(r=-i*this.anchor.y,Ng.y>=r&&Ng.y<r+i)}destroy(t){if(super.destroy(t),this._texture.off("update",this._onTextureUpdate,this),this._anchor=null,"boolean"==typeof t?t:t?.texture){const e="boolean"==typeof t?t:t?.baseTexture;this._texture.destroy(!!e)}this._texture=null}static from(t,e){const i=t instanceof om?t:om.from(t,e);return new Rg(i)}set roundPixels(t){this._roundPixels!==t&&(this._transformID=-1,this._transformTrimmedID=-1),this._roundPixels=t}get roundPixels(){return this._roundPixels}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(t){const e=rp(this.scale.x)||1;this.scale.x=e*t/this._texture.orig.width,this._width=t}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(t){const e=rp(this.scale.y)||1;this.scale.y=e*t/this._texture.orig.height,this._height=t}get anchor(){return this._anchor}set anchor(t){this._anchor.copyFrom(t)}get tint(){return this._tintColor.value}set tint(t){this._tintColor.setValue(t),this._tintRGB=this._tintColor.toLittleEndianNumber()}get tintValue(){return this._tintColor.toNumber()}get texture(){return this._texture}set texture(t){this._texture!==t&&(this._texture&&this._texture.off("update",this._onTextureUpdate,this),this._texture=t||om.EMPTY,this._cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.valid?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}const kg={build(t){const e=t.points;let i,s,r,n,o,a;if(t.type===Jp.CIRC){const e=t.shape;i=e.x,s=e.y,o=a=e.radius,r=n=0}else if(t.type===Jp.ELIP){const e=t.shape;i=e.x,s=e.y,o=e.width,a=e.height,r=n=0}else{const e=t.shape,l=e.width/2,h=e.height/2;i=e.x+l,s=e.y+h,o=a=Math.max(0,Math.min(e.radius,Math.min(l,h))),r=l-o,n=h-a}if(!(o>=0&&a>=0&&r>=0&&n>=0))return void(e.length=0);const l=Math.ceil(2.3*Math.sqrt(o+a)),h=8*l+(r?4:0)+(n?4:0);if(e.length=h,0===h)return;if(0===l)return e.length=8,e[0]=e[6]=i+r,e[1]=e[3]=s+n,e[2]=e[4]=i-r,void(e[5]=e[7]=s-n);let u=0,c=4*l+(r?2:0)+2,d=c,p=h;{const t=r+o,a=n,l=i+t,h=i-t,f=s+a;if(e[u++]=l,e[u++]=f,e[--c]=f,e[--c]=h,n){const t=s-a;e[d++]=h,e[d++]=t,e[--p]=t,e[--p]=l}}for(let f=1;f<l;f++){const t=Math.PI/2*(f/l),h=r+Math.cos(t)*o,m=n+Math.sin(t)*a,g=i+h,y=i-h,v=s+m,x=s-m;e[u++]=g,e[u++]=v,e[--c]=v,e[--c]=y,e[d++]=y,e[d++]=x,e[--p]=x,e[--p]=g}{const t=n+a,o=i+r,l=i-r,h=s+t,c=s-t;e[u++]=o,e[u++]=h,e[--p]=c,e[--p]=o,r&&(e[u++]=l,e[u++]=h,e[--p]=c,e[--p]=l)}},triangulate(t,e){const i=t.points,s=e.points,r=e.indices;if(0===i.length)return;let n=s.length/2;const o=n;let a,l;if(t.type!==Jp.RREC){const e=t.shape;a=e.x,l=e.y}else{const e=t.shape;a=e.x+e.width/2,l=e.y+e.height/2}const h=t.matrix;s.push(t.matrix?h.a*a+h.c*l+h.tx:a,t.matrix?h.b*a+h.d*l+h.ty:l),n++,s.push(i[0],i[1]);for(let u=2;u<i.length;u+=2)s.push(i[u],i[u+1]),r.push(n++,o,n);r.push(o+1,o,n)}};function Bg(t,e=!1){const i=t.length;if(i<6)return;let s=0;for(let r=0,n=t[i-2],o=t[i-1];r<i;r+=2){const e=t[r],i=t[r+1];s+=(e-n)*(i+o),n=e,o=i}if(!e&&s>0||e&&s<=0){const e=i/2;for(let s=e+e%2;s<i;s+=2){const e=i-s-2,r=i-s-1,n=s,o=s+1;[t[e],t[n]]=[t[n],t[e]],[t[r],t[o]]=[t[o],t[r]]}}}const Fg={build(t){t.points=t.shape.points.slice()},triangulate(t,e){let i=t.points;const s=t.holes,r=e.points,n=e.indices;if(i.length>=6){Bg(i,!1);const t=[];for(let r=0;r<s.length;r++){const e=s[r];Bg(e.points,!0),t.push(i.length/2),i=i.concat(e.points)}const e=Nt(i,t,2);if(!e)return;const o=r.length/2;for(let i=0;i<e.length;i+=3)n.push(e[i]+o),n.push(e[i+1]+o),n.push(e[i+2]+o);for(let s=0;s<i.length;s++)r.push(i[s])}}},Dg={build(t){const e=t.shape,i=e.x,s=e.y,r=e.width,n=e.height,o=t.points;o.length=0,r>=0&&n>=0&&o.push(i,s,i+r,s,i+r,s+n,i,s+n)},triangulate(t,e){const i=t.points,s=e.points;if(0===i.length)return;const r=s.length/2;s.push(i[0],i[1],i[2],i[3],i[6],i[7],i[4],i[5]),e.indices.push(r,r+1,r+2,r+1,r+2,r+3)}},Ug={build(t){kg.build(t)},triangulate(t,e){kg.triangulate(t,e)}};var Gg=/* @__PURE__ */(t=>(t.MITER="miter",t.BEVEL="bevel",t.ROUND="round",t))(Gg||{}),Xg=/* @__PURE__ */(t=>(t.BUTT="butt",t.ROUND="round",t.SQUARE="square",t))(Xg||{});const Wg={adaptive:!0,maxLength:10,minSegments:8,maxSegments:2048,epsilon:1e-4,_segmentsCount(t,e=20){if(!this.adaptive||!t||isNaN(t))return e;let i=Math.ceil(t/this.maxLength);return i<this.minSegments?i=this.minSegments:i>this.maxSegments&&(i=this.maxSegments),i}};class Yg{static curveTo(t,e,i,s,r,n){const o=n[n.length-2],a=n[n.length-1]-e,l=o-t,h=s-e,u=i-t,c=Math.abs(a*u-l*h);if(c<1e-8||0===r)return(n[n.length-2]!==t||n[n.length-1]!==e)&&n.push(t,e),null;const d=a*a+l*l,p=h*h+u*u,f=a*h+l*u,m=r*Math.sqrt(d)/c,g=r*Math.sqrt(p)/c,y=m*f/d,v=g*f/p,x=m*u+g*l,b=m*h+g*a,_=l*(g+y),w=a*(g+y),P=u*(m+v),E=h*(m+v);return{cx:x+t,cy:b+e,radius:r,startAngle:Math.atan2(w-b,_-x),endAngle:Math.atan2(E-b,P-x),anticlockwise:l*h>u*a}}static arc(t,e,i,s,r,n,o,a,l){const h=o-n,u=Wg._segmentsCount(Math.abs(h)*r,40*Math.ceil(Math.abs(h)/zp)),c=h/(2*u),d=2*c,p=Math.cos(c),f=Math.sin(c),m=u-1,g=m%1/m;for(let y=0;y<=m;++y){const t=c+n+d*(y+g*y),e=Math.cos(t),o=-Math.sin(t);l.push((p*e+f*o)*r+i,(p*-o+f*e)*r+s)}}}class Hg{constructor(){this.reset()}begin(t,e,i){this.reset(),this.style=t,this.start=e,this.attribStart=i}end(t,e){this.attribSize=e-this.attribStart,this.size=t-this.start}reset(){this.style=null,this.size=0,this.start=0,this.attribStart=0,this.attribSize=0}}class $g{static curveLength(t,e,i,s,r,n,o,a){let l=0,h=0,u=0,c=0,d=0,p=0,f=0,m=0,g=0,y=0,v=0,x=t,b=e;for(let _=1;_<=10;++_)h=_/10,u=h*h,c=u*h,d=1-h,p=d*d,f=p*d,m=f*t+3*p*h*i+3*d*u*r+c*o,g=f*e+3*p*h*s+3*d*u*n+c*a,y=x-m,v=b-g,x=m,b=g,l+=Math.sqrt(y*y+v*v);return l}static curveTo(t,e,i,s,r,n,o){const a=o[o.length-2],l=o[o.length-1];o.length-=2;const h=Wg._segmentsCount($g.curveLength(a,l,t,e,i,s,r,n));let u=0,c=0,d=0,p=0,f=0;o.push(a,l);for(let m=1,g=0;m<=h;++m)g=m/h,u=1-g,c=u*u,d=c*u,p=g*g,f=p*g,o.push(d*a+3*c*g*t+3*u*p*i+f*r,d*l+3*c*g*e+3*u*p*s+f*n)}}function jg(t,e,i,s,r,n,o,a){let l,h;o?(l=s,h=-i):(l=-s,h=i);const u=t-i*r+l,c=e-s*r+h,d=t+i*n+l,p=e+s*n+h;return a.push(u,c,d,p),2}function zg(t,e,i,s,r,n,o,a){const l=i-t,h=s-e;let u=Math.atan2(l,h),c=Math.atan2(r-t,n-e);a&&u<c?u+=2*Math.PI:!a&&u>c&&(c+=2*Math.PI);let d=u;const p=c-u,f=Math.abs(p),m=Math.sqrt(l*l+h*h),g=1+(15*f*Math.sqrt(m)/Math.PI|0),y=p/g;if(d+=y,a){o.push(t,e,i,s);for(let i=1,s=d;i<g;i++,s+=y)o.push(t,e,t+Math.sin(s)*m,e+Math.cos(s)*m);o.push(t,e,r,n)}else{o.push(i,s,t,e);for(let i=1,s=d;i<g;i++,s+=y)o.push(t+Math.sin(s)*m,e+Math.cos(s)*m,t,e);o.push(r,n,t,e)}return 2*g}function Vg(t,e){t.lineStyle.native?function(t,e){let i=0;const s=t.shape,r=t.points||s.points,n=s.type!==Jp.POLY||s.closeStroke;if(0===r.length)return;const o=e.points,a=e.indices,l=r.length/2,h=o.length/2;let u=h;for(o.push(r[0],r[1]),i=1;i<l;i++)o.push(r[2*i],r[2*i+1]),a.push(u,u+1),u++;n&&a.push(u,h)}(t,e):function(t,e){const i=t.shape;let s=t.points||i.points.slice();const r=e.closePointEps;if(0===s.length)return;const n=t.lineStyle,o=new Kp(s[0],s[1]),a=new Kp(s[s.length-2],s[s.length-1]),l=i.type!==Jp.POLY||i.closeStroke,h=Math.abs(o.x-a.x)<r&&Math.abs(o.y-a.y)<r;if(l){s=s.slice(),h&&(s.pop(),s.pop(),a.set(s[s.length-2],s[s.length-1]));const t=.5*(o.x+a.x),e=.5*(a.y+o.y);s.unshift(t,e),s.push(t,e)}const u=e.points,c=s.length/2;let d=s.length;const p=u.length/2,f=n.width/2,m=f*f,g=n.miterLimit*n.miterLimit;let y=s[0],v=s[1],x=s[2],b=s[3],_=0,w=0,P=-(v-b),E=y-x,T=0,A=0,I=Math.sqrt(P*P+E*E);P/=I,E/=I,P*=f,E*=f;const S=n.alignment,C=2*(1-S),M=2*S;l||(n.cap===Xg.ROUND?d+=zg(y-P*(C-M)*.5,v-E*(C-M)*.5,y-P*C,v-E*C,y+P*M,v+E*M,u,!0)+2:n.cap===Xg.SQUARE&&(d+=jg(y,v,P,E,C,M,!0,u))),u.push(y-P*C,v-E*C,y+P*M,v+E*M);for(let L=1;L<c-1;++L){y=s[2*(L-1)],v=s[2*(L-1)+1],x=s[2*L],b=s[2*L+1],_=s[2*(L+1)],w=s[2*(L+1)+1],P=-(v-b),E=y-x,I=Math.sqrt(P*P+E*E),P/=I,E/=I,P*=f,E*=f,T=-(b-w),A=x-_,I=Math.sqrt(T*T+A*A),T/=I,A/=I,T*=f,A*=f;const t=x-y,e=v-b,i=x-_,r=w-b,o=t*i+e*r,a=e*i-r*t,l=a<0;if(Math.abs(a)<.001*Math.abs(o)){u.push(x-P*C,b-E*C,x+P*M,b+E*M),o>=0&&(n.join===Gg.ROUND?d+=zg(x,b,x-P*C,b-E*C,x-T*C,b-A*C,u,!1)+4:d+=2,u.push(x-T*M,b-A*M,x+T*C,b+A*C));continue}const h=(-P+y)*(-E+b)-(-P+x)*(-E+v),c=(-T+_)*(-A+b)-(-T+x)*(-A+w),p=(t*c-i*h)/a,S=(r*h-e*c)/a,O=(p-x)*(p-x)+(S-b)*(S-b),N=x+(p-x)*C,R=b+(S-b)*C,k=x-(p-x)*M,B=b-(S-b)*M,F=l?C:M,D=O<=Math.min(t*t+e*e,i*i+r*r)+F*F*m;let U=n.join;if(U===Gg.MITER&&O/m>g&&(U=Gg.BEVEL),D)switch(U){case Gg.MITER:u.push(N,R,k,B);break;case Gg.BEVEL:l?u.push(N,R,x+P*M,b+E*M,N,R,x+T*M,b+A*M):u.push(x-P*C,b-E*C,k,B,x-T*C,b-A*C,k,B),d+=2;break;case Gg.ROUND:l?(u.push(N,R,x+P*M,b+E*M),d+=zg(x,b,x+P*M,b+E*M,x+T*M,b+A*M,u,!0)+4,u.push(N,R,x+T*M,b+A*M)):(u.push(x-P*C,b-E*C,k,B),d+=zg(x,b,x-P*C,b-E*C,x-T*C,b-A*C,u,!1)+4,u.push(x-T*C,b-A*C,k,B))}else{switch(u.push(x-P*C,b-E*C,x+P*M,b+E*M),U){case Gg.MITER:l?u.push(k,B,k,B):u.push(N,R,N,R),d+=2;break;case Gg.ROUND:d+=l?zg(x,b,x+P*M,b+E*M,x+T*M,b+A*M,u,!0)+2:zg(x,b,x-P*C,b-E*C,x-T*C,b-A*C,u,!1)+2}u.push(x-T*C,b-A*C,x+T*M,b+A*M),d+=2}}y=s[2*(c-2)],v=s[2*(c-2)+1],x=s[2*(c-1)],b=s[2*(c-1)+1],P=-(v-b),E=y-x,I=Math.sqrt(P*P+E*E),P/=I,E/=I,P*=f,E*=f,u.push(x-P*C,b-E*C,x+P*M,b+E*M),l||(n.cap===Xg.ROUND?d+=zg(x-P*(C-M)*.5,b-E*(C-M)*.5,x-P*C,b-E*C,x+P*M,b+E*M,u,!1)+2:n.cap===Xg.SQUARE&&(d+=jg(x,b,P,E,C,M,!1,u)));const O=e.indices,N=Wg.epsilon*Wg.epsilon;for(let L=p;L<d+p-2;++L)y=u[2*L],v=u[2*L+1],x=u[2*(L+1)],b=u[2*(L+1)+1],_=u[2*(L+2)],w=u[2*(L+2)+1],!(Math.abs(y*(b-w)+x*(w-v)+_*(v-b))<N)&&O.push(L,L+1,L+2)}(t,e)}class qg{static curveLength(t,e,i,s,r,n){const o=t-2*i+r,a=e-2*s+n,l=2*i-2*t,h=2*s-2*e,u=4*(o*o+a*a),c=4*(o*l+a*h),d=l*l+h*h,p=2*Math.sqrt(u+c+d),f=Math.sqrt(u),m=2*u*f,g=2*Math.sqrt(d),y=c/f;return(m*p+f*c*(p-g)+(4*d*u-c*c)*Math.log((2*f+y+p)/(y+g)))/(4*m)}static curveTo(t,e,i,s,r){const n=r[r.length-2],o=r[r.length-1],a=Wg._segmentsCount(qg.curveLength(n,o,t,e,i,s));let l=0,h=0;for(let u=1;u<=a;++u){const c=u/a;l=n+(t-n)*c,h=o+(e-o)*c,r.push(l+(t+(i-t)*c-l)*c,h+(e+(s-e)*c-h)*c)}}}const Jg={[Jp.POLY]:Fg,[Jp.CIRC]:kg,[Jp.ELIP]:kg,[Jp.RECT]:Dg,[Jp.RREC]:Ug},Kg=[],Zg=[];class Qg{constructor(t,e=null,i=null,s=null){this.points=[],this.holes=[],this.shape=t,this.lineStyle=i,this.fillStyle=e,this.matrix=s,this.type=t.type}clone(){return new Qg(this.shape,this.fillStyle,this.lineStyle,this.matrix)}destroy(){this.shape=null,this.holes.length=0,this.holes=null,this.points.length=0,this.points=null,this.lineStyle=null,this.fillStyle=null}}const ty=new Kp,ey=class t extends jp{constructor(){super(),this.closePointEps=1e-4,this.boundsPadding=0,this.uvsFloat32=null,this.indicesUint16=null,this.batchable=!1,this.points=[],this.colors=[],this.uvs=[],this.indices=[],this.textureIds=[],this.graphicsData=[],this.drawCalls=[],this.batchDirty=-1,this.batches=[],this.dirty=0,this.cacheDirty=-1,this.clearDirty=0,this.shapeIndex=0,this._bounds=new Tg,this.boundsDirty=-1}get bounds(){return this.updateBatches(),this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.calculateBounds()),this._bounds}invalidate(){this.boundsDirty=-1,this.dirty++,this.batchDirty++,this.shapeIndex=0,this.points.length=0,this.colors.length=0,this.uvs.length=0,this.indices.length=0,this.textureIds.length=0;for(let t=0;t<this.drawCalls.length;t++)this.drawCalls[t].texArray.clear(),Zg.push(this.drawCalls[t]);this.drawCalls.length=0;for(let t=0;t<this.batches.length;t++){const e=this.batches[t];e.reset(),Kg.push(e)}this.batches.length=0}clear(){return this.graphicsData.length>0&&(this.invalidate(),this.clearDirty++,this.graphicsData.length=0),this}drawShape(t,e=null,i=null,s=null){const r=new Qg(t,e,i,s);return this.graphicsData.push(r),this.dirty++,this}drawHole(t,e=null){if(!this.graphicsData.length)return null;const i=new Qg(t,null,null,e),s=this.graphicsData[this.graphicsData.length-1];return i.lineStyle=s.lineStyle,s.holes.push(i),this.dirty++,this}destroy(){super.destroy();for(let t=0;t<this.graphicsData.length;++t)this.graphicsData[t].destroy();this.points.length=0,this.points=null,this.colors.length=0,this.colors=null,this.uvs.length=0,this.uvs=null,this.indices.length=0,this.indices=null,this.indexBuffer.destroy(),this.indexBuffer=null,this.graphicsData.length=0,this.graphicsData=null,this.drawCalls.length=0,this.drawCalls=null,this.batches.length=0,this.batches=null,this._bounds=null}containsPoint(t){const e=this.graphicsData;for(let i=0;i<e.length;++i){const s=e[i];if(s.fillStyle.visible&&s.shape&&(s.matrix?s.matrix.applyInverse(t,ty):ty.copyFrom(t),s.shape.contains(ty.x,ty.y))){let t=!1;if(s.holes)for(let e=0;e<s.holes.length;e++)if(s.holes[e].shape.contains(ty.x,ty.y)){t=!0;break}if(!t)return!0}}return!1}updateBatches(){if(!this.graphicsData.length)return void(this.batchable=!0);if(!this.validateBatching())return;this.cacheDirty=this.dirty;const t=this.uvs,e=this.graphicsData;let i=null,s=null;this.batches.length>0&&(i=this.batches[this.batches.length-1],s=i.style);for(let a=this.shapeIndex;a<e.length;a++){this.shapeIndex++;const r=e[a],n=r.fillStyle,o=r.lineStyle;Jg[r.type].build(r),r.matrix&&this.transformPoints(r.points,r.matrix),(n.visible||o.visible)&&this.processHoles(r.holes);for(let e=0;e<2;e++){const a=0===e?n:o;if(!a.visible)continue;const l=a.texture.baseTexture,h=this.indices.length,u=this.points.length/2;l.wrapMode=rh.REPEAT,0===e?this.processFill(r):this.processLine(r);const c=this.points.length/2-u;0!==c&&(i&&!this._compareStyles(s,a)&&(i.end(h,u),i=null),i||(i=Kg.pop()||new Hg,i.begin(a,h,u),this.batches.push(i),s=a),this.addUvs(this.points,t,a.texture,u,c,a.matrix))}}const r=this.indices.length,n=this.points.length/2;if(i&&i.end(r,n),0===this.batches.length)return void(this.batchable=!0);const o=n>65535;this.indicesUint16&&this.indices.length===this.indicesUint16.length&&o===this.indicesUint16.BYTES_PER_ELEMENT>2?this.indicesUint16.set(this.indices):this.indicesUint16=o?new Uint32Array(this.indices):new Uint16Array(this.indices),this.batchable=this.isBatchable(),this.batchable?this.packBatches():this.buildDrawCalls()}_compareStyles(t,e){return!(!t||!e||t.texture.baseTexture!==e.texture.baseTexture||t.color+t.alpha!==e.color+e.alpha||!!t.native!=!!e.native)}validateBatching(){if(this.dirty===this.cacheDirty||!this.graphicsData.length)return!1;for(let t=0,e=this.graphicsData.length;t<e;t++){const e=this.graphicsData[t],i=e.fillStyle,s=e.lineStyle;if(i&&!i.texture.baseTexture.valid||s&&!s.texture.baseTexture.valid)return!1}return!0}packBatches(){this.batchDirty++,this.uvsFloat32=new Float32Array(this.uvs);const t=this.batches;for(let e=0,i=t.length;e<i;e++){const i=t[e];for(let t=0;t<i.size;t++){const e=i.start+t;this.indicesUint16[e]=this.indicesUint16[e]-i.attribStart}}}isBatchable(){if(this.points.length>131070)return!1;const e=this.batches;for(let t=0;t<e.length;t++)if(e[t].style.native)return!1;return this.points.length<2*t.BATCHABLE_SIZE}buildDrawCalls(){let t=++Bp._globalBatch;for(let u=0;u<this.drawCalls.length;u++)this.drawCalls[u].texArray.clear(),Zg.push(this.drawCalls[u]);this.drawCalls.length=0;const e=this.colors,i=this.textureIds;let s=Zg.pop();s||(s=new Fp,s.texArray=new Yf),s.texArray.count=0,s.start=0,s.size=0,s.type=Zl.TRIANGLES;let r=0,n=null,o=0,a=!1,l=Zl.TRIANGLES,h=0;this.drawCalls.push(s);for(let u=0;u<this.batches.length;u++){const c=this.batches[u],d=8,p=c.style,f=p.texture.baseTexture;a!==!!p.native&&(a=!!p.native,l=a?Zl.LINES:Zl.TRIANGLES,n=null,r=d,t++),n!==f&&(n=f,f._batchEnabled!==t&&(r===d&&(t++,r=0,s.size>0&&(s=Zg.pop(),s||(s=new Fp,s.texArray=new Yf),this.drawCalls.push(s)),s.start=h,s.size=0,s.texArray.count=0,s.type=l),f.touched=1,f._batchEnabled=t,f._batchLocation=r,f.wrapMode=rh.REPEAT,s.texArray.elements[s.texArray.count++]=f,r++)),s.size+=c.size,h+=c.size,o=f._batchLocation,this.addColors(e,p.color,p.alpha,c.attribSize,c.attribStart),this.addTextureIds(i,o,c.attribSize,c.attribStart)}Bp._globalBatch=t,this.packAttributes()}packAttributes(){const t=this.points,e=this.uvs,i=this.colors,s=this.textureIds,r=new ArrayBuffer(3*t.length*4),n=new Float32Array(r),o=new Uint32Array(r);let a=0;for(let l=0;l<t.length/2;l++)n[a++]=t[2*l],n[a++]=t[2*l+1],n[a++]=e[2*l],n[a++]=e[2*l+1],o[a++]=i[l],n[a++]=s[l];this._buffer.update(r),this._indexBuffer.update(this.indicesUint16)}processFill(t){t.holes.length?Fg.triangulate(t,this):Jg[t.type].triangulate(t,this)}processLine(t){Vg(t,this);for(let e=0;e<t.holes.length;e++)Vg(t.holes[e],this)}processHoles(t){for(let e=0;e<t.length;e++){const i=t[e];Jg[i.type].build(i),i.matrix&&this.transformPoints(i.points,i.matrix)}}calculateBounds(){const t=this._bounds;t.clear(),t.addVertexData(this.points,0,this.points.length),t.pad(this.boundsPadding,this.boundsPadding)}transformPoints(t,e){for(let i=0;i<t.length/2;i++){const s=t[2*i],r=t[2*i+1];t[2*i]=e.a*s+e.c*r+e.tx,t[2*i+1]=e.b*s+e.d*r+e.ty}}addColors(t,e,i,s,r=0){const n=qd.shared.setValue(e).toLittleEndianNumber(),o=qd.shared.setValue(n).toPremultiplied(i);t.length=Math.max(t.length,r+s);for(let a=0;a<s;a++)t[r+a]=o}addTextureIds(t,e,i,s=0){t.length=Math.max(t.length,s+i);for(let r=0;r<i;r++)t[s+r]=e}addUvs(t,e,i,s,r,n=null){let o=0;const a=e.length,l=i.frame;for(;o<r;){let i=t[2*(s+o)],r=t[2*(s+o)+1];if(n){const t=n.a*i+n.c*r+n.tx;r=n.b*i+n.d*r+n.ty,i=t}o++,e.push(i/l.width,r/l.height)}const h=i.baseTexture;(l.width<h.width||l.height<h.height)&&this.adjustUvs(e,i,a,r)}adjustUvs(t,e,i,s){const r=e.baseTexture,n=1e-6,o=i+2*s,a=e.frame,l=a.width/r.width,h=a.height/r.height;let u=a.x/a.width,c=a.y/a.height,d=Math.floor(t[i]+n),p=Math.floor(t[i+1]+n);for(let f=i+2;f<o;f+=2)d=Math.min(d,Math.floor(t[f]+n)),p=Math.min(p,Math.floor(t[f+1]+n));u-=d,c-=p;for(let f=i;f<o;f+=2)t[f]=(t[f]+u)*l,t[f+1]=(t[f+1]+c)*h}};ey.BATCHABLE_SIZE=100;let iy=ey;class sy{constructor(){this.color=16777215,this.alpha=1,this.texture=om.WHITE,this.matrix=null,this.visible=!1,this.reset()}clone(){const t=new sy;return t.color=this.color,t.alpha=this.alpha,t.texture=this.texture,t.matrix=this.matrix,t.visible=this.visible,t}reset(){this.color=16777215,this.alpha=1,this.texture=om.WHITE,this.matrix=null,this.visible=!1}destroy(){this.texture=null,this.matrix=null}}class ry extends sy{constructor(){super(...arguments),this.width=0,this.alignment=.5,this.native=!1,this.cap=Xg.BUTT,this.join=Gg.MITER,this.miterLimit=10}clone(){const t=new ry;return t.color=this.color,t.alpha=this.alpha,t.texture=this.texture,t.matrix=this.matrix,t.visible=this.visible,t.width=this.width,t.alignment=this.alignment,t.native=this.native,t.cap=this.cap,t.join=this.join,t.miterLimit=this.miterLimit,t}reset(){super.reset(),this.color=0,this.alignment=.5,this.width=0,this.native=!1,this.cap=Xg.BUTT,this.join=Gg.MITER,this.miterLimit=10}}const ny={},oy=class t extends Og{constructor(t=null){super(),this.shader=null,this.pluginName="batch",this.currentPath=null,this.batches=[],this.batchTint=-1,this.batchDirty=-1,this.vertexData=null,this._fillStyle=new sy,this._lineStyle=new ry,this._matrix=null,this._holeMode=!1,this.state=Sp.for2d(),this._geometry=t||new iy,this._geometry.refCount++,this._transformID=-1,this._tintColor=new qd(16777215),this.blendMode=Kl.NORMAL}get geometry(){return this._geometry}clone(){return this.finishPoly(),new t(this._geometry)}set blendMode(t){this.state.blendMode=t}get blendMode(){return this.state.blendMode}get tint(){return this._tintColor.value}set tint(t){this._tintColor.setValue(t)}get fill(){return this._fillStyle}get line(){return this._lineStyle}lineStyle(t=null,e=0,i,s=.5,r=!1){return"number"==typeof t&&(t={width:t,color:e,alpha:i,alignment:s,native:r}),this.lineTextureStyle(t)}lineTextureStyle(t){const e={width:0,texture:om.WHITE,color:t?.texture?16777215:0,matrix:null,alignment:.5,native:!1,cap:Xg.BUTT,join:Gg.MITER,miterLimit:10};t=Object.assign(e,t),this.normalizeColor(t),this.currentPath&&this.startPoly();const i=t.width>0&&t.alpha>0;return i?(t.matrix&&(t.matrix=t.matrix.clone(),t.matrix.invert()),Object.assign(this._lineStyle,{visible:i},t)):this._lineStyle.reset(),this}startPoly(){if(this.currentPath){const t=this.currentPath.points,e=this.currentPath.points.length;e>2&&(this.drawShape(this.currentPath),this.currentPath=new sf,this.currentPath.closeStroke=!1,this.currentPath.points.push(t[e-2],t[e-1]))}else this.currentPath=new sf,this.currentPath.closeStroke=!1}finishPoly(){this.currentPath&&(this.currentPath.points.length>2?(this.drawShape(this.currentPath),this.currentPath=null):this.currentPath.points.length=0)}moveTo(t,e){return this.startPoly(),this.currentPath.points[0]=t,this.currentPath.points[1]=e,this}lineTo(t,e){this.currentPath||this.moveTo(0,0);const i=this.currentPath.points,s=i[i.length-2],r=i[i.length-1];return(s!==t||r!==e)&&i.push(t,e),this}_initCurve(t=0,e=0){this.currentPath?0===this.currentPath.points.length&&(this.currentPath.points=[t,e]):this.moveTo(t,e)}quadraticCurveTo(t,e,i,s){this._initCurve();const r=this.currentPath.points;return 0===r.length&&this.moveTo(0,0),qg.curveTo(t,e,i,s,r),this}bezierCurveTo(t,e,i,s,r,n){return this._initCurve(),$g.curveTo(t,e,i,s,r,n,this.currentPath.points),this}arcTo(t,e,i,s,r){this._initCurve(t,e);const n=this.currentPath.points,o=Yg.curveTo(t,e,i,s,r,n);if(o){const{cx:t,cy:e,radius:i,startAngle:s,endAngle:r,anticlockwise:n}=o;this.arc(t,e,i,s,r,n)}return this}arc(t,e,i,s,r,n=!1){if(s===r)return this;if(!n&&r<=s?r+=zp:n&&s<=r&&(s+=zp),r-s===0)return this;const o=t+Math.cos(s)*i,a=e+Math.sin(s)*i,l=this._geometry.closePointEps;let h=this.currentPath?this.currentPath.points:null;if(h){const t=Math.abs(h[h.length-2]-o),e=Math.abs(h[h.length-1]-a);t<l&&e<l||h.push(o,a)}else this.moveTo(o,a),h=this.currentPath.points;return Yg.arc(o,a,t,e,i,s,r,n,h),this}beginFill(t=0,e){return this.beginTextureFill({texture:om.WHITE,color:t,alpha:e})}normalizeColor(t){const e=qd.shared.setValue(t.color??0);t.color=e.toNumber(),t.alpha??(t.alpha=e.alpha)}beginTextureFill(t){const e={texture:om.WHITE,color:16777215,matrix:null};t=Object.assign(e,t),this.normalizeColor(t),this.currentPath&&this.startPoly();const i=t.alpha>0;return i?(t.matrix&&(t.matrix=t.matrix.clone(),t.matrix.invert()),Object.assign(this._fillStyle,{visible:i},t)):this._fillStyle.reset(),this}endFill(){return this.finishPoly(),this._fillStyle.reset(),this}drawRect(t,e,i,s){return this.drawShape(new Qp(t,e,i,s))}drawRoundedRect(t,e,i,s,r){return this.drawShape(new rf(t,e,i,s,r))}drawCircle(t,e,i){return this.drawShape(new tf(t,e,i))}drawEllipse(t,e,i,s){return this.drawShape(new ef(t,e,i,s))}drawPolygon(...t){let e,i=!0;const s=t[0];s.points?(i=s.closeStroke,e=s.points):e=Array.isArray(t[0])?t[0]:t;const r=new sf(e);return r.closeStroke=i,this.drawShape(r),this}drawShape(t){return this._holeMode?this._geometry.drawHole(t,this._matrix):this._geometry.drawShape(t,this._fillStyle.clone(),this._lineStyle.clone(),this._matrix),this}clear(){return this._geometry.clear(),this._lineStyle.reset(),this._fillStyle.reset(),this._boundsID++,this._matrix=null,this._holeMode=!1,this.currentPath=null,this}isFastRect(){const t=this._geometry.graphicsData;return!(1!==t.length||t[0].shape.type!==Jp.RECT||t[0].matrix||t[0].holes.length||t[0].lineStyle.visible&&t[0].lineStyle.width)}_render(t){this.finishPoly();const e=this._geometry;e.updateBatches(),e.batchable?(this.batchDirty!==e.batchDirty&&this._populateBatches(),this._renderBatched(t)):(t.batch.flush(),this._renderDirect(t))}_populateBatches(){const t=this._geometry,e=this.blendMode,i=t.batches.length;this.batchTint=-1,this._transformID=-1,this.batchDirty=t.batchDirty,this.batches.length=i,this.vertexData=new Float32Array(t.points);for(let s=0;s<i;s++){const i=t.batches[s],r=i.style.color,n=new Float32Array(this.vertexData.buffer,4*i.attribStart*2,2*i.attribSize),o=new Float32Array(t.uvsFloat32.buffer,4*i.attribStart*2,2*i.attribSize),a={vertexData:n,blendMode:e,indices:new Uint16Array(t.indicesUint16.buffer,2*i.start,i.size),uvs:o,_batchRGB:qd.shared.setValue(r).toRgbArray(),_tintRGB:r,_texture:i.style.texture,alpha:i.style.alpha,worldAlpha:1};this.batches[s]=a}}_renderBatched(t){if(this.batches.length){t.batch.setObjectRenderer(t.plugins[this.pluginName]),this.calculateVertices(),this.calculateTints();for(let e=0,i=this.batches.length;e<i;e++){const i=this.batches[e];i.worldAlpha=this.worldAlpha*i.alpha,t.plugins[this.pluginName].render(i)}}}_renderDirect(t){const e=this._resolveDirectShader(t),i=this._geometry,s=this.worldAlpha,r=e.uniforms,n=i.drawCalls;r.translationMatrix=this.transform.worldTransform,qd.shared.setValue(this._tintColor).premultiply(s).toArray(r.tint),t.shader.bind(e),t.geometry.bind(i,e),t.state.set(this.state);for(let o=0,a=n.length;o<a;o++)this._renderDrawCallDirect(t,i.drawCalls[o])}_renderDrawCallDirect(t,e){const{texArray:i,type:s,size:r,start:n}=e,o=i.count;for(let a=0;a<o;a++)t.texture.bind(i.elements[a],a);t.geometry.draw(s,r,n)}_resolveDirectShader(t){let e=this.shader;const i=this.pluginName;if(!e){if(!ny[i]){const{maxTextures:e}=t.plugins[i],s=new Int32Array(e);for(let t=0;t<e;t++)s[t]=t;const r={tint:new Float32Array([1,1,1,1]),translationMatrix:new nf,default:Gf.from({uSamplers:s},!0)},n=t.plugins[i]._shader.program;ny[i]=new Xf(n,r)}e=ny[i]}return e}_calculateBounds(){this.finishPoly();const t=this._geometry;if(!t.graphicsData.length)return;const{minX:e,minY:i,maxX:s,maxY:r}=t.bounds;this._bounds.addFrame(this.transform,e,i,s,r)}containsPoint(e){return this.worldTransform.applyInverse(e,t._TEMP_POINT),this._geometry.containsPoint(t._TEMP_POINT)}calculateTints(){if(this.batchTint!==this.tint){this.batchTint=this._tintColor.toNumber();for(let t=0;t<this.batches.length;t++){const e=this.batches[t];e._tintRGB=qd.shared.setValue(this._tintColor).multiply(e._batchRGB).toLittleEndianNumber()}}}calculateVertices(){const t=this.transform._worldID;if(this._transformID===t)return;this._transformID=t;const e=this.transform.worldTransform,i=e.a,s=e.b,r=e.c,n=e.d,o=e.tx,a=e.ty,l=this._geometry.points,h=this.vertexData;let u=0;for(let c=0;c<l.length;c+=2){const t=l[c],e=l[c+1];h[u++]=i*t+r*e+o,h[u++]=n*e+s*t+a}}closePath(){const t=this.currentPath;return t&&(t.closeStroke=!0,this.finishPoly()),this}setMatrix(t){return this._matrix=t,this}beginHole(){return this.finishPoly(),this._holeMode=!0,this}endHole(){return this.finishPoly(),this._holeMode=!1,this}destroy(t){this._geometry.refCount--,0===this._geometry.refCount&&this._geometry.dispose(),this._matrix=null,this.currentPath=null,this._lineStyle.destroy(),this._lineStyle=null,this._fillStyle.destroy(),this._fillStyle=null,this._geometry=null,this.shader=null,this.vertexData=null,this.batches.length=0,this.batches=null,super.destroy(t)}};oy.curves=Wg,oy._TEMP_POINT=new Kp;let ay=oy;var ly=/* @__PURE__ */(t=>(t[t.LINEAR_VERTICAL=0]="LINEAR_VERTICAL",t[t.LINEAR_HORIZONTAL=1]="LINEAR_HORIZONTAL",t))(ly||{});const hy={willReadFrequently:!0},uy=class t{static get experimentalLetterSpacingSupported(){let e=t._experimentalLetterSpacingSupported;if(void 0!==e){const i=ph.ADAPTER.getCanvasRenderingContext2D().prototype;e=t._experimentalLetterSpacingSupported="letterSpacing"in i||"textLetterSpacing"in i}return e}constructor(t,e,i,s,r,n,o,a,l){this.text=t,this.style=e,this.width=i,this.height=s,this.lines=r,this.lineWidths=n,this.lineHeight=o,this.maxLineWidth=a,this.fontProperties=l}static measureText(e,i,s,r=t._canvas){s=s??i.wordWrap;const n=i.toFontString(),o=t.measureFont(n);0===o.fontSize&&(o.fontSize=i.fontSize,o.ascent=i.fontSize);const a=r.getContext("2d",hy);a.font=n;const l=(s?t.wordWrap(e,i,r):e).split(/(?:\r\n|\r|\n)/),h=new Array(l.length);let u=0;for(let f=0;f<l.length;f++){const e=t._measureText(l[f],i.letterSpacing,a);h[f]=e,u=Math.max(u,e)}let c=u+i.strokeThickness;i.dropShadow&&(c+=i.dropShadowDistance);const d=i.lineHeight||o.fontSize+i.strokeThickness;let p=Math.max(d,o.fontSize+2*i.strokeThickness)+i.leading+(l.length-1)*(d+i.leading);return i.dropShadow&&(p+=i.dropShadowDistance),new t(e,i,c,p,l,h,d+i.leading,u,o)}static _measureText(e,i,s){let r=!1;t.experimentalLetterSpacingSupported&&(t.experimentalLetterSpacing?(s.letterSpacing=`${i}px`,s.textLetterSpacing=`${i}px`,r=!0):(s.letterSpacing="0px",s.textLetterSpacing="0px"));let n=s.measureText(e).width;return n>0&&(r?n-=i:n+=(t.graphemeSegmenter(e).length-1)*i),n}static wordWrap(e,i,s=t._canvas){const r=s.getContext("2d",hy);let n=0,o="",a="";const l=/* @__PURE__ */Object.create(null),{letterSpacing:h,whiteSpace:u}=i,c=t.collapseSpaces(u),d=t.collapseNewlines(u);let p=!c;const f=i.wordWrapWidth+h,m=t.tokenize(e);for(let g=0;g<m.length;g++){let e=m[g];if(t.isNewline(e)){if(!d){a+=t.addLine(o),p=!c,o="",n=0;continue}e=" "}if(c){const i=t.isBreakingSpace(e),s=t.isBreakingSpace(o[o.length-1]);if(i&&s)continue}const s=t.getFromCache(e,h,l,r);if(s>f)if(""!==o&&(a+=t.addLine(o),o="",n=0),t.canBreakWords(e,i.breakWords)){const s=t.wordWrapSplit(e);for(let u=0;u<s.length;u++){let c=s[u],d=c,m=1;for(;s[u+m];){const r=s[u+m];if(t.canBreakChars(d,r,e,u,i.breakWords))break;c+=r,d=r,m++}u+=m-1;const g=t.getFromCache(c,h,l,r);g+n>f&&(a+=t.addLine(o),p=!1,o="",n=0),o+=c,n+=g}}else{o.length>0&&(a+=t.addLine(o),o="",n=0);const i=g===m.length-1;a+=t.addLine(e,!i),p=!1,o="",n=0}else s+n>f&&(p=!1,a+=t.addLine(o),o="",n=0),(o.length>0||!t.isBreakingSpace(e)||p)&&(o+=e,n+=s)}return a+=t.addLine(o,!1),a}static addLine(e,i=!0){return e=t.trimRight(e),e=i?`${e}\n`:e}static getFromCache(e,i,s,r){let n=s[e];return"number"!=typeof n&&(n=t._measureText(e,i,r)+i,s[e]=n),n}static collapseSpaces(t){return"normal"===t||"pre-line"===t}static collapseNewlines(t){return"normal"===t}static trimRight(e){if("string"!=typeof e)return"";for(let i=e.length-1;i>=0;i--){const s=e[i];if(!t.isBreakingSpace(s))break;e=e.slice(0,-1)}return e}static isNewline(e){return"string"==typeof e&&t._newlines.includes(e.charCodeAt(0))}static isBreakingSpace(e,i){return"string"==typeof e&&t._breakingSpaces.includes(e.charCodeAt(0))}static tokenize(e){const i=[];let s="";if("string"!=typeof e)return i;for(let r=0;r<e.length;r++){const n=e[r],o=e[r+1];t.isBreakingSpace(n,o)||t.isNewline(n)?(""!==s&&(i.push(s),s=""),i.push(n)):s+=n}return""!==s&&i.push(s),i}static canBreakWords(t,e){return e}static canBreakChars(t,e,i,s,r){return!0}static wordWrapSplit(e){return t.graphemeSegmenter(e)}static measureFont(e){if(t._fonts[e])return t._fonts[e];const i={ascent:0,descent:0,fontSize:0},s=t._canvas,r=t._context;r.font=e;const n=t.METRICS_STRING+t.BASELINE_SYMBOL,o=Math.ceil(r.measureText(n).width);let a=Math.ceil(r.measureText(t.BASELINE_SYMBOL).width);const l=Math.ceil(t.HEIGHT_MULTIPLIER*a);if(a=a*t.BASELINE_MULTIPLIER|0,0===o||0===l)return t._fonts[e]=i,i;s.width=o,s.height=l,r.fillStyle="#f00",r.fillRect(0,0,o,l),r.font=e,r.textBaseline="alphabetic",r.fillStyle="#000",r.fillText(n,0,a);const h=r.getImageData(0,0,o,l).data,u=h.length,c=4*o;let d=0,p=0,f=!1;for(d=0;d<a;++d){for(let t=0;t<c;t+=4)if(255!==h[p+t]){f=!0;break}if(f)break;p+=c}for(i.ascent=a-d,p=u-c,f=!1,d=l;d>a;--d){for(let t=0;t<c;t+=4)if(255!==h[p+t]){f=!0;break}if(f)break;p-=c}return i.descent=d-a,i.fontSize=i.ascent+i.descent,t._fonts[e]=i,i}static clearMetrics(e=""){e?delete t._fonts[e]:t._fonts={}}static get _canvas(){if(!t.__canvas){let e;try{const i=new OffscreenCanvas(0,0);if(i.getContext("2d",hy)?.measureText)return t.__canvas=i,i;e=ph.ADAPTER.createCanvas()}catch{e=ph.ADAPTER.createCanvas()}e.width=e.height=10,t.__canvas=e}return t.__canvas}static get _context(){return t.__context||(t.__context=t._canvas.getContext("2d",hy)),t.__context}};uy.METRICS_STRING="|ÉqÅ",uy.BASELINE_SYMBOL="M",uy.BASELINE_MULTIPLIER=1.4,uy.HEIGHT_MULTIPLIER=2,uy.graphemeSegmenter=(()=>{if("function"==typeof Intl?.Segmenter){const t=new Intl.Segmenter;return e=>[...t.segment(e)].map(t=>t.segment)}return t=>[...t]})(),uy.experimentalLetterSpacing=!1,uy._fonts={},uy._newlines=[10,13],uy._breakingSpaces=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288];let cy=uy;const dy=["serif","sans-serif","monospace","cursive","fantasy","system-ui"],py=class t{constructor(t){this.styleID=0,this.reset(),gy(this,t,t)}clone(){const e={};return gy(e,this,t.defaultStyle),new t(e)}reset(){gy(this,t.defaultStyle,t.defaultStyle)}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this.styleID++)}get breakWords(){return this._breakWords}set breakWords(t){this._breakWords!==t&&(this._breakWords=t,this.styleID++)}get dropShadow(){return this._dropShadow}set dropShadow(t){this._dropShadow!==t&&(this._dropShadow=t,this.styleID++)}get dropShadowAlpha(){return this._dropShadowAlpha}set dropShadowAlpha(t){this._dropShadowAlpha!==t&&(this._dropShadowAlpha=t,this.styleID++)}get dropShadowAngle(){return this._dropShadowAngle}set dropShadowAngle(t){this._dropShadowAngle!==t&&(this._dropShadowAngle=t,this.styleID++)}get dropShadowBlur(){return this._dropShadowBlur}set dropShadowBlur(t){this._dropShadowBlur!==t&&(this._dropShadowBlur=t,this.styleID++)}get dropShadowColor(){return this._dropShadowColor}set dropShadowColor(t){const e=my(t);this._dropShadowColor!==e&&(this._dropShadowColor=e,this.styleID++)}get dropShadowDistance(){return this._dropShadowDistance}set dropShadowDistance(t){this._dropShadowDistance!==t&&(this._dropShadowDistance=t,this.styleID++)}get fill(){return this._fill}set fill(t){const e=my(t);this._fill!==e&&(this._fill=e,this.styleID++)}get fillGradientType(){return this._fillGradientType}set fillGradientType(t){this._fillGradientType!==t&&(this._fillGradientType=t,this.styleID++)}get fillGradientStops(){return this._fillGradientStops}set fillGradientStops(t){(function(t,e){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;++i)if(t[i]!==e[i])return!1;return!0})(this._fillGradientStops,t)||(this._fillGradientStops=t,this.styleID++)}get fontFamily(){return this._fontFamily}set fontFamily(t){this.fontFamily!==t&&(this._fontFamily=t,this.styleID++)}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(this._fontSize=t,this.styleID++)}get fontStyle(){return this._fontStyle}set fontStyle(t){this._fontStyle!==t&&(this._fontStyle=t,this.styleID++)}get fontVariant(){return this._fontVariant}set fontVariant(t){this._fontVariant!==t&&(this._fontVariant=t,this.styleID++)}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this.styleID++)}get letterSpacing(){return this._letterSpacing}set letterSpacing(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.styleID++)}get lineHeight(){return this._lineHeight}set lineHeight(t){this._lineHeight!==t&&(this._lineHeight=t,this.styleID++)}get leading(){return this._leading}set leading(t){this._leading!==t&&(this._leading=t,this.styleID++)}get lineJoin(){return this._lineJoin}set lineJoin(t){this._lineJoin!==t&&(this._lineJoin=t,this.styleID++)}get miterLimit(){return this._miterLimit}set miterLimit(t){this._miterLimit!==t&&(this._miterLimit=t,this.styleID++)}get padding(){return this._padding}set padding(t){this._padding!==t&&(this._padding=t,this.styleID++)}get stroke(){return this._stroke}set stroke(t){const e=my(t);this._stroke!==e&&(this._stroke=e,this.styleID++)}get strokeThickness(){return this._strokeThickness}set strokeThickness(t){this._strokeThickness!==t&&(this._strokeThickness=t,this.styleID++)}get textBaseline(){return this._textBaseline}set textBaseline(t){this._textBaseline!==t&&(this._textBaseline=t,this.styleID++)}get trim(){return this._trim}set trim(t){this._trim!==t&&(this._trim=t,this.styleID++)}get whiteSpace(){return this._whiteSpace}set whiteSpace(t){this._whiteSpace!==t&&(this._whiteSpace=t,this.styleID++)}get wordWrap(){return this._wordWrap}set wordWrap(t){this._wordWrap!==t&&(this._wordWrap=t,this.styleID++)}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this.styleID++)}toFontString(){const t="number"==typeof this.fontSize?`${this.fontSize}px`:this.fontSize;let e=this.fontFamily;Array.isArray(this.fontFamily)||(e=this.fontFamily.split(","));for(let i=e.length-1;i>=0;i--){let t=e[i].trim();!/([\"\'])[^\'\"]+\1/.test(t)&&!dy.includes(t)&&(t=`"${t}"`),e[i]=t}return`${this.fontStyle} ${this.fontVariant} ${this.fontWeight} ${t} ${e.join(",")}`}};py.defaultStyle={align:"left",breakWords:!1,dropShadow:!1,dropShadowAlpha:1,dropShadowAngle:Math.PI/6,dropShadowBlur:0,dropShadowColor:"black",dropShadowDistance:5,fill:"black",fillGradientType:ly.LINEAR_VERTICAL,fillGradientStops:[],fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,lineJoin:"miter",miterLimit:10,padding:0,stroke:"black",strokeThickness:0,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let fy=py;function my(t){const e=qd.shared,i=t=>{const i=e.setValue(t);return 1===i.alpha?i.toHex():i.toRgbaString()};return Array.isArray(t)?t.map(i):i(t)}function gy(t,e,i){for(const s in i)Array.isArray(e[s])?t[s]=e[s].slice():t[s]=e[s]}const yy={texture:!0,children:!1,baseTexture:!0},vy=class t extends Rg{constructor(e,i,s){let r=!1;s||(s=ph.ADAPTER.createCanvas(),r=!0),s.width=3,s.height=3;const n=om.from(s);n.orig=new Qp,n.trim=new Qp,super(n),this._ownCanvas=r,this.canvas=s,this.context=s.getContext("2d",{willReadFrequently:!0}),this._resolution=t.defaultResolution??ph.RESOLUTION,this._autoResolution=t.defaultAutoResolution,this._text=null,this._style=null,this._styleListener=null,this._font="",this.text=e,this.style=i,this.localStyleID=-1}static get experimentalLetterSpacing(){return cy.experimentalLetterSpacing}static set experimentalLetterSpacing(t){dd("7.1.0","Text.experimentalLetterSpacing is deprecated, use TextMetrics.experimentalLetterSpacing"),cy.experimentalLetterSpacing=t}updateText(t){const e=this._style;if(this.localStyleID!==e.styleID&&(this.dirty=!0,this.localStyleID=e.styleID),!this.dirty&&t)return;this._font=this._style.toFontString();const i=this.context,s=cy.measureText(this._text||" ",this._style,this._style.wordWrap,this.canvas),r=s.width,n=s.height,o=s.lines,a=s.lineHeight,l=s.lineWidths,h=s.maxLineWidth,u=s.fontProperties;let c,d;this.canvas.width=Math.ceil(Math.ceil(Math.max(1,r)+2*e.padding)*this._resolution),this.canvas.height=Math.ceil(Math.ceil(Math.max(1,n)+2*e.padding)*this._resolution),i.scale(this._resolution,this._resolution),i.clearRect(0,0,this.canvas.width,this.canvas.height),i.font=this._font,i.lineWidth=e.strokeThickness,i.textBaseline=e.textBaseline,i.lineJoin=e.lineJoin,i.miterLimit=e.miterLimit;const p=e.dropShadow?2:1;for(let f=0;f<p;++f){const t=e.dropShadow&&0===f,r=t?Math.ceil(Math.max(1,n)+2*e.padding):0,p=r*this._resolution;if(t){i.fillStyle="black",i.strokeStyle="black";const t=e.dropShadowColor,s=e.dropShadowBlur*this._resolution,r=e.dropShadowDistance*this._resolution;i.shadowColor=qd.shared.setValue(t).setAlpha(e.dropShadowAlpha).toRgbaString(),i.shadowBlur=s,i.shadowOffsetX=Math.cos(e.dropShadowAngle)*r,i.shadowOffsetY=Math.sin(e.dropShadowAngle)*r+p}else i.fillStyle=this._generateFillStyle(e,o,s),i.strokeStyle=e.stroke,i.shadowColor="black",i.shadowBlur=0,i.shadowOffsetX=0,i.shadowOffsetY=0;let m=(a-u.fontSize)/2;a-u.fontSize<0&&(m=0);for(let i=0;i<o.length;i++)c=e.strokeThickness/2,d=e.strokeThickness/2+i*a+u.ascent+m,"right"===e.align?c+=h-l[i]:"center"===e.align&&(c+=(h-l[i])/2),e.stroke&&e.strokeThickness&&this.drawLetterSpacing(o[i],c+e.padding,d+e.padding-r,!0),e.fill&&this.drawLetterSpacing(o[i],c+e.padding,d+e.padding-r)}this.updateTexture()}drawLetterSpacing(t,e,i,s=!1){const r=this._style.letterSpacing;let n=!1;if(cy.experimentalLetterSpacingSupported&&(cy.experimentalLetterSpacing?(this.context.letterSpacing=`${r}px`,this.context.textLetterSpacing=`${r}px`,n=!0):(this.context.letterSpacing="0px",this.context.textLetterSpacing="0px")),0===r||n)return void(s?this.context.strokeText(t,e,i):this.context.fillText(t,e,i));let o=e;const a=cy.graphemeSegmenter(t);let l=this.context.measureText(t).width,h=0;for(let u=0;u<a.length;++u){const t=a[u];s?this.context.strokeText(t,o,i):this.context.fillText(t,o,i);let e="";for(let i=u+1;i<a.length;++i)e+=a[i];h=this.context.measureText(e).width,o+=l-h+r,l=h}}updateTexture(){const t=this.canvas;if(this._style.trim){const e=yp(t);e.data&&(t.width=e.width,t.height=e.height,this.context.putImageData(e.data,0,0))}const e=this._texture,i=this._style,s=i.trim?0:i.padding,r=e.baseTexture;e.trim.width=e._frame.width=t.width/this._resolution,e.trim.height=e._frame.height=t.height/this._resolution,e.trim.x=-s,e.trim.y=-s,e.orig.width=e._frame.width-2*s,e.orig.height=e._frame.height-2*s,this._onTextureUpdate(),r.setRealSize(t.width,t.height,this._resolution),e.updateUvs(),this.dirty=!1}_render(t){this._autoResolution&&this._resolution!==t.resolution&&(this._resolution=t.resolution,this.dirty=!0),this.updateText(!0),super._render(t)}updateTransform(){this.updateText(!0),super.updateTransform()}getBounds(t,e){return this.updateText(!0),-1===this._textureID&&(t=!1),super.getBounds(t,e)}getLocalBounds(t){return this.updateText(!0),super.getLocalBounds.call(this,t)}_calculateBounds(){this.calculateVertices(),this._bounds.addQuad(this.vertexData)}_generateFillStyle(t,e,i){const s=t.fill;if(!Array.isArray(s))return s;if(1===s.length)return s[0];let r;const n=t.dropShadow?t.dropShadowDistance:0,o=t.padding||0,a=this.canvas.width/this._resolution-n-2*o,l=this.canvas.height/this._resolution-n-2*o,h=s.slice(),u=t.fillGradientStops.slice();if(!u.length){const t=h.length+1;for(let e=1;e<t;++e)u.push(e/t)}if(h.unshift(s[0]),u.unshift(0),h.push(s[s.length-1]),u.push(1),t.fillGradientType===ly.LINEAR_VERTICAL){r=this.context.createLinearGradient(a/2,o,a/2,l+o);const s=i.fontProperties.fontSize+t.strokeThickness;for(let t=0;t<e.length;t++){const n=i.lineHeight*(t-1)+s,o=i.lineHeight*t;let a=o;t>0&&n>o&&(a=(o+n)/2);const c=o+s,d=i.lineHeight*(t+1);let p=c;t+1<e.length&&d<c&&(p=(c+d)/2);const f=(p-a)/l;for(let t=0;t<h.length;t++){let e=0;e="number"==typeof u[t]?u[t]:t/h.length;let i=Math.min(1,Math.max(0,a/l+e*f));i=Number(i.toFixed(5)),r.addColorStop(i,h[t])}}}else{r=this.context.createLinearGradient(o,l/2,a+o,l/2);const t=h.length+1;let e=1;for(let i=0;i<h.length;i++){let s;s="number"==typeof u[i]?u[i]:e/t,r.addColorStop(s,h[i]),e++}}return r}destroy(t){"boolean"==typeof t&&(t={children:t}),t=Object.assign({},yy,t),super.destroy(t),this._ownCanvas&&(this.canvas.height=this.canvas.width=0),this.context=null,this.canvas=null,this._style=null}get width(){return this.updateText(!0),Math.abs(this.scale.x)*this._texture.orig.width}set width(t){this.updateText(!0);const e=rp(this.scale.x)||1;this.scale.x=e*t/this._texture.orig.width,this._width=t}get height(){return this.updateText(!0),Math.abs(this.scale.y)*this._texture.orig.height}set height(t){this.updateText(!0);const e=rp(this.scale.y)||1;this.scale.y=e*t/this._texture.orig.height,this._height=t}get style(){return this._style}set style(t){t=t||{},this._style=t instanceof fy?t:new fy(t),this.localStyleID=-1,this.dirty=!0}get text(){return this._text}set text(t){t=String(t??""),this._text!==t&&(this._text=t,this.dirty=!0)}get resolution(){return this._resolution}set resolution(t){this._autoResolution=!1,this._resolution!==t&&(this._resolution=t,this.dirty=!0)}};vy.defaultAutoResolution=!0;let xy=vy;class by extends Vf{constructor(){super("attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n",{m:new Float32Array([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0]),uAlpha:1}),this.alpha=1}_loadMatrix(t,e=!1){let i=t;e&&(this._multiply(i,this.uniforms.m,t),i=this._colorMatrix(i)),this.uniforms.m=i}_multiply(t,e,i){return t[0]=e[0]*i[0]+e[1]*i[5]+e[2]*i[10]+e[3]*i[15],t[1]=e[0]*i[1]+e[1]*i[6]+e[2]*i[11]+e[3]*i[16],t[2]=e[0]*i[2]+e[1]*i[7]+e[2]*i[12]+e[3]*i[17],t[3]=e[0]*i[3]+e[1]*i[8]+e[2]*i[13]+e[3]*i[18],t[4]=e[0]*i[4]+e[1]*i[9]+e[2]*i[14]+e[3]*i[19]+e[4],t[5]=e[5]*i[0]+e[6]*i[5]+e[7]*i[10]+e[8]*i[15],t[6]=e[5]*i[1]+e[6]*i[6]+e[7]*i[11]+e[8]*i[16],t[7]=e[5]*i[2]+e[6]*i[7]+e[7]*i[12]+e[8]*i[17],t[8]=e[5]*i[3]+e[6]*i[8]+e[7]*i[13]+e[8]*i[18],t[9]=e[5]*i[4]+e[6]*i[9]+e[7]*i[14]+e[8]*i[19]+e[9],t[10]=e[10]*i[0]+e[11]*i[5]+e[12]*i[10]+e[13]*i[15],t[11]=e[10]*i[1]+e[11]*i[6]+e[12]*i[11]+e[13]*i[16],t[12]=e[10]*i[2]+e[11]*i[7]+e[12]*i[12]+e[13]*i[17],t[13]=e[10]*i[3]+e[11]*i[8]+e[12]*i[13]+e[13]*i[18],t[14]=e[10]*i[4]+e[11]*i[9]+e[12]*i[14]+e[13]*i[19]+e[14],t[15]=e[15]*i[0]+e[16]*i[5]+e[17]*i[10]+e[18]*i[15],t[16]=e[15]*i[1]+e[16]*i[6]+e[17]*i[11]+e[18]*i[16],t[17]=e[15]*i[2]+e[16]*i[7]+e[17]*i[12]+e[18]*i[17],t[18]=e[15]*i[3]+e[16]*i[8]+e[17]*i[13]+e[18]*i[18],t[19]=e[15]*i[4]+e[16]*i[9]+e[17]*i[14]+e[18]*i[19]+e[19],t}_colorMatrix(t){const e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e}brightness(t,e){const i=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(i,e)}tint(t,e){const[i,s,r]=qd.shared.setValue(t).toArray(),n=[i,0,0,0,0,0,s,0,0,0,0,0,r,0,0,0,0,0,1,0];this._loadMatrix(n,e)}greyscale(t,e){const i=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(i,e)}blackAndWhite(t){this._loadMatrix([.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0],t)}hue(t,e){t=(t||0)/180*Math.PI;const i=Math.cos(t),s=Math.sin(t),r=1/3,n=(0,Math.sqrt)(r),o=[i+(1-i)*r,r*(1-i)-n*s,r*(1-i)+n*s,0,0,r*(1-i)+n*s,i+r*(1-i),r*(1-i)-n*s,0,0,r*(1-i)-n*s,r*(1-i)+n*s,i+r*(1-i),0,0,0,0,0,1,0];this._loadMatrix(o,e)}contrast(t,e){const i=(t||0)+1,s=-.5*(i-1),r=[i,0,0,0,s,0,i,0,0,s,0,0,i,0,s,0,0,0,1,0];this._loadMatrix(r,e)}saturate(t=0,e){const i=2*t/3+1,s=-.5*(i-1),r=[i,s,s,0,0,s,i,s,0,0,s,s,i,0,0,0,0,0,1,0];this._loadMatrix(r,e)}desaturate(){this.saturate(-1)}negative(t){this._loadMatrix([-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,0],t)}sepia(t){this._loadMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0],t)}technicolor(t){this._loadMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0],t)}polaroid(t){this._loadMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],t)}toBGR(t){this._loadMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0],t)}kodachrome(t){this._loadMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0],t)}browni(t){this._loadMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0],t)}vintage(t){this._loadMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0],t)}colorTone(t,e,i,s,r){t=t||.2,e=e||.15,i=i||16770432,s=s||3375104;const n=qd.shared,[o,a,l]=n.setValue(i).toArray(),[h,u,c]=n.setValue(s).toArray(),d=[.3,.59,.11,0,0,o,a,l,t,0,h,u,c,e,0,o-h,a-u,l-c,0,0];this._loadMatrix(d,r)}night(t,e){const i=[-2*(t=t||.1),-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(i,e)}predator(t,e){const i=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(i,e)}lsd(t){this._loadMatrix([2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0],t)}reset(){this._loadMatrix([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],!1)}get matrix(){return this.uniforms.m}set matrix(t){this.uniforms.m=t}get alpha(){return this.uniforms.uAlpha}set alpha(t){this.uniforms.uAlpha=t}}by.prototype.grayscale=by.prototype.greyscale;var _y,wy={exports:{}},Py=wy.exports;var Ey=(_y||(_y=1,function(t){(function(){var e,i;i=e={linear:function(t,e,i,s){return i*t/s+e},easeInQuad:function(t,e,i,s){return i*(t/=s)*t+e},easeOutQuad:function(t,e,i,s){return-i*(t/=s)*(t-2)+e},easeInOutQuad:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e},easeInCubic:function(t,e,i,s){return i*(t/=s)*t*t+e},easeOutCubic:function(t,e,i,s){return i*((t=t/s-1)*t*t+1)+e},easeInOutCubic:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e},easeInQuart:function(t,e,i,s){return i*(t/=s)*t*t*t+e},easeOutQuart:function(t,e,i,s){return-i*((t=t/s-1)*t*t*t-1)+e},easeInOutQuart:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t*t+e:-i/2*((t-=2)*t*t*t-2)+e},easeInQuint:function(t,e,i,s){return i*(t/=s)*t*t*t*t+e},easeOutQuint:function(t,e,i,s){return i*((t=t/s-1)*t*t*t*t+1)+e},easeInOutQuint:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e},easeInSine:function(t,e,i,s){return-i*Math.cos(t/s*(Math.PI/2))+i+e},easeOutSine:function(t,e,i,s){return i*Math.sin(t/s*(Math.PI/2))+e},easeInOutSine:function(t,e,i,s){return-i/2*(Math.cos(Math.PI*t/s)-1)+e},easeInExpo:function(t,e,i,s){return 0===t?e:i*Math.pow(2,10*(t/s-1))+e},easeOutExpo:function(t,e,i,s){return t===s?e+i:i*(1-Math.pow(2,-10*t/s))+e},easeInOutExpo:function(t,e,i,s){return(t/=s/2)<1?i/2*Math.pow(2,10*(t-1))+e:i/2*(2-Math.pow(2,-10*--t))+e},easeInCirc:function(t,e,i,s){return-i*(Math.sqrt(1-(t/=s)*t)-1)+e},easeOutCirc:function(t,e,i,s){return i*Math.sqrt(1-(t=t/s-1)*t)+e},easeInOutCirc:function(t,e,i,s){return(t/=s/2)<1?-i/2*(Math.sqrt(1-t*t)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e},easeInElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s),(n=0)||(n=.3*s),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),-r*Math.pow(2,10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)+e},easeOutElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s),(n=0)||(n=.3*s),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),r*Math.pow(2,-10*t)*Math.sin((t*s-o)*(2*Math.PI)/n)+i+e},easeInOutElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s/2),(n=0)||(n=s*(.3*1.5)),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),t<1?r*Math.pow(2,10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)*-.5+e:r*Math.pow(2,-10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)*.5+i+e},easeInBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),i*(t/=s)*t*((r+1)*t-r)+e},easeOutBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),i*((t=t/s-1)*t*((r+1)*t+r)+1)+e},easeInOutBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),(t/=s/2)<1?i/2*(t*t*((1+(r*=1.525))*t-r))+e:i/2*((t-=2)*t*((1+(r*=1.525))*t+r)+2)+e},easeInBounce:function(t,i,s,r){return s-e.easeOutBounce(r-t,0,s,r)+i},easeOutBounce:function(t,e,i,s){return(t/=s)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e},easeInOutBounce:function(t,i,s,r){return t<r/2?.5*e.easeInBounce(2*t,0,s,r)+i:.5*e.easeOutBounce(2*t-r,0,s,r)+.5*s+i}},t.exports=i}).call(Py)}(wy)),wy.exports);const Ty=/* @__PURE__ */It(Ey);Og.prototype._renderCanvas=function(t){},Og.prototype.renderCanvas=function(t){if(this.visible&&!(this.worldAlpha<=0)&&this.renderable){this._mask&&t.mask.pushMask(this._mask),this._renderCanvas(t);for(let e=0,i=this.children.length;e<i;++e)this.children[e].renderCanvas(t);this._mask&&t.mask.popMask(t)}},Ag.prototype.renderCanvas=function(t){},xy.prototype._renderCanvas=function(t){this._autoResolution&&this._resolution!==t.resolution&&(this._resolution=t.resolution,this.dirty=!0),this.updateText(!0),Rg.prototype._renderCanvas.call(this,t)},Ag.prototype.name=null,Og.prototype.getChildByName=function(t,e){for(let i=0,s=this.children.length;i<s;i++)if(this.children[i].name===t)return this.children[i];if(e)for(let i=0,s=this.children.length;i<s;i++){const e=this.children[i];if(!e.getChildByName)continue;const s=e.getChildByName(t,!0);if(s)return s}return null};const Ay={vec3(t,e,i,s){(i[0]!==s[0]||i[1]!==s[1]||i[2]!==s[2])&&(i[0]=s[0],i[1]=s[1],i[2]=s[2],t.uniform3f(e,s[0],s[1],s[2]))},int(t,e,i,s){t.uniform1i(e,s)},ivec2(t,e,i,s){t.uniform2i(e,s[0],s[1])},ivec3(t,e,i,s){t.uniform3i(e,s[0],s[1],s[2])},ivec4(t,e,i,s){t.uniform4i(e,s[0],s[1],s[2],s[3])},uint(t,e,i,s){t.uniform1ui(e,s)},uvec2(t,e,i,s){t.uniform2ui(e,s[0],s[1])},uvec3(t,e,i,s){t.uniform3ui(e,s[0],s[1],s[2])},uvec4(t,e,i,s){t.uniform4ui(e,s[0],s[1],s[2],s[3])},bvec2(t,e,i,s){t.uniform2i(e,s[0],s[1])},bvec3(t,e,i,s){t.uniform3i(e,s[0],s[1],s[2])},bvec4(t,e,i,s){t.uniform4i(e,s[0],s[1],s[2],s[3])},mat2(t,e,i,s){t.uniformMatrix2fv(e,!1,s)},mat4(t,e,i,s){t.uniformMatrix4fv(e,!1,s)}},Iy={float(t,e,i,s){t.uniform1fv(e,s)},vec2(t,e,i,s){t.uniform2fv(e,s)},vec3(t,e,i,s){t.uniform3fv(e,s)},vec4(t,e,i,s){t.uniform4fv(e,s)},int(t,e,i,s){t.uniform1iv(e,s)},ivec2(t,e,i,s){t.uniform2iv(e,s)},ivec3(t,e,i,s){t.uniform3iv(e,s)},ivec4(t,e,i,s){t.uniform4iv(e,s)},uint(t,e,i,s){t.uniform1uiv(e,s)},uvec2(t,e,i,s){t.uniform2uiv(e,s)},uvec3(t,e,i,s){t.uniform3uiv(e,s)},uvec4(t,e,i,s){t.uniform4uiv(e,s)},bool(t,e,i,s){t.uniform1iv(e,s)},bvec2(t,e,i,s){t.uniform2iv(e,s)},bvec3(t,e,i,s){t.uniform3iv(e,s)},bvec4(t,e,i,s){t.uniform4iv(e,s)},sampler2D(t,e,i,s){t.uniform1iv(e,s)},samplerCube(t,e,i,s){t.uniform1iv(e,s)},sampler2DArray(t,e,i,s){t.uniform1iv(e,s)}};Object.assign(zm.prototype,{systemCheck(){},syncUniforms(t,e){const{shader:i,renderer:s}=this;!function(t,e,i,s,r){let n=0,o=null,a=null;const l=r.gl;for(const h in t.uniforms){const u=e[h],c=s[h],d=i[h],p=t.uniforms[h];u?"float"!==u.type||1!==u.size||u.isArray?"bool"!==u.type||1!==u.size||u.isArray?"sampler2D"!==u.type&&"samplerCube"!==u.type&&"sampler2DArray"!==u.type||1!==u.size||u.isArray?"mat3"!==u.type||1!==u.size||u.isArray?"vec2"!==u.type||1!==u.size||u.isArray?"vec4"!==u.type||1!==u.size||u.isArray?(1!==u.size||u.isArray?Iy:Ay)[u.type].call(null,l,d.location,d.value,c):void 0!==p.width?(a=d.value,o=c,(a[0]!==o.x||a[1]!==o.y||a[2]!==o.width||a[3]!==o.height)&&(a[0]=o.x,a[1]=o.y,a[2]=o.width,a[3]=o.height,l.uniform4f(d.location,o.x,o.y,o.width,o.height))):(a=d.value,o=c,(a[0]!==o[0]||a[1]!==o[1]||a[2]!==o[2]||a[3]!==o[3])&&(a[0]=o[0],a[1]=o[1],a[2]=o[2],a[3]=o[3],l.uniform4f(d.location,o[0],o[1],o[2],o[3]))):void 0!==p.x?(a=d.value,o=c,(a[0]!==o.x||a[1]!==o.y)&&(a[0]=o.x,a[1]=o.y,l.uniform2f(d.location,o.x,o.y))):(a=d.value,o=c,(a[0]!==o[0]||a[1]!==o[1])&&(a[0]=o[0],a[1]=o[1],l.uniform2f(d.location,o[0],o[1]))):void 0!==p.a?l.uniformMatrix3fv(d.location,!1,c.toArray(!0)):l.uniformMatrix3fv(d.location,!1,c):(r.texture.bind(c,n),d.value!==n&&(d.value=n,l.uniform1i(d.location,n)),n++):c!==d.value&&(d.value=c,l.uniform1i(d.location,Number(c))):c!==d.value&&(d.value=c,l.uniform1f(d.location,c)):!0===p.group&&r.shader.syncUniformGroup(c)}}(t,i.program.uniformData,e.uniformData,t.uniforms,s)}});const Sy=new class{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this.tickerAdded=!1,this._pauseUpdate=!0}init(t){this.removeTickerListener(),this.events=t,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this.tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(t){this._pauseUpdate=t}addTickerListener(){this.tickerAdded||!this.domElement||(ag.system.add(this.tickerUpdate,this,rg.INTERACTION),this.tickerAdded=!0)}removeTickerListener(){this.tickerAdded&&(ag.system.remove(this.tickerUpdate,this),this.tickerAdded=!1)}pointerMoved(){this._didMove=!0}update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove)return void(this._didMove=!1);const t=this.events.rootPointerEvent;this.events.supportsTouchEvents&&"touch"===t.pointerType||globalThis.document.dispatchEvent(new PointerEvent("pointermove",{clientX:t.clientX,clientY:t.clientY}))}tickerUpdate(t){this._deltaTime+=t,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this.update())}};class Cy{constructor(t){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=Cy.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new Kp,this.page=new Kp,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=t}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(t,e,i){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(t,e,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}}class My extends Cy{constructor(){super(...arguments),this.client=new Kp,this.movement=new Kp,this.offset=new Kp,this.global=new Kp,this.screen=new Kp}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(t,e,i){return t.worldTransform.applyInverse(i||this.global,e)}getModifierState(t){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(t)}initMouseEvent(t,e,i,s,r,n,o,a,l,h,u,c,d,p,f){throw new Error("Method not implemented.")}}class Oy extends My{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return"pointermove"===this.type||"mousemove"===this.type||"touchmove"===this.type?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class Ny extends My{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}Ny.DOM_DELTA_PIXEL=0,Ny.DOM_DELTA_LINE=1,Ny.DOM_DELTA_PAGE=2;const Ly=new Kp,Ry=new Kp;class ky{constructor(t){this.dispatch=new kh,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=/* @__PURE__ */new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=t,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(t,e){this.mappingTable[t]||(this.mappingTable[t]=[]),this.mappingTable[t].push({fn:e,priority:0}),this.mappingTable[t].sort((t,e)=>t.priority-e.priority)}dispatchEvent(t,e){t.propagationStopped=!1,t.propagationImmediatelyStopped=!1,this.propagate(t,e),this.dispatch.emit(e||t.type,t)}mapEvent(t){if(!this.rootTarget)return;const e=this.mappingTable[t.type];if(e)for(let i=0,s=e.length;i<s;i++)e[i].fn(t);else console.warn(`[EventBoundary]: Event mapping not defined for ${t.type}`)}hitTest(t,e){Sy.pauseUpdate=!0;const i=this[this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive"](this.rootTarget,this.rootTarget.eventMode,Ly.set(t,e),this.hitTestFn,this.hitPruneFn);return i&&i[0]}propagate(t,e){if(!t.target)return;const i=t.composedPath();t.eventPhase=t.CAPTURING_PHASE;for(let s=0,r=i.length-1;s<r;s++)if(t.currentTarget=i[s],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return;if(t.eventPhase=t.AT_TARGET,t.currentTarget=t.target,this.notifyTarget(t,e),!t.propagationStopped&&!t.propagationImmediatelyStopped){t.eventPhase=t.BUBBLING_PHASE;for(let s=i.length-2;s>=0;s--)if(t.currentTarget=i[s],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return}}all(t,e,i=this._allInteractiveElements){if(0===i.length)return;t.eventPhase=t.BUBBLING_PHASE;const s=Array.isArray(e)?e:[e];for(let r=i.length-1;r>=0;r--)s.forEach(e=>{t.currentTarget=i[r],this.notifyTarget(t,e)})}propagationPath(t){const e=[t];for(let i=0;i<2048&&t!==this.rootTarget;i++){if(!t.parent)throw new Error("Cannot find propagation path to disconnected target");e.push(t.parent),t=t.parent}return e.reverse(),e}hitTestMoveRecursive(t,e,i,s,r,n=!1){let o=!1;if(this._interactivePrune(t))return null;if(("dynamic"===t.eventMode||"dynamic"===e)&&(Sy.pauseUpdate=!1),t.interactiveChildren&&t.children){const a=t.children;for(let l=a.length-1;l>=0;l--){const h=a[l],u=this.hitTestMoveRecursive(h,this._isInteractive(e)?e:h.eventMode,i,s,r,n||r(t,i));if(u){if(u.length>0&&!u[u.length-1].parent)continue;const e=t.isInteractive();(u.length>0||e)&&(e&&this._allInteractiveElements.push(t),u.push(t)),0===this._hitElements.length&&(this._hitElements=u),o=!0}}}const a=this._isInteractive(e),l=t.isInteractive();return a&&l&&this._allInteractiveElements.push(t),n||this._hitElements.length>0?null:o?this._hitElements:a&&!r(t,i)&&s(t,i)?l?[t]:[]:null}hitTestRecursive(t,e,i,s,r){if(this._interactivePrune(t)||r(t,i))return null;if(("dynamic"===t.eventMode||"dynamic"===e)&&(Sy.pauseUpdate=!1),t.interactiveChildren&&t.children){const n=t.children;for(let o=n.length-1;o>=0;o--){const a=n[o],l=this.hitTestRecursive(a,this._isInteractive(e)?e:a.eventMode,i,s,r);if(l){if(l.length>0&&!l[l.length-1].parent)continue;const e=t.isInteractive();return(l.length>0||e)&&l.push(t),l}}}const n=this._isInteractive(e),o=t.isInteractive();return n&&s(t,i)?o?[t]:[]:null}_isInteractive(t){return"static"===t||"dynamic"===t}_interactivePrune(t){return!(t&&!t.isMask&&t.visible&&t.renderable&&"none"!==t.eventMode&&("passive"!==t.eventMode||t.interactiveChildren)&&!t.isMask)}hitPruneFn(t,e){if(t.hitArea&&(t.worldTransform.applyInverse(e,Ry),!t.hitArea.contains(Ry.x,Ry.y)))return!0;if(t._mask){const i=t._mask.isMaskData?t._mask.maskObject:t._mask;if(i&&!i.containsPoint?.(e))return!0}return!1}hitTestFn(t,e){return"passive"!==t.eventMode&&(!!t.hitArea||!!t.containsPoint&&t.containsPoint(e))}notifyTarget(t,e){const i=`on${e=e??t.type}`;t.currentTarget[i]?.(t);const s=t.eventPhase===t.CAPTURING_PHASE||t.eventPhase===t.AT_TARGET?`${e}capture`:e;this.notifyListeners(t,s),t.eventPhase===t.AT_TARGET&&this.notifyListeners(t,e)}mapPointerDown(t){if(!(t instanceof Oy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.createPointerEvent(t);if(this.dispatchEvent(e,"pointerdown"),"touch"===e.pointerType)this.dispatchEvent(e,"touchstart");else if("mouse"===e.pointerType||"pen"===e.pointerType){const t=2===e.button;this.dispatchEvent(e,t?"rightdown":"mousedown")}this.trackingData(t.pointerId).pressTargetsByButton[t.button]=e.composedPath(),this.freeEvent(e)}mapPointerMove(t){if(!(t instanceof Oy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const e=this.createPointerEvent(t);this._isPointerMoveEvent=!1;const i="mouse"===e.pointerType||"pen"===e.pointerType,s=this.trackingData(t.pointerId),r=this.findMountedTarget(s.overTargets);if(s.overTargets?.length>0&&r!==e.target){const s="mousemove"===t.type?"mouseout":"pointerout",n=this.createPointerEvent(t,s,r);if(this.dispatchEvent(n,"pointerout"),i&&this.dispatchEvent(n,"mouseout"),!e.composedPath().includes(r)){const s=this.createPointerEvent(t,"pointerleave",r);for(s.eventPhase=s.AT_TARGET;s.target&&!e.composedPath().includes(s.target);)s.currentTarget=s.target,this.notifyTarget(s),i&&this.notifyTarget(s,"mouseleave"),s.target=s.target.parent;this.freeEvent(s)}this.freeEvent(n)}if(r!==e.target){const s="mousemove"===t.type?"mouseover":"pointerover",n=this.clonePointerEvent(e,s);this.dispatchEvent(n,"pointerover"),i&&this.dispatchEvent(n,"mouseover");let o=r?.parent;for(;o&&o!==this.rootTarget.parent&&o!==e.target;)o=o.parent;if(!o||o===this.rootTarget.parent){const t=this.clonePointerEvent(e,"pointerenter");for(t.eventPhase=t.AT_TARGET;t.target&&t.target!==r&&t.target!==this.rootTarget.parent;)t.currentTarget=t.target,this.notifyTarget(t),i&&this.notifyTarget(t,"mouseenter"),t.target=t.target.parent;this.freeEvent(t)}this.freeEvent(n)}const n=[],o=this.enableGlobalMoveEvents??!0;this.moveOnAll?n.push("pointermove"):this.dispatchEvent(e,"pointermove"),o&&n.push("globalpointermove"),"touch"===e.pointerType&&(this.moveOnAll?n.splice(1,0,"touchmove"):this.dispatchEvent(e,"touchmove"),o&&n.push("globaltouchmove")),i&&(this.moveOnAll?n.splice(1,0,"mousemove"):this.dispatchEvent(e,"mousemove"),o&&n.push("globalmousemove"),this.cursor=e.target?.cursor),n.length>0&&this.all(e,n),this._allInteractiveElements.length=0,this._hitElements.length=0,s.overTargets=e.composedPath(),this.freeEvent(e)}mapPointerOver(t){if(!(t instanceof Oy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.trackingData(t.pointerId),i=this.createPointerEvent(t),s="mouse"===i.pointerType||"pen"===i.pointerType;this.dispatchEvent(i,"pointerover"),s&&this.dispatchEvent(i,"mouseover"),"mouse"===i.pointerType&&(this.cursor=i.target?.cursor);const r=this.clonePointerEvent(i,"pointerenter");for(r.eventPhase=r.AT_TARGET;r.target&&r.target!==this.rootTarget.parent;)r.currentTarget=r.target,this.notifyTarget(r),s&&this.notifyTarget(r,"mouseenter"),r.target=r.target.parent;e.overTargets=i.composedPath(),this.freeEvent(i),this.freeEvent(r)}mapPointerOut(t){if(!(t instanceof Oy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.trackingData(t.pointerId);if(e.overTargets){const i="mouse"===t.pointerType||"pen"===t.pointerType,s=this.findMountedTarget(e.overTargets),r=this.createPointerEvent(t,"pointerout",s);this.dispatchEvent(r),i&&this.dispatchEvent(r,"mouseout");const n=this.createPointerEvent(t,"pointerleave",s);for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),i&&this.notifyTarget(n,"mouseleave"),n.target=n.target.parent;e.overTargets=null,this.freeEvent(r),this.freeEvent(n)}this.cursor=null}mapPointerUp(t){if(!(t instanceof Oy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=performance.now(),i=this.createPointerEvent(t);if(this.dispatchEvent(i,"pointerup"),"touch"===i.pointerType)this.dispatchEvent(i,"touchend");else if("mouse"===i.pointerType||"pen"===i.pointerType){const t=2===i.button;this.dispatchEvent(i,t?"rightup":"mouseup")}const s=this.trackingData(t.pointerId),r=this.findMountedTarget(s.pressTargetsByButton[t.button]);let n=r;if(r&&!i.composedPath().includes(r)){let e=r;for(;e&&!i.composedPath().includes(e);){if(i.currentTarget=e,this.notifyTarget(i,"pointerupoutside"),"touch"===i.pointerType)this.notifyTarget(i,"touchendoutside");else if("mouse"===i.pointerType||"pen"===i.pointerType){const t=2===i.button;this.notifyTarget(i,t?"rightupoutside":"mouseupoutside")}e=e.parent}delete s.pressTargetsByButton[t.button],n=e}if(n){const r=this.clonePointerEvent(i,"click");r.target=n,r.path=null,s.clicksByButton[t.button]||(s.clicksByButton[t.button]={clickCount:0,target:r.target,timeStamp:e});const o=s.clicksByButton[t.button];if(o.target===r.target&&e-o.timeStamp<200?++o.clickCount:o.clickCount=1,o.target=r.target,o.timeStamp=e,r.detail=o.clickCount,"mouse"===r.pointerType){const t=2===r.button;this.dispatchEvent(r,t?"rightclick":"click")}else"touch"===r.pointerType&&this.dispatchEvent(r,"tap");this.dispatchEvent(r,"pointertap"),this.freeEvent(r)}this.freeEvent(i)}mapPointerUpOutside(t){if(!(t instanceof Oy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.trackingData(t.pointerId),i=this.findMountedTarget(e.pressTargetsByButton[t.button]),s=this.createPointerEvent(t);if(i){let r=i;for(;r;)s.currentTarget=r,this.notifyTarget(s,"pointerupoutside"),"touch"===s.pointerType?this.notifyTarget(s,"touchendoutside"):("mouse"===s.pointerType||"pen"===s.pointerType)&&this.notifyTarget(s,2===s.button?"rightupoutside":"mouseupoutside"),r=r.parent;delete e.pressTargetsByButton[t.button]}this.freeEvent(s)}mapWheel(t){if(!(t instanceof Ny))return void console.warn("EventBoundary cannot map a non-wheel event as a wheel event");const e=this.createWheelEvent(t);this.dispatchEvent(e),this.freeEvent(e)}findMountedTarget(t){if(!t)return null;let e=t[0];for(let i=1;i<t.length&&t[i].parent===e;i++)e=t[i];return e}createPointerEvent(t,e,i){const s=this.allocateEvent(Oy);return this.copyPointerData(t,s),this.copyMouseData(t,s),this.copyData(t,s),s.nativeEvent=t.nativeEvent,s.originalEvent=t,s.target=i??this.hitTest(s.global.x,s.global.y)??this._hitElements[0],"string"==typeof e&&(s.type=e),s}createWheelEvent(t){const e=this.allocateEvent(Ny);return this.copyWheelData(t,e),this.copyMouseData(t,e),this.copyData(t,e),e.nativeEvent=t.nativeEvent,e.originalEvent=t,e.target=this.hitTest(e.global.x,e.global.y),e}clonePointerEvent(t,e){const i=this.allocateEvent(Oy);return i.nativeEvent=t.nativeEvent,i.originalEvent=t.originalEvent,this.copyPointerData(t,i),this.copyMouseData(t,i),this.copyData(t,i),i.target=t.target,i.path=t.composedPath().slice(),i.type=e??i.type,i}copyWheelData(t,e){e.deltaMode=t.deltaMode,e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ}copyPointerData(t,e){t instanceof Oy&&e instanceof Oy&&(e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist)}copyMouseData(t,e){t instanceof My&&e instanceof My&&(e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.copyFrom(t.client),e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.copyFrom(t.movement),e.screen.copyFrom(t.screen),e.shiftKey=t.shiftKey,e.global.copyFrom(t.global))}copyData(t,e){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.detail=t.detail,e.view=t.view,e.which=t.which,e.layer.copyFrom(t.layer),e.page.copyFrom(t.page)}trackingData(t){return this.mappingState.trackingData[t]||(this.mappingState.trackingData[t]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[t]}allocateEvent(t){this.eventPool.has(t)||this.eventPool.set(t,[]);const e=this.eventPool.get(t).pop()||new t(this);return e.eventPhase=e.NONE,e.currentTarget=null,e.path=null,e.target=null,e}freeEvent(t){if(t.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const e=t.constructor;this.eventPool.has(e)||this.eventPool.set(e,[]),this.eventPool.get(e).push(t)}notifyListeners(t,e){const i=t.currentTarget._events[e];if(i&&t.currentTarget.isInteractive())if("fn"in i)i.once&&t.currentTarget.removeListener(e,i.fn,void 0,!0),i.fn.call(i.context,t);else for(let s=0,r=i.length;s<r&&!t.propagationImmediatelyStopped;s++)i[s].once&&t.currentTarget.removeListener(e,i[s].fn,void 0,!0),i[s].fn.call(i[s].context,t)}}const By={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},Fy=class t{constructor(e){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=e,this.rootBoundary=new ky(null),Sy.init(this),this.autoPreventDefault=!0,this.eventsAdded=!1,this.rootPointerEvent=new Oy(null),this.rootWheelEvent=new Ny(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...t.defaultEventFeatures},{set:(t,e,i)=>("globalMove"===e&&(this.rootBoundary.enableGlobalMoveEvents=i),t[e]=i,!0)}),this.onPointerDown=this.onPointerDown.bind(this),this.onPointerMove=this.onPointerMove.bind(this),this.onPointerUp=this.onPointerUp.bind(this),this.onPointerOverOut=this.onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{view:i,resolution:s}=this.renderer;this.setTargetElement(i),this.resolution=s,t._defaultEventMode=e.eventMode??"auto",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(t){this.resolution=t}destroy(){this.setTargetElement(null),this.renderer=null}setCursor(t){t=t||"default";let e=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(e=!1),this.currentCursor===t)return;this.currentCursor=t;const i=this.cursorStyles[t];if(i)switch(typeof i){case"string":e&&(this.domElement.style.cursor=i);break;case"function":i(t);break;case"object":e&&Object.assign(this.domElement.style,i)}else e&&"string"==typeof t&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,t)&&(this.domElement.style.cursor=t)}get pointer(){return this.rootPointerEvent}onPointerDown(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this.normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&(t.cancelable||!("cancelable"in t))&&t.preventDefault();for(let i=0,s=e.length;i<s;i++){const t=e[i],s=this.bootstrapEvent(this.rootPointerEvent,t);this.rootBoundary.mapEvent(s)}this.setCursor(this.rootBoundary.cursor)}onPointerMove(t){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,Sy.pointerMoved();const e=this.normalizeToPointerData(t);for(let i=0,s=e.length;i<s;i++){const t=this.bootstrapEvent(this.rootPointerEvent,e[i]);this.rootBoundary.mapEvent(t)}this.setCursor(this.rootBoundary.cursor)}onPointerUp(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let e=t.target;t.composedPath&&t.composedPath().length>0&&(e=t.composedPath()[0]);const i=e!==this.domElement?"outside":"",s=this.normalizeToPointerData(t);for(let r=0,n=s.length;r<n;r++){const t=this.bootstrapEvent(this.rootPointerEvent,s[r]);t.type+=i,this.rootBoundary.mapEvent(t)}this.setCursor(this.rootBoundary.cursor)}onPointerOverOut(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this.normalizeToPointerData(t);for(let i=0,s=e.length;i<s;i++){const t=this.bootstrapEvent(this.rootPointerEvent,e[i]);this.rootBoundary.mapEvent(t)}this.setCursor(this.rootBoundary.cursor)}onWheel(t){if(!this.features.wheel)return;const e=this.normalizeWheelEvent(t);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(e)}setTargetElement(t){this.removeEvents(),this.domElement=t,Sy.domElement=t,this.addEvents()}addEvents(){if(this.eventsAdded||!this.domElement)return;Sy.addTickerListener();const t=this.domElement.style;t&&(globalThis.navigator.msPointerEnabled?(t.msContentZooming="none",t.msTouchAction="none"):this.supportsPointerEvents&&(t.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this.onPointerMove,!0),this.domElement.addEventListener("pointerdown",this.onPointerDown,!0),this.domElement.addEventListener("pointerleave",this.onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this.onPointerOverOut,!0),globalThis.addEventListener("pointerup",this.onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this.onPointerMove,!0),this.domElement.addEventListener("mousedown",this.onPointerDown,!0),this.domElement.addEventListener("mouseout",this.onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this.onPointerOverOut,!0),globalThis.addEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this.onPointerDown,!0),this.domElement.addEventListener("touchend",this.onPointerUp,!0),this.domElement.addEventListener("touchmove",this.onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this.eventsAdded=!0}removeEvents(){if(!this.eventsAdded||!this.domElement)return;Sy.removeTickerListener();const t=this.domElement.style;globalThis.navigator.msPointerEnabled?(t.msContentZooming="",t.msTouchAction=""):this.supportsPointerEvents&&(t.touchAction=""),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this.onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this.onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this.onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this.onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this.onPointerMove,!0),this.domElement.removeEventListener("mousedown",this.onPointerDown,!0),this.domElement.removeEventListener("mouseout",this.onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this.onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this.onPointerDown,!0),this.domElement.removeEventListener("touchend",this.onPointerUp,!0),this.domElement.removeEventListener("touchmove",this.onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this.eventsAdded=!1}mapPositionToPoint(t,e,i){const s=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},r=1/this.resolution;t.x=(e-s.left)*(this.domElement.width/s.width)*r,t.y=(i-s.top)*(this.domElement.height/s.height)*r}normalizeToPointerData(t){const e=[];if(this.supportsTouchEvents&&t instanceof TouchEvent)for(let i=0,s=t.changedTouches.length;i<s;i++){const s=t.changedTouches[i];typeof s.button>"u"&&(s.button=0),typeof s.buttons>"u"&&(s.buttons=1),typeof s.isPrimary>"u"&&(s.isPrimary=1===t.touches.length&&"touchstart"===t.type),typeof s.width>"u"&&(s.width=s.radiusX||1),typeof s.height>"u"&&(s.height=s.radiusY||1),typeof s.tiltX>"u"&&(s.tiltX=0),typeof s.tiltY>"u"&&(s.tiltY=0),typeof s.pointerType>"u"&&(s.pointerType="touch"),typeof s.pointerId>"u"&&(s.pointerId=s.identifier||0),typeof s.pressure>"u"&&(s.pressure=s.force||.5),typeof s.twist>"u"&&(s.twist=0),typeof s.tangentialPressure>"u"&&(s.tangentialPressure=0),typeof s.layerX>"u"&&(s.layerX=s.offsetX=s.clientX),typeof s.layerY>"u"&&(s.layerY=s.offsetY=s.clientY),s.isNormalized=!0,s.type=t.type,e.push(s)}else if(globalThis.MouseEvent&&(!(t instanceof MouseEvent)||this.supportsPointerEvents&&t instanceof globalThis.PointerEvent))e.push(t);else{const i=t;typeof i.isPrimary>"u"&&(i.isPrimary=!0),typeof i.width>"u"&&(i.width=1),typeof i.height>"u"&&(i.height=1),typeof i.tiltX>"u"&&(i.tiltX=0),typeof i.tiltY>"u"&&(i.tiltY=0),typeof i.pointerType>"u"&&(i.pointerType="mouse"),typeof i.pointerId>"u"&&(i.pointerId=1),typeof i.pressure>"u"&&(i.pressure=.5),typeof i.twist>"u"&&(i.twist=0),typeof i.tangentialPressure>"u"&&(i.tangentialPressure=0),i.isNormalized=!0,e.push(i)}return e}normalizeWheelEvent(t){const e=this.rootWheelEvent;return this.transferMouseData(e,t),e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ,e.deltaMode=t.deltaMode,this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.nativeEvent=t,e.type=t.type,e}bootstrapEvent(t,e){return t.originalEvent=null,t.nativeEvent=e,t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist,this.transferMouseData(t,e),this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.isTrusted=e.isTrusted,"pointerleave"===t.type&&(t.type="pointerout"),t.type.startsWith("mouse")&&(t.type=t.type.replace("mouse","pointer")),t.type.startsWith("touch")&&(t.type=By[t.type]||t.type),t}transferMouseData(t,e){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.x=e.clientX,t.client.y=e.clientY,t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.x=e.movementX,t.movement.y=e.movementY,t.page.x=e.pageX,t.page.y=e.pageY,t.relatedTarget=null,t.shiftKey=e.shiftKey}};Fy.extension={name:"events",type:[_p.RendererSystem,_p.CanvasRendererSystem]},Fy.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let Dy=Fy;function Uy(t){return"dynamic"===t||"static"===t}Ep.add(Dy);const Gy={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,_internalInteractive:void 0,get interactive(){return this._internalInteractive??Uy(Dy.defaultEventMode)},set interactive(t){dd("7.2.0","Setting interactive is deprecated, use eventMode = 'none'/'passive'/'auto'/'static'/'dynamic' instead."),this._internalInteractive=t,this.eventMode=t?"static":"auto"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??Dy.defaultEventMode},set eventMode(t){this._internalInteractive=Uy(t),this._internalEventMode=t},isInteractive(){return"static"===this.eventMode||"dynamic"===this.eventMode},interactiveChildren:!0,hitArea:null,addEventListener(t,e,i){const s="boolean"==typeof i&&i||"object"==typeof i&&i.capture,r="object"==typeof i?i.signal:void 0,n="object"==typeof i&&!0===i.once,o="function"==typeof e?void 0:e;t=s?`${t}capture`:t;const a="function"==typeof e?e:e.handleEvent,l=this;r&&r.addEventListener("abort",()=>{l.off(t,a,o)}),n?l.once(t,a,o):l.on(t,a,o)},removeEventListener(t,e,i){const s="function"==typeof e?void 0:e;t="boolean"==typeof i&&i||"object"==typeof i&&i.capture?`${t}capture`:t,e="function"==typeof e?e:e.handleEvent,this.off(t,e,s)},dispatchEvent(t){if(!(t instanceof Cy))throw new Error("DisplayObject cannot propagate events outside of the Federated Events API");return t.defaultPrevented=!1,t.path=null,t.target=this,t.manager.dispatchEvent(t),!t.defaultPrevented}};Ag.mixin(Gy);const Xy=new Qp;class Wy{constructor(t){this.renderer=t}async image(t,e,i,s){const r=new Image;return r.src=await this.base64(t,e,i,s),r}async base64(t,e,i,s){const r=this.canvas(t,s);if(void 0!==r.toBlob)return new Promise((t,s)=>{r.toBlob(e=>{if(!e)return void s(new Error("ICanvas.toBlob failed!"));const i=new FileReader;i.onload=()=>t(i.result),i.onerror=s,i.readAsDataURL(e)},e,i)});if(void 0!==r.toDataURL)return r.toDataURL(e,i);if(void 0!==r.convertToBlob){const t=await r.convertToBlob({type:e,quality:i});return new Promise((e,i)=>{const s=new FileReader;s.onload=()=>e(s.result),s.onerror=i,s.readAsDataURL(t)})}throw new Error("CanvasExtract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(t,e){const i=this.renderer;if(!i)throw new Error("The CanvasExtract has already been destroyed");let s,r,n;t&&(t instanceof am?n=t:(n=i.generateTexture(t,{region:e,resolution:i.resolution}),e&&(Xy.width=e.width,Xy.height=e.height,e=Xy))),n?(s=n.baseTexture._canvasRenderTarget.context,r=n.baseTexture._canvasRenderTarget.resolution,e=e??n.frame):(s=i.canvasContext.rootContext,r=i._view.resolution,e||((e=Xy).width=i.width/r,e.height=i.height/r));const o=Math.round(e.x*r),a=Math.round(e.y*r),l=Math.max(Math.round(e.width*r),1),h=Math.max(Math.round(e.height*r),1),u=new pp(l,h,1),c=s.getImageData(o,a,l,h);return u.context.putImageData(c,0,0),u.canvas}pixels(t,e){const i=this.renderer;if(!i)throw new Error("The CanvasExtract has already been destroyed");let s,r,n;t&&(t instanceof am?n=t:(n=i.generateTexture(t,{region:e,resolution:i.resolution}),e&&(Xy.width=e.width,Xy.height=e.height,e=Xy))),n?(s=n.baseTexture._canvasRenderTarget.context,r=n.baseTexture._canvasRenderTarget.resolution,e=e??n.frame):(s=i.canvasContext.rootContext,r=i.resolution,e||((e=Xy).width=i.width/r,e.height=i.height/r));const o=Math.round(e.x*r),a=Math.round(e.y*r),l=Math.max(Math.round(e.width*r),1),h=Math.max(Math.round(e.height*r),1);return s.getImageData(o,a,l,h).data}destroy(){this.renderer=null}}let Yy;function Hy(t){const e=ph.ADAPTER.createCanvas(6,1),i=e.getContext("2d");return i.fillStyle=t,i.fillRect(0,0,6,1),e}function $y(){if(typeof document>"u")return!1;if(void 0!==Yy)return Yy;const t=Hy("#ff00ff"),e=Hy("#ffff00"),i=ph.ADAPTER.createCanvas(6,1).getContext("2d");i.globalCompositeOperation="multiply",i.drawImage(t,0,0),i.drawImage(e,2,0);const s=i.getImageData(2,0,1,1);if(s){const t=s.data;Yy=255===t[0]&&0===t[1]&&0===t[2]}else Yy=!1;return Yy}Wy.extension={name:"extract",type:_p.CanvasRendererSystem},Ep.add(Wy),Bp.prototype.getDrawableSource=function(){const t=this.resource;return t?t.bitmap||t.source:null},tm.prototype._canvasRenderTarget=null,om.prototype.patternCache=null,om.prototype.tintCache=null;const jy=new nf;class zy{constructor(t){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=function(t=[]){return $y()?(t[Kl.NORMAL]="source-over",t[Kl.ADD]="lighter",t[Kl.MULTIPLY]="multiply",t[Kl.SCREEN]="screen",t[Kl.OVERLAY]="overlay",t[Kl.DARKEN]="darken",t[Kl.LIGHTEN]="lighten",t[Kl.COLOR_DODGE]="color-dodge",t[Kl.COLOR_BURN]="color-burn",t[Kl.HARD_LIGHT]="hard-light",t[Kl.SOFT_LIGHT]="soft-light",t[Kl.DIFFERENCE]="difference",t[Kl.EXCLUSION]="exclusion",t[Kl.HUE]="hue",t[Kl.SATURATION]="saturation",t[Kl.COLOR]="color",t[Kl.LUMINOSITY]="luminosity"):(t[Kl.NORMAL]="source-over",t[Kl.ADD]="lighter",t[Kl.MULTIPLY]="source-over",t[Kl.SCREEN]="source-over",t[Kl.OVERLAY]="source-over",t[Kl.DARKEN]="source-over",t[Kl.LIGHTEN]="source-over",t[Kl.COLOR_DODGE]="source-over",t[Kl.COLOR_BURN]="source-over",t[Kl.HARD_LIGHT]="source-over",t[Kl.SOFT_LIGHT]="source-over",t[Kl.DIFFERENCE]="source-over",t[Kl.EXCLUSION]="source-over",t[Kl.HUE]="source-over",t[Kl.SATURATION]="source-over",t[Kl.COLOR]="source-over",t[Kl.LUMINOSITY]="source-over"),t[Kl.NORMAL_NPM]=t[Kl.NORMAL],t[Kl.ADD_NPM]=t[Kl.ADD],t[Kl.SCREEN_NPM]=t[Kl.SCREEN],t[Kl.SRC_IN]="source-in",t[Kl.SRC_OUT]="source-out",t[Kl.SRC_ATOP]="source-atop",t[Kl.DST_OVER]="destination-over",t[Kl.DST_IN]="destination-in",t[Kl.DST_OUT]="destination-out",t[Kl.DST_ATOP]="destination-atop",t[Kl.XOR]="xor",t[Kl.SUBTRACT]="source-over",t}(),this._activeBlendMode=null,this._projTransform=null,this._outerBlend=!1,this.renderer=t}init(){const t=this.renderer.background.alpha<1;if(this.rootContext=this.renderer.view.getContext("2d",{alpha:t}),this.activeContext=this.rootContext,!this.rootContext.imageSmoothingEnabled){const t=this.rootContext;t.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":t.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":t.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":t.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")}}setContextTransform(t,e,i){let s=t;const r=this._projTransform,n=this.activeResolution;i=i||n,r&&(s=jy,s.copyFrom(t),s.prepend(r)),e?this.activeContext.setTransform(s.a*i,s.b*i,s.c*i,s.d*i,s.tx*n|0,s.ty*n|0):this.activeContext.setTransform(s.a*i,s.b*i,s.c*i,s.d*i,s.tx*n,s.ty*n)}clear(t,e){const{activeContext:i,renderer:s}=this,r=t?qd.shared.setValue(t):this.renderer.background.backgroundColor;i.clearRect(0,0,s.width,s.height),t&&(i.globalAlpha=e??this.renderer.background.alpha,i.fillStyle=r.toHex(),i.fillRect(0,0,s.width,s.height),i.globalAlpha=1)}setBlendMode(t,e){const i=t===Kl.SRC_IN||t===Kl.SRC_OUT||t===Kl.DST_IN||t===Kl.DST_ATOP;!e&&i&&(t=Kl.NORMAL),this._activeBlendMode!==t&&(this._activeBlendMode=t,this._outerBlend=i,this.activeContext.globalCompositeOperation=this.blendModes[t])}resize(){this.smoothProperty&&(this.rootContext[this.smoothProperty]=Bp.defaultOptions.scaleMode===sh.LINEAR)}invalidateBlendMode(){this._activeBlendMode=this.blendModes.indexOf(this.activeContext.globalCompositeOperation)}destroy(){this.renderer=null,this.rootContext=null,this.activeContext=null,this.smoothProperty=null}}zy.extension={type:_p.CanvasRendererSystem,name:"canvasContext"},Ep.add(zy);class Vy{constructor(t){this._foundShapes=[],this.renderer=t}pushMask(t){const e=this.renderer,i=t.maskObject||t;e.canvasContext.activeContext.save();const s=this._foundShapes;if(this.recursiveFindShapes(i,s),s.length>0){const t=e.canvasContext.activeContext;t.beginPath();for(let e=0;e<s.length;e++){const t=s[e],i=t.transform.worldTransform;this.renderer.canvasContext.setContextTransform(i),this.renderGraphicsShape(t)}s.length=0,t.clip()}}recursiveFindShapes(t,e){t.geometry&&t.geometry.graphicsData&&e.push(t);const{children:i}=t;if(i)for(let s=0;s<i.length;s++)this.recursiveFindShapes(i[s],e)}renderGraphicsShape(t){t.finishPoly();const e=this.renderer.canvasContext.activeContext,i=t.geometry.graphicsData,s=i.length;if(0!==s)for(let r=0;r<s;r++){const t=i[r],s=t.shape;if(s.type===Jp.POLY){let i=s.points;const r=t.holes;let n,o,a,l;e.moveTo(i[0],i[1]);for(let t=1;t<i.length/2;t++)e.lineTo(i[2*t],i[2*t+1]);if(r.length>0){n=0,a=i[0],l=i[1];for(let t=2;t+2<i.length;t+=2)n+=(i[t]-a)*(i[t+3]-l)-(i[t+2]-a)*(i[t+1]-l);for(let t=0;t<r.length;t++)if(i=r[t].shape.points,i){o=0,a=i[0],l=i[1];for(let t=2;t+2<i.length;t+=2)o+=(i[t]-a)*(i[t+3]-l)-(i[t+2]-a)*(i[t+1]-l);if(o*n<0){e.moveTo(i[0],i[1]);for(let t=2;t<i.length;t+=2)e.lineTo(i[t],i[t+1])}else{e.moveTo(i[i.length-2],i[i.length-1]);for(let t=i.length-4;t>=0;t-=2)e.lineTo(i[t],i[t+1])}r[t].shape.closeStroke&&e.closePath()}}i[0]===i[i.length-2]&&i[1]===i[i.length-1]&&e.closePath()}else if(s.type===Jp.RECT)e.rect(s.x,s.y,s.width,s.height),e.closePath();else if(s.type===Jp.CIRC)e.arc(s.x,s.y,s.radius,0,2*Math.PI),e.closePath();else if(s.type===Jp.ELIP){const t=2*s.width,i=2*s.height,r=s.x-t/2,n=s.y-i/2,o=.5522848,a=t/2*o,l=i/2*o,h=r+t,u=n+i,c=r+t/2,d=n+i/2;e.moveTo(r,d),e.bezierCurveTo(r,d-l,c-a,n,c,n),e.bezierCurveTo(c+a,n,h,d-l,h,d),e.bezierCurveTo(h,d+l,c+a,u,c,u),e.bezierCurveTo(c-a,u,r,d+l,r,d),e.closePath()}else if(s.type===Jp.RREC){const t=s.x,i=s.y,r=s.width,n=s.height;let o=s.radius;const a=Math.min(r,n)/2;o=o>a?a:o,e.moveTo(t,i+o),e.lineTo(t,i+n-o),e.quadraticCurveTo(t,i+n,t+o,i+n),e.lineTo(t+r-o,i+n),e.quadraticCurveTo(t+r,i+n,t+r,i+n-o),e.lineTo(t+r,i+o),e.quadraticCurveTo(t+r,i,t+r-o,i),e.lineTo(t+o,i),e.quadraticCurveTo(t,i,t,i+o),e.closePath()}}}popMask(t){t.canvasContext.activeContext.restore(),t.canvasContext.invalidateBlendMode()}destroy(){}}Vy.extension={type:_p.CanvasRendererSystem,name:"mask"},Ep.add(Vy);class qy{constructor(t){this.renderer=t}render(t,e){const i=this.renderer;if(!i.view)return;const s=i.canvasContext;let r,n,o,a;e&&(r=e.renderTexture,n=e.clear,o=e.transform,a=e.skipUpdateTransform),this.renderingToScreen=!r,i.emit("prerender");const l=i.resolution;r?(r=r.castToBaseTexture(),r._canvasRenderTarget||(r._canvasRenderTarget=new pp(r.width,r.height,r.resolution),r.resource=new yg(r._canvasRenderTarget.canvas),r.valid=!0),s.activeContext=r._canvasRenderTarget.context,i.canvasContext.activeResolution=r._canvasRenderTarget.resolution):(s.activeContext=s.rootContext,s.activeResolution=l);const h=s.activeContext;if(s._projTransform=o||null,r||(this.lastObjectRendered=t),!a){const e=t.enableTempParent();t.updateTransform(),t.disableTempParent(e)}if(h.save(),h.setTransform(1,0,0,1,0,0),h.globalAlpha=1,s._activeBlendMode=Kl.NORMAL,s._outerBlend=!1,h.globalCompositeOperation=s.blendModes[Kl.NORMAL],n??i.background.clearBeforeRender)if(this.renderingToScreen){h.clearRect(0,0,i.width,i.height);const t=i.background;t.alpha>0&&(h.globalAlpha=t.backgroundColor.alpha,h.fillStyle=t.backgroundColor.toHex(),h.fillRect(0,0,i.width,i.height),h.globalAlpha=1)}else r._canvasRenderTarget.clear(),r.clear.alpha>0&&(h.globalAlpha=r.clear.alpha,h.fillStyle=r.clear.toHex(),h.fillRect(0,0,r.realWidth,r.realHeight),h.globalAlpha=1);const u=s.activeContext;s.activeContext=h,t.renderCanvas(i),s.activeContext=u,h.restore(),s.activeResolution=l,s._projTransform=null,i.emit("postrender")}destroy(){this.lastObjectRendered=null,this.render=null}}qy.extension={type:_p.CanvasRendererSystem,name:"objectRenderer"},Ep.add(qy);const{deprecation:Jy}=bp,Ky=class t extends Km{constructor(e){super(),this.type=ql.CANVAS,this.rendererLogId="Canvas",e=Object.assign({},ph.RENDER_OPTIONS,e);const i={runners:["init","destroy","contextChange","resolutionChange","reset","update","postrender","prerender","resize"],systems:t.__systems,priority:["textureGenerator","background","_view","_plugin","startup","mask","canvasContext","objectRenderer"]};this.setup(i),"useContextAlpha"in e&&(Jy("7.0.0","options.useContextAlpha is deprecated, use options.backgroundAlpha instead"),e.backgroundAlpha=!1===e.useContextAlpha?1:e.backgroundAlpha),this._plugin.rendererPlugins=t.__plugins,this.options=e,this.startup.run(this.options)}static test(){return!0}generateTexture(t,e){return this.textureGenerator.generateTexture(t,e)}reset(){}render(t,e){this.objectRenderer.render(t,e)}clear(){this.canvasContext.clear()}destroy(t){this.runners.destroy.items.reverse(),this.emitWithCustomOptions(this.runners.destroy,{_view:t}),super.destroy()}get plugins(){return this._plugin.plugins}resize(t,e){this._view.resizeView(t,e)}get width(){return this._view.element.width}get height(){return this._view.element.height}get resolution(){return this._view.resolution}set resolution(t){this._view.resolution=t,this.runners.resolutionChange.emit(t)}get autoDensity(){return this._view.autoDensity}get view(){return this._view.element}get screen(){return this._view.screen}get lastObjectRendered(){return this.objectRenderer.lastObjectRendered}get renderingToScreen(){return this.objectRenderer.renderingToScreen}get clearBeforeRender(){return this.background.clearBeforeRender}get blendModes(){return Jy("7.0.0","renderer.blendModes has been deprecated, please use renderer.canvasContext.blendModes instead"),this.canvasContext.blendModes}get maskManager(){return Jy("7.0.0","renderer.maskManager has been deprecated, please use renderer.mask instead"),this.mask}get refresh(){return Jy("7.0.0","renderer.refresh has been deprecated"),!0}get rootContext(){return Jy("7.0.0","renderer.rootContext has been deprecated, please use renderer.canvasContext.rootContext instead"),this.canvasContext.rootContext}get context(){return Jy("7.0.0","renderer.context has been deprecated, please use renderer.canvasContext.activeContext instead"),this.canvasContext.activeContext}get smoothProperty(){return Jy("7.0.0","renderer.smoothProperty has been deprecated, please use renderer.canvasContext.smoothProperty instead"),this.canvasContext.smoothProperty}setBlendMode(t,e){Jy("7.0.0","renderer.setBlendMode has been deprecated, use renderer.canvasContext.setBlendMode instead"),this.canvasContext.setBlendMode(t,e)}invalidateBlendMode(){Jy("7.0.0","renderer.invalidateBlendMode has been deprecated, use renderer.canvasContext.invalidateBlendMode instead"),this.canvasContext.invalidateBlendMode()}setContextTransform(t,e,i){Jy("7.0.0","renderer.setContextTransform has been deprecated, use renderer.canvasContext.setContextTransform instead"),this.canvasContext.setContextTransform(t,e,i)}get backgroundColor(){return Jy("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color}set backgroundColor(t){Jy("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color=t}get backgroundAlpha(){return Jy("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha}set backgroundAlpha(t){Jy("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha=t}get preserveDrawingBuffer(){return Jy("7.0.0","renderer.preserveDrawingBuffer has been deprecated"),!1}get useContextAlpha(){return Jy("7.0.0","renderer.useContextAlpha has been deprecated"),!1}};Ky.extension={type:_p.Renderer,priority:0},Ky.__plugins={},Ky.__systems={};let Zy=Ky;Ep.handleByMap(_p.CanvasRendererPlugin,Zy.__plugins),Ep.handleByMap(_p.CanvasRendererSystem,Zy.__systems),Ep.add(Zy);const Qy={canvas:null,getTintedCanvas:(t,e)=>{const i=t.texture,s=qd.shared.setValue(e).toHex();i.tintCache=i.tintCache||{};const r=i.tintCache[s];let n;if(r){if(r.tintId===i._updateID)return i.tintCache[s];n=i.tintCache[s]}else n=ph.ADAPTER.createCanvas();if(Qy.tintMethod(i,e,n),n.tintId=i._updateID,Qy.convertTintToImage&&void 0!==n.toDataURL){const t=new Image;t.src=n.toDataURL(),i.tintCache[s]=t}else i.tintCache[s]=n;return n},getTintedPattern:(t,e)=>{const i=qd.shared.setValue(e).toHex();t.patternCache=t.patternCache||{};let s=t.patternCache[i];return s?.tintId===t._updateID||(Qy.canvas||(Qy.canvas=ph.ADAPTER.createCanvas()),Qy.tintMethod(t,e,Qy.canvas),s=Qy.canvas.getContext("2d").createPattern(Qy.canvas,"repeat"),s.tintId=t._updateID,t.patternCache[i]=s),s},tintWithMultiply:(t,e,i)=>{const s=i.getContext("2d"),r=t._frame.clone(),n=t.baseTexture.resolution;r.x*=n,r.y*=n,r.width*=n,r.height*=n,i.width=Math.ceil(r.width),i.height=Math.ceil(r.height),s.save(),s.fillStyle=qd.shared.setValue(e).toHex(),s.fillRect(0,0,r.width,r.height),s.globalCompositeOperation="multiply";const o=t.baseTexture.getDrawableSource();s.drawImage(o,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.globalCompositeOperation="destination-atop",s.drawImage(o,r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore()},tintWithOverlay:(t,e,i)=>{const s=i.getContext("2d"),r=t._frame.clone(),n=t.baseTexture.resolution;r.x*=n,r.y*=n,r.width*=n,r.height*=n,i.width=Math.ceil(r.width),i.height=Math.ceil(r.height),s.save(),s.globalCompositeOperation="copy",s.fillStyle=`#${`00000${(0|e).toString(16)}`.slice(-6)}`,s.fillRect(0,0,r.width,r.height),s.globalCompositeOperation="destination-atop",s.drawImage(t.baseTexture.getDrawableSource(),r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore()},tintWithPerPixel:(t,e,i)=>{const s=i.getContext("2d"),r=t._frame.clone(),n=t.baseTexture.resolution;r.x*=n,r.y*=n,r.width*=n,r.height*=n,i.width=Math.ceil(r.width),i.height=Math.ceil(r.height),s.save(),s.globalCompositeOperation="copy",s.drawImage(t.baseTexture.getDrawableSource(),r.x,r.y,r.width,r.height,0,0,r.width,r.height),s.restore();const[o,a,l]=qd.shared.setValue(e).toArray(),h=s.getImageData(0,0,r.width,r.height),u=h.data;for(let c=0;c<u.length;c+=4)u[c+0]*=o,u[c+1]*=a,u[c+2]*=l;s.putImageData(h,0,0)},roundColor:t=>(dd("7.3.0","PIXI.canvasUtils.roundColor is deprecated"),qd.shared.setValue(t).round(Qy.cacheStepsPerColorChannel).toNumber()),cacheStepsPerColorChannel:8,convertTintToImage:!1,canUseMultiply:$y(),tintMethod:null};let tv;Qy.tintMethod=Qy.canUseMultiply?Qy.tintWithMultiply:Qy.tintWithPerPixel;const ev=new nf;ay.prototype.generateCanvasTexture=function(t,e=1){const i=this.getLocalBounds(new Qp);i.width=Math.max(i.width,1/e),i.height=Math.max(i.height,1/e);const s=am.create({width:i.width,height:i.height,scaleMode:t,resolution:e});tv||(tv=new Zy),this.transform.updateLocalTransform(),this.transform.localTransform.copyTo(ev),ev.invert(),ev.tx-=i.x,ev.ty-=i.y,tv.render(this,{renderTexture:s,clear:!0,transform:ev});const r=om.from(s.baseTexture._canvasRenderTarget.canvas,{scaleMode:t});return r.baseTexture.setResolution(e),r},ay.prototype.cachedGraphicsData=[],ay.prototype._renderCanvas=function(t){!0!==this.isMask&&(this.finishPoly(),t.plugins.graphics.render(this))};class iv{static offsetPolygon(t,e){const i=[],s=t.length;e=iv.isPolygonClockwise(t)?e:-1*e;for(let r=0;r<s;r+=2){let n=r-2;n<0&&(n+=s);const o=(r+2)%s;let a=t[r]-t[n],l=t[r+1]-t[n+1],h=Math.sqrt(a*a+l*l);a/=h,l/=h,a*=e,l*=e;const u=-l,c=a,d=[t[n]+u,t[n+1]+c],p=[t[r]+u,t[r+1]+c];let f=t[o]-t[r],m=t[o+1]-t[r+1];h=Math.sqrt(f*f+m*m),f/=h,m/=h,f*=e,m*=e;const g=-m,y=f,v=[t[r]+g,t[r+1]+y],x=[t[o]+g,t[o+1]+y],b=iv.findIntersection(d[0],d[1],p[0],p[1],v[0],v[1],x[0],x[1]);b&&i.push(...b)}return i}static findIntersection(t,e,i,s,r,n,o,a){const l=(a-n)*(i-t)-(o-r)*(s-e),h=(o-r)*(e-n)-(a-n)*(t-r);if(0===l)return 0===h&&0===(i-t)*(e-n)-(s-e)*(t-r)?[(t+i)/2,(e+s)/2]:null;const u=h/l;return[t+u*(i-t),e+u*(s-e)]}static isPolygonClockwise(t){let e=0;for(let i=0,s=t.length-2;i<t.length;s=i,i+=2)e+=(t[i]-t[s])*(t[i+1]+t[s+1]);return e>0}}class sv{constructor(t){this._svgMatrix=null,this._tempMatrix=new nf,this.renderer=t}_calcCanvasStyle(t,e){let i;return t.texture&&t.texture.baseTexture!==om.WHITE.baseTexture?t.texture.valid?(i=Qy.getTintedPattern(t.texture,e),this.setPatternTransform(i,t.matrix||nf.IDENTITY)):i="#808080":i=`#${`00000${(0|e).toString(16)}`.slice(-6)}`,i}render(t){const e=this.renderer,i=e.canvasContext.activeContext,s=t.worldAlpha,r=t.transform.worldTransform;e.canvasContext.setContextTransform(r),e.canvasContext.setBlendMode(t.blendMode);const n=t.geometry.graphicsData;let o,a;const l=qd.shared.setValue(t.tint).toArray();for(let h=0;h<n.length;h++){const t=n[h],u=t.shape,c=t.fillStyle,d=t.lineStyle,p=0|t.fillStyle.color,f=0|t.lineStyle.color;if(t.matrix&&e.canvasContext.setContextTransform(r.copyTo(this._tempMatrix).append(t.matrix)),c.visible&&(o=this._calcCanvasStyle(c,qd.shared.setValue(p).multiply(l).toNumber())),d.visible&&(a=this._calcCanvasStyle(d,qd.shared.setValue(f).multiply(l).toNumber())),i.lineWidth=d.width,i.lineCap=d.cap,i.lineJoin=d.join,i.miterLimit=d.miterLimit,t.type===Jp.POLY){i.beginPath();const e=u;let r=e.points;const n=t.holes;let l,h,p,f,m;i.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)i.lineTo(r[t],r[t+1]);if(e.closeStroke&&i.closePath(),n.length>0){m=[],l=0,p=r[0],f=r[1];for(let t=2;t+2<r.length;t+=2)l+=(r[t]-p)*(r[t+3]-f)-(r[t+2]-p)*(r[t+1]-f);for(let t=0;t<n.length;t++)if(r=n[t].shape.points,r){h=0,p=r[0],f=r[1];for(let t=2;t+2<r.length;t+=2)h+=(r[t]-p)*(r[t+3]-f)-(r[t+2]-p)*(r[t+1]-f);if(h*l<0){i.moveTo(r[0],r[1]);for(let t=2;t<r.length;t+=2)i.lineTo(r[t],r[t+1])}else{i.moveTo(r[r.length-2],r[r.length-1]);for(let t=r.length-4;t>=0;t-=2)i.lineTo(r[t],r[t+1])}n[t].shape.closeStroke&&i.closePath(),m[t]=h*l<0}}c.visible&&(i.globalAlpha=c.alpha*s,i.fillStyle=o,i.fill()),d.visible&&this.paintPolygonStroke(e,d,a,n,m,s,i)}else if(t.type===Jp.RECT){const t=u;if(c.visible&&(i.globalAlpha=c.alpha*s,i.fillStyle=o,i.fillRect(t.x,t.y,t.width,t.height)),d.visible){const e=d.width*(.5-(1-d.alignment)),r=t.width+2*e,n=t.height+2*e;i.globalAlpha=d.alpha*s,i.strokeStyle=a,i.strokeRect(t.x-e,t.y-e,r,n)}}else if(t.type===Jp.CIRC){const t=u;if(i.beginPath(),i.arc(t.x,t.y,t.radius,0,2*Math.PI),i.closePath(),c.visible&&(i.globalAlpha=c.alpha*s,i.fillStyle=o,i.fill()),d.visible){if(.5!==d.alignment){const e=d.width*(.5-(1-d.alignment));i.beginPath(),i.arc(t.x,t.y,t.radius+e,0,2*Math.PI),i.closePath()}i.globalAlpha=d.alpha*s,i.strokeStyle=a,i.stroke()}}else if(t.type===Jp.ELIP){const t=u,e=1===d.alignment;if(e||this.paintEllipse(t,c,d,o,s,i),d.visible){if(.5!==d.alignment){const e=.5522848,s=d.width*(.5-(1-d.alignment)),r=2*(t.width+s),n=2*(t.height+s),o=t.x-r/2,a=t.y-n/2,l=r/2*e,h=n/2*e,u=o+r,c=a+n,p=o+r/2,f=a+n/2;i.beginPath(),i.moveTo(o,f),i.bezierCurveTo(o,f-h,p-l,a,p,a),i.bezierCurveTo(p+l,a,u,f-h,u,f),i.bezierCurveTo(u,f+h,p+l,c,p,c),i.bezierCurveTo(p-l,c,o,f+h,o,f),i.closePath()}i.globalAlpha=d.alpha*s,i.strokeStyle=a,i.stroke()}e&&this.paintEllipse(t,c,d,o,s,i)}else if(t.type===Jp.RREC){const t=u,e=1===d.alignment;if(e||this.paintRoundedRectangle(t,c,d,o,s,i),d.visible){if(.5!==d.alignment){const e=t.width,s=t.height,r=d.width*(.5-(1-d.alignment)),n=t.x-r,o=t.y-r,a=t.width+2*r,l=t.height+2*r,h=r*(d.alignment>=1?Math.min(a/e,l/s):Math.min(e/a,s/l));let u=t.radius+h;const c=Math.min(a,l)/2;u=u>c?c:u,i.beginPath(),i.moveTo(n,o+u),i.lineTo(n,o+l-u),i.quadraticCurveTo(n,o+l,n+u,o+l),i.lineTo(n+a-u,o+l),i.quadraticCurveTo(n+a,o+l,n+a,o+l-u),i.lineTo(n+a,o+u),i.quadraticCurveTo(n+a,o,n+a-u,o),i.lineTo(n+u,o),i.quadraticCurveTo(n,o,n,o+u),i.closePath()}i.globalAlpha=d.alpha*s,i.strokeStyle=a,i.stroke()}e&&this.paintRoundedRectangle(t,c,d,o,s,i)}}}paintPolygonStroke(t,e,i,s,r,n,o){if(.5!==e.alignment){const i=e.width*(.5-(1-e.alignment));let n,a=iv.offsetPolygon(t.points,i);o.beginPath(),o.moveTo(a[0],a[1]);for(let t=2;t<a.length;t+=2)o.lineTo(a[t],a[t+1]);t.closeStroke&&o.closePath();for(let t=0;t<s.length;t++){if(n=s[t].shape.points,a=iv.offsetPolygon(n,i),r[t]){o.moveTo(a[0],a[1]);for(let t=2;t<a.length;t+=2)o.lineTo(a[t],a[t+1])}else{o.moveTo(a[a.length-2],a[a.length-1]);for(let t=a.length-4;t>=0;t-=2)o.lineTo(a[t],a[t+1])}s[t].shape.closeStroke&&o.closePath()}}o.globalAlpha=e.alpha*n,o.strokeStyle=i,o.stroke()}paintEllipse(t,e,i,s,r,n){const o=2*t.width,a=2*t.height,l=t.x-o/2,h=t.y-a/2,u=.5522848,c=o/2*u,d=a/2*u,p=l+o,f=h+a,m=l+o/2,g=h+a/2;0===i.alignment&&n.save(),n.beginPath(),n.moveTo(l,g),n.bezierCurveTo(l,g-d,m-c,h,m,h),n.bezierCurveTo(m+c,h,p,g-d,p,g),n.bezierCurveTo(p,g+d,m+c,f,m,f),n.bezierCurveTo(m-c,f,l,g+d,l,g),n.closePath(),0===i.alignment&&n.clip(),e.visible&&(n.globalAlpha=e.alpha*r,n.fillStyle=s,n.fill()),0===i.alignment&&n.restore()}paintRoundedRectangle(t,e,i,s,r,n){const o=t.x,a=t.y,l=t.width,h=t.height;let u=t.radius;const c=Math.min(l,h)/2;u=u>c?c:u,0===i.alignment&&n.save(),n.beginPath(),n.moveTo(o,a+u),n.lineTo(o,a+h-u),n.quadraticCurveTo(o,a+h,o+u,a+h),n.lineTo(o+l-u,a+h),n.quadraticCurveTo(o+l,a+h,o+l,a+h-u),n.lineTo(o+l,a+u),n.quadraticCurveTo(o+l,a,o+l-u,a),n.lineTo(o+u,a),n.quadraticCurveTo(o,a,o,a+u),n.closePath(),0===i.alignment&&n.clip(),e.visible&&(n.globalAlpha=e.alpha*r,n.fillStyle=s,n.fill()),0===i.alignment&&n.restore()}setPatternTransform(t,e){if(!1!==this._svgMatrix){if(!this._svgMatrix){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");if(e?.createSVGMatrix&&(this._svgMatrix=e.createSVGMatrix()),!this._svgMatrix||!t.setTransform)return void(this._svgMatrix=!1)}this._svgMatrix.a=e.a,this._svgMatrix.b=e.b,this._svgMatrix.c=e.c,this._svgMatrix.d=e.d,this._svgMatrix.e=e.tx,this._svgMatrix.f=e.ty,t.setTransform(this._svgMatrix.inverse())}}destroy(){this.renderer=null,this._svgMatrix=null,this._tempMatrix=null}}sv.extension={name:"graphics",type:_p.CanvasRendererPlugin},Ep.add(sv);class rv{constructor(t){this.maxItemsPerFrame=t,this.itemsLeft=0}beginFrame(){this.itemsLeft=this.maxItemsPerFrame}allowedToUpload(){return this.itemsLeft-- >0}}function nv(t,e){let i=!1;if(t?._textures?.length)for(let s=0;s<t._textures.length;s++)if(t._textures[s]instanceof om){const r=t._textures[s].baseTexture;e.includes(r)||(e.push(r),i=!0)}return i}function ov(t,e){if(t.baseTexture instanceof Bp){const i=t.baseTexture;return e.includes(i)||e.push(i),!0}return!1}function av(t,e){if(t._texture&&t._texture instanceof om){const i=t._texture.baseTexture;return e.includes(i)||e.push(i),!0}return!1}function lv(t,e){return e instanceof xy&&(e.updateText(!0),!0)}function hv(t,e){if(e instanceof fy){const t=e.toFontString();return cy.measureFont(t),!0}return!1}function uv(t,e){if(t instanceof xy){e.includes(t.style)||e.push(t.style),e.includes(t)||e.push(t);const i=t._texture.baseTexture;return e.includes(i)||e.push(i),!0}return!1}function cv(t,e){return t instanceof fy&&(e.includes(t)||e.push(t),!0)}const dv=class t{constructor(e){this.limiter=new rv(t.uploadsPerFrame),this.renderer=e,this.uploadHookHelper=null,this.queue=[],this.addHooks=[],this.uploadHooks=[],this.completes=[],this.ticking=!1,this.delayedTick=()=>{this.queue&&this.prepareItems()},this.registerFindHook(uv),this.registerFindHook(cv),this.registerFindHook(nv),this.registerFindHook(ov),this.registerFindHook(av),this.registerUploadHook(lv),this.registerUploadHook(hv)}upload(t){return new Promise(e=>{t&&this.add(t),this.queue.length?(this.completes.push(e),this.ticking||(this.ticking=!0,ag.system.addOnce(this.tick,this,rg.UTILITY))):e()})}tick(){setTimeout(this.delayedTick,0)}prepareItems(){for(this.limiter.beginFrame();this.queue.length&&this.limiter.allowedToUpload();){const t=this.queue[0];let e=!1;if(t&&!t._destroyed)for(let i=0,s=this.uploadHooks.length;i<s;i++)if(this.uploadHooks[i](this.uploadHookHelper,t)){this.queue.shift(),e=!0;break}e||this.queue.shift()}if(this.queue.length)ag.system.addOnce(this.tick,this,rg.UTILITY);else{this.ticking=!1;const t=this.completes.slice(0);this.completes.length=0;for(let e=0,i=t.length;e<i;e++)t[e]()}}registerFindHook(t){return t&&this.addHooks.push(t),this}registerUploadHook(t){return t&&this.uploadHooks.push(t),this}add(t){for(let e=0,i=this.addHooks.length;e<i&&!this.addHooks[e](t,this.queue);e++);if(t instanceof Og)for(let e=t.children.length-1;e>=0;e--)this.add(t.children[e]);return this}destroy(){this.ticking&&ag.system.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.limiter=null,this.uploadHookHelper=null}};dv.uploadsPerFrame=4;let pv=dv;function fv(t,e){return e instanceof Bp&&(e._glTextures[t.CONTEXT_UID]||t.texture.bind(e),!0)}function mv(t,e){if(!(e instanceof ay))return!1;const{geometry:i}=e;e.finishPoly(),i.updateBatches();const{batches:s}=i;for(let r=0;r<s.length;r++){const{texture:e}=s[r].style;e&&fv(t,e.baseTexture)}return i.batchable||t.geometry.bind(i,e._resolveDirectShader(t)),!0}function gv(t,e){return t instanceof ay&&(e.push(t),!0)}Object.defineProperties(ph,{UPLOADS_PER_FRAME:{get:()=>pv.uploadsPerFrame,set(t){dd("7.1.0","settings.UPLOADS_PER_FRAME is deprecated, use prepare.BasePrepare.uploadsPerFrame"),pv.uploadsPerFrame=t}}});class yv extends pv{constructor(t){super(t),this.uploadHookHelper=this.renderer,this.registerFindHook(gv),this.registerUploadHook(fv),this.registerUploadHook(mv)}}yv.extension={name:"prepare",type:_p.RendererSystem},Ep.add(yv);function vv(t,e){const i=t;if(e instanceof Bp){const t=e.source,s=0===t.width?i.canvas.width:Math.min(i.canvas.width,t.width),r=0===t.height?i.canvas.height:Math.min(i.canvas.height,t.height);return i.ctx.drawImage(t,0,0,s,r,0,0,i.canvas.width,i.canvas.height),!0}return!1}class xv extends pv{constructor(t){super(t),this.uploadHookHelper=this,this.canvas=ph.ADAPTER.createCanvas(16,16),this.ctx=this.canvas.getContext("2d"),this.registerUploadHook(vv)}destroy(){super.destroy(),this.ctx=null,this.canvas=null}}xv.extension={name:"prepare",type:_p.CanvasRendererSystem},Ep.add(xv),Rg.prototype._tintedCanvas=null,Rg.prototype._renderCanvas=function(t){t.plugins.sprite.render(this)};const bv=new nf;class _v{constructor(t){this.renderer=t}render(t){const e=t._texture,i=this.renderer,s=i.canvasContext.activeContext,r=i.canvasContext.activeResolution;if(!e.valid)return;const n=e._frame.width,o=e._frame.height;let a=e._frame.width,l=e._frame.height;e.trim&&(a=e.trim.width,l=e.trim.height);let h=t.transform.worldTransform,u=0,c=0;const d=e.baseTexture.getDrawableSource();if(e.orig.width<=0||e.orig.height<=0||!e.valid||!d)return;i.canvasContext.setBlendMode(t.blendMode,!0),s.globalAlpha=t.worldAlpha;const p=e.baseTexture.scaleMode===sh.LINEAR,f=i.canvasContext.smoothProperty;f&&s[f]!==p&&(s[f]=p),e.trim?(u=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,c=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(u=(.5-t.anchor.x)*e.orig.width,c=(.5-t.anchor.y)*e.orig.height),e.rotate&&(h.copyTo(bv),h=bv,pf.matrixAppendRotationInv(h,e.rotate,u,c),u=0,c=0),u-=a/2,c-=l/2,i.canvasContext.setContextTransform(h,t.roundPixels,1),t.roundPixels&&(u|=0,c|=0);const m=e.baseTexture.resolution,g=i.canvasContext._outerBlend;g&&(s.save(),s.beginPath(),s.rect(u*r,c*r,a*r,l*r),s.clip()),16777215!==t.tint?((t._cachedTint!==t.tintValue||t._tintedCanvas.tintId!==t._texture._updateID)&&(t._cachedTint=t.tintValue,t._tintedCanvas=Qy.getTintedCanvas(t,t.tintValue)),s.drawImage(t._tintedCanvas,0,0,Math.floor(n*m),Math.floor(o*m),Math.floor(u*r),Math.floor(c*r),Math.floor(a*r),Math.floor(l*r))):s.drawImage(d,e._frame.x*m,e._frame.y*m,Math.floor(n*m),Math.floor(o*m),Math.floor(u*r),Math.floor(c*r),Math.floor(a*r),Math.floor(l*r)),g&&s.restore(),i.canvasContext.setBlendMode(Kl.NORMAL)}destroy(){this.renderer=null}}_v.extension={name:"sprite",type:_p.CanvasRendererPlugin},Ep.add(_v);var wv=Object.defineProperty,Pv=(t,e,i)=>(((t,e,i)=>{e in t?wv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i})(t,"symbol"!=typeof e?e+"":e,i),i);let Ev=class{constructor(t){Pv(this,"parent"),Pv(this,"paused"),this.parent=t,this.paused=!1}destroy(){}down(t){return!1}move(t){return!1}up(t){return!1}wheel(t){return!1}update(t){}resize(){}reset(){}pause(){this.paused=!0}resume(){this.paused=!1}};var Tv,Av=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Iv={exports:{}};Tv=Iv,function(){var t,e;e=t={linear:function(t,e,i,s){return i*t/s+e},easeInQuad:function(t,e,i,s){return i*(t/=s)*t+e},easeOutQuad:function(t,e,i,s){return-i*(t/=s)*(t-2)+e},easeInOutQuad:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e},easeInCubic:function(t,e,i,s){return i*(t/=s)*t*t+e},easeOutCubic:function(t,e,i,s){return i*((t=t/s-1)*t*t+1)+e},easeInOutCubic:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e},easeInQuart:function(t,e,i,s){return i*(t/=s)*t*t*t+e},easeOutQuart:function(t,e,i,s){return-i*((t=t/s-1)*t*t*t-1)+e},easeInOutQuart:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t*t+e:-i/2*((t-=2)*t*t*t-2)+e},easeInQuint:function(t,e,i,s){return i*(t/=s)*t*t*t*t+e},easeOutQuint:function(t,e,i,s){return i*((t=t/s-1)*t*t*t*t+1)+e},easeInOutQuint:function(t,e,i,s){return(t/=s/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e},easeInSine:function(t,e,i,s){return-i*Math.cos(t/s*(Math.PI/2))+i+e},easeOutSine:function(t,e,i,s){return i*Math.sin(t/s*(Math.PI/2))+e},easeInOutSine:function(t,e,i,s){return-i/2*(Math.cos(Math.PI*t/s)-1)+e},easeInExpo:function(t,e,i,s){return 0===t?e:i*Math.pow(2,10*(t/s-1))+e},easeOutExpo:function(t,e,i,s){return t===s?e+i:i*(1-Math.pow(2,-10*t/s))+e},easeInOutExpo:function(t,e,i,s){return(t/=s/2)<1?i/2*Math.pow(2,10*(t-1))+e:i/2*(2-Math.pow(2,-10*--t))+e},easeInCirc:function(t,e,i,s){return-i*(Math.sqrt(1-(t/=s)*t)-1)+e},easeOutCirc:function(t,e,i,s){return i*Math.sqrt(1-(t=t/s-1)*t)+e},easeInOutCirc:function(t,e,i,s){return(t/=s/2)<1?-i/2*(Math.sqrt(1-t*t)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e},easeInElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s),(n=0)||(n=.3*s),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),-r*Math.pow(2,10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)+e},easeOutElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s),(n=0)||(n=.3*s),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),r*Math.pow(2,-10*t)*Math.sin((t*s-o)*(2*Math.PI)/n)+i+e},easeInOutElastic:function(t,e,i,s){var r,n,o;return o=1.70158,0===t||(t/=s/2),(n=0)||(n=s*(.3*1.5)),(r=i)<Math.abs(i)?(r=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/r),t<1?r*Math.pow(2,10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)*-.5+e:r*Math.pow(2,-10*(t-=1))*Math.sin((t*s-o)*(2*Math.PI)/n)*.5+i+e},easeInBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),i*(t/=s)*t*((r+1)*t-r)+e},easeOutBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),i*((t=t/s-1)*t*((r+1)*t+r)+1)+e},easeInOutBack:function(t,e,i,s,r){return void 0===r&&(r=1.70158),(t/=s/2)<1?i/2*(t*t*((1+(r*=1.525))*t-r))+e:i/2*((t-=2)*t*((1+(r*=1.525))*t+r)+2)+e},easeInBounce:function(e,i,s,r){return s-t.easeOutBounce(r-e,0,s,r)+i},easeOutBounce:function(t,e,i,s){return(t/=s)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e},easeInOutBounce:function(e,i,s,r){return e<r/2?.5*t.easeInBounce(2*e,0,s,r)+i:.5*t.easeOutBounce(2*e-r,0,s,r)+.5*s+i}},Tv.exports=e}.call(Av);const Sv=Iv.exports;function Cv(t,e){return t?"function"==typeof t?t:"string"==typeof t?Sv[t]:void 0:Sv[e]}const Mv={removeOnInterrupt:!1,ease:"linear",time:1e3};let Ov=class extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"startX"),Pv(this,"startY"),Pv(this,"deltaX"),Pv(this,"deltaY"),Pv(this,"keepCenter"),Pv(this,"startWidth",null),Pv(this,"startHeight",null),Pv(this,"deltaWidth",null),Pv(this,"deltaHeight",null),Pv(this,"width",null),Pv(this,"height",null),Pv(this,"time",0),this.options=Object.assign({},Mv,e),this.options.ease=Cv(this.options.ease),this.setupPosition(),this.setupZoom(),this.time=0}setupPosition(){typeof this.options.position<"u"?(this.startX=this.parent.center.x,this.startY=this.parent.center.y,this.deltaX=this.options.position.x-this.parent.center.x,this.deltaY=this.options.position.y-this.parent.center.y,this.keepCenter=!1):this.keepCenter=!0}setupZoom(){this.width=null,this.height=null,typeof this.options.scale<"u"?this.width=this.parent.screenWidth/this.options.scale:typeof this.options.scaleX<"u"||typeof this.options.scaleY<"u"?(typeof this.options.scaleX<"u"&&(this.width=this.parent.screenWidth/this.options.scaleX),typeof this.options.scaleY<"u"&&(this.height=this.parent.screenHeight/this.options.scaleY)):(typeof this.options.width<"u"&&(this.width=this.options.width),typeof this.options.height<"u"&&(this.height=this.options.height)),null!==this.width&&(this.startWidth=this.parent.screenWidthInWorldPixels,this.deltaWidth=this.width-this.startWidth),null!==this.height&&(this.startHeight=this.parent.screenHeightInWorldPixels,this.deltaHeight=this.height-this.startHeight)}down(){return this.options.removeOnInterrupt&&this.parent.plugins.remove("animate"),!1}complete(){this.parent.plugins.remove("animate"),null!==this.width&&this.parent.fitWidth(this.width,this.keepCenter,null===this.height),null!==this.height&&this.parent.fitHeight(this.height,this.keepCenter,null===this.width),!this.keepCenter&&this.options.position&&this.parent.moveCenter(this.options.position),this.parent.emit("animate-end",this.parent),this.options.callbackOnComplete&&this.options.callbackOnComplete(this.parent)}update(t){if(this.paused)return;this.time+=t;const e=new Kp(this.parent.scale.x,this.parent.scale.y);if(this.time>=this.options.time){const t=this.parent.width,i=this.parent.height;this.complete(),(t!==this.parent.width||i!==this.parent.height)&&this.parent.emit("zoomed",{viewport:this.parent,original:e,type:"animate"})}else{const t=this.options.ease(this.time,0,1,this.options.time);if(null!==this.width){const e=this.startWidth,i=this.deltaWidth;this.parent.fitWidth(e+i*t,this.keepCenter,null===this.height)}if(null!==this.height){const e=this.startHeight,i=this.deltaHeight;this.parent.fitHeight(e+i*t,this.keepCenter,null===this.width)}if(null===this.width?this.parent.scale.x=this.parent.scale.y:null===this.height&&(this.parent.scale.y=this.parent.scale.x),!this.keepCenter){const e=this.startX,i=this.startY,s=this.deltaX,r=this.deltaY,n=new Kp(this.parent.x,this.parent.y);this.parent.moveCenter(e+s*t,i+r*t),this.parent.emit("moved",{viewport:this.parent,original:n,type:"animate"})}(this.width||this.height)&&this.parent.emit("zoomed",{viewport:this.parent,original:e,type:"animate"})}}};const Nv={sides:"all",friction:.5,time:150,ease:"easeInOutSine",underflow:"center",bounceBox:null};class Lv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"left"),Pv(this,"top"),Pv(this,"right"),Pv(this,"bottom"),Pv(this,"underflowX"),Pv(this,"underflowY"),Pv(this,"ease"),Pv(this,"toX"),Pv(this,"toY"),this.options=Object.assign({},Nv,e),this.ease=Cv(this.options.ease,"easeInOutSine"),this.options.sides?"all"===this.options.sides?this.top=this.bottom=this.left=this.right=!0:"horizontal"===this.options.sides?(this.right=this.left=!0,this.top=this.bottom=!1):"vertical"===this.options.sides?(this.left=this.right=!1,this.top=this.bottom=!0):(this.top=-1!==this.options.sides.indexOf("top"),this.bottom=-1!==this.options.sides.indexOf("bottom"),this.left=-1!==this.options.sides.indexOf("left"),this.right=-1!==this.options.sides.indexOf("right")):this.left=this.top=this.right=this.bottom=!1;const i=this.options.underflow.toLowerCase();"center"===i?(this.underflowX=0,this.underflowY=0):(this.underflowX=-1!==i.indexOf("left")?-1:-1!==i.indexOf("right")?1:0,this.underflowY=-1!==i.indexOf("top")?-1:-1!==i.indexOf("bottom")?1:0),this.reset()}isActive(){return null!==this.toX||null!==this.toY}down(){return this.toX=this.toY=null,!1}up(){return this.bounce(),!1}update(t){if(!this.paused){if(this.bounce(),this.toX){const e=this.toX;e.time+=t,this.parent.emit("moved",{viewport:this.parent,type:"bounce-x"}),e.time>=this.options.time?(this.parent.x=e.end,this.toX=null,this.parent.emit("bounce-x-end",this.parent)):this.parent.x=this.ease(e.time,e.start,e.delta,this.options.time)}if(this.toY){const e=this.toY;e.time+=t,this.parent.emit("moved",{viewport:this.parent,type:"bounce-y"}),e.time>=this.options.time?(this.parent.y=e.end,this.toY=null,this.parent.emit("bounce-y-end",this.parent)):this.parent.y=this.ease(e.time,e.start,e.delta,this.options.time)}}}calcUnderflowX(){let t;switch(this.underflowX){case-1:t=0;break;case 1:t=this.parent.screenWidth-this.parent.screenWorldWidth;break;default:t=(this.parent.screenWidth-this.parent.screenWorldWidth)/2}return t}calcUnderflowY(){let t;switch(this.underflowY){case-1:t=0;break;case 1:t=this.parent.screenHeight-this.parent.screenWorldHeight;break;default:t=(this.parent.screenHeight-this.parent.screenWorldHeight)/2}return t}oob(){const t=this.options.bounceBox;if(t){const e=typeof t.x>"u"?0:t.x,i=typeof t.y>"u"?0:t.y,s=typeof t.width>"u"?this.parent.worldWidth:t.width,r=typeof t.height>"u"?this.parent.worldHeight:t.height;return{left:this.parent.left<e,right:this.parent.right>s,top:this.parent.top<i,bottom:this.parent.bottom>r,topLeft:new Kp(e*this.parent.scale.x,i*this.parent.scale.y),bottomRight:new Kp(s*this.parent.scale.x-this.parent.screenWidth,r*this.parent.scale.y-this.parent.screenHeight)}}return{left:this.parent.left<0,right:this.parent.right>this.parent.worldWidth,top:this.parent.top<0,bottom:this.parent.bottom>this.parent.worldHeight,topLeft:new Kp(0,0),bottomRight:new Kp(this.parent.worldWidth*this.parent.scale.x-this.parent.screenWidth,this.parent.worldHeight*this.parent.scale.y-this.parent.screenHeight)}}bounce(){var t,e;if(this.paused)return;let i,s=this.parent.plugins.get("decelerate",!0);s&&(s.x||s.y)&&(s.x&&s.percentChangeX===(null==(t=s.options)?void 0:t.friction)||s.y&&s.percentChangeY===(null==(e=s.options)?void 0:e.friction))&&(i=this.oob(),(i.left&&this.left||i.right&&this.right)&&(s.percentChangeX=this.options.friction),(i.top&&this.top||i.bottom&&this.bottom)&&(s.percentChangeY=this.options.friction));const r=this.parent.plugins.get("drag",!0)||{},n=this.parent.plugins.get("pinch",!0)||{};if(s=s||{},!(null!=r&&r.active||null!=n&&n.active||this.toX&&this.toY||s.x&&s.y)){i=i||this.oob();const t=i.topLeft,e=i.bottomRight;if(!this.toX&&!s.x){let s=null;i.left&&this.left?s=this.parent.screenWorldWidth<this.parent.screenWidth?this.calcUnderflowX():-t.x:i.right&&this.right&&(s=this.parent.screenWorldWidth<this.parent.screenWidth?this.calcUnderflowX():-e.x),null!==s&&this.parent.x!==s&&(this.toX={time:0,start:this.parent.x,delta:s-this.parent.x,end:s},this.parent.emit("bounce-x-start",this.parent))}if(!this.toY&&!s.y){let s=null;i.top&&this.top?s=this.parent.screenWorldHeight<this.parent.screenHeight?this.calcUnderflowY():-t.y:i.bottom&&this.bottom&&(s=this.parent.screenWorldHeight<this.parent.screenHeight?this.calcUnderflowY():-e.y),null!==s&&this.parent.y!==s&&(this.toY={time:0,start:this.parent.y,delta:s-this.parent.y,end:s},this.parent.emit("bounce-y-start",this.parent))}}}reset(){this.toX=this.toY=null,this.bounce()}}const Rv={left:!1,right:!1,top:!1,bottom:!1,direction:null,underflow:"center"};class kv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"last"),Pv(this,"noUnderflow"),Pv(this,"underflowX"),Pv(this,"underflowY"),this.options=Object.assign({},Rv,e),this.options.direction&&(this.options.left="x"===this.options.direction||"all"===this.options.direction||null,this.options.right="x"===this.options.direction||"all"===this.options.direction||null,this.options.top="y"===this.options.direction||"all"===this.options.direction||null,this.options.bottom="y"===this.options.direction||"all"===this.options.direction||null),this.parseUnderflow(),this.last={x:null,y:null,scaleX:null,scaleY:null},this.update()}parseUnderflow(){const t=this.options.underflow.toLowerCase();"none"===t?this.noUnderflow=!0:"center"===t?(this.underflowX=this.underflowY=0,this.noUnderflow=!1):(this.underflowX=-1!==t.indexOf("left")?-1:-1!==t.indexOf("right")?1:0,this.underflowY=-1!==t.indexOf("top")?-1:-1!==t.indexOf("bottom")?1:0,this.noUnderflow=!1)}move(){return this.update(),!1}update(){if(this.paused||this.parent.x===this.last.x&&this.parent.y===this.last.y&&this.parent.scale.x===this.last.scaleX&&this.parent.scale.y===this.last.scaleY)return;const t=new Kp(this.parent.x,this.parent.y),e=this.parent.plugins.decelerate||{};if(null!==this.options.left||null!==this.options.right){let i=!1;if(!this.noUnderflow&&this.parent.screenWorldWidth<this.parent.screenWidth)switch(this.underflowX){case-1:0!==this.parent.x&&(this.parent.x=0,i=!0);break;case 1:this.parent.x!==this.parent.screenWidth-this.parent.screenWorldWidth&&(this.parent.x=this.parent.screenWidth-this.parent.screenWorldWidth,i=!0);break;default:this.parent.x!==(this.parent.screenWidth-this.parent.screenWorldWidth)/2&&(this.parent.x=(this.parent.screenWidth-this.parent.screenWorldWidth)/2,i=!0)}else null!==this.options.left&&this.parent.left<(!0===this.options.left?0:this.options.left)&&(this.parent.x=-(!0===this.options.left?0:this.options.left)*this.parent.scale.x,e.x=0,i=!0),null!==this.options.right&&this.parent.right>(!0===this.options.right?this.parent.worldWidth:this.options.right)&&(this.parent.x=-(!0===this.options.right?this.parent.worldWidth:this.options.right)*this.parent.scale.x+this.parent.screenWidth,e.x=0,i=!0);i&&this.parent.emit("moved",{viewport:this.parent,original:t,type:"clamp-x"})}if(null!==this.options.top||null!==this.options.bottom){let i=!1;if(!this.noUnderflow&&this.parent.screenWorldHeight<this.parent.screenHeight)switch(this.underflowY){case-1:0!==this.parent.y&&(this.parent.y=0,i=!0);break;case 1:this.parent.y!==this.parent.screenHeight-this.parent.screenWorldHeight&&(this.parent.y=this.parent.screenHeight-this.parent.screenWorldHeight,i=!0);break;default:this.parent.y!==(this.parent.screenHeight-this.parent.screenWorldHeight)/2&&(this.parent.y=(this.parent.screenHeight-this.parent.screenWorldHeight)/2,i=!0)}else null!==this.options.top&&this.parent.top<(!0===this.options.top?0:this.options.top)&&(this.parent.y=-(!0===this.options.top?0:this.options.top)*this.parent.scale.y,e.y=0,i=!0),null!==this.options.bottom&&this.parent.bottom>(!0===this.options.bottom?this.parent.worldHeight:this.options.bottom)&&(this.parent.y=-(!0===this.options.bottom?this.parent.worldHeight:this.options.bottom)*this.parent.scale.y+this.parent.screenHeight,e.y=0,i=!0);i&&this.parent.emit("moved",{viewport:this.parent,original:t,type:"clamp-y"})}this.last.x=this.parent.x,this.last.y=this.parent.y,this.last.scaleX=this.parent.scale.x,this.last.scaleY=this.parent.scale.y}reset(){this.update()}}const Bv={minWidth:null,minHeight:null,maxWidth:null,maxHeight:null,minScale:null,maxScale:null};class Fv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),this.options=Object.assign({},Bv,e),this.clamp()}resize(){this.clamp()}clamp(){if(!this.paused)if(this.options.minWidth||this.options.minHeight||this.options.maxWidth||this.options.maxHeight){let t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight;if(null!==this.options.minWidth&&t<this.options.minWidth){const i=this.parent.scale.x;this.parent.fitWidth(this.options.minWidth,!1,!1,!0),this.parent.scale.y*=this.parent.scale.x/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.maxWidth&&t>this.options.maxWidth){const i=this.parent.scale.x;this.parent.fitWidth(this.options.maxWidth,!1,!1,!0),this.parent.scale.y*=this.parent.scale.x/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.minHeight&&e<this.options.minHeight){const i=this.parent.scale.y;this.parent.fitHeight(this.options.minHeight,!1,!1,!0),this.parent.scale.x*=this.parent.scale.y/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.maxHeight&&e>this.options.maxHeight){const t=this.parent.scale.y;this.parent.fitHeight(this.options.maxHeight,!1,!1,!0),this.parent.scale.x*=this.parent.scale.y/t,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}}else if(this.options.minScale||this.options.maxScale){const t={x:null,y:null},e={x:null,y:null};if("number"==typeof this.options.minScale)t.x=this.options.minScale,t.y=this.options.minScale;else if(null!==this.options.minScale){const e=this.options.minScale;t.x=typeof e.x>"u"?null:e.x,t.y=typeof e.y>"u"?null:e.y}if("number"==typeof this.options.maxScale)e.x=this.options.maxScale,e.y=this.options.maxScale;else if(null!==this.options.maxScale){const t=this.options.maxScale;e.x=typeof t.x>"u"?null:t.x,e.y=typeof t.y>"u"?null:t.y}let i=this.parent.scale.x,s=this.parent.scale.y;null!==t.x&&i<t.x&&(i=t.x),null!==e.x&&i>e.x&&(i=e.x),null!==t.y&&s<t.y&&(s=t.y),null!==e.y&&s>e.y&&(s=e.y),(i!==this.parent.scale.x||s!==this.parent.scale.y)&&(this.parent.scale.set(i,s),this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"}))}}reset(){this.clamp()}}const Dv={friction:.98,bounce:.8,minSpeed:.01},Uv=16;class Gv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"x"),Pv(this,"y"),Pv(this,"percentChangeX"),Pv(this,"percentChangeY"),Pv(this,"saved"),Pv(this,"timeSinceRelease"),this.options=Object.assign({},Dv,e),this.saved=[],this.timeSinceRelease=0,this.reset(),this.parent.on("moved",t=>this.handleMoved(t))}down(){return this.saved=[],this.x=this.y=null,!1}isActive(){return!(!this.x&&!this.y)}move(){if(this.paused)return!1;const t=this.parent.input.count();return(1===t||t>1&&!this.parent.plugins.get("pinch",!0))&&(this.saved.push({x:this.parent.x,y:this.parent.y,time:performance.now()}),this.saved.length>60&&this.saved.splice(0,30)),!1}handleMoved(t){if(this.saved.length){const e=this.saved[this.saved.length-1];"clamp-x"===t.type&&t.original?e.x===t.original.x&&(e.x=this.parent.x):"clamp-y"===t.type&&t.original&&e.y===t.original.y&&(e.y=this.parent.y)}}up(){if(0===this.parent.input.count()&&this.saved.length){const t=performance.now();for(const e of this.saved)if(e.time>=t-100){const i=t-e.time;this.x=(this.parent.x-e.x)/i,this.y=(this.parent.y-e.y)/i,this.percentChangeX=this.percentChangeY=this.options.friction,this.timeSinceRelease=0;break}}return!1}activate(t){typeof(t=t||{}).x<"u"&&(this.x=t.x,this.percentChangeX=this.options.friction),typeof t.y<"u"&&(this.y=t.y,this.percentChangeY=this.options.friction)}update(t){if(this.paused)return;const e=this.x||this.y,i=this.timeSinceRelease,s=this.timeSinceRelease+t;if(this.x){const e=this.percentChangeX,r=Math.log(e);this.parent.x+=this.x*Uv/r*(Math.pow(e,s/Uv)-Math.pow(e,i/Uv)),this.x*=Math.pow(this.percentChangeX,t/Uv)}if(this.y){const e=this.percentChangeY,r=Math.log(e);this.parent.y+=this.y*Uv/r*(Math.pow(e,s/Uv)-Math.pow(e,i/Uv)),this.y*=Math.pow(this.percentChangeY,t/Uv)}this.timeSinceRelease+=t,this.x&&this.y?Math.abs(this.x)<this.options.minSpeed&&Math.abs(this.y)<this.options.minSpeed&&(this.x=0,this.y=0):(Math.abs(this.x||0)<this.options.minSpeed&&(this.x=0),Math.abs(this.y||0)<this.options.minSpeed&&(this.y=0)),e&&this.parent.emit("moved",{viewport:this.parent,type:"decelerate"})}reset(){this.x=this.y=null}}const Xv={direction:"all",pressDrag:!0,wheel:!0,wheelScroll:1,reverse:!1,clampWheel:!1,underflow:"center",factor:1,mouseButtons:"all",keyToPress:null,ignoreKeyToPressOnTouch:!1,lineHeight:20,wheelSwapAxes:!1};class Wv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"moved"),Pv(this,"reverse"),Pv(this,"xDirection"),Pv(this,"yDirection"),Pv(this,"keyIsPressed"),Pv(this,"mouse"),Pv(this,"underflowX"),Pv(this,"underflowY"),Pv(this,"last"),Pv(this,"current"),Pv(this,"windowEventHandlers",[]),this.options=Object.assign({},Xv,e),this.moved=!1,this.reverse=this.options.reverse?1:-1,this.xDirection=!this.options.direction||"all"===this.options.direction||"x"===this.options.direction,this.yDirection=!this.options.direction||"all"===this.options.direction||"y"===this.options.direction,this.keyIsPressed=!1,this.parseUnderflow(),this.mouseButtons(this.options.mouseButtons),this.options.keyToPress&&this.handleKeyPresses(this.options.keyToPress)}handleKeyPresses(t){this.addWindowEventHandler("keyup",e=>{t.includes(e.code)&&(this.keyIsPressed=!1)}),this.addWindowEventHandler("keydown",e=>{t.includes(e.code)&&(this.keyIsPressed=!0)})}addWindowEventHandler(t,e){window.addEventListener(t,e),this.windowEventHandlers.push({event:t,handler:e})}destroy(){this.windowEventHandlers.forEach(({event:t,handler:e})=>{window.removeEventListener(t,e)})}mouseButtons(t){this.mouse=t&&"all"!==t?[-1!==t.indexOf("left"),-1!==t.indexOf("middle"),-1!==t.indexOf("right")]:[!0,!0,!0]}parseUnderflow(){const t=this.options.underflow.toLowerCase();"center"===t?(this.underflowX=0,this.underflowY=0):(t.includes("left")?this.underflowX=-1:t.includes("right")?this.underflowX=1:this.underflowX=0,t.includes("top")?this.underflowY=-1:t.includes("bottom")?this.underflowY=1:this.underflowY=0)}checkButtons(t){const e="mouse"===t.pointerType,i=this.parent.input.count();return!(!(1===i||i>1&&!this.parent.plugins.get("pinch",!0))||e&&!this.mouse[t.button])}checkKeyPress(t){return!this.options.keyToPress||this.keyIsPressed||this.options.ignoreKeyToPressOnTouch&&"touch"===t.data.pointerType}down(t){return!(this.paused||!this.options.pressDrag)&&(this.checkButtons(t)&&this.checkKeyPress(t)?(this.last={x:t.global.x,y:t.global.y},this.current=t.pointerId,!0):(this.last=null,!1))}get active(){return this.moved}move(t){if(this.paused||!this.options.pressDrag)return!1;if(this.last&&this.current===t.data.pointerId){const e=t.global.x,i=t.global.y,s=this.parent.input.count();if(1===s||s>1&&!this.parent.plugins.get("pinch",!0)){const s=e-this.last.x,r=i-this.last.y;if(this.moved||this.xDirection&&this.parent.input.checkThreshold(s)||this.yDirection&&this.parent.input.checkThreshold(r)){const s={x:e,y:i};return this.xDirection&&(this.parent.x+=(s.x-this.last.x)*this.options.factor),this.yDirection&&(this.parent.y+=(s.y-this.last.y)*this.options.factor),this.last=s,this.moved||this.parent.emit("drag-start",{event:t,screen:new Kp(this.last.x,this.last.y),world:this.parent.toWorld(new Kp(this.last.x,this.last.y)),viewport:this.parent}),this.moved=!0,this.parent.emit("moved",{viewport:this.parent,type:"drag"}),!0}}else this.moved=!1}return!1}up(t){if(this.paused)return!1;const e=this.parent.input.touches;if(1===e.length){const t=e[0];return t.last&&(this.last={x:t.last.x,y:t.last.y},this.current=t.id),this.moved=!1,!0}if(this.last&&this.moved){const e=new Kp(this.last.x,this.last.y);return this.parent.emit("drag-end",{event:t,screen:e,world:this.parent.toWorld(e),viewport:this.parent}),this.last=null,this.moved=!1,!0}return!1}wheel(t){if(this.paused)return!1;if(this.options.wheel){const e=this.parent.plugins.get("wheel",!0);if(!e||!e.options.wheelZoom&&!t.ctrlKey){const e=t.deltaMode?this.options.lineHeight:1,i=[t.deltaX,t.deltaY],[s,r]=this.options.wheelSwapAxes?i.reverse():i;return this.xDirection&&(this.parent.x+=s*e*this.options.wheelScroll*this.reverse),this.yDirection&&(this.parent.y+=r*e*this.options.wheelScroll*this.reverse),this.options.clampWheel&&this.clamp(),this.parent.emit("wheel-scroll",this.parent),this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.options.passiveWheel||t.preventDefault(),this.parent.options.stopPropagation&&t.stopPropagation(),!0}}return!1}resume(){this.last=null,this.paused=!1}clamp(){const t=this.parent.plugins.get("decelerate",!0)||{};if("y"!==this.options.clampWheel)if(this.parent.screenWorldWidth<this.parent.screenWidth)switch(this.underflowX){case-1:this.parent.x=0;break;case 1:this.parent.x=this.parent.screenWidth-this.parent.screenWorldWidth;break;default:this.parent.x=(this.parent.screenWidth-this.parent.screenWorldWidth)/2}else this.parent.left<0?(this.parent.x=0,t.x=0):this.parent.right>this.parent.worldWidth&&(this.parent.x=-this.parent.worldWidth*this.parent.scale.x+this.parent.screenWidth,t.x=0);if("x"!==this.options.clampWheel)if(this.parent.screenWorldHeight<this.parent.screenHeight)switch(this.underflowY){case-1:this.parent.y=0;break;case 1:this.parent.y=this.parent.screenHeight-this.parent.screenWorldHeight;break;default:this.parent.y=(this.parent.screenHeight-this.parent.screenWorldHeight)/2}else this.parent.top<0&&(this.parent.y=0,t.y=0),this.parent.bottom>this.parent.worldHeight&&(this.parent.y=-this.parent.worldHeight*this.parent.scale.y+this.parent.screenHeight,t.y=0)}}const Yv={speed:0,acceleration:null,radius:null};class Hv extends Ev{constructor(t,e,i={}){super(t),Pv(this,"options"),Pv(this,"target"),Pv(this,"velocity"),this.target=e,this.options=Object.assign({},Yv,i),this.velocity={x:0,y:0}}update(t){if(this.paused)return;const e=this.parent.center;let i=this.target.x,s=this.target.y;if(this.options.radius){if(!(Math.sqrt(Math.pow(this.target.y-e.y,2)+Math.pow(this.target.x-e.x,2))>this.options.radius))return;{const t=Math.atan2(this.target.y-e.y,this.target.x-e.x);i=this.target.x-Math.cos(t)*this.options.radius,s=this.target.y-Math.sin(t)*this.options.radius}}const r=i-e.x,n=s-e.y;if(r||n)if(this.options.speed)if(this.options.acceleration){const t=Math.atan2(s-e.y,i-e.x),o=Math.sqrt(Math.pow(r,2)+Math.pow(n,2));if(o){const a=(Math.pow(this.velocity.x,2)+Math.pow(this.velocity.y,2))/(2*this.options.acceleration);this.velocity=o>a?{x:Math.min(this.velocity.x+(this.options.acceleration,this.options.speed)),y:Math.min(this.velocity.y+(this.options.acceleration,this.options.speed))}:{x:Math.max(this.velocity.x-this.options.acceleration*this.options.speed,0),y:Math.max(this.velocity.y-this.options.acceleration*this.options.speed,0)};const l=Math.cos(t)*this.velocity.x,h=Math.sin(t)*this.velocity.y,u=Math.abs(l)>Math.abs(r)?i:e.x+l,c=Math.abs(h)>Math.abs(n)?s:e.y+h;this.parent.moveCenter(u,c),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}else{const t=Math.atan2(s-e.y,i-e.x),o=Math.cos(t)*this.options.speed,a=Math.sin(t)*this.options.speed,l=Math.abs(o)>Math.abs(r)?i:e.x+o,h=Math.abs(a)>Math.abs(n)?s:e.y+a;this.parent.moveCenter(l,h),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}else this.parent.moveCenter(i,s),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}const $v={radius:null,distance:null,top:null,bottom:null,left:null,right:null,speed:8,reverse:!1,noDecelerate:!1,linear:!1,allowButtons:!1};let jv=class extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"reverse"),Pv(this,"radiusSquared"),Pv(this,"left"),Pv(this,"top"),Pv(this,"right"),Pv(this,"bottom"),Pv(this,"horizontal"),Pv(this,"vertical"),this.options=Object.assign({},$v,e),this.reverse=this.options.reverse?1:-1,this.radiusSquared="number"==typeof this.options.radius?Math.pow(this.options.radius,2):null,this.resize()}resize(){const t=this.options.distance;null!==t?(this.left=t,this.top=t,this.right=this.parent.screenWidth-t,this.bottom=this.parent.screenHeight-t):this.options.radius||(this.left=this.options.left,this.top=this.options.top,this.right=null===this.options.right?null:this.parent.screenWidth-this.options.right,this.bottom=null===this.options.bottom?null:this.parent.screenHeight-this.options.bottom)}down(){return this.paused||this.options.allowButtons||(this.horizontal=this.vertical=null),!1}move(t){if(this.paused||"mouse"!==t.pointerType&&1!==t.pointerId||!this.options.allowButtons&&0!==t.buttons)return!1;const e=t.global.x,i=t.global.y;if(this.radiusSquared){const t=this.parent.toScreen(this.parent.center);if(Math.pow(t.x-e,2)+Math.pow(t.y-i,2)>=this.radiusSquared){const s=Math.atan2(t.y-i,t.x-e);this.options.linear?(this.horizontal=Math.round(Math.cos(s))*this.options.speed*this.reverse*.06,this.vertical=Math.round(Math.sin(s))*this.options.speed*this.reverse*.06):(this.horizontal=Math.cos(s)*this.options.speed*this.reverse*.06,this.vertical=Math.sin(s)*this.options.speed*this.reverse*.06)}else this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=0}else null!==this.left&&e<this.left?this.horizontal=Number(this.reverse)*this.options.speed*.06:null!==this.right&&e>this.right?this.horizontal=-1*this.reverse*this.options.speed*.06:(this.decelerateHorizontal(),this.horizontal=0),null!==this.top&&i<this.top?this.vertical=Number(this.reverse)*this.options.speed*.06:null!==this.bottom&&i>this.bottom?this.vertical=-1*this.reverse*this.options.speed*.06:(this.decelerateVertical(),this.vertical=0);return!1}decelerateHorizontal(){const t=this.parent.plugins.get("decelerate",!0);this.horizontal&&t&&!this.options.noDecelerate&&t.activate({x:this.horizontal*this.options.speed*this.reverse/(1e3/60)})}decelerateVertical(){const t=this.parent.plugins.get("decelerate",!0);this.vertical&&t&&!this.options.noDecelerate&&t.activate({y:this.vertical*this.options.speed*this.reverse/(1e3/60)})}up(){return this.paused||(this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=null),!1}update(){if(!this.paused&&(this.horizontal||this.vertical)){const t=this.parent.center;this.horizontal&&(t.x+=this.horizontal*this.options.speed),this.vertical&&(t.y+=this.vertical*this.options.speed),this.parent.moveCenter(t),this.parent.emit("moved",{viewport:this.parent,type:"mouse-edges"})}}};const zv={noDrag:!1,percent:1,center:null,factor:1,axis:"all"};class Vv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"active",!1),Pv(this,"pinching",!1),Pv(this,"moved",!1),Pv(this,"lastCenter"),this.options=Object.assign({},zv,e)}down(){return this.parent.input.count()>=2&&(this.active=!0,!0)}isAxisX(){return["all","x"].includes(this.options.axis)}isAxisY(){return["all","y"].includes(this.options.axis)}move(t){if(this.paused||!this.active)return!1;const e=t.global.x,i=t.global.y,s=this.parent.input.touches;if(s.length>=2){const r=s[0],n=s[1],o=r.last&&n.last?Math.sqrt(Math.pow(n.last.x-r.last.x,2)+Math.pow(n.last.y-r.last.y,2)):null;if(r.id===t.pointerId?r.last={x:e,y:i,data:t}:n.id===t.pointerId&&(n.last={x:e,y:i,data:t}),o){let t;const e=new Kp(r.last.x+(n.last.x-r.last.x)/2,r.last.y+(n.last.y-r.last.y)/2);this.options.center||(t=this.parent.toLocal(e));let i=Math.sqrt(Math.pow(n.last.x-r.last.x,2)+Math.pow(n.last.y-r.last.y,2));i=0===i?i=1e-10:i;const s=(1-o/i)*this.options.percent*(this.isAxisX()?this.parent.scale.x:this.parent.scale.y);this.isAxisX()&&(this.parent.scale.x+=s),this.isAxisY()&&(this.parent.scale.y+=s),this.parent.emit("zoomed",{viewport:this.parent,type:"pinch",center:e});const a=this.parent.plugins.get("clamp-zoom",!0);if(a&&a.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const i=this.parent.toGlobal(t);this.parent.x+=(e.x-i.x)*this.options.factor,this.parent.y+=(e.y-i.y)*this.options.factor,this.parent.emit("moved",{viewport:this.parent,type:"pinch"})}!this.options.noDrag&&this.lastCenter&&(this.parent.x+=(e.x-this.lastCenter.x)*this.options.factor,this.parent.y+=(e.y-this.lastCenter.y)*this.options.factor,this.parent.emit("moved",{viewport:this.parent,type:"pinch"})),this.lastCenter=e,this.moved=!0}else this.pinching||(this.parent.emit("pinch-start",this.parent),this.pinching=!0);return!0}return!1}up(){return!!(this.pinching&&this.parent.input.touches.length<=1)&&(this.active=!1,this.lastCenter=null,this.pinching=!1,this.moved=!1,this.parent.emit("pinch-end",this.parent),!0)}}const qv={topLeft:!1,friction:.8,time:1e3,ease:"easeInOutSine",interrupt:!0,removeOnComplete:!1,removeOnInterrupt:!1,forceStart:!1};class Jv extends Ev{constructor(t,e,i,s={}){super(t),Pv(this,"options"),Pv(this,"ease"),Pv(this,"x"),Pv(this,"y"),Pv(this,"percent"),Pv(this,"snapping"),Pv(this,"deltaX"),Pv(this,"deltaY"),Pv(this,"startX"),Pv(this,"startY"),this.options=Object.assign({},qv,s),this.ease=Cv(s.ease,"easeInOutSine"),this.x=e,this.y=i,this.options.forceStart&&this.snapStart()}snapStart(){this.percent=0,this.snapping={time:0};const t=this.options.topLeft?this.parent.corner:this.parent.center;this.deltaX=this.x-t.x,this.deltaY=this.y-t.y,this.startX=t.x,this.startY=t.y,this.parent.emit("snap-start",this.parent)}wheel(){return this.options.removeOnInterrupt&&this.parent.plugins.remove("snap"),!1}down(){return this.options.removeOnInterrupt?this.parent.plugins.remove("snap"):this.options.interrupt&&(this.snapping=null),!1}up(){if(0===this.parent.input.count()){const t=this.parent.plugins.get("decelerate",!0);t&&(t.x||t.y)&&(t.percentChangeX=t.percentChangeY=this.options.friction)}return!1}update(t){if(!(this.paused||this.options.interrupt&&0!==this.parent.input.count()))if(this.snapping){const e=this.snapping;let i,s,r;e.time+=t;const n=this.startX,o=this.startY,a=this.deltaX,l=this.deltaY;if(e.time>this.options.time)i=!0,s=n+a,r=o+l;else{const t=this.ease(e.time,0,1,this.options.time);s=n+a*t,r=o+l*t}this.options.topLeft?this.parent.moveCorner(s,r):this.parent.moveCenter(s,r),this.parent.emit("moved",{viewport:this.parent,type:"snap"}),i&&(this.options.removeOnComplete&&this.parent.plugins.remove("snap"),this.parent.emit("snap-end",this.parent),this.snapping=null)}else{const t=this.options.topLeft?this.parent.corner:this.parent.center;(t.x!==this.x||t.y!==this.y)&&this.snapStart()}}}const Kv={width:0,height:0,time:1e3,ease:"easeInOutSine",center:null,interrupt:!0,removeOnComplete:!1,removeOnInterrupt:!1,forceStart:!1,noMove:!1};class Zv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"ease"),Pv(this,"xScale"),Pv(this,"yScale"),Pv(this,"xIndependent"),Pv(this,"yIndependent"),Pv(this,"snapping"),this.options=Object.assign({},Kv,e),this.ease=Cv(this.options.ease),this.xIndependent=!1,this.yIndependent=!1,this.xScale=0,this.yScale=0,this.options.width>0&&(this.xScale=t.screenWidth/this.options.width,this.xIndependent=!0),this.options.height>0&&(this.yScale=t.screenHeight/this.options.height,this.yIndependent=!0),this.xScale=this.xIndependent?this.xScale:this.yScale,this.yScale=this.yIndependent?this.yScale:this.xScale,0===this.options.time?(t.container.scale.x=this.xScale,t.container.scale.y=this.yScale,this.options.removeOnComplete&&this.parent.plugins.remove("snap-zoom")):e.forceStart&&this.createSnapping()}createSnapping(){const t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,i=this.parent.screenWidth/this.xScale,s=this.parent.screenHeight/this.yScale;this.snapping={time:0,startX:t,startY:e,deltaX:i-t,deltaY:s-e},this.parent.emit("snap-zoom-start",this.parent)}resize(){this.snapping=null,this.options.width>0&&(this.xScale=this.parent.screenWidth/this.options.width),this.options.height>0&&(this.yScale=this.parent.screenHeight/this.options.height),this.xScale=this.xIndependent?this.xScale:this.yScale,this.yScale=this.yIndependent?this.yScale:this.xScale}wheel(){return this.options.removeOnInterrupt&&this.parent.plugins.remove("snap-zoom"),!1}down(){return this.options.removeOnInterrupt?this.parent.plugins.remove("snap-zoom"):this.options.interrupt&&(this.snapping=null),!1}update(t){if(this.paused||this.options.interrupt&&0!==this.parent.input.count())return;let e;if(!this.options.center&&!this.options.noMove&&(e=this.parent.center),this.snapping){if(this.snapping){const i=this.snapping;if(i.time+=t,i.time>=this.options.time)this.parent.scale.set(this.xScale,this.yScale),this.options.removeOnComplete&&this.parent.plugins.remove("snap-zoom"),this.parent.emit("snap-zoom-end",this.parent),this.snapping=null;else{const t=this.snapping,e=this.ease(t.time,t.startX,t.deltaX,this.options.time),i=this.ease(t.time,t.startY,t.deltaY,this.options.time);this.parent.scale.x=this.parent.screenWidth/e,this.parent.scale.y=this.parent.screenHeight/i}const s=this.parent.plugins.get("clamp-zoom",!0);s&&s.clamp(),this.options.noMove||(this.options.center?this.parent.moveCenter(this.options.center):this.parent.moveCenter(e))}}else(this.parent.scale.x!==this.xScale||this.parent.scale.y!==this.yScale)&&this.createSnapping()}resume(){this.snapping=null,super.resume()}}const Qv={percent:.1,smooth:!1,interrupt:!0,reverse:!1,center:null,lineHeight:20,axis:"all",keyToPress:null,trackpadPinch:!1,wheelZoom:!0};class tx extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"smoothing"),Pv(this,"smoothingCenter"),Pv(this,"smoothingCount"),Pv(this,"keyIsPressed"),this.options=Object.assign({},Qv,e),this.keyIsPressed=!1,this.options.keyToPress&&this.handleKeyPresses(this.options.keyToPress)}handleKeyPresses(t){window.addEventListener("keydown",e=>{t.includes(e.code)&&(this.keyIsPressed=!0)}),window.addEventListener("keyup",e=>{t.includes(e.code)&&(this.keyIsPressed=!1)})}checkKeyPress(){return!this.options.keyToPress||this.keyIsPressed}down(){return this.options.interrupt&&(this.smoothing=null),!1}isAxisX(){return["all","x"].includes(this.options.axis)}isAxisY(){return["all","y"].includes(this.options.axis)}update(){if(this.smoothing){const t=this.smoothingCenter,e=this.smoothing;let i;this.options.center||(i=this.parent.toLocal(t)),this.isAxisX()&&(this.parent.scale.x+=e.x),this.isAxisY()&&(this.parent.scale.y+=e.y),this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const s=this.parent.plugins.get("clamp-zoom",!0);if(s&&s.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const e=this.parent.toGlobal(i);this.parent.x+=t.x-e.x,this.parent.y+=t.y-e.y}this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.smoothingCount++,this.smoothingCount>=this.options.smooth&&(this.smoothing=null)}}pinch(t){if(this.paused)return;const e=this.parent.input.getPointerPosition(t),i=-t.deltaY*(t.deltaMode?this.options.lineHeight:1)/200,s=Math.pow(2,(1+this.options.percent)*i);let r;this.options.center||(r=this.parent.toLocal(e)),this.isAxisX()&&(this.parent.scale.x*=s),this.isAxisY()&&(this.parent.scale.y*=s),this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const n=this.parent.plugins.get("clamp-zoom",!0);if(n&&n.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const t=this.parent.toGlobal(r);this.parent.x+=e.x-t.x,this.parent.y+=e.y-t.y}this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.emit("wheel-start",{event:t,viewport:this.parent})}wheel(t){if(this.paused||!this.checkKeyPress())return!1;if(t.ctrlKey&&this.options.trackpadPinch)this.pinch(t);else if(this.options.wheelZoom){const e=this.parent.input.getPointerPosition(t),i=(this.options.reverse?-1:1)*-t.deltaY*(t.deltaMode?this.options.lineHeight:1)/500,s=Math.pow(2,(1+this.options.percent)*i);if(this.options.smooth){const t={x:this.smoothing?this.smoothing.x*(this.options.smooth-this.smoothingCount):0,y:this.smoothing?this.smoothing.y*(this.options.smooth-this.smoothingCount):0};this.smoothing={x:((this.parent.scale.x+t.x)*s-this.parent.scale.x)/this.options.smooth,y:((this.parent.scale.y+t.y)*s-this.parent.scale.y)/this.options.smooth},this.smoothingCount=0,this.smoothingCenter=e}else{let t;this.options.center||(t=this.parent.toLocal(e)),this.isAxisX()&&(this.parent.scale.x*=s),this.isAxisY()&&(this.parent.scale.y*=s),this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const i=this.parent.plugins.get("clamp-zoom",!0);if(i&&i.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const i=this.parent.toGlobal(t);this.parent.x+=e.x-i.x,this.parent.y+=e.y-i.y}}this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.emit("wheel-start",{event:t,viewport:this.parent})}return!this.parent.options.passiveWheel}}let ex=class{constructor(t){Pv(this,"viewport"),Pv(this,"clickedAvailable"),Pv(this,"isMouseDown"),Pv(this,"last"),Pv(this,"wheelFunction"),Pv(this,"touches"),this.viewport=t,this.touches=[],this.addListeners()}addListeners(){this.viewport.eventMode="static",this.viewport.forceHitArea||(this.viewport.hitArea=new Qp(0,0,this.viewport.worldWidth,this.viewport.worldHeight)),this.viewport.on("pointerdown",this.down,this),this.viewport.options.allowPreserveDragOutside?this.viewport.on("globalpointermove",this.move,this):this.viewport.on("pointermove",this.move,this),this.viewport.on("pointerup",this.up,this),this.viewport.on("pointerupoutside",this.up,this),this.viewport.on("pointercancel",this.up,this),this.viewport.options.allowPreserveDragOutside||this.viewport.on("pointerleave",this.up,this),this.wheelFunction=t=>this.handleWheel(t),this.viewport.options.events.domElement.addEventListener("wheel",this.wheelFunction,{passive:this.viewport.options.passiveWheel}),this.isMouseDown=!1}destroy(){this.viewport.options.events.domElement.removeEventListener("wheel",this.wheelFunction)}down(t){if(!this.viewport.pause&&this.viewport.worldVisible){if("mouse"===t.pointerType?this.isMouseDown=!0:this.get(t.pointerId)||this.touches.push({id:t.pointerId,last:null}),1===this.count()){this.last=t.global.clone();const e=this.viewport.plugins.get("decelerate",!0),i=this.viewport.plugins.get("bounce",!0);e&&e.isActive()||i&&i.isActive()?this.clickedAvailable=!1:this.clickedAvailable=!0}else this.clickedAvailable=!1;this.viewport.plugins.down(t)&&this.viewport.options.stopPropagation&&t.stopPropagation()}}clear(){this.isMouseDown=!1,this.touches=[],this.last=null}checkThreshold(t){return Math.abs(t)>=this.viewport.threshold}move(t){if(this.viewport.pause||!this.viewport.worldVisible)return;const e=this.viewport.plugins.move(t);if(this.clickedAvailable&&this.last){const e=t.global.x-this.last.x,i=t.global.y-this.last.y;(this.checkThreshold(e)||this.checkThreshold(i))&&(this.clickedAvailable=!1)}e&&this.viewport.options.stopPropagation&&t.stopPropagation()}up(t){if(this.viewport.pause||!this.viewport.worldVisible)return;"mouse"===t.pointerType&&(this.isMouseDown=!1),"mouse"!==t.pointerType&&this.remove(t.pointerId);const e=this.viewport.plugins.up(t);this.clickedAvailable&&0===this.count()&&this.last&&(this.viewport.emit("clicked",{event:t,screen:this.last,world:this.viewport.toWorld(this.last),viewport:this.viewport}),this.clickedAvailable=!1),e&&this.viewport.options.stopPropagation&&t.stopPropagation()}getPointerPosition(t){const e=new Kp;return this.viewport.options.events.mapPositionToPoint(e,t.clientX,t.clientY),e}handleWheel(t){if(this.viewport.pause||!this.viewport.worldVisible)return;const e=this.viewport.toLocal(this.getPointerPosition(t));this.viewport.left<=e.x&&e.x<=this.viewport.right&&this.viewport.top<=e.y&&e.y<=this.viewport.bottom&&this.viewport.plugins.wheel(t)&&!this.viewport.options.passiveWheel&&t.preventDefault()}pause(){this.touches=[],this.isMouseDown=!1}get(t){for(const e of this.touches)if(e.id===t)return e;return null}remove(t){for(let e=0;e<this.touches.length;e++)if(this.touches[e].id===t)return void this.touches.splice(e,1)}count(){return(this.isMouseDown?1:0)+this.touches.length}};const ix=["drag","pinch","wheel","follow","mouse-edges","decelerate","animate","bounce","snap-zoom","clamp-zoom","snap","clamp"];class sx{constructor(t){Pv(this,"plugins"),Pv(this,"list"),Pv(this,"viewport"),this.viewport=t,this.list=[],this.plugins={}}add(t,e,i=ix.length){const s=this.plugins[t];s&&s.destroy(),this.plugins[t]=e;const r=ix.indexOf(t);-1!==r&&ix.splice(r,1),ix.splice(i,0,t),this.sort()}get(t,e){var i;return e&&null!=(i=this.plugins[t])&&i.paused?null:this.plugins[t]}update(t){for(const e of this.list)e.update(t)}resize(){for(const t of this.list)t.resize()}reset(){for(const t of this.list)t.reset()}removeAll(){this.list.forEach(t=>{t.destroy()}),this.plugins={},this.sort()}remove(t){var e;this.plugins[t]&&(null==(e=this.plugins[t])||e.destroy(),delete this.plugins[t],this.viewport.emit("plugin-remove",t),this.sort())}pause(t){var e;null==(e=this.plugins[t])||e.pause()}resume(t){var e;null==(e=this.plugins[t])||e.resume()}sort(){this.list=[];for(const t of ix)this.plugins[t]&&this.list.push(this.plugins[t])}down(t){let e=!1;for(const i of this.list)i.down(t)&&(e=!0);return e}move(t){let e=!1;for(const i of this.viewport.plugins.list)i.move(t)&&(e=!0);return e}up(t){let e=!1;for(const i of this.list)i.up(t)&&(e=!0);return e}wheel(t){let e=!1;for(const i of this.list)i.wheel(t)&&(e=!0);return e}}const rx={screenWidth:window.innerWidth,screenHeight:window.innerHeight,worldWidth:null,worldHeight:null,threshold:5,passiveWheel:!0,stopPropagation:!1,forceHitArea:null,noTicker:!1,disableOnContextMenu:!1,ticker:ag.shared,allowPreserveDragOutside:!1};class nx extends Og{constructor(t){super(),Pv(this,"moving"),Pv(this,"screenWidth"),Pv(this,"screenHeight"),Pv(this,"threshold"),Pv(this,"input"),Pv(this,"plugins"),Pv(this,"zooming"),Pv(this,"lastViewport"),Pv(this,"options"),Pv(this,"_dirty"),Pv(this,"_forceHitArea"),Pv(this,"_hitAreaDefault"),Pv(this,"_pause"),Pv(this,"tickerFunction"),Pv(this,"_worldWidth"),Pv(this,"_worldHeight"),Pv(this,"_disableOnContextMenu",t=>t.preventDefault()),this.options={...rx,...t},this.screenWidth=this.options.screenWidth,this.screenHeight=this.options.screenHeight,this._worldWidth=this.options.worldWidth,this._worldHeight=this.options.worldHeight,this.forceHitArea=this.options.forceHitArea,this.threshold=this.options.threshold,this.options.disableOnContextMenu&&this.options.events.domElement.addEventListener("contextmenu",this._disableOnContextMenu),this.options.noTicker||(this.tickerFunction=()=>this.update(this.options.ticker.elapsedMS),this.options.ticker.add(this.tickerFunction)),this.input=new ex(this),this.plugins=new sx(this)}destroy(t){!this.options.noTicker&&this.tickerFunction&&this.options.ticker.remove(this.tickerFunction),this.options.disableOnContextMenu&&this.options.events.domElement.removeEventListener("contextmenu",this._disableOnContextMenu),this.input.destroy(),super.destroy(t)}update(t){this.pause||(this.plugins.update(t),this.lastViewport&&(this.lastViewport.x!==this.x||this.lastViewport.y!==this.y?this.moving=!0:this.moving&&(this.emit("moved-end",this),this.moving=!1),this.lastViewport.scaleX!==this.scale.x||this.lastViewport.scaleY!==this.scale.y?this.zooming=!0:this.zooming&&(this.emit("zoomed-end",this),this.zooming=!1)),this.forceHitArea||(this._hitAreaDefault=new Qp(this.left,this.top,this.worldScreenWidth,this.worldScreenHeight),this.hitArea=this._hitAreaDefault),this._dirty=this._dirty||!this.lastViewport||this.lastViewport.x!==this.x||this.lastViewport.y!==this.y||this.lastViewport.scaleX!==this.scale.x||this.lastViewport.scaleY!==this.scale.y,this.lastViewport={x:this.x,y:this.y,scaleX:this.scale.x,scaleY:this.scale.y},this.emit("frame-end",this))}resize(t=window.innerWidth,e=window.innerHeight,i,s){this.screenWidth=t,this.screenHeight=e,typeof i<"u"&&(this._worldWidth=i),typeof s<"u"&&(this._worldHeight=s),this.plugins.resize(),this.dirty=!0}get worldWidth(){return this._worldWidth?this._worldWidth:this.width/this.scale.x}set worldWidth(t){this._worldWidth=t,this.plugins.resize()}get worldHeight(){return this._worldHeight?this._worldHeight:this.height/this.scale.y}set worldHeight(t){this._worldHeight=t,this.plugins.resize()}getVisibleBounds(){return new Qp(this.left,this.top,this.worldScreenWidth,this.worldScreenHeight)}toWorld(t,e){return 2===arguments.length?this.toLocal(new Kp(t,e)):this.toLocal(t)}toScreen(t,e){return 2===arguments.length?this.toGlobal(new Kp(t,e)):this.toGlobal(t)}get worldScreenWidth(){return this.screenWidth/this.scale.x}get worldScreenHeight(){return this.screenHeight/this.scale.y}get screenWorldWidth(){return this.worldWidth*this.scale.x}get screenWorldHeight(){return this.worldHeight*this.scale.y}get center(){return new Kp(this.worldScreenWidth/2-this.x/this.scale.x,this.worldScreenHeight/2-this.y/this.scale.y)}set center(t){this.moveCenter(t)}moveCenter(...t){let e,i;"number"==typeof t[0]?(e=t[0],i=t[1]):(e=t[0].x,i=t[0].y);const s=(this.worldScreenWidth/2-e)*this.scale.x,r=(this.worldScreenHeight/2-i)*this.scale.y;return(this.x!==s||this.y!==r)&&(this.position.set(s,r),this.plugins.reset(),this.dirty=!0),this}get corner(){return new Kp(-this.x/this.scale.x,-this.y/this.scale.y)}set corner(t){this.moveCorner(t)}moveCorner(...t){let e,i;return 1===t.length?(e=-t[0].x*this.scale.x,i=-t[0].y*this.scale.y):(e=-t[0]*this.scale.x,i=-t[1]*this.scale.y),(e!==this.x||i!==this.y)&&(this.position.set(e,i),this.plugins.reset(),this.dirty=!0),this}get screenWidthInWorldPixels(){return this.screenWidth/this.scale.x}get screenHeightInWorldPixels(){return this.screenHeight/this.scale.y}findFitWidth(t){return this.screenWidth/t}findFitHeight(t){return this.screenHeight/t}findFit(t,e){const i=this.screenWidth/t,s=this.screenHeight/e;return Math.min(i,s)}findCover(t,e){const i=this.screenWidth/t,s=this.screenHeight/e;return Math.max(i,s)}fitWidth(t=this.worldWidth,e,i=!0,s){let r;e&&(r=this.center),this.scale.x=this.screenWidth/t,i&&(this.scale.y=this.scale.x);const n=this.plugins.get("clamp-zoom",!0);return!s&&n&&n.clamp(),e&&r&&this.moveCenter(r),this}fitHeight(t=this.worldHeight,e,i=!0,s){let r;e&&(r=this.center),this.scale.y=this.screenHeight/t,i&&(this.scale.x=this.scale.y);const n=this.plugins.get("clamp-zoom",!0);return!s&&n&&n.clamp(),e&&r&&this.moveCenter(r),this}fitWorld(t){let e;t&&(e=this.center),this.scale.x=this.screenWidth/this.worldWidth,this.scale.y=this.screenHeight/this.worldHeight,this.scale.x<this.scale.y?this.scale.y=this.scale.x:this.scale.x=this.scale.y;const i=this.plugins.get("clamp-zoom",!0);return i&&i.clamp(),t&&e&&this.moveCenter(e),this}fit(t,e=this.worldWidth,i=this.worldHeight){let s;t&&(s=this.center),this.scale.x=this.screenWidth/e,this.scale.y=this.screenHeight/i,this.scale.x<this.scale.y?this.scale.y=this.scale.x:this.scale.x=this.scale.y;const r=this.plugins.get("clamp-zoom",!0);return r&&r.clamp(),t&&s&&this.moveCenter(s),this}setZoom(t,e){let i;e&&(i=this.center),this.scale.set(t);const s=this.plugins.get("clamp-zoom",!0);return s&&s.clamp(),e&&i&&this.moveCenter(i),this}zoomPercent(t,e){return this.setZoom(this.scale.x+this.scale.x*t,e)}zoom(t,e){return this.fitWidth(t+this.worldScreenWidth,e),this}get scaled(){return this.scale.x}set scaled(t){this.setZoom(t,!0)}snapZoom(t){return this.plugins.add("snap-zoom",new Zv(this,t)),this}OOB(){return{left:this.left<0,right:this.right>this.worldWidth,top:this.top<0,bottom:this.bottom>this.worldHeight,cornerPoint:new Kp(this.worldWidth*this.scale.x-this.screenWidth,this.worldHeight*this.scale.y-this.screenHeight)}}get right(){return-this.x/this.scale.x+this.worldScreenWidth}set right(t){this.x=-t*this.scale.x+this.screenWidth,this.plugins.reset()}get left(){return-this.x/this.scale.x}set left(t){this.x=-t*this.scale.x,this.plugins.reset()}get top(){return-this.y/this.scale.y}set top(t){this.y=-t*this.scale.y,this.plugins.reset()}get bottom(){return-this.y/this.scale.y+this.worldScreenHeight}set bottom(t){this.y=-t*this.scale.y+this.screenHeight,this.plugins.reset()}get dirty(){return!!this._dirty}set dirty(t){this._dirty=t}get forceHitArea(){return this._forceHitArea}set forceHitArea(t){t?(this._forceHitArea=t,this.hitArea=t):(this._forceHitArea=null,this.hitArea=new Qp(0,0,this.worldWidth,this.worldHeight))}drag(t){return this.plugins.add("drag",new Wv(this,t)),this}clamp(t){return this.plugins.add("clamp",new kv(this,t)),this}decelerate(t){return this.plugins.add("decelerate",new Gv(this,t)),this}bounce(t){return this.plugins.add("bounce",new Lv(this,t)),this}pinch(t){return this.plugins.add("pinch",new Vv(this,t)),this}snap(t,e,i){return this.plugins.add("snap",new Jv(this,t,e,i)),this}follow(t,e){return this.plugins.add("follow",new Hv(this,t,e)),this}wheel(t){return this.plugins.add("wheel",new tx(this,t)),this}animate(t){return this.plugins.add("animate",new Ov(this,t)),this}clampZoom(t){return this.plugins.add("clamp-zoom",new Fv(this,t)),this}mouseEdges(t){return this.plugins.add("mouse-edges",new jv(this,t)),this}get pause(){return!!this._pause}set pause(t){this._pause=t,this.lastViewport=null,this.moving=!1,this.zooming=!1,t&&this.input.pause()}ensureVisible(t,e,i,s,r){r&&(i>this.worldScreenWidth||s>this.worldScreenHeight)&&(this.fit(!0,i,s),this.emit("zoomed",{viewport:this,type:"ensureVisible"}));let n=!1;t<this.left?(this.left=t,n=!0):t+i>this.right&&(this.right=t+i,n=!0),e<this.top?(this.top=e,n=!0):e+s>this.bottom&&(this.bottom=e+s,n=!0),n&&this.emit("moved",{viewport:this,type:"ensureVisible"})}}const ox=100;var ax,lx={exports:{}};var hx=function(){if(ax)return lx.exports;function t(){}return ax=1,t.prototype={on:function(t,e,i){var s=this.e||(this.e={});return(s[t]||(s[t]=[])).push({fn:e,ctx:i}),this},once:function(t,e,i){var s=this;function r(){s.off(t,r),e.apply(i,arguments)}return r._=e,this.on(t,r,i)},emit:function(t){for(var e=[].slice.call(arguments,1),i=((this.e||(this.e={}))[t]||[]).slice(),s=0,r=i.length;s<r;s++)i[s].fn.apply(i[s].ctx,e);return this},off:function(t,e){var i=this.e||(this.e={}),s=i[t],r=[];if(s&&e)for(var n=0,o=s.length;n<o;n++)s[n].fn!==e&&s[n].fn._!==e&&r.push(s[n]);return r.length?i[t]=r:delete i[t],this}},lx.exports=t,lx.exports.TinyEmitter=t,lx.exports}();class ux extends hx.TinyEmitter{constructor({floorPlan:t,helperId:e}){super(),this.floorPlan=t,this.helperId=e}destroy(){delete this.floorPlan.helper[this.helperId],this.floorPlan=null}}class cx extends ux{constructor({floorPlan:t,parentEl:e,helperId:i}){super({floorPlan:t,helperId:i}),e&&t&&(this.data={cursor:["0","0"]},this.floorPlan.on("mousemove",this.update,this),this.mount(e),this.update())}update(){this.rootEl&&this.setData({cursor:[c(this.floorPlan.interaction.cursor[0],this.floorPlan.settings.units.system,this.floorPlan.settings.units.lengthDecimals),c(this.floorPlan.interaction.cursor[1],this.floorPlan.settings.units.system,this.floorPlan.settings.units.lengthDecimals)]})}setData(t={}){for(let e in t)this.data[e]=t[e];this.rootEl.innerHTML=this.template(this.data)}template(t={}){return`<span class="fpe-coordinates__unit">x:${t.cursor[0]}</span>\n <span class="fpe-coordinates__unit">z:${t.cursor[1]}</span>`}mount(t){this.rootEl||(this.rootEl=document.createElement("div"),this.rootEl.classList.add("fpe-coordinates"),t.appendChild(this.rootEl))}destroy(){this.floorPlan.off("mousemove",this.update),this.rootEl.remove(),delete this.floorPlan,delete this.data}}class dx extends ux{constructor({floorPlan:t,parentEl:e,helperId:i}){super({floorPlan:t,helperId:i}),e&&t&&(this.data={width:100,height:4,margin:2,style:"lines",box:{},scaleStep:null,scaleDisplay:null,steps:[],leftHanded:!1,isImperial:"imperial"===t.settings.units.system},this.floorPlan.view.on("zoom",this.update,this),this.floorPlan.on("update-settings",this.update,this),this.mount(e),this.update())}update(){this.data.isImperial="imperial"===this.floorPlan.settings.units.system;const t=this.data.isImperial?3.28084:1;if(!this.floorPlan.view.viewbox)return;this.data.box.length=this.floorPlan.view.viewbox.max[0]-this.floorPlan.view.viewbox.min[0],this.data.box.width=this.floorPlan.view.viewbox.max[1]-this.floorPlan.view.viewbox.min[1];const e=Math.min(this.floorPlan.view.client[0],this.floorPlan.view.client[1]),i=Math.min(this.data.box.length,this.data.box.width),s=e/i;if(!s)return;const r=200/s;this.data.scaleStep=i<=.5/t?.01/t:i<=1/t?.05/t:i<=2.5/t?.1/t:i<=5.4/t?.2/t:i<=12/t?.5/t:i<=25/t?1/t:i<=50/t?2/t:i<=100/t?5/t:i<=200/t?10/t:i<=550/t?20/t:50/t,this.data.scaleDisplay=this.data.scaleStep*t;const n=this.data.width,o=n*this.data.scaleStep/r,a=this.leftHanded?0:n;let l=0,h=[];if(this.data.leftHanded)for(;l<n-o;){let t=o<n-l?o:n-l;h.push([l+a,t]),l+=o}else for(;l>-n+o;){let t=o;h.push([l+a,-t]),l-=o}this.data.steps=h,this.setData()}setData(t={}){for(let e in t)this.data[e]=t[e];this.rootEl.setAttribute("viewBox",`-${this.data.margin} -${3*this.data.margin} ${this.data.width+2*this.data.margin} ${this.data.height+2*this.data.margin}`),this.rootEl.innerHTML=this.template(this.data)}template(t={}){let e="";return t.steps[0]&&(e+=`<rect\n class="fpe-scale-bar__background"\n style="fill:${this.backgroundClr()}"\n y="${2.5*-t.height}"\n x="${t.width+t.steps[0][1]-t.margin}"\n width="${-t.steps[0][1]+2*t.margin}"\n height="${4*t.height}"\n />`),e+=`<text x="${t.leftHanded?0:t.width}" text-anchor="${t.leftHanded?"start":"end"}" y="-3">\n ${t.scaleDisplay} ${t.isImperial?"ft":"m"}\n </text>`,"lines"===t.style&&(e+=`<path d="${this.stepStr(t.steps)}" />`),"solid"===t.style&&(e+="<g>",t.steps.forEach((t,i)=>{e+=`<rect\n class="${i%2!=0?"white":""}"\n x="${t[0]}"\n y="0"\n width="${t[1]}"\n height="0.5"\n />`}),e+="</g>"),e}backgroundClr(){let t=this.floorPlan.settings&&function(t,e=1){if(null!==f(t).match(/^#[a-f0-9]{6}$/i)){const{r:i,g:s,b:r}=g(t);return`rgba(${i},${s},${r},${e})`}}(this.floorPlan.settings.theme.background.color);return t||(t="rgba(255, 255, 255, 0.8)"),t+"!important"}stepStr(t){if(!t)return"";let e="",i=this.data.height;return t.forEach((t,s)=>{if(s>=1&&!this.data.leftHanded)return;t=t.map(t=>Math.round(1e3*t)/1e3);let r=s%2==0?0:i,n=s%2==0?i:0;0===s&&(e+=`M ${t[0]} ${i} L ${t[0]} 0`),e+=`L ${t[0]+t[1]} ${r} `,e+=`L ${t[0]+t[1]} ${n} `}),e}mount(t){this.rootEl||(this.rootEl=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.rootEl.classList.add("fpe-scale-bar"),t.appendChild(this.rootEl))}destroy(){this.floorPlan.view.off("viewbox",this.update),this.floorPlan.off("update-settings",this.update),this.rootEl.remove(),delete this.floorPlan.helper.scaleBar,delete this.floorPlan,delete this.data}}const px=100,fx=80;class mx{constructor({width:t,height:e,position:i=[0,0],html:s="",closeButton:r=!0,floorPlan:n}={}){this._floorPlan=n,this.position=i,this.html=s,this.closeButton=r,this._anchorPos=null;let o=t||px;this.width=Math.max(100,o);let a=e||fx;this.height=Math.max(50,a),this._getPosition=()=>{this._anchorPos=this._floorPlan.getScreenPosition(this.position),this._updateInfoWindow()},this._getPosition(),this._createInfoWindow(),this._floorPlan.view.on("viewbox",this._getPosition,this),this._floorPlan.view.on("resize-canvas",this._getPosition,this)}_createInfoWindow(){const t=document.querySelector(`#${this._floorPlan.fpeId}.fpe`),e=t.querySelector("canvas");this.el||(this.el=document.createElement("div"),this.el.classList.add("fpe-info-window"),t.appendChild(this.el),this.el.addEventListener("wheel",t=>{let i=new WheelEvent(t.type,t);e.dispatchEvent(i)})),this._setContent(),this._updateInfoWindow()}_setContent(){let t=`<div class="fpe-info-window__content">${this.html}</div>`;this.closeButton&&(t+='<div class="fpe-info-window__close" @click="infoWindow.remove"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">\n <g fill="none" stroke="#000" stroke-width="1.2" stroke-miterlimit="10">\n <path d="M11.8 11.8l16.4 16.4M11.8 28.2l16.3-16.4" />\n </g>\n</svg></div>'),this.el.innerHTML=t;const e=this.el.querySelector(".fpe-info-window__close");e&&e.addEventListener("click",this.remove.bind(this))}_updateInfoWindow(){if(!this.el)return;const t=this._floorPlan.interaction.isPanning?"pointer-events: none;":"",e=this._anchorPos[0]-47,i=this._anchorPos[1]-this.height-15,s=1e3+2*this.position[1],r=this.height,n=this.width;this.el.setAttribute("style",`transform: translate(${e}px, ${i}px);${t} height:${r}px; width:${n}px; z-index:${s}`)}set({width:t,height:e,position:i,html:s,closeButton:r}){void 0!==i&&(this.position=i),void 0!==t&&(this.width=Math.max(100,t)),void 0!==e&&(this.height=Math.max(50,e)),void 0!==s&&(this.html=s),void 0!==r&&(this.closeButton=r),void 0===s&&void 0===r||this._setContent(),this._getPosition()}remove(){this._floorPlan.view.off("viewbox",this._getPosition),this._floorPlan.view.off("resize-canvas",this._getPosition),this.el.remove(),this._floorPlan=null}}class gx{constructor({position:t=[0,0],offset:e=[0,0],el:i,floorPlan:s}){if(this._updateHtmlMarker=()=>{this.el&&(this.isHidden=!(([t,e],i,s=0)=>i.min[0]-s<t&&i.max[0]+s>t&&i.min[1]-s<e&&i.max[1]+s>e)(this.position,this._floorPlan.view.viewbox,5),this.el.classList.toggle("fpe-marker--hidden",this.isHidden),this.isHidden||(this._anchorPos=this._floorPlan.getScreenPosition(this.position),this._updateHtmlMarkerStyle()))},!s)return;if(i instanceof HTMLElement==!1)return void dl.warn("no Element provided");this.el=i;const r=document.querySelector(`#${s.fpeId}.fpe`),n=r.querySelector("canvas");r.appendChild(this.el),this.el.classList.add("fpe-marker");const{width:o,height:a}=i.getBoundingClientRect();this.el.addEventListener("wheel",t=>{let e=new WheelEvent(t.type,t);n.dispatchEvent(e)}),this.id=O(),this._floorPlan=s,this.position=t,this.size=[o,a],this.offset=e,this._updateHtmlMarker(),this._floorPlan.view.on("viewbox",this._updateHtmlMarker),this._floorPlan.on("drag-end",this._updateHtmlMarker),this._floorPlan.view.on("resize-canvas",this._updateHtmlMarker)}_updateHtmlMarkerStyle(){const t=this._floorPlan.interaction.isPanning,e=this.offset?this.offset:[0,0],i=this._anchorPos[0]-this.size[0]/2+e[0],s=this._anchorPos[1]-this.size[1]/2+e[1];this.el.style.pointerEvents=t?"none":"",this.el.style.transform=`translate(${i}px, ${s}px)`}set({position:t,offset:e}){void 0!==t&&(this.position=t),void 0!==e&&(this.offset=e),this._updateHtmlMarker()}remove(){this._floorPlan.view.off("viewbox",this._updateHtmlMarker),this._floorPlan.view.off("resize-canvas",this._updateHtmlMarker),this._floorPlan.off("drag-end",this._updateHtmlMarker),this.el.remove(),this._floorPlan=null}}var yx={grad:.9,turn:360,rad:360/(2*Math.PI)},vx=function(t){return"string"==typeof t?t.length>0:"number"==typeof t},xx=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=Math.pow(10,e)),Math.round(i*t)/i+0},bx=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=1),t>i?i:t>e?t:e},_x=function(t){return(t=isFinite(t)?t%360:0)>0?t:t+360},wx=function(t){return{r:bx(t.r,0,255),g:bx(t.g,0,255),b:bx(t.b,0,255),a:bx(t.a)}},Px=function(t){return{r:xx(t.r),g:xx(t.g),b:xx(t.b),a:xx(t.a,3)}},Ex=/^#([0-9a-f]{3,8})$/i,Tx=function(t){var e=t.toString(16);return e.length<2?"0"+e:e},Ax=function(t){var e=t.r,i=t.g,s=t.b,r=t.a,n=Math.max(e,i,s),o=n-Math.min(e,i,s),a=o?n===e?(i-s)/o:n===i?2+(s-e)/o:4+(e-i)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:r}},Ix=function(t){var e=t.h,i=t.s,s=t.v,r=t.a;e=e/360*6,i/=100,s/=100;var n=Math.floor(e),o=s*(1-i),a=s*(1-(e-n)*i),l=s*(1-(1-e+n)*i),h=n%6;return{r:255*[s,a,o,o,l,s][h],g:255*[l,s,s,a,o,o][h],b:255*[o,o,l,s,s,a][h],a:r}},Sx=function(t){return{h:_x(t.h),s:bx(t.s,0,100),l:bx(t.l,0,100),a:bx(t.a)}},Cx=function(t){return{h:xx(t.h),s:xx(t.s),l:xx(t.l),a:xx(t.a,3)}},Mx=function(t){return Ix((i=(e=t).s,{h:e.h,s:(i*=((s=e.l)<50?s:100-s)/100)>0?2*i/(s+i)*100:0,v:s+i,a:e.a}));var e,i,s},Ox=function(t){return{h:(e=Ax(t)).h,s:(r=(200-(i=e.s))*(s=e.v)/100)>0&&r<200?i*s/100/(r<=100?r:200-r)*100:0,l:r/2,a:e.a};var e,i,s,r},Nx=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Lx=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Rx=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,kx=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Bx={string:[[function(t){var e=Ex.exec(t);return e?(t=e[1]).length<=4?{r:parseInt(t[0]+t[0],16),g:parseInt(t[1]+t[1],16),b:parseInt(t[2]+t[2],16),a:4===t.length?xx(parseInt(t[3]+t[3],16)/255,2):1}:6===t.length||8===t.length?{r:parseInt(t.substr(0,2),16),g:parseInt(t.substr(2,2),16),b:parseInt(t.substr(4,2),16),a:8===t.length?xx(parseInt(t.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(t){var e=Rx.exec(t)||kx.exec(t);return e?e[2]!==e[4]||e[4]!==e[6]?null:wx({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:void 0===e[7]?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(t){var e=Nx.exec(t)||Lx.exec(t);if(!e)return null;var i,s,r=Sx({h:(i=e[1],s=e[2],void 0===s&&(s="deg"),Number(i)*(yx[s]||1)),s:Number(e[3]),l:Number(e[4]),a:void 0===e[5]?1:Number(e[5])/(e[6]?100:1)});return Mx(r)},"hsl"]],object:[[function(t){var e=t.r,i=t.g,s=t.b,r=t.a,n=void 0===r?1:r;return vx(e)&&vx(i)&&vx(s)?wx({r:Number(e),g:Number(i),b:Number(s),a:Number(n)}):null},"rgb"],[function(t){var e=t.h,i=t.s,s=t.l,r=t.a,n=void 0===r?1:r;if(!vx(e)||!vx(i)||!vx(s))return null;var o=Sx({h:Number(e),s:Number(i),l:Number(s),a:Number(n)});return Mx(o)},"hsl"],[function(t){var e=t.h,i=t.s,s=t.v,r=t.a,n=void 0===r?1:r;if(!vx(e)||!vx(i)||!vx(s))return null;var o,a=(o={h:Number(e),s:Number(i),v:Number(s),a:Number(n)},{h:_x(o.h),s:bx(o.s,0,100),v:bx(o.v,0,100),a:bx(o.a)});return Ix(a)},"hsv"]]},Fx=function(t,e){for(var i=0;i<e.length;i++){var s=e[i][0](t);if(s)return[s,e[i][1]]}return[null,void 0]},Dx=function(t,e){var i=Ox(t);return{h:i.h,s:bx(i.s+100*e,0,100),l:i.l,a:i.a}},Ux=function(t){return(299*t.r+587*t.g+114*t.b)/1e3/255},Gx=function(t,e){var i=Ox(t);return{h:i.h,s:i.s,l:bx(i.l+100*e,0,100),a:i.a}},Xx=function(){function t(t){this.parsed=function(t){return"string"==typeof t?Fx(t.trim(),Bx.string):"object"==typeof t&&null!==t?Fx(t,Bx.object):[null,void 0]}(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return t.prototype.isValid=function(){return null!==this.parsed},t.prototype.brightness=function(){return xx(Ux(this.rgba),2)},t.prototype.isDark=function(){return Ux(this.rgba)<.5},t.prototype.isLight=function(){return Ux(this.rgba)>=.5},t.prototype.toHex=function(){return e=(t=Px(this.rgba)).r,i=t.g,s=t.b,n=(r=t.a)<1?Tx(xx(255*r)):"","#"+Tx(e)+Tx(i)+Tx(s)+n;var t,e,i,s,r,n},t.prototype.toRgb=function(){return Px(this.rgba)},t.prototype.toRgbString=function(){return e=(t=Px(this.rgba)).r,i=t.g,s=t.b,(r=t.a)<1?"rgba("+e+", "+i+", "+s+", "+r+")":"rgb("+e+", "+i+", "+s+")";var t,e,i,s,r},t.prototype.toHsl=function(){return Cx(Ox(this.rgba))},t.prototype.toHslString=function(){return e=(t=Cx(Ox(this.rgba))).h,i=t.s,s=t.l,(r=t.a)<1?"hsla("+e+", "+i+"%, "+s+"%, "+r+")":"hsl("+e+", "+i+"%, "+s+"%)";var t,e,i,s,r},t.prototype.toHsv=function(){return t=Ax(this.rgba),{h:xx(t.h),s:xx(t.s),v:xx(t.v),a:xx(t.a,3)};var t},t.prototype.invert=function(){return Wx({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},t.prototype.saturate=function(t){return void 0===t&&(t=.1),Wx(Dx(this.rgba,t))},t.prototype.desaturate=function(t){return void 0===t&&(t=.1),Wx(Dx(this.rgba,-t))},t.prototype.grayscale=function(){return Wx(Dx(this.rgba,-1))},t.prototype.lighten=function(t){return void 0===t&&(t=.1),Wx(Gx(this.rgba,t))},t.prototype.darken=function(t){return void 0===t&&(t=.1),Wx(Gx(this.rgba,-t))},t.prototype.rotate=function(t){return void 0===t&&(t=15),this.hue(this.hue()+t)},t.prototype.alpha=function(t){return"number"==typeof t?Wx({r:(e=this.rgba).r,g:e.g,b:e.b,a:t}):xx(this.rgba.a,3);var e},t.prototype.hue=function(t){var e=Ox(this.rgba);return"number"==typeof t?Wx({h:t,s:e.s,l:e.l,a:e.a}):xx(e.h)},t.prototype.isEqual=function(t){return this.toHex()===Wx(t).toHex()},t}(),Wx=function(t){return t instanceof Xx?t:new Xx(t)},Yx=[];!function(t){t.forEach(function(t){Yx.indexOf(t)<0&&(t(Xx,Bx),Yx.push(t))})}([function(t,e){var i={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"},s={};for(var r in i)s[i[r]]=r;var n={};t.prototype.toName=function(e){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var r,o,a=s[this.toHex()];if(a)return a;if(null==e?void 0:e.closest){var l=this.toRgb(),h=1/0,u="black";if(!n.length)for(var c in i)n[c]=new t(i[c]).toRgb();for(var d in i){var p=(r=l,o=n[d],Math.pow(r.r-o.r,2)+Math.pow(r.g-o.g,2)+Math.pow(r.b-o.b,2));p<h&&(h=p,u=d)}return u}},e.string.push([function(e){var s=e.toLowerCase(),r="transparent"===s?"#0000":i[s];return r?new t(r).toRgb():null},"name"])}]);const Hx=class t{constructor(t=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=t}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(t){return this.value=t,this}set value(e){if(e instanceof t)this._value=this.cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(null===e)throw new Error("Cannot set PIXI.Color#value to null");(null===this._value||!this.isSourceEqual(this._value,e))&&(this.normalize(e),this._value=this.cloneSource(e))}}get value(){return this._value}cloneSource(t){return"string"==typeof t||"number"==typeof t||t instanceof Number||null===t?t:Array.isArray(t)||ArrayBuffer.isView(t)?t.slice(0):"object"==typeof t&&null!==t?{...t}:t}isSourceEqual(t,e){const i=typeof t;if(i!==typeof e)return!1;if("number"===i||"string"===i||t instanceof Number)return t===e;if(Array.isArray(t)&&Array.isArray(e)||ArrayBuffer.isView(t)&&ArrayBuffer.isView(e))return t.length===e.length&&t.every((t,i)=>t===e[i]);if(null!==t&&null!==e){const i=Object.keys(t),s=Object.keys(e);return i.length===s.length&&i.every(i=>t[i]===e[i])}return t===e}toRgba(){const[t,e,i,s]=this._components;return{r:t,g:e,b:i,a:s}}toRgb(){const[t,e,i]=this._components;return{r:t,g:e,b:i}}toRgbaString(){const[t,e,i]=this.toUint8RgbArray();return`rgba(${t},${e},${i},${this.alpha})`}toUint8RgbArray(t){const[e,i,s]=this._components;return(t=t??[])[0]=Math.round(255*e),t[1]=Math.round(255*i),t[2]=Math.round(255*s),t}toRgbArray(t){t=t??[];const[e,i,s]=this._components;return t[0]=e,t[1]=i,t[2]=s,t}toNumber(){return this._int}toLittleEndianNumber(){const t=this._int;return(t>>16)+(65280&t)+((255&t)<<16)}multiply(e){const[i,s,r,n]=t.temp.setValue(e)._components;return this._components[0]*=i,this._components[1]*=s,this._components[2]*=r,this._components[3]*=n,this.refreshInt(),this._value=null,this}premultiply(t,e=!0){return e&&(this._components[0]*=t,this._components[1]*=t,this._components[2]*=t),this._components[3]=t,this.refreshInt(),this._value=null,this}toPremultiplied(t,e=!0){if(1===t)return(255<<24)+this._int;if(0===t)return e?0:this._int;let i=this._int>>16&255,s=this._int>>8&255,r=255&this._int;return e&&(i=i*t+.5|0,s=s*t+.5|0,r=r*t+.5|0),(255*t<<24)+(i<<16)+(s<<8)+r}toHex(){const t=this._int.toString(16);return`#${"000000".substring(0,6-t.length)+t}`}toHexa(){const t=Math.round(255*this._components[3]).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(t){return this._components[3]=this._clamp(t),this}round(t){const[e,i,s]=this._components;return this._components[0]=Math.round(e*t)/t,this._components[1]=Math.round(i*t)/t,this._components[2]=Math.round(s*t)/t,this.refreshInt(),this._value=null,this}toArray(t){t=t??[];const[e,i,s,r]=this._components;return t[0]=e,t[1]=i,t[2]=s,t[3]=r,t}normalize(e){let i,s,r,n;if(("number"==typeof e||e instanceof Number)&&e>=0&&e<=16777215){i=(e>>16&255)/255,s=(e>>8&255)/255,r=(255&e)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[i,s,r,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[i,s,r,n=255]=e,i/=255,s/=255,r/=255,n/=255;else if("string"==typeof e||"object"==typeof e){if("string"==typeof e){const i=t.HEX_PATTERN.exec(e);i&&(e=`#${i[2]}`)}const o=Wx(e);o.isValid()&&(({r:i,g:s,b:r,a:n}=o.rgba),i/=255,s/=255,r/=255)}if(void 0===i)throw new Error(`Unable to convert color ${e}`);this._components[0]=i,this._components[1]=s,this._components[2]=r,this._components[3]=n,this.refreshInt()}refreshInt(){this._clamp(this._components);const[t,e,i]=this._components;this._int=(255*t<<16)+(255*e<<8)+(255*i|0)}_clamp(t,e=0,i=1){return"number"==typeof t?Math.min(Math.max(t,e),i):(t.forEach((s,r)=>{t[r]=Math.min(Math.max(s,e),i)}),t)}};Hx.shared=new Hx,Hx.temp=new Hx,Hx.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let $x=Hx;class jx{constructor({position:t,color:e,size:i,floorPlan:s}){this.position=t,this.color=e,this.size=i,this.floorPlan=s,this.id=O(),this.draw()}draw(){const t=this.size/4e3;this.layer=this.floorPlan.addLayer({id:"fpe-markers"});let e=[{type:"curve:composite",segments:[{type:"curve:arc",position:[0,-27.8],radius:12.4,startAngle:-25,endAngle:205},{type:"curve:line",end:[0,0],start:[-11.2,-22.5]}],style:{fill:new $x(this.color).toNumber(),stroke:6710886,strokeWidth:.5/t}},{type:"curve:circle",position:[0,-28],radius:5,style:{fill:1,fillOpacity:.2}}];this.graphic=this.layer.addGraphic({shapes:e,position:this.position,id:"marker_"+this.id,scale:t,scaleOnZoom:!0})}remove(){this.off("click"),this.layer.deleteGraphic(this.graphic),delete this.floorPlan,0===this.layer.graphics.size&&this.layer.destroy()}on(t="click",e,i){this.graphic.gfx.eventMode="static",this.graphic.gfx.on(t,e,i)}off(t="click",e){this.graphic.gfx.off(t,e)}set(t){let e=["position","color","size"];Object.keys(t).forEach(i=>{e.includes(i)&&(this[i]=t[i])}),this.draw()}}const zx=t=>{if(t?.children)for(var e=t.children.length-1;e>=0;e--)t.children[e].destroy({children:!0}),t.removeChild(t.children[e])};function Vx(t,e,i){const s=new Rg(t);return s.x=0,s.y=0,s.anchor.x=.5,s.anchor.y=.5,s.rotation=0,e&&(s.width=e),i&&(s.height=i),s}function qx(t=[]){return(t=t.sort((t,e)=>K(t)>K(e)?-1:1))&&t.length?[{type:"curve:polygonWithHoles",polygons:t}]:[]}function Jx(t,e,i=!1,s=16,r=8){let n=[];for(let m=0;m<e.length-1;m+=2)n.push({x:e[m],y:e[m+1]});let o,a,l,h=0,u=0,c=i?1:0;for(o=0;o<n.length-c;o++){a=n[o],l=o==n.length-1?n[0]:n[o+1];let e=l.x-a.x,i=l.y-a.y;var d=Math.sqrt(e*e+i*i),p={x:e/d,y:i/d},f=0;for(t.moveTo(a.x+u*p.x,a.y+u*p.y);f<=d;)f+=u,(f+=h>0?h:s)>d?(h=f-d,f=d):h=0,t.lineTo(a.x+f*p.x,a.y+f*p.y),(f+=r)>d&&0==h?u=f-d:(u=0,t.moveTo(a.x+f*p.x,a.y+f*p.y))}}function Kx(t){return t.stroke?{alpha:t.strokeOpacity||1,color:Dl(t.stroke),native:"native"===t.strokeWidth,width:"number"==typeof t.strokeWidth?t.strokeWidth:1,alignment:"number"==typeof t.alignment?t.alignment:.5}:{}}function Zx({shape:t,settings:e,gfx:i,style:s={}}){if(!i||!i.lineStyle)return;let r={...s,...t.style||{}};const n=ox,o=!["curve:line","curve:polyline","curve:arc"].includes(t.type)&&!!r.fill;if("string"==typeof r?.fill&&r.fill.startsWith("url("))!function({shape:t,settings:e,style:i,gfx:s}){if(Bp.defaultOptions.scaleMode=sh.NEAREST,"string"!=typeof i.fill||"curve:rectangle"!==t.type&&"curve:polygon"!==t.type)return;let r,n,o=[0,0],a=i.fill.match(/url\((.*?)\)/)?.[1];if(!a||!a.startsWith("data:image")&&!a.startsWith("https://"))return;let l=Rg.from(a);if("curve:polygon"===t.type){let{min:i,max:a}=W([t.points]);r=a[0]-i[0],n=a[1]-i[1],o=i;let h=new ay;Zx({shape:{type:"curve:polygon",points:t.points,style:{fill:16777215}},settings:e,gfx:h}),s.addChild(h),l.mask=h}else r=t.dimensions[0],n=t.dimensions[1],o=t.position;l.width=r*ox,l.height=n*ox,l.x=o[0]*ox,l.y=o[1]*ox,l.anchor.set(0),s.addChild(l)}({shape:t,settings:e,style:r,gfx:i});else{if(o&&r.fill&&i.beginFill(Dl(r.fill),r.fillOpacity),i.lineStyle(Kx(r)),"curve:rectangle"===t.type){let{position:e,dimensions:s}=t;i.drawRect(e[0]*n,e[1]*n,s[0]*n,s[1]*n)}else if("curve:circle"===t.type||"curve:composite"===t.type){Qx((t=>{const e={type:"curve:polygon",points:[]};switch(t.type){case"curve:circle":const i=t.radius,s=Hl(2*Math.PI,i),r=t.position,n=2*Math.PI/s;let o=0;for(let t=0;t<s;t++)e.points.push([i*Math.cos(o)+r[0],-i*Math.sin(o)+r[1]]),o+=n;break;case"curve:polygon":e.points=t.points;break;case"curve:rectangle":const a=t.dimensions,[l,h]=t.position||[0,0];e.points=[[l,h],[l,h+a[1]],[l+a[0],h+a[1]],[l+a[0],h]];break;case"curve:composite":for(const u of t.segments){let t=$l(u);e.points.push(...t.points)}}return e})(t).points,[],r,n,i,o)}else if("curve:arc"===t.type||"curve:quadraticBezier"===t.type){$l(t).points.forEach((t,e)=>{0===e?i.moveTo(t[0]*n,t[1]*n):i.lineTo(t[0]*n,t[1]*n)})}else if("curve:polygon"===t.type)Qx(t.points,[],r,n,i,o);else if("curve:polygonWithHoles"===t.type){let{polygons:e}=t;Qx(e[0],e.slice(1),r,n,i,o)}else if("curve:line"===t.type){let{start:e=[],end:s=[]}=t;i.moveTo(e[0]*n,e[1]*n),i.lineTo(s[0]*n,s[1]*n)}else if("curve:polyline"===t.type){let{points:e}=t;r.dash?Jx(i,e.flat().map(t=>t*n),!0):e.forEach((t,e)=>{0===e?i.moveTo(t[0]*n,t[1]*n):i.lineTo(t[0]*n,t[1]*n)})}else if("group"===t.type){let{position:r=[0,0],rotation:o=0}=t,a=new ay;a.x=r[0]*n,a.y=r[1]*n,a.rotation=-Math.PI/180*o,t.children.forEach(t=>Zx({shape:t,settings:e,gfx:a,style:s})),i.addChild(a)}else if("text"===t.type){let s=t.style?.fill?Dl(t.style.fill):0,r=t.style?.stroke?Dl(t.style.stroke):16777215,{position:o=[0,0],rotation:a=0,text:l,alignH:h="center",alignV:u="center",fontSize:c=16}=t;const d=new fy({fontFamily:e?.theme?.fontFamily||ll.theme.fontFamily,fontSize:c,fill:s,align:h,stroke:r,strokeThickness:3});let p=new xy(l,d);p.x=o[0]*n,p.y=o[1]*n,p.rotation=-Math.PI/180*a,p.anchor.x=.5,p.anchor.y="center"===u?.5:"bottom"===u?1:0,i.addChild(p)}o&&i.endFill()}}function Qx(t=[],e=[],i={},s=100,r,n){if(!t||!Array.isArray(t)||!t.length)return r;r.lineStyle(Kx(i));let o=t.flat().map(t=>t*s);if(i.dash?(Jx(r,o),n&&(r.lineStyle(0),r.drawPolygon(o))):r.drawPolygon(o),e.length){n&&r.beginHole();for(const t of e){let e=t.flat().map(t=>t*s);r.drawPolygon(e)}n&&r.endHole()}return r}function tb(t,e){e.on("product-load-texture",({resourceId:i})=>{!function(t,e){let i=t.resources.productJson.get(e);if(!i.boundingBox)return void dl.warn("product boundingBox missing");const{boundingBox:s}=i,r=Tl(s);let n={x:s.min[0],y:s.min[2]},o={x:Math.abs(s.min[0]/r[0]),y:Math.abs(s.min[2]/r[2])},a={x:s.max[0]-r[0]/2,y:s.max[2]-r[2]/2},l=t.resources.texture.get(e);l.offset=a,l.anchor=o,l.position=n}(e,i),eb({view:t,resourceId:i,loader:e})});const i=new ay;i.lineStyle({native:!0,color:3355443}),i.drawCircle(0,0,1),t._dummyTexture=t._renderer.generateTexture(i)}function eb({resourceId:t,loader:e,view:i}){if(!e.resources.texture.has(t))return Promise.reject(`no texture data to load ${t}`);const s=e.resources.texture.get(t);if(s.texture)return Promise.resolve();let{textureUrl:r}=s;return dp(),function(t){return new Promise((e,i)=>{var s=new Image;s.addEventListener("load",()=>{URL.revokeObjectURL(s.src),e(new om(new Bp(s)))}),s.addEventListener("error",()=>{URL.revokeObjectURL(s.src),i("image loading failed: "+t)});const r=t.includes("/storage/get/"),n=t.startsWith("https://")?t:ul+t;s.src=n,s.crossOrigin=r?"use-credentials":"anonymous"})}(r).then(r=>{s.imageData=r,function(t,e,i){const s=e?._renderer,r=i.resources.texture.get(t),n=r.error;if(dp(),!r.texture){const e=i.resources.productJson.get(t),o=new Og;let a,l;n||(a=new Rg(r.imageData),a=sb(a,r.applyFilter),o.addChild(a));const h=i.resources.productContour.get(t),u=h?.length?[{type:"curve:polygon",points:h[0],holes:h.slice(1)}]:[];if(u.length&&e?.boundingBox){let t;n?t={strokeWidth:.5,stroke:1,fill:16316664}:(t=Xl({settings:{theme:{showAssetTextures:!0,elements:{}}},elementType:"element:asset"}),t.stroke=Ka),l=ib(u,t);const i=new Rg(l);i.anchor.x=r.anchor.x,i.anchor.y=r.anchor.y;const s=Tl(e.boundingBox);if(!n){let t=a.width/s[0],e=r?.offset||{x:0,y:0};i.scale.x=a.width/i.width,i.scale.y=a.height/i.height,i.x=a.width/2-e.x*t,i.y=a.height/2-e.y*t}o.addChild(i)}r.texture=s.generateTexture(o,{scaleMode:sh.LINEAR,resolution:1.5}),o.destroy(!0),l&&l.destroy(!0)}i.emit("resource-loaded",{resourceId:t})}(t,i,e)}).catch(i=>{dl.warn(i),s.error={message:i},e.emit("resource-loaded",{resourceId:t})})}function ib(t,e){let i,s=new ay;for(const r of t)Zx({shape:r,gfx:s,style:e});return i=s.generateCanvasTexture(sh.LINEAR,2),s.destroy(),i}function sb(t,e){switch(e){case _l.Default:{const e=new by;e.matrix=[.7,0,0,0,.25,0,.7,0,0,.25,0,0,.7,0,.25,0,0,0,1,0],t.filters=[e];break}case _l.Grayscale:{const e=new by;e.blackAndWhite(!0),t.filters=[e];break}case _l.None:}return t}function rb(t,e,i,s,r,n,o){const a=Tl(t.boundingBox),l=Vx(e.texture,a[0]*o,a[2]*o);l.anchor.x=e.anchor.x,l.anchor.y=e.anchor.y,l.zIndex=1,function(t,e,i,s){if(!e.categories?.includes("tables")&&!e.categories?.includes("seating")||!i[0]?.polygons[0])return;const r=new sf(i[0].polygons[0].flatMap(e=>[e[0]*s/t.scale.x,e[1]*s/t.scale.y]));t.hitArea=r,t.eventMode="static"}(l,t,i,o);const h=[];let u=[];if(!n&&(null!=r.fill||null!=r.stroke)&&i?.length){const t=function(t,e,i,s,r){const n=null!=i.fill,o=null!=i.stroke,a=e.fillOpacity??1;if(!n&&!o)return null;if(n&&a<=0&&!o)return null;const l=ib(t,{fill:n?e.fill:void 0,fillOpacity:n?a:0,stroke:o?e.stroke:void 0,strokeWidth:o?e.strokeWidth:void 0,strokeOpacity:o?e.strokeOpacity:void 0}),h=new Rg(l);return h.anchor.x=s,h.anchor.y=r,h.zIndex=2,h.eventMode="none",h}(i,s,r,e.anchor.x,e.anchor.y);t&&h.push(t)}if("selected"===n)h.push(function(t,e,i,s){e.contourTexture||(e.contourTexture=ib(t,{stroke:i.stroke,strokeWidth:i.strokeWidth||1}));const r=new Rg(e.contourTexture);return r.anchor.x=e.anchor.x,r.anchor.y=e.anchor.y,r.zIndex=5,r.eventMode="none",i.fill&&(s.tint=Dl(i.fill)),r}(i,e,s,l));else if(n){const{overlay:t,shapes:e}=function(t){const e=new ay;return e.zIndex=5,e.eventMode="none",{overlay:e,shapes:t||[]}}(i);h.push(t),u=e}return{gfx:l,overlays:h,shapes:u}}function nb(t,e,i,s){!function(t,e){const i=t.product?.id,{loader:s}=e,r=s.resources.nodes.get(i);if(i&&!r?.has(t))pl(e.loader,t).catch(t=>dl.warn(t))}(t,i);const{view:r,settings:n,loader:o}=i,{theme:a,showCeilingLamps:l}=n;let h,u=[];const c=[],d=t.product?.id,p=o.resources.productJson.get(d)||{subCategories:[]},f="product:component"===t.product?.type,m=o.resources.productContour.get(d),g=o.resources.texture.get(d),y=qx(m);if(p?.subCategories.includes("ceilingLight")&&!l)return[];const v=function(t,e,i){if(!i)return zl(e);let s=0;for(const r of t.elements){if("element:asset"!==r.type||!r.product)continue;const t=zl(r.product.attributes);t>s&&(s=t)}return s}(t,p,f),x=Rl(t.type,v);e.zIndex=x||0;let b=Xl({element:t,settings:n,style:s});if(m||f||!p.boundingBox)if(a.showAssetTextures&&!g?.error||!m)if(a.showAssetTextures&&g?.texture){const e=rb(p,g,y,b,Ul({settings:n,element:t,elementType:t.type}),s,100);h=e.gfx,c.push(...e.overlays),u=e.shapes}else h=new Rg(r._dummyTexture);else{const e={...a,showAssetTextures:!1};b=Xl({element:t,settings:{...n,theme:e},style:s}),u=y,h=new ay}else{u=qx(function(t){const e=t;if(e){let t;return t=[[e.min[0],e.min[2]],[e.min[0],e.max[2]],[e.max[0],e.max[2]],[e.max[0],e.min[2]]],[t]}return[]}(p.boundingBox)),h=new ay}const _=c.length>0?c[c.length-1]:h;for(const w of u)Zx({shape:w,settings:n,gfx:_,style:b});return[h,...c].filter(Boolean)}function ob(t,e){const i=[];if("element:wall"===t.type)i.push(...function(t){let{valid:e,points:i}=t.geometryProfile,s=[];if(t.layout?.debugIds){for(let t of i)s.push({type:"curve:circle",radius:.02,position:t,style:{stroke:0,fill:e?32768:16711680,fillOpacity:.2}});let r=Xl({element:t});e||(r.stroke=16711680),s.push({type:"curve:polygon",points:i,style:r})}else s.push({type:"curve:polygon",points:i});return s}(t));else if("element:opening"===t.type)i.push(...Al(t));else if("spatialGraph:edge"===t.type)i.push(...function(t,e={}){let[i,s]=t.vertices,r="selected"===e,n=[{type:"curve:line",start:i.position,end:s.position}];if(t.layout.debugIds){let e,r=za(t.id)?t.id.substring(0,4):t.id;t.element&&(e=za(t.element.id)?t.element.id.substring(0,4):t.element.id);let o=t.element?`${r} (${e})`:r;n.push({type:"text",position:ii(i.position,ci(di(s.position,i.position),.5)),text:o,fontSize:10})}if(null===t.element||"element:spaceDivider"===t.element.type){let t=hi(ui(di(s.position,i.position))),e=.02,o=ii(i.position,ci(t,-e)),a=ii(i.position,ci(t,e)),l=ii(s.position,ci(t,e)),h=ii(s.position,ci(t,-e));n.unshift({type:"curve:polygon",points:[o,a,l,h],style:{stroke:null,fill:r?nl:sl,fillOpacity:.1}})}return n}(t));else if("layout:space"===t.type){const e=t.geometry.polygons;e.length>0&&i.push({type:"curve:polygonWithHoles",polygons:e})}else if("geometries"in t&&t.geometries.length){const{shapes:s,maxY:r}=function(t){const e=$a(t).sort((t,e)=>t.boundingBox.max[1]<e.boundingBox.max[1]?-1:1);"element:door"!==t.type&&"element:window"!==t.type||e.pop();let i=e.length?e[e.length-1].boundingBox.max[1]:0,s=[];for(let r of e)for(let t=0;t<r.outlines.length;t++)s.push({type:"curve:polygonWithHoles",polygons:[r.outlines[t],...r.holes[t]||[]]});return{shapes:s,maxY:i}}(t);i.push(...s),e.zIndex=e.zIndex+r}return i}function ab(t,e,i,s,r,n){if(!e||e.destroyed)return void dl.warn(`graphic container for node ${t.id} is missing`);let o,a,l=[];const{view:h}=i;if("element:asset"!==t.type||t.isComponentInstance)if("annotation:floorPlanImage"===t.type){const s=function(t,e,i){const{view:s,settings:r,loader:n}=i,o=ox;let a,l;e.x=t.position[0]*o,e.y=t.position[2]*o,e.rotation=-Math.PI/180*t.rotation||0;const{uri:h,length:u,width:c}=t.parameters,d=t.id,p=r.theme.elements?.floorPlan?.grayscale?_l.Grayscale:_l.None,f=n.resources.texture.get(d);return f?.texture?(a=Vx(f.texture,u*o,c*o),a=sb(a,p),l=new ay,a.zIndex=1,l.zIndex=5):(n.resources.nodes.set(d,/* @__PURE__ */new Set([t])),n.resources.texture.set(d,{textureUrl:h,applyFilter:p}),eb({loader:n,view:s,resourceId:d}),a=new ay),[a,l]}(t,e,i);o=s[0],a=s[1]}else o=function(t,e,i,s){const{settings:r}=i,n=ob(t,e),o=Nl(t);n.push(...o);const a=new ay,l=Xl({element:t,settings:r,style:s});for(const h of n)Zx({shape:h,settings:r,gfx:a,style:l});return a}(t,e,i,s);else{const r=nb(t,e,i,s);o=r[0],l=r.slice(1)}!function(t,e,i){if(!function(t){var e;return null==(e=null==t?void 0:t.type)?void 0:e.startsWith("element")}(t))return;const s=t.parent&&t.parent.id!==i?.name?t.getWorldTransform():t.getTransform();e.x=s.position[0]*ox,e.y=s.position[2]*ox,e.rotation=-Math.PI/180*s.rotation||0}(t,e,n),!r&&o&&function(t,e,i,s){s.gfxNodes[t.id]=e,i.eventMode="static";let r=t.id;"element"in t&&t.element&&(r=t.element.id),i._nodeId=r}(t,e,o,h),o&&e.addChild(o),a&&e.addChild(a);for(const u of l)u&&e.addChild(u)}function lb(t,e,{ctx:i,style:s,container:r,preview:n}){const{view:o,settings:a}=e;if(!t?.spaceGraph)return;let l;n||(s?o.styleCache[t.id]=s:!1===s?delete o.styleCache[t.id]:s=o.styleCache[t.id]),r?(l=r,zx(l)):l=new Og;const h=a.hideElements.includes(t.type)||"spatialGraph:edge"===t.type&&!a.showSpaceDividers||"element:spaceDivider"===t.type||"annotation:floorPlanImage"===t.type&&!a.showFloorPlan||"element:asset"===t.type&&"product"in t&&t.product?.attributes?.subCategories?.includes("ceilingLight")&&!a.showCeilingLamps||"space"in t||("element:window"===t.type||"element:door"===t.type)&&!t.parent||e.computed.wallContours.length&&["element:wall","element:boundaryWall","element:column","spatialGraph:edge"].includes(t.type),u=Rl(t.type);if(l.zIndex=u||0,l.name=t.id,h||ab(t,l,e,s,n,i),t&&"elements"in t){t.elements.length&&(l.sortableChildren=!0);for(const i of t.elements)lb(i,e,{ctx:l,style:s,preview:n})}r||i.addChild(l),o.viewportNeedsUpdate=!0}function hb(t,e){const i=e.getChildByName(t);i?.destroy(!0)}function ub(t,e,i,s){if(hb(t.id,e),s.hideElements.includes("roomStamp"))return;const{text:r,textOutline:n=!0}=s.theme.elements?.roomStamp||{},o=s.theme.background.color,a="transparent"!==o?o:"#eee",l=r?(h=r.map(t=>t/255),"#"+((255*h[0]<<16)+(255*h[1]<<8)+(255*h[2]|0)).toString(16).padStart(6,"0")):"#333333";var h;const u=new fy({fontFamily:s.theme.fontFamily||ll.theme.fontFamily,fontSize:16,align:"center",fill:l,stroke:a,strokeThickness:n?3:0});let c=t.geometry.polygons;if(0===c.length)return;let p=Ei(c),f=function(t,e){let i=t.getArea(),s=t.attributes.usage;if("void"===Ll(s))return[];let{roomStampDisplay:r}=e.theme.elements?.roomStamp||{};const n=e.spaceLabelMapping||{};let o,a;void 0!==n[s]&&(o=n[s]),void 0!==n[t.id]&&(o=n[t.id]),a="area"===e.units.roomDimensions?d(i,e.units.system,e.units.areaDecimals):"";let l="";l||"undefined"===s||(l=(s||"").replace(/([A-Z])/g,t=>` ${t}`).replace(/^./,t=>t.toUpperCase()).trim()),void 0!==o&&("string"!=typeof o?dl.warn("space label mapping has to be a string"):o.length>50?dl.warn("space label mapping has to be less than 50 characters"):l=o),r||(r=[],!1!==e.theme.elements?.roomStamp&&(t.layout.debugIds?r.push("id"):r.push("usage","area")));const h=[];return r.forEach(e=>{switch(e){case"id":let i=za(t.id)?t.id.substring(0,4):t.id;h.push(i);break;case"name":t.name&&h.push(t.name);break;case"customId":t.customId&&h.push(t.customId);break;case"usage":h.push(l);break;case"area":h.push(a);break;default:Array.isArray(e)&&"customAttribute"===e[0]&&t.customAttributes[e[1]]&&h.push(String(t.customAttributes[e[1]]))}}),h}(t,s),m=f.join("\n");const g=new xy(m,u);g.x=p[0]*ox,g.y=p[1]*ox,g.anchor.x=.5,g.anchor.y=.5,cb(g,i,t),g.name=t.id,g.eventMode="none",e.addChild(g)}function cb(t,e,i){let s=Math.min(1/e,2);t.scale.x=s,t.scale.y=s,t.visible=i.getArea()>1.5*s}function db(t="linear"){return Ty[t]}function pb({bb:t,animate:e=!1,view:i}){const s=i._viewport;if(!s)throw new Error("no viewport");return i.viewportPaused&&i.startAnimationLoop(),new Promise(r=>{Number.isFinite(t.min?.[0])||r(!1);const{min:n,max:o}=t;let a=n[0],l=n[1];let h=o[0]-a,u=o[1]-l;a*=ox,l*=ox,h*=ox,u*=ox;let c=0;"number"==typeof e&&Number.isFinite(e)?c=e:!0===e&&(c=500);let d={x:a+h/2,y:l+u/2,width:h,height:u};if(c){let t={x:s.center.x,y:s.center.y,width:s.worldScreenWidth,height:s.worldScreenHeight},e={x:t.x-d.x,y:t.y-d.y,width:t.width-d.width,height:t.height-d.height};i._zoomTarget={delta:e,start:t,target:d,time:0,duration:c,destroy:()=>{i.ticker.remove("animateView"),delete i._zoomTarget,r(!0)},ease:db("easeInOutQuad"),updateViewport:mb.bind(i)},i.ticker.add("animateView",fb,i)}else s.fit(!1,d.width,d.height).moveCenter(d.x,d.y),mb.bind(i)({type:"animation"}),i.viewportNeedsUpdate=!0,r(!0)})}function fb(t){let e=this._zoomTarget,i=!1;e.time+=t;let s=e.ease(e.time,0,1,e.duration),r={x:e.start.x-e.delta.x*s,y:e.start.y-e.delta.y*s,width:e.start.width-e.delta.width*s,height:e.start.height-e.delta.height*s};e.time>e.duration&&(r=e.target,i=!0),this._viewport.fit(!1,r.width,r.height).moveCenter(r.x,r.y),this.viewportNeedsUpdate=!0,e.updateViewport({type:"animation"});const n=0!==this._viewport.input.count();(i||n)&&e.destroy()}function mb(t){this.viewportNeedsUpdate=!0,this.viewportPaused&&this.startAnimationLoop();const e=this._viewport;"animation"!==t.type&&this._zoomTarget&&this._zoomTarget.destroy();const i=ox,s=e.scale._x,r=e.left,n=e.top,o=e.worldScreenWidth,a=e.worldScreenHeight;this.viewbox={min:[r/i,n/i],max:[(r+o)/i,(n+a)/i]},this.client=[e.screenWidth,e.screenHeight];const l=this.zoom!==s;this.zoom=s;const h={sourceEvent:{type:t.type},viewbox:this.viewbox,zoom:this.zoom};l?this.emit("zoom",h):this.emit("pan",h),this.emit("viewbox",h)}function gb({position:t,nodeId:e}){yb(this.interaction,{cursor:t,cursorTarget:e&&this.layout&&(this.layout.elementsById[e]||this.layout.spacesById[e])})}function yb(t,e){for(const i in e)t[i]=e[i],"cursorAction"===i&&vb(e[i])}function vb(t){let e="";switch(t){case"split-wall":e="var(--fpe-split-cursor) 16 16, pointer";break;case"duplicate":e="var(--fpe-duplicate-cursor) 16 16, pointer";break;case"move":e="move";break;default:e="default"}document.body.style.cursor=e}function xb(t){if(2===t?.data?.originalEvent?.button)return;if(!this||!this.view)throw new Error("Viewport context is missing");let e=this.interaction._dragStart||{x:0,y:0},i=t.data.global||{x:0,y:0},s=Math.abs(i.x-e.x),r=Math.abs(i.y-e.y);if(!(s<5&&r<5))return;let n,o=/* @__PURE__ */(new Date).getTime();if(this.interaction.lastClick){let t=o-this.interaction.lastClick.time,e=this.interaction.lastClick.position&&Math.max(Math.abs(i.x-this.interaction.lastClick.position.x),Math.abs(i.y-this.interaction.lastClick.position.y));n=t<400&&e<10}this.interaction.lastClick={time:o,position:{...i}};const a=n?"dblclick":"click",l=t.target?._nodeId,{x:h,y:u}=t.data?.global||{},c=this.getPlanPosition([h,u]);yb(this.interaction,{cursor:[c[0],c[1]]});let d={sourceEvent:t,nodeId:l,position:c,isDoubleClick:!!n};this.emit(a,d)}function bb(t){const{x:e,y:i}=t.data.global;this.view.windowPos=[e,i];const s=this.getPlanPosition(this.view.windowPos);this.interaction.lastSceneClick=s;const r=t.target?._nodeId;this.emit("context-menu",{sourceEvent:t,nodeId:r,position:s})}function _b(t){t.drag().pinch({percent:4}).wheel()}function wb(t){t.plugins.remove("wheel"),t.plugins.remove("pinch"),t.plugins.remove("drag")}function Pb(t){const{settings:e,view:i}=t;e.panZoom&&_b(i._viewport),i._viewport.on("pointerdown",Eb,t).on("pointerup",Tb,t).on("pointerup",xb,t).on("rightup",bb,t).on("pointerupoutside",Tb,t).on("pointermove",Ab,t).on("moved",mb,i).on("zoomed",mb,i);const s=Ib(t),r=(t=>{const{view:e,interaction:i}=t,s=(s,r)=>{e.viewportInFocus&&("Alt"===s.key&&"keyup"===r&&i.preventFocusoutOnAltKeyup&&s.preventDefault(),i.shiftKey=s.shiftKey,i.ctrlKey=s.ctrlKey,i.altKey=s.altKey,i.metaKey=s.metaKey,t.emit(r,{key:s.key,lowerCaseKey:s.key&&s.key.toLowerCase(),sourceEvent:s}))},r=t=>s(t,"keyup"),n=t=>s(t,"key");return document.addEventListener("keydown",n),document.addEventListener("keyup",r),()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",r)}})(t);return t.on("mousemove",gb,t),()=>{e.panZoom&&wb(i._viewport),i._viewport.destroyed||i._viewport.off("pointerdown",Eb).off("pointerup",Tb).off("pointerup",xb).off("rightup",bb).off("pointerupoutside",Tb).off("pointermove",Ab).off("moved",mb).off("zoomed",mb),s?.(),r?.(),t.off("mousemove",gb)}}function Eb(t){this.interaction._dragStart={x:t.data.global.x,y:t.data.global.y};const e=t.data.getLocalPosition(this.view._viewport);this.emit("drag-start",{position:this.interaction.cursor,sourceEvent:t,screenPos:[e.x,e.y]})}function Tb(t){this.view.resume("drag");const e=t.data.getLocalPosition(this.view._viewport);this.emit("drag-end",{position:this.interaction.cursor,sourceEvent:t,screenPos:[e.x,e.y]}),this.interaction.isDragging=!1,this.interaction.dragOffset=null}function Ab(t){const{srcElement:e}=t?.data?.originalEvent||{};if(!e)return;if(!(e===this.view._renderer.view))return;const i=t.data.getLocalPosition(this.view._viewport);let s=[i.x/ox,i.y/ox];const r=t.target&&t.target._nodeId;if(this.interaction.cursor=s,this.interaction.isDragging){const e=[i.x,i.y];this.emit("drag-move",{position:this.interaction.cursor,screenPos:e,sourceEvent:t})}this.emit("mousemove",{sourceEvent:t,nodeId:r,position:s})}const Ib=t=>{const e=document.querySelector(`#${t.fpeId} .fpe__plan`);if(!e)return()=>{};const i=()=>t.view.emit("focus",!1,t.view),s=()=>t.view.emit("focus",!0,t.view),r=()=>t.view.emit("focus","visible"===document.visibilityState,t.view),n=t=>(t.preventDefault(),!1);return e.addEventListener("mouseleave",i),e.addEventListener("mouseenter",s),document.addEventListener("visibilitychange",r),e.addEventListener("contextmenu",n,!1),()=>{e.removeEventListener("mouseleave",i),e.removeEventListener("mouseenter",s),document.removeEventListener("visibilitychange",r),e.removeEventListener("contextmenu",n,!1)}};function Sb({floorPlan:t,update:e=!1}){const{layout:i,view:s,settings:r}=t,{_renderer:n,_viewport:o}=s;let a=r.theme.background.color;4===a.length&&(a=a[0]+a[1]+a[1]+a[2]+a[2]+a[3]+a[3]),n.background.color=new $x(a).toNumber();const l=s.gfxLayers.scene;zx(l);let h={ctx:l};e||(s.styleCache={});for(let u of i.spaces)lb(u,t,h);for(let u of i.elements)lb(u,t,h);for(let u of i.annotations)lb(u,t,h);for(let u of i.spatialGraph.edges)lb(u,t,h);t.computed.wallContours.length&&function(t,e){const{ctx:i,style:s}=e,{wallContours:r}=t.computed,n="wallContours",o=r.map(t=>({type:"curve:polygonWithHoles",polygons:t}));let a=i.getChildByName(n);a?zx(a):(a=new Og,a.name=n);const l=Rl("element:wall");a.zIndex=l||0;const h=Xl({style:s,settings:t.settings,elementType:"element:wall"}),u=new ay;for(const c of o)Zx({shape:c,gfx:u,style:h});a.addChild(u),i.addChild(a)}(t,h),Cb(t,!0),s.emit("scene-rendered",{update:e}),s.viewportNeedsUpdate=!0,e&&(r.panZoom?_b(o):wb(o)),s.viewportPaused&&s.startAnimationLoop()}function Cb(t,e=!1){const{view:i,layout:s,settings:r}=t,n=t.addLayer({id:"fpe-room-stamp",baseLayer:"annotation"});e?(zx(n.container),s.spaces.forEach(t=>ub(t,n.container,i.zoom,r))):n.container.children.forEach(t=>{let e=s.spaces.find(e=>e.id===t.name);cb(t,i.zoom,e)})}function Mb(t){const{shapeLayers:e}=t.settings;for(const i in e){const s=e[i];t.addLayer({id:i}).addGraphic({shapes:s})}}Ep.add(jf),Ep.add(Wy),Ep.add(sv),Ep.add(xv),Ep.add(_v);class Ob extends nx{}const Nb=(t,e,i)=>{const s=t.getChildByName(e);if(s)return zx(s),s;{const s=new Og;return s.sortableChildren=!0,s.zIndex=i,s.name=e,t.addChild(s),s}},Lb={top:0,left:0,center:.5,right:1,bottom:1};class Rb{constructor(){this.methods={},this.add=(t,e,i)=>{this.methods[t]={fn:e,ctx:i}},this.remove=t=>{delete this.methods[t]}}}class kb extends hx.TinyEmitter{constructor(t,e,i){super(),this.windowPos=[0,0],this.zoom=1,this.client=[0,0],this.layers=/* @__PURE__ */new Map,this.viewbox={min:[0,0],max:[0,0]},this.styleCache={},this.viewportNeedsUpdate=!1,this.viewportPaused=!1,this.viewportInFocus=!1,this.wallNodesToUpdate=[],this.wallNodeUpdateInProgress=!1,this.gfxNodes={},this._canvasMargin={x:0,y:0},this.ticker=new Rb,this._oldTime=Date.now(),this.parentEl=i;const s=this.parentEl.querySelector(".fpe__canvas");let r=this.parentEl.clientWidth,n=this.parentEl.clientHeight;this._settings=e;const o=window.devicePixelRatio||1;let a=e.theme.background.color;const l="transparent"===a;4===a.length&&(a=a[0]+a[1]+a[1]+a[2]+a[2]+a[3]+a[3]),this._renderer=function(t){for(const e of hg)if(e.test(t))return new e(t);throw new Error("Unable to auto-detect a suitable renderer.")}({width:r,height:n,view:s,antialias:!0,hello:!1,backgroundAlpha:l?0:1,autoDensity:!0,resolution:o,powerPreference:"high-performance",preserveDrawingBuffer:!0,backgroundColor:l?new $x(a).toNumber():void 0}),this.parentEl.appendChild(this._renderer.view),4===a.length&&(a=a[0]+a[1]+a[1]+a[2]+a[2]+a[3]+a[3]),l||(this._renderer.background.color=new $x(a).toNumber()),this._stage=new Og,this._stage.sortableChildren=!0,this._viewport=new Ob({screenWidth:r,screenHeight:n,worldWidth:r,worldHeight:n,events:this._renderer.events,noTicker:!0,passiveWheel:!1}),ag?.system&&ag.system.stop(),this.startAnimationLoop(),this.watchResize(),this._stage.addChild(this._viewport),this.on("focus",t=>{t&&this.viewportPaused?this.startAnimationLoop():t||this.stopAnimationLoop(),this.viewportInFocus=t}),this.gfxLayers=Bb(this._viewport),tb(this,t)}draw(){if(!this._viewport||this._viewport?.destroyed)return;const t=Date.now();let e=t-this._oldTime;this._oldTime=t,e<0&&(e=0),e>1e3&&(e=1e3);let i=Object.keys(this.ticker.methods).length;(this.viewportNeedsUpdate||i)&&(this.ticker?.methods&&Object.values(this.ticker.methods).forEach(({fn:t,ctx:i})=>{"function"==typeof t&&(i?t.call(i,e):t(e))}),this._viewport.update(e),this._renderer.render(this._stage)),this.viewportPaused||requestAnimationFrame(()=>this.draw()),this.viewportNeedsUpdate=!1}startAnimationLoop(){this._oldTime=Date.now(),this.viewportNeedsUpdate=!0,this.viewportPaused=!1,requestAnimationFrame(()=>this.draw())}stopAnimationLoop(){this.viewportPaused=!0}updateView(){if(!this.parentEl.clientWidth||!this.parentEl.clientHeight)return;const t=this._viewport,e=this._renderer,i=ox,s=t.screenWidth,r=t.screenHeight,n=this.parentEl.clientWidth-this._canvasMargin.x,o=this.parentEl.clientHeight-this._canvasMargin.y;e.resize(n,o),t.resize(n,o);const a=s-n,l=r-o,h=this._settings.preserveViewbox,[u=.5,c=.5]=h.split("-").map(t=>Lb[t]),d=u*a,p=c*l;t.position.set(t.x-d,t.y-p),t.plugins.get("clamp-zoom")||t.clampZoom({minHeight:this._settings.zoomRange[0]*i,maxHeight:this._settings.zoomRange[1]*i}),e.render(this._stage);let f=t.left,m=t.top,g=t.worldScreenWidth,y=t.worldScreenHeight;this.viewbox={min:[f/i,m/i],max:[(f+g)/i,(m+y)/i]},this.client=[t.screenWidth,t.screenHeight]}async watchResize(){this._canvasMargin.x=this.parentEl.clientWidth-this._viewport.screenWidth,this._canvasMargin.y=this.parentEl.clientHeight-this._viewport.screenHeight,this._resizeObserver=new ResizeObserver(()=>{this.updateView(),this.emit("resize-canvas",this.viewbox)}),this._resizeObserver.observe(this.parentEl)}get gfxNodeCount(){return Object.keys(this.gfxNodes).length}reset(){this.styleCache={},this.gfxNodes={},this.gfxLayers=Bb(this._viewport)}pause(t="drag"){this._viewport.plugins.pause(t)}resume(t="drag"){this._viewport.plugins.resume(t)}destroy(){this.stopAnimationLoop(),this._resizeObserver?.disconnect(),this._viewport?.destroy(),this._renderer?.destroy(!0)}}const Bb=t=>{t.sortableChildren=!0;return{base:Nb(t,"base",0),scene:Nb(t,"scene",1),preview:Nb(t,"preview",2),annotation:Nb(t,"annotation",3),helper:Nb(t,"helper",4)}};function Fb(t,e,i){e=e||this;const{view:s,settings:r}=e,n=s.gfxNodes[t.id];if(n&&!n.destroyed){if("layout:space"===t.type){const e=s.layers.get("fpe-room-stamp");e&&ub(t,e.container,s.zoom,r)}lb(t,e,{ctx:n.parent,container:n,...i}),s.viewportNeedsUpdate=!0,s.viewportPaused&&s.startAnimationLoop()}}class Db{constructor({shapes:t=[],position:e=[0,0],alpha:i=1,scale:s=1,clearLayer:r=!1,interactive:n=!1,id:o,isHandler:a=!1,scaleOnZoom:l=!1,updatePositionOnDrag:h=!1,baseLayer:u,container:c,floorPlan:d}){if(this.shapes=t,this.gfxScale=s,this.scaleOnZoom=l,this.container=c,this.floorPlan=d,!this.container)return;r&&zx(this.container);let p=new ay;this.gfx=p,p.alpha=i;const f=Math.min(1/this.floorPlan.view.zoom)*this.gfxScale;e&&(p.x=e[0]*ox,p.y=e[1]*ox),p.eventMode=n?"static":"none",p._nodeId=o,a&&(p._isHandler=!0),h&&this.on("drag",this.doUpdatePositionOnDrag,this),f&&l&&(p.scale.x=p.scale.y=f),u.addChild(this.container),this.container.addChild(p),t.forEach(t=>Zx({shape:t,settings:this.floorPlan.settings,gfx:p})),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}set({position:t,rotation:e,style:i,shapes:s}={}){const r=Math.min(1/this.floorPlan.view.zoom)*this.gfxScale,n=this.gfx;if(function(t,{position:e,rotation:i}){e&&(t.x=e[0]*ox,t.y=e[1]*ox),i&&(t.rotation=-Math.PI/180*i)}(n,{position:t,rotation:e}),s&&(this.shapes=s,n.clear(),zx(n),s.forEach(t=>Zx({shape:t,settings:this.floorPlan.settings,gfx:n}))),r&&this.scaleOnZoom&&(n.scale.x=n.scale.y=r),i){const t=Kx(i);i.fill&&(n.geometry.graphicsData[0].fillStyle.color=Dl(i.fill)),n.geometry.graphicsData[0].lineStyle.color=Number(t.color),n.geometry.graphicsData[0].lineStyle.width=t.width,n.geometry.graphicsData[0].lineStyle.native=t.native,n.geometry.invalidate()}this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}doUpdatePositionOnDrag({position:t}){this.set({position:t})}on(t,e,i){return this.gfx.eventMode="static","drag"===t?this.addDragEvent(e,i):this.gfx.on(t,e,i),this}off(t,e){return"drag"===t?this.removeDragEvent():this.gfx.off(t,e),this}destroy(){this.off("drag"),this.gfx.destroy(),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}addDragEvent(t,e){function i(){this.floorPlan.interaction.isDragging=!1,this.floorPlan.view.resume("drag"),this.floorPlan.off("mousemove",t)}this.on("pointerdown",function(){this.floorPlan.interaction.isDragging=!0,this.floorPlan.view.pause("drag"),this.floorPlan.on("mousemove",t,e)},this),this.on("pointerup",i,this),this.on("pointerupoutside",i,this),this.on("pointercancel",i,this)}removeDragEvent(){this.off("pointerdown"),this.off("pointerup"),this.off("pointerupoutside"),this.off("pointercancel")}}class Ub{constructor(t,e,i){this.graphics=/* @__PURE__ */new Set,this.container=new Og,this.id=i,this.baseLayer=t.view.gfxLayers[e]||t.view.gfxLayers.helper,this.floorPlan=t,this.baseLayer.addChild(this.container)}addGraphic(t){const e=new Db({...t,floorPlan:this.floorPlan,baseLayer:this.baseLayer,container:this.container});return this.graphics.add(e),e}findGraphic(t){return this.container.getChildByName(t)}deleteGraphic(t){this.graphics.delete(t),t.destroy()}clear(){zx(this.container),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}destroy(){this.container&&(this.floorPlan.view.layers.delete(this.id),this.container.destroy({children:!0,texture:!0,baseTexture:!0}),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop(),delete this.container,delete this.floorPlan)}}function Gb(t,{format:e,fileName:i,quality:s}={}){if("svg"===e)return;const r=new Image;r.src=t,r.onload=function(){const t=document.createElement("canvas");t.width=r.naturalWidth,t.height=r.naturalHeight;const n=t.getContext("2d");n.imageSmoothingEnabled=!1,n.drawImage(r,0,0),function(t,{format:e="png",fileName:i="floorplan",quality:s=.95}){let r="png"===e?"image/png":"image/jpeg";t.toBlob(function(t){!function({fileName:t,href:e,ext:i}){const s=document.createElement("a");Object.assign(s,{href:e,download:p(t,i),target:"_blank",rel:"noopener",style:"display:none;"}),document.body.appendChild(s),s.click(),document.body.removeChild(s)}({fileName:i,href:URL.createObjectURL(t),ext:e})},r,s)}(t,{format:e,fileName:i,quality:s})}}const Xb=nl,Wb=nl,Yb=rl,Hb=nl,$b=nl,jb=qa;class zb extends ux{constructor({floorPlan:t,helperId:e,mode:i="distance"}){super({floorPlan:t,helperId:e}),this.drawing=!1,this.polygonsOrPolylines=[],this.floorPlan=t,this.mode=i,this.floorPlan.on("mousemove",this.handlePointerMove,this),this.floorPlan.on("click",this.handlePointerDown,this),this.floorPlan.on("dblclick",this.handlePointerDown,this),this.floorPlan.on("update-settings",this.draw,this),this.startDrawing()}get isInAreaMode(){return"area"===this.mode}get isDrawing(){return this.drawing}set({mode:t}){this.mode=t,this.draw()}handlePointerMove(t){this.setSnapCursor(t)}handlePointerDown(t){this.setSnapCursor(t),this.drawPoint(t)}setSnapCursor({position:t}){this._snapCursor??=this.floorPlan.addHelper("snapCursor",{position:t});const{snapPoints:e,snapMargin:i}=this.floorPlan.computed;if(!e.length)return this._snapCursor.set({position:t}),void this.draw();const s=jl(t,e,i);this._snapCursor.isSnapping=!!s,this._snapCursor.set({position:s||t}),this.draw()}stopDrawing(){this.polygonsOrPolylines[this.polygonsOrPolylines.length-1].points.length>1&&this.drawing&&this.polygonDone()}cancelDrawing(){this.destroy()}startDrawing(){this.drawing=!0,this.polygonsOrPolylines.push({points:[],isClosed:!1,length:0,area:0,areaDisplay:"",lengthDisplay:"",contour:null,label:null,pointGraphics:[]})}removeLastPoint(){const t=this.polygonsOrPolylines[this.polygonsOrPolylines.length-1];if(t?.points.length>0){t.points.pop();const e=t.pointGraphics.pop();e&&this.layer.deleteGraphic(e),t.points.length<=1&&(t.contour&&(this.layer?.deleteGraphic(t.contour),t.contour=null),t.label&&(this.layer?.deleteGraphic(t.label),t.label=null)),0===t.points.length?(this.polygonsOrPolylines.pop(),this.drawing=!1):this.draw()}}polygonDone(){this.drawing=!1,this.emit("polygon-done",{}),this.draw()}drawPoint(t){this.drawing||this.startDrawing();const e=this.polygonsOrPolylines.length-1,i=this.polygonsOrPolylines[e],s=t.nodeId?.startsWith(`point/${e}/`);if(s||t.isDoubleClick){const s=t.nodeId===`point/${e}/0`;return"distance"===this.mode&&s&&(i.isClosed=!0),void this.polygonDone()}const{position:r}=this._snapCursor;i.points.push([...r]);const n=i.points.length-1,o=`point/${e}/${n}`;this.layer||(this.layer=this.floorPlan.addLayer());const a=this.layer.addGraphic({shapes:[{type:"curve:circle",position:[0,0],radius:.15,style:{fill:Hb,fillOpacity:.1}},{type:"curve:circle",position:[0,0],radius:.05,style:{stroke:$b,fill:jb,strokeWidth:1.5}}],position:r,scaleOnZoom:!0,id:o,isHandler:!0});i.pointGraphics[n]=a,a.on("drag",function(){this.updatePolygon(e,n,this.floorPlan.interaction.cursor),a.set({position:i.points[n]})},this)}updatePolygon(t,e,i){const s=i,{snapPoints:r,snapMargin:n}=this.floorPlan.computed,o=r.length&&jl(s,r,n);this.polygonsOrPolylines[t].points[e]=o||s,this.draw()}getLengthText(t){const{units:e}=this.floorPlan.settings;return c(t,e.system,e.lengthDecimals)}getAreaText(t){const{units:e}=this.floorPlan.settings;return d(t,e.system,e.areaDecimals)}reset(){this.drawing=!1,this.polygonsOrPolylines=[],this.floorPlan.removeHelper("snapCursor"),this._snapCursor=null,this.layer&&(this.layer.destroy(),this.layer=null)}draw(){this.polygonsOrPolylines.length&&(this.layer||(this.layer=this.floorPlan.addLayer()),this.polygonsOrPolylines.forEach((t,e)=>{if(!t.points.length)return;const i=this.drawing&&this._snapCursor&&e===this.polygonsOrPolylines.length-1?[...t.points,this._snapCursor.position]:t.points;if(i.length<2)return;t.length=function(t,e=!0){let i=0,s=e?t.length:t.length-1;for(var r=0;r<s;r++){let e=r,s=r<t.length-1?r+1:0;i+=ai(t[e],t[s])}return i}(i,t.isClosed),t.lengthDisplay=this.getLengthText(t.length);const s=i.length<2?0:180*yi(i[0],i[1])/Math.PI,r=i.map(t=>t.map(t=>Number(t.toFixed(10)))).slice(0,this.isInAreaMode?void 0:2),n=this.isInAreaMode?Ei([r]):[r[0][0]+(r[1][0]-r[0][0])/2,r[0][1]+(r[1][1]-r[0][1])/2];t.area=Math.abs(J(i)),t.areaDisplay=this.getAreaText(t.area);const o=this.isInAreaMode||t.isClosed?"curve:polygon":"curve:polyline",a={stroke:Yb,dash:!0,strokeWidth:"native"};let l=t.lengthDisplay,h=s;this.isInAreaMode&&(a.fill=Wb,a.fillOpacity=.04,l=t.areaDisplay,h=0);const u=[{type:o,points:i,style:a}],c={shapes:[{type:"text",text:l,position:[0,0],rotation:h,alignV:"bottom",fontSize:15,style:{fill:Xb}}],id:"text",position:n,scaleOnZoom:!0};t.contour?t.contour.set({shapes:u}):t.contour=this.layer.addGraphic({shapes:u}),t.label?t.label.set(c):t.label=this.layer.addGraphic(c);const d=this.isInAreaMode?{area:t.area}:{distance:t.length};this.emit("polygon-draw",d)}))}destroy(){this.reset(),this.floorPlan.off("mousemove",this.handlePointerMove),this.floorPlan.off("click",this.handlePointerDown),this.floorPlan.off("dblclick",this.handlePointerDown),this.floorPlan.off("update-settings",this.draw),super.destroy()}}class Vb extends ux{constructor({floorPlan:t,helperId:e,position:i}){super({floorPlan:t,helperId:e}),this.position=[0,0],this.floorPlan.on("mousemove",this.draw,this),this.isSnapping=!1,this.isEdge=!1,this.isError=!1,i&&(this.position=i)}draw(){if(this.floorPlan)if(this.layer||(this.layer=this.floorPlan.addLayer({id:"fpe-snap-cursor"})),this.cursor){let t=Ka;this.isError?t=al:this.isSnapping&&(t=nl);const e=this.isSnapping?2:1.5;this.cursor.set({position:this.position,style:{stroke:t,strokeWidth:e}})}else this.cursor=this.layer.addGraphic({shapes:[{type:"curve:circle",position:[0,0],radius:.06,style:{stroke:nl,strokeWidth:1.5}}],position:this.position,scaleOnZoom:!0})}set({position:t,isSnapping:e,isEdge:i,isError:s}){this.position=t,this.isSnapping=e,this.isEdge=i,this.isError=s,this.draw()}snapState(){return this.isSnapping?this.isEdge?"edge":"point":""}destroy(){this.floorPlan?.off("mousemove",this.draw),this.layer&&this.layer.destroy(),this.layer=void 0,this.cursor=null,super.destroy()}}function qb(t,e){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: node ID change, type ${t.type}, previous ID ${e}`),this.drawNodeUpdate(t.id))}function Jb(t,e){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: node property change, type ${t.type}, property name ${e}`),this.drawNodeUpdate(t.id))}function Kb(t){this.preventUpdateOnSpaceGraphEvent||dl.debug(`${t.id}: vertex create`)}function Zb(t){this.preventUpdateOnSpaceGraphEvent||dl.debug(`${t.id}: vertex delete`)}function Qb(t){if(!this.preventUpdateOnSpaceGraphEvent){dl.debug(`${t.id}: vertex set position`);for(let e of t.edges)this.drawNodeUpdate(e.id)}}function t_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: edge create`),this.drawNodeUpdate(t.id))}function e_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: edge delete`),this.drawNodeUpdate(t.id))}function i_(t,e){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: edge set vertices`),this.drawNodeUpdate(t.id))}function s_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: space create`),this.drawNodeUpdate(t.id))}function r_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: space delete`),this.drawNodeUpdate(t.id))}function n_(t,e){this.preventUpdateOnSpaceGraphEvent||dl.debug(`${t.id}: space split into ${e[0].id} and ${e[1].id}`)}function o_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: space attributes change`),this.drawNodeUpdate(t.id))}function a_(t){this.preventUpdateOnSpaceGraphEvent||"layout:space"!==t.type||(dl.debug(`${t.id}: custom attributes change`),this.drawNodeUpdate(t.id))}function l_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: element create, type ${t.type}`),this.drawNodeUpdate(t.id))}function h_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: element delete, type ${t.type}`),this.drawNodeUpdate(t.id))}function u_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: element transform change, type ${t.type}`),this.drawNodeUpdate(t.id))}function c_(t){if(!this.preventUpdateOnSpaceGraphEvent)if(dl.debug(`${t.id}: element parameters change, type ${t.type}`),"element:wall"===t.type){let e=t.getAdjacentElementsByVertex().flat();if(this.view.wallNodesToUpdate.push(t.id,...e.map(t=>t.id)),this.view.wallNodeUpdateInProgress)return;this.view.wallNodeUpdateInProgress=!0,setTimeout(()=>{const t=new Set(this.view.wallNodesToUpdate);Pa(this.layout);for(const e of t)this.drawNodeUpdate(e);this.view.wallNodeUpdateInProgress=!1,this.view.wallNodesToUpdate=[]})}else kr(t),this.drawNodeUpdate(t.id)}function d_(t){this.preventUpdateOnSpaceGraphEvent||queueMicrotask(()=>this.drawNodeUpdate(t.id))}function p_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: annotation change, type ${t.type}`),this.drawNodeUpdate(t.id))}function f_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: geometry profile update`),this.drawNodeUpdate(t.id))}function m_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: geometry update`),["element:boundaryWall","element:generic"].includes(t.type)&&this.drawNodeUpdate(t.id))}function g_(t){const e=t.addLayer({id:"fpe-grid-lines",baseLayer:"base"});let i;function s(t,e,s=!1){const r=ox;if(!t)return;let n;if(n=e.view.zoom>2?.1:e.view.zoom>.25?1:(e.view.zoom,10),!s&&n===i)return;if(zx(t),!e.settings.theme.background.showGrid)return;const o=new ay;let a=Dl(il);o.lineStyle({width:1,color:a,native:!0});for(let i=-100;i<100;i+=n)Math.round(100*i)/100==0?o.lineStyle({width:2,color:a,native:!0}):(Math.round(100*i)/100%10==0||Math.round(100*i),o.lineStyle({width:1,color:a,native:!0})),o.moveTo(-1e4,i*r),o.lineTo(1e4,i*r),o.moveTo(i*r,-1e4),o.lineTo(i*r,1e4);t.addChild(o),i=n}return s(e?.container,t),{update:i=>s(e.container,t,i)}}function y_(t,e="Floor plan engine couldn't load properly on this page. For technical details check the browser console."){const i=t.querySelector(".fpe-err")??function(t){const e=document.createElement("div"),i=document.createElement("div"),s=document.createElement("div"),r=document.createElement("div");return e.classList.add("fpe-err"),i.classList.add("fpe-err__box"),s.classList.add("fpe-err__title"),r.classList.add("fpe-err__msg"),t.append(e),e.append(i),i.append(s),i.append(r),s.textContent="Something went wrong",t.append(e),t}(t);i.querySelector(".fpe-err__msg").textContent=e}const v_={lastSceneClick:[0,0],cursor:[0,0],cursorTarget:null,isDragging:!1,altKey:!1,shiftKey:!1,metaKey:!1,ctrlKey:!1,dragOffset:null,cursorAction:"none",isPanning:!1,lastClick:{time:null,position:{x:0,y:0}},_dragStart:{x:0,y:0},preventFocusoutOnAltKeyup:!1};class x_ extends Ml{constructor({container:t,options:e={}}={}){let i;super({options:e}),this.interaction=v_,this.availableHelpers={cursorCoordinates:cx,scaleBar:dx},this.helper={},this.preventUpdateOnSpaceGraphEvent=!1,this.#t=ll.theme.fontFamily,i=t instanceof Element?t:document.body,this.mountFloorPlan(i),this.availableHelpers.polygonHelper=zb,this.availableHelpers.snapCursor=Vb,this.on("space-api-floor-error",(t,e)=>{y_(this.fpeNode,e)}),this.on("space-api-floor-loaded",()=>{!function(t){t.querySelector(".fpe-err")?.remove()}(this.fpeNode)})}#t;#e;prevent(t){t.preventDefault()}on(t,e,i){return this._emitter.on(t,e,i),this}once(t,e,i){return this._emitter.once(t,e,i),this}off(t,e,i){return this._emitter.off(t,e),this}emit(t,...e){return this._emitter.emit(t,...e),this}handleDrop(t){t.preventDefault(),t.stopPropagation();const e=[t.offsetX,t.offsetY],i=this.getPlanPosition(e);this.interaction.cursor=[...i];const{spaces:s}=this.getResourcesFromPosition(i),r=s[0]?.slabs.find(t=>"element:floor"===t.type),n=r?.parameters.elevation||0;this.emit("drop",{position:i,sourceEvent:t,verticalPos:n,screenPos:e})}set(t){super.set(t),this.view&&(Sb({floorPlan:this,update:!0}),Mb(this),g_(this))}drawNodePreview(t,e,i,s){lb(e?.elementsById[t]||e?.spacesById[t]||e?.spatialGraph.edgesById[t],this,{preview:!0,style:s,ctx:i.container})}drawNodeUpdate(t,e){if(!this.layout)return;let i=this.layout?.elementsById[t]||this.layout?.spacesById[t]||this.layout?.annotationsById[t]||this.layout?.spatialGraph.edgesById[t];if(i)if(this.view.gfxNodes[t]&&!this.view.gfxNodes[t].destroyed)Fb(i,this,{style:e});else{let t=this.view.gfxLayers.scene;"parent"in i&&this.view.gfxNodes[i.parent?.id]&&(t=this.view.gfxNodes[i.parent.id]),lb(i,this,{ctx:t,style:e})}else!function(t,e){const i=e.view.gfxNodes[t];i&&(i.parent.removeChild(i),i.destroy({children:!0})),delete e.view.gfxNodes[t],delete e.view.styleCache[t],hb(t,e.getLayer("fpe-room-stamp").container),e.view.viewportNeedsUpdate=!0,e.view.viewportPaused&&e.view.startAnimationLoop()}(t,this);if(i&&"getEdges"in i)for(const s of i.getEdges())this.drawNodeUpdate(s.id,e)}drawResourceUpdate({resourceId:t}){let e=this.loader.resources.nodes.get(t);for(let i of e)Fb(i,this,{})}mountFloorPlan(t){const e=t.querySelector(".fpe");e&&e.remove();const i=document.createElement("div");i.id=this.fpeId,i.classList.add("fpe"),t.appendChild(i);const s=document.createElement("div");s.classList.add("fpe__plan");const r=document.createElement("canvas");r.setAttribute("alt","fpe-canvas"),r.classList.add("fpe__canvas"),i.appendChild(s),s.appendChild(r),this.fpeNode=i;try{i.style.setProperty("--fpe-font-family",this.settings.theme.fontFamily)}catch(n){console.warn("Failed to set font-family",n)}this.view=new kb(this.loader,this.settings,s),this.loader.on("resource-loaded",this.drawResourceUpdate,this),this.loader.on("spaces-loaded",this.initDrawing,this),r.addEventListener("drop",this.handleDrop.bind(this)),r.addEventListener("gesturestart",this.prevent),r.addEventListener("gesturechange",this.prevent),r.addEventListener("gestureend",this.prevent),r.addEventListener("dragover",this.prevent),this.settings.destroyOnDomRemove&&function(t,e,i){const s=new MutationObserver(()=>{(function t(i){return i.parentNode!==e&&(null===i.parentNode||t(i.parentNode))})(t)&&(s.disconnect(),i())});s.observe(e,{childList:!0,subtree:!0})}(i,t,()=>this.destroy()),this.#e=Pb(this),this.view.on("scene-rendered",({update:t})=>{t||this.zoomExtents(1,0)}),this.view.on("zoom",()=>{this.view.layers.forEach(t=>{t.graphics.forEach(t=>{t.scaleOnZoom&&!t.gfx.destroyed&&t.set()})}),Cb(this),g_(this)}),this.view&&g_(this),this.#i(this.settings.theme.fontFamily),this.on("update-settings",t=>{this.#i(t.theme.fontFamily)}),this.generateUi()}initDrawing(){!this.loader.initialLoading&&this.view.gfxLayers?.scene&&zx(this.view.gfxLayers.scene),Sb({floorPlan:this}),Mb(this),this.initDrawingEvents()}initDrawingEvents(){this.spaceGraph&&(this.spaceGraph.on("node-id-change",qb,this),this.spaceGraph.on("node-property-change",Jb,this),this.spaceGraph.on("node-custom-attributes-change",a_,this),this.spaceGraph.on("vertex-create",Kb,this),this.spaceGraph.on("vertex-delete",Zb,this),this.spaceGraph.on("vertex-set-position",Qb,this),this.spaceGraph.on("edge-create",t_,this),this.spaceGraph.on("edge-delete",e_,this),this.spaceGraph.on("edge-set-vertices",i_,this),this.spaceGraph.on("space-create",s_,this),this.spaceGraph.on("space-delete",r_,this),this.spaceGraph.on("space-split",n_,this),this.spaceGraph.on("space-attributes-change",o_,this),this.spaceGraph.on("element-create",l_,this),this.spaceGraph.on("element-delete",h_,this),this.spaceGraph.on("element-transform-change",u_,this),this.spaceGraph.on("element-parameters-change",c_,this),this.spaceGraph.on("element-edges-change",d_,this),this.spaceGraph.on("geometry-profile-update",f_,this),this.spaceGraph.on("geometry-update",m_,this),this.spaceGraph.on("annotation-transform-change",p_,this),this.spaceGraph.on("annotation-parameters-change",p_,this))}freeDrawingEvents(){this.spaceGraph&&(this.spaceGraph.off("node-id-change",qb),this.spaceGraph.off("node-property-change",Jb),this.spaceGraph.off("vertex-create",Kb),this.spaceGraph.off("vertex-delete",Zb),this.spaceGraph.off("vertex-set-position",Qb),this.spaceGraph.off("edge-create",t_),this.spaceGraph.off("edge-delete",e_),this.spaceGraph.off("edge-set-vertices",i_),this.spaceGraph.off("space-create",s_),this.spaceGraph.off("space-delete",r_),this.spaceGraph.off("space-split",n_),this.spaceGraph.off("space-attributes-change",o_),this.spaceGraph.off("element-create",l_),this.spaceGraph.off("element-delete",h_),this.spaceGraph.off("element-transform-change",u_),this.spaceGraph.off("element-parameters-change",c_),this.spaceGraph.off("geometry-profile-update",f_),this.spaceGraph.off("geometry-update",m_),this.spaceGraph.off("annotation-transform-change",p_),this.spaceGraph.off("annotation-parameters-change",p_))}generateUi(){this.settings.ui.coordinates?this.addHelper("cursorCoordinates",{parentEl:this.fpeNode}):this.helper.cursorCoordinates&&this.removeHelper("cursorCoordinates"),this.settings.ui.scale?this.addHelper("scaleBar",{parentEl:this.fpeNode}):this.helper.scaleBar&&this.removeHelper("scaleBar")}getZoomExtentsBoundingBox(t,e,i,s,r,n,o){return function({layoutBoundingBox:t,rectLeft:e,rectTop:i,rectRight:s,rectBottom:r,viewportWidth:n,viewportHeight:o}){if([e,i,s,r].some(t=>t>0)&&n&&o){const a=s-e,l=r-i,h=function(t,e,i){const{min:s,max:r}=t;let n=s[0],o=s[1],a=r[0],l=r[1],h=a-n,u=l-o;const c=e/i;if(h/u>c){const t=u;u=h/c;const e=(t-u)/2;o+=e,l-=e}else{const t=h;h=u*c;const e=(t-h)/2;n+=e,a-=e}return{min:[n,o],max:[a,l]}}(t,a,l);let{min:u,max:c}=h,d=u[0],p=u[1],f=c[0]-d,m=c[1]-p;return f*=n/a,m*=o/l,d-=e/n*f,p-=i/o*m,{min:[d,p],max:[d+f,p+m]}}return t}({layoutBoundingBox:t,rectLeft:e,rectTop:i,rectRight:s,rectBottom:r,viewportWidth:n,viewportHeight:o})}zoomExtents(t=1,e=!1,i=null){return function({margin:t=0,animate:e,floorPlan:i,boundingBox:s}){return i.view.gfxLayers.scene?pb(s?{bb:s,animate:e,view:i.view}:{bb:i.getBoundingBox(t),animate:e,view:i.view}):Promise.resolve(!1)}({margin:t,animate:e,floorPlan:this,boundingBox:i})}zoomToElement(t,e=1,i){let s;if("string"==typeof t){const e=t;s=this.layout.elementsById[e]||this.layout.spacesById[e]||this.layout.spatialGraph.edgesById[e]||null}else s=t;if(!s)return Promise.resolve(!0);const{min:[r,n,o],max:[a,l,h]}=s.getAxisAlignedBoundingBox();return pb({bb:{min:[r-e,o-e],max:[a+e,h+e]},animate:i,view:this.view})}setZoom(t,e=!0){return pb({bb:t,animate:e,view:this.view})}zoomByFactor(t,e=!0){if(!Number.isFinite(t)||t<=0)return Promise.reject("factor is not a positive number");let{min:i,max:s}=this.view.viewbox,r=i[0],n=i[1],o=s[0]-r,a=s[1]-n;r-=(o/t-o)/2,n-=(a/t-a)/2;const l=r+o,h=n+a;return this.setZoom({min:[r,n],max:[l,h]},e)}addInfoWindow(t={}){return new mx({...t,floorPlan:this})}addHtmlMarker(t={}){return new gx({...t,floorPlan:this})}addMarker({position:t=[0,0],color:e="#669cff",size:i=40}={}){return new jx({position:t,color:e,size:i,floorPlan:this})}getPlanPosition(t){if(!this.view._viewport||this.view._viewport.destroyed)throw Error("No viewport present");const e=this.view._viewport.toWorld(t[0],t[1]);return[e.x/ox,e.y/ox]}getScreenPosition(t){if(!this.view._viewport||this.view._viewport.destroyed)throw Error("No viewport present");const e=t.map(t=>t*ox),i=this.view._viewport.toScreen(e[0],e[1]);return[i.x,i.y]}addLayer({id:t,baseLayer:e}={}){if(!this.view?.layers)return;if(t||(t=O()),this.view.layers.has(t)){const e=this.view.layers.get(t);if(e?.container)return e}const i=new Ub(this,e,t);return this.view.layers.set(t,i),i}getLayer(t){return this.view.layers.get(t)}addPlanGraphic(){return new Ub(this)}addHelper(t,e={}){let i=e?.helperId;return i||(i="string"==typeof t?t:O()),this.helper[i]&&this.removeHelper(i),"string"==typeof t?this.availableHelpers[t]?this.helper[i]=new this.availableHelpers[t]({floorPlan:this,helperId:i,...e}):dl.warn(`No helper registered for: ${t}`):this.helper[i]=new t({floorPlan:this,helperId:i,...e}),this.helper[i]}removeHelper(t){this.helper[t]?.destroy?.(),delete this.helper[t]}async exportImage({format:t="png",fileName:e,quality:i=90,output:s="base64",maxWidth:r,download:n=!1}={}){let o={format:t,quality:i};n&&(o.format="png");const a=document.querySelector("#"+this.fpeId+" canvas"),l=await function(t,{format:e="png",quality:i=.95}){return new Promise(s=>{let r;r="jpg"===e?t.toDataURL("image/jpeg",i):t.toDataURL(),s(r)})}(a,o).catch(t=>t);if(!n)return l;Gb(l,{format:t,fileName:e,quality:i})}#i(t){if(t!==this.#t){this.#t=t;try{this.fpeNode.style.setProperty("--fpe-font-family",t)}catch(e){console.warn("Failed to set font-family",e)}}}destroy(){this.#e?.(),this.view.destroy(),this.loader.reset(),this.freeDrawingEvents(),delete this.layout,delete this.utils,this.fpeNode&&this.fpeNode.remove(),delete this.fpeNode}}export{x_ as FloorPlanEngine,cl as setApiUrls};
1
+ const t=3.28084,e=(t,e=1/64)=>{const i=1/e;return Math.round(t*i)/i};function i(t){return Math.sign(t)*Math.floor(Math.abs(t))}function r(t,e){return typeof t<"u"&&null!==t&&Number.isFinite(t)&&t>=-e&&t<=e}const s=" ",n="m",o="′",a="″",l="m²",h="ft²";function u(t,e=.5,i=1/64){return!(t%e)||e<=i?[t/e,1/e]:u(t,e/2)}const c=(r=0,l="metric",h=3)=>{if("imperial"===l){const{feet:n,inches:l,fraction:h,isNegative:c}=function(r){const s=r*t,n=Math.abs(s),o=e(n%1*12);return{feet:i(n),inches:i(o),fraction:e(o%1),isNegative:Math.sign(r)<0}}(r);let d="";if(h>0){const[t,i]=u(e(h));d=`${s}${t}/${i}`}return`${c?"-":""}${n}${o}${s}${l}${d}${a}`}const c=Math.pow(10,h);return`${Math.round(r*c)/c}${s}${n}`},d=(e=0,i="metric",r=0,n=!0)=>{let o="",a="";const u=Math.pow(10,r);if("imperial"===i){const i=function(e){return e*t*t}(e);o=""+Math.round(i*u)/u,a=`${s}${h}`}else o=""+Math.round(e*u)/u,a=`${s}${l}`;return n&&(o+=a),o};["US","USA","United States","U.S","U.S.A","England","UK","U.K","United Kingdom","Liberia","Myanmar"].map(t=>t.toLowerCase());const p=(t,e)=>{const i=`.${e}`;return(t=>t.replace(/[/\\]/g,"_"))((t=>t.replace(/[.,\s]/g,"_"))(t.endsWith(i)?t.split(i)[0]:t))+i};function f(t){const e=function(t){return"#"===t.slice(0,1)&&(t=t.slice(1)),t}(t);return 3===e.length?`#${e.split("").map(t=>t+t).join("")}`:t}function m(t){return t>=0&&t<=255}function g(t){const e=f(t),i={r:parseInt(e.substring(1,3),16),g:parseInt(e.substring(3,5),16),b:parseInt(e.substring(5,7),16)};if(function({r:t,g:e,b:i}){return m(t)&&m(e)&&m(i)}(i))return i;throw"invalid hex color input"}function y(t){return JSON.parse(JSON.stringify(t))}function v(...t){let e={};for(const i of t)if(i instanceof Array)e instanceof Array||(e=[]),e=[...e,...i];else if(i instanceof Object)for(const t of Object.entries(i)){const i=t[0];let r=t[1];r instanceof Object&&i in e&&(r=v(e[i],r)),e={...e,[i]:r}}return e}function x(){return typeof window<"u"&&typeof navigator<"u"&&typeof document<"u"}!x()||window.self===window.top||window.location.ancestorOrigins&&window.location.ancestorOrigins[0]||document.referrer,x()&&navigator.platform.toUpperCase().indexOf("MAC");var b={exports:{}};function _(){}_.prototype={on:function(t,e,i){var r=this.e||(this.e={});return(r[t]||(r[t]=[])).push({fn:e,ctx:i}),this},once:function(t,e,i){var r=this;function s(){r.off(t,s),e.apply(i,arguments)}return s._=e,this.on(t,s,i)},emit:function(t){for(var e=[].slice.call(arguments,1),i=((this.e||(this.e={}))[t]||[]).slice(),r=0,s=i.length;r<s;r++)i[r].fn.apply(i[r].ctx,e);return this},off:function(t,e){var i=this.e||(this.e={}),r=i[t],s=[];if(r&&e)for(var n=0,o=r.length;n<o;n++)r[n].fn!==e&&r[n].fn._!==e&&s.push(r[n]);return s.length?i[t]=s:delete i[t],this}},b.exports=_;var w=b.exports.TinyEmitter=_;const P=["info","warnings","errors"];class E extends w{constructor(t){super(),this.levels=P.slice(),this.info=this.log,t&&this.setLevels(t),this.levelStack=[]}setLevels(t){const e=this.levels.slice();if("string"==typeof t)switch(t){case"none":this.levels=[];break;case"all":this.levels=["debug","info","warnings","errors"];break;case"debug":this.levels=["debug"];break;case"info":this.levels=["info"];break;case"warnings":this.levels=["warnings"];break;case"errors":this.levels=["errors"];break;default:console.error(`Unknown setting '${t}'.`)}else this.levels=t.slice();return e}push(){this.levelStack.push(this.levels)}pushAndSetLevels(t){return this.push(),this.setLevels(t)}pop(){if(this.levelStack.length>0){const t=this.levelStack.pop();this.setLevels(t)}}debug(...t){this.levels.includes("debug")&&(console.debug(...t),this.emit("debug",...t))}log(...t){this.levels.includes("info")&&(console.log(...t),this.emit("info",...t))}warn(...t){this.levels.includes("warnings")&&(console.warn(...t),this.emit("warning",...t))}error(...t){this.levels.includes("errors")&&(console.error(...t),this.emit("error",...t))}}for(var T,A=[],I=0;I<256;++I)A.push((I+256).toString(16).slice(1));var S=new Uint8Array(16);function C(){if(!T&&!(T="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return T(S)}const M={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function O(t,e,i){if(M.randomUUID&&!t)return M.randomUUID();var r=(t=t||{}).random||(t.rng||C)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(t,e=0){return(A[t[e+0]]+A[t[e+1]]+A[t[e+2]]+A[t[e+3]]+"-"+A[t[e+4]]+A[t[e+5]]+"-"+A[t[e+6]]+A[t[e+7]]+"-"+A[t[e+8]]+A[t[e+9]]+"-"+A[t[e+10]]+A[t[e+11]]+A[t[e+12]]+A[t[e+13]]+A[t[e+14]]+A[t[e+15]]).toLowerCase()}(r)}const N=t=>{const e=[];for(const[i,r]of Object.entries(t))void 0!==r&&e.push(`${i}=${String(r)}`);return e.length?`?${e.join("&")}`:""};class L extends Error{code;data;constructor(t,e,i){super(t||"There was a problem. Please check your internet connection and try again."),this.name="SpaceApiError",this.stack=(new Error).stack,this.code=e,this.data=i}}let R="https://api.archilogic.com";function k(t){let e;if(t.secretAccessToken)e={type:"secret",secretAccessToken:t.secretAccessToken};else if(t.temporaryAccessToken||t.temporaryAccessTokenFunction)e={type:"temporary",temporaryAccessToken:t.temporaryAccessToken};else{if(!t.publishableAccessToken)throw new L("Programming error: token is not provided.",void 0,void 0);e={type:"publishable",publishableAccessToken:t.publishableAccessToken}}return t.sdkVersion&&(e.sdkVersion=t.sdkVersion),e}function B(t){return t.status>=200&&t.status<400?t:t.json().then(e=>{const i=e?.message||e?.error||e;switch(typeof i){case"string":return Promise.reject(new L(i,t.status,void 0));case"object":return Promise.reject(new L(i.message,t.status,i.data));default:return Promise.reject(new L(null,null,e))}})}async function F(t,e,i={},r){const s=new URL(R+e),n=function(t){const e=new Headers;switch(t.type){case"secret":e.set("authorization",`AL-Secret-Token ${t.secretAccessToken}`);break;case"temporary":e.set("authorization",`${t.temporaryAccessToken?.authorization}`)}return t.sdkVersion&&e.set("x-sdk-version",t.sdkVersion),e}(r);let o=!1;switch("publishable"===r.type&&s.searchParams.set("pubtoken",r.publishableAccessToken),t){case"GET":i&&"object"==typeof i&&Object.entries(i).forEach(([t,e])=>{void 0!==e&&s.searchParams.set(t,e.toString())});break;case"POST":case"PUT":case"PATCH":n.set("content-type","application/json"),o=!0;break;case"DELETE":break;default:return Promise.reject(new L("Programming error, unsupported method: "+t,void 0,void 0))}return fetch(s.toString(),{method:t,headers:n,body:o?JSON.stringify(i):void 0}).then(B,t=>{throw t}).then(t=>t.json()).catch(t=>Promise.reject(t))}class D{config;temporaryAccessTokenFunction;tempScopes=[{resource:"floor",action:"readPublic"},{resource:"floor",action:"readPrivate"},{resource:"floor",action:"queryPublic"},{resource:"floor",action:"queryPrivate"},{resource:"floor",action:"archive"},{resource:"customFields",action:"readPublic"},{resource:"customFields",action:"readPrivate"},{resource:"customFields",action:"write"}];temporaryAccessToken;temporaryAccessTokenPromise;durationSeconds=3600;constructor(t){this.config=k(t),(t.temporaryAccessToken||t.temporaryAccessTokenFunction)&&(this.temporaryAccessTokenFunction=t.temporaryAccessTokenFunction,this.temporaryAccessToken=t.temporaryAccessToken),t.temporaryAccessTokenScopes&&(this.tempScopes=t.temporaryAccessTokenScopes)}get isAccessTokenActive(){const t=/* @__PURE__ */(new Date).getTime()/1e3;return!!this.temporaryAccessToken&&this.temporaryAccessToken.expiresAt>t}async getTemporaryAccessToken(){if(this.isAccessTokenActive&&this.temporaryAccessToken)return this.temporaryAccessToken;this.temporaryAccessTokenPromise||(this.temporaryAccessTokenPromise=new Promise(async(t,e)=>{if(this.temporaryAccessTokenFunction&&(this.temporaryAccessToken=await this.temporaryAccessTokenFunction({scopes:this.tempScopes,durationSeconds:this.durationSeconds}),this.isAccessTokenActive&&t(this.temporaryAccessToken)),this.temporaryAccessToken){const t=/* @__PURE__ */new Date;t.setTime(1e3*this.temporaryAccessToken.expiresAt),e(new L(`Temporary access token expired at ${t.toString()}`,void 0,void 0))}else e(new L("Temporary access token not defined",void 0,void 0))}));try{return await this.temporaryAccessTokenPromise}catch(t){throw this.temporaryAccessTokenPromise=void 0,t}finally{this.isAccessTokenActive&&(this.temporaryAccessTokenPromise=void 0)}}async callSpaceAPI(t,e,i={},r=this.config){switch(r.type){case"secret":case"publishable":return F(t,e,i,r);case"temporary":{const s=await this.getTemporaryAccessToken();return F(t,e,i,{...r,temporaryAccessToken:s})}}}}class U{connection;constructor(t,e={}){this.connection=new D(t);for(const[i,r]of Object.entries(e))this[i]=r}async getTemporaryAccessToken(){return this.connection.getTemporaryAccessToken()}async createFloor(t){return this.connection.callSpaceAPI("POST","/v2/floor",t)}async duplicateFloor(t,e){const i=e.revisionId?`?revisionId=${e.revisionId}`:"";return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/duplicate${i}`)}async updateFloor(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/floor/${t}`,e)}async archiveFloor(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/archive`)}async unarchiveFloor(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/unarchive`)}async searchFloorsBasic(t){const{name:e,id:i,paginationInput:r,teamId:s}=t,n=((t,e,i,r)=>{const s={};return t&&(s.name={contains:`${t}`}),e&&(s.ids=[e]),r&&(s.team={id:{eq:r}}),{query:"query ($floorFilter: FloorFilter!, $paginationInput: PaginationInput) { getFloors(where: $floorFilter, paginationInput: $paginationInput) { floors { id name area createdAt updatedAt labels { name color } }, paginationInfo { currentPage limit offset totalCount totalPageCount} } }",variables:{floorFilter:s,paginationInput:i}}})(e,i,r,s);return this.connection.callSpaceAPI("POST","/graphql",n)}async searchFloorsAdvanced(t,e){const i=((t,e)=>({query:t,variables:{paginationInput:e}}))(t,e);return this.connection.callSpaceAPI("POST","/graphql",i)}async getFloorById(t,e=!1,i=!0,r=!1,s,n=!1){const o=N({includeAddress:r,includeRelations:i,includeCustomAttributes:n}),a=await this.connection.callSpaceAPI("GET",`/v2/floor/${t}${e?"/geo-json":""}${o}`);let l={};if(a.properties?.defaultLayoutId){const{layout:t,id:e,lastRevision:i,categories:r}=await this.getLayout(a.properties.defaultLayoutId,s);l={layout:{id:e,layout:t,lastRevision:i,categories:r}}}return{...a,...l}}async getFloorGeoJson(t,e){const i=N(e??{}),r=await this.connection.callSpaceAPI("GET",`/v2/floor/${t}/geo-json${i}`);let s;if(e?.includeAllElements){const t=r.features.find(t=>"Floor"===t.properties.resourceType);s=t?.properties.defaultLayoutId}else{s=r.properties.defaultLayoutId}if(s){const{layout:t,id:e,lastRevision:i,categories:n}=await this.getLayout(s);return{...r,layout:{id:e,layout:t,lastRevision:i,categories:n}}}return r}getFloorStatistics(t){return this.connection.callSpaceAPI("GET",`/v2/floor/${t}/statistics`)}queryFloors(t){return this.connection.callSpaceAPI("GET","/v2/floor",t)}async getAllFloors(t=!1,e=!1,i=!1,r,s){const n=t||i?1e3:1e4,o=await this.queryFloors({geometry:t,includeArchived:e,includeRelations:i,includeCustomAttributes:s,teamId:r,limit:n});let a=o.features||[];if(a.length<n)return o;for(;a?.length;)a=(await this.queryFloors({geometry:t,includeArchived:e,includeRelations:i,includeCustomAttributes:s,teamId:r,offset:o.features.length,limit:n})).features||[],o.features.push(...a);return o}getFloorplanImage(t,e){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/2d-image`,e)}getSceneStructure(t,e=!1){return this.connection.callSpaceAPI("GET",`/v2/floor/${t}/scene-structure`,{includeMetadata:e})}assignLabel(t,e){return this.connection.callSpaceAPI("PUT",`/v2/floor/${t}/label/${e}`)}removeLabel(t,e){return this.connection.callSpaceAPI("DELETE",`/v2/floor/${t}/label/${e}`)}getSpaceById(t,e=!1,i=!0){const r=`?includeRelations=${i}`;return this.connection.callSpaceAPI("GET",`/v2/space/${t}/${e?"geo-json":""}${r}`)}querySpaces(t){return this.connection.callSpaceAPI("GET","/v2/space",t)}async getAllSpacesByFloorId(t,e=!1,i,r){const s=1e3,n=await this.querySpaces({floorId:t,geometry:e,includeRelations:i,includeCustomAttributes:r,limit:s});let o=n.features||[];if(o.length<s)return n;for(;o?.length;)o=(await this.querySpaces({floorId:t,geometry:e,includeRelations:i,includeCustomAttributes:r,offset:n.features.length,limit:s})).features||[],n.features.push(...o);return n}getAssetById(t,e=!1,i=!0,r=!1){const s=N({includeRelations:i,includeCustomAttributes:r});return this.connection.callSpaceAPI("GET",`/v2/asset/${t}/${e?"geo-json":""}${s}`)}queryAssets(t){return this.connection.callSpaceAPI("GET","/v2/asset",t)}async getAllAssets(t){const{limit:e=1e4,...i}=t,r=await this.queryAssets({...i,limit:e});let s=r.features||[];if(s.length<e)return r;for(;s?.length;)s=(await this.queryAssets({...t,offset:(t.offset||0)+r.features.length,limit:e})).features||[],r.features.push(...s);return r}getAllAssetsByFloorId(t,e=!1,i,r){return this.getAllAssets({floorId:t,geometry:e,includeRelations:i,includeCustomAttributes:r})}getAllAssetsBySpaceId(t,e=!1,i,r){return this.getAllAssets({spaceId:t,geometry:e,includeRelations:i,includeCustomAttributes:r})}getCustomField(t,e,i){return this.connection.callSpaceAPI("GET",`/v2/${t}/${e}/custom-field/${i}`)}getAllCustomFields(t,e){return this.connection.callSpaceAPI("GET",`/v2/${t}/${e}/custom-field`)}setCustomField(t,e,i,r){return this.connection.callSpaceAPI("PUT",`/v2/${t}/${e}/custom-field/${i}`,r)}deleteCustomField(t,e,i){return this.connection.callSpaceAPI("DELETE",`/v2/${t}/${e}/custom-field/${i}`)}getLabel(t){return this.connection.callSpaceAPI("GET",`/v2/label/${t}`)}listLabels(){return this.connection.callSpaceAPI("GET","/v2/label/")}createOrUpdateLabel(t,e){return this.connection.callSpaceAPI("PUT",`/v2/label/${t}`,e)}deleteLabel(t){return this.connection.callSpaceAPI("DELETE",`/v2/label/${t}`)}getCustomAttributes(){return this.connection.callSpaceAPI("GET","/v2/custom-attributes")}getCustomAttribute(t,e){return this.connection.callSpaceAPI("GET",`/v2/${t.toLowerCase()}/custom-attributes/${e}`)}getCustomAttributesForResourceType(t){return this.connection.callSpaceAPI("GET",`/v2/${t.toLowerCase()}/custom-attributes`)}createCustomAttribute(t){const{resourceType:e,...i}=t;return this.connection.callSpaceAPI("POST",`/v2/${e.toLowerCase()}/custom-attributes`,i)}updateCustomAttribute(t){const{apiFieldName:e,resourceType:i,...r}=t;return this.connection.callSpaceAPI("PATCH",`/v2/${i.toLowerCase()}/custom-attributes/${e}`,r)}deleteCustomAttribute(t,e){return this.connection.callSpaceAPI("DELETE",`/v2/${t.toLowerCase()}/custom-attributes/${e}`)}getCustomAttributeValues(t,e){return this.connection.callSpaceAPI("GET",`/v2/${t.toLowerCase()}/${e}/custom-attributes`)}createCustomAttributeValue(t){const{apiFieldName:e,resourceId:i,resourceType:r,...s}=t;return this.connection.callSpaceAPI("POST",`/v2/${r.toLowerCase()}/${i}/custom-attributes/${e}`,s)}updateCustomAttributeValue(t){const{apiFieldName:e,resourceId:i,resourceType:r,...s}=t;return this.connection.callSpaceAPI("PATCH",`/v2/${r.toLowerCase()}/${i}/custom-attributes/${e}`,s)}deleteCustomAttributeValue(t,e,i){return this.connection.callSpaceAPI("DELETE",`/v2/${e.toLowerCase()}/${t}/custom-attributes/${i}`)}createLayout(t,e,i){return this.connection.callSpaceAPI("POST","/v2/layout",{floorId:t,layout:e,isDefault:i})}duplicateLayout(t,e){const i=N({revisionId:e});return this.connection.callSpaceAPI("POST",`/v2/layout/${t}/duplicate${i}`,{layoutId:t,revisionId:e})}getLayout(t,e){const i=N(e?{filter:e}:{});return this.connection.callSpaceAPI("GET",`/v2/layout/${t}${i}`)}getLayouts(t,e){const i=N({floorId:t,isDefault:e});return this.connection.callSpaceAPI("GET",`/v2/layout/${i}`)}updateLayout(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/layout/${t}`,e)}deleteLayout(t){return this.connection.callSpaceAPI("DELETE",`/v2/layout/${t}`)}createLayoutRevision(t,e){return this.connection.callSpaceAPI("POST",`/v2/layout/${t}/revisions`,e)}updateLayoutRevision(t,e,i){return this.connection.callSpaceAPI("PATCH",`/v2/layout/${t}/revisions/${e}`,i)}getLayoutRevisions(t,e){const i=N(e?{filter:e}:{});return this.connection.callSpaceAPI("GET",`/v2/layout/${t}/revisions${i}`)}getLayoutRevision(t,e){return this.connection.callSpaceAPI("GET",`/v2/layout/${t}/revisions/${e}`)}convertLanguageToQuery(t){return this.connection.callSpaceAPI("POST","/v2/language/graphql",t)}convertLanguageToAgentResponse(t){return this.connection.callSpaceAPI("POST","/v2/language/query-floors",t)}getDxf(t){return this.connection.callSpaceAPI("GET",`/v2/floor/${t}/dxf`)}getIfc(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/ifc`)}getGltf(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/gltf`)}getImdf(t){return this.connection.callSpaceAPI("POST",`/v2/floor/${t}/imdf`)}getImdfs(t){return this.connection.callSpaceAPI("POST","/v2/floor/imdf",t)}listExtensions(t){return this.connection.callSpaceAPI("GET","/v2/extensions",t)}createExtension(t){return this.connection.callSpaceAPI("POST","/v2/extensions",t)}updateExtension(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/extensions/${t}`,e)}deleteExtension(t){return this.connection.callSpaceAPI("DELETE",`/v2/extensions/${t}`)}listExtensionAccess(t){return this.connection.callSpaceAPI("GET",`/v2/extensions/${t}/access`)}grantExtensionAccess(t,e){return this.connection.callSpaceAPI("PUT",`/v2/extensions/${t}/access/${e}`)}revokeExtensionAccess(t,e){return this.connection.callSpaceAPI("DELETE",`/v2/extensions/${t}/access/${e}`)}listBuildings(){return this.connection.callSpaceAPI("GET","/v2/buildings")}createBuilding(t){return this.connection.callSpaceAPI("POST","/v2/buildings",t)}getBuildingById(t){return this.connection.callSpaceAPI("GET",`/v2/buildings/${t}`)}updateBuilding(t,e){return this.connection.callSpaceAPI("PATCH",`/v2/buildings/${t}`,e)}deleteBuilding(t){return this.connection.callSpaceAPI("DELETE",`/v2/buildings/${t}`)}}var G;(t=>{t.version="6.4.2.3",t.use_lines=!0;class e{m_Parent=null;m_polygon=[];m_Index=0;m_jointype=0;m_endtype=0;m_Children=[];IsOpen=!1;IsHoleNode(){for(var t=!0,e=this.m_Parent;null!==e;)t=!t,e=e.m_Parent;return t}ChildCount(){return this.m_Children.length}Contour(){return this.m_polygon}AddChild(t){var e=this.m_Children.length;this.m_Children.push(t),t.m_Parent=this,t.m_Index=e}GetNext(){return this.m_Children.length>0?this.m_Children[0]:this.GetNextSiblingUp()}GetNextSiblingUp(){return null===this.m_Parent?null:this.m_Index===this.m_Parent.m_Children.length-1?this.m_Parent.GetNextSiblingUp():this.m_Parent.m_Children[this.m_Index+1]}Children(){return this.m_Children}Parent(){return this.m_Parent}IsHole(){return this.IsHoleNode()}}t.PolyNode=e;t.PolyTree=class extends e{m_AllPolys=[];constructor(){super()}Clear(){for(var t=0,e=this.m_AllPolys.length;t<e;t++)this.m_AllPolys[t]=null;this.m_AllPolys.length=0,this.m_Children.length=0}GetFirst(){return this.m_Children.length>0?this.m_Children[0]:null}Total(){var t=this.m_AllPolys.length;return t>0&&this.m_Children[0]!==this.m_AllPolys[0]&&t--,t}},t.Clear=function(t){t.length=0},t.PI=3.141592653589793,t.PI2=6.283185307179586;t.FPoint=class{X=0;Y=0;constructor(...e){var i=e,r=e.length;if(this.X=0,this.Y=0,2===r)this.X=i[0],this.Y=i[1];else if(1===r)if(i[0]instanceof t.FPoint){var s=i[0];this.X=s.X,this.Y=s.Y}else{var n=i[0];this.X=n.X,this.Y=n.Y}else this.X=0,this.Y=0}static op_Equality(t,e){return t.X===e.X&&t.Y===e.Y}static op_Inequality(t,e){return t.X!==e.X||t.Y!==e.Y}};var i,r,s,n,o,a,l,h;t.FRect=class{left;top;right;bottom;constructor(...t){var e=t,i=t.length;if(4===i)this.left=e[0],this.top=e[1],this.right=e[2],this.bottom=e[3];else if(1===i){var r=e[0];this.left=r.left,this.top=r.top,this.right=r.right,this.bottom=r.bottom}else this.left=0,this.top=0,this.right=0,this.bottom=0}},(i=t.ClipType||(t.ClipType={}))[i.ctIntersection=0]="ctIntersection",i[i.ctUnion=1]="ctUnion",i[i.ctDifference=2]="ctDifference",i[i.ctXor=3]="ctXor",(r=t.PolyType||(t.PolyType={}))[r.ptSubject=0]="ptSubject",r[r.ptClip=1]="ptClip",(s=t.PolyFillType||(t.PolyFillType={}))[s.pftEvenOdd=0]="pftEvenOdd",s[s.pftNonZero=1]="pftNonZero",s[s.pftPositive=2]="pftPositive",s[s.pftNegative=3]="pftNegative",(n=t.JoinType||(t.JoinType={}))[n.jtSquare=0]="jtSquare",n[n.jtRound=1]="jtRound",n[n.jtMiter=2]="jtMiter",(o=t.EndType||(t.EndType={}))[o.etOpenSquare=0]="etOpenSquare",o[o.etOpenRound=1]="etOpenRound",o[o.etOpenButt=2]="etOpenButt",o[o.etClosedLine=3]="etClosedLine",o[o.etClosedPolygon=4]="etClosedPolygon",(a=t.EdgeSide||(t.EdgeSide={}))[a.esLeft=0]="esLeft",a[a.esRight=1]="esRight",(l=t.Direction||(t.Direction={}))[l.dRightToLeft=0]="dRightToLeft",l[l.dLeftToRight=1]="dLeftToRight",(h=t.NodeType||(t.NodeType={}))[h.ntAny=0]="ntAny",h[h.ntOpen=1]="ntOpen",h[h.ntClosed=2]="ntClosed";t.TEdge=class{Bot=new t.FPoint;Curr=new t.FPoint;Top=new t.FPoint;Delta=new t.FPoint;Dx=0;PolyTyp=0;Side=0;WindDelta=0;WindCnt=0;WindCnt2=0;OutIdx=0;Next=null;Prev=null;NextInLML=null;NextInAEL=null;PrevInAEL=null;NextInSEL=null;PrevInSEL=null};t.IntersectNode=class{Edge1=null;Edge2=null;Pt=new t.FPoint},t.Compare=function(t,e){var i=e.Pt.Y-t.Pt.Y;return i>0?1:i<0?-1:0};t.LocalMinima=class{Y=0;LeftBound=null;RightBound=null;Next=null};t.Scanbeam=class{Y=0;Next=null};t.Maxima=class{X=0;Next=null;Prev=null};t.OutRec=class{Idx=0;IsHole=!1;IsOpen=!1;FirstLeft=null;Pts=null;BottomPt=null;PolyNode=null};t.OutPt=class{Idx=0;Pt=new t.FPoint;Next=null;Prev=null};t.Join=class{OutPt1=null;OutPt2=null;OffPt=new t.FPoint};class u{m_MinimaList=null;m_CurrentLM=null;m_edges=new Array;m_HasOpenPaths=!1;PreserveCollinear=!1;m_Scanbeam=null;m_PolyOuts=null;m_ActiveEdges=null;static horizontal=-34e37;static Skip=-2;static Unassigned=-1;static tolerance=1e-20;static maxValue=Math.sqrt(Number.MAX_VALUE);static minValue=Math.sqrt(Number.MIN_VALUE);static near_zero(e){return e>-t.ClipperBase.tolerance&&e<t.ClipperBase.tolerance}static IsHorizontal(t){return 0===t.Delta.Y}PointIsVertex(e,i){var r=i;do{if(t.FPoint.op_Equality(r.Pt,e))return!0;r=r.Next}while(r!==i);return!1}PointOnLineSegment(t,e,i){return t.X===e.X&&t.Y===e.Y||t.X===i.X&&t.Y===i.Y||t.X>e.X==t.X<i.X&&t.Y>e.Y==t.Y<i.Y&&(t.X-e.X)*(i.Y-e.Y)===(i.X-e.X)*(t.Y-e.Y)}PointOnPolygon(t,e){for(var i=e;;){if(this.PointOnLineSegment(t,i.Pt,i.Next.Pt))return!0;if((i=i.Next)===e)break}return!1}static SlopesEqual(){var t,e,i,r,s,n,o=arguments,a=o.length;return 2===a?(e=o[1],(t=o[0]).Delta.Y*e.Delta.X===t.Delta.X*e.Delta.Y):3===a?(r=o[1],s=o[2],((i=o[0]).Y-r.Y)*(r.X-s.X)-(i.X-r.X)*(r.Y-s.Y)===0):(r=o[1],s=o[2],n=o[3],((i=o[0]).Y-r.Y)*(s.X-n.X)-(i.X-r.X)*(s.Y-n.Y)===0)}static SlopesEqual3(t,e){return t.Delta.Y*e.Delta.X===t.Delta.X*e.Delta.Y}static SlopesEqual4(t,e,i){return(t.Y-e.Y)*(e.X-i.X)-(t.X-e.X)*(e.Y-i.Y)===0}static SlopesEqual5(t,e,i,r){return(t.Y-e.Y)*(i.X-r.X)-(t.X-e.X)*(i.Y-r.Y)===0}Clear(){this.DisposeLocalMinimaList();for(var e=0,i=this.m_edges.length;e<i;++e){for(var r=0,s=this.m_edges[e].length;r<s;++r)this.m_edges[e][r]=null;t.Clear(this.m_edges[e])}t.Clear(this.m_edges),this.m_HasOpenPaths=!1}DisposeLocalMinimaList(){for(;null!==this.m_MinimaList;){var t=this.m_MinimaList.Next;this.m_MinimaList=null,this.m_MinimaList=t}this.m_CurrentLM=null}RangeTest(e){(e.X>t.ClipperBase.maxValue||e.X<-t.ClipperBase.maxValue||e.Y>t.ClipperBase.maxValue||e.Y<-t.ClipperBase.maxValue||e.X>0&&e.X<t.ClipperBase.minValue||e.Y>0&&e.Y<t.ClipperBase.minValue||e.X<0&&e.X>-t.ClipperBase.minValue||e.Y<0&&e.Y>-t.ClipperBase.minValue)&&t.Error("Coordinate outside allowed range in RangeTest().")}InitEdge(t,e,i,r){t.Next=e,t.Prev=i,t.Curr.X=r.X,t.Curr.Y=r.Y,t.OutIdx=-1}InitEdge2(t,e){t.Curr.Y>=t.Next.Curr.Y?(t.Bot.X=t.Curr.X,t.Bot.Y=t.Curr.Y,t.Top.X=t.Next.Curr.X,t.Top.Y=t.Next.Curr.Y):(t.Top.X=t.Curr.X,t.Top.Y=t.Curr.Y,t.Bot.X=t.Next.Curr.X,t.Bot.Y=t.Next.Curr.Y),this.SetDx(t),t.PolyTyp=e}FindNextLocMin(e){for(var i;;){for(;t.FPoint.op_Inequality(e.Bot,e.Prev.Bot)||t.FPoint.op_Equality(e.Curr,e.Top);)e=e.Next;if(e.Dx!==t.ClipperBase.horizontal&&e.Prev.Dx!==t.ClipperBase.horizontal)break;for(;e.Prev.Dx===t.ClipperBase.horizontal;)e=e.Prev;for(i=e;e.Dx===t.ClipperBase.horizontal;)e=e.Next;if(e.Top.Y!==e.Prev.Bot.Y){i.Prev.Bot.X<e.Bot.X&&(e=i);break}}return e}ProcessBound(e,i){var r,s,n=e;if(n.OutIdx===t.ClipperBase.Skip){if(e=n,i){for(;e.Top.Y===e.Next.Bot.Y;)e=e.Next;for(;e!==n&&e.Dx===t.ClipperBase.horizontal;)e=e.Prev}else{for(;e.Top.Y===e.Prev.Bot.Y;)e=e.Prev;for(;e!==n&&e.Dx===t.ClipperBase.horizontal;)e=e.Next}if(e===n)n=i?e.Next:e.Prev;else{e=i?n.Next:n.Prev;var o=new t.LocalMinima;o.Next=null,o.Y=e.Bot.Y,o.LeftBound=null,o.RightBound=e,e.WindDelta=0,n=this.ProcessBound(e,i),this.InsertLocalMinima(o)}return n}if(e.Dx===t.ClipperBase.horizontal&&((r=i?e.Prev:e.Next).Dx===t.ClipperBase.horizontal?r.Bot.X!==e.Bot.X&&r.Top.X!==e.Bot.X&&this.ReverseHorizontal(e):r.Bot.X!==e.Bot.X&&this.ReverseHorizontal(e)),r=e,i){for(;n.Top.Y===n.Next.Bot.Y&&n.Next.OutIdx!==t.ClipperBase.Skip;)n=n.Next;if(n.Dx===t.ClipperBase.horizontal&&n.Next.OutIdx!==t.ClipperBase.Skip){for(s=n;s.Prev.Dx===t.ClipperBase.horizontal;)s=s.Prev;s.Prev.Top.X>n.Next.Top.X&&(n=s.Prev)}for(;e!==n;)e.NextInLML=e.Next,e.Dx===t.ClipperBase.horizontal&&e!==r&&e.Bot.X!==e.Prev.Top.X&&this.ReverseHorizontal(e),e=e.Next;e.Dx===t.ClipperBase.horizontal&&e!==r&&e.Bot.X!==e.Prev.Top.X&&this.ReverseHorizontal(e),n=n.Next}else{for(;n.Top.Y===n.Prev.Bot.Y&&n.Prev.OutIdx!==t.ClipperBase.Skip;)n=n.Prev;if(n.Dx===t.ClipperBase.horizontal&&n.Prev.OutIdx!==t.ClipperBase.Skip){for(s=n;s.Next.Dx===t.ClipperBase.horizontal;)s=s.Next;(s.Next.Top.X===n.Prev.Top.X||s.Next.Top.X>n.Prev.Top.X)&&(n=s.Next)}for(;e!==n;)e.NextInLML=e.Prev,e.Dx===t.ClipperBase.horizontal&&e!==r&&e.Bot.X!==e.Next.Top.X&&this.ReverseHorizontal(e),e=e.Prev;e.Dx===t.ClipperBase.horizontal&&e!==r&&e.Bot.X!==e.Next.Top.X&&this.ReverseHorizontal(e),n=n.Prev}return n}AddPath(e,i,r){t.use_lines?r||1!==i||t.Error("AddPath: Open paths must be subject."):r||t.Error("AddPath: Open paths have been disabled.");var s=e.length-1;if(r)for(;s>0&&t.FPoint.op_Equality(e[s],e[0]);)--s;for(;s>0&&t.FPoint.op_Equality(e[s],e[s-1]);)--s;if(r&&s<2||!r&&s<1)return!1;for(var n=new Array,o=0;o<=s;o++)n.push(new t.TEdge);var a=!0;n[1].Curr.X=e[1].X,n[1].Curr.Y=e[1].Y,this.RangeTest(e[0]),this.RangeTest(e[s]),this.InitEdge(n[0],n[1],n[s],e[0]),this.InitEdge(n[s],n[0],n[s-1],e[s]);for(o=s-1;o>=1;--o)this.RangeTest(e[o]),this.InitEdge(n[o],n[o+1],n[o-1],e[o]);for(var l,h=n[0],u=h,c=h;;)if(u.Curr!==u.Next.Curr||!r&&u.Next===h){if(u.Prev===u.Next)break;if(!r||!t.ClipperBase.SlopesEqual4(u.Prev.Curr,u.Curr,u.Next.Curr)||this.PreserveCollinear&&this.Pt2IsBetweenPt1AndPt3(u.Prev.Curr,u.Curr,u.Next.Curr)){if((u=u.Next)===c||!r&&u.Next===h)break}else u===h&&(h=u.Next),c=u=(u=this.RemoveEdge(u)).Prev}else{if(u===u.Next)break;u===h&&(h=u.Next),c=u=this.RemoveEdge(u)}if(!r&&u===u.Next||r&&u.Prev===u.Next)return!1;r||(this.m_HasOpenPaths=!0,h.Prev.OutIdx=t.ClipperBase.Skip),u=h;do{this.InitEdge2(u,i),u=u.Next,a&&u.Curr.Y!==h.Curr.Y&&(a=!1)}while(u!==h);if(a){if(r)return!1;for(u.Prev.OutIdx=t.ClipperBase.Skip,(p=new t.LocalMinima).Next=null,p.Y=u.Bot.Y,p.LeftBound=null,p.RightBound=u,p.RightBound.Side=1,p.RightBound.WindDelta=0;u.Bot.X!==u.Prev.Top.X&&this.ReverseHorizontal(u),u.Next.OutIdx!==t.ClipperBase.Skip;)u.NextInLML=u.Next,u=u.Next;return this.InsertLocalMinima(p),this.m_edges.push(n),!0}this.m_edges.push(n);var d=null;for(t.FPoint.op_Equality(u.Prev.Bot,u.Prev.Top)&&(u=u.Next);(u=this.FindNextLocMin(u))!==d;){var p;null===d&&(d=u),(p=new t.LocalMinima).Next=null,p.Y=u.Bot.Y,u.Dx<u.Prev.Dx?(p.LeftBound=u.Prev,p.RightBound=u,l=!1):(p.LeftBound=u,p.RightBound=u.Prev,l=!0),p.LeftBound.Side=0,p.RightBound.Side=1,r?p.LeftBound.Next===p.RightBound?p.LeftBound.WindDelta=-1:p.LeftBound.WindDelta=1:p.LeftBound.WindDelta=0,p.RightBound.WindDelta=-p.LeftBound.WindDelta,(u=this.ProcessBound(p.LeftBound,l)).OutIdx===t.ClipperBase.Skip&&(u=this.ProcessBound(u,l));var f=this.ProcessBound(p.RightBound,!l);f.OutIdx===t.ClipperBase.Skip&&(f=this.ProcessBound(f,!l)),p.LeftBound.OutIdx===t.ClipperBase.Skip?p.LeftBound=null:p.RightBound.OutIdx===t.ClipperBase.Skip&&(p.RightBound=null),this.InsertLocalMinima(p),l||(u=f)}return!0}AddPaths(t,e,i){for(var r=!1,s=0,n=t.length;s<n;++s)this.AddPath(t[s],e,i)&&(r=!0);return r}Pt2IsBetweenPt1AndPt3(e,i,r){return!(t.FPoint.op_Equality(e,r)||t.FPoint.op_Equality(e,i)||t.FPoint.op_Equality(r,i))&&(e.X!==r.X?i.X>e.X==i.X<r.X:i.Y>e.Y==i.Y<r.Y)}RemoveEdge(t){t.Prev.Next=t.Next,t.Next.Prev=t.Prev;var e=t.Next;return t.Prev=null,e}SetDx(e){e.Delta.X=e.Top.X-e.Bot.X,e.Delta.Y=e.Top.Y-e.Bot.Y,0===e.Delta.Y?e.Dx=t.ClipperBase.horizontal:e.Dx=e.Delta.X/e.Delta.Y}InsertLocalMinima(t){if(null===this.m_MinimaList)this.m_MinimaList=t;else if(t.Y>=this.m_MinimaList.Y)t.Next=this.m_MinimaList,this.m_MinimaList=t;else{for(var e=this.m_MinimaList;null!==e.Next&&t.Y<e.Next.Y;)e=e.Next;t.Next=e.Next,e.Next=t}}PopLocalMinima(t,e){return e.v=this.m_CurrentLM,null!==this.m_CurrentLM&&this.m_CurrentLM.Y===t&&(this.m_CurrentLM=this.m_CurrentLM.Next,!0)}ReverseHorizontal(t){var e=t.Top.X;t.Top.X=t.Bot.X,t.Bot.X=e}Reset(){if(this.m_CurrentLM=this.m_MinimaList,null!==this.m_CurrentLM){this.m_Scanbeam=null;for(var e=this.m_MinimaList;null!==e;){this.InsertScanbeam(e.Y);var i=e.LeftBound;null!==i&&(i.Curr.X=i.Bot.X,i.Curr.Y=i.Bot.Y,i.OutIdx=t.ClipperBase.Unassigned),null!==(i=e.RightBound)&&(i.Curr.X=i.Bot.X,i.Curr.Y=i.Bot.Y,i.OutIdx=t.ClipperBase.Unassigned),e=e.Next}this.m_ActiveEdges=null}}InsertScanbeam(e){if(null===this.m_Scanbeam)this.m_Scanbeam=new t.Scanbeam,this.m_Scanbeam.Next=null,this.m_Scanbeam.Y=e;else if(e>this.m_Scanbeam.Y){var i=new t.Scanbeam;i.Y=e,i.Next=this.m_Scanbeam,this.m_Scanbeam=i}else{for(var r=this.m_Scanbeam;null!==r.Next&&e<=r.Next.Y;)r=r.Next;if(e===r.Y)return;var s=new t.Scanbeam;s.Y=e,s.Next=r.Next,r.Next=s}}PopScanbeam(t){return null===this.m_Scanbeam?(t.v=0,!1):(t.v=this.m_Scanbeam.Y,this.m_Scanbeam=this.m_Scanbeam.Next,!0)}LocalMinimaPending(){return null!==this.m_CurrentLM}CreateOutRec(){var e=new t.OutRec;return e.Idx=t.ClipperBase.Unassigned,e.IsHole=!1,e.IsOpen=!1,e.FirstLeft=null,e.Pts=null,e.BottomPt=null,e.PolyNode=null,this.m_PolyOuts.push(e),e.Idx=this.m_PolyOuts.length-1,e}DisposeOutRec(t){var e=this.m_PolyOuts[t];e.Pts=null,e=null,this.m_PolyOuts[t]=null}UpdateEdgeIntoAEL(e){null===e.NextInLML&&t.Error("UpdateEdgeIntoAEL: invalid call");var i=e.PrevInAEL,r=e.NextInAEL;return e.NextInLML.OutIdx=e.OutIdx,null!==i?i.NextInAEL=e.NextInLML:this.m_ActiveEdges=e.NextInLML,null!==r&&(r.PrevInAEL=e.NextInLML),e.NextInLML.Side=e.Side,e.NextInLML.WindDelta=e.WindDelta,e.NextInLML.WindCnt=e.WindCnt,e.NextInLML.WindCnt2=e.WindCnt2,(e=e.NextInLML).Curr.X=e.Bot.X,e.Curr.Y=e.Bot.Y,e.PrevInAEL=i,e.NextInAEL=r,t.ClipperBase.IsHorizontal(e)||this.InsertScanbeam(e.Top.Y),e}SwapPositionsInAEL(t,e){if(t.NextInAEL!==t.PrevInAEL&&e.NextInAEL!==e.PrevInAEL){if(t.NextInAEL===e){var i=e.NextInAEL;null!==i&&(i.PrevInAEL=t);var r=t.PrevInAEL;null!==r&&(r.NextInAEL=e),e.PrevInAEL=r,e.NextInAEL=t,t.PrevInAEL=e,t.NextInAEL=i}else if(e.NextInAEL===t){var s=t.NextInAEL;null!==s&&(s.PrevInAEL=e);var n=e.PrevInAEL;null!==n&&(n.NextInAEL=t),t.PrevInAEL=n,t.NextInAEL=e,e.PrevInAEL=t,e.NextInAEL=s}else{var o=t.NextInAEL,a=t.PrevInAEL;t.NextInAEL=e.NextInAEL,null!==t.NextInAEL&&(t.NextInAEL.PrevInAEL=t),t.PrevInAEL=e.PrevInAEL,null!==t.PrevInAEL&&(t.PrevInAEL.NextInAEL=t),e.NextInAEL=o,null!==e.NextInAEL&&(e.NextInAEL.PrevInAEL=e),e.PrevInAEL=a,null!==e.PrevInAEL&&(e.PrevInAEL.NextInAEL=e)}null===t.PrevInAEL?this.m_ActiveEdges=t:null===e.PrevInAEL&&(this.m_ActiveEdges=e)}}DeleteFromAEL(t){var e=t.PrevInAEL,i=t.NextInAEL;null===e&&null===i&&t!==this.m_ActiveEdges||(null!==e?e.NextInAEL=i:this.m_ActiveEdges=i,null!==i&&(i.PrevInAEL=e),t.NextInAEL=null,t.PrevInAEL=null)}}t.ClipperBase=u;t.Clipper=class extends u{m_SortedEdges=null;m_IntersectList=null;m_IntersectNodeComparer=null;m_ExecuteLocked=!1;m_ClipFillType=0;m_SubjFillType=0;m_Joins=null;m_GhostJoins=null;m_UsingPolyTree=!1;ReverseSolution=!1;StrictlySimple=!1;m_ClipType=0;m_Maxima=null;ZFillFunction;constructor(e){super(),void 0===e&&(e=0),this.m_PolyOuts=null,this.m_Scanbeam=null,this.m_ActiveEdges=null,this.m_Scanbeam=null,this.m_Maxima=null,this.m_ActiveEdges=null,this.m_SortedEdges=null,this.m_IntersectList=new Array,this.m_IntersectNodeComparer=t.Compare,this.m_ExecuteLocked=!1,this.m_UsingPolyTree=!1,this.m_PolyOuts=new Array,this.m_Joins=new Array,this.m_GhostJoins=new Array,this.ReverseSolution=!!(1&e),this.StrictlySimple=!!(2&e),this.PreserveCollinear=!!(4&e)}static ioReverseSolution=1;static ioStrictlySimple=2;static ioPreserveCollinear=4;Clear(){0!==this.m_edges.length&&(this.DisposeAllPolyPts(),super.Clear())}InsertMaxima(e){var i=new t.Maxima;if(i.X=e,null===this.m_Maxima)this.m_Maxima=i,this.m_Maxima.Next=null,this.m_Maxima.Prev=null;else if(e<this.m_Maxima.X)i.Next=this.m_Maxima,i.Prev=null,this.m_Maxima=i;else{for(var r=this.m_Maxima;null!==r.Next&&e>=r.Next.X;)r=r.Next;if(e===r.X)return;i.Next=r.Next,i.Prev=r,null!==r.Next&&(r.Next.Prev=i),r.Next=i}}Execute(...e){var i=e,r=i.length,s=i[1]instanceof t.PolyTree;if(4===r&&!s){var n=i[0],o=i[1],a=i[2],l=i[3];if(this.m_ExecuteLocked)return!1;this.m_HasOpenPaths&&t.Error("Error: PolyTree struct is needed for open path clipping."),this.m_ExecuteLocked=!0,t.Clear(o),this.m_SubjFillType=a,this.m_ClipFillType=l,this.m_ClipType=n,this.m_UsingPolyTree=!1;try{(u=this.ExecuteInternal())&&this.BuildResult(o)}finally{this.DisposeAllPolyPts(),this.m_ExecuteLocked=!1}return u}if(4===r&&s){n=i[0];var h=i[1];a=i[2],l=i[3];if(this.m_ExecuteLocked)return!1;this.m_ExecuteLocked=!0,this.m_SubjFillType=a,this.m_ClipFillType=l,this.m_ClipType=n,this.m_UsingPolyTree=!0;try{var u;(u=this.ExecuteInternal())&&this.BuildResult2(h)}finally{this.DisposeAllPolyPts(),this.m_ExecuteLocked=!1}return u}if(2===r&&!s){n=i[0],o=i[1];return this.Execute(n,o,0,0)}if(2===r&&s){n=i[0],h=i[1];return this.Execute(n,h,0,0)}}FixHoleLinkage(t){if(null!==t.FirstLeft&&(t.IsHole===t.FirstLeft.IsHole||null===t.FirstLeft.Pts)){for(var e=t.FirstLeft;null!==e&&(e.IsHole===t.IsHole||null===e.Pts);)e=e.FirstLeft;t.FirstLeft=e}}ExecuteInternal(){try{this.Reset(),this.m_SortedEdges=null,this.m_Maxima=null;var t,e,i,r={},s={};if(!this.PopScanbeam(r))return!1;for(this.InsertLocalMinimaIntoAEL(r.v);this.PopScanbeam(s)||this.LocalMinimaPending();){if(this.ProcessHorizontals(),this.m_GhostJoins.length=0,!this.ProcessIntersections(s.v))return!1;this.ProcessEdgesAtTopOfScanbeam(s.v),r.v=s.v,this.InsertLocalMinimaIntoAEL(r.v)}for(e=0,i=this.m_PolyOuts.length;e<i;e++)null===(t=this.m_PolyOuts[e]).Pts||t.IsOpen||(t.IsHole^this.ReverseSolution)==this.Area$1(t)>0&&this.ReversePolyPtLinks(t.Pts);for(this.JoinCommonEdges(),e=0,i=this.m_PolyOuts.length;e<i;e++)null!==(t=this.m_PolyOuts[e]).Pts&&(t.IsOpen?this.FixupOutPolyline(t):this.FixupOutPolygon(t));return this.StrictlySimple&&this.DoSimplePolygons(),!0}finally{this.m_Joins.length=0,this.m_GhostJoins.length=0}}DisposeAllPolyPts(){for(var e=0,i=this.m_PolyOuts.length;e<i;++e)this.DisposeOutRec(e);t.Clear(this.m_PolyOuts)}AddJoin(e,i,r){var s=new t.Join;s.OutPt1=e,s.OutPt2=i,s.OffPt.X=r.X,s.OffPt.Y=r.Y,this.m_Joins.push(s)}AddGhostJoin(e,i){var r=new t.Join;r.OutPt1=e,r.OffPt.X=i.X,r.OffPt.Y=i.Y,this.m_GhostJoins.push(r)}InsertLocalMinimaIntoAEL(e){for(var i,r,s={};this.PopLocalMinima(e,s);){i=s.v.LeftBound,r=s.v.RightBound;var n=null;if(null===i?(this.InsertEdgeIntoAEL(r,null),this.SetWindingCount(r),this.IsContributing(r)&&(n=this.AddOutPt(r,r.Bot))):null===r?(this.InsertEdgeIntoAEL(i,null),this.SetWindingCount(i),this.IsContributing(i)&&(n=this.AddOutPt(i,i.Bot)),this.InsertScanbeam(i.Top.Y)):(this.InsertEdgeIntoAEL(i,null),this.InsertEdgeIntoAEL(r,i),this.SetWindingCount(i),r.WindCnt=i.WindCnt,r.WindCnt2=i.WindCnt2,this.IsContributing(i)&&(n=this.AddLocalMinPoly(i,r,i.Bot)),this.InsertScanbeam(i.Top.Y)),null!==r&&(t.ClipperBase.IsHorizontal(r)?(null!==r.NextInLML&&this.InsertScanbeam(r.NextInLML.Top.Y),this.AddEdgeToSEL(r)):this.InsertScanbeam(r.Top.Y)),null!==i&&null!==r){if(null!==n&&t.ClipperBase.IsHorizontal(r)&&this.m_GhostJoins.length>0&&0!==r.WindDelta)for(var o=0,a=this.m_GhostJoins.length;o<a;o++){var l=this.m_GhostJoins[o];this.HorzSegmentsOverlap(l.OutPt1.Pt.X,l.OffPt.X,r.Bot.X,r.Top.X)&&this.AddJoin(l.OutPt1,n,l.OffPt)}if(i.OutIdx>=0&&null!==i.PrevInAEL&&i.PrevInAEL.Curr.X===i.Bot.X&&i.PrevInAEL.OutIdx>=0&&t.ClipperBase.SlopesEqual5(i.PrevInAEL.Curr,i.PrevInAEL.Top,i.Curr,i.Top)&&0!==i.WindDelta&&0!==i.PrevInAEL.WindDelta){var h=this.AddOutPt(i.PrevInAEL,i.Bot);this.AddJoin(n,h,i.Top)}if(i.NextInAEL!==r){if(r.OutIdx>=0&&r.PrevInAEL.OutIdx>=0&&t.ClipperBase.SlopesEqual5(r.PrevInAEL.Curr,r.PrevInAEL.Top,r.Curr,r.Top)&&0!==r.WindDelta&&0!==r.PrevInAEL.WindDelta){h=this.AddOutPt(r.PrevInAEL,r.Bot);this.AddJoin(n,h,r.Top)}var u=i.NextInAEL;if(null!==u)for(;u!==r;)this.IntersectEdges(r,u,i.Curr),u=u.NextInAEL}}}}InsertEdgeIntoAEL(t,e){if(null===this.m_ActiveEdges)t.PrevInAEL=null,t.NextInAEL=null,this.m_ActiveEdges=t;else if(null===e&&this.E2InsertsBeforeE1(this.m_ActiveEdges,t))t.PrevInAEL=null,t.NextInAEL=this.m_ActiveEdges,this.m_ActiveEdges.PrevInAEL=t,this.m_ActiveEdges=t;else{for(null===e&&(e=this.m_ActiveEdges);null!==e.NextInAEL&&!this.E2InsertsBeforeE1(e.NextInAEL,t);)e=e.NextInAEL;t.NextInAEL=e.NextInAEL,null!==e.NextInAEL&&(e.NextInAEL.PrevInAEL=t),t.PrevInAEL=e,e.NextInAEL=t}}E2InsertsBeforeE1(e,i){return i.Curr.X===e.Curr.X?i.Top.Y>e.Top.Y?i.Top.X<t.Clipper.TopX(e,i.Top.Y):e.Top.X>t.Clipper.TopX(i,e.Top.Y):i.Curr.X<e.Curr.X}IsEvenOddFillType(t){return 0===t.PolyTyp?0===this.m_SubjFillType:0===this.m_ClipFillType}IsEvenOddAltFillType(t){return 0===t.PolyTyp?0===this.m_ClipFillType:0===this.m_SubjFillType}IsContributing(t){var e,i;switch(0===t.PolyTyp?(e=this.m_SubjFillType,i=this.m_ClipFillType):(e=this.m_ClipFillType,i=this.m_SubjFillType),e){case 0:if(0===t.WindDelta&&1!==t.WindCnt)return!1;break;case 1:if(1!==Math.abs(t.WindCnt))return!1;break;case 2:if(1!==t.WindCnt)return!1;break;default:if(-1!==t.WindCnt)return!1}switch(this.m_ClipType){case 0:switch(i){case 0:case 1:return 0!==t.WindCnt2;case 2:return t.WindCnt2>0;default:return t.WindCnt2<0}case 1:switch(i){case 0:case 1:return 0===t.WindCnt2;case 2:return t.WindCnt2<=0;default:return t.WindCnt2>=0}case 2:if(0===t.PolyTyp)switch(i){case 0:case 1:return 0===t.WindCnt2;case 2:return t.WindCnt2<=0;default:return t.WindCnt2>=0}else switch(i){case 0:case 1:return 0!==t.WindCnt2;case 2:return t.WindCnt2>0;default:return t.WindCnt2<0}case 3:if(0!==t.WindDelta)return!0;switch(i){case 0:case 1:return 0===t.WindCnt2;case 2:return t.WindCnt2<=0;default:return t.WindCnt2>=0}}return!0}SetWindingCount(t){for(var e=t.PrevInAEL;null!==e&&(e.PolyTyp!==t.PolyTyp||0===e.WindDelta);)e=e.PrevInAEL;if(null===e){var i=0===t.PolyTyp?this.m_SubjFillType:this.m_ClipFillType;0===t.WindDelta?t.WindCnt=3===i?-1:1:t.WindCnt=t.WindDelta,t.WindCnt2=0,e=this.m_ActiveEdges}else if(0===t.WindDelta&&1!==this.m_ClipType)t.WindCnt=1,t.WindCnt2=e.WindCnt2,e=e.NextInAEL;else if(this.IsEvenOddFillType(t)){if(0===t.WindDelta){for(var r=!0,s=e.PrevInAEL;null!==s;)s.PolyTyp===e.PolyTyp&&0!==s.WindDelta&&(r=!r),s=s.PrevInAEL;t.WindCnt=r?0:1}else t.WindCnt=t.WindDelta;t.WindCnt2=e.WindCnt2,e=e.NextInAEL}else e.WindCnt*e.WindDelta<0?Math.abs(e.WindCnt)>1?e.WindDelta*t.WindDelta<0?t.WindCnt=e.WindCnt:t.WindCnt=e.WindCnt+t.WindDelta:t.WindCnt=0===t.WindDelta?1:t.WindDelta:0===t.WindDelta?t.WindCnt=e.WindCnt<0?e.WindCnt-1:e.WindCnt+1:e.WindDelta*t.WindDelta<0?t.WindCnt=e.WindCnt:t.WindCnt=e.WindCnt+t.WindDelta,t.WindCnt2=e.WindCnt2,e=e.NextInAEL;if(this.IsEvenOddAltFillType(t))for(;e!==t;)0!==e.WindDelta&&(t.WindCnt2=0===t.WindCnt2?1:0),e=e.NextInAEL;else for(;e!==t;)t.WindCnt2+=e.WindDelta,e=e.NextInAEL}AddEdgeToSEL(t){null===this.m_SortedEdges?(this.m_SortedEdges=t,t.PrevInSEL=null,t.NextInSEL=null):(t.NextInSEL=this.m_SortedEdges,t.PrevInSEL=null,this.m_SortedEdges.PrevInSEL=t,this.m_SortedEdges=t)}PopEdgeFromSEL(t){if(t.v=this.m_SortedEdges,null===t.v)return!1;var e=t.v;return this.m_SortedEdges=t.v.NextInSEL,null!==this.m_SortedEdges&&(this.m_SortedEdges.PrevInSEL=null),e.NextInSEL=null,e.PrevInSEL=null,!0}CopyAELToSEL(){var t=this.m_ActiveEdges;for(this.m_SortedEdges=t;null!==t;)t.PrevInSEL=t.PrevInAEL,t.NextInSEL=t.NextInAEL,t=t.NextInAEL}SwapPositionsInSEL(t,e){if(!(null===t.NextInSEL&&null===t.PrevInSEL||null===e.NextInSEL&&null===e.PrevInSEL)){if(t.NextInSEL===e)null!==(i=e.NextInSEL)&&(i.PrevInSEL=t),null!==(r=t.PrevInSEL)&&(r.NextInSEL=e),e.PrevInSEL=r,e.NextInSEL=t,t.PrevInSEL=e,t.NextInSEL=i;else if(e.NextInSEL===t){null!==(i=t.NextInSEL)&&(i.PrevInSEL=e),null!==(r=e.PrevInSEL)&&(r.NextInSEL=t),t.PrevInSEL=r,t.NextInSEL=e,e.PrevInSEL=t,e.NextInSEL=i}else{var i=t.NextInSEL,r=t.PrevInSEL;t.NextInSEL=e.NextInSEL,null!==t.NextInSEL&&(t.NextInSEL.PrevInSEL=t),t.PrevInSEL=e.PrevInSEL,null!==t.PrevInSEL&&(t.PrevInSEL.NextInSEL=t),e.NextInSEL=i,null!==e.NextInSEL&&(e.NextInSEL.PrevInSEL=e),e.PrevInSEL=r,null!==e.PrevInSEL&&(e.PrevInSEL.NextInSEL=e)}null===t.PrevInSEL?this.m_SortedEdges=t:null===e.PrevInSEL&&(this.m_SortedEdges=e)}}AddLocalMaxPoly(t,e,i){this.AddOutPt(t,i),0===e.WindDelta&&this.AddOutPt(e,i),t.OutIdx===e.OutIdx?(t.OutIdx=-1,e.OutIdx=-1):t.OutIdx<e.OutIdx?this.AppendPolygon(t,e):this.AppendPolygon(e,t)}AddLocalMinPoly(e,i,r){var s,n,o;if(t.ClipperBase.IsHorizontal(i)||e.Dx>i.Dx?(s=this.AddOutPt(e,r),i.OutIdx=e.OutIdx,e.Side=0,i.Side=1,o=(n=e).PrevInAEL===i?i.PrevInAEL:n.PrevInAEL):(s=this.AddOutPt(i,r),e.OutIdx=i.OutIdx,e.Side=1,i.Side=0,o=(n=i).PrevInAEL===e?e.PrevInAEL:n.PrevInAEL),null!==o&&o.OutIdx>=0&&o.Top.Y<r.Y&&n.Top.Y<r.Y){var a=t.Clipper.TopX(o,r.Y),l=t.Clipper.TopX(n,r.Y);if(a===l&&0!==n.WindDelta&&0!==o.WindDelta&&t.ClipperBase.SlopesEqual5(new t.FPoint(a,r.Y),o.Top,new t.FPoint(l,r.Y),n.Top)){var h=this.AddOutPt(o,r);this.AddJoin(s,h,n.Top)}}return s}AddOutPt(e,i){if(e.OutIdx<0){let s=this.CreateOutRec();s.IsOpen=0===e.WindDelta;var r=new t.OutPt;return s.Pts=r,r.Idx=s.Idx,r.Pt.X=i.X,r.Pt.Y=i.Y,r.Next=r,r.Prev=r,s.IsOpen||this.SetHoleState(e,s),e.OutIdx=s.Idx,r}{let o=this.m_PolyOuts[e.OutIdx];var s=o.Pts,n=0===e.Side;return n&&t.FPoint.op_Equality(i,s.Pt)?s:!n&&t.FPoint.op_Equality(i,s.Prev.Pt)?s.Prev:((r=new t.OutPt).Idx=o.Idx,r.Pt.X=i.X,r.Pt.Y=i.Y,r.Next=s,r.Prev=s.Prev,r.Prev.Next=r,s.Prev=r,n&&(o.Pts=r),r)}}GetLastOutPt(t){var e=this.m_PolyOuts[t.OutIdx];return 0===t.Side?e.Pts:e.Pts.Prev}SwapPoints(e,i){var r=new t.FPoint(e.Value);e.Value.X=i.Value.X,e.Value.Y=i.Value.Y,i.Value.X=r.X,i.Value.Y=r.Y}HorzSegmentsOverlap(t,e,i,r){var s;return t>e&&(s=t,t=e,e=s),i>r&&(s=i,i=r,r=s),t<r&&i<e}SetHoleState(t,e){for(var i=t.PrevInAEL,r=null;null!==i;)i.OutIdx>=0&&0!==i.WindDelta&&(null===r?r=i:r.OutIdx===i.OutIdx&&(r=null)),i=i.PrevInAEL;null===r?(e.FirstLeft=null,e.IsHole=!1):(e.FirstLeft=this.m_PolyOuts[r.OutIdx],e.IsHole=!e.FirstLeft.IsHole)}GetDx(e,i){return e.Y===i.Y?t.ClipperBase.horizontal:(i.X-e.X)/(i.Y-e.Y)}FirstIsBottomPt(e,i){for(var r=e.Prev;t.FPoint.op_Equality(r.Pt,e.Pt)&&r!==e;)r=r.Prev;var s=Math.abs(this.GetDx(e.Pt,r.Pt));for(r=e.Next;t.FPoint.op_Equality(r.Pt,e.Pt)&&r!==e;)r=r.Next;var n=Math.abs(this.GetDx(e.Pt,r.Pt));for(r=i.Prev;t.FPoint.op_Equality(r.Pt,i.Pt)&&r!==i;)r=r.Prev;var o=Math.abs(this.GetDx(i.Pt,r.Pt));for(r=i.Next;t.FPoint.op_Equality(r.Pt,i.Pt)&&r!==i;)r=r.Next;var a=Math.abs(this.GetDx(i.Pt,r.Pt));return Math.max(s,n)===Math.max(o,a)&&Math.min(s,n)===Math.min(o,a)?this.Area(e)>0:s>=o&&s>=a||n>=o&&n>=a}GetBottomPt(e){for(var i=null,r=e.Next;r!==e;)r.Pt.Y>e.Pt.Y?(e=r,i=null):r.Pt.Y===e.Pt.Y&&r.Pt.X<=e.Pt.X&&(r.Pt.X<e.Pt.X?(i=null,e=r):r.Next!==e&&r.Prev!==e&&(i=r)),r=r.Next;if(null!==i)for(;i!==r;)for(this.FirstIsBottomPt(r,i)||(e=i),i=i.Next;t.FPoint.op_Inequality(i.Pt,e.Pt);)i=i.Next;return e}GetLowermostRec(t,e){null===t.BottomPt&&(t.BottomPt=this.GetBottomPt(t.Pts)),null===e.BottomPt&&(e.BottomPt=this.GetBottomPt(e.Pts));var i=t.BottomPt,r=e.BottomPt;return i.Pt.Y>r.Pt.Y?t:i.Pt.Y<r.Pt.Y?e:i.Pt.X<r.Pt.X?t:i.Pt.X>r.Pt.X||i.Next===i?e:r.Next===r||this.FirstIsBottomPt(i,r)?t:e}OutRec1RightOfOutRec2(t,e){do{if((t=t.FirstLeft)===e)return!0}while(null!==t);return!1}GetOutRec(t){for(var e=this.m_PolyOuts[t];e!==this.m_PolyOuts[e.Idx];)e=this.m_PolyOuts[e.Idx];return e}AppendPolygon(t,e){var i,r=this.m_PolyOuts[t.OutIdx],s=this.m_PolyOuts[e.OutIdx];i=this.OutRec1RightOfOutRec2(r,s)?s:this.OutRec1RightOfOutRec2(s,r)?r:this.GetLowermostRec(r,s);var n=r.Pts,o=n.Prev,a=s.Pts,l=a.Prev;0===t.Side?0===e.Side?(this.ReversePolyPtLinks(a),a.Next=n,n.Prev=a,o.Next=l,l.Prev=o,r.Pts=l):(l.Next=n,n.Prev=l,a.Prev=o,o.Next=a,r.Pts=a):1===e.Side?(this.ReversePolyPtLinks(a),o.Next=l,l.Prev=o,a.Next=n,n.Prev=a):(o.Next=a,a.Prev=o,n.Prev=l,l.Next=n),r.BottomPt=null,i===s&&(s.FirstLeft!==r&&(r.FirstLeft=s.FirstLeft),r.IsHole=s.IsHole),s.Pts=null,s.BottomPt=null,s.FirstLeft=r;var h=t.OutIdx,u=e.OutIdx;t.OutIdx=-1,e.OutIdx=-1;for(var c=this.m_ActiveEdges;null!==c;){if(c.OutIdx===u){c.OutIdx=h,c.Side=t.Side;break}c=c.NextInAEL}s.Idx=r.Idx}ReversePolyPtLinks(t){if(null!==t){var e,i;e=t;do{i=e.Next,e.Next=e.Prev,e.Prev=i,e=i}while(e!==t)}}static SwapSides(t,e){var i=t.Side;t.Side=e.Side,e.Side=i}static SwapPolyIndexes(t,e){var i=t.OutIdx;t.OutIdx=e.OutIdx,e.OutIdx=i}IntersectEdges(e,i,r){var s=e.OutIdx>=0,n=i.OutIdx>=0;if(!t.use_lines||0!==e.WindDelta&&0!==i.WindDelta){if(e.PolyTyp===i.PolyTyp)if(this.IsEvenOddFillType(e)){var o=e.WindCnt;e.WindCnt=i.WindCnt,i.WindCnt=o}else e.WindCnt+i.WindDelta===0?e.WindCnt=-e.WindCnt:e.WindCnt+=i.WindDelta,i.WindCnt-e.WindDelta===0?i.WindCnt=-i.WindCnt:i.WindCnt-=e.WindDelta;else this.IsEvenOddFillType(i)?e.WindCnt2=0===e.WindCnt2?1:0:e.WindCnt2+=i.WindDelta,this.IsEvenOddFillType(e)?i.WindCnt2=0===i.WindCnt2?1:0:i.WindCnt2-=e.WindDelta;var a,l,h,u,c,d;switch(0===e.PolyTyp?(a=this.m_SubjFillType,h=this.m_ClipFillType):(a=this.m_ClipFillType,h=this.m_SubjFillType),0===i.PolyTyp?(l=this.m_SubjFillType,u=this.m_ClipFillType):(l=this.m_ClipFillType,u=this.m_SubjFillType),a){case 2:c=e.WindCnt;break;case 3:c=-e.WindCnt;break;default:c=Math.abs(e.WindCnt)}switch(l){case 2:d=i.WindCnt;break;case 3:d=-i.WindCnt;break;default:d=Math.abs(i.WindCnt)}if(s&&n)0!==c&&1!==c||0!==d&&1!==d||e.PolyTyp!==i.PolyTyp&&3!==this.m_ClipType?this.AddLocalMaxPoly(e,i,r):(this.AddOutPt(e,r),this.AddOutPt(i,r),t.Clipper.SwapSides(e,i),t.Clipper.SwapPolyIndexes(e,i));else if(s)0!==d&&1!==d||(this.AddOutPt(e,r),t.Clipper.SwapSides(e,i),t.Clipper.SwapPolyIndexes(e,i));else if(n)0!==c&&1!==c||(this.AddOutPt(i,r),t.Clipper.SwapSides(e,i),t.Clipper.SwapPolyIndexes(e,i));else if(!(0!==c&&1!==c||0!==d&&1!==d)){var p,f;switch(h){case 2:p=e.WindCnt2;break;case 3:p=-e.WindCnt2;break;default:p=Math.abs(e.WindCnt2)}switch(u){case 2:f=i.WindCnt2;break;case 3:f=-i.WindCnt2;break;default:f=Math.abs(i.WindCnt2)}if(e.PolyTyp!==i.PolyTyp)this.AddLocalMinPoly(e,i,r);else if(1===c&&1===d)switch(this.m_ClipType){case 0:p>0&&f>0&&this.AddLocalMinPoly(e,i,r);break;case 1:p<=0&&f<=0&&this.AddLocalMinPoly(e,i,r);break;case 2:(1===e.PolyTyp&&p>0&&f>0||0===e.PolyTyp&&p<=0&&f<=0)&&this.AddLocalMinPoly(e,i,r);break;case 3:this.AddLocalMinPoly(e,i,r)}else t.Clipper.SwapSides(e,i)}}else{if(0===e.WindDelta&&0===i.WindDelta)return;e.PolyTyp===i.PolyTyp&&e.WindDelta!==i.WindDelta&&1===this.m_ClipType?0===e.WindDelta?n&&(this.AddOutPt(e,r),s&&(e.OutIdx=-1)):s&&(this.AddOutPt(i,r),n&&(i.OutIdx=-1)):e.PolyTyp!==i.PolyTyp&&(0!==e.WindDelta||1!==Math.abs(i.WindCnt)||1===this.m_ClipType&&0!==i.WindCnt2?0!==i.WindDelta||1!==Math.abs(e.WindCnt)||1===this.m_ClipType&&0!==e.WindCnt2||(this.AddOutPt(i,r),n&&(i.OutIdx=-1)):(this.AddOutPt(e,r),s&&(e.OutIdx=-1)))}}DeleteFromSEL(t){var e=t.PrevInSEL,i=t.NextInSEL;null===e&&null===i&&t!==this.m_SortedEdges||(null!==e?e.NextInSEL=i:this.m_SortedEdges=i,null!==i&&(i.PrevInSEL=e),t.NextInSEL=null,t.PrevInSEL=null)}ProcessHorizontals(){for(var t={};this.PopEdgeFromSEL(t);)this.ProcessHorizontal(t.v)}GetHorzDirection(t,e){t.Bot.X<t.Top.X?(e.Left=t.Bot.X,e.Right=t.Top.X,e.Dir=1):(e.Left=t.Top.X,e.Right=t.Bot.X,e.Dir=0)}ProcessHorizontal(e){var i={Dir:null,Left:null,Right:null};this.GetHorzDirection(e,i);for(var r=i.Dir,s=i.Left,n=i.Right,o=0===e.WindDelta,a=e,l=null;null!==a.NextInLML&&t.ClipperBase.IsHorizontal(a.NextInLML);)a=a.NextInLML;null===a.NextInLML&&(l=this.GetMaximaPair(a));var h=this.m_Maxima;if(null!==h)if(1===r){for(;null!==h&&h.X<=e.Bot.X;)h=h.Next;null!==h&&h.X>=a.Top.X&&(h=null)}else{for(;null!==h.Next&&h.Next.X<e.Bot.X;)h=h.Next;h.X<=a.Top.X&&(h=null)}for(var u=null;;){for(var c=e===a,d=this.GetNextInAEL(e,r);null!==d;){if(null!==h)if(1===r)for(;null!==h&&h.X<d.Curr.X;)e.OutIdx>=0&&!o&&this.AddOutPt(e,new t.FPoint(h.X,e.Bot.Y)),h=h.Next;else for(;null!==h&&h.X>d.Curr.X;)e.OutIdx>=0&&!o&&this.AddOutPt(e,new t.FPoint(h.X,e.Bot.Y)),h=h.Prev;if(1===r&&d.Curr.X>n||0===r&&d.Curr.X<s)break;if(d.Curr.X===e.Top.X&&null!==e.NextInLML&&d.Dx<e.NextInLML.Dx)break;if(e.OutIdx>=0&&!o){u=this.AddOutPt(e,d.Curr);for(var p=this.m_SortedEdges;null!==p;){if(p.OutIdx>=0&&this.HorzSegmentsOverlap(e.Bot.X,e.Top.X,p.Bot.X,p.Top.X)){var f=this.GetLastOutPt(p);this.AddJoin(f,u,p.Top)}p=p.NextInSEL}this.AddGhostJoin(u,e.Bot)}if(d===l&&c)return e.OutIdx>=0&&this.AddLocalMaxPoly(e,l,e.Top),this.DeleteFromAEL(e),void this.DeleteFromAEL(l);if(1===r){var m=new t.FPoint(d.Curr.X,e.Curr.Y);this.IntersectEdges(e,d,m)}else{m=new t.FPoint(d.Curr.X,e.Curr.Y);this.IntersectEdges(d,e,m)}var g=this.GetNextInAEL(d,r);this.SwapPositionsInAEL(e,d),d=g}if(null===e.NextInLML||!t.ClipperBase.IsHorizontal(e.NextInLML))break;(e=this.UpdateEdgeIntoAEL(e)).OutIdx>=0&&this.AddOutPt(e,e.Bot),i={Dir:r,Left:s,Right:n},this.GetHorzDirection(e,i),r=i.Dir,s=i.Left,n=i.Right}if(e.OutIdx>=0&&null===u){u=this.GetLastOutPt(e);for(p=this.m_SortedEdges;null!==p;){if(p.OutIdx>=0&&this.HorzSegmentsOverlap(e.Bot.X,e.Top.X,p.Bot.X,p.Top.X)){f=this.GetLastOutPt(p);this.AddJoin(f,u,p.Top)}p=p.NextInSEL}this.AddGhostJoin(u,e.Top)}if(null!==e.NextInLML)if(e.OutIdx>=0){if(u=this.AddOutPt(e,e.Top),0===(e=this.UpdateEdgeIntoAEL(e)).WindDelta)return;var y=e.PrevInAEL;g=e.NextInAEL;if(null!==y&&y.Curr.X===e.Bot.X&&y.Curr.Y===e.Bot.Y&&0===y.WindDelta&&y.OutIdx>=0&&y.Curr.Y>y.Top.Y&&t.ClipperBase.SlopesEqual3(e,y)){let t=this.AddOutPt(y,e.Bot);this.AddJoin(u,t,e.Top)}else if(null!==g&&g.Curr.X===e.Bot.X&&g.Curr.Y===e.Bot.Y&&0!==g.WindDelta&&g.OutIdx>=0&&g.Curr.Y>g.Top.Y&&t.ClipperBase.SlopesEqual3(e,g)){let t=this.AddOutPt(g,e.Bot);this.AddJoin(u,t,e.Top)}}else e=this.UpdateEdgeIntoAEL(e);else e.OutIdx>=0&&this.AddOutPt(e,e.Top),this.DeleteFromAEL(e)}GetNextInAEL(t,e){return 1===e?t.NextInAEL:t.PrevInAEL}IsMinima(t){return null!==t&&t.Prev.NextInLML!==t&&t.Next.NextInLML!==t}IsMaxima(t,e){return null!==t&&t.Top.Y===e&&null===t.NextInLML}IsIntermediate(t,e){return t.Top.Y===e&&null!==t.NextInLML}GetMaximaPair(e){return t.FPoint.op_Equality(e.Next.Top,e.Top)&&null===e.Next.NextInLML?e.Next:t.FPoint.op_Equality(e.Prev.Top,e.Top)&&null===e.Prev.NextInLML?e.Prev:null}GetMaximaPairEx(e){var i=this.GetMaximaPair(e);return null===i||i.OutIdx===t.ClipperBase.Skip||i.NextInAEL===i.PrevInAEL&&!t.ClipperBase.IsHorizontal(i)?null:i}ProcessIntersections(e){if(null===this.m_ActiveEdges)return!0;try{if(this.BuildIntersectList(e),0===this.m_IntersectList.length)return!0;if(1!==this.m_IntersectList.length&&!this.FixupIntersectionOrder())return!1;this.ProcessIntersectList()}catch(i){this.m_SortedEdges=null,this.m_IntersectList.length=0,t.Error("ProcessIntersections error")}return this.m_SortedEdges=null,!0}BuildIntersectList(e){if(null!==this.m_ActiveEdges){var i=this.m_ActiveEdges;for(this.m_SortedEdges=i;null!==i;)i.PrevInSEL=i.PrevInAEL,i.NextInSEL=i.NextInAEL,i.Curr.X=t.Clipper.TopX(i,e),i=i.NextInAEL;for(var r=!0;r&&null!==this.m_SortedEdges;){for(r=!1,i=this.m_SortedEdges;null!==i.NextInSEL;){var s=i.NextInSEL,n=new t.FPoint;if(i.Curr.X>s.Curr.X){this.IntersectPoint(i,s,n),n.Y<e&&(n=new t.FPoint(t.Clipper.TopX(i,e),e));var o=new t.IntersectNode;o.Edge1=i,o.Edge2=s,o.Pt.X=n.X,o.Pt.Y=n.Y,this.m_IntersectList.push(o),this.SwapPositionsInSEL(i,s),r=!0}else i=s}if(null===i.PrevInSEL)break;i.PrevInSEL.NextInSEL=null}this.m_SortedEdges=null}}EdgesAdjacent(t){return t.Edge1.NextInSEL===t.Edge2||t.Edge1.PrevInSEL===t.Edge2}static IntersectNodeSort(t,e){return e.Pt.Y-t.Pt.Y}FixupIntersectionOrder(){this.m_IntersectList.sort(this.m_IntersectNodeComparer),this.CopyAELToSEL();for(var t=this.m_IntersectList.length,e=0;e<t;e++){if(!this.EdgesAdjacent(this.m_IntersectList[e])){for(var i=e+1;i<t&&!this.EdgesAdjacent(this.m_IntersectList[i]);)i++;if(i===t)return!1;var r=this.m_IntersectList[e];this.m_IntersectList[e]=this.m_IntersectList[i],this.m_IntersectList[i]=r}this.SwapPositionsInSEL(this.m_IntersectList[e].Edge1,this.m_IntersectList[e].Edge2)}return!0}ProcessIntersectList(){for(var t=0,e=this.m_IntersectList.length;t<e;t++){var i=this.m_IntersectList[t];this.IntersectEdges(i.Edge1,i.Edge2,i.Pt),this.SwapPositionsInAEL(i.Edge1,i.Edge2)}this.m_IntersectList.length=0}static TopX(t,e){return e===t.Top.Y?t.Top.X:t.Bot.X+t.Dx*(e-t.Bot.Y)}IntersectPoint(e,i,r){var s,n;if(r.X=0,r.Y=0,e.Dx===i.Dx)return r.Y=e.Curr.Y,void(r.X=t.Clipper.TopX(e,r.Y));if(0===e.Delta.X)r.X=e.Bot.X,t.ClipperBase.IsHorizontal(i)?r.Y=i.Bot.Y:(n=i.Bot.Y-i.Bot.X/i.Dx,r.Y=r.X/i.Dx+n);else if(0===i.Delta.X)r.X=i.Bot.X,t.ClipperBase.IsHorizontal(e)?r.Y=e.Bot.Y:(s=e.Bot.Y-e.Bot.X/e.Dx,r.Y=r.X/e.Dx+s);else{s=e.Bot.X-e.Bot.Y*e.Dx;var o=((n=i.Bot.X-i.Bot.Y*i.Dx)-s)/(e.Dx-i.Dx);r.Y=o,Math.abs(e.Dx)<Math.abs(i.Dx)?r.X=e.Dx*o+s:r.X=i.Dx*o+n}if(r.Y<e.Top.Y||r.Y<i.Top.Y){if(e.Top.Y>i.Top.Y)return r.Y=e.Top.Y,r.X=t.Clipper.TopX(i,e.Top.Y),r.X<e.Top.X;r.Y=i.Top.Y,Math.abs(e.Dx)<Math.abs(i.Dx)?r.X=t.Clipper.TopX(e,r.Y):r.X=t.Clipper.TopX(i,r.Y)}r.Y>e.Curr.Y&&(r.Y=e.Curr.Y,Math.abs(e.Dx)>Math.abs(i.Dx)?r.X=t.Clipper.TopX(i,r.Y):r.X=t.Clipper.TopX(e,r.Y))}ProcessEdgesAtTopOfScanbeam(e){for(var i=this.m_ActiveEdges;null!==i;){var r=this.IsMaxima(i,e);if(r){var s=this.GetMaximaPairEx(i);r=null===s||!t.ClipperBase.IsHorizontal(s)}if(r){this.StrictlySimple&&this.InsertMaxima(i.Top.X);var n=i.PrevInAEL;this.DoMaxima(i),i=null===n?this.m_ActiveEdges:n.NextInAEL}else{if(this.IsIntermediate(i,e)&&t.ClipperBase.IsHorizontal(i.NextInLML)?((i=this.UpdateEdgeIntoAEL(i)).OutIdx>=0&&this.AddOutPt(i,i.Bot),this.AddEdgeToSEL(i)):(i.Curr.X=t.Clipper.TopX(i,e),i.Curr.Y=e),this.StrictlySimple){n=i.PrevInAEL;if(i.OutIdx>=0&&0!==i.WindDelta&&null!==n&&n.OutIdx>=0&&n.Curr.X===i.Curr.X&&0!==n.WindDelta){var o=new t.FPoint(i.Curr),a=this.AddOutPt(n,o),l=this.AddOutPt(i,o);this.AddJoin(a,l,o)}}i=i.NextInAEL}}for(this.ProcessHorizontals(),this.m_Maxima=null,i=this.m_ActiveEdges;null!==i;){if(this.IsIntermediate(i,e)){a=null;i.OutIdx>=0&&(a=this.AddOutPt(i,i.Top));n=(i=this.UpdateEdgeIntoAEL(i)).PrevInAEL;var h=i.NextInAEL;if(null!==n&&n.Curr.X===i.Bot.X&&n.Curr.Y===i.Bot.Y&&null!==a&&n.OutIdx>=0&&n.Curr.Y===n.Top.Y&&t.ClipperBase.SlopesEqual5(i.Curr,i.Top,n.Curr,n.Top)&&0!==i.WindDelta&&0!==n.WindDelta){l=this.AddOutPt(n,i.Bot);this.AddJoin(a,l,i.Top)}else if(null!==h&&h.Curr.X===i.Bot.X&&h.Curr.Y===i.Bot.Y&&null!==a&&h.OutIdx>=0&&h.Curr.Y===h.Top.Y&&t.ClipperBase.SlopesEqual5(i.Curr,i.Top,h.Curr,h.Top)&&0!==i.WindDelta&&0!==h.WindDelta){l=this.AddOutPt(h,i.Bot);this.AddJoin(a,l,i.Top)}}i=i.NextInAEL}}DoMaxima(e){var i=this.GetMaximaPairEx(e);if(null===i)return e.OutIdx>=0&&this.AddOutPt(e,e.Top),void this.DeleteFromAEL(e);for(var r=e.NextInAEL;null!==r&&r!==i;)this.IntersectEdges(e,r,e.Top),this.SwapPositionsInAEL(e,r),r=e.NextInAEL;-1===e.OutIdx&&-1===i.OutIdx?(this.DeleteFromAEL(e),this.DeleteFromAEL(i)):e.OutIdx>=0&&i.OutIdx>=0?(e.OutIdx>=0&&this.AddLocalMaxPoly(e,i,e.Top),this.DeleteFromAEL(e),this.DeleteFromAEL(i)):t.use_lines&&0===e.WindDelta?(e.OutIdx>=0&&(this.AddOutPt(e,e.Top),e.OutIdx=t.ClipperBase.Unassigned),this.DeleteFromAEL(e),i.OutIdx>=0&&(this.AddOutPt(i,e.Top),i.OutIdx=t.ClipperBase.Unassigned),this.DeleteFromAEL(i)):t.Error("DoMaxima error")}static ReversePaths(t){for(var e=0,i=t.length;e<i;e++)t[e].reverse()}static Orientation(e){return t.Clipper.Area(e)>=0}PointCount(t){if(null===t)return 0;var e=0,i=t;do{e++,i=i.Next}while(i!==t);return e}BuildResult(e){t.Clear(e);for(var i=0,r=this.m_PolyOuts.length;i<r;i++){var s=this.m_PolyOuts[i];if(null!==s.Pts){var n=s.Pts.Prev,o=this.PointCount(n);if(!(o<2)){for(var a=new Array(o),l=0;l<o;l++)a[l]=n.Pt,n=n.Prev;e.push(a)}}}}BuildResult2(e){e.Clear();for(var i=0,r=this.m_PolyOuts.length;i<r;i++){var s=this.m_PolyOuts[i],n=this.PointCount(s.Pts);if(!(s.IsOpen&&n<2||!s.IsOpen&&n<3)){this.FixHoleLinkage(s);var o=new t.PolyNode;e.m_AllPolys.push(o),s.PolyNode=o,o.m_polygon.length=n;for(var a=s.Pts.Prev,l=0;l<n;l++)o.m_polygon[l]=a.Pt,a=a.Prev}}for(i=0,r=this.m_PolyOuts.length;i<r;i++){null!==(s=this.m_PolyOuts[i]).PolyNode&&(s.IsOpen?(s.PolyNode.IsOpen=!0,e.AddChild(s.PolyNode)):null!==s.FirstLeft&&null!==s.FirstLeft.PolyNode?s.FirstLeft.PolyNode.AddChild(s.PolyNode):e.AddChild(s.PolyNode))}}FixupOutPolyline(e){for(var i=e.Pts,r=i.Prev;i!==r;)if(i=i.Next,t.FPoint.op_Equality(i.Pt,i.Prev.Pt)){i===r&&(r=i.Prev);var s=i.Prev;s.Next=i.Next,i.Next.Prev=s,i=s}i===i.Prev&&(e.Pts=null)}FixupOutPolygon(e){var i=null;e.BottomPt=null;for(var r=e.Pts,s=this.PreserveCollinear||this.StrictlySimple;;){if(r.Prev===r||r.Prev===r.Next)return void(e.Pts=null);if(t.FPoint.op_Equality(r.Pt,r.Next.Pt)||t.FPoint.op_Equality(r.Pt,r.Prev.Pt)||t.ClipperBase.SlopesEqual4(r.Prev.Pt,r.Pt,r.Next.Pt)&&(!s||!this.Pt2IsBetweenPt1AndPt3(r.Prev.Pt,r.Pt,r.Next.Pt)))i=null,r.Prev.Next=r.Next,r.Next.Prev=r.Prev,r=r.Prev;else{if(r===i)break;null===i&&(i=r),r=r.Next}}e.Pts=r}DupOutPt(e,i){var r=new t.OutPt;return r.Pt.X=e.Pt.X,r.Pt.Y=e.Pt.Y,r.Idx=e.Idx,i?(r.Next=e.Next,r.Prev=e,e.Next.Prev=r,e.Next=r):(r.Prev=e.Prev,r.Next=e,e.Prev.Next=r,e.Prev=r),r}GetOverlap(t,e,i,r,s){return t<e?i<r?(s.Left=Math.max(t,i),s.Right=Math.min(e,r)):(s.Left=Math.max(t,r),s.Right=Math.min(e,i)):i<r?(s.Left=Math.max(e,i),s.Right=Math.min(t,r)):(s.Left=Math.max(e,r),s.Right=Math.min(t,i)),s.Left<s.Right}JoinHorz(e,i,r,s,n,o){var a=e.Pt.X>i.Pt.X?0:1,l=r.Pt.X>s.Pt.X?0:1;if(a===l)return!1;if(1===a){for(;e.Next.Pt.X<=n.X&&e.Next.Pt.X>=e.Pt.X&&e.Next.Pt.Y===n.Y;)e=e.Next;o&&e.Pt.X!==n.X&&(e=e.Next),i=this.DupOutPt(e,!o),t.FPoint.op_Inequality(i.Pt,n)&&((e=i).Pt.X=n.X,e.Pt.Y=n.Y,i=this.DupOutPt(e,!o))}else{for(;e.Next.Pt.X>=n.X&&e.Next.Pt.X<=e.Pt.X&&e.Next.Pt.Y===n.Y;)e=e.Next;o||e.Pt.X===n.X||(e=e.Next),i=this.DupOutPt(e,o),t.FPoint.op_Inequality(i.Pt,n)&&((e=i).Pt.X=n.X,e.Pt.Y=n.Y,i=this.DupOutPt(e,o))}if(1===l){for(;r.Next.Pt.X<=n.X&&r.Next.Pt.X>=r.Pt.X&&r.Next.Pt.Y===n.Y;)r=r.Next;o&&r.Pt.X!==n.X&&(r=r.Next),s=this.DupOutPt(r,!o),t.FPoint.op_Inequality(s.Pt,n)&&((r=s).Pt.X=n.X,r.Pt.Y=n.Y,s=this.DupOutPt(r,!o))}else{for(;r.Next.Pt.X>=n.X&&r.Next.Pt.X<=r.Pt.X&&r.Next.Pt.Y===n.Y;)r=r.Next;o||r.Pt.X===n.X||(r=r.Next),s=this.DupOutPt(r,o),t.FPoint.op_Inequality(s.Pt,n)&&((r=s).Pt.X=n.X,r.Pt.Y=n.Y,s=this.DupOutPt(r,o))}return 1===a===o?(e.Prev=r,r.Next=e,i.Next=s,s.Prev=i):(e.Next=r,r.Prev=e,i.Prev=s,s.Next=i),!0}JoinPoints(e,i,r){var s=e.OutPt1,n=new t.OutPt,o=e.OutPt2,a=new t.OutPt,l=e.OutPt1.Pt.Y===e.OffPt.Y;if(l&&t.FPoint.op_Equality(e.OffPt,e.OutPt1.Pt)&&t.FPoint.op_Equality(e.OffPt,e.OutPt2.Pt)){if(i!==r)return!1;for(n=e.OutPt1.Next;n!==s&&t.FPoint.op_Equality(n.Pt,e.OffPt);)n=n.Next;var h=n.Pt.Y>e.OffPt.Y;for(a=e.OutPt2.Next;a!==o&&t.FPoint.op_Equality(a.Pt,e.OffPt);)a=a.Next;return h!==a.Pt.Y>e.OffPt.Y&&(h?(n=this.DupOutPt(s,!1),a=this.DupOutPt(o,!0),s.Prev=o,o.Next=s,n.Next=a,a.Prev=n,e.OutPt1=s,e.OutPt2=n,!0):(n=this.DupOutPt(s,!0),a=this.DupOutPt(o,!1),s.Next=o,o.Prev=s,n.Prev=a,a.Next=n,e.OutPt1=s,e.OutPt2=n,!0))}if(l){for(n=s;s.Prev.Pt.Y===s.Pt.Y&&s.Prev!==n&&s.Prev!==o;)s=s.Prev;for(;n.Next.Pt.Y===n.Pt.Y&&n.Next!==s&&n.Next!==o;)n=n.Next;if(n.Next===s||n.Next===o)return!1;for(a=o;o.Prev.Pt.Y===o.Pt.Y&&o.Prev!==a&&o.Prev!==n;)o=o.Prev;for(;a.Next.Pt.Y===a.Pt.Y&&a.Next!==o&&a.Next!==s;)a=a.Next;if(a.Next===o||a.Next===s)return!1;var u={Left:null,Right:null};if(!this.GetOverlap(s.Pt.X,n.Pt.X,o.Pt.X,a.Pt.X,u))return!1;var c,d=u.Left,p=u.Right,f=new t.FPoint;return s.Pt.X>=d&&s.Pt.X<=p?(f.X=s.Pt.X,f.Y=s.Pt.Y,c=s.Pt.X>n.Pt.X):o.Pt.X>=d&&o.Pt.X<=p?(f.X=o.Pt.X,f.Y=o.Pt.Y,c=o.Pt.X>a.Pt.X):n.Pt.X>=d&&n.Pt.X<=p?(f.X=n.Pt.X,f.Y=n.Pt.Y,c=n.Pt.X>s.Pt.X):(f.X=a.Pt.X,f.Y=a.Pt.Y,c=a.Pt.X>o.Pt.X),e.OutPt1=s,e.OutPt2=o,this.JoinHorz(s,n,o,a,f,c)}for(n=s.Next;t.FPoint.op_Equality(n.Pt,s.Pt)&&n!==s;)n=n.Next;var m=n.Pt.Y>s.Pt.Y||!t.ClipperBase.SlopesEqual4(s.Pt,n.Pt,e.OffPt);if(m){for(n=s.Prev;t.FPoint.op_Equality(n.Pt,s.Pt)&&n!==s;)n=n.Prev;if(n.Pt.Y>s.Pt.Y||!t.ClipperBase.SlopesEqual4(s.Pt,n.Pt,e.OffPt))return!1}for(a=o.Next;t.FPoint.op_Equality(a.Pt,o.Pt)&&a!==o;)a=a.Next;var g=a.Pt.Y>o.Pt.Y||!t.ClipperBase.SlopesEqual4(o.Pt,a.Pt,e.OffPt);if(g){for(a=o.Prev;t.FPoint.op_Equality(a.Pt,o.Pt)&&a!==o;)a=a.Prev;if(a.Pt.Y>o.Pt.Y||!t.ClipperBase.SlopesEqual4(o.Pt,a.Pt,e.OffPt))return!1}return n!==s&&a!==o&&n!==a&&(i!==r||m!==g)&&(m?(n=this.DupOutPt(s,!1),a=this.DupOutPt(o,!0),s.Prev=o,o.Next=s,n.Next=a,a.Prev=n,e.OutPt1=s,e.OutPt2=n,!0):(n=this.DupOutPt(s,!0),a=this.DupOutPt(o,!1),s.Next=o,o.Prev=s,n.Prev=a,a.Next=n,e.OutPt1=s,e.OutPt2=n,!0))}static GetBounds(e){for(var i=0,r=e.length;i<r&&0===e[i].length;)i++;if(i===r)return new t.FRect(0,0,0,0);var s=new t.FRect;for(s.left=e[i][0].X,s.right=s.left,s.top=e[i][0].Y,s.bottom=s.top;i<r;i++)for(var n=0,o=e[i].length;n<o;n++)e[i][n].X<s.left?s.left=e[i][n].X:e[i][n].X>s.right&&(s.right=e[i][n].X),e[i][n].Y<s.top?s.top=e[i][n].Y:e[i][n].Y>s.bottom&&(s.bottom=e[i][n].Y);return s}GetBounds2(e){var i=e,r=new t.FRect;for(r.left=e.Pt.X,r.right=e.Pt.X,r.top=e.Pt.Y,r.bottom=e.Pt.Y,e=e.Next;e!==i;)e.Pt.X<r.left&&(r.left=e.Pt.X),e.Pt.X>r.right&&(r.right=e.Pt.X),e.Pt.Y<r.top&&(r.top=e.Pt.Y),e.Pt.Y>r.bottom&&(r.bottom=e.Pt.Y),e=e.Next;return r}static PointInPolygon(t,e){var i=0,r=e.length;if(r<3)return 0;for(var s=e[0],n=1;n<=r;++n){var o=n===r?e[0]:e[n];if(o.Y===t.Y&&(o.X===t.X||s.Y===t.Y&&o.X>t.X==s.X<t.X))return-1;if(s.Y<t.Y!=o.Y<t.Y)if(s.X>=t.X)if(o.X>t.X)i=1-i;else{if(0===(a=(s.X-t.X)*(o.Y-t.Y)-(o.X-t.X)*(s.Y-t.Y)))return-1;a>0==o.Y>s.Y&&(i=1-i)}else if(o.X>t.X){var a;if(0===(a=(s.X-t.X)*(o.Y-t.Y)-(o.X-t.X)*(s.Y-t.Y)))return-1;a>0==o.Y>s.Y&&(i=1-i)}s=o}return i}PointInPolygon(t,e){var i=0,r=e,s=t.X,n=t.Y,o=e.Pt.X,a=e.Pt.Y;do{var l=(e=e.Next).Pt.X,h=e.Pt.Y;if(h===n&&(l===s||a===n&&l>s==o<s))return-1;if(a<n!=h<n)if(o>=s)if(l>s)i=1-i;else{if(0===(u=(o-s)*(h-n)-(l-s)*(a-n)))return-1;u>0==h>a&&(i=1-i)}else if(l>s){var u;if(0===(u=(o-s)*(h-n)-(l-s)*(a-n)))return-1;u>0==h>a&&(i=1-i)}o=l,a=h}while(r!==e);return i}Poly2ContainsPoly1(t,e){var i=t;do{var r=this.PointInPolygon(i.Pt,e);if(r>=0)return r>0;i=i.Next}while(i!==t);return!0}FixupFirstLefts1(e,i){for(var r,s,n=0,o=this.m_PolyOuts.length;n<o;n++)r=this.m_PolyOuts[n],s=t.Clipper.ParseFirstLeft(r.FirstLeft),null!==r.Pts&&s===e&&this.Poly2ContainsPoly1(r.Pts,i.Pts)&&(r.FirstLeft=i)}FixupFirstLefts2(e,i){for(var r,s,n=i.FirstLeft,o=0,a=this.m_PolyOuts.length;o<a;o++)null!==(r=this.m_PolyOuts[o]).Pts&&r!==i&&r!==e&&((s=t.Clipper.ParseFirstLeft(r.FirstLeft))!==n&&s!==e&&s!==i||(this.Poly2ContainsPoly1(r.Pts,e.Pts)?r.FirstLeft=e:this.Poly2ContainsPoly1(r.Pts,i.Pts)?r.FirstLeft=i:r.FirstLeft!==e&&r.FirstLeft!==i||(r.FirstLeft=n)))}FixupFirstLefts3(e,i){for(var r,s,n=0,o=this.m_PolyOuts.length;n<o;n++)r=this.m_PolyOuts[n],s=t.Clipper.ParseFirstLeft(r.FirstLeft),null!==r.Pts&&s===e&&(r.FirstLeft=i)}static ParseFirstLeft(t){for(;null!==t&&null===t.Pts;)t=t.FirstLeft;return t}JoinCommonEdges(){for(var t=0,e=this.m_Joins.length;t<e;t++){var i,r=this.m_Joins[t],s=this.GetOutRec(r.OutPt1.Idx),n=this.GetOutRec(r.OutPt2.Idx);if(null!==s.Pts&&null!==n.Pts)if(!s.IsOpen&&!n.IsOpen)i=s===n?s:this.OutRec1RightOfOutRec2(s,n)?n:this.OutRec1RightOfOutRec2(n,s)?s:this.GetLowermostRec(s,n),this.JoinPoints(r,s,n)&&(s===n?(s.Pts=r.OutPt1,s.BottomPt=null,(n=this.CreateOutRec()).Pts=r.OutPt2,this.UpdateOutPtIdxs(n),this.Poly2ContainsPoly1(n.Pts,s.Pts)?(n.IsHole=!s.IsHole,n.FirstLeft=s,this.m_UsingPolyTree&&this.FixupFirstLefts2(n,s),(n.IsHole^this.ReverseSolution)==this.Area$1(n)>0&&this.ReversePolyPtLinks(n.Pts)):this.Poly2ContainsPoly1(s.Pts,n.Pts)?(n.IsHole=s.IsHole,s.IsHole=!n.IsHole,n.FirstLeft=s.FirstLeft,s.FirstLeft=n,this.m_UsingPolyTree&&this.FixupFirstLefts2(s,n),(s.IsHole^this.ReverseSolution)==this.Area$1(s)>0&&this.ReversePolyPtLinks(s.Pts)):(n.IsHole=s.IsHole,n.FirstLeft=s.FirstLeft,this.m_UsingPolyTree&&this.FixupFirstLefts1(s,n))):(n.Pts=null,n.BottomPt=null,n.Idx=s.Idx,s.IsHole=i.IsHole,i===n&&(s.FirstLeft=n.FirstLeft),n.FirstLeft=s,this.m_UsingPolyTree&&this.FixupFirstLefts3(n,s)))}}UpdateOutPtIdxs(t){var e=t.Pts;do{e.Idx=t.Idx,e=e.Prev}while(e!==t.Pts)}DoSimplePolygons(){for(var e=0;e<this.m_PolyOuts.length;){var i=this.m_PolyOuts[e++],r=i.Pts;if(null!==r&&!i.IsOpen)do{for(var s=r.Next;s!==i.Pts;){if(t.FPoint.op_Equality(r.Pt,s.Pt)&&s.Next!==r&&s.Prev!==r){var n=r.Prev,o=s.Prev;r.Prev=o,o.Next=r,s.Prev=n,n.Next=s,i.Pts=r;var a=this.CreateOutRec();a.Pts=s,this.UpdateOutPtIdxs(a),this.Poly2ContainsPoly1(a.Pts,i.Pts)?(a.IsHole=!i.IsHole,a.FirstLeft=i,this.m_UsingPolyTree&&this.FixupFirstLefts2(a,i)):this.Poly2ContainsPoly1(i.Pts,a.Pts)?(a.IsHole=i.IsHole,i.IsHole=!a.IsHole,a.FirstLeft=i.FirstLeft,i.FirstLeft=a,this.m_UsingPolyTree&&this.FixupFirstLefts2(i,a)):(a.IsHole=i.IsHole,a.FirstLeft=i.FirstLeft,this.m_UsingPolyTree&&this.FixupFirstLefts1(i,a)),s=r}s=s.Next}r=r.Next}while(r!==i.Pts)}}static Area(t){if(!Array.isArray(t))return 0;var e=t.length;if(e<3)return 0;for(var i=0,r=0,s=e-1;r<e;++r)i+=(t[s].X+t[r].X)*(t[s].Y-t[r].Y),s=r;return.5*-i}Area(t){var e=t;if(null===t)return 0;var i=0;do{i+=(t.Prev.Pt.X+t.Pt.X)*(t.Prev.Pt.Y-t.Pt.Y),t=t.Next}while(t!==e);return.5*i}Area$1(t){return this.Area(t.Pts)}static SimplifyPolygon(e,i){var r=new Array,s=new t.Clipper(0);return s.StrictlySimple=!0,s.AddPath(e,0,!0),s.Execute(1,r,i,i),r}static SimplifyPolygons(e,i){void 0===i&&(i=0);var r=new Array,s=new t.Clipper(0);return s.StrictlySimple=!0,s.AddPaths(e,0,!0),s.Execute(1,r,i,i),r}static DistanceSqrd(t,e){var i=t.X-e.X,r=t.Y-e.Y;return i*i+r*r}static DistanceFromLineSqrd(t,e,i){var r=e.Y-i.Y,s=i.X-e.X,n=r*e.X+s*e.Y;return(n=r*t.X+s*t.Y-n)*n/(r*r+s*s)}static SlopesNearCollinear(e,i,r,s){return Math.abs(e.X-i.X)>Math.abs(e.Y-i.Y)?e.X>i.X==e.X<r.X?t.Clipper.DistanceFromLineSqrd(e,i,r)<s:i.X>e.X==i.X<r.X?t.Clipper.DistanceFromLineSqrd(i,e,r)<s:t.Clipper.DistanceFromLineSqrd(r,e,i)<s:e.Y>i.Y==e.Y<r.Y?t.Clipper.DistanceFromLineSqrd(e,i,r)<s:i.Y>e.Y==i.Y<r.Y?t.Clipper.DistanceFromLineSqrd(i,e,r)<s:t.Clipper.DistanceFromLineSqrd(r,e,i)<s}static PointsAreClose(t,e,i){var r=t.X-e.X,s=t.Y-e.Y;return r*r+s*s<=i}static ExcludeOp(t){var e=t.Prev;return e.Next=t.Next,t.Next.Prev=e,e.Idx=0,e}static CleanPolygon(e,i){void 0===i&&(i=1.415);var r=e.length;if(0===r)return new Array;for(var s=new Array(r),n=0;n<r;++n)s[n]=new t.OutPt;for(n=0;n<r;++n)s[n].Pt=e[n],s[n].Next=s[(n+1)%r],s[n].Next.Prev=s[n],s[n].Idx=0;for(var o=i*i,a=s[0];0===a.Idx&&a.Next!==a.Prev;)t.Clipper.PointsAreClose(a.Pt,a.Prev.Pt,o)?(a=t.Clipper.ExcludeOp(a),r--):t.Clipper.PointsAreClose(a.Prev.Pt,a.Next.Pt,o)?(t.Clipper.ExcludeOp(a.Next),a=t.Clipper.ExcludeOp(a),r-=2):t.Clipper.SlopesNearCollinear(a.Prev.Pt,a.Pt,a.Next.Pt,o)?(a=t.Clipper.ExcludeOp(a),r--):(a.Idx=1,a=a.Next);r<3&&(r=0);var l=new Array(r);for(n=0;n<r;++n)l[n]=new t.FPoint(a.Pt),a=a.Next;return s=null,l}static CleanPolygons(e,i){for(var r=new Array(e.length),s=0,n=e.length;s<n;s++)r[s]=t.Clipper.CleanPolygon(e[s],i);return r}static Minkowski(e,i,r,s){var n=s?1:0,o=e.length,a=i.length,l=new Array;if(r)for(var h=0;h<a;h++){for(var u=new Array(o),c=0,d=e.length,p=e[c];c<d;p=e[++c])u[c]=new t.FPoint(i[h].X+p.X,i[h].Y+p.Y);l.push(u)}else for(h=0;h<a;h++){for(u=new Array(o),c=0,d=e.length,p=e[c];c<d;p=e[++c])u[c]=new t.FPoint(i[h].X-p.X,i[h].Y-p.Y);l.push(u)}var f=new Array;for(h=0;h<a-1+n;h++)for(c=0;c<o;c++){var m=new Array;m.push(l[h%a][c%o]),m.push(l[(h+1)%a][c%o]),m.push(l[(h+1)%a][(c+1)%o]),m.push(l[h%a][(c+1)%o]),t.Clipper.Orientation(m)||m.reverse(),f.push(m)}return f}static MinkowskiSum(e,i,r){if(i[0]instanceof Array){let l=i;for(var s=[],n=(a=new t.Clipper,0);n<l.length;++n){var o=t.Clipper.Minkowski(e,l[n],!0,r);if(a.AddPaths(o,0,!0),r){let i=t.Clipper.TranslatePath(l[n],e[0]);a.AddPath(i,1,!0)}}return a.Execute(1,s,1,1),s}{let s=i,n=t.Clipper.Minkowski(e,s,!0,r);var a;return(a=new t.Clipper).AddPaths(n,0,!0),a.Execute(1,n,1,1),n}}static TranslatePath(e,i){for(var r=[],s=0;s<e.length;s++)r.push(new t.FPoint(e[s].X+i.X,e[s].Y+i.Y));return r}static MinkowskiDiff(e,i){var r=t.Clipper.Minkowski(e,i,!1,!0),s=new t.Clipper;return s.AddPaths(r,0,!0),s.Execute(1,r,1,1),r}static PolyTreeToPaths(e){var i=new Array;return t.Clipper.AddPolyNodeToPaths(e,0,i),i}static AddPolyNodeToPaths(e,i,r){var s=!0;switch(i){case 1:return;case 2:s=!e.IsOpen}e.m_polygon.length>0&&s&&r.push(e.m_polygon);for(var n=0,o=e.Children(),a=o.length,l=o[n];n<a;l=o[++n])t.Clipper.AddPolyNodeToPaths(l,i,r)}static OpenPathsFromPolyTree(t){for(var e=[],i=0,r=t.ChildCount();i<r;i++)t.Children()[i].IsOpen&&e.push(t.Children()[i].m_polygon);return e}static ClosedPathsFromPolyTree(e){var i=[];return t.Clipper.AddPolyNodeToPaths(e,2,i),i}};t.ClipperOffset=class{m_destPolys=[];m_srcPoly=[];m_destPoly=[];m_normals=new Array;m_delta=0;m_sinA=0;m_sin=0;m_cos=0;m_miterLim=0;m_StepsPerRad=0;m_lowest=new t.FPoint;m_polyNodes=new t.PolyNode;MiterLimit;ArcTolerance;constructor(e,i){void 0===e&&(e=2),void 0===i&&(i=t.ClipperOffset.def_arc_tolerance),this.MiterLimit=e,this.ArcTolerance=i,this.m_lowest.X=-1}static two_pi=6.28318530717959;static def_arc_tolerance=.25;Clear(){t.Clear(this.m_polyNodes.Children()),this.m_lowest.X=-1}AddPath(e,i,r){var s=e.length-1;if(!(s<0)){var n=new t.PolyNode;if(n.m_jointype=i,n.m_endtype=r,3===r||4===r)for(;s>0&&t.FPoint.op_Equality(e[0],e[s]);)s--;n.m_polygon.push(e[0]);for(var o=0,a=0,l=1;l<=s;l++)t.FPoint.op_Inequality(n.m_polygon[o],e[l])&&(o++,n.m_polygon.push(e[l]),(e[l].Y>n.m_polygon[a].Y||e[l].Y===n.m_polygon[a].Y&&e[l].X<n.m_polygon[a].X)&&(a=o));if(!(4===r&&o<2)&&(this.m_polyNodes.AddChild(n),4===r))if(this.m_lowest.X<0)this.m_lowest=new t.FPoint(this.m_polyNodes.ChildCount()-1,a);else{var h=this.m_polyNodes.Children()[this.m_lowest.X].m_polygon[this.m_lowest.Y];(n.m_polygon[a].Y>h.Y||n.m_polygon[a].Y===h.Y&&n.m_polygon[a].X<h.X)&&(this.m_lowest=new t.FPoint(this.m_polyNodes.ChildCount()-1,a))}}}AddPaths(t,e,i){for(var r=0,s=t.length;r<s;r++)this.AddPath(t[r],e,i)}FixOrientations(){if(this.m_lowest.X>=0&&!t.Clipper.Orientation(this.m_polyNodes.Children()[this.m_lowest.X].m_polygon))for(var e=0;e<this.m_polyNodes.ChildCount();e++){(4===(i=this.m_polyNodes.Children()[e]).m_endtype||3===i.m_endtype&&t.Clipper.Orientation(i.m_polygon))&&i.m_polygon.reverse()}else for(e=0;e<this.m_polyNodes.ChildCount();e++){var i;3!==(i=this.m_polyNodes.Children()[e]).m_endtype||t.Clipper.Orientation(i.m_polygon)||i.m_polygon.reverse()}}static GetUnitNormal(e,i){var r=i.X-e.X,s=i.Y-e.Y;if(0===r&&0===s)return new t.FPoint(0,0);var n=1/Math.sqrt(r*r+s*s);return r*=n,s*=n,new t.FPoint(s,-r)}DoOffset(e){if(this.m_destPolys=new Array,this.m_delta=e,t.ClipperBase.near_zero(e))for(var i=0;i<this.m_polyNodes.ChildCount();i++){4===(n=this.m_polyNodes.Children()[i]).m_endtype&&this.m_destPolys.push(n.m_polygon)}else{var r;this.MiterLimit>2?this.m_miterLim=2/(this.MiterLimit*this.MiterLimit):this.m_miterLim=.5,r=this.ArcTolerance<=0?t.ClipperOffset.def_arc_tolerance:this.ArcTolerance>Math.abs(e)*t.ClipperOffset.def_arc_tolerance?Math.abs(e)*t.ClipperOffset.def_arc_tolerance:this.ArcTolerance;var s=3.14159265358979/Math.acos(1-r/Math.abs(e));this.m_sin=Math.sin(t.ClipperOffset.two_pi/s),this.m_cos=Math.cos(t.ClipperOffset.two_pi/s),this.m_StepsPerRad=s/t.ClipperOffset.two_pi,e<0&&(this.m_sin=-this.m_sin);for(i=0;i<this.m_polyNodes.ChildCount();i++){var n=this.m_polyNodes.Children()[i];this.m_srcPoly=n.m_polygon;var o=this.m_srcPoly.length;if(!(0===o||e<=0&&(o<3||4!==n.m_endtype)))if(this.m_destPoly=new Array,1!==o){this.m_normals.length=0;for(d=0;d<o-1;d++)this.m_normals.push(t.ClipperOffset.GetUnitNormal(this.m_srcPoly[d],this.m_srcPoly[d+1]));if(3===n.m_endtype||4===n.m_endtype?this.m_normals.push(t.ClipperOffset.GetUnitNormal(this.m_srcPoly[o-1],this.m_srcPoly[0])):this.m_normals.push(new t.FPoint(this.m_normals[o-2])),4===n.m_endtype){var a=o-1;for(d=0;d<o;d++)a=this.OffsetPoint(d,a,n.m_jointype);this.m_destPolys.push(this.m_destPoly)}else if(3===n.m_endtype){for(a=o-1,d=0;d<o;d++)a=this.OffsetPoint(d,a,n.m_jointype);this.m_destPolys.push(this.m_destPoly),this.m_destPoly=new Array;var l=this.m_normals[o-1];for(d=o-1;d>0;d--)this.m_normals[d]=new t.FPoint(-this.m_normals[d-1].X,-this.m_normals[d-1].Y);this.m_normals[0]=new t.FPoint(-l.X,-l.Y),a=0;for(d=o-1;d>=0;d--)a=this.OffsetPoint(d,a,n.m_jointype);this.m_destPolys.push(this.m_destPoly)}else{var h;for(a=0,d=1;d<o-1;++d)a=this.OffsetPoint(d,a,n.m_jointype);if(2===n.m_endtype){d=o-1;h=new t.FPoint(this.m_srcPoly[d].X+this.m_normals[d].X*e,this.m_srcPoly[d].Y+this.m_normals[d].Y*e),this.m_destPoly.push(h),h=new t.FPoint(this.m_srcPoly[d].X-this.m_normals[d].X*e,this.m_srcPoly[d].Y-this.m_normals[d].Y*e),this.m_destPoly.push(h)}else{d=o-1;a=o-2,this.m_sinA=0,this.m_normals[d]=new t.FPoint(-this.m_normals[d].X,-this.m_normals[d].Y),0===n.m_endtype?this.DoSquare(d,a):this.DoRound(d,a)}for(d=o-1;d>0;d--)this.m_normals[d]=new t.FPoint(-this.m_normals[d-1].X,-this.m_normals[d-1].Y);this.m_normals[0]=new t.FPoint(-this.m_normals[1].X,-this.m_normals[1].Y);for(d=(a=o-1)-1;d>0;--d)a=this.OffsetPoint(d,a,n.m_jointype);2===n.m_endtype?(h=new t.FPoint(this.m_srcPoly[0].X-this.m_normals[0].X*e,this.m_srcPoly[0].Y-this.m_normals[0].Y*e),this.m_destPoly.push(h),h=new t.FPoint(this.m_srcPoly[0].X+this.m_normals[0].X*e,this.m_srcPoly[0].Y+this.m_normals[0].Y*e),this.m_destPoly.push(h)):(a=1,this.m_sinA=0,0===n.m_endtype?this.DoSquare(0,1):this.DoRound(0,1)),this.m_destPolys.push(this.m_destPoly)}}else{if(1===n.m_jointype)for(var u=1,c=0,d=1;d<=s;d++){this.m_destPoly.push(new t.FPoint(this.m_srcPoly[0].X+u*e,this.m_srcPoly[0].Y+c*e));var p=u;u=u*this.m_cos-this.m_sin*c,c=p*this.m_sin+c*this.m_cos}else{u=-1,c=-1;for(var d=0;d<4;++d)this.m_destPoly.push(new t.FPoint(this.m_srcPoly[0].X+u*e,this.m_srcPoly[0].Y+c*e)),u<0?u=1:c<0?c=1:u=-1}this.m_destPolys.push(this.m_destPoly)}}}}Execute(...e){var i=e;if(i[0]instanceof t.PolyTree){o=i[0],a=i[1];if(o.Clear(),this.FixOrientations(),this.DoOffset(a),(n=new t.Clipper(0)).AddPaths(this.m_destPolys,0,!0),a>0)n.Execute(1,o,2,2);else{h=t.Clipper.GetBounds(this.m_destPolys);if((l=[]).push(new t.FPoint(h.left-10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.top-10)),l.push(new t.FPoint(h.left-10,h.top-10)),n.AddPath(l,0,!0),n.ReverseSolution=!0,n.Execute(1,o,3,3),1===o.ChildCount()&&o.Children()[0].ChildCount()>0){var r=o.Children()[0];o.Children()[0]=r.Children()[0],o.Children()[0].m_Parent=o;for(var s=1;s<r.ChildCount();s++)o.AddChild(r.Children()[s])}else o.Clear()}}else{var n,o=i[0],a=i[1];if(t.Clear(o),this.FixOrientations(),this.DoOffset(a),(n=new t.Clipper(0)).AddPaths(this.m_destPolys,0,!0),a>0)n.Execute(1,o,2,2);else{var l,h=t.Clipper.GetBounds(this.m_destPolys);(l=[]).push(new t.FPoint(h.left-10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.bottom+10)),l.push(new t.FPoint(h.right+10,h.top-10)),l.push(new t.FPoint(h.left-10,h.top-10)),n.AddPath(l,0,!0),n.ReverseSolution=!0,n.Execute(1,o,3,3),o.length>0&&o.splice(0,1)}}}OffsetPoint(e,i,r){if(this.m_sinA=this.m_normals[i].X*this.m_normals[e].Y-this.m_normals[e].X*this.m_normals[i].Y,0===this.m_sinA)return i;if(this.m_sinA>1?this.m_sinA=1:this.m_sinA<-1&&(this.m_sinA=-1),this.m_sinA*this.m_delta<0)this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_normals[i].X*this.m_delta,this.m_srcPoly[e].Y+this.m_normals[i].Y*this.m_delta)),this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e])),this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_normals[e].X*this.m_delta,this.m_srcPoly[e].Y+this.m_normals[e].Y*this.m_delta));else switch(r){case 2:var s=this.m_normals[e].X*this.m_normals[i].X+this.m_normals[e].Y*this.m_normals[i].Y+1;s>=this.m_miterLim?this.DoMiter(e,i,s):this.DoSquare(e,i);break;case 0:this.DoSquare(e,i);break;case 1:this.DoRound(e,i)}return i=e}DoSquare(e,i){var r=Math.tan(Math.atan2(this.m_sinA,this.m_normals[i].X*this.m_normals[e].X+this.m_normals[i].Y*this.m_normals[e].Y)/4);this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_delta*(this.m_normals[i].X-this.m_normals[i].Y*r),this.m_srcPoly[e].Y+this.m_delta*(this.m_normals[i].Y+this.m_normals[i].X*r))),this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_delta*(this.m_normals[e].X+this.m_normals[e].Y*r),this.m_srcPoly[e].Y+this.m_delta*(this.m_normals[e].Y-this.m_normals[e].X*r)))}DoMiter(e,i,r){var s=this.m_delta/r;this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+(this.m_normals[i].X+this.m_normals[e].X)*s,this.m_srcPoly[e].Y+(this.m_normals[i].Y+this.m_normals[e].Y)*s))}DoRound(e,i){for(var r,s=Math.atan2(this.m_sinA,this.m_normals[i].X*this.m_normals[e].X+this.m_normals[i].Y*this.m_normals[e].Y),n=Math.max(Math.round(this.m_StepsPerRad*Math.abs(s)),1),o=this.m_normals[i].X,a=this.m_normals[i].Y,l=0;l<n;++l)this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+o*this.m_delta,this.m_srcPoly[e].Y+a*this.m_delta)),r=o,o=o*this.m_cos-this.m_sin*a,a=r*this.m_sin+a*this.m_cos;this.m_destPoly.push(new t.FPoint(this.m_srcPoly[e].X+this.m_normals[e].X*this.m_delta,this.m_srcPoly[e].Y+this.m_normals[e].Y*this.m_delta))}},t.Error=function(e){throw new t.Error(e)}})(G||(G={}));const X=G;function W(t){let e=et(t),i=X.Clipper.GetBounds(e);return{min:[i.left,-i.bottom],max:[i.right,-i.top]}}function Y(t){if(!t.length)return[];let e=t.filter(t=>t&&t.length>0);if(!e.length)return[];if(1===e.length)return[e[0]];let i=et(e);if(!i.length)return[];let r=[i[0]],s=i.slice(1),n=new X.Clipper;n.AddPaths(r,X.PolyType.ptSubject,!0),n.AddPaths(s,X.PolyType.ptClip,!0);let o=[];return n.Execute(X.ClipType.ctUnion,o,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),it(o)}function H(t,e=0,i=[],r=[],s=[]){for(let n of t.m_Children){if(!n.m_polygon.length)continue;let t=e%2!=0,o=it([n.m_polygon])[0],a={polygon:o,children:[]};i.push(a),t?s.push(o):(s=[o],r.push(s)),H(n,e+1,a.children,r,s)}return r.sort((t,e)=>K(t[0])>K(e[0])?-1:1),{polyTree:i,polygons:r}}function $(t,e=.1,i,r){if(!t.length||!t[0])return[];void 0===i&&(i=X.EndType.etClosedPolygon),e=e&&"number"==typeof e?e:.1;let s=et(t=r?t:Q(t)),n=new X.ClipperOffset(2),o=[];return n.AddPaths(s,X.JoinType.jtMiter,i),n.Execute(o,e),it(o)}function j(t,e=.1,i=X.EndType.etClosedPolygon){if(!t.length||!t[0])return{polygons:[],polyTree:[]};let r=[];for(let o of t)r.push(...et(o));let s=new X.ClipperOffset(2);s.AddPaths(r,X.JoinType.jtMiter,i);let n=new X.PolyTree;return s.Execute(n,e),H(n)}function z(t,e,i){if(!t.length||!t[0])return[];if(!e.length)return t;let r=et(t),s=et(e),n=new X.Clipper;n.AddPaths(r,X.PolyType.ptSubject,!0),n.AddPaths(s,X.PolyType.ptClip,!0);let o=[];return new X.PolyTree,n.Execute(X.ClipType.ctDifference,o,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),it(o)}function V(t,e){if(!t.length||!t[0])return{polygons:[],polyTree:[]};if(!e.length){let e=t.map(t=>[...t]),i=e.map(t=>({polygon:t[0],children:[]}));return{polygons:e,polyTree:i}}let i=[];for(let o=0;o<t.length;o++)i.push(...et(t[o]));let r=[];for(let o=0;o<e.length;o++)r.push(...et(e[o]));let s=new X.Clipper;s.AddPaths(i,X.PolyType.ptSubject,!0),s.AddPaths(r,X.PolyType.ptClip,!0);let n=new X.PolyTree;return s.Execute(X.ClipType.ctDifference,n,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),H(n)}function q(t,e,i=[]){let r=new X.FPoint(t[0],-t[1]),s=et([e])[0],n=X.Clipper.PointInPolygon(r,s);for(let o of i){let e=q(t,o);1===e?n=0:-1===e&&(n=-1)}return n}function J(t){let e=et([t]);return X.Clipper.Area(e[0])}function K(t){return Math.abs(J(t))}function Z(t){let e=Math.abs(J(t[0]));for(let i of t.slice(1))e-=Math.abs(J(i));return e}function Q(t,e=.01){let i=et(t);return it(X.Clipper.CleanPolygons(i,e))}function tt(t,e=.01){return Q([t],e)[0]}function et(t=[]){let e=[],i=0;for(let r=0;r<t.length;r++){let s=t[r];if(!s?.length)continue;let n=new Array(s.length);for(let t=0;t<s.length;t++){let e=s[t];n[t]={X:e[0],Y:-e[1]}}e[i]=n,i++}return e}function it(t){let e=new Array(t.length);for(let i=0;i<t.length;i++){let r=t[i]||[],s=new Array(r.length);for(let t=0;t<r.length;t++){let e=r[t];s[t]=[e.X,-e.Y]}e[i]=s}return e}var rt=1e-6,st="undefined"!=typeof Float32Array?Float32Array:Array;function nt(){var t=new st(16);return st!=Float32Array&&(t[1]=0,t[2]=0,t[3]=0,t[4]=0,t[6]=0,t[7]=0,t[8]=0,t[9]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0),t[0]=1,t[5]=1,t[10]=1,t[15]=1,t}function ot(t,e){return t[0]=e[0],t[1]=e[1],t[2]=e[2],t[3]=e[3],t[4]=e[4],t[5]=e[5],t[6]=e[6],t[7]=e[7],t[8]=e[8],t[9]=e[9],t[10]=e[10],t[11]=e[11],t[12]=e[12],t[13]=e[13],t[14]=e[14],t[15]=e[15],t}function at(t,e){if(t===e){var i=e[1],r=e[2],s=e[3],n=e[6],o=e[7],a=e[11];t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=i,t[6]=e[9],t[7]=e[13],t[8]=r,t[9]=n,t[11]=e[14],t[12]=s,t[13]=o,t[14]=a}else t[0]=e[0],t[1]=e[4],t[2]=e[8],t[3]=e[12],t[4]=e[1],t[5]=e[5],t[6]=e[9],t[7]=e[13],t[8]=e[2],t[9]=e[6],t[10]=e[10],t[11]=e[14],t[12]=e[3],t[13]=e[7],t[14]=e[11],t[15]=e[15];return t}function lt(t,e){var i=e[0],r=e[1],s=e[2],n=e[3],o=e[4],a=e[5],l=e[6],h=e[7],u=e[8],c=e[9],d=e[10],p=e[11],f=e[12],m=e[13],g=e[14],y=e[15],v=i*a-r*o,x=i*l-s*o,b=i*h-n*o,_=r*l-s*a,w=r*h-n*a,P=s*h-n*l,E=u*m-c*f,T=u*g-d*f,A=u*y-p*f,I=c*g-d*m,S=c*y-p*m,C=d*y-p*g,M=v*C-x*S+b*I+_*A-w*T+P*E;return M?(M=1/M,t[0]=(a*C-l*S+h*I)*M,t[1]=(s*S-r*C-n*I)*M,t[2]=(m*P-g*w+y*_)*M,t[3]=(d*w-c*P-p*_)*M,t[4]=(l*A-o*C-h*T)*M,t[5]=(i*C-s*A+n*T)*M,t[6]=(g*b-f*P-y*x)*M,t[7]=(u*P-d*b+p*x)*M,t[8]=(o*S-a*A+h*E)*M,t[9]=(r*A-i*S-n*E)*M,t[10]=(f*w-m*b+y*v)*M,t[11]=(c*b-u*w-p*v)*M,t[12]=(a*T-o*I-l*E)*M,t[13]=(i*I-r*T+s*E)*M,t[14]=(m*x-f*_-g*v)*M,t[15]=(u*_-c*x+d*v)*M,t):null}function ht(t,e,i){var r=e[0],s=e[1],n=e[2],o=e[3],a=e[4],l=e[5],h=e[6],u=e[7],c=e[8],d=e[9],p=e[10],f=e[11],m=e[12],g=e[13],y=e[14],v=e[15],x=i[0],b=i[1],_=i[2],w=i[3];return t[0]=x*r+b*a+_*c+w*m,t[1]=x*s+b*l+_*d+w*g,t[2]=x*n+b*h+_*p+w*y,t[3]=x*o+b*u+_*f+w*v,x=i[4],b=i[5],_=i[6],w=i[7],t[4]=x*r+b*a+_*c+w*m,t[5]=x*s+b*l+_*d+w*g,t[6]=x*n+b*h+_*p+w*y,t[7]=x*o+b*u+_*f+w*v,x=i[8],b=i[9],_=i[10],w=i[11],t[8]=x*r+b*a+_*c+w*m,t[9]=x*s+b*l+_*d+w*g,t[10]=x*n+b*h+_*p+w*y,t[11]=x*o+b*u+_*f+w*v,x=i[12],b=i[13],_=i[14],w=i[15],t[12]=x*r+b*a+_*c+w*m,t[13]=x*s+b*l+_*d+w*g,t[14]=x*n+b*h+_*p+w*y,t[15]=x*o+b*u+_*f+w*v,t}function ut(t,e){return t[0]=e[12],t[1]=e[13],t[2]=e[14],t}function ct(t,e){var i=new st(3);!function(t,e){var i=e[0],r=e[1],s=e[2],n=e[4],o=e[5],a=e[6],l=e[8],h=e[9],u=e[10];t[0]=Math.sqrt(i*i+r*r+s*s),t[1]=Math.sqrt(n*n+o*o+a*a),t[2]=Math.sqrt(l*l+h*h+u*u)}(i,e);var r=1/i[0],s=1/i[1],n=1/i[2],o=e[0]*r,a=e[1]*s,l=e[2]*n,h=e[4]*r,u=e[5]*s,c=e[6]*n,d=e[8]*r,p=e[9]*s,f=e[10]*n,m=o+u+f,g=0;return m>0?(g=2*Math.sqrt(m+1),t[3]=.25*g,t[0]=(c-p)/g,t[1]=(d-l)/g,t[2]=(a-h)/g):o>u&&o>f?(g=2*Math.sqrt(1+o-u-f),t[3]=(c-p)/g,t[0]=.25*g,t[1]=(a+h)/g,t[2]=(d+l)/g):u>f?(g=2*Math.sqrt(1+u-o-f),t[3]=(d-l)/g,t[0]=(a+h)/g,t[1]=.25*g,t[2]=(c+p)/g):(g=2*Math.sqrt(1+f-o-u),t[3]=(a-h)/g,t[0]=(d+l)/g,t[1]=(c+p)/g,t[2]=.25*g),t}function dt(){var t=new st(3);return st!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t}function pt(t){var e=new st(3);return e[0]=t[0],e[1]=t[1],e[2]=t[2],e}function ft(t,e,i){var r=new st(3);return r[0]=t,r[1]=e,r[2]=i,r}function mt(t,e,i,r){return t[0]=e,t[1]=i,t[2]=r,t}function gt(t,e,i){return t[0]=e[0]+i[0],t[1]=e[1]+i[1],t[2]=e[2]+i[2],t}function yt(t,e,i){return t[0]=e[0]-i[0],t[1]=e[1]-i[1],t[2]=e[2]-i[2],t}function vt(t,e){var i=e[0],r=e[1],s=e[2],n=i*i+r*r+s*s;return n>0&&(n=1/Math.sqrt(n)),t[0]=e[0]*n,t[1]=e[1]*n,t[2]=e[2]*n,t}function xt(t,e,i){var r=e[0],s=e[1],n=e[2],o=i[0],a=i[1],l=i[2];return t[0]=s*l-n*a,t[1]=n*o-r*l,t[2]=r*a-s*o,t}function bt(t,e,i){var r=e[0],s=e[1],n=e[2],o=i[3]*r+i[7]*s+i[11]*n+i[15];return o=o||1,t[0]=(i[0]*r+i[4]*s+i[8]*n+i[12])/o,t[1]=(i[1]*r+i[5]*s+i[9]*n+i[13])/o,t[2]=(i[2]*r+i[6]*s+i[10]*n+i[14])/o,t}var _t=yt;function wt(){var t=new st(4);return st!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0),t[3]=1,t}function Pt(t,e,i){i*=.5;var r=Math.sin(i);return t[0]=r*e[0],t[1]=r*e[1],t[2]=r*e[2],t[3]=Math.cos(i),t}dt(),function(){var t,e=(t=new st(4),st!=Float32Array&&(t[0]=0,t[1]=0,t[2]=0,t[3]=0),t)}();var Et;function Tt(){var t=new st(2);return st!=Float32Array&&(t[0]=0,t[1]=0),t}dt(),ft(1,0,0),ft(0,1,0),wt(),wt(),Et=new st(9),st!=Float32Array&&(Et[1]=0,Et[2]=0,Et[3]=0,Et[5]=0,Et[6]=0,Et[7]=0),Et[0]=1,Et[4]=1,Et[8]=1,function(){var t=Tt()}();var At="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function It(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function St(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if("function"==typeof e){var i=function t(){var i=!1;try{i=this instanceof t}catch{}return i?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};i.prototype=e.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(t).forEach(function(e){var r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(i,e,r.get?r:{enumerable:!0,get:function(){return t[e]}})}),i}var Ct,Mt={exports:{}};var Ot=function(){if(Ct)return Mt.exports;function t(t,i,s){s=s||2;var n,o,a,u,c,p,f,m=i&&i.length,g=m?i[0]*s:t.length,y=e(t,0,g,s,!0),v=[];if(!y||y.next===y.prev)return v;if(m&&(y=function(t,i,r,s){var n,o,a,u=[];for(n=0,o=i.length;n<o;n++)(a=e(t,i[n]*s,n<o-1?i[n+1]*s:t.length,s,!1))===a.next&&(a.steiner=!0),u.push(d(a));for(u.sort(l),n=0;n<u.length;n++)r=h(u[n],r);return r}(t,i,y,s)),t.length>80*s){n=a=t[0],o=u=t[1];for(var x=s;x<g;x+=s)(c=t[x])<n&&(n=c),(p=t[x+1])<o&&(o=p),c>a&&(a=c),p>u&&(u=p);f=0!==(f=Math.max(a-n,u-o))?32767/f:0}return r(y,v,s,n,o,f,0),v}function e(t,e,i,r,s){var n,o;if(s===T(t,e,i,r)>0)for(n=e;n<i;n+=r)o=w(n,t[n],t[n+1],o);else for(n=i-r;n>=e;n-=r)o=w(n,t[n],t[n+1],o);return o&&g(o,o.next)&&(P(o),o=o.next),o}function i(t,e){if(!t)return t;e||(e=t);var i,r=t;do{if(i=!1,r.steiner||!g(r,r.next)&&0!==m(r.prev,r,r.next))r=r.next;else{if(P(r),(r=e=r.prev)===r.next)break;i=!0}}while(i||r!==e);return e}function r(t,e,l,h,u,d,p){if(t){!p&&d&&function(t,e,i,r){var s=t;do{0===s.z&&(s.z=c(s.x,s.y,e,i,r)),s.prevZ=s.prev,s.nextZ=s.next,s=s.next}while(s!==t);s.prevZ.nextZ=null,s.prevZ=null,function(t){var e,i,r,s,n,o,a,l,h=1;do{for(i=t,t=null,n=null,o=0;i;){for(o++,r=i,a=0,e=0;e<h&&(a++,r=r.nextZ);e++);for(l=h;a>0||l>0&&r;)0!==a&&(0===l||!r||i.z<=r.z)?(s=i,i=i.nextZ,a--):(s=r,r=r.nextZ,l--),n?n.nextZ=s:t=s,s.prevZ=n,n=s;i=r}n.nextZ=null,h*=2}while(o>1)}(s)}(t,h,u,d);for(var f,m,g=t;t.prev!==t.next;)if(f=t.prev,m=t.next,d?n(t,h,u,d):s(t))e.push(f.i/l|0),e.push(t.i/l|0),e.push(m.i/l|0),P(t),t=m.next,g=m.next;else if((t=m)===g){p?1===p?r(t=o(i(t),e,l),e,l,h,u,d,2):2===p&&a(t,e,l,h,u,d):r(i(t),e,l,h,u,d,1);break}}}function s(t){var e=t.prev,i=t,r=t.next;if(m(e,i,r)>=0)return!1;for(var s=e.x,n=i.x,o=r.x,a=e.y,l=i.y,h=r.y,u=s<n?s<o?s:o:n<o?n:o,c=a<l?a<h?a:h:l<h?l:h,d=s>n?s>o?s:o:n>o?n:o,f=a>l?a>h?a:h:l>h?l:h,g=r.next;g!==e;){if(g.x>=u&&g.x<=d&&g.y>=c&&g.y<=f&&p(s,a,n,l,o,h,g.x,g.y)&&m(g.prev,g,g.next)>=0)return!1;g=g.next}return!0}function n(t,e,i,r){var s=t.prev,n=t,o=t.next;if(m(s,n,o)>=0)return!1;for(var a=s.x,l=n.x,h=o.x,u=s.y,d=n.y,f=o.y,g=a<l?a<h?a:h:l<h?l:h,y=u<d?u<f?u:f:d<f?d:f,v=a>l?a>h?a:h:l>h?l:h,x=u>d?u>f?u:f:d>f?d:f,b=c(g,y,e,i,r),_=c(v,x,e,i,r),w=t.prevZ,P=t.nextZ;w&&w.z>=b&&P&&P.z<=_;){if(w.x>=g&&w.x<=v&&w.y>=y&&w.y<=x&&w!==s&&w!==o&&p(a,u,l,d,h,f,w.x,w.y)&&m(w.prev,w,w.next)>=0)return!1;if(w=w.prevZ,P.x>=g&&P.x<=v&&P.y>=y&&P.y<=x&&P!==s&&P!==o&&p(a,u,l,d,h,f,P.x,P.y)&&m(P.prev,P,P.next)>=0)return!1;P=P.nextZ}for(;w&&w.z>=b;){if(w.x>=g&&w.x<=v&&w.y>=y&&w.y<=x&&w!==s&&w!==o&&p(a,u,l,d,h,f,w.x,w.y)&&m(w.prev,w,w.next)>=0)return!1;w=w.prevZ}for(;P&&P.z<=_;){if(P.x>=g&&P.x<=v&&P.y>=y&&P.y<=x&&P!==s&&P!==o&&p(a,u,l,d,h,f,P.x,P.y)&&m(P.prev,P,P.next)>=0)return!1;P=P.nextZ}return!0}function o(t,e,r){var s=t;do{var n=s.prev,o=s.next.next;!g(n,o)&&y(n,s,s.next,o)&&b(n,o)&&b(o,n)&&(e.push(n.i/r|0),e.push(s.i/r|0),e.push(o.i/r|0),P(s),P(s.next),s=t=o),s=s.next}while(s!==t);return i(s)}function a(t,e,s,n,o,a){var l=t;do{for(var h=l.next.next;h!==l.prev;){if(l.i!==h.i&&f(l,h)){var u=_(l,h);return l=i(l,l.next),u=i(u,u.next),r(l,e,s,n,o,a,0),void r(u,e,s,n,o,a,0)}h=h.next}l=l.next}while(l!==t)}function l(t,e){return t.x-e.x}function h(t,e){var r=function(t,e){var i,r=e,s=t.x,n=t.y,o=-1/0;do{if(n<=r.y&&n>=r.next.y&&r.next.y!==r.y){var a=r.x+(n-r.y)*(r.next.x-r.x)/(r.next.y-r.y);if(a<=s&&a>o&&(o=a,i=r.x<r.next.x?r:r.next,a===s))return i}r=r.next}while(r!==e);if(!i)return null;var l,h=i,c=i.x,d=i.y,f=1/0;r=i;do{s>=r.x&&r.x>=c&&s!==r.x&&p(n<d?s:o,n,c,d,n<d?o:s,n,r.x,r.y)&&(l=Math.abs(n-r.y)/(s-r.x),b(r,t)&&(l<f||l===f&&(r.x>i.x||r.x===i.x&&u(i,r)))&&(i=r,f=l)),r=r.next}while(r!==h);return i}(t,e);if(!r)return e;var s=_(r,t);return i(s,s.next),i(r,r.next)}function u(t,e){return m(t.prev,t,e.prev)<0&&m(e.next,t,t.next)<0}function c(t,e,i,r,s){return(t=1431655765&((t=858993459&((t=252645135&((t=16711935&((t=(t-i)*s|0)|t<<8))|t<<4))|t<<2))|t<<1))|(e=1431655765&((e=858993459&((e=252645135&((e=16711935&((e=(e-r)*s|0)|e<<8))|e<<4))|e<<2))|e<<1))<<1}function d(t){var e=t,i=t;do{(e.x<i.x||e.x===i.x&&e.y<i.y)&&(i=e),e=e.next}while(e!==t);return i}function p(t,e,i,r,s,n,o,a){return(s-o)*(e-a)>=(t-o)*(n-a)&&(t-o)*(r-a)>=(i-o)*(e-a)&&(i-o)*(n-a)>=(s-o)*(r-a)}function f(t,e){return t.next.i!==e.i&&t.prev.i!==e.i&&!function(t,e){var i=t;do{if(i.i!==t.i&&i.next.i!==t.i&&i.i!==e.i&&i.next.i!==e.i&&y(i,i.next,t,e))return!0;i=i.next}while(i!==t);return!1}(t,e)&&(b(t,e)&&b(e,t)&&function(t,e){var i=t,r=!1,s=(t.x+e.x)/2,n=(t.y+e.y)/2;do{i.y>n!=i.next.y>n&&i.next.y!==i.y&&s<(i.next.x-i.x)*(n-i.y)/(i.next.y-i.y)+i.x&&(r=!r),i=i.next}while(i!==t);return r}(t,e)&&(m(t.prev,t,e.prev)||m(t,e.prev,e))||g(t,e)&&m(t.prev,t,t.next)>0&&m(e.prev,e,e.next)>0)}function m(t,e,i){return(e.y-t.y)*(i.x-e.x)-(e.x-t.x)*(i.y-e.y)}function g(t,e){return t.x===e.x&&t.y===e.y}function y(t,e,i,r){var s=x(m(t,e,i)),n=x(m(t,e,r)),o=x(m(i,r,t)),a=x(m(i,r,e));return s!==n&&o!==a||(!(0!==s||!v(t,i,e))||(!(0!==n||!v(t,r,e))||(!(0!==o||!v(i,t,r))||!(0!==a||!v(i,e,r)))))}function v(t,e,i){return e.x<=Math.max(t.x,i.x)&&e.x>=Math.min(t.x,i.x)&&e.y<=Math.max(t.y,i.y)&&e.y>=Math.min(t.y,i.y)}function x(t){return t>0?1:t<0?-1:0}function b(t,e){return m(t.prev,t,t.next)<0?m(t,e,t.next)>=0&&m(t,t.prev,e)>=0:m(t,e,t.prev)<0||m(t,t.next,e)<0}function _(t,e){var i=new E(t.i,t.x,t.y),r=new E(e.i,e.x,e.y),s=t.next,n=e.prev;return t.next=e,e.prev=t,i.next=s,s.prev=i,r.next=i,i.prev=r,n.next=r,r.prev=n,r}function w(t,e,i,r){var s=new E(t,e,i);return r?(s.next=r.next,s.prev=r,r.next.prev=s,r.next=s):(s.prev=s,s.next=s),s}function P(t){t.next.prev=t.prev,t.prev.next=t.next,t.prevZ&&(t.prevZ.nextZ=t.nextZ),t.nextZ&&(t.nextZ.prevZ=t.prevZ)}function E(t,e,i){this.i=t,this.x=e,this.y=i,this.prev=null,this.next=null,this.z=0,this.prevZ=null,this.nextZ=null,this.steiner=!1}function T(t,e,i,r){for(var s=0,n=e,o=i-r;n<i;n+=r)s+=(t[o]-t[n])*(t[n+1]+t[o+1]),o=n;return s}return Ct=1,Mt.exports=t,Mt.exports.default=t,t.deviation=function(t,e,i,r){var s=e&&e.length,n=s?e[0]*i:t.length,o=Math.abs(T(t,0,n,i));if(s)for(var a=0,l=e.length;a<l;a++){var h=e[a]*i,u=a<l-1?e[a+1]*i:t.length;o-=Math.abs(T(t,h,u,i))}var c=0;for(a=0;a<r.length;a+=3){var d=r[a]*i,p=r[a+1]*i,f=r[a+2]*i;c+=Math.abs((t[d]-t[f])*(t[p+1]-t[d+1])-(t[d]-t[p])*(t[f+1]-t[d+1]))}return 0===o&&0===c?0:Math.abs((c-o)/o)},t.flatten=function(t){for(var e=t[0][0].length,i={vertices:[],holes:[],dimensions:e},r=0,s=0;s<t.length;s++){for(var n=0;n<t[s].length;n++)for(var o=0;o<e;o++)i.vertices.push(t[s][n][o]);s>0&&(r+=t[s-1].length,i.holes.push(r))}return i},Mt.exports}();const Nt=/* @__PURE__ */It(Ot);for(var Lt,Rt=[],kt=0;kt<256;++kt)Rt.push((kt+256).toString(16).slice(1));var Bt=new Uint8Array(16);function Ft(){if(!Lt&&!(Lt="undefined"!=typeof crypto&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto)))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return Lt(Bt)}const Dt={randomUUID:"undefined"!=typeof crypto&&crypto.randomUUID&&crypto.randomUUID.bind(crypto)};function Ut(t,e,i){if(Dt.randomUUID&&!t)return Dt.randomUUID();var r=(t=t||{}).random||(t.rng||Ft)();return r[6]=15&r[6]|64,r[8]=63&r[8]|128,function(t,e=0){return(Rt[t[e+0]]+Rt[t[e+1]]+Rt[t[e+2]]+Rt[t[e+3]]+"-"+Rt[t[e+4]]+Rt[t[e+5]]+"-"+Rt[t[e+6]]+Rt[t[e+7]]+"-"+Rt[t[e+8]]+Rt[t[e+9]]+"-"+Rt[t[e+10]]+Rt[t[e+11]]+Rt[t[e+12]]+Rt[t[e+13]]+Rt[t[e+14]]+Rt[t[e+15]]).toLowerCase()}(r)}function Gt(t,e,i,r,s){Xt(t,e,i||0,r||t.length-1,s||Yt)}function Xt(t,e,i,r,s){for(;r>i;){if(r-i>600){var n=r-i+1,o=e-i+1,a=Math.log(n),l=.5*Math.exp(2*a/3),h=.5*Math.sqrt(a*l*(n-l)/n)*(o-n/2<0?-1:1);Xt(t,e,Math.max(i,Math.floor(e-o*l/n+h)),Math.min(r,Math.floor(e+(n-o)*l/n+h)),s)}var u=t[e],c=i,d=r;for(Wt(t,i,e),s(t[r],u)>0&&Wt(t,i,r);c<d;){for(Wt(t,c,d),c++,d--;s(t[c],u)<0;)c++;for(;s(t[d],u)>0;)d--}0===s(t[i],u)?Wt(t,i,d):Wt(t,++d,r),d<=e&&(i=d+1),e<=d&&(r=d-1)}}function Wt(t,e,i){var r=t[e];t[e]=t[i],t[i]=r}function Yt(t,e){return t<e?-1:t>e?1:0}class Ht{constructor(t=9){this._maxEntries=Math.max(4,t),this._minEntries=Math.max(2,Math.ceil(.4*this._maxEntries)),this.clear()}all(){return this._all(this.data,[])}search(t){let e=this.data;const i=[];if(!ie(t,e))return i;const r=this.toBBox,s=[];for(;e;){for(let n=0;n<e.children.length;n++){const o=e.children[n],a=e.leaf?r(o):o;ie(t,a)&&(e.leaf?i.push(o):ee(t,a)?this._all(o,i):s.push(o))}e=s.pop()}return i}collides(t){let e=this.data;if(!ie(t,e))return!1;const i=[];for(;e;){for(let r=0;r<e.children.length;r++){const s=e.children[r],n=e.leaf?this.toBBox(s):s;if(ie(t,n)){if(e.leaf||ee(t,n))return!0;i.push(s)}}e=i.pop()}return!1}load(t){if(!t||!t.length)return this;if(t.length<this._minEntries){for(let e=0;e<t.length;e++)this.insert(t[e]);return this}let e=this._build(t.slice(),0,t.length-1,0);if(this.data.children.length)if(this.data.height===e.height)this._splitRoot(this.data,e);else{if(this.data.height<e.height){const t=this.data;this.data=e,e=t}this._insert(e,this.data.height-e.height-1,!0)}else this.data=e;return this}insert(t){return t&&this._insert(t,this.data.height-1),this}clear(){return this.data=re([]),this}remove(t,e){if(!t)return this;let i=this.data;const r=this.toBBox(t),s=[],n=[];let o,a,l;for(;i||s.length;){if(i||(i=s.pop(),a=s[s.length-1],o=n.pop(),l=!0),i.leaf){const r=$t(t,i.children,e);if(-1!==r)return i.children.splice(r,1),s.push(i),this._condense(s),this}l||i.leaf||!ee(i,r)?a?(o++,i=a.children[o],l=!1):i=null:(s.push(i),n.push(o),o=0,a=i,i=i.children[0])}return this}toBBox(t){return t}compareMinX(t,e){return t.minX-e.minX}compareMinY(t,e){return t.minY-e.minY}toJSON(){return this.data}fromJSON(t){return this.data=t,this}_all(t,e){const i=[];for(;t;)t.leaf?e.push(...t.children):i.push(...t.children),t=i.pop();return e}_build(t,e,i,r){const s=i-e+1;let n,o=this._maxEntries;if(s<=o)return n=re(t.slice(e,i+1)),jt(n,this.toBBox),n;r||(r=Math.ceil(Math.log(s)/Math.log(o)),o=Math.ceil(s/Math.pow(o,r-1))),n=re([]),n.leaf=!1,n.height=r;const a=Math.ceil(s/o),l=a*Math.ceil(Math.sqrt(o));se(t,e,i,l,this.compareMinX);for(let h=e;h<=i;h+=l){const e=Math.min(h+l-1,i);se(t,h,e,a,this.compareMinY);for(let i=h;i<=e;i+=a){const s=Math.min(i+a-1,e);n.children.push(this._build(t,i,s,r-1))}}return jt(n,this.toBBox),n}_chooseSubtree(t,e,i,r){for(;r.push(e),!e.leaf&&r.length-1!==i;){let i,r=1/0,s=1/0;for(let n=0;n<e.children.length;n++){const o=e.children[n],a=Kt(o),l=Qt(t,o)-a;l<s?(s=l,r=a<r?a:r,i=o):l===s&&a<r&&(r=a,i=o)}e=i||e.children[0]}return e}_insert(t,e,i){const r=i?t:this.toBBox(t),s=[],n=this._chooseSubtree(r,this.data,e,s);for(n.children.push(t),Vt(n,r);e>=0&&s[e].children.length>this._maxEntries;)this._split(s,e),e--;this._adjustParentBBoxes(r,s,e)}_split(t,e){const i=t[e],r=i.children.length,s=this._minEntries;this._chooseSplitAxis(i,s,r);const n=this._chooseSplitIndex(i,s,r),o=re(i.children.splice(n,i.children.length-n));o.height=i.height,o.leaf=i.leaf,jt(i,this.toBBox),jt(o,this.toBBox),e?t[e-1].children.push(o):this._splitRoot(i,o)}_splitRoot(t,e){this.data=re([t,e]),this.data.height=t.height+1,this.data.leaf=!1,jt(this.data,this.toBBox)}_chooseSplitIndex(t,e,i){let r,s=1/0,n=1/0;for(let o=e;o<=i-e;o++){const e=zt(t,0,o,this.toBBox),a=zt(t,o,i,this.toBBox),l=te(e,a),h=Kt(e)+Kt(a);l<s?(s=l,r=o,n=h<n?h:n):l===s&&h<n&&(n=h,r=o)}return r||i-e}_chooseSplitAxis(t,e,i){const r=t.leaf?this.compareMinX:qt,s=t.leaf?this.compareMinY:Jt;this._allDistMargin(t,e,i,r)<this._allDistMargin(t,e,i,s)&&t.children.sort(r)}_allDistMargin(t,e,i,r){t.children.sort(r);const s=this.toBBox,n=zt(t,0,e,s),o=zt(t,i-e,i,s);let a=Zt(n)+Zt(o);for(let l=e;l<i-e;l++){const e=t.children[l];Vt(n,t.leaf?s(e):e),a+=Zt(n)}for(let l=i-e-1;l>=e;l--){const e=t.children[l];Vt(o,t.leaf?s(e):e),a+=Zt(o)}return a}_adjustParentBBoxes(t,e,i){for(let r=i;r>=0;r--)Vt(e[r],t)}_condense(t){for(let e,i=t.length-1;i>=0;i--)0===t[i].children.length?i>0?(e=t[i-1].children,e.splice(e.indexOf(t[i]),1)):this.clear():jt(t[i],this.toBBox)}}function $t(t,e,i){if(!i)return e.indexOf(t);for(let r=0;r<e.length;r++)if(i(t,e[r]))return r;return-1}function jt(t,e){zt(t,0,t.children.length,e,t)}function zt(t,e,i,r,s){s||(s=re(null)),s.minX=1/0,s.minY=1/0,s.maxX=-1/0,s.maxY=-1/0;for(let n=e;n<i;n++){const e=t.children[n];Vt(s,t.leaf?r(e):e)}return s}function Vt(t,e){return t.minX=Math.min(t.minX,e.minX),t.minY=Math.min(t.minY,e.minY),t.maxX=Math.max(t.maxX,e.maxX),t.maxY=Math.max(t.maxY,e.maxY),t}function qt(t,e){return t.minX-e.minX}function Jt(t,e){return t.minY-e.minY}function Kt(t){return(t.maxX-t.minX)*(t.maxY-t.minY)}function Zt(t){return t.maxX-t.minX+(t.maxY-t.minY)}function Qt(t,e){return(Math.max(e.maxX,t.maxX)-Math.min(e.minX,t.minX))*(Math.max(e.maxY,t.maxY)-Math.min(e.minY,t.minY))}function te(t,e){const i=Math.max(t.minX,e.minX),r=Math.max(t.minY,e.minY),s=Math.min(t.maxX,e.maxX),n=Math.min(t.maxY,e.maxY);return Math.max(0,s-i)*Math.max(0,n-r)}function ee(t,e){return t.minX<=e.minX&&t.minY<=e.minY&&e.maxX<=t.maxX&&e.maxY<=t.maxY}function ie(t,e){return e.minX<=t.maxX&&e.minY<=t.maxY&&e.maxX>=t.minX&&e.maxY>=t.minY}function re(t){return{children:t,height:1,leaf:!0,minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0}}function se(t,e,i,r,s){const n=[e,i];for(;n.length;){if((i=n.pop())-(e=n.pop())<=r)continue;const o=e+Math.ceil((i-e)/r/2)*r;Gt(t,o,e,i,s),n.push(e,o,o,i)}}var ne,oe={exports:{}};var ae,le,he,ue,ce,de,pe=function(){if(ne)return oe.exports;function t(){}return ne=1,t.prototype={on:function(t,e,i){var r=this.e||(this.e={});return(r[t]||(r[t]=[])).push({fn:e,ctx:i}),this},once:function(t,e,i){var r=this;function s(){r.off(t,s),e.apply(i,arguments)}return s._=e,this.on(t,s,i)},emit:function(t){for(var e=[].slice.call(arguments,1),i=((this.e||(this.e={}))[t]||[]).slice(),r=0,s=i.length;r<s;r++)i[r].fn.apply(i[r].ctx,e);return this},off:function(t,e){var i=this.e||(this.e={}),r=i[t],s=[];if(r&&e)for(var n=0,o=r.length;n<o;n++)r[n].fn!==e&&r[n].fn._!==e&&s.push(r[n]);return s.length?i[t]=s:delete i[t],this}},oe.exports=t,oe.exports.TinyEmitter=t,oe.exports}(),fe=t=>{throw TypeError(t)},me=(t,e,i)=>e.has(t)||fe("Cannot "+i),ge=(t,e,i)=>(me(t,e,"read from private field"),i?i.call(t):e.get(t)),ye=(t,e,i)=>e.has(t)?fe("Cannot add the same private member more than once"):e instanceof WeakSet?e.add(t):e.set(t,i),ve=(t,e,i,r)=>(me(t,e,"write to private field"),e.set(t,i),i),xe=(t,e,i)=>(me(t,e,"access private method"),i);let be=new class extends E{error(...t){this.levels.includes("errors")&&(t.length>0&&(t[0]="Internal error: "+t[0]),console.error(...t),this.emit("error",...t))}}(["info","warnings","errors"]);class _e{constructor(t){this.spaceGraph=null,this.type=t}}class we extends _e{constructor(t,e){super(e),this.name="",this.customId="",this.id=t}copyForClone(t){this.name=t.name,this.customId=t.customId}setName(t){this.name=t,this.emit("node-property-change",this,"name")}setCustomId(t){this.customId=t,this.emit("node-property-change",this,"customId")}emit(t,...e){this.spaceGraph&&this.spaceGraph.emit(t,...e)}toJSON(){return{type:this.type,id:this.id,name:""===this.name?void 0:this.name,customId:""===this.customId?void 0:this.customId}}}const Pe="material:color";class Ee extends we{constructor(t,e=[1,1,1],i=1){super(t,Pe),this.color=[...e],this.opacity=i}toJSON(){let t;return t=1===this.opacity?[...this.color]:[this.color[0],this.color[1],this.color[2],this.opacity],{...super.toJSON(),value:t}}}const Te="material:standard";class Ae extends we{constructor(t,e){super(t,Te),this.reference=e}toJSON(){return{...super.toJSON(),reference:this.reference}}}const Ie="material:embedded";class Se extends we{constructor(t,e,i){super(t,Ce),this.reference=e,this.format=i}toJSON(){return be.warn("Embedded material not supported in materials section."),{...super.toJSON(),type:"material:color",value:[1,1,1,1]}}}const Ce="material:basic";class Me extends we{constructor(t){super(t,Ce),this.colorDiffuse=[1,1,1],this.colorSpecular=[1,1,1],this.specularCoefficient=1,this.opacity=1}copyForClone(t){super.copyForClone(t),this.colorDiffuse=[...t.colorDiffuse],this.colorSpecular=[...t.colorSpecular],this.specularCoefficient=t.specularCoefficient,this.opacity=t.opacity}toJSON(){return{...super.toJSON(),colorDiffuse:[...this.colorDiffuse],colorSpecular:[...this.colorSpecular],specularCoefficient:this.specularCoefficient,opacity:this.opacity}}}const Oe="default",Ne=[1,1,1],Le=[1,1,1],Re=[...Ne,1];function ke(t,e){return Number.isFinite(t)?!(t<0||t>1)||(be.warn(`Value out of range (0 to 1) in color literal: '${e}'.`),!1):(be.warn(`Invalid float value in color literal: '${e}'.`),!1)}function Be(t,e){return Number.isInteger(t)?!(t<0||t>255)||(be.warn(`Value out of range (0 to 255) in color literal: '${e}'.`),!1):(be.warn(`Invalid byte value in color literal: '${e}'.`),!1)}function Fe(t){if(t.length<3||t.length>4)return be.warn(`Invalid number of components in color literal: '${t}'.`),Re;let e=t.toString(),i=[0,0,0,0];for(let r=0;r<t.length;r++){let s=t[r];if(!ke(s,e))return Re;i[r]=s}return 3===t.length&&(i[3]=Re[3]),i}function De(t){let e,i,r,s,n=t.substring(1),o=parseInt(n,16);if(isNaN(o))return be.warn(`Invalid hexadecimal color literal: '${t}'.`),Re;if(3===n.length?o=o<<4|15:6===n.length&&(o=o<<8|255),3===n.length||4===n.length)e=(o>>12&15)/15,i=(o>>8&15)/15,r=(o>>4&15)/15,s=(15&o)/15;else{if(6!==n.length&&8!==n.length)return be.warn(`Invalid hexademical color literal length: '${t}'.`),Re;e=(o>>24&255)/255,i=(o>>16&255)/255,r=(o>>8&255)/255,s=(255&o)/255}return[e,i,r,s]}function Ue(t,e){if(!t.endsWith(")"))return be.warn(`Missing closing parenthesis: '${t}'.`),Re;let i=e?5:4,r=t.substring(i,t.length-1).split(",");if(r.length<3||r.length>4||3===r.length&&e||4===r.length&&!e)return be.warn(`Invalid number of components in color literal: '${t}'.`),Re;let s=[0,0,0,0];for(let n=0;n<3;n++){let e=r[n],i=parseFloat(e);if(!Be(i,t))return Re;s[n]=i/255}if(4===r.length){let e=parseFloat(r[3]);if(!ke(e,t))return Re;s[3]=e}else s[3]=Re[3];return s}function Ge([t,e,i]){return"#"+Math.round(255*t).toString(16).padStart(2,"0")+Math.round(255*e).toString(16).padStart(2,"0")+Math.round(255*i).toString(16).padStart(2,"0")}function Xe({name:t=Oe,color:e=Ne,specularColor:i=Le,specularCoefficient:r=1,opacity:s=1,reference:n}={}){return n?{name:t,reference:n}:{name:t,color:[...e],specularColor:[...i],specularCoefficient:r,opacity:s}}function We(t,e={}){if(Array.isArray(t)){let[e,i,r,s]=Fe(t);return Xe({name:t.toString(),color:[e,i,r],opacity:s})}if("string"==typeof t){let i,r,s,n;if(""===t)return be.warn("Empty string not a valid color value."),Xe({name:t});if(t===Oe)return Xe();if("#"===t.charAt(0))[i,r,s,n]=De(t);else if(t.startsWith("rgb("))[i,r,s,n]=Ue(t,!1);else{if(!t.startsWith("rgba(")){if(t.startsWith("asm:")){let e=t.substring(4,t.length);return Xe({name:t,reference:e})}if(t.startsWith("data3d:")){let e=t.substring(7,t.length);return Xe({name:t,reference:e})}{let i=e[t];if(void 0===i)return be.warn(`Unknown material: '${t}'.`),Xe();{let e;switch(i.type){case Pe:e=Xe({name:t,color:i.color,specularColor:i.color});break;case Te:e=Xe({name:t,reference:i.reference});break;case Ie:be.warn("Embedded material not supported in materials section."),e=Xe();break;case Ce:e=Xe({name:t,color:i.colorDiffuse,specularColor:i.colorSpecular,specularCoefficient:i.specularCoefficient,opacity:i.opacity});break;default:be.warn(`Unknown material type ${i.type}.`),e=Xe()}return e}}}[i,r,s,n]=Ue(t,!0)}return Xe({name:t,color:[i,r,s],opacity:n})}return be.warn(`Material can only be an array or a string: '${t}'.`),Xe()}const Ye="default";function He(t,e){return new Array(e-t).fill(void 0).map((e,i)=>t+i)}function $e(t,e){let i=new Array(3*e.length),r=0;for(let s=0;s<e.length;s++){let n=3*e[s];i[r++]=t[n],i[r++]=t[n+1],i[r++]=t[n+2]}return i}function je(t,e,i){let r=3*e,s=new Array(r*i.length),n=0;for(let o=0;o<i.length;o++){let e=r*i[o];for(let i=0;i<r;i++)s[n++]=t[e++]}return s}function ze(t,e,i){let r=[],s=e.faces,{surfaces:n,materials:o}=function(t){let e=t.surfaces??{[Ye]:"all"},i=t.materials??{[Ye]:"default"};if(e&&0===Object.keys(e).length)be.warn("Empty 'surfaces' field not allowed.");else if(i&&0===Object.keys(i).length)be.warn("Empty 'materials' field not allowed.");else if(t.material)t.materials?be.warn("Cannot use 'material' and 'materials' at the same time."):i={[Ye]:t.material};else if(i[Ye])Object.keys(i).length>1&&be.warn("Extraneous material assignments ignored.");else{let t=Object.keys(e);for(let e of t)i[e]||be.warn(`Surface '${e}' not assigned a material, using default.`);let r=Object.keys(i);for(let i of r)e[i]||be.warn(`Surface '${i}' not found.`)}return{surfaces:e,materials:i}}(t);for(let[a,l]of Object.entries(n)){if("all"!==l&&!Array.isArray(l)&&"object"!=typeof l){be.warn(`Unknown face indices type, skipping surface '${a}'.`);continue}let n=[];if("geometry:mesh"===t.type)if("all"===l){let t=e.indices.length/3;n.push(...He(0,t))}else if(Array.isArray(l))n.push(...l);else{let{start:t,end:e}=l;n.push(...He(t,e))}else if("all"===l)for(let t of s){let{index:e,count:i}=t;n.push(...He(e,e+i))}else if(Array.isArray(l))for(let t=0;t<l.length;t++){let e=s[l[t]],{index:i,count:r}=e;n.push(...He(i,i+r))}else{let{start:t,end:e}=l;for(let i=t;i<e;i++){let t=s[i],{index:e,count:r}=t;n.push(...He(e,e+r))}}let h,{vertices:u,indices:c,normals:d,uvs:p}=e;h=o[Ye]?o[Ye]:o[a]??"default";let f=We(h,i),m={name:a,vertices:u,indices:$e(c,n),material:f};d&&(m.normals=je(d,3,n)),p&&(m.uvs=je(p,2,n)),r.push(m)}return r}function Ve(t,e){let i=function(t){if(Array.isArray(t))return[t];if("vector3:list"===t.type)return t.list;if("vector3:range"===t.type){let{start:e,step:i,count:r}=t.range;return function(t,e,i){let r=[];for(let s=0;s<i;s++){let i=t[0]+s*e[0],n=t[1]+s*e[1],o=t[2]+s*e[2];r.push([i,n,o])}return r}(e,i,r)}return be.warn(`Unknown position type: ${t}`),[[0,0,0]]}(t),r=function(t){if("number"==typeof t)return[t];if("number:list"===t.type)return t.list;if("number:range"===t.type){let{start:e,step:i,count:r}=t.range;return function(t,e,i){let r=[];for(let s=0;s<i;s++){let i=t+s*e;r.push(i)}return r}(e,i,r)}return be.warn(`Unknown rotation type: ${t}`),[0]}(e),s=Math.max(i.length,r.length),n=[];for(let o=0;o<s;o++){let t=i[Math.min(o,i.length-1)],e=r[Math.min(o,r.length-1)];void 0!==t&&void 0!==e&&n.push({position:t,rotation:e})}return n}function qe(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Je(t){if(Object.prototype.hasOwnProperty.call(t,"__esModule"))return t;var e=t.default;if("function"==typeof e){var i=function t(){return this instanceof t?Reflect.construct(e,arguments,this.constructor):e.apply(this,arguments)};i.prototype=e.prototype}else i={};return Object.defineProperty(i,"__esModule",{value:!0}),Object.keys(t).forEach(function(e){var r=Object.getOwnPropertyDescriptor(t,e);Object.defineProperty(i,e,r.get?r:{enumerable:!0,get:function(){return t[e]}})}),i}var Ke={exports:{}};function Ze(t,e){return t<e?-1:t>e?1:0}const Qe=/* @__PURE__ */Je(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:class{constructor(t=[],e=Ze){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(t){this.data.push(t),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:i}=this,r=e[t];for(;t>0;){const s=t-1>>1,n=e[s];if(i(r,n)>=0)break;e[t]=n,t=s}e[t]=r}_down(t){const{data:e,compare:i}=this,r=this.length>>1,s=e[t];for(;t<r;){let r=1+(t<<1),n=e[r];const o=r+1;if(o<this.length&&i(e[o],n)<0&&(r=o,n=e[o]),i(n,s)>=0)break;e[t]=n,t=r}e[t]=s}}},Symbol.toStringTag,{value:"Module"})));var ti;const ei=/* @__PURE__ */qe(function(){if(ti)return Ke.exports;ti=1;var t=Qe;function e(e,s,n){var o,a,l,h;s=s||1;for(var u=0;u<e[0].length;u++){var c=e[0][u];(!u||c[0]<o)&&(o=c[0]),(!u||c[1]<a)&&(a=c[1]),(!u||c[0]>l)&&(l=c[0]),(!u||c[1]>h)&&(h=c[1])}var d=l-o,p=h-a,f=Math.min(d,p),m=f/2;if(0===f){var g=[o,a];return g.distance=0,g}for(var y=new t(void 0,i),v=o;v<l;v+=f)for(var x=a;x<h;x+=f)y.push(new r(v+m,x+m,m,e));var b=function(t){for(var e=0,i=0,s=0,n=t[0],o=0,a=n.length,l=a-1;o<a;l=o++){var h=n[o],u=n[l],c=h[0]*u[1]-u[0]*h[1];i+=(h[0]+u[0])*c,s+=(h[1]+u[1])*c,e+=3*c}return 0===e?new r(n[0][0],n[0][1],0,t):new r(i/e,s/e,0,t)}(e),_=new r(o+d/2,a+p/2,0,e);_.d>b.d&&(b=_);for(var w=y.length;y.length;){var P=y.pop();P.d>b.d&&(b=P,n&&console.log("found best %d after %d probes",Math.round(1e4*P.d)/1e4,w)),P.max-b.d<=s||(m=P.h/2,y.push(new r(P.x-m,P.y-m,m,e)),y.push(new r(P.x+m,P.y-m,m,e)),y.push(new r(P.x-m,P.y+m,m,e)),y.push(new r(P.x+m,P.y+m,m,e)),w+=4)}n&&(console.log("num probes: "+w),console.log("best distance: "+b.d));var E=[b.x,b.y];return E.distance=b.d,E}function i(t,e){return e.max-t.max}function r(t,e,i,r){this.x=t,this.y=e,this.h=i,this.d=function(t,e,i){for(var r=!1,n=1/0,o=0;o<i.length;o++)for(var a=i[o],l=0,h=a.length,u=h-1;l<h;u=l++){var c=a[l],d=a[u];c[1]>e!=d[1]>e&&t<(d[0]-c[0])*(e-c[1])/(d[1]-c[1])+c[0]&&(r=!r),n=Math.min(n,s(t,e,c,d))}return 0===n?0:(r?1:-1)*Math.sqrt(n)}(t,e,r),this.max=this.d+this.h*Math.SQRT2}function s(t,e,i,r){var s=i[0],n=i[1],o=r[0]-s,a=r[1]-n;if(0!==o||0!==a){var l=((t-s)*o+(e-n)*a)/(o*o+a*a);l>1?(s=r[0],n=r[1]):l>0&&(s+=o*l,n+=a*l)}return(o=t-s)*o+(a=e-n)*a}return t.default&&(t=t.default),Ke.exports=e,Ke.exports.default=e,Ke.exports}());function ii(t,e){return[t[0]+e[0],t[1]+e[1]]}function ri(t){let e;return 0===t[0]?e=t[1]>0?Math.PI/2:t[1]<0?3*Math.PI/2:0:(e=Math.atan2(t[1],t[0]),e<0&&(e+=2*Math.PI)),e}function si(t,e){return t[0]*e[1]-t[1]*e[0]}function ni(t,e,i){return Math.abs(t[0]-e[0])<i&&Math.abs(t[1]-e[1])<i}function oi(t){return Math.sqrt(function(t){return t[0]*t[0]+t[1]*t[1]}(t))}function ai(t,e){return oi(di(e,t))}function li(t,e,i){return[t[0]+i*(e[0]-t[0]),t[1]+i*(e[1]-t[1])]}function hi(t){let e=oi(t);return[t[0]/e,t[1]/e]}function ui(t){return[-t[1],t[0]]}function ci(t,e){return[t[0]*e,t[1]*e]}function di(t,e){return[t[0]-e[0],t[1]-e[1]]}function pi(t,e){return[t[0]+e[0],t[1]+e[1],t[2]+e[2]]}function fi(t,e){return[t[0]-e[0],t[1]-e[1],t[2]-e[2]]}function mi(t,e,i){return[t[0]+i*(e[0]-t[0]),t[1]+i*(e[1]-t[1]),t[2]+i*(e[2]-t[2])]}function gi(t,e,i){let r=si(di(e,t),di(i,t));return r>1e-7?1:r<-1e-7?-1:0}function yi(t,e){return ri([e[0]-t[0],e[1]-t[1]])}function vi(t,e,i,r){let s=di(e,t),n=di(r,i),o=function(t,e){return t[0]*e[0]+t[1]*e[1]}(s,n),a=si(s,n);return Math.atan2(Math.abs(a),o)}function xi(t,e){let i=!1;const r=t[0],s=t[1];for(let n=0;n<e.length;n++){const t=e[n],o=n===e.length-1?e[0]:e[n+1];if(t[1]<s&&o[1]>=s||o[1]<s&&t[1]>=s){const e=o[0]-t[0],n=o[1]-t[1];Math.abs(n)>=1e-9&&t[0]+(s-t[1])/n*e<r&&(i=!i)}}return i}function bi(t,e){if(!xi(t,e[0]))return!1;for(let i=1;i<e.length;i++){if(xi(t,e[i]))return!1}return!0}function _i(t,e,i){return function(t,e,i){const r=di(i,e),s=r[0]*r[0]+r[1]*r[1];let n;if(s<1e-9)n=e;else{const o=((t[0]-e[0])*r[0]+(t[1]-e[1])*r[1])/s;n=o<0?e:o>1?i:li(e,i,o)}const o=di(n,t);return o[0]*o[0]+o[1]*o[1]}(t,e,i)**.5}function wi(t){let e=0;for(let i=0;i<t.length;i++){let r=i,s=i<t.length-1?i+1:0,n=t[r],o=t[s];e+=n[0]*o[1]-o[0]*n[1]}return.5*e}function Pi(t){return Math.abs(wi(t))}function Ei(t,e=.1){let i;if(function(t){if(0===t.length)return 0;let e=Pi(t[0]);for(let i=1;i<t.length;i++)e-=Pi(t[i]);return e}(t)<.1)i=function(t){const{min:e,max:i}=W([t]);return[e[0]+(i[0]-e[0])/2,e[1]+(i[1]-e[1])/2]}(t[0]);else{const r=ei(t,e);i=[r[0],r[1]]}return i}function Ti(t){return wi(t)>0}function Ai(t,e,i){if(0!==t[0]||0!==t[1]||0!==t[2]||0!==e){let r=nt(),s=ft(t[0],t[1],t[2]),n=function(t=0,e=[0,1,0]){let i=t*Math.PI/180,r=wt();return Pt(r,e,i),r}(e,i);return function(t,e,i){var r=e[0],s=e[1],n=e[2],o=e[3],a=r+r,l=s+s,h=n+n,u=r*a,c=r*l,d=r*h,p=s*l,f=s*h,m=n*h,g=o*a,y=o*l,v=o*h;t[0]=1-(p+m),t[1]=c+v,t[2]=d-y,t[3]=0,t[4]=c-v,t[5]=1-(u+m),t[6]=f+g,t[7]=0,t[8]=d+y,t[9]=f-g,t[10]=1-(u+p),t[11]=0,t[12]=i[0],t[13]=i[1],t[14]=i[2],t[15]=1}(r,n,s),r}return nt()}function Ii(t){let e=dt(),i=wt();ut(e,t),ct(i,t);let r=dt(),s=(n=r,o=i,a=2*Math.acos(o[3]),(l=Math.sin(a/2))>rt?(n[0]=o[0]/l,n[1]=o[1]/l,n[2]=o[2]/l):(n[0]=1,n[1]=0,n[2]=0),a);var n,o,a,l;return 0===s&&(r=[0,1,0]),{position:[e[0],e[1],e[2]],rotation:180*s/Math.PI,rotationAxis:[r[0],r[1],r[2]]}}function Si(t,e){let i=dt();for(let r=0;r<t.length;r+=3)i[0]=t[r],i[1]=t[r+1],i[2]=t[r+2],bt(i,i,e),t[r]=i[0],t[r+1]=i[1],t[r+2]=i[2]}function Ci(t){let e=function(t,e){return t[0]=1,t[1]=0,t[2]=0,t[3]=1,t[4]=e[0],t[5]=e[1],t}(function(){var t=new st(6);return st!=Float32Array&&(t[1]=0,t[2]=0,t[4]=0,t[5]=0),t[0]=1,t[3]=1,t}(),t.position);return function(t,e,i){var r=e[0],s=e[1],n=e[2],o=e[3],a=e[4],l=e[5],h=Math.sin(i),u=Math.cos(i);t[0]=r*u+n*h,t[1]=s*u+o*h,t[2]=r*-h+n*u,t[3]=s*-h+o*u,t[4]=a,t[5]=l}(e,e,-t.rotation*Math.PI/180),e}function Mi(t,e){return function(t,e){let i=function(t,e,i){var r=e[0],s=e[1];return t[0]=i[0]*r+i[2]*s+i[4],t[1]=i[1]*r+i[3]*s+i[5],t}(Tt(),t.position,e),r=t.rotation+Math.atan2(-e[1],e[0])*(180/Math.PI);return{position:[i[0],i[1]],rotation:(s=r,n=360,(s%n+n)%n)};var s,n}(t,Ci(e))}function Oi(t,e){return t.map(t=>{let{position:i}=Mi({position:t,rotation:0},e);return i})}function Ni({position:t=[0,0,0],rotation:e=0,rotationAxis:i=[0,1,0],name:r,vertices:s,indices:n,normals:o,uvs:a,material:l}){let h=Ve(t,e),u=[],c=[],d=[],p=[],f=nt();for(let g=0;g<h.length;g++){let t=h[g],{position:e,rotation:r}=t,l=Ai(e,r,i),m=s.slice();Si(m,l);let y=u.length/3;for(const i of m)u.push(i);for(const i of n)c.push(y+i);if(Array.isArray(o)){ot(f,l),f[12]=0,f[13]=0,f[14]=0,at(f,f),lt(f,f);let t=o.slice();Si(t,f),d.push(...t)}Array.isArray(a)&&p.push(...a)}let m={name:r,vertices:u,indices:c,material:l};return Array.isArray(o)&&(m.normals=d),Array.isArray(a)&&(m.uvs=p),m}class Li{constructor(){this.polygons=[]}clone(){const t=new Li;for(const e of this.polygons)t.polygons.push(e.clone());return t}toPolygons(){return this.polygons}union(t){var e=new Li.Node(this.clone().polygons),i=new Li.Node(t.clone().polygons);return e.clipTo(i),i.clipTo(e),i.invert(),i.clipTo(e),i.invert(),e.build(i.allPolygons()),Li.fromPolygons(e.allPolygons())}subtract(t){var e=new Li.Node(this.polygons),i=new Li.Node(t.polygons);return e.invert(),e.clipTo(i),i.clipTo(e),i.invert(),i.clipTo(e),i.invert(),e.build(i.allPolygons()),e.invert(),Li.fromPolygons(e.allPolygons())}intersect(t){var e=new Li.Node(this.clone().polygons),i=new Li.Node(t.clone().polygons);return e.invert(),i.clipTo(e),i.invert(),e.clipTo(i),i.clipTo(e),e.build(i.allPolygons()),e.invert(),Li.fromPolygons(e.allPolygons())}inverse(){var t=this.clone();return t.polygons.forEach(function(t){t.flip()}),t}}(t=>{function e(t){return[-t[0],-t[1],-t[2]]}function i(t,e){return t[0]*e[0]+t[1]*e[1]+t[2]*e[2]}function r(t){const e=function(t){return Math.sqrt(i(t,t))}(t);return[t[0]/e,t[1]/e,t[2]/e]}t.fromPolygons=function(e){var i=new t;return i.polygons=e,i};t.Vertex=class{constructor(t,e){this.pos=t,this.normal=e}clone(){return new t.Vertex([...this.pos],this.normal?[...this.normal]:void 0)}flip(){this.normal&&(this.normal=e(this.normal))}interpolate(e,i){return new t.Vertex(mi(this.pos,e.pos,i),this.normal&&e.normal?mi(this.normal,e.normal,i):void 0)}};const s=class{constructor(t,e){this.normal=t,this.w=e}clone(){return new t.Plane([...this.normal],this.w)}flip(){this.normal=e(this.normal),this.w=-this.w}splitPolygon(e,r,s,n,o){for(var a=0,l=[],h=0;h<e.vertices.length;h++){var u=(v=i(this.normal,e.vertices[h].pos)-this.w)<-t.Plane.EPSILON?2:v>t.Plane.EPSILON?1:0;a|=u,l.push(u)}switch(a){case 0:(i(this.normal,e.plane.normal)>0?r:s).push(e);break;case 1:n.push(e);break;case 2:o.push(e);break;case 3:var c=[],d=[];for(h=0;h<e.vertices.length;h++){var p=(h+1)%e.vertices.length,f=l[h],m=l[p],g=e.vertices[h],y=e.vertices[p];if(2!=f&&c.push(g),1!=f&&d.push(2!=f?g.clone():g),3==(f|m)){var v=(this.w-i(this.normal,g.pos))/i(this.normal,fi(y.pos,g.pos)),x=g.interpolate(y,v);c.push(x),d.push(x.clone())}}c.length>=3&&n.push(new t.Polygon(c,e.shared)),d.length>=3&&o.push(new t.Polygon(d,e.shared))}}};s.EPSILON=1e-5,s.fromPoints=function(e,s,n){var o,a,l=r((o=fi(s,e),a=fi(n,e),[o[1]*a[2]-o[2]*a[1],o[2]*a[0]-o[0]*a[2],o[0]*a[1]-o[1]*a[0]]));return new t.Plane(l,i(l,e))};let n=s;t.Plane=n;t.Polygon=class{constructor(e,i){this.vertices=e,this.shared=i,this.plane=t.Plane.fromPoints(e[0].pos,e[1].pos,e[2].pos)}clone(){const e=[];for(const t of this.vertices)e.push(t.clone());return new t.Polygon(e,this.shared)}flip(){this.vertices.reverse();for(const t of this.vertices)t.flip();this.plane.flip()}};t.Node=class{constructor(t){this.plane=null,this.front=null,this.back=null,this.polygons=[],t&&this.build(t)}clone(){var e=new t.Node;e.plane=this.plane&&this.plane.clone(),e.front=this.front&&this.front.clone(),e.back=this.back&&this.back.clone();for(const t of this.polygons)e.polygons.push(t.clone());return e}invert(){var t;for(let i=0;i<this.polygons.length;i++)this.polygons[i].flip();null==(t=this.plane)||t.flip(),this.front&&this.front.invert(),this.back&&this.back.invert();const e=this.front;this.front=this.back,this.back=e}clipPolygons(t){if(!this.plane)return t.slice();for(var e=[],i=[],r=0;r<t.length;r++)this.plane.splitPolygon(t[r],e,i,e,i);this.front&&(e=this.front.clipPolygons(e)),i=this.back?this.back.clipPolygons(i):[];const s=new Array(e.length+i.length);for(let n=0;n<e.length;n++)s[n]=e[n];for(let n=0;n<i.length;n++)s[e.length+n]=i[n];return s}clipTo(t){this.polygons=t.clipPolygons(this.polygons),this.front&&this.front.clipTo(t),this.back&&this.back.clipTo(t)}allPolygons(t=!0){var e=t?this.polygons.slice():this.polygons;return this.front&&(e=e.concat(this.front.allPolygons(!1))),this.back&&(e=e.concat(this.back.allPolygons(!1))),e}build(e){if(e.length){this.plane||(this.plane=e[0].plane.clone());for(var i=[],r=[],s=0;s<e.length;s++)this.plane.splitPolygon(e[s],this.polygons,this.polygons,i,r);i.length&&(this.front||(this.front=new t.Node),this.front.build(i)),r.length&&(this.back||(this.back=new t.Node),this.back.build(r))}}}})(Li||(Li={}));const Ri=Li;function ki(t,e,i){let r=.5*i,s=[[-r,-r,0],[r,-r,0],[r,r,0],[-r,r,0]],{u:n,v:o,n:a}=function(t){const e=1/Math.sqrt(2);let i=[0,0,0],r=[0,0,0],s=[0,0,0];return vt(s,t),xt(i,Math.abs(s[1])<e?ft(0,1,0):ft(1,0,0),t),xt(r,t,i),vt(i,i),vt(r,r),{u:i,v:r,n:s}}(e),l=t,h=function(t,e,i,r,s,n,o,a,l,h,u,c,d,p,f,m){var g=new st(16);return g[0]=t,g[1]=e,g[2]=i,g[3]=r,g[4]=s,g[5]=n,g[6]=o,g[7]=a,g[8]=l,g[9]=h,g[10]=u,g[11]=c,g[12]=d,g[13]=p,g[14]=f,g[15]=m,g}(n[0],n[1],n[2],0,o[0],o[1],o[2],0,a[0],a[1],a[2],0,l[0],l[1],l[2],1);for(let u of s)bt(u,u,h);return s}function Bi(t,e){const i=[],r=t.nextId++,{name:s,vertices:n,indices:o,material:a}=e;for(let l=0;l<o.length;l+=3){const t=3*o[l],e=3*o[l+1],h=3*o[l+2],u=[n[t],n[t+1],n[t+2]],c=[n[e],n[e+1],n[e+2]],d=[n[h],n[h+1],n[h+2]],p=[new Ri.Vertex(u),new Ri.Vertex(c),new Ri.Vertex(d)];i.push(new Ri.Polygon(p,{id:r,name:s,material:a}))}return i}function Fi(){let t=Math.random(),e=Math.random(),i=Math.random();return Xe({name:Ge([t,e,i]),color:[t,e,i],opacity:1})}function Di(t,e){const i=[],r=[],s={};for(let n=0;n<e.length;n++){const o=3*e[n],a=t[o],l=t[o+1],h=t[o+2],u=73856093*a^19349663*l^83492791*h;let c=s[u];void 0===c&&(c=i.push(a,l,h)/3-1,s[u]=c),r.push(c)}return{vertices:i,indices:r}}function Ui(t,e){const i=[];for(const r of e){const e=Bi(t,r);for(const t of e)i.push(t)}return Ri.fromPolygons(i)}function Gi(t,{debugMode:e=!1,sharedVertices:i=!0}={}){const r={},{polygons:s}=t;for(let n=0;n<s.length;n++){const t=s[n],i=t.vertices.length;if(i<3){be.warn(`Skipping CSG polygon with '${i}' '${1===i?"vertex":"vertices"}.`);continue}const o=[];o.length=3*i;for(let e=0;e<i;e++){const i=t.vertices[e];o[3*e]=i.pos[0],o[3*e+1]=i.pos[1],o[3*e+2]=i.pos[2]}let a;if(3===i)a=[0,1,2];else{a=[];for(let t=1;t<i-1;t++)a.push(0,t,t+1)}if(e){const t=Fi();r[n]={name:t.name,vertices:o,indices:a,material:t}}else{const{id:e,name:i,material:s}=t.shared,n=r[e];if(n){const t=n.vertices.length;n.vertices.length=t+o.length;for(let r=0;r<o.length;r++)n.vertices[t+r]=o[r];const e=n.indices.length;n.indices.length=e+a.length;const i=t/3;for(let r=0;r<a.length;r++)n.indices[e+r]=a[r]+i}else r[e]={name:i,vertices:o,indices:a,material:s}}}if(i)for(const n of Object.values(r)){const{vertices:t,indices:e}=n,i=Di(t,e);n.vertices=i.vertices,n.indices=i.indices}return Object.values(r)}function Xi(t,e,i,r){let s,n,o,a,l;if("string"==typeof t){if(s=t,l=e[s],!l)return be.warn(`Geometry '${s}' not found.`),[];n=[0,0,0],o=0,a=[0,1,0]}else{let i=t;if("string"==typeof i.geometry){if(s=i.geometry,l=e[s],!l)return be.warn(`Geometry '${s}' not found.`),[]}else l=i.geometry;n=i.position??[0,0,0],o=i.rotation??0,a=i.rotationAxis??[0,1,0]}if(r.indexOf(l)>-1)return be.warn(`Cycle detected while resolving geometry '${l.id}'.`),[];let h=ar(l,e,i,r);"string"!=typeof t&&"csg:clip"!==t.type&&function(t,e,i,r){let s;if(t.material?t.materials?be.warn("Cannot use 'material' and 'materials' at the same time."):s={[Ye]:t.material}:t.materials&&(0===Object.keys(t.materials).length?be.warn("Empty 'materials' field not allowed."):s=t.materials),s)if(s[Ye]){let t=We(s[Ye],i);for(let i of e)i.material=t;Object.keys(s).length>1&&be.warn(`Extraneous material assignments to '${r}' ignored.`)}else for(let[n,o]of Object.entries(s)){let t=e.find(t=>t.name===n);if(t){let e=We(o,i);t.material=e}else be.warn(`Surface '${n}' not found in geometry '${r}', skipping material assignment.`)}}(t,h,i,l.id);let u=[];for(let c of h){let{name:t,vertices:e,indices:i,normals:r,uvs:s,material:l}=c,h=Ni({position:n,rotation:o,rotationAxis:a,name:t,vertices:e,indices:i,normals:r,uvs:s,material:l});u.push(h)}return u}function Wi(t,e,i,r,s){return[...t,...Xi(e,i,r,s)]}function Yi(t,e,i,r){let{plane:s,material:n}=i,o=Ui(t,e);{let e=function(t,e,i,r,s=100){let n=t.nextId++,{position:o,normal:a}=e,l=We(i,r),h=[0,0,0],u=[0,0,0];vt(h,a),function(t,e,i,r){t[0]=e[0]+i[0]*r,t[1]=e[1]+i[1]*r,t[2]=e[2]+i[2]*r}(u,o,h,s);let c=ki(o,h,s),d=ki(u,h,s),p=c.concat(d),f=[[0,1,2,3],[4,5,6,7],[0,4,5,1],[1,5,6,2],[2,6,7,3],[3,7,4,0]],m=[];for(let g of f){let t=[];for(let i of g)t.push(new Ri.Vertex(p[i]));let e=new Ri.Polygon(t,{id:n,name:"",material:l});m.push(e)}return Ri.fromPolygons(m)}(t,s,n,r);o.polygons.length>0&&(o=o.subtract(e))}return Gi(o,{debugMode:!1})}function Hi(t,e,i,r,s,n){const o=Xi(i,r,s,n),a=Ui(t,e),l=Ui(t,o);let h=[];if(a.polygons.length&&l.polygons.length){let t;switch(i.type){case"csg:subtract":t=a.subtract(l);break;case"csg:union":t=a.union(l);break;case"csg:intersect":t=a.intersect(l);break;default:t=a}h=Gi(t,{debugMode:!1})}return h}function $i(t,e,i){e[0]=t[i+0],e[1]=t[i+1],e[2]=t[i+2]}function ji(t,e,i){t[i+0]=e[0],t[i+1]=e[1],t[i+2]=e[2]}function zi(t,e){let i=new Array(3*e.length),r=dt(),s=dt(),n=dt(),o=dt(),a=dt(),l=dt(),h=0;for(let u=0;u<e.length;u+=3){let c=e[u],d=e[u+1],p=e[u+2];$i(t,r,3*c),$i(t,s,3*d),$i(t,n,3*p),_t(o,s,r),_t(a,n,r),xt(l,o,a),vt(l,l),ji(i,l,h+0),ji(i,l,h+3),ji(i,l,h+6),h+=9}return i}function Vi(t,e){let i=new Array(3*e.length),r=dt(),s=dt(),n=dt(),o=dt(),a=dt(),l=dt(),h=e.length/3,u=new Array(h),c=0;for(let f=0;f<e.length;f+=3){let i=e[f],h=e[f+1],d=e[f+2];$i(t,r,3*i),$i(t,s,3*h),$i(t,n,3*d),_t(o,s,r),_t(a,n,r),xt(l,o,a),vt(l,l),u[c++]={index1:i,index2:h,index3:d,normal1:pt(l),normal2:pt(l),normal3:pt(l)}}let d=[];for(let f=0;f<t.length;f++)d[f]={normals:[],normal:dt()};for(let f=0;f<u.length;f++){let t=u[f],{index1:e,index2:i,index3:r}=t;d[e].normals.push(t.normal1),d[i].normals.push(t.normal2),d[r].normals.push(t.normal3)}for(let f=0;f<d.length;f++){let t=d[f],e=t.normals.length;if(e>0){let i=t.normal;mt(i,0,0,0);for(let r=0;r<e;r++)gt(i,i,t.normals[r]);vt(i,i)}}let p=0;for(let f=0;f<e.length;f+=3){let t=e[f],r=e[f+1],s=e[f+2],n=d[t].normal,o=d[r].normal,a=d[s].normal;ji(i,n,p+0),ji(i,o,p+3),ji(i,a,p+6),p+=9}return i}function qi(t,e,i){e[0]=t[i+0],e[1]=t[i+1],e[2]=t[i+2]}function Ji(t,e){let i=new Array(2*e.length),r=dt(),s=dt(),n=dt(),o=dt(),a=dt(),l=dt(),h=0;for(let u=0;u<e.length;u+=3){let c,d,p=e[u],f=e[u+1],m=e[u+2];qi(t,r,3*p),qi(t,s,3*f),qi(t,n,3*m),_t(o,s,r),_t(a,n,r),xt(l,o,a),vt(l,l),l[0]=Math.abs(l[0]),l[1]=Math.abs(l[1]),l[2]=Math.abs(l[2]),l[0]>=l[1]&&l[0]>=l[2]?(c=2,d=1):l[1]>=l[0]&&l[1]>=l[2]?(c=0,d=2):(c=0,d=1),i[h++]=r[c],i[h++]=r[d],i[h++]=s[c],i[h++]=s[d],i[h++]=n[c],i[h++]=n[d]}return i}function Ki(t,e){let i=new Array(2*e.length),r=0;for(let s=0;s<e.length;s++){let n=3*e[s],o=t[n],a=t[n+1],l=t[n+2],h=.5+Math.atan2(o,l)/(2*Math.PI),u=.5+Math.asin(a)/Math.PI;i[r++]=h,i[r++]=u}return i}function Zi(t,e,i){let r=Math.cos(e),s=Math.sin(e);return[t*s*Math.cos(i),t*r,t*s*Math.sin(i)]}const Qi=48,tr=12;function er(t,e){return[e*Math.cos(t),-e*Math.sin(t)]}function ir(t,e,i,r=!0){let s=[],n=e-t,o=function(t,e){let i=Math.ceil(Qi/(2*Math.PI)*t*e);const r=Math.ceil(tr/(2*Math.PI)*t);return Math.max(r,i)}(Math.abs(n),i),a=n/o;for(let l=0;l<o;l++){let e=er(t+l*a,i);s.push(e)}if(r){let t=er(e,i);s.push(t)}return s}function rr(t){let e=[];switch(t.type){case"curve:line":e.push(t.start,t.end);break;case"curve:arc":e=ir(Math.PI*t.startAngle/180,Math.PI*t.endAngle/180,t.radius);break;case"curve:polyline":e=t.points}return e}function sr(t){let e=[],i=[],r=[];switch(t.type){case"curve:circle":e=ir(0,2*Math.PI,t.radius,!1),i.push({index:0,count:e.length});break;case"curve:polygon":e=t.points;for(let t=0;t<e.length;t++)i.push({index:t,count:1});break;case"curve:polygonWithHoles":e=t.polygons[0];for(let t=0;t<e.length;t++)i.push({index:t,count:1});const s=t.polygons.slice(1);if(s.length>=1){const t=s.length>1?Y(s):s;for(let e of t)r.push(sr({type:"curve:polygon",points:e}))}break;case"curve:rectangle":let{dimensions:n}=t,o=n[0],a=n[1];e=[[0,0],[0,a],[o,a],[o,0]];for(let t=0;t<e.length;t++)i.push({index:t,count:1});break;case"curve:composite":const l=1e-7;let h,u,c=t.segments;for(let t=0;t<c.length;t++){let r=rr(c[t]),s=r[0],n=r[r.length-1];0===t||ni(s,u,l)||be.warn(`Composite curve segments ${t} and ${t+1} are not continuous.`),0===t&&(h=s),u=n,i.push({index:e.length,count:r.length-1}),e.push(...r.slice(0,r.length-1))}c.length>0&&!ni(u,h,l)&&be.warn("Composite curve not closed.")}return{points:e,segmentRanges:i,holes:r}}function nr(t,e,i){let r,s=i.holes??[],n=i.y??0,o=i.flipSide??!1,a=t,l=[];if(8===a.length&&0===s.length){r=(e?o:!o)?[3,0,1,1,2,3]:[1,0,3,3,2,1]}else{if(s.length>0){let t=new Array(s.length);for(let e=0;e<s.length;e++)t[e]=a.length/2,a=a.concat(s[e]);r=Nt(a,t)}else r=Nt(a);if(!o)for(let t=0;t<r.length;t+=3){let e=r[t];r[t]=r[t+2],r[t+2]=e}}let h=0;for(let u=0;u<a.length;u+=2)l[h++]=a[u],l[h++]=n,l[h++]=a[u+1];return{vertices:l,indices:r}}function or(t,e,i=0,r=!1){let s=new Array(2*t*3),n=0;for(let o=0;o<t;o++){o===t-1?r?(s[n++]=o+i,s[n++]=i,s[n++]=e+i,s[n++]=o+i,s[n++]=e+i,s[n++]=o+e+i):(s[n++]=e+i,s[n++]=i,s[n++]=o+i,s[n++]=o+e+i,s[n++]=e+i,s[n++]=o+i):r?(s[n++]=o+i,s[n++]=o+1+i,s[n++]=o+e+1+i,s[n++]=o+i,s[n++]=o+e+1+i,s[n++]=o+e+i):(s[n++]=o+e+1+i,s[n++]=o+1+i,s[n++]=o+i,s[n++]=o+e+i,s[n++]=o+e+1+i,s[n++]=o+i)}return s}function ar(t,e,i,r=[]){var s;let n,o=[];switch(t.type){case"geometry:plane":n=function(t){let{normal:e,size:i,doubleSided:r}=t,s=ki([0,0,0],e,i).flat(),n=[0,1,2,0,2,3],o=[{index:0,count:2}];return r&&(n=n.concat([0,2,1,0,3,2]),o.push({index:2,count:2})),{vertices:s,indices:n,faces:o}}(t);break;case"geometry:cuboid":n=function(t){let{dimensions:e}=t,i=e[0],r=e[1],s=e[2],n=[0,r,s,i,r,s,i,r,0,0,r,0,0,0,s,i,0,s,i,0,0,0,0,0],o=[];for(let a=0;a<6;a++)o.push({index:2*a,count:2});return{vertices:n,indices:[0,1,2,0,2,3,4,7,6,4,6,5,0,4,5,0,5,1,1,5,6,1,6,2,2,6,7,2,7,3,3,7,4,3,4,0],faces:o}}(t);break;case"geometry:sphere":n=function(t){const e=16,i=16;let r,s,n=t.radius,o=[],a=[],l="generator"===t.uvs?[]:void 0;o.push(0,n,0);for(let u=1;u<i;u++){let t=Math.PI*u/i;for(let i=0;i<e;i++){let r=Zi(n,t,2*Math.PI*i/e);o.push(r[0],r[1],r[2])}}let h=o.push(0,-n,0)/3-1;r=1,s=.9375;for(let u=0;u<e;u++){let t=1+u,i=1+(u+1)%e;if(a.push(0,i,t),l){let t=1-u/e,i=1-(u+1)/e,n=.5*(t+i);l.push(n,r,i,s,t,s)}}for(let u=0;u<14;u++)for(let t=0;t<e;t++){let r=1+u*e+t,s=1+u*e+(t+1)%e,n=1+(u+1)*e+(t+1)%e,o=1+(u+1)*e+t;if(a.push(r,s,n),a.push(r,n,o),l){let r=1-t/e,s=1-(u+1)/i,n=1-(t+1)/e,o=1-(u+2)/i;l.push(r,s,n,s,n,o),l.push(r,s,n,o,r,o)}}r=.0625,s=0;for(let u=0;u<e;u++){let t=225+u,i=225+(u+1)%e;if(a.push(t,i,h),l){let t=1-u/e,i=1-(u+1)/e,n=.5*(t+i);l.push(t,r,i,r,n,s)}}return{vertices:o,indices:a,uvs:l,faces:[{index:0,count:a.length/3}]}}(t);break;case"geometry:extrusion":n=function(t){let{profile:e,height:i}=t,r=sr(e),{points:s,segmentRanges:n,holes:o}=r,a=s.flat(),l=[],h=s.length,u=[{points:s,segmentRanges:n}];for(let w of o)l.push(w.points.flat()),u.push(w),h+=w.points.length;let c=Ti(s),d=nr(a,c,{y:i,flipSide:!1,holes:l}),p=nr(a,c,{y:0,flipSide:!0,holes:l}),f=[];f.push(...d.vertices),f.push(...p.vertices);let m=d.indices,g=p.indices.map(t=>t+h),y=[];y.push(...m),y.push(...g);let v=m.length/3,x=[];x[0]={index:0,count:v},x[1]={index:v,count:v};let b=2*v,_=0;for(let w=0;w<u.length;w++){let{points:t,segmentRanges:e}=u[w],i=0===w?Ti(t):!Ti(t),r=or(t.length,d.vertices.length/3,_,i);_=t.length,y.push(...r);for(let s of e){let t=b+2*s.index,e=2*s.count;x.push({index:t,count:e})}b+=2*t.length}return{vertices:f,indices:y,faces:x}}(t);break;case"geometry:mesh":n=function(t){let{vertices:e,indices:i,normals:r,uvs:s}=t,n={vertices:e,indices:i,faces:[]};return Array.isArray(r)&&(n.normals=r),Array.isArray(s)&&(n.uvs=s),n}(t);break;default:return be.warn(`Invalid geometry type ${t.type}.`),o}o=ze(t,n,i),"geometry:plane"!==t.type&&"geometry:cuboid"!==t.type&&"geometry:sphere"!==t.type&&"geometry:extrusion"!==t.type||(null==(s=t.geometries)?void 0:s.length)&&(r.push(t),o=function(t,e,i,r,s){let n={nextId:0},o=t.geometries??[];for(let a of o)e="string"==typeof a||"reference:geometry"===a.type?Wi(e,a,i,r,s):"csg:clip"===a.type?Yi(n,e,a,r):Hi(n,e,a,i,r,s);return e}(t,o,e,i,r),r.pop());let a=[];for(let u of o){let{name:e,vertices:i,indices:r,normals:s,uvs:n,material:o}=u,{position:l,rotation:h,rotationAxis:c}=t,d=Ni({position:l,rotation:h,rotationAxis:c,name:e,vertices:i,indices:r,normals:s,uvs:n,material:o});a.push(d)}o=a;let l=t.normals??"flat";if("flat"===l||"smooth"===l)for(let u of o){let{vertices:t,indices:e}=u;u.normals="flat"===l?zi(t,e):Vi(t,e)}let h=t.uvs??"automatic";if("automatic"==h||"spherical"===h)for(let u of o){let{vertices:t,indices:e}=u;u.uvs="automatic"===h?Ji(t,e):Ki(t,e)}return o}function lr(t){let e,i,r,s={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]};for(let n=0;n<t.length;n+=3)e=t[n],i=t[n+1],r=t[n+2],s.min[0]=Math.min(s.min[0],e),s.max[0]=Math.max(s.max[0],e),s.min[1]=Math.min(s.min[1],i),s.max[1]=Math.max(s.max[1],i),s.min[2]=Math.min(s.min[2],r),s.max[2]=Math.max(s.max[2],r);return s}class hr{constructor(){this.vertices=[],this.edges=[],this.geometryProfile=[]}toJSON(){return{edges:this.edges.map(t=>t.id)}}}function ur(t,e){return"integer"===e.type?"number"==typeof t&&Number.isInteger(t):typeof t===e.type&&(!("enum"in e)||e.enum.includes(t))}const cr={"spatialStructure:layout":"layout","layout:space":"space","product:static":"product","product:component":"product","spatialStructure:building":"building","spatialStructure:floor":"floor","element:asset":"element","element:beam":"element","element:casework":"element","element:column":"element","element:door":"element","element:kitchen":"element","element:railing":"element","element:ramp":"element","element:roof":"element","element:slab":"element","element:stairs":"element","element:stairFlight":"element","element:window":"element","element:generic":"element","element:floor":"element","element:ceiling":"element","element:boundaryWall":"element","element:curtainWall":"element","element:opening":"element","element:spaceDivider":"element","element:wall":"element"},dr=(t,e)=>{const i=cr[e];return i||be.error(`Missing custom attribute resource type for node type: "${e}"`),`${t}:${i}`};function pr(t,e){if("boolean"===e.type&&"string"==typeof t){if("true"===t.toLowerCase())return!0;if("false"===t.toLowerCase())return!1}if("number"===e.type&&"string"==typeof t){const e=Number(t);if(!isNaN(e))return e}return null}class fr extends we{constructor(t,e){super(t,"customAttribute:definition"),this.attributes={resourceType:"space",schema:{type:"string"}},e&&this.setAttributes(e)}getInputType(){return function(t){switch(t.type){case"integer":return"Integer";case"boolean":return"Boolean";case"number":return"Number";case"string":return"enum"in t?"Select":"Text"}}(this.attributes.schema)}setAttributes(t){let e=this.attributes;e.resourceType=t.resourceType??e.resourceType,e.updatedAt=t.updatedAt??e.updatedAt,e.description=t.description??e.description,e.schema=function(t){return t.schema?JSON.parse(JSON.stringify(t.schema)):"Text"===t.valueType?{type:"string"}:"Number"===t.valueType?{type:"number"}:"Boolean"===t.valueType?{type:"boolean"}:void 0}(t)}copyForClone(t){super.copyForClone(t),this.attributes=JSON.parse(JSON.stringify(t.attributes))}toJSON(){const t=super.toJSON();let e={resourceType:this.attributes.resourceType,schema:JSON.parse(JSON.stringify(this.attributes.schema))};return void 0!==this.attributes.updatedAt&&(e.updatedAt=this.attributes.updatedAt),void 0!==this.attributes.description&&(e.description=this.attributes.description),t.attributes=e,t}}const mr={"customAttribute:definition":fr};class gr extends we{constructor(t,e){super(t,e),this.customAttributes={}}setCustomAttributes(t,e){let i=null,r=!1;if(null===t&&(this.customAttributes={},r=!0),t&&e)for(const s in t){let n=t[s];if(null===n){delete this.customAttributes[s],r=!0;continue}const o=dr(s,this.type),a=e[o];if(a){if(!ur(n,a.attributes.schema)){let t=pr(n,a.attributes.schema);if(null===t){be.error(`Value type mismatch for custom attribute. Received value: "${n}". Expected type: ${a.attributes.schema.type}`),i=`Value type mismatch for custom attribute. Received value: "${n}". Expected type: ${a.attributes.schema.type}`;continue}n=t}this.customAttributes[s]!==n&&(this.customAttributes[s]=n,r=!0)}else i=`Missing custom attribute definition for node key: "${s}", node type: "${this.type}" and definition id: ${o}`}r&&this.emit("node-custom-attributes-change",this),i&&be.error(i)}toJSON(){const t=super.toJSON();return Object.keys(this.customAttributes).length>0&&(t.customAttributes=JSON.parse(JSON.stringify(this.customAttributes))),t}copyForClone(t){super.copyForClone(t),this.customAttributes=JSON.parse(JSON.stringify(t.customAttributes))}}class yr extends gr{constructor(t,e){super(t,e),this.layout=null}}class vr extends yr{constructor(){super(...arguments),this.axisAlignedBoundingBox=null,this.objectAlignedBoundingBox=null,this.boundingBoxContour=null,this.transform=null,this.worldTransform=null}calculateTransform(){return{position:[0,0,0],rotation:0,rotationAxis:[0,1,0]}}getTransform(){return this.transform||(this.transform=this.calculateTransform()),this.transform}calculateWorldTransform(){return this.getTransform()}getWorldTransform(){return this.worldTransform||(this.worldTransform=this.calculateWorldTransform()),this.worldTransform}resetTransform(t=!1){var e;this.transform=null,this.worldTransform=null,this.axisAlignedBoundingBox=null,this.boundingBoxContour=null,t&&(null==(e=this.layout)||e.spatialIndex.addNode(this))}resetBoundingBox(t=!1){var e;this.objectAlignedBoundingBox=null,this.axisAlignedBoundingBox=null,this.boundingBoxContour=null,t&&(null==(e=this.layout)||e.spatialIndex.addNode(this))}resetSpatialIndexing(){this.resetTransform(),this.resetBoundingBox(!0)}calculateBoundingBox(){return{min:[0,0,0],max:[0,0,0]}}getBoundingBox(t=!1){this.objectAlignedBoundingBox||(this.objectAlignedBoundingBox=this.calculateBoundingBox());const{min:e,max:i}=this.objectAlignedBoundingBox;return{min:e,max:i,transform:t?this.getTransform():this.getWorldTransform()}}getAxisAlignedBoundingBox(){return this.axisAlignedBoundingBox||(this.axisAlignedBoundingBox=function({min:t,max:e,transform:i}){if(0===i.rotation)return{min:pi(t,i.position),max:pi(e,i.position)};{let r=Ai(i.position,i.rotation,i.rotationAxis);const s=[[...t],[...e],[t[0],t[1],e[2]],[e[0],e[1],t[2]]];for(const t of s)bt(t,t,r);return lr(s.flat())}}(this.getBoundingBox())),this.axisAlignedBoundingBox}calculateBoundingBoxContour(t=!1){const{min:[e,,i],max:[r,,s],transform:n}=this.getBoundingBox(t),{position:[o,,a],rotation:l}=n;let h=[[e,i],[r,i],[r,s],[e,s]];return(o||a||l)&&(h=Oi(h,{position:[o,a],rotation:l})),h}getBoundingBoxContour(){return this.boundingBoxContour||(this.boundingBoxContour=this.calculateBoundingBoxContour()),this.boundingBoxContour}}class xr extends vr{}class br extends xr{constructor(t,e,i){super(t,"spatialGraph:vertex"),this.position=[0,0],this.edges=[],this.position[0]=e,this.position[1]=i}sortVertexEdges(){let t=[];for(let e of this.edges){let i=this===e.vertices[0]?e.vertices[1]:e.vertices[0],r=ri([i.position[0]-this.position[0],i.position[1]-this.position[1]]);t.push({edge:e,edgeAngle:r})}t.sort((t,e)=>t.edgeAngle-e.edgeAngle),this.edges=t.map(t=>t.edge)}calculateTransform(){return{position:[this.position[0],0,this.position[1]],rotation:0,rotationAxis:[0,1,0]}}addEdge(t){this.edges.push(t),this.sortVertexEdges(),this.emit("vertex-add-edge",this,t)}removeEdge(t){let e=this.edges.indexOf(t);if(e>-1){let t=this.edges.splice(e,1)[0];this.emit("vertex-remove-edge",this,t)}else be.error(`Vertex does not reference edge ${t.id}.`)}setPosition(t,e){this.position[0]=t,this.position[1]=e,this.edges.length>0&&(this.layout.spatialGraph.graphChanged=!0),this.resetSpatialIndexing(),this.emit("vertex-set-position",this)}resetSpatialIndexing(){super.resetSpatialIndexing();const t=/* @__PURE__ */new Set;for(const e of this.edges){e.resetSpatialIndexing();for(const i of e.spaces)i&&t.add(i)}for(const e of t)e.resetSpatialIndexing()}toJSON(){return{...super.toJSON(),position:[...this.position]}}}function _r(t,e,i,r,s=!1){if(e.layout)return be.warn(`${r} ${e.id} already part of layout ${e.layout.id}.`),!1;if(i[e.id])return be.error(`${r} ${e.id} already registered in layout.`),!1;let n=t.spaceGraph;if(n&&n.nodesById[e.id])return be.error(`${r} ${e.id} already registered in space graph.`),!1;if(e.type.startsWith("space:")){let t=e;if(t.slabs.length>0)return be.warn(`Detached space ${t.id} references boundary slab elements.`),!1}else if(e.type.startsWith("element:")){let n=e;if(s&&n.parent)return be.warn(`${r} ${n.id} already a child of ${r} ${n.parent.id}.`),!1;for(let e of n.elements)if(!_r(t,e,i,r,!1))return!1}return!0}function wr(t,e){if(e.layout=t,t.elementsById[e.id])return void be.error(`Element ${e.id} already registered.`);t.elementsById[e.id]=e;const i=t.elementsByType[e.type];i||(be.warn(`unrecognized layout element type: ${e.type}`),t.elementsByType[e.type]=[]),i.push(e);let r=t.spaceGraph;r&&("element:asset"===e.type&&e.product&&!r.productsById[e.product.id]&&r.insertProduct(e.product),r.registerNode(e),r.emit("element-create",e));for(let s of e.elements)wr(t,s)}function Pr(t,e,i){for(let o of e.elements)Pr(t,o,e);if(t.elementsById[e.id]!==e)return void be.error(`Entry ${e.id} in 'elements stored by ID' record does not contain this object.`);delete t.elementsById[e.id];const r=t.elementsByType[e.type],s=null==r?void 0:r.indexOf(e);if(!r||-1===s)return void be.error(`element ${e.id} not found in 'elements stored by type' record.`);r.splice(s,1);let n=t.spaceGraph;n&&(n.unregisterNode(e),n.emit("element-delete",e,i)),e.layout=null}function Er(t){return"object"==typeof t&&null!==t}function Tr(t){return Er(t)&&!function(t){return Array.isArray(t)||ArrayBuffer.isView(t)}(t)}function Ar(t,e,i,r){Tr(t)&&Tr(e)||be.error("Both arguments must be objects.");let{onNewKeys:s,copyScopes:n,cloneObjects:o}=r,a=Object.keys(e);for(let l of a){if(s){let{allow:e,excludedScopes:r}=s;if(e===(!!r&&r.includes(i))&&!(l in t)){be.warn(`Key '${l}' not found in scope ${i}, skipped.`);continue}}let a=e[l],h=t[l];if(Er(a)){let e=`${i}.${l}`;!(null==n?void 0:n.includes(e))&&Tr(h)?Ar(h,a,e,r):t[l]=o?JSON.parse(JSON.stringify(a)):a}else t[l]=a}}function Ir(t,e,i={onNewKeys:{allow:!1,excludedScopes:[]},copyScopes:[],cloneObjects:!0}){let r;i.onNewKeys?(r=i.onNewKeys,r.allow=i.onNewKeys.allow??!1,r.excludedScopes=i.onNewKeys.excludedScopes??[]):r={allow:!1,excludedScopes:[]},Ar(t,e,"",{onNewKeys:r,copyScopes:i.copyScopes??[],cloneObjects:i.cloneObjects??!0})}function Sr(t,e){t.name=e.name??t.name,t.customId=e.customId??t.customId}function Cr(t,e,i){t.setCustomAttributes(e.customAttributes,i)}function Mr(t){let e=t.getEdges();return 1===e.length?e[0].id:e.map(t=>t.id)}function Or(t){let e;switch(t.type){case"element:ceiling":case"element:floor":e=function(t){let e=[];for(let i of t.boundaries){let t=i.toJSON();e.push(t)}return{id:t.id,type:t.type,boundaries:e,parameters:{height:t.parameters.height,elevation:t.parameters.elevation,materials:{...t.parameters.materials}}}}(t);break;case"element:boundaryWall":e=function(t){let e=[];for(let r of t.boundaries){let t=r.toJSON();e.push(t)}let i=JSON.parse(JSON.stringify(t.parameters.surfaces));return{id:t.id,type:t.type,boundaries:e,parameters:{height:t.parameters.height,elevation:t.parameters.elevation,surfaces:i,materials:{...t.parameters.materials}}}}(t);break;case"element:curtainWall":e={id:(n=t).id,type:n.type,edge:Mr(n)};break;case"element:spaceDivider":e={id:(s=t).id,type:s.type,edge:Mr(s)};break;case"element:wall":e=function(t){let{width:e,height:i,offset:r,elevation:s,materials:n}=t.parameters;return{id:t.id,type:t.type,parameters:{width:e,height:i,offset:r,elevation:s,materials:{...n}},edge:Mr(t)}}(t);break;case"element:opening":e=function(t){let{position:e,dimensions:i,materials:r}=t.parameters;return{id:t.id,type:t.type,parameters:{position:[...e],dimensions:[...i],materials:{...r}}}}(t);break;case"element:asset":e={id:(i=t).id,type:i.type,position:[...i.position],rotation:i.rotation,rotationAxis:i.rotationAxis,product:null==(r=i.product)?void 0:r.id,geometries:JSON.parse(JSON.stringify(i.geometries))};break;case"element:beam":case"element:casework":case"element:column":case"element:door":case"element:generic":case"element:kitchen":case"element:railing":case"element:ramp":case"element:roof":case"element:slab":case"element:stairs":case"element:stairFlight":case"element:window":e=function(t){let e={id:t.id,type:t.type,position:[...t.position],parameters:JSON.parse(JSON.stringify(t.parameters)),rotation:t.rotation,rotationAxis:t.rotationAxis};return"element:generic"!==t.type&&"element:asset"!==t.type||(e.geometries=JSON.parse(JSON.stringify(t.geometries))),e}(t);break;default:return void be.warn(`Unknown element type '${t.type}, skipping element.`)}var i,r,s,n,o,a;if(o=e,""!==(a=t).name&&(o.name=a.name),""!==a.customId&&(o.customId=a.customId),function(t,e){e.customAttributes===Object(e.customAttributes)&&Object.keys(e.customAttributes).length>0&&(t.customAttributes=e.customAttributes)}(e,t),t.elements.length){e.elements=[];for(let i of t.elements){let t=Or(i);t&&e.elements.push(t)}}return e}class Nr extends vr{constructor(){super(...arguments),this.parent=null,this.elements=[],this.geometries=[]}insertElement(t){let e=this.layout;e&&!_r(e,t,e.elementsById,"Element",!0)||(t.parent=this,this.elements.push(t),e&&wr(e,t))}get isExternal(){if(this.parent)return this.parent.isExternal;const t=this.getSpaces().flatMap(t=>t?[t]:[]);return!t.length||t[0].isExternal}resetTransform(t=!1){super.resetTransform(t);for(const e of this.elements)e.resetTransform(t)}resetBoundingBox(t=!1){super.resetBoundingBox(t);for(const e of this.elements)e.resetBoundingBox(t)}removeElement(t){if(t.parent!==this)return void be.warn(`Element ${t.id} not a child of element ${this.id}.`);let e=this.elements.indexOf(t);if(-1===e)return void be.error(`Element ${t.id} not found in parent ${this.id}.`);let i=t.parent;t.parent=null,this.elements.splice(e,1),t.layout&&Pr(t.layout,t,i)}copyForClone(t){super.copyForClone(t),this.parameters=JSON.parse(JSON.stringify(t.parameters)),this.geometries=JSON.parse(JSON.stringify(t.geometries))}setParameters(t){Ir(this.parameters,t,{onNewKeys:{allow:!1},cloneObjects:!0}),this.resetBoundingBox(),this.emit("element-parameters-change",this)}getSpaces(){return this.parent?this.parent.getSpaces():[]}toJSON(){return Or(this)}}function Lr(t,e,i){let r=t.getAxisLength(),s=[];for(let n of t.elements)if("element:opening"===n.type){let t=n.parameters.position[0],o=t/r,a=(t+n.parameters.dimensions[0])/r;i?e>=o&&e<a&&s.push(n):e>o&&e<a&&s.push(n)}return s}class Rr extends Nr{constructor(t,e,i){super(t,e),ye(this,ae),this.edges=[],this.vertices=[],this.boundingBoxTransform=null,this.edgesChanged=!1,this.setEdges(i)}setEdges(t){var e,i;if(!t.length)return this.edges=[],this.vertices=[],void xe(this,ae,le).call(this);if(1===t.length)return this.edges=[t[0]],this.vertices=[t[0].vertices[0],t[0].vertices[1]],void xe(this,ae,le).call(this);const r=function(t){var e;const i=/* @__PURE__ */new Map;for(const r of t)for(const t of r.vertices)i.has(t)||i.set(t,[]),null==(e=i.get(t))||e.push(r);return i}(t),s=[];let n,o;for(const[h,u]of r.entries())if(1===u.length){n=u[0];const t=n.vertices.find(t=>t!==h);if(2!==(null==(e=r.get(t))?void 0:e.length))return void be.error("Edge sequence is not continuous");s.push(h,t),o=t;break}if(!n||!o)return void be.error("Unable to find start of edge sequence");const a=[n];let l=n;for(;a.length<t.length;){const t=o&&(null==(i=r.get(o))?void 0:i.find(t=>t!==l));if(!t)return void be.error("Edge sequence is not continuous");if(a.includes(t))return void be.error("Duplicate Edge in sequence",t.id,l.id);const e=t.vertices.find(t=>t!==o);s.push(e),a.push(t),o=e,l=t}this.edges=a,this.vertices=s,xe(this,ae,le).call(this)}getEdges(){return[...this.edges]}getVertices(){return xe(this,ae,he).call(this),[...this.vertices]}getStartVertex(){return xe(this,ae,he).call(this),this.vertices.at(0)}getEndVertex(){return xe(this,ae,he).call(this),this.vertices.at(-1)}getAxisPoints(){const t=this.getStartVertex(),e=this.getEndVertex();return t&&e?[t.position,e.position]:[]}getAxisLength(){const[t,e]=this.getAxisPoints();return t&&e?oi(di(t,e)):0}getEdgeAtLinearPosition(t){if(t<0||t>1)return;if(1===this.edges.length)return this.edges[0];let e=this.getAxisLength();if(!e)return;let i=this.vertices[0].position;for(let r=0;r<this.vertices.length-1;r++){if(ai(i,this.vertices[r+1].position)/e>=t)return this.edges[r]}}getEdgesAtLinearSegment(t,e){if(t>e)return[];if(1===this.edges.length)return[this.edges[0]];let i=this.getAxisLength();if(!i)return[];let r=[],s=this.vertices[0].position,n=s;for(let o=0;o<this.vertices.length-1;o++){let a=this.vertices[o+1].position,l=ai(s,n)/i,h=ai(s,a)/i;(t<=l&&e>=h||t>=l&&t<h||e>l&&e<=h)&&r.push(this.edges[o]),n=a}return r}resetTransform(){this.boundingBoxTransform=null,this.objectAlignedBoundingBox=null,super.resetTransform()}getBoundingBox(){this.objectAlignedBoundingBox||(this.objectAlignedBoundingBox=this.calculateBoundingBox());const{min:t,max:e}=this.objectAlignedBoundingBox;return this.boundingBoxTransform||(this.boundingBoxTransform=this.calculateBoundingBoxTransform()),{min:t,max:e,transform:this.boundingBoxTransform}}calculateBoundingBoxTransform(){const[t,e]=this.getAxisPoints();if(!t||!e)return super.calculateTransform();const i={rotation:-(yi(t,e)/Math.PI*180)};return{position:[t[0],0,t[1]],rotation:i.rotation,rotationAxis:[0,1,0]}}get edge(){return be.warn("Use getEdges() instead of edge"),this.edges[0]||null}getAdjacentElementsByVertex(){let t=[[],[]];for(let e=0;e<this.vertices.length;e++){let i=this.vertices[e].edges.filter(t=>t.element&&t.element.id!==this.id).map(t=>t.element);t[e]=i}return t}getAdjacentSpacesBySide(){let t=[[],[]];for(let e=0;e<2;e++){let i=this.edges.filter(t=>t.spaces[e]).map(t=>t.spaces[e]);t[e]=i}return t}getSpaces(){let t=[];for(let e of this.edges)e.spaces[0]&&t.push(e.spaces[0]),e.spaces[1]&&t.push(e.spaces[1]);return t}getElementsAtLinearPosition(t){return Lr(this,t,!0)}get isExternal(){let t=0,e=0;for(const i of this.getEdges())i.isExternal?t+=i.getLength():e+=i.getLength();return t>=e}}function kr(t){for(let e of t.elements)if("element:door"===e.type){let t=e.parameters;t.hingeSide="right"===t.hingeSide?"left":"right",t.doorSide="side1"===t.doorSide?"side2":"side1"}}ae=/* @__PURE__ */new WeakSet,le=function(){this.edgesChanged=!1,this.resetSpatialIndexing(),this.emit("element-edges-change",this)},he=function(){this.edgesChanged&&this.edges.length&&this.setEdges(this.edges)};class Br extends xr{constructor(t,e,i){super(t,"spatialGraph:edge"),this.spaces=[void 0,void 0],this.boundaryWalls=[null,null],this.element=null,this.vertices=[e,i]}getPoints(){return[this.vertices[0].position,this.vertices[1].position]}getLength(){return ai(...this.getPoints())}get isExternal(){return this.spaces.some(t=>!t||t.isExternal)}setVertices(t,e){if(t===e)return void be.warn("Cannot set both edge vertices to the same vertex.");let i,r,s=this.vertices[0],n=this.vertices[1];this.vertices[0]=t,this.vertices[1]=e,s!==t?(s.removeEdge(this),t.addEdge(this),i=!0):i=!1,n!==e?(n.removeEdge(this),e.addEdge(this),r=!0):r=!1,this.layout.spatialGraph.graphChanged=!0,this.element&&(this.element.edgesChanged=!0),this.resetSpatialIndexing(),(i||r)&&this.emit("edge-set-vertices",this,{previousVertices:[s,n]})}resetSpatialIndexing(){super.resetSpatialIndexing(),this.element&&this.element.resetSpatialIndexing()}calculateBoundingBox(){const[t,e]=this.getPoints();return{min:[Math.min(t[0],e[0]),0,Math.min(t[1],e[1])],max:[Math.max(t[0],e[0]),0,Math.max(t[1],e[1])]}}setVerticesByIds(t,e){let i=this.layout.spatialGraph,r=i.verticesById[t];if(!r)return void be.error(`Cannot find vertex ${t}.`);let s=i.verticesById[e];s?this.setVertices(r,s):be.error(`Cannot find vertex ${e}.`)}canSplit(t,e={}){let{minimumLength:i}=e;if(void 0!==i){if(t<0||t>1)return!1;let[e,r]=this.getPoints(),s=li(e,r,t),n=oi(di(s,e)),o=oi(di(s,r));if(n<i||o<i)return!1}else if(t<=0||t>=1)return!1;if(this.element){let[e,i]=this.getPoints(),r=li(e,i,t),[s]=this.element.getAxisPoints();if(!s)return!1;let n=this.element.getAxisLength(),o=ai(s,r)/n;return 0===Lr(this.element,o,!1).length}return!0}split(t,e={},i=!1){var r,s,n;let o=this.layout.spatialGraph,a=this.vertices[0],l=this.vertices[1],h=null==(r=this.element)?void 0:r.getAxisLength(),u=null==(n=null==(s=this.element)?void 0:s.getStartVertex())?void 0:n.position,[c,d]=this.getPoints(),p=li(c,d,t),f=e.vertexId??(this.layout.debugIds?o.debugVertexCount.toString():Ut()),m=o.verticesById[f]??o.createVertex(f,p[0],p[1]);this.setVertices(a,m);let g=e.edgeId??o.getEdgeId(),y=o.createEdge(g,m,l);if(y.spaces[0]=this.spaces[0],y.spaces[1]=this.spaces[1],y.boundaryWalls[0]=this.boundaryWalls[0],y.boundaryWalls[1]=this.boundaryWalls[1],this.element&&e.elementId&&h&&u){let i=ai(u,p)/h,r=this.element.getEdges(),s=r.indexOf(this)+1,n=[y,...r.splice(s)];this.element.setEdges(r);let o=e.elementId??this.layout.getElementId(this.element),a=this.layout.createElement(this.element.type,o,n);a.parameters=JSON.parse(JSON.stringify(this.element.parameters));let l=ai(u,p),c=[...this.element.elements];for(let e of c)if("element:opening"===e.type){let r=e.parameters.position[0],s=r/h,n=(r+e.parameters.dimensions[0])/h;i<=s?(e.parameters.position[0]=s*h-l,this.element.removeElement(e),a.insertElement(e)):t<n&&be.warn(`Opening ${e.id} overlaps split position.`)}}else if(this.element){const t=this.element.getEdges();this.element.setEdges([...t,y]),y.element=this.element}if(i)for(let v of y.spaces){if(!v)continue;let{boundary:t}=v.getBoundaryFromEdge(this);if(t){let e,i=t.vertices.indexOf(a),r=t.vertices.indexOf(l);e=0===i&&r===t.vertices.length-1?r:0===r&&i===t.vertices.length-1||i<r?i:r,t.vertices.splice(e+1,0,m),t.edges=[];for(let s=0;s<t.vertices.length;s++){let e=s,i=s<t.vertices.length-1?s+1:0,r=t.vertices[e],n=t.vertices[i],a=o.getEdgeFromVertices(r,n);a?t.edges.push(a):be.error(`Cannot find edge with vertices ${r.id} and ${n.id}.`)}}else be.error(`Edge ${this.id} not found in space boundary.`)}for(let v of y.boundaryWalls){if(!v)continue;let t,e=v.boundaries[0],i=e.vertices.indexOf(a),r=e.vertices.indexOf(l);t=0===i&&r===e.vertices.length-1?r:0===r&&i===e.vertices.length-1||i<r?i:r,e.vertices.splice(t+1,0,m),e.edges=[];for(let s=0;s<e.vertices.length;s++){let t=s,i=s<e.vertices.length-1?s+1:0,r=e.vertices[t],n=e.vertices[i],a=o.getEdgeFromVertices(r,n);a?e.edges.push(a):be.error(`Cannot find edge with vertices ${r.id} and ${n.id}.`)}}return{vertex:m,edge:y,element:undefined}}canMerge(t){if(this.element&&!t.element||!this.element&&t.element)return!1;let e,i=this.vertices[0],r=this.vertices[1],s=t.vertices[0],n=t.vertices[1];if(i===s)e=[r,i,n];else if(i===n)e=[r,i,s];else if(r===s)e=[i,r,n];else{if(r!==n)return!1;e=[i,r,s]}if(0!==gi(e[0].position,e[1].position,e[2].position))return!1;let o=e[1];return!(!o.edges.includes(this)||!o.edges.includes(t))}merge(t,e=!1){var i;if(this.element&&!t.element||!this.element&&t.element)return void be.warn("Either none or both edges must have an element, cannot merge.");let r,s,n=this.layout.spatialGraph,o=this.vertices[0],a=this.vertices[1],l=t.vertices[0],h=t.vertices[1];if(o===l)r=[h,o,a],s=!0;else if(o===h)r=[l,o,a],s=!1;else if(a===l)r=[o,a,h],s=!1;else{if(a!==h)return void be.warn(`Edge ${this.id} does not share a vertex with edge ${t.id}, cannot merge.`);r=[o,a,l],s=!0}let u=r[0].position,c=r[1].position;if(0!==gi(u,c,r[2].position))return void be.warn(`Edges ${this.id} and ${t.id} are not collinear, cannot merge.`);let d=r[1];if(d.edges.includes(this)&&d.edges.includes(t)||be.error(`Common vertex ${d.id} edge list does not contain either one or both edges, cannot merge.`),t.element&&s&&function(t){let e=t.getAxisLength();for(let i of t.elements){if("element:opening"!==i.type)continue;let t=i.parameters;t.position[0]=e-(t.position[0]+t.dimensions[0]),kr(i)}}(t.element),this.setVertices(r[0],r[2]),this.element&&this.element===t.element){const e=this.element.getEdges(),i=e.indexOf(t);e.splice(i,1),this.element.setEdges(e),t.element=null}else if(this.element&&t.element){const e=t.element.getEdges(),r=e.indexOf(t);e.splice(r,1);let s=[...this.element.getEdges(),...e];this.element.setEdges(s),t.element.setEdges([t]);for(const t of s)t.element=this.element;let n=null==(i=this.element.getStartVertex())?void 0:i.position;if(!n)return;let o=ai(c,n),a=[...t.element.elements];for(let i of a){if("element:opening"!==i.type)continue;t.element.removeElement(i),this.element.insertElement(i),i.parameters.position[0]+=o}}if(e)for(let p of t.spaces){if(!p)continue;let{boundary:e,edgeIndex:i}=p.getBoundaryFromEdge(t);if(e){e.edges.splice(i,1);let t=e.vertices.indexOf(r[1]);t>-1?e.vertices.splice(t,1):be.error(`Cannot find vertex ${r[1].id} in space ${p.id}`)}else be.error(`Cannot find edge ${t.id} in space ${p.id}.`)}for(let p of t.boundaryWalls){if(!p)continue;let e=p.boundaries[0],i=e.edges.indexOf(t);if(i>-1){e.edges.splice(i,1);let t=e.vertices.indexOf(r[1]);t>-1?e.vertices.splice(t,1):be.error(`Cannot find vertex ${r[1].id} in boundary wall ${p.id}`)}else be.error(`Cannot find edge ${t.id} in boundary wall ${p.id}.`)}t.spaces[0]=null,t.spaces[1]=null,t.boundaryWalls[0]=null,t.boundaryWalls[1]=null,n.removeEdge(t),0===d.edges.length&&n.removeVertex(d)}toJSON(){const t=this.vertices[0],e=this.vertices[1];return{...super.toJSON(),vertices:[t.id,e.id]}}}const Fr={usage:"generic",program:"none"};function Dr(t,e){const i=e.parent,r=i.getAxisLength(),{position:s,dimensions:n}=e.parameters,o=s[0]/r,a=(s[0]+n[0])/r;return i.getEdgesAtLinearSegment(o,a).some(e=>e.spaces[0]===t||e.spaces[1]===t)}class Ur extends vr{constructor(t,e){super(t,"layout:space"),ye(this,ue),ve(this,ue,null),this.boundaries=[],this.slabs=[],this.attributes={...Fr},this.boundaries=e,this.geometry={polygons:[]}}copyForClone(t){super.copyForClone(t),this.attributes=JSON.parse(JSON.stringify(t.attributes)),this.geometry=JSON.parse(JSON.stringify(t.geometry))}setId(t){if(t===this.id)return;let e=this.layout;if((null==e?void 0:e.spacesById[t])||(null==e?void 0:e.elementsById[t])||(null==e?void 0:e.annotationsById[t]))return void be.error(`ID ${t} already in use in layout ${e.id}.`);if(e&&e.spacesById[this.id]!==this)return void be.error(`Entry ${this.id} in 'spaces stored by ID' record does not contain space ${this.id}.`);let i=this.spaceGraph;if(null==i?void 0:i.nodesById[t])return void be.error(`ID ${t} already in use in space graph object.`);if(i&&i.nodesById[this.id]!==this)return void be.error(`Entry ${this.id} in 'nodes stored by ID' record does not contain space ${this.id}.`);let r=this.id;this.id=t,e&&(delete e.spacesById[r],e.spacesById[this.id]=this),i&&(delete i.nodesById[r],i.nodesById[this.id]=this),this.emit("node-id-change",this,r)}setAttributes(t){this.attributes.usage=t.usage??this.attributes.usage,this.attributes.program=t.program??this.attributes.program,this.emit("space-attributes-change",this)}get isExternal(){return["balcony","terrace","buildingOpening"].includes(this.attributes.usage)}calculateArea(){let t=this.geometry.polygons;if(0===t.length)return be.error(`Geometry has not been computed for space ${this.id}.`),0;let e=Pi(t[0]);for(let i=1;i<t.length;i++){e-=Pi(t[i])}return e}getArea(){return null===ge(this,ue)&&ve(this,ue,this.calculateArea()),ge(this,ue)}getAdjacentSpaces(t,{connectivity:e}={}){var i;let r=null==(i=t.nodeMap.get(this))?void 0:i.get("graph:adjacentTo");if(!r)return[];if(void 0===e)return Array.from(r);{let i=0===e?2:2*e;return Array.from(r).filter(r=>{let s=t.findShortestPath("graph:connectedTo",r,this,{depthLimit:i});return!!(null==s?void 0:s.length)&&(0!==e||"element:spaceDivider"===s[1].type)})}}getElements(t){let e=t&&(Array.isArray(t)?t:[t]),i=[],r=this.layout.getElementList();for(let s of r){if(e&&!e.includes(s.type))continue;let t;switch(s.type){case"element:ceiling":case"element:floor":t=s.space===this;break;case"element:boundaryWall":break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":t=s.getEdges().some(t=>t.spaces[0]===this||t.spaces[1]===this);break;case"element:opening":t=Dr(this,s);break;case"element:door":case"element:window":t=Dr(this,s.parent);break;default:{let e,i=s;if(i.parent){let t=i.parent;for(;t.parent;)t=t.parent;e=t.getTransform().position}else e=i.position;t=bi([e[0],e[2]],this.geometry.polygons);break}}t&&i.push(s)}return i}getBoundaryFromVertex(t){for(let e of this.boundaries){let i=e.vertices.indexOf(t);if(i>-1)return{boundary:e,itemIndex:i}}return{boundary:void 0,itemIndex:-1}}getBoundaryFromEdge(t){for(let e of this.boundaries){let i=e.edges.indexOf(t);if(i>-1)return{boundary:e,edgeIndex:i}}return{boundary:void 0,edgeIndex:-1}}calculateBoundingBox(){var t;const e=W([null==(t=this.boundaries[0])?void 0:t.geometryProfile]);let i=0,r=0;for(const s of this.slabs)"element:floor"===s.type&&(i=s.parameters.elevation),"element:ceiling"===s.type&&(r=s.parameters.elevation);return{min:[e.min[0],i,e.min[1]],max:[e.max[0],r,e.max[1]]}}getAxisAlignedBoundingBox(){const{min:t,max:e}=this.getBoundingBox();return{min:t,max:e}}resetBoundingBox(t){super.resetBoundingBox(t),ve(this,ue,null)}resetSpatialIndexing(){super.resetSpatialIndexing();for(const t of this.slabs)t.resetSpatialIndexing()}attachSlab(t){if(null!==t.space)return void be.warn(`Boundary slab ${t.id} already attached to space ${t.space.id}.`);this.slabs.indexOf(t)>-1?be.warn(`Boundary slab ${t.id} already referenced by space ${this.id}.`):(t.boundaries=this.boundaries,t.space=this,this.slabs.push(t),this.resetBoundingBox())}detachSlab(t){if(t.space!==this)return void be.warn(`Boundary slab ${t.id} not attached to space ${this.id}.`);let e=this.slabs.indexOf(t);-1!==e?(t.space=null,t.boundaries=ps(this.boundaries),this.slabs.splice(e,1),this.resetBoundingBox()):be.warn(`Boundary slab ${t.id} not referenced by space ${this.id}.`)}toJSON(){const{program:t,usage:e}=this.attributes,i={...super.toJSON(),boundaries:[],attributes:{program:t,usage:e}};for(const r of this.boundaries)i.boundaries.push(r.toJSON());return i}}ue=/* @__PURE__ */new WeakMap;class Gr extends Nr{constructor(t,e,i){super(t,e),this.boundaries=ps(i)}calculateBoundingBox(){const t=[0,0,0],e=[0,0,0],i=W([this.boundaries[0].geometryProfile]);return t[0]=i.min[0],e[0]=i.max[0],t[2]=i.min[1],e[2]=i.max[1],"element:floor"===this.type?(t[1]=this.parameters.elevation-this.parameters.height,e[1]=this.parameters.elevation):(t[1]=this.parameters.elevation,e[1]=this.parameters.elevation+this.parameters.height),{min:t,max:e}}}const Xr={top:"#202020",bottom:"#000000",side1:"asm:basic-wall",side2:"asm:basic-wall",join1:"asm:basic-wall",join2:"asm:basic-wall"},Wr={width:.15,height:3,offset:0,elevation:0,materials:{...Xr}};class Yr extends Rr{constructor(t,e){super(t,"element:wall",e);for(const i of e)i.element=this;this.parameters=JSON.parse(JSON.stringify(Wr)),this.geometryProfile={valid:!0,skipped:!1,selfIntersecting:!1,sidePoints1:[],sidePoints2:[],joinPoints1:[],joinPoints2:[],points:[]}}copyForClone(t){super.copyForClone(t),this.geometryProfile=JSON.parse(JSON.stringify(t.geometryProfile))}setParameters(t){super.setParameters(t)}calculateBoundingBox(){const t=[0,0,0],e=[0,0,0],[i,r]=this.getAxisPoints();if(!i||!r)return super.calculateBoundingBox();const s=ai(i,r),{width:n,offset:o}=this.parameters,a=-.5*n+o,l=a+n,h=W([[[0,a],[s,a],[s,l],[0,l]]]);return t[0]=h.min[0],e[0]=h.max[0],t[2]=h.min[1],e[2]=h.max[1],t[1]=this.parameters.elevation,e[1]=this.parameters.elevation+this.parameters.height,{min:t,max:e}}}const Hr={"element:ceiling":{height:.2,elevation:Wr.elevation+Wr.height,materials:{top:"#808080",bottom:"asm:basic-ceiling",sides:"asm:basic-wall"}},"element:floor":{height:.2,elevation:0,materials:{top:"asm:basic-floor",bottom:"#808080",sides:"asm:basic-wall"}}};class $r extends Gr{constructor(t,e,i){super(t,e,i);let r=Hr[this.type];this.parameters=JSON.parse(JSON.stringify(r)),this.space=null}setParameters(t){super.setParameters(t)}getSpaces(){return null===this.space?[]:[this.space]}}function jr(t,e){var i;let r,s=t.vertices.map(t=>t.position),n=[];for(let o of t.edges){if("element:wall"!==(null==(i=o.element)?void 0:i.type))continue;let t=o.element.geometryProfile.points;n.push(t)}if(0===n.length)r=[s];else if(e){r=z([s],Y(n))}else r=Y([s,...n]);return r=r.filter(t=>K(t)>1e-7),0===r.length?(be.warn("No valid polygons, returning boundary polygon."),s):(r=Q(r,.001),r=r.filter(t=>t.length>0),0===r.length?(be.warn("No valid polygons after filtering, returning boundary polygon."),s):(r.length>1&&(be.warn(`Result has ${r.length} polygons, returning largest one.`),r=r.sort((t,e)=>K(e)-K(t))),r[0]))}function zr(t,e){var i;let r=[jr(e.boundaries[0],!0)];for(let o=1;o<e.boundaries.length;o++){r=z(r,[jr(e.boundaries[o],!1)])}let{edges:s}=t.spatialGraph,n=[];for(let o of s){if(o.spaces[0]!==e||o.spaces[1]!==e||"element:wall"!==(null==(i=o.element)?void 0:i.type))continue;let[t,s]=o.getPoints();if(bi(li(t,s,.5),r)){let t=o.element.geometryProfile.points;n.push(t)}}n.length>0&&(r=z(r,n)),r.sort((t,e)=>{let i=K(t);return K(e)-i}),e.geometry.polygons=r}function Vr(t,e){return new Array(e-t).fill(void 0).map((e,i)=>t+i)}function qr(t){return`${t.type.split(":")[1]}Geometry-${t.id.substring(0,8)}`}function Jr(t){let e;switch(t.type){case"curve:rectangle":e=4;break;case"curve:polygon":e=t.points.length;break;case"curve:polygonWithHoles":e=t.polygons.reduce((t,e)=>t+Jr({type:"curve:polygon",points:e}),0);break;case"curve:composite":e=t.segments.reduce((t,e)=>t+Jr(e),0);break;case"curve:polyline":e=t.points.length-1;break;case"curve:circle":case"curve:arc":case"curve:line":e=1}return e}function Kr(){return Ge([Math.random(),Math.random(),Math.random()])}function Zr(t,e=!1){let{materials:i,height:r,elevation:s}=t.parameters,n="element:floor"===t.type?-r:0,o=[];for(let d=1;d<t.boundaries.length;d++){let e=t.boundaries[d].geometryProfile.slice();o.push(e)}o=Y(o);let a=t.boundaries[0].geometryProfile.slice(),l=s+n,h={id:`boundarySlabGeometry-${t.id}-boundary`,type:"geometry:extrusion",position:[0,l,0],height:r,profile:{type:"curve:polygonWithHoles",polygons:[a,...o]},geometries:[]},u={top:[0],bottom:[1],sides:Vr(2,2+a.length)},c={top:e?Kr():i.top,bottom:i.bottom,sides:i.sides};h.surfaces=u,h.materials=c,t.geometries=[{type:"reference:geometry",geometry:h}],t.emit("geometry-update",t)}function Qr(t){for(let e=0;e<t.boundaries.length;e++){const i=t.boundaries[e];for(const r of i.edges){const s=r.vertices[0],n=r.vertices[1],o=i.vertices.indexOf(s),a=i.vertices.indexOf(n);let l,h;if(l=0===o?1===a:o===i.vertices.length-1?0===a:a-o===1,h=0===e?l?1:0:l?0:1,null===r.spaces[h])r.spaces[h]=t;else{const t=0===h?"left":"right";be.error(`Edge ${r.id} already references a space on its ${t} side.`)}}}}function ts(t){for(const e of t.boundaries)for(const i of e.edges)i.spaces[0]||null!==i.boundaryWalls[0]?i.spaces[1]||null!==i.boundaryWalls[1]?be.error(`Edge ${i.id} referenced by more than two adjacent nodes.`):i.boundaryWalls[1]=t:i.boundaryWalls[0]=t}function es(t,e){let i=t.spatialGraph;for(let r=0;r<e.edges.length;r++){let t=e.edges[r],s=i.edgesById[t.id];s?e.edges[r]=s:i.insertEdge(t)}ls(e)}function is(t,e){if(0!==e.boundaries.length){for(let i of e.boundaries)es(t,i);switch(e.type){case"element:boundaryWall":ts(e);break;case"element:ceiling":case"element:floor":{let i=function(t,e){for(const i of t.spaces){if(i.boundaries.length!==e.length)continue;let t=0;for(;t<i.boundaries.length;){if(!hs(i.boundaries[t],e[t]))break;t++}if(t===i.boundaries.length)return cs(i,[{boundaries:e}])?i:void 0}return}(t,e.boundaries);i?i.attachSlab(e):be.warn(`Matching space not found for boundary slab element ${e.id}.`);break}}}else be.warn(`Boundary slab element ${e.id} does not specify boundaries.`)}function rs(t,e){let i=t.spatialGraph;const r=e.getEdges(),s=new Set(r);let n=!1;for(let o of r){let t=i.edgesById[o.id];t?(n=!0,s.delete(o),s.add(t)):i.insertEdge(o)}n&&e.setEdges(Array.from(s)),function(t){for(const e of t.getEdges())null===e.element?e.element=t:e.element!==t&&be.error(`Edge ${e.id} referenced by more than one edge element.`)}(e)}function ss(t){var e;switch(t.type){case"element:boundaryWall":case"element:ceiling":case"element:floor":!function(t){switch(t.type){case"element:boundaryWall":for(let e of t.boundaries)for(let i of e.edges)i.boundaryWalls[0]===t&&(i.boundaryWalls[0]=null),i.boundaryWalls[1]===t&&(i.boundaryWalls[1]=null);break;case"element:ceiling":case"element:floor":{let e=t.space;e?e.detachSlab(t):be.warn(`Boundary slab element ${t.id} not attached to a space.`);break}}}(t);break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":!function(t){for(const e of t.getEdges())e.element=null}(t);break;case"element:asset":null==(e=t.product)||e.instances.delete(t)}}function ns(t){const e=[];for(const i of t.boundaries){const t=[];for(const e of i.vertices)t.push(e.position);e.push(t)}return e}function os(t){let e=[];if(0===t.length)return e;if(1===t.length){let i=t[0];return e.push(i.vertices[0]),e.push(i.vertices[1]),e}for(let i=0;i<t.length;i++){let r=t[i],s=t[(i+1)%t.length],n=r.vertices[0],o=r.vertices[1],a=s.vertices[0],l=s.vertices[1];if(n===a||n===l)e.push(o);else{if(o!==a&&o!==l)return void be.warn(`Could not add edge ${r.id} to current path.`);e.push(n)}}return e}function as(t){let e=[];for(let i=0;i<t.length-1;i++){let r=t[i],s=t[i+1];for(let t of r.edges)if(s.edges.indexOf(t)>-1){e.push(t);break}}return e}function ls(t){let e=os(t.edges);if(!e)return!1;if(t.vertices=e,t.geometryProfile=t.vertices.map(t=>t.position),!Ti(t.geometryProfile)){let{vertices:e,edges:i,geometryProfile:r}=t;e.reverse(),r.reverse();{i.reverse();let t=e[e.length-1],r=i[0];r.vertices[0]!==t&&r.vertices[1]!==t||(e.pop(),e.unshift(t))}}return!0}function hs(t,e,i){if(t.edges.length!==e.edges.length)return!1;const r=function(t,e){let i=0;for(const r of t.edges)for(const t of e.edges)if(r.id===t.id){i++;break}return i}(t,e);let s;return s=r===t.edges.length,s}function us(t,e,i){if(t.length!==e.length)return!1;for(let r=0;r<t.length;r++){if(!hs(t[r],e[r]))return!1}return!0}function cs(t,e,i=!1){const r=.01;if(!i){const i=t.boundaries.map(t=>t.geometryProfile),s=e.map(t=>t.boundaries.map(t=>t.geometryProfile)),n=Z(i),o=s.map(t=>Z(t)).reduce((t,e)=>t+e,0);if(Math.abs(n-o)>r)return!1}const s=e.map(t=>[t.boundaries[0].geometryProfile]),{polygons:n}=j(s,.01),{polygons:o}=j(n,-.01);if(0===o.length)return be.warn(`No union polygon, cannot match space ${t.id}.`),!1;if(o.length>1)return be.warn(` Disjoint union area, cannot match space ${t.id}.`),!1;const a=o[0][0],l=t.boundaries[0].geometryProfile,h=V([[l]],[[a]]).polygons,u=V([[a]],[[l]]).polygons,c=h.length?Z(h[0]):0,d=u.length?Z(u[0]):0;return c<r&&d<r}function ds(t){let e=new hr;return e.vertices=[...t.vertices],e.edges=[...t.edges],e.geometryProfile=JSON.parse(JSON.stringify(t.geometryProfile)),e}function ps(t){let e=[];for(let i of t){let t=ds(i);e.push(t)}return e}function fs(t,e,i){for(let r of t.edges)r.spaces[0]===e?r.spaces[0]=i:r.spaces[1]===e?r.spaces[1]=i:be.warn(`Edge ${r.id} not in space ${e.id} boundary.`)}function ms(t,e,i,r){let s=function(t,e,i,r){let s=t.vertices,n=Math.min(e,i),o=Math.max(e,i),a=o-n+1,l=s.length-a+2;if(a<3||l<3)return be.warn("Cannot split boundary, both fragments should have three or more vertices."),[];let h=s.slice(0,n+1),u=s.slice(n,o+1),c=s.slice(o,s.length).concat(h),d=u,p=as(c).concat(r),f=as(d).concat(r),m=c.map(t=>t.position),g=d.map(t=>t.position),y=new hr;y.vertices=c,y.edges=p,y.geometryProfile=m;let v=new hr;return v.vertices=d,v.edges=f,v.geometryProfile=g,[y,v]}(t.boundaries[0],e,i,r);if(!s)return void be.warn(`Could not split outer boundary of space ${t.id}.`);let n=[s[0]],o=[s[1]];for(let f=1;f<t.boundaries.length;f++){let e=t.boundaries[f],i=e.vertices[0].position;if(xi(i,s[0].geometryProfile))n.push(e);else{if(!xi(i,s[1].geometryProfile)){be.warn("Inner boundary is not contained by either of the two split boundaries.");continue}o.push(e)}}let a,l,h=t.layout;(null==h?void 0:h.debugIds)?(a=h.getSpaceId(),l=h.getSpaceId()):(a=Ut(),l=Ut());let u=new Ur(a,n),c=new Ur(l,o);for(let f of n)fs(f,t,u);for(let f of o)fs(f,t,c);for(let f of n)u.geometry.polygons.push(f.geometryProfile);for(let f of o)c.geometry.polygons.push(f.geometryProfile);zr(h,u),zr(h,c);let d=[],p=[];for(let f=0;f<t.slabs.length;f++){let e,i,r=t.slabs[f];if(null==h?void 0:h.debugIds){let t="element:ceiling"===r.type?"ceiling":"floor";e=`${t}-${f+1}-in-${a}`,i=`${t}-${f+1}-in-${l}`}else e=Ut(),i=Ut();let s=new $r(e,r.type,n),u=new $r(i,r.type,o);Zr(s,!0),Zr(u,!0),d.push(s),p.push(u)}return{spaces:[u,c],slabs:[d,p]}}function gs(t,e){let{position:i,rotation:r,rotationAxis:s}=t.getTransform(),n=Ai(i,r,s);return e&&ht(n,e,n),n}function ys(t){let e;return t.parent&&(e=ys(t.parent)),gs(t,e)}function vs(t,e){switch(e.type){case"annotation:floorPlanDxf":case"annotation:floorPlanImage":return{name:"annotation",nodes:t.annotations,nodesById:t.annotationsById,nodesByType:t.annotationsByType};case"view:2d":case"view:3d":return{name:"view",nodes:t.views,nodesById:t.viewsById,nodesByType:t.viewsByType}}}class xs{constructor(t){this.vertices=[],this.verticesById={},this.edges=[],this.edgesById={},this.graphChanged=!1,this.debugVertexCount=0,this.debugEdgeCount=0,this.layout=t}emit(t,...e){let i=this.layout.spaceGraph;i&&i.emit(t,...e)}copyForClone(t){this.debugVertexCount=t.debugVertexCount,this.debugEdgeCount=t.debugEdgeCount}deleteVertexAtIndex(t,e){let i=this.vertices[t];if(e){let t=i.edges.slice();for(let r of t){let t=r.vertices[0],s=r.vertices[1];t!==i&&s!==i||this.removeEdge(r,e)}}if(this.vertices.splice(t,1),this.verticesById[i.id]===i)return delete this.verticesById[i.id],i;be.error(`Entry ${i.id} in 'vertices by ID' record does not contain this object.`)}deleteEdgeAtIndex(t,e){let i=this.edges[t];if(i.element&&this.layout.removeElement(i.element),i.vertices[0].removeEdge(i),i.vertices[1].removeEdge(i),e){if(i.spaces[0]!==i.spaces[1]){if(i.spaces[0]){let t=i.spaces[0].slabs;for(let e of t)this.layout.removeElement(e);this.layout.removeSpace(i.spaces[0])}if(i.spaces[1]){let t=i.spaces[1].slabs;for(let e of t)this.layout.removeElement(e);this.layout.removeSpace(i.spaces[1])}}i.boundaryWalls[0]&&this.layout.removeElement(i.boundaryWalls[0]),i.boundaryWalls[1]&&this.layout.removeElement(i.boundaryWalls[1])}if(this.edges.splice(t,1),this.edgesById[i.id]===i)return delete this.edgesById[i.id],this.graphChanged=!0,i;be.error(`Entry ${i.id} in 'edges by id' record does not contain this object.`)}insertVertex(t){if(!_r(this.layout,t,this.edgesById,"Edge"))return;t.layout=this.layout,this.vertices.push(t),this.verticesById[t.id]=t;let e=this.layout.spaceGraph;e&&(e.registerNode(t),e.emit("vertex-create",t))}removeVertex(t,e=!1){let i=this.vertices.indexOf(t);if(-1===i)return void be.warn(`Vertex ${t.id} not found.`);this.deleteVertexAtIndex(i,e);let r=this.layout.spaceGraph;return r&&(r.unregisterNode(t),r.emit("vertex-delete",t)),t.layout=null,t}removeVertexAtIndex(t,e=!1){let i=this.vertices[t];if(!i)return void be.warn(`Vertex not found at index ${t}.`);this.deleteVertexAtIndex(t,e);let r=this.layout.spaceGraph;return r&&(r.unregisterNode(i),r.emit("vertex-delete",i)),i.layout=null,i}removeVertexById(t,e=!1){let i=this.verticesById[t];if(i&&i.id===t)return this.removeVertex(i,e);be.error(`Entry ${t} in 'vertices by id' record does not contain this object.`)}insertEdge(t,e=!1){if(!_r(this.layout,t,this.edgesById,"Edge"))return;let i=this.verticesById[t.vertices[0].id],r=this.verticesById[t.vertices[1].id];i?t.vertices[0]=i:this.insertVertex(t.vertices[0]),r?t.vertices[1]=r:this.insertVertex(t.vertices[1]),t.layout=this.layout,this.edges.push(t),this.edgesById[t.id]=t,t.vertices[0].addEdge(t),t.vertices[1].addEdge(t);let s=this.layout.spaceGraph;s&&(s.registerNode(t),s.emit("edge-create",t)),e&&function(t){let e=t.layout,i=t.vertices[0],r=t.vertices[1];for(let s of e.spaces){let n=s.boundaries[0],o=n.vertices.indexOf(i),a=n.vertices.indexOf(r);if(o>-1&&a>-1){t.spaces[0]=s,t.spaces[1]=s;let i=ms(s,o,a,t);if(i){let r=s.slabs.slice();for(let t of r)e.removeElement(t);e.removeSpace(s);let[n,o]=i.spaces,[a,l]=i.slabs;e.insertSpace(n);for(let t of a)e.insertElement(t);e.insertSpace(o);for(let t of l)e.insertElement(t);t.emit("space-split",s,[n,o]),n.emit("geometry-profile-update",n),o.emit("geometry-profile-update",o);for(let t of n.slabs)t.emit("geometry-profile-update",t);for(let t of o.slabs)t.emit("geometry-profile-update",t)}else be.warn(`Failed to split space ${s.id}.`);break}}}(t),this.graphChanged=!0}removeEdge(t,e=!1){let i=this.edges.indexOf(t);if(-1===i)return void be.warn(`Edge ${t.id} not found.`);this.deleteEdgeAtIndex(i,e);let r=this.layout.spaceGraph;return r&&(r.unregisterNode(t),r.emit("edge-delete",t)),t.layout=null,t}removeEdgeAtIndex(t,e=!1){let i=this.edges[t];if(!i)return void be.warn(`Edge not found at index ${t}.`);this.deleteEdgeAtIndex(t,e);let r=this.layout.spaceGraph;return r&&(r.unregisterNode(i),r.emit("edge-delete",i)),i.layout=null,i}removeEdgeById(t,e=!1){let i=this.edgesById[t];if(i&&i.id===t)return this.removeEdge(i,e);be.error(`Entry ${t} in 'edges by id' record does not contain this object.`)}getEdgeFromVertices(t,e){let i=t.edges,r=e.edges;for(let s of i)for(let t of r)if(s===t)return s}getVertexId(t){return this.layout.debugIds?(t??"vertex-")+this.debugVertexCount:Ut()}getEdgeId(t){return this.layout.debugIds?(t??"edge-")+this.debugEdgeCount:Ut()}createVertex(t,e,i){let r=new br(t,e,i);return this.insertVertex(r),r}createEdge(t,e,i,r=!1){let s=new Br(t,e,i);return this.insertEdge(s,r),s}createEdgeByVertexIds(t,e,i,r=!1){let s=this.verticesById[e],n=this.verticesById[i];return this.createEdge(t,s,n,r)}toJSON(){let t=[];for(let i of this.vertices){let e=i.toJSON();t.push(e)}let e=[];for(let i of this.edges){let t=i.toJSON();e.push(t)}return{vertices:t,edges:e}}}const bs={height:3,elevation:0,surfaces:{top:[0],bottom:[1],sides:"..."},materials:{top:"#202020",bottom:"#000000",sides:"asm:basic-wall"}};class _s extends Gr{constructor(t,e){super(t,"element:boundaryWall",e),this.parameters=JSON.parse(JSON.stringify(bs))}setParameters(t){super.setParameters(t)}}const ws={materials:{}};class Ps extends Rr{constructor(t,e){super(t,"element:curtainWall",e);for(const i of e)i.element=this;this.parameters=JSON.parse(JSON.stringify(ws))}setParameters(t){super.setParameters(t)}}const Es={materials:{}};class Ts extends Rr{constructor(t,e){super(t,"element:spaceDivider",e);for(const i of e)i.element=this;this.parameters=JSON.parse(JSON.stringify(Es))}setParameters(t){super.setParameters(t)}calculateBoundingBox(){const[t,e]=this.getAxisPoints();if(!t||!e)return super.calculateBoundingBox();return{min:[0,0,-.01],max:[ai(t,e),0,.01]}}}class As extends Nr{constructor(t,e){super(t,e)}}function Is(t,e,i=0){let{width:r,offset:s,elevation:n}=t.parameters,[o,a]=t.getAxisPoints();if(!o||!a)return{position:[0,0,0],rotation:0};let l=di(a,o),h=oi(l),u=li(o,a,e.parameters.position[0]/h);u=ii(u,ci(ui(hi(l)),-.5*r+s-i));let c=e.parameters.position[1]+n;return{position:[u[0],c,u[1]],rotation:180*-ri(di(a,o))/Math.PI}}function Ss(t,e,i,r){const s=.001;let n=r.parameters.dimensions[0],o=r.parameters.dimensions[1],{width:a,elevation:l}=e.parameters,{position:[h,u,c],rotation:d}=Is(e,r,s),p=r.parameters.materials,f={id:i,type:"geometry:cuboid",position:[h,u-s-l,c],rotation:d,dimensions:[n,o+s,a+.002],surfaces:{top:[0],bottom:[1],frontBack:[2,4],sides:[3,5]}},m={top:p.top,bottom:p.bottom,frontBack:"#FFFFFF",sides:p.sides};f.materials=m;let g=e.geometries[0].geometry;g.geometries??(g.geometries=[]),g.geometries.push({type:"csg:subtract",geometry:f}),r.emit("geometry-update",r)}function Cs(t,e){let i,r={},s=Vr(0,e);for(let[n,o]of Object.entries(t))if("string"==typeof o)"..."===o?i=n:be.warn("Invalid surface definition string.");else if(Array.isArray(o)){r[n]=[];for(let t of o){if(t<0||t>=e){be.warn(`Face index ${t} out of range when defining surface ${n}.`);continue}let i=s.indexOf(t);-1!==i?(r[n].push(t),s.splice(i,1)):be.warn(`Face index ${t} already assigned when defining surface ${n}.`)}}else be.warn("Invalid surface definition.");return i&&s.length>0&&(r[i]=s),r}function Ms(t){let e,{surfaces:i,materials:r}=t.parameters;for(let s=0;s<t.boundaries.length;s++){let n=t.boundaries[s],o=t.parameters.elevation,a=os(n.edges);if(!a)return void be.warn(`Could not create geometry for boundary wall ${t.id}.`);let l=a.map(t=>t.position),h=0===s?"boundary":"hole-"+s,u={id:`boundaryWallGeometry-${t.id}-${h}`,type:"geometry:extrusion",position:[0,o,0],height:t.parameters.height,profile:{type:"curve:polygon",points:l},geometries:[]};u.surfaces=Cs(i,2+l.length),u.materials=JSON.parse(JSON.stringify(r)),0===s?(e=u,t.geometries=[{type:"reference:geometry",geometry:u}]):e.geometries.push({type:"csg:subtract",geometry:u})}t.emit("geometry-update",t)}function Os(t){let{length:e,height:i,frameThickness:r,frameDepth:s,doorAngle:n,hingeSide:o,doorSide:a,doorType:l,materials:h}=t.parameters,u="right"===o,c=[e/2,s/2],d=qr(t),p=.05,f=[],m=(180-Math.min(180,Math.max(0,n)))/180,g=(s-p)/2,y=e-2*r,v=i-r;switch(l){case"singleSwing":u?f.push({position:[r-c[0],0,-c[1]],rotation:n,dimensions:[y,v,p]}):f.push({position:[c[0]-r,0,-c[1]],dimensions:[p,v,y],rotation:270-n});break;case"doubleSwing":y=e/2-r,f.push({position:[r-c[0],0,-c[1]],rotation:n,dimensions:[y,v,p]}),f.push({position:[c[0]-r,0,-c[1]],rotation:270-n,dimensions:[p,v,y]});break;case"slidingDoor":y=(e-2*r)*m;let t=u?r-c[0]:c[0]-y-r;f.push({position:[t,0,-c[1]+g],rotation:0,dimensions:[y,v,p]});break;case"garageDoor":f.push({position:[r-c[0],v*(1-m),-c[1]+g],rotation:0,dimensions:[y,v*m,p]});break;case"elevatorDoor":y=(e-2*r)/2-.005,f.push({position:[r-c[0],0,-c[1]+g],rotation:0,dimensions:[y,v,p]}),f.push({position:[0,0,-c[1]+g],rotation:0,dimensions:[y,v,p]})}let x=[];for(let b=0;b<f.length;b++){let{position:t,rotation:e,dimensions:i}=f[b],r={id:d+"-leaf-"+b,type:"geometry:cuboid",position:t,rotation:e,dimensions:i,material:h.leaf};x.push({type:"reference:geometry",position:[c[0],0,c[1]],rotation:"side2"===a?180:0,geometry:r})}return x}function Ns(t,e,i){let r=qr(t),{stepCount:s,stepHeight:n,angle:o,radius:a,width:l,circulation:h}=i,u=a-l,c=a-l/2,d=Math.PI*o/180*c/s/(u+l/2),p=[0,n,0],f=180/Math.PI*d,m=0;"right"===h&&(f=-f,m=180);let g=function(t,e,i){let{stepThickness:r,stepHeight:s,angle:n,width:o,stepCount:a,radius:l,circulation:h}=i,u=l-o/2,c=l-o,d=Math.PI*n/180*u/a/(c+o/2),p="right"===h,f=s,m=c,g=(p?-1:1)*Math.sin(d)*c,y=s-r,v=Math.cos(d)*c,x=-r,b=c+o,_=(p?-1:1)*Math.sin(d)*(c+o),w=Math.cos(d)*(c+o),P=[0,f,m,0,0,m,g,y,v,g,f,v,0,x,m,0,f,b,0,0,b,_,y,w,_,f,w,0,x,b],E=[0,8,3,0,5,8,0,3,2,0,2,1,1,2,4,0,6,5,0,1,6,5,7,8,5,6,7,6,9,7,2,7,4,4,7,9,8,7,3,7,2,3];if(p)for(let T=0;T<E.length;T+=3){let t=E[T+1];E[T+1]=E[T+2],E[T+2]=t}return{id:t,type:"geometry:mesh",vertices:P,indices:E,rotation:0,surfaces:{top:[0,1],base:[2,3,4,5,6,7,8,9,10,11,12,13]},materials:{top:e.tread,base:e.steps}}}(r,e,i);return{type:"reference:geometry",position:{type:"vector3:range",range:{start:[0,0,0],step:p,count:s}},rotation:{type:"number:range",range:{start:m,step:f,count:s}},geometry:g}}function Ls(t){let{width:e,height:i,materials:r}=t.parameters;const s=Math.max(1,Math.round(i/.17)),n={height:i,width:e,stepCount:s,stepHeight:i/s,stepThickness:.1};let o;if("straight"===t.parameters.stairFlightType){let{length:e}=t.parameters;o=function(t,e,i){let{stepCount:r,width:s,stepHeight:n,length:o,stepThickness:a}=i,l=o/r,h=[l,n,0],u=function(t,e,i){let{riser:r,tread:s,width:n,thickness:o}=i;return{id:t,type:"geometry:extrusion",rotation:90,rotationAxis:[1,0,0],height:n,profile:{type:"curve:polygon",points:[[0,0],[0,o],[s,o-r],[s,-r],[0,-r]]},surfaces:{top:[5],base:[0,1,2,3,4,6]},materials:{top:e.tread,base:e.steps}}}(qr(t),e,{tread:l,riser:n,width:s,thickness:a});return{type:"reference:geometry",position:{type:"vector3:range",range:{start:[0,0,0],step:h,count:r}},geometry:u}}(t,r,{...n,length:e})}else{let{radius:e,angle:i,circulation:s}=t.parameters;o=Ns(t,r,{...n,radius:e,angle:i,circulation:s})}t.geometries=[o],t.emit("geometry-update",t)}function Rs(t,e=!1){let{sidePoints1:i,sidePoints2:r,joinPoints1:s,joinPoints2:n,points:o}=t.geometryProfile;if(0===o.length)return;let a="wallGeometry-"+t.id,l={id:a,type:"geometry:extrusion",position:[0,t.parameters.elevation,0],height:t.parameters.height,profile:{type:"curve:composite",segments:[{type:"curve:polyline",points:i},{type:"curve:polyline",points:s},{type:"curve:polyline",points:r},{type:"curve:polyline",points:n}]}},h=t.parameters.materials,u={top:[0],bottom:[1],side1:[2],side2:[4]},c={top:e?Kr():h.top??Xr.top,bottom:h.bottom??Xr.bottom,side1:h.side1??Xr.side1,side2:h.side2??Xr.side2},[d,p]=function(t){let e=[!1,!1],i=[t.getStartVertex(),t.getEndVertex()];for(let r=0;r<i.length;r++){let t=i[r];t&&(t.edges.filter(t=>{var e;return"element:wall"===(null==(e=t.element)?void 0:e.type)}).map(t=>t.element).length>0?e[r]=!0:be.error(`Vertex ${t.id} not referencing edge that references it.`))}return e}(t);d&&(u.join1=[3],c.join1=h.join1??Xr.join1),p&&(u.join2=[5],c.join2=h.join2??Xr.join2),l.surfaces=u,l.materials=c,t.geometries=[{type:"reference:geometry",geometry:l}];for(let f=0;f<t.elements.length;f++){let e=t.elements[f];if("element:opening"!==e.type)continue;let i=a+"-opening-"+(f+1);Ss(t.layout,t,i,e)}t.emit("geometry-update",t)}function ks(t){switch(t.type){case"element:asset":case"element:beam":case"element:curtainWall":case"element:opening":case"element:ramp":case"element:roof":case"element:spaceDivider":case"element:stairs":break;case"element:casework":!function(t){let{length:e,width:i,height:r,counterHeight:s,materials:n}=t.parameters,o=Math.min(.6,e),a=Math.floor(e/o),l=e%o,h=i-.02,u=r-s,c=.02,d=qr(t),p=[],f=t.elements;for(let y of f)if("product"in y&&y.product){let{min:t,max:e}=y.product.attributes.boundingBox,i=fi(t,[0,.01,0]),r=fi(e,i),s=pi(i,y.position);p.push({id:d+"-subtraction-"+y.id.substring(0,8),type:"geometry:cuboid",position:[...s],dimensions:r})}let m=[];s>0&&m.push({id:d+"-counter",type:"geometry:cuboid",position:[0,u,0],dimensions:[e,s,i],material:n.counter}),m.push({id:d+"-doors",type:"geometry:cuboid",position:{type:"vector3:range",range:{start:[c,c,h],step:[o,0,0],count:a}},dimensions:[o-.04,u-.04,c],material:n.cabinetDoors}),l>.04&&m.push({id:d+"-doors+2",type:"geometry:cuboid",position:[a*o+c,c,h],dimensions:[l-.04,u-.04,c],material:n.cabinet});let g={id:d+"-cabinet",type:"geometry:cuboid",position:[0,0,0],dimensions:[e,u,h],geometries:[...m.map(t=>({type:"reference:geometry",geometry:t})),...p.map(t=>({type:"csg:subtract",geometry:t}))],material:n.cabinet};t.geometries=[{type:"reference:geometry",geometry:g}],t.emit("geometry-update",t)}(t);break;case"element:column":!function(t){let{profile:e,height:i,materials:r}=t.parameters,s=qr(t),n=[0,0,0];"curve:rectangle"===e.type&&(n=[-e.dimensions[0]/2,0,-e.dimensions[1]/2]);let o={id:s,type:"geometry:extrusion",position:n,profile:e,height:i},a=Jr(e);o.surfaces={top:[0],bottom:[1],sides:Vr(2,2+a)},o.materials={top:r.top,bottom:r.bottom,sides:r.sides},t.geometries=[{type:"reference:geometry",geometry:o}],t.emit("geometry-update",t)}(t);break;case"element:ceiling":case"element:floor":Zr(t);break;case"element:boundaryWall":Ms(t);break;case"element:door":!function(t){let{height:e,length:i,frameThickness:r,frameDepth:s,materials:n}=t.parameters,o=qr(t),a={id:o+"-frame-top",type:"geometry:cuboid",position:[0,e-r,0],rotation:0,dimensions:[i,r,s],material:n.frame},l={id:o+"-frame-side",type:"geometry:cuboid",position:{type:"vector3:list",list:[[0,0,0],[i-r,0,0]]},rotation:0,dimensions:[r,e-r,s],material:n.frame};t.geometries=[{type:"reference:geometry",geometry:a},{type:"reference:geometry",geometry:l},...Os(t)],t.emit("geometry-update",t)}(t);break;case"element:generic":!function(t){let{profile:e,height:i,materials:r}=t.parameters;if("none"===e)return;let s=Jr(e),n={id:qr(t),type:"geometry:extrusion",position:[0,0,0],profile:e,height:i,surfaces:{top:[0],bottom:[1],sides:Vr(2,2+s)},materials:{top:r.top,bottom:r.bottom,sides:r.sides}};t.geometries=[{type:"reference:geometry",geometry:n}],t.emit("geometry-update",t)}(t);break;case"element:railing":!function(t){let e,{height:i,length:r,width:s,segmentCount:n,segmentLength:o,materials:a}=t.parameters,l=.01;e=o&&o>0?Math.max(Math.round(r/o),1):n&&n>0?n:Math.max(Math.round(r/.12),1);let h=(r-l)/e,u=qr(t),c={id:u+"-horizontal",type:"geometry:cuboid",position:{type:"vector3:list",list:[[0,i-l,-s/2],[0,0,-s/2]]},rotation:0,dimensions:[r,l,s],material:a.surface},d={id:u+"-vertical",type:"geometry:cuboid",position:{type:"vector3:range",range:{start:[0,l,-s/2],step:[h,0,0],count:e+1}},rotation:0,dimensions:[l,i-.02,s],material:a.surface};t.geometries=[{type:"reference:geometry",geometry:c},{type:"reference:geometry",geometry:d}],t.emit("geometry-update",t)}(t);break;case"element:slab":!function(t){let{profile:e,height:i,materials:r}=t.parameters,s={id:qr(t),type:"geometry:extrusion",position:[0,0,0],profile:e,height:i},n=Jr(e);s.surfaces={top:[0],bottom:[1],sides:Vr(2,2+n)},s.materials={top:r.top,bottom:r.bottom,sides:r.sides},t.geometries=[{type:"reference:geometry",geometry:s}],t.emit("geometry-update",t)}(t);break;case"element:stairFlight":Ls(t);break;case"element:wall":Rs(t);break;case"element:window":!function(t){let{panelCount:e,panelLength:i,height:r,length:s,frameThickness:n,frameDepth:o,materials:a}=t.parameters,l=qr(t),h={id:l,type:"geometry:cuboid",position:{type:"vector3:list",list:[[0,r-n,0],[0,0,0]]},rotation:0,dimensions:[s,n,o],material:a.frame},u=[[0,n,0]],c=s-n;if(e&&(i=c/e),i&&i>n){let t=i;for(;t<c;)u.push([t,n,0]),t+=i}u.push([s-n,n,0]);let d={id:l+"-vertical",type:"geometry:cuboid",position:{type:"vector3:list",list:u},rotation:0,dimensions:[n,r-2*n,o],material:a.frame},p={id:l+"-glass",type:"geometry:extrusion",position:[n,n,o/2],rotation:0,height:r-2*n,profile:{type:"curve:rectangle",dimensions:[s-2*n,.01]},material:a.panel};t.geometries=[{type:"reference:geometry",geometry:h},{type:"reference:geometry",geometry:d},{type:"reference:geometry",geometry:p}],t.emit("geometry-update",t)}(t)}for(let e of t.elements)ks(e)}const Bs={position:[0,0],dimensions:[1,2],materials:{top:"#FFFFFF",bottom:"#FFFFFF",sides:"#FFFFFF"}};class Fs extends As{constructor(t){super(t,"element:opening"),this.parameters=JSON.parse(JSON.stringify(Bs))}getTransform(){var t;if("element:wall"!==(null==(t=this.parent)?void 0:t.type)){const t=this.parent?`Parent of element ${this.id} is not a wall.`:`Element ${this.id} does not have a parent.`;return be.error(t),{position:[0,0,0],rotation:0,rotationAxis:[0,1,0]}}let{position:e,rotation:i}=Is(this.parent,this);return{position:e,rotation:i,rotationAxis:[0,1,0]}}get position(){return this.getTransform().position}get rotation(){return this.getTransform().rotation}setParameters(t){let e=!!t.position,i=!!t.dimensions;if(super.setParameters(t),this.emit("element-parameters-change",this),e||i){let t=this.parent;if(t&&ks(t),i)for(let e of this.elements)ks(e);this.resetSpatialIndexing()}}getBoundingBox(t=!1){const{dimensions:e}=this.parameters,i=this.parent,r=(null==i?void 0:i.parameters.width)||0;return{min:[0,0,0],max:[e[0],e[1],r],transform:t?this.getTransform():this.getWorldTransform()}}getSpaces(){if(this.parent){return this.parent.getSpaces().filter(t=>Dr(t,this))}return be.error(`Element ${this.id} does not have a parent.`),[]}get isExternal(){const t=this.parent;if(!t)return super.isExternal;const[e]=t.getAxisPoints();if(!e)return super.isExternal;const i=t.getAxisLength(),{position:r,dimensions:s}=this.parameters,n=r[0]/i,o=(r[0]+s[0])/i,a=t.getEdgesAtLinearSegment(n,o);if(1===a.length)return a[0].isExternal;let l=0,h=0;for(const u of a){const[t,r]=u.getPoints().map(t=>ai(e,t)/i).sort((t,e)=>t-e),s=(o>r?r:o)-(n>t?n:t);u.isExternal?l+=s:h+=s}return l>=h}}class Ds extends Nr{constructor(t,e){super(t,e),this.position=[0,0,0],this.rotation=0,this.rotationAxis=[0,1,0]}copyForClone(t){super.copyForClone(t),this.position=[...t.position],this.rotation=t.rotation,this.rotationAxis=[...t.rotationAxis]}setPosition(t){this.position=[...t],this.resetTransform(!0),this.emit("element-transform-change",this)}setRotation(t,e){this.rotation=t,e&&(this.rotationAxis=[...e]),this.resetTransform(!0),this.emit("element-transform-change",this)}setTransform(t,e,i){this.position=[...t],this.rotation=e,i&&(this.rotationAxis=[...i]),this.resetTransform(!0),this.emit("element-transform-change",this)}getSpaces(){if(this.parent)return this.parent.getSpaces();let t=[this.position[0],this.position[2]];for(let e of this.layout.spaces)if(bi(t,e.geometry.polygons))return[e];return[]}calculateTransform(){return{position:[...this.position],rotation:this.rotation,rotationAxis:[...this.rotationAxis]}}calculateWorldTransform(){if(!this.parent)return this.getTransform();let t=ys(this),{position:e,rotation:i,rotationAxis:r}=Ii(t);return 0===r[0]&&r[1]<0&&0===r[2]&&(r=[0,1,0],i=-i),{position:e,rotation:i,rotationAxis:r}}calculateBoundingBox(){const t=[0,0,0],e=[0,0,0];if("length"in this.parameters&&(e[0]=this.parameters.length),"height"in this.parameters&&(e[1]=this.parameters.height),"width"in this.parameters?e[2]=this.parameters.width:"frameDepth"in this.parameters&&(e[2]=this.parameters.frameDepth),"radius"in this.parameters&&(t[0]=t[2]=-this.parameters.radius,e[0]=e[2]=this.parameters.radius),"profile"in this.parameters&&"none"!==this.parameters.profile)switch(this.parameters.profile.type){case"curve:rectangle":{let[i,r]=this.parameters.profile.dimensions;e[0]=i,e[2]=r,"element:column"===this.type&&(t[0]=-i/2,e[0]=i/2,t[2]=-r/2,e[2]=r/2);break}case"curve:circle":t[0]=t[2]=-this.parameters.profile.radius,e[0]=e[2]=this.parameters.profile.radius;break;case"curve:polygon":let i=W([this.parameters.profile.points]);t[0]=i.min[0],e[0]=i.max[0],t[2]=i.min[1],e[2]=i.max[1]}return{min:t,max:e}}setParameters(t){super.setParameters(t),ks(this)}}const Us={materials:{}};class Gs extends Ds{constructor(t){super(t,"element:asset"),this.product=null,this.parameters=JSON.parse(JSON.stringify(Us))}get isComponentInstance(){var t;return"product:component"===(null==(t=this.product)?void 0:t.type)}get isComponentInstanceChild(){var t;return"element:asset"===(null==(t=this.parent)?void 0:t.type)&&this.parent.isComponentInstance}setParameters(t){super.setParameters(t)}setProduct(t){this.product=t,this.product.instances.add(this),this.resetBoundingBox(),this.emit("node-property-change",this,"product"),this.emit("geometry-update",this)}calculateBoundingBox(){if(!this.product)return super.calculateBoundingBox();const{min:t,max:e}=this.product.attributes.boundingBox;return{min:t,max:e}}}const Xs={length:2,width:.1,height:.2,materials:{top:"#202020",bottom:"#000000",sides:"asm:basic-wall"}};class Ws extends Ds{constructor(t){super(t,"element:beam"),this.parameters=JSON.parse(JSON.stringify(Xs))}setParameters(t){super.setParameters(t)}}const Ys={length:2,height:.7,width:.6,counterHeight:.03,materials:{cabinet:"asm:cabinet_paint_white",cabinetDoors:"asm:cabinet_paint_white",counter:"asm:cabinet_paint_white"}};class Hs extends Ds{constructor(t){super(t,"element:casework"),this.parameters=JSON.parse(JSON.stringify(Ys))}setParameters(t){super.setParameters(t)}}const $s={type:"curve:circle",radius:.1},js={"curve:circle":{...$s},"curve:rectangle":{type:"curve:rectangle",dimensions:[.1,.1]},"curve:polygon":{type:"curve:polygon",points:[[0,0],[.1,0],[.1,.1],[0,.1]]},"curve:polygonWithHoles":{type:"curve:polygonWithHoles",polygons:[[[0,0],[.1,0],[.1,.1],[0,.1]],[[.02,.02],[.02,.08],[.08,.08],[.08,.02]]]}},zs={profile:{...$s},height:3,materials:{top:"#202020",bottom:"#000000",sides:"asm:basic-wall"}};class Vs extends Ds{constructor(t){super(t,"element:column"),this.parameters=JSON.parse(JSON.stringify(zs))}setParameters(t){var e;(null==(e=t.profile)?void 0:e.type)&&t.profile.type!==this.parameters.profile.type&&(this.parameters.profile=JSON.parse(JSON.stringify(js[t.profile.type]))),super.setParameters(t)}}const qs={length:1,height:2,frameThickness:.05,frameDepth:.1,doorType:"singleSwing",doorAngle:90,hardware:!0,hingeSide:"right",doorSide:"side1",materials:{frame:"asm:doorLeaf-flush-white",leaf:"asm:doorLeaf-flush-white"}};class Js extends Ds{constructor(t){super(t,"element:door"),this.parameters=JSON.parse(JSON.stringify(qs))}setParameters(t){super.setParameters(t)}calculateBoundingBox(){const t=super.calculateBoundingBox(),{doorType:e,frameThickness:i,frameDepth:r,doorSide:s,length:n}=this.parameters;if("singleSwing"===e||"doubleSwing"===e){const o="singleSwing"===e?n-2*i:n/2-i;"side1"===s?t.min[2]=-o:t.max[2]=r+o}return t}}const Ks={"curve:circle":{type:"curve:circle",radius:.5},"curve:rectangle":{type:"curve:rectangle",dimensions:[1,1]},"curve:polygon":{type:"curve:polygon",points:[[0,0],[1,0],[1,1],[0,1]]},"curve:polygonWithHoles":{type:"curve:polygonWithHoles",polygons:[[[0,0],[1,0],[1,1],[0,1]],[[.25,.25],[.25,.75],[.75,.75],[.75,.25]]]}},Zs={profile:"none",height:0,materials:{top:"#F0F0F0",bottom:"#F0F0F0",sides:"#F0F0F0"}};class Qs extends Ds{constructor(t){super(t,"element:generic"),this.parameters=JSON.parse(JSON.stringify(Zs))}setParameters(t){t.profile&&"none"!==t.profile&&t.profile.type&&"none"!==this.parameters.profile&&this.parameters.profile.type!==t.profile.type&&(this.parameters.profile=JSON.parse(JSON.stringify(Ks[t.profile.type]))),super.setParameters(t)}}const tn="product:static",en={manufacturer:"",categories:[],subCategories:[],thumbnail:"",boundingBox:{min:[0,0,0],max:[0,0,0]},seatCapacity:0,updatedAt:""};class rn extends gr{constructor(t,e){super(t,e),ye(this,ce),this.instances=/* @__PURE__ */new Set,this.attributes=JSON.parse(JSON.stringify(en))}copyForClone(t){super.copyForClone(t),this.attributes=JSON.parse(JSON.stringify(t.attributes))}setAttributes(t){var e,i;let r=this.attributes;r.manufacturer=t.manufacturer??r.manufacturer,r.categories=(null==(e=t.categories)?void 0:e.slice())??r.categories,r.subCategories=(null==(i=t.subCategories)?void 0:i.slice())??r.subCategories,r.thumbnail=t.thumbnail??r.thumbnail,t.boundingBox&&(r.boundingBox.min=[...t.boundingBox.min],r.boundingBox.max=[...t.boundingBox.max]),r.seatCapacity=t.seatCapacity??r.seatCapacity,r.updatedAt=t.updatedAt??r.updatedAt}getBoundingBox(){return this.attributes.boundingBox}toJSON(){const t=super.toJSON();return t.attributes=xe(this,ce,de).call(this),t}}ce=/* @__PURE__ */new WeakSet,de=function(){const t={},e=this.attributes;""!==e.manufacturer&&(t.manufacturer=e.manufacturer),e.categories.length>0&&(t.categories=[...e.categories]),e.subCategories.length>0&&(t.subCategories=[...e.subCategories]),""!==e.thumbnail&&(t.thumbnail=e.thumbnail);let{min:i,max:r}=e.boundingBox;return 1!==i[0]&&-1!==r[0]&&(t.boundingBox={min:[...e.boundingBox.min],max:[...e.boundingBox.max]}),e.seatCapacity>0&&(t.seatCapacity=e.seatCapacity),void 0!==e.updatedAt&&(t.updatedAt=e.updatedAt),t};class sn extends rn{constructor(t){super(t,tn),this.geometries=[]}copyForClone(t){super.copyForClone(t),this.geometries=JSON.parse(JSON.stringify(t.geometries))}toJSON(){return{...super.toJSON(),type:tn,geometries:JSON.parse(JSON.stringify(this.geometries))}}}const nn="product:component";class on extends rn{constructor(t){super(t,nn),this.products=[],this.geometries=[],this.attributes=JSON.parse(JSON.stringify(en))}copyForClone(t){super.copyForClone(t),this.products=JSON.parse(JSON.stringify(t.products))}toJSON(){return{...super.toJSON(),type:nn,products:JSON.parse(JSON.stringify(this.products)),geometries:[]}}setProducts(t){this.products=JSON.parse(JSON.stringify(t))}setInstances(){var t;for(const e of this.instances){if(this.products.length===e.elements.length&&this.products.every((t,i)=>{var r;const s=e.elements[i];return"element:asset"===(null==s?void 0:s.type)&&t.product===(null==(r=s.product)?void 0:r.id)}))for(let i=0;i<this.products.length;i++){const r=this.products[i];if("type"in r.position)continue;if("number"!=typeof r.rotation)continue;const s=e.elements[i];"element:asset"===s.type&&(null==(t=s.product)?void 0:t.id)===r.product&&s.setTransform(r.position,r.rotation)}else{for(let t=e.elements.length-1;t>=0;t--)e.removeElement(e.elements[t]);for(const t of this.products){const i=new Gs(Ut()),r=this.spaceGraph.productsById[t.product];r||be.error(`Product ${t.product} is missing`),i.setProduct(r),"type"in t.position||"number"==typeof t.rotation&&(i.setTransform(t.position,t.rotation),e.insertElement(i))}}}}}function an(t){for(let e=t.elements.length-1;e>=0;e--)t.removeElement(t.elements[e])}function ln(t,e,i){let r=t.elements.filter(t=>t.type===e);for(let s=r.length-1;s>=i;s--)t.removeElement(r[s]);for(let s=0;s<i;s++)if(!r[s]){let i=Ut();r[s]="element:casework"===e?new Hs(i):new Gs(i),t.insertElement(r[s])}return r}function hn(t){let{length:e,width:i,height:r,wallCabinet:s,leftHighCabinetCount:n,rightHighCabinetCount:o,sinkElementSlot:a,materials:l}=t.parameters,h=Math.min(.6,e),u=r-1.5,c=Math.min(e,h*Math.max(n,0)),d=e>c?h*o:0,p=Math.max(e-c-d,0);d=Math.max(e-c-p,0);let f=0;p>0&&(f++,s&&f++),c>0&&f++,d>0&&f++;let m=p>0&&a*h>=c&&a*h<=c+p,g=ln(t,"element:casework",f),y={cabinet:l.cabinet,cabinetDoors:l.cabinetDoors,counter:l.counter};if(p>0){let e=g.shift();if(e){let r=ln(e,"element:asset",m?1:0);if(m){let e=r[0],s=function(t){const e="7f24bd1c-1ebc-4724-8cd4-ca78c7d4a1e5";if(null==t?void 0:t.productsById[e])return null==t?void 0:t.productsById[e];let i=new sn(e);return i.setAttributes({categories:["appliances"],subCategories:["kitchen"],boundingBox:{max:[.54,.21,0],min:[0,-.17,-.47]}}),i.geometries=[{type:"reference:geometry",geometry:{id:"sinkGeometry",type:"geometry:uri",format:"data3d",uri:"015f8f8e-e588-4f51-a342-2930559834ee/201208-0355-60hukz/bf4e4a56-ed95-4b58-a214-4b1a0a84ae0e.gz.data3d.buffer"}}],i}(t.spaceGraph),{min:n,max:o}=s.attributes.boundingBox,l=pi(n,(v=fi(o,n),x=.5,[v[0]*x,v[1]*x,v[2]*x]));l[1]=0;let u=pi([a*h-c,.9,0],[h/2,0,i/2]);s&&(e.setProduct(s),e.setPosition(fi(u,l)))}e.setParameters({length:p,width:i,height:.9,counterHeight:.03,materials:{...y}}),e.setTransform([c,0,0],0)}let r=s&&g.shift();r&&(an(r),r.setParameters({length:p,width:.45,height:u,counterHeight:0,materials:{...y}}),r.setTransform([c,1.5,0],0))}var v,x;let b=c>0&&g.shift();b&&(an(b),b.setParameters({length:c,width:i,height:r,counterHeight:0,materials:{...y}}),b.setTransform([0,0,0],0));let _=d>0&&g.shift();_&&(an(_),_.setParameters({length:d,width:i,height:r,counterHeight:0,materials:{...y}}),_.setTransform([c+p,0,0],0))}const un={length:3,width:.6,height:2.2,wallCabinet:!0,leftHighCabinetCount:1,rightHighCabinetCount:0,sinkElementSlot:-1,cooktopElementSlot:-1,ovenElementSlot:-1,materials:{cabinet:"asm:cabinet_paint_white",cabinetDoors:"asm:cabinet_paint_white",counter:"asm:cabinet_paint_white"}};class cn extends Ds{constructor(t){super(t,"element:kitchen"),this.parameters=JSON.parse(JSON.stringify(un))}setParameters(t,e=!1){super.setParameters(t),e||hn(this),this.emit("element-parameters-change",this)}}const dn={length:2,width:.05,height:1,segmentCount:0,segmentLength:.12,materials:{surface:"#CCCCCC"}};class pn extends Ds{constructor(t){super(t,"element:railing"),this.parameters=JSON.parse(JSON.stringify(dn))}setParameters(t){super.setParameters(t)}}const fn={length:2,width:1,height:.5,materials:{top:"asm:basic-floor",bottom:"asm:basic-wall",sides:"asm:basic-wall"}};class mn extends Ds{constructor(t){super(t,"element:ramp"),this.parameters=JSON.parse(JSON.stringify(fn))}}const gn={materials:{}};class yn extends Ds{constructor(t){super(t,"element:roof"),this.parameters=JSON.parse(JSON.stringify(gn))}}const vn={type:"curve:rectangle",dimensions:[1,1]},xn={"curve:circle":{type:"curve:circle",radius:1},"curve:rectangle":{...vn},"curve:polygon":{type:"curve:polygon",points:[[0,0],[1,0],[1,1],[0,1]]},"curve:polygonWithHoles":{type:"curve:polygonWithHoles",polygons:[[[0,0],[1,0],[1,1],[0,1]],[[.25,.25],[.25,.75],[.75,.75],[.75,.25]]]}},bn={profile:{...vn},height:.1,materials:{top:"asm:basic-floor",bottom:"asm:basic-floor",sides:"asm:basic-wall"}};class _n extends Ds{constructor(t){super(t,"element:slab"),this.parameters=JSON.parse(JSON.stringify(bn))}setParameters(t){var e;(null==(e=t.profile)?void 0:e.type)&&t.profile.type!==this.parameters.profile.type&&(this.parameters.profile=JSON.parse(JSON.stringify(xn[t.profile.type]))),super.setParameters(t)}}const wn={height:3,width:1.2,materials:{steps:"asm:basic-wall",tread:"asm:basic-floor"}},Pn={straight:{stairFlightType:"straight",length:3,...wn},spiral:{stairFlightType:"spiral",angle:270,radius:1.5,circulation:"right",...wn}};class En extends Ds{constructor(t){super(t,"element:stairFlight"),this.parameters=JSON.parse(JSON.stringify(Pn.straight))}setParameters(t){if(t.stairFlightType&&this.parameters.stairFlightType!==t.stairFlightType){let{height:e,materials:i,width:r}=this.parameters;this.parameters={...JSON.parse(JSON.stringify(Pn[t.stairFlightType])),height:e,materials:i,width:r}}super.setParameters(t)}}function Tn(t,e,i){let r=t.elements.filter(t=>t.type===e);for(let s=r.length-1;s>=i;s--)t.removeElement(r[s]);for(let s=0;s<i;s++)if(!r[s]){let i=Ut();r[s]="element:stairFlight"===e?new En(i):new _n(i),t.insertElement(r[s])}return r}const An=.1;const In={height:3,railing:"right",materials:{steps:"asm:basic-wall",tread:"asm:basic-floor",railing:"#CCCCCC"}},Sn={straight:{stairsType:"straight",length:4,width:1.2,...In},straightLanding:{stairsType:"straightLanding",length:4,width:1.2,...In},halfLanding:{stairsType:"halfLanding",length:4,width:2.5,stepWidth:1.2,circulation:"right",...In},quarterLanding:{stairsType:"quarterLanding",length:4,width:2.5,stepWidth:1.2,circulation:"right",...In},twoQuarterLanding:{stairsType:"twoQuarterLanding",length:3,width:4,stepWidth:1.2,circulation:"right",...In},winder:{stairsType:"winder",length:4,width:2.5,stepWidth:1.2,circulation:"right",...In},doubleWinder:{stairsType:"doubleWinder",length:4,width:2.5,stepWidth:1.2,circulation:"right",...In},spiral:{stairsType:"spiral",radius:1.5,angle:270,stepWidth:1.2,circulation:"right",...In},custom:{stairsType:"custom",stepWidth:1.2,...In}},Cn=Sn.straight;class Mn extends Ds{constructor(t){super(t,"element:stairs"),this.parameters=JSON.parse(JSON.stringify(Cn))}setParameters(t,e=!1){if(t.stairsType&&this.parameters.stairsType!==t.stairsType){let{height:e,railing:i,materials:r}=this.parameters;this.parameters={...JSON.parse(JSON.stringify(Sn[t.stairsType])),height:e,railing:i,materials:r}}super.setParameters(t),e||function(t){switch(t.parameters.stairsType){case"straight":{let{length:e,width:i,height:r,materials:s}=t.parameters,[n]=Tn(t,"element:stairFlight",1);Tn(t,"element:slab",0),n.setParameters({stairFlightType:"straight",length:e,width:i,height:r,materials:{steps:s.steps,tread:s.tread}}),n.setTransform([0,0,0],0);break}case"straightLanding":{let{length:e,width:i,height:r,materials:s}=t.parameters,n=(e-i)/2,[o,a]=Tn(t,"element:stairFlight",2),[l]=Tn(t,"element:slab",1);o.setParameters({stairFlightType:"straight",length:n,width:i,height:r/2,materials:{steps:s.steps,tread:s.tread}}),o.setTransform([0,0,0],0),l.setParameters({profile:{type:"curve:rectangle",dimensions:[i,i]},height:An,materials:{top:s.tread,bottom:s.steps,sides:s.steps}}),l.setTransform([n,r/2-An,0],0),a.setParameters({stairFlightType:"straight",length:n,width:i,height:r/2}),a.setTransform([e-n,r/2,0],0);break}case"halfLanding":{let{length:e,width:i,height:r,stepWidth:s,circulation:n,materials:o}=t.parameters,a="right"===n,[l,h]=Tn(t,"element:stairFlight",2),[u]=Tn(t,"element:slab",1);l.setParameters({stairFlightType:"straight",length:e-s,width:s,height:r/2,materials:{steps:o.steps,tread:o.tread}}),l.setTransform([0,0,a?0:-s],0),u.setParameters({profile:{type:"curve:rectangle",dimensions:[s,i]},height:An,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),u.setPosition([e-s,r/2-An,a?0:-i]),h.setParameters({stairFlightType:"straight",length:e-s,width:s,height:r/2,materials:{steps:o.steps,tread:o.tread}}),h.setTransform([e-s,r/2,a?i:-i+s],-180);break}case"quarterLanding":{let{length:e,width:i,height:r,stepWidth:s,circulation:n,materials:o}=t.parameters,a="right"===n,l=e-s,h=i-s,u=l/(l+h)*r,c=h/(l+h)*r,[d,p]=Tn(t,"element:stairFlight",2),[f]=Tn(t,"element:slab",1);d.setParameters({stairFlightType:"straight",length:l,width:s,height:u,materials:{steps:o.steps,tread:o.tread}}),d.setTransform([0,0,a?0:-s],0),f.setParameters({profile:{type:"curve:rectangle",dimensions:[s,s]},height:An,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),f.setPosition([e-s,u-An,a?0:-s]),p.setParameters({stairFlightType:"straight",length:h,width:s,height:c,materials:{steps:o.steps,tread:o.tread}}),a?p.setTransform([e,u,s],-90):p.setTransform([e-s,u,-s],90);break}case"twoQuarterLanding":{let{length:e,width:i,height:r,stepWidth:s,circulation:n,materials:o}=t.parameters,a="right"===n,l=e-s,h=i-2*s,u=l/(2*l+h)*r,c=h/(2*l+h)*r,[d,p,f]=Tn(t,"element:stairFlight",3),[m,g]=Tn(t,"element:slab",2);d.setParameters({stairFlightType:"straight",length:l,width:s,height:u,materials:{steps:o.steps,tread:o.tread}}),d.setTransform([0,0,a?0:-s],0),m.setParameters({profile:{type:"curve:rectangle",dimensions:[s,s]},height:An,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),m.setPosition([e-s,u-An,a?0:-s]),p.setParameters({stairFlightType:"straight",length:h,width:s,height:c,materials:{steps:o.steps,tread:o.tread}}),a?p.setTransform([e,u,s],-90):p.setTransform([e-s,u,-s],90),g.setParameters({profile:{type:"curve:rectangle",dimensions:[s,s]},height:An,materials:{top:o.tread,bottom:o.steps,sides:o.steps}}),g.setPosition([e-s,u+c-An,a?i-s:-i]),f.setParameters({stairFlightType:"straight",length:l,width:s,height:u,materials:{steps:o.steps,tread:o.tread}}),f.setTransform([e-s,u+c,a?i:-i+s],-180);break}case"spiral":{let{radius:e,angle:i,height:r,stepWidth:s,circulation:n,materials:o}=t.parameters,a="right"===n,[l]=Tn(t,"element:stairFlight",1);Tn(t,"element:slab",0),l.setParameters({stairFlightType:"spiral",radius:e,angle:i,height:r,width:s,circulation:n,materials:{steps:o.steps,tread:o.tread}}),l.setTransform([0,0,a?e:-e],0);break}}}(this),this.emit("element-parameters-change",this)}calculateBoundingBox(){const t=super.calculateBoundingBox();return"radius"in this.parameters&&(t.min[2]=0,t.max[2]=2*this.parameters.radius,t.min[0]=-this.parameters.radius,t.max[0]=this.parameters.radius),"circulation"in this.parameters&&"left"===this.parameters.circulation&&(t.min[2]=-t.max[2],t.max[2]=0),t}}const On={length:1,height:1.2,frameThickness:.05,frameDepth:.1,panelLength:0,panelCount:1,materials:{frame:"#CCCCCC",panel:"asm:glass"}};class Nn extends Ds{constructor(t){super(t,"element:window"),this.parameters=JSON.parse(JSON.stringify(On))}setParameters(t){super.setParameters(t)}}class Ln extends yr{constructor(){super(...arguments),this.position=[0,0,0],this.rotation=0}copyForClone(t){super.copyForClone(t),this.position=[...t.position],this.rotation=t.rotation,this.parameters=JSON.parse(JSON.stringify(t.parameters))}setTransform(t,e){this.position=[...t],this.rotation=e,this.emit("annotation-transform-change",this)}setParameters(t){Ir(this.parameters,t,{onNewKeys:{allow:!1},cloneObjects:!0}),this.emit("annotation-parameters-change",this)}toJSON(){return{...super.toJSON(),position:[...this.position],parameters:JSON.parse(JSON.stringify(this.parameters)),rotation:this.rotation}}}const Rn={uri:"",drawingOrigin:[0,0],drawingUnits:"unitLess",hiddenLayers:[]};class kn extends Ln{constructor(t){super(t,"annotation:floorPlanDxf"),this.parameters=JSON.parse(JSON.stringify(Rn))}setParameters(t){super.setParameters(t)}}class Bn extends yr{copyForClone(t){super.copyForClone(t),this.parameters=JSON.parse(JSON.stringify(t.parameters))}setParameters(t){Ir(this.parameters,t,{onNewKeys:{allow:!1},cloneObjects:!0}),this.emit("view-parameters-change",this)}toJSON(){return{...super.toJSON(),parameters:JSON.parse(JSON.stringify(this.parameters))}}}const Fn={style:{background:{fill:"#f7f8fa"},units:"metric",byId:{},byType:{},byAttribute:{program:{},usage:{}}},hidden:[]};class Dn extends Bn{constructor(t){super(t,"view:2d"),this.parameters=JSON.parse(JSON.stringify(Fn))}setParameters(t){var e,i;let{style:r}=t;void 0===(null==r?void 0:r.byId)&&(this.parameters.style.byId={}),void 0===(null==r?void 0:r.byType)&&(this.parameters.style.byType={}),void 0===(null==(e=null==r?void 0:r.byAttribute)?void 0:e.program)&&(this.parameters.style.byAttribute.program={}),void 0===(null==(i=null==r?void 0:r.byAttribute)?void 0:i.usage)&&(this.parameters.style.byAttribute.usage={}),Ir(this.parameters,t,{onNewKeys:{allow:!1},copyScopes:[".style.byId",".style.byType",".style.byAttribute.program",".style.byAttribute.usage"],cloneObjects:!0}),this.emit("view-parameters-change",this)}}const Un={position:[0,0,0],normal:[0,0,1],fov:"default",scale:1,lensShiftX:0,lensShiftY:0,projection:"perspective"};class Gn extends Bn{constructor(t){super(t,"view:3d"),this.parameters=JSON.parse(JSON.stringify(Un))}setParameters(t){super.setParameters(t)}}const Xn="relation:group";class Wn extends we{constructor(t){super(t,Xn),this.elements=/* @__PURE__ */new Set}insertElements(t){for(let e of t)this.elements.add(e)}removeElements(t){for(let e of t)this.elements.delete(e)}copyForClone(t){super.copyForClone(t)}toJSON(){const t=super.toJSON();return t.elements=Array.from(this.elements).map(t=>t.id),t}}class Yn extends gr{constructor(t,e){super(t,e)}}function Hn(t,e){e.registerNode(t),function(t,e){let{vertices:i,edges:r}=t.spatialGraph;for(let s of i)e.registerNode(s),e.emit("vertex-create",s);for(let s of r)e.registerNode(s),e.emit("edge-create",s)}(t,e);for(let r of t.spaces)e.registerNode(r);let i=t.getElementList();for(let r of i)e.registerNode(r);for(let r of t.annotations)e.registerNode(r);for(let r of t.views)e.registerNode(r);e.emit("spatial-structure-create",t)}function $n(t,e){e.unregisterNode(t),function(t,e){let{vertices:i,edges:r}=t.spatialGraph;for(let s of i)e.unregisterNode(s),e.emit("vertex-delete",s);for(let s of r)e.unregisterNode(s),e.emit("edge-delete",s)}(t,e);for(let r of t.spaces)e.unregisterNode(r);let i=t.getElementList();for(let r of i)e.unregisterNode(r);for(let r of t.annotations)e.unregisterNode(r);e.emit("spatial-structure-delete",t)}function jn(t,e){e.registerNode(t);for(let i of t.layouts)Hn(i,e);e.emit("spatial-structure-create",t)}function zn(t,e){e.unregisterNode(t);for(let i of t.layouts)$n(i,e);e.emit("spatial-structure-delete",t)}function Vn(t,e,...i){let r;switch(t){case"element:ceiling":case"element:floor":r=new $r(e,t,i[0]);break;case"element:boundaryWall":r=new _s(e,i[0]);break;case"element:curtainWall":r=new Ps(e,i[0]);break;case"element:spaceDivider":r=new Ts(e,i[0]);break;case"element:wall":r=new Yr(e,i[0]);break;case"element:opening":r=new Fs(e);break;case"element:asset":r=new Gs(e);break;case"element:beam":r=new Ws(e);break;case"element:casework":r=new Hs(e);break;case"element:column":r=new Vs(e);break;case"element:door":r=new Js(e);break;case"element:generic":r=new Qs(e);break;case"element:kitchen":r=new cn(e);break;case"element:ramp":r=new mn(e);break;case"element:roof":r=new yn(e);break;case"element:railing":r=new pn(e);break;case"element:slab":r=new _n(e);break;case"element:stairs":r=new Mn(e);break;case"element:stairFlight":r=new En(e);break;case"element:window":r=new Nn(e)}return r}const qn={uri:"",length:1,width:1};class Jn extends Ln{constructor(t){super(t,"annotation:floorPlanImage"),this.parameters=JSON.parse(JSON.stringify(qn))}setParameters(t){super.setParameters(t)}}function Kn(t,e){let i;switch(t){case"annotation:floorPlanDxf":i=new kn(e);break;case"annotation:floorPlanImage":i=new Jn(e)}return i}function Zn(t,e){let i;switch(t){case"view:2d":i=new Dn(e);break;case"view:3d":i=new Gn(e)}return i}class Qn{constructor(){this.nodeMap=/* @__PURE__ */new Map}addNode(t){return this.nodeMap.has(t)||this.nodeMap.set(t,/* @__PURE__ */new Map),this.nodeMap.get(t)}addEdge(t,e,i){var r,s;let n=this.addNode(e),o=this.addNode(i);n.has(t)||n.set(t,/* @__PURE__ */new Set),o.has(t)||o.set(t,/* @__PURE__ */new Set),null==(r=n.get(t))||r.add(i),null==(s=o.get(t))||s.add(e)}removeNode(t){if(this.nodeMap.has(t)){for(let e of this.nodeMap.get(t))for(let i of e[1])this.removeEdge(e[0],t,i);this.nodeMap.delete(t)}}removeEdge(t,e,i){var r,s,n,o;null==(s=null==(r=this.nodeMap.get(e))?void 0:r.get(t))||s.delete(i),null==(o=null==(n=this.nodeMap.get(i))?void 0:n.get(t))||o.delete(e)}findShortestPath(t,e,i,r={}){var s;let n=[[e]],o=/* @__PURE__ */new Set;for(;n.length>0;){let e=n.shift();if(!e)return null;if(r.depthLimit&&e.length-1>r.depthLimit)return null;let a=e[e.length-1];if(a===i)return e;if(!o.has(a)&&this.nodeMap.has(a)&&(null==(s=this.nodeMap.get(a))?void 0:s.has(t))){o.add(a);for(let i of this.nodeMap.get(a).get(t))n.push([...e,i])}}return null}toJSON(){const t=[],e=[];for(const[i,r]of this.nodeMap.entries()){t.push({id:i.id,type:i.type});for(const[t,s]of r.entries())for(const r of s)i.id<r.id&&e.push({type:String(t),nodes:[i.id,r.id]})}return{nodes:t,edges:e}}}const to=t=>{const e={};for(const i in t)e[i]=[];return e},eo={"element:ceiling":$r,"element:floor":$r,"element:boundaryWall":_s,"element:curtainWall":Ps,"element:spaceDivider":Ts,"element:wall":Yr,"element:opening":Fs,"element:asset":Gs,"element:beam":Ws,"element:casework":Hs,"element:column":Vs,"element:door":Js,"element:generic":Qs,"element:kitchen":cn,"element:railing":pn,"element:ramp":mn,"element:roof":yn,"element:slab":_n,"element:stairs":Mn,"element:stairFlight":En,"element:window":Nn},io={"annotation:floorPlanDxf":kn,"annotation:floorPlanImage":Jn},ro={"view:2d":Dn,"view:3d":Gn};const so=t=>{const{min:e,max:i}=t.getAxisAlignedBoundingBox();return{id:t.id,type:t.type,minX:e[0],minY:e[2],maxX:i[0],maxY:i[2]}};class no extends Ht{constructor(t){super(),this.nodeIds=/* @__PURE__ */new Set,this.layout=t}find({min:t,max:e,margin:i,types:r}){i??(i=0),e??(e=t);const s={minX:t[0]-i,maxX:e[0]+i,minY:t[1]-i,maxY:e[1]+i},n=this.search(s),o=[];for(const a of n)(null==r?void 0:r.length)&&!(null==r?void 0:r.includes(a.type))||(this.layout.spaceGraph.nodesById[a.id]?o.push(this.layout.spaceGraph.nodesById[a.id]):be.warn(`Indexed node ${a.id} is not part of the layout anymore`));return o}addNode(t){const e=so(t);this.nodeIds.has(t.id)&&this.remove(e),this.insert(e),this.nodeIds.add(t.id)}removeNode(t){const e=so(t);this.nodeIds.has(t.id)&&this.remove(e)}remove(t){return this.nodeIds.delete(t.id),super.remove(t,(t,e)=>t.id===e.id),this}}const oo={...eo,"spatialGraph:edge":Br,"spatialGraph:vertex":br,"layout:space":Ur,"view:2d":Dn,"view:3d":Gn,"annotation:floorPlanDxf":kn,"annotation:floorPlanImage":Jn};class ao extends we{constructor(t,e){super(t,e),this.position=[0,0,0],this.rotation=0,this.rotationAxis=[0,1,0],this.surfaces={},this.materials={},this.boundingBox={min:[1/0,1/0,1/0],max:[-1/0,-1/0,-1/0]}}}class lo extends ao{constructor(t,e){super(t,e),this.normals="generator",this.uvs="generator",this.geometries=[]}}const ho={"geometry:plane":class extends lo{constructor(t){super(t,"geometry:plane"),this.normal=[0,1,0],this.size=1,this.doubleSided=!1}},"geometry:cuboid":class extends lo{constructor(t){super(t,"geometry:cuboid"),this.dimensions=[1,1,1]}},"geometry:sphere":class extends lo{constructor(t){super(t,"geometry:sphere"),this.radius=1}},"geometry:extrusion":class extends lo{constructor(t,e){super(t,"geometry:extrusion"),this.height=1,this.profile=e}},"geometry:mesh":class extends ao{constructor(t){super(t,"geometry:mesh"),this.vertices=[],this.indices=[],this.normals=[],this.uvs=[]}},"geometry:uri":class extends ao{constructor(t){super(t,"geometry:uri"),this.format="data3d",this.uri="",this.normals="smooth"}}},uo={"material:embedded":Se,"material:basic":Me,"material:color":Ee,"material:standard":Ae},co={"product:static":sn,"product:component":on},po={"relation:group":Wn},fo={...oo,...ho,...uo,...co,...po,"spatialStructure:building":null,"spatialStructure:floor":null,"spatialStructure:layout":null};function mo(t,e){t.name=e.name??t.name,t.customId=e.customId??t.customId}function go(t,e){let i;return t.type===nn?(i=new on(t.id),i.products=JSON.parse(JSON.stringify(t.products))):(i=new sn(t.id),i.geometries=JSON.parse(JSON.stringify(t.geometries))),t.attributes&&i.setAttributes(t.attributes),t.customAttributes&&i.setCustomAttributes(t.customAttributes,e),mo(i,t),i}function yo(t){return JSON.parse(JSON.stringify(t))}function vo(t){let e;if(Array.isArray(t)||"string"==typeof t)be.warn("Color literal or standard material reference not allowed in shared resources section.");else if("object"==typeof t)switch(t.type){case Pe:let[i,r,s,n]=function(t){let[e,i,r,s]=[1,1,1,1];return Array.isArray(t)?[e,i,r,s]=Fe(t):"string"==typeof t&&([e,i,r,s]=[1,1,1,1],""===t?be.warn("Empty string not a valid color literal."):t.startsWith("#")?[e,i,r,s]=De(t):t.startsWith("rgb(")?[e,i,r,s]=Ue(t,!1):t.startsWith("rgba(")?[e,i,r,s]=Ue(t,!0):be.warn(`String ${t} not a valid color literal.`)),[e,i,r,s]}(t.value);e=new Ee(t.id,[i,r,s],n);break;case Te:e=new Ae(t.id,t.reference);break;case Ce:e=new Me(t.id),mo(e,t),e.colorDiffuse=[...t.colorDiffuse],t.colorSpecular&&(e.colorSpecular=[...t.colorSpecular]),e.specularCoefficient=t.specularCoefficient??e.specularCoefficient,e.opacity=t.opacity??e.opacity;break;default:e=new Ee(t.id,[1,1,1],1),be.warn(`Unknown material type ${t.type}, creating default material.`)}else be.warn("Material not an array, string or object.");return e}function xo(t,e){let i;if(e.type===Xn){i=new Wn(e.id);let r=[];for(let s of e.elements)t.nodesById[s]?r.push(t.nodesById[s]):be.error(`Element ${s} not found, referenced by relation ${i.id}.`);i.insertElements(r)}return mo(i,e),i}function bo(t){const e=function(t){const{id:e,attributes:{resourceType:i}}=t;return e.endsWith(`:${i}`)?e:`${e}:${i}`}(t),i=new fr(e,t.attributes);return mo(i,t),i}function _o(t,e){!function(t,e){for(let i of e){let e=bo(i);e&&t.insertCustomAttribute(e)}}(t,e.customAttributes||[]),function(t,e){for(let i of e){let e=go(i,t.customAttributesById);t.insertProduct(e)}}(t,e.products),function(t,e){for(let i of e){let e=yo(i);t.insertGeometry(e)}}(t,e.geometries),function(t,e){for(let i of e){let e=vo(i);e&&t.insertMaterial(e)}}(t,e.materials)}function wo(t,e){let i=function(t,e){let i;switch(e.type){case Ho:i=$o.fromJSON(e,{spaceGraph:t,skipInsert:!0});break;case Wo:i=Yo.fromJSON(e,{spaceGraph:t,skipInsert:!0});break;case Go:i=Xo.fromJSON(e,{spaceGraph:t,skipInsert:!0})}return i}(t,e);t.insertSpatialStructure(i)}function Po(t,e){_o(t,e.sharedResources),wo(t,e.spatialStructure),function(t,e){for(let i of e){let e=xo(t,i);e&&t.insertRelation(e)}}(t,e.sharedResources.relations||[])}class Eo{constructor(t){this.products=[],this.productsById={},this.productsByType=to(co),this.customAttributes=[],this.customAttributesById={},this.customAttributesByType=to(mr),this.geometries=[],this.geometriesById={},this.geometriesByType=to(ho),this.materials=[],this.materialsById={},this.materialsByType=to(uo),this.relations=[],this.relationsById={},this.relationsByType=to(po),this.nodes=[],this.nodesById={},this.nodesByType=to(fo),this.spatialStructure=null,this.emitter=new pe.TinyEmitter,this.sourceSchemaVersion=t}getEvents(){return this.emitter.e??{}}copyEvents(t){let e=t.getEvents();for(let[i,r]of Object.entries(e))this.emitter.on(i,r)}deleteNodeAtIndex(t,e,i,r){let s=e[t];if(e.splice(t,1),i[s.id]!==s)return void be.error(`Entry ${s.id} in 'nodes stored by ID' record does not contain this object.`);delete i[s.id];let n=r[s.type];if(!n)return void be.error(`Node ${s.id} not found in 'nodes stored by type' record.`);let o=n.indexOf(s);if(-1!==o)return n.splice(o,1),s;be.error(`Node ${s.id} not found in 'nodes stored by type' record.`)}insertNode(t,e,i,r){i[t.id]?be.error(`Node ${t.id} already registered.`):(e.push(t),i[t.id]=t,r[t.type]||(r[t.type]=[]),r[t.type].push(t))}removeNode(t,e,i,r){let s=e.indexOf(t);if(-1!==s)return this.deleteNodeAtIndex(s,e,i,r),t;be.warn(`Node ${t.id} not found.`)}registerNode(t){var e,i;t.spaceGraph=this;let{nodes:r,nodesById:s,nodesByType:n}=this;this.insertNode(t,r,s,n),"getBoundingBox"in t&&"layout"in t&&(null==(e=t.layout)?void 0:e.spatialIndex)&&(null==(i=t.layout)||i.spatialIndex.addNode(t))}unregisterNode(t){var e,i;t.spaceGraph=null;let{nodes:r,nodesById:s,nodesByType:n}=this;this.removeNode(t,r,s,n),"getBoundingBox"in t&&"layout"in t&&(null==(e=t.layout)?void 0:e.spatialIndex)&&(null==(i=t.layout)||i.spatialIndex.removeNode(t))}insertSpatialStructure(t){if(this.spatialStructure)be.warn(`Space graph object already has spatial structure ${this.spatialStructure.id} attached.`);else if(t.spaceGraph)be.warn(`Spatial structure ${t.id} already part of a space graph object.`);else{switch(t.spaceGraph=this,this.spatialStructure=t,t.type){case"spatialStructure:building":!function(t,e){e.registerNode(t);for(let i of t.floors)jn(i,e);e.emit("spatial-structure-create",t)}(t,this);break;case"spatialStructure:floor":jn(t,this);break;case"spatialStructure:layout":Hn(t,this)}this.emit("spatial-structure-create",t)}}removeSpatialStructure(){let t=this.spatialStructure;if(t){switch(t.spaceGraph=null,this.spatialStructure=null,t.type){case"spatialStructure:building":!function(t,e){e.unregisterNode(t);for(let i of t.floors)zn(i,e);e.emit("spatial-structure-delete",t)}(t,this);break;case"spatialStructure:floor":zn(t,this);break;case"spatialStructure:layout":$n(t,this)}return this.emit("spatial-structure-delete",t),t}be.warn("No spatial structure attached to space graph object.")}insertProduct(t){t.spaceGraph?be.warn(`Product ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.products,this.productsById,this.productsByType),this.registerNode(t),this.emit("product-create",t))}removeProduct(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.products,this.productsById,this.productsByType),this.unregisterNode(t),this.emit("product-delete",t)):be.warn(`Product ${t.id} already in a detached state.`)}createProduct(t,e){let i;return i=e===nn?new on(t):new sn(t),this.insertProduct(i),i}insertGeometry(t){let{geometries:e,geometriesById:i,geometriesByType:r}=this;e.push(t),i[t.id]=t,r[t.type].push(t)}removeGeometry(t){let{geometries:e,geometriesById:i,geometriesByType:r}=this,s=e.indexOf(t);if(-1===s)return void be.warn(`Geometry ${t.id} not found.`);if(e.splice(s,1),i[t.id]!==t)return void be.error(`Entry ${t.id} in 'geometries stored by ID' record does not contain this object.`);delete this.geometriesById[t.id];let n=r[t.type];if(!n)return void be.error(`Geometry ${t.id} not found in 'geometries stored by type' record.`);let o=n.indexOf(t);-1!==o?n.splice(o,1):be.error(`Node ${t.id} not found in 'nodes stored by type' record.`)}insertMaterial(t){t.spaceGraph?be.warn(`Material ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.materials,this.materialsById,this.materialsByType),this.registerNode(t),this.emit("material-create",t))}removeMaterial(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.materials,this.materialsById,this.materialsByType),this.unregisterNode(t),this.emit("material-delete",t)):be.warn(`Material ${t.id} already in a detached state.`)}createMaterial(t,e,...i){let r;switch(t){case Pe:r=new Ee(e,i[0],i[1]);break;case Te:r=new Ae(e,i[0]);break;case Ie:r=new Se(e,i[0],i[1]);break;case Ce:r=new Me(e)}return this.insertMaterial(r),r}insertRelation(t){t.spaceGraph?be.warn(`Relation ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.relations,this.relationsById,this.relationsByType),this.registerNode(t),this.emit("relation-create",t))}removeRelation(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.relations,this.relationsById,this.relationsByType),this.unregisterNode(t),this.emit("relation-delete",t)):be.warn(`Relation ${t.id} already in a detached state.`)}createRelation(t,e){let i;if(t===Xn)i=new Wn(e);return this.insertRelation(i),i}insertCustomAttribute(t){t.spaceGraph?be.warn(`Custom attribute ${t.id} already part of a space graph object.`):(t.spaceGraph=this,this.insertNode(t,this.customAttributes,this.customAttributesById,this.customAttributesByType),this.registerNode(t),this.emit("custom-attribute-create",t))}removeCustomAttribute(t){t.spaceGraph?(t.spaceGraph=null,this.removeNode(t,this.customAttributes,this.customAttributesById,this.customAttributesByType),this.unregisterNode(t),this.emit("custom-attribute-delete",t)):be.warn(`Custom attribute ${t.id} already in a detached state.`)}getId(){return Ut()}emit(t,...e){this.emitter.emit(t,...e)}on(t,e,i){this.emitter.on(t,e,i)}once(t,e,i){this.emitter.once(t,e,i)}off(t,e){this.emitter.off(t,e)}toJSON(){let t=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.products),e=function(t){let e=[];for(let i of t){let t=y(i);e.push(t)}return e}(this.geometries),i=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.materials),r=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.relations),s=function(t){let e=[];for(let i of t){let t=i.toJSON();e.push(t)}return e}(this.customAttributes);return{schemaVersion:"0.24.2",spatialStructure:this.spatialStructure.toJSON(),sharedResources:{products:t,geometries:e,materials:i,relations:r,customAttributes:s}}}static fromJSON(t){const e=new Eo(t.schemaVersion);return Po(e,t),e}}function To(t,e){let i=t.spatialGraph,r=new hr;for(let s of e.edges){let t=i.edgesById[s];if(!t)return void be.warn(`Edge ${s} not found, skipping boundary.`);r.edges.push(t)}if(ls(r))return r}function Ao(t,e){let i=[];for(let r of e){let e=To(t,r);if(!e)return;i.push(e)}return i}function Io(t,e){let{id:i,position:r}=e,s=new br(i,r[0],r[1]);return Sr(s,e),s}function So(t,e){let i=t.spatialGraph,r=e.vertices[0],s=e.vertices[1];if(r===s)return void be.warn(`Same vertex referenced twice, skipping edge ${e.id}.`);let n=i.verticesById[r],o=i.verticesById[s];if(!n||!o)return void be.warn(`One or both vertices not found, skipping edge ${e.id}.`);let a=new Br(e.id,n,o);return Sr(a,e),a}function Co(t,e,i){i??(i=t.spaceGraph.customAttributesById);let r=Ao(t,e.boundaries);if(!r)return void be.warn(`Invalid boundaries, skipping space ${e.id}.`);let s=new Ur(e.id,r);return Sr(s,e),Cr(s,e,i),e.attributes&&s.setAttributes(e.attributes),s}function Mo(t,e){let i=Kn(e.type,e.id);return Sr(i,e),i.setTransform(e.position,e.rotation??0),e.parameters&&i.setParameters(e.parameters),i}function Oo(t,e){let i=Zn(e.type,e.id);return Sr(i,e),e.parameters&&i.setParameters(e.parameters),i}const No={};function Lo(t,e,i){return No[t]||(No[t]={}),No[t][e]=i,i}const Ro={.15:t=>{if(("layout:space"===t.type||"element:floor"===t.type||"element:ceiling"===t.type)&&t.id.includes(":")){const e=JSON.parse(JSON.stringify(t));return e.id=Ut(),e}return t},.16:t=>{if("element:window"===t.type&&t.parameters&&"framePosition"in t.parameters){const e=JSON.parse(JSON.stringify(t));return delete e.parameters.framePosition,e}return t},"0.20.3":t=>{if("layout:space"===t.type||!t.parameters)return t;let e=!1;const i=JSON.parse(JSON.stringify(t.parameters));if("height"in i&&i.height<.01&&(i.height=.01,e=!0),"width"in i&&i.width<.01&&(i.width=.01,e=!0),"length"in i&&i.length<.01&&(i.length=.01,e=!0),e){const e=JSON.parse(JSON.stringify(t));return e.parameters=i,e}return t}};function ko(t,e){return!e||function(t,e){var i;if(void 0!==(null==(i=No[t])?void 0:i[e]))return No[t][e];const r=t.split(".").map(t=>parseInt(t)),s=e.split(".").map(t=>parseInt(t));for(let n=0;n<Math.max(r.length,s.length);n++){const i=r[n]||0,o=s[n]||0;if(i>o)return Lo(t,e,1);if(i<o)return Lo(t,e,-1)}return Lo(t,e,0)}(e,t)<0}function Bo(t,e){let i=t;for(const r in Ro)ko(r,e)&&(i=Ro[r](i));return i}function Fo(t,e){var i;let{position:r,rotation:s,rotationAxis:n}=e;if(t.setTransform(r??[0,0,0],s??0,n),e.parameters){let r=!!(null==(i=e.elements)?void 0:i.length);!function(t,e,i=!1){switch(t.type){case"element:ceiling":case"element:floor":case"element:boundaryWall":case"element:curtainWall":case"element:spaceDivider":case"element:wall":case"element:opening":case"element:asset":case"element:beam":case"element:casework":case"element:column":case"element:door":case"element:generic":case"element:ramp":case"element:roof":case"element:railing":case"element:slab":case"element:stairFlight":case"element:window":t.setParameters(e);break;case"element:kitchen":case"element:stairs":t.setParameters(e,i)}}(t,e.parameters,r)}"element:generic"!==e.type&&"element:asset"!==e.type||(t.geometries=e.geometries?JSON.parse(JSON.stringify(e.geometries)):[])}function Do(t,e,i){i??(i=t.spaceGraph);let r,s=Bo(e,null==i?void 0:i.sourceSchemaVersion);switch(s.type){case"element:boundaryWall":case"element:ceiling":case"element:floor":r=function(t,e){let i=Ao(t,e.boundaries);if(!i)return void be.warn(`Invalid boundaries, skipping boundary wall ${e.id}.`);let r=Vn(e.type,e.id,i);return e.parameters&&r.setParameters(e.parameters),r}(t,s);break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":r=function(t,e){let i=[];if(i=Array.isArray(e.edge)?e.edge:[e.edge],!i.length)return void be.warn(`Element ${e.id} references no edges and is skipped.`);let r=[];for(let n of i){let i=t.spatialGraph.edgesById[n];if(!i)return void be.warn(`Edge ${e.edge} not found, skipping edge element ${e.id}.`);r.push(i)}let s=Vn(e.type,e.id,r);return e.parameters&&s.setParameters(e.parameters),s}(t,s);break;case"element:opening":r=function(t,e){let i=Vn("element:opening",e.id);return e.parameters&&i.setParameters(e.parameters),i}(0,s);break;case"element:asset":r=function(t,e,i){let r=Vn(e.type,e.id);if(Fo(r,e),!e.product)return e.geometries||be.warn(`Element ${r.id} does not specify a 'geometries' field and does not reference a product.`),r;let s=t.spaceGraph??i;if(s){let t=s.nodesById[e.product];if(!t)return void be.warn(`Product ${e.product} not found, skipping element ${e.id}.`);r.setProduct(t)}else be.warn(`Layout not attached and space graph not passed as an argument, cannot find product ${e.product}.`);return r}(t,s,i);break;case"element:beam":case"element:casework":case"element:column":case"element:door":case"element:generic":case"element:kitchen":case"element:railing":case"element:ramp":case"element:roof":case"element:slab":case"element:stairFlight":case"element:stairs":case"element:window":r=function(t,e){let i=Vn(e.type,e.id);return Fo(i,e),i}(0,s);break;default:return void be.warn(`Unknown element type '${s.type}', skipping element.`)}if(!r)return;Sr(r,s),Cr(r,s,null==i?void 0:i.customAttributesById);let n=s.elements??[];for(let o of n){let e=Do(t,o,i);e&&r.insertElement(e)}return r}function Uo(t,e,i){Cr(t,e,i.customAttributesById),Sr(t,e),function(t,e){let i=t.spatialGraph,r=e.spatialGraph;for(let s of r.vertices){let t=Io(0,s);i.insertVertex(t)}for(let s of r.edges){let e=So(t,s);e&&i.insertEdge(e)}}(t,e),function(t,e,i){for(let r of e.spaces){let e=Co(t,Bo(r),i.customAttributesById);e&&t.insertSpace(e)}}(t,e,i),function(t,e,i){for(let r of e.elements){let e=Do(t,r,i);e&&t.insertElement(e)}}(t,e,i),function(t,e){let i=e.annotations??[];for(let r of i){let e=Mo(0,r);t.insertAnnotation(e)}}(t,e),function(t,e){let i=e.views??[];for(let r of i){let e=Oo(0,r);t.insertView(e)}}(t,e),function(t){const e=t.spatialGraph.edges;for(const r of e)r.spaces=[null,null],r.boundaryWalls=[null,null];const i=[];for(const r of t.spaces)Qr(r),i.push(ns(r));for(const r of e){if(null!==r.spaces[0]||null!==r.spaces[1])continue;const[e,s]=r.getPoints(),n=li(e,s,.5);for(let o=0;o<t.spaces.length;o++)if(bi(n,i[o])){r.spaces[0]=t.spaces[o],r.spaces[1]=t.spaces[o];break}}for(const r of t.elements)"element:boundaryWall"===r.type&&ts(r)}(t)}const Go="spatialStructure:layout";class Xo extends Yn{constructor(t){super(t,Go),this.parent=null,this.spaces=[],this.spacesById={},this.elements=[],this.elementsById={},this.elementsByType=to(eo),this.annotations=[],this.annotationsById={},this.annotationsByType=to(io),this.views=[],this.viewsById={},this.viewsByType=to(ro),this.debugIds=!1,this.suggestedIds={},this.spatialGraph=new xs(this),this.spatialIndex=new no(this)}copyForClone(t){super.copyForClone(t),this.debugIds=t.debugIds,this.suggestedIds={...t.suggestedIds}}insertSpace(t){_r(this,t,this.spacesById,"Space")&&(!function(t,e){for(let i of t.elements)"element:ceiling"!==i.type&&"element:floor"!==i.type||us(e.boundaries,i.boundaries)&&e.attachSlab(i)}(this,t),t.layout=this,this.spaces.push(t),this.spacesById[t.id]=t,t.boundaries.length&&(this.spatialGraph.graphChanged=!0),this.spaceGraph&&(this.spaceGraph.registerNode(t),this.spaceGraph.emit("space-create",t)))}removeSpace(t){let e=this.spaces.indexOf(t);if(-1!==e){if(function(t){let e=t.slabs.slice();for(let i of e)t.detachSlab(i);for(let i of t.boundaries)for(let e of i.edges)e.spaces[0]===t&&(e.spaces[0]=null),e.spaces[1]===t&&(e.spaces[1]=null)}(t),this.spaces.splice(e,1),this.spacesById[t.id]===t)return delete this.spacesById[t.id],this.spaceGraph&&(this.spaceGraph.unregisterNode(t),this.spaceGraph.emit("space-delete",t)),t.layout=null,t;be.error(`Entry ${t.id} in 'spaces stored by ID' record does not contain this object.`)}else be.warn(`Space ${t.id} not found.`)}createSpace(t,e){let i=new Ur(t,e);return this.insertSpace(i),i}insertElement(t){_r(this,t,this.elementsById,"Element",!0)&&(!function(t,e){switch(e.type){case"element:boundaryWall":case"element:ceiling":case"element:floor":is(t,e);break;case"element:curtainWall":case"element:spaceDivider":case"element:wall":rs(t,e)}}(this,t),this.elements.push(t),wr(this,t))}removeElement(t){if(t.layout!==this)return void be.warn(`Element ${t.id} not part of layout ${this.id}.`);if(t.parent)return void be.warn(`Element ${t.id} not a root element, cannot remove from layout.`);ss(t);let e=this.elements.indexOf(t);if(-1!==e)return this.elements.splice(e,1),Pr(this,t,null),t;be.warn(`Element ${t.id} not found.`)}createElement(t,e,...i){let r=Vn(t,e,...i);return this.insertElement(r),r}insertNode(t){let{nodes:e,nodesById:i,nodesByType:r}=vs(this,t);t.layout=this,e.push(t),i[t.id]=t,r[t.type]||(r[t.type]=[]),r[t.type].push(t)}removeNode(t){let{name:e,nodes:i,nodesById:r,nodesByType:s}=vs(this,t),n=i.indexOf(t);if(-1===n)return void be.warn(`Node ${t.id} not found in '${e}' list.`);if(i.splice(n,1),r[t.id]!==t)return void be.error(`Entry ${t.id} in '${e} stored by ID' record does not contain this object.`);delete r[t.id];let o=s[t.type],a=null==o?void 0:o.indexOf(t);o&&-1!==a?s[t.type].splice(a,1):be.error(`Node ${t.id} not found in '${e} stored by type' record.`)}insertAnnotation(t){_r(this,t,this.annotationsById,"Annotation")&&(this.insertNode(t),this.spaceGraph&&(this.spaceGraph.registerNode(t),this.spaceGraph.emit("annotation-create",t)))}removeAnnotation(t){return this.removeNode(t),this.spaceGraph&&(this.spaceGraph.unregisterNode(t),this.spaceGraph.emit("annotation-delete",t)),t.layout=null,t}createAnnotation(t,e){let i=Kn(t,e);return this.insertAnnotation(i),i}insertView(t){_r(this,t,this.viewsById,"View")&&(this.insertNode(t),this.spaceGraph&&(this.spaceGraph.registerNode(t),this.spaceGraph.emit("view-create",t)))}removeView(t){return this.removeNode(t),this.spaceGraph&&(this.spaceGraph.unregisterNode(t),this.spaceGraph.emit("view-delete",t)),t.layout=null,t}createView(t,e){let i=Zn(t,e);return this.insertView(i),i}clearSpaces(){let t=[...this.spaces];for(let e of t)this.removeSpace(e)}getElementList(){return Object.values(this.elementsById)}getArea(t={program:{exclude:["void"]}}){var e,i;let r=(null==(e=null==t?void 0:t.program)?void 0:e.include)??[],s=(null==(i=null==t?void 0:t.program)?void 0:i.exclude)??[];if(r.length&&s.length)return be.warn("Cannot use 'include' and 'exclude' filters at the same time, skipping area calculation."),0;let n=0;for(let o of this.spaces){let t=!1;r.length&&(t=r.includes(o.attributes.program)),s.length&&(t=s.includes(o.attributes.program)),t||(n+=o.getArea())}return n}getLayoutGraph(){var t;let e=new Qn,i=this.elementsByType["element:spaceDivider"].slice();for(let r of this.elementsByType["element:opening"])"element:window"!==(null==(t=r.elements[0])?void 0:t.type)&&i.push(r);for(let r of i)for(let t of r.getSpaces())t&&e.addEdge("graph:connectedTo",t,r);for(let r of this.spatialGraph.edges)r.spaces[0]&&r.spaces[1]&&e.addEdge("graph:adjacentTo",r.spaces[0],r.spaces[1]);return e}getUniqueId(t,e){let i=0,r=t+i++;for(;this.suggestedIds[r]||e[r];)r=t+i++;return this.suggestedIds[r]=!0,r}getSpaceId(t){let e;return t=t??"space-",e=this.debugIds?this.getUniqueId(t,this.spacesById):Ut(),e}getElementId(t,e){let i;return e=e??t.type.split(":")[1]+"-",i=this.debugIds?this.getUniqueId(e,this.elementsById):Ut(),i}getBoundingBox(){const t={position:[0,0,0],rotation:0,rotationAxis:[0,1,0]};if(0===this.spaces.length)return{min:[0,0,0],max:[0,0,0],transform:t};const e=[];for(const s of this.spaces){const{min:t,max:i}=s.getAxisAlignedBoundingBox();e.push(t,i)}for(const s of this.getElementList()){const{min:t,max:i}=s.getAxisAlignedBoundingBox();e.push(t,i)}const{min:i,max:r}=lr(e.flat());return{min:i,max:r,transform:t}}toJSON(){let t=this.spatialGraph.toJSON(),e=function(t){let e=[];for(let i of t.spaces){let t=i.toJSON();e.push(t)}return e}(this),i=function(t){let e=[];for(let i of t.elements){let t=i.toJSON();t&&e.push(t)}return e}(this),r=function(t){let e=[];for(let i of t.annotations){let t=i.toJSON();e.push(t)}return e}(this),s=function(t){let e=[];for(let i of t.views){let t=i.toJSON();e.push(t)}return e}(this);return{...super.toJSON(),spatialGraph:t,spaces:e,elements:i,annotations:r,views:s}}static fromJSON(t,e){const i=(null==e?void 0:e.spaceGraph)??new Eo,r=new Xo(t.id);return Uo(r,t,i),(null==e?void 0:e.skipInsert)||i.insertSpatialStructure(r),r}}const Wo="spatialStructure:floor";class Yo extends Yn{constructor(t){super(t,Wo),this.parent=null,this.position=[0,0,0],this.rotation=0,this.layouts=[]}copyForClone(t){super.copyForClone(t),this.position=[...t.position],this.rotation=t.rotation}insertLayout(t){t.parent?be.warn(`SpaceGraphLayout ${t.id} already part of floor ${t.parent.id}.`):(t.parent=this,this.layouts.push(t),this.spaceGraph&&Hn(t,this.spaceGraph))}removeLayout(t){-1!==this.layouts.indexOf(t)?(this.spaceGraph&&$n(t,this.spaceGraph),t.parent=null):be.warn(`Floor ${t.id} not found.`)}createLayout(t){let e=new Xo(t);return this.insertLayout(e),e}toJSON(){const t={...super.toJSON(),position:[...this.position],rotation:this.rotation,layouts:[]};for(let e of this.layouts){let i=e.toJSON();t.layouts.push(i)}return t}static fromJSON(t,e){const i=(null==e?void 0:e.spaceGraph)??new Eo,r=new Yo(t.id);mo(r,t),Cr(r,t,i.customAttributesById),r.position=[...t.position],r.rotation=t.rotation;for(const s of t.layouts){const t=Xo.fromJSON(s,{spaceGraph:i,skipInsert:!0});r.insertLayout(t)}return(null==e?void 0:e.skipInsert)||i.insertSpatialStructure(r),r}}const Ho="spatialStructure:building";class $o extends Yn{constructor(t){super(t,Ho),this.floors=[],this.location={latLong:[0,0],rotation:0}}copyForClone(t){super.copyForClone(t),this.location=JSON.parse(JSON.stringify(t.location))}insertFloor(t){t.parent?be.warn(`Floor ${t.id} already part of building ${t.parent.id}.`):(t.parent=this,this.floors.push(t),this.spaceGraph&&jn(t,this.spaceGraph))}removeFloor(t){-1!==this.floors.indexOf(t)?(this.spaceGraph&&zn(t,this.spaceGraph),t.parent=null):be.warn(`Floor ${t.id} not found.`)}createFloor(t){let e=new Yo(t);return this.insertFloor(e),e}toJSON(){let t={...super.toJSON(),floors:[]},e=this.location;e.latLong[0]&&e.latLong[1]&&e.rotation&&(t.location={latLong:[...e.latLong],rotation:e.rotation});for(let i of this.floors){let e=i.toJSON();t.floors.push(e)}return t}static fromJSON(t,e){const i=e.spaceGraph??new Eo,r=new $o(t.id);mo(r,t),Cr(r,t,i.customAttributesById),t.location&&(r.location=JSON.parse(JSON.stringify(r.location)));for(const s of t.floors){const t=Yo.fromJSON(s,{spaceGraph:i,skipInsert:!0});r.insertFloor(t)}return e.skipInsert||i.insertSpatialStructure(r),r}}function jo(t,e,i,r){const s=1e-7*1e-7;let n=[e[0]-t[0],e[1]-t[1]],o=[r[0]-i[0],r[1]-i[1]],a=i[0]-t[0],l=i[1]-t[1],h=n[0]*o[1]-n[1]*o[0],u=h*h,c=n[0]*n[0]+n[1]*n[1];if(u>s*c*(o[0]*o[0]+o[1]*o[1])){let e=(a*o[1]-l*o[0])/h,i=(a*n[1]-l*n[0])/h;return{tag:2,intersect:!0,p:[t[0]+e*n[0],t[1]+e*n[1]],u:e,v:i}}return h=a*n[1]-l*n[0],u=h*h,u>s*c*(a*a+l*l)?{tag:0,intersect:!1}:{tag:1,intersect:!0}}function zo(t,e,i,r){const s=[e[0]-t[0],e[1]-t[1]],n=[r[0]-i[0],r[1]-i[1]],o=i[0]-t[0],a=i[1]-t[1];let l=s[0]*n[1]-s[1]*n[0],h=l*l;const u=s[0]*s[0]+s[1]*s[1];let c,d,p,f;if(h>1e-14*u*(n[0]*n[0]+n[1]*n[1])){const e=(o*n[1]-a*n[0])/l;if(e<0||e>1)return{tag:0,intersect:!1};{const i=(o*s[1]-a*s[0])/l;return i<0||i>1?{tag:0,intersect:!1}:(c=t[0]+e*s[0],d=t[1]+e*s[1],{tag:1,intersect:!0,p:[c,d],u:e,v:i})}}if(l=o*s[1]-a*s[0],h=l*l,h>1e-14*u*(o*o+a*a))return{tag:2,intersect:!1};{const e=(s[0]*o+s[1]*a)/u,i=e+(s[0]*n[0]+s[1]*n[1])/u;let r,l;e<i?(r=e,l=i):(r=i,l=e);const h=function(t,e,i,r){if(e<i||t>r)return{tag:0,intersect:!1};if(t===i&&e===r)return{tag:1,intersect:!0};if(e>i)return e<r?{tag:3,intersect:!0,w0:t<i?i:t,w1:e>r?r:e}:{tag:2,intersect:!0,w:t};return{tag:2,intersect:!0,w:e}}(0,1,r,l);switch(h.tag){case 0:return{tag:3,intersect:!1};case 1:return{tag:4,intersect:!0};case 2:{const e=h.w;return c=t[0]+e*s[0],d=t[1]+e*s[1],{tag:5,intersect:!0,p:[c,d],u:e}}case 3:{const e=h.w0,i=h.w1;return c=t[0]+e*s[0],d=t[1]+e*s[1],p=t[0]+i*s[0],f=t[1]+i*s[1],{tag:6,intersect:!0,p:[c,d],q:[p,f],u0:e,u1:i}}default:throw new Error("Unknown tag value.")}}}function Vo(...t){}function qo(t,e,i,r){let s=t[0],n=t[1];for(let o=1;o<e.length-1;o++){let a=e[o];if(_i(a,s,n)<1e-7)return i?t[0]=a:t[1]=a,void(r?e.splice(0,o):e.splice(o+1))}}function Jo(t){let e=0;for(;e<t.length-2;){let i=t[e],r=t[e+2];_i(t[e+1],i,r)<1e-7?t.splice(e+1,1):e++}}function Ko(t){if(t.length<3)return!1;let e=t.slice();e.push(t[0]);for(let i=0;i<e.length-2;i++){let t=e[i],r=e[i+1];for(let s=i+1;s<e.length-1;s++){const i=1e-7;let n=zo(t,r,e[s],e[s+1]);if(1===n.tag&&n.u>i&&n.u<1-i)return!0}}return!1}function Zo(t,e){return{position:[t,e],edges:[],geometry:{parameters:{joinStyle:{type:"miter",parameters:{distance:.05}}}}}}function Qo(t,e){let i={indices:[t,e],faces:[-1,-1],geometry:{tangible:!0,skipped:!1,parameters:{width:.15,height:2.5,offset:0},fragments:[],computed:{valid:!0,skipped:!1,selfIntersecting:!1,sidePoints1:[],sidePoints2:[],joinPoints1:[],joinPoints2:[],points:[]}},openings:[]};return i.geometry.fragments=[{edge:i,angle:0,points:[],joinPoints:[],sidePoints:[]},{edge:i,angle:0,points:[],joinPoints:[],sidePoints:[]}],i}const ta="intersectCap",ea="intersectCap";function ia(...t){}function ra(t){let e=t.toFixed(3),i=parseFloat(e);return e+=t>i?"+":t<i?"-":" ",t>=0&&(e=" "+e),e}function sa(t){if(t.length>0)for(let e=0;e<t.length;e++){let i=t[e];ia((i[0],i[1]))}}function na(t,e){for(let i of e)if(t.length>0){let e=t[0],r=t[t.length-1],s=oi(di(i,e)),n=oi(di(i,r));s>1e-7&&n>1e-7&&t.push(i)}else t.push(i)}function oa(t,e,i,r,s){0===t.joinPoints.length?(na(t.joinPoints,[...r,i]),na(t.sidePoints[0],s)):(na(t.joinPoints,r),na(t.sidePoints[1],s.slice().reverse())),sa(t.joinPoints),sa(t.sidePoints[0]),sa(t.sidePoints[1])}function aa(t,e,i,r,s){oa(t,0,i,[r],[r]),oa(e,0,i,[s],[s]),t.edge.geometry.computed.skipped=!0,e.edge.geometry.computed.skipped=!0}function la(t,e,i,r){oa(t,0,i,[r],[r]),oa(e,0,i,[r],[r])}function ha(t,e,i,r,s){oa(t,0,i,[r],[r]),oa(e,0,i,[s],[s])}function ua(t,e,i,r,s,n,o,a,l,h,u){if("ignore"===u)aa(t,e,i,s,a);else{let u;if(u=h?jo(r,s,l,a):jo(n,s,o,a),2!==u.tag)return be.warn("Edge side line does not intersect edge cap line, ignoring result."),void aa(t,e,i,s,a);let c=u.p;h?(oa(t,0,i,[c],[c]),oa(e,0,i,[a,c],[a])):(oa(t,0,i,[s,c],[s]),oa(e,0,i,[c],[c]))}}function ca(t,e,i,r,s,n,o,a,l,h,u,c){t.edge.id,e.edge.id;let d=jo(r,s,a,l);if(2!==d.tag)return be.warn("Edge side lines do not intersect, ignoring result.",d),void aa(t,e,i,s,l);let p=oi(di(s,r)),f=oi(di(l,a)),m=Math.max(0,1-.2/p),g=Math.max(0,1-.2/f),{p:y,u:v,v:x}=d,b="",_="";if(v>=.9999999)if(o)if(x>=.9999999){const r=1;if(oi(di(y,i))>r){let r,n=jo(y,i,s,l);2!==n.tag?(be.warn("Bevel construction failed, using center point.",n),r=li(s,l,.5)):r=n.p,oa(t,0,i,[r],[s,r]),oa(e,0,i,[r],[l,r])}else la(t,e,i,y)}else if(x>=g)la(t,e,i,y);else{let c=o&&u?ta:"ignore";ua(t,e,i,r,s,n,a,l,h,!0,c),_="ignore"===c?"* (ignore)":"* (intersectCap)"}else aa(t,e,i,s,l);else if(x>=.9999999)if(u)if(v>=m)la(t,e,i,y);else{let c=o&&u?ta:"ignore";ua(t,e,i,r,s,n,a,l,h,!1,c),b="ignore"===c?"* (ignore)":"* (intersectCap)"}else aa(t,e,i,s,l);else be.warn("Edge side line segments cross, ignoring result."),aa(t,e,i,s,l);ra(v),m.toFixed(3),ra(x),g.toFixed(3)}function da(t,e,i,r,s,n,o,a,l,h,u,c){t.edge.id,e.edge.id;let d=jo(r,s,a,l);if(2!==d.tag)return be.warn("Edge side lines do not intersect, ignoring result.",d),void aa(t,e,i,s,l);let p=oi(di(s,r)),f=oi(di(l,a)),m=Math.max(0,1-1/p),g=Math.max(0,1-1/f),{p:y,u:v,v:x}=d,b="",_="";if(v>=0&&v<=1+1e-7&&x>=0&&x<=1+1e-7)la(t,e,i,y);else if(v>1&&x>1)be.warn("Edge side line segments do not cross, ignoring result."),aa(t,e,i,s,l);else if(v>1)if(x>=g)la(t,e,i,y);else{let c=o&&u?ea:"ignore";ua(t,e,i,r,s,n,a,l,h,!1,c),_="ignore"===c?"* (ignore)":"* (intersectCap)"}else if(x>1)if(v>=m)la(t,e,i,y);else{let c=o&&u?ea:"ignore";ua(t,e,i,r,s,n,a,l,h,!0,c),b="ignore"===c?"* (ignore)":"* (intersectCap)"}else aa(t,e,i,s,l);ra(v),m.toFixed(3),ra(x),g.toFixed(3)}function pa(t,e){let i,r,s,n=e[0];n.indices[0]===t?(i=n.geometry.fragments[0],r=i.points[0],s=i.points[1]):(i=n.geometry.fragments[1],r=i.points[1],s=i.points[0]),i.joinPoints.push(r,s),i.sidePoints[0].push(r),i.sidePoints[1].push(s)}function fa(t,e,i){for(let r=0;r<e.length;r++){let s,n,o,a,l,h,u,c,d,p,f,m,g=e[r],y=r<e.length-1?e[r+1]:e[0],v=!g.geometry.skipped&&0!==g.geometry.parameters.width,x=!y.geometry.skipped&&0!==y.geometry.parameters.width;if(!v&&!x)continue;g.indices[0]===t?(s=g.geometry.fragments[0],n=g.geometry.fragments[1],o=n.points[0],a=s.points[0],l=s.points[1],h=i[g.indices[1]].position):(s=g.geometry.fragments[1],n=g.geometry.fragments[0],o=n.points[1],a=s.points[1],l=s.points[0],h=i[g.indices[0]].position),y.indices[0]===t?(u=y.geometry.fragments[0],c=y.geometry.fragments[1],d=c.points[1],p=u.points[1],f=u.points[0],m=i[y.indices[1]].position):(u=y.geometry.fragments[1],c=y.geometry.fragments[0],d=c.points[0],p=u.points[0],f=u.points[1],m=i[y.indices[0]].position);let b=i[t].position;const _=.01;let w=vi(o,a,d,p);if(w<_||w>Math.PI-_)ha(s,u,b,a,p);else{1===gi(h,b,m)?ca(s,u,b,o,a,l,v,d,p,f,x):da(s,u,b,o,a,l,v,d,p,f,x)}}}function ma(t){let e=t.geometry;e.fragments[0].joinPoints=[],e.fragments[0].sidePoints[0]=[],e.fragments[0].sidePoints[1]=[],e.fragments[1].joinPoints=[],e.fragments[1].sidePoints[0]=[],e.fragments[1].sidePoints[1]=[],e.computed={valid:!0,skipped:!1,selfIntersecting:!1,sidePoints1:[],sidePoints2:[],joinPoints1:[],joinPoints2:[],points:[]}}function ga(t,e){let i=function(t){let e={};for(let i of t){let t=i.indices[0],r=i.indices[1],s=Math.min(t,r),n=Math.max(t,r);e[s.toString()+"_"+n.toString()]=i}return e}(e),r=[];for(let n of e){if(!n.geometry.tangible||n.geometry.skipped)continue;let t=n.indices[0],e=n.indices[1];r[t]=!0,r[e]=!0,ma(n)}let{vertices:s}=t;for(let n=0;n<s.length;n++){if(!r[n])continue;let t=[],e=s[n];for(let r of e.edges){if(!r.geometry.tangible||r.geometry.skipped)continue;let e=r.indices[0],s=r.indices[1],n=Math.min(e,s),o=Math.max(e,s);i[n.toString()+"_"+o.toString()]&&t.push(r)}ia(t.length),1===t.length?pa(n,t):fa(n,t,s)}}function ya(t,e){let i=e.element;if(i?t.geometry.tangible="element:spaceDivider"!==i.type:e.boundaryWalls[0]||e.boundaryWalls[1]?t.geometry.tangible=!0:t.geometry.tangible=!1,i&&"element:wall"===i.type){let{width:e,height:r,offset:s}=i.parameters;t.geometry.parameters={width:e,height:r,offset:s}}else t.geometry.parameters={width:0,height:0,offset:0}}function va(t,e){let i=[],r={};for(let a of e)for(let t of a.vertices)if(void 0===r[t.id]){let e=Zo(t.position[0],t.position[1]);e.reference=t,r[t.id]=i.push(e)-1}let s=[],n={};for(let a of e){let t=a.vertices[0],e=a.vertices[1],i=Qo(r[t.id],r[e.id]);ya(i,a),i.id=a.id,i.reference=a,s.push(i),n[a.id]=!0}let o=function(t,e){return{vertices:t,edges:e,cycles:[],faces:[]}}(i,s);return function(t){let{vertices:e,edges:i}=t;for(let r of e)r.edges=[];for(let r of i){let t=r.indices[0],i=r.indices[1];e[t].edges.push(r),e[i].edges.push(r)}}(o),function(t){let{vertices:e}=t;for(let i=0;i<e.length;i++){let t=e[i],r=t.edges,s=[];for(let n of r){let r=e[i===n.indices[0]?n.indices[1]:n.indices[0]],o={edge:n,angle:ri([r.position[0]-t.position[0],r.position[1]-t.position[1]]),points:[],joinPoints:[],sidePoints:[[],[]]},a={edge:n,fragment:o};i===n.indices[0]?n.geometry.fragments[0]=o:n.geometry.fragments[1]=o,s.push(a)}s.sort((t,e)=>t.fragment.angle-e.fragment.angle),t.edges=s.map(t=>t.edge)}}(o),o}function xa(t){const e=t.map(t=>t.geometry.computed),i=function(t){var e;if(0===t.length)return[];const i={};for(const l of t)for(const t of l.indices)i[t]??(i[t]=[]),i[t].push(l);let r=(null==(e=Object.entries(i).find(([,t])=>1===t.length))?void 0:e[0])||Object.keys(i)[0];const s=[],n=/* @__PURE__ */new Set;let o=parseInt(r),a=i[o][0];for(;s.length<t.length;){if(n.has(a)){if(a=t.find(t=>!n.has(t)),!a)break;o=a.indices[0];continue}const e=a.indices[0]!==o;s.push({edge:a,reverse:e}),n.add(a);const r=e?a.indices[0]:a.indices[1],l=i[r].find(t=>!n.has(t));if(l)o=r,a=l;else{if(a=t.find(t=>!n.has(t)),!a)break;o=a.indices[0]}}return s}(t),r=t[0].geometry.computed;let s=r.valid;const n=i[0].reverse,o=i[0].edge.geometry.computed,a=i[i.length-1].reverse,l=i[i.length-1].edge.geometry.computed,h=n?o.joinPoints2:o.joinPoints1,u=a?l.joinPoints1:l.joinPoints2,c=[],d=[];for(const{edge:m,reverse:g}of i){const{computed:t}=m.geometry;g?(c.unshift(...t.sidePoints2),d.push(...t.sidePoints1)):(c.unshift(...t.sidePoints1),d.push(...t.sidePoints2))}const p=Y(e.map(t=>t.points));let f=[];if(1===p.length)f=p[0];else if(p.length>1){const t=$(p,.001,void 0,!0);t.length>0&&(f=t[0])}return 0===f.length&&(be.warn(`Empty wall geometry after merging edge profiles: ${t.map(t=>t.id).join(", ")}`),s=!1),{valid:s,skipped:r.skipped,selfIntersecting:r.selfIntersecting,sidePoints1:c.slice(),sidePoints2:d.slice(),joinPoints1:h.slice(),joinPoints2:u.slice(),points:f}}function ba(t,e){zr(t,e),e.emit("geometry-profile-update",e);for(let i of e.slabs)i.emit("geometry-profile-update",i)}function _a(t){let e=function(t){let e=/* @__PURE__ */new Map;for(let i of t)for(let t of i.boundaryWalls)t&&e.set(t.id,t);return[...e.values()]}(t);for(let i of e)Ms(i)}function wa(t){let e=t.spatialGraph.edges,i=va(0,e);!function(t){let{vertices:e,edges:i}=t;for(let r of i){let{geometry:t}=r,i=r.indices[0],s=r.indices[1],n=t.parameters.width,o=t.parameters.offset,a=e[i].position,l=e[s].position,h=di(l,a);if(t.skipped=oi(h)<1e-7,!t.skipped){let e=ui(hi(h)),i=ci(e,.5*n+o),r=ci(e,-.5*n+o),s=ii(a,i),u=ii(a,r),c=ii(l,i),d=ii(l,r);t.fragments[0].points=[s,u],t.fragments[1].points=[c,d]}}}(i),ga(i,i.edges),function(t,e){for(let i of e){let{geometry:t}=i;if(!t.tangible||t.skipped||0===t.parameters.width)continue;let e=t.fragments[0],r=t.fragments[1],s=[...e.joinPoints],n=[...r.joinPoints],o=[...e.sidePoints[0]],a=[...e.sidePoints[1]],l=[...r.sidePoints[0]],h=[...r.sidePoints[1]],u=jo(s[0],n[n.length-1],s[s.length-1],n[0]);2===u.tag&&u.u>0&&u.u<1&&u.v>0&&u.v<1&&(n.reverse(),l.reverse(),h.reverse(),[l,h]=[h,l]);let c=h.concat(o),d=a.concat(l);2===c.length&&2===d.length&&(qo(c,s,!1,!0),qo(c,n,!0,!1),qo(d,s,!0,!1),qo(d,n,!1,!0)),Jo(c),Jo(s),Jo(d),Jo(n),1===gi(c[0],c[c.length-1],d[0])&&(c.reverse(),d.reverse(),s.reverse(),n.reverse(),[c,d]=[d,c]);let p=c.slice(0,c.length-1),f=s.slice(0,s.length-1),m=d.slice(0,d.length-1),g=n.slice(0,n.length-1),y=tt(p.concat(f).concat(m).concat(g),.001),v=i.geometry.computed;v.sidePoints1=c,v.sidePoints2=d,v.joinPoints1=s,v.joinPoints2=n,v.points=y,v.selfIntersecting=Ko(v.points),v.valid=v.points.length>=3&&!v.skipped&&!v.selfIntersecting,Vo(i.id),Vo(v.valid),Vo(v.skipped),Vo(v.selfIntersecting)}}(0,i.edges),function(t){var e;let i={};for(let r of t.edges){let t=r.reference.element;if("element:wall"===(null==t?void 0:t.type)){let s=r.geometry.computed;1===t.getEdges().length?(t.geometryProfile={valid:s.valid,skipped:s.skipped,selfIntersecting:s.selfIntersecting,sidePoints1:s.sidePoints1.slice(),sidePoints2:s.sidePoints2.slice(),joinPoints1:s.joinPoints1.slice(),joinPoints2:s.joinPoints2.slice(),points:s.points.slice()},t.emit("geometry-profile-update",t)):(i[e=t.id]??(i[e]=[]),i[t.id].push(r),i[t.id].length===t.getEdges().length&&(t.geometryProfile=xa(i[t.id]),t.emit("geometry-profile-update",t)))}}}(i),function(t){var e;for(let i of t)"element:wall"===(null==(e=i.element)?void 0:e.type)&&Rs(i.element)}(e),_a(e)}function Pa(t){wa(t),function(t){let e=t.spaces;for(let i of e){ba(t,i);for(let t of i.slabs)Zr(t)}}(t)}function Ea(t){return new Promise((e,i)=>{t.oncomplete=t.onsuccess=()=>e(t.result),t.onabort=t.onerror=()=>i(t.error)})}function Ta(t,e){let i;return(r,s)=>(()=>{if(i)return i;const r=indexedDB.open(t);return r.onupgradeneeded=()=>r.result.createObjectStore(e),i=Ea(r),i.then(t=>{t.onclose=()=>i=void 0},()=>{}),i})().then(t=>s(t.transaction(e,r).objectStore(e)))}let Aa;function Ia(){return Aa||(Aa=Ta("keyval-store","keyval")),Aa}for(var Sa="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",Ca="undefined"==typeof Uint8Array?[]:new Uint8Array(256),Ma=0;Ma<64;Ma++)Ca[Sa.charCodeAt(Ma)]=Ma;var Oa={exports:{}};function Na(t,e){return t<e?-1:t>e?1:0}const La=/* @__PURE__ */St(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:class{constructor(t=[],e=Na){if(this.data=t,this.length=this.data.length,this.compare=e,this.length>0)for(let i=(this.length>>1)-1;i>=0;i--)this._down(i)}push(t){this.data.push(t),this.length++,this._up(this.length-1)}pop(){if(0===this.length)return;const t=this.data[0],e=this.data.pop();return this.length--,this.length>0&&(this.data[0]=e,this._down(0)),t}peek(){return this.data[0]}_up(t){const{data:e,compare:i}=this,r=e[t];for(;t>0;){const s=t-1>>1,n=e[s];if(i(r,n)>=0)break;e[t]=n,t=s}e[t]=r}_down(t){const{data:e,compare:i}=this,r=this.length>>1,s=e[t];for(;t<r;){let r=1+(t<<1),n=e[r];const o=r+1;if(o<this.length&&i(e[o],n)<0&&(r=o,n=e[o]),i(n,s)>=0)break;e[t]=n,t=r}e[t]=s}}},Symbol.toStringTag,{value:"Module"})));var Ra;!function(){if(Ra)return Oa.exports;Ra=1;var t=La;function e(e,s,n){var o,a,l,h;s=s||1;for(var u=0;u<e[0].length;u++){var c=e[0][u];(!u||c[0]<o)&&(o=c[0]),(!u||c[1]<a)&&(a=c[1]),(!u||c[0]>l)&&(l=c[0]),(!u||c[1]>h)&&(h=c[1])}var d=l-o,p=h-a,f=Math.min(d,p),m=f/2;if(0===f){var g=[o,a];return g.distance=0,g}for(var y=new t(void 0,i),v=o;v<l;v+=f)for(var x=a;x<h;x+=f)y.push(new r(v+m,x+m,m,e));var b=function(t){for(var e=0,i=0,s=0,n=t[0],o=0,a=n.length,l=a-1;o<a;l=o++){var h=n[o],u=n[l],c=h[0]*u[1]-u[0]*h[1];i+=(h[0]+u[0])*c,s+=(h[1]+u[1])*c,e+=3*c}return 0===e?new r(n[0][0],n[0][1],0,t):new r(i/e,s/e,0,t)}(e),_=new r(o+d/2,a+p/2,0,e);_.d>b.d&&(b=_);for(var w=y.length;y.length;){var P=y.pop();P.d>b.d&&(b=P,n&&console.log("found best %d after %d probes",Math.round(1e4*P.d)/1e4,w)),P.max-b.d<=s||(m=P.h/2,y.push(new r(P.x-m,P.y-m,m,e)),y.push(new r(P.x+m,P.y-m,m,e)),y.push(new r(P.x-m,P.y+m,m,e)),y.push(new r(P.x+m,P.y+m,m,e)),w+=4)}n&&(console.log("num probes: "+w),console.log("best distance: "+b.d));var E=[b.x,b.y];return E.distance=b.d,E}function i(t,e){return e.max-t.max}function r(t,e,i,r){this.x=t,this.y=e,this.h=i,this.d=function(t,e,i){for(var r=!1,n=1/0,o=0;o<i.length;o++)for(var a=i[o],l=0,h=a.length,u=h-1;l<h;u=l++){var c=a[l],d=a[u];c[1]>e!=d[1]>e&&t<(d[0]-c[0])*(e-c[1])/(d[1]-c[1])+c[0]&&(r=!r),n=Math.min(n,s(t,e,c,d))}return 0===n?0:(r?1:-1)*Math.sqrt(n)}(t,e,r),this.max=this.d+this.h*Math.SQRT2}function s(t,e,i,r){var s=i[0],n=i[1],o=r[0]-s,a=r[1]-n;if(0!==o||0!==a){var l=((t-s)*o+(e-n)*a)/(o*o+a*a);l>1?(s=r[0],n=r[1]):l>0&&(s+=o*l,n+=a*l)}return(o=t-s)*o+(a=e-n)*a}t.default&&(t=t.default),Oa.exports=e,Oa.exports.default=e,Oa.exports}();var ka,Ba={exports:{}};var Fa,Da,Ua=(ka||(ka=1,Fa=Ba,Da=function(){var t={},e=Math.PI/180,i=180/Math.PI,r=6378137,s=20037508.342789244;function n(t){return Number(t)===t&&t%1!=0}function o(e){if(e=e||{},this.size=e.size||256,this.expansion=!0===e.antimeridian?2:1,!t[this.size]){var i=this.size,r=t[this.size]={};r.Bc=[],r.Cc=[],r.zc=[],r.Ac=[];for(var s=0;s<30;s++)r.Bc.push(i/360),r.Cc.push(i/(2*Math.PI)),r.zc.push(i/2),r.Ac.push(i),i*=2}this.Bc=t[this.size].Bc,this.Cc=t[this.size].Cc,this.zc=t[this.size].zc,this.Ac=t[this.size].Ac}return o.prototype.px=function(t,i){if(n(i)){var r=this.size*Math.pow(2,i),s=r/2,o=r/360,a=r/(2*Math.PI),l=r,h=Math.min(Math.max(Math.sin(e*t[1]),-.9999),.9999),u=s+t[0]*o,c=s+.5*Math.log((1+h)/(1-h))*-a;return u>l*this.expansion&&(u=l*this.expansion),c>l&&(c=l),[u,c]}return s=this.zc[i],h=Math.min(Math.max(Math.sin(e*t[1]),-.9999),.9999),u=Math.round(s+t[0]*this.Bc[i]),c=Math.round(s+.5*Math.log((1+h)/(1-h))*-this.Cc[i]),u>this.Ac[i]*this.expansion&&(u=this.Ac[i]*this.expansion),c>this.Ac[i]&&(c=this.Ac[i]),[u,c]},o.prototype.ll=function(t,e){if(n(e)){var r=this.size*Math.pow(2,e),s=r/360,o=r/(2*Math.PI),a=r/2,l=(t[1]-a)/-o;return[(t[0]-a)/s,i*(2*Math.atan(Math.exp(l))-.5*Math.PI)]}return l=(t[1]-this.zc[e])/-this.Cc[e],[(t[0]-this.zc[e])/this.Bc[e],i*(2*Math.atan(Math.exp(l))-.5*Math.PI)]},o.prototype.bbox=function(t,e,i,r,s){r&&(e=Math.pow(2,i)-1-e);var n=[t*this.size,(+e+1)*this.size],o=[(+t+1)*this.size,e*this.size],a=this.ll(n,i).concat(this.ll(o,i));return"900913"===s?this.convert(a,"900913"):a},o.prototype.xyz=function(t,e,i,r){"900913"===r&&(t=this.convert(t,"WGS84"));var s=[t[0],t[1]],n=[t[2],t[3]],o=this.px(s,e),a=this.px(n,e),l=[Math.floor(o[0]/this.size),Math.floor((a[0]-1)/this.size)],h=[Math.floor(a[1]/this.size),Math.floor((o[1]-1)/this.size)],u={minX:Math.min.apply(Math,l)<0?0:Math.min.apply(Math,l),minY:Math.min.apply(Math,h)<0?0:Math.min.apply(Math,h),maxX:Math.max.apply(Math,l),maxY:Math.max.apply(Math,h)};if(i){var c={minY:Math.pow(2,e)-1-u.maxY,maxY:Math.pow(2,e)-1-u.minY};u.minY=c.minY,u.maxY=c.maxY}return u},o.prototype.convert=function(t,e){return"900913"===e?this.forward(t.slice(0,2)).concat(this.forward(t.slice(2,4))):this.inverse(t.slice(0,2)).concat(this.inverse(t.slice(2,4)))},o.prototype.forward=function(t){var i=[r*t[0]*e,r*Math.log(Math.tan(.25*Math.PI+.5*t[1]*e))];return i[0]>s&&(i[0]=s),i[0]<-s&&(i[0]=-s),i[1]>s&&(i[1]=s),i[1]<-s&&(i[1]=-s),i},o.prototype.inverse=function(t){return[t[0]*i/r,(.5*Math.PI-2*Math.atan(Math.exp(-t[1]/r)))*i]},o}(),Fa.exports=Da),Ba.exports);const Ga=/* @__PURE__ */It(Ua),Xa={work:{name:"Work",isHidden:!0,description:"space for individual head-down work",spaceUsage:{privateOffice:{name:"Private office",category:["office"]},focusRoom:{name:"Focus room",category:["office"]},openWorkspace:{name:"Open workspace",category:["office"]},enclosedWorkspace:{name:"Enclosed workspace",category:["office"]},closedWorkspace:{name:"Closed workspace",isDeprecated:!0,category:["office"]},executiveOffice:{name:"Executive office",isDeprecated:!0,category:["office"]}}},meet:{name:"Meet",isHidden:!0,spaceUsage:{meetingRoom:{name:"Meeting room",category:["office"]},hub:{name:"Hub",category:["office"]},assembly:{name:"Assembly",category:["office"]},boardRoom:{name:"Board room",category:["office"]},trainingRoom:{name:"Training room",category:["office"]},collaboration:{name:"Collaboration",isDeprecated:!0,category:["office"]}}},live:{name:"live",isHidden:!0,spaceUsage:{living:{name:"Living",category:["residential"]},dining:{name:"Dining",category:["residential"]},dining_living:{name:"Living & Dining",category:["residential"]},homeOffice:{name:"Home office",category:["residential"]},bedroom:{name:"Bedroom",category:["residential"]}}},socialize:{name:"Socialize",isHidden:!0,spaceUsage:{lobby:{name:"Lobby",category:["office","residential"]},reception:{name:"Reception",category:["office"]},lounge:{name:"Lounge",category:["office"]},cafe:{name:"Cafe",category:["office"]},canteen:{name:"Canteen",category:["office"]},pantry:{name:"Pantry",category:["office"]},terrace:{name:"Terrace",isOutdoor:!0,category:["office","residential"]},balcony:{name:"Balcony",isOutdoor:!0,category:["office","residential"]},rooftop:{name:"Rooftop",isOutdoor:!0,category:["office","residential"]},courtyard:{name:"Courtyard",isOutdoor:!0,category:["office","residential"]},garden:{name:"Garden",isOutdoor:!0,category:["residential"]},common:{name:"Common",isDeprecated:!0,category:["office"]}}},support:{name:"Support",isHidden:!0,spaceUsage:{serviceKitchen:{name:"Service kitchen",category:["office"]},printStation:{name:"Print station",category:["office"]},storage:{name:"Storage",category:["lightIndustrial","residential","office","parking"]},mailRoom:{name:"Mail room",category:["office"]},operationalRoom:{name:"Operational room",category:["lightIndustrial","office","parking"]},serviceRoom:{name:"Service room",category:["office"]},laundryRoom:{name:"Laundry room",category:["residential"]},loadingDock:{name:"Loading dock",category:["lightIndustrial"]},operate:{name:"Operate",isDeprecated:!0,category:["office"]},services:{name:"Services",isDeprecated:!0,category:["office","residential"]}}},care:{name:"Care",isHidden:!0,spaceUsage:{kitchen:{name:"Kitchen",category:["residential"]},wellnessRoom:{name:"Wellness room",category:["lightIndustrial","office"]},restroom:{name:"Restroom",category:["lightIndustrial","office","parking"]},bathroom:{name:"Bathroom",category:["residential"]},shower:{name:"Shower",category:["lightIndustrial","office","residential"]},toilet:{name:"Toilet",category:["residential"]}}},circulate:{name:"Circulate",isHidden:!0,spaceUsage:{corridor:{name:"Corridor",category:["lightIndustrial","residential","office","parking"]},foyer:{name:"Foyer",category:["lightIndustrial","residential","office","parking"]},staircase:{name:"Staircase",isVertical:!0,category:["lightIndustrial","residential","office","parking"]},elevator:{name:"Elevator",isVertical:!0,category:["lightIndustrial","residential","office","parking"]}}},drive:{name:"Drive",isHidden:!0,spaceUsage:{parkingSpot:{name:"Parking spot",category:["parking"]},driveway:{name:"Driveway",category:["parking"]},garage:{name:"Garage",category:["residential"]}}},produce:{name:"Produce",isHidden:!0,spaceUsage:{productionArea:{name:"Production area",category:["lightIndustrial"]}}},void:{isHidden:!0,name:"Void",spaceUsage:{shaft:{name:"Shaft",isVertical:!0,category:["lightIndustrial","residential","office","parking"]},buildingOpening:{name:"Building opening",isVertical:!0,category:["lightIndustrial","residential","office","parking"]},floorOpening:{name:"Floor opening",isVertical:!0,category:["lightIndustrial","residential","office","parking"]}}},undefined:{isHidden:!0,spaceUsage:{undefined:{name:"Undefined",category:["residential","office"],isHidden:!0}}}},Wa={};function Ya(t,e,i){let r=ft(...t),s=ft(...e),n=ft(...i),o=dt(),a=dt(),l=dt();return yt(o,r,n),yt(a,s,n),xt(l,o,a),vt(l,l),[...l]}function Ha(t){let{indices:e,vertices:i}=t,r=[],s=[],n=[],o=lr(i);for(let u=0;u<i.length;u+=3){let t=i[u],e=i[u+1],n=i[u+2];r.push([t,e,n]),s.push([t,n])}for(let u=0;u<e.length;u+=3){let t=e[u],i=e[u+1],o=e[u+2];Ya(r[t],r[i],r[o])[1]<.01||n.push([s[t],s[i],s[o]])}let a=[],l=[[]];if(!n.length)return{outlines:a,holes:l,boundingBox:o};let h=Q(Y(n),.0015);h=h.filter(t=>t&&t.length&&K(t)>5e-4);for(let u of h)Ti(u)?l[0].push(u):a.push(u);return{outlines:a,holes:l,boundingBox:o}}function $a(t,e={}){let i=function(t,e=nt(),i=/* @__PURE__ */new Map,r=!0){let s=[],n=t.spaceGraph;if("geometries"in t&&t.geometries)for(let o of t.geometries){let t,a,l,h;if("string"==typeof o){if(t=n.geometriesById[o],!t){be.warn(`Geometry ${o} not found.`);continue}a=[0,0,0],l=0,h=[0,1,0]}else{if("reference:geometry"!==o.type){be.warn(`Operation ${o.type} not supported.`);continue}let e=o.geometry;if("string"==typeof e){if(t=n.geometriesById[e],!t){be.warn(`Geometry ${e} not found.`);continue}}else t=e;a=o.position??[0,0,0],l=o.rotation??0,h=o.rotationAxis??[0,1,0]}let u=Ve(a,l);for(let o of u){let a=Ai(o.position,o.rotation,h);r&&(a=ht(nt(),e,a));let l=[];if("geometry:uri"===t.type&&"data3d"===t.format){let e=i.get(t.uri),r=(null==e?void 0:e.meshGeometries)||{};for(let t in r){let e=r[t];l.push(...ar(e,n.geometriesById,n.materialsById,[]))}}else l=ar(t,n.geometriesById,n.materialsById,[]);let u=wt(),c=dt();ct(u,a),ut(c,a);for(let t of l)Si(t.vertices,a);s.push({meshes:l,rotation:u,position:c})}}return s}(t,e.applyElementMatrix?gs(t,e.parentMatrix):void 0,e.resources),r=[];for(let s of i)for(let t of s.meshes)r.push(Ha(t));return r}Object.keys(Xa).forEach(t=>{const e=Xa[t];Wa[t]={name:e.name,type:"program",category:[]},e.isHidden&&(Wa[t].isHidden=e.isHidden);const i={};Object.keys(Xa[t].spaceUsage).forEach(e=>{const r=Xa[t].spaceUsage[e];Wa[e]={...r,type:"space",program:t},r.category.forEach(t=>{i[t]=!0})}),Wa[t].category=Object.keys(i)}),new Ga({size:256});const ja=/^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000|ffffffff-ffff-ffff-ffff-ffffffffffff)$/i;function za(t){return"string"==typeof t&&ja.test(t)}const Va={programs:{care:[{name:"bathroom",tags:[],categories:["residential"]},{name:"kitchen",tags:[],categories:["residential"]},{name:"restroom",tags:[],categories:["lightIndustrial","office","parking","laboratory"]},{name:"shower",tags:[],categories:["lightIndustrial","office","residential","laboratory"]},{name:"toilet",tags:[],categories:["residential"]},{name:"wellnessRoom",tags:[],categories:["lightIndustrial","office","laboratory"]}],circulate:[{name:"corridor",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"elevator",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"foyer",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"staircase",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]}],drive:[{name:"driveway",tags:[],categories:["parking"]},{name:"garage",tags:[],categories:["residential"]},{name:"parkingSpot",tags:[],categories:["parking"]}],live:[{name:"bedroom",tags:[],categories:["residential"]},{name:"dining",tags:[],categories:["residential"]},{name:"dining_living",tags:[],categories:["residential"]},{name:"homeOffice",tags:[],categories:["residential"]},{name:"living",tags:[],categories:["residential"]}],meet:[{name:"assembly",tags:[],categories:["office"]},{name:"boardRoom",tags:[],categories:["office"]},{name:"hub",tags:[],categories:["office"]},{name:"meetingRoom",tags:[],categories:["office"]},{name:"trainingRoom",tags:[],categories:["office"]}],none:[{name:"generic",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]}],produce:[{name:"productionArea",tags:[],categories:["lightIndustrial"]}],research:[{name:"lab",tags:[],categories:["lightIndustrial","laboratory"]}],socialize:[{name:"balcony",tags:["outdoor"],categories:["office","residential"]},{name:"cafe",tags:[],categories:["office","laboratory"]},{name:"canteen",tags:[],categories:["office"]},{name:"courtyard",tags:["outdoor"],categories:["office","residential"]},{name:"garden",tags:["outdoor"],categories:["residential"]},{name:"lobby",tags:[],categories:["office","residential","laboratory"]},{name:"lounge",tags:[],categories:["office","laboratory"]},{name:"pantry",tags:[],categories:["office"]},{name:"reception",tags:[],categories:["office","laboratory"]},{name:"rooftop",tags:["outdoor"],categories:["office","residential"]},{name:"terrace",tags:["outdoor"],categories:["office","residential"]}],support:[{name:"chemicalStore",tags:[],categories:["laboratory"]},{name:"cleanRoom",tags:[],categories:["laboratory"]},{name:"coldRoom",tags:[],categories:["laboratory"]},{name:"laundryRoom",tags:[],categories:["residential"]},{name:"loadingDock",tags:[],categories:["lightIndustrial"]},{name:"mailRoom",tags:[],categories:["office"]},{name:"operationalRoom",tags:[],categories:["lightIndustrial","office","parking","laboratory"]},{name:"printStation",tags:[],categories:["office"]},{name:"serviceKitchen",tags:[],categories:["office"]},{name:"serviceRoom",tags:[],categories:["office"]},{name:"storage",tags:[],categories:["lightIndustrial","office","parking","residential","laboratory"]}],void:[{name:"buildingOpening",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"floorOpening",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]},{name:"shaft",tags:["vertical"],categories:["lightIndustrial","office","parking","residential","laboratory"]}],work:[{name:"enclosedWorkspace",tags:[],categories:["office"]},{name:"focusRoom",tags:[],categories:["office"]},{name:"openWorkspace",tags:[],categories:["office"]},{name:"privateOffice",tags:[],categories:["office"]}]}},qa="#ffffff",Ja="#0c1829",Ka="#4d586b",Za="#929baa",Qa="#72849e",tl="#f1f2f3",el="#cfd5de",il="#e8ebef",rl="#f7f8fa",sl="#bdd7ff",nl="#3355ff",ol="#dfecff",al="#ab220a",ll={api:{productDataCacheAge:864e5,productContourCacheAge:864e6},hideElements:[],panZoom:!0,preserveViewbox:"center-center",roomStampSize:null,showCeilingLamps:!1,destroyOnDomRemove:!1,ui:{scale:!0,coordinates:!1},spaceLabelMapping:{},theme:{fontFamily:"Inter, Avenir, Verdana, sans-serif",background:{color:rl,showGrid:!1},wallContours:!1,showAssetTextures:!1,elements:{floorPlan:{grayscale:!1},roomStamp:{}}},units:{system:"metric",areaDecimals:0,lengthDecimals:3,roomDimensions:"area"},zoomRange:[3,300]};let hl="archilogic/product",ul="https://storage.archilogic.com";const cl=({apiStorageUrl:t,spaceApiUrl:e,apiProductDataPath:i}={})=>{"string"==typeof t&&(ul=t),"string"==typeof i&&(hl=i),"string"==typeof e&&(R=e)};let dl=new E(["info","warnings","errors"]);function pl(t,e){let i,r=e.product.geometries[0];const s="product:component"===e.product?.type;if("string"==typeof r){let t=r;i=e.spaceGraph.geometriesById[t]}else"reference:geometry"===r?.type&&"string"!=typeof r.geometry&&(i=r.geometry);if(!s&&!("geometry:uri"===i?.type))return Promise.reject("Unsupported product geometry: "+e.product.id);const n=s?["productJson"]:["productJson","productContour"];return t.loadResources(e.product.id,e,n).catch(t=>dl.error(t))}const fl=t=>{const e=[];return t.layout.elementsByType["element:asset"].forEach(t=>{"product"in t&&"product:static"===t.product?.type&&e.push(t)}),Promise.allSettled(e.map(e=>pl(t.loader,e)))};function ml(t){return fetch(`${ul}/${hl}/outline/${t}.json`).then(t=>{if(t.ok)return t.json();throw Error(t.statusText)})}const gl="undefined"==typeof window||"undefined"!=typeof process;let yl;try{yl=!gl&&Ta("al-kvs","al-keyval")}catch(b_){dl.warn("indexedDb initialization failed")}async function vl(t,e,i){if(!yl)return Promise.resolve();i=i||2592e6;try{const r={timeStamp:/* @__PURE__ */(new Date).getTime(),content:e,maxAge:i};return await function(t,e,i=Ia()){return i("readwrite",i=>(i.put(e,t),Ea(i.transaction)))}(t,r,yl),t}catch(r){return}}async function xl(t,e){if(!yl)return Promise.resolve();const i=e||2592e6,r=/* @__PURE__ */(new Date).getTime();let s;try{s=await function(t,e=Ia()){return e("readonly",e=>Ea(e.get(t)))}(t,yl);const e=r-s.timeStamp;if(e>Math.min(s.maxAge,i))return;if(s.content)return s.content}catch(n){return}}const bl="fpe-dc2-";var _l=/* @__PURE__ */(t=>(t[t.None=0]="None",t[t.Default=1]="Default",t[t.Grayscale=2]="Grayscale",t))(_l||{});class wl extends pe.TinyEmitter{constructor(t){super(),this.promiseCache=/* @__PURE__ */new Map,this.loadStages={product:!0,productContour:!0,productTexture:!1},this.queue={productJson:/* @__PURE__ */new Map,productContour:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this.resources={nodes:/* @__PURE__ */new Map,productJson:/* @__PURE__ */new Map,productContour:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this.initialLoading=!0,this._requestCounter=0,this._loadCounter=0;const{settings:e}=t;this.floorPlan=t,this.productContourCacheAge=e.api?.productContourCacheAge,this.productDataCacheAge=e.api?.productDataCacheAge,this.loadStages.productTexture=!!e.theme?.showAssetTextures&&!1!==e.loadTextures,this.on("resource-loaded",this.loadStatus,this)}loadStatus(){const t=this._requestCounter;this._loadCounter++,this.emit("loading-status",{totalCount:t,doneCount:this._loadCounter}),t===this._loadCounter&&this.emit("loading-done",{totalCount:t})}loadResources(t,e,i){return Promise.all(i.map(i=>this.loadResource(t,e,i)))}loadResource(t,e,i){if(this.resources.nodes.has(t)||this.resources.nodes.set(t,/* @__PURE__ */new Set),this.resources.nodes.get(t).add(e),this.queue[i].has(t))return this.queue[i].get(t);let r;switch(this._requestCounter++,i){case"productJson":r=Pl(t,this,e.product);break;case"productContour":this.loadStages.productTexture&&this._requestCounter++,r=El(t,this).then(()=>{if(this.loadStages.productTexture&&!this.resources.texture.has(t)){if(!this.resources.productJson.has(t))return void dl.warn("texture loading failed, no product info yet");const e=`${ul}/${hl}/thumb/${t}.png`;this.resources.texture.set(t,{textureUrl:e,applyFilter:1}),this.emit("product-load-texture",{resourceId:t})}})}return this.queue[i].set(t,r),r}reset(){this.resources={nodes:/* @__PURE__ */new Map,productContour:/* @__PURE__ */new Map,productJson:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this.queue={productContour:/* @__PURE__ */new Map,productJson:/* @__PURE__ */new Map,texture:/* @__PURE__ */new Map},this._loadCounter=0,this._requestCounter=0,this.promiseCache=/* @__PURE__ */new Map,this.initialLoading=!0}}const Pl=(t,e,i)=>{const r=e.floorPlan.spaceGraph;t!==i?.id||r.productsById[t]||r.insertProduct(i);const s=JSON.parse(JSON.stringify(i?.attributes||{}));return Number.isFinite(s.boundingBox?.min[0])||(dl.warn("invalid product bounding box"),delete s.boundingBox),e.resources.productJson.set(t,s),Promise.resolve().then(()=>{e.emit("resource-loaded",{resourceId:t})})},El=async(t,e)=>{const i=bl+t,r=e.promiseCache.get(i);if(r)return r;const s=function(t,e){const i=e.productContourCacheAge,r=i||864e6;if(!t)return Promise.reject("product id missing");const s=bl+t,n=e.promiseCache.get(s);if(n)return n;const o=xl(s,i).then(e=>e||ml(t).then(t=>(vl(s,t,r),t))).catch(t=>{dl.warn(t)});return e.promiseCache.set(s,o),o}(t,e).then(i=>{const r=i,s=e.resources.productJson.get(t);if(!s.boundingBox){dl.warn("product boundingbox missing - creating from contour");let t=W(r);s.boundingBox={min:[t.min[0],0,t.min[1]],max:[t.max[0],0,t.max[1]]}}e.resources.productContour.set(t,r),e.emit("resource-loaded",{resourceId:t})}).catch(()=>{});return e.promiseCache.set(i,s),s};function Tl(t){return t.max.map((e,i)=>e-t.min[i])}function Al(t,e=[0,0]){const{dimensions:i}=t.parameters,r=t.parent;let s=[];if("element:wall"===r?.type){let t=r.parameters.width;s=[[-e[0],-e[1]],[i[0]+e[0],-e[1]],[i[0]+e[0],t+e[1]],[-e[0],t+e[1]]]}return[{type:"curve:polygon",points:s}]}function Il(t,e){const i=t.elements[0]||t,r=e?.[i?.type];return void 0===r||("boolean"==typeof r?r:i.isExternal?r.external:r.internal)}function Sl(t,e={clip:{"element:door":!0,"element:window":!0}}){const i=.01,r=t.elementsByType["element:wall"],s=t.elementsByType["element:boundaryWall"],n=t.elementsByType["element:column"],o=t.elementsByType["element:opening"],a=[];for(const c of o){if(!Il(c,e.clip))continue;const t=Al(c,[0,i]),{position:r,rotation:s}=c,n={position:[r[0],r[2]],rotation:s},o=Oi(t[0].points,n);a.push([o])}const l=[];for(const c of r){let{points:t}=c.geometryProfile;t=$([t],i)[0],l.push([t])}for(const c of n){const{profile:t}=c.parameters;let{points:e}=sr(t);if("curve:rectangle"===t.type){const[i,r]=t.dimensions;e=[[-i/2,-r/2],[i/2,-r/2],[i/2,r/2],[-i/2,r/2]]}e=Oi(e,{position:[c.position[0],c.position[2]],rotation:c.rotation}),e=$([e],i)[0],l.push([e])}for(const c of s){let t=c.boundaries[0].geometryProfile;t=$([t],i)[0],l.push([t])}let{polygons:h}=function(t){if(!t.length||!t[0])return{polygons:[],polyTree:[]};let e=et(t[0]),i=[];for(let n=1;n<t.length;n++)i.push(...et(t[n]));let r=new X.Clipper;r.AddPaths(e,X.PolyType.ptSubject,!0),r.AddPaths(i,X.PolyType.ptClip,!0);let s=new X.PolyTree;return r.Execute(X.ClipType.ctUnion,s,X.PolyFillType.pftNonZero,X.PolyFillType.pftNonZero),H(s)}(l);h=j(h,-.01).polygons,a.length&&(h=V(h,a).polygons);const u=[];for(const c of h){const t=[];for(const e of c){let i=tt(e,.001);i.length&&t.push(i)}t.length&&u.push(t)}return u}const Cl=class t{constructor({options:t={}}={}){this.settings=y(ll),this.fpeId="fpe-"+Math.random().toString(36).replace(/[^a-z]+/g,"").substr(0,3),this.computed={wallContours:[],snapPoints:[],snapMargin:0},this.isBrowser="object"!=typeof process&&"undefined"!=typeof window,this.location={latitude:0,longitude:0,bearing:0},this._emitter=new pe.TinyEmitter,be.setLevels("errors"),this.set(t),this.loader=new wl(this)}on(t,e,i){return this._emitter.on(t,e,i),this}once(t,e,i){return this._emitter.once(t,e,i),this}off(t,e){return this._emitter.off(t,e),this}emit(t,...e){return this._emitter.emit(t,...e),this}loadLayout(t,{skipGeometryCompute:e=!1}={}){this.loadSpaceGraph(t.spaceGraph,{skipGeometryCompute:e,layoutId:t.id})}loadSpaceGraph(t,{skipGeometryCompute:e=!1,layoutId:i}={}){this.loader.initialLoading||this.loader.reset(),this.spaceGraph=t,this.layout=i?t.nodesById[i]:t.nodesByType["spatialStructure:layout"][0],this.layout&&"spatialStructure:layout"===this.layout.type?(e||(Pa(this.layout),function(t){for(let e of t.elements)ks(e)}(this.layout)),this.settings.theme.wallContours&&(this.computed.wallContours=Sl(this.layout)),setTimeout(()=>{this.loader.emit("spaces-loaded")},0),fl(this).then(()=>{const t=this.settings.hideElements.includes("element:asset"),e=0===Object.keys(this.spaceGraph.products).length;this.loader.emit("assets-loaded",!0),(t||e)&&this.loader.emit("loading-done",{totalCount:0})}).catch(t=>dl.warn(t)),this.loader.initialLoading=!1):dl.warn("No layout to load")}loadSpaceGraphJson(t){this.loadSpaceGraph(function(t){return Eo.fromJSON(t)}(t))}async loadFloorById(e,i=this.settings.api){return new Promise(async(s,n)=>{e&&"string"==typeof e||n(`Expected non-empty string floorId parameter; instead got: "${e}"`);try{const n=k({...i,sdkVersion:t.version}),a=new U(n);this.loader.once("assets-loaded",s);const l=await a.getFloorById(e,!1,!1,!0),h=l.properties?.address;if(o=h?.latitude,r(o,90)&&(this.location.latitude=h.latitude),function(t){return r(t,180)}(h?.longitude)&&(this.location.longitude=h.longitude),function(t){return r(t,180)}(h?.bearing)&&(this.location.bearing=h.bearing),!l.layout?.layout)throw new Error(`The floor ${e} has no space graph layout`);this.emit("space-api-floor-loaded",e),this.loadSpaceGraphJson(l.layout.layout)}catch(b_){n(b_)}var o}).catch(t=>{throw this.emit("space-api-floor-error",e,t),t})}set(t={}){const e=this.settings.hideElements?.includes("element:asset");let i=y(t);i.theme&&(i.theme=v(ll.theme,i.theme)),i.ui&&(i.ui={...ll.ui,...i.ui}),i.api&&(i.api={...ll.api,...i.api}),i.units&&(i.units={...ll.units,...i.units});const r=!i.hideElements?.includes("element:asset");for(let s in i)this.settings[s]=i[s];if(this.settings.theme?.elements?.["layout:space"]?.program){const t=this.settings.theme.elements["layout:space"].program,e={wash:"care",operate:"support",common:"socialize"};Object.keys(t).forEach(i=>{Object.keys(e).includes(i)&&(t[e[i]]=t[i],delete t[i])})}this.layout&&(e&&r&&fl(this),i.theme?.wallContours&&!this.computed.wallContours?.length?this.computed.wallContours=Sl(this.layout):!i.theme?.wallContours&&this.computed.wallContours?.length&&(this.computed.wallContours=[])),this.emit("update-settings",this.settings)}getBoundingBox(t=0){const{min:[e,,i],max:[r,,s]}=this.layout.getBoundingBox();return{min:[e-t,i-t],max:[r+t,s+t]}}getResourcesFromPosition(t){const e=this.layout?.spaces?.filter(e=>bi(t,e.geometry.polygons))||[],i=[];return e.forEach(e=>{const r=e.getElements("element:asset").filter(e=>{if(e.product.attributes.subCategories.includes("ceilingLight")&&!this.settings.showCeilingLamps)return;const i=e.getBoundingBoxContour();return i?.length?q(t,i):void 0});i.push(...r)}),{spaces:e,assets:i}}destroy(){delete this.layout,delete this.settings,delete this.utils}};Cl.version="5.1.21";let Ml=Cl;function Ol(t){let{length:e,hingeSide:i,doorSide:r,doorAngle:s,doorType:n,frameThickness:o,frameDepth:a}=t.parameters,l=[],h="right"===i,u="side1"===r,c=u?0:a,d=!1,p=0,f=0;if(s<5&&s>-5){s=20;const t=s/180*Math.PI;p=Math.sin(t),f=Math.cos(t),d=!0}if("singleSwing"===n){let t,i,r,n,a=e-2*o;u?h?(t=0,i=s,r=[o,c],n=[r[0]+f*a,r[1]-p*a]):(t=180-s,i=180,r=[e-o,c],n=[r[0]-f*a,r[1]-p*a]):h?(t=-180,i=-180+s,r=[e-o,c],n=[r[0]-f*a,r[1]+p*a]):(t=360-s,i=360,r=[o,c],n=[r[0]+f*a,r[1]+p*a]),l.push({type:"curve:arc",radius:a,position:r,startAngle:t,endAngle:i}),d&&l.push({type:"curve:line",start:r,end:n})}else if("doubleSwing"===n){let t,i,r,n,a,h,m,g,y=e/2-o;u?(t=0,i=s,r=[o,c],m=[e-o,c],a=180-s,h=180,n=[r[0]+f*y,r[1]-p*y],g=[m[0]-f*y,m[1]-p*y]):(t=360-s,i=360,r=[o,c],m=[e-o,c],a=180,h=180+s,n=[r[0]+f*y,r[1]+p*y],g=[m[0]-f*y,m[1]+p*y]),l.push({type:"curve:arc",radius:y,position:r,startAngle:t,endAngle:i}),l.push({type:"curve:arc",radius:y,position:m,startAngle:a,endAngle:h}),d&&(l.push({type:"curve:line",start:r,end:n}),l.push({type:"curve:line",start:m,end:g}))}return l}function Nl(t){let e=[];switch(t.type){case"element:door":e=Ol(t);break;case"element:stairFlight":e=function(t){let e=t.parent?.elements.find(t=>"element:stairFlight"===t.type);if(e?.id!==t.id||"spiral"===t.parameters.stairFlightType)return[];let{width:i,length:r,height:s}=t.parameters,n=r/Math.round(s/.17);return[{type:"curve:polyline",points:[[n/2-.06,i/2+.12],[n/2+.06,i/2],[n/2-.06,i/2-.12]]}]}(t)}return e}function Ll(t){for(const e of Object.keys(Va.programs)){if(Va.programs[e].find(e=>e.name===t))return e}return""}function Rl(t,e=0){return({"element:door":45,"element:window":45,"element:opening":40,"element:spaceDivider":35,"spatialGraph:edge":35,"element:column":30,"element:wall":30,"element:boundaryWall":30,"element:casework":20,"element:kitchen":20,"element:railing":20,"element:generic":11,"element:asset":10,"element:stairs":5,"element:stairFlight":5,"element:slab":5,"layout:space":1,"annotation:floorPlanDxf":0,"annotation:floorPlanImage":0}[t]||0)+e}const kl={default:{fill:qa,stroke:Za,strokeWidth:"native",fillOpacity:1},selected:{fill:ol,stroke:Za,strokeWidth:1}},Bl=t=>{const e=t.toString(16);return 1===e.length?"0"+e:e},Fl=t=>Number(parseInt(t.slice(1),16));function Dl(t){return"number"==typeof t?t:"string"==typeof t&&t.startsWith("#")?Fl(t):Array.isArray(t)?Fl(((t,e,i)=>"#"+[t,e,i].map(Bl).join(""))(...t)):void 0}const Ul=({settings:t,element:e,elementType:i})=>{const r=t?.theme?.elements;if(!r)return{};let s=r.byId?.[e?.id]||r[i]||r[e?.type]||null;if(e){const t=r["layout:space"];if("layout:space"===e.type){const i=Ll(e.attributes.usage);t?.usage?.[e.attributes.usage]?s=t.usage[e.attributes.usage]:t?.program?.[i]&&(s=t.program[i])}else"element:stairs"!==e.type||s||(t?.usage?.staircase?s=t.usage.staircase:t?.program?.circulate&&(s=t.program.circulate))}return(t=>{const{fill:e,fillOpacity:i,stroke:r,strokeWidth:s,strokeOpacity:n}=t,o={};return e&&(o.fill=Dl(e)),r&&(o.stroke=Dl(r)),"number"==typeof i&&Number.isFinite(i)&&(o.fillOpacity=Math.max(Math.min(i,1),0)),"number"==typeof n&&Number.isFinite(n)&&(o.strokeOpacity=Math.max(Math.min(n,1),0)),"string"==typeof s?"native"===s&&(o.strokeWidth=s):Number.isFinite(s)&&s>=0&&(o.strokeWidth=s),o})(s||{})},Gl=t=>{if(t?.layout?.debugIds){let i=/\d+/.exec(t.id)?.[0]||"0",r=(e=parseInt(i),function(){let t=e+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296});return{fill:Math.round(5*r()*16777215)%16777215,fillOpacity:.5}}var e;return{}},Xl=({style:t,settings:e,element:i,elementType:r})=>{const s="selected"===t?"selected":"default",n=function({element:t,settings:e,elementType:i,state:r="default"}){const s=e?.theme?.showAssetTextures,n={"element:wall":{default:{fill:Ka,stroke:Ka},selected:{fill:Qa,stroke:nl,strokeWidth:"native"}},"element:boundaryWall":{default:{fill:Ka,stroke:Ja},selected:{fill:Qa,stroke:nl}},"element:curtainWall":{default:{fill:tl},selected:{strokeWidth:"native"}},"element:column":{default:{fill:Ka,stroke:Ka},selected:{fill:Qa,stroke:nl,strokeWidth:"native"}},"element:asset":{default:{fill:s?null:tl},selected:{fill:ol,stroke:nl,strokeWidth:.5,alignment:0}},"element:stairs":{default:{fill:rl},selected:{strokeWidth:"native"}},"element:stairFlight":{default:{fill:rl}},"element:slab":{default:{fill:rl}},"layout:space":(()=>{const e={default:{fill:qa,stroke:el},selected:{fill:ol,stroke:el,strokeWidth:"native"}};if(t&&"layout:space"===t.type){const i="kitchen"!==t.attributes.usage&&Ll(t.attributes.usage),r={care:el,circulate:rl};i&&r[i]&&(e.default.fill=r[i]),"void"===i&&(e.default.fillOpacity=.05)}return e})(),"spatialGraph:edge":{default:{fill:el,stroke:Ja,strokeOpacity:.8,strokeWidth:.5},selected:{stroke:nl,strokeWidth:.5}},"element:spaceDivider":{default:{fill:el,stroke:Ja,strokeOpacity:.8,strokeWidth:.5},selected:{stroke:nl,strokeWidth:.5}}}[i]||kl,o=Ul({settings:e,element:t,elementType:i});return"selected"===r?{...kl.default,...n.default,...o,...kl.selected,...n.selected}:{...kl.default,...n.default,...o}}({element:i,elementType:r||i?.type,settings:e,state:s});return{...n,...t?{}:Gl(i),..."object"==typeof t?t:{}}};function Wl(t,e,i=.5){let r=[e[0]-t[0],e[1]-t[1]];return[t[0]+r[0]*i,t[1]+r[1]*i]}function Yl(t,e,i,r=5){const s=[];let n,o,a,l=0;for(let h=0;h<=r;++h)l=h/r,n=Wl(t,e,l),o=Wl(e,i,l),a=Wl(n,o,l),s.push(a);return s}const Hl=(t,e)=>{const i=Math.ceil(48/(2*Math.PI)*t*e),r=Math.ceil(12/(2*Math.PI)*t);return Math.min(100,Math.max(r,i))},$l=t=>{const e={type:"curve:polyline",points:[]};switch(t.type){case"curve:line":e.points=[t.start,t.end];break;case"curve:arc":const i=t.startAngle/180*Math.PI,r=t.endAngle/180*Math.PI-i,s=t.radius,n=Hl(Math.abs(r),s),o=t.position,a=r/n;let l=i;for(let t=0;t<n+1;t++)e.points.push([s*Math.cos(l)+o[0],-s*Math.sin(l)+o[1]]),l+=a;break;case"curve:polyline":e.points=t.points;break;case"curve:quadraticBezier":e.points.push(t.points[0]);for(let h=0;h<=t.points.length-3;h++){let i=t.points[h],r=t.points[h+1],s=t.points[h+2],n=Yl(0===h?i:Wl(i,r),r,h===t.points.length-3?s:Wl(r,s));e.points.push(...n.slice(1))}}return e},jl=(t,e,i=.15)=>{let r,s,n;for(const o of e)if(r=Math.abs(t[0]-o[0]),!(r>i)&&(s=Math.abs(t[1]-o[1]),r<i&&s<i)){n=o;break}return n};function zl(t){const e={10:["ceilingLight","wallLight"],9:["modularMeetingRoom","phoneBooth"],8:["floorLamp","tableLamp","deskDivider","cushion","plant","officeSupply","tableware","decoration","laundry","electronics","kitchen","car"],7:["shelf","cabinet","wardrobe","storageCombination","outdoor","bicycle","people","sink"],6:["highTable","diningTable","conferenceTable","desk"],5:["sofa","armchair","loungeChair","ottoman","sideboard","pedestal"],4:["taskChair","diningChair","conferenceChair","stool","barStool","bench"],3:["shower"],2:["singleBed","doubleBed","daybed","toilet","bathtub"],1:["sideTable","coffeeTable","radiator","nightstand"],0:["rug"]};let i=0;return t.subCategories.forEach(t=>{Object.keys(e).forEach(r=>{let s=parseInt(r);e[r].includes(t)&&s>i&&(i=s)})}),1===i&&t.categories.includes("tables")&&t.boundingBox.max[1]-t.boundingBox.min[1]>.6&&(i=6),i}var Vl=/* @__PURE__ */(t=>(t[t.WEBGL_LEGACY=0]="WEBGL_LEGACY",t[t.WEBGL=1]="WEBGL",t[t.WEBGL2=2]="WEBGL2",t))(Vl||{}),ql=/* @__PURE__ */(t=>(t[t.UNKNOWN=0]="UNKNOWN",t[t.WEBGL=1]="WEBGL",t[t.CANVAS=2]="CANVAS",t))(ql||{}),Jl=/* @__PURE__ */(t=>(t[t.COLOR=16384]="COLOR",t[t.DEPTH=256]="DEPTH",t[t.STENCIL=1024]="STENCIL",t))(Jl||{}),Kl=/* @__PURE__ */(t=>(t[t.NORMAL=0]="NORMAL",t[t.ADD=1]="ADD",t[t.MULTIPLY=2]="MULTIPLY",t[t.SCREEN=3]="SCREEN",t[t.OVERLAY=4]="OVERLAY",t[t.DARKEN=5]="DARKEN",t[t.LIGHTEN=6]="LIGHTEN",t[t.COLOR_DODGE=7]="COLOR_DODGE",t[t.COLOR_BURN=8]="COLOR_BURN",t[t.HARD_LIGHT=9]="HARD_LIGHT",t[t.SOFT_LIGHT=10]="SOFT_LIGHT",t[t.DIFFERENCE=11]="DIFFERENCE",t[t.EXCLUSION=12]="EXCLUSION",t[t.HUE=13]="HUE",t[t.SATURATION=14]="SATURATION",t[t.COLOR=15]="COLOR",t[t.LUMINOSITY=16]="LUMINOSITY",t[t.NORMAL_NPM=17]="NORMAL_NPM",t[t.ADD_NPM=18]="ADD_NPM",t[t.SCREEN_NPM=19]="SCREEN_NPM",t[t.NONE=20]="NONE",t[t.SRC_OVER=0]="SRC_OVER",t[t.SRC_IN=21]="SRC_IN",t[t.SRC_OUT=22]="SRC_OUT",t[t.SRC_ATOP=23]="SRC_ATOP",t[t.DST_OVER=24]="DST_OVER",t[t.DST_IN=25]="DST_IN",t[t.DST_OUT=26]="DST_OUT",t[t.DST_ATOP=27]="DST_ATOP",t[t.ERASE=26]="ERASE",t[t.SUBTRACT=28]="SUBTRACT",t[t.XOR=29]="XOR",t))(Kl||{}),Zl=/* @__PURE__ */(t=>(t[t.POINTS=0]="POINTS",t[t.LINES=1]="LINES",t[t.LINE_LOOP=2]="LINE_LOOP",t[t.LINE_STRIP=3]="LINE_STRIP",t[t.TRIANGLES=4]="TRIANGLES",t[t.TRIANGLE_STRIP=5]="TRIANGLE_STRIP",t[t.TRIANGLE_FAN=6]="TRIANGLE_FAN",t))(Zl||{}),Ql=/* @__PURE__ */(t=>(t[t.RGBA=6408]="RGBA",t[t.RGB=6407]="RGB",t[t.RG=33319]="RG",t[t.RED=6403]="RED",t[t.RGBA_INTEGER=36249]="RGBA_INTEGER",t[t.RGB_INTEGER=36248]="RGB_INTEGER",t[t.RG_INTEGER=33320]="RG_INTEGER",t[t.RED_INTEGER=36244]="RED_INTEGER",t[t.ALPHA=6406]="ALPHA",t[t.LUMINANCE=6409]="LUMINANCE",t[t.LUMINANCE_ALPHA=6410]="LUMINANCE_ALPHA",t[t.DEPTH_COMPONENT=6402]="DEPTH_COMPONENT",t[t.DEPTH_STENCIL=34041]="DEPTH_STENCIL",t))(Ql||{}),th=/* @__PURE__ */(t=>(t[t.TEXTURE_2D=3553]="TEXTURE_2D",t[t.TEXTURE_CUBE_MAP=34067]="TEXTURE_CUBE_MAP",t[t.TEXTURE_2D_ARRAY=35866]="TEXTURE_2D_ARRAY",t[t.TEXTURE_CUBE_MAP_POSITIVE_X=34069]="TEXTURE_CUBE_MAP_POSITIVE_X",t[t.TEXTURE_CUBE_MAP_NEGATIVE_X=34070]="TEXTURE_CUBE_MAP_NEGATIVE_X",t[t.TEXTURE_CUBE_MAP_POSITIVE_Y=34071]="TEXTURE_CUBE_MAP_POSITIVE_Y",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Y=34072]="TEXTURE_CUBE_MAP_NEGATIVE_Y",t[t.TEXTURE_CUBE_MAP_POSITIVE_Z=34073]="TEXTURE_CUBE_MAP_POSITIVE_Z",t[t.TEXTURE_CUBE_MAP_NEGATIVE_Z=34074]="TEXTURE_CUBE_MAP_NEGATIVE_Z",t))(th||{}),eh=/* @__PURE__ */(t=>(t[t.UNSIGNED_BYTE=5121]="UNSIGNED_BYTE",t[t.UNSIGNED_SHORT=5123]="UNSIGNED_SHORT",t[t.UNSIGNED_SHORT_5_6_5=33635]="UNSIGNED_SHORT_5_6_5",t[t.UNSIGNED_SHORT_4_4_4_4=32819]="UNSIGNED_SHORT_4_4_4_4",t[t.UNSIGNED_SHORT_5_5_5_1=32820]="UNSIGNED_SHORT_5_5_5_1",t[t.UNSIGNED_INT=5125]="UNSIGNED_INT",t[t.UNSIGNED_INT_10F_11F_11F_REV=35899]="UNSIGNED_INT_10F_11F_11F_REV",t[t.UNSIGNED_INT_2_10_10_10_REV=33640]="UNSIGNED_INT_2_10_10_10_REV",t[t.UNSIGNED_INT_24_8=34042]="UNSIGNED_INT_24_8",t[t.UNSIGNED_INT_5_9_9_9_REV=35902]="UNSIGNED_INT_5_9_9_9_REV",t[t.BYTE=5120]="BYTE",t[t.SHORT=5122]="SHORT",t[t.INT=5124]="INT",t[t.FLOAT=5126]="FLOAT",t[t.FLOAT_32_UNSIGNED_INT_24_8_REV=36269]="FLOAT_32_UNSIGNED_INT_24_8_REV",t[t.HALF_FLOAT=36193]="HALF_FLOAT",t))(eh||{}),ih=/* @__PURE__ */(t=>(t[t.FLOAT=0]="FLOAT",t[t.INT=1]="INT",t[t.UINT=2]="UINT",t))(ih||{}),rh=/* @__PURE__ */(t=>(t[t.NEAREST=0]="NEAREST",t[t.LINEAR=1]="LINEAR",t))(rh||{}),sh=/* @__PURE__ */(t=>(t[t.CLAMP=33071]="CLAMP",t[t.REPEAT=10497]="REPEAT",t[t.MIRRORED_REPEAT=33648]="MIRRORED_REPEAT",t))(sh||{}),nh=/* @__PURE__ */(t=>(t[t.OFF=0]="OFF",t[t.POW2=1]="POW2",t[t.ON=2]="ON",t[t.ON_MANUAL=3]="ON_MANUAL",t))(nh||{}),oh=/* @__PURE__ */(t=>(t[t.NPM=0]="NPM",t[t.UNPACK=1]="UNPACK",t[t.PMA=2]="PMA",t[t.NO_PREMULTIPLIED_ALPHA=0]="NO_PREMULTIPLIED_ALPHA",t[t.PREMULTIPLY_ON_UPLOAD=1]="PREMULTIPLY_ON_UPLOAD",t[t.PREMULTIPLIED_ALPHA=2]="PREMULTIPLIED_ALPHA",t))(oh||{}),ah=/* @__PURE__ */(t=>(t[t.NO=0]="NO",t[t.YES=1]="YES",t[t.AUTO=2]="AUTO",t[t.BLEND=0]="BLEND",t[t.CLEAR=1]="CLEAR",t[t.BLIT=2]="BLIT",t))(ah||{}),lh=/* @__PURE__ */(t=>(t[t.AUTO=0]="AUTO",t[t.MANUAL=1]="MANUAL",t))(lh||{}),hh=/* @__PURE__ */(t=>(t.LOW="lowp",t.MEDIUM="mediump",t.HIGH="highp",t))(hh||{}),uh=/* @__PURE__ */(t=>(t[t.NONE=0]="NONE",t[t.SCISSOR=1]="SCISSOR",t[t.STENCIL=2]="STENCIL",t[t.SPRITE=3]="SPRITE",t[t.COLOR=4]="COLOR",t))(uh||{}),ch=/* @__PURE__ */(t=>(t[t.NONE=0]="NONE",t[t.LOW=2]="LOW",t[t.MEDIUM=4]="MEDIUM",t[t.HIGH=8]="HIGH",t))(ch||{}),dh=/* @__PURE__ */(t=>(t[t.ELEMENT_ARRAY_BUFFER=34963]="ELEMENT_ARRAY_BUFFER",t[t.ARRAY_BUFFER=34962]="ARRAY_BUFFER",t[t.UNIFORM_BUFFER=35345]="UNIFORM_BUFFER",t))(dh||{});const ph={ADAPTER:{createCanvas:(t,e)=>{const i=document.createElement("canvas");return i.width=t,i.height=e,i},getCanvasRenderingContext2D:()=>CanvasRenderingContext2D,getWebGLRenderingContext:()=>WebGLRenderingContext,getNavigator:()=>navigator,getBaseUrl:()=>document.baseURI??window.location.href,getFontFaceSet:()=>document.fonts,fetch:(t,e)=>fetch(t,e),parseXML:t=>(new DOMParser).parseFromString(t,"text/xml")},RESOLUTION:1,CREATE_IMAGE_BITMAP:!1,ROUND_PIXELS:!1};var fh=/iPhone/i,mh=/iPod/i,gh=/iPad/i,yh=/\biOS-universal(?:.+)Mac\b/i,vh=/\bAndroid(?:.+)Mobile\b/i,xh=/Android/i,bh=/(?:SD4930UR|\bSilk(?:.+)Mobile\b)/i,_h=/Silk/i,wh=/Windows Phone/i,Ph=/\bWindows(?:.+)ARM\b/i,Eh=/BlackBerry/i,Th=/BB10/i,Ah=/Opera Mini/i,Ih=/\b(CriOS|Chrome)(?:.+)Mobile/i,Sh=/Mobile(?:.+)Firefox\b/i,Ch=function(t){return void 0!==t&&"MacIntel"===t.platform&&"number"==typeof t.maxTouchPoints&&t.maxTouchPoints>1&&"undefined"==typeof MSStream};function Mh(t){var e={userAgent:"",platform:"",maxTouchPoints:0};t||"undefined"==typeof navigator?"string"==typeof t?e.userAgent=t:t&&t.userAgent&&(e={userAgent:t.userAgent,platform:t.platform,maxTouchPoints:t.maxTouchPoints||0}):e={userAgent:navigator.userAgent,platform:navigator.platform,maxTouchPoints:navigator.maxTouchPoints||0};var i=e.userAgent,r=i.split("[FBAN");void 0!==r[1]&&(i=r[0]),void 0!==(r=i.split("Twitter"))[1]&&(i=r[0]);var s=function(t){return function(e){return e.test(t)}}(i),n={apple:{phone:s(fh)&&!s(wh),ipod:s(mh),tablet:!s(fh)&&(s(gh)||Ch(e))&&!s(wh),universal:s(yh),device:(s(fh)||s(mh)||s(gh)||s(yh)||Ch(e))&&!s(wh)},amazon:{phone:s(bh),tablet:!s(bh)&&s(_h),device:s(bh)||s(_h)},android:{phone:!s(wh)&&s(bh)||!s(wh)&&s(vh),tablet:!s(wh)&&!s(bh)&&!s(vh)&&(s(_h)||s(xh)),device:!s(wh)&&(s(bh)||s(_h)||s(vh)||s(xh))||s(/\bokhttp\b/i)},windows:{phone:s(wh),tablet:s(Ph),device:s(wh)||s(Ph)},other:{blackberry:s(Eh),blackberry10:s(Th),opera:s(Ah),firefox:s(Sh),chrome:s(Ih),device:s(Eh)||s(Th)||s(Ah)||s(Sh)||s(Ih)},any:!1,phone:!1,tablet:!1};return n.any=n.apple.device||n.android.device||n.windows.device||n.other.device,n.phone=n.apple.phone||n.android.phone||n.windows.phone,n.tablet=n.apple.tablet||n.android.tablet||n.windows.tablet,n}const Oh=(Mh.default??Mh)(globalThis.navigator);ph.RETINA_PREFIX=/@([0-9\.]+)x/,ph.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT=!1;var Nh,Lh={exports:{}};var Rh=(Nh||(Nh=1,function(t){var e=Object.prototype.hasOwnProperty,i="~";function r(){}function s(t,e,i){this.fn=t,this.context=e,this.once=i||!1}function n(t,e,r,n,o){if("function"!=typeof r)throw new TypeError("The listener must be a function");var a=new s(r,n||t,o),l=i?i+e:e;return t._events[l]?t._events[l].fn?t._events[l]=[t._events[l],a]:t._events[l].push(a):(t._events[l]=a,t._eventsCount++),t}function o(t,e){0===--t._eventsCount?t._events=new r:delete t._events[e]}function a(){this._events=new r,this._eventsCount=0}Object.create&&(r.prototype=/* @__PURE__ */Object.create(null),(new r).__proto__||(i=!1)),a.prototype.eventNames=function(){var t,r,s=[];if(0===this._eventsCount)return s;for(r in t=this._events)e.call(t,r)&&s.push(i?r.slice(1):r);return Object.getOwnPropertySymbols?s.concat(Object.getOwnPropertySymbols(t)):s},a.prototype.listeners=function(t){var e=i?i+t:t,r=this._events[e];if(!r)return[];if(r.fn)return[r.fn];for(var s=0,n=r.length,o=new Array(n);s<n;s++)o[s]=r[s].fn;return o},a.prototype.listenerCount=function(t){var e=i?i+t:t,r=this._events[e];return r?r.fn?1:r.length:0},a.prototype.emit=function(t,e,r,s,n,o){var a=i?i+t:t;if(!this._events[a])return!1;var l,h,u=this._events[a],c=arguments.length;if(u.fn){switch(u.once&&this.removeListener(t,u.fn,void 0,!0),c){case 1:return u.fn.call(u.context),!0;case 2:return u.fn.call(u.context,e),!0;case 3:return u.fn.call(u.context,e,r),!0;case 4:return u.fn.call(u.context,e,r,s),!0;case 5:return u.fn.call(u.context,e,r,s,n),!0;case 6:return u.fn.call(u.context,e,r,s,n,o),!0}for(h=1,l=new Array(c-1);h<c;h++)l[h-1]=arguments[h];u.fn.apply(u.context,l)}else{var d,p=u.length;for(h=0;h<p;h++)switch(u[h].once&&this.removeListener(t,u[h].fn,void 0,!0),c){case 1:u[h].fn.call(u[h].context);break;case 2:u[h].fn.call(u[h].context,e);break;case 3:u[h].fn.call(u[h].context,e,r);break;case 4:u[h].fn.call(u[h].context,e,r,s);break;default:if(!l)for(d=1,l=new Array(c-1);d<c;d++)l[d-1]=arguments[d];u[h].fn.apply(u[h].context,l)}}return!0},a.prototype.on=function(t,e,i){return n(this,t,e,i,!1)},a.prototype.once=function(t,e,i){return n(this,t,e,i,!0)},a.prototype.removeListener=function(t,e,r,s){var n=i?i+t:t;if(!this._events[n])return this;if(!e)return o(this,n),this;var a=this._events[n];if(a.fn)a.fn!==e||s&&!a.once||r&&a.context!==r||o(this,n);else{for(var l=0,h=[],u=a.length;l<u;l++)(a[l].fn!==e||s&&!a[l].once||r&&a[l].context!==r)&&h.push(a[l]);h.length?this._events[n]=1===h.length?h[0]:h:o(this,n)}return this},a.prototype.removeAllListeners=function(t){var e;return t?(e=i?i+t:t,this._events[e]&&o(this,e)):(this._events=new r,this._eventsCount=0),this},a.prototype.off=a.prototype.removeListener,a.prototype.addListener=a.prototype.on,a.prefixed=i,a.EventEmitter=a,t.exports=a}(Lh)),Lh.exports);const kh=/* @__PURE__ */It(Rh);var Bh,Fh,Dh,Uh={},Gh={exports:{}},Xh=Gh.exports;function Wh(){return Dh?Fh:(Dh=1,Fh=TypeError)}const Yh=/* @__PURE__ */St(/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,default:{}},Symbol.toStringTag,{value:"Module"})));var Hh,$h,jh,zh,Vh,qh,Jh,Kh,Zh,Qh,tu,eu,iu,ru,su,nu,ou,au,lu,hu,uu,cu,du,pu,fu,mu,gu,yu,vu,xu,bu,_u,wu,Pu,Eu,Tu,Au,Iu,Su,Cu,Mu,Ou,Nu,Lu,Ru,ku,Bu,Fu,Du,Uu,Gu,Xu,Wu,Yu,Hu,$u,ju,zu,Vu,qu,Ju,Ku,Zu,Qu,tc,ec,ic,rc,sc,nc,oc,ac,lc,hc,uc,cc,dc,pc,fc,mc,gc,yc,vc,xc,bc,_c,wc,Pc,Ec;function Tc(){if($h)return Hh;$h=1;var t="function"==typeof Map&&Map.prototype,e=Object.getOwnPropertyDescriptor&&t?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,i=t&&e&&"function"==typeof e.get?e.get:null,r=t&&Map.prototype.forEach,s="function"==typeof Set&&Set.prototype,n=Object.getOwnPropertyDescriptor&&s?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,o=s&&n&&"function"==typeof n.get?n.get:null,a=s&&Set.prototype.forEach,l="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,h="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,u="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,c=Boolean.prototype.valueOf,d=Object.prototype.toString,p=Function.prototype.toString,f=String.prototype.match,m=String.prototype.slice,g=String.prototype.replace,y=String.prototype.toUpperCase,v=String.prototype.toLowerCase,x=RegExp.prototype.test,b=Array.prototype.concat,_=Array.prototype.join,w=Array.prototype.slice,P=Math.floor,E="function"==typeof BigInt?BigInt.prototype.valueOf:null,T=Object.getOwnPropertySymbols,A="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,I="function"==typeof Symbol&&"object"==typeof Symbol.iterator,S="function"==typeof Symbol&&Symbol.toStringTag&&(typeof Symbol.toStringTag===I||"symbol")?Symbol.toStringTag:null,C=Object.prototype.propertyIsEnumerable,M=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(t){return t.__proto__}:null);function O(t,e){if(t===1/0||t===-1/0||t!=t||t&&t>-1e3&&t<1e3||x.call(/e/,e))return e;var i=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof t){var r=t<0?-P(-t):P(t);if(r!==t){var s=String(r),n=m.call(e,s.length+1);return g.call(s,i,"$&_")+"."+g.call(g.call(n,/([0-9]{3})/g,"$&_"),/_$/,"")}}return g.call(e,i,"$&_")}var N=Yh,L=N.custom,R=W(L)?L:null,k={__proto__:null,double:'"',single:"'"},B={__proto__:null,double:/(["\\])/g,single:/(['\\])/g};function F(t,e,i){var r=i.quoteStyle||e,s=k[r];return s+t+s}function D(t){return g.call(String(t),/"/g,"&quot;")}function U(t){return!S||!("object"==typeof t&&(S in t||void 0!==t[S]))}function G(t){return"[object Array]"===$(t)&&U(t)}function X(t){return"[object RegExp]"===$(t)&&U(t)}function W(t){if(I)return t&&"object"==typeof t&&t instanceof Symbol;if("symbol"==typeof t)return!0;if(!t||"object"!=typeof t||!A)return!1;try{return A.call(t),!0}catch(e){}return!1}Hh=function t(e,s,n,d){var y=s||{};if(H(y,"quoteStyle")&&!H(k,y.quoteStyle))throw new TypeError('option "quoteStyle" must be "single" or "double"');if(H(y,"maxStringLength")&&("number"==typeof y.maxStringLength?y.maxStringLength<0&&y.maxStringLength!==1/0:null!==y.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var x=!H(y,"customInspect")||y.customInspect;if("boolean"!=typeof x&&"symbol"!==x)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(H(y,"indent")&&null!==y.indent&&"\t"!==y.indent&&!(parseInt(y.indent,10)===y.indent&&y.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(H(y,"numericSeparator")&&"boolean"!=typeof y.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var P=y.numericSeparator;if(void 0===e)return"undefined";if(null===e)return"null";if("boolean"==typeof e)return e?"true":"false";if("string"==typeof e)return z(e,y);if("number"==typeof e){if(0===e)return 1/0/e>0?"0":"-0";var T=String(e);return P?O(e,T):T}if("bigint"==typeof e){var L=String(e)+"n";return P?O(e,L):L}var B=void 0===y.depth?5:y.depth;if(void 0===n&&(n=0),n>=B&&B>0&&"object"==typeof e)return G(e)?"[Array]":"[Object]";var Y=function(t,e){var i;if("\t"===t.indent)i="\t";else{if(!("number"==typeof t.indent&&t.indent>0))return null;i=_.call(Array(t.indent+1)," ")}return{base:i,prev:_.call(Array(e+1),i)}}(y,n);if(void 0===d)d=[];else if(j(d,e)>=0)return"[Circular]";function V(e,i,r){if(i&&(d=w.call(d)).push(i),r){var s={depth:y.depth};return H(y,"quoteStyle")&&(s.quoteStyle=y.quoteStyle),t(e,s,n+1,d)}return t(e,y,n+1,d)}if("function"==typeof e&&!X(e)){var tt=function(t){if(t.name)return t.name;var e=f.call(p.call(t),/^function\s*([\w$]+)/);if(e)return e[1];return null}(e),et=Q(e,V);return"[Function"+(tt?": "+tt:" (anonymous)")+"]"+(et.length>0?" { "+_.call(et,", ")+" }":"")}if(W(e)){var it=I?g.call(String(e),/^(Symbol\(.*\))_[^)]*$/,"$1"):A.call(e);return"object"!=typeof e||I?it:q(it)}if(function(t){if(!t||"object"!=typeof t)return!1;if("undefined"!=typeof HTMLElement&&t instanceof HTMLElement)return!0;return"string"==typeof t.nodeName&&"function"==typeof t.getAttribute}(e)){for(var rt="<"+v.call(String(e.nodeName)),st=e.attributes||[],nt=0;nt<st.length;nt++)rt+=" "+st[nt].name+"="+F(D(st[nt].value),"double",y);return rt+=">",e.childNodes&&e.childNodes.length&&(rt+="..."),rt+="</"+v.call(String(e.nodeName))+">"}if(G(e)){if(0===e.length)return"[]";var ot=Q(e,V);return Y&&!function(t){for(var e=0;e<t.length;e++)if(j(t[e],"\n")>=0)return!1;return!0}(ot)?"["+Z(ot,Y)+"]":"[ "+_.call(ot,", ")+" ]"}if(function(t){return"[object Error]"===$(t)&&U(t)}(e)){var at=Q(e,V);return"cause"in Error.prototype||!("cause"in e)||C.call(e,"cause")?0===at.length?"["+String(e)+"]":"{ ["+String(e)+"] "+_.call(at,", ")+" }":"{ ["+String(e)+"] "+_.call(b.call("[cause]: "+V(e.cause),at),", ")+" }"}if("object"==typeof e&&x){if(R&&"function"==typeof e[R]&&N)return N(e,{depth:B-n});if("symbol"!==x&&"function"==typeof e.inspect)return e.inspect()}if(function(t){if(!i||!t||"object"!=typeof t)return!1;try{i.call(t);try{o.call(t)}catch(rt){return!0}return t instanceof Map}catch(e){}return!1}(e)){var lt=[];return r&&r.call(e,function(t,i){lt.push(V(i,e,!0)+" => "+V(t,e))}),K("Map",i.call(e),lt,Y)}if(function(t){if(!o||!t||"object"!=typeof t)return!1;try{o.call(t);try{i.call(t)}catch(e){return!0}return t instanceof Set}catch(r){}return!1}(e)){var ht=[];return a&&a.call(e,function(t){ht.push(V(t,e))}),K("Set",o.call(e),ht,Y)}if(function(t){if(!l||!t||"object"!=typeof t)return!1;try{l.call(t,l);try{h.call(t,h)}catch(rt){return!0}return t instanceof WeakMap}catch(e){}return!1}(e))return J("WeakMap");if(function(t){if(!h||!t||"object"!=typeof t)return!1;try{h.call(t,h);try{l.call(t,l)}catch(rt){return!0}return t instanceof WeakSet}catch(e){}return!1}(e))return J("WeakSet");if(function(t){if(!u||!t||"object"!=typeof t)return!1;try{return u.call(t),!0}catch(e){}return!1}(e))return J("WeakRef");if(function(t){return"[object Number]"===$(t)&&U(t)}(e))return q(V(Number(e)));if(function(t){if(!t||"object"!=typeof t||!E)return!1;try{return E.call(t),!0}catch(e){}return!1}(e))return q(V(E.call(e)));if(function(t){return"[object Boolean]"===$(t)&&U(t)}(e))return q(c.call(e));if(function(t){return"[object String]"===$(t)&&U(t)}(e))return q(V(String(e)));if("undefined"!=typeof window&&e===window)return"{ [object Window] }";if("undefined"!=typeof globalThis&&e===globalThis||void 0!==At&&e===At)return"{ [object globalThis] }";if(!function(t){return"[object Date]"===$(t)&&U(t)}(e)&&!X(e)){var ut=Q(e,V),ct=M?M(e)===Object.prototype:e instanceof Object||e.constructor===Object,dt=e instanceof Object?"":"null prototype",pt=!ct&&S&&Object(e)===e&&S in e?m.call($(e),8,-1):dt?"Object":"",ft=(ct||"function"!=typeof e.constructor?"":e.constructor.name?e.constructor.name+" ":"")+(pt||dt?"["+_.call(b.call([],pt||[],dt||[]),": ")+"] ":"");return 0===ut.length?ft+"{}":Y?ft+"{"+Z(ut,Y)+"}":ft+"{ "+_.call(ut,", ")+" }"}return String(e)};var Y=Object.prototype.hasOwnProperty||function(t){return t in this};function H(t,e){return Y.call(t,e)}function $(t){return d.call(t)}function j(t,e){if(t.indexOf)return t.indexOf(e);for(var i=0,r=t.length;i<r;i++)if(t[i]===e)return i;return-1}function z(t,e){if(t.length>e.maxStringLength){var i=t.length-e.maxStringLength,r="... "+i+" more character"+(i>1?"s":"");return z(m.call(t,0,e.maxStringLength),e)+r}var s=B[e.quoteStyle||"single"];return s.lastIndex=0,F(g.call(g.call(t,s,"\\$1"),/[\x00-\x1f]/g,V),"single",e)}function V(t){var e=t.charCodeAt(0),i={8:"b",9:"t",10:"n",12:"f",13:"r"}[e];return i?"\\"+i:"\\x"+(e<16?"0":"")+y.call(e.toString(16))}function q(t){return"Object("+t+")"}function J(t){return t+" { ? }"}function K(t,e,i,r){return t+" ("+e+") {"+(r?Z(i,r):_.call(i,", "))+"}"}function Z(t,e){if(0===t.length)return"";var i="\n"+e.prev+e.base;return i+_.call(t,","+i)+"\n"+e.prev}function Q(t,e){var i=G(t),r=[];if(i){r.length=t.length;for(var s=0;s<t.length;s++)r[s]=H(t,s)?e(t[s],t):""}var n,o="function"==typeof T?T(t):[];if(I){n={};for(var a=0;a<o.length;a++)n["$"+o[a]]=o[a]}for(var l in t)H(t,l)&&(i&&String(Number(l))===l&&l<t.length||I&&n["$"+l]instanceof Symbol||(x.call(/[^\w$]/,l)?r.push(e(l,t)+": "+e(t[l],t)):r.push(l+": "+e(t[l],t))));if("function"==typeof T)for(var h=0;h<o.length;h++)C.call(t,o[h])&&r.push("["+e(o[h])+"]: "+e(t[o[h]],t));return r}return Hh}function Ac(){if(zh)return jh;zh=1;var t=/* @__PURE__ */Tc(),e=/* @__PURE__ */Wh(),i=function(t,e,i){for(var r,s=t;null!=(r=s.next);s=r)if(r.key===e)return s.next=r.next,i||(r.next=t.next,t.next=r),r};return jh=function(){var r,s={assert:function(i){if(!s.has(i))throw new e("Side channel does not contain "+t(i))},delete:function(t){var e=r&&r.next,s=function(t,e){if(t)return i(t,e,!0)}(r,t);return s&&e&&e===s&&(r=void 0),!!s},get:function(t){return function(t,e){if(t){var r=i(t,e);return r&&r.value}}(r,t)},has:function(t){return function(t,e){return!!t&&!!i(t,e)}(r,t)},set:function(t,e){r||(r={next:void 0}),function(t,e,r){var s=i(t,e);s?s.value=r:t.next={key:e,next:t.next,value:r}}(r,t,e)}};return s}}function Ic(){return qh?Vh:(qh=1,Vh=Object)}function Sc(){return Kh?Jh:(Kh=1,Jh=Error)}function Cc(){return Qh?Zh:(Qh=1,Zh=EvalError)}function Mc(){return eu?tu:(eu=1,tu=RangeError)}function Oc(){return ru?iu:(ru=1,iu=ReferenceError)}function Nc(){return nu?su:(nu=1,su=SyntaxError)}function Lc(){return au?ou:(au=1,ou=URIError)}function Rc(){return hu?lu:(hu=1,lu=Math.abs)}function kc(){return cu?uu:(cu=1,uu=Math.floor)}function Bc(){return pu?du:(pu=1,du=Math.max)}function Fc(){return mu?fu:(mu=1,fu=Math.min)}function Dc(){return yu?gu:(yu=1,gu=Math.pow)}function Uc(){return xu?vu:(xu=1,vu=Math.round)}function Gc(){return _u?bu:(_u=1,bu=Number.isNaN||function(t){return t!=t})}function Xc(){if(Pu)return wu;Pu=1;var t=/* @__PURE__ */Gc();return wu=function(e){return t(e)||0===e?e:e<0?-1:1}}function Wc(){return Tu?Eu:(Tu=1,Eu=Object.getOwnPropertyDescriptor)}function Yc(){if(Iu)return Au;Iu=1;var t=/* @__PURE__ */Wc();if(t)try{t([],"length")}catch(e){t=null}return Au=t}function Hc(){if(Cu)return Su;Cu=1;var t=Object.defineProperty||!1;if(t)try{t({},"a",{value:1})}catch(e){t=!1}return Su=t}function $c(){if(Lu)return Nu;Lu=1;var t="undefined"!=typeof Symbol&&Symbol,e=Ou?Mu:(Ou=1,Mu=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var t={},e=/* @__PURE__ */Symbol("test"),i=Object(e);if("string"==typeof e)return!1;if("[object Symbol]"!==Object.prototype.toString.call(e))return!1;if("[object Symbol]"!==Object.prototype.toString.call(i))return!1;for(var r in t[e]=42,t)return!1;if("function"==typeof Object.keys&&0!==Object.keys(t).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(t).length)return!1;var s=Object.getOwnPropertySymbols(t);if(1!==s.length||s[0]!==e)return!1;if(!Object.prototype.propertyIsEnumerable.call(t,e))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var n=Object.getOwnPropertyDescriptor(t,e);if(42!==n.value||!0!==n.enumerable)return!1}return!0});return Nu=function(){return"function"==typeof t&&("function"==typeof Symbol&&("symbol"==typeof t("foo")&&("symbol"==typeof/* @__PURE__ */Symbol("bar")&&e())))}}function jc(){return ku?Ru:(ku=1,Ru="undefined"!=typeof Reflect&&Reflect.getPrototypeOf||null)}function zc(){return Fu?Bu:(Fu=1,Bu=/* @__PURE__ */Ic().getPrototypeOf||null)}function Vc(){if(Xu)return Gu;Xu=1;var t=function(){if(Uu)return Du;Uu=1;var t=Object.prototype.toString,e=Math.max,i=function(t,e){for(var i=[],r=0;r<t.length;r+=1)i[r]=t[r];for(var s=0;s<e.length;s+=1)i[s+t.length]=e[s];return i};return Du=function(r){var s=this;if("function"!=typeof s||"[object Function]"!==t.apply(s))throw new TypeError("Function.prototype.bind called on incompatible "+s);for(var n,o=function(t){for(var e=[],i=1,r=0;i<t.length;i+=1,r+=1)e[r]=t[i];return e}(arguments),a=e(0,s.length-o.length),l=[],h=0;h<a;h++)l[h]="$"+h;if(n=Function("binder","return function ("+function(t,e){for(var i="",r=0;r<t.length;r+=1)i+=t[r],r+1<t.length&&(i+=e);return i}(l,",")+"){ return binder.apply(this,arguments); }")(function(){if(this instanceof n){var t=s.apply(this,i(o,arguments));return Object(t)===t?t:this}return s.apply(r,i(o,arguments))}),s.prototype){var u=function(){};u.prototype=s.prototype,n.prototype=new u,u.prototype=null}return n},Du}();return Gu=Function.prototype.bind||t}function qc(){return Yu?Wu:(Yu=1,Wu=Function.prototype.call)}function Jc(){return $u?Hu:($u=1,Hu=Function.prototype.apply)}function Kc(){if(qu)return Vu;qu=1;var t=Vc(),e=Jc(),i=qc(),r=zu?ju:(zu=1,ju="undefined"!=typeof Reflect&&Reflect&&Reflect.apply);return Vu=r||t.call(i,e)}function Zc(){if(Ku)return Ju;Ku=1;var t=Vc(),e=/* @__PURE__ */Wh(),i=qc(),r=Kc();return Ju=function(s){if(s.length<1||"function"!=typeof s[0])throw new e("a function is required");return r(t,i,s)}}function Qc(){if(Qu)return Zu;Qu=1;var t,e=Zc(),i=/* @__PURE__ */Yc();try{t=[].__proto__===Array.prototype}catch(o){if(!o||"object"!=typeof o||!("code"in o)||"ERR_PROTO_ACCESS"!==o.code)throw o}var r=!!t&&i&&i(Object.prototype,"__proto__"),s=Object,n=s.getPrototypeOf;return Zu=r&&"function"==typeof r.get?e([r.get]):"function"==typeof n&&function(t){return n(null==t?t:s(t))}}function td(){if(rc)return ic;rc=1;var t=Function.prototype.call,e=Object.prototype.hasOwnProperty,i=Vc();return ic=i.call(t,e)}function ed(){if(nc)return sc;var t;nc=1;var e=/* @__PURE__ */Ic(),i=/* @__PURE__ */Sc(),r=/* @__PURE__ */Cc(),s=/* @__PURE__ */Mc(),n=/* @__PURE__ */Oc(),o=/* @__PURE__ */Nc(),a=/* @__PURE__ */Wh(),l=/* @__PURE__ */Lc(),h=/* @__PURE__ */Rc(),u=/* @__PURE__ */kc(),c=/* @__PURE__ */Bc(),d=/* @__PURE__ */Fc(),p=/* @__PURE__ */Dc(),f=/* @__PURE__ */Uc(),m=/* @__PURE__ */Xc(),g=Function,y=function(t){try{return g('"use strict"; return ('+t+").constructor;")()}catch(e){}},v=/* @__PURE__ */Yc(),x=/* @__PURE__ */Hc(),b=function(){throw new a},_=v?function(){try{return b}catch(t){try{return v(arguments,"callee").get}catch(e){return b}}}():b,w=$c()(),P=function(){if(ec)return tc;ec=1;var t=jc(),e=zc(),i=/* @__PURE__ */Qc();return tc=t?function(e){return t(e)}:e?function(t){if(!t||"object"!=typeof t&&"function"!=typeof t)throw new TypeError("getProto: not an object");return e(t)}:i?function(t){return i(t)}:null}(),E=zc(),T=jc(),A=Jc(),I=qc(),S={},C="undefined"!=typeof Uint8Array&&P?P(Uint8Array):t,M={__proto__:null,"%AggregateError%":"undefined"==typeof AggregateError?t:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?t:ArrayBuffer,"%ArrayIteratorPrototype%":w&&P?P([][Symbol.iterator]()):t,"%AsyncFromSyncIteratorPrototype%":t,"%AsyncFunction%":S,"%AsyncGenerator%":S,"%AsyncGeneratorFunction%":S,"%AsyncIteratorPrototype%":S,"%Atomics%":"undefined"==typeof Atomics?t:Atomics,"%BigInt%":"undefined"==typeof BigInt?t:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?t:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?t:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?t:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":i,"%eval%":eval,"%EvalError%":r,"%Float16Array%":"undefined"==typeof Float16Array?t:Float16Array,"%Float32Array%":"undefined"==typeof Float32Array?t:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?t:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?t:FinalizationRegistry,"%Function%":g,"%GeneratorFunction%":S,"%Int8Array%":"undefined"==typeof Int8Array?t:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?t:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?t:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":w&&P?P(P([][Symbol.iterator]())):t,"%JSON%":"object"==typeof JSON?JSON:t,"%Map%":"undefined"==typeof Map?t:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&w&&P?P(/* @__PURE__ */(new Map)[Symbol.iterator]()):t,"%Math%":Math,"%Number%":Number,"%Object%":e,"%Object.getOwnPropertyDescriptor%":v,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?t:Promise,"%Proxy%":"undefined"==typeof Proxy?t:Proxy,"%RangeError%":s,"%ReferenceError%":n,"%Reflect%":"undefined"==typeof Reflect?t:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?t:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&w&&P?P(/* @__PURE__ */(new Set)[Symbol.iterator]()):t,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?t:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":w&&P?P(""[Symbol.iterator]()):t,"%Symbol%":w?Symbol:t,"%SyntaxError%":o,"%ThrowTypeError%":_,"%TypedArray%":C,"%TypeError%":a,"%Uint8Array%":"undefined"==typeof Uint8Array?t:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?t:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?t:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?t:Uint32Array,"%URIError%":l,"%WeakMap%":"undefined"==typeof WeakMap?t:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?t:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?t:WeakSet,"%Function.prototype.call%":I,"%Function.prototype.apply%":A,"%Object.defineProperty%":x,"%Object.getPrototypeOf%":E,"%Math.abs%":h,"%Math.floor%":u,"%Math.max%":c,"%Math.min%":d,"%Math.pow%":p,"%Math.round%":f,"%Math.sign%":m,"%Reflect.getPrototypeOf%":T};if(P)try{null.error}catch(H){var O=P(P(H));M["%Error.prototype%"]=O}var N=function t(e){var i;if("%AsyncFunction%"===e)i=y("async function () {}");else if("%GeneratorFunction%"===e)i=y("function* () {}");else if("%AsyncGeneratorFunction%"===e)i=y("async function* () {}");else if("%AsyncGenerator%"===e){var r=t("%AsyncGeneratorFunction%");r&&(i=r.prototype)}else if("%AsyncIteratorPrototype%"===e){var s=t("%AsyncGenerator%");s&&P&&(i=P(s.prototype))}return M[e]=i,i},L={__proto__:null,"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},R=Vc(),k=/* @__PURE__ */td(),B=R.call(I,Array.prototype.concat),F=R.call(A,Array.prototype.splice),D=R.call(I,String.prototype.replace),U=R.call(I,String.prototype.slice),G=R.call(I,RegExp.prototype.exec),X=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,W=/\\(\\)?/g,Y=function(t,e){var i,r=t;if(k(L,r)&&(r="%"+(i=L[r])[0]+"%"),k(M,r)){var s=M[r];if(s===S&&(s=N(r)),void 0===s&&!e)throw new a("intrinsic "+t+" exists, but is not available. Please file an issue!");return{alias:i,name:r,value:s}}throw new o("intrinsic "+t+" does not exist!")};return sc=function(t,e){if("string"!=typeof t||0===t.length)throw new a("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof e)throw new a('"allowMissing" argument must be a boolean');if(null===G(/^%?[^%]*%?$/,t))throw new o("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var i=function(t){var e=U(t,0,1),i=U(t,-1);if("%"===e&&"%"!==i)throw new o("invalid intrinsic syntax, expected closing `%`");if("%"===i&&"%"!==e)throw new o("invalid intrinsic syntax, expected opening `%`");var r=[];return D(t,X,function(t,e,i,s){r[r.length]=i?D(s,W,"$1"):e||t}),r}(t),r=i.length>0?i[0]:"",s=Y("%"+r+"%",e),n=s.name,l=s.value,h=!1,u=s.alias;u&&(r=u[0],F(i,B([0,1],u)));for(var c=1,d=!0;c<i.length;c+=1){var p=i[c],f=U(p,0,1),m=U(p,-1);if(('"'===f||"'"===f||"`"===f||'"'===m||"'"===m||"`"===m)&&f!==m)throw new o("property names with quotes must have matching quotes");if("constructor"!==p&&d||(h=!0),k(M,n="%"+(r+="."+p)+"%"))l=M[n];else if(null!=l){if(!(p in l)){if(!e)throw new a("base intrinsic for "+t+" exists, but the property is not available.");return}if(v&&c+1>=i.length){var g=v(l,p);l=(d=!!g)&&"get"in g&&!("originalValue"in g.get)?g.get:l[p]}else d=k(l,p),l=l[p];d&&!h&&(M[n]=l)}}return l},sc}function id(){if(ac)return oc;ac=1;var t=/* @__PURE__ */ed(),e=Zc(),i=e([t("%String.prototype.indexOf%")]);return oc=function(r,s){var n=t(r,!!s);return"function"==typeof n&&i(r,".prototype.")>-1?e([n]):n}}function rd(){if(hc)return lc;hc=1;var t=/* @__PURE__ */ed(),e=/* @__PURE__ */id(),i=/* @__PURE__ */Tc(),r=/* @__PURE__ */Wh(),s=t("%Map%",!0),n=e("Map.prototype.get",!0),o=e("Map.prototype.set",!0),a=e("Map.prototype.has",!0),l=e("Map.prototype.delete",!0),h=e("Map.prototype.size",!0);return lc=!!s&&function(){var t,e={assert:function(t){if(!e.has(t))throw new r("Side channel does not contain "+i(t))},delete:function(e){if(t){var i=l(t,e);return 0===h(t)&&(t=void 0),i}return!1},get:function(e){if(t)return n(t,e)},has:function(e){return!!t&&a(t,e)},set:function(e,i){t||(t=new s),o(t,e,i)}};return e}}function sd(){if(pc)return dc;pc=1;var t=/* @__PURE__ */Wh(),e=/* @__PURE__ */Tc(),i=Ac(),r=rd(),s=function(){if(cc)return uc;cc=1;var t=/* @__PURE__ */ed(),e=/* @__PURE__ */id(),i=/* @__PURE__ */Tc(),r=rd(),s=/* @__PURE__ */Wh(),n=t("%WeakMap%",!0),o=e("WeakMap.prototype.get",!0),a=e("WeakMap.prototype.set",!0),l=e("WeakMap.prototype.has",!0),h=e("WeakMap.prototype.delete",!0);return uc=n?function(){var t,e,u={assert:function(t){if(!u.has(t))throw new s("Side channel does not contain "+i(t))},delete:function(i){if(n&&i&&("object"==typeof i||"function"==typeof i)){if(t)return h(t,i)}else if(r&&e)return e.delete(i);return!1},get:function(i){return n&&i&&("object"==typeof i||"function"==typeof i)&&t?o(t,i):e&&e.get(i)},has:function(i){return n&&i&&("object"==typeof i||"function"==typeof i)&&t?l(t,i):!!e&&e.has(i)},set:function(i,s){n&&i&&("object"==typeof i||"function"==typeof i)?(t||(t=new n),a(t,i,s)):r&&(e||(e=r()),e.set(i,s))}};return u}:r}(),n=s||r||i;return dc=function(){var i,r={assert:function(i){if(!r.has(i))throw new t("Side channel does not contain "+e(i))},delete:function(t){return!!i&&i.delete(t)},get:function(t){return i&&i.get(t)},has:function(t){return!!i&&i.has(t)},set:function(t,e){i||(i=n()),i.set(t,e)}};return r}}function nd(){if(mc)return fc;mc=1;var t=String.prototype.replace,e=/%20/g,i="RFC3986";return fc={default:i,formatters:{RFC1738:function(i){return t.call(i,e,"+")},RFC3986:function(t){return String(t)}},RFC1738:"RFC1738",RFC3986:i}}function od(){if(yc)return gc;yc=1;var t=/* @__PURE__ */nd(),e=Object.prototype.hasOwnProperty,i=Array.isArray,r=function(){for(var t=[],e=0;e<256;++e)t.push("%"+((e<16?"0":"")+e.toString(16)).toUpperCase());return t}(),s=function(t,e){for(var i=e&&e.plainObjects?{__proto__:null}:{},r=0;r<t.length;++r)void 0!==t[r]&&(i[r]=t[r]);return i},n=1024;return gc={arrayToObject:s,assign:function(t,e){return Object.keys(e).reduce(function(t,i){return t[i]=e[i],t},t)},combine:function(t,e){return[].concat(t,e)},compact:function(t){for(var e=[{obj:{o:t},prop:"o"}],r=[],s=0;s<e.length;++s)for(var n=e[s],o=n.obj[n.prop],a=Object.keys(o),l=0;l<a.length;++l){var h=a[l],u=o[h];"object"==typeof u&&null!==u&&-1===r.indexOf(u)&&(e.push({obj:o,prop:h}),r.push(u))}return function(t){for(;t.length>1;){var e=t.pop(),r=e.obj[e.prop];if(i(r)){for(var s=[],n=0;n<r.length;++n)void 0!==r[n]&&s.push(r[n]);e.obj[e.prop]=s}}}(e),t},decode:function(t,e,i){var r=t.replace(/\+/g," ");if("iso-8859-1"===i)return r.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(r)}catch(s){return r}},encode:function(e,i,s,o,a){if(0===e.length)return e;var l=e;if("symbol"==typeof e?l=Symbol.prototype.toString.call(e):"string"!=typeof e&&(l=String(e)),"iso-8859-1"===s)return escape(l).replace(/%u[0-9a-f]{4}/gi,function(t){return"%26%23"+parseInt(t.slice(2),16)+"%3B"});for(var h="",u=0;u<l.length;u+=n){for(var c=l.length>=n?l.slice(u,u+n):l,d=[],p=0;p<c.length;++p){var f=c.charCodeAt(p);45===f||46===f||95===f||126===f||f>=48&&f<=57||f>=65&&f<=90||f>=97&&f<=122||a===t.RFC1738&&(40===f||41===f)?d[d.length]=c.charAt(p):f<128?d[d.length]=r[f]:f<2048?d[d.length]=r[192|f>>6]+r[128|63&f]:f<55296||f>=57344?d[d.length]=r[224|f>>12]+r[128|f>>6&63]+r[128|63&f]:(p+=1,f=65536+((1023&f)<<10|1023&c.charCodeAt(p)),d[d.length]=r[240|f>>18]+r[128|f>>12&63]+r[128|f>>6&63]+r[128|63&f])}h+=d.join("")}return h},isBuffer:function(t){return!(!t||"object"!=typeof t)&&!!(t.constructor&&t.constructor.isBuffer&&t.constructor.isBuffer(t))},isRegExp:function(t){return"[object RegExp]"===Object.prototype.toString.call(t)},maybeMap:function(t,e){if(i(t)){for(var r=[],s=0;s<t.length;s+=1)r.push(e(t[s]));return r}return e(t)},merge:function t(r,n,o){if(!n)return r;if("object"!=typeof n&&"function"!=typeof n){if(i(r))r.push(n);else{if(!r||"object"!=typeof r)return[r,n];(o&&(o.plainObjects||o.allowPrototypes)||!e.call(Object.prototype,n))&&(r[n]=!0)}return r}if(!r||"object"!=typeof r)return[r].concat(n);var a=r;return i(r)&&!i(n)&&(a=s(r,o)),i(r)&&i(n)?(n.forEach(function(i,s){if(e.call(r,s)){var n=r[s];n&&"object"==typeof n&&i&&"object"==typeof i?r[s]=t(n,i,o):r.push(i)}else r[s]=i}),r):Object.keys(n).reduce(function(i,r){var s=n[r];return e.call(i,r)?i[r]=t(i[r],s,o):i[r]=s,i},a)}},gc}function ad(){if(xc)return vc;xc=1;var t=sd(),e=/* @__PURE__ */od(),i=/* @__PURE__ */nd(),r=Object.prototype.hasOwnProperty,s={brackets:function(t){return t+"[]"},comma:"comma",indices:function(t,e){return t+"["+e+"]"},repeat:function(t){return t}},n=Array.isArray,o=Array.prototype.push,a=function(t,e){o.apply(t,n(e)?e:[e])},l=Date.prototype.toISOString,h=i.default,u={addQueryPrefix:!1,allowDots:!1,allowEmptyArrays:!1,arrayFormat:"indices",charset:"utf-8",charsetSentinel:!1,commaRoundTrip:!1,delimiter:"&",encode:!0,encodeDotInKeys:!1,encoder:e.encode,encodeValuesOnly:!1,filter:void 0,format:h,formatter:i.formatters[h],indices:!1,serializeDate:function(t){return l.call(t)},skipNulls:!1,strictNullHandling:!1},c={},d=function i(r,s,o,l,h,d,p,f,m,g,y,v,x,b,_,w,P,E){for(var T,A=r,I=E,S=0,C=!1;void 0!==(I=I.get(c))&&!C;){var M=I.get(r);if(S+=1,void 0!==M){if(M===S)throw new RangeError("Cyclic object value");C=!0}void 0===I.get(c)&&(S=0)}if("function"==typeof g?A=g(s,A):A instanceof Date?A=x(A):"comma"===o&&n(A)&&(A=e.maybeMap(A,function(t){return t instanceof Date?x(t):t})),null===A){if(d)return m&&!w?m(s,u.encoder,P,"key",b):s;A=""}if("string"==typeof(T=A)||"number"==typeof T||"boolean"==typeof T||"symbol"==typeof T||"bigint"==typeof T||e.isBuffer(A))return m?[_(w?s:m(s,u.encoder,P,"key",b))+"="+_(m(A,u.encoder,P,"value",b))]:[_(s)+"="+_(String(A))];var O,N=[];if(void 0===A)return N;if("comma"===o&&n(A))w&&m&&(A=e.maybeMap(A,m)),O=[{value:A.length>0?A.join(",")||null:void 0}];else if(n(g))O=g;else{var L=Object.keys(A);O=y?L.sort(y):L}var R=f?String(s).replace(/\./g,"%2E"):String(s),k=l&&n(A)&&1===A.length?R+"[]":R;if(h&&n(A)&&0===A.length)return k+"[]";for(var B=0;B<O.length;++B){var F=O[B],D="object"==typeof F&&F&&void 0!==F.value?F.value:A[F];if(!p||null!==D){var U=v&&f?String(F).replace(/\./g,"%2E"):String(F),G=n(A)?"function"==typeof o?o(k,U):k:k+(v?"."+U:"["+U+"]");E.set(r,S);var X=t();X.set(c,E),a(N,i(D,G,o,l,h,d,p,f,"comma"===o&&w&&n(A)?null:m,g,y,v,x,b,_,w,P,X))}}return N};return vc=function(e,o){var l,h=e,c=function(t){if(!t)return u;if(void 0!==t.allowEmptyArrays&&"boolean"!=typeof t.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==t.encodeDotInKeys&&"boolean"!=typeof t.encodeDotInKeys)throw new TypeError("`encodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==t.encoder&&void 0!==t.encoder&&"function"!=typeof t.encoder)throw new TypeError("Encoder has to be a function.");var e=t.charset||u.charset;if(void 0!==t.charset&&"utf-8"!==t.charset&&"iso-8859-1"!==t.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var o=i.default;if(void 0!==t.format){if(!r.call(i.formatters,t.format))throw new TypeError("Unknown format option provided.");o=t.format}var a,l=i.formatters[o],h=u.filter;if(("function"==typeof t.filter||n(t.filter))&&(h=t.filter),a=t.arrayFormat in s?t.arrayFormat:"indices"in t?t.indices?"indices":"repeat":u.arrayFormat,"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var c=void 0===t.allowDots?!0===t.encodeDotInKeys||u.allowDots:!!t.allowDots;return{addQueryPrefix:"boolean"==typeof t.addQueryPrefix?t.addQueryPrefix:u.addQueryPrefix,allowDots:c,allowEmptyArrays:"boolean"==typeof t.allowEmptyArrays?!!t.allowEmptyArrays:u.allowEmptyArrays,arrayFormat:a,charset:e,charsetSentinel:"boolean"==typeof t.charsetSentinel?t.charsetSentinel:u.charsetSentinel,commaRoundTrip:!!t.commaRoundTrip,delimiter:void 0===t.delimiter?u.delimiter:t.delimiter,encode:"boolean"==typeof t.encode?t.encode:u.encode,encodeDotInKeys:"boolean"==typeof t.encodeDotInKeys?t.encodeDotInKeys:u.encodeDotInKeys,encoder:"function"==typeof t.encoder?t.encoder:u.encoder,encodeValuesOnly:"boolean"==typeof t.encodeValuesOnly?t.encodeValuesOnly:u.encodeValuesOnly,filter:h,format:o,formatter:l,serializeDate:"function"==typeof t.serializeDate?t.serializeDate:u.serializeDate,skipNulls:"boolean"==typeof t.skipNulls?t.skipNulls:u.skipNulls,sort:"function"==typeof t.sort?t.sort:null,strictNullHandling:"boolean"==typeof t.strictNullHandling?t.strictNullHandling:u.strictNullHandling}}(o);"function"==typeof c.filter?h=(0,c.filter)("",h):n(c.filter)&&(l=c.filter);var p=[];if("object"!=typeof h||null===h)return"";var f=s[c.arrayFormat],m="comma"===f&&c.commaRoundTrip;l||(l=Object.keys(h)),c.sort&&l.sort(c.sort);for(var g=t(),y=0;y<l.length;++y){var v=l[y],x=h[v];c.skipNulls&&null===x||a(p,d(x,v,f,m,c.allowEmptyArrays,c.strictNullHandling,c.skipNulls,c.encodeDotInKeys,c.encode?c.encoder:null,c.filter,c.sort,c.allowDots,c.serializeDate,c.format,c.formatter,c.encodeValuesOnly,c.charset,g))}var b=p.join(c.delimiter),_=!0===c.addQueryPrefix?"?":"";return c.charsetSentinel&&("iso-8859-1"===c.charset?_+="utf8=%26%2310003%3B&":_+="utf8=%E2%9C%93&"),b.length>0?_+b:""}}function ld(){if(_c)return bc;_c=1;var t=/* @__PURE__ */od(),e=Object.prototype.hasOwnProperty,i=Array.isArray,r={allowDots:!1,allowEmptyArrays:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decodeDotInKeys:!1,decoder:t.decode,delimiter:"&",depth:5,duplicates:"combine",ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictDepth:!1,strictNullHandling:!1,throwOnLimitExceeded:!1},s=function(t){return t.replace(/&#(\d+);/g,function(t,e){return String.fromCharCode(parseInt(e,10))})},n=function(t,e,i){if(t&&"string"==typeof t&&e.comma&&t.indexOf(",")>-1)return t.split(",");if(e.throwOnLimitExceeded&&i>=e.arrayLimit)throw new RangeError("Array limit exceeded. Only "+e.arrayLimit+" element"+(1===e.arrayLimit?"":"s")+" allowed in an array.");return t},o=function(i,r,s,o){if(i){var a=s.allowDots?i.replace(/\.([^.[]+)/g,"[$1]"):i,l=/(\[[^[\]]*])/g,h=s.depth>0&&/(\[[^[\]]*])/.exec(a),u=h?a.slice(0,h.index):a,c=[];if(u){if(!s.plainObjects&&e.call(Object.prototype,u)&&!s.allowPrototypes)return;c.push(u)}for(var d=0;s.depth>0&&null!==(h=l.exec(a))&&d<s.depth;){if(d+=1,!s.plainObjects&&e.call(Object.prototype,h[1].slice(1,-1))&&!s.allowPrototypes)return;c.push(h[1])}if(h){if(!0===s.strictDepth)throw new RangeError("Input depth exceeded depth option of "+s.depth+" and strictDepth is true");c.push("["+a.slice(h.index)+"]")}return function(e,i,r,s){var o=0;if(e.length>0&&"[]"===e[e.length-1]){var a=e.slice(0,-1).join("");o=Array.isArray(i)&&i[a]?i[a].length:0}for(var l=s?i:n(i,r,o),h=e.length-1;h>=0;--h){var u,c=e[h];if("[]"===c&&r.parseArrays)u=r.allowEmptyArrays&&(""===l||r.strictNullHandling&&null===l)?[]:t.combine([],l);else{u=r.plainObjects?{__proto__:null}:{};var d="["===c.charAt(0)&&"]"===c.charAt(c.length-1)?c.slice(1,-1):c,p=r.decodeDotInKeys?d.replace(/%2E/g,"."):d,f=parseInt(p,10);r.parseArrays||""!==p?!isNaN(f)&&c!==p&&String(f)===p&&f>=0&&r.parseArrays&&f<=r.arrayLimit?(u=[])[f]=l:"__proto__"!==p&&(u[p]=l):u={0:l}}l=u}return l}(c,r,s,o)}};return bc=function(a,l){var h=function(e){if(!e)return r;if(void 0!==e.allowEmptyArrays&&"boolean"!=typeof e.allowEmptyArrays)throw new TypeError("`allowEmptyArrays` option can only be `true` or `false`, when provided");if(void 0!==e.decodeDotInKeys&&"boolean"!=typeof e.decodeDotInKeys)throw new TypeError("`decodeDotInKeys` option can only be `true` or `false`, when provided");if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");if(void 0!==e.throwOnLimitExceeded&&"boolean"!=typeof e.throwOnLimitExceeded)throw new TypeError("`throwOnLimitExceeded` option must be a boolean");var i=void 0===e.charset?r.charset:e.charset,s=void 0===e.duplicates?r.duplicates:e.duplicates;if("combine"!==s&&"first"!==s&&"last"!==s)throw new TypeError("The duplicates option must be either combine, first, or last");return{allowDots:void 0===e.allowDots?!0===e.decodeDotInKeys||r.allowDots:!!e.allowDots,allowEmptyArrays:"boolean"==typeof e.allowEmptyArrays?!!e.allowEmptyArrays:r.allowEmptyArrays,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:r.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:r.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:r.arrayLimit,charset:i,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:r.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:r.comma,decodeDotInKeys:"boolean"==typeof e.decodeDotInKeys?e.decodeDotInKeys:r.decodeDotInKeys,decoder:"function"==typeof e.decoder?e.decoder:r.decoder,delimiter:"string"==typeof e.delimiter||t.isRegExp(e.delimiter)?e.delimiter:r.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:r.depth,duplicates:s,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:r.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:r.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:r.plainObjects,strictDepth:"boolean"==typeof e.strictDepth?!!e.strictDepth:r.strictDepth,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:r.strictNullHandling,throwOnLimitExceeded:"boolean"==typeof e.throwOnLimitExceeded&&e.throwOnLimitExceeded}}(l);if(""===a||null==a)return h.plainObjects?{__proto__:null}:{};for(var u="string"==typeof a?function(o,a){var l={__proto__:null},h=a.ignoreQueryPrefix?o.replace(/^\?/,""):o;h=h.replace(/%5B/gi,"[").replace(/%5D/gi,"]");var u=a.parameterLimit===1/0?void 0:a.parameterLimit,c=h.split(a.delimiter,a.throwOnLimitExceeded?u+1:u);if(a.throwOnLimitExceeded&&c.length>u)throw new RangeError("Parameter limit exceeded. Only "+u+" parameter"+(1===u?"":"s")+" allowed.");var d,p=-1,f=a.charset;if(a.charsetSentinel)for(d=0;d<c.length;++d)0===c[d].indexOf("utf8=")&&("utf8=%E2%9C%93"===c[d]?f="utf-8":"utf8=%26%2310003%3B"===c[d]&&(f="iso-8859-1"),p=d,d=c.length);for(d=0;d<c.length;++d)if(d!==p){var m,g,y=c[d],v=y.indexOf("]="),x=-1===v?y.indexOf("="):v+1;-1===x?(m=a.decoder(y,r.decoder,f,"key"),g=a.strictNullHandling?null:""):(m=a.decoder(y.slice(0,x),r.decoder,f,"key"),g=t.maybeMap(n(y.slice(x+1),a,i(l[m])?l[m].length:0),function(t){return a.decoder(t,r.decoder,f,"value")})),g&&a.interpretNumericEntities&&"iso-8859-1"===f&&(g=s(String(g))),y.indexOf("[]=")>-1&&(g=i(g)?[g]:g);var b=e.call(l,m);b&&"combine"===a.duplicates?l[m]=t.combine(l[m],g):b&&"last"!==a.duplicates||(l[m]=g)}return l}(a,h):a,c=h.plainObjects?{__proto__:null}:{},d=Object.keys(u),p=0;p<d.length;++p){var f=d[p],m=o(f,u[f],h,"string"==typeof a);c=t.merge(c,m,h)}return!0===h.allowSparse?c:t.compact(c)}}function hd(){if(Pc)return wc;Pc=1;var t=/* @__PURE__ */ad(),e=/* @__PURE__ */ld();return wc={formats:/* @__PURE__ */nd(),parse:e,stringify:t}}var ud=function(){if(Ec)return Uh;Ec=1;var t=(Bh||(Bh=1,function(t,e){!function(i){var r=e&&!e.nodeType&&e,s=t&&!t.nodeType&&t,n="object"==typeof At&&At;n.global!==n&&n.window!==n&&n.self!==n||(i=n);var o,a,l=2147483647,h=36,u=/^xn--/,c=/[^\x20-\x7E]/,d=/[\x2E\u3002\uFF0E\uFF61]/g,p={overflow:"Overflow: input needs wider integers to process","not-basic":"Illegal input >= 0x80 (not a basic code point)","invalid-input":"Invalid input"},f=Math.floor,m=String.fromCharCode;function g(t){throw new RangeError(p[t])}function y(t,e){for(var i=t.length,r=[];i--;)r[i]=e(t[i]);return r}function v(t,e){var i=t.split("@"),r="";return i.length>1&&(r=i[0]+"@",t=i[1]),r+y((t=t.replace(d,".")).split("."),e).join(".")}function x(t){for(var e,i,r=[],s=0,n=t.length;s<n;)(e=t.charCodeAt(s++))>=55296&&e<=56319&&s<n?56320==(64512&(i=t.charCodeAt(s++)))?r.push(((1023&e)<<10)+(1023&i)+65536):(r.push(e),s--):r.push(e);return r}function b(t){return y(t,function(t){var e="";return t>65535&&(e+=m((t-=65536)>>>10&1023|55296),t=56320|1023&t),e+m(t)}).join("")}function _(t){return t-48<10?t-22:t-65<26?t-65:t-97<26?t-97:h}function w(t,e){return t+22+75*(t<26)-((0!=e)<<5)}function P(t,e,i){var r=0;for(t=i?f(t/700):t>>1,t+=f(t/e);t>455;r+=h)t=f(t/35);return f(r+36*t/(t+38))}function E(t){var e,i,r,s,n,o,a,u,c,d,p=[],m=t.length,y=0,v=128,x=72;for((i=t.lastIndexOf("-"))<0&&(i=0),r=0;r<i;++r)t.charCodeAt(r)>=128&&g("not-basic"),p.push(t.charCodeAt(r));for(s=i>0?i+1:0;s<m;){for(n=y,o=1,a=h;s>=m&&g("invalid-input"),((u=_(t.charCodeAt(s++)))>=h||u>f((l-y)/o))&&g("overflow"),y+=u*o,!(u<(c=a<=x?1:a>=x+26?26:a-x));a+=h)o>f(l/(d=h-c))&&g("overflow"),o*=d;x=P(y-n,e=p.length+1,0==n),f(y/e)>l-v&&g("overflow"),v+=f(y/e),y%=e,p.splice(y++,0,v)}return b(p)}function T(t){var e,i,r,s,n,o,a,u,c,d,p,y,v,b,_,E=[];for(y=(t=x(t)).length,e=128,i=0,n=72,o=0;o<y;++o)(p=t[o])<128&&E.push(m(p));for(r=s=E.length,s&&E.push("-");r<y;){for(a=l,o=0;o<y;++o)(p=t[o])>=e&&p<a&&(a=p);for(a-e>f((l-i)/(v=r+1))&&g("overflow"),i+=(a-e)*v,e=a,o=0;o<y;++o)if((p=t[o])<e&&++i>l&&g("overflow"),p==e){for(u=i,c=h;!(u<(d=c<=n?1:c>=n+26?26:c-n));c+=h)_=u-d,b=h-d,E.push(m(w(d+_%b,0))),u=f(_/b);E.push(m(w(u,0))),n=P(i,v,r==s),i=0,++r}++i,++e}return E.join("")}if(o={version:"1.4.1",ucs2:{decode:x,encode:b},decode:E,encode:T,toASCII:function(t){return v(t,function(t){return c.test(t)?"xn--"+T(t):t})},toUnicode:function(t){return v(t,function(t){return u.test(t)?E(t.slice(4).toLowerCase()):t})}},r&&s)if(t.exports==r)s.exports=o;else for(a in o)o.hasOwnProperty(a)&&(r[a]=o[a]);else i.punycode=o}(Xh)}(Gh,Gh.exports)),Gh.exports);function e(){this.protocol=null,this.slashes=null,this.auth=null,this.host=null,this.port=null,this.hostname=null,this.hash=null,this.search=null,this.query=null,this.pathname=null,this.path=null,this.href=null}var i=/^([a-z0-9.+-]+:)/i,r=/:[0-9]*$/,s=/^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/,n=["{","}","|","\\","^","`"].concat(["<",">",'"',"`"," ","\r","\n","\t"]),o=["'"].concat(n),a=["%","/","?",";","#"].concat(o),l=["/","?","#"],h=/^[+a-z0-9A-Z_-]{0,63}$/,u=/^([+a-z0-9A-Z_-]{0,63})(.*)$/,c={javascript:!0,"javascript:":!0},d={javascript:!0,"javascript:":!0},p={http:!0,https:!0,ftp:!0,gopher:!0,file:!0,"http:":!0,"https:":!0,"ftp:":!0,"gopher:":!0,"file:":!0},f=/* @__PURE__ */hd();function m(t,i,r){if(t&&"object"==typeof t&&t instanceof e)return t;var s=new e;return s.parse(t,i,r),s}return e.prototype.parse=function(e,r,n){if("string"!=typeof e)throw new TypeError("Parameter 'url' must be a string, not "+typeof e);var m=e.indexOf("?"),g=-1!==m&&m<e.indexOf("#")?"?":"#",y=e.split(g);y[0]=y[0].replace(/\\/g,"/");var v=e=y.join(g);if(v=v.trim(),!n&&1===e.split("#").length){var x=s.exec(v);if(x)return this.path=v,this.href=v,this.pathname=x[1],x[2]?(this.search=x[2],this.query=r?f.parse(this.search.substr(1)):this.search.substr(1)):r&&(this.search="",this.query={}),this}var b=i.exec(v);if(b){var _=(b=b[0]).toLowerCase();this.protocol=_,v=v.substr(b.length)}if(n||b||v.match(/^\/\/[^@/]+@[^@/]+/)){var w="//"===v.substr(0,2);!w||b&&d[b]||(v=v.substr(2),this.slashes=!0)}if(!d[b]&&(w||b&&!p[b])){for(var P,E,T=-1,A=0;A<l.length;A++){-1!==(I=v.indexOf(l[A]))&&(-1===T||I<T)&&(T=I)}-1!==(E=-1===T?v.lastIndexOf("@"):v.lastIndexOf("@",T))&&(P=v.slice(0,E),v=v.slice(E+1),this.auth=decodeURIComponent(P)),T=-1;for(A=0;A<a.length;A++){var I;-1!==(I=v.indexOf(a[A]))&&(-1===T||I<T)&&(T=I)}-1===T&&(T=v.length),this.host=v.slice(0,T),v=v.slice(T),this.parseHost(),this.hostname=this.hostname||"";var S="["===this.hostname[0]&&"]"===this.hostname[this.hostname.length-1];if(!S)for(var C=this.hostname.split(/\./),M=(A=0,C.length);A<M;A++){var O=C[A];if(O&&!O.match(h)){for(var N="",L=0,R=O.length;L<R;L++)O.charCodeAt(L)>127?N+="x":N+=O[L];if(!N.match(h)){var k=C.slice(0,A),B=C.slice(A+1),F=O.match(u);F&&(k.push(F[1]),B.unshift(F[2])),B.length&&(v="/"+B.join(".")+v),this.hostname=k.join(".");break}}}this.hostname.length>255?this.hostname="":this.hostname=this.hostname.toLowerCase(),S||(this.hostname=t.toASCII(this.hostname));var D=this.port?":"+this.port:"",U=this.hostname||"";this.host=U+D,this.href+=this.host,S&&(this.hostname=this.hostname.substr(1,this.hostname.length-2),"/"!==v[0]&&(v="/"+v))}if(!c[_])for(A=0,M=o.length;A<M;A++){var G=o[A];if(-1!==v.indexOf(G)){var X=encodeURIComponent(G);X===G&&(X=escape(G)),v=v.split(G).join(X)}}var W=v.indexOf("#");-1!==W&&(this.hash=v.substr(W),v=v.slice(0,W));var Y=v.indexOf("?");if(-1!==Y?(this.search=v.substr(Y),this.query=v.substr(Y+1),r&&(this.query=f.parse(this.query)),v=v.slice(0,Y)):r&&(this.search="",this.query={}),v&&(this.pathname=v),p[_]&&this.hostname&&!this.pathname&&(this.pathname="/"),this.pathname||this.search){D=this.pathname||"";var H=this.search||"";this.path=D+H}return this.href=this.format(),this},e.prototype.format=function(){var t=this.auth||"";t&&(t=(t=encodeURIComponent(t)).replace(/%3A/i,":"),t+="@");var e=this.protocol||"",i=this.pathname||"",r=this.hash||"",s=!1,n="";this.host?s=t+this.host:this.hostname&&(s=t+(-1===this.hostname.indexOf(":")?this.hostname:"["+this.hostname+"]"),this.port&&(s+=":"+this.port)),this.query&&"object"==typeof this.query&&Object.keys(this.query).length&&(n=f.stringify(this.query,{arrayFormat:"repeat",addQueryPrefix:!1}));var o=this.search||n&&"?"+n||"";return e&&":"!==e.substr(-1)&&(e+=":"),this.slashes||(!e||p[e])&&!1!==s?(s="//"+(s||""),i&&"/"!==i.charAt(0)&&(i="/"+i)):s||(s=""),r&&"#"!==r.charAt(0)&&(r="#"+r),o&&"?"!==o.charAt(0)&&(o="?"+o),e+s+(i=i.replace(/[?#]/g,function(t){return encodeURIComponent(t)}))+(o=o.replace("#","%23"))+r},e.prototype.resolve=function(t){return this.resolveObject(m(t,!1,!0)).format()},e.prototype.resolveObject=function(t){if("string"==typeof t){var i=new e;i.parse(t,!1,!0),t=i}for(var r=new e,s=Object.keys(this),n=0;n<s.length;n++){var o=s[n];r[o]=this[o]}if(r.hash=t.hash,""===t.href)return r.href=r.format(),r;if(t.slashes&&!t.protocol){for(var a=Object.keys(t),l=0;l<a.length;l++){var h=a[l];"protocol"!==h&&(r[h]=t[h])}return p[r.protocol]&&r.hostname&&!r.pathname&&(r.pathname="/",r.path=r.pathname),r.href=r.format(),r}if(t.protocol&&t.protocol!==r.protocol){if(!p[t.protocol]){for(var u=Object.keys(t),c=0;c<u.length;c++){var f=u[c];r[f]=t[f]}return r.href=r.format(),r}if(r.protocol=t.protocol,t.host||d[t.protocol])r.pathname=t.pathname;else{for(var m=(t.pathname||"").split("/");m.length&&!(t.host=m.shift()););t.host||(t.host=""),t.hostname||(t.hostname=""),""!==m[0]&&m.unshift(""),m.length<2&&m.unshift(""),r.pathname=m.join("/")}if(r.search=t.search,r.query=t.query,r.host=t.host||"",r.auth=t.auth,r.hostname=t.hostname||t.host,r.port=t.port,r.pathname||r.search){var g=r.pathname||"",y=r.search||"";r.path=g+y}return r.slashes=r.slashes||t.slashes,r.href=r.format(),r}var v=r.pathname&&"/"===r.pathname.charAt(0),x=t.host||t.pathname&&"/"===t.pathname.charAt(0),b=x||v||r.host&&t.pathname,_=b,w=r.pathname&&r.pathname.split("/")||[],P=(m=t.pathname&&t.pathname.split("/")||[],r.protocol&&!p[r.protocol]);if(P&&(r.hostname="",r.port=null,r.host&&(""===w[0]?w[0]=r.host:w.unshift(r.host)),r.host="",t.protocol&&(t.hostname=null,t.port=null,t.host&&(""===m[0]?m[0]=t.host:m.unshift(t.host)),t.host=null),b=b&&(""===m[0]||""===w[0])),x)r.host=t.host||""===t.host?t.host:r.host,r.hostname=t.hostname||""===t.hostname?t.hostname:r.hostname,r.search=t.search,r.query=t.query,w=m;else if(m.length)w||(w=[]),w.pop(),w=w.concat(m),r.search=t.search,r.query=t.query;else if(null!=t.search){if(P)r.host=w.shift(),r.hostname=r.host,(S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=S.shift(),r.hostname=S.shift(),r.host=r.hostname);return r.search=t.search,r.query=t.query,null===r.pathname&&null===r.search||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.href=r.format(),r}if(!w.length)return r.pathname=null,r.search?r.path="/"+r.search:r.path=null,r.href=r.format(),r;for(var E=w.slice(-1)[0],T=(r.host||t.host||w.length>1)&&("."===E||".."===E)||""===E,A=0,I=w.length;I>=0;I--)"."===(E=w[I])?w.splice(I,1):".."===E?(w.splice(I,1),A++):A&&(w.splice(I,1),A--);if(!b&&!_)for(;A--;A)w.unshift("..");!b||""===w[0]||w[0]&&"/"===w[0].charAt(0)||w.unshift(""),T&&"/"!==w.join("/").substr(-1)&&w.push("");var S,C=""===w[0]||w[0]&&"/"===w[0].charAt(0);P&&(r.hostname=C?"":w.length?w.shift():"",r.host=r.hostname,(S=!!(r.host&&r.host.indexOf("@")>0)&&r.host.split("@"))&&(r.auth=S.shift(),r.hostname=S.shift(),r.host=r.hostname));return(b=b||r.host&&w.length)&&!C&&w.unshift(""),w.length>0?r.pathname=w.join("/"):(r.pathname=null,r.path=null),null===r.pathname&&null===r.search||(r.path=(r.pathname?r.pathname:"")+(r.search?r.search:"")),r.auth=t.auth||r.auth,r.slashes=r.slashes||t.slashes,r.href=r.format(),r},e.prototype.parseHost=function(){var t=this.host,e=r.exec(t);e&&(":"!==(e=e[0])&&(this.port=e.substr(1)),t=t.substr(0,t.length-e.length)),t&&(this.hostname=t)},Uh.parse=m,Uh.resolve=function(t,e){return m(t,!1,!0).resolve(e)},Uh.resolveObject=function(t,e){return t?m(t,!1,!0).resolveObject(e):e},Uh.format=function(t){return"string"==typeof t&&(t=m(t)),t instanceof e?t.format():e.prototype.format.call(t)},Uh.Url=e,Uh}();const cd={};function dd(t,e,i=3){if(cd[e])return;let r=(new Error).stack;typeof r>"u"?console.warn("PixiJS Deprecation Warning: ",`${e}\nDeprecated since v${t}`):(r=r.split("\n").splice(i).join("\n"),console.groupCollapsed?(console.groupCollapsed("%cPixiJS Deprecation Warning: %c%s","color:#614108;background:#fffbe6","font-weight:normal;color:#614108;background:#fffbe6",`${e}\nDeprecated since v${t}`),console.warn(r),console.groupEnd()):(console.warn("PixiJS Deprecation Warning: ",`${e}\nDeprecated since v${t}`),console.warn(r))),cd[e]=!0}const pd={get parse(){return dd("7.3.0","utils.url.parse is deprecated, use native URL API instead."),ud.parse},get format(){return dd("7.3.0","utils.url.format is deprecated, use native URL API instead."),ud.format},get resolve(){return dd("7.3.0","utils.url.resolve is deprecated, use native URL API instead."),ud.resolve}};function fd(t){if("string"!=typeof t)throw new TypeError(`Path must be a string. Received ${JSON.stringify(t)}`)}function md(t){return t.split("?")[0].split("#")[0]}const gd={toPosix(t){return e="\\",i="/",t.replace(new RegExp(e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&"),"g"),i);var e,i},isUrl(t){return/^https?:/.test(this.toPosix(t))},isDataUrl:t=>/^data:([a-z]+\/[a-z0-9-+.]+(;[a-z0-9-.!#$%*+.{}|~`]+=[a-z0-9-.!#$%*+.{}()_|~`]+)*)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s<>]*?)$/i.test(t),isBlobUrl:t=>t.startsWith("blob:"),hasProtocol(t){return/^[^/:]+:/.test(this.toPosix(t))},getProtocol(t){fd(t),t=this.toPosix(t);const e=/^file:\/\/\//.exec(t);if(e)return e[0];const i=/^[^/:]+:\/{0,2}/.exec(t);return i?i[0]:""},toAbsolute(t,e,i){if(fd(t),this.isDataUrl(t)||this.isBlobUrl(t))return t;const r=md(this.toPosix(e??ph.ADAPTER.getBaseUrl())),s=md(this.toPosix(i??this.rootname(r)));return(t=this.toPosix(t)).startsWith("/")?gd.join(s,t.slice(1)):this.isAbsolute(t)?t:this.join(r,t)},normalize(t){if(fd(t),0===t.length)return".";if(this.isDataUrl(t)||this.isBlobUrl(t))return t;let e="";const i=(t=this.toPosix(t)).startsWith("/");this.hasProtocol(t)&&(e=this.rootname(t),t=t.slice(e.length));const r=t.endsWith("/");return(t=function(t){let e="",i=0,r=-1,s=0,n=-1;for(let o=0;o<=t.length;++o){if(o<t.length)n=t.charCodeAt(o);else{if(47===n)break;n=47}if(47===n){if(r!==o-1&&1!==s)if(r!==o-1&&2===s){if(e.length<2||2!==i||46!==e.charCodeAt(e.length-1)||46!==e.charCodeAt(e.length-2))if(e.length>2){const t=e.lastIndexOf("/");if(t!==e.length-1){-1===t?(e="",i=0):(e=e.slice(0,t),i=e.length-1-e.lastIndexOf("/")),r=o,s=0;continue}}else if(2===e.length||1===e.length){e="",i=0,r=o,s=0;continue}}else e.length>0?e+=`/${t.slice(r+1,o)}`:e=t.slice(r+1,o),i=o-r-1;r=o,s=0}else 46===n&&-1!==s?++s:s=-1}return e}(t)).length>0&&r&&(t+="/"),i?`/${t}`:e+t},isAbsolute(t){return fd(t),t=this.toPosix(t),!!this.hasProtocol(t)||t.startsWith("/")},join(...t){if(0===t.length)return".";let e;for(let i=0;i<t.length;++i){const r=t[i];if(fd(r),r.length>0)if(void 0===e)e=r;else{const s=t[i-1]??"";this.joinExtensions.includes(this.extname(s).toLowerCase())?e+=`/../${r}`:e+=`/${r}`}}return void 0===e?".":this.normalize(e)},dirname(t){if(fd(t),0===t.length)return".";let e=(t=this.toPosix(t)).charCodeAt(0);const i=47===e;let r=-1,s=!0;const n=this.getProtocol(t),o=t;for(let a=(t=t.slice(n.length)).length-1;a>=1;--a)if(e=t.charCodeAt(a),47===e){if(!s){r=a;break}}else s=!1;return-1===r?i?"/":this.isUrl(o)?n+t:n:i&&1===r?"//":n+t.slice(0,r)},rootname(t){fd(t);let e="";if(e=(t=this.toPosix(t)).startsWith("/")?"/":this.getProtocol(t),this.isUrl(t)){const i=t.indexOf("/",e.length);e=-1!==i?t.slice(0,i):t,e.endsWith("/")||(e+="/")}return e},basename(t,e){fd(t),e&&fd(e),t=md(this.toPosix(t));let i,r=0,s=-1,n=!0;if(void 0!==e&&e.length>0&&e.length<=t.length){if(e.length===t.length&&e===t)return"";let o=e.length-1,a=-1;for(i=t.length-1;i>=0;--i){const l=t.charCodeAt(i);if(47===l){if(!n){r=i+1;break}}else-1===a&&(n=!1,a=i+1),o>=0&&(l===e.charCodeAt(o)?-1===--o&&(s=i):(o=-1,s=a))}return r===s?s=a:-1===s&&(s=t.length),t.slice(r,s)}for(i=t.length-1;i>=0;--i)if(47===t.charCodeAt(i)){if(!n){r=i+1;break}}else-1===s&&(n=!1,s=i+1);return-1===s?"":t.slice(r,s)},extname(t){fd(t);let e=-1,i=0,r=-1,s=!0,n=0;for(let o=(t=md(this.toPosix(t))).length-1;o>=0;--o){const a=t.charCodeAt(o);if(47!==a)-1===r&&(s=!1,r=o+1),46===a?-1===e?e=o:1!==n&&(n=1):-1!==e&&(n=-1);else if(!s){i=o+1;break}}return-1===e||-1===r||0===n||1===n&&e===r-1&&e===i+1?"":t.slice(e,r)},parse(t){fd(t);const e={root:"",dir:"",base:"",ext:"",name:""};if(0===t.length)return e;let i=(t=md(this.toPosix(t))).charCodeAt(0);const r=this.isAbsolute(t);let s;e.root=this.rootname(t),s=r||this.hasProtocol(t)?1:0;let n=-1,o=0,a=-1,l=!0,h=t.length-1,u=0;for(;h>=s;--h)if(i=t.charCodeAt(h),47!==i)-1===a&&(l=!1,a=h+1),46===i?-1===n?n=h:1!==u&&(u=1):-1!==n&&(u=-1);else if(!l){o=h+1;break}return-1===n||-1===a||0===u||1===u&&n===a-1&&n===o+1?-1!==a&&(e.base=e.name=0===o&&r?t.slice(1,a):t.slice(o,a)):(0===o&&r?(e.name=t.slice(1,n),e.base=t.slice(1,a)):(e.name=t.slice(o,n),e.base=t.slice(o,a)),e.ext=t.slice(n,a)),e.dir=this.dirname(t),e},sep:"/",delimiter:":",joinExtensions:[".html"]};let yd,vd;function xd(){return typeof vd>"u"&&(vd=function(){const t={stencil:!0,failIfMajorPerformanceCaveat:ph.FAIL_IF_MAJOR_PERFORMANCE_CAVEAT};try{if(!ph.ADAPTER.getWebGLRenderingContext())return!1;const e=ph.ADAPTER.createCanvas();let i=e.getContext("webgl",t)||e.getContext("experimental-webgl",t);const r=!!i?.getContextAttributes()?.stencil;if(i){const t=i.getExtension("WEBGL_lose_context");t&&t.loseContext()}return i=null,r}catch{return!1}}()),vd}var bd,_d={grad:.9,turn:360,rad:360/(2*Math.PI)},wd=function(t){return"string"==typeof t?t.length>0:"number"==typeof t},Pd=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=Math.pow(10,e)),Math.round(i*t)/i+0},Ed=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=1),t>i?i:t>e?t:e},Td=function(t){return(t=isFinite(t)?t%360:0)>0?t:t+360},Ad=function(t){return{r:Ed(t.r,0,255),g:Ed(t.g,0,255),b:Ed(t.b,0,255),a:Ed(t.a)}},Id=function(t){return{r:Pd(t.r),g:Pd(t.g),b:Pd(t.b),a:Pd(t.a,3)}},Sd=/^#([0-9a-f]{3,8})$/i,Cd=function(t){var e=t.toString(16);return e.length<2?"0"+e:e},Md=function(t){var e=t.r,i=t.g,r=t.b,s=t.a,n=Math.max(e,i,r),o=n-Math.min(e,i,r),a=o?n===e?(i-r)/o:n===i?2+(r-e)/o:4+(e-i)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:s}},Od=function(t){var e=t.h,i=t.s,r=t.v,s=t.a;e=e/360*6,i/=100,r/=100;var n=Math.floor(e),o=r*(1-i),a=r*(1-(e-n)*i),l=r*(1-(1-e+n)*i),h=n%6;return{r:255*[r,a,o,o,l,r][h],g:255*[l,r,r,a,o,o][h],b:255*[o,o,l,r,r,a][h],a:s}},Nd=function(t){return{h:Td(t.h),s:Ed(t.s,0,100),l:Ed(t.l,0,100),a:Ed(t.a)}},Ld=function(t){return{h:Pd(t.h),s:Pd(t.s),l:Pd(t.l),a:Pd(t.a,3)}},Rd=function(t){return Od((i=(e=t).s,{h:e.h,s:(i*=((r=e.l)<50?r:100-r)/100)>0?2*i/(r+i)*100:0,v:r+i,a:e.a}));var e,i,r},kd=function(t){return{h:(e=Md(t)).h,s:(s=(200-(i=e.s))*(r=e.v)/100)>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,l:s/2,a:e.a};var e,i,r,s},Bd=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Fd=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Dd=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Ud=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Gd={string:[[function(t){var e=Sd.exec(t);return e?(t=e[1]).length<=4?{r:parseInt(t[0]+t[0],16),g:parseInt(t[1]+t[1],16),b:parseInt(t[2]+t[2],16),a:4===t.length?Pd(parseInt(t[3]+t[3],16)/255,2):1}:6===t.length||8===t.length?{r:parseInt(t.substr(0,2),16),g:parseInt(t.substr(2,2),16),b:parseInt(t.substr(4,2),16),a:8===t.length?Pd(parseInt(t.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(t){var e=Dd.exec(t)||Ud.exec(t);return e?e[2]!==e[4]||e[4]!==e[6]?null:Ad({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:void 0===e[7]?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(t){var e=Bd.exec(t)||Fd.exec(t);if(!e)return null;var i,r,s=Nd({h:(i=e[1],r=e[2],void 0===r&&(r="deg"),Number(i)*(_d[r]||1)),s:Number(e[3]),l:Number(e[4]),a:void 0===e[5]?1:Number(e[5])/(e[6]?100:1)});return Rd(s)},"hsl"]],object:[[function(t){var e=t.r,i=t.g,r=t.b,s=t.a,n=void 0===s?1:s;return wd(e)&&wd(i)&&wd(r)?Ad({r:Number(e),g:Number(i),b:Number(r),a:Number(n)}):null},"rgb"],[function(t){var e=t.h,i=t.s,r=t.l,s=t.a,n=void 0===s?1:s;if(!wd(e)||!wd(i)||!wd(r))return null;var o=Nd({h:Number(e),s:Number(i),l:Number(r),a:Number(n)});return Rd(o)},"hsl"],[function(t){var e=t.h,i=t.s,r=t.v,s=t.a,n=void 0===s?1:s;if(!wd(e)||!wd(i)||!wd(r))return null;var o,a=(o={h:Number(e),s:Number(i),v:Number(r),a:Number(n)},{h:Td(o.h),s:Ed(o.s,0,100),v:Ed(o.v,0,100),a:Ed(o.a)});return Od(a)},"hsv"]]},Xd=function(t,e){for(var i=0;i<e.length;i++){var r=e[i][0](t);if(r)return[r,e[i][1]]}return[null,void 0]},Wd=function(t,e){var i=kd(t);return{h:i.h,s:Ed(i.s+100*e,0,100),l:i.l,a:i.a}},Yd=function(t){return(299*t.r+587*t.g+114*t.b)/1e3/255},Hd=function(t,e){var i=kd(t);return{h:i.h,s:i.s,l:Ed(i.l+100*e,0,100),a:i.a}},$d=function(){function t(t){this.parsed=function(t){return"string"==typeof t?Xd(t.trim(),Gd.string):"object"==typeof t&&null!==t?Xd(t,Gd.object):[null,void 0]}(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return t.prototype.isValid=function(){return null!==this.parsed},t.prototype.brightness=function(){return Pd(Yd(this.rgba),2)},t.prototype.isDark=function(){return Yd(this.rgba)<.5},t.prototype.isLight=function(){return Yd(this.rgba)>=.5},t.prototype.toHex=function(){return e=(t=Id(this.rgba)).r,i=t.g,r=t.b,n=(s=t.a)<1?Cd(Pd(255*s)):"","#"+Cd(e)+Cd(i)+Cd(r)+n;var t,e,i,r,s,n},t.prototype.toRgb=function(){return Id(this.rgba)},t.prototype.toRgbString=function(){return e=(t=Id(this.rgba)).r,i=t.g,r=t.b,(s=t.a)<1?"rgba("+e+", "+i+", "+r+", "+s+")":"rgb("+e+", "+i+", "+r+")";var t,e,i,r,s},t.prototype.toHsl=function(){return Ld(kd(this.rgba))},t.prototype.toHslString=function(){return e=(t=Ld(kd(this.rgba))).h,i=t.s,r=t.l,(s=t.a)<1?"hsla("+e+", "+i+"%, "+r+"%, "+s+")":"hsl("+e+", "+i+"%, "+r+"%)";var t,e,i,r,s},t.prototype.toHsv=function(){return t=Md(this.rgba),{h:Pd(t.h),s:Pd(t.s),v:Pd(t.v),a:Pd(t.a,3)};var t},t.prototype.invert=function(){return jd({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},t.prototype.saturate=function(t){return void 0===t&&(t=.1),jd(Wd(this.rgba,t))},t.prototype.desaturate=function(t){return void 0===t&&(t=.1),jd(Wd(this.rgba,-t))},t.prototype.grayscale=function(){return jd(Wd(this.rgba,-1))},t.prototype.lighten=function(t){return void 0===t&&(t=.1),jd(Hd(this.rgba,t))},t.prototype.darken=function(t){return void 0===t&&(t=.1),jd(Hd(this.rgba,-t))},t.prototype.rotate=function(t){return void 0===t&&(t=15),this.hue(this.hue()+t)},t.prototype.alpha=function(t){return"number"==typeof t?jd({r:(e=this.rgba).r,g:e.g,b:e.b,a:t}):Pd(this.rgba.a,3);var e},t.prototype.hue=function(t){var e=kd(this.rgba);return"number"==typeof t?jd({h:t,s:e.s,l:e.l,a:e.a}):Pd(e.h)},t.prototype.isEqual=function(t){return this.toHex()===jd(t).toHex()},t}(),jd=function(t){return t instanceof $d?t:new $d(t)},zd=[];bd=[function(t,e){var i={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},r={};for(var s in i)r[i[s]]=s;var n={};t.prototype.toName=function(e){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var s,o,a=r[this.toHex()];if(a)return a;if(null==e?void 0:e.closest){var l=this.toRgb(),h=1/0,u="black";if(!n.length)for(var c in i)n[c]=new t(i[c]).toRgb();for(var d in i){var p=(s=l,o=n[d],Math.pow(s.r-o.r,2)+Math.pow(s.g-o.g,2)+Math.pow(s.b-o.b,2));p<h&&(h=p,u=d)}return u}},e.string.push([function(e){var r=e.toLowerCase(),s="transparent"===r?"#0000":i[r];return s?new t(s).toRgb():null},"name"])}],bd.forEach(function(t){zd.indexOf(t)<0&&(t($d,Gd),zd.push(t))});const Vd=class t{constructor(t=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=t}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(t){return this.value=t,this}set value(e){if(e instanceof t)this._value=this.cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(null===e)throw new Error("Cannot set PIXI.Color#value to null");(null===this._value||!this.isSourceEqual(this._value,e))&&(this.normalize(e),this._value=this.cloneSource(e))}}get value(){return this._value}cloneSource(t){return"string"==typeof t||"number"==typeof t||t instanceof Number||null===t?t:Array.isArray(t)||ArrayBuffer.isView(t)?t.slice(0):"object"==typeof t&&null!==t?{...t}:t}isSourceEqual(t,e){const i=typeof t;if(i!==typeof e)return!1;if("number"===i||"string"===i||t instanceof Number)return t===e;if(Array.isArray(t)&&Array.isArray(e)||ArrayBuffer.isView(t)&&ArrayBuffer.isView(e))return t.length===e.length&&t.every((t,i)=>t===e[i]);if(null!==t&&null!==e){const i=Object.keys(t),r=Object.keys(e);return i.length===r.length&&i.every(i=>t[i]===e[i])}return t===e}toRgba(){const[t,e,i,r]=this._components;return{r:t,g:e,b:i,a:r}}toRgb(){const[t,e,i]=this._components;return{r:t,g:e,b:i}}toRgbaString(){const[t,e,i]=this.toUint8RgbArray();return`rgba(${t},${e},${i},${this.alpha})`}toUint8RgbArray(t){const[e,i,r]=this._components;return(t=t??[])[0]=Math.round(255*e),t[1]=Math.round(255*i),t[2]=Math.round(255*r),t}toRgbArray(t){t=t??[];const[e,i,r]=this._components;return t[0]=e,t[1]=i,t[2]=r,t}toNumber(){return this._int}toLittleEndianNumber(){const t=this._int;return(t>>16)+(65280&t)+((255&t)<<16)}multiply(e){const[i,r,s,n]=t.temp.setValue(e)._components;return this._components[0]*=i,this._components[1]*=r,this._components[2]*=s,this._components[3]*=n,this.refreshInt(),this._value=null,this}premultiply(t,e=!0){return e&&(this._components[0]*=t,this._components[1]*=t,this._components[2]*=t),this._components[3]=t,this.refreshInt(),this._value=null,this}toPremultiplied(t,e=!0){if(1===t)return(255<<24)+this._int;if(0===t)return e?0:this._int;let i=this._int>>16&255,r=this._int>>8&255,s=255&this._int;return e&&(i=i*t+.5|0,r=r*t+.5|0,s=s*t+.5|0),(255*t<<24)+(i<<16)+(r<<8)+s}toHex(){const t=this._int.toString(16);return`#${"000000".substring(0,6-t.length)+t}`}toHexa(){const t=Math.round(255*this._components[3]).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(t){return this._components[3]=this._clamp(t),this}round(t){const[e,i,r]=this._components;return this._components[0]=Math.round(e*t)/t,this._components[1]=Math.round(i*t)/t,this._components[2]=Math.round(r*t)/t,this.refreshInt(),this._value=null,this}toArray(t){t=t??[];const[e,i,r,s]=this._components;return t[0]=e,t[1]=i,t[2]=r,t[3]=s,t}normalize(e){let i,r,s,n;if(("number"==typeof e||e instanceof Number)&&e>=0&&e<=16777215){i=(e>>16&255)/255,r=(e>>8&255)/255,s=(255&e)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[i,r,s,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[i,r,s,n=255]=e,i/=255,r/=255,s/=255,n/=255;else if("string"==typeof e||"object"==typeof e){if("string"==typeof e){const i=t.HEX_PATTERN.exec(e);i&&(e=`#${i[2]}`)}const o=jd(e);o.isValid()&&(({r:i,g:r,b:s,a:n}=o.rgba),i/=255,r/=255,s/=255)}if(void 0===i)throw new Error(`Unable to convert color ${e}`);this._components[0]=i,this._components[1]=r,this._components[2]=s,this._components[3]=n,this.refreshInt()}refreshInt(){this._clamp(this._components);const[t,e,i]=this._components;this._int=(255*t<<16)+(255*e<<8)+(255*i|0)}_clamp(t,e=0,i=1){return"number"==typeof t?Math.min(Math.max(t,e),i):(t.forEach((r,s)=>{t[s]=Math.min(Math.max(r,e),i)}),t)}};Vd.shared=new Vd,Vd.temp=new Vd,Vd.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let qd=Vd;const Jd=function(){const t=[],e=[];for(let r=0;r<32;r++)t[r]=r,e[r]=r;t[Kl.NORMAL_NPM]=Kl.NORMAL,t[Kl.ADD_NPM]=Kl.ADD,t[Kl.SCREEN_NPM]=Kl.SCREEN,e[Kl.NORMAL]=Kl.NORMAL_NPM,e[Kl.ADD]=Kl.ADD_NPM,e[Kl.SCREEN]=Kl.SCREEN_NPM;const i=[];return i.push(e),i.push(t),i}();const Kd=/^\s*data:(?:([\w-]+)\/([\w+.-]+))?(?:;charset=([\w-]+))?(?:;(base64))?,(.*)/i;function Zd(t){if(4===t.BYTES_PER_ELEMENT)return t instanceof Float32Array?"Float32Array":t instanceof Uint32Array?"Uint32Array":"Int32Array";if(2===t.BYTES_PER_ELEMENT){if(t instanceof Uint16Array)return"Uint16Array"}else if(1===t.BYTES_PER_ELEMENT&&t instanceof Uint8Array)return"Uint8Array";return null}const Qd={Float32Array:Float32Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Uint8Array:Uint8Array};function tp(t){return t+=0===t?1:0,--t,t|=t>>>1,t|=t>>>2,t|=t>>>4,t|=t>>>8,(t|=t>>>16)+1}function ep(t){return!(t&t-1||!t)}function ip(t){let e=(t>65535?1:0)<<4,i=((t>>>=e)>255?1:0)<<3;return e|=i,i=((t>>>=i)>15?1:0)<<2,e|=i,i=((t>>>=i)>3?1:0)<<1,e|=i,e|(t>>>=i)>>1}function rp(t,e,i){const r=t.length;let s;if(e>=r||0===i)return;const n=r-(i=e+i>r?r-e:i);for(s=e;s<n;++s)t[s]=t[s+i];t.length=n}function sp(t){return 0===t?0:t<0?-1:1}let np=0;function op(){return++np}const ap=class{constructor(t,e,i,r){this.left=t,this.top=e,this.right=i,this.bottom=r}get width(){return this.right-this.left}get height(){return this.bottom-this.top}isEmpty(){return this.left===this.right||this.top===this.bottom}};ap.EMPTY=new ap(0,0,0,0);let lp=ap;const hp={},up=/* @__PURE__ */Object.create(null),cp=/* @__PURE__ */Object.create(null);function dp(){let t;for(t in up)delete up[t];for(t in cp)delete cp[t]}class pp{constructor(t,e,i){this._canvas=ph.ADAPTER.createCanvas(),this._context=this._canvas.getContext("2d"),this.resolution=i||ph.RESOLUTION,this.resize(t,e)}clear(){this._checkDestroyed(),this._context.setTransform(1,0,0,1,0,0),this._context.clearRect(0,0,this._canvas.width,this._canvas.height)}resize(t,e){this._checkDestroyed(),this._canvas.width=Math.round(t*this.resolution),this._canvas.height=Math.round(e*this.resolution)}destroy(){this._context=null,this._canvas=null}get width(){return this._checkDestroyed(),this._canvas.width}set width(t){this._checkDestroyed(),this._canvas.width=Math.round(t)}get height(){return this._checkDestroyed(),this._canvas.height}set height(t){this._checkDestroyed(),this._canvas.height=Math.round(t)}get canvas(){return this._checkDestroyed(),this._canvas}get context(){return this._checkDestroyed(),this._context}_checkDestroyed(){if(null===this._canvas)throw new TypeError("The CanvasRenderTarget has already been destroyed")}}function fp(t,e,i){for(let r=0,s=4*i*e;r<e;++r,s+=4)if(0!==t[s+3])return!1;return!0}function mp(t,e,i,r,s){const n=4*e;for(let o=r,a=r*n+4*i;o<=s;++o,a+=n)if(0!==t[a+3])return!1;return!0}function gp(t){const{width:e,height:i}=t,r=t.getContext("2d",{willReadFrequently:!0});if(null===r)throw new TypeError("Failed to get canvas 2D context");const s=r.getImageData(0,0,e,i).data;let n=0,o=0,a=e-1,l=i-1;for(;o<i&&fp(s,e,o);)++o;if(o===i)return lp.EMPTY;for(;fp(s,e,l);)--l;for(;mp(s,e,n,o,l);)++n;for(;mp(s,e,a,o,l);)--a;return++a,++l,new lp(n,o,a,l)}function yp(t){const e=gp(t),{width:i,height:r}=e;let s=null;if(!e.isEmpty()){const n=t.getContext("2d");if(null===n)throw new TypeError("Failed to get canvas 2D context");s=n.getImageData(e.left,e.top,i,r)}return{width:i,height:r,data:s}}function vp(t,e=globalThis.location){if(t.startsWith("data:"))return"";e=e||globalThis.location;const i=new URL(t,document.baseURI);return i.hostname!==e.hostname||i.port!==e.port||i.protocol!==e.protocol?"anonymous":""}function xp(t,e=1){const i=ph.RETINA_PREFIX?.exec(t);return i?parseFloat(i[1]):e}const bp=/* @__PURE__ */Object.freeze(/* @__PURE__ */Object.defineProperty({__proto__:null,BaseTextureCache:cp,BoundingBox:lp,CanvasRenderTarget:pp,DATA_URI:Kd,EventEmitter:kh,ProgramCache:hp,TextureCache:up,clearTextureCache:dp,correctBlendMode:function(t,e){return Jd[e?1:0][t]},createIndicesForQuads:function(t,e=null){const i=6*t;if((e=e||new Uint16Array(i)).length!==i)throw new Error(`Out buffer length is incorrect, got ${e.length} and expected ${i}`);for(let r=0,s=0;r<i;r+=6,s+=4)e[r+0]=s+0,e[r+1]=s+1,e[r+2]=s+2,e[r+3]=s+0,e[r+4]=s+2,e[r+5]=s+3;return e},decomposeDataUri:function(t){const e=Kd.exec(t);if(e)return{mediaType:e[1]?e[1].toLowerCase():void 0,subType:e[2]?e[2].toLowerCase():void 0,charset:e[3]?e[3].toLowerCase():void 0,encoding:e[4]?e[4].toLowerCase():void 0,data:e[5]}},deprecation:dd,destroyTextureCache:function(){let t;for(t in up)up[t].destroy();for(t in cp)cp[t].destroy()},detectVideoAlphaMode:async function(){return yd??(yd=(async()=>{const t=document.createElement("canvas").getContext("webgl");if(!t)return oh.UNPACK;const e=await new Promise(t=>{const e=document.createElement("video");e.onloadeddata=()=>t(e),e.onerror=()=>t(null),e.autoplay=!1,e.crossOrigin="anonymous",e.preload="auto",e.src="data:video/webm;base64,GkXfo59ChoEBQveBAULygQRC84EIQoKEd2VibUKHgQJChYECGFOAZwEAAAAAAAHTEU2bdLpNu4tTq4QVSalmU6yBoU27i1OrhBZUrmtTrIHGTbuMU6uEElTDZ1OsggEXTbuMU6uEHFO7a1OsggG97AEAAAAAAABZAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAVSalmoCrXsYMPQkBNgIRMYXZmV0GETGF2ZkSJiEBEAAAAAAAAFlSua8yuAQAAAAAAAEPXgQFzxYgAAAAAAAAAAZyBACK1nIN1bmSIgQCGhVZfVlA5g4EBI+ODhAJiWgDglLCBArqBApqBAlPAgQFVsIRVuYEBElTDZ9Vzc9JjwItjxYgAAAAAAAAAAWfInEWjh0VOQ09ERVJEh49MYXZjIGxpYnZweC12cDlnyKJFo4hEVVJBVElPTkSHlDAwOjAwOjAwLjA0MDAwMDAwMAAAH0O2dcfngQCgwqGggQAAAIJJg0IAABAAFgA4JBwYSgAAICAAEb///4r+AAB1oZ2mm+6BAaWWgkmDQgAAEAAWADgkHBhKAAAgIABIQBxTu2uRu4+zgQC3iveBAfGCAXHwgQM=",e.load()});if(!e)return oh.UNPACK;const i=t.createTexture();t.bindTexture(t.TEXTURE_2D,i);const r=t.createFramebuffer();t.bindFramebuffer(t.FRAMEBUFFER,r),t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i,0),t.pixelStorei(t.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),t.pixelStorei(t.UNPACK_COLORSPACE_CONVERSION_WEBGL,t.NONE),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,t.RGBA,t.UNSIGNED_BYTE,e);const s=new Uint8Array(4);return t.readPixels(0,0,1,1,t.RGBA,t.UNSIGNED_BYTE,s),t.deleteFramebuffer(r),t.deleteTexture(i),t.getExtension("WEBGL_lose_context")?.loseContext(),s[0]<=s[3]?oh.PMA:oh.UNPACK})()),yd},determineCrossOrigin:vp,earcut:Nt,getBufferType:Zd,getCanvasBoundingBox:gp,getResolutionOfUrl:xp,hex2rgb:function(t,e=[]){return dd("7.2.0","utils.hex2rgb is deprecated, use Color#toRgbArray instead"),qd.shared.setValue(t).toRgbArray(e)},hex2string:function(t){return dd("7.2.0","utils.hex2string is deprecated, use Color#toHex instead"),qd.shared.setValue(t).toHex()},interleaveTypedArrays:function(t,e){let i=0,r=0;const s={};for(let l=0;l<t.length;l++)r+=e[l],i+=t[l].length;const n=new ArrayBuffer(4*i);let o=null,a=0;for(let l=0;l<t.length;l++){const i=e[l],h=t[l],u=Zd(h);s[u]||(s[u]=new Qd[u](n)),o=s[u];for(let t=0;t<h.length;t++){o[(t/i|0)*r+a+t%i]=h[t]}a+=i}return new Float32Array(n)},isMobile:Oh,isPow2:ep,isWebGLSupported:xd,log2:ip,nextPow2:tp,path:gd,premultiplyBlendMode:Jd,premultiplyRgba:function(t,e,i,r=!0){return dd("7.2.0","utils.premultiplyRgba has moved to Color.premultiply"),qd.shared.setValue(t).premultiply(e,r).toArray(i??new Float32Array(4))},premultiplyTint:function(t,e){return dd("7.2.0","utils.premultiplyTint has moved to Color.toPremultiplied"),qd.shared.setValue(t).toPremultiplied(e)},premultiplyTintToRgba:function(t,e,i,r=!0){return dd("7.2.0","utils.premultiplyTintToRgba has moved to Color.premultiply"),qd.shared.setValue(t).premultiply(e,r).toArray(i??new Float32Array(4))},removeItems:rp,rgb2hex:function(t){return dd("7.2.0","utils.rgb2hex is deprecated, use Color#toNumber instead"),qd.shared.setValue(t).toNumber()},sayHello:function(){dd("7.0.0",'sayHello is deprecated, please use Renderer\'s "hello" option')},sign:sp,skipHello:function(){dd("7.0.0","skipHello is deprecated, please use settings.RENDER_OPTIONS.hello")},string2hex:function(t){return dd("7.2.0","utils.string2hex is deprecated, use Color#toNumber instead"),qd.shared.setValue(t).toNumber()},trimCanvas:yp,uid:op,url:pd},Symbol.toStringTag,{value:"Module"}));var _p=/* @__PURE__ */(t=>(t.Renderer="renderer",t.Application="application",t.RendererSystem="renderer-webgl-system",t.RendererPlugin="renderer-webgl-plugin",t.CanvasRendererSystem="renderer-canvas-system",t.CanvasRendererPlugin="renderer-canvas-plugin",t.Asset="asset",t.LoadParser="load-parser",t.ResolveParser="resolve-parser",t.CacheParser="cache-parser",t.DetectionParser="detection-parser",t))(_p||{});const wp=t=>{if("function"==typeof t||"object"==typeof t&&t.extension){if(!t.extension)throw new Error("Extension class must have an extension object");t={..."object"!=typeof t.extension?{type:t.extension}:t.extension,ref:t}}if("object"!=typeof t)throw new Error("Invalid extension type");return"string"==typeof(t={...t}).type&&(t.type=[t.type]),t},Pp=(t,e)=>wp(t).priority??e,Ep={_addHandlers:{},_removeHandlers:{},_queue:{},remove(...t){return t.map(wp).forEach(t=>{t.type.forEach(e=>this._removeHandlers[e]?.(t))}),this},add(...t){return t.map(wp).forEach(t=>{t.type.forEach(e=>{const i=this._addHandlers,r=this._queue;i[e]?i[e]?.(t):(r[e]=r[e]||[],r[e]?.push(t))})}),this},handle(t,e,i){const r=this._addHandlers,s=this._removeHandlers;if(r[t]||s[t])throw new Error(`Extension type ${t} already has a handler`);r[t]=e,s[t]=i;const n=this._queue;return n[t]&&(n[t]?.forEach(t=>e(t)),delete n[t]),this},handleByMap(t,e){return this.handle(t,t=>{t.name&&(e[t.name]=t.ref)},t=>{t.name&&delete e[t.name]})},handleByList(t,e,i=-1){return this.handle(t,t=>{e.includes(t.ref)||(e.push(t.ref),e.sort((t,e)=>Pp(e,i)-Pp(t,i)))},t=>{const i=e.indexOf(t.ref);-1!==i&&e.splice(i,1)})}};class Tp{constructor(t){"number"==typeof t?this.rawBinaryData=new ArrayBuffer(t):t instanceof Uint8Array?this.rawBinaryData=t.buffer:this.rawBinaryData=t,this.uint32View=new Uint32Array(this.rawBinaryData),this.float32View=new Float32Array(this.rawBinaryData)}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 uint16View(){return this._uint16View||(this._uint16View=new Uint16Array(this.rawBinaryData)),this._uint16View}get int32View(){return this._int32View||(this._int32View=new Int32Array(this.rawBinaryData)),this._int32View}view(t){return this[`${t}View`]}destroy(){this.rawBinaryData=null,this._int8View=null,this._uint8View=null,this._int16View=null,this._uint16View=null,this._int32View=null,this.uint32View=null,this.float32View=null}static sizeOf(t){switch(t){case"int8":case"uint8":return 1;case"int16":case"uint16":return 2;case"int32":case"uint32":case"float32":return 4;default:throw new Error(`${t} isn't a valid view type`)}}}const Ap=["precision mediump float;","void main(void){","float test = 0.1;","%forloop%","gl_FragColor = vec4(0.0);","}"].join("\n");function Ip(t){let e="";for(let i=0;i<t;++i)i>0&&(e+="\nelse "),i<t-1&&(e+=`if(test == ${i}.0){}`);return e}class Sp{constructor(){this.data=0,this.blendMode=Kl.NORMAL,this.polygonOffset=0,this.blend=!0,this.depthMask=!0}get blend(){return!!(1&this.data)}set blend(t){!!(1&this.data)!==t&&(this.data^=1)}get offsets(){return!!(2&this.data)}set offsets(t){!!(2&this.data)!==t&&(this.data^=2)}get culling(){return!!(4&this.data)}set culling(t){!!(4&this.data)!==t&&(this.data^=4)}get depthTest(){return!!(8&this.data)}set depthTest(t){!!(8&this.data)!==t&&(this.data^=8)}get depthMask(){return!!(32&this.data)}set depthMask(t){!!(32&this.data)!==t&&(this.data^=32)}get clockwiseFrontFace(){return!!(16&this.data)}set clockwiseFrontFace(t){!!(16&this.data)!==t&&(this.data^=16)}get blendMode(){return this._blendMode}set blendMode(t){this.blend=t!==Kl.NONE,this._blendMode=t}get polygonOffset(){return this._polygonOffset}set polygonOffset(t){this.offsets=!!t,this._polygonOffset=t}static for2d(){const t=new Sp;return t.depthTest=!1,t.blend=!0,t}}Sp.prototype.toString=function(){return`[@pixi/core:State blendMode=${this.blendMode} clockwiseFrontFace=${this.clockwiseFrontFace} culling=${this.culling} depthMask=${this.depthMask} polygonOffset=${this.polygonOffset}]`};const Cp=[];function Mp(t,e){if(!t)return null;let i="";if("string"==typeof t){const e=/\.(\w{3,4})(?:$|\?|#)/i.exec(t);e&&(i=e[1].toLowerCase())}for(let r=Cp.length-1;r>=0;--r){const s=Cp[r];if(s.test&&s.test(t,i))return new s(t,e)}throw new Error("Unrecognized source type to auto-detect Resource")}class Op{constructor(t){this.items=[],this._name=t,this._aliasCount=0}emit(t,e,i,r,s,n,o,a){if(arguments.length>8)throw new Error("max arguments reached");const{name:l,items:h}=this;this._aliasCount++;for(let u=0,c=h.length;u<c;u++)h[u][l](t,e,i,r,s,n,o,a);return h===this.items&&this._aliasCount--,this}ensureNonAliasedItems(){this._aliasCount>0&&this.items.length>1&&(this._aliasCount=0,this.items=this.items.slice(0))}add(t){return t[this._name]&&(this.ensureNonAliasedItems(),this.remove(t),this.items.push(t)),this}remove(t){const e=this.items.indexOf(t);return-1!==e&&(this.ensureNonAliasedItems(),this.items.splice(e,1)),this}contains(t){return this.items.includes(t)}removeAll(){return this.ensureNonAliasedItems(),this.items.length=0,this}destroy(){this.removeAll(),this.items.length=0,this._name=""}get empty(){return 0===this.items.length}get name(){return this._name}}Object.defineProperties(Op.prototype,{dispatch:{value:Op.prototype.emit},run:{value:Op.prototype.emit}});class Np{constructor(t=0,e=0){this._width=t,this._height=e,this.destroyed=!1,this.internal=!1,this.onResize=new Op("setRealSize"),this.onUpdate=new Op("update"),this.onError=new Op("onError")}bind(t){this.onResize.add(t),this.onUpdate.add(t),this.onError.add(t),(this._width||this._height)&&this.onResize.emit(this._width,this._height)}unbind(t){this.onResize.remove(t),this.onUpdate.remove(t),this.onError.remove(t)}resize(t,e){(t!==this._width||e!==this._height)&&(this._width=t,this._height=e,this.onResize.emit(t,e))}get valid(){return!!this._width&&!!this._height}update(){this.destroyed||this.onUpdate.emit()}load(){return Promise.resolve(this)}get width(){return this._width}get height(){return this._height}style(t,e,i){return!1}dispose(){}destroy(){this.destroyed||(this.destroyed=!0,this.dispose(),this.onError.removeAll(),this.onError=null,this.onResize.removeAll(),this.onResize=null,this.onUpdate.removeAll(),this.onUpdate=null)}static test(t,e){return!1}}class Lp extends Np{constructor(t,e){const{width:i,height:r}=e||{};if(!i||!r)throw new Error("BufferResource width or height invalid");super(i,r),this.data=t,this.unpackAlignment=e.unpackAlignment??4}upload(t,e,i){const r=t.gl;r.pixelStorei(r.UNPACK_ALIGNMENT,this.unpackAlignment),r.pixelStorei(r.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.alphaMode===oh.UNPACK);const s=e.realWidth,n=e.realHeight;return i.width===s&&i.height===n?r.texSubImage2D(e.target,0,0,0,s,n,e.format,i.type,this.data):(i.width=s,i.height=n,r.texImage2D(e.target,0,i.internalFormat,s,n,0,e.format,i.type,this.data)),!0}dispose(){this.data=null}static test(t){return null===t||t instanceof Int8Array||t instanceof Uint8Array||t instanceof Uint8ClampedArray||t instanceof Int16Array||t instanceof Uint16Array||t instanceof Int32Array||t instanceof Uint32Array||t instanceof Float32Array}}const Rp={scaleMode:rh.NEAREST,alphaMode:oh.NPM},kp=class t extends kh{constructor(e=null,i=null){super(),i=Object.assign({},t.defaultOptions,i);const{alphaMode:r,mipmap:s,anisotropicLevel:n,scaleMode:o,width:a,height:l,wrapMode:h,format:u,type:c,target:d,resolution:p,resourceOptions:f}=i;e&&!(e instanceof Np)&&((e=Mp(e,f)).internal=!0),this.resolution=p||ph.RESOLUTION,this.width=Math.round((a||0)*this.resolution)/this.resolution,this.height=Math.round((l||0)*this.resolution)/this.resolution,this._mipmap=s,this.anisotropicLevel=n,this._wrapMode=h,this._scaleMode=o,this.format=u,this.type=c,this.target=d,this.alphaMode=r,this.uid=op(),this.touched=0,this.isPowerOfTwo=!1,this._refreshPOT(),this._glTextures={},this.dirtyId=0,this.dirtyStyleId=0,this.cacheId=null,this.valid=a>0&&l>0,this.textureCacheIds=[],this.destroyed=!1,this.resource=null,this._batchEnabled=0,this._batchLocation=0,this.parentTextureArray=null,this.setResource(e)}get realWidth(){return Math.round(this.width*this.resolution)}get realHeight(){return Math.round(this.height*this.resolution)}get mipmap(){return this._mipmap}set mipmap(t){this._mipmap!==t&&(this._mipmap=t,this.dirtyStyleId++)}get scaleMode(){return this._scaleMode}set scaleMode(t){this._scaleMode!==t&&(this._scaleMode=t,this.dirtyStyleId++)}get wrapMode(){return this._wrapMode}set wrapMode(t){this._wrapMode!==t&&(this._wrapMode=t,this.dirtyStyleId++)}setStyle(t,e){let i;return void 0!==t&&t!==this.scaleMode&&(this.scaleMode=t,i=!0),void 0!==e&&e!==this.mipmap&&(this.mipmap=e,i=!0),i&&this.dirtyStyleId++,this}setSize(t,e,i){return i=i||this.resolution,this.setRealSize(t*i,e*i,i)}setRealSize(t,e,i){return this.resolution=i||this.resolution,this.width=Math.round(t)/this.resolution,this.height=Math.round(e)/this.resolution,this._refreshPOT(),this.update(),this}_refreshPOT(){this.isPowerOfTwo=ep(this.realWidth)&&ep(this.realHeight)}setResolution(t){const e=this.resolution;return e===t||(this.resolution=t,this.valid&&(this.width=Math.round(this.width*e)/t,this.height=Math.round(this.height*e)/t,this.emit("update",this)),this._refreshPOT()),this}setResource(t){if(this.resource===t)return this;if(this.resource)throw new Error("Resource can be set only once");return t.bind(this),this.resource=t,this}update(){this.valid?(this.dirtyId++,this.dirtyStyleId++,this.emit("update",this)):this.width>0&&this.height>0&&(this.valid=!0,this.emit("loaded",this),this.emit("update",this))}onError(t){this.emit("error",this,t)}destroy(){this.resource&&(this.resource.unbind(this),this.resource.internal&&this.resource.destroy(),this.resource=null),this.cacheId&&(delete cp[this.cacheId],delete up[this.cacheId],this.cacheId=null),this.valid=!1,this.dispose(),t.removeFromCache(this),this.textureCacheIds=null,this.destroyed=!0,this.emit("destroyed",this),this.removeAllListeners()}dispose(){this.emit("dispose",this)}castToBaseTexture(){return this}static from(e,i,r=ph.STRICT_TEXTURE_CACHE){const s="string"==typeof e;let n=null;if(s)n=e;else{if(!e._pixiId){const t=i?.pixiIdPrefix||"pixiid";e._pixiId=`${t}_${op()}`}n=e._pixiId}let o=cp[n];if(s&&r&&!o)throw new Error(`The cacheId "${n}" does not exist in BaseTextureCache.`);return o||(o=new t(e,i),o.cacheId=n,t.addToCache(o,n)),o}static fromBuffer(e,i,r,s){e=e||new Float32Array(i*r*4);const n=new Lp(e,{width:i,height:r,...s?.resourceOptions});let o,a;return e instanceof Float32Array?(o=Ql.RGBA,a=eh.FLOAT):e instanceof Int32Array?(o=Ql.RGBA_INTEGER,a=eh.INT):e instanceof Uint32Array?(o=Ql.RGBA_INTEGER,a=eh.UNSIGNED_INT):e instanceof Int16Array?(o=Ql.RGBA_INTEGER,a=eh.SHORT):e instanceof Uint16Array?(o=Ql.RGBA_INTEGER,a=eh.UNSIGNED_SHORT):e instanceof Int8Array?(o=Ql.RGBA,a=eh.BYTE):(o=Ql.RGBA,a=eh.UNSIGNED_BYTE),n.internal=!0,new t(n,Object.assign({},Rp,{type:a,format:o},s))}static addToCache(t,e){e&&(t.textureCacheIds.includes(e)||t.textureCacheIds.push(e),cp[e]&&cp[e]!==t&&console.warn(`BaseTexture added to the cache with an id [${e}] that already had an entry`),cp[e]=t)}static removeFromCache(t){if("string"==typeof t){const e=cp[t];if(e){const i=e.textureCacheIds.indexOf(t);return i>-1&&e.textureCacheIds.splice(i,1),delete cp[t],e}}else if(t?.textureCacheIds){for(let e=0;e<t.textureCacheIds.length;++e)delete cp[t.textureCacheIds[e]];return t.textureCacheIds.length=0,t}return null}};kp.defaultOptions={mipmap:nh.POW2,anisotropicLevel:0,scaleMode:rh.LINEAR,wrapMode:sh.CLAMP,alphaMode:oh.UNPACK,target:th.TEXTURE_2D,format:Ql.RGBA,type:eh.UNSIGNED_BYTE},kp._globalBatch=0;let Bp=kp;class Fp{constructor(){this.texArray=null,this.blend=0,this.type=Zl.TRIANGLES,this.start=0,this.size=0,this.data=null}}let Dp=0;class Up{constructor(t,e=!0,i=!1){this.data=t||new Float32Array(1),this._glBuffers={},this._updateID=0,this.index=i,this.static=e,this.id=Dp++,this.disposeRunner=new Op("disposeBuffer")}update(t){t instanceof Array&&(t=new Float32Array(t)),this.data=t||this.data,this._updateID++}dispose(){this.disposeRunner.emit(this,!1)}destroy(){this.dispose(),this.data=null}set index(t){this.type=t?dh.ELEMENT_ARRAY_BUFFER:dh.ARRAY_BUFFER}get index(){return this.type===dh.ELEMENT_ARRAY_BUFFER}static from(t){return t instanceof Array&&(t=new Float32Array(t)),new Up(t)}}class Gp{constructor(t,e=0,i=!1,r=eh.FLOAT,s,n,o,a=1){this.buffer=t,this.size=e,this.normalized=i,this.type=r,this.stride=s,this.start=n,this.instance=o,this.divisor=a}destroy(){this.buffer=null}static from(t,e,i,r,s){return new Gp(t,e,i,r,s)}}const Xp={Float32Array:Float32Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Uint8Array:Uint8Array};const Wp={5126:4,5123:2,5121:1};let Yp=0;const Hp={Float32Array:Float32Array,Uint32Array:Uint32Array,Int32Array:Int32Array,Uint8Array:Uint8Array,Uint16Array:Uint16Array};class $p{constructor(t=[],e={}){this.buffers=t,this.indexBuffer=null,this.attributes=e,this.glVertexArrayObjects={},this.id=Yp++,this.instanced=!1,this.instanceCount=1,this.disposeRunner=new Op("disposeGeometry"),this.refCount=0}addAttribute(t,e,i=0,r=!1,s,n,o,a=!1){if(!e)throw new Error("You must pass a buffer when creating an attribute");e instanceof Up||(e instanceof Array&&(e=new Float32Array(e)),e=new Up(e));const l=t.split("|");if(l.length>1){for(let t=0;t<l.length;t++)this.addAttribute(l[t],e,i,r,s);return this}let h=this.buffers.indexOf(e);return-1===h&&(this.buffers.push(e),h=this.buffers.length-1),this.attributes[t]=new Gp(h,i,r,s,n,o,a),this.instanced=this.instanced||a,this}getAttribute(t){return this.attributes[t]}getBuffer(t){return this.buffers[this.getAttribute(t).buffer]}addIndex(t){return t instanceof Up||(t instanceof Array&&(t=new Uint16Array(t)),t=new Up(t)),t.type=dh.ELEMENT_ARRAY_BUFFER,this.indexBuffer=t,this.buffers.includes(t)||this.buffers.push(t),this}getIndex(){return this.indexBuffer}interleave(){if(1===this.buffers.length||2===this.buffers.length&&this.indexBuffer)return this;const t=[],e=[],i=new Up;let r;for(r in this.attributes){const i=this.attributes[r],s=this.buffers[i.buffer];t.push(s.data),e.push(i.size*Wp[i.type]/4),i.buffer=0}for(i.data=function(t,e){let i=0,r=0;const s={};for(let l=0;l<t.length;l++)r+=e[l],i+=t[l].length;const n=new ArrayBuffer(4*i);let o=null,a=0;for(let l=0;l<t.length;l++){const i=e[l],h=t[l],u=Zd(h);s[u]||(s[u]=new Xp[u](n)),o=s[u];for(let t=0;t<h.length;t++)o[(t/i|0)*r+a+t%i]=h[t];a+=i}return new Float32Array(n)}(t,e),r=0;r<this.buffers.length;r++)this.buffers[r]!==this.indexBuffer&&this.buffers[r].destroy();return this.buffers=[i],this.indexBuffer&&this.buffers.push(this.indexBuffer),this}getSize(){for(const t in this.attributes){const e=this.attributes[t];return this.buffers[e.buffer].data.length/(e.stride/4||e.size)}return 0}dispose(){this.disposeRunner.emit(this,!1)}destroy(){this.dispose(),this.buffers=null,this.indexBuffer=null,this.attributes=null}clone(){const t=new $p;for(let e=0;e<this.buffers.length;e++)t.buffers[e]=new Up(this.buffers[e].data.slice(0));for(const e in this.attributes){const i=this.attributes[e];t.attributes[e]=new Gp(i.buffer,i.size,i.normalized,i.type,i.stride,i.start,i.instance)}return this.indexBuffer&&(t.indexBuffer=t.buffers[this.buffers.indexOf(this.indexBuffer)],t.indexBuffer.type=dh.ELEMENT_ARRAY_BUFFER),t}static merge(t){const e=new $p,i=[],r=[],s=[];let n;for(let o=0;o<t.length;o++){n=t[o];for(let t=0;t<n.buffers.length;t++)r[t]=r[t]||0,r[t]+=n.buffers[t].data.length,s[t]=0}for(let o=0;o<n.buffers.length;o++)i[o]=new(Hp[Zd(n.buffers[o].data)])(r[o]),e.buffers[o]=new Up(i[o]);for(let o=0;o<t.length;o++){n=t[o];for(let t=0;t<n.buffers.length;t++)i[t].set(n.buffers[t].data,s[t]),s[t]+=n.buffers[t].data.length}if(e.attributes=n.attributes,n.indexBuffer){e.indexBuffer=e.buffers[n.buffers.indexOf(n.indexBuffer)],e.indexBuffer.type=dh.ELEMENT_ARRAY_BUFFER;let i=0,r=0,s=0,o=0;for(let t=0;t<n.buffers.length;t++)if(n.buffers[t]!==n.indexBuffer){o=t;break}for(const t in n.attributes){const e=n.attributes[t];(0|e.buffer)===o&&(r+=e.size*Wp[e.type]/4)}for(let n=0;n<t.length;n++){const a=t[n].indexBuffer.data;for(let t=0;t<a.length;t++)e.indexBuffer.data[t+s]+=i;i+=t[n].buffers[o].data.length/r,s+=a.length}}return e}}class jp extends $p{constructor(t=!1){super(),this._buffer=new Up(null,t,!1),this._indexBuffer=new Up(null,t,!0),this.addAttribute("aVertexPosition",this._buffer,2,!1,eh.FLOAT).addAttribute("aTextureCoord",this._buffer,2,!1,eh.FLOAT).addAttribute("aColor",this._buffer,4,!0,eh.UNSIGNED_BYTE).addAttribute("aTextureId",this._buffer,1,!0,eh.FLOAT).addIndex(this._indexBuffer)}}const zp=2*Math.PI,Vp=180/Math.PI,qp=Math.PI/180;var Jp=/* @__PURE__ */(t=>(t[t.POLY=0]="POLY",t[t.RECT=1]="RECT",t[t.CIRC=2]="CIRC",t[t.ELIP=3]="ELIP",t[t.RREC=4]="RREC",t))(Jp||{});class Kp{constructor(t=0,e=0){this.x=0,this.y=0,this.x=t,this.y=e}clone(){return new Kp(this.x,this.y)}copyFrom(t){return this.set(t.x,t.y),this}copyTo(t){return t.set(this.x,this.y),t}equals(t){return t.x===this.x&&t.y===this.y}set(t=0,e=t){return this.x=t,this.y=e,this}}Kp.prototype.toString=function(){return`[@pixi/math:Point x=${this.x} y=${this.y}]`};const Zp=[new Kp,new Kp,new Kp,new Kp];class Qp{constructor(t=0,e=0,i=0,r=0){this.x=Number(t),this.y=Number(e),this.width=Number(i),this.height=Number(r),this.type=Jp.RECT}get left(){return this.x}get right(){return this.x+this.width}get top(){return this.y}get bottom(){return this.y+this.height}static get EMPTY(){return new Qp(0,0,0,0)}clone(){return new Qp(this.x,this.y,this.width,this.height)}copyFrom(t){return this.x=t.x,this.y=t.y,this.width=t.width,this.height=t.height,this}copyTo(t){return t.x=this.x,t.y=this.y,t.width=this.width,t.height=this.height,t}contains(t,e){return!(this.width<=0||this.height<=0)&&(t>=this.x&&t<this.x+this.width&&e>=this.y&&e<this.y+this.height)}intersects(t,e){if(!e){const e=this.x<t.x?t.x:this.x;if((this.right>t.right?t.right:this.right)<=e)return!1;const i=this.y<t.y?t.y:this.y;return(this.bottom>t.bottom?t.bottom:this.bottom)>i}const i=this.left,r=this.right,s=this.top,n=this.bottom;if(r<=i||n<=s)return!1;const o=Zp[0].set(t.left,t.top),a=Zp[1].set(t.left,t.bottom),l=Zp[2].set(t.right,t.top),h=Zp[3].set(t.right,t.bottom);if(l.x<=o.x||a.y<=o.y)return!1;const u=Math.sign(e.a*e.d-e.b*e.c);if(0===u||(e.apply(o,o),e.apply(a,a),e.apply(l,l),e.apply(h,h),Math.max(o.x,a.x,l.x,h.x)<=i||Math.min(o.x,a.x,l.x,h.x)>=r||Math.max(o.y,a.y,l.y,h.y)<=s||Math.min(o.y,a.y,l.y,h.y)>=n))return!1;const c=u*(a.y-o.y),d=u*(o.x-a.x),p=c*i+d*s,f=c*r+d*s,m=c*i+d*n,g=c*r+d*n;if(Math.max(p,f,m,g)<=c*o.x+d*o.y||Math.min(p,f,m,g)>=c*h.x+d*h.y)return!1;const y=u*(o.y-l.y),v=u*(l.x-o.x),x=y*i+v*s,b=y*r+v*s,_=y*i+v*n,w=y*r+v*n;return!(Math.max(x,b,_,w)<=y*o.x+v*o.y||Math.min(x,b,_,w)>=y*h.x+v*h.y)}pad(t=0,e=t){return this.x-=t,this.y-=e,this.width+=2*t,this.height+=2*e,this}fit(t){const e=Math.max(this.x,t.x),i=Math.min(this.x+this.width,t.x+t.width),r=Math.max(this.y,t.y),s=Math.min(this.y+this.height,t.y+t.height);return this.x=e,this.width=Math.max(i-e,0),this.y=r,this.height=Math.max(s-r,0),this}ceil(t=1,e=.001){const i=Math.ceil((this.x+this.width-e)*t)/t,r=Math.ceil((this.y+this.height-e)*t)/t;return this.x=Math.floor((this.x+e)*t)/t,this.y=Math.floor((this.y+e)*t)/t,this.width=i-this.x,this.height=r-this.y,this}enlarge(t){const e=Math.min(this.x,t.x),i=Math.max(this.x+this.width,t.x+t.width),r=Math.min(this.y,t.y),s=Math.max(this.y+this.height,t.y+t.height);return this.x=e,this.width=i-e,this.y=r,this.height=s-r,this}}Qp.prototype.toString=function(){return`[@pixi/math:Rectangle x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`};class tf{constructor(t=0,e=0,i=0){this.x=t,this.y=e,this.radius=i,this.type=Jp.CIRC}clone(){return new tf(this.x,this.y,this.radius)}contains(t,e){if(this.radius<=0)return!1;const i=this.radius*this.radius;let r=this.x-t,s=this.y-e;return r*=r,s*=s,r+s<=i}getBounds(){return new Qp(this.x-this.radius,this.y-this.radius,2*this.radius,2*this.radius)}}tf.prototype.toString=function(){return`[@pixi/math:Circle x=${this.x} y=${this.y} radius=${this.radius}]`};class ef{constructor(t=0,e=0,i=0,r=0){this.x=t,this.y=e,this.width=i,this.height=r,this.type=Jp.ELIP}clone(){return new ef(this.x,this.y,this.width,this.height)}contains(t,e){if(this.width<=0||this.height<=0)return!1;let i=(t-this.x)/this.width,r=(e-this.y)/this.height;return i*=i,r*=r,i+r<=1}getBounds(){return new Qp(this.x-this.width,this.y-this.height,this.width,this.height)}}ef.prototype.toString=function(){return`[@pixi/math:Ellipse x=${this.x} y=${this.y} width=${this.width} height=${this.height}]`};class rf{constructor(...t){let e=Array.isArray(t[0])?t[0]:t;if("number"!=typeof e[0]){const t=[];for(let i=0,r=e.length;i<r;i++)t.push(e[i].x,e[i].y);e=t}this.points=e,this.type=Jp.POLY,this.closeStroke=!0}clone(){const t=this.points.slice(),e=new rf(t);return e.closeStroke=this.closeStroke,e}contains(t,e){let i=!1;const r=this.points.length/2;for(let s=0,n=r-1;s<r;n=s++){const r=this.points[2*s],o=this.points[2*s+1],a=this.points[2*n],l=this.points[2*n+1];o>e!=l>e&&t<(e-o)/(l-o)*(a-r)+r&&(i=!i)}return i}}rf.prototype.toString=function(){return`[@pixi/math:PolygoncloseStroke=${this.closeStroke}points=${this.points.reduce((t,e)=>`${t}, ${e}`,"")}]`};class sf{constructor(t=0,e=0,i=0,r=0,s=20){this.x=t,this.y=e,this.width=i,this.height=r,this.radius=s,this.type=Jp.RREC}clone(){return new sf(this.x,this.y,this.width,this.height,this.radius)}contains(t,e){if(this.width<=0||this.height<=0)return!1;if(t>=this.x&&t<=this.x+this.width&&e>=this.y&&e<=this.y+this.height){const i=Math.max(0,Math.min(this.radius,Math.min(this.width,this.height)/2));if(e>=this.y+i&&e<=this.y+this.height-i||t>=this.x+i&&t<=this.x+this.width-i)return!0;let r=t-(this.x+i),s=e-(this.y+i);const n=i*i;if(r*r+s*s<=n||(r=t-(this.x+this.width-i),r*r+s*s<=n)||(s=e-(this.y+this.height-i),r*r+s*s<=n)||(r=t-(this.x+i),r*r+s*s<=n))return!0}return!1}}sf.prototype.toString=function(){return`[@pixi/math:RoundedRectangle x=${this.x} y=${this.y}width=${this.width} height=${this.height} radius=${this.radius}]`};class nf{constructor(t=1,e=0,i=0,r=1,s=0,n=0){this.array=null,this.a=t,this.b=e,this.c=i,this.d=r,this.tx=s,this.ty=n}fromArray(t){this.a=t[0],this.b=t[1],this.c=t[3],this.d=t[4],this.tx=t[2],this.ty=t[5]}set(t,e,i,r,s,n){return this.a=t,this.b=e,this.c=i,this.d=r,this.tx=s,this.ty=n,this}toArray(t,e){this.array||(this.array=new Float32Array(9));const i=e||this.array;return t?(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(t,e){e=e||new Kp;const i=t.x,r=t.y;return e.x=this.a*i+this.c*r+this.tx,e.y=this.b*i+this.d*r+this.ty,e}applyInverse(t,e){e=e||new Kp;const i=1/(this.a*this.d+this.c*-this.b),r=t.x,s=t.y;return e.x=this.d*i*r+-this.c*i*s+(this.ty*this.c-this.tx*this.d)*i,e.y=this.a*i*s+-this.b*i*r+(-this.ty*this.a+this.tx*this.b)*i,e}translate(t,e){return this.tx+=t,this.ty+=e,this}scale(t,e){return this.a*=t,this.d*=e,this.c*=t,this.b*=e,this.tx*=t,this.ty*=e,this}rotate(t){const e=Math.cos(t),i=Math.sin(t),r=this.a,s=this.c,n=this.tx;return this.a=r*e-this.b*i,this.b=r*i+this.b*e,this.c=s*e-this.d*i,this.d=s*i+this.d*e,this.tx=n*e-this.ty*i,this.ty=n*i+this.ty*e,this}append(t){const e=this.a,i=this.b,r=this.c,s=this.d;return this.a=t.a*e+t.b*r,this.b=t.a*i+t.b*s,this.c=t.c*e+t.d*r,this.d=t.c*i+t.d*s,this.tx=t.tx*e+t.ty*r+this.tx,this.ty=t.tx*i+t.ty*s+this.ty,this}setTransform(t,e,i,r,s,n,o,a,l){return this.a=Math.cos(o+l)*s,this.b=Math.sin(o+l)*s,this.c=-Math.sin(o-a)*n,this.d=Math.cos(o-a)*n,this.tx=t-(i*this.a+r*this.c),this.ty=e-(i*this.b+r*this.d),this}prepend(t){const e=this.tx;if(1!==t.a||0!==t.b||0!==t.c||1!==t.d){const e=this.a,i=this.c;this.a=e*t.a+this.b*t.c,this.b=e*t.b+this.b*t.d,this.c=i*t.a+this.d*t.c,this.d=i*t.b+this.d*t.d}return this.tx=e*t.a+this.ty*t.c+t.tx,this.ty=e*t.b+this.ty*t.d+t.ty,this}decompose(t){const e=this.a,i=this.b,r=this.c,s=this.d,n=t.pivot,o=-Math.atan2(-r,s),a=Math.atan2(i,e),l=Math.abs(o+a);return l<1e-5||Math.abs(zp-l)<1e-5?(t.rotation=a,t.skew.x=t.skew.y=0):(t.rotation=0,t.skew.x=o,t.skew.y=a),t.scale.x=Math.sqrt(e*e+i*i),t.scale.y=Math.sqrt(r*r+s*s),t.position.x=this.tx+(n.x*e+n.y*r),t.position.y=this.ty+(n.x*i+n.y*s),t}invert(){const t=this.a,e=this.b,i=this.c,r=this.d,s=this.tx,n=t*r-e*i;return this.a=r/n,this.b=-e/n,this.c=-i/n,this.d=t/n,this.tx=(i*this.ty-r*s)/n,this.ty=-(t*this.ty-e*s)/n,this}identity(){return this.a=1,this.b=0,this.c=0,this.d=1,this.tx=0,this.ty=0,this}clone(){const t=new nf;return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyTo(t){return t.a=this.a,t.b=this.b,t.c=this.c,t.d=this.d,t.tx=this.tx,t.ty=this.ty,t}copyFrom(t){return this.a=t.a,this.b=t.b,this.c=t.c,this.d=t.d,this.tx=t.tx,this.ty=t.ty,this}static get IDENTITY(){return new nf}static get TEMP_MATRIX(){return new nf}}nf.prototype.toString=function(){return`[@pixi/math:Matrix a=${this.a} b=${this.b} c=${this.c} d=${this.d} tx=${this.tx} ty=${this.ty}]`};const of=[1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1,0,1],af=[0,1,1,1,0,-1,-1,-1,0,1,1,1,0,-1,-1,-1],lf=[0,-1,-1,-1,0,1,1,1,0,1,1,1,0,-1,-1,-1],hf=[1,1,0,-1,-1,-1,0,1,-1,-1,0,1,1,1,0,-1],uf=[],cf=[],df=Math.sign;!function(){for(let t=0;t<16;t++){const e=[];uf.push(e);for(let i=0;i<16;i++){const r=df(of[t]*of[i]+lf[t]*af[i]),s=df(af[t]*of[i]+hf[t]*af[i]),n=df(of[t]*lf[i]+lf[t]*hf[i]),o=df(af[t]*lf[i]+hf[t]*hf[i]);for(let t=0;t<16;t++)if(of[t]===r&&af[t]===s&&lf[t]===n&&hf[t]===o){e.push(t);break}}}for(let t=0;t<16;t++){const e=new nf;e.set(of[t],af[t],lf[t],hf[t],0,0),cf.push(e)}}();const pf={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:t=>of[t],uY:t=>af[t],vX:t=>lf[t],vY:t=>hf[t],inv:t=>8&t?15&t:7&-t,add:(t,e)=>uf[t][e],sub:(t,e)=>uf[t][pf.inv(e)],rotate180:t=>4^t,isVertical:t=>2==(3&t),byDirection:(t,e)=>2*Math.abs(t)<=Math.abs(e)?e>=0?pf.S:pf.N:2*Math.abs(e)<=Math.abs(t)?t>0?pf.E:pf.W:e>0?t>0?pf.SE:pf.SW:t>0?pf.NE:pf.NW,matrixAppendRotationInv:(t,e,i=0,r=0)=>{const s=cf[pf.inv(e)];s.tx=i,s.ty=r,t.append(s)}};class ff{constructor(t,e,i=0,r=0){this._x=i,this._y=r,this.cb=t,this.scope=e}clone(t=this.cb,e=this.scope){return new ff(t,e,this._x,this._y)}set(t=0,e=t){return(this._x!==t||this._y!==e)&&(this._x=t,this._y=e,this.cb.call(this.scope)),this}copyFrom(t){return(this._x!==t.x||this._y!==t.y)&&(this._x=t.x,this._y=t.y,this.cb.call(this.scope)),this}copyTo(t){return t.set(this._x,this._y),t}equals(t){return t.x===this._x&&t.y===this._y}get x(){return this._x}set x(t){this._x!==t&&(this._x=t,this.cb.call(this.scope))}get y(){return this._y}set y(t){this._y!==t&&(this._y=t,this.cb.call(this.scope))}}ff.prototype.toString=function(){return`[@pixi/math:ObservablePoint x=${this.x} y=${this.y} scope=${this.scope}]`};const mf=class{constructor(){this.worldTransform=new nf,this.localTransform=new nf,this.position=new ff(this.onChange,this,0,0),this.scale=new ff(this.onChange,this,1,1),this.pivot=new ff(this.onChange,this,0,0),this.skew=new ff(this.updateSkew,this,0,0),this._rotation=0,this._cx=1,this._sx=0,this._cy=0,this._sy=1,this._localID=0,this._currentLocalID=0,this._worldID=0,this._parentID=0}onChange(){this._localID++}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._localID++}updateLocalTransform(){const t=this.localTransform;this._localID!==this._currentLocalID&&(t.a=this._cx*this.scale.x,t.b=this._sx*this.scale.x,t.c=this._cy*this.scale.y,t.d=this._sy*this.scale.y,t.tx=this.position.x-(this.pivot.x*t.a+this.pivot.y*t.c),t.ty=this.position.y-(this.pivot.x*t.b+this.pivot.y*t.d),this._currentLocalID=this._localID,this._parentID=-1)}updateTransform(t){const e=this.localTransform;if(this._localID!==this._currentLocalID&&(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._currentLocalID=this._localID,this._parentID=-1),this._parentID!==t._worldID){const i=t.worldTransform,r=this.worldTransform;r.a=e.a*i.a+e.b*i.c,r.b=e.a*i.b+e.b*i.d,r.c=e.c*i.a+e.d*i.c,r.d=e.c*i.b+e.d*i.d,r.tx=e.tx*i.a+e.ty*i.c+i.tx,r.ty=e.tx*i.b+e.ty*i.d+i.ty,this._parentID=t._worldID,this._worldID++}}setFromMatrix(t){t.decompose(this),this._localID++}get rotation(){return this._rotation}set rotation(t){this._rotation!==t&&(this._rotation=t,this.updateSkew())}};mf.IDENTITY=new mf;let gf=mf;gf.prototype.toString=function(){return`[@pixi/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}) ]`};function yf(t,e,i){const r=t.createShader(e);return t.shaderSource(r,i),t.compileShader(r),r}function vf(t){const e=new Array(t);for(let i=0;i<e.length;i++)e[i]=!1;return e}function xf(t,e){switch(t){case"float":case"int":case"uint":case"sampler2D":case"sampler2DArray":return 0;case"vec2":return new Float32Array(2*e);case"vec3":return new Float32Array(3*e);case"vec4":return new Float32Array(4*e);case"ivec2":return new Int32Array(2*e);case"ivec3":return new Int32Array(3*e);case"ivec4":return new Int32Array(4*e);case"uvec2":return new Uint32Array(2*e);case"uvec3":return new Uint32Array(3*e);case"uvec4":return new Uint32Array(4*e);case"bool":return!1;case"bvec2":return vf(2*e);case"bvec3":return vf(3*e);case"bvec4":return vf(4*e);case"mat2":return new Float32Array([1,0,0,1]);case"mat3":return new Float32Array([1,0,0,0,1,0,0,0,1]);case"mat4":return new Float32Array([1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1])}return null}const bf=[{test:t=>"float"===t.type&&1===t.size&&!t.isArray,code:t=>`\n if(uv["${t}"] !== ud["${t}"].value)\n {\n ud["${t}"].value = uv["${t}"]\n gl.uniform1f(ud["${t}"].location, uv["${t}"])\n }\n `},{test:(t,e)=>!("sampler2D"!==t.type&&"samplerCube"!==t.type&&"sampler2DArray"!==t.type||1!==t.size||t.isArray||null!=e&&void 0===e.castToBaseTexture),code:t=>`t = syncData.textureCount++;\n\n renderer.texture.bind(uv["${t}"], t);\n\n if(ud["${t}"].value !== t)\n {\n ud["${t}"].value = t;\n gl.uniform1i(ud["${t}"].location, t);\n; // eslint-disable-line max-len\n }`},{test:(t,e)=>"mat3"===t.type&&1===t.size&&!t.isArray&&void 0!==e.a,code:t=>`\n gl.uniformMatrix3fv(ud["${t}"].location, false, uv["${t}"].toArray(true));\n `,codeUbo:t=>`\n var ${t}_matrix = uv.${t}.toArray(true);\n\n data[offset] = ${t}_matrix[0];\n data[offset+1] = ${t}_matrix[1];\n data[offset+2] = ${t}_matrix[2];\n \n data[offset + 4] = ${t}_matrix[3];\n data[offset + 5] = ${t}_matrix[4];\n data[offset + 6] = ${t}_matrix[5];\n \n data[offset + 8] = ${t}_matrix[6];\n data[offset + 9] = ${t}_matrix[7];\n data[offset + 10] = ${t}_matrix[8];\n `},{test:(t,e)=>"vec2"===t.type&&1===t.size&&!t.isArray&&void 0!==e.x,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.x || cv[1] !== v.y)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n gl.uniform2f(ud["${t}"].location, v.x, v.y);\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n `},{test:t=>"vec2"===t.type&&1===t.size&&!t.isArray,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n gl.uniform2f(ud["${t}"].location, v[0], v[1]);\n }\n `},{test:(t,e)=>"vec4"===t.type&&1===t.size&&!t.isArray&&void 0!==e.width,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.x || cv[1] !== v.y || cv[2] !== v.width || cv[3] !== v.height)\n {\n cv[0] = v.x;\n cv[1] = v.y;\n cv[2] = v.width;\n cv[3] = v.height;\n gl.uniform4f(ud["${t}"].location, v.x, v.y, v.width, v.height)\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.x;\n data[offset+1] = v.y;\n data[offset+2] = v.width;\n data[offset+3] = v.height;\n `},{test:(t,e)=>"vec4"===t.type&&1===t.size&&!t.isArray&&void 0!==e.red,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.alpha)\n {\n cv[0] = v.red;\n cv[1] = v.green;\n cv[2] = v.blue;\n cv[3] = v.alpha;\n gl.uniform4f(ud["${t}"].location, v.red, v.green, v.blue, v.alpha)\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.red;\n data[offset+1] = v.green;\n data[offset+2] = v.blue;\n data[offset+3] = v.alpha;\n `},{test:(t,e)=>"vec3"===t.type&&1===t.size&&!t.isArray&&void 0!==e.red,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v.red || cv[1] !== v.green || cv[2] !== v.blue || cv[3] !== v.a)\n {\n cv[0] = v.red;\n cv[1] = v.green;\n cv[2] = v.blue;\n \n gl.uniform3f(ud["${t}"].location, v.red, v.green, v.blue)\n }`,codeUbo:t=>`\n v = uv.${t};\n\n data[offset] = v.red;\n data[offset+1] = v.green;\n data[offset+2] = v.blue;\n `},{test:t=>"vec4"===t.type&&1===t.size&&!t.isArray,code:t=>`\n cv = ud["${t}"].value;\n v = uv["${t}"];\n\n if(cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(ud["${t}"].location, v[0], v[1], v[2], v[3])\n }`}],_f={float:"\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1f(location, v);\n }",vec2:"\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2f(location, v[0], v[1])\n }",vec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3f(location, v[0], v[1], v[2])\n }",vec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4f(location, v[0], v[1], v[2], v[3]);\n }",int:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",ivec2:"\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }",ivec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }",ivec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }",uint:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1ui(location, v);\n }",uvec2:"\n if (cv[0] !== v[0] || cv[1] !== v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2ui(location, v[0], v[1]);\n }",uvec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3ui(location, v[0], v[1], v[2]);\n }",uvec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4ui(location, v[0], v[1], v[2], v[3]);\n }",bool:"\n if (cv !== v)\n {\n cu.value = v;\n gl.uniform1i(location, v);\n }",bvec2:"\n if (cv[0] != v[0] || cv[1] != v[1])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n\n gl.uniform2i(location, v[0], v[1]);\n }",bvec3:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n\n gl.uniform3i(location, v[0], v[1], v[2]);\n }",bvec4:"\n if (cv[0] !== v[0] || cv[1] !== v[1] || cv[2] !== v[2] || cv[3] !== v[3])\n {\n cv[0] = v[0];\n cv[1] = v[1];\n cv[2] = v[2];\n cv[3] = v[3];\n\n gl.uniform4i(location, v[0], v[1], v[2], v[3]);\n }",mat2:"gl.uniformMatrix2fv(location, false, v)",mat3:"gl.uniformMatrix3fv(location, false, v)",mat4:"gl.uniformMatrix4fv(location, false, v)",sampler2D:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",samplerCube:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }",sampler2DArray:"\n if (cv !== v)\n {\n cu.value = v;\n\n gl.uniform1i(location, v);\n }"},wf={float:"gl.uniform1fv(location, v)",vec2:"gl.uniform2fv(location, v)",vec3:"gl.uniform3fv(location, v)",vec4:"gl.uniform4fv(location, v)",mat4:"gl.uniformMatrix4fv(location, false, v)",mat3:"gl.uniformMatrix3fv(location, false, v)",mat2:"gl.uniformMatrix2fv(location, false, v)",int:"gl.uniform1iv(location, v)",ivec2:"gl.uniform2iv(location, v)",ivec3:"gl.uniform3iv(location, v)",ivec4:"gl.uniform4iv(location, v)",uint:"gl.uniform1uiv(location, v)",uvec2:"gl.uniform2uiv(location, v)",uvec3:"gl.uniform3uiv(location, v)",uvec4:"gl.uniform4uiv(location, v)",bool:"gl.uniform1iv(location, v)",bvec2:"gl.uniform2iv(location, v)",bvec3:"gl.uniform3iv(location, v)",bvec4:"gl.uniform4iv(location, v)",sampler2D:"gl.uniform1iv(location, v)",samplerCube:"gl.uniform1iv(location, v)",sampler2DArray:"gl.uniform1iv(location, v)"};const Pf={};let Ef,Tf=Pf;function Af(){if(!Ef){Ef=hh.MEDIUM;const t=function(){if(Tf===Pf||Tf?.isContextLost()){const t=ph.ADAPTER.createCanvas();let e;ph.PREFER_ENV>=Vl.WEBGL2&&(e=t.getContext("webgl2",{})),e||(e=t.getContext("webgl",{})||t.getContext("experimental-webgl",{}),e?e.getExtension("WEBGL_draw_buffers"):e=null),Tf=e}return Tf}();if(t&&t.getShaderPrecisionFormat){const e=t.getShaderPrecisionFormat(t.FRAGMENT_SHADER,t.HIGH_FLOAT);e&&(Ef=e.precision?hh.HIGH:hh.MEDIUM)}}return Ef}function If(t,e){const i=t.getShaderSource(e).split("\n").map((t,e)=>`${e}: ${t}`),r=t.getShaderInfoLog(e),s=r.split("\n"),n={},o=s.map(t=>parseFloat(t.replace(/^ERROR\: 0\:([\d]+)\:.*$/,"$1"))).filter(t=>!(!t||n[t])&&(n[t]=!0,!0)),a=[""];o.forEach(t=>{i[t-1]=`%c${i[t-1]}%c`,a.push("background: #FF0000; color:#FFFFFF; font-size: 10px","font-size: 10px")});const l=i.join("\n");a[0]=l,console.error(r),console.groupCollapsed("click to view full shader code"),console.warn(...a),console.groupEnd()}const Sf={float:1,vec2:2,vec3:3,vec4:4,int:1,ivec2:2,ivec3:3,ivec4:4,uint:1,uvec2:2,uvec3:3,uvec4:4,bool:1,bvec2:2,bvec3:3,bvec4:4,mat2:4,mat3:9,mat4:16,sampler2D:1};function Cf(t){return Sf[t]}let Mf=null;const Of={FLOAT:"float",FLOAT_VEC2:"vec2",FLOAT_VEC3:"vec3",FLOAT_VEC4:"vec4",INT:"int",INT_VEC2:"ivec2",INT_VEC3:"ivec3",INT_VEC4:"ivec4",UNSIGNED_INT:"uint",UNSIGNED_INT_VEC2:"uvec2",UNSIGNED_INT_VEC3:"uvec3",UNSIGNED_INT_VEC4:"uvec4",BOOL:"bool",BOOL_VEC2:"bvec2",BOOL_VEC3:"bvec3",BOOL_VEC4:"bvec4",FLOAT_MAT2:"mat2",FLOAT_MAT3:"mat3",FLOAT_MAT4:"mat4",SAMPLER_2D:"sampler2D",INT_SAMPLER_2D:"sampler2D",UNSIGNED_INT_SAMPLER_2D:"sampler2D",SAMPLER_CUBE:"samplerCube",INT_SAMPLER_CUBE:"samplerCube",UNSIGNED_INT_SAMPLER_CUBE:"samplerCube",SAMPLER_2D_ARRAY:"sampler2DArray",INT_SAMPLER_2D_ARRAY:"sampler2DArray",UNSIGNED_INT_SAMPLER_2D_ARRAY:"sampler2DArray"};function Nf(t,e){if(!Mf){const e=Object.keys(Of);Mf={};for(let i=0;i<e.length;++i){const r=e[i];Mf[t[r]]=Of[r]}}return Mf[e]}function Lf(t,e,i){if("precision"!==t.substring(0,9)){let r=e;return e===hh.HIGH&&i!==hh.HIGH&&(r=hh.MEDIUM),`precision ${r} float;\n${t}`}return i!==hh.HIGH&&"precision highp"===t.substring(0,15)?t.replace("precision highp","precision mediump"):t}let Rf;let kf=0;const Bf={},Ff=class t{constructor(e,i,r="pixi-shader",s={}){this.extra={},this.id=kf++,this.vertexSrc=e||t.defaultVertexSrc,this.fragmentSrc=i||t.defaultFragmentSrc,this.vertexSrc=this.vertexSrc.trim(),this.fragmentSrc=this.fragmentSrc.trim(),this.extra=s,"#version"!==this.vertexSrc.substring(0,8)&&(r=r.replace(/\s+/g,"-"),Bf[r]?(Bf[r]++,r+=`-${Bf[r]}`):Bf[r]=1,this.vertexSrc=`#define SHADER_NAME ${r}\n${this.vertexSrc}`,this.fragmentSrc=`#define SHADER_NAME ${r}\n${this.fragmentSrc}`,this.vertexSrc=Lf(this.vertexSrc,t.defaultVertexPrecision,hh.HIGH),this.fragmentSrc=Lf(this.fragmentSrc,t.defaultFragmentPrecision,Af())),this.glPrograms={},this.syncUniforms=null}static get defaultVertexSrc(){return"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n vTextureCoord = aTextureCoord;\n}\n"}static get defaultFragmentSrc(){return"varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor *= texture2D(uSampler, vTextureCoord);\n}"}static from(e,i,r){const s=e+i;let n=hp[s];return n||(hp[s]=n=new t(e,i,r)),n}};Ff.defaultVertexPrecision=hh.HIGH,Ff.defaultFragmentPrecision=Oh.apple.device?hh.HIGH:hh.MEDIUM;let Df=Ff,Uf=0;class Gf{constructor(t,e,i){this.group=!0,this.syncUniforms={},this.dirtyId=0,this.id=Uf++,this.static=!!e,this.ubo=!!i,t instanceof Up?(this.buffer=t,this.buffer.type=dh.UNIFORM_BUFFER,this.autoManage=!1,this.ubo=!0):(this.uniforms=t,this.ubo&&(this.buffer=new Up(new Float32Array(1)),this.buffer.type=dh.UNIFORM_BUFFER,this.autoManage=!0))}update(){this.dirtyId++,!this.autoManage&&this.buffer&&this.buffer.update()}add(t,e,i){if(this.ubo)throw new Error("[UniformGroup] uniform groups in ubo mode cannot be modified, or have uniform groups nested in them");this.uniforms[t]=new Gf(e,i)}static from(t,e,i){return new Gf(t,e,i)}static uboFrom(t,e){return new Gf(t,e??!0,!0)}}class Xf{constructor(t,e){this.uniformBindCount=0,this.program=t,this.uniformGroup=e?e instanceof Gf?e:new Gf(e):new Gf({}),this.disposeRunner=new Op("disposeShader")}checkUniformExists(t,e){if(e.uniforms[t])return!0;for(const i in e.uniforms){const r=e.uniforms[i];if(!0===r.group&&this.checkUniformExists(t,r))return!0}return!1}destroy(){this.uniformGroup=null,this.disposeRunner.emit(this),this.disposeRunner.destroy()}get uniforms(){return this.uniformGroup.uniforms}static from(t,e,i){const r=Df.from(t,e);return new Xf(r,i)}}class Wf{constructor(t,e){if(this.vertexSrc=t,this.fragTemplate=e,this.programCache={},this.defaultGroupCache={},!e.includes("%count%"))throw new Error('Fragment template must contain "%count%".');if(!e.includes("%forloop%"))throw new Error('Fragment template must contain "%forloop%".')}generateShader(t){if(!this.programCache[t]){const e=new Int32Array(t);for(let r=0;r<t;r++)e[r]=r;this.defaultGroupCache[t]=Gf.from({uSamplers:e},!0);let i=this.fragTemplate;i=i.replace(/%count%/gi,`${t}`),i=i.replace(/%forloop%/gi,this.generateSampleSrc(t)),this.programCache[t]=new Df(this.vertexSrc,i)}const e={tint:new Float32Array([1,1,1,1]),translationMatrix:new nf,default:this.defaultGroupCache[t]};return new Xf(this.programCache[t],e)}generateSampleSrc(t){let e="";e+="\n",e+="\n";for(let i=0;i<t;i++)i>0&&(e+="\nelse "),i<t-1&&(e+=`if(vTextureId < ${i}.5)`),e+="\n{",e+=`\n\tcolor = texture2D(uSamplers[${i}], vTextureCoord);`,e+="\n}";return e+="\n",e+="\n",e}}class Yf{constructor(){this.elements=[],this.ids=[],this.count=0}clear(){for(let t=0;t<this.count;t++)this.elements[t]=null;this.count=0}}class Hf{constructor(t){this.renderer=t}flush(){}destroy(){this.renderer=null}start(){}stop(){this.flush()}render(t){}}const $f=class t extends Hf{constructor(e){super(e),this.setShaderGenerator(),this.geometryClass=jp,this.vertexSize=6,this.state=Sp.for2d(),this.size=4*t.defaultBatchSize,this._vertexCount=0,this._indexCount=0,this._bufferedElements=[],this._bufferedTextures=[],this._bufferSize=0,this._shader=null,this._packedGeometries=[],this._packedGeometryPoolSize=2,this._flushId=0,this._aBuffers={},this._iBuffers={},this.maxTextures=1,this.renderer.on("prerender",this.onPrerender,this),e.runners.contextChange.add(this),this._dcIndex=0,this._aIndex=0,this._iIndex=0,this._attributeBuffer=null,this._indexBuffer=null,this._tempBoundTextures=[]}static get defaultMaxTextures(){return this._defaultMaxTextures=this._defaultMaxTextures??function(t){let e=!0;const i=ph.ADAPTER.getNavigator();if(Oh.tablet||Oh.phone){if(Oh.apple.device){const t=i.userAgent.match(/OS (\d+)_(\d+)?/);t&&parseInt(t[1],10)<11&&(e=!1)}if(Oh.android.device){const t=i.userAgent.match(/Android\s([0-9.]*)/);t&&parseInt(t[1],10)<7&&(e=!1)}}return e?t:4}(32),this._defaultMaxTextures}static set defaultMaxTextures(t){this._defaultMaxTextures=t}static get canUploadSameBuffer(){return this._canUploadSameBuffer=this._canUploadSameBuffer??!Oh.apple.device,this._canUploadSameBuffer}static set canUploadSameBuffer(t){this._canUploadSameBuffer=t}get MAX_TEXTURES(){return dd("7.1.0","BatchRenderer#MAX_TEXTURES renamed to BatchRenderer#maxTextures"),this.maxTextures}static get defaultVertexSrc(){return"precision highp float;\nattribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\nattribute vec4 aColor;\nattribute float aTextureId;\n\nuniform mat3 projectionMatrix;\nuniform mat3 translationMatrix;\nuniform vec4 tint;\n\nvarying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\n\nvoid main(void){\n gl_Position = vec4((projectionMatrix * translationMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vTextureId = aTextureId;\n vColor = aColor * tint;\n}\n"}static get defaultFragmentTemplate(){return"varying vec2 vTextureCoord;\nvarying vec4 vColor;\nvarying float vTextureId;\nuniform sampler2D uSamplers[%count%];\n\nvoid main(void){\n vec4 color;\n %forloop%\n gl_FragColor = color * vColor;\n}\n"}setShaderGenerator({vertex:e=t.defaultVertexSrc,fragment:i=t.defaultFragmentTemplate}={}){this.shaderGenerator=new Wf(e,i)}contextChange(){const e=this.renderer.gl;ph.PREFER_ENV===Vl.WEBGL_LEGACY?this.maxTextures=1:(this.maxTextures=Math.min(e.getParameter(e.MAX_TEXTURE_IMAGE_UNITS),t.defaultMaxTextures),this.maxTextures=function(t,e){if(0===t)throw new Error("Invalid value of `0` passed to `checkMaxIfStatementsInShader`");const i=e.createShader(e.FRAGMENT_SHADER);for(;;){const r=Ap.replace(/%forloop%/gi,Ip(t));if(e.shaderSource(i,r),e.compileShader(i),e.getShaderParameter(i,e.COMPILE_STATUS))break;t=t/2|0}return t}(this.maxTextures,e)),this._shader=this.shaderGenerator.generateShader(this.maxTextures);for(let t=0;t<this._packedGeometryPoolSize;t++)this._packedGeometries[t]=new this.geometryClass;this.initFlushBuffers()}initFlushBuffers(){const{_drawCallPool:e,_textureArrayPool:i}=t,r=this.size/4,s=Math.floor(r/this.maxTextures)+1;for(;e.length<r;)e.push(new Fp);for(;i.length<s;)i.push(new Yf);for(let t=0;t<this.maxTextures;t++)this._tempBoundTextures[t]=null}onPrerender(){this._flushId=0}render(t){t._texture.valid&&(this._vertexCount+t.vertexData.length/2>this.size&&this.flush(),this._vertexCount+=t.vertexData.length/2,this._indexCount+=t.indices.length,this._bufferedTextures[this._bufferSize]=t._texture.baseTexture,this._bufferedElements[this._bufferSize++]=t)}buildTexturesAndDrawCalls(){const{_bufferedTextures:e,maxTextures:i}=this,r=t._textureArrayPool,s=this.renderer.batch,n=this._tempBoundTextures,o=this.renderer.textureGC.count;let a=++Bp._globalBatch,l=0,h=r[0],u=0;s.copyBoundTextures(n,i);for(let t=0;t<this._bufferSize;++t){const c=e[t];e[t]=null,c._batchEnabled!==a&&(h.count>=i&&(s.boundArray(h,n,a,i),this.buildDrawCalls(h,u,t),u=t,h=r[++l],++a),c._batchEnabled=a,c.touched=o,h.elements[h.count++]=c)}h.count>0&&(s.boundArray(h,n,a,i),this.buildDrawCalls(h,u,this._bufferSize),++l,++a);for(let t=0;t<n.length;t++)n[t]=null;Bp._globalBatch=a}buildDrawCalls(e,i,r){const{_bufferedElements:s,_attributeBuffer:n,_indexBuffer:o,vertexSize:a}=this,l=t._drawCallPool;let h=this._dcIndex,u=this._aIndex,c=this._iIndex,d=l[h];d.start=this._iIndex,d.texArray=e;for(let t=i;t<r;++t){const r=s[t],p=r._texture.baseTexture,f=Jd[p.alphaMode?1:0][r.blendMode];s[t]=null,i<t&&d.blend!==f&&(d.size=c-d.start,i=t,d=l[++h],d.texArray=e,d.start=c),this.packInterleavedGeometry(r,n,o,u,c),u+=r.vertexData.length/2*a,c+=r.indices.length,d.blend=f}i<r&&(d.size=c-d.start,++h),this._dcIndex=h,this._aIndex=u,this._iIndex=c}bindAndClearTexArray(t){const e=this.renderer.texture;for(let i=0;i<t.count;i++)e.bind(t.elements[i],t.ids[i]),t.elements[i]=null;t.count=0}updateGeometry(){const{_packedGeometries:e,_attributeBuffer:i,_indexBuffer:r}=this;t.canUploadSameBuffer?(e[this._flushId]._buffer.update(i.rawBinaryData),e[this._flushId]._indexBuffer.update(r),this.renderer.geometry.updateBuffers()):(this._packedGeometryPoolSize<=this._flushId&&(this._packedGeometryPoolSize++,e[this._flushId]=new this.geometryClass),e[this._flushId]._buffer.update(i.rawBinaryData),e[this._flushId]._indexBuffer.update(r),this.renderer.geometry.bind(e[this._flushId]),this.renderer.geometry.updateBuffers(),this._flushId++)}drawBatches(){const e=this._dcIndex,{gl:i,state:r}=this.renderer,s=t._drawCallPool;let n=null;for(let t=0;t<e;t++){const{texArray:e,type:o,size:a,start:l,blend:h}=s[t];n!==e&&(n=e,this.bindAndClearTexArray(e)),this.state.blendMode=h,r.set(this.state),i.drawElements(o,a,i.UNSIGNED_SHORT,2*l)}}flush(){0!==this._vertexCount&&(this._attributeBuffer=this.getAttributeBuffer(this._vertexCount),this._indexBuffer=this.getIndexBuffer(this._indexCount),this._aIndex=0,this._iIndex=0,this._dcIndex=0,this.buildTexturesAndDrawCalls(),this.updateGeometry(),this.drawBatches(),this._bufferSize=0,this._vertexCount=0,this._indexCount=0)}start(){this.renderer.state.set(this.state),this.renderer.texture.ensureSamplerType(this.maxTextures),this.renderer.shader.bind(this._shader),t.canUploadSameBuffer&&this.renderer.geometry.bind(this._packedGeometries[this._flushId])}stop(){this.flush()}destroy(){for(let t=0;t<this._packedGeometryPoolSize;t++)this._packedGeometries[t]&&this._packedGeometries[t].destroy();this.renderer.off("prerender",this.onPrerender,this),this._aBuffers=null,this._iBuffers=null,this._packedGeometries=null,this._attributeBuffer=null,this._indexBuffer=null,this._shader&&(this._shader.destroy(),this._shader=null),super.destroy()}getAttributeBuffer(t){const e=tp(Math.ceil(t/8)),i=ip(e),r=8*e;this._aBuffers.length<=i&&(this._iBuffers.length=i+1);let s=this._aBuffers[r];return s||(this._aBuffers[r]=s=new Tp(r*this.vertexSize*4)),s}getIndexBuffer(t){const e=tp(Math.ceil(t/12)),i=ip(e),r=12*e;this._iBuffers.length<=i&&(this._iBuffers.length=i+1);let s=this._iBuffers[i];return s||(this._iBuffers[i]=s=new Uint16Array(r)),s}packInterleavedGeometry(t,e,i,r,s){const{uint32View:n,float32View:o}=e,a=r/this.vertexSize,l=t.uvs,h=t.indices,u=t.vertexData,c=t._texture.baseTexture._batchLocation,d=Math.min(t.worldAlpha,1),p=qd.shared.setValue(t._tintRGB).toPremultiplied(d,t._texture.baseTexture.alphaMode>0);for(let f=0;f<u.length;f+=2)o[r++]=u[f],o[r++]=u[f+1],o[r++]=l[f],o[r++]=l[f+1],n[r++]=p,o[r++]=c;for(let f=0;f<h.length;f++)i[s++]=a+h[f]}};$f.defaultBatchSize=4096,$f.extension={name:"batch",type:_p.RendererPlugin},$f._drawCallPool=[],$f._textureArrayPool=[];let jf=$f;Ep.add(jf);const zf=class t extends Xf{constructor(e,i,r){super(Df.from(e||t.defaultVertexSrc,i||t.defaultFragmentSrc),r),this.padding=0,this.resolution=t.defaultResolution,this.multisample=t.defaultMultisample,this.enabled=!0,this.autoFit=!0,this.state=new Sp}apply(t,e,i,r,s){t.applyFilter(this,e,i,r)}get blendMode(){return this.state.blendMode}set blendMode(t){this.state.blendMode=t}get resolution(){return this._resolution}set resolution(t){this._resolution=t}static get defaultVertexSrc(){return"attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n"}static get defaultFragmentSrc(){return"varying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\n\nvoid main(void){\n gl_FragColor = texture2D(uSampler, vTextureCoord);\n}\n"}};zf.defaultResolution=1,zf.defaultMultisample=ch.NONE;let Vf=zf;class qf{constructor(){this.clearBeforeRender=!0,this._backgroundColor=new qd(0),this.alpha=1}init(t){this.clearBeforeRender=t.clearBeforeRender;const{backgroundColor:e,background:i,backgroundAlpha:r}=t,s=i??e;void 0!==s&&(this.color=s),this.alpha=r}get color(){return this._backgroundColor.value}set color(t){this._backgroundColor.setValue(t)}get alpha(){return this._backgroundColor.alpha}set alpha(t){this._backgroundColor.setAlpha(t)}get backgroundColor(){return this._backgroundColor}destroy(){}}qf.defaultOptions={backgroundAlpha:1,backgroundColor:0,clearBeforeRender:!0},qf.extension={type:[_p.RendererSystem,_p.CanvasRendererSystem],name:"background"},Ep.add(qf);class Jf{constructor(t){this.renderer=t,this.emptyRenderer=new Hf(t),this.currentRenderer=this.emptyRenderer}setObjectRenderer(t){this.currentRenderer!==t&&(this.currentRenderer.stop(),this.currentRenderer=t,this.currentRenderer.start())}flush(){this.setObjectRenderer(this.emptyRenderer)}reset(){this.setObjectRenderer(this.emptyRenderer)}copyBoundTextures(t,e){const{boundTextures:i}=this.renderer.texture;for(let r=e-1;r>=0;--r)t[r]=i[r]||null,t[r]&&(t[r]._batchLocation=r)}boundArray(t,e,i,r){const{elements:s,ids:n,count:o}=t;let a=0;for(let l=0;l<o;l++){const t=s[l],o=t._batchLocation;if(o>=0&&o<r&&e[o]===t)n[l]=o;else for(;a<r;){const r=e[a];if(!r||r._batchEnabled!==i||r._batchLocation!==a){n[l]=a,t._batchLocation=a,e[a]=t;break}a++}}}destroy(){this.renderer=null}}Jf.extension={type:_p.RendererSystem,name:"batch"},Ep.add(Jf);let Kf=0;class Zf{constructor(t){this.renderer=t,this.webGLVersion=1,this.extensions={},this.supports={uint32Indices:!1},this.handleContextLost=this.handleContextLost.bind(this),this.handleContextRestored=this.handleContextRestored.bind(this)}get isLost(){return!this.gl||this.gl.isContextLost()}contextChange(t){this.gl=t,this.renderer.gl=t,this.renderer.CONTEXT_UID=Kf++}init(t){if(t.context)this.initFromContext(t.context);else{const e=this.renderer.background.alpha<1,i=t.premultipliedAlpha;this.preserveDrawingBuffer=t.preserveDrawingBuffer,this.useContextAlpha=t.useContextAlpha,this.powerPreference=t.powerPreference,this.initFromOptions({alpha:e,premultipliedAlpha:i,antialias:t.antialias,stencil:!0,preserveDrawingBuffer:t.preserveDrawingBuffer,powerPreference:t.powerPreference})}}initFromContext(t){this.gl=t,this.validateContext(t),this.renderer.gl=t,this.renderer.CONTEXT_UID=Kf++,this.renderer.runners.contextChange.emit(t);const e=this.renderer.view;void 0!==e.addEventListener&&(e.addEventListener("webglcontextlost",this.handleContextLost,!1),e.addEventListener("webglcontextrestored",this.handleContextRestored,!1))}initFromOptions(t){const e=this.createContext(this.renderer.view,t);this.initFromContext(e)}createContext(t,e){let i;if(ph.PREFER_ENV>=Vl.WEBGL2&&(i=t.getContext("webgl2",e)),i)this.webGLVersion=2;else if(this.webGLVersion=1,i=t.getContext("webgl",e)||t.getContext("experimental-webgl",e),!i)throw new Error("This browser does not support WebGL. Try using the canvas renderer");return this.gl=i,this.getExtensions(),this.gl}getExtensions(){const{gl:t}=this,e={loseContext:t.getExtension("WEBGL_lose_context"),anisotropicFiltering:t.getExtension("EXT_texture_filter_anisotropic"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),s3tc:t.getExtension("WEBGL_compressed_texture_s3tc"),s3tc_sRGB:t.getExtension("WEBGL_compressed_texture_s3tc_srgb"),etc:t.getExtension("WEBGL_compressed_texture_etc"),etc1:t.getExtension("WEBGL_compressed_texture_etc1"),pvrtc:t.getExtension("WEBGL_compressed_texture_pvrtc")||t.getExtension("WEBKIT_WEBGL_compressed_texture_pvrtc"),atc:t.getExtension("WEBGL_compressed_texture_atc"),astc:t.getExtension("WEBGL_compressed_texture_astc"),bptc:t.getExtension("EXT_texture_compression_bptc")};1===this.webGLVersion?Object.assign(this.extensions,e,{drawBuffers:t.getExtension("WEBGL_draw_buffers"),depthTexture:t.getExtension("WEBGL_depth_texture"),vertexArrayObject:t.getExtension("OES_vertex_array_object")||t.getExtension("MOZ_OES_vertex_array_object")||t.getExtension("WEBKIT_OES_vertex_array_object"),uint32ElementIndex:t.getExtension("OES_element_index_uint"),floatTexture:t.getExtension("OES_texture_float"),floatTextureLinear:t.getExtension("OES_texture_float_linear"),textureHalfFloat:t.getExtension("OES_texture_half_float"),textureHalfFloatLinear:t.getExtension("OES_texture_half_float_linear")}):2===this.webGLVersion&&Object.assign(this.extensions,e,{colorBufferFloat:t.getExtension("EXT_color_buffer_float")})}handleContextLost(t){t.preventDefault(),setTimeout(()=>{this.gl.isContextLost()&&this.extensions.loseContext&&this.extensions.loseContext.restoreContext()},0)}handleContextRestored(){this.renderer.runners.contextChange.emit(this.gl)}destroy(){const t=this.renderer.view;this.renderer=null,void 0!==t.removeEventListener&&(t.removeEventListener("webglcontextlost",this.handleContextLost),t.removeEventListener("webglcontextrestored",this.handleContextRestored)),this.gl.useProgram(null),this.extensions.loseContext&&this.extensions.loseContext.loseContext()}postrender(){this.renderer.objectRenderer.renderingToScreen&&this.gl.flush()}validateContext(t){const e=t.getContextAttributes(),i="WebGL2RenderingContext"in globalThis&&t instanceof globalThis.WebGL2RenderingContext;i&&(this.webGLVersion=2),e&&!e.stencil&&console.warn("Provided WebGL context does not have a stencil buffer, masks may not render correctly");const r=i||!!t.getExtension("OES_element_index_uint");this.supports.uint32Indices=r,r||console.warn("Provided WebGL context does not support 32 index buffer, complex graphics may not render correctly")}}Zf.defaultOptions={context:null,antialias:!1,premultipliedAlpha:!0,preserveDrawingBuffer:!1,powerPreference:"default"},Zf.extension={type:_p.RendererSystem,name:"context"},Ep.add(Zf);class Qf{constructor(t,e){if(this.width=Math.round(t),this.height=Math.round(e),!this.width||!this.height)throw new Error("Framebuffer width or height is zero");this.stencil=!1,this.depth=!1,this.dirtyId=0,this.dirtyFormat=0,this.dirtySize=0,this.depthTexture=null,this.colorTextures=[],this.glFramebuffers={},this.disposeRunner=new Op("disposeFramebuffer"),this.multisample=ch.NONE}get colorTexture(){return this.colorTextures[0]}addColorTexture(t=0,e){return this.colorTextures[t]=e||new Bp(null,{scaleMode:rh.NEAREST,resolution:1,mipmap:nh.OFF,width:this.width,height:this.height}),this.dirtyId++,this.dirtyFormat++,this}addDepthTexture(t){return this.depthTexture=t||new Bp(null,{scaleMode:rh.NEAREST,resolution:1,width:this.width,height:this.height,mipmap:nh.OFF,format:Ql.DEPTH_COMPONENT,type:eh.UNSIGNED_SHORT}),this.dirtyId++,this.dirtyFormat++,this}enableDepth(){return this.depth=!0,this.dirtyId++,this.dirtyFormat++,this}enableStencil(){return this.stencil=!0,this.dirtyId++,this.dirtyFormat++,this}resize(t,e){if(t=Math.round(t),e=Math.round(e),!t||!e)throw new Error("Framebuffer width and height must not be zero");if(t!==this.width||e!==this.height){this.width=t,this.height=e,this.dirtyId++,this.dirtySize++;for(let i=0;i<this.colorTextures.length;i++){const r=this.colorTextures[i],s=r.resolution;r.setSize(t/s,e/s)}if(this.depthTexture){const i=this.depthTexture.resolution;this.depthTexture.setSize(t/i,e/i)}}}dispose(){this.disposeRunner.emit(this,!1)}destroyDepthTexture(){this.depthTexture&&(this.depthTexture.destroy(),this.depthTexture=null,++this.dirtyId,++this.dirtyFormat)}}class tm extends Bp{constructor(t={}){if("number"==typeof t){t={width:arguments[0],height:arguments[1],scaleMode:arguments[2],resolution:arguments[3]}}t.width=t.width??100,t.height=t.height??100,t.multisample??(t.multisample=ch.NONE),super(null,t),this.mipmap=nh.OFF,this.valid=!0,this._clear=new qd([0,0,0,0]),this.framebuffer=new Qf(this.realWidth,this.realHeight).addColorTexture(0,this),this.framebuffer.multisample=t.multisample,this.maskStack=[],this.filterStack=[{}]}set clearColor(t){this._clear.setValue(t)}get clearColor(){return this._clear.value}get clear(){return this._clear}get multisample(){return this.framebuffer.multisample}set multisample(t){this.framebuffer.multisample=t}resize(t,e){this.framebuffer.resize(t*this.resolution,e*this.resolution),this.setRealSize(this.framebuffer.width,this.framebuffer.height)}dispose(){this.framebuffer.dispose(),super.dispose()}destroy(){super.destroy(),this.framebuffer.destroyDepthTexture(),this.framebuffer=null}}class em extends Np{constructor(t){const e=t;super(e.naturalWidth||e.videoWidth||e.displayWidth||e.width,e.naturalHeight||e.videoHeight||e.displayHeight||e.height),this.source=t,this.noSubImage=!1}static crossOrigin(t,e,i){void 0!==i||e.startsWith("data:")?!1!==i&&(t.crossOrigin="string"==typeof i?i:"anonymous"):t.crossOrigin=vp(e)}upload(t,e,i,r){const s=t.gl,n=e.realWidth,o=e.realHeight;if(r=r||this.source,typeof HTMLImageElement<"u"&&r instanceof HTMLImageElement){if(!r.complete||0===r.naturalWidth)return!1}else if(typeof HTMLVideoElement<"u"&&r instanceof HTMLVideoElement&&r.readyState<=1)return!1;return s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,e.alphaMode===oh.UNPACK),this.noSubImage||e.target!==s.TEXTURE_2D||i.width!==n||i.height!==o?(i.width=n,i.height=o,s.texImage2D(e.target,0,i.internalFormat,e.format,i.type,r)):s.texSubImage2D(s.TEXTURE_2D,0,0,0,e.format,i.type,r),!0}update(){if(this.destroyed)return;const t=this.source,e=t.naturalWidth||t.videoWidth||t.width,i=t.naturalHeight||t.videoHeight||t.height;this.resize(e,i),super.update()}dispose(){this.source=null}}class im extends em{constructor(t,e){if(e=e||{},"string"==typeof t){const i=new Image;em.crossOrigin(i,t,e.crossorigin),i.src=t,t=i}super(t),!t.complete&&this._width&&this._height&&(this._width=0,this._height=0),this.url=t.src,this._process=null,this.preserveBitmap=!1,this.createBitmap=(e.createBitmap??ph.CREATE_IMAGE_BITMAP)&&!!globalThis.createImageBitmap,this.alphaMode="number"==typeof e.alphaMode?e.alphaMode:null,this.bitmap=null,this._load=null,!1!==e.autoLoad&&this.load()}load(t){return this._load||(void 0!==t&&(this.createBitmap=t),this._load=new Promise((t,e)=>{const i=this.source;this.url=i.src;const r=()=>{this.destroyed||(i.onload=null,i.onerror=null,this.update(),this._load=null,this.createBitmap?t(this.process()):t(this))};i.complete&&i.src?r():(i.onload=r,i.onerror=t=>{e(t),this.onError.emit(t)})})),this._load}process(){const t=this.source;if(null!==this._process)return this._process;if(null!==this.bitmap||!globalThis.createImageBitmap)return Promise.resolve(this);const e=globalThis.createImageBitmap,i=!t.crossOrigin||"anonymous"===t.crossOrigin;return this._process=fetch(t.src,{mode:i?"cors":"no-cors"}).then(t=>t.blob()).then(i=>e(i,0,0,t.width,t.height,{premultiplyAlpha:null===this.alphaMode||this.alphaMode===oh.UNPACK?"premultiply":"none"})).then(t=>this.destroyed?Promise.reject():(this.bitmap=t,this.update(),this._process=null,Promise.resolve(this))),this._process}upload(t,e,i){if("number"==typeof this.alphaMode&&(e.alphaMode=this.alphaMode),!this.createBitmap)return super.upload(t,e,i);if(!this.bitmap&&(this.process(),!this.bitmap))return!1;if(super.upload(t,e,i,this.bitmap),!this.preserveBitmap){let t=!0;const r=e._glTextures;for(const s in r){const n=r[s];if(n!==i&&n.dirtyId!==e.dirtyId){t=!1;break}}t&&(this.bitmap.close&&this.bitmap.close(),this.bitmap=null)}return!0}dispose(){this.source.onload=null,this.source.onerror=null,super.dispose(),this.bitmap&&(this.bitmap.close(),this.bitmap=null),this._process=null,this._load=null}static test(t){return typeof HTMLImageElement<"u"&&("string"==typeof t||t instanceof HTMLImageElement)}}class rm{constructor(){this.x0=0,this.y0=0,this.x1=1,this.y1=0,this.x2=1,this.y2=1,this.x3=0,this.y3=1,this.uvsFloat32=new Float32Array(8)}set(t,e,i){const r=e.width,s=e.height;if(i){const e=t.width/2/r,n=t.height/2/s,o=t.x/r+e,a=t.y/s+n;i=pf.add(i,pf.NW),this.x0=o+e*pf.uX(i),this.y0=a+n*pf.uY(i),i=pf.add(i,2),this.x1=o+e*pf.uX(i),this.y1=a+n*pf.uY(i),i=pf.add(i,2),this.x2=o+e*pf.uX(i),this.y2=a+n*pf.uY(i),i=pf.add(i,2),this.x3=o+e*pf.uX(i),this.y3=a+n*pf.uY(i)}else this.x0=t.x/r,this.y0=t.y/s,this.x1=(t.x+t.width)/r,this.y1=t.y/s,this.x2=(t.x+t.width)/r,this.y2=(t.y+t.height)/s,this.x3=t.x/r,this.y3=(t.y+t.height)/s;this.uvsFloat32[0]=this.x0,this.uvsFloat32[1]=this.y0,this.uvsFloat32[2]=this.x1,this.uvsFloat32[3]=this.y1,this.uvsFloat32[4]=this.x2,this.uvsFloat32[5]=this.y2,this.uvsFloat32[6]=this.x3,this.uvsFloat32[7]=this.y3}}rm.prototype.toString=function(){return`[@pixi/core:TextureUvs x0=${this.x0} y0=${this.y0} x1=${this.x1} y1=${this.y1} x2=${this.x2} y2=${this.y2} x3=${this.x3} y3=${this.y3}]`};const sm=new rm;function nm(t){t.destroy=function(){},t.on=function(){},t.once=function(){},t.emit=function(){}}class om extends kh{constructor(t,e,i,r,s,n,o){if(super(),this.noFrame=!1,e||(this.noFrame=!0,e=new Qp(0,0,1,1)),t instanceof om&&(t=t.baseTexture),this.baseTexture=t,this._frame=e,this.trim=r,this.valid=!1,this.destroyed=!1,this._uvs=sm,this.uvMatrix=null,this.orig=i||e,this._rotate=Number(s||0),!0===s)this._rotate=2;else if(this._rotate%2!=0)throw new Error("attempt to use diamond-shaped UVs. If you are sure, set rotation manually");this.defaultAnchor=n?new Kp(n.x,n.y):new Kp(0,0),this.defaultBorders=o,this._updateID=0,this.textureCacheIds=[],t.valid?this.noFrame?t.valid&&this.onBaseTextureUpdated(t):this.frame=e:t.once("loaded",this.onBaseTextureUpdated,this),this.noFrame&&t.on("update",this.onBaseTextureUpdated,this)}update(){this.baseTexture.resource&&this.baseTexture.resource.update()}onBaseTextureUpdated(t){if(this.noFrame){if(!this.baseTexture.valid)return;this._frame.width=t.width,this._frame.height=t.height,this.valid=!0,this.updateUvs()}else this.frame=this._frame;this.emit("update",this)}destroy(t){if(this.baseTexture){if(t){const{resource:t}=this.baseTexture;t?.url&&up[t.url]&&om.removeFromCache(t.url),this.baseTexture.destroy()}this.baseTexture.off("loaded",this.onBaseTextureUpdated,this),this.baseTexture.off("update",this.onBaseTextureUpdated,this),this.baseTexture=null}this._frame=null,this._uvs=null,this.trim=null,this.orig=null,this.valid=!1,om.removeFromCache(this),this.textureCacheIds=null,this.destroyed=!0,this.emit("destroyed",this),this.removeAllListeners()}clone(){const t=this._frame.clone(),e=this._frame===this.orig?t:this.orig.clone(),i=new om(this.baseTexture,!this.noFrame&&t,e,this.trim?.clone(),this.rotate,this.defaultAnchor,this.defaultBorders);return this.noFrame&&(i._frame=t),i}updateUvs(){this._uvs===sm&&(this._uvs=new rm),this._uvs.set(this._frame,this.baseTexture,this.rotate),this._updateID++}static from(t,e={},i=ph.STRICT_TEXTURE_CACHE){const r="string"==typeof t;let s=null;if(r)s=t;else if(t instanceof Bp){if(!t.cacheId){const i=e?.pixiIdPrefix||"pixiid";t.cacheId=`${i}-${op()}`,Bp.addToCache(t,t.cacheId)}s=t.cacheId}else{if(!t._pixiId){const i=e?.pixiIdPrefix||"pixiid";t._pixiId=`${i}_${op()}`}s=t._pixiId}let n=up[s];if(r&&i&&!n)throw new Error(`The cacheId "${s}" does not exist in TextureCache.`);return n||t instanceof Bp?!n&&t instanceof Bp&&(n=new om(t),om.addToCache(n,s)):(e.resolution||(e.resolution=xp(t)),n=new om(new Bp(t,e)),n.baseTexture.cacheId=s,Bp.addToCache(n.baseTexture,s),om.addToCache(n,s)),n}static fromURL(t,e){const i=Object.assign({autoLoad:!1},e?.resourceOptions),r=om.from(t,Object.assign({resourceOptions:i},e),!1),s=r.baseTexture.resource;return r.baseTexture.valid?Promise.resolve(r):s.load().then(()=>Promise.resolve(r))}static fromBuffer(t,e,i,r){return new om(Bp.fromBuffer(t,e,i,r))}static fromLoader(t,e,i,r){const s=new Bp(t,Object.assign({scaleMode:Bp.defaultOptions.scaleMode,resolution:xp(e)},r)),{resource:n}=s;n instanceof im&&(n.url=e);const o=new om(s);return i||(i=e),Bp.addToCache(o.baseTexture,i),om.addToCache(o,i),i!==e&&(Bp.addToCache(o.baseTexture,e),om.addToCache(o,e)),o.baseTexture.valid?Promise.resolve(o):new Promise(t=>{o.baseTexture.once("loaded",()=>t(o))})}static addToCache(t,e){e&&(t.textureCacheIds.includes(e)||t.textureCacheIds.push(e),up[e]&&up[e]!==t&&console.warn(`Texture added to the cache with an id [${e}] that already had an entry`),up[e]=t)}static removeFromCache(t){if("string"==typeof t){const e=up[t];if(e){const i=e.textureCacheIds.indexOf(t);return i>-1&&e.textureCacheIds.splice(i,1),delete up[t],e}}else if(t?.textureCacheIds){for(let e=0;e<t.textureCacheIds.length;++e)up[t.textureCacheIds[e]]===t&&delete up[t.textureCacheIds[e]];return t.textureCacheIds.length=0,t}return null}get resolution(){return this.baseTexture.resolution}get frame(){return this._frame}set frame(t){this._frame=t,this.noFrame=!1;const{x:e,y:i,width:r,height:s}=t,n=e+r>this.baseTexture.width,o=i+s>this.baseTexture.height;if(n||o){const t=n&&o?"and":"or",a=`X: ${e} + ${r} = ${e+r} > ${this.baseTexture.width}`,l=`Y: ${i} + ${s} = ${i+s} > ${this.baseTexture.height}`;throw new Error(`Texture Error: frame does not fit inside the base Texture dimensions: ${a} ${t} ${l}`)}this.valid=r&&s&&this.baseTexture.valid,!this.trim&&!this.rotate&&(this.orig=t),this.valid&&this.updateUvs()}get rotate(){return this._rotate}set rotate(t){this._rotate=t,this.valid&&this.updateUvs()}get width(){return this.orig.width}get height(){return this.orig.height}castToBaseTexture(){return this.baseTexture}static get EMPTY(){return om._EMPTY||(om._EMPTY=new om(new Bp),nm(om._EMPTY),nm(om._EMPTY.baseTexture)),om._EMPTY}static get WHITE(){if(!om._WHITE){const t=ph.ADAPTER.createCanvas(16,16),e=t.getContext("2d");t.width=16,t.height=16,e.fillStyle="white",e.fillRect(0,0,16,16),om._WHITE=new om(Bp.from(t)),nm(om._WHITE),nm(om._WHITE.baseTexture)}return om._WHITE}}class am extends om{constructor(t,e){super(t,e),this.valid=!0,this.filterFrame=null,this.filterPoolKey=null,this.updateUvs()}get framebuffer(){return this.baseTexture.framebuffer}get multisample(){return this.framebuffer.multisample}set multisample(t){this.framebuffer.multisample=t}resize(t,e,i=!0){const r=this.baseTexture.resolution,s=Math.round(t*r)/r,n=Math.round(e*r)/r;this.valid=s>0&&n>0,this._frame.width=this.orig.width=s,this._frame.height=this.orig.height=n,i&&this.baseTexture.resize(s,n),this.updateUvs()}setResolution(t){const{baseTexture:e}=this;e.resolution!==t&&(e.setResolution(t),this.resize(e.width,e.height,!1))}static create(t){return new am(new tm(t))}}class lm{constructor(t){this.texturePool={},this.textureOptions=t||{},this.enableFullScreen=!1,this._pixelsWidth=0,this._pixelsHeight=0}createTexture(t,e,i=ch.NONE){const r=new tm(Object.assign({width:t,height:e,resolution:1,multisample:i},this.textureOptions));return new am(r)}getOptimalTexture(t,e,i=1,r=ch.NONE){let s;t=Math.max(Math.ceil(t*i-1e-6),1),e=Math.max(Math.ceil(e*i-1e-6),1),this.enableFullScreen&&t===this._pixelsWidth&&e===this._pixelsHeight?s=r>1?-r:-1:(s=((65535&(t=tp(t)))<<16|65535&(e=tp(e)))>>>0,r>1&&(s+=4294967296*r)),this.texturePool[s]||(this.texturePool[s]=[]);let n=this.texturePool[s].pop();return n||(n=this.createTexture(t,e,r)),n.filterPoolKey=s,n.setResolution(i),n}getFilterTexture(t,e,i){const r=this.getOptimalTexture(t.width,t.height,e||t.resolution,i||ch.NONE);return r.filterFrame=t.filterFrame,r}returnTexture(t){const e=t.filterPoolKey;t.filterFrame=null,this.texturePool[e].push(t)}returnFilterTexture(t){this.returnTexture(t)}clear(t){if(t=!1!==t)for(const e in this.texturePool){const t=this.texturePool[e];if(t)for(let e=0;e<t.length;e++)t[e].destroy(!0)}this.texturePool={}}setScreenSize(t){if(t.width!==this._pixelsWidth||t.height!==this._pixelsHeight){this.enableFullScreen=t.width>0&&t.height>0;for(const t in this.texturePool){if(!(Number(t)<0))continue;const e=this.texturePool[t];if(e)for(let t=0;t<e.length;t++)e[t].destroy(!0);this.texturePool[t]=[]}this._pixelsWidth=t.width,this._pixelsHeight=t.height}}}lm.SCREEN_KEY=-1;class hm extends $p{constructor(){super(),this.addAttribute("aVertexPosition",new Float32Array([0,0,1,0,1,1,0,1])).addIndex([0,1,3,2])}}class um extends $p{constructor(){super(),this.vertices=new Float32Array([-1,-1,1,-1,1,1,-1,1]),this.uvs=new Float32Array([0,0,1,0,1,1,0,1]),this.vertexBuffer=new Up(this.vertices),this.uvBuffer=new Up(this.uvs),this.addAttribute("aVertexPosition",this.vertexBuffer).addAttribute("aTextureCoord",this.uvBuffer).addIndex([0,1,2,0,2,3])}map(t,e){let i=0,r=0;return this.uvs[0]=i,this.uvs[1]=r,this.uvs[2]=i+e.width/t.width,this.uvs[3]=r,this.uvs[4]=i+e.width/t.width,this.uvs[5]=r+e.height/t.height,this.uvs[6]=i,this.uvs[7]=r+e.height/t.height,i=e.x,r=e.y,this.vertices[0]=i,this.vertices[1]=r,this.vertices[2]=i+e.width,this.vertices[3]=r,this.vertices[4]=i+e.width,this.vertices[5]=r+e.height,this.vertices[6]=i,this.vertices[7]=r+e.height,this.invalidate(),this}invalidate(){return this.vertexBuffer._updateID++,this.uvBuffer._updateID++,this}}class cm{constructor(){this.renderTexture=null,this.target=null,this.legacy=!1,this.resolution=1,this.multisample=ch.NONE,this.sourceFrame=new Qp,this.destinationFrame=new Qp,this.bindingSourceFrame=new Qp,this.bindingDestinationFrame=new Qp,this.filters=[],this.transform=null}clear(){this.target=null,this.filters=null,this.renderTexture=null}}const dm=[new Kp,new Kp,new Kp,new Kp],pm=new nf;class fm{constructor(t){this.renderer=t,this.defaultFilterStack=[{}],this.texturePool=new lm,this.statePool=[],this.quad=new hm,this.quadUv=new um,this.tempRect=new Qp,this.activeState={},this.globalUniforms=new Gf({outputFrame:new Qp,inputSize:new Float32Array(4),inputPixel:new Float32Array(4),inputClamp:new Float32Array(4),resolution:1,filterArea:new Float32Array(4),filterClamp:new Float32Array(4)},!0),this.forceClear=!1,this.useMaxPadding=!1}init(){this.texturePool.setScreenSize(this.renderer.view)}push(t,e){const i=this.renderer,r=this.defaultFilterStack,s=this.statePool.pop()||new cm,n=i.renderTexture;let o,a;if(n.current){const t=n.current;o=t.resolution,a=t.multisample}else o=i.resolution,a=i.multisample;let l=e[0].resolution||o,h=e[0].multisample??a,u=e[0].padding,c=e[0].autoFit,d=e[0].legacy??!0;for(let m=1;m<e.length;m++){const t=e[m];l=Math.min(l,t.resolution||o),h=Math.min(h,t.multisample??a),u=this.useMaxPadding?Math.max(u,t.padding):u+t.padding,c=c&&t.autoFit,d=d||(t.legacy??!0)}1===r.length&&(this.defaultFilterStack[0].renderTexture=n.current),r.push(s),s.resolution=l,s.multisample=h,s.legacy=d,s.target=t,s.sourceFrame.copyFrom(t.filterArea||t.getBounds(!0)),s.sourceFrame.pad(u);const p=this.tempRect.copyFrom(n.sourceFrame);i.projection.transform&&this.transformAABB(pm.copyFrom(i.projection.transform).invert(),p),c?(s.sourceFrame.fit(p),(s.sourceFrame.width<=0||s.sourceFrame.height<=0)&&(s.sourceFrame.width=0,s.sourceFrame.height=0)):s.sourceFrame.intersects(p)||(s.sourceFrame.width=0,s.sourceFrame.height=0),this.roundFrame(s.sourceFrame,n.current?n.current.resolution:i.resolution,n.sourceFrame,n.destinationFrame,i.projection.transform),s.renderTexture=this.getOptimalFilterTexture(s.sourceFrame.width,s.sourceFrame.height,l,h),s.filters=e,s.destinationFrame.width=s.renderTexture.width,s.destinationFrame.height=s.renderTexture.height;const f=this.tempRect;f.x=0,f.y=0,f.width=s.sourceFrame.width,f.height=s.sourceFrame.height,s.renderTexture.filterFrame=s.sourceFrame,s.bindingSourceFrame.copyFrom(n.sourceFrame),s.bindingDestinationFrame.copyFrom(n.destinationFrame),s.transform=i.projection.transform,i.projection.transform=null,n.bind(s.renderTexture,s.sourceFrame,f),i.framebuffer.clear(0,0,0,0)}pop(){const t=this.defaultFilterStack,e=t.pop(),i=e.filters;this.activeState=e;const r=this.globalUniforms.uniforms;r.outputFrame=e.sourceFrame,r.resolution=e.resolution;const s=r.inputSize,n=r.inputPixel,o=r.inputClamp;if(s[0]=e.destinationFrame.width,s[1]=e.destinationFrame.height,s[2]=1/s[0],s[3]=1/s[1],n[0]=Math.round(s[0]*e.resolution),n[1]=Math.round(s[1]*e.resolution),n[2]=1/n[0],n[3]=1/n[1],o[0]=.5*n[2],o[1]=.5*n[3],o[2]=e.sourceFrame.width*s[2]-.5*n[2],o[3]=e.sourceFrame.height*s[3]-.5*n[3],e.legacy){const t=r.filterArea;t[0]=e.destinationFrame.width,t[1]=e.destinationFrame.height,t[2]=e.sourceFrame.x,t[3]=e.sourceFrame.y,r.filterClamp=r.inputClamp}this.globalUniforms.update();const a=t[t.length-1];if(this.renderer.framebuffer.blit(),1===i.length)i[0].apply(this,e.renderTexture,a.renderTexture,ah.BLEND,e),this.returnFilterTexture(e.renderTexture);else{let t=e.renderTexture,r=this.getOptimalFilterTexture(t.width,t.height,e.resolution);r.filterFrame=t.filterFrame;let s=0;for(s=0;s<i.length-1;++s){1===s&&e.multisample>1&&(r=this.getOptimalFilterTexture(t.width,t.height,e.resolution),r.filterFrame=t.filterFrame),i[s].apply(this,t,r,ah.CLEAR,e);const n=t;t=r,r=n}i[s].apply(this,t,a.renderTexture,ah.BLEND,e),s>1&&e.multisample>1&&this.returnFilterTexture(e.renderTexture),this.returnFilterTexture(t),this.returnFilterTexture(r)}e.clear(),this.statePool.push(e)}bindAndClear(t,e=ah.CLEAR){const{renderTexture:i,state:r}=this.renderer;if(t===this.defaultFilterStack[this.defaultFilterStack.length-1].renderTexture?this.renderer.projection.transform=this.activeState.transform:this.renderer.projection.transform=null,t?.filterFrame){const e=this.tempRect;e.x=0,e.y=0,e.width=t.filterFrame.width,e.height=t.filterFrame.height,i.bind(t,t.filterFrame,e)}else t!==this.defaultFilterStack[this.defaultFilterStack.length-1].renderTexture?i.bind(t):this.renderer.renderTexture.bind(t,this.activeState.bindingSourceFrame,this.activeState.bindingDestinationFrame);const s=1&r.stateId||this.forceClear;(e===ah.CLEAR||e===ah.BLIT&&s)&&this.renderer.framebuffer.clear(0,0,0,0)}applyFilter(t,e,i,r){const s=this.renderer;s.state.set(t.state),this.bindAndClear(i,r),t.uniforms.uSampler=e,t.uniforms.filterGlobals=this.globalUniforms,s.shader.bind(t),t.legacy=!!t.program.attributeData.aTextureCoord,t.legacy?(this.quadUv.map(e._frame,e.filterFrame),s.geometry.bind(this.quadUv),s.geometry.draw(Zl.TRIANGLES)):(s.geometry.bind(this.quad),s.geometry.draw(Zl.TRIANGLE_STRIP))}calculateSpriteMatrix(t,e){const{sourceFrame:i,destinationFrame:r}=this.activeState,{orig:s}=e._texture,n=t.set(r.width,0,0,r.height,i.x,i.y),o=e.worldTransform.copyTo(nf.TEMP_MATRIX);return o.invert(),n.prepend(o),n.scale(1/s.width,1/s.height),n.translate(e.anchor.x,e.anchor.y),n}destroy(){this.renderer=null,this.texturePool.clear(!1)}getOptimalFilterTexture(t,e,i=1,r=ch.NONE){return this.texturePool.getOptimalTexture(t,e,i,r)}getFilterTexture(t,e,i){if("number"==typeof t){const i=t;t=e,e=i}t=t||this.activeState.renderTexture;const r=this.texturePool.getOptimalTexture(t.width,t.height,e||t.resolution,i||ch.NONE);return r.filterFrame=t.filterFrame,r}returnFilterTexture(t){this.texturePool.returnTexture(t)}emptyPool(){this.texturePool.clear(!0)}resize(){this.texturePool.setScreenSize(this.renderer.view)}transformAABB(t,e){const i=dm[0],r=dm[1],s=dm[2],n=dm[3];i.set(e.left,e.top),r.set(e.left,e.bottom),s.set(e.right,e.top),n.set(e.right,e.bottom),t.apply(i,i),t.apply(r,r),t.apply(s,s),t.apply(n,n);const o=Math.min(i.x,r.x,s.x,n.x),a=Math.min(i.y,r.y,s.y,n.y),l=Math.max(i.x,r.x,s.x,n.x),h=Math.max(i.y,r.y,s.y,n.y);e.x=o,e.y=a,e.width=l-o,e.height=h-a}roundFrame(t,e,i,r,s){if(!(t.width<=0||t.height<=0||i.width<=0||i.height<=0)){if(s){const{a:t,b:e,c:i,d:r}=s;if((Math.abs(e)>1e-4||Math.abs(i)>1e-4)&&(Math.abs(t)>1e-4||Math.abs(r)>1e-4))return}(s=s?pm.copyFrom(s):pm.identity()).translate(-i.x,-i.y).scale(r.width/i.width,r.height/i.height).translate(r.x,r.y),this.transformAABB(s,t),t.ceil(e),this.transformAABB(s.invert(),t)}}}fm.extension={type:_p.RendererSystem,name:"filter"},Ep.add(fm);class mm{constructor(t){this.framebuffer=t,this.stencil=null,this.dirtyId=-1,this.dirtyFormat=-1,this.dirtySize=-1,this.multisample=ch.NONE,this.msaaBuffer=null,this.blitFramebuffer=null,this.mipLevel=0}}const gm=new Qp;class ym{constructor(t){this.renderer=t,this.managedFramebuffers=[],this.unknownFramebuffer=new Qf(10,10),this.msaaSamples=null}contextChange(){this.disposeAll(!0);const t=this.gl=this.renderer.gl;if(this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.current=this.unknownFramebuffer,this.viewport=new Qp,this.hasMRT=!0,this.writeDepthTexture=!0,1===this.renderer.context.webGLVersion){let e=this.renderer.context.extensions.drawBuffers,i=this.renderer.context.extensions.depthTexture;ph.PREFER_ENV===Vl.WEBGL_LEGACY&&(e=null,i=null),e?t.drawBuffers=t=>e.drawBuffersWEBGL(t):(this.hasMRT=!1,t.drawBuffers=()=>{}),i||(this.writeDepthTexture=!1)}else this.msaaSamples=t.getInternalformatParameter(t.RENDERBUFFER,t.RGBA8,t.SAMPLES)}bind(t,e,i=0){const{gl:r}=this;if(t){const s=t.glFramebuffers[this.CONTEXT_UID]||this.initFramebuffer(t);this.current!==t&&(this.current=t,r.bindFramebuffer(r.FRAMEBUFFER,s.framebuffer)),s.mipLevel!==i&&(t.dirtyId++,t.dirtyFormat++,s.mipLevel=i),s.dirtyId!==t.dirtyId&&(s.dirtyId=t.dirtyId,s.dirtyFormat!==t.dirtyFormat?(s.dirtyFormat=t.dirtyFormat,s.dirtySize=t.dirtySize,this.updateFramebuffer(t,i)):s.dirtySize!==t.dirtySize&&(s.dirtySize=t.dirtySize,this.resizeFramebuffer(t)));for(let e=0;e<t.colorTextures.length;e++){const i=t.colorTextures[e];this.renderer.texture.unbind(i.parentTextureArray||i)}if(t.depthTexture&&this.renderer.texture.unbind(t.depthTexture),e){const t=e.width>>i,r=e.height>>i,s=t/e.width;this.setViewport(e.x*s,e.y*s,t,r)}else{const e=t.width>>i,r=t.height>>i;this.setViewport(0,0,e,r)}}else this.current&&(this.current=null,r.bindFramebuffer(r.FRAMEBUFFER,null)),e?this.setViewport(e.x,e.y,e.width,e.height):this.setViewport(0,0,this.renderer.width,this.renderer.height)}setViewport(t,e,i,r){const s=this.viewport;t=Math.round(t),e=Math.round(e),i=Math.round(i),r=Math.round(r),(s.width!==i||s.height!==r||s.x!==t||s.y!==e)&&(s.x=t,s.y=e,s.width=i,s.height=r,this.gl.viewport(t,e,i,r))}get size(){return this.current?{x:0,y:0,width:this.current.width,height:this.current.height}:{x:0,y:0,width:this.renderer.width,height:this.renderer.height}}clear(t,e,i,r,s=Jl.COLOR|Jl.DEPTH){const{gl:n}=this;n.clearColor(t,e,i,r),n.clear(s)}initFramebuffer(t){const{gl:e}=this,i=new mm(e.createFramebuffer());return i.multisample=this.detectSamples(t.multisample),t.glFramebuffers[this.CONTEXT_UID]=i,this.managedFramebuffers.push(t),t.disposeRunner.add(this),i}resizeFramebuffer(t){const{gl:e}=this,i=t.glFramebuffers[this.CONTEXT_UID];if(i.stencil){let r;e.bindRenderbuffer(e.RENDERBUFFER,i.stencil),r=1===this.renderer.context.webGLVersion?e.DEPTH_STENCIL:t.depth&&t.stencil?e.DEPTH24_STENCIL8:t.depth?e.DEPTH_COMPONENT24:e.STENCIL_INDEX8,i.msaaBuffer?e.renderbufferStorageMultisample(e.RENDERBUFFER,i.multisample,r,t.width,t.height):e.renderbufferStorage(e.RENDERBUFFER,r,t.width,t.height)}const r=t.colorTextures;let s=r.length;e.drawBuffers||(s=Math.min(s,1));for(let n=0;n<s;n++){const s=r[n],o=s.parentTextureArray||s;this.renderer.texture.bind(o,0),0===n&&i.msaaBuffer&&(e.bindRenderbuffer(e.RENDERBUFFER,i.msaaBuffer),e.renderbufferStorageMultisample(e.RENDERBUFFER,i.multisample,o._glTextures[this.CONTEXT_UID].internalFormat,t.width,t.height))}t.depthTexture&&this.writeDepthTexture&&this.renderer.texture.bind(t.depthTexture,0)}updateFramebuffer(t,e){const{gl:i}=this,r=t.glFramebuffers[this.CONTEXT_UID],s=t.colorTextures;let n=s.length;i.drawBuffers||(n=Math.min(n,1)),r.multisample>1&&this.canMultisampleFramebuffer(t)?r.msaaBuffer=r.msaaBuffer||i.createRenderbuffer():r.msaaBuffer&&(i.deleteRenderbuffer(r.msaaBuffer),r.msaaBuffer=null,r.blitFramebuffer&&(r.blitFramebuffer.dispose(),r.blitFramebuffer=null));const o=[];for(let a=0;a<n;a++){const n=s[a],l=n.parentTextureArray||n;this.renderer.texture.bind(l,0),0===a&&r.msaaBuffer?(i.bindRenderbuffer(i.RENDERBUFFER,r.msaaBuffer),i.renderbufferStorageMultisample(i.RENDERBUFFER,r.multisample,l._glTextures[this.CONTEXT_UID].internalFormat,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0,i.RENDERBUFFER,r.msaaBuffer)):(i.framebufferTexture2D(i.FRAMEBUFFER,i.COLOR_ATTACHMENT0+a,n.target,l._glTextures[this.CONTEXT_UID].texture,e),o.push(i.COLOR_ATTACHMENT0+a))}if(o.length>1&&i.drawBuffers(o),t.depthTexture&&this.writeDepthTexture){const r=t.depthTexture;this.renderer.texture.bind(r,0),i.framebufferTexture2D(i.FRAMEBUFFER,i.DEPTH_ATTACHMENT,i.TEXTURE_2D,r._glTextures[this.CONTEXT_UID].texture,e)}if(!t.stencil&&!t.depth||t.depthTexture&&this.writeDepthTexture)r.stencil&&(i.deleteRenderbuffer(r.stencil),r.stencil=null);else{let e,s;r.stencil=r.stencil||i.createRenderbuffer(),1===this.renderer.context.webGLVersion?(e=i.DEPTH_STENCIL_ATTACHMENT,s=i.DEPTH_STENCIL):t.depth&&t.stencil?(e=i.DEPTH_STENCIL_ATTACHMENT,s=i.DEPTH24_STENCIL8):t.depth?(e=i.DEPTH_ATTACHMENT,s=i.DEPTH_COMPONENT24):(e=i.STENCIL_ATTACHMENT,s=i.STENCIL_INDEX8),i.bindRenderbuffer(i.RENDERBUFFER,r.stencil),r.msaaBuffer?i.renderbufferStorageMultisample(i.RENDERBUFFER,r.multisample,s,t.width,t.height):i.renderbufferStorage(i.RENDERBUFFER,s,t.width,t.height),i.framebufferRenderbuffer(i.FRAMEBUFFER,e,i.RENDERBUFFER,r.stencil)}}canMultisampleFramebuffer(t){return 1!==this.renderer.context.webGLVersion&&t.colorTextures.length<=1&&!t.depthTexture}detectSamples(t){const{msaaSamples:e}=this;let i=ch.NONE;if(t<=1||null===e)return i;for(let r=0;r<e.length;r++)if(e[r]<=t){i=e[r];break}return 1===i&&(i=ch.NONE),i}blit(t,e,i){const{current:r,renderer:s,gl:n,CONTEXT_UID:o}=this;if(2!==s.context.webGLVersion||!r)return;const a=r.glFramebuffers[o];if(!a)return;if(!t){if(!a.msaaBuffer)return;const e=r.colorTextures[0];if(!e)return;a.blitFramebuffer||(a.blitFramebuffer=new Qf(r.width,r.height),a.blitFramebuffer.addColorTexture(0,e)),(t=a.blitFramebuffer).colorTextures[0]!==e&&(t.colorTextures[0]=e,t.dirtyId++,t.dirtyFormat++),(t.width!==r.width||t.height!==r.height)&&(t.width=r.width,t.height=r.height,t.dirtyId++,t.dirtySize++)}e||((e=gm).width=r.width,e.height=r.height),i||(i=e);const l=e.width===i.width&&e.height===i.height;this.bind(t),n.bindFramebuffer(n.READ_FRAMEBUFFER,a.framebuffer),n.blitFramebuffer(e.left,e.top,e.right,e.bottom,i.left,i.top,i.right,i.bottom,n.COLOR_BUFFER_BIT,l?n.NEAREST:n.LINEAR),n.bindFramebuffer(n.READ_FRAMEBUFFER,t.glFramebuffers[this.CONTEXT_UID].framebuffer)}disposeFramebuffer(t,e){const i=t.glFramebuffers[this.CONTEXT_UID],r=this.gl;if(!i)return;delete t.glFramebuffers[this.CONTEXT_UID];const s=this.managedFramebuffers.indexOf(t);s>=0&&this.managedFramebuffers.splice(s,1),t.disposeRunner.remove(this),e||(r.deleteFramebuffer(i.framebuffer),i.msaaBuffer&&r.deleteRenderbuffer(i.msaaBuffer),i.stencil&&r.deleteRenderbuffer(i.stencil)),i.blitFramebuffer&&this.disposeFramebuffer(i.blitFramebuffer,e)}disposeAll(t){const e=this.managedFramebuffers;this.managedFramebuffers=[];for(let i=0;i<e.length;i++)this.disposeFramebuffer(e[i],t)}forceStencil(){const t=this.current;if(!t)return;const e=t.glFramebuffers[this.CONTEXT_UID];if(!e||e.stencil&&t.stencil)return;t.stencil=!0;const i=t.width,r=t.height,s=this.gl,n=e.stencil=s.createRenderbuffer();let o,a;s.bindRenderbuffer(s.RENDERBUFFER,n),1===this.renderer.context.webGLVersion?(o=s.DEPTH_STENCIL_ATTACHMENT,a=s.DEPTH_STENCIL):t.depth?(o=s.DEPTH_STENCIL_ATTACHMENT,a=s.DEPTH24_STENCIL8):(o=s.STENCIL_ATTACHMENT,a=s.STENCIL_INDEX8),e.msaaBuffer?s.renderbufferStorageMultisample(s.RENDERBUFFER,e.multisample,a,i,r):s.renderbufferStorage(s.RENDERBUFFER,a,i,r),s.framebufferRenderbuffer(s.FRAMEBUFFER,o,s.RENDERBUFFER,n)}reset(){this.current=this.unknownFramebuffer,this.viewport=new Qp}destroy(){this.renderer=null}}ym.extension={type:_p.RendererSystem,name:"framebuffer"},Ep.add(ym);const vm={5126:4,5123:2,5121:1};class xm{constructor(t){this.renderer=t,this._activeGeometry=null,this._activeVao=null,this.hasVao=!0,this.hasInstance=!0,this.canUseUInt32ElementIndex=!1,this.managedGeometries={}}contextChange(){this.disposeAll(!0);const t=this.gl=this.renderer.gl,e=this.renderer.context;if(this.CONTEXT_UID=this.renderer.CONTEXT_UID,2!==e.webGLVersion){let e=this.renderer.context.extensions.vertexArrayObject;ph.PREFER_ENV===Vl.WEBGL_LEGACY&&(e=null),e?(t.createVertexArray=()=>e.createVertexArrayOES(),t.bindVertexArray=t=>e.bindVertexArrayOES(t),t.deleteVertexArray=t=>e.deleteVertexArrayOES(t)):(this.hasVao=!1,t.createVertexArray=()=>null,t.bindVertexArray=()=>null,t.deleteVertexArray=()=>null)}if(2!==e.webGLVersion){const e=t.getExtension("ANGLE_instanced_arrays");e?(t.vertexAttribDivisor=(t,i)=>e.vertexAttribDivisorANGLE(t,i),t.drawElementsInstanced=(t,i,r,s,n)=>e.drawElementsInstancedANGLE(t,i,r,s,n),t.drawArraysInstanced=(t,i,r,s)=>e.drawArraysInstancedANGLE(t,i,r,s)):this.hasInstance=!1}this.canUseUInt32ElementIndex=2===e.webGLVersion||!!e.extensions.uint32ElementIndex}bind(t,e){e=e||this.renderer.shader.shader;const{gl:i}=this;let r=t.glVertexArrayObjects[this.CONTEXT_UID],s=!1;r||(this.managedGeometries[t.id]=t,t.disposeRunner.add(this),t.glVertexArrayObjects[this.CONTEXT_UID]=r={},s=!0);const n=r[e.program.id]||this.initGeometryVao(t,e,s);this._activeGeometry=t,this._activeVao!==n&&(this._activeVao=n,this.hasVao?i.bindVertexArray(n):this.activateVao(t,e.program)),this.updateBuffers()}reset(){this.unbind()}updateBuffers(){const t=this._activeGeometry,e=this.renderer.buffer;for(let i=0;i<t.buffers.length;i++){const r=t.buffers[i];e.update(r)}}checkCompatibility(t,e){const i=t.attributes,r=e.attributeData;for(const s in r)if(!i[s])throw new Error(`shader and geometry incompatible, geometry missing the "${s}" attribute`)}getSignature(t,e){const i=t.attributes,r=e.attributeData,s=["g",t.id];for(const n in i)r[n]&&s.push(n,r[n].location);return s.join("-")}initGeometryVao(t,e,i=!0){const r=this.gl,s=this.CONTEXT_UID,n=this.renderer.buffer,o=e.program;o.glPrograms[s]||this.renderer.shader.generateProgram(e),this.checkCompatibility(t,o);const a=this.getSignature(t,o),l=t.glVertexArrayObjects[this.CONTEXT_UID];let h=l[a];if(h)return l[o.id]=h,h;const u=t.buffers,c=t.attributes,d={},p={};for(const f in u)d[f]=0,p[f]=0;for(const f in c)!c[f].size&&o.attributeData[f]?c[f].size=o.attributeData[f].size:c[f].size||console.warn(`PIXI Geometry attribute '${f}' size cannot be determined (likely the bound shader does not have the attribute)`),d[c[f].buffer]+=c[f].size*vm[c[f].type];for(const f in c){const t=c[f],e=t.size;void 0===t.stride&&(d[t.buffer]===e*vm[t.type]?t.stride=0:t.stride=d[t.buffer]),void 0===t.start&&(t.start=p[t.buffer],p[t.buffer]+=e*vm[t.type])}h=r.createVertexArray(),r.bindVertexArray(h);for(let f=0;f<u.length;f++){const t=u[f];n.bind(t),i&&t._glBuffers[s].refCount++}return this.activateVao(t,o),l[o.id]=h,l[a]=h,r.bindVertexArray(null),n.unbind(dh.ARRAY_BUFFER),h}disposeGeometry(t,e){if(!this.managedGeometries[t.id])return;delete this.managedGeometries[t.id];const i=t.glVertexArrayObjects[this.CONTEXT_UID],r=this.gl,s=t.buffers,n=this.renderer?.buffer;if(t.disposeRunner.remove(this),i){if(n)for(let t=0;t<s.length;t++){const i=s[t]._glBuffers[this.CONTEXT_UID];i&&(i.refCount--,0===i.refCount&&!e&&n.dispose(s[t],e))}if(!e)for(const t in i)if("g"===t[0]){const e=i[t];this._activeVao===e&&this.unbind(),r.deleteVertexArray(e)}delete t.glVertexArrayObjects[this.CONTEXT_UID]}}disposeAll(t){const e=Object.keys(this.managedGeometries);for(let i=0;i<e.length;i++)this.disposeGeometry(this.managedGeometries[e[i]],t)}activateVao(t,e){const i=this.gl,r=this.CONTEXT_UID,s=this.renderer.buffer,n=t.buffers,o=t.attributes;t.indexBuffer&&s.bind(t.indexBuffer);let a=null;for(const l in o){const t=o[l],h=n[t.buffer],u=h._glBuffers[r];if(e.attributeData[l]){a!==u&&(s.bind(h),a=u);const r=e.attributeData[l].location;if(i.enableVertexAttribArray(r),i.vertexAttribPointer(r,t.size,t.type||i.FLOAT,t.normalized,t.stride,t.start),t.instance){if(!this.hasInstance)throw new Error("geometry error, GPU Instancing is not supported on this device");i.vertexAttribDivisor(r,t.divisor)}}}}draw(t,e,i,r){const{gl:s}=this,n=this._activeGeometry;if(n.indexBuffer){const o=n.indexBuffer.data.BYTES_PER_ELEMENT,a=2===o?s.UNSIGNED_SHORT:s.UNSIGNED_INT;2===o||4===o&&this.canUseUInt32ElementIndex?n.instanced?s.drawElementsInstanced(t,e||n.indexBuffer.data.length,a,(i||0)*o,r||1):s.drawElements(t,e||n.indexBuffer.data.length,a,(i||0)*o):console.warn("unsupported index buffer type: uint32")}else n.instanced?s.drawArraysInstanced(t,i,e||n.getSize(),r||1):s.drawArrays(t,i,e||n.getSize());return this}unbind(){this.gl.bindVertexArray(null),this._activeVao=null,this._activeGeometry=null}destroy(){this.renderer=null}}xm.extension={type:_p.RendererSystem,name:"geometry"},Ep.add(xm);const bm=new nf;class _m{constructor(t,e){this._texture=t,this.mapCoord=new nf,this.uClampFrame=new Float32Array(4),this.uClampOffset=new Float32Array(2),this._textureID=-1,this._updateID=0,this.clampOffset=0,this.clampMargin=typeof e>"u"?.5:e,this.isSimple=!1}get texture(){return this._texture}set texture(t){this._texture=t,this._textureID=-1}multiplyUvs(t,e){void 0===e&&(e=t);const i=this.mapCoord;for(let r=0;r<t.length;r+=2){const s=t[r],n=t[r+1];e[r]=s*i.a+n*i.c+i.tx,e[r+1]=s*i.b+n*i.d+i.ty}return e}update(t){const e=this._texture;if(!e||!e.valid||!t&&this._textureID===e._updateID)return!1;this._textureID=e._updateID,this._updateID++;const i=e._uvs;this.mapCoord.set(i.x1-i.x0,i.y1-i.y0,i.x3-i.x0,i.y3-i.y0,i.x0,i.y0);const r=e.orig,s=e.trim;s&&(bm.set(r.width/s.width,0,0,r.height/s.height,-s.x/s.width,-s.y/s.height),this.mapCoord.append(bm));const n=e.baseTexture,o=this.uClampFrame,a=this.clampMargin/n.resolution,l=this.clampOffset;return o[0]=(e._frame.x+a+l)/n.width,o[1]=(e._frame.y+a+l)/n.height,o[2]=(e._frame.x+e._frame.width-a+l)/n.width,o[3]=(e._frame.y+e._frame.height-a+l)/n.height,this.uClampOffset[0]=l/n.realWidth,this.uClampOffset[1]=l/n.realHeight,this.isSimple=e._frame.width===n.width&&e._frame.height===n.height&&0===e.rotate,!0}}class wm extends Vf{constructor(t,e,i){let r=null;"string"!=typeof t&&void 0===e&&void 0===i&&(r=t,t=void 0,e=void 0,i=void 0),super(t||"attribute vec2 aVertexPosition;\nattribute vec2 aTextureCoord;\n\nuniform mat3 projectionMatrix;\nuniform mat3 otherMatrix;\n\nvarying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nvoid main(void)\n{\n gl_Position = vec4((projectionMatrix * vec3(aVertexPosition, 1.0)).xy, 0.0, 1.0);\n\n vTextureCoord = aTextureCoord;\n vMaskCoord = ( otherMatrix * vec3( aTextureCoord, 1.0) ).xy;\n}\n",e||"varying vec2 vMaskCoord;\nvarying vec2 vTextureCoord;\n\nuniform sampler2D uSampler;\nuniform sampler2D mask;\nuniform float alpha;\nuniform float npmAlpha;\nuniform vec4 maskClamp;\n\nvoid main(void)\n{\n float clip = step(3.5,\n step(maskClamp.x, vMaskCoord.x) +\n step(maskClamp.y, vMaskCoord.y) +\n step(vMaskCoord.x, maskClamp.z) +\n step(vMaskCoord.y, maskClamp.w));\n\n vec4 original = texture2D(uSampler, vTextureCoord);\n vec4 masky = texture2D(mask, vMaskCoord);\n float alphaMul = 1.0 - npmAlpha * (1.0 - masky.a);\n\n original *= (alphaMul * masky.r * alpha * clip);\n\n gl_FragColor = original;\n}\n",i),this.maskSprite=r,this.maskMatrix=new nf}get maskSprite(){return this._maskSprite}set maskSprite(t){this._maskSprite=t,this._maskSprite&&(this._maskSprite.renderable=!1)}apply(t,e,i,r){const s=this._maskSprite,n=s._texture;n.valid&&(n.uvMatrix||(n.uvMatrix=new _m(n,0)),n.uvMatrix.update(),this.uniforms.npmAlpha=n.baseTexture.alphaMode?0:1,this.uniforms.mask=n,this.uniforms.otherMatrix=t.calculateSpriteMatrix(this.maskMatrix,s).prepend(n.uvMatrix.mapCoord),this.uniforms.alpha=s.worldAlpha,this.uniforms.maskClamp=n.uvMatrix.uClampFrame,t.applyFilter(this,e,i,r))}}class Pm{constructor(t=null){this.type=uh.NONE,this.autoDetect=!0,this.maskObject=t||null,this.pooled=!1,this.isMaskData=!0,this.resolution=null,this.multisample=Vf.defaultMultisample,this.enabled=!0,this.colorMask=15,this._filters=null,this._stencilCounter=0,this._scissorCounter=0,this._scissorRect=null,this._scissorRectLocal=null,this._colorMask=15,this._target=null}get filter(){return this._filters?this._filters[0]:null}set filter(t){t?this._filters?this._filters[0]=t:this._filters=[t]:this._filters=null}reset(){this.pooled&&(this.maskObject=null,this.type=uh.NONE,this.autoDetect=!0),this._target=null,this._scissorRectLocal=null}copyCountersOrReset(t){t?(this._stencilCounter=t._stencilCounter,this._scissorCounter=t._scissorCounter,this._scissorRect=t._scissorRect):(this._stencilCounter=0,this._scissorCounter=0,this._scissorRect=null)}}class Em{constructor(t){this.renderer=t,this.enableScissor=!0,this.alphaMaskPool=[],this.maskDataPool=[],this.maskStack=[],this.alphaMaskIndex=0}setMaskStack(t){this.maskStack=t,this.renderer.scissor.setMaskStack(t),this.renderer.stencil.setMaskStack(t)}push(t,e){let i=e;if(!i.isMaskData){const t=this.maskDataPool.pop()||new Pm;t.pooled=!0,t.maskObject=e,i=t}const r=0!==this.maskStack.length?this.maskStack[this.maskStack.length-1]:null;if(i.copyCountersOrReset(r),i._colorMask=r?r._colorMask:15,i.autoDetect&&this.detect(i),i._target=t,i.type!==uh.SPRITE&&this.maskStack.push(i),i.enabled)switch(i.type){case uh.SCISSOR:this.renderer.scissor.push(i);break;case uh.STENCIL:this.renderer.stencil.push(i);break;case uh.SPRITE:i.copyCountersOrReset(null),this.pushSpriteMask(i);break;case uh.COLOR:this.pushColorMask(i)}i.type===uh.SPRITE&&this.maskStack.push(i)}pop(t){const e=this.maskStack.pop();if(e&&e._target===t){if(e.enabled)switch(e.type){case uh.SCISSOR:this.renderer.scissor.pop(e);break;case uh.STENCIL:this.renderer.stencil.pop(e.maskObject);break;case uh.SPRITE:this.popSpriteMask(e);break;case uh.COLOR:this.popColorMask(e)}if(e.reset(),e.pooled&&this.maskDataPool.push(e),0!==this.maskStack.length){const t=this.maskStack[this.maskStack.length-1];t.type===uh.SPRITE&&t._filters&&(t._filters[0].maskSprite=t.maskObject)}}}detect(t){const e=t.maskObject;e?e.isSprite?t.type=uh.SPRITE:this.enableScissor&&this.renderer.scissor.testScissor(t)?t.type=uh.SCISSOR:t.type=uh.STENCIL:t.type=uh.COLOR}pushSpriteMask(t){const{maskObject:e}=t,i=t._target;let r=t._filters;r||(r=this.alphaMaskPool[this.alphaMaskIndex],r||(r=this.alphaMaskPool[this.alphaMaskIndex]=[new wm])),r[0].resolution=t.resolution,r[0].multisample=t.multisample,r[0].maskSprite=e;const s=i.filterArea;i.filterArea=e.getBounds(!0),this.renderer.filter.push(i,r),i.filterArea=s,t._filters||this.alphaMaskIndex++}popSpriteMask(t){this.renderer.filter.pop(),t._filters?t._filters[0].maskSprite=null:(this.alphaMaskIndex--,this.alphaMaskPool[this.alphaMaskIndex][0].maskSprite=null)}pushColorMask(t){const e=t._colorMask,i=t._colorMask=e&t.colorMask;i!==e&&this.renderer.gl.colorMask(!!(1&i),!!(2&i),!!(4&i),!!(8&i))}popColorMask(t){const e=t._colorMask,i=this.maskStack.length>0?this.maskStack[this.maskStack.length-1]._colorMask:15;i!==e&&this.renderer.gl.colorMask(!!(1&i),!!(2&i),!!(4&i),!!(8&i))}destroy(){this.renderer=null}}Em.extension={type:_p.RendererSystem,name:"mask"},Ep.add(Em);class Tm{constructor(t){this.renderer=t,this.maskStack=[],this.glConst=0}getStackLength(){return this.maskStack.length}setMaskStack(t){const{gl:e}=this.renderer,i=this.getStackLength();this.maskStack=t;const r=this.getStackLength();r!==i&&(0===r?e.disable(this.glConst):(e.enable(this.glConst),this._useCurrent()))}_useCurrent(){}destroy(){this.renderer=null,this.maskStack=null}}const Am=new nf,Im=[],Sm=class t extends Tm{constructor(t){super(t),this.glConst=ph.ADAPTER.getWebGLRenderingContext().SCISSOR_TEST}getStackLength(){const t=this.maskStack[this.maskStack.length-1];return t?t._scissorCounter:0}calcScissorRect(t){if(t._scissorRectLocal)return;const e=t._scissorRect,{maskObject:i}=t,{renderer:r}=this,s=r.renderTexture,n=i.getBounds(!0,Im.pop()??new Qp);this.roundFrameToPixels(n,s.current?s.current.resolution:r.resolution,s.sourceFrame,s.destinationFrame,r.projection.transform),e&&n.fit(e),t._scissorRectLocal=n}static isMatrixRotated(t){if(!t)return!1;const{a:e,b:i,c:r,d:s}=t;return(Math.abs(i)>1e-4||Math.abs(r)>1e-4)&&(Math.abs(e)>1e-4||Math.abs(s)>1e-4)}testScissor(e){const{maskObject:i}=e;if(!i.isFastRect||!i.isFastRect()||t.isMatrixRotated(i.worldTransform)||t.isMatrixRotated(this.renderer.projection.transform))return!1;this.calcScissorRect(e);const r=e._scissorRectLocal;return r.width>0&&r.height>0}roundFrameToPixels(e,i,r,s,n){t.isMatrixRotated(n)||((n=n?Am.copyFrom(n):Am.identity()).translate(-r.x,-r.y).scale(s.width/r.width,s.height/r.height).translate(s.x,s.y),this.renderer.filter.transformAABB(n,e),e.fit(s),e.x=Math.round(e.x*i),e.y=Math.round(e.y*i),e.width=Math.round(e.width*i),e.height=Math.round(e.height*i))}push(t){t._scissorRectLocal||this.calcScissorRect(t);const{gl:e}=this.renderer;t._scissorRect||e.enable(e.SCISSOR_TEST),t._scissorCounter++,t._scissorRect=t._scissorRectLocal,this._useCurrent()}pop(t){const{gl:e}=this.renderer;t&&Im.push(t._scissorRectLocal),this.getStackLength()>0?this._useCurrent():e.disable(e.SCISSOR_TEST)}_useCurrent(){const t=this.maskStack[this.maskStack.length-1]._scissorRect;let e;e=this.renderer.renderTexture.current?t.y:this.renderer.height-t.height-t.y,this.renderer.gl.scissor(t.x,e,t.width,t.height)}};Sm.extension={type:_p.RendererSystem,name:"scissor"};let Cm=Sm;Ep.add(Cm);class Mm extends Tm{constructor(t){super(t),this.glConst=ph.ADAPTER.getWebGLRenderingContext().STENCIL_TEST}getStackLength(){const t=this.maskStack[this.maskStack.length-1];return t?t._stencilCounter:0}push(t){const e=t.maskObject,{gl:i}=this.renderer,r=t._stencilCounter;0===r&&(this.renderer.framebuffer.forceStencil(),i.clearStencil(0),i.clear(i.STENCIL_BUFFER_BIT),i.enable(i.STENCIL_TEST)),t._stencilCounter++;const s=t._colorMask;0!==s&&(t._colorMask=0,i.colorMask(!1,!1,!1,!1)),i.stencilFunc(i.EQUAL,r,4294967295),i.stencilOp(i.KEEP,i.KEEP,i.INCR),e.renderable=!0,e.render(this.renderer),this.renderer.batch.flush(),e.renderable=!1,0!==s&&(t._colorMask=s,i.colorMask(!!(1&s),!!(2&s),!!(4&s),!!(8&s))),this._useCurrent()}pop(t){const e=this.renderer.gl;if(0===this.getStackLength())e.disable(e.STENCIL_TEST);else{const i=0!==this.maskStack.length?this.maskStack[this.maskStack.length-1]:null,r=i?i._colorMask:15;0!==r&&(i._colorMask=0,e.colorMask(!1,!1,!1,!1)),e.stencilOp(e.KEEP,e.KEEP,e.DECR),t.renderable=!0,t.render(this.renderer),this.renderer.batch.flush(),t.renderable=!1,0!==r&&(i._colorMask=r,e.colorMask(!!(1&r),!!(2&r),!!(4&r),!!(8&r))),this._useCurrent()}}_useCurrent(){const t=this.renderer.gl;t.stencilFunc(t.EQUAL,this.getStackLength(),4294967295),t.stencilOp(t.KEEP,t.KEEP,t.KEEP)}}Mm.extension={type:_p.RendererSystem,name:"stencil"},Ep.add(Mm);class Om{constructor(t){this.renderer=t,this.plugins={},Object.defineProperties(this.plugins,{extract:{enumerable:!1,get:()=>(dd("7.0.0","renderer.plugins.extract has moved to renderer.extract"),t.extract)},prepare:{enumerable:!1,get:()=>(dd("7.0.0","renderer.plugins.prepare has moved to renderer.prepare"),t.prepare)},interaction:{enumerable:!1,get:()=>(dd("7.0.0","renderer.plugins.interaction has been deprecated, use renderer.events"),t.events)}})}init(){const t=this.rendererPlugins;for(const e in t)this.plugins[e]=new t[e](this.renderer)}destroy(){for(const t in this.plugins)this.plugins[t].destroy(),this.plugins[t]=null}}Om.extension={type:[_p.RendererSystem,_p.CanvasRendererSystem],name:"_plugin"},Ep.add(Om);class Nm{constructor(t){this.renderer=t,this.destinationFrame=null,this.sourceFrame=null,this.defaultFrame=null,this.projectionMatrix=new nf,this.transform=null}update(t,e,i,r){this.destinationFrame=t||this.destinationFrame||this.defaultFrame,this.sourceFrame=e||this.sourceFrame||t,this.calculateProjection(this.destinationFrame,this.sourceFrame,i,r),this.transform&&this.projectionMatrix.append(this.transform);const s=this.renderer;s.globalUniforms.uniforms.projectionMatrix=this.projectionMatrix,s.globalUniforms.update(),s.shader.shader&&s.shader.syncUniformGroup(s.shader.shader.uniforms.globals)}calculateProjection(t,e,i,r){const s=this.projectionMatrix,n=r?-1:1;s.identity(),s.a=1/e.width*2,s.d=n*(1/e.height*2),s.tx=-1-e.x*s.a,s.ty=-n-e.y*s.d}setTransform(t){}destroy(){this.renderer=null}}Nm.extension={type:_p.RendererSystem,name:"projection"},Ep.add(Nm);const Lm=new gf,Rm=new Qp;class km{constructor(t){this.renderer=t,this._tempMatrix=new nf}generateTexture(t,e){const{region:i,...r}=e||{},s=i?.copyTo(Rm)||t.getLocalBounds(Rm,!0),n=r.resolution||this.renderer.resolution;s.width=Math.max(s.width,1/n),s.height=Math.max(s.height,1/n),r.width=s.width,r.height=s.height,r.resolution=n,r.multisample??(r.multisample=this.renderer.multisample);const o=am.create(r);this._tempMatrix.tx=-s.x,this._tempMatrix.ty=-s.y;const a=t.transform;return t.transform=Lm,this.renderer.render(t,{renderTexture:o,transform:this._tempMatrix,skipUpdateTransform:!!t.parent,blit:!0}),t.transform=a,o}destroy(){}}km.extension={type:[_p.RendererSystem,_p.CanvasRendererSystem],name:"textureGenerator"},Ep.add(km);const Bm=new Qp,Fm=new Qp;class Dm{constructor(t){this.renderer=t,this.defaultMaskStack=[],this.current=null,this.sourceFrame=new Qp,this.destinationFrame=new Qp,this.viewportFrame=new Qp}contextChange(){const t=this.renderer?.gl.getContextAttributes();this._rendererPremultipliedAlpha=!!(t&&t.alpha&&t.premultipliedAlpha)}bind(t=null,e,i){const r=this.renderer;let s,n,o;this.current=t,t?(s=t.baseTexture,o=s.resolution,e||(Bm.width=t.frame.width,Bm.height=t.frame.height,e=Bm),i||(Fm.x=t.frame.x,Fm.y=t.frame.y,Fm.width=e.width,Fm.height=e.height,i=Fm),n=s.framebuffer):(o=r.resolution,e||(Bm.width=r._view.screen.width,Bm.height=r._view.screen.height,e=Bm),i||((i=Bm).width=e.width,i.height=e.height));const a=this.viewportFrame;a.x=i.x*o,a.y=i.y*o,a.width=i.width*o,a.height=i.height*o,t||(a.y=r.view.height-(a.y+a.height)),a.ceil(),this.renderer.framebuffer.bind(n,a),this.renderer.projection.update(i,e,o,!n),t?this.renderer.mask.setMaskStack(s.maskStack):this.renderer.mask.setMaskStack(this.defaultMaskStack),this.sourceFrame.copyFrom(e),this.destinationFrame.copyFrom(i)}clear(t,e){const i=this.current?this.current.baseTexture.clear:this.renderer.background.backgroundColor,r=qd.shared.setValue(t||i);(this.current&&this.current.baseTexture.alphaMode>0||!this.current&&this._rendererPremultipliedAlpha)&&r.premultiply(r.alpha);const s=this.destinationFrame,n=this.current?this.current.baseTexture:this.renderer._view.screen,o=s.width!==n.width||s.height!==n.height;if(o){let{x:t,y:e,width:i,height:r}=this.viewportFrame;t=Math.round(t),e=Math.round(e),i=Math.round(i),r=Math.round(r),this.renderer.gl.enable(this.renderer.gl.SCISSOR_TEST),this.renderer.gl.scissor(t,e,i,r)}this.renderer.framebuffer.clear(r.red,r.green,r.blue,r.alpha,e),o&&this.renderer.scissor.pop()}resize(){this.bind(null)}reset(){this.bind(null)}destroy(){this.renderer=null}}Dm.extension={type:_p.RendererSystem,name:"renderTexture"},Ep.add(Dm);class Um{constructor(t,e){this.program=t,this.uniformData=e,this.uniformGroups={},this.uniformDirtyGroups={},this.uniformBufferBindings={}}destroy(){this.uniformData=null,this.uniformGroups=null,this.uniformDirtyGroups=null,this.uniformBufferBindings=null,this.program=null}}function Gm(t,e){const i=yf(t,t.VERTEX_SHADER,e.vertexSrc),r=yf(t,t.FRAGMENT_SHADER,e.fragmentSrc),s=t.createProgram();t.attachShader(s,i),t.attachShader(s,r);const n=e.extra?.transformFeedbackVaryings;if(n&&("function"!=typeof t.transformFeedbackVaryings?console.warn("TransformFeedback is not supported but TransformFeedbackVaryings are given."):t.transformFeedbackVaryings(s,n.names,"separate"===n.bufferMode?t.SEPARATE_ATTRIBS:t.INTERLEAVED_ATTRIBS)),t.linkProgram(s),t.getProgramParameter(s,t.LINK_STATUS)||function(t,e,i,r){t.getProgramParameter(e,t.LINK_STATUS)||(t.getShaderParameter(i,t.COMPILE_STATUS)||If(t,i),t.getShaderParameter(r,t.COMPILE_STATUS)||If(t,r),console.error("PixiJS Error: Could not initialize shader."),""!==t.getProgramInfoLog(e)&&console.warn("PixiJS Warning: gl.getProgramInfoLog()",t.getProgramInfoLog(e)))}(t,s,i,r),e.attributeData=function(t,e){const i={},r=e.getProgramParameter(t,e.ACTIVE_ATTRIBUTES);for(let s=0;s<r;s++){const r=e.getActiveAttrib(t,s);if(r.name.startsWith("gl_"))continue;const n=Nf(e,r.type),o={type:n,name:r.name,size:Cf(n),location:e.getAttribLocation(t,r.name)};i[r.name]=o}return i}(s,t),e.uniformData=function(t,e){const i={},r=e.getProgramParameter(t,e.ACTIVE_UNIFORMS);for(let s=0;s<r;s++){const r=e.getActiveUniform(t,s),n=r.name.replace(/\[.*?\]$/,""),o=!!r.name.match(/\[.*?\]$/),a=Nf(e,r.type);i[n]={name:n,index:s,type:a,size:r.size,isArray:o,value:xf(a,r.size)}}return i}(s,t),!/^[ \t]*#[ \t]*version[ \t]+300[ \t]+es[ \t]*$/m.test(e.vertexSrc)){const i=Object.keys(e.attributeData);i.sort((t,e)=>t>e?1:-1);for(let r=0;r<i.length;r++)e.attributeData[i[r]].location=r,t.bindAttribLocation(s,r,i[r]);t.linkProgram(s)}t.deleteShader(i),t.deleteShader(r);const o={};for(const a in e.uniformData){const i=e.uniformData[a];o[a]={location:t.getUniformLocation(s,a),value:xf(i.type,i.size)}}return new Um(s,o)}function Xm(t,e,i,r,s){i.buffer.update(s)}const Wm={float:"\n data[offset] = v;\n ",vec2:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n ",vec3:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n ",vec4:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n data[offset+3] = v[3];\n ",mat2:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n\n data[offset+4] = v[2];\n data[offset+5] = v[3];\n ",mat3:"\n data[offset] = v[0];\n data[offset+1] = v[1];\n data[offset+2] = v[2];\n\n data[offset + 4] = v[3];\n data[offset + 5] = v[4];\n data[offset + 6] = v[5];\n\n data[offset + 8] = v[6];\n data[offset + 9] = v[7];\n data[offset + 10] = v[8];\n ",mat4:"\n for(var i = 0; i < 16; i++)\n {\n data[offset + i] = v[i];\n }\n "},Ym={float:4,vec2:8,vec3:12,vec4:16,int:4,ivec2:8,ivec3:12,ivec4:16,uint:4,uvec2:8,uvec3:12,uvec4:16,bool:4,bvec2:8,bvec3:12,bvec4:16,mat2:32,mat3:48,mat4:64};function Hm(t,e){if(!t.autoManage)return{size:0,syncFunc:Xm};const i=function(t,e){const i=[];for(const r in t)e[r]&&i.push(e[r]);return i.sort((t,e)=>t.index-e.index),i}(t.uniforms,e),{uboElements:r,size:s}=function(t){const e=t.map(t=>({data:t,offset:0,dataLen:0,dirty:0}));let i=0,r=0,s=0;for(let n=0;n<e.length;n++){const t=e[n];if(i=Ym[t.data.type],t.data.size>1&&(i=Math.max(i,16)*t.data.size),t.dataLen=i,r%i!==0&&r<16){const t=r%i%16;r+=t,s+=t}r+i>16?(s=16*Math.ceil(s/16),t.offset=s,s+=i,r=i):(t.offset=s,r+=i,s+=i)}return s=16*Math.ceil(s/16),{uboElements:e,size:s}}(i),n=["\n var v = null;\n var v2 = null;\n var cv = null;\n var t = 0;\n var gl = renderer.gl\n var index = 0;\n var data = buffer.data;\n "];for(let o=0;o<r.length;o++){const e=r[o],i=t.uniforms[e.data.name],s=e.data.name;let a=!1;for(let t=0;t<bf.length;t++){const r=bf[t];if(r.codeUbo&&r.test(e.data,i)){n.push(`offset = ${e.offset/4};`,bf[t].codeUbo(e.data.name,i)),a=!0;break}}if(!a)if(e.data.size>1){const t=Cf(e.data.type),i=Math.max(Ym[e.data.type]/16,1),r=t/i,o=(4-r%4)%4;n.push(`\n cv = ud.${s}.value;\n v = uv.${s};\n offset = ${e.offset/4};\n\n t = 0;\n\n for(var i=0; i < ${e.data.size*i}; i++)\n {\n for(var j = 0; j < ${r}; j++)\n {\n data[offset++] = v[t++];\n }\n offset += ${o};\n }\n\n `)}else{const t=Wm[e.data.type];n.push(`\n cv = ud.${s}.value;\n v = uv.${s};\n offset = ${e.offset/4};\n ${t};\n `)}}return n.push("\n renderer.buffer.update(buffer);\n "),{size:s,syncFunc:new Function("ud","uv","renderer","syncData","buffer",n.join("\n"))}}let $m=0;const jm={textureCount:0,uboCount:0};class zm{constructor(t){this.destroyed=!1,this.renderer=t,this.systemCheck(),this.gl=null,this.shader=null,this.program=null,this.cache={},this._uboCache={},this.id=$m++}systemCheck(){if(!function(){if("boolean"==typeof Rf)return Rf;try{Rf=!0===new Function("param1","param2","param3","return param1[param2] === param3;")({a:"b"},"a","b")}catch{Rf=!1}return Rf}())throw new Error("Current environment does not allow unsafe-eval, please use @pixi/unsafe-eval module to enable support.")}contextChange(t){this.gl=t,this.reset()}bind(t,e){t.disposeRunner.add(this),t.uniforms.globals=this.renderer.globalUniforms;const i=t.program,r=i.glPrograms[this.renderer.CONTEXT_UID]||this.generateProgram(t);return this.shader=t,this.program!==i&&(this.program=i,this.gl.useProgram(r.program)),e||(jm.textureCount=0,jm.uboCount=0,this.syncUniformGroup(t.uniformGroup,jm)),r}setUniforms(t){const e=this.shader.program,i=e.glPrograms[this.renderer.CONTEXT_UID];e.syncUniforms(i.uniformData,t,this.renderer)}syncUniformGroup(t,e){const i=this.getGlProgram();(!t.static||t.dirtyId!==i.uniformDirtyGroups[t.id])&&(i.uniformDirtyGroups[t.id]=t.dirtyId,this.syncUniforms(t,i,e))}syncUniforms(t,e,i){(t.syncUniforms[this.shader.program.id]||this.createSyncGroups(t))(e.uniformData,t.uniforms,this.renderer,i)}createSyncGroups(t){const e=this.getSignature(t,this.shader.program.uniformData,"u");return this.cache[e]||(this.cache[e]=function(t,e){const i=["\n var v = null;\n var cv = null;\n var cu = null;\n var t = 0;\n var gl = renderer.gl;\n "];for(const r in t.uniforms){const s=e[r];if(!s){!0===t.uniforms[r]?.group&&(t.uniforms[r].ubo?i.push(`\n renderer.shader.syncUniformBufferGroup(uv.${r}, '${r}');\n `):i.push(`\n renderer.shader.syncUniformGroup(uv.${r}, syncData);\n `));continue}const n=t.uniforms[r];let o=!1;for(let t=0;t<bf.length;t++)if(bf[t].test(s,n)){i.push(bf[t].code(r,n)),o=!0;break}if(!o){const t=(1!==s.size||s.isArray?wf:_f)[s.type].replace("location",`ud["${r}"].location`);i.push(`\n cu = ud["${r}"];\n cv = cu.value;\n v = uv["${r}"];\n ${t};`)}}return new Function("ud","uv","renderer","syncData",i.join("\n"))}(t,this.shader.program.uniformData)),t.syncUniforms[this.shader.program.id]=this.cache[e],t.syncUniforms[this.shader.program.id]}syncUniformBufferGroup(t,e){const i=this.getGlProgram();if(!t.static||0!==t.dirtyId||!i.uniformGroups[t.id]){t.dirtyId=0;const r=i.uniformGroups[t.id]||this.createSyncBufferGroup(t,i,e);t.buffer.update(),r(i.uniformData,t.uniforms,this.renderer,jm,t.buffer)}this.renderer.buffer.bindBufferBase(t.buffer,i.uniformBufferBindings[e])}createSyncBufferGroup(t,e,i){const{gl:r}=this.renderer;this.renderer.buffer.bind(t.buffer);const s=this.gl.getUniformBlockIndex(e.program,i);e.uniformBufferBindings[i]=this.shader.uniformBindCount,r.uniformBlockBinding(e.program,s,this.shader.uniformBindCount),this.shader.uniformBindCount++;const n=this.getSignature(t,this.shader.program.uniformData,"ubo");let o=this._uboCache[n];if(o||(o=this._uboCache[n]=Hm(t,this.shader.program.uniformData)),t.autoManage){const e=new Float32Array(o.size/4);t.buffer.update(e)}return e.uniformGroups[t.id]=o.syncFunc,e.uniformGroups[t.id]}getSignature(t,e,i){const r=t.uniforms,s=[`${i}-`];for(const n in r)s.push(n),e[n]&&s.push(e[n].type);return s.join("-")}getGlProgram(){return this.shader?this.shader.program.glPrograms[this.renderer.CONTEXT_UID]:null}generateProgram(t){const e=this.gl,i=t.program,r=Gm(e,i);return i.glPrograms[this.renderer.CONTEXT_UID]=r,r}reset(){this.program=null,this.shader=null}disposeShader(t){this.shader===t&&(this.shader=null)}destroy(){this.renderer=null,this.destroyed=!0}}zm.extension={type:_p.RendererSystem,name:"shader"},Ep.add(zm);class Vm{constructor(t){this.renderer=t}run(t){const{renderer:e}=this;e.runners.init.emit(e.options),t.hello&&console.log(`PixiJS 7.4.2 - ${e.rendererLogId} - https://pixijs.com`),e.resize(e.screen.width,e.screen.height)}destroy(){}}Vm.defaultOptions={hello:!1},Vm.extension={type:[_p.RendererSystem,_p.CanvasRendererSystem],name:"startup"},Ep.add(Vm);const qm=class t{constructor(){this.gl=null,this.stateId=0,this.polygonOffset=0,this.blendMode=Kl.NONE,this._blendEq=!1,this.map=[],this.map[0]=this.setBlend,this.map[1]=this.setOffset,this.map[2]=this.setCullFace,this.map[3]=this.setDepthTest,this.map[4]=this.setFrontFace,this.map[5]=this.setDepthMask,this.checks=[],this.defaultState=new Sp,this.defaultState.blend=!0}contextChange(t){this.gl=t,this.blendModes=function(t,e=[]){return e[Kl.NORMAL]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.ADD]=[t.ONE,t.ONE],e[Kl.MULTIPLY]=[t.DST_COLOR,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.SCREEN]=[t.ONE,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.OVERLAY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.DARKEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.LIGHTEN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.COLOR_DODGE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.COLOR_BURN]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.HARD_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.SOFT_LIGHT]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.DIFFERENCE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.EXCLUSION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.HUE]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.SATURATION]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.COLOR]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.LUMINOSITY]=[t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.NONE]=[0,0],e[Kl.NORMAL_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_ALPHA,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.ADD_NPM]=[t.SRC_ALPHA,t.ONE,t.ONE,t.ONE],e[Kl.SCREEN_NPM]=[t.SRC_ALPHA,t.ONE_MINUS_SRC_COLOR,t.ONE,t.ONE_MINUS_SRC_ALPHA],e[Kl.SRC_IN]=[t.DST_ALPHA,t.ZERO],e[Kl.SRC_OUT]=[t.ONE_MINUS_DST_ALPHA,t.ZERO],e[Kl.SRC_ATOP]=[t.DST_ALPHA,t.ONE_MINUS_SRC_ALPHA],e[Kl.DST_OVER]=[t.ONE_MINUS_DST_ALPHA,t.ONE],e[Kl.DST_IN]=[t.ZERO,t.SRC_ALPHA],e[Kl.DST_OUT]=[t.ZERO,t.ONE_MINUS_SRC_ALPHA],e[Kl.DST_ATOP]=[t.ONE_MINUS_DST_ALPHA,t.SRC_ALPHA],e[Kl.XOR]=[t.ONE_MINUS_DST_ALPHA,t.ONE_MINUS_SRC_ALPHA],e[Kl.SUBTRACT]=[t.ONE,t.ONE,t.ONE,t.ONE,t.FUNC_REVERSE_SUBTRACT,t.FUNC_ADD],e}(t),this.set(this.defaultState),this.reset()}set(t){if(t=t||this.defaultState,this.stateId!==t.data){let e=this.stateId^t.data,i=0;for(;e;)1&e&&this.map[i].call(this,!!(t.data&1<<i)),e>>=1,i++;this.stateId=t.data}for(let e=0;e<this.checks.length;e++)this.checks[e](this,t)}forceState(t){t=t||this.defaultState;for(let e=0;e<this.map.length;e++)this.map[e].call(this,!!(t.data&1<<e));for(let e=0;e<this.checks.length;e++)this.checks[e](this,t);this.stateId=t.data}setBlend(e){this.updateCheck(t.checkBlendMode,e),this.gl[e?"enable":"disable"](this.gl.BLEND)}setOffset(e){this.updateCheck(t.checkPolygonOffset,e),this.gl[e?"enable":"disable"](this.gl.POLYGON_OFFSET_FILL)}setDepthTest(t){this.gl[t?"enable":"disable"](this.gl.DEPTH_TEST)}setDepthMask(t){this.gl.depthMask(t)}setCullFace(t){this.gl[t?"enable":"disable"](this.gl.CULL_FACE)}setFrontFace(t){this.gl.frontFace(this.gl[t?"CW":"CCW"])}setBlendMode(t){if(t===this.blendMode)return;this.blendMode=t;const e=this.blendModes[t],i=this.gl;2===e.length?i.blendFunc(e[0],e[1]):i.blendFuncSeparate(e[0],e[1],e[2],e[3]),6===e.length?(this._blendEq=!0,i.blendEquationSeparate(e[4],e[5])):this._blendEq&&(this._blendEq=!1,i.blendEquationSeparate(i.FUNC_ADD,i.FUNC_ADD))}setPolygonOffset(t,e){this.gl.polygonOffset(t,e)}reset(){this.gl.pixelStorei(this.gl.UNPACK_FLIP_Y_WEBGL,!1),this.forceState(this.defaultState),this._blendEq=!0,this.blendMode=-1,this.setBlendMode(0)}updateCheck(t,e){const i=this.checks.indexOf(t);e&&-1===i?this.checks.push(t):!e&&-1!==i&&this.checks.splice(i,1)}static checkBlendMode(t,e){t.setBlendMode(e.blendMode)}static checkPolygonOffset(t,e){t.setPolygonOffset(1,e.polygonOffset)}destroy(){this.gl=null}};qm.extension={type:_p.RendererSystem,name:"state"};let Jm=qm;Ep.add(Jm);class Km extends kh{constructor(){super(...arguments),this.runners={},this._systemsHash={}}setup(t){this.addRunners(...t.runners);const e=(t.priority??[]).filter(e=>t.systems[e]),i=[...e,...Object.keys(t.systems).filter(t=>!e.includes(t))];for(const r of i)this.addSystem(t.systems[r],r)}addRunners(...t){t.forEach(t=>{this.runners[t]=new Op(t)})}addSystem(t,e){const i=new t(this);if(this[e])throw new Error(`Whoops! The name "${e}" is already in use`);this[e]=i,this._systemsHash[e]=i;for(const r in this.runners)this.runners[r].add(i);return this}emitWithCustomOptions(t,e){const i=Object.keys(this._systemsHash);t.items.forEach(r=>{const s=i.find(t=>this._systemsHash[t]===r);r[t.name](e[s])})}destroy(){Object.values(this.runners).forEach(t=>{t.destroy()}),this._systemsHash={}}}const Zm=class t{constructor(e){this.renderer=e,this.count=0,this.checkCount=0,this.maxIdle=t.defaultMaxIdle,this.checkCountMax=t.defaultCheckCountMax,this.mode=t.defaultMode}postrender(){this.renderer.objectRenderer.renderingToScreen&&(this.count++,this.mode!==lh.MANUAL&&(this.checkCount++,this.checkCount>this.checkCountMax&&(this.checkCount=0,this.run())))}run(){const t=this.renderer.texture,e=t.managedTextures;let i=!1;for(let r=0;r<e.length;r++){const s=e[r];s.resource&&this.count-s.touched>this.maxIdle&&(t.destroyTexture(s,!0),e[r]=null,i=!0)}if(i){let t=0;for(let i=0;i<e.length;i++)null!==e[i]&&(e[t++]=e[i]);e.length=t}}unload(t){const e=this.renderer.texture,i=t._texture;i&&!i.framebuffer&&e.destroyTexture(i);for(let r=t.children.length-1;r>=0;r--)this.unload(t.children[r])}destroy(){this.renderer=null}};Zm.defaultMode=lh.AUTO,Zm.defaultMaxIdle=3600,Zm.defaultCheckCountMax=600,Zm.extension={type:_p.RendererSystem,name:"textureGC"};let Qm=Zm;Ep.add(Qm);class tg{constructor(t){this.texture=t,this.width=-1,this.height=-1,this.dirtyId=-1,this.dirtyStyleId=-1,this.mipmap=!1,this.wrapMode=33071,this.type=eh.UNSIGNED_BYTE,this.internalFormat=Ql.RGBA,this.samplerType=0}}class eg{constructor(t){this.renderer=t,this.boundTextures=[],this.currentLocation=-1,this.managedTextures=[],this._unknownBoundTextures=!1,this.unknownTexture=new Bp,this.hasIntegerTextures=!1}contextChange(){const t=this.gl=this.renderer.gl;this.CONTEXT_UID=this.renderer.CONTEXT_UID,this.webGLVersion=this.renderer.context.webGLVersion,this.internalFormats=function(t){let e;return e="WebGL2RenderingContext"in globalThis&&t instanceof globalThis.WebGL2RenderingContext?{[eh.UNSIGNED_BYTE]:{[Ql.RGBA]:t.RGBA8,[Ql.RGB]:t.RGB8,[Ql.RG]:t.RG8,[Ql.RED]:t.R8,[Ql.RGBA_INTEGER]:t.RGBA8UI,[Ql.RGB_INTEGER]:t.RGB8UI,[Ql.RG_INTEGER]:t.RG8UI,[Ql.RED_INTEGER]:t.R8UI,[Ql.ALPHA]:t.ALPHA,[Ql.LUMINANCE]:t.LUMINANCE,[Ql.LUMINANCE_ALPHA]:t.LUMINANCE_ALPHA},[eh.BYTE]:{[Ql.RGBA]:t.RGBA8_SNORM,[Ql.RGB]:t.RGB8_SNORM,[Ql.RG]:t.RG8_SNORM,[Ql.RED]:t.R8_SNORM,[Ql.RGBA_INTEGER]:t.RGBA8I,[Ql.RGB_INTEGER]:t.RGB8I,[Ql.RG_INTEGER]:t.RG8I,[Ql.RED_INTEGER]:t.R8I},[eh.UNSIGNED_SHORT]:{[Ql.RGBA_INTEGER]:t.RGBA16UI,[Ql.RGB_INTEGER]:t.RGB16UI,[Ql.RG_INTEGER]:t.RG16UI,[Ql.RED_INTEGER]:t.R16UI,[Ql.DEPTH_COMPONENT]:t.DEPTH_COMPONENT16},[eh.SHORT]:{[Ql.RGBA_INTEGER]:t.RGBA16I,[Ql.RGB_INTEGER]:t.RGB16I,[Ql.RG_INTEGER]:t.RG16I,[Ql.RED_INTEGER]:t.R16I},[eh.UNSIGNED_INT]:{[Ql.RGBA_INTEGER]:t.RGBA32UI,[Ql.RGB_INTEGER]:t.RGB32UI,[Ql.RG_INTEGER]:t.RG32UI,[Ql.RED_INTEGER]:t.R32UI,[Ql.DEPTH_COMPONENT]:t.DEPTH_COMPONENT24},[eh.INT]:{[Ql.RGBA_INTEGER]:t.RGBA32I,[Ql.RGB_INTEGER]:t.RGB32I,[Ql.RG_INTEGER]:t.RG32I,[Ql.RED_INTEGER]:t.R32I},[eh.FLOAT]:{[Ql.RGBA]:t.RGBA32F,[Ql.RGB]:t.RGB32F,[Ql.RG]:t.RG32F,[Ql.RED]:t.R32F,[Ql.DEPTH_COMPONENT]:t.DEPTH_COMPONENT32F},[eh.HALF_FLOAT]:{[Ql.RGBA]:t.RGBA16F,[Ql.RGB]:t.RGB16F,[Ql.RG]:t.RG16F,[Ql.RED]:t.R16F},[eh.UNSIGNED_SHORT_5_6_5]:{[Ql.RGB]:t.RGB565},[eh.UNSIGNED_SHORT_4_4_4_4]:{[Ql.RGBA]:t.RGBA4},[eh.UNSIGNED_SHORT_5_5_5_1]:{[Ql.RGBA]:t.RGB5_A1},[eh.UNSIGNED_INT_2_10_10_10_REV]:{[Ql.RGBA]:t.RGB10_A2,[Ql.RGBA_INTEGER]:t.RGB10_A2UI},[eh.UNSIGNED_INT_10F_11F_11F_REV]:{[Ql.RGB]:t.R11F_G11F_B10F},[eh.UNSIGNED_INT_5_9_9_9_REV]:{[Ql.RGB]:t.RGB9_E5},[eh.UNSIGNED_INT_24_8]:{[Ql.DEPTH_STENCIL]:t.DEPTH24_STENCIL8},[eh.FLOAT_32_UNSIGNED_INT_24_8_REV]:{[Ql.DEPTH_STENCIL]:t.DEPTH32F_STENCIL8}}:{[eh.UNSIGNED_BYTE]:{[Ql.RGBA]:t.RGBA,[Ql.RGB]:t.RGB,[Ql.ALPHA]:t.ALPHA,[Ql.LUMINANCE]:t.LUMINANCE,[Ql.LUMINANCE_ALPHA]:t.LUMINANCE_ALPHA},[eh.UNSIGNED_SHORT_5_6_5]:{[Ql.RGB]:t.RGB},[eh.UNSIGNED_SHORT_4_4_4_4]:{[Ql.RGBA]:t.RGBA},[eh.UNSIGNED_SHORT_5_5_5_1]:{[Ql.RGBA]:t.RGBA}},e}(t),this.samplerTypes=function(t){let e;return e="WebGL2RenderingContext"in globalThis&&t instanceof globalThis.WebGL2RenderingContext?{[t.RGB]:ih.FLOAT,[t.RGBA]:ih.FLOAT,[t.ALPHA]:ih.FLOAT,[t.LUMINANCE]:ih.FLOAT,[t.LUMINANCE_ALPHA]:ih.FLOAT,[t.R8]:ih.FLOAT,[t.R8_SNORM]:ih.FLOAT,[t.RG8]:ih.FLOAT,[t.RG8_SNORM]:ih.FLOAT,[t.RGB8]:ih.FLOAT,[t.RGB8_SNORM]:ih.FLOAT,[t.RGB565]:ih.FLOAT,[t.RGBA4]:ih.FLOAT,[t.RGB5_A1]:ih.FLOAT,[t.RGBA8]:ih.FLOAT,[t.RGBA8_SNORM]:ih.FLOAT,[t.RGB10_A2]:ih.FLOAT,[t.RGB10_A2UI]:ih.FLOAT,[t.SRGB8]:ih.FLOAT,[t.SRGB8_ALPHA8]:ih.FLOAT,[t.R16F]:ih.FLOAT,[t.RG16F]:ih.FLOAT,[t.RGB16F]:ih.FLOAT,[t.RGBA16F]:ih.FLOAT,[t.R32F]:ih.FLOAT,[t.RG32F]:ih.FLOAT,[t.RGB32F]:ih.FLOAT,[t.RGBA32F]:ih.FLOAT,[t.R11F_G11F_B10F]:ih.FLOAT,[t.RGB9_E5]:ih.FLOAT,[t.R8I]:ih.INT,[t.R8UI]:ih.UINT,[t.R16I]:ih.INT,[t.R16UI]:ih.UINT,[t.R32I]:ih.INT,[t.R32UI]:ih.UINT,[t.RG8I]:ih.INT,[t.RG8UI]:ih.UINT,[t.RG16I]:ih.INT,[t.RG16UI]:ih.UINT,[t.RG32I]:ih.INT,[t.RG32UI]:ih.UINT,[t.RGB8I]:ih.INT,[t.RGB8UI]:ih.UINT,[t.RGB16I]:ih.INT,[t.RGB16UI]:ih.UINT,[t.RGB32I]:ih.INT,[t.RGB32UI]:ih.UINT,[t.RGBA8I]:ih.INT,[t.RGBA8UI]:ih.UINT,[t.RGBA16I]:ih.INT,[t.RGBA16UI]:ih.UINT,[t.RGBA32I]:ih.INT,[t.RGBA32UI]:ih.UINT,[t.DEPTH_COMPONENT16]:ih.FLOAT,[t.DEPTH_COMPONENT24]:ih.FLOAT,[t.DEPTH_COMPONENT32F]:ih.FLOAT,[t.DEPTH_STENCIL]:ih.FLOAT,[t.DEPTH24_STENCIL8]:ih.FLOAT,[t.DEPTH32F_STENCIL8]:ih.FLOAT}:{[t.RGB]:ih.FLOAT,[t.RGBA]:ih.FLOAT,[t.ALPHA]:ih.FLOAT,[t.LUMINANCE]:ih.FLOAT,[t.LUMINANCE_ALPHA]:ih.FLOAT,[t.DEPTH_STENCIL]:ih.FLOAT},e}(t);const e=t.getParameter(t.MAX_TEXTURE_IMAGE_UNITS);this.boundTextures.length=e;for(let r=0;r<e;r++)this.boundTextures[r]=null;this.emptyTextures={};const i=new tg(t.createTexture());t.bindTexture(t.TEXTURE_2D,i.texture),t.texImage2D(t.TEXTURE_2D,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,new Uint8Array(4)),this.emptyTextures[t.TEXTURE_2D]=i,this.emptyTextures[t.TEXTURE_CUBE_MAP]=new tg(t.createTexture()),t.bindTexture(t.TEXTURE_CUBE_MAP,this.emptyTextures[t.TEXTURE_CUBE_MAP].texture);for(let r=0;r<6;r++)t.texImage2D(t.TEXTURE_CUBE_MAP_POSITIVE_X+r,0,t.RGBA,1,1,0,t.RGBA,t.UNSIGNED_BYTE,null);t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_MAG_FILTER,t.LINEAR),t.texParameteri(t.TEXTURE_CUBE_MAP,t.TEXTURE_MIN_FILTER,t.LINEAR);for(let r=0;r<this.boundTextures.length;r++)this.bind(null,r)}bind(t,e=0){const{gl:i}=this;if(t=t?.castToBaseTexture(),t?.valid&&!t.parentTextureArray){t.touched=this.renderer.textureGC.count;const r=t._glTextures[this.CONTEXT_UID]||this.initTexture(t);this.boundTextures[e]!==t&&(this.currentLocation!==e&&(this.currentLocation=e,i.activeTexture(i.TEXTURE0+e)),i.bindTexture(t.target,r.texture)),r.dirtyId!==t.dirtyId?(this.currentLocation!==e&&(this.currentLocation=e,i.activeTexture(i.TEXTURE0+e)),this.updateTexture(t)):r.dirtyStyleId!==t.dirtyStyleId&&this.updateTextureStyle(t),this.boundTextures[e]=t}else this.currentLocation!==e&&(this.currentLocation=e,i.activeTexture(i.TEXTURE0+e)),i.bindTexture(i.TEXTURE_2D,this.emptyTextures[i.TEXTURE_2D].texture),this.boundTextures[e]=null}reset(){this._unknownBoundTextures=!0,this.hasIntegerTextures=!1,this.currentLocation=-1;for(let t=0;t<this.boundTextures.length;t++)this.boundTextures[t]=this.unknownTexture}unbind(t){const{gl:e,boundTextures:i}=this;if(this._unknownBoundTextures){this._unknownBoundTextures=!1;for(let t=0;t<i.length;t++)i[t]===this.unknownTexture&&this.bind(null,t)}for(let r=0;r<i.length;r++)i[r]===t&&(this.currentLocation!==r&&(e.activeTexture(e.TEXTURE0+r),this.currentLocation=r),e.bindTexture(t.target,this.emptyTextures[t.target].texture),i[r]=null)}ensureSamplerType(t){const{boundTextures:e,hasIntegerTextures:i,CONTEXT_UID:r}=this;if(i)for(let s=t-1;s>=0;--s){const t=e[s];t&&t._glTextures[r].samplerType!==ih.FLOAT&&this.renderer.texture.unbind(t)}}initTexture(t){const e=new tg(this.gl.createTexture());return e.dirtyId=-1,t._glTextures[this.CONTEXT_UID]=e,this.managedTextures.push(t),t.on("dispose",this.destroyTexture,this),e}initTextureType(t,e){e.internalFormat=this.internalFormats[t.type]?.[t.format]??t.format,e.samplerType=this.samplerTypes[e.internalFormat]??ih.FLOAT,2===this.webGLVersion&&t.type===eh.HALF_FLOAT?e.type=this.gl.HALF_FLOAT:e.type=t.type}updateTexture(t){const e=t._glTextures[this.CONTEXT_UID];if(!e)return;const i=this.renderer;if(this.initTextureType(t,e),t.resource?.upload(i,t,e))e.samplerType!==ih.FLOAT&&(this.hasIntegerTextures=!0);else{const r=t.realWidth,s=t.realHeight,n=i.gl;(e.width!==r||e.height!==s||e.dirtyId<0)&&(e.width=r,e.height=s,n.texImage2D(t.target,0,e.internalFormat,r,s,0,t.format,e.type,null))}t.dirtyStyleId!==e.dirtyStyleId&&this.updateTextureStyle(t),e.dirtyId=t.dirtyId}destroyTexture(t,e){const{gl:i}=this;if((t=t.castToBaseTexture())._glTextures[this.CONTEXT_UID]&&(this.unbind(t),i.deleteTexture(t._glTextures[this.CONTEXT_UID].texture),t.off("dispose",this.destroyTexture,this),delete t._glTextures[this.CONTEXT_UID],!e)){const e=this.managedTextures.indexOf(t);-1!==e&&rp(this.managedTextures,e,1)}}updateTextureStyle(t){const e=t._glTextures[this.CONTEXT_UID];e&&(t.mipmap!==nh.POW2&&2===this.webGLVersion||t.isPowerOfTwo?e.mipmap=t.mipmap>=1:e.mipmap=!1,2===this.webGLVersion||t.isPowerOfTwo?e.wrapMode=t.wrapMode:e.wrapMode=sh.CLAMP,t.resource?.style(this.renderer,t,e)||this.setStyle(t,e),e.dirtyStyleId=t.dirtyStyleId)}setStyle(t,e){const i=this.gl;if(e.mipmap&&t.mipmap!==nh.ON_MANUAL&&i.generateMipmap(t.target),i.texParameteri(t.target,i.TEXTURE_WRAP_S,e.wrapMode),i.texParameteri(t.target,i.TEXTURE_WRAP_T,e.wrapMode),e.mipmap){i.texParameteri(t.target,i.TEXTURE_MIN_FILTER,t.scaleMode===rh.LINEAR?i.LINEAR_MIPMAP_LINEAR:i.NEAREST_MIPMAP_NEAREST);const e=this.renderer.context.extensions.anisotropicFiltering;if(e&&t.anisotropicLevel>0&&t.scaleMode===rh.LINEAR){const r=Math.min(t.anisotropicLevel,i.getParameter(e.MAX_TEXTURE_MAX_ANISOTROPY_EXT));i.texParameterf(t.target,e.TEXTURE_MAX_ANISOTROPY_EXT,r)}}else i.texParameteri(t.target,i.TEXTURE_MIN_FILTER,t.scaleMode===rh.LINEAR?i.LINEAR:i.NEAREST);i.texParameteri(t.target,i.TEXTURE_MAG_FILTER,t.scaleMode===rh.LINEAR?i.LINEAR:i.NEAREST)}destroy(){this.renderer=null}}eg.extension={type:_p.RendererSystem,name:"texture"},Ep.add(eg);class ig{constructor(t){this.renderer=t}contextChange(){this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID}bind(t){const{gl:e,CONTEXT_UID:i}=this,r=t._glTransformFeedbacks[i]||this.createGLTransformFeedback(t);e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,r)}unbind(){const{gl:t}=this;t.bindTransformFeedback(t.TRANSFORM_FEEDBACK,null)}beginTransformFeedback(t,e){const{gl:i,renderer:r}=this;e&&r.shader.bind(e),i.beginTransformFeedback(t)}endTransformFeedback(){const{gl:t}=this;t.endTransformFeedback()}createGLTransformFeedback(t){const{gl:e,renderer:i,CONTEXT_UID:r}=this,s=e.createTransformFeedback();t._glTransformFeedbacks[r]=s,e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,s);for(let n=0;n<t.buffers.length;n++){const s=t.buffers[n];s&&(i.buffer.update(s),s._glBuffers[r].refCount++,e.bindBufferBase(e.TRANSFORM_FEEDBACK_BUFFER,n,s._glBuffers[r].buffer||null))}return e.bindTransformFeedback(e.TRANSFORM_FEEDBACK,null),t.disposeRunner.add(this),s}disposeTransformFeedback(t,e){const i=t._glTransformFeedbacks[this.CONTEXT_UID],r=this.gl;t.disposeRunner.remove(this);const s=this.renderer.buffer;if(s)for(let n=0;n<t.buffers.length;n++){const i=t.buffers[n];if(!i)continue;const r=i._glBuffers[this.CONTEXT_UID];r&&(r.refCount--,0===r.refCount&&!e&&s.dispose(i,e))}i&&(e||r.deleteTransformFeedback(i),delete t._glTransformFeedbacks[this.CONTEXT_UID])}destroy(){this.renderer=null}}ig.extension={type:_p.RendererSystem,name:"transformFeedback"},Ep.add(ig);class rg{constructor(t){this.renderer=t}init(t){this.screen=new Qp(0,0,t.width,t.height),this.element=t.view||ph.ADAPTER.createCanvas(),this.resolution=t.resolution||ph.RESOLUTION,this.autoDensity=!!t.autoDensity}resizeView(t,e){this.element.width=Math.round(t*this.resolution),this.element.height=Math.round(e*this.resolution);const i=this.element.width/this.resolution,r=this.element.height/this.resolution;this.screen.width=i,this.screen.height=r,this.autoDensity&&(this.element.style.width=`${i}px`,this.element.style.height=`${r}px`),this.renderer.emit("resize",i,r),this.renderer.runners.resize.emit(this.screen.width,this.screen.height)}destroy(t){t&&this.element.parentNode?.removeChild(this.element),this.renderer=null,this.element=null,this.screen=null}}rg.defaultOptions={width:800,height:600,resolution:void 0,autoDensity:!1},rg.extension={type:[_p.RendererSystem,_p.CanvasRendererSystem],name:"_view"},Ep.add(rg),ph.PREFER_ENV=Vl.WEBGL2,ph.STRICT_TEXTURE_CACHE=!1,ph.RENDER_OPTIONS={...Zf.defaultOptions,...qf.defaultOptions,...rg.defaultOptions,...Vm.defaultOptions},Object.defineProperties(ph,{WRAP_MODE:{get:()=>Bp.defaultOptions.wrapMode,set(t){dd("7.1.0","settings.WRAP_MODE is deprecated, use BaseTexture.defaultOptions.wrapMode"),Bp.defaultOptions.wrapMode=t}},SCALE_MODE:{get:()=>Bp.defaultOptions.scaleMode,set(t){dd("7.1.0","settings.SCALE_MODE is deprecated, use BaseTexture.defaultOptions.scaleMode"),Bp.defaultOptions.scaleMode=t}},MIPMAP_TEXTURES:{get:()=>Bp.defaultOptions.mipmap,set(t){dd("7.1.0","settings.MIPMAP_TEXTURES is deprecated, use BaseTexture.defaultOptions.mipmap"),Bp.defaultOptions.mipmap=t}},ANISOTROPIC_LEVEL:{get:()=>Bp.defaultOptions.anisotropicLevel,set(t){dd("7.1.0","settings.ANISOTROPIC_LEVEL is deprecated, use BaseTexture.defaultOptions.anisotropicLevel"),Bp.defaultOptions.anisotropicLevel=t}},FILTER_RESOLUTION:{get:()=>(dd("7.1.0","settings.FILTER_RESOLUTION is deprecated, use Filter.defaultResolution"),Vf.defaultResolution),set(t){Vf.defaultResolution=t}},FILTER_MULTISAMPLE:{get:()=>(dd("7.1.0","settings.FILTER_MULTISAMPLE is deprecated, use Filter.defaultMultisample"),Vf.defaultMultisample),set(t){Vf.defaultMultisample=t}},SPRITE_MAX_TEXTURES:{get:()=>jf.defaultMaxTextures,set(t){dd("7.1.0","settings.SPRITE_MAX_TEXTURES is deprecated, use BatchRenderer.defaultMaxTextures"),jf.defaultMaxTextures=t}},SPRITE_BATCH_SIZE:{get:()=>jf.defaultBatchSize,set(t){dd("7.1.0","settings.SPRITE_BATCH_SIZE is deprecated, use BatchRenderer.defaultBatchSize"),jf.defaultBatchSize=t}},CAN_UPLOAD_SAME_BUFFER:{get:()=>jf.canUploadSameBuffer,set(t){dd("7.1.0","settings.CAN_UPLOAD_SAME_BUFFER is deprecated, use BatchRenderer.canUploadSameBuffer"),jf.canUploadSameBuffer=t}},GC_MODE:{get:()=>Qm.defaultMode,set(t){dd("7.1.0","settings.GC_MODE is deprecated, use TextureGCSystem.defaultMode"),Qm.defaultMode=t}},GC_MAX_IDLE:{get:()=>Qm.defaultMaxIdle,set(t){dd("7.1.0","settings.GC_MAX_IDLE is deprecated, use TextureGCSystem.defaultMaxIdle"),Qm.defaultMaxIdle=t}},GC_MAX_CHECK_COUNT:{get:()=>Qm.defaultCheckCountMax,set(t){dd("7.1.0","settings.GC_MAX_CHECK_COUNT is deprecated, use TextureGCSystem.defaultCheckCountMax"),Qm.defaultCheckCountMax=t}},PRECISION_VERTEX:{get:()=>Df.defaultVertexPrecision,set(t){dd("7.1.0","settings.PRECISION_VERTEX is deprecated, use Program.defaultVertexPrecision"),Df.defaultVertexPrecision=t}},PRECISION_FRAGMENT:{get:()=>Df.defaultFragmentPrecision,set(t){dd("7.1.0","settings.PRECISION_FRAGMENT is deprecated, use Program.defaultFragmentPrecision"),Df.defaultFragmentPrecision=t}}});var sg=/* @__PURE__ */(t=>(t[t.INTERACTION=50]="INTERACTION",t[t.HIGH=25]="HIGH",t[t.NORMAL=0]="NORMAL",t[t.LOW=-25]="LOW",t[t.UTILITY=-50]="UTILITY",t))(sg||{});class ng{constructor(t,e=null,i=0,r=!1){this.next=null,this.previous=null,this._destroyed=!1,this.fn=t,this.context=e,this.priority=i,this.once=r}match(t,e=null){return this.fn===t&&this.context===e}emit(t){this.fn&&(this.context?this.fn.call(this.context,t):this.fn(t));const e=this.next;return this.once&&this.destroy(!0),this._destroyed&&(this.next=null),e}connect(t){this.previous=t,t.next&&(t.next.previous=this),this.next=t.next,t.next=this}destroy(t=!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 e=this.next;return this.next=t?null:e,this.previous=null,e}}const og=class t{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 ng(null,null,1/0),this.deltaMS=1/t.targetFPMS,this.elapsedMS=1/t.targetFPMS,this._tick=t=>{this._requestId=null,this.started&&(this.update(t),this.started&&null===this._requestId&&this._head.next&&(this._requestId=requestAnimationFrame(this._tick)))}}_requestIfNeeded(){null===this._requestId&&this._head.next&&(this.lastTime=performance.now(),this._lastFrame=this.lastTime,this._requestId=requestAnimationFrame(this._tick))}_cancelIfNeeded(){null!==this._requestId&&(cancelAnimationFrame(this._requestId),this._requestId=null)}_startIfPossible(){this.started?this._requestIfNeeded():this.autoStart&&this.start()}add(t,e,i=sg.NORMAL){return this._addListener(new ng(t,e,i))}addOnce(t,e,i=sg.NORMAL){return this._addListener(new ng(t,e,i,!0))}_addListener(t){let e=this._head.next,i=this._head;if(e){for(;e;){if(t.priority>e.priority){t.connect(i);break}i=e,e=e.next}t.previous||t.connect(i)}else t.connect(i);return this._startIfPossible(),this}remove(t,e){let i=this._head.next;for(;i;)i=i.match(t,e)?i.destroy():i.next;return this._head.next||this._cancelIfNeeded(),this}get count(){if(!this._head)return 0;let t=0,e=this._head;for(;e=e.next;)t++;return t}start(){this.started||(this.started=!0,this._requestIfNeeded())}stop(){this.started&&(this.started=!1,this._cancelIfNeeded())}destroy(){if(!this._protected){this.stop();let t=this._head.next;for(;t;)t=t.destroy(!0);this._head.destroy(),this._head=null}}update(e=performance.now()){let i;if(e>this.lastTime){if(i=this.elapsedMS=e-this.lastTime,i>this._maxElapsedMS&&(i=this._maxElapsedMS),i*=this.speed,this._minElapsedMS){const t=e-this._lastFrame|0;if(t<this._minElapsedMS)return;this._lastFrame=e-t%this._minElapsedMS}this.deltaMS=i,this.deltaTime=this.deltaMS*t.targetFPMS;const r=this._head;let s=r.next;for(;s;)s=s.emit(this.deltaTime);r.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 i=Math.min(this.maxFPS,e),r=Math.min(Math.max(0,i)/1e3,t.targetFPMS);this._maxElapsedMS=1/r}get maxFPS(){return this._minElapsedMS?Math.round(1e3/this._minElapsedMS):0}set maxFPS(t){if(0===t)this._minElapsedMS=0;else{const e=Math.max(this.minFPS,t);this._minElapsedMS=1/(e/1e3)}}static get shared(){if(!t._shared){const e=t._shared=new t;e.autoStart=!0,e._protected=!0}return t._shared}static get system(){if(!t._system){const e=t._system=new t;e.autoStart=!0,e._protected=!0}return t._system}};og.targetFPMS=.06;let ag=og;Object.defineProperties(ph,{TARGET_FPMS:{get:()=>ag.targetFPMS,set(t){dd("7.1.0","settings.TARGET_FPMS is deprecated, use Ticker.targetFPMS"),ag.targetFPMS=t}}});class lg{static init(t){t=Object.assign({autoStart:!0,sharedTicker:!1},t),Object.defineProperty(this,"ticker",{set(t){this._ticker&&this._ticker.remove(this.render,this),this._ticker=t,t&&t.add(this.render,this,sg.LOW)},get(){return this._ticker}}),this.stop=()=>{this._ticker.stop()},this.start=()=>{this._ticker.start()},this._ticker=null,this.ticker=t.sharedTicker?ag.shared:new ag,t.autoStart&&this.start()}static destroy(){if(this._ticker){const t=this._ticker;this.ticker=null,t.destroy()}}}lg.extension=_p.Application,Ep.add(lg);const hg=[];Ep.handleByList(_p.Renderer,hg);class ug{constructor(t){this.renderer=t}contextChange(t){let e;if(1===this.renderer.context.webGLVersion){const i=t.getParameter(t.FRAMEBUFFER_BINDING);t.bindFramebuffer(t.FRAMEBUFFER,null),e=t.getParameter(t.SAMPLES),t.bindFramebuffer(t.FRAMEBUFFER,i)}else{const i=t.getParameter(t.DRAW_FRAMEBUFFER_BINDING);t.bindFramebuffer(t.DRAW_FRAMEBUFFER,null),e=t.getParameter(t.SAMPLES),t.bindFramebuffer(t.DRAW_FRAMEBUFFER,i)}e>=ch.HIGH?this.multisample=ch.HIGH:e>=ch.MEDIUM?this.multisample=ch.MEDIUM:e>=ch.LOW?this.multisample=ch.LOW:this.multisample=ch.NONE}destroy(){}}ug.extension={type:_p.RendererSystem,name:"_multisample"},Ep.add(ug);class cg{constructor(t){this.buffer=t||null,this.updateID=-1,this.byteLength=-1,this.refCount=0}}class dg{constructor(t){this.renderer=t,this.managedBuffers={},this.boundBufferBases={}}destroy(){this.renderer=null}contextChange(){this.disposeAll(!0),this.gl=this.renderer.gl,this.CONTEXT_UID=this.renderer.CONTEXT_UID}bind(t){const{gl:e,CONTEXT_UID:i}=this,r=t._glBuffers[i]||this.createGLBuffer(t);e.bindBuffer(t.type,r.buffer)}unbind(t){const{gl:e}=this;e.bindBuffer(t,null)}bindBufferBase(t,e){const{gl:i,CONTEXT_UID:r}=this;if(this.boundBufferBases[e]!==t){const s=t._glBuffers[r]||this.createGLBuffer(t);this.boundBufferBases[e]=t,i.bindBufferBase(i.UNIFORM_BUFFER,e,s.buffer)}}bindBufferRange(t,e,i){const{gl:r,CONTEXT_UID:s}=this;i=i||0;const n=t._glBuffers[s]||this.createGLBuffer(t);r.bindBufferRange(r.UNIFORM_BUFFER,e||0,n.buffer,256*i,256)}update(t){const{gl:e,CONTEXT_UID:i}=this,r=t._glBuffers[i]||this.createGLBuffer(t);if(t._updateID!==r.updateID)if(r.updateID=t._updateID,e.bindBuffer(t.type,r.buffer),r.byteLength>=t.data.byteLength)e.bufferSubData(t.type,0,t.data);else{const i=t.static?e.STATIC_DRAW:e.DYNAMIC_DRAW;r.byteLength=t.data.byteLength,e.bufferData(t.type,t.data,i)}}dispose(t,e){if(!this.managedBuffers[t.id])return;delete this.managedBuffers[t.id];const i=t._glBuffers[this.CONTEXT_UID],r=this.gl;t.disposeRunner.remove(this),i&&(e||r.deleteBuffer(i.buffer),delete t._glBuffers[this.CONTEXT_UID])}disposeAll(t){const e=Object.keys(this.managedBuffers);for(let i=0;i<e.length;i++)this.dispose(this.managedBuffers[e[i]],t)}createGLBuffer(t){const{CONTEXT_UID:e,gl:i}=this;return t._glBuffers[e]=new cg(i.createBuffer()),this.managedBuffers[t.id]=t,t.disposeRunner.add(this),t._glBuffers[e]}}dg.extension={type:_p.RendererSystem,name:"buffer"},Ep.add(dg);class pg{constructor(t){this.renderer=t}render(t,e){const i=this.renderer;let r,s,n,o;if(e&&(r=e.renderTexture,s=e.clear,n=e.transform,o=e.skipUpdateTransform),this.renderingToScreen=!r,i.runners.prerender.emit(),i.emit("prerender"),i.projection.transform=n,!i.context.isLost){if(r||(this.lastObjectRendered=t),!o){const e=t.enableTempParent();t.updateTransform(),t.disableTempParent(e)}i.renderTexture.bind(r),i.batch.currentRenderer.start(),(s??i.background.clearBeforeRender)&&i.renderTexture.clear(),t.render(i),i.batch.currentRenderer.flush(),r&&(e.blit&&i.framebuffer.blit(),r.baseTexture.update()),i.runners.postrender.emit(),i.projection.transform=null,i.emit("postrender")}}destroy(){this.renderer=null,this.lastObjectRendered=null}}pg.extension={type:_p.RendererSystem,name:"objectRenderer"},Ep.add(pg);const fg=class t extends Km{constructor(e){super(),this.type=ql.WEBGL,e=Object.assign({},ph.RENDER_OPTIONS,e),this.gl=null,this.CONTEXT_UID=0,this.globalUniforms=new Gf({projectionMatrix:new nf},!0);const i={runners:["init","destroy","contextChange","resolutionChange","reset","update","postrender","prerender","resize"],systems:t.__systems,priority:["_view","textureGenerator","background","_plugin","startup","context","state","texture","buffer","geometry","framebuffer","transformFeedback","mask","scissor","stencil","projection","textureGC","filter","renderTexture","batch","objectRenderer","_multisample"]};this.setup(i),"useContextAlpha"in e&&(dd("7.0.0","options.useContextAlpha is deprecated, use options.premultipliedAlpha and options.backgroundAlpha instead"),e.premultipliedAlpha=e.useContextAlpha&&"notMultiplied"!==e.useContextAlpha,e.backgroundAlpha=!1===e.useContextAlpha?1:e.backgroundAlpha),this._plugin.rendererPlugins=t.__plugins,this.options=e,this.startup.run(this.options)}static test(t){return!t?.forceCanvas&&xd()}render(t,e){this.objectRenderer.render(t,e)}resize(t,e){this._view.resizeView(t,e)}reset(){return this.runners.reset.emit(),this}clear(){this.renderTexture.bind(),this.renderTexture.clear()}destroy(t=!1){this.runners.destroy.items.reverse(),this.emitWithCustomOptions(this.runners.destroy,{_view:t}),super.destroy()}get plugins(){return this._plugin.plugins}get multisample(){return this._multisample.multisample}get width(){return this._view.element.width}get height(){return this._view.element.height}get resolution(){return this._view.resolution}set resolution(t){this._view.resolution=t,this.runners.resolutionChange.emit(t)}get autoDensity(){return this._view.autoDensity}get view(){return this._view.element}get screen(){return this._view.screen}get lastObjectRendered(){return this.objectRenderer.lastObjectRendered}get renderingToScreen(){return this.objectRenderer.renderingToScreen}get rendererLogId(){return`WebGL ${this.context.webGLVersion}`}get clearBeforeRender(){return dd("7.0.0","renderer.clearBeforeRender has been deprecated, please use renderer.background.clearBeforeRender instead."),this.background.clearBeforeRender}get useContextAlpha(){return dd("7.0.0","renderer.useContextAlpha has been deprecated, please use renderer.context.premultipliedAlpha instead."),this.context.useContextAlpha}get preserveDrawingBuffer(){return dd("7.0.0","renderer.preserveDrawingBuffer has been deprecated, we cannot truly know this unless pixi created the context"),this.context.preserveDrawingBuffer}get backgroundColor(){return dd("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color}set backgroundColor(t){dd("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color=t}get backgroundAlpha(){return dd("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha}set backgroundAlpha(t){dd("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha=t}get powerPreference(){return dd("7.0.0","renderer.powerPreference has been deprecated, we can only know this if pixi creates the context"),this.context.powerPreference}generateTexture(t,e){return this.textureGenerator.generateTexture(t,e)}};fg.extension={type:_p.Renderer,priority:1},fg.__plugins={},fg.__systems={};let mg=fg;Ep.handleByMap(_p.RendererPlugin,mg.__plugins),Ep.handleByMap(_p.RendererSystem,mg.__systems),Ep.add(mg);class gg extends Np{constructor(t,e){const{width:i,height:r}=e||{};super(i,r),this.items=[],this.itemDirtyIds=[];for(let s=0;s<t;s++){const t=new Bp;this.items.push(t),this.itemDirtyIds.push(-2)}this.length=t,this._load=null,this.baseTexture=null}initFromArray(t,e){for(let i=0;i<this.length;i++)t[i]&&(t[i].castToBaseTexture?this.addBaseTextureAt(t[i].castToBaseTexture(),i):t[i]instanceof Np?this.addResourceAt(t[i],i):this.addResourceAt(Mp(t[i],e),i))}dispose(){for(let t=0,e=this.length;t<e;t++)this.items[t].destroy();this.items=null,this.itemDirtyIds=null,this._load=null}addResourceAt(t,e){if(!this.items[e])throw new Error(`Index ${e} is out of bounds`);return t.valid&&!this.valid&&this.resize(t.width,t.height),this.items[e].setResource(t),this}bind(t){if(null!==this.baseTexture)throw new Error("Only one base texture per TextureArray is allowed");super.bind(t);for(let e=0;e<this.length;e++)this.items[e].parentTextureArray=t,this.items[e].on("update",t.update,t)}unbind(t){super.unbind(t);for(let e=0;e<this.length;e++)this.items[e].parentTextureArray=null,this.items[e].off("update",t.update,t)}load(){if(this._load)return this._load;const t=this.items.map(t=>t.resource).filter(t=>t).map(t=>t.load());return this._load=Promise.all(t).then(()=>{const{realWidth:t,realHeight:e}=this.items[0];return this.resize(t,e),this.update(),Promise.resolve(this)}),this._load}}class yg extends em{constructor(t){super(t)}static test(t){const{OffscreenCanvas:e}=globalThis;return!!(e&&t instanceof e)||globalThis.HTMLCanvasElement&&t instanceof HTMLCanvasElement}}const vg=class t extends gg{constructor(e,i){const{width:r,height:s,autoLoad:n,linkBaseTexture:o}=i||{};if(e&&e.length!==t.SIDES)throw new Error(`Invalid length. Got ${e.length}, expected 6`);super(6,{width:r,height:s});for(let a=0;a<t.SIDES;a++)this.items[a].target=th.TEXTURE_CUBE_MAP_POSITIVE_X+a;this.linkBaseTexture=!1!==o,e&&this.initFromArray(e,i),!1!==n&&this.load()}bind(t){super.bind(t),t.target=th.TEXTURE_CUBE_MAP}addBaseTextureAt(t,e,i){if(void 0===i&&(i=this.linkBaseTexture),!this.items[e])throw new Error(`Index ${e} is out of bounds`);if(!this.linkBaseTexture||t.parentTextureArray||Object.keys(t._glTextures).length>0){if(!t.resource)throw new Error("CubeResource does not support copying of renderTexture.");this.addResourceAt(t.resource,e)}else t.target=th.TEXTURE_CUBE_MAP_POSITIVE_X+e,t.parentTextureArray=this.baseTexture,this.items[e]=t;return t.valid&&!this.valid&&this.resize(t.realWidth,t.realHeight),this.items[e]=t,this}upload(e,i,r){const s=this.itemDirtyIds;for(let n=0;n<t.SIDES;n++){const t=this.items[n];(s[n]<t.dirtyId||r.dirtyId<i.dirtyId)&&(t.valid&&t.resource?(t.resource.upload(e,t,r),s[n]=t.dirtyId):s[n]<-1&&(e.gl.texImage2D(t.target,0,r.internalFormat,i.realWidth,i.realHeight,0,i.format,r.type,null),s[n]=-1))}return!0}static test(e){return Array.isArray(e)&&e.length===t.SIDES}};vg.SIDES=6;let xg=vg;class bg extends em{constructor(t,e){let i,r,s;e=e||{},"string"==typeof t?(i=bg.EMPTY,r=t,s=!0):(i=t,r=null,s=!1),super(i),this.url=r,this.crossOrigin=e.crossOrigin??!0,this.alphaMode="number"==typeof e.alphaMode?e.alphaMode:null,this.ownsImageBitmap=e.ownsImageBitmap??s,this._load=null,!1!==e.autoLoad&&this.load()}load(){return this._load||(this._load=new Promise(async(t,e)=>{if(null!==this.url)try{const e=await ph.ADAPTER.fetch(this.url,{mode:this.crossOrigin?"cors":"no-cors"});if(this.destroyed)return;const i=await e.blob();if(this.destroyed)return;const r=await createImageBitmap(i,{premultiplyAlpha:null===this.alphaMode||this.alphaMode===oh.UNPACK?"premultiply":"none"});if(this.destroyed)return void r.close();this.source=r,this.update(),t(this)}catch(i){if(this.destroyed)return;e(i),this.onError.emit(i)}else t(this)})),this._load}upload(t,e,i){return this.source instanceof ImageBitmap?("number"==typeof this.alphaMode&&(e.alphaMode=this.alphaMode),super.upload(t,e,i)):(this.load(),!1)}dispose(){this.ownsImageBitmap&&this.source instanceof ImageBitmap&&this.source.close(),super.dispose(),this._load=null}static test(t){return!!globalThis.createImageBitmap&&typeof ImageBitmap<"u"&&("string"==typeof t||t instanceof ImageBitmap)}static get EMPTY(){return bg._EMPTY=bg._EMPTY??ph.ADAPTER.createCanvas(0,0),bg._EMPTY}}const _g=class t extends em{constructor(t,e){e=e||{},super(ph.ADAPTER.createCanvas()),this._width=0,this._height=0,this.svg=t,this.scale=e.scale||1,this._overrideWidth=e.width,this._overrideHeight=e.height,this._resolve=null,this._crossorigin=e.crossorigin,this._load=null,!1!==e.autoLoad&&this.load()}load(){return this._load||(this._load=new Promise(e=>{if(this._resolve=()=>{this.update(),e(this)},t.SVG_XML.test(this.svg.trim())){if(!btoa)throw new Error("Your browser doesn't support base64 conversions.");this.svg=`data:image/svg+xml;base64,${btoa(unescape(encodeURIComponent(this.svg)))}`}this._loadSvg()})),this._load}_loadSvg(){const t=new Image;em.crossOrigin(t,this.svg,this._crossorigin),t.src=this.svg,t.onerror=e=>{this._resolve&&(t.onerror=null,this.onError.emit(e))},t.onload=()=>{if(!this._resolve)return;const e=t.width,i=t.height;if(!e||!i)throw new Error("The SVG image must have width and height defined (in pixels), canvas API needs them.");let r=e*this.scale,s=i*this.scale;(this._overrideWidth||this._overrideHeight)&&(r=this._overrideWidth||this._overrideHeight/i*e,s=this._overrideHeight||this._overrideWidth/e*i),r=Math.round(r),s=Math.round(s);const n=this.source;n.width=r,n.height=s,n._pixiId=`canvas_${op()}`,n.getContext("2d").drawImage(t,0,0,e,i,0,0,r,s),this._resolve(),this._resolve=null}}static getSize(e){const i=t.SVG_SIZE.exec(e),r={};return i&&(r[i[1]]=Math.round(parseFloat(i[3])),r[i[5]]=Math.round(parseFloat(i[7]))),r}dispose(){super.dispose(),this._resolve=null,this._crossorigin=null}static test(e,i){return"svg"===i||"string"==typeof e&&e.startsWith("data:image/svg+xml")||"string"==typeof e&&t.SVG_XML.test(e)}};_g.SVG_XML=/^(<\?xml[^?]+\?>)?\s*(<!--[^(-->)]*-->)?\s*\<svg/m,_g.SVG_SIZE=/<svg[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*(?:\s(width|height)=('|")(\d*(?:\.\d+)?)(?:px)?('|"))[^>]*>/i;let wg=_g;const Pg=class t extends em{constructor(e,i){if(i=i||{},!(e instanceof HTMLVideoElement)){const r=document.createElement("video");!1!==i.autoLoad&&r.setAttribute("preload","auto"),!1!==i.playsinline&&(r.setAttribute("webkit-playsinline",""),r.setAttribute("playsinline","")),!0===i.muted&&(r.setAttribute("muted",""),r.muted=!0),!0===i.loop&&r.setAttribute("loop",""),!1!==i.autoPlay&&r.setAttribute("autoplay",""),"string"==typeof e&&(e=[e]);const s=e[0].src||e[0];em.crossOrigin(r,s,i.crossorigin);for(let i=0;i<e.length;++i){const s=document.createElement("source");let{src:n,mime:o}=e[i];if(n=n||e[i],n.startsWith("data:"))o=n.slice(5,n.indexOf(";"));else if(!n.startsWith("blob:")){const e=n.split("?").shift().toLowerCase(),i=e.slice(e.lastIndexOf(".")+1);o=o||t.MIME_TYPES[i]||`video/${i}`}s.src=n,o&&(s.type=o),r.appendChild(s)}e=r}super(e),this.noSubImage=!0,this._autoUpdate=!0,this._isConnectedToTicker=!1,this._updateFPS=i.updateFPS||0,this._msToNextUpdate=0,this.autoPlay=!1!==i.autoPlay,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._onError=this._onError.bind(this),this._onPlayStart=this._onPlayStart.bind(this),this._onPlayStop=this._onPlayStop.bind(this),this._onSeeked=this._onSeeked.bind(this),!1!==i.autoLoad&&this.load()}update(t=0){if(!this.destroyed){if(this._updateFPS){const t=ag.shared.elapsedMS*this.source.playbackRate;this._msToNextUpdate=Math.floor(this._msToNextUpdate-t)}(!this._updateFPS||this._msToNextUpdate<=0)&&(super.update(),this._msToNextUpdate=this._updateFPS?Math.floor(1e3/this._updateFPS):0)}}_videoFrameRequestCallback(){this.update(),this.destroyed?this._videoFrameRequestCallbackHandle=null:this._videoFrameRequestCallbackHandle=this.source.requestVideoFrameCallback(this._videoFrameRequestCallback)}load(){if(this._load)return this._load;const t=this.source;return(t.readyState===t.HAVE_ENOUGH_DATA||t.readyState===t.HAVE_FUTURE_DATA)&&t.width&&t.height&&(t.complete=!0),t.addEventListener("play",this._onPlayStart),t.addEventListener("pause",this._onPlayStop),t.addEventListener("seeked",this._onSeeked),this._isSourceReady()?this._onCanPlay():(t.addEventListener("canplay",this._onCanPlay),t.addEventListener("canplaythrough",this._onCanPlay),t.addEventListener("error",this._onError,!0)),this._load=new Promise((e,i)=>{this.valid?e(this):(this._resolve=e,this._reject=i,t.load())}),this._load}_onError(t){this.source.removeEventListener("error",this._onError,!0),this.onError.emit(t),this._reject&&(this._reject(t),this._reject=null,this._resolve=null)}_isSourcePlaying(){const t=this.source;return!t.paused&&!t.ended}_isSourceReady(){return this.source.readyState>2}_onPlayStart(){this.valid||this._onCanPlay(),this._configureAutoUpdate()}_onPlayStop(){this._configureAutoUpdate()}_onSeeked(){this._autoUpdate&&!this._isSourcePlaying()&&(this._msToNextUpdate=0,this.update(),this._msToNextUpdate=0)}_onCanPlay(){const t=this.source;t.removeEventListener("canplay",this._onCanPlay),t.removeEventListener("canplaythrough",this._onCanPlay);const e=this.valid;this._msToNextUpdate=0,this.update(),this._msToNextUpdate=0,!e&&this._resolve&&(this._resolve(this),this._resolve=null,this._reject=null),this._isSourcePlaying()?this._onPlayStart():this.autoPlay&&t.play()}dispose(){this._configureAutoUpdate();const t=this.source;t&&(t.removeEventListener("play",this._onPlayStart),t.removeEventListener("pause",this._onPlayStop),t.removeEventListener("seeked",this._onSeeked),t.removeEventListener("canplay",this._onCanPlay),t.removeEventListener("canplaythrough",this._onCanPlay),t.removeEventListener("error",this._onError,!0),t.pause(),t.src="",t.load()),super.dispose()}get autoUpdate(){return this._autoUpdate}set autoUpdate(t){t!==this._autoUpdate&&(this._autoUpdate=t,this._configureAutoUpdate())}get updateFPS(){return this._updateFPS}set updateFPS(t){t!==this._updateFPS&&(this._updateFPS=t,this._configureAutoUpdate())}_configureAutoUpdate(){this._autoUpdate&&this._isSourcePlaying()?!this._updateFPS&&this.source.requestVideoFrameCallback?(this._isConnectedToTicker&&(ag.shared.remove(this.update,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0),null===this._videoFrameRequestCallbackHandle&&(this._videoFrameRequestCallbackHandle=this.source.requestVideoFrameCallback(this._videoFrameRequestCallback))):(null!==this._videoFrameRequestCallbackHandle&&(this.source.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker||(ag.shared.add(this.update,this),this._isConnectedToTicker=!0,this._msToNextUpdate=0)):(null!==this._videoFrameRequestCallbackHandle&&(this.source.cancelVideoFrameCallback(this._videoFrameRequestCallbackHandle),this._videoFrameRequestCallbackHandle=null),this._isConnectedToTicker&&(ag.shared.remove(this.update,this),this._isConnectedToTicker=!1,this._msToNextUpdate=0))}static test(e,i){return globalThis.HTMLVideoElement&&e instanceof HTMLVideoElement||t.TYPES.includes(i)}};Pg.TYPES=["mp4","m4v","webm","ogg","ogv","h264","avi","mov"],Pg.MIME_TYPES={ogv:"video/ogg",mov:"video/quicktime",m4v:"video/mp4"};let Eg=Pg;Cp.push(bg,im,yg,Eg,class extends em{constructor(t){super(t)}static test(t){return!!globalThis.VideoFrame&&t instanceof globalThis.VideoFrame}},wg,Lp,xg,class extends gg{constructor(t,e){const{width:i,height:r}=e||{};let s,n;Array.isArray(t)?(s=t,n=t.length):n=t,super(n,{width:i,height:r}),s&&this.initFromArray(s,e)}addBaseTextureAt(t,e){if(!t.resource)throw new Error("ArrayResource does not support RenderTexture");return this.addResourceAt(t.resource,e),this}bind(t){super.bind(t),t.target=th.TEXTURE_2D_ARRAY}upload(t,e,i){const{length:r,itemDirtyIds:s,items:n}=this,{gl:o}=t;i.dirtyId<0&&o.texImage3D(o.TEXTURE_2D_ARRAY,0,i.internalFormat,this._width,this._height,r,0,e.format,i.type,null);for(let a=0;a<r;a++){const t=n[a];s[a]<t.dirtyId&&(s[a]=t.dirtyId,t.valid&&o.texSubImage3D(o.TEXTURE_2D_ARRAY,0,0,0,a,t.resource.width,t.resource.height,1,e.format,i.type,t.resource.source))}return!0}});class Tg{constructor(){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0,this.rect=null,this.updateID=-1}isEmpty(){return this.minX>this.maxX||this.minY>this.maxY}clear(){this.minX=1/0,this.minY=1/0,this.maxX=-1/0,this.maxY=-1/0}getRectangle(t){return this.minX>this.maxX||this.minY>this.maxY?Qp.EMPTY:((t=t||new Qp(0,0,1,1)).x=this.minX,t.y=this.minY,t.width=this.maxX-this.minX,t.height=this.maxY-this.minY,t)}addPoint(t){this.minX=Math.min(this.minX,t.x),this.maxX=Math.max(this.maxX,t.x),this.minY=Math.min(this.minY,t.y),this.maxY=Math.max(this.maxY,t.y)}addPointMatrix(t,e){const{a:i,b:r,c:s,d:n,tx:o,ty:a}=t,l=i*e.x+s*e.y+o,h=r*e.x+n*e.y+a;this.minX=Math.min(this.minX,l),this.maxX=Math.max(this.maxX,l),this.minY=Math.min(this.minY,h),this.maxY=Math.max(this.maxY,h)}addQuad(t){let e=this.minX,i=this.minY,r=this.maxX,s=this.maxY,n=t[0],o=t[1];e=n<e?n:e,i=o<i?o:i,r=n>r?n:r,s=o>s?o:s,n=t[2],o=t[3],e=n<e?n:e,i=o<i?o:i,r=n>r?n:r,s=o>s?o:s,n=t[4],o=t[5],e=n<e?n:e,i=o<i?o:i,r=n>r?n:r,s=o>s?o:s,n=t[6],o=t[7],e=n<e?n:e,i=o<i?o:i,r=n>r?n:r,s=o>s?o:s,this.minX=e,this.minY=i,this.maxX=r,this.maxY=s}addFrame(t,e,i,r,s){this.addFrameMatrix(t.worldTransform,e,i,r,s)}addFrameMatrix(t,e,i,r,s){const n=t.a,o=t.b,a=t.c,l=t.d,h=t.tx,u=t.ty;let c=this.minX,d=this.minY,p=this.maxX,f=this.maxY,m=n*e+a*i+h,g=o*e+l*i+u;c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,m=n*r+a*i+h,g=o*r+l*i+u,c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,m=n*e+a*s+h,g=o*e+l*s+u,c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,m=n*r+a*s+h,g=o*r+l*s+u,c=m<c?m:c,d=g<d?g:d,p=m>p?m:p,f=g>f?g:f,this.minX=c,this.minY=d,this.maxX=p,this.maxY=f}addVertexData(t,e,i){let r=this.minX,s=this.minY,n=this.maxX,o=this.maxY;for(let a=e;a<i;a+=2){const e=t[a],i=t[a+1];r=e<r?e:r,s=i<s?i:s,n=e>n?e:n,o=i>o?i:o}this.minX=r,this.minY=s,this.maxX=n,this.maxY=o}addVertices(t,e,i,r){this.addVerticesMatrix(t.worldTransform,e,i,r)}addVerticesMatrix(t,e,i,r,s=0,n=s){const o=t.a,a=t.b,l=t.c,h=t.d,u=t.tx,c=t.ty;let d=this.minX,p=this.minY,f=this.maxX,m=this.maxY;for(let g=i;g<r;g+=2){const t=e[g],i=e[g+1],r=o*t+l*i+u,y=h*i+a*t+c;d=Math.min(d,r-s),f=Math.max(f,r+s),p=Math.min(p,y-n),m=Math.max(m,y+n)}this.minX=d,this.minY=p,this.maxX=f,this.maxY=m}addBounds(t){const e=this.minX,i=this.minY,r=this.maxX,s=this.maxY;this.minX=t.minX<e?t.minX:e,this.minY=t.minY<i?t.minY:i,this.maxX=t.maxX>r?t.maxX:r,this.maxY=t.maxY>s?t.maxY:s}addBoundsMask(t,e){const i=t.minX>e.minX?t.minX:e.minX,r=t.minY>e.minY?t.minY:e.minY,s=t.maxX<e.maxX?t.maxX:e.maxX,n=t.maxY<e.maxY?t.maxY:e.maxY;if(i<=s&&r<=n){const t=this.minX,e=this.minY,o=this.maxX,a=this.maxY;this.minX=i<t?i:t,this.minY=r<e?r:e,this.maxX=s>o?s:o,this.maxY=n>a?n:a}}addBoundsMatrix(t,e){this.addFrameMatrix(e,t.minX,t.minY,t.maxX,t.maxY)}addBoundsArea(t,e){const i=t.minX>e.x?t.minX:e.x,r=t.minY>e.y?t.minY:e.y,s=t.maxX<e.x+e.width?t.maxX:e.x+e.width,n=t.maxY<e.y+e.height?t.maxY:e.y+e.height;if(i<=s&&r<=n){const t=this.minX,e=this.minY,o=this.maxX,a=this.maxY;this.minX=i<t?i:t,this.minY=r<e?r:e,this.maxX=s>o?s:o,this.maxY=n>a?n:a}}pad(t=0,e=t){this.isEmpty()||(this.minX-=t,this.maxX+=t,this.minY-=e,this.maxY+=e)}addFramePad(t,e,i,r,s,n){t-=s,e-=n,i+=s,r+=n,this.minX=this.minX<t?this.minX:t,this.maxX=this.maxX>i?this.maxX:i,this.minY=this.minY<e?this.minY:e,this.maxY=this.maxY>r?this.maxY:r}}class Ag extends kh{constructor(){super(),this.tempDisplayObjectParent=null,this.transform=new gf,this.alpha=1,this.visible=!0,this.renderable=!0,this.cullable=!1,this.cullArea=null,this.parent=null,this.worldAlpha=1,this._lastSortedIndex=0,this._zIndex=0,this.filterArea=null,this.filters=null,this._enabledFilters=null,this._bounds=new Tg,this._localBounds=null,this._boundsID=0,this._boundsRect=null,this._localBoundsRect=null,this._mask=null,this._maskRefCount=0,this._destroyed=!1,this.isSprite=!1,this.isMask=!1}static mixin(t){const e=Object.keys(t);for(let i=0;i<e.length;++i){const r=e[i];Object.defineProperty(Ag.prototype,r,Object.getOwnPropertyDescriptor(t,r))}}get destroyed(){return this._destroyed}_recursivePostUpdateTransform(){this.parent?(this.parent._recursivePostUpdateTransform(),this.transform.updateTransform(this.parent.transform)):this.transform.updateTransform(this._tempDisplayObjectParent.transform)}updateTransform(){this._boundsID++,this.transform.updateTransform(this.parent.transform),this.worldAlpha=this.alpha*this.parent.worldAlpha}getBounds(t,e){return t||(this.parent?(this._recursivePostUpdateTransform(),this.updateTransform()):(this.parent=this._tempDisplayObjectParent,this.updateTransform(),this.parent=null)),this._bounds.updateID!==this._boundsID&&(this.calculateBounds(),this._bounds.updateID=this._boundsID),e||(this._boundsRect||(this._boundsRect=new Qp),e=this._boundsRect),this._bounds.getRectangle(e)}getLocalBounds(t){t||(this._localBoundsRect||(this._localBoundsRect=new Qp),t=this._localBoundsRect),this._localBounds||(this._localBounds=new Tg);const e=this.transform,i=this.parent;this.parent=null,this._tempDisplayObjectParent.worldAlpha=i?.worldAlpha??1,this.transform=this._tempDisplayObjectParent.transform;const r=this._bounds,s=this._boundsID;this._bounds=this._localBounds;const n=this.getBounds(!1,t);return this.parent=i,this.transform=e,this._bounds=r,this._bounds.updateID+=this._boundsID-s,n}toGlobal(t,e,i=!1){return i||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.apply(t,e)}toLocal(t,e,i,r){return e&&(t=e.toGlobal(t,i,r)),r||(this._recursivePostUpdateTransform(),this.parent?this.displayObjectUpdateTransform():(this.parent=this._tempDisplayObjectParent,this.displayObjectUpdateTransform(),this.parent=null)),this.worldTransform.applyInverse(t,i)}setParent(t){if(!t||!t.addChild)throw new Error("setParent: Argument must be a Container");return t.addChild(this),t}removeFromParent(){this.parent?.removeChild(this)}setTransform(t=0,e=0,i=1,r=1,s=0,n=0,o=0,a=0,l=0){return this.position.x=t,this.position.y=e,this.scale.x=i||1,this.scale.y=r||1,this.rotation=s,this.skew.x=n,this.skew.y=o,this.pivot.x=a,this.pivot.y=l,this}destroy(t){this.removeFromParent(),this._destroyed=!0,this.transform=null,this.parent=null,this._bounds=null,this.mask=null,this.cullArea=null,this.filters=null,this.filterArea=null,this.hitArea=null,this.eventMode="auto",this.interactiveChildren=!1,this.emit("destroyed"),this.removeAllListeners()}get _tempDisplayObjectParent(){return null===this.tempDisplayObjectParent&&(this.tempDisplayObjectParent=new Ig),this.tempDisplayObjectParent}enableTempParent(){const t=this.parent;return this.parent=this._tempDisplayObjectParent,t}disableTempParent(t){this.parent=t}get x(){return this.position.x}set x(t){this.transform.position.x=t}get y(){return this.position.y}set y(t){this.transform.position.y=t}get worldTransform(){return this.transform.worldTransform}get localTransform(){return this.transform.localTransform}get position(){return this.transform.position}set position(t){this.transform.position.copyFrom(t)}get scale(){return this.transform.scale}set scale(t){this.transform.scale.copyFrom(t)}get pivot(){return this.transform.pivot}set pivot(t){this.transform.pivot.copyFrom(t)}get skew(){return this.transform.skew}set skew(t){this.transform.skew.copyFrom(t)}get rotation(){return this.transform.rotation}set rotation(t){this.transform.rotation=t}get angle(){return this.transform.rotation*Vp}set angle(t){this.transform.rotation=t*qp}get zIndex(){return this._zIndex}set zIndex(t){this._zIndex!==t&&(this._zIndex=t,this.parent&&(this.parent.sortDirty=!0))}get worldVisible(){let t=this;do{if(!t.visible)return!1;t=t.parent}while(t);return!0}get mask(){return this._mask}set mask(t){if(this._mask!==t){if(this._mask){const t=this._mask.isMaskData?this._mask.maskObject:this._mask;t&&(t._maskRefCount--,0===t._maskRefCount&&(t.renderable=!0,t.isMask=!1))}if(this._mask=t,this._mask){const t=this._mask.isMaskData?this._mask.maskObject:this._mask;t&&(0===t._maskRefCount&&(t.renderable=!1,t.isMask=!0),t._maskRefCount++)}}}}class Ig extends Ag{constructor(){super(...arguments),this.sortDirty=null}}Ag.prototype.displayObjectUpdateTransform=Ag.prototype.updateTransform;const Sg=new nf;function Cg(t,e){return t.zIndex===e.zIndex?t._lastSortedIndex-e._lastSortedIndex:t.zIndex-e.zIndex}const Mg=class t extends Ag{constructor(){super(),this.children=[],this.sortableChildren=t.defaultSortableChildren,this.sortDirty=!1}onChildrenChange(t){}addChild(...t){if(t.length>1)for(let e=0;e<t.length;e++)this.addChild(t[e]);else{const e=t[0];e.parent&&e.parent.removeChild(e),e.parent=this,this.sortDirty=!0,e.transform._parentID=-1,this.children.push(e),this._boundsID++,this.onChildrenChange(this.children.length-1),this.emit("childAdded",e,this,this.children.length-1),e.emit("added",this)}return t[0]}addChildAt(t,e){if(e<0||e>this.children.length)throw new Error(`${t}addChildAt: The index ${e} supplied is out of bounds ${this.children.length}`);return t.parent&&t.parent.removeChild(t),t.parent=this,this.sortDirty=!0,t.transform._parentID=-1,this.children.splice(e,0,t),this._boundsID++,this.onChildrenChange(e),t.emit("added",this),this.emit("childAdded",t,this,e),t}swapChildren(t,e){if(t===e)return;const i=this.getChildIndex(t),r=this.getChildIndex(e);this.children[i]=e,this.children[r]=t,this.onChildrenChange(i<r?i:r)}getChildIndex(t){const e=this.children.indexOf(t);if(-1===e)throw new Error("The supplied DisplayObject must be a child of the caller");return e}setChildIndex(t,e){if(e<0||e>=this.children.length)throw new Error(`The index ${e} supplied is out of bounds ${this.children.length}`);const i=this.getChildIndex(t);rp(this.children,i,1),this.children.splice(e,0,t),this.onChildrenChange(e)}getChildAt(t){if(t<0||t>=this.children.length)throw new Error(`getChildAt: Index (${t}) does not exist.`);return this.children[t]}removeChild(...t){if(t.length>1)for(let e=0;e<t.length;e++)this.removeChild(t[e]);else{const e=t[0],i=this.children.indexOf(e);if(-1===i)return null;e.parent=null,e.transform._parentID=-1,rp(this.children,i,1),this._boundsID++,this.onChildrenChange(i),e.emit("removed",this),this.emit("childRemoved",e,this,i)}return t[0]}removeChildAt(t){const e=this.getChildAt(t);return e.parent=null,e.transform._parentID=-1,rp(this.children,t,1),this._boundsID++,this.onChildrenChange(t),e.emit("removed",this),this.emit("childRemoved",e,this,t),e}removeChildren(t=0,e=this.children.length){const i=t,r=e-i;let s;if(r>0&&r<=e){s=this.children.splice(i,r);for(let t=0;t<s.length;++t)s[t].parent=null,s[t].transform&&(s[t].transform._parentID=-1);this._boundsID++,this.onChildrenChange(t);for(let t=0;t<s.length;++t)s[t].emit("removed",this),this.emit("childRemoved",s[t],this,t);return s}if(0===r&&0===this.children.length)return[];throw new RangeError("removeChildren: numeric values are outside the acceptable range.")}sortChildren(){let t=!1;for(let e=0,i=this.children.length;e<i;++e){const i=this.children[e];i._lastSortedIndex=e,!t&&0!==i.zIndex&&(t=!0)}t&&this.children.length>1&&this.children.sort(Cg),this.sortDirty=!1}updateTransform(){this.sortableChildren&&this.sortDirty&&this.sortChildren(),this._boundsID++,this.transform.updateTransform(this.parent.transform),this.worldAlpha=this.alpha*this.parent.worldAlpha;for(let t=0,e=this.children.length;t<e;++t){const e=this.children[t];e.visible&&e.updateTransform()}}calculateBounds(){this._bounds.clear(),this._calculateBounds();for(let t=0;t<this.children.length;t++){const e=this.children[t];if(e.visible&&e.renderable)if(e.calculateBounds(),e._mask){const t=e._mask.isMaskData?e._mask.maskObject:e._mask;t?(t.calculateBounds(),this._bounds.addBoundsMask(e._bounds,t._bounds)):this._bounds.addBounds(e._bounds)}else e.filterArea?this._bounds.addBoundsArea(e._bounds,e.filterArea):this._bounds.addBounds(e._bounds)}this._bounds.updateID=this._boundsID}getLocalBounds(t,e=!1){const i=super.getLocalBounds(t);if(!e)for(let r=0,s=this.children.length;r<s;++r){const t=this.children[r];t.visible&&t.updateTransform()}return i}_calculateBounds(){}_renderWithCulling(e){const i=e.renderTexture.sourceFrame;if(!(i.width>0&&i.height>0))return;let r,s;this.cullArea?(r=this.cullArea,s=this.worldTransform):this._render!==t.prototype._render&&(r=this.getBounds(!0));const n=e.projection.transform;if(n&&(s?(s=Sg.copyFrom(s),s.prepend(n)):s=n),r&&i.intersects(r,s))this._render(e);else if(this.cullArea)return;for(let t=0,o=this.children.length;t<o;++t){const i=this.children[t],r=i.cullable;i.cullable=r||!this.cullArea,i.render(e),i.cullable=r}}render(t){if(this.visible&&!(this.worldAlpha<=0)&&this.renderable)if(this._mask||this.filters?.length)this.renderAdvanced(t);else if(this.cullable)this._renderWithCulling(t);else{this._render(t);for(let e=0,i=this.children.length;e<i;++e)this.children[e].render(t)}}renderAdvanced(t){const e=this.filters,i=this._mask;if(e){this._enabledFilters||(this._enabledFilters=[]),this._enabledFilters.length=0;for(let t=0;t<e.length;t++)e[t].enabled&&this._enabledFilters.push(e[t])}const r=e&&this._enabledFilters?.length||i&&(!i.isMaskData||i.enabled&&(i.autoDetect||i.type!==uh.NONE));if(r&&t.batch.flush(),e&&this._enabledFilters?.length&&t.filter.push(this,this._enabledFilters),i&&t.mask.push(this,this._mask),this.cullable)this._renderWithCulling(t);else{this._render(t);for(let e=0,i=this.children.length;e<i;++e)this.children[e].render(t)}r&&t.batch.flush(),i&&t.mask.pop(this),e&&this._enabledFilters?.length&&t.filter.pop()}_render(t){}destroy(t){super.destroy(),this.sortDirty=!1;const e="boolean"==typeof t?t:t?.children,i=this.removeChildren(0,this.children.length);if(e)for(let r=0;r<i.length;++r)i[r].destroy(t)}get width(){return this.scale.x*this.getLocalBounds().width}set width(t){const e=this.getLocalBounds().width;this.scale.x=0!==e?t/e:1,this._width=t}get height(){return this.scale.y*this.getLocalBounds().height}set height(t){const e=this.getLocalBounds().height;this.scale.y=0!==e?t/e:1,this._height=t}};Mg.defaultSortableChildren=!1;let Og=Mg;Og.prototype.containerUpdateTransform=Og.prototype.updateTransform,Object.defineProperties(ph,{SORTABLE_CHILDREN:{get:()=>Og.defaultSortableChildren,set(t){dd("7.1.0","settings.SORTABLE_CHILDREN is deprecated, use Container.defaultSortableChildren"),Og.defaultSortableChildren=t}}});const Ng=new Kp,Lg=new Uint16Array([0,1,2,0,2,3]);class Rg extends Og{constructor(t){super(),this._anchor=new ff(this._onAnchorUpdate,this,t?t.defaultAnchor.x:0,t?t.defaultAnchor.y:0),this._texture=null,this._width=0,this._height=0,this._tintColor=new qd(16777215),this._tintRGB=null,this.tint=16777215,this.blendMode=Kl.NORMAL,this._cachedTint=16777215,this.uvs=null,this.texture=t||om.EMPTY,this.vertexData=new Float32Array(8),this.vertexTrimmedData=null,this._transformID=-1,this._textureID=-1,this._transformTrimmedID=-1,this._textureTrimmedID=-1,this.indices=Lg,this.pluginName="batch",this.isSprite=!0,this._roundPixels=ph.ROUND_PIXELS}_onTextureUpdate(){this._textureID=-1,this._textureTrimmedID=-1,this._cachedTint=16777215,this._width&&(this.scale.x=sp(this.scale.x)*this._width/this._texture.orig.width),this._height&&(this.scale.y=sp(this.scale.y)*this._height/this._texture.orig.height)}_onAnchorUpdate(){this._transformID=-1,this._transformTrimmedID=-1}calculateVertices(){const t=this._texture;if(this._transformID===this.transform._worldID&&this._textureID===t._updateID)return;this._textureID!==t._updateID&&(this.uvs=this._texture._uvs.uvsFloat32),this._transformID=this.transform._worldID,this._textureID=t._updateID;const e=this.transform.worldTransform,i=e.a,r=e.b,s=e.c,n=e.d,o=e.tx,a=e.ty,l=this.vertexData,h=t.trim,u=t.orig,c=this._anchor;let d=0,p=0,f=0,m=0;if(h?(p=h.x-c._x*u.width,d=p+h.width,m=h.y-c._y*u.height,f=m+h.height):(p=-c._x*u.width,d=p+u.width,m=-c._y*u.height,f=m+u.height),l[0]=i*p+s*m+o,l[1]=n*m+r*p+a,l[2]=i*d+s*m+o,l[3]=n*m+r*d+a,l[4]=i*d+s*f+o,l[5]=n*f+r*d+a,l[6]=i*p+s*f+o,l[7]=n*f+r*p+a,this._roundPixels){const t=ph.RESOLUTION;for(let e=0;e<l.length;++e)l[e]=Math.round(l[e]*t)/t}}calculateTrimmedVertices(){if(this.vertexTrimmedData){if(this._transformTrimmedID===this.transform._worldID&&this._textureTrimmedID===this._texture._updateID)return}else this.vertexTrimmedData=new Float32Array(8);this._transformTrimmedID=this.transform._worldID,this._textureTrimmedID=this._texture._updateID;const t=this._texture,e=this.vertexTrimmedData,i=t.orig,r=this._anchor,s=this.transform.worldTransform,n=s.a,o=s.b,a=s.c,l=s.d,h=s.tx,u=s.ty,c=-r._x*i.width,d=c+i.width,p=-r._y*i.height,f=p+i.height;if(e[0]=n*c+a*p+h,e[1]=l*p+o*c+u,e[2]=n*d+a*p+h,e[3]=l*p+o*d+u,e[4]=n*d+a*f+h,e[5]=l*f+o*d+u,e[6]=n*c+a*f+h,e[7]=l*f+o*c+u,this._roundPixels){const t=ph.RESOLUTION;for(let i=0;i<e.length;++i)e[i]=Math.round(e[i]*t)/t}}_render(t){this.calculateVertices(),t.batch.setObjectRenderer(t.plugins[this.pluginName]),t.plugins[this.pluginName].render(this)}_calculateBounds(){const t=this._texture.trim,e=this._texture.orig;!t||t.width===e.width&&t.height===e.height?(this.calculateVertices(),this._bounds.addQuad(this.vertexData)):(this.calculateTrimmedVertices(),this._bounds.addQuad(this.vertexTrimmedData))}getLocalBounds(t){return 0===this.children.length?(this._localBounds||(this._localBounds=new Tg),this._localBounds.minX=this._texture.orig.width*-this._anchor._x,this._localBounds.minY=this._texture.orig.height*-this._anchor._y,this._localBounds.maxX=this._texture.orig.width*(1-this._anchor._x),this._localBounds.maxY=this._texture.orig.height*(1-this._anchor._y),t||(this._localBoundsRect||(this._localBoundsRect=new Qp),t=this._localBoundsRect),this._localBounds.getRectangle(t)):super.getLocalBounds.call(this,t)}containsPoint(t){this.worldTransform.applyInverse(t,Ng);const e=this._texture.orig.width,i=this._texture.orig.height,r=-e*this.anchor.x;let s=0;return Ng.x>=r&&Ng.x<r+e&&(s=-i*this.anchor.y,Ng.y>=s&&Ng.y<s+i)}destroy(t){if(super.destroy(t),this._texture.off("update",this._onTextureUpdate,this),this._anchor=null,"boolean"==typeof t?t:t?.texture){const e="boolean"==typeof t?t:t?.baseTexture;this._texture.destroy(!!e)}this._texture=null}static from(t,e){const i=t instanceof om?t:om.from(t,e);return new Rg(i)}set roundPixels(t){this._roundPixels!==t&&(this._transformID=-1,this._transformTrimmedID=-1),this._roundPixels=t}get roundPixels(){return this._roundPixels}get width(){return Math.abs(this.scale.x)*this._texture.orig.width}set width(t){const e=sp(this.scale.x)||1;this.scale.x=e*t/this._texture.orig.width,this._width=t}get height(){return Math.abs(this.scale.y)*this._texture.orig.height}set height(t){const e=sp(this.scale.y)||1;this.scale.y=e*t/this._texture.orig.height,this._height=t}get anchor(){return this._anchor}set anchor(t){this._anchor.copyFrom(t)}get tint(){return this._tintColor.value}set tint(t){this._tintColor.setValue(t),this._tintRGB=this._tintColor.toLittleEndianNumber()}get tintValue(){return this._tintColor.toNumber()}get texture(){return this._texture}set texture(t){this._texture!==t&&(this._texture&&this._texture.off("update",this._onTextureUpdate,this),this._texture=t||om.EMPTY,this._cachedTint=16777215,this._textureID=-1,this._textureTrimmedID=-1,t&&(t.baseTexture.valid?this._onTextureUpdate():t.once("update",this._onTextureUpdate,this)))}}const kg={build(t){const e=t.points;let i,r,s,n,o,a;if(t.type===Jp.CIRC){const e=t.shape;i=e.x,r=e.y,o=a=e.radius,s=n=0}else if(t.type===Jp.ELIP){const e=t.shape;i=e.x,r=e.y,o=e.width,a=e.height,s=n=0}else{const e=t.shape,l=e.width/2,h=e.height/2;i=e.x+l,r=e.y+h,o=a=Math.max(0,Math.min(e.radius,Math.min(l,h))),s=l-o,n=h-a}if(!(o>=0&&a>=0&&s>=0&&n>=0))return void(e.length=0);const l=Math.ceil(2.3*Math.sqrt(o+a)),h=8*l+(s?4:0)+(n?4:0);if(e.length=h,0===h)return;if(0===l)return e.length=8,e[0]=e[6]=i+s,e[1]=e[3]=r+n,e[2]=e[4]=i-s,void(e[5]=e[7]=r-n);let u=0,c=4*l+(s?2:0)+2,d=c,p=h;{const t=s+o,a=n,l=i+t,h=i-t,f=r+a;if(e[u++]=l,e[u++]=f,e[--c]=f,e[--c]=h,n){const t=r-a;e[d++]=h,e[d++]=t,e[--p]=t,e[--p]=l}}for(let f=1;f<l;f++){const t=Math.PI/2*(f/l),h=s+Math.cos(t)*o,m=n+Math.sin(t)*a,g=i+h,y=i-h,v=r+m,x=r-m;e[u++]=g,e[u++]=v,e[--c]=v,e[--c]=y,e[d++]=y,e[d++]=x,e[--p]=x,e[--p]=g}{const t=n+a,o=i+s,l=i-s,h=r+t,c=r-t;e[u++]=o,e[u++]=h,e[--p]=c,e[--p]=o,s&&(e[u++]=l,e[u++]=h,e[--p]=c,e[--p]=l)}},triangulate(t,e){const i=t.points,r=e.points,s=e.indices;if(0===i.length)return;let n=r.length/2;const o=n;let a,l;if(t.type!==Jp.RREC){const e=t.shape;a=e.x,l=e.y}else{const e=t.shape;a=e.x+e.width/2,l=e.y+e.height/2}const h=t.matrix;r.push(t.matrix?h.a*a+h.c*l+h.tx:a,t.matrix?h.b*a+h.d*l+h.ty:l),n++,r.push(i[0],i[1]);for(let u=2;u<i.length;u+=2)r.push(i[u],i[u+1]),s.push(n++,o,n);s.push(o+1,o,n)}};function Bg(t,e=!1){const i=t.length;if(i<6)return;let r=0;for(let s=0,n=t[i-2],o=t[i-1];s<i;s+=2){const e=t[s],i=t[s+1];r+=(e-n)*(i+o),n=e,o=i}if(!e&&r>0||e&&r<=0){const e=i/2;for(let r=e+e%2;r<i;r+=2){const e=i-r-2,s=i-r-1,n=r,o=r+1;[t[e],t[n]]=[t[n],t[e]],[t[s],t[o]]=[t[o],t[s]]}}}const Fg={build(t){t.points=t.shape.points.slice()},triangulate(t,e){let i=t.points;const r=t.holes,s=e.points,n=e.indices;if(i.length>=6){Bg(i,!1);const t=[];for(let s=0;s<r.length;s++){const e=r[s];Bg(e.points,!0),t.push(i.length/2),i=i.concat(e.points)}const e=Nt(i,t,2);if(!e)return;const o=s.length/2;for(let i=0;i<e.length;i+=3)n.push(e[i]+o),n.push(e[i+1]+o),n.push(e[i+2]+o);for(let r=0;r<i.length;r++)s.push(i[r])}}},Dg={build(t){const e=t.shape,i=e.x,r=e.y,s=e.width,n=e.height,o=t.points;o.length=0,s>=0&&n>=0&&o.push(i,r,i+s,r,i+s,r+n,i,r+n)},triangulate(t,e){const i=t.points,r=e.points;if(0===i.length)return;const s=r.length/2;r.push(i[0],i[1],i[2],i[3],i[6],i[7],i[4],i[5]),e.indices.push(s,s+1,s+2,s+1,s+2,s+3)}},Ug={build(t){kg.build(t)},triangulate(t,e){kg.triangulate(t,e)}};var Gg=/* @__PURE__ */(t=>(t.MITER="miter",t.BEVEL="bevel",t.ROUND="round",t))(Gg||{}),Xg=/* @__PURE__ */(t=>(t.BUTT="butt",t.ROUND="round",t.SQUARE="square",t))(Xg||{});const Wg={adaptive:!0,maxLength:10,minSegments:8,maxSegments:2048,epsilon:1e-4,_segmentsCount(t,e=20){if(!this.adaptive||!t||isNaN(t))return e;let i=Math.ceil(t/this.maxLength);return i<this.minSegments?i=this.minSegments:i>this.maxSegments&&(i=this.maxSegments),i}};class Yg{static curveTo(t,e,i,r,s,n){const o=n[n.length-2],a=n[n.length-1]-e,l=o-t,h=r-e,u=i-t,c=Math.abs(a*u-l*h);if(c<1e-8||0===s)return(n[n.length-2]!==t||n[n.length-1]!==e)&&n.push(t,e),null;const d=a*a+l*l,p=h*h+u*u,f=a*h+l*u,m=s*Math.sqrt(d)/c,g=s*Math.sqrt(p)/c,y=m*f/d,v=g*f/p,x=m*u+g*l,b=m*h+g*a,_=l*(g+y),w=a*(g+y),P=u*(m+v),E=h*(m+v);return{cx:x+t,cy:b+e,radius:s,startAngle:Math.atan2(w-b,_-x),endAngle:Math.atan2(E-b,P-x),anticlockwise:l*h>u*a}}static arc(t,e,i,r,s,n,o,a,l){const h=o-n,u=Wg._segmentsCount(Math.abs(h)*s,40*Math.ceil(Math.abs(h)/zp)),c=h/(2*u),d=2*c,p=Math.cos(c),f=Math.sin(c),m=u-1,g=m%1/m;for(let y=0;y<=m;++y){const t=c+n+d*(y+g*y),e=Math.cos(t),o=-Math.sin(t);l.push((p*e+f*o)*s+i,(p*-o+f*e)*s+r)}}}class Hg{constructor(){this.reset()}begin(t,e,i){this.reset(),this.style=t,this.start=e,this.attribStart=i}end(t,e){this.attribSize=e-this.attribStart,this.size=t-this.start}reset(){this.style=null,this.size=0,this.start=0,this.attribStart=0,this.attribSize=0}}class $g{static curveLength(t,e,i,r,s,n,o,a){let l=0,h=0,u=0,c=0,d=0,p=0,f=0,m=0,g=0,y=0,v=0,x=t,b=e;for(let _=1;_<=10;++_)h=_/10,u=h*h,c=u*h,d=1-h,p=d*d,f=p*d,m=f*t+3*p*h*i+3*d*u*s+c*o,g=f*e+3*p*h*r+3*d*u*n+c*a,y=x-m,v=b-g,x=m,b=g,l+=Math.sqrt(y*y+v*v);return l}static curveTo(t,e,i,r,s,n,o){const a=o[o.length-2],l=o[o.length-1];o.length-=2;const h=Wg._segmentsCount($g.curveLength(a,l,t,e,i,r,s,n));let u=0,c=0,d=0,p=0,f=0;o.push(a,l);for(let m=1,g=0;m<=h;++m)g=m/h,u=1-g,c=u*u,d=c*u,p=g*g,f=p*g,o.push(d*a+3*c*g*t+3*u*p*i+f*s,d*l+3*c*g*e+3*u*p*r+f*n)}}function jg(t,e,i,r,s,n,o,a){let l,h;o?(l=r,h=-i):(l=-r,h=i);const u=t-i*s+l,c=e-r*s+h,d=t+i*n+l,p=e+r*n+h;return a.push(u,c,d,p),2}function zg(t,e,i,r,s,n,o,a){const l=i-t,h=r-e;let u=Math.atan2(l,h),c=Math.atan2(s-t,n-e);a&&u<c?u+=2*Math.PI:!a&&u>c&&(c+=2*Math.PI);let d=u;const p=c-u,f=Math.abs(p),m=Math.sqrt(l*l+h*h),g=1+(15*f*Math.sqrt(m)/Math.PI|0),y=p/g;if(d+=y,a){o.push(t,e,i,r);for(let i=1,r=d;i<g;i++,r+=y)o.push(t,e,t+Math.sin(r)*m,e+Math.cos(r)*m);o.push(t,e,s,n)}else{o.push(i,r,t,e);for(let i=1,r=d;i<g;i++,r+=y)o.push(t+Math.sin(r)*m,e+Math.cos(r)*m,t,e);o.push(s,n,t,e)}return 2*g}function Vg(t,e){t.lineStyle.native?function(t,e){let i=0;const r=t.shape,s=t.points||r.points,n=r.type!==Jp.POLY||r.closeStroke;if(0===s.length)return;const o=e.points,a=e.indices,l=s.length/2,h=o.length/2;let u=h;for(o.push(s[0],s[1]),i=1;i<l;i++)o.push(s[2*i],s[2*i+1]),a.push(u,u+1),u++;n&&a.push(u,h)}(t,e):function(t,e){const i=t.shape;let r=t.points||i.points.slice();const s=e.closePointEps;if(0===r.length)return;const n=t.lineStyle,o=new Kp(r[0],r[1]),a=new Kp(r[r.length-2],r[r.length-1]),l=i.type!==Jp.POLY||i.closeStroke,h=Math.abs(o.x-a.x)<s&&Math.abs(o.y-a.y)<s;if(l){r=r.slice(),h&&(r.pop(),r.pop(),a.set(r[r.length-2],r[r.length-1]));const t=.5*(o.x+a.x),e=.5*(a.y+o.y);r.unshift(t,e),r.push(t,e)}const u=e.points,c=r.length/2;let d=r.length;const p=u.length/2,f=n.width/2,m=f*f,g=n.miterLimit*n.miterLimit;let y=r[0],v=r[1],x=r[2],b=r[3],_=0,w=0,P=-(v-b),E=y-x,T=0,A=0,I=Math.sqrt(P*P+E*E);P/=I,E/=I,P*=f,E*=f;const S=n.alignment,C=2*(1-S),M=2*S;l||(n.cap===Xg.ROUND?d+=zg(y-P*(C-M)*.5,v-E*(C-M)*.5,y-P*C,v-E*C,y+P*M,v+E*M,u,!0)+2:n.cap===Xg.SQUARE&&(d+=jg(y,v,P,E,C,M,!0,u))),u.push(y-P*C,v-E*C,y+P*M,v+E*M);for(let L=1;L<c-1;++L){y=r[2*(L-1)],v=r[2*(L-1)+1],x=r[2*L],b=r[2*L+1],_=r[2*(L+1)],w=r[2*(L+1)+1],P=-(v-b),E=y-x,I=Math.sqrt(P*P+E*E),P/=I,E/=I,P*=f,E*=f,T=-(b-w),A=x-_,I=Math.sqrt(T*T+A*A),T/=I,A/=I,T*=f,A*=f;const t=x-y,e=v-b,i=x-_,s=w-b,o=t*i+e*s,a=e*i-s*t,l=a<0;if(Math.abs(a)<.001*Math.abs(o)){u.push(x-P*C,b-E*C,x+P*M,b+E*M),o>=0&&(n.join===Gg.ROUND?d+=zg(x,b,x-P*C,b-E*C,x-T*C,b-A*C,u,!1)+4:d+=2,u.push(x-T*M,b-A*M,x+T*C,b+A*C));continue}const h=(-P+y)*(-E+b)-(-P+x)*(-E+v),c=(-T+_)*(-A+b)-(-T+x)*(-A+w),p=(t*c-i*h)/a,S=(s*h-e*c)/a,O=(p-x)*(p-x)+(S-b)*(S-b),N=x+(p-x)*C,R=b+(S-b)*C,k=x-(p-x)*M,B=b-(S-b)*M,F=l?C:M,D=O<=Math.min(t*t+e*e,i*i+s*s)+F*F*m;let U=n.join;if(U===Gg.MITER&&O/m>g&&(U=Gg.BEVEL),D)switch(U){case Gg.MITER:u.push(N,R,k,B);break;case Gg.BEVEL:l?u.push(N,R,x+P*M,b+E*M,N,R,x+T*M,b+A*M):u.push(x-P*C,b-E*C,k,B,x-T*C,b-A*C,k,B),d+=2;break;case Gg.ROUND:l?(u.push(N,R,x+P*M,b+E*M),d+=zg(x,b,x+P*M,b+E*M,x+T*M,b+A*M,u,!0)+4,u.push(N,R,x+T*M,b+A*M)):(u.push(x-P*C,b-E*C,k,B),d+=zg(x,b,x-P*C,b-E*C,x-T*C,b-A*C,u,!1)+4,u.push(x-T*C,b-A*C,k,B))}else{switch(u.push(x-P*C,b-E*C,x+P*M,b+E*M),U){case Gg.MITER:l?u.push(k,B,k,B):u.push(N,R,N,R),d+=2;break;case Gg.ROUND:d+=l?zg(x,b,x+P*M,b+E*M,x+T*M,b+A*M,u,!0)+2:zg(x,b,x-P*C,b-E*C,x-T*C,b-A*C,u,!1)+2}u.push(x-T*C,b-A*C,x+T*M,b+A*M),d+=2}}y=r[2*(c-2)],v=r[2*(c-2)+1],x=r[2*(c-1)],b=r[2*(c-1)+1],P=-(v-b),E=y-x,I=Math.sqrt(P*P+E*E),P/=I,E/=I,P*=f,E*=f,u.push(x-P*C,b-E*C,x+P*M,b+E*M),l||(n.cap===Xg.ROUND?d+=zg(x-P*(C-M)*.5,b-E*(C-M)*.5,x-P*C,b-E*C,x+P*M,b+E*M,u,!1)+2:n.cap===Xg.SQUARE&&(d+=jg(x,b,P,E,C,M,!1,u)));const O=e.indices,N=Wg.epsilon*Wg.epsilon;for(let L=p;L<d+p-2;++L)y=u[2*L],v=u[2*L+1],x=u[2*(L+1)],b=u[2*(L+1)+1],_=u[2*(L+2)],w=u[2*(L+2)+1],!(Math.abs(y*(b-w)+x*(w-v)+_*(v-b))<N)&&O.push(L,L+1,L+2)}(t,e)}class qg{static curveLength(t,e,i,r,s,n){const o=t-2*i+s,a=e-2*r+n,l=2*i-2*t,h=2*r-2*e,u=4*(o*o+a*a),c=4*(o*l+a*h),d=l*l+h*h,p=2*Math.sqrt(u+c+d),f=Math.sqrt(u),m=2*u*f,g=2*Math.sqrt(d),y=c/f;return(m*p+f*c*(p-g)+(4*d*u-c*c)*Math.log((2*f+y+p)/(y+g)))/(4*m)}static curveTo(t,e,i,r,s){const n=s[s.length-2],o=s[s.length-1],a=Wg._segmentsCount(qg.curveLength(n,o,t,e,i,r));let l=0,h=0;for(let u=1;u<=a;++u){const c=u/a;l=n+(t-n)*c,h=o+(e-o)*c,s.push(l+(t+(i-t)*c-l)*c,h+(e+(r-e)*c-h)*c)}}}const Jg={[Jp.POLY]:Fg,[Jp.CIRC]:kg,[Jp.ELIP]:kg,[Jp.RECT]:Dg,[Jp.RREC]:Ug},Kg=[],Zg=[];class Qg{constructor(t,e=null,i=null,r=null){this.points=[],this.holes=[],this.shape=t,this.lineStyle=i,this.fillStyle=e,this.matrix=r,this.type=t.type}clone(){return new Qg(this.shape,this.fillStyle,this.lineStyle,this.matrix)}destroy(){this.shape=null,this.holes.length=0,this.holes=null,this.points.length=0,this.points=null,this.lineStyle=null,this.fillStyle=null}}const ty=new Kp,ey=class t extends jp{constructor(){super(),this.closePointEps=1e-4,this.boundsPadding=0,this.uvsFloat32=null,this.indicesUint16=null,this.batchable=!1,this.points=[],this.colors=[],this.uvs=[],this.indices=[],this.textureIds=[],this.graphicsData=[],this.drawCalls=[],this.batchDirty=-1,this.batches=[],this.dirty=0,this.cacheDirty=-1,this.clearDirty=0,this.shapeIndex=0,this._bounds=new Tg,this.boundsDirty=-1}get bounds(){return this.updateBatches(),this.boundsDirty!==this.dirty&&(this.boundsDirty=this.dirty,this.calculateBounds()),this._bounds}invalidate(){this.boundsDirty=-1,this.dirty++,this.batchDirty++,this.shapeIndex=0,this.points.length=0,this.colors.length=0,this.uvs.length=0,this.indices.length=0,this.textureIds.length=0;for(let t=0;t<this.drawCalls.length;t++)this.drawCalls[t].texArray.clear(),Zg.push(this.drawCalls[t]);this.drawCalls.length=0;for(let t=0;t<this.batches.length;t++){const e=this.batches[t];e.reset(),Kg.push(e)}this.batches.length=0}clear(){return this.graphicsData.length>0&&(this.invalidate(),this.clearDirty++,this.graphicsData.length=0),this}drawShape(t,e=null,i=null,r=null){const s=new Qg(t,e,i,r);return this.graphicsData.push(s),this.dirty++,this}drawHole(t,e=null){if(!this.graphicsData.length)return null;const i=new Qg(t,null,null,e),r=this.graphicsData[this.graphicsData.length-1];return i.lineStyle=r.lineStyle,r.holes.push(i),this.dirty++,this}destroy(){super.destroy();for(let t=0;t<this.graphicsData.length;++t)this.graphicsData[t].destroy();this.points.length=0,this.points=null,this.colors.length=0,this.colors=null,this.uvs.length=0,this.uvs=null,this.indices.length=0,this.indices=null,this.indexBuffer.destroy(),this.indexBuffer=null,this.graphicsData.length=0,this.graphicsData=null,this.drawCalls.length=0,this.drawCalls=null,this.batches.length=0,this.batches=null,this._bounds=null}containsPoint(t){const e=this.graphicsData;for(let i=0;i<e.length;++i){const r=e[i];if(r.fillStyle.visible&&r.shape&&(r.matrix?r.matrix.applyInverse(t,ty):ty.copyFrom(t),r.shape.contains(ty.x,ty.y))){let t=!1;if(r.holes)for(let e=0;e<r.holes.length;e++)if(r.holes[e].shape.contains(ty.x,ty.y)){t=!0;break}if(!t)return!0}}return!1}updateBatches(){if(!this.graphicsData.length)return void(this.batchable=!0);if(!this.validateBatching())return;this.cacheDirty=this.dirty;const t=this.uvs,e=this.graphicsData;let i=null,r=null;this.batches.length>0&&(i=this.batches[this.batches.length-1],r=i.style);for(let a=this.shapeIndex;a<e.length;a++){this.shapeIndex++;const s=e[a],n=s.fillStyle,o=s.lineStyle;Jg[s.type].build(s),s.matrix&&this.transformPoints(s.points,s.matrix),(n.visible||o.visible)&&this.processHoles(s.holes);for(let e=0;e<2;e++){const a=0===e?n:o;if(!a.visible)continue;const l=a.texture.baseTexture,h=this.indices.length,u=this.points.length/2;l.wrapMode=sh.REPEAT,0===e?this.processFill(s):this.processLine(s);const c=this.points.length/2-u;0!==c&&(i&&!this._compareStyles(r,a)&&(i.end(h,u),i=null),i||(i=Kg.pop()||new Hg,i.begin(a,h,u),this.batches.push(i),r=a),this.addUvs(this.points,t,a.texture,u,c,a.matrix))}}const s=this.indices.length,n=this.points.length/2;if(i&&i.end(s,n),0===this.batches.length)return void(this.batchable=!0);const o=n>65535;this.indicesUint16&&this.indices.length===this.indicesUint16.length&&o===this.indicesUint16.BYTES_PER_ELEMENT>2?this.indicesUint16.set(this.indices):this.indicesUint16=o?new Uint32Array(this.indices):new Uint16Array(this.indices),this.batchable=this.isBatchable(),this.batchable?this.packBatches():this.buildDrawCalls()}_compareStyles(t,e){return!(!t||!e||t.texture.baseTexture!==e.texture.baseTexture||t.color+t.alpha!==e.color+e.alpha||!!t.native!=!!e.native)}validateBatching(){if(this.dirty===this.cacheDirty||!this.graphicsData.length)return!1;for(let t=0,e=this.graphicsData.length;t<e;t++){const e=this.graphicsData[t],i=e.fillStyle,r=e.lineStyle;if(i&&!i.texture.baseTexture.valid||r&&!r.texture.baseTexture.valid)return!1}return!0}packBatches(){this.batchDirty++,this.uvsFloat32=new Float32Array(this.uvs);const t=this.batches;for(let e=0,i=t.length;e<i;e++){const i=t[e];for(let t=0;t<i.size;t++){const e=i.start+t;this.indicesUint16[e]=this.indicesUint16[e]-i.attribStart}}}isBatchable(){if(this.points.length>131070)return!1;const e=this.batches;for(let t=0;t<e.length;t++)if(e[t].style.native)return!1;return this.points.length<2*t.BATCHABLE_SIZE}buildDrawCalls(){let t=++Bp._globalBatch;for(let u=0;u<this.drawCalls.length;u++)this.drawCalls[u].texArray.clear(),Zg.push(this.drawCalls[u]);this.drawCalls.length=0;const e=this.colors,i=this.textureIds;let r=Zg.pop();r||(r=new Fp,r.texArray=new Yf),r.texArray.count=0,r.start=0,r.size=0,r.type=Zl.TRIANGLES;let s=0,n=null,o=0,a=!1,l=Zl.TRIANGLES,h=0;this.drawCalls.push(r);for(let u=0;u<this.batches.length;u++){const c=this.batches[u],d=8,p=c.style,f=p.texture.baseTexture;a!==!!p.native&&(a=!!p.native,l=a?Zl.LINES:Zl.TRIANGLES,n=null,s=d,t++),n!==f&&(n=f,f._batchEnabled!==t&&(s===d&&(t++,s=0,r.size>0&&(r=Zg.pop(),r||(r=new Fp,r.texArray=new Yf),this.drawCalls.push(r)),r.start=h,r.size=0,r.texArray.count=0,r.type=l),f.touched=1,f._batchEnabled=t,f._batchLocation=s,f.wrapMode=sh.REPEAT,r.texArray.elements[r.texArray.count++]=f,s++)),r.size+=c.size,h+=c.size,o=f._batchLocation,this.addColors(e,p.color,p.alpha,c.attribSize,c.attribStart),this.addTextureIds(i,o,c.attribSize,c.attribStart)}Bp._globalBatch=t,this.packAttributes()}packAttributes(){const t=this.points,e=this.uvs,i=this.colors,r=this.textureIds,s=new ArrayBuffer(3*t.length*4),n=new Float32Array(s),o=new Uint32Array(s);let a=0;for(let l=0;l<t.length/2;l++)n[a++]=t[2*l],n[a++]=t[2*l+1],n[a++]=e[2*l],n[a++]=e[2*l+1],o[a++]=i[l],n[a++]=r[l];this._buffer.update(s),this._indexBuffer.update(this.indicesUint16)}processFill(t){t.holes.length?Fg.triangulate(t,this):Jg[t.type].triangulate(t,this)}processLine(t){Vg(t,this);for(let e=0;e<t.holes.length;e++)Vg(t.holes[e],this)}processHoles(t){for(let e=0;e<t.length;e++){const i=t[e];Jg[i.type].build(i),i.matrix&&this.transformPoints(i.points,i.matrix)}}calculateBounds(){const t=this._bounds;t.clear(),t.addVertexData(this.points,0,this.points.length),t.pad(this.boundsPadding,this.boundsPadding)}transformPoints(t,e){for(let i=0;i<t.length/2;i++){const r=t[2*i],s=t[2*i+1];t[2*i]=e.a*r+e.c*s+e.tx,t[2*i+1]=e.b*r+e.d*s+e.ty}}addColors(t,e,i,r,s=0){const n=qd.shared.setValue(e).toLittleEndianNumber(),o=qd.shared.setValue(n).toPremultiplied(i);t.length=Math.max(t.length,s+r);for(let a=0;a<r;a++)t[s+a]=o}addTextureIds(t,e,i,r=0){t.length=Math.max(t.length,r+i);for(let s=0;s<i;s++)t[r+s]=e}addUvs(t,e,i,r,s,n=null){let o=0;const a=e.length,l=i.frame;for(;o<s;){let i=t[2*(r+o)],s=t[2*(r+o)+1];if(n){const t=n.a*i+n.c*s+n.tx;s=n.b*i+n.d*s+n.ty,i=t}o++,e.push(i/l.width,s/l.height)}const h=i.baseTexture;(l.width<h.width||l.height<h.height)&&this.adjustUvs(e,i,a,s)}adjustUvs(t,e,i,r){const s=e.baseTexture,n=1e-6,o=i+2*r,a=e.frame,l=a.width/s.width,h=a.height/s.height;let u=a.x/a.width,c=a.y/a.height,d=Math.floor(t[i]+n),p=Math.floor(t[i+1]+n);for(let f=i+2;f<o;f+=2)d=Math.min(d,Math.floor(t[f]+n)),p=Math.min(p,Math.floor(t[f+1]+n));u-=d,c-=p;for(let f=i;f<o;f+=2)t[f]=(t[f]+u)*l,t[f+1]=(t[f+1]+c)*h}};ey.BATCHABLE_SIZE=100;let iy=ey;class ry{constructor(){this.color=16777215,this.alpha=1,this.texture=om.WHITE,this.matrix=null,this.visible=!1,this.reset()}clone(){const t=new ry;return t.color=this.color,t.alpha=this.alpha,t.texture=this.texture,t.matrix=this.matrix,t.visible=this.visible,t}reset(){this.color=16777215,this.alpha=1,this.texture=om.WHITE,this.matrix=null,this.visible=!1}destroy(){this.texture=null,this.matrix=null}}class sy extends ry{constructor(){super(...arguments),this.width=0,this.alignment=.5,this.native=!1,this.cap=Xg.BUTT,this.join=Gg.MITER,this.miterLimit=10}clone(){const t=new sy;return t.color=this.color,t.alpha=this.alpha,t.texture=this.texture,t.matrix=this.matrix,t.visible=this.visible,t.width=this.width,t.alignment=this.alignment,t.native=this.native,t.cap=this.cap,t.join=this.join,t.miterLimit=this.miterLimit,t}reset(){super.reset(),this.color=0,this.alignment=.5,this.width=0,this.native=!1,this.cap=Xg.BUTT,this.join=Gg.MITER,this.miterLimit=10}}const ny={},oy=class t extends Og{constructor(t=null){super(),this.shader=null,this.pluginName="batch",this.currentPath=null,this.batches=[],this.batchTint=-1,this.batchDirty=-1,this.vertexData=null,this._fillStyle=new ry,this._lineStyle=new sy,this._matrix=null,this._holeMode=!1,this.state=Sp.for2d(),this._geometry=t||new iy,this._geometry.refCount++,this._transformID=-1,this._tintColor=new qd(16777215),this.blendMode=Kl.NORMAL}get geometry(){return this._geometry}clone(){return this.finishPoly(),new t(this._geometry)}set blendMode(t){this.state.blendMode=t}get blendMode(){return this.state.blendMode}get tint(){return this._tintColor.value}set tint(t){this._tintColor.setValue(t)}get fill(){return this._fillStyle}get line(){return this._lineStyle}lineStyle(t=null,e=0,i,r=.5,s=!1){return"number"==typeof t&&(t={width:t,color:e,alpha:i,alignment:r,native:s}),this.lineTextureStyle(t)}lineTextureStyle(t){const e={width:0,texture:om.WHITE,color:t?.texture?16777215:0,matrix:null,alignment:.5,native:!1,cap:Xg.BUTT,join:Gg.MITER,miterLimit:10};t=Object.assign(e,t),this.normalizeColor(t),this.currentPath&&this.startPoly();const i=t.width>0&&t.alpha>0;return i?(t.matrix&&(t.matrix=t.matrix.clone(),t.matrix.invert()),Object.assign(this._lineStyle,{visible:i},t)):this._lineStyle.reset(),this}startPoly(){if(this.currentPath){const t=this.currentPath.points,e=this.currentPath.points.length;e>2&&(this.drawShape(this.currentPath),this.currentPath=new rf,this.currentPath.closeStroke=!1,this.currentPath.points.push(t[e-2],t[e-1]))}else this.currentPath=new rf,this.currentPath.closeStroke=!1}finishPoly(){this.currentPath&&(this.currentPath.points.length>2?(this.drawShape(this.currentPath),this.currentPath=null):this.currentPath.points.length=0)}moveTo(t,e){return this.startPoly(),this.currentPath.points[0]=t,this.currentPath.points[1]=e,this}lineTo(t,e){this.currentPath||this.moveTo(0,0);const i=this.currentPath.points,r=i[i.length-2],s=i[i.length-1];return(r!==t||s!==e)&&i.push(t,e),this}_initCurve(t=0,e=0){this.currentPath?0===this.currentPath.points.length&&(this.currentPath.points=[t,e]):this.moveTo(t,e)}quadraticCurveTo(t,e,i,r){this._initCurve();const s=this.currentPath.points;return 0===s.length&&this.moveTo(0,0),qg.curveTo(t,e,i,r,s),this}bezierCurveTo(t,e,i,r,s,n){return this._initCurve(),$g.curveTo(t,e,i,r,s,n,this.currentPath.points),this}arcTo(t,e,i,r,s){this._initCurve(t,e);const n=this.currentPath.points,o=Yg.curveTo(t,e,i,r,s,n);if(o){const{cx:t,cy:e,radius:i,startAngle:r,endAngle:s,anticlockwise:n}=o;this.arc(t,e,i,r,s,n)}return this}arc(t,e,i,r,s,n=!1){if(r===s)return this;if(!n&&s<=r?s+=zp:n&&r<=s&&(r+=zp),s-r===0)return this;const o=t+Math.cos(r)*i,a=e+Math.sin(r)*i,l=this._geometry.closePointEps;let h=this.currentPath?this.currentPath.points:null;if(h){const t=Math.abs(h[h.length-2]-o),e=Math.abs(h[h.length-1]-a);t<l&&e<l||h.push(o,a)}else this.moveTo(o,a),h=this.currentPath.points;return Yg.arc(o,a,t,e,i,r,s,n,h),this}beginFill(t=0,e){return this.beginTextureFill({texture:om.WHITE,color:t,alpha:e})}normalizeColor(t){const e=qd.shared.setValue(t.color??0);t.color=e.toNumber(),t.alpha??(t.alpha=e.alpha)}beginTextureFill(t){const e={texture:om.WHITE,color:16777215,matrix:null};t=Object.assign(e,t),this.normalizeColor(t),this.currentPath&&this.startPoly();const i=t.alpha>0;return i?(t.matrix&&(t.matrix=t.matrix.clone(),t.matrix.invert()),Object.assign(this._fillStyle,{visible:i},t)):this._fillStyle.reset(),this}endFill(){return this.finishPoly(),this._fillStyle.reset(),this}drawRect(t,e,i,r){return this.drawShape(new Qp(t,e,i,r))}drawRoundedRect(t,e,i,r,s){return this.drawShape(new sf(t,e,i,r,s))}drawCircle(t,e,i){return this.drawShape(new tf(t,e,i))}drawEllipse(t,e,i,r){return this.drawShape(new ef(t,e,i,r))}drawPolygon(...t){let e,i=!0;const r=t[0];r.points?(i=r.closeStroke,e=r.points):e=Array.isArray(t[0])?t[0]:t;const s=new rf(e);return s.closeStroke=i,this.drawShape(s),this}drawShape(t){return this._holeMode?this._geometry.drawHole(t,this._matrix):this._geometry.drawShape(t,this._fillStyle.clone(),this._lineStyle.clone(),this._matrix),this}clear(){return this._geometry.clear(),this._lineStyle.reset(),this._fillStyle.reset(),this._boundsID++,this._matrix=null,this._holeMode=!1,this.currentPath=null,this}isFastRect(){const t=this._geometry.graphicsData;return!(1!==t.length||t[0].shape.type!==Jp.RECT||t[0].matrix||t[0].holes.length||t[0].lineStyle.visible&&t[0].lineStyle.width)}_render(t){this.finishPoly();const e=this._geometry;e.updateBatches(),e.batchable?(this.batchDirty!==e.batchDirty&&this._populateBatches(),this._renderBatched(t)):(t.batch.flush(),this._renderDirect(t))}_populateBatches(){const t=this._geometry,e=this.blendMode,i=t.batches.length;this.batchTint=-1,this._transformID=-1,this.batchDirty=t.batchDirty,this.batches.length=i,this.vertexData=new Float32Array(t.points);for(let r=0;r<i;r++){const i=t.batches[r],s=i.style.color,n=new Float32Array(this.vertexData.buffer,4*i.attribStart*2,2*i.attribSize),o=new Float32Array(t.uvsFloat32.buffer,4*i.attribStart*2,2*i.attribSize),a={vertexData:n,blendMode:e,indices:new Uint16Array(t.indicesUint16.buffer,2*i.start,i.size),uvs:o,_batchRGB:qd.shared.setValue(s).toRgbArray(),_tintRGB:s,_texture:i.style.texture,alpha:i.style.alpha,worldAlpha:1};this.batches[r]=a}}_renderBatched(t){if(this.batches.length){t.batch.setObjectRenderer(t.plugins[this.pluginName]),this.calculateVertices(),this.calculateTints();for(let e=0,i=this.batches.length;e<i;e++){const i=this.batches[e];i.worldAlpha=this.worldAlpha*i.alpha,t.plugins[this.pluginName].render(i)}}}_renderDirect(t){const e=this._resolveDirectShader(t),i=this._geometry,r=this.worldAlpha,s=e.uniforms,n=i.drawCalls;s.translationMatrix=this.transform.worldTransform,qd.shared.setValue(this._tintColor).premultiply(r).toArray(s.tint),t.shader.bind(e),t.geometry.bind(i,e),t.state.set(this.state);for(let o=0,a=n.length;o<a;o++)this._renderDrawCallDirect(t,i.drawCalls[o])}_renderDrawCallDirect(t,e){const{texArray:i,type:r,size:s,start:n}=e,o=i.count;for(let a=0;a<o;a++)t.texture.bind(i.elements[a],a);t.geometry.draw(r,s,n)}_resolveDirectShader(t){let e=this.shader;const i=this.pluginName;if(!e){if(!ny[i]){const{maxTextures:e}=t.plugins[i],r=new Int32Array(e);for(let t=0;t<e;t++)r[t]=t;const s={tint:new Float32Array([1,1,1,1]),translationMatrix:new nf,default:Gf.from({uSamplers:r},!0)},n=t.plugins[i]._shader.program;ny[i]=new Xf(n,s)}e=ny[i]}return e}_calculateBounds(){this.finishPoly();const t=this._geometry;if(!t.graphicsData.length)return;const{minX:e,minY:i,maxX:r,maxY:s}=t.bounds;this._bounds.addFrame(this.transform,e,i,r,s)}containsPoint(e){return this.worldTransform.applyInverse(e,t._TEMP_POINT),this._geometry.containsPoint(t._TEMP_POINT)}calculateTints(){if(this.batchTint!==this.tint){this.batchTint=this._tintColor.toNumber();for(let t=0;t<this.batches.length;t++){const e=this.batches[t];e._tintRGB=qd.shared.setValue(this._tintColor).multiply(e._batchRGB).toLittleEndianNumber()}}}calculateVertices(){const t=this.transform._worldID;if(this._transformID===t)return;this._transformID=t;const e=this.transform.worldTransform,i=e.a,r=e.b,s=e.c,n=e.d,o=e.tx,a=e.ty,l=this._geometry.points,h=this.vertexData;let u=0;for(let c=0;c<l.length;c+=2){const t=l[c],e=l[c+1];h[u++]=i*t+s*e+o,h[u++]=n*e+r*t+a}}closePath(){const t=this.currentPath;return t&&(t.closeStroke=!0,this.finishPoly()),this}setMatrix(t){return this._matrix=t,this}beginHole(){return this.finishPoly(),this._holeMode=!0,this}endHole(){return this.finishPoly(),this._holeMode=!1,this}destroy(t){this._geometry.refCount--,0===this._geometry.refCount&&this._geometry.dispose(),this._matrix=null,this.currentPath=null,this._lineStyle.destroy(),this._lineStyle=null,this._fillStyle.destroy(),this._fillStyle=null,this._geometry=null,this.shader=null,this.vertexData=null,this.batches.length=0,this.batches=null,super.destroy(t)}};oy.curves=Wg,oy._TEMP_POINT=new Kp;let ay=oy;var ly=/* @__PURE__ */(t=>(t[t.LINEAR_VERTICAL=0]="LINEAR_VERTICAL",t[t.LINEAR_HORIZONTAL=1]="LINEAR_HORIZONTAL",t))(ly||{});const hy={willReadFrequently:!0},uy=class t{static get experimentalLetterSpacingSupported(){let e=t._experimentalLetterSpacingSupported;if(void 0!==e){const i=ph.ADAPTER.getCanvasRenderingContext2D().prototype;e=t._experimentalLetterSpacingSupported="letterSpacing"in i||"textLetterSpacing"in i}return e}constructor(t,e,i,r,s,n,o,a,l){this.text=t,this.style=e,this.width=i,this.height=r,this.lines=s,this.lineWidths=n,this.lineHeight=o,this.maxLineWidth=a,this.fontProperties=l}static measureText(e,i,r,s=t._canvas){r=r??i.wordWrap;const n=i.toFontString(),o=t.measureFont(n);0===o.fontSize&&(o.fontSize=i.fontSize,o.ascent=i.fontSize);const a=s.getContext("2d",hy);a.font=n;const l=(r?t.wordWrap(e,i,s):e).split(/(?:\r\n|\r|\n)/),h=new Array(l.length);let u=0;for(let f=0;f<l.length;f++){const e=t._measureText(l[f],i.letterSpacing,a);h[f]=e,u=Math.max(u,e)}let c=u+i.strokeThickness;i.dropShadow&&(c+=i.dropShadowDistance);const d=i.lineHeight||o.fontSize+i.strokeThickness;let p=Math.max(d,o.fontSize+2*i.strokeThickness)+i.leading+(l.length-1)*(d+i.leading);return i.dropShadow&&(p+=i.dropShadowDistance),new t(e,i,c,p,l,h,d+i.leading,u,o)}static _measureText(e,i,r){let s=!1;t.experimentalLetterSpacingSupported&&(t.experimentalLetterSpacing?(r.letterSpacing=`${i}px`,r.textLetterSpacing=`${i}px`,s=!0):(r.letterSpacing="0px",r.textLetterSpacing="0px"));let n=r.measureText(e).width;return n>0&&(s?n-=i:n+=(t.graphemeSegmenter(e).length-1)*i),n}static wordWrap(e,i,r=t._canvas){const s=r.getContext("2d",hy);let n=0,o="",a="";const l=/* @__PURE__ */Object.create(null),{letterSpacing:h,whiteSpace:u}=i,c=t.collapseSpaces(u),d=t.collapseNewlines(u);let p=!c;const f=i.wordWrapWidth+h,m=t.tokenize(e);for(let g=0;g<m.length;g++){let e=m[g];if(t.isNewline(e)){if(!d){a+=t.addLine(o),p=!c,o="",n=0;continue}e=" "}if(c){const i=t.isBreakingSpace(e),r=t.isBreakingSpace(o[o.length-1]);if(i&&r)continue}const r=t.getFromCache(e,h,l,s);if(r>f)if(""!==o&&(a+=t.addLine(o),o="",n=0),t.canBreakWords(e,i.breakWords)){const r=t.wordWrapSplit(e);for(let u=0;u<r.length;u++){let c=r[u],d=c,m=1;for(;r[u+m];){const s=r[u+m];if(t.canBreakChars(d,s,e,u,i.breakWords))break;c+=s,d=s,m++}u+=m-1;const g=t.getFromCache(c,h,l,s);g+n>f&&(a+=t.addLine(o),p=!1,o="",n=0),o+=c,n+=g}}else{o.length>0&&(a+=t.addLine(o),o="",n=0);const i=g===m.length-1;a+=t.addLine(e,!i),p=!1,o="",n=0}else r+n>f&&(p=!1,a+=t.addLine(o),o="",n=0),(o.length>0||!t.isBreakingSpace(e)||p)&&(o+=e,n+=r)}return a+=t.addLine(o,!1),a}static addLine(e,i=!0){return e=t.trimRight(e),e=i?`${e}\n`:e}static getFromCache(e,i,r,s){let n=r[e];return"number"!=typeof n&&(n=t._measureText(e,i,s)+i,r[e]=n),n}static collapseSpaces(t){return"normal"===t||"pre-line"===t}static collapseNewlines(t){return"normal"===t}static trimRight(e){if("string"!=typeof e)return"";for(let i=e.length-1;i>=0;i--){const r=e[i];if(!t.isBreakingSpace(r))break;e=e.slice(0,-1)}return e}static isNewline(e){return"string"==typeof e&&t._newlines.includes(e.charCodeAt(0))}static isBreakingSpace(e,i){return"string"==typeof e&&t._breakingSpaces.includes(e.charCodeAt(0))}static tokenize(e){const i=[];let r="";if("string"!=typeof e)return i;for(let s=0;s<e.length;s++){const n=e[s],o=e[s+1];t.isBreakingSpace(n,o)||t.isNewline(n)?(""!==r&&(i.push(r),r=""),i.push(n)):r+=n}return""!==r&&i.push(r),i}static canBreakWords(t,e){return e}static canBreakChars(t,e,i,r,s){return!0}static wordWrapSplit(e){return t.graphemeSegmenter(e)}static measureFont(e){if(t._fonts[e])return t._fonts[e];const i={ascent:0,descent:0,fontSize:0},r=t._canvas,s=t._context;s.font=e;const n=t.METRICS_STRING+t.BASELINE_SYMBOL,o=Math.ceil(s.measureText(n).width);let a=Math.ceil(s.measureText(t.BASELINE_SYMBOL).width);const l=Math.ceil(t.HEIGHT_MULTIPLIER*a);if(a=a*t.BASELINE_MULTIPLIER|0,0===o||0===l)return t._fonts[e]=i,i;r.width=o,r.height=l,s.fillStyle="#f00",s.fillRect(0,0,o,l),s.font=e,s.textBaseline="alphabetic",s.fillStyle="#000",s.fillText(n,0,a);const h=s.getImageData(0,0,o,l).data,u=h.length,c=4*o;let d=0,p=0,f=!1;for(d=0;d<a;++d){for(let t=0;t<c;t+=4)if(255!==h[p+t]){f=!0;break}if(f)break;p+=c}for(i.ascent=a-d,p=u-c,f=!1,d=l;d>a;--d){for(let t=0;t<c;t+=4)if(255!==h[p+t]){f=!0;break}if(f)break;p-=c}return i.descent=d-a,i.fontSize=i.ascent+i.descent,t._fonts[e]=i,i}static clearMetrics(e=""){e?delete t._fonts[e]:t._fonts={}}static get _canvas(){if(!t.__canvas){let e;try{const i=new OffscreenCanvas(0,0);if(i.getContext("2d",hy)?.measureText)return t.__canvas=i,i;e=ph.ADAPTER.createCanvas()}catch{e=ph.ADAPTER.createCanvas()}e.width=e.height=10,t.__canvas=e}return t.__canvas}static get _context(){return t.__context||(t.__context=t._canvas.getContext("2d",hy)),t.__context}};uy.METRICS_STRING="|ÉqÅ",uy.BASELINE_SYMBOL="M",uy.BASELINE_MULTIPLIER=1.4,uy.HEIGHT_MULTIPLIER=2,uy.graphemeSegmenter=(()=>{if("function"==typeof Intl?.Segmenter){const t=new Intl.Segmenter;return e=>[...t.segment(e)].map(t=>t.segment)}return t=>[...t]})(),uy.experimentalLetterSpacing=!1,uy._fonts={},uy._newlines=[10,13],uy._breakingSpaces=[9,32,8192,8193,8194,8195,8196,8197,8198,8200,8201,8202,8287,12288];let cy=uy;const dy=["serif","sans-serif","monospace","cursive","fantasy","system-ui"],py=class t{constructor(t){this.styleID=0,this.reset(),gy(this,t,t)}clone(){const e={};return gy(e,this,t.defaultStyle),new t(e)}reset(){gy(this,t.defaultStyle,t.defaultStyle)}get align(){return this._align}set align(t){this._align!==t&&(this._align=t,this.styleID++)}get breakWords(){return this._breakWords}set breakWords(t){this._breakWords!==t&&(this._breakWords=t,this.styleID++)}get dropShadow(){return this._dropShadow}set dropShadow(t){this._dropShadow!==t&&(this._dropShadow=t,this.styleID++)}get dropShadowAlpha(){return this._dropShadowAlpha}set dropShadowAlpha(t){this._dropShadowAlpha!==t&&(this._dropShadowAlpha=t,this.styleID++)}get dropShadowAngle(){return this._dropShadowAngle}set dropShadowAngle(t){this._dropShadowAngle!==t&&(this._dropShadowAngle=t,this.styleID++)}get dropShadowBlur(){return this._dropShadowBlur}set dropShadowBlur(t){this._dropShadowBlur!==t&&(this._dropShadowBlur=t,this.styleID++)}get dropShadowColor(){return this._dropShadowColor}set dropShadowColor(t){const e=my(t);this._dropShadowColor!==e&&(this._dropShadowColor=e,this.styleID++)}get dropShadowDistance(){return this._dropShadowDistance}set dropShadowDistance(t){this._dropShadowDistance!==t&&(this._dropShadowDistance=t,this.styleID++)}get fill(){return this._fill}set fill(t){const e=my(t);this._fill!==e&&(this._fill=e,this.styleID++)}get fillGradientType(){return this._fillGradientType}set fillGradientType(t){this._fillGradientType!==t&&(this._fillGradientType=t,this.styleID++)}get fillGradientStops(){return this._fillGradientStops}set fillGradientStops(t){(function(t,e){if(!Array.isArray(t)||!Array.isArray(e)||t.length!==e.length)return!1;for(let i=0;i<t.length;++i)if(t[i]!==e[i])return!1;return!0})(this._fillGradientStops,t)||(this._fillGradientStops=t,this.styleID++)}get fontFamily(){return this._fontFamily}set fontFamily(t){this.fontFamily!==t&&(this._fontFamily=t,this.styleID++)}get fontSize(){return this._fontSize}set fontSize(t){this._fontSize!==t&&(this._fontSize=t,this.styleID++)}get fontStyle(){return this._fontStyle}set fontStyle(t){this._fontStyle!==t&&(this._fontStyle=t,this.styleID++)}get fontVariant(){return this._fontVariant}set fontVariant(t){this._fontVariant!==t&&(this._fontVariant=t,this.styleID++)}get fontWeight(){return this._fontWeight}set fontWeight(t){this._fontWeight!==t&&(this._fontWeight=t,this.styleID++)}get letterSpacing(){return this._letterSpacing}set letterSpacing(t){this._letterSpacing!==t&&(this._letterSpacing=t,this.styleID++)}get lineHeight(){return this._lineHeight}set lineHeight(t){this._lineHeight!==t&&(this._lineHeight=t,this.styleID++)}get leading(){return this._leading}set leading(t){this._leading!==t&&(this._leading=t,this.styleID++)}get lineJoin(){return this._lineJoin}set lineJoin(t){this._lineJoin!==t&&(this._lineJoin=t,this.styleID++)}get miterLimit(){return this._miterLimit}set miterLimit(t){this._miterLimit!==t&&(this._miterLimit=t,this.styleID++)}get padding(){return this._padding}set padding(t){this._padding!==t&&(this._padding=t,this.styleID++)}get stroke(){return this._stroke}set stroke(t){const e=my(t);this._stroke!==e&&(this._stroke=e,this.styleID++)}get strokeThickness(){return this._strokeThickness}set strokeThickness(t){this._strokeThickness!==t&&(this._strokeThickness=t,this.styleID++)}get textBaseline(){return this._textBaseline}set textBaseline(t){this._textBaseline!==t&&(this._textBaseline=t,this.styleID++)}get trim(){return this._trim}set trim(t){this._trim!==t&&(this._trim=t,this.styleID++)}get whiteSpace(){return this._whiteSpace}set whiteSpace(t){this._whiteSpace!==t&&(this._whiteSpace=t,this.styleID++)}get wordWrap(){return this._wordWrap}set wordWrap(t){this._wordWrap!==t&&(this._wordWrap=t,this.styleID++)}get wordWrapWidth(){return this._wordWrapWidth}set wordWrapWidth(t){this._wordWrapWidth!==t&&(this._wordWrapWidth=t,this.styleID++)}toFontString(){const t="number"==typeof this.fontSize?`${this.fontSize}px`:this.fontSize;let e=this.fontFamily;Array.isArray(this.fontFamily)||(e=this.fontFamily.split(","));for(let i=e.length-1;i>=0;i--){let t=e[i].trim();!/([\"\'])[^\'\"]+\1/.test(t)&&!dy.includes(t)&&(t=`"${t}"`),e[i]=t}return`${this.fontStyle} ${this.fontVariant} ${this.fontWeight} ${t} ${e.join(",")}`}};py.defaultStyle={align:"left",breakWords:!1,dropShadow:!1,dropShadowAlpha:1,dropShadowAngle:Math.PI/6,dropShadowBlur:0,dropShadowColor:"black",dropShadowDistance:5,fill:"black",fillGradientType:ly.LINEAR_VERTICAL,fillGradientStops:[],fontFamily:"Arial",fontSize:26,fontStyle:"normal",fontVariant:"normal",fontWeight:"normal",leading:0,letterSpacing:0,lineHeight:0,lineJoin:"miter",miterLimit:10,padding:0,stroke:"black",strokeThickness:0,textBaseline:"alphabetic",trim:!1,whiteSpace:"pre",wordWrap:!1,wordWrapWidth:100};let fy=py;function my(t){const e=qd.shared,i=t=>{const i=e.setValue(t);return 1===i.alpha?i.toHex():i.toRgbaString()};return Array.isArray(t)?t.map(i):i(t)}function gy(t,e,i){for(const r in i)Array.isArray(e[r])?t[r]=e[r].slice():t[r]=e[r]}const yy={texture:!0,children:!1,baseTexture:!0},vy=class t extends Rg{constructor(e,i,r){let s=!1;r||(r=ph.ADAPTER.createCanvas(),s=!0),r.width=3,r.height=3;const n=om.from(r);n.orig=new Qp,n.trim=new Qp,super(n),this._ownCanvas=s,this.canvas=r,this.context=r.getContext("2d",{willReadFrequently:!0}),this._resolution=t.defaultResolution??ph.RESOLUTION,this._autoResolution=t.defaultAutoResolution,this._text=null,this._style=null,this._styleListener=null,this._font="",this.text=e,this.style=i,this.localStyleID=-1}static get experimentalLetterSpacing(){return cy.experimentalLetterSpacing}static set experimentalLetterSpacing(t){dd("7.1.0","Text.experimentalLetterSpacing is deprecated, use TextMetrics.experimentalLetterSpacing"),cy.experimentalLetterSpacing=t}updateText(t){const e=this._style;if(this.localStyleID!==e.styleID&&(this.dirty=!0,this.localStyleID=e.styleID),!this.dirty&&t)return;this._font=this._style.toFontString();const i=this.context,r=cy.measureText(this._text||" ",this._style,this._style.wordWrap,this.canvas),s=r.width,n=r.height,o=r.lines,a=r.lineHeight,l=r.lineWidths,h=r.maxLineWidth,u=r.fontProperties;let c,d;this.canvas.width=Math.ceil(Math.ceil(Math.max(1,s)+2*e.padding)*this._resolution),this.canvas.height=Math.ceil(Math.ceil(Math.max(1,n)+2*e.padding)*this._resolution),i.scale(this._resolution,this._resolution),i.clearRect(0,0,this.canvas.width,this.canvas.height),i.font=this._font,i.lineWidth=e.strokeThickness,i.textBaseline=e.textBaseline,i.lineJoin=e.lineJoin,i.miterLimit=e.miterLimit;const p=e.dropShadow?2:1;for(let f=0;f<p;++f){const t=e.dropShadow&&0===f,s=t?Math.ceil(Math.max(1,n)+2*e.padding):0,p=s*this._resolution;if(t){i.fillStyle="black",i.strokeStyle="black";const t=e.dropShadowColor,r=e.dropShadowBlur*this._resolution,s=e.dropShadowDistance*this._resolution;i.shadowColor=qd.shared.setValue(t).setAlpha(e.dropShadowAlpha).toRgbaString(),i.shadowBlur=r,i.shadowOffsetX=Math.cos(e.dropShadowAngle)*s,i.shadowOffsetY=Math.sin(e.dropShadowAngle)*s+p}else i.fillStyle=this._generateFillStyle(e,o,r),i.strokeStyle=e.stroke,i.shadowColor="black",i.shadowBlur=0,i.shadowOffsetX=0,i.shadowOffsetY=0;let m=(a-u.fontSize)/2;a-u.fontSize<0&&(m=0);for(let i=0;i<o.length;i++)c=e.strokeThickness/2,d=e.strokeThickness/2+i*a+u.ascent+m,"right"===e.align?c+=h-l[i]:"center"===e.align&&(c+=(h-l[i])/2),e.stroke&&e.strokeThickness&&this.drawLetterSpacing(o[i],c+e.padding,d+e.padding-s,!0),e.fill&&this.drawLetterSpacing(o[i],c+e.padding,d+e.padding-s)}this.updateTexture()}drawLetterSpacing(t,e,i,r=!1){const s=this._style.letterSpacing;let n=!1;if(cy.experimentalLetterSpacingSupported&&(cy.experimentalLetterSpacing?(this.context.letterSpacing=`${s}px`,this.context.textLetterSpacing=`${s}px`,n=!0):(this.context.letterSpacing="0px",this.context.textLetterSpacing="0px")),0===s||n)return void(r?this.context.strokeText(t,e,i):this.context.fillText(t,e,i));let o=e;const a=cy.graphemeSegmenter(t);let l=this.context.measureText(t).width,h=0;for(let u=0;u<a.length;++u){const t=a[u];r?this.context.strokeText(t,o,i):this.context.fillText(t,o,i);let e="";for(let i=u+1;i<a.length;++i)e+=a[i];h=this.context.measureText(e).width,o+=l-h+s,l=h}}updateTexture(){const t=this.canvas;if(this._style.trim){const e=yp(t);e.data&&(t.width=e.width,t.height=e.height,this.context.putImageData(e.data,0,0))}const e=this._texture,i=this._style,r=i.trim?0:i.padding,s=e.baseTexture;e.trim.width=e._frame.width=t.width/this._resolution,e.trim.height=e._frame.height=t.height/this._resolution,e.trim.x=-r,e.trim.y=-r,e.orig.width=e._frame.width-2*r,e.orig.height=e._frame.height-2*r,this._onTextureUpdate(),s.setRealSize(t.width,t.height,this._resolution),e.updateUvs(),this.dirty=!1}_render(t){this._autoResolution&&this._resolution!==t.resolution&&(this._resolution=t.resolution,this.dirty=!0),this.updateText(!0),super._render(t)}updateTransform(){this.updateText(!0),super.updateTransform()}getBounds(t,e){return this.updateText(!0),-1===this._textureID&&(t=!1),super.getBounds(t,e)}getLocalBounds(t){return this.updateText(!0),super.getLocalBounds.call(this,t)}_calculateBounds(){this.calculateVertices(),this._bounds.addQuad(this.vertexData)}_generateFillStyle(t,e,i){const r=t.fill;if(!Array.isArray(r))return r;if(1===r.length)return r[0];let s;const n=t.dropShadow?t.dropShadowDistance:0,o=t.padding||0,a=this.canvas.width/this._resolution-n-2*o,l=this.canvas.height/this._resolution-n-2*o,h=r.slice(),u=t.fillGradientStops.slice();if(!u.length){const t=h.length+1;for(let e=1;e<t;++e)u.push(e/t)}if(h.unshift(r[0]),u.unshift(0),h.push(r[r.length-1]),u.push(1),t.fillGradientType===ly.LINEAR_VERTICAL){s=this.context.createLinearGradient(a/2,o,a/2,l+o);const r=i.fontProperties.fontSize+t.strokeThickness;for(let t=0;t<e.length;t++){const n=i.lineHeight*(t-1)+r,o=i.lineHeight*t;let a=o;t>0&&n>o&&(a=(o+n)/2);const c=o+r,d=i.lineHeight*(t+1);let p=c;t+1<e.length&&d<c&&(p=(c+d)/2);const f=(p-a)/l;for(let t=0;t<h.length;t++){let e=0;e="number"==typeof u[t]?u[t]:t/h.length;let i=Math.min(1,Math.max(0,a/l+e*f));i=Number(i.toFixed(5)),s.addColorStop(i,h[t])}}}else{s=this.context.createLinearGradient(o,l/2,a+o,l/2);const t=h.length+1;let e=1;for(let i=0;i<h.length;i++){let r;r="number"==typeof u[i]?u[i]:e/t,s.addColorStop(r,h[i]),e++}}return s}destroy(t){"boolean"==typeof t&&(t={children:t}),t=Object.assign({},yy,t),super.destroy(t),this._ownCanvas&&(this.canvas.height=this.canvas.width=0),this.context=null,this.canvas=null,this._style=null}get width(){return this.updateText(!0),Math.abs(this.scale.x)*this._texture.orig.width}set width(t){this.updateText(!0);const e=sp(this.scale.x)||1;this.scale.x=e*t/this._texture.orig.width,this._width=t}get height(){return this.updateText(!0),Math.abs(this.scale.y)*this._texture.orig.height}set height(t){this.updateText(!0);const e=sp(this.scale.y)||1;this.scale.y=e*t/this._texture.orig.height,this._height=t}get style(){return this._style}set style(t){t=t||{},this._style=t instanceof fy?t:new fy(t),this.localStyleID=-1,this.dirty=!0}get text(){return this._text}set text(t){t=String(t??""),this._text!==t&&(this._text=t,this.dirty=!0)}get resolution(){return this._resolution}set resolution(t){this._autoResolution=!1,this._resolution!==t&&(this._resolution=t,this.dirty=!0)}};vy.defaultAutoResolution=!0;let xy=vy;class by extends Vf{constructor(){super("attribute vec2 aVertexPosition;\n\nuniform mat3 projectionMatrix;\n\nvarying vec2 vTextureCoord;\n\nuniform vec4 inputSize;\nuniform vec4 outputFrame;\n\nvec4 filterVertexPosition( void )\n{\n vec2 position = aVertexPosition * max(outputFrame.zw, vec2(0.)) + outputFrame.xy;\n\n return vec4((projectionMatrix * vec3(position, 1.0)).xy, 0.0, 1.0);\n}\n\nvec2 filterTextureCoord( void )\n{\n return aVertexPosition * (outputFrame.zw * inputSize.zw);\n}\n\nvoid main(void)\n{\n gl_Position = filterVertexPosition();\n vTextureCoord = filterTextureCoord();\n}\n","varying vec2 vTextureCoord;\nuniform sampler2D uSampler;\nuniform float m[20];\nuniform float uAlpha;\n\nvoid main(void)\n{\n vec4 c = texture2D(uSampler, vTextureCoord);\n\n if (uAlpha == 0.0) {\n gl_FragColor = c;\n return;\n }\n\n // Un-premultiply alpha before applying the color matrix. See issue #3539.\n if (c.a > 0.0) {\n c.rgb /= c.a;\n }\n\n vec4 result;\n\n result.r = (m[0] * c.r);\n result.r += (m[1] * c.g);\n result.r += (m[2] * c.b);\n result.r += (m[3] * c.a);\n result.r += m[4];\n\n result.g = (m[5] * c.r);\n result.g += (m[6] * c.g);\n result.g += (m[7] * c.b);\n result.g += (m[8] * c.a);\n result.g += m[9];\n\n result.b = (m[10] * c.r);\n result.b += (m[11] * c.g);\n result.b += (m[12] * c.b);\n result.b += (m[13] * c.a);\n result.b += m[14];\n\n result.a = (m[15] * c.r);\n result.a += (m[16] * c.g);\n result.a += (m[17] * c.b);\n result.a += (m[18] * c.a);\n result.a += m[19];\n\n vec3 rgb = mix(c.rgb, result.rgb, uAlpha);\n\n // Premultiply alpha again.\n rgb *= result.a;\n\n gl_FragColor = vec4(rgb, result.a);\n}\n",{m:new Float32Array([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0]),uAlpha:1}),this.alpha=1}_loadMatrix(t,e=!1){let i=t;e&&(this._multiply(i,this.uniforms.m,t),i=this._colorMatrix(i)),this.uniforms.m=i}_multiply(t,e,i){return t[0]=e[0]*i[0]+e[1]*i[5]+e[2]*i[10]+e[3]*i[15],t[1]=e[0]*i[1]+e[1]*i[6]+e[2]*i[11]+e[3]*i[16],t[2]=e[0]*i[2]+e[1]*i[7]+e[2]*i[12]+e[3]*i[17],t[3]=e[0]*i[3]+e[1]*i[8]+e[2]*i[13]+e[3]*i[18],t[4]=e[0]*i[4]+e[1]*i[9]+e[2]*i[14]+e[3]*i[19]+e[4],t[5]=e[5]*i[0]+e[6]*i[5]+e[7]*i[10]+e[8]*i[15],t[6]=e[5]*i[1]+e[6]*i[6]+e[7]*i[11]+e[8]*i[16],t[7]=e[5]*i[2]+e[6]*i[7]+e[7]*i[12]+e[8]*i[17],t[8]=e[5]*i[3]+e[6]*i[8]+e[7]*i[13]+e[8]*i[18],t[9]=e[5]*i[4]+e[6]*i[9]+e[7]*i[14]+e[8]*i[19]+e[9],t[10]=e[10]*i[0]+e[11]*i[5]+e[12]*i[10]+e[13]*i[15],t[11]=e[10]*i[1]+e[11]*i[6]+e[12]*i[11]+e[13]*i[16],t[12]=e[10]*i[2]+e[11]*i[7]+e[12]*i[12]+e[13]*i[17],t[13]=e[10]*i[3]+e[11]*i[8]+e[12]*i[13]+e[13]*i[18],t[14]=e[10]*i[4]+e[11]*i[9]+e[12]*i[14]+e[13]*i[19]+e[14],t[15]=e[15]*i[0]+e[16]*i[5]+e[17]*i[10]+e[18]*i[15],t[16]=e[15]*i[1]+e[16]*i[6]+e[17]*i[11]+e[18]*i[16],t[17]=e[15]*i[2]+e[16]*i[7]+e[17]*i[12]+e[18]*i[17],t[18]=e[15]*i[3]+e[16]*i[8]+e[17]*i[13]+e[18]*i[18],t[19]=e[15]*i[4]+e[16]*i[9]+e[17]*i[14]+e[18]*i[19]+e[19],t}_colorMatrix(t){const e=new Float32Array(t);return e[4]/=255,e[9]/=255,e[14]/=255,e[19]/=255,e}brightness(t,e){const i=[t,0,0,0,0,0,t,0,0,0,0,0,t,0,0,0,0,0,1,0];this._loadMatrix(i,e)}tint(t,e){const[i,r,s]=qd.shared.setValue(t).toArray(),n=[i,0,0,0,0,0,r,0,0,0,0,0,s,0,0,0,0,0,1,0];this._loadMatrix(n,e)}greyscale(t,e){const i=[t,t,t,0,0,t,t,t,0,0,t,t,t,0,0,0,0,0,1,0];this._loadMatrix(i,e)}blackAndWhite(t){this._loadMatrix([.3,.6,.1,0,0,.3,.6,.1,0,0,.3,.6,.1,0,0,0,0,0,1,0],t)}hue(t,e){t=(t||0)/180*Math.PI;const i=Math.cos(t),r=Math.sin(t),s=1/3,n=(0,Math.sqrt)(s),o=[i+(1-i)*s,s*(1-i)-n*r,s*(1-i)+n*r,0,0,s*(1-i)+n*r,i+s*(1-i),s*(1-i)-n*r,0,0,s*(1-i)-n*r,s*(1-i)+n*r,i+s*(1-i),0,0,0,0,0,1,0];this._loadMatrix(o,e)}contrast(t,e){const i=(t||0)+1,r=-.5*(i-1),s=[i,0,0,0,r,0,i,0,0,r,0,0,i,0,r,0,0,0,1,0];this._loadMatrix(s,e)}saturate(t=0,e){const i=2*t/3+1,r=-.5*(i-1),s=[i,r,r,0,0,r,i,r,0,0,r,r,i,0,0,0,0,0,1,0];this._loadMatrix(s,e)}desaturate(){this.saturate(-1)}negative(t){this._loadMatrix([-1,0,0,1,0,0,-1,0,1,0,0,0,-1,1,0,0,0,0,1,0],t)}sepia(t){this._loadMatrix([.393,.7689999,.18899999,0,0,.349,.6859999,.16799999,0,0,.272,.5339999,.13099999,0,0,0,0,0,1,0],t)}technicolor(t){this._loadMatrix([1.9125277891456083,-.8545344976951645,-.09155508482755585,0,11.793603434377337,-.3087833385928097,1.7658908555458428,-.10601743074722245,0,-70.35205161461398,-.231103377548616,-.7501899197440212,1.847597816108189,0,30.950940869491138,0,0,0,1,0],t)}polaroid(t){this._loadMatrix([1.438,-.062,-.062,0,0,-.122,1.378,-.122,0,0,-.016,-.016,1.483,0,0,0,0,0,1,0],t)}toBGR(t){this._loadMatrix([0,0,1,0,0,0,1,0,0,0,1,0,0,0,0,0,0,0,1,0],t)}kodachrome(t){this._loadMatrix([1.1285582396593525,-.3967382283601348,-.03992559172921793,0,63.72958762196502,-.16404339962244616,1.0835251566291304,-.05498805115633132,0,24.732407896706203,-.16786010706155763,-.5603416277695248,1.6014850761964943,0,35.62982807460946,0,0,0,1,0],t)}browni(t){this._loadMatrix([.5997023498159715,.34553243048391263,-.2708298674538042,0,47.43192855600873,-.037703249837783157,.8609577587992641,.15059552388459913,0,-36.96841498319127,.24113635128153335,-.07441037908422492,.44972182064877153,0,-7.562075277591283,0,0,0,1,0],t)}vintage(t){this._loadMatrix([.6279345635605994,.3202183420819367,-.03965408211312453,0,9.651285835294123,.02578397704808868,.6441188644374771,.03259127616149294,0,7.462829176470591,.0466055556782719,-.0851232987247891,.5241648018700465,0,5.159190588235296,0,0,0,1,0],t)}colorTone(t,e,i,r,s){t=t||.2,e=e||.15,i=i||16770432,r=r||3375104;const n=qd.shared,[o,a,l]=n.setValue(i).toArray(),[h,u,c]=n.setValue(r).toArray(),d=[.3,.59,.11,0,0,o,a,l,t,0,h,u,c,e,0,o-h,a-u,l-c,0,0];this._loadMatrix(d,s)}night(t,e){const i=[-2*(t=t||.1),-t,0,0,0,-t,0,t,0,0,0,t,2*t,0,0,0,0,0,1,0];this._loadMatrix(i,e)}predator(t,e){const i=[11.224130630493164*t,-4.794486999511719*t,-2.8746118545532227*t,0*t,.40342438220977783*t,-3.6330697536468506*t,9.193157196044922*t,-2.951810836791992*t,0*t,-1.316135048866272*t,-3.2184197902679443*t,-4.2375030517578125*t,7.476448059082031*t,0*t,.8044459223747253*t,0,0,0,1,0];this._loadMatrix(i,e)}lsd(t){this._loadMatrix([2,-.4,.5,0,0,-.5,2,-.4,0,0,-.4,-.5,3,0,0,0,0,0,1,0],t)}reset(){this._loadMatrix([1,0,0,0,0,0,1,0,0,0,0,0,1,0,0,0,0,0,1,0],!1)}get matrix(){return this.uniforms.m}set matrix(t){this.uniforms.m=t}get alpha(){return this.uniforms.uAlpha}set alpha(t){this.uniforms.uAlpha=t}}by.prototype.grayscale=by.prototype.greyscale;var _y,wy={exports:{}},Py=wy.exports;var Ey=(_y||(_y=1,function(t){(function(){var e,i;i=e={linear:function(t,e,i,r){return i*t/r+e},easeInQuad:function(t,e,i,r){return i*(t/=r)*t+e},easeOutQuad:function(t,e,i,r){return-i*(t/=r)*(t-2)+e},easeInOutQuad:function(t,e,i,r){return(t/=r/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e},easeInCubic:function(t,e,i,r){return i*(t/=r)*t*t+e},easeOutCubic:function(t,e,i,r){return i*((t=t/r-1)*t*t+1)+e},easeInOutCubic:function(t,e,i,r){return(t/=r/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e},easeInQuart:function(t,e,i,r){return i*(t/=r)*t*t*t+e},easeOutQuart:function(t,e,i,r){return-i*((t=t/r-1)*t*t*t-1)+e},easeInOutQuart:function(t,e,i,r){return(t/=r/2)<1?i/2*t*t*t*t+e:-i/2*((t-=2)*t*t*t-2)+e},easeInQuint:function(t,e,i,r){return i*(t/=r)*t*t*t*t+e},easeOutQuint:function(t,e,i,r){return i*((t=t/r-1)*t*t*t*t+1)+e},easeInOutQuint:function(t,e,i,r){return(t/=r/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e},easeInSine:function(t,e,i,r){return-i*Math.cos(t/r*(Math.PI/2))+i+e},easeOutSine:function(t,e,i,r){return i*Math.sin(t/r*(Math.PI/2))+e},easeInOutSine:function(t,e,i,r){return-i/2*(Math.cos(Math.PI*t/r)-1)+e},easeInExpo:function(t,e,i,r){return 0===t?e:i*Math.pow(2,10*(t/r-1))+e},easeOutExpo:function(t,e,i,r){return t===r?e+i:i*(1-Math.pow(2,-10*t/r))+e},easeInOutExpo:function(t,e,i,r){return(t/=r/2)<1?i/2*Math.pow(2,10*(t-1))+e:i/2*(2-Math.pow(2,-10*--t))+e},easeInCirc:function(t,e,i,r){return-i*(Math.sqrt(1-(t/=r)*t)-1)+e},easeOutCirc:function(t,e,i,r){return i*Math.sqrt(1-(t=t/r-1)*t)+e},easeInOutCirc:function(t,e,i,r){return(t/=r/2)<1?-i/2*(Math.sqrt(1-t*t)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e},easeInElastic:function(t,e,i,r){var s,n,o;return o=1.70158,0===t||(t/=r),(n=0)||(n=.3*r),(s=i)<Math.abs(i)?(s=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/s),-s*Math.pow(2,10*(t-=1))*Math.sin((t*r-o)*(2*Math.PI)/n)+e},easeOutElastic:function(t,e,i,r){var s,n,o;return o=1.70158,0===t||(t/=r),(n=0)||(n=.3*r),(s=i)<Math.abs(i)?(s=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/s),s*Math.pow(2,-10*t)*Math.sin((t*r-o)*(2*Math.PI)/n)+i+e},easeInOutElastic:function(t,e,i,r){var s,n,o;return o=1.70158,0===t||(t/=r/2),(n=0)||(n=r*(.3*1.5)),(s=i)<Math.abs(i)?(s=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/s),t<1?s*Math.pow(2,10*(t-=1))*Math.sin((t*r-o)*(2*Math.PI)/n)*-.5+e:s*Math.pow(2,-10*(t-=1))*Math.sin((t*r-o)*(2*Math.PI)/n)*.5+i+e},easeInBack:function(t,e,i,r,s){return void 0===s&&(s=1.70158),i*(t/=r)*t*((s+1)*t-s)+e},easeOutBack:function(t,e,i,r,s){return void 0===s&&(s=1.70158),i*((t=t/r-1)*t*((s+1)*t+s)+1)+e},easeInOutBack:function(t,e,i,r,s){return void 0===s&&(s=1.70158),(t/=r/2)<1?i/2*(t*t*((1+(s*=1.525))*t-s))+e:i/2*((t-=2)*t*((1+(s*=1.525))*t+s)+2)+e},easeInBounce:function(t,i,r,s){return r-e.easeOutBounce(s-t,0,r,s)+i},easeOutBounce:function(t,e,i,r){return(t/=r)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e},easeInOutBounce:function(t,i,r,s){return t<s/2?.5*e.easeInBounce(2*t,0,r,s)+i:.5*e.easeOutBounce(2*t-s,0,r,s)+.5*r+i}},t.exports=i}).call(Py)}(wy)),wy.exports);const Ty=/* @__PURE__ */It(Ey);Og.prototype._renderCanvas=function(t){},Og.prototype.renderCanvas=function(t){if(this.visible&&!(this.worldAlpha<=0)&&this.renderable){this._mask&&t.mask.pushMask(this._mask),this._renderCanvas(t);for(let e=0,i=this.children.length;e<i;++e)this.children[e].renderCanvas(t);this._mask&&t.mask.popMask(t)}},Ag.prototype.renderCanvas=function(t){},xy.prototype._renderCanvas=function(t){this._autoResolution&&this._resolution!==t.resolution&&(this._resolution=t.resolution,this.dirty=!0),this.updateText(!0),Rg.prototype._renderCanvas.call(this,t)},Ag.prototype.name=null,Og.prototype.getChildByName=function(t,e){for(let i=0,r=this.children.length;i<r;i++)if(this.children[i].name===t)return this.children[i];if(e)for(let i=0,r=this.children.length;i<r;i++){const e=this.children[i];if(!e.getChildByName)continue;const r=e.getChildByName(t,!0);if(r)return r}return null};const Ay={vec3(t,e,i,r){(i[0]!==r[0]||i[1]!==r[1]||i[2]!==r[2])&&(i[0]=r[0],i[1]=r[1],i[2]=r[2],t.uniform3f(e,r[0],r[1],r[2]))},int(t,e,i,r){t.uniform1i(e,r)},ivec2(t,e,i,r){t.uniform2i(e,r[0],r[1])},ivec3(t,e,i,r){t.uniform3i(e,r[0],r[1],r[2])},ivec4(t,e,i,r){t.uniform4i(e,r[0],r[1],r[2],r[3])},uint(t,e,i,r){t.uniform1ui(e,r)},uvec2(t,e,i,r){t.uniform2ui(e,r[0],r[1])},uvec3(t,e,i,r){t.uniform3ui(e,r[0],r[1],r[2])},uvec4(t,e,i,r){t.uniform4ui(e,r[0],r[1],r[2],r[3])},bvec2(t,e,i,r){t.uniform2i(e,r[0],r[1])},bvec3(t,e,i,r){t.uniform3i(e,r[0],r[1],r[2])},bvec4(t,e,i,r){t.uniform4i(e,r[0],r[1],r[2],r[3])},mat2(t,e,i,r){t.uniformMatrix2fv(e,!1,r)},mat4(t,e,i,r){t.uniformMatrix4fv(e,!1,r)}},Iy={float(t,e,i,r){t.uniform1fv(e,r)},vec2(t,e,i,r){t.uniform2fv(e,r)},vec3(t,e,i,r){t.uniform3fv(e,r)},vec4(t,e,i,r){t.uniform4fv(e,r)},int(t,e,i,r){t.uniform1iv(e,r)},ivec2(t,e,i,r){t.uniform2iv(e,r)},ivec3(t,e,i,r){t.uniform3iv(e,r)},ivec4(t,e,i,r){t.uniform4iv(e,r)},uint(t,e,i,r){t.uniform1uiv(e,r)},uvec2(t,e,i,r){t.uniform2uiv(e,r)},uvec3(t,e,i,r){t.uniform3uiv(e,r)},uvec4(t,e,i,r){t.uniform4uiv(e,r)},bool(t,e,i,r){t.uniform1iv(e,r)},bvec2(t,e,i,r){t.uniform2iv(e,r)},bvec3(t,e,i,r){t.uniform3iv(e,r)},bvec4(t,e,i,r){t.uniform4iv(e,r)},sampler2D(t,e,i,r){t.uniform1iv(e,r)},samplerCube(t,e,i,r){t.uniform1iv(e,r)},sampler2DArray(t,e,i,r){t.uniform1iv(e,r)}};Object.assign(zm.prototype,{systemCheck(){},syncUniforms(t,e){const{shader:i,renderer:r}=this;!function(t,e,i,r,s){let n=0,o=null,a=null;const l=s.gl;for(const h in t.uniforms){const u=e[h],c=r[h],d=i[h],p=t.uniforms[h];u?"float"!==u.type||1!==u.size||u.isArray?"bool"!==u.type||1!==u.size||u.isArray?"sampler2D"!==u.type&&"samplerCube"!==u.type&&"sampler2DArray"!==u.type||1!==u.size||u.isArray?"mat3"!==u.type||1!==u.size||u.isArray?"vec2"!==u.type||1!==u.size||u.isArray?"vec4"!==u.type||1!==u.size||u.isArray?(1!==u.size||u.isArray?Iy:Ay)[u.type].call(null,l,d.location,d.value,c):void 0!==p.width?(a=d.value,o=c,(a[0]!==o.x||a[1]!==o.y||a[2]!==o.width||a[3]!==o.height)&&(a[0]=o.x,a[1]=o.y,a[2]=o.width,a[3]=o.height,l.uniform4f(d.location,o.x,o.y,o.width,o.height))):(a=d.value,o=c,(a[0]!==o[0]||a[1]!==o[1]||a[2]!==o[2]||a[3]!==o[3])&&(a[0]=o[0],a[1]=o[1],a[2]=o[2],a[3]=o[3],l.uniform4f(d.location,o[0],o[1],o[2],o[3]))):void 0!==p.x?(a=d.value,o=c,(a[0]!==o.x||a[1]!==o.y)&&(a[0]=o.x,a[1]=o.y,l.uniform2f(d.location,o.x,o.y))):(a=d.value,o=c,(a[0]!==o[0]||a[1]!==o[1])&&(a[0]=o[0],a[1]=o[1],l.uniform2f(d.location,o[0],o[1]))):void 0!==p.a?l.uniformMatrix3fv(d.location,!1,c.toArray(!0)):l.uniformMatrix3fv(d.location,!1,c):(s.texture.bind(c,n),d.value!==n&&(d.value=n,l.uniform1i(d.location,n)),n++):c!==d.value&&(d.value=c,l.uniform1i(d.location,Number(c))):c!==d.value&&(d.value=c,l.uniform1f(d.location,c)):!0===p.group&&s.shader.syncUniformGroup(c)}}(t,i.program.uniformData,e.uniformData,t.uniforms,r)}});const Sy=new class{constructor(){this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this.tickerAdded=!1,this._pauseUpdate=!0}init(t){this.removeTickerListener(),this.events=t,this.interactionFrequency=10,this._deltaTime=0,this._didMove=!1,this.tickerAdded=!1,this._pauseUpdate=!0}get pauseUpdate(){return this._pauseUpdate}set pauseUpdate(t){this._pauseUpdate=t}addTickerListener(){this.tickerAdded||!this.domElement||(ag.system.add(this.tickerUpdate,this,sg.INTERACTION),this.tickerAdded=!0)}removeTickerListener(){this.tickerAdded&&(ag.system.remove(this.tickerUpdate,this),this.tickerAdded=!1)}pointerMoved(){this._didMove=!0}update(){if(!this.domElement||this._pauseUpdate)return;if(this._didMove)return void(this._didMove=!1);const t=this.events.rootPointerEvent;this.events.supportsTouchEvents&&"touch"===t.pointerType||globalThis.document.dispatchEvent(new PointerEvent("pointermove",{clientX:t.clientX,clientY:t.clientY}))}tickerUpdate(t){this._deltaTime+=t,!(this._deltaTime<this.interactionFrequency)&&(this._deltaTime=0,this.update())}};class Cy{constructor(t){this.bubbles=!0,this.cancelBubble=!0,this.cancelable=!1,this.composed=!1,this.defaultPrevented=!1,this.eventPhase=Cy.prototype.NONE,this.propagationStopped=!1,this.propagationImmediatelyStopped=!1,this.layer=new Kp,this.page=new Kp,this.NONE=0,this.CAPTURING_PHASE=1,this.AT_TARGET=2,this.BUBBLING_PHASE=3,this.manager=t}get layerX(){return this.layer.x}get layerY(){return this.layer.y}get pageX(){return this.page.x}get pageY(){return this.page.y}get data(){return this}composedPath(){return this.manager&&(!this.path||this.path[this.path.length-1]!==this.target)&&(this.path=this.target?this.manager.propagationPath(this.target):[]),this.path}initEvent(t,e,i){throw new Error("initEvent() is a legacy DOM API. It is not implemented in the Federated Events API.")}initUIEvent(t,e,i,r,s){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}}class My extends Cy{constructor(){super(...arguments),this.client=new Kp,this.movement=new Kp,this.offset=new Kp,this.global=new Kp,this.screen=new Kp}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(t,e,i){return t.worldTransform.applyInverse(i||this.global,e)}getModifierState(t){return"getModifierState"in this.nativeEvent&&this.nativeEvent.getModifierState(t)}initMouseEvent(t,e,i,r,s,n,o,a,l,h,u,c,d,p,f){throw new Error("Method not implemented.")}}class Oy extends My{constructor(){super(...arguments),this.width=0,this.height=0,this.isPrimary=!1}getCoalescedEvents(){return"pointermove"===this.type||"mousemove"===this.type||"touchmove"===this.type?[this]:[]}getPredictedEvents(){throw new Error("getPredictedEvents is not supported!")}}class Ny extends My{constructor(){super(...arguments),this.DOM_DELTA_PIXEL=0,this.DOM_DELTA_LINE=1,this.DOM_DELTA_PAGE=2}}Ny.DOM_DELTA_PIXEL=0,Ny.DOM_DELTA_LINE=1,Ny.DOM_DELTA_PAGE=2;const Ly=new Kp,Ry=new Kp;class ky{constructor(t){this.dispatch=new kh,this.moveOnAll=!1,this.enableGlobalMoveEvents=!0,this.mappingState={trackingData:{}},this.eventPool=/* @__PURE__ */new Map,this._allInteractiveElements=[],this._hitElements=[],this._isPointerMoveEvent=!1,this.rootTarget=t,this.hitPruneFn=this.hitPruneFn.bind(this),this.hitTestFn=this.hitTestFn.bind(this),this.mapPointerDown=this.mapPointerDown.bind(this),this.mapPointerMove=this.mapPointerMove.bind(this),this.mapPointerOut=this.mapPointerOut.bind(this),this.mapPointerOver=this.mapPointerOver.bind(this),this.mapPointerUp=this.mapPointerUp.bind(this),this.mapPointerUpOutside=this.mapPointerUpOutside.bind(this),this.mapWheel=this.mapWheel.bind(this),this.mappingTable={},this.addEventMapping("pointerdown",this.mapPointerDown),this.addEventMapping("pointermove",this.mapPointerMove),this.addEventMapping("pointerout",this.mapPointerOut),this.addEventMapping("pointerleave",this.mapPointerOut),this.addEventMapping("pointerover",this.mapPointerOver),this.addEventMapping("pointerup",this.mapPointerUp),this.addEventMapping("pointerupoutside",this.mapPointerUpOutside),this.addEventMapping("wheel",this.mapWheel)}addEventMapping(t,e){this.mappingTable[t]||(this.mappingTable[t]=[]),this.mappingTable[t].push({fn:e,priority:0}),this.mappingTable[t].sort((t,e)=>t.priority-e.priority)}dispatchEvent(t,e){t.propagationStopped=!1,t.propagationImmediatelyStopped=!1,this.propagate(t,e),this.dispatch.emit(e||t.type,t)}mapEvent(t){if(!this.rootTarget)return;const e=this.mappingTable[t.type];if(e)for(let i=0,r=e.length;i<r;i++)e[i].fn(t);else console.warn(`[EventBoundary]: Event mapping not defined for ${t.type}`)}hitTest(t,e){Sy.pauseUpdate=!0;const i=this[this._isPointerMoveEvent&&this.enableGlobalMoveEvents?"hitTestMoveRecursive":"hitTestRecursive"](this.rootTarget,this.rootTarget.eventMode,Ly.set(t,e),this.hitTestFn,this.hitPruneFn);return i&&i[0]}propagate(t,e){if(!t.target)return;const i=t.composedPath();t.eventPhase=t.CAPTURING_PHASE;for(let r=0,s=i.length-1;r<s;r++)if(t.currentTarget=i[r],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return;if(t.eventPhase=t.AT_TARGET,t.currentTarget=t.target,this.notifyTarget(t,e),!t.propagationStopped&&!t.propagationImmediatelyStopped){t.eventPhase=t.BUBBLING_PHASE;for(let r=i.length-2;r>=0;r--)if(t.currentTarget=i[r],this.notifyTarget(t,e),t.propagationStopped||t.propagationImmediatelyStopped)return}}all(t,e,i=this._allInteractiveElements){if(0===i.length)return;t.eventPhase=t.BUBBLING_PHASE;const r=Array.isArray(e)?e:[e];for(let s=i.length-1;s>=0;s--)r.forEach(e=>{t.currentTarget=i[s],this.notifyTarget(t,e)})}propagationPath(t){const e=[t];for(let i=0;i<2048&&t!==this.rootTarget;i++){if(!t.parent)throw new Error("Cannot find propagation path to disconnected target");e.push(t.parent),t=t.parent}return e.reverse(),e}hitTestMoveRecursive(t,e,i,r,s,n=!1){let o=!1;if(this._interactivePrune(t))return null;if(("dynamic"===t.eventMode||"dynamic"===e)&&(Sy.pauseUpdate=!1),t.interactiveChildren&&t.children){const a=t.children;for(let l=a.length-1;l>=0;l--){const h=a[l],u=this.hitTestMoveRecursive(h,this._isInteractive(e)?e:h.eventMode,i,r,s,n||s(t,i));if(u){if(u.length>0&&!u[u.length-1].parent)continue;const e=t.isInteractive();(u.length>0||e)&&(e&&this._allInteractiveElements.push(t),u.push(t)),0===this._hitElements.length&&(this._hitElements=u),o=!0}}}const a=this._isInteractive(e),l=t.isInteractive();return a&&l&&this._allInteractiveElements.push(t),n||this._hitElements.length>0?null:o?this._hitElements:a&&!s(t,i)&&r(t,i)?l?[t]:[]:null}hitTestRecursive(t,e,i,r,s){if(this._interactivePrune(t)||s(t,i))return null;if(("dynamic"===t.eventMode||"dynamic"===e)&&(Sy.pauseUpdate=!1),t.interactiveChildren&&t.children){const n=t.children;for(let o=n.length-1;o>=0;o--){const a=n[o],l=this.hitTestRecursive(a,this._isInteractive(e)?e:a.eventMode,i,r,s);if(l){if(l.length>0&&!l[l.length-1].parent)continue;const e=t.isInteractive();return(l.length>0||e)&&l.push(t),l}}}const n=this._isInteractive(e),o=t.isInteractive();return n&&r(t,i)?o?[t]:[]:null}_isInteractive(t){return"static"===t||"dynamic"===t}_interactivePrune(t){return!(t&&!t.isMask&&t.visible&&t.renderable&&"none"!==t.eventMode&&("passive"!==t.eventMode||t.interactiveChildren)&&!t.isMask)}hitPruneFn(t,e){if(t.hitArea&&(t.worldTransform.applyInverse(e,Ry),!t.hitArea.contains(Ry.x,Ry.y)))return!0;if(t._mask){const i=t._mask.isMaskData?t._mask.maskObject:t._mask;if(i&&!i.containsPoint?.(e))return!0}return!1}hitTestFn(t,e){return"passive"!==t.eventMode&&(!!t.hitArea||!!t.containsPoint&&t.containsPoint(e))}notifyTarget(t,e){const i=`on${e=e??t.type}`;t.currentTarget[i]?.(t);const r=t.eventPhase===t.CAPTURING_PHASE||t.eventPhase===t.AT_TARGET?`${e}capture`:e;this.notifyListeners(t,r),t.eventPhase===t.AT_TARGET&&this.notifyListeners(t,e)}mapPointerDown(t){if(!(t instanceof Oy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.createPointerEvent(t);if(this.dispatchEvent(e,"pointerdown"),"touch"===e.pointerType)this.dispatchEvent(e,"touchstart");else if("mouse"===e.pointerType||"pen"===e.pointerType){const t=2===e.button;this.dispatchEvent(e,t?"rightdown":"mousedown")}this.trackingData(t.pointerId).pressTargetsByButton[t.button]=e.composedPath(),this.freeEvent(e)}mapPointerMove(t){if(!(t instanceof Oy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");this._allInteractiveElements.length=0,this._hitElements.length=0,this._isPointerMoveEvent=!0;const e=this.createPointerEvent(t);this._isPointerMoveEvent=!1;const i="mouse"===e.pointerType||"pen"===e.pointerType,r=this.trackingData(t.pointerId),s=this.findMountedTarget(r.overTargets);if(r.overTargets?.length>0&&s!==e.target){const r="mousemove"===t.type?"mouseout":"pointerout",n=this.createPointerEvent(t,r,s);if(this.dispatchEvent(n,"pointerout"),i&&this.dispatchEvent(n,"mouseout"),!e.composedPath().includes(s)){const r=this.createPointerEvent(t,"pointerleave",s);for(r.eventPhase=r.AT_TARGET;r.target&&!e.composedPath().includes(r.target);)r.currentTarget=r.target,this.notifyTarget(r),i&&this.notifyTarget(r,"mouseleave"),r.target=r.target.parent;this.freeEvent(r)}this.freeEvent(n)}if(s!==e.target){const r="mousemove"===t.type?"mouseover":"pointerover",n=this.clonePointerEvent(e,r);this.dispatchEvent(n,"pointerover"),i&&this.dispatchEvent(n,"mouseover");let o=s?.parent;for(;o&&o!==this.rootTarget.parent&&o!==e.target;)o=o.parent;if(!o||o===this.rootTarget.parent){const t=this.clonePointerEvent(e,"pointerenter");for(t.eventPhase=t.AT_TARGET;t.target&&t.target!==s&&t.target!==this.rootTarget.parent;)t.currentTarget=t.target,this.notifyTarget(t),i&&this.notifyTarget(t,"mouseenter"),t.target=t.target.parent;this.freeEvent(t)}this.freeEvent(n)}const n=[],o=this.enableGlobalMoveEvents??!0;this.moveOnAll?n.push("pointermove"):this.dispatchEvent(e,"pointermove"),o&&n.push("globalpointermove"),"touch"===e.pointerType&&(this.moveOnAll?n.splice(1,0,"touchmove"):this.dispatchEvent(e,"touchmove"),o&&n.push("globaltouchmove")),i&&(this.moveOnAll?n.splice(1,0,"mousemove"):this.dispatchEvent(e,"mousemove"),o&&n.push("globalmousemove"),this.cursor=e.target?.cursor),n.length>0&&this.all(e,n),this._allInteractiveElements.length=0,this._hitElements.length=0,r.overTargets=e.composedPath(),this.freeEvent(e)}mapPointerOver(t){if(!(t instanceof Oy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.trackingData(t.pointerId),i=this.createPointerEvent(t),r="mouse"===i.pointerType||"pen"===i.pointerType;this.dispatchEvent(i,"pointerover"),r&&this.dispatchEvent(i,"mouseover"),"mouse"===i.pointerType&&(this.cursor=i.target?.cursor);const s=this.clonePointerEvent(i,"pointerenter");for(s.eventPhase=s.AT_TARGET;s.target&&s.target!==this.rootTarget.parent;)s.currentTarget=s.target,this.notifyTarget(s),r&&this.notifyTarget(s,"mouseenter"),s.target=s.target.parent;e.overTargets=i.composedPath(),this.freeEvent(i),this.freeEvent(s)}mapPointerOut(t){if(!(t instanceof Oy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.trackingData(t.pointerId);if(e.overTargets){const i="mouse"===t.pointerType||"pen"===t.pointerType,r=this.findMountedTarget(e.overTargets),s=this.createPointerEvent(t,"pointerout",r);this.dispatchEvent(s),i&&this.dispatchEvent(s,"mouseout");const n=this.createPointerEvent(t,"pointerleave",r);for(n.eventPhase=n.AT_TARGET;n.target&&n.target!==this.rootTarget.parent;)n.currentTarget=n.target,this.notifyTarget(n),i&&this.notifyTarget(n,"mouseleave"),n.target=n.target.parent;e.overTargets=null,this.freeEvent(s),this.freeEvent(n)}this.cursor=null}mapPointerUp(t){if(!(t instanceof Oy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=performance.now(),i=this.createPointerEvent(t);if(this.dispatchEvent(i,"pointerup"),"touch"===i.pointerType)this.dispatchEvent(i,"touchend");else if("mouse"===i.pointerType||"pen"===i.pointerType){const t=2===i.button;this.dispatchEvent(i,t?"rightup":"mouseup")}const r=this.trackingData(t.pointerId),s=this.findMountedTarget(r.pressTargetsByButton[t.button]);let n=s;if(s&&!i.composedPath().includes(s)){let e=s;for(;e&&!i.composedPath().includes(e);){if(i.currentTarget=e,this.notifyTarget(i,"pointerupoutside"),"touch"===i.pointerType)this.notifyTarget(i,"touchendoutside");else if("mouse"===i.pointerType||"pen"===i.pointerType){const t=2===i.button;this.notifyTarget(i,t?"rightupoutside":"mouseupoutside")}e=e.parent}delete r.pressTargetsByButton[t.button],n=e}if(n){const s=this.clonePointerEvent(i,"click");s.target=n,s.path=null,r.clicksByButton[t.button]||(r.clicksByButton[t.button]={clickCount:0,target:s.target,timeStamp:e});const o=r.clicksByButton[t.button];if(o.target===s.target&&e-o.timeStamp<200?++o.clickCount:o.clickCount=1,o.target=s.target,o.timeStamp=e,s.detail=o.clickCount,"mouse"===s.pointerType){const t=2===s.button;this.dispatchEvent(s,t?"rightclick":"click")}else"touch"===s.pointerType&&this.dispatchEvent(s,"tap");this.dispatchEvent(s,"pointertap"),this.freeEvent(s)}this.freeEvent(i)}mapPointerUpOutside(t){if(!(t instanceof Oy))return void console.warn("EventBoundary cannot map a non-pointer event as a pointer event");const e=this.trackingData(t.pointerId),i=this.findMountedTarget(e.pressTargetsByButton[t.button]),r=this.createPointerEvent(t);if(i){let s=i;for(;s;)r.currentTarget=s,this.notifyTarget(r,"pointerupoutside"),"touch"===r.pointerType?this.notifyTarget(r,"touchendoutside"):("mouse"===r.pointerType||"pen"===r.pointerType)&&this.notifyTarget(r,2===r.button?"rightupoutside":"mouseupoutside"),s=s.parent;delete e.pressTargetsByButton[t.button]}this.freeEvent(r)}mapWheel(t){if(!(t instanceof Ny))return void console.warn("EventBoundary cannot map a non-wheel event as a wheel event");const e=this.createWheelEvent(t);this.dispatchEvent(e),this.freeEvent(e)}findMountedTarget(t){if(!t)return null;let e=t[0];for(let i=1;i<t.length&&t[i].parent===e;i++)e=t[i];return e}createPointerEvent(t,e,i){const r=this.allocateEvent(Oy);return this.copyPointerData(t,r),this.copyMouseData(t,r),this.copyData(t,r),r.nativeEvent=t.nativeEvent,r.originalEvent=t,r.target=i??this.hitTest(r.global.x,r.global.y)??this._hitElements[0],"string"==typeof e&&(r.type=e),r}createWheelEvent(t){const e=this.allocateEvent(Ny);return this.copyWheelData(t,e),this.copyMouseData(t,e),this.copyData(t,e),e.nativeEvent=t.nativeEvent,e.originalEvent=t,e.target=this.hitTest(e.global.x,e.global.y),e}clonePointerEvent(t,e){const i=this.allocateEvent(Oy);return i.nativeEvent=t.nativeEvent,i.originalEvent=t.originalEvent,this.copyPointerData(t,i),this.copyMouseData(t,i),this.copyData(t,i),i.target=t.target,i.path=t.composedPath().slice(),i.type=e??i.type,i}copyWheelData(t,e){e.deltaMode=t.deltaMode,e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ}copyPointerData(t,e){t instanceof Oy&&e instanceof Oy&&(e.pointerId=t.pointerId,e.width=t.width,e.height=t.height,e.isPrimary=t.isPrimary,e.pointerType=t.pointerType,e.pressure=t.pressure,e.tangentialPressure=t.tangentialPressure,e.tiltX=t.tiltX,e.tiltY=t.tiltY,e.twist=t.twist)}copyMouseData(t,e){t instanceof My&&e instanceof My&&(e.altKey=t.altKey,e.button=t.button,e.buttons=t.buttons,e.client.copyFrom(t.client),e.ctrlKey=t.ctrlKey,e.metaKey=t.metaKey,e.movement.copyFrom(t.movement),e.screen.copyFrom(t.screen),e.shiftKey=t.shiftKey,e.global.copyFrom(t.global))}copyData(t,e){e.isTrusted=t.isTrusted,e.srcElement=t.srcElement,e.timeStamp=performance.now(),e.type=t.type,e.detail=t.detail,e.view=t.view,e.which=t.which,e.layer.copyFrom(t.layer),e.page.copyFrom(t.page)}trackingData(t){return this.mappingState.trackingData[t]||(this.mappingState.trackingData[t]={pressTargetsByButton:{},clicksByButton:{},overTarget:null}),this.mappingState.trackingData[t]}allocateEvent(t){this.eventPool.has(t)||this.eventPool.set(t,[]);const e=this.eventPool.get(t).pop()||new t(this);return e.eventPhase=e.NONE,e.currentTarget=null,e.path=null,e.target=null,e}freeEvent(t){if(t.manager!==this)throw new Error("It is illegal to free an event not managed by this EventBoundary!");const e=t.constructor;this.eventPool.has(e)||this.eventPool.set(e,[]),this.eventPool.get(e).push(t)}notifyListeners(t,e){const i=t.currentTarget._events[e];if(i&&t.currentTarget.isInteractive())if("fn"in i)i.once&&t.currentTarget.removeListener(e,i.fn,void 0,!0),i.fn.call(i.context,t);else for(let r=0,s=i.length;r<s&&!t.propagationImmediatelyStopped;r++)i[r].once&&t.currentTarget.removeListener(e,i[r].fn,void 0,!0),i[r].fn.call(i[r].context,t)}}const By={touchstart:"pointerdown",touchend:"pointerup",touchendoutside:"pointerupoutside",touchmove:"pointermove",touchcancel:"pointercancel"},Fy=class t{constructor(e){this.supportsTouchEvents="ontouchstart"in globalThis,this.supportsPointerEvents=!!globalThis.PointerEvent,this.domElement=null,this.resolution=1,this.renderer=e,this.rootBoundary=new ky(null),Sy.init(this),this.autoPreventDefault=!0,this.eventsAdded=!1,this.rootPointerEvent=new Oy(null),this.rootWheelEvent=new Ny(null),this.cursorStyles={default:"inherit",pointer:"pointer"},this.features=new Proxy({...t.defaultEventFeatures},{set:(t,e,i)=>("globalMove"===e&&(this.rootBoundary.enableGlobalMoveEvents=i),t[e]=i,!0)}),this.onPointerDown=this.onPointerDown.bind(this),this.onPointerMove=this.onPointerMove.bind(this),this.onPointerUp=this.onPointerUp.bind(this),this.onPointerOverOut=this.onPointerOverOut.bind(this),this.onWheel=this.onWheel.bind(this)}static get defaultEventMode(){return this._defaultEventMode}init(e){const{view:i,resolution:r}=this.renderer;this.setTargetElement(i),this.resolution=r,t._defaultEventMode=e.eventMode??"auto",Object.assign(this.features,e.eventFeatures??{}),this.rootBoundary.enableGlobalMoveEvents=this.features.globalMove}resolutionChange(t){this.resolution=t}destroy(){this.setTargetElement(null),this.renderer=null}setCursor(t){t=t||"default";let e=!0;if(globalThis.OffscreenCanvas&&this.domElement instanceof OffscreenCanvas&&(e=!1),this.currentCursor===t)return;this.currentCursor=t;const i=this.cursorStyles[t];if(i)switch(typeof i){case"string":e&&(this.domElement.style.cursor=i);break;case"function":i(t);break;case"object":e&&Object.assign(this.domElement.style,i)}else e&&"string"==typeof t&&!Object.prototype.hasOwnProperty.call(this.cursorStyles,t)&&(this.domElement.style.cursor=t)}get pointer(){return this.rootPointerEvent}onPointerDown(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this.normalizeToPointerData(t);this.autoPreventDefault&&e[0].isNormalized&&(t.cancelable||!("cancelable"in t))&&t.preventDefault();for(let i=0,r=e.length;i<r;i++){const t=e[i],r=this.bootstrapEvent(this.rootPointerEvent,t);this.rootBoundary.mapEvent(r)}this.setCursor(this.rootBoundary.cursor)}onPointerMove(t){if(!this.features.move)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,Sy.pointerMoved();const e=this.normalizeToPointerData(t);for(let i=0,r=e.length;i<r;i++){const t=this.bootstrapEvent(this.rootPointerEvent,e[i]);this.rootBoundary.mapEvent(t)}this.setCursor(this.rootBoundary.cursor)}onPointerUp(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;let e=t.target;t.composedPath&&t.composedPath().length>0&&(e=t.composedPath()[0]);const i=e!==this.domElement?"outside":"",r=this.normalizeToPointerData(t);for(let s=0,n=r.length;s<n;s++){const t=this.bootstrapEvent(this.rootPointerEvent,r[s]);t.type+=i,this.rootBoundary.mapEvent(t)}this.setCursor(this.rootBoundary.cursor)}onPointerOverOut(t){if(!this.features.click)return;this.rootBoundary.rootTarget=this.renderer.lastObjectRendered;const e=this.normalizeToPointerData(t);for(let i=0,r=e.length;i<r;i++){const t=this.bootstrapEvent(this.rootPointerEvent,e[i]);this.rootBoundary.mapEvent(t)}this.setCursor(this.rootBoundary.cursor)}onWheel(t){if(!this.features.wheel)return;const e=this.normalizeWheelEvent(t);this.rootBoundary.rootTarget=this.renderer.lastObjectRendered,this.rootBoundary.mapEvent(e)}setTargetElement(t){this.removeEvents(),this.domElement=t,Sy.domElement=t,this.addEvents()}addEvents(){if(this.eventsAdded||!this.domElement)return;Sy.addTickerListener();const t=this.domElement.style;t&&(globalThis.navigator.msPointerEnabled?(t.msContentZooming="none",t.msTouchAction="none"):this.supportsPointerEvents&&(t.touchAction="none")),this.supportsPointerEvents?(globalThis.document.addEventListener("pointermove",this.onPointerMove,!0),this.domElement.addEventListener("pointerdown",this.onPointerDown,!0),this.domElement.addEventListener("pointerleave",this.onPointerOverOut,!0),this.domElement.addEventListener("pointerover",this.onPointerOverOut,!0),globalThis.addEventListener("pointerup",this.onPointerUp,!0)):(globalThis.document.addEventListener("mousemove",this.onPointerMove,!0),this.domElement.addEventListener("mousedown",this.onPointerDown,!0),this.domElement.addEventListener("mouseout",this.onPointerOverOut,!0),this.domElement.addEventListener("mouseover",this.onPointerOverOut,!0),globalThis.addEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.addEventListener("touchstart",this.onPointerDown,!0),this.domElement.addEventListener("touchend",this.onPointerUp,!0),this.domElement.addEventListener("touchmove",this.onPointerMove,!0))),this.domElement.addEventListener("wheel",this.onWheel,{passive:!0,capture:!0}),this.eventsAdded=!0}removeEvents(){if(!this.eventsAdded||!this.domElement)return;Sy.removeTickerListener();const t=this.domElement.style;globalThis.navigator.msPointerEnabled?(t.msContentZooming="",t.msTouchAction=""):this.supportsPointerEvents&&(t.touchAction=""),this.supportsPointerEvents?(globalThis.document.removeEventListener("pointermove",this.onPointerMove,!0),this.domElement.removeEventListener("pointerdown",this.onPointerDown,!0),this.domElement.removeEventListener("pointerleave",this.onPointerOverOut,!0),this.domElement.removeEventListener("pointerover",this.onPointerOverOut,!0),globalThis.removeEventListener("pointerup",this.onPointerUp,!0)):(globalThis.document.removeEventListener("mousemove",this.onPointerMove,!0),this.domElement.removeEventListener("mousedown",this.onPointerDown,!0),this.domElement.removeEventListener("mouseout",this.onPointerOverOut,!0),this.domElement.removeEventListener("mouseover",this.onPointerOverOut,!0),globalThis.removeEventListener("mouseup",this.onPointerUp,!0),this.supportsTouchEvents&&(this.domElement.removeEventListener("touchstart",this.onPointerDown,!0),this.domElement.removeEventListener("touchend",this.onPointerUp,!0),this.domElement.removeEventListener("touchmove",this.onPointerMove,!0))),this.domElement.removeEventListener("wheel",this.onWheel,!0),this.domElement=null,this.eventsAdded=!1}mapPositionToPoint(t,e,i){const r=this.domElement.isConnected?this.domElement.getBoundingClientRect():{width:this.domElement.width,height:this.domElement.height,left:0,top:0},s=1/this.resolution;t.x=(e-r.left)*(this.domElement.width/r.width)*s,t.y=(i-r.top)*(this.domElement.height/r.height)*s}normalizeToPointerData(t){const e=[];if(this.supportsTouchEvents&&t instanceof TouchEvent)for(let i=0,r=t.changedTouches.length;i<r;i++){const r=t.changedTouches[i];typeof r.button>"u"&&(r.button=0),typeof r.buttons>"u"&&(r.buttons=1),typeof r.isPrimary>"u"&&(r.isPrimary=1===t.touches.length&&"touchstart"===t.type),typeof r.width>"u"&&(r.width=r.radiusX||1),typeof r.height>"u"&&(r.height=r.radiusY||1),typeof r.tiltX>"u"&&(r.tiltX=0),typeof r.tiltY>"u"&&(r.tiltY=0),typeof r.pointerType>"u"&&(r.pointerType="touch"),typeof r.pointerId>"u"&&(r.pointerId=r.identifier||0),typeof r.pressure>"u"&&(r.pressure=r.force||.5),typeof r.twist>"u"&&(r.twist=0),typeof r.tangentialPressure>"u"&&(r.tangentialPressure=0),typeof r.layerX>"u"&&(r.layerX=r.offsetX=r.clientX),typeof r.layerY>"u"&&(r.layerY=r.offsetY=r.clientY),r.isNormalized=!0,r.type=t.type,e.push(r)}else if(globalThis.MouseEvent&&(!(t instanceof MouseEvent)||this.supportsPointerEvents&&t instanceof globalThis.PointerEvent))e.push(t);else{const i=t;typeof i.isPrimary>"u"&&(i.isPrimary=!0),typeof i.width>"u"&&(i.width=1),typeof i.height>"u"&&(i.height=1),typeof i.tiltX>"u"&&(i.tiltX=0),typeof i.tiltY>"u"&&(i.tiltY=0),typeof i.pointerType>"u"&&(i.pointerType="mouse"),typeof i.pointerId>"u"&&(i.pointerId=1),typeof i.pressure>"u"&&(i.pressure=.5),typeof i.twist>"u"&&(i.twist=0),typeof i.tangentialPressure>"u"&&(i.tangentialPressure=0),i.isNormalized=!0,e.push(i)}return e}normalizeWheelEvent(t){const e=this.rootWheelEvent;return this.transferMouseData(e,t),e.deltaX=t.deltaX,e.deltaY=t.deltaY,e.deltaZ=t.deltaZ,e.deltaMode=t.deltaMode,this.mapPositionToPoint(e.screen,t.clientX,t.clientY),e.global.copyFrom(e.screen),e.offset.copyFrom(e.screen),e.nativeEvent=t,e.type=t.type,e}bootstrapEvent(t,e){return t.originalEvent=null,t.nativeEvent=e,t.pointerId=e.pointerId,t.width=e.width,t.height=e.height,t.isPrimary=e.isPrimary,t.pointerType=e.pointerType,t.pressure=e.pressure,t.tangentialPressure=e.tangentialPressure,t.tiltX=e.tiltX,t.tiltY=e.tiltY,t.twist=e.twist,this.transferMouseData(t,e),this.mapPositionToPoint(t.screen,e.clientX,e.clientY),t.global.copyFrom(t.screen),t.offset.copyFrom(t.screen),t.isTrusted=e.isTrusted,"pointerleave"===t.type&&(t.type="pointerout"),t.type.startsWith("mouse")&&(t.type=t.type.replace("mouse","pointer")),t.type.startsWith("touch")&&(t.type=By[t.type]||t.type),t}transferMouseData(t,e){t.isTrusted=e.isTrusted,t.srcElement=e.srcElement,t.timeStamp=performance.now(),t.type=e.type,t.altKey=e.altKey,t.button=e.button,t.buttons=e.buttons,t.client.x=e.clientX,t.client.y=e.clientY,t.ctrlKey=e.ctrlKey,t.metaKey=e.metaKey,t.movement.x=e.movementX,t.movement.y=e.movementY,t.page.x=e.pageX,t.page.y=e.pageY,t.relatedTarget=null,t.shiftKey=e.shiftKey}};Fy.extension={name:"events",type:[_p.RendererSystem,_p.CanvasRendererSystem]},Fy.defaultEventFeatures={move:!0,globalMove:!0,click:!0,wheel:!0};let Dy=Fy;function Uy(t){return"dynamic"===t||"static"===t}Ep.add(Dy);const Gy={onclick:null,onmousedown:null,onmouseenter:null,onmouseleave:null,onmousemove:null,onglobalmousemove:null,onmouseout:null,onmouseover:null,onmouseup:null,onmouseupoutside:null,onpointercancel:null,onpointerdown:null,onpointerenter:null,onpointerleave:null,onpointermove:null,onglobalpointermove:null,onpointerout:null,onpointerover:null,onpointertap:null,onpointerup:null,onpointerupoutside:null,onrightclick:null,onrightdown:null,onrightup:null,onrightupoutside:null,ontap:null,ontouchcancel:null,ontouchend:null,ontouchendoutside:null,ontouchmove:null,onglobaltouchmove:null,ontouchstart:null,onwheel:null,_internalInteractive:void 0,get interactive(){return this._internalInteractive??Uy(Dy.defaultEventMode)},set interactive(t){dd("7.2.0","Setting interactive is deprecated, use eventMode = 'none'/'passive'/'auto'/'static'/'dynamic' instead."),this._internalInteractive=t,this.eventMode=t?"static":"auto"},_internalEventMode:void 0,get eventMode(){return this._internalEventMode??Dy.defaultEventMode},set eventMode(t){this._internalInteractive=Uy(t),this._internalEventMode=t},isInteractive(){return"static"===this.eventMode||"dynamic"===this.eventMode},interactiveChildren:!0,hitArea:null,addEventListener(t,e,i){const r="boolean"==typeof i&&i||"object"==typeof i&&i.capture,s="object"==typeof i?i.signal:void 0,n="object"==typeof i&&!0===i.once,o="function"==typeof e?void 0:e;t=r?`${t}capture`:t;const a="function"==typeof e?e:e.handleEvent,l=this;s&&s.addEventListener("abort",()=>{l.off(t,a,o)}),n?l.once(t,a,o):l.on(t,a,o)},removeEventListener(t,e,i){const r="function"==typeof e?void 0:e;t="boolean"==typeof i&&i||"object"==typeof i&&i.capture?`${t}capture`:t,e="function"==typeof e?e:e.handleEvent,this.off(t,e,r)},dispatchEvent(t){if(!(t instanceof Cy))throw new Error("DisplayObject cannot propagate events outside of the Federated Events API");return t.defaultPrevented=!1,t.path=null,t.target=this,t.manager.dispatchEvent(t),!t.defaultPrevented}};Ag.mixin(Gy);const Xy=new Qp;class Wy{constructor(t){this.renderer=t}async image(t,e,i,r){const s=new Image;return s.src=await this.base64(t,e,i,r),s}async base64(t,e,i,r){const s=this.canvas(t,r);if(void 0!==s.toBlob)return new Promise((t,r)=>{s.toBlob(e=>{if(!e)return void r(new Error("ICanvas.toBlob failed!"));const i=new FileReader;i.onload=()=>t(i.result),i.onerror=r,i.readAsDataURL(e)},e,i)});if(void 0!==s.toDataURL)return s.toDataURL(e,i);if(void 0!==s.convertToBlob){const t=await s.convertToBlob({type:e,quality:i});return new Promise((e,i)=>{const r=new FileReader;r.onload=()=>e(r.result),r.onerror=i,r.readAsDataURL(t)})}throw new Error("CanvasExtract.base64() requires ICanvas.toDataURL, ICanvas.toBlob, or ICanvas.convertToBlob to be implemented")}canvas(t,e){const i=this.renderer;if(!i)throw new Error("The CanvasExtract has already been destroyed");let r,s,n;t&&(t instanceof am?n=t:(n=i.generateTexture(t,{region:e,resolution:i.resolution}),e&&(Xy.width=e.width,Xy.height=e.height,e=Xy))),n?(r=n.baseTexture._canvasRenderTarget.context,s=n.baseTexture._canvasRenderTarget.resolution,e=e??n.frame):(r=i.canvasContext.rootContext,s=i._view.resolution,e||((e=Xy).width=i.width/s,e.height=i.height/s));const o=Math.round(e.x*s),a=Math.round(e.y*s),l=Math.max(Math.round(e.width*s),1),h=Math.max(Math.round(e.height*s),1),u=new pp(l,h,1),c=r.getImageData(o,a,l,h);return u.context.putImageData(c,0,0),u.canvas}pixels(t,e){const i=this.renderer;if(!i)throw new Error("The CanvasExtract has already been destroyed");let r,s,n;t&&(t instanceof am?n=t:(n=i.generateTexture(t,{region:e,resolution:i.resolution}),e&&(Xy.width=e.width,Xy.height=e.height,e=Xy))),n?(r=n.baseTexture._canvasRenderTarget.context,s=n.baseTexture._canvasRenderTarget.resolution,e=e??n.frame):(r=i.canvasContext.rootContext,s=i.resolution,e||((e=Xy).width=i.width/s,e.height=i.height/s));const o=Math.round(e.x*s),a=Math.round(e.y*s),l=Math.max(Math.round(e.width*s),1),h=Math.max(Math.round(e.height*s),1);return r.getImageData(o,a,l,h).data}destroy(){this.renderer=null}}let Yy;function Hy(t){const e=ph.ADAPTER.createCanvas(6,1),i=e.getContext("2d");return i.fillStyle=t,i.fillRect(0,0,6,1),e}function $y(){if(typeof document>"u")return!1;if(void 0!==Yy)return Yy;const t=Hy("#ff00ff"),e=Hy("#ffff00"),i=ph.ADAPTER.createCanvas(6,1).getContext("2d");i.globalCompositeOperation="multiply",i.drawImage(t,0,0),i.drawImage(e,2,0);const r=i.getImageData(2,0,1,1);if(r){const t=r.data;Yy=255===t[0]&&0===t[1]&&0===t[2]}else Yy=!1;return Yy}Wy.extension={name:"extract",type:_p.CanvasRendererSystem},Ep.add(Wy),Bp.prototype.getDrawableSource=function(){const t=this.resource;return t?t.bitmap||t.source:null},tm.prototype._canvasRenderTarget=null,om.prototype.patternCache=null,om.prototype.tintCache=null;const jy=new nf;class zy{constructor(t){this.activeResolution=1,this.smoothProperty="imageSmoothingEnabled",this.blendModes=function(t=[]){return $y()?(t[Kl.NORMAL]="source-over",t[Kl.ADD]="lighter",t[Kl.MULTIPLY]="multiply",t[Kl.SCREEN]="screen",t[Kl.OVERLAY]="overlay",t[Kl.DARKEN]="darken",t[Kl.LIGHTEN]="lighten",t[Kl.COLOR_DODGE]="color-dodge",t[Kl.COLOR_BURN]="color-burn",t[Kl.HARD_LIGHT]="hard-light",t[Kl.SOFT_LIGHT]="soft-light",t[Kl.DIFFERENCE]="difference",t[Kl.EXCLUSION]="exclusion",t[Kl.HUE]="hue",t[Kl.SATURATION]="saturation",t[Kl.COLOR]="color",t[Kl.LUMINOSITY]="luminosity"):(t[Kl.NORMAL]="source-over",t[Kl.ADD]="lighter",t[Kl.MULTIPLY]="source-over",t[Kl.SCREEN]="source-over",t[Kl.OVERLAY]="source-over",t[Kl.DARKEN]="source-over",t[Kl.LIGHTEN]="source-over",t[Kl.COLOR_DODGE]="source-over",t[Kl.COLOR_BURN]="source-over",t[Kl.HARD_LIGHT]="source-over",t[Kl.SOFT_LIGHT]="source-over",t[Kl.DIFFERENCE]="source-over",t[Kl.EXCLUSION]="source-over",t[Kl.HUE]="source-over",t[Kl.SATURATION]="source-over",t[Kl.COLOR]="source-over",t[Kl.LUMINOSITY]="source-over"),t[Kl.NORMAL_NPM]=t[Kl.NORMAL],t[Kl.ADD_NPM]=t[Kl.ADD],t[Kl.SCREEN_NPM]=t[Kl.SCREEN],t[Kl.SRC_IN]="source-in",t[Kl.SRC_OUT]="source-out",t[Kl.SRC_ATOP]="source-atop",t[Kl.DST_OVER]="destination-over",t[Kl.DST_IN]="destination-in",t[Kl.DST_OUT]="destination-out",t[Kl.DST_ATOP]="destination-atop",t[Kl.XOR]="xor",t[Kl.SUBTRACT]="source-over",t}(),this._activeBlendMode=null,this._projTransform=null,this._outerBlend=!1,this.renderer=t}init(){const t=this.renderer.background.alpha<1;if(this.rootContext=this.renderer.view.getContext("2d",{alpha:t}),this.activeContext=this.rootContext,!this.rootContext.imageSmoothingEnabled){const t=this.rootContext;t.webkitImageSmoothingEnabled?this.smoothProperty="webkitImageSmoothingEnabled":t.mozImageSmoothingEnabled?this.smoothProperty="mozImageSmoothingEnabled":t.oImageSmoothingEnabled?this.smoothProperty="oImageSmoothingEnabled":t.msImageSmoothingEnabled&&(this.smoothProperty="msImageSmoothingEnabled")}}setContextTransform(t,e,i){let r=t;const s=this._projTransform,n=this.activeResolution;i=i||n,s&&(r=jy,r.copyFrom(t),r.prepend(s)),e?this.activeContext.setTransform(r.a*i,r.b*i,r.c*i,r.d*i,r.tx*n|0,r.ty*n|0):this.activeContext.setTransform(r.a*i,r.b*i,r.c*i,r.d*i,r.tx*n,r.ty*n)}clear(t,e){const{activeContext:i,renderer:r}=this,s=t?qd.shared.setValue(t):this.renderer.background.backgroundColor;i.clearRect(0,0,r.width,r.height),t&&(i.globalAlpha=e??this.renderer.background.alpha,i.fillStyle=s.toHex(),i.fillRect(0,0,r.width,r.height),i.globalAlpha=1)}setBlendMode(t,e){const i=t===Kl.SRC_IN||t===Kl.SRC_OUT||t===Kl.DST_IN||t===Kl.DST_ATOP;!e&&i&&(t=Kl.NORMAL),this._activeBlendMode!==t&&(this._activeBlendMode=t,this._outerBlend=i,this.activeContext.globalCompositeOperation=this.blendModes[t])}resize(){this.smoothProperty&&(this.rootContext[this.smoothProperty]=Bp.defaultOptions.scaleMode===rh.LINEAR)}invalidateBlendMode(){this._activeBlendMode=this.blendModes.indexOf(this.activeContext.globalCompositeOperation)}destroy(){this.renderer=null,this.rootContext=null,this.activeContext=null,this.smoothProperty=null}}zy.extension={type:_p.CanvasRendererSystem,name:"canvasContext"},Ep.add(zy);class Vy{constructor(t){this._foundShapes=[],this.renderer=t}pushMask(t){const e=this.renderer,i=t.maskObject||t;e.canvasContext.activeContext.save();const r=this._foundShapes;if(this.recursiveFindShapes(i,r),r.length>0){const t=e.canvasContext.activeContext;t.beginPath();for(let e=0;e<r.length;e++){const t=r[e],i=t.transform.worldTransform;this.renderer.canvasContext.setContextTransform(i),this.renderGraphicsShape(t)}r.length=0,t.clip()}}recursiveFindShapes(t,e){t.geometry&&t.geometry.graphicsData&&e.push(t);const{children:i}=t;if(i)for(let r=0;r<i.length;r++)this.recursiveFindShapes(i[r],e)}renderGraphicsShape(t){t.finishPoly();const e=this.renderer.canvasContext.activeContext,i=t.geometry.graphicsData,r=i.length;if(0!==r)for(let s=0;s<r;s++){const t=i[s],r=t.shape;if(r.type===Jp.POLY){let i=r.points;const s=t.holes;let n,o,a,l;e.moveTo(i[0],i[1]);for(let t=1;t<i.length/2;t++)e.lineTo(i[2*t],i[2*t+1]);if(s.length>0){n=0,a=i[0],l=i[1];for(let t=2;t+2<i.length;t+=2)n+=(i[t]-a)*(i[t+3]-l)-(i[t+2]-a)*(i[t+1]-l);for(let t=0;t<s.length;t++)if(i=s[t].shape.points,i){o=0,a=i[0],l=i[1];for(let t=2;t+2<i.length;t+=2)o+=(i[t]-a)*(i[t+3]-l)-(i[t+2]-a)*(i[t+1]-l);if(o*n<0){e.moveTo(i[0],i[1]);for(let t=2;t<i.length;t+=2)e.lineTo(i[t],i[t+1])}else{e.moveTo(i[i.length-2],i[i.length-1]);for(let t=i.length-4;t>=0;t-=2)e.lineTo(i[t],i[t+1])}s[t].shape.closeStroke&&e.closePath()}}i[0]===i[i.length-2]&&i[1]===i[i.length-1]&&e.closePath()}else if(r.type===Jp.RECT)e.rect(r.x,r.y,r.width,r.height),e.closePath();else if(r.type===Jp.CIRC)e.arc(r.x,r.y,r.radius,0,2*Math.PI),e.closePath();else if(r.type===Jp.ELIP){const t=2*r.width,i=2*r.height,s=r.x-t/2,n=r.y-i/2,o=.5522848,a=t/2*o,l=i/2*o,h=s+t,u=n+i,c=s+t/2,d=n+i/2;e.moveTo(s,d),e.bezierCurveTo(s,d-l,c-a,n,c,n),e.bezierCurveTo(c+a,n,h,d-l,h,d),e.bezierCurveTo(h,d+l,c+a,u,c,u),e.bezierCurveTo(c-a,u,s,d+l,s,d),e.closePath()}else if(r.type===Jp.RREC){const t=r.x,i=r.y,s=r.width,n=r.height;let o=r.radius;const a=Math.min(s,n)/2;o=o>a?a:o,e.moveTo(t,i+o),e.lineTo(t,i+n-o),e.quadraticCurveTo(t,i+n,t+o,i+n),e.lineTo(t+s-o,i+n),e.quadraticCurveTo(t+s,i+n,t+s,i+n-o),e.lineTo(t+s,i+o),e.quadraticCurveTo(t+s,i,t+s-o,i),e.lineTo(t+o,i),e.quadraticCurveTo(t,i,t,i+o),e.closePath()}}}popMask(t){t.canvasContext.activeContext.restore(),t.canvasContext.invalidateBlendMode()}destroy(){}}Vy.extension={type:_p.CanvasRendererSystem,name:"mask"},Ep.add(Vy);class qy{constructor(t){this.renderer=t}render(t,e){const i=this.renderer;if(!i.view)return;const r=i.canvasContext;let s,n,o,a;e&&(s=e.renderTexture,n=e.clear,o=e.transform,a=e.skipUpdateTransform),this.renderingToScreen=!s,i.emit("prerender");const l=i.resolution;s?(s=s.castToBaseTexture(),s._canvasRenderTarget||(s._canvasRenderTarget=new pp(s.width,s.height,s.resolution),s.resource=new yg(s._canvasRenderTarget.canvas),s.valid=!0),r.activeContext=s._canvasRenderTarget.context,i.canvasContext.activeResolution=s._canvasRenderTarget.resolution):(r.activeContext=r.rootContext,r.activeResolution=l);const h=r.activeContext;if(r._projTransform=o||null,s||(this.lastObjectRendered=t),!a){const e=t.enableTempParent();t.updateTransform(),t.disableTempParent(e)}if(h.save(),h.setTransform(1,0,0,1,0,0),h.globalAlpha=1,r._activeBlendMode=Kl.NORMAL,r._outerBlend=!1,h.globalCompositeOperation=r.blendModes[Kl.NORMAL],n??i.background.clearBeforeRender)if(this.renderingToScreen){h.clearRect(0,0,i.width,i.height);const t=i.background;t.alpha>0&&(h.globalAlpha=t.backgroundColor.alpha,h.fillStyle=t.backgroundColor.toHex(),h.fillRect(0,0,i.width,i.height),h.globalAlpha=1)}else s._canvasRenderTarget.clear(),s.clear.alpha>0&&(h.globalAlpha=s.clear.alpha,h.fillStyle=s.clear.toHex(),h.fillRect(0,0,s.realWidth,s.realHeight),h.globalAlpha=1);const u=r.activeContext;r.activeContext=h,t.renderCanvas(i),r.activeContext=u,h.restore(),r.activeResolution=l,r._projTransform=null,i.emit("postrender")}destroy(){this.lastObjectRendered=null,this.render=null}}qy.extension={type:_p.CanvasRendererSystem,name:"objectRenderer"},Ep.add(qy);const{deprecation:Jy}=bp,Ky=class t extends Km{constructor(e){super(),this.type=ql.CANVAS,this.rendererLogId="Canvas",e=Object.assign({},ph.RENDER_OPTIONS,e);const i={runners:["init","destroy","contextChange","resolutionChange","reset","update","postrender","prerender","resize"],systems:t.__systems,priority:["textureGenerator","background","_view","_plugin","startup","mask","canvasContext","objectRenderer"]};this.setup(i),"useContextAlpha"in e&&(Jy("7.0.0","options.useContextAlpha is deprecated, use options.backgroundAlpha instead"),e.backgroundAlpha=!1===e.useContextAlpha?1:e.backgroundAlpha),this._plugin.rendererPlugins=t.__plugins,this.options=e,this.startup.run(this.options)}static test(){return!0}generateTexture(t,e){return this.textureGenerator.generateTexture(t,e)}reset(){}render(t,e){this.objectRenderer.render(t,e)}clear(){this.canvasContext.clear()}destroy(t){this.runners.destroy.items.reverse(),this.emitWithCustomOptions(this.runners.destroy,{_view:t}),super.destroy()}get plugins(){return this._plugin.plugins}resize(t,e){this._view.resizeView(t,e)}get width(){return this._view.element.width}get height(){return this._view.element.height}get resolution(){return this._view.resolution}set resolution(t){this._view.resolution=t,this.runners.resolutionChange.emit(t)}get autoDensity(){return this._view.autoDensity}get view(){return this._view.element}get screen(){return this._view.screen}get lastObjectRendered(){return this.objectRenderer.lastObjectRendered}get renderingToScreen(){return this.objectRenderer.renderingToScreen}get clearBeforeRender(){return this.background.clearBeforeRender}get blendModes(){return Jy("7.0.0","renderer.blendModes has been deprecated, please use renderer.canvasContext.blendModes instead"),this.canvasContext.blendModes}get maskManager(){return Jy("7.0.0","renderer.maskManager has been deprecated, please use renderer.mask instead"),this.mask}get refresh(){return Jy("7.0.0","renderer.refresh has been deprecated"),!0}get rootContext(){return Jy("7.0.0","renderer.rootContext has been deprecated, please use renderer.canvasContext.rootContext instead"),this.canvasContext.rootContext}get context(){return Jy("7.0.0","renderer.context has been deprecated, please use renderer.canvasContext.activeContext instead"),this.canvasContext.activeContext}get smoothProperty(){return Jy("7.0.0","renderer.smoothProperty has been deprecated, please use renderer.canvasContext.smoothProperty instead"),this.canvasContext.smoothProperty}setBlendMode(t,e){Jy("7.0.0","renderer.setBlendMode has been deprecated, use renderer.canvasContext.setBlendMode instead"),this.canvasContext.setBlendMode(t,e)}invalidateBlendMode(){Jy("7.0.0","renderer.invalidateBlendMode has been deprecated, use renderer.canvasContext.invalidateBlendMode instead"),this.canvasContext.invalidateBlendMode()}setContextTransform(t,e,i){Jy("7.0.0","renderer.setContextTransform has been deprecated, use renderer.canvasContext.setContextTransform instead"),this.canvasContext.setContextTransform(t,e,i)}get backgroundColor(){return Jy("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color}set backgroundColor(t){Jy("7.0.0","renderer.backgroundColor has been deprecated, use renderer.background.color instead."),this.background.color=t}get backgroundAlpha(){return Jy("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha}set backgroundAlpha(t){Jy("7.0.0","renderer.backgroundAlpha has been deprecated, use renderer.background.alpha instead."),this.background.alpha=t}get preserveDrawingBuffer(){return Jy("7.0.0","renderer.preserveDrawingBuffer has been deprecated"),!1}get useContextAlpha(){return Jy("7.0.0","renderer.useContextAlpha has been deprecated"),!1}};Ky.extension={type:_p.Renderer,priority:0},Ky.__plugins={},Ky.__systems={};let Zy=Ky;Ep.handleByMap(_p.CanvasRendererPlugin,Zy.__plugins),Ep.handleByMap(_p.CanvasRendererSystem,Zy.__systems),Ep.add(Zy);const Qy={canvas:null,getTintedCanvas:(t,e)=>{const i=t.texture,r=qd.shared.setValue(e).toHex();i.tintCache=i.tintCache||{};const s=i.tintCache[r];let n;if(s){if(s.tintId===i._updateID)return i.tintCache[r];n=i.tintCache[r]}else n=ph.ADAPTER.createCanvas();if(Qy.tintMethod(i,e,n),n.tintId=i._updateID,Qy.convertTintToImage&&void 0!==n.toDataURL){const t=new Image;t.src=n.toDataURL(),i.tintCache[r]=t}else i.tintCache[r]=n;return n},getTintedPattern:(t,e)=>{const i=qd.shared.setValue(e).toHex();t.patternCache=t.patternCache||{};let r=t.patternCache[i];return r?.tintId===t._updateID||(Qy.canvas||(Qy.canvas=ph.ADAPTER.createCanvas()),Qy.tintMethod(t,e,Qy.canvas),r=Qy.canvas.getContext("2d").createPattern(Qy.canvas,"repeat"),r.tintId=t._updateID,t.patternCache[i]=r),r},tintWithMultiply:(t,e,i)=>{const r=i.getContext("2d"),s=t._frame.clone(),n=t.baseTexture.resolution;s.x*=n,s.y*=n,s.width*=n,s.height*=n,i.width=Math.ceil(s.width),i.height=Math.ceil(s.height),r.save(),r.fillStyle=qd.shared.setValue(e).toHex(),r.fillRect(0,0,s.width,s.height),r.globalCompositeOperation="multiply";const o=t.baseTexture.getDrawableSource();r.drawImage(o,s.x,s.y,s.width,s.height,0,0,s.width,s.height),r.globalCompositeOperation="destination-atop",r.drawImage(o,s.x,s.y,s.width,s.height,0,0,s.width,s.height),r.restore()},tintWithOverlay:(t,e,i)=>{const r=i.getContext("2d"),s=t._frame.clone(),n=t.baseTexture.resolution;s.x*=n,s.y*=n,s.width*=n,s.height*=n,i.width=Math.ceil(s.width),i.height=Math.ceil(s.height),r.save(),r.globalCompositeOperation="copy",r.fillStyle=`#${`00000${(0|e).toString(16)}`.slice(-6)}`,r.fillRect(0,0,s.width,s.height),r.globalCompositeOperation="destination-atop",r.drawImage(t.baseTexture.getDrawableSource(),s.x,s.y,s.width,s.height,0,0,s.width,s.height),r.restore()},tintWithPerPixel:(t,e,i)=>{const r=i.getContext("2d"),s=t._frame.clone(),n=t.baseTexture.resolution;s.x*=n,s.y*=n,s.width*=n,s.height*=n,i.width=Math.ceil(s.width),i.height=Math.ceil(s.height),r.save(),r.globalCompositeOperation="copy",r.drawImage(t.baseTexture.getDrawableSource(),s.x,s.y,s.width,s.height,0,0,s.width,s.height),r.restore();const[o,a,l]=qd.shared.setValue(e).toArray(),h=r.getImageData(0,0,s.width,s.height),u=h.data;for(let c=0;c<u.length;c+=4)u[c+0]*=o,u[c+1]*=a,u[c+2]*=l;r.putImageData(h,0,0)},roundColor:t=>(dd("7.3.0","PIXI.canvasUtils.roundColor is deprecated"),qd.shared.setValue(t).round(Qy.cacheStepsPerColorChannel).toNumber()),cacheStepsPerColorChannel:8,convertTintToImage:!1,canUseMultiply:$y(),tintMethod:null};let tv;Qy.tintMethod=Qy.canUseMultiply?Qy.tintWithMultiply:Qy.tintWithPerPixel;const ev=new nf;ay.prototype.generateCanvasTexture=function(t,e=1){const i=this.getLocalBounds(new Qp);i.width=Math.max(i.width,1/e),i.height=Math.max(i.height,1/e);const r=am.create({width:i.width,height:i.height,scaleMode:t,resolution:e});tv||(tv=new Zy),this.transform.updateLocalTransform(),this.transform.localTransform.copyTo(ev),ev.invert(),ev.tx-=i.x,ev.ty-=i.y,tv.render(this,{renderTexture:r,clear:!0,transform:ev});const s=om.from(r.baseTexture._canvasRenderTarget.canvas,{scaleMode:t});return s.baseTexture.setResolution(e),s},ay.prototype.cachedGraphicsData=[],ay.prototype._renderCanvas=function(t){!0!==this.isMask&&(this.finishPoly(),t.plugins.graphics.render(this))};class iv{static offsetPolygon(t,e){const i=[],r=t.length;e=iv.isPolygonClockwise(t)?e:-1*e;for(let s=0;s<r;s+=2){let n=s-2;n<0&&(n+=r);const o=(s+2)%r;let a=t[s]-t[n],l=t[s+1]-t[n+1],h=Math.sqrt(a*a+l*l);a/=h,l/=h,a*=e,l*=e;const u=-l,c=a,d=[t[n]+u,t[n+1]+c],p=[t[s]+u,t[s+1]+c];let f=t[o]-t[s],m=t[o+1]-t[s+1];h=Math.sqrt(f*f+m*m),f/=h,m/=h,f*=e,m*=e;const g=-m,y=f,v=[t[s]+g,t[s+1]+y],x=[t[o]+g,t[o+1]+y],b=iv.findIntersection(d[0],d[1],p[0],p[1],v[0],v[1],x[0],x[1]);b&&i.push(...b)}return i}static findIntersection(t,e,i,r,s,n,o,a){const l=(a-n)*(i-t)-(o-s)*(r-e),h=(o-s)*(e-n)-(a-n)*(t-s);if(0===l)return 0===h&&0===(i-t)*(e-n)-(r-e)*(t-s)?[(t+i)/2,(e+r)/2]:null;const u=h/l;return[t+u*(i-t),e+u*(r-e)]}static isPolygonClockwise(t){let e=0;for(let i=0,r=t.length-2;i<t.length;r=i,i+=2)e+=(t[i]-t[r])*(t[i+1]+t[r+1]);return e>0}}class rv{constructor(t){this._svgMatrix=null,this._tempMatrix=new nf,this.renderer=t}_calcCanvasStyle(t,e){let i;return t.texture&&t.texture.baseTexture!==om.WHITE.baseTexture?t.texture.valid?(i=Qy.getTintedPattern(t.texture,e),this.setPatternTransform(i,t.matrix||nf.IDENTITY)):i="#808080":i=`#${`00000${(0|e).toString(16)}`.slice(-6)}`,i}render(t){const e=this.renderer,i=e.canvasContext.activeContext,r=t.worldAlpha,s=t.transform.worldTransform;e.canvasContext.setContextTransform(s),e.canvasContext.setBlendMode(t.blendMode);const n=t.geometry.graphicsData;let o,a;const l=qd.shared.setValue(t.tint).toArray();for(let h=0;h<n.length;h++){const t=n[h],u=t.shape,c=t.fillStyle,d=t.lineStyle,p=0|t.fillStyle.color,f=0|t.lineStyle.color;if(t.matrix&&e.canvasContext.setContextTransform(s.copyTo(this._tempMatrix).append(t.matrix)),c.visible&&(o=this._calcCanvasStyle(c,qd.shared.setValue(p).multiply(l).toNumber())),d.visible&&(a=this._calcCanvasStyle(d,qd.shared.setValue(f).multiply(l).toNumber())),i.lineWidth=d.width,i.lineCap=d.cap,i.lineJoin=d.join,i.miterLimit=d.miterLimit,t.type===Jp.POLY){i.beginPath();const e=u;let s=e.points;const n=t.holes;let l,h,p,f,m;i.moveTo(s[0],s[1]);for(let t=2;t<s.length;t+=2)i.lineTo(s[t],s[t+1]);if(e.closeStroke&&i.closePath(),n.length>0){m=[],l=0,p=s[0],f=s[1];for(let t=2;t+2<s.length;t+=2)l+=(s[t]-p)*(s[t+3]-f)-(s[t+2]-p)*(s[t+1]-f);for(let t=0;t<n.length;t++)if(s=n[t].shape.points,s){h=0,p=s[0],f=s[1];for(let t=2;t+2<s.length;t+=2)h+=(s[t]-p)*(s[t+3]-f)-(s[t+2]-p)*(s[t+1]-f);if(h*l<0){i.moveTo(s[0],s[1]);for(let t=2;t<s.length;t+=2)i.lineTo(s[t],s[t+1])}else{i.moveTo(s[s.length-2],s[s.length-1]);for(let t=s.length-4;t>=0;t-=2)i.lineTo(s[t],s[t+1])}n[t].shape.closeStroke&&i.closePath(),m[t]=h*l<0}}c.visible&&(i.globalAlpha=c.alpha*r,i.fillStyle=o,i.fill()),d.visible&&this.paintPolygonStroke(e,d,a,n,m,r,i)}else if(t.type===Jp.RECT){const t=u;if(c.visible&&(i.globalAlpha=c.alpha*r,i.fillStyle=o,i.fillRect(t.x,t.y,t.width,t.height)),d.visible){const e=d.width*(.5-(1-d.alignment)),s=t.width+2*e,n=t.height+2*e;i.globalAlpha=d.alpha*r,i.strokeStyle=a,i.strokeRect(t.x-e,t.y-e,s,n)}}else if(t.type===Jp.CIRC){const t=u;if(i.beginPath(),i.arc(t.x,t.y,t.radius,0,2*Math.PI),i.closePath(),c.visible&&(i.globalAlpha=c.alpha*r,i.fillStyle=o,i.fill()),d.visible){if(.5!==d.alignment){const e=d.width*(.5-(1-d.alignment));i.beginPath(),i.arc(t.x,t.y,t.radius+e,0,2*Math.PI),i.closePath()}i.globalAlpha=d.alpha*r,i.strokeStyle=a,i.stroke()}}else if(t.type===Jp.ELIP){const t=u,e=1===d.alignment;if(e||this.paintEllipse(t,c,d,o,r,i),d.visible){if(.5!==d.alignment){const e=.5522848,r=d.width*(.5-(1-d.alignment)),s=2*(t.width+r),n=2*(t.height+r),o=t.x-s/2,a=t.y-n/2,l=s/2*e,h=n/2*e,u=o+s,c=a+n,p=o+s/2,f=a+n/2;i.beginPath(),i.moveTo(o,f),i.bezierCurveTo(o,f-h,p-l,a,p,a),i.bezierCurveTo(p+l,a,u,f-h,u,f),i.bezierCurveTo(u,f+h,p+l,c,p,c),i.bezierCurveTo(p-l,c,o,f+h,o,f),i.closePath()}i.globalAlpha=d.alpha*r,i.strokeStyle=a,i.stroke()}e&&this.paintEllipse(t,c,d,o,r,i)}else if(t.type===Jp.RREC){const t=u,e=1===d.alignment;if(e||this.paintRoundedRectangle(t,c,d,o,r,i),d.visible){if(.5!==d.alignment){const e=t.width,r=t.height,s=d.width*(.5-(1-d.alignment)),n=t.x-s,o=t.y-s,a=t.width+2*s,l=t.height+2*s,h=s*(d.alignment>=1?Math.min(a/e,l/r):Math.min(e/a,r/l));let u=t.radius+h;const c=Math.min(a,l)/2;u=u>c?c:u,i.beginPath(),i.moveTo(n,o+u),i.lineTo(n,o+l-u),i.quadraticCurveTo(n,o+l,n+u,o+l),i.lineTo(n+a-u,o+l),i.quadraticCurveTo(n+a,o+l,n+a,o+l-u),i.lineTo(n+a,o+u),i.quadraticCurveTo(n+a,o,n+a-u,o),i.lineTo(n+u,o),i.quadraticCurveTo(n,o,n,o+u),i.closePath()}i.globalAlpha=d.alpha*r,i.strokeStyle=a,i.stroke()}e&&this.paintRoundedRectangle(t,c,d,o,r,i)}}}paintPolygonStroke(t,e,i,r,s,n,o){if(.5!==e.alignment){const i=e.width*(.5-(1-e.alignment));let n,a=iv.offsetPolygon(t.points,i);o.beginPath(),o.moveTo(a[0],a[1]);for(let t=2;t<a.length;t+=2)o.lineTo(a[t],a[t+1]);t.closeStroke&&o.closePath();for(let t=0;t<r.length;t++){if(n=r[t].shape.points,a=iv.offsetPolygon(n,i),s[t]){o.moveTo(a[0],a[1]);for(let t=2;t<a.length;t+=2)o.lineTo(a[t],a[t+1])}else{o.moveTo(a[a.length-2],a[a.length-1]);for(let t=a.length-4;t>=0;t-=2)o.lineTo(a[t],a[t+1])}r[t].shape.closeStroke&&o.closePath()}}o.globalAlpha=e.alpha*n,o.strokeStyle=i,o.stroke()}paintEllipse(t,e,i,r,s,n){const o=2*t.width,a=2*t.height,l=t.x-o/2,h=t.y-a/2,u=.5522848,c=o/2*u,d=a/2*u,p=l+o,f=h+a,m=l+o/2,g=h+a/2;0===i.alignment&&n.save(),n.beginPath(),n.moveTo(l,g),n.bezierCurveTo(l,g-d,m-c,h,m,h),n.bezierCurveTo(m+c,h,p,g-d,p,g),n.bezierCurveTo(p,g+d,m+c,f,m,f),n.bezierCurveTo(m-c,f,l,g+d,l,g),n.closePath(),0===i.alignment&&n.clip(),e.visible&&(n.globalAlpha=e.alpha*s,n.fillStyle=r,n.fill()),0===i.alignment&&n.restore()}paintRoundedRectangle(t,e,i,r,s,n){const o=t.x,a=t.y,l=t.width,h=t.height;let u=t.radius;const c=Math.min(l,h)/2;u=u>c?c:u,0===i.alignment&&n.save(),n.beginPath(),n.moveTo(o,a+u),n.lineTo(o,a+h-u),n.quadraticCurveTo(o,a+h,o+u,a+h),n.lineTo(o+l-u,a+h),n.quadraticCurveTo(o+l,a+h,o+l,a+h-u),n.lineTo(o+l,a+u),n.quadraticCurveTo(o+l,a,o+l-u,a),n.lineTo(o+u,a),n.quadraticCurveTo(o,a,o,a+u),n.closePath(),0===i.alignment&&n.clip(),e.visible&&(n.globalAlpha=e.alpha*s,n.fillStyle=r,n.fill()),0===i.alignment&&n.restore()}setPatternTransform(t,e){if(!1!==this._svgMatrix){if(!this._svgMatrix){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");if(e?.createSVGMatrix&&(this._svgMatrix=e.createSVGMatrix()),!this._svgMatrix||!t.setTransform)return void(this._svgMatrix=!1)}this._svgMatrix.a=e.a,this._svgMatrix.b=e.b,this._svgMatrix.c=e.c,this._svgMatrix.d=e.d,this._svgMatrix.e=e.tx,this._svgMatrix.f=e.ty,t.setTransform(this._svgMatrix.inverse())}}destroy(){this.renderer=null,this._svgMatrix=null,this._tempMatrix=null}}rv.extension={name:"graphics",type:_p.CanvasRendererPlugin},Ep.add(rv);class sv{constructor(t){this.maxItemsPerFrame=t,this.itemsLeft=0}beginFrame(){this.itemsLeft=this.maxItemsPerFrame}allowedToUpload(){return this.itemsLeft-- >0}}function nv(t,e){let i=!1;if(t?._textures?.length)for(let r=0;r<t._textures.length;r++)if(t._textures[r]instanceof om){const s=t._textures[r].baseTexture;e.includes(s)||(e.push(s),i=!0)}return i}function ov(t,e){if(t.baseTexture instanceof Bp){const i=t.baseTexture;return e.includes(i)||e.push(i),!0}return!1}function av(t,e){if(t._texture&&t._texture instanceof om){const i=t._texture.baseTexture;return e.includes(i)||e.push(i),!0}return!1}function lv(t,e){return e instanceof xy&&(e.updateText(!0),!0)}function hv(t,e){if(e instanceof fy){const t=e.toFontString();return cy.measureFont(t),!0}return!1}function uv(t,e){if(t instanceof xy){e.includes(t.style)||e.push(t.style),e.includes(t)||e.push(t);const i=t._texture.baseTexture;return e.includes(i)||e.push(i),!0}return!1}function cv(t,e){return t instanceof fy&&(e.includes(t)||e.push(t),!0)}const dv=class t{constructor(e){this.limiter=new sv(t.uploadsPerFrame),this.renderer=e,this.uploadHookHelper=null,this.queue=[],this.addHooks=[],this.uploadHooks=[],this.completes=[],this.ticking=!1,this.delayedTick=()=>{this.queue&&this.prepareItems()},this.registerFindHook(uv),this.registerFindHook(cv),this.registerFindHook(nv),this.registerFindHook(ov),this.registerFindHook(av),this.registerUploadHook(lv),this.registerUploadHook(hv)}upload(t){return new Promise(e=>{t&&this.add(t),this.queue.length?(this.completes.push(e),this.ticking||(this.ticking=!0,ag.system.addOnce(this.tick,this,sg.UTILITY))):e()})}tick(){setTimeout(this.delayedTick,0)}prepareItems(){for(this.limiter.beginFrame();this.queue.length&&this.limiter.allowedToUpload();){const t=this.queue[0];let e=!1;if(t&&!t._destroyed)for(let i=0,r=this.uploadHooks.length;i<r;i++)if(this.uploadHooks[i](this.uploadHookHelper,t)){this.queue.shift(),e=!0;break}e||this.queue.shift()}if(this.queue.length)ag.system.addOnce(this.tick,this,sg.UTILITY);else{this.ticking=!1;const t=this.completes.slice(0);this.completes.length=0;for(let e=0,i=t.length;e<i;e++)t[e]()}}registerFindHook(t){return t&&this.addHooks.push(t),this}registerUploadHook(t){return t&&this.uploadHooks.push(t),this}add(t){for(let e=0,i=this.addHooks.length;e<i&&!this.addHooks[e](t,this.queue);e++);if(t instanceof Og)for(let e=t.children.length-1;e>=0;e--)this.add(t.children[e]);return this}destroy(){this.ticking&&ag.system.remove(this.tick,this),this.ticking=!1,this.addHooks=null,this.uploadHooks=null,this.renderer=null,this.completes=null,this.queue=null,this.limiter=null,this.uploadHookHelper=null}};dv.uploadsPerFrame=4;let pv=dv;function fv(t,e){return e instanceof Bp&&(e._glTextures[t.CONTEXT_UID]||t.texture.bind(e),!0)}function mv(t,e){if(!(e instanceof ay))return!1;const{geometry:i}=e;e.finishPoly(),i.updateBatches();const{batches:r}=i;for(let s=0;s<r.length;s++){const{texture:e}=r[s].style;e&&fv(t,e.baseTexture)}return i.batchable||t.geometry.bind(i,e._resolveDirectShader(t)),!0}function gv(t,e){return t instanceof ay&&(e.push(t),!0)}Object.defineProperties(ph,{UPLOADS_PER_FRAME:{get:()=>pv.uploadsPerFrame,set(t){dd("7.1.0","settings.UPLOADS_PER_FRAME is deprecated, use prepare.BasePrepare.uploadsPerFrame"),pv.uploadsPerFrame=t}}});class yv extends pv{constructor(t){super(t),this.uploadHookHelper=this.renderer,this.registerFindHook(gv),this.registerUploadHook(fv),this.registerUploadHook(mv)}}yv.extension={name:"prepare",type:_p.RendererSystem},Ep.add(yv);function vv(t,e){const i=t;if(e instanceof Bp){const t=e.source,r=0===t.width?i.canvas.width:Math.min(i.canvas.width,t.width),s=0===t.height?i.canvas.height:Math.min(i.canvas.height,t.height);return i.ctx.drawImage(t,0,0,r,s,0,0,i.canvas.width,i.canvas.height),!0}return!1}class xv extends pv{constructor(t){super(t),this.uploadHookHelper=this,this.canvas=ph.ADAPTER.createCanvas(16,16),this.ctx=this.canvas.getContext("2d"),this.registerUploadHook(vv)}destroy(){super.destroy(),this.ctx=null,this.canvas=null}}xv.extension={name:"prepare",type:_p.CanvasRendererSystem},Ep.add(xv),Rg.prototype._tintedCanvas=null,Rg.prototype._renderCanvas=function(t){t.plugins.sprite.render(this)};const bv=new nf;class _v{constructor(t){this.renderer=t}render(t){const e=t._texture,i=this.renderer,r=i.canvasContext.activeContext,s=i.canvasContext.activeResolution;if(!e.valid)return;const n=e._frame.width,o=e._frame.height;let a=e._frame.width,l=e._frame.height;e.trim&&(a=e.trim.width,l=e.trim.height);let h=t.transform.worldTransform,u=0,c=0;const d=e.baseTexture.getDrawableSource();if(e.orig.width<=0||e.orig.height<=0||!e.valid||!d)return;i.canvasContext.setBlendMode(t.blendMode,!0),r.globalAlpha=t.worldAlpha;const p=e.baseTexture.scaleMode===rh.LINEAR,f=i.canvasContext.smoothProperty;f&&r[f]!==p&&(r[f]=p),e.trim?(u=e.trim.width/2+e.trim.x-t.anchor.x*e.orig.width,c=e.trim.height/2+e.trim.y-t.anchor.y*e.orig.height):(u=(.5-t.anchor.x)*e.orig.width,c=(.5-t.anchor.y)*e.orig.height),e.rotate&&(h.copyTo(bv),h=bv,pf.matrixAppendRotationInv(h,e.rotate,u,c),u=0,c=0),u-=a/2,c-=l/2,i.canvasContext.setContextTransform(h,t.roundPixels,1),t.roundPixels&&(u|=0,c|=0);const m=e.baseTexture.resolution,g=i.canvasContext._outerBlend;g&&(r.save(),r.beginPath(),r.rect(u*s,c*s,a*s,l*s),r.clip()),16777215!==t.tint?((t._cachedTint!==t.tintValue||t._tintedCanvas.tintId!==t._texture._updateID)&&(t._cachedTint=t.tintValue,t._tintedCanvas=Qy.getTintedCanvas(t,t.tintValue)),r.drawImage(t._tintedCanvas,0,0,Math.floor(n*m),Math.floor(o*m),Math.floor(u*s),Math.floor(c*s),Math.floor(a*s),Math.floor(l*s))):r.drawImage(d,e._frame.x*m,e._frame.y*m,Math.floor(n*m),Math.floor(o*m),Math.floor(u*s),Math.floor(c*s),Math.floor(a*s),Math.floor(l*s)),g&&r.restore(),i.canvasContext.setBlendMode(Kl.NORMAL)}destroy(){this.renderer=null}}_v.extension={name:"sprite",type:_p.CanvasRendererPlugin},Ep.add(_v);var wv=Object.defineProperty,Pv=(t,e,i)=>(((t,e,i)=>{e in t?wv(t,e,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[e]=i})(t,"symbol"!=typeof e?e+"":e,i),i);let Ev=class{constructor(t){Pv(this,"parent"),Pv(this,"paused"),this.parent=t,this.paused=!1}destroy(){}down(t){return!1}move(t){return!1}up(t){return!1}wheel(t){return!1}update(t){}resize(){}reset(){}pause(){this.paused=!0}resume(){this.paused=!1}};var Tv,Av=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},Iv={exports:{}};Tv=Iv,function(){var t,e;e=t={linear:function(t,e,i,r){return i*t/r+e},easeInQuad:function(t,e,i,r){return i*(t/=r)*t+e},easeOutQuad:function(t,e,i,r){return-i*(t/=r)*(t-2)+e},easeInOutQuad:function(t,e,i,r){return(t/=r/2)<1?i/2*t*t+e:-i/2*(--t*(t-2)-1)+e},easeInCubic:function(t,e,i,r){return i*(t/=r)*t*t+e},easeOutCubic:function(t,e,i,r){return i*((t=t/r-1)*t*t+1)+e},easeInOutCubic:function(t,e,i,r){return(t/=r/2)<1?i/2*t*t*t+e:i/2*((t-=2)*t*t+2)+e},easeInQuart:function(t,e,i,r){return i*(t/=r)*t*t*t+e},easeOutQuart:function(t,e,i,r){return-i*((t=t/r-1)*t*t*t-1)+e},easeInOutQuart:function(t,e,i,r){return(t/=r/2)<1?i/2*t*t*t*t+e:-i/2*((t-=2)*t*t*t-2)+e},easeInQuint:function(t,e,i,r){return i*(t/=r)*t*t*t*t+e},easeOutQuint:function(t,e,i,r){return i*((t=t/r-1)*t*t*t*t+1)+e},easeInOutQuint:function(t,e,i,r){return(t/=r/2)<1?i/2*t*t*t*t*t+e:i/2*((t-=2)*t*t*t*t+2)+e},easeInSine:function(t,e,i,r){return-i*Math.cos(t/r*(Math.PI/2))+i+e},easeOutSine:function(t,e,i,r){return i*Math.sin(t/r*(Math.PI/2))+e},easeInOutSine:function(t,e,i,r){return-i/2*(Math.cos(Math.PI*t/r)-1)+e},easeInExpo:function(t,e,i,r){return 0===t?e:i*Math.pow(2,10*(t/r-1))+e},easeOutExpo:function(t,e,i,r){return t===r?e+i:i*(1-Math.pow(2,-10*t/r))+e},easeInOutExpo:function(t,e,i,r){return(t/=r/2)<1?i/2*Math.pow(2,10*(t-1))+e:i/2*(2-Math.pow(2,-10*--t))+e},easeInCirc:function(t,e,i,r){return-i*(Math.sqrt(1-(t/=r)*t)-1)+e},easeOutCirc:function(t,e,i,r){return i*Math.sqrt(1-(t=t/r-1)*t)+e},easeInOutCirc:function(t,e,i,r){return(t/=r/2)<1?-i/2*(Math.sqrt(1-t*t)-1)+e:i/2*(Math.sqrt(1-(t-=2)*t)+1)+e},easeInElastic:function(t,e,i,r){var s,n,o;return o=1.70158,0===t||(t/=r),(n=0)||(n=.3*r),(s=i)<Math.abs(i)?(s=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/s),-s*Math.pow(2,10*(t-=1))*Math.sin((t*r-o)*(2*Math.PI)/n)+e},easeOutElastic:function(t,e,i,r){var s,n,o;return o=1.70158,0===t||(t/=r),(n=0)||(n=.3*r),(s=i)<Math.abs(i)?(s=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/s),s*Math.pow(2,-10*t)*Math.sin((t*r-o)*(2*Math.PI)/n)+i+e},easeInOutElastic:function(t,e,i,r){var s,n,o;return o=1.70158,0===t||(t/=r/2),(n=0)||(n=r*(.3*1.5)),(s=i)<Math.abs(i)?(s=i,o=n/4):o=n/(2*Math.PI)*Math.asin(i/s),t<1?s*Math.pow(2,10*(t-=1))*Math.sin((t*r-o)*(2*Math.PI)/n)*-.5+e:s*Math.pow(2,-10*(t-=1))*Math.sin((t*r-o)*(2*Math.PI)/n)*.5+i+e},easeInBack:function(t,e,i,r,s){return void 0===s&&(s=1.70158),i*(t/=r)*t*((s+1)*t-s)+e},easeOutBack:function(t,e,i,r,s){return void 0===s&&(s=1.70158),i*((t=t/r-1)*t*((s+1)*t+s)+1)+e},easeInOutBack:function(t,e,i,r,s){return void 0===s&&(s=1.70158),(t/=r/2)<1?i/2*(t*t*((1+(s*=1.525))*t-s))+e:i/2*((t-=2)*t*((1+(s*=1.525))*t+s)+2)+e},easeInBounce:function(e,i,r,s){return r-t.easeOutBounce(s-e,0,r,s)+i},easeOutBounce:function(t,e,i,r){return(t/=r)<1/2.75?i*(7.5625*t*t)+e:t<2/2.75?i*(7.5625*(t-=1.5/2.75)*t+.75)+e:t<2.5/2.75?i*(7.5625*(t-=2.25/2.75)*t+.9375)+e:i*(7.5625*(t-=2.625/2.75)*t+.984375)+e},easeInOutBounce:function(e,i,r,s){return e<s/2?.5*t.easeInBounce(2*e,0,r,s)+i:.5*t.easeOutBounce(2*e-s,0,r,s)+.5*r+i}},Tv.exports=e}.call(Av);const Sv=Iv.exports;function Cv(t,e){return t?"function"==typeof t?t:"string"==typeof t?Sv[t]:void 0:Sv[e]}const Mv={removeOnInterrupt:!1,ease:"linear",time:1e3};let Ov=class extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"startX"),Pv(this,"startY"),Pv(this,"deltaX"),Pv(this,"deltaY"),Pv(this,"keepCenter"),Pv(this,"startWidth",null),Pv(this,"startHeight",null),Pv(this,"deltaWidth",null),Pv(this,"deltaHeight",null),Pv(this,"width",null),Pv(this,"height",null),Pv(this,"time",0),this.options=Object.assign({},Mv,e),this.options.ease=Cv(this.options.ease),this.setupPosition(),this.setupZoom(),this.time=0}setupPosition(){typeof this.options.position<"u"?(this.startX=this.parent.center.x,this.startY=this.parent.center.y,this.deltaX=this.options.position.x-this.parent.center.x,this.deltaY=this.options.position.y-this.parent.center.y,this.keepCenter=!1):this.keepCenter=!0}setupZoom(){this.width=null,this.height=null,typeof this.options.scale<"u"?this.width=this.parent.screenWidth/this.options.scale:typeof this.options.scaleX<"u"||typeof this.options.scaleY<"u"?(typeof this.options.scaleX<"u"&&(this.width=this.parent.screenWidth/this.options.scaleX),typeof this.options.scaleY<"u"&&(this.height=this.parent.screenHeight/this.options.scaleY)):(typeof this.options.width<"u"&&(this.width=this.options.width),typeof this.options.height<"u"&&(this.height=this.options.height)),null!==this.width&&(this.startWidth=this.parent.screenWidthInWorldPixels,this.deltaWidth=this.width-this.startWidth),null!==this.height&&(this.startHeight=this.parent.screenHeightInWorldPixels,this.deltaHeight=this.height-this.startHeight)}down(){return this.options.removeOnInterrupt&&this.parent.plugins.remove("animate"),!1}complete(){this.parent.plugins.remove("animate"),null!==this.width&&this.parent.fitWidth(this.width,this.keepCenter,null===this.height),null!==this.height&&this.parent.fitHeight(this.height,this.keepCenter,null===this.width),!this.keepCenter&&this.options.position&&this.parent.moveCenter(this.options.position),this.parent.emit("animate-end",this.parent),this.options.callbackOnComplete&&this.options.callbackOnComplete(this.parent)}update(t){if(this.paused)return;this.time+=t;const e=new Kp(this.parent.scale.x,this.parent.scale.y);if(this.time>=this.options.time){const t=this.parent.width,i=this.parent.height;this.complete(),(t!==this.parent.width||i!==this.parent.height)&&this.parent.emit("zoomed",{viewport:this.parent,original:e,type:"animate"})}else{const t=this.options.ease(this.time,0,1,this.options.time);if(null!==this.width){const e=this.startWidth,i=this.deltaWidth;this.parent.fitWidth(e+i*t,this.keepCenter,null===this.height)}if(null!==this.height){const e=this.startHeight,i=this.deltaHeight;this.parent.fitHeight(e+i*t,this.keepCenter,null===this.width)}if(null===this.width?this.parent.scale.x=this.parent.scale.y:null===this.height&&(this.parent.scale.y=this.parent.scale.x),!this.keepCenter){const e=this.startX,i=this.startY,r=this.deltaX,s=this.deltaY,n=new Kp(this.parent.x,this.parent.y);this.parent.moveCenter(e+r*t,i+s*t),this.parent.emit("moved",{viewport:this.parent,original:n,type:"animate"})}(this.width||this.height)&&this.parent.emit("zoomed",{viewport:this.parent,original:e,type:"animate"})}}};const Nv={sides:"all",friction:.5,time:150,ease:"easeInOutSine",underflow:"center",bounceBox:null};class Lv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"left"),Pv(this,"top"),Pv(this,"right"),Pv(this,"bottom"),Pv(this,"underflowX"),Pv(this,"underflowY"),Pv(this,"ease"),Pv(this,"toX"),Pv(this,"toY"),this.options=Object.assign({},Nv,e),this.ease=Cv(this.options.ease,"easeInOutSine"),this.options.sides?"all"===this.options.sides?this.top=this.bottom=this.left=this.right=!0:"horizontal"===this.options.sides?(this.right=this.left=!0,this.top=this.bottom=!1):"vertical"===this.options.sides?(this.left=this.right=!1,this.top=this.bottom=!0):(this.top=-1!==this.options.sides.indexOf("top"),this.bottom=-1!==this.options.sides.indexOf("bottom"),this.left=-1!==this.options.sides.indexOf("left"),this.right=-1!==this.options.sides.indexOf("right")):this.left=this.top=this.right=this.bottom=!1;const i=this.options.underflow.toLowerCase();"center"===i?(this.underflowX=0,this.underflowY=0):(this.underflowX=-1!==i.indexOf("left")?-1:-1!==i.indexOf("right")?1:0,this.underflowY=-1!==i.indexOf("top")?-1:-1!==i.indexOf("bottom")?1:0),this.reset()}isActive(){return null!==this.toX||null!==this.toY}down(){return this.toX=this.toY=null,!1}up(){return this.bounce(),!1}update(t){if(!this.paused){if(this.bounce(),this.toX){const e=this.toX;e.time+=t,this.parent.emit("moved",{viewport:this.parent,type:"bounce-x"}),e.time>=this.options.time?(this.parent.x=e.end,this.toX=null,this.parent.emit("bounce-x-end",this.parent)):this.parent.x=this.ease(e.time,e.start,e.delta,this.options.time)}if(this.toY){const e=this.toY;e.time+=t,this.parent.emit("moved",{viewport:this.parent,type:"bounce-y"}),e.time>=this.options.time?(this.parent.y=e.end,this.toY=null,this.parent.emit("bounce-y-end",this.parent)):this.parent.y=this.ease(e.time,e.start,e.delta,this.options.time)}}}calcUnderflowX(){let t;switch(this.underflowX){case-1:t=0;break;case 1:t=this.parent.screenWidth-this.parent.screenWorldWidth;break;default:t=(this.parent.screenWidth-this.parent.screenWorldWidth)/2}return t}calcUnderflowY(){let t;switch(this.underflowY){case-1:t=0;break;case 1:t=this.parent.screenHeight-this.parent.screenWorldHeight;break;default:t=(this.parent.screenHeight-this.parent.screenWorldHeight)/2}return t}oob(){const t=this.options.bounceBox;if(t){const e=typeof t.x>"u"?0:t.x,i=typeof t.y>"u"?0:t.y,r=typeof t.width>"u"?this.parent.worldWidth:t.width,s=typeof t.height>"u"?this.parent.worldHeight:t.height;return{left:this.parent.left<e,right:this.parent.right>r,top:this.parent.top<i,bottom:this.parent.bottom>s,topLeft:new Kp(e*this.parent.scale.x,i*this.parent.scale.y),bottomRight:new Kp(r*this.parent.scale.x-this.parent.screenWidth,s*this.parent.scale.y-this.parent.screenHeight)}}return{left:this.parent.left<0,right:this.parent.right>this.parent.worldWidth,top:this.parent.top<0,bottom:this.parent.bottom>this.parent.worldHeight,topLeft:new Kp(0,0),bottomRight:new Kp(this.parent.worldWidth*this.parent.scale.x-this.parent.screenWidth,this.parent.worldHeight*this.parent.scale.y-this.parent.screenHeight)}}bounce(){var t,e;if(this.paused)return;let i,r=this.parent.plugins.get("decelerate",!0);r&&(r.x||r.y)&&(r.x&&r.percentChangeX===(null==(t=r.options)?void 0:t.friction)||r.y&&r.percentChangeY===(null==(e=r.options)?void 0:e.friction))&&(i=this.oob(),(i.left&&this.left||i.right&&this.right)&&(r.percentChangeX=this.options.friction),(i.top&&this.top||i.bottom&&this.bottom)&&(r.percentChangeY=this.options.friction));const s=this.parent.plugins.get("drag",!0)||{},n=this.parent.plugins.get("pinch",!0)||{};if(r=r||{},!(null!=s&&s.active||null!=n&&n.active||this.toX&&this.toY||r.x&&r.y)){i=i||this.oob();const t=i.topLeft,e=i.bottomRight;if(!this.toX&&!r.x){let r=null;i.left&&this.left?r=this.parent.screenWorldWidth<this.parent.screenWidth?this.calcUnderflowX():-t.x:i.right&&this.right&&(r=this.parent.screenWorldWidth<this.parent.screenWidth?this.calcUnderflowX():-e.x),null!==r&&this.parent.x!==r&&(this.toX={time:0,start:this.parent.x,delta:r-this.parent.x,end:r},this.parent.emit("bounce-x-start",this.parent))}if(!this.toY&&!r.y){let r=null;i.top&&this.top?r=this.parent.screenWorldHeight<this.parent.screenHeight?this.calcUnderflowY():-t.y:i.bottom&&this.bottom&&(r=this.parent.screenWorldHeight<this.parent.screenHeight?this.calcUnderflowY():-e.y),null!==r&&this.parent.y!==r&&(this.toY={time:0,start:this.parent.y,delta:r-this.parent.y,end:r},this.parent.emit("bounce-y-start",this.parent))}}}reset(){this.toX=this.toY=null,this.bounce()}}const Rv={left:!1,right:!1,top:!1,bottom:!1,direction:null,underflow:"center"};class kv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"last"),Pv(this,"noUnderflow"),Pv(this,"underflowX"),Pv(this,"underflowY"),this.options=Object.assign({},Rv,e),this.options.direction&&(this.options.left="x"===this.options.direction||"all"===this.options.direction||null,this.options.right="x"===this.options.direction||"all"===this.options.direction||null,this.options.top="y"===this.options.direction||"all"===this.options.direction||null,this.options.bottom="y"===this.options.direction||"all"===this.options.direction||null),this.parseUnderflow(),this.last={x:null,y:null,scaleX:null,scaleY:null},this.update()}parseUnderflow(){const t=this.options.underflow.toLowerCase();"none"===t?this.noUnderflow=!0:"center"===t?(this.underflowX=this.underflowY=0,this.noUnderflow=!1):(this.underflowX=-1!==t.indexOf("left")?-1:-1!==t.indexOf("right")?1:0,this.underflowY=-1!==t.indexOf("top")?-1:-1!==t.indexOf("bottom")?1:0,this.noUnderflow=!1)}move(){return this.update(),!1}update(){if(this.paused||this.parent.x===this.last.x&&this.parent.y===this.last.y&&this.parent.scale.x===this.last.scaleX&&this.parent.scale.y===this.last.scaleY)return;const t=new Kp(this.parent.x,this.parent.y),e=this.parent.plugins.decelerate||{};if(null!==this.options.left||null!==this.options.right){let i=!1;if(!this.noUnderflow&&this.parent.screenWorldWidth<this.parent.screenWidth)switch(this.underflowX){case-1:0!==this.parent.x&&(this.parent.x=0,i=!0);break;case 1:this.parent.x!==this.parent.screenWidth-this.parent.screenWorldWidth&&(this.parent.x=this.parent.screenWidth-this.parent.screenWorldWidth,i=!0);break;default:this.parent.x!==(this.parent.screenWidth-this.parent.screenWorldWidth)/2&&(this.parent.x=(this.parent.screenWidth-this.parent.screenWorldWidth)/2,i=!0)}else null!==this.options.left&&this.parent.left<(!0===this.options.left?0:this.options.left)&&(this.parent.x=-(!0===this.options.left?0:this.options.left)*this.parent.scale.x,e.x=0,i=!0),null!==this.options.right&&this.parent.right>(!0===this.options.right?this.parent.worldWidth:this.options.right)&&(this.parent.x=-(!0===this.options.right?this.parent.worldWidth:this.options.right)*this.parent.scale.x+this.parent.screenWidth,e.x=0,i=!0);i&&this.parent.emit("moved",{viewport:this.parent,original:t,type:"clamp-x"})}if(null!==this.options.top||null!==this.options.bottom){let i=!1;if(!this.noUnderflow&&this.parent.screenWorldHeight<this.parent.screenHeight)switch(this.underflowY){case-1:0!==this.parent.y&&(this.parent.y=0,i=!0);break;case 1:this.parent.y!==this.parent.screenHeight-this.parent.screenWorldHeight&&(this.parent.y=this.parent.screenHeight-this.parent.screenWorldHeight,i=!0);break;default:this.parent.y!==(this.parent.screenHeight-this.parent.screenWorldHeight)/2&&(this.parent.y=(this.parent.screenHeight-this.parent.screenWorldHeight)/2,i=!0)}else null!==this.options.top&&this.parent.top<(!0===this.options.top?0:this.options.top)&&(this.parent.y=-(!0===this.options.top?0:this.options.top)*this.parent.scale.y,e.y=0,i=!0),null!==this.options.bottom&&this.parent.bottom>(!0===this.options.bottom?this.parent.worldHeight:this.options.bottom)&&(this.parent.y=-(!0===this.options.bottom?this.parent.worldHeight:this.options.bottom)*this.parent.scale.y+this.parent.screenHeight,e.y=0,i=!0);i&&this.parent.emit("moved",{viewport:this.parent,original:t,type:"clamp-y"})}this.last.x=this.parent.x,this.last.y=this.parent.y,this.last.scaleX=this.parent.scale.x,this.last.scaleY=this.parent.scale.y}reset(){this.update()}}const Bv={minWidth:null,minHeight:null,maxWidth:null,maxHeight:null,minScale:null,maxScale:null};class Fv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),this.options=Object.assign({},Bv,e),this.clamp()}resize(){this.clamp()}clamp(){if(!this.paused)if(this.options.minWidth||this.options.minHeight||this.options.maxWidth||this.options.maxHeight){let t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight;if(null!==this.options.minWidth&&t<this.options.minWidth){const i=this.parent.scale.x;this.parent.fitWidth(this.options.minWidth,!1,!1,!0),this.parent.scale.y*=this.parent.scale.x/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.maxWidth&&t>this.options.maxWidth){const i=this.parent.scale.x;this.parent.fitWidth(this.options.maxWidth,!1,!1,!0),this.parent.scale.y*=this.parent.scale.x/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.minHeight&&e<this.options.minHeight){const i=this.parent.scale.y;this.parent.fitHeight(this.options.minHeight,!1,!1,!0),this.parent.scale.x*=this.parent.scale.y/i,t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}if(null!==this.options.maxHeight&&e>this.options.maxHeight){const t=this.parent.scale.y;this.parent.fitHeight(this.options.maxHeight,!1,!1,!0),this.parent.scale.x*=this.parent.scale.y/t,this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"})}}else if(this.options.minScale||this.options.maxScale){const t={x:null,y:null},e={x:null,y:null};if("number"==typeof this.options.minScale)t.x=this.options.minScale,t.y=this.options.minScale;else if(null!==this.options.minScale){const e=this.options.minScale;t.x=typeof e.x>"u"?null:e.x,t.y=typeof e.y>"u"?null:e.y}if("number"==typeof this.options.maxScale)e.x=this.options.maxScale,e.y=this.options.maxScale;else if(null!==this.options.maxScale){const t=this.options.maxScale;e.x=typeof t.x>"u"?null:t.x,e.y=typeof t.y>"u"?null:t.y}let i=this.parent.scale.x,r=this.parent.scale.y;null!==t.x&&i<t.x&&(i=t.x),null!==e.x&&i>e.x&&(i=e.x),null!==t.y&&r<t.y&&(r=t.y),null!==e.y&&r>e.y&&(r=e.y),(i!==this.parent.scale.x||r!==this.parent.scale.y)&&(this.parent.scale.set(i,r),this.parent.emit("zoomed",{viewport:this.parent,type:"clamp-zoom"}))}}reset(){this.clamp()}}const Dv={friction:.98,bounce:.8,minSpeed:.01},Uv=16;class Gv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"x"),Pv(this,"y"),Pv(this,"percentChangeX"),Pv(this,"percentChangeY"),Pv(this,"saved"),Pv(this,"timeSinceRelease"),this.options=Object.assign({},Dv,e),this.saved=[],this.timeSinceRelease=0,this.reset(),this.parent.on("moved",t=>this.handleMoved(t))}down(){return this.saved=[],this.x=this.y=null,!1}isActive(){return!(!this.x&&!this.y)}move(){if(this.paused)return!1;const t=this.parent.input.count();return(1===t||t>1&&!this.parent.plugins.get("pinch",!0))&&(this.saved.push({x:this.parent.x,y:this.parent.y,time:performance.now()}),this.saved.length>60&&this.saved.splice(0,30)),!1}handleMoved(t){if(this.saved.length){const e=this.saved[this.saved.length-1];"clamp-x"===t.type&&t.original?e.x===t.original.x&&(e.x=this.parent.x):"clamp-y"===t.type&&t.original&&e.y===t.original.y&&(e.y=this.parent.y)}}up(){if(0===this.parent.input.count()&&this.saved.length){const t=performance.now();for(const e of this.saved)if(e.time>=t-100){const i=t-e.time;this.x=(this.parent.x-e.x)/i,this.y=(this.parent.y-e.y)/i,this.percentChangeX=this.percentChangeY=this.options.friction,this.timeSinceRelease=0;break}}return!1}activate(t){typeof(t=t||{}).x<"u"&&(this.x=t.x,this.percentChangeX=this.options.friction),typeof t.y<"u"&&(this.y=t.y,this.percentChangeY=this.options.friction)}update(t){if(this.paused)return;const e=this.x||this.y,i=this.timeSinceRelease,r=this.timeSinceRelease+t;if(this.x){const e=this.percentChangeX,s=Math.log(e);this.parent.x+=this.x*Uv/s*(Math.pow(e,r/Uv)-Math.pow(e,i/Uv)),this.x*=Math.pow(this.percentChangeX,t/Uv)}if(this.y){const e=this.percentChangeY,s=Math.log(e);this.parent.y+=this.y*Uv/s*(Math.pow(e,r/Uv)-Math.pow(e,i/Uv)),this.y*=Math.pow(this.percentChangeY,t/Uv)}this.timeSinceRelease+=t,this.x&&this.y?Math.abs(this.x)<this.options.minSpeed&&Math.abs(this.y)<this.options.minSpeed&&(this.x=0,this.y=0):(Math.abs(this.x||0)<this.options.minSpeed&&(this.x=0),Math.abs(this.y||0)<this.options.minSpeed&&(this.y=0)),e&&this.parent.emit("moved",{viewport:this.parent,type:"decelerate"})}reset(){this.x=this.y=null}}const Xv={direction:"all",pressDrag:!0,wheel:!0,wheelScroll:1,reverse:!1,clampWheel:!1,underflow:"center",factor:1,mouseButtons:"all",keyToPress:null,ignoreKeyToPressOnTouch:!1,lineHeight:20,wheelSwapAxes:!1};class Wv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"moved"),Pv(this,"reverse"),Pv(this,"xDirection"),Pv(this,"yDirection"),Pv(this,"keyIsPressed"),Pv(this,"mouse"),Pv(this,"underflowX"),Pv(this,"underflowY"),Pv(this,"last"),Pv(this,"current"),Pv(this,"windowEventHandlers",[]),this.options=Object.assign({},Xv,e),this.moved=!1,this.reverse=this.options.reverse?1:-1,this.xDirection=!this.options.direction||"all"===this.options.direction||"x"===this.options.direction,this.yDirection=!this.options.direction||"all"===this.options.direction||"y"===this.options.direction,this.keyIsPressed=!1,this.parseUnderflow(),this.mouseButtons(this.options.mouseButtons),this.options.keyToPress&&this.handleKeyPresses(this.options.keyToPress)}handleKeyPresses(t){this.addWindowEventHandler("keyup",e=>{t.includes(e.code)&&(this.keyIsPressed=!1)}),this.addWindowEventHandler("keydown",e=>{t.includes(e.code)&&(this.keyIsPressed=!0)})}addWindowEventHandler(t,e){window.addEventListener(t,e),this.windowEventHandlers.push({event:t,handler:e})}destroy(){this.windowEventHandlers.forEach(({event:t,handler:e})=>{window.removeEventListener(t,e)})}mouseButtons(t){this.mouse=t&&"all"!==t?[-1!==t.indexOf("left"),-1!==t.indexOf("middle"),-1!==t.indexOf("right")]:[!0,!0,!0]}parseUnderflow(){const t=this.options.underflow.toLowerCase();"center"===t?(this.underflowX=0,this.underflowY=0):(t.includes("left")?this.underflowX=-1:t.includes("right")?this.underflowX=1:this.underflowX=0,t.includes("top")?this.underflowY=-1:t.includes("bottom")?this.underflowY=1:this.underflowY=0)}checkButtons(t){const e="mouse"===t.pointerType,i=this.parent.input.count();return!(!(1===i||i>1&&!this.parent.plugins.get("pinch",!0))||e&&!this.mouse[t.button])}checkKeyPress(t){return!this.options.keyToPress||this.keyIsPressed||this.options.ignoreKeyToPressOnTouch&&"touch"===t.data.pointerType}down(t){return!(this.paused||!this.options.pressDrag)&&(this.checkButtons(t)&&this.checkKeyPress(t)?(this.last={x:t.global.x,y:t.global.y},this.current=t.pointerId,!0):(this.last=null,!1))}get active(){return this.moved}move(t){if(this.paused||!this.options.pressDrag)return!1;if(this.last&&this.current===t.data.pointerId){const e=t.global.x,i=t.global.y,r=this.parent.input.count();if(1===r||r>1&&!this.parent.plugins.get("pinch",!0)){const r=e-this.last.x,s=i-this.last.y;if(this.moved||this.xDirection&&this.parent.input.checkThreshold(r)||this.yDirection&&this.parent.input.checkThreshold(s)){const r={x:e,y:i};return this.xDirection&&(this.parent.x+=(r.x-this.last.x)*this.options.factor),this.yDirection&&(this.parent.y+=(r.y-this.last.y)*this.options.factor),this.last=r,this.moved||this.parent.emit("drag-start",{event:t,screen:new Kp(this.last.x,this.last.y),world:this.parent.toWorld(new Kp(this.last.x,this.last.y)),viewport:this.parent}),this.moved=!0,this.parent.emit("moved",{viewport:this.parent,type:"drag"}),!0}}else this.moved=!1}return!1}up(t){if(this.paused)return!1;const e=this.parent.input.touches;if(1===e.length){const t=e[0];return t.last&&(this.last={x:t.last.x,y:t.last.y},this.current=t.id),this.moved=!1,!0}if(this.last&&this.moved){const e=new Kp(this.last.x,this.last.y);return this.parent.emit("drag-end",{event:t,screen:e,world:this.parent.toWorld(e),viewport:this.parent}),this.last=null,this.moved=!1,!0}return!1}wheel(t){if(this.paused)return!1;if(this.options.wheel){const e=this.parent.plugins.get("wheel",!0);if(!e||!e.options.wheelZoom&&!t.ctrlKey){const e=t.deltaMode?this.options.lineHeight:1,i=[t.deltaX,t.deltaY],[r,s]=this.options.wheelSwapAxes?i.reverse():i;return this.xDirection&&(this.parent.x+=r*e*this.options.wheelScroll*this.reverse),this.yDirection&&(this.parent.y+=s*e*this.options.wheelScroll*this.reverse),this.options.clampWheel&&this.clamp(),this.parent.emit("wheel-scroll",this.parent),this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.options.passiveWheel||t.preventDefault(),this.parent.options.stopPropagation&&t.stopPropagation(),!0}}return!1}resume(){this.last=null,this.paused=!1}clamp(){const t=this.parent.plugins.get("decelerate",!0)||{};if("y"!==this.options.clampWheel)if(this.parent.screenWorldWidth<this.parent.screenWidth)switch(this.underflowX){case-1:this.parent.x=0;break;case 1:this.parent.x=this.parent.screenWidth-this.parent.screenWorldWidth;break;default:this.parent.x=(this.parent.screenWidth-this.parent.screenWorldWidth)/2}else this.parent.left<0?(this.parent.x=0,t.x=0):this.parent.right>this.parent.worldWidth&&(this.parent.x=-this.parent.worldWidth*this.parent.scale.x+this.parent.screenWidth,t.x=0);if("x"!==this.options.clampWheel)if(this.parent.screenWorldHeight<this.parent.screenHeight)switch(this.underflowY){case-1:this.parent.y=0;break;case 1:this.parent.y=this.parent.screenHeight-this.parent.screenWorldHeight;break;default:this.parent.y=(this.parent.screenHeight-this.parent.screenWorldHeight)/2}else this.parent.top<0&&(this.parent.y=0,t.y=0),this.parent.bottom>this.parent.worldHeight&&(this.parent.y=-this.parent.worldHeight*this.parent.scale.y+this.parent.screenHeight,t.y=0)}}const Yv={speed:0,acceleration:null,radius:null};class Hv extends Ev{constructor(t,e,i={}){super(t),Pv(this,"options"),Pv(this,"target"),Pv(this,"velocity"),this.target=e,this.options=Object.assign({},Yv,i),this.velocity={x:0,y:0}}update(t){if(this.paused)return;const e=this.parent.center;let i=this.target.x,r=this.target.y;if(this.options.radius){if(!(Math.sqrt(Math.pow(this.target.y-e.y,2)+Math.pow(this.target.x-e.x,2))>this.options.radius))return;{const t=Math.atan2(this.target.y-e.y,this.target.x-e.x);i=this.target.x-Math.cos(t)*this.options.radius,r=this.target.y-Math.sin(t)*this.options.radius}}const s=i-e.x,n=r-e.y;if(s||n)if(this.options.speed)if(this.options.acceleration){const t=Math.atan2(r-e.y,i-e.x),o=Math.sqrt(Math.pow(s,2)+Math.pow(n,2));if(o){const a=(Math.pow(this.velocity.x,2)+Math.pow(this.velocity.y,2))/(2*this.options.acceleration);this.velocity=o>a?{x:Math.min(this.velocity.x+(this.options.acceleration,this.options.speed)),y:Math.min(this.velocity.y+(this.options.acceleration,this.options.speed))}:{x:Math.max(this.velocity.x-this.options.acceleration*this.options.speed,0),y:Math.max(this.velocity.y-this.options.acceleration*this.options.speed,0)};const l=Math.cos(t)*this.velocity.x,h=Math.sin(t)*this.velocity.y,u=Math.abs(l)>Math.abs(s)?i:e.x+l,c=Math.abs(h)>Math.abs(n)?r:e.y+h;this.parent.moveCenter(u,c),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}else{const t=Math.atan2(r-e.y,i-e.x),o=Math.cos(t)*this.options.speed,a=Math.sin(t)*this.options.speed,l=Math.abs(o)>Math.abs(s)?i:e.x+o,h=Math.abs(a)>Math.abs(n)?r:e.y+a;this.parent.moveCenter(l,h),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}else this.parent.moveCenter(i,r),this.parent.emit("moved",{viewport:this.parent,type:"follow"})}}const $v={radius:null,distance:null,top:null,bottom:null,left:null,right:null,speed:8,reverse:!1,noDecelerate:!1,linear:!1,allowButtons:!1};let jv=class extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"reverse"),Pv(this,"radiusSquared"),Pv(this,"left"),Pv(this,"top"),Pv(this,"right"),Pv(this,"bottom"),Pv(this,"horizontal"),Pv(this,"vertical"),this.options=Object.assign({},$v,e),this.reverse=this.options.reverse?1:-1,this.radiusSquared="number"==typeof this.options.radius?Math.pow(this.options.radius,2):null,this.resize()}resize(){const t=this.options.distance;null!==t?(this.left=t,this.top=t,this.right=this.parent.screenWidth-t,this.bottom=this.parent.screenHeight-t):this.options.radius||(this.left=this.options.left,this.top=this.options.top,this.right=null===this.options.right?null:this.parent.screenWidth-this.options.right,this.bottom=null===this.options.bottom?null:this.parent.screenHeight-this.options.bottom)}down(){return this.paused||this.options.allowButtons||(this.horizontal=this.vertical=null),!1}move(t){if(this.paused||"mouse"!==t.pointerType&&1!==t.pointerId||!this.options.allowButtons&&0!==t.buttons)return!1;const e=t.global.x,i=t.global.y;if(this.radiusSquared){const t=this.parent.toScreen(this.parent.center);if(Math.pow(t.x-e,2)+Math.pow(t.y-i,2)>=this.radiusSquared){const r=Math.atan2(t.y-i,t.x-e);this.options.linear?(this.horizontal=Math.round(Math.cos(r))*this.options.speed*this.reverse*.06,this.vertical=Math.round(Math.sin(r))*this.options.speed*this.reverse*.06):(this.horizontal=Math.cos(r)*this.options.speed*this.reverse*.06,this.vertical=Math.sin(r)*this.options.speed*this.reverse*.06)}else this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=0}else null!==this.left&&e<this.left?this.horizontal=Number(this.reverse)*this.options.speed*.06:null!==this.right&&e>this.right?this.horizontal=-1*this.reverse*this.options.speed*.06:(this.decelerateHorizontal(),this.horizontal=0),null!==this.top&&i<this.top?this.vertical=Number(this.reverse)*this.options.speed*.06:null!==this.bottom&&i>this.bottom?this.vertical=-1*this.reverse*this.options.speed*.06:(this.decelerateVertical(),this.vertical=0);return!1}decelerateHorizontal(){const t=this.parent.plugins.get("decelerate",!0);this.horizontal&&t&&!this.options.noDecelerate&&t.activate({x:this.horizontal*this.options.speed*this.reverse/(1e3/60)})}decelerateVertical(){const t=this.parent.plugins.get("decelerate",!0);this.vertical&&t&&!this.options.noDecelerate&&t.activate({y:this.vertical*this.options.speed*this.reverse/(1e3/60)})}up(){return this.paused||(this.horizontal&&this.decelerateHorizontal(),this.vertical&&this.decelerateVertical(),this.horizontal=this.vertical=null),!1}update(){if(!this.paused&&(this.horizontal||this.vertical)){const t=this.parent.center;this.horizontal&&(t.x+=this.horizontal*this.options.speed),this.vertical&&(t.y+=this.vertical*this.options.speed),this.parent.moveCenter(t),this.parent.emit("moved",{viewport:this.parent,type:"mouse-edges"})}}};const zv={noDrag:!1,percent:1,center:null,factor:1,axis:"all"};class Vv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"active",!1),Pv(this,"pinching",!1),Pv(this,"moved",!1),Pv(this,"lastCenter"),this.options=Object.assign({},zv,e)}down(){return this.parent.input.count()>=2&&(this.active=!0,!0)}isAxisX(){return["all","x"].includes(this.options.axis)}isAxisY(){return["all","y"].includes(this.options.axis)}move(t){if(this.paused||!this.active)return!1;const e=t.global.x,i=t.global.y,r=this.parent.input.touches;if(r.length>=2){const s=r[0],n=r[1],o=s.last&&n.last?Math.sqrt(Math.pow(n.last.x-s.last.x,2)+Math.pow(n.last.y-s.last.y,2)):null;if(s.id===t.pointerId?s.last={x:e,y:i,data:t}:n.id===t.pointerId&&(n.last={x:e,y:i,data:t}),o){let t;const e=new Kp(s.last.x+(n.last.x-s.last.x)/2,s.last.y+(n.last.y-s.last.y)/2);this.options.center||(t=this.parent.toLocal(e));let i=Math.sqrt(Math.pow(n.last.x-s.last.x,2)+Math.pow(n.last.y-s.last.y,2));i=0===i?i=1e-10:i;const r=(1-o/i)*this.options.percent*(this.isAxisX()?this.parent.scale.x:this.parent.scale.y);this.isAxisX()&&(this.parent.scale.x+=r),this.isAxisY()&&(this.parent.scale.y+=r),this.parent.emit("zoomed",{viewport:this.parent,type:"pinch",center:e});const a=this.parent.plugins.get("clamp-zoom",!0);if(a&&a.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const i=this.parent.toGlobal(t);this.parent.x+=(e.x-i.x)*this.options.factor,this.parent.y+=(e.y-i.y)*this.options.factor,this.parent.emit("moved",{viewport:this.parent,type:"pinch"})}!this.options.noDrag&&this.lastCenter&&(this.parent.x+=(e.x-this.lastCenter.x)*this.options.factor,this.parent.y+=(e.y-this.lastCenter.y)*this.options.factor,this.parent.emit("moved",{viewport:this.parent,type:"pinch"})),this.lastCenter=e,this.moved=!0}else this.pinching||(this.parent.emit("pinch-start",this.parent),this.pinching=!0);return!0}return!1}up(){return!!(this.pinching&&this.parent.input.touches.length<=1)&&(this.active=!1,this.lastCenter=null,this.pinching=!1,this.moved=!1,this.parent.emit("pinch-end",this.parent),!0)}}const qv={topLeft:!1,friction:.8,time:1e3,ease:"easeInOutSine",interrupt:!0,removeOnComplete:!1,removeOnInterrupt:!1,forceStart:!1};class Jv extends Ev{constructor(t,e,i,r={}){super(t),Pv(this,"options"),Pv(this,"ease"),Pv(this,"x"),Pv(this,"y"),Pv(this,"percent"),Pv(this,"snapping"),Pv(this,"deltaX"),Pv(this,"deltaY"),Pv(this,"startX"),Pv(this,"startY"),this.options=Object.assign({},qv,r),this.ease=Cv(r.ease,"easeInOutSine"),this.x=e,this.y=i,this.options.forceStart&&this.snapStart()}snapStart(){this.percent=0,this.snapping={time:0};const t=this.options.topLeft?this.parent.corner:this.parent.center;this.deltaX=this.x-t.x,this.deltaY=this.y-t.y,this.startX=t.x,this.startY=t.y,this.parent.emit("snap-start",this.parent)}wheel(){return this.options.removeOnInterrupt&&this.parent.plugins.remove("snap"),!1}down(){return this.options.removeOnInterrupt?this.parent.plugins.remove("snap"):this.options.interrupt&&(this.snapping=null),!1}up(){if(0===this.parent.input.count()){const t=this.parent.plugins.get("decelerate",!0);t&&(t.x||t.y)&&(t.percentChangeX=t.percentChangeY=this.options.friction)}return!1}update(t){if(!(this.paused||this.options.interrupt&&0!==this.parent.input.count()))if(this.snapping){const e=this.snapping;let i,r,s;e.time+=t;const n=this.startX,o=this.startY,a=this.deltaX,l=this.deltaY;if(e.time>this.options.time)i=!0,r=n+a,s=o+l;else{const t=this.ease(e.time,0,1,this.options.time);r=n+a*t,s=o+l*t}this.options.topLeft?this.parent.moveCorner(r,s):this.parent.moveCenter(r,s),this.parent.emit("moved",{viewport:this.parent,type:"snap"}),i&&(this.options.removeOnComplete&&this.parent.plugins.remove("snap"),this.parent.emit("snap-end",this.parent),this.snapping=null)}else{const t=this.options.topLeft?this.parent.corner:this.parent.center;(t.x!==this.x||t.y!==this.y)&&this.snapStart()}}}const Kv={width:0,height:0,time:1e3,ease:"easeInOutSine",center:null,interrupt:!0,removeOnComplete:!1,removeOnInterrupt:!1,forceStart:!1,noMove:!1};class Zv extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"ease"),Pv(this,"xScale"),Pv(this,"yScale"),Pv(this,"xIndependent"),Pv(this,"yIndependent"),Pv(this,"snapping"),this.options=Object.assign({},Kv,e),this.ease=Cv(this.options.ease),this.xIndependent=!1,this.yIndependent=!1,this.xScale=0,this.yScale=0,this.options.width>0&&(this.xScale=t.screenWidth/this.options.width,this.xIndependent=!0),this.options.height>0&&(this.yScale=t.screenHeight/this.options.height,this.yIndependent=!0),this.xScale=this.xIndependent?this.xScale:this.yScale,this.yScale=this.yIndependent?this.yScale:this.xScale,0===this.options.time?(t.container.scale.x=this.xScale,t.container.scale.y=this.yScale,this.options.removeOnComplete&&this.parent.plugins.remove("snap-zoom")):e.forceStart&&this.createSnapping()}createSnapping(){const t=this.parent.worldScreenWidth,e=this.parent.worldScreenHeight,i=this.parent.screenWidth/this.xScale,r=this.parent.screenHeight/this.yScale;this.snapping={time:0,startX:t,startY:e,deltaX:i-t,deltaY:r-e},this.parent.emit("snap-zoom-start",this.parent)}resize(){this.snapping=null,this.options.width>0&&(this.xScale=this.parent.screenWidth/this.options.width),this.options.height>0&&(this.yScale=this.parent.screenHeight/this.options.height),this.xScale=this.xIndependent?this.xScale:this.yScale,this.yScale=this.yIndependent?this.yScale:this.xScale}wheel(){return this.options.removeOnInterrupt&&this.parent.plugins.remove("snap-zoom"),!1}down(){return this.options.removeOnInterrupt?this.parent.plugins.remove("snap-zoom"):this.options.interrupt&&(this.snapping=null),!1}update(t){if(this.paused||this.options.interrupt&&0!==this.parent.input.count())return;let e;if(!this.options.center&&!this.options.noMove&&(e=this.parent.center),this.snapping){if(this.snapping){const i=this.snapping;if(i.time+=t,i.time>=this.options.time)this.parent.scale.set(this.xScale,this.yScale),this.options.removeOnComplete&&this.parent.plugins.remove("snap-zoom"),this.parent.emit("snap-zoom-end",this.parent),this.snapping=null;else{const t=this.snapping,e=this.ease(t.time,t.startX,t.deltaX,this.options.time),i=this.ease(t.time,t.startY,t.deltaY,this.options.time);this.parent.scale.x=this.parent.screenWidth/e,this.parent.scale.y=this.parent.screenHeight/i}const r=this.parent.plugins.get("clamp-zoom",!0);r&&r.clamp(),this.options.noMove||(this.options.center?this.parent.moveCenter(this.options.center):this.parent.moveCenter(e))}}else(this.parent.scale.x!==this.xScale||this.parent.scale.y!==this.yScale)&&this.createSnapping()}resume(){this.snapping=null,super.resume()}}const Qv={percent:.1,smooth:!1,interrupt:!0,reverse:!1,center:null,lineHeight:20,axis:"all",keyToPress:null,trackpadPinch:!1,wheelZoom:!0};class tx extends Ev{constructor(t,e={}){super(t),Pv(this,"options"),Pv(this,"smoothing"),Pv(this,"smoothingCenter"),Pv(this,"smoothingCount"),Pv(this,"keyIsPressed"),this.options=Object.assign({},Qv,e),this.keyIsPressed=!1,this.options.keyToPress&&this.handleKeyPresses(this.options.keyToPress)}handleKeyPresses(t){window.addEventListener("keydown",e=>{t.includes(e.code)&&(this.keyIsPressed=!0)}),window.addEventListener("keyup",e=>{t.includes(e.code)&&(this.keyIsPressed=!1)})}checkKeyPress(){return!this.options.keyToPress||this.keyIsPressed}down(){return this.options.interrupt&&(this.smoothing=null),!1}isAxisX(){return["all","x"].includes(this.options.axis)}isAxisY(){return["all","y"].includes(this.options.axis)}update(){if(this.smoothing){const t=this.smoothingCenter,e=this.smoothing;let i;this.options.center||(i=this.parent.toLocal(t)),this.isAxisX()&&(this.parent.scale.x+=e.x),this.isAxisY()&&(this.parent.scale.y+=e.y),this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const r=this.parent.plugins.get("clamp-zoom",!0);if(r&&r.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const e=this.parent.toGlobal(i);this.parent.x+=t.x-e.x,this.parent.y+=t.y-e.y}this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.smoothingCount++,this.smoothingCount>=this.options.smooth&&(this.smoothing=null)}}pinch(t){if(this.paused)return;const e=this.parent.input.getPointerPosition(t),i=-t.deltaY*(t.deltaMode?this.options.lineHeight:1)/200,r=Math.pow(2,(1+this.options.percent)*i);let s;this.options.center||(s=this.parent.toLocal(e)),this.isAxisX()&&(this.parent.scale.x*=r),this.isAxisY()&&(this.parent.scale.y*=r),this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const n=this.parent.plugins.get("clamp-zoom",!0);if(n&&n.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const t=this.parent.toGlobal(s);this.parent.x+=e.x-t.x,this.parent.y+=e.y-t.y}this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.emit("wheel-start",{event:t,viewport:this.parent})}wheel(t){if(this.paused||!this.checkKeyPress())return!1;if(t.ctrlKey&&this.options.trackpadPinch)this.pinch(t);else if(this.options.wheelZoom){const e=this.parent.input.getPointerPosition(t),i=(this.options.reverse?-1:1)*-t.deltaY*(t.deltaMode?this.options.lineHeight:1)/500,r=Math.pow(2,(1+this.options.percent)*i);if(this.options.smooth){const t={x:this.smoothing?this.smoothing.x*(this.options.smooth-this.smoothingCount):0,y:this.smoothing?this.smoothing.y*(this.options.smooth-this.smoothingCount):0};this.smoothing={x:((this.parent.scale.x+t.x)*r-this.parent.scale.x)/this.options.smooth,y:((this.parent.scale.y+t.y)*r-this.parent.scale.y)/this.options.smooth},this.smoothingCount=0,this.smoothingCenter=e}else{let t;this.options.center||(t=this.parent.toLocal(e)),this.isAxisX()&&(this.parent.scale.x*=r),this.isAxisY()&&(this.parent.scale.y*=r),this.parent.emit("zoomed",{viewport:this.parent,type:"wheel"});const i=this.parent.plugins.get("clamp-zoom",!0);if(i&&i.clamp(),this.options.center)this.parent.moveCenter(this.options.center);else{const i=this.parent.toGlobal(t);this.parent.x+=e.x-i.x,this.parent.y+=e.y-i.y}}this.parent.emit("moved",{viewport:this.parent,type:"wheel"}),this.parent.emit("wheel-start",{event:t,viewport:this.parent})}return!this.parent.options.passiveWheel}}let ex=class{constructor(t){Pv(this,"viewport"),Pv(this,"clickedAvailable"),Pv(this,"isMouseDown"),Pv(this,"last"),Pv(this,"wheelFunction"),Pv(this,"touches"),this.viewport=t,this.touches=[],this.addListeners()}addListeners(){this.viewport.eventMode="static",this.viewport.forceHitArea||(this.viewport.hitArea=new Qp(0,0,this.viewport.worldWidth,this.viewport.worldHeight)),this.viewport.on("pointerdown",this.down,this),this.viewport.options.allowPreserveDragOutside?this.viewport.on("globalpointermove",this.move,this):this.viewport.on("pointermove",this.move,this),this.viewport.on("pointerup",this.up,this),this.viewport.on("pointerupoutside",this.up,this),this.viewport.on("pointercancel",this.up,this),this.viewport.options.allowPreserveDragOutside||this.viewport.on("pointerleave",this.up,this),this.wheelFunction=t=>this.handleWheel(t),this.viewport.options.events.domElement.addEventListener("wheel",this.wheelFunction,{passive:this.viewport.options.passiveWheel}),this.isMouseDown=!1}destroy(){this.viewport.options.events.domElement.removeEventListener("wheel",this.wheelFunction)}down(t){if(!this.viewport.pause&&this.viewport.worldVisible){if("mouse"===t.pointerType?this.isMouseDown=!0:this.get(t.pointerId)||this.touches.push({id:t.pointerId,last:null}),1===this.count()){this.last=t.global.clone();const e=this.viewport.plugins.get("decelerate",!0),i=this.viewport.plugins.get("bounce",!0);e&&e.isActive()||i&&i.isActive()?this.clickedAvailable=!1:this.clickedAvailable=!0}else this.clickedAvailable=!1;this.viewport.plugins.down(t)&&this.viewport.options.stopPropagation&&t.stopPropagation()}}clear(){this.isMouseDown=!1,this.touches=[],this.last=null}checkThreshold(t){return Math.abs(t)>=this.viewport.threshold}move(t){if(this.viewport.pause||!this.viewport.worldVisible)return;const e=this.viewport.plugins.move(t);if(this.clickedAvailable&&this.last){const e=t.global.x-this.last.x,i=t.global.y-this.last.y;(this.checkThreshold(e)||this.checkThreshold(i))&&(this.clickedAvailable=!1)}e&&this.viewport.options.stopPropagation&&t.stopPropagation()}up(t){if(this.viewport.pause||!this.viewport.worldVisible)return;"mouse"===t.pointerType&&(this.isMouseDown=!1),"mouse"!==t.pointerType&&this.remove(t.pointerId);const e=this.viewport.plugins.up(t);this.clickedAvailable&&0===this.count()&&this.last&&(this.viewport.emit("clicked",{event:t,screen:this.last,world:this.viewport.toWorld(this.last),viewport:this.viewport}),this.clickedAvailable=!1),e&&this.viewport.options.stopPropagation&&t.stopPropagation()}getPointerPosition(t){const e=new Kp;return this.viewport.options.events.mapPositionToPoint(e,t.clientX,t.clientY),e}handleWheel(t){if(this.viewport.pause||!this.viewport.worldVisible)return;const e=this.viewport.toLocal(this.getPointerPosition(t));this.viewport.left<=e.x&&e.x<=this.viewport.right&&this.viewport.top<=e.y&&e.y<=this.viewport.bottom&&this.viewport.plugins.wheel(t)&&!this.viewport.options.passiveWheel&&t.preventDefault()}pause(){this.touches=[],this.isMouseDown=!1}get(t){for(const e of this.touches)if(e.id===t)return e;return null}remove(t){for(let e=0;e<this.touches.length;e++)if(this.touches[e].id===t)return void this.touches.splice(e,1)}count(){return(this.isMouseDown?1:0)+this.touches.length}};const ix=["drag","pinch","wheel","follow","mouse-edges","decelerate","animate","bounce","snap-zoom","clamp-zoom","snap","clamp"];class rx{constructor(t){Pv(this,"plugins"),Pv(this,"list"),Pv(this,"viewport"),this.viewport=t,this.list=[],this.plugins={}}add(t,e,i=ix.length){const r=this.plugins[t];r&&r.destroy(),this.plugins[t]=e;const s=ix.indexOf(t);-1!==s&&ix.splice(s,1),ix.splice(i,0,t),this.sort()}get(t,e){var i;return e&&null!=(i=this.plugins[t])&&i.paused?null:this.plugins[t]}update(t){for(const e of this.list)e.update(t)}resize(){for(const t of this.list)t.resize()}reset(){for(const t of this.list)t.reset()}removeAll(){this.list.forEach(t=>{t.destroy()}),this.plugins={},this.sort()}remove(t){var e;this.plugins[t]&&(null==(e=this.plugins[t])||e.destroy(),delete this.plugins[t],this.viewport.emit("plugin-remove",t),this.sort())}pause(t){var e;null==(e=this.plugins[t])||e.pause()}resume(t){var e;null==(e=this.plugins[t])||e.resume()}sort(){this.list=[];for(const t of ix)this.plugins[t]&&this.list.push(this.plugins[t])}down(t){let e=!1;for(const i of this.list)i.down(t)&&(e=!0);return e}move(t){let e=!1;for(const i of this.viewport.plugins.list)i.move(t)&&(e=!0);return e}up(t){let e=!1;for(const i of this.list)i.up(t)&&(e=!0);return e}wheel(t){let e=!1;for(const i of this.list)i.wheel(t)&&(e=!0);return e}}const sx={screenWidth:window.innerWidth,screenHeight:window.innerHeight,worldWidth:null,worldHeight:null,threshold:5,passiveWheel:!0,stopPropagation:!1,forceHitArea:null,noTicker:!1,disableOnContextMenu:!1,ticker:ag.shared,allowPreserveDragOutside:!1};class nx extends Og{constructor(t){super(),Pv(this,"moving"),Pv(this,"screenWidth"),Pv(this,"screenHeight"),Pv(this,"threshold"),Pv(this,"input"),Pv(this,"plugins"),Pv(this,"zooming"),Pv(this,"lastViewport"),Pv(this,"options"),Pv(this,"_dirty"),Pv(this,"_forceHitArea"),Pv(this,"_hitAreaDefault"),Pv(this,"_pause"),Pv(this,"tickerFunction"),Pv(this,"_worldWidth"),Pv(this,"_worldHeight"),Pv(this,"_disableOnContextMenu",t=>t.preventDefault()),this.options={...sx,...t},this.screenWidth=this.options.screenWidth,this.screenHeight=this.options.screenHeight,this._worldWidth=this.options.worldWidth,this._worldHeight=this.options.worldHeight,this.forceHitArea=this.options.forceHitArea,this.threshold=this.options.threshold,this.options.disableOnContextMenu&&this.options.events.domElement.addEventListener("contextmenu",this._disableOnContextMenu),this.options.noTicker||(this.tickerFunction=()=>this.update(this.options.ticker.elapsedMS),this.options.ticker.add(this.tickerFunction)),this.input=new ex(this),this.plugins=new rx(this)}destroy(t){!this.options.noTicker&&this.tickerFunction&&this.options.ticker.remove(this.tickerFunction),this.options.disableOnContextMenu&&this.options.events.domElement.removeEventListener("contextmenu",this._disableOnContextMenu),this.input.destroy(),super.destroy(t)}update(t){this.pause||(this.plugins.update(t),this.lastViewport&&(this.lastViewport.x!==this.x||this.lastViewport.y!==this.y?this.moving=!0:this.moving&&(this.emit("moved-end",this),this.moving=!1),this.lastViewport.scaleX!==this.scale.x||this.lastViewport.scaleY!==this.scale.y?this.zooming=!0:this.zooming&&(this.emit("zoomed-end",this),this.zooming=!1)),this.forceHitArea||(this._hitAreaDefault=new Qp(this.left,this.top,this.worldScreenWidth,this.worldScreenHeight),this.hitArea=this._hitAreaDefault),this._dirty=this._dirty||!this.lastViewport||this.lastViewport.x!==this.x||this.lastViewport.y!==this.y||this.lastViewport.scaleX!==this.scale.x||this.lastViewport.scaleY!==this.scale.y,this.lastViewport={x:this.x,y:this.y,scaleX:this.scale.x,scaleY:this.scale.y},this.emit("frame-end",this))}resize(t=window.innerWidth,e=window.innerHeight,i,r){this.screenWidth=t,this.screenHeight=e,typeof i<"u"&&(this._worldWidth=i),typeof r<"u"&&(this._worldHeight=r),this.plugins.resize(),this.dirty=!0}get worldWidth(){return this._worldWidth?this._worldWidth:this.width/this.scale.x}set worldWidth(t){this._worldWidth=t,this.plugins.resize()}get worldHeight(){return this._worldHeight?this._worldHeight:this.height/this.scale.y}set worldHeight(t){this._worldHeight=t,this.plugins.resize()}getVisibleBounds(){return new Qp(this.left,this.top,this.worldScreenWidth,this.worldScreenHeight)}toWorld(t,e){return 2===arguments.length?this.toLocal(new Kp(t,e)):this.toLocal(t)}toScreen(t,e){return 2===arguments.length?this.toGlobal(new Kp(t,e)):this.toGlobal(t)}get worldScreenWidth(){return this.screenWidth/this.scale.x}get worldScreenHeight(){return this.screenHeight/this.scale.y}get screenWorldWidth(){return this.worldWidth*this.scale.x}get screenWorldHeight(){return this.worldHeight*this.scale.y}get center(){return new Kp(this.worldScreenWidth/2-this.x/this.scale.x,this.worldScreenHeight/2-this.y/this.scale.y)}set center(t){this.moveCenter(t)}moveCenter(...t){let e,i;"number"==typeof t[0]?(e=t[0],i=t[1]):(e=t[0].x,i=t[0].y);const r=(this.worldScreenWidth/2-e)*this.scale.x,s=(this.worldScreenHeight/2-i)*this.scale.y;return(this.x!==r||this.y!==s)&&(this.position.set(r,s),this.plugins.reset(),this.dirty=!0),this}get corner(){return new Kp(-this.x/this.scale.x,-this.y/this.scale.y)}set corner(t){this.moveCorner(t)}moveCorner(...t){let e,i;return 1===t.length?(e=-t[0].x*this.scale.x,i=-t[0].y*this.scale.y):(e=-t[0]*this.scale.x,i=-t[1]*this.scale.y),(e!==this.x||i!==this.y)&&(this.position.set(e,i),this.plugins.reset(),this.dirty=!0),this}get screenWidthInWorldPixels(){return this.screenWidth/this.scale.x}get screenHeightInWorldPixels(){return this.screenHeight/this.scale.y}findFitWidth(t){return this.screenWidth/t}findFitHeight(t){return this.screenHeight/t}findFit(t,e){const i=this.screenWidth/t,r=this.screenHeight/e;return Math.min(i,r)}findCover(t,e){const i=this.screenWidth/t,r=this.screenHeight/e;return Math.max(i,r)}fitWidth(t=this.worldWidth,e,i=!0,r){let s;e&&(s=this.center),this.scale.x=this.screenWidth/t,i&&(this.scale.y=this.scale.x);const n=this.plugins.get("clamp-zoom",!0);return!r&&n&&n.clamp(),e&&s&&this.moveCenter(s),this}fitHeight(t=this.worldHeight,e,i=!0,r){let s;e&&(s=this.center),this.scale.y=this.screenHeight/t,i&&(this.scale.x=this.scale.y);const n=this.plugins.get("clamp-zoom",!0);return!r&&n&&n.clamp(),e&&s&&this.moveCenter(s),this}fitWorld(t){let e;t&&(e=this.center),this.scale.x=this.screenWidth/this.worldWidth,this.scale.y=this.screenHeight/this.worldHeight,this.scale.x<this.scale.y?this.scale.y=this.scale.x:this.scale.x=this.scale.y;const i=this.plugins.get("clamp-zoom",!0);return i&&i.clamp(),t&&e&&this.moveCenter(e),this}fit(t,e=this.worldWidth,i=this.worldHeight){let r;t&&(r=this.center),this.scale.x=this.screenWidth/e,this.scale.y=this.screenHeight/i,this.scale.x<this.scale.y?this.scale.y=this.scale.x:this.scale.x=this.scale.y;const s=this.plugins.get("clamp-zoom",!0);return s&&s.clamp(),t&&r&&this.moveCenter(r),this}setZoom(t,e){let i;e&&(i=this.center),this.scale.set(t);const r=this.plugins.get("clamp-zoom",!0);return r&&r.clamp(),e&&i&&this.moveCenter(i),this}zoomPercent(t,e){return this.setZoom(this.scale.x+this.scale.x*t,e)}zoom(t,e){return this.fitWidth(t+this.worldScreenWidth,e),this}get scaled(){return this.scale.x}set scaled(t){this.setZoom(t,!0)}snapZoom(t){return this.plugins.add("snap-zoom",new Zv(this,t)),this}OOB(){return{left:this.left<0,right:this.right>this.worldWidth,top:this.top<0,bottom:this.bottom>this.worldHeight,cornerPoint:new Kp(this.worldWidth*this.scale.x-this.screenWidth,this.worldHeight*this.scale.y-this.screenHeight)}}get right(){return-this.x/this.scale.x+this.worldScreenWidth}set right(t){this.x=-t*this.scale.x+this.screenWidth,this.plugins.reset()}get left(){return-this.x/this.scale.x}set left(t){this.x=-t*this.scale.x,this.plugins.reset()}get top(){return-this.y/this.scale.y}set top(t){this.y=-t*this.scale.y,this.plugins.reset()}get bottom(){return-this.y/this.scale.y+this.worldScreenHeight}set bottom(t){this.y=-t*this.scale.y+this.screenHeight,this.plugins.reset()}get dirty(){return!!this._dirty}set dirty(t){this._dirty=t}get forceHitArea(){return this._forceHitArea}set forceHitArea(t){t?(this._forceHitArea=t,this.hitArea=t):(this._forceHitArea=null,this.hitArea=new Qp(0,0,this.worldWidth,this.worldHeight))}drag(t){return this.plugins.add("drag",new Wv(this,t)),this}clamp(t){return this.plugins.add("clamp",new kv(this,t)),this}decelerate(t){return this.plugins.add("decelerate",new Gv(this,t)),this}bounce(t){return this.plugins.add("bounce",new Lv(this,t)),this}pinch(t){return this.plugins.add("pinch",new Vv(this,t)),this}snap(t,e,i){return this.plugins.add("snap",new Jv(this,t,e,i)),this}follow(t,e){return this.plugins.add("follow",new Hv(this,t,e)),this}wheel(t){return this.plugins.add("wheel",new tx(this,t)),this}animate(t){return this.plugins.add("animate",new Ov(this,t)),this}clampZoom(t){return this.plugins.add("clamp-zoom",new Fv(this,t)),this}mouseEdges(t){return this.plugins.add("mouse-edges",new jv(this,t)),this}get pause(){return!!this._pause}set pause(t){this._pause=t,this.lastViewport=null,this.moving=!1,this.zooming=!1,t&&this.input.pause()}ensureVisible(t,e,i,r,s){s&&(i>this.worldScreenWidth||r>this.worldScreenHeight)&&(this.fit(!0,i,r),this.emit("zoomed",{viewport:this,type:"ensureVisible"}));let n=!1;t<this.left?(this.left=t,n=!0):t+i>this.right&&(this.right=t+i,n=!0),e<this.top?(this.top=e,n=!0):e+r>this.bottom&&(this.bottom=e+r,n=!0),n&&this.emit("moved",{viewport:this,type:"ensureVisible"})}}const ox=100;var ax,lx={exports:{}};var hx=function(){if(ax)return lx.exports;function t(){}return ax=1,t.prototype={on:function(t,e,i){var r=this.e||(this.e={});return(r[t]||(r[t]=[])).push({fn:e,ctx:i}),this},once:function(t,e,i){var r=this;function s(){r.off(t,s),e.apply(i,arguments)}return s._=e,this.on(t,s,i)},emit:function(t){for(var e=[].slice.call(arguments,1),i=((this.e||(this.e={}))[t]||[]).slice(),r=0,s=i.length;r<s;r++)i[r].fn.apply(i[r].ctx,e);return this},off:function(t,e){var i=this.e||(this.e={}),r=i[t],s=[];if(r&&e)for(var n=0,o=r.length;n<o;n++)r[n].fn!==e&&r[n].fn._!==e&&s.push(r[n]);return s.length?i[t]=s:delete i[t],this}},lx.exports=t,lx.exports.TinyEmitter=t,lx.exports}();class ux extends hx.TinyEmitter{constructor({floorPlan:t,helperId:e}){super(),this.floorPlan=t,this.helperId=e}destroy(){delete this.floorPlan.helper[this.helperId],this.floorPlan=null}}class cx extends ux{constructor({floorPlan:t,parentEl:e,helperId:i}){super({floorPlan:t,helperId:i}),e&&t&&(this.data={cursor:["0","0"]},this.floorPlan.on("mousemove",this.update,this),this.mount(e),this.update())}update(){this.rootEl&&this.setData({cursor:[c(this.floorPlan.interaction.cursor[0],this.floorPlan.settings.units.system,this.floorPlan.settings.units.lengthDecimals),c(this.floorPlan.interaction.cursor[1],this.floorPlan.settings.units.system,this.floorPlan.settings.units.lengthDecimals)]})}setData(t={}){for(let e in t)this.data[e]=t[e];this.rootEl.innerHTML=this.template(this.data)}template(t={}){return`<span class="fpe-coordinates__unit">x:${t.cursor[0]}</span>\n <span class="fpe-coordinates__unit">z:${t.cursor[1]}</span>`}mount(t){this.rootEl||(this.rootEl=document.createElement("div"),this.rootEl.classList.add("fpe-coordinates"),t.appendChild(this.rootEl))}destroy(){this.floorPlan.off("mousemove",this.update),this.rootEl.remove(),delete this.floorPlan,delete this.data}}class dx extends ux{constructor({floorPlan:t,parentEl:e,helperId:i}){super({floorPlan:t,helperId:i}),e&&t&&(this.data={width:100,height:4,margin:2,style:"lines",box:{},scaleStep:null,scaleDisplay:null,steps:[],leftHanded:!1,isImperial:"imperial"===t.settings.units.system},this.floorPlan.view.on("zoom",this.update,this),this.floorPlan.on("update-settings",this.update,this),this.mount(e),this.update())}update(){this.data.isImperial="imperial"===this.floorPlan.settings.units.system;const t=this.data.isImperial?3.28084:1;if(!this.floorPlan.view.viewbox)return;this.data.box.length=this.floorPlan.view.viewbox.max[0]-this.floorPlan.view.viewbox.min[0],this.data.box.width=this.floorPlan.view.viewbox.max[1]-this.floorPlan.view.viewbox.min[1];const e=Math.min(this.floorPlan.view.client[0],this.floorPlan.view.client[1]),i=Math.min(this.data.box.length,this.data.box.width),r=e/i;if(!r)return;const s=200/r;this.data.scaleStep=i<=.5/t?.01/t:i<=1/t?.05/t:i<=2.5/t?.1/t:i<=5.4/t?.2/t:i<=12/t?.5/t:i<=25/t?1/t:i<=50/t?2/t:i<=100/t?5/t:i<=200/t?10/t:i<=550/t?20/t:50/t,this.data.scaleDisplay=this.data.scaleStep*t;const n=this.data.width,o=n*this.data.scaleStep/s,a=this.leftHanded?0:n;let l=0,h=[];if(this.data.leftHanded)for(;l<n-o;){let t=o<n-l?o:n-l;h.push([l+a,t]),l+=o}else for(;l>-n+o;){let t=o;h.push([l+a,-t]),l-=o}this.data.steps=h,this.setData()}setData(t={}){for(let e in t)this.data[e]=t[e];this.rootEl.setAttribute("viewBox",`-${this.data.margin} -${3*this.data.margin} ${this.data.width+2*this.data.margin} ${this.data.height+2*this.data.margin}`),this.rootEl.innerHTML=this.template(this.data)}template(t={}){let e="";return t.steps[0]&&(e+=`<rect\n class="fpe-scale-bar__background"\n style="fill:${this.backgroundClr()}"\n y="${2.5*-t.height}"\n x="${t.width+t.steps[0][1]-t.margin}"\n width="${-t.steps[0][1]+2*t.margin}"\n height="${4*t.height}"\n />`),e+=`<text x="${t.leftHanded?0:t.width}" text-anchor="${t.leftHanded?"start":"end"}" y="-3">\n ${t.scaleDisplay} ${t.isImperial?"ft":"m"}\n </text>`,"lines"===t.style&&(e+=`<path d="${this.stepStr(t.steps)}" />`),"solid"===t.style&&(e+="<g>",t.steps.forEach((t,i)=>{e+=`<rect\n class="${i%2!=0?"white":""}"\n x="${t[0]}"\n y="0"\n width="${t[1]}"\n height="0.5"\n />`}),e+="</g>"),e}backgroundClr(){let t=this.floorPlan.settings&&function(t,e=1){if(null!==f(t).match(/^#[a-f0-9]{6}$/i)){const{r:i,g:r,b:s}=g(t);return`rgba(${i},${r},${s},${e})`}}(this.floorPlan.settings.theme.background.color);return t||(t="rgba(255, 255, 255, 0.8)"),t+"!important"}stepStr(t){if(!t)return"";let e="",i=this.data.height;return t.forEach((t,r)=>{if(r>=1&&!this.data.leftHanded)return;t=t.map(t=>Math.round(1e3*t)/1e3);let s=r%2==0?0:i,n=r%2==0?i:0;0===r&&(e+=`M ${t[0]} ${i} L ${t[0]} 0`),e+=`L ${t[0]+t[1]} ${s} `,e+=`L ${t[0]+t[1]} ${n} `}),e}mount(t){this.rootEl||(this.rootEl=document.createElementNS("http://www.w3.org/2000/svg","svg"),this.rootEl.classList.add("fpe-scale-bar"),t.appendChild(this.rootEl))}destroy(){this.floorPlan.view.off("viewbox",this.update),this.floorPlan.off("update-settings",this.update),this.rootEl.remove(),delete this.floorPlan.helper.scaleBar,delete this.floorPlan,delete this.data}}const px=100,fx=80;class mx{constructor({width:t,height:e,position:i=[0,0],html:r="",closeButton:s=!0,floorPlan:n}={}){this._floorPlan=n,this.position=i,this.html=r,this.closeButton=s,this._anchorPos=null;let o=t||px;this.width=Math.max(100,o);let a=e||fx;this.height=Math.max(50,a),this._getPosition=()=>{this._anchorPos=this._floorPlan.getScreenPosition(this.position),this._updateInfoWindow()},this._getPosition(),this._createInfoWindow(),this._floorPlan.view.on("viewbox",this._getPosition,this),this._floorPlan.view.on("resize-canvas",this._getPosition,this)}_createInfoWindow(){const t=document.querySelector(`#${this._floorPlan.fpeId}.fpe`),e=t.querySelector("canvas");this.el||(this.el=document.createElement("div"),this.el.classList.add("fpe-info-window"),t.appendChild(this.el),this.el.addEventListener("wheel",t=>{let i=new WheelEvent(t.type,t);e.dispatchEvent(i)})),this._setContent(),this._updateInfoWindow()}_setContent(){let t=`<div class="fpe-info-window__content">${this.html}</div>`;this.closeButton&&(t+='<div class="fpe-info-window__close" @click="infoWindow.remove"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 40 40">\n <g fill="none" stroke="#000" stroke-width="1.2" stroke-miterlimit="10">\n <path d="M11.8 11.8l16.4 16.4M11.8 28.2l16.3-16.4" />\n </g>\n</svg></div>'),this.el.innerHTML=t;const e=this.el.querySelector(".fpe-info-window__close");e&&e.addEventListener("click",this.remove.bind(this))}_updateInfoWindow(){if(!this.el)return;const t=this._floorPlan.interaction.isPanning?"pointer-events: none;":"",e=this._anchorPos[0]-47,i=this._anchorPos[1]-this.height-15,r=1e3+2*this.position[1],s=this.height,n=this.width;this.el.setAttribute("style",`transform: translate(${e}px, ${i}px);${t} height:${s}px; width:${n}px; z-index:${r}`)}set({width:t,height:e,position:i,html:r,closeButton:s}){void 0!==i&&(this.position=i),void 0!==t&&(this.width=Math.max(100,t)),void 0!==e&&(this.height=Math.max(50,e)),void 0!==r&&(this.html=r),void 0!==s&&(this.closeButton=s),void 0===r&&void 0===s||this._setContent(),this._getPosition()}remove(){this._floorPlan.view.off("viewbox",this._getPosition),this._floorPlan.view.off("resize-canvas",this._getPosition),this.el.remove(),this._floorPlan=null}}class gx{constructor({position:t=[0,0],offset:e=[0,0],el:i,floorPlan:r}){if(this._updateHtmlMarker=()=>{this.el&&(this.isHidden=!(([t,e],i,r=0)=>i.min[0]-r<t&&i.max[0]+r>t&&i.min[1]-r<e&&i.max[1]+r>e)(this.position,this._floorPlan.view.viewbox,5),this.el.classList.toggle("fpe-marker--hidden",this.isHidden),this.isHidden||(this._anchorPos=this._floorPlan.getScreenPosition(this.position),this._updateHtmlMarkerStyle()))},!r)return;if(i instanceof HTMLElement==!1)return void dl.warn("no Element provided");this.el=i;const s=document.querySelector(`#${r.fpeId}.fpe`),n=s.querySelector("canvas");s.appendChild(this.el),this.el.classList.add("fpe-marker");const{width:o,height:a}=i.getBoundingClientRect();this.el.addEventListener("wheel",t=>{let e=new WheelEvent(t.type,t);n.dispatchEvent(e)}),this.id=O(),this._floorPlan=r,this.position=t,this.size=[o,a],this.offset=e,this._updateHtmlMarker(),this._floorPlan.view.on("viewbox",this._updateHtmlMarker),this._floorPlan.on("drag-end",this._updateHtmlMarker),this._floorPlan.view.on("resize-canvas",this._updateHtmlMarker)}_updateHtmlMarkerStyle(){const t=this._floorPlan.interaction.isPanning,e=this.offset?this.offset:[0,0],i=this._anchorPos[0]-this.size[0]/2+e[0],r=this._anchorPos[1]-this.size[1]/2+e[1];this.el.style.pointerEvents=t?"none":"",this.el.style.transform=`translate(${i}px, ${r}px)`}set({position:t,offset:e}){void 0!==t&&(this.position=t),void 0!==e&&(this.offset=e),this._updateHtmlMarker()}remove(){this._floorPlan.view.off("viewbox",this._updateHtmlMarker),this._floorPlan.view.off("resize-canvas",this._updateHtmlMarker),this._floorPlan.off("drag-end",this._updateHtmlMarker),this.el.remove(),this._floorPlan=null}}var yx={grad:.9,turn:360,rad:360/(2*Math.PI)},vx=function(t){return"string"==typeof t?t.length>0:"number"==typeof t},xx=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=Math.pow(10,e)),Math.round(i*t)/i+0},bx=function(t,e,i){return void 0===e&&(e=0),void 0===i&&(i=1),t>i?i:t>e?t:e},_x=function(t){return(t=isFinite(t)?t%360:0)>0?t:t+360},wx=function(t){return{r:bx(t.r,0,255),g:bx(t.g,0,255),b:bx(t.b,0,255),a:bx(t.a)}},Px=function(t){return{r:xx(t.r),g:xx(t.g),b:xx(t.b),a:xx(t.a,3)}},Ex=/^#([0-9a-f]{3,8})$/i,Tx=function(t){var e=t.toString(16);return e.length<2?"0"+e:e},Ax=function(t){var e=t.r,i=t.g,r=t.b,s=t.a,n=Math.max(e,i,r),o=n-Math.min(e,i,r),a=o?n===e?(i-r)/o:n===i?2+(r-e)/o:4+(e-i)/o:0;return{h:60*(a<0?a+6:a),s:n?o/n*100:0,v:n/255*100,a:s}},Ix=function(t){var e=t.h,i=t.s,r=t.v,s=t.a;e=e/360*6,i/=100,r/=100;var n=Math.floor(e),o=r*(1-i),a=r*(1-(e-n)*i),l=r*(1-(1-e+n)*i),h=n%6;return{r:255*[r,a,o,o,l,r][h],g:255*[l,r,r,a,o,o][h],b:255*[o,o,l,r,r,a][h],a:s}},Sx=function(t){return{h:_x(t.h),s:bx(t.s,0,100),l:bx(t.l,0,100),a:bx(t.a)}},Cx=function(t){return{h:xx(t.h),s:xx(t.s),l:xx(t.l),a:xx(t.a,3)}},Mx=function(t){return Ix((i=(e=t).s,{h:e.h,s:(i*=((r=e.l)<50?r:100-r)/100)>0?2*i/(r+i)*100:0,v:r+i,a:e.a}));var e,i,r},Ox=function(t){return{h:(e=Ax(t)).h,s:(s=(200-(i=e.s))*(r=e.v)/100)>0&&s<200?i*r/100/(s<=100?s:200-s)*100:0,l:s/2,a:e.a};var e,i,r,s},Nx=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s*,\s*([+-]?\d*\.?\d+)%\s*,\s*([+-]?\d*\.?\d+)%\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Lx=/^hsla?\(\s*([+-]?\d*\.?\d+)(deg|rad|grad|turn)?\s+([+-]?\d*\.?\d+)%\s+([+-]?\d*\.?\d+)%\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Rx=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*,\s*([+-]?\d*\.?\d+)(%)?\s*(?:,\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,kx=/^rgba?\(\s*([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s+([+-]?\d*\.?\d+)(%)?\s*(?:\/\s*([+-]?\d*\.?\d+)(%)?\s*)?\)$/i,Bx={string:[[function(t){var e=Ex.exec(t);return e?(t=e[1]).length<=4?{r:parseInt(t[0]+t[0],16),g:parseInt(t[1]+t[1],16),b:parseInt(t[2]+t[2],16),a:4===t.length?xx(parseInt(t[3]+t[3],16)/255,2):1}:6===t.length||8===t.length?{r:parseInt(t.substr(0,2),16),g:parseInt(t.substr(2,2),16),b:parseInt(t.substr(4,2),16),a:8===t.length?xx(parseInt(t.substr(6,2),16)/255,2):1}:null:null},"hex"],[function(t){var e=Rx.exec(t)||kx.exec(t);return e?e[2]!==e[4]||e[4]!==e[6]?null:wx({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:void 0===e[7]?1:Number(e[7])/(e[8]?100:1)}):null},"rgb"],[function(t){var e=Nx.exec(t)||Lx.exec(t);if(!e)return null;var i,r,s=Sx({h:(i=e[1],r=e[2],void 0===r&&(r="deg"),Number(i)*(yx[r]||1)),s:Number(e[3]),l:Number(e[4]),a:void 0===e[5]?1:Number(e[5])/(e[6]?100:1)});return Mx(s)},"hsl"]],object:[[function(t){var e=t.r,i=t.g,r=t.b,s=t.a,n=void 0===s?1:s;return vx(e)&&vx(i)&&vx(r)?wx({r:Number(e),g:Number(i),b:Number(r),a:Number(n)}):null},"rgb"],[function(t){var e=t.h,i=t.s,r=t.l,s=t.a,n=void 0===s?1:s;if(!vx(e)||!vx(i)||!vx(r))return null;var o=Sx({h:Number(e),s:Number(i),l:Number(r),a:Number(n)});return Mx(o)},"hsl"],[function(t){var e=t.h,i=t.s,r=t.v,s=t.a,n=void 0===s?1:s;if(!vx(e)||!vx(i)||!vx(r))return null;var o,a=(o={h:Number(e),s:Number(i),v:Number(r),a:Number(n)},{h:_x(o.h),s:bx(o.s,0,100),v:bx(o.v,0,100),a:bx(o.a)});return Ix(a)},"hsv"]]},Fx=function(t,e){for(var i=0;i<e.length;i++){var r=e[i][0](t);if(r)return[r,e[i][1]]}return[null,void 0]},Dx=function(t,e){var i=Ox(t);return{h:i.h,s:bx(i.s+100*e,0,100),l:i.l,a:i.a}},Ux=function(t){return(299*t.r+587*t.g+114*t.b)/1e3/255},Gx=function(t,e){var i=Ox(t);return{h:i.h,s:i.s,l:bx(i.l+100*e,0,100),a:i.a}},Xx=function(){function t(t){this.parsed=function(t){return"string"==typeof t?Fx(t.trim(),Bx.string):"object"==typeof t&&null!==t?Fx(t,Bx.object):[null,void 0]}(t)[0],this.rgba=this.parsed||{r:0,g:0,b:0,a:1}}return t.prototype.isValid=function(){return null!==this.parsed},t.prototype.brightness=function(){return xx(Ux(this.rgba),2)},t.prototype.isDark=function(){return Ux(this.rgba)<.5},t.prototype.isLight=function(){return Ux(this.rgba)>=.5},t.prototype.toHex=function(){return e=(t=Px(this.rgba)).r,i=t.g,r=t.b,n=(s=t.a)<1?Tx(xx(255*s)):"","#"+Tx(e)+Tx(i)+Tx(r)+n;var t,e,i,r,s,n},t.prototype.toRgb=function(){return Px(this.rgba)},t.prototype.toRgbString=function(){return e=(t=Px(this.rgba)).r,i=t.g,r=t.b,(s=t.a)<1?"rgba("+e+", "+i+", "+r+", "+s+")":"rgb("+e+", "+i+", "+r+")";var t,e,i,r,s},t.prototype.toHsl=function(){return Cx(Ox(this.rgba))},t.prototype.toHslString=function(){return e=(t=Cx(Ox(this.rgba))).h,i=t.s,r=t.l,(s=t.a)<1?"hsla("+e+", "+i+"%, "+r+"%, "+s+")":"hsl("+e+", "+i+"%, "+r+"%)";var t,e,i,r,s},t.prototype.toHsv=function(){return t=Ax(this.rgba),{h:xx(t.h),s:xx(t.s),v:xx(t.v),a:xx(t.a,3)};var t},t.prototype.invert=function(){return Wx({r:255-(t=this.rgba).r,g:255-t.g,b:255-t.b,a:t.a});var t},t.prototype.saturate=function(t){return void 0===t&&(t=.1),Wx(Dx(this.rgba,t))},t.prototype.desaturate=function(t){return void 0===t&&(t=.1),Wx(Dx(this.rgba,-t))},t.prototype.grayscale=function(){return Wx(Dx(this.rgba,-1))},t.prototype.lighten=function(t){return void 0===t&&(t=.1),Wx(Gx(this.rgba,t))},t.prototype.darken=function(t){return void 0===t&&(t=.1),Wx(Gx(this.rgba,-t))},t.prototype.rotate=function(t){return void 0===t&&(t=15),this.hue(this.hue()+t)},t.prototype.alpha=function(t){return"number"==typeof t?Wx({r:(e=this.rgba).r,g:e.g,b:e.b,a:t}):xx(this.rgba.a,3);var e},t.prototype.hue=function(t){var e=Ox(this.rgba);return"number"==typeof t?Wx({h:t,s:e.s,l:e.l,a:e.a}):xx(e.h)},t.prototype.isEqual=function(t){return this.toHex()===Wx(t).toHex()},t}(),Wx=function(t){return t instanceof Xx?t:new Xx(t)},Yx=[];!function(t){t.forEach(function(t){Yx.indexOf(t)<0&&(t(Xx,Bx),Yx.push(t))})}([function(t,e){var i={white:"#ffffff",bisque:"#ffe4c4",blue:"#0000ff",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",antiquewhite:"#faebd7",aqua:"#00ffff",azure:"#f0ffff",whitesmoke:"#f5f5f5",papayawhip:"#ffefd5",plum:"#dda0dd",blanchedalmond:"#ffebcd",black:"#000000",gold:"#ffd700",goldenrod:"#daa520",gainsboro:"#dcdcdc",cornsilk:"#fff8dc",cornflowerblue:"#6495ed",burlywood:"#deb887",aquamarine:"#7fffd4",beige:"#f5f5dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkkhaki:"#bdb76b",darkgray:"#a9a9a9",darkgreen:"#006400",darkgrey:"#a9a9a9",peachpuff:"#ffdab9",darkmagenta:"#8b008b",darkred:"#8b0000",darkorchid:"#9932cc",darkorange:"#ff8c00",darkslateblue:"#483d8b",gray:"#808080",darkslategray:"#2f4f4f",darkslategrey:"#2f4f4f",deeppink:"#ff1493",deepskyblue:"#00bfff",wheat:"#f5deb3",firebrick:"#b22222",floralwhite:"#fffaf0",ghostwhite:"#f8f8ff",darkviolet:"#9400d3",magenta:"#ff00ff",green:"#008000",dodgerblue:"#1e90ff",grey:"#808080",honeydew:"#f0fff0",hotpink:"#ff69b4",blueviolet:"#8a2be2",forestgreen:"#228b22",lawngreen:"#7cfc00",indianred:"#cd5c5c",indigo:"#4b0082",fuchsia:"#ff00ff",brown:"#a52a2a",maroon:"#800000",mediumblue:"#0000cd",lightcoral:"#f08080",darkturquoise:"#00ced1",lightcyan:"#e0ffff",ivory:"#fffff0",lightyellow:"#ffffe0",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",linen:"#faf0e6",mediumaquamarine:"#66cdaa",lemonchiffon:"#fffacd",lime:"#00ff00",khaki:"#f0e68c",mediumseagreen:"#3cb371",limegreen:"#32cd32",mediumspringgreen:"#00fa9a",lightskyblue:"#87cefa",lightblue:"#add8e6",midnightblue:"#191970",lightpink:"#ffb6c1",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",mintcream:"#f5fffa",lightslategray:"#778899",lightslategrey:"#778899",navajowhite:"#ffdead",navy:"#000080",mediumvioletred:"#c71585",powderblue:"#b0e0e6",palegoldenrod:"#eee8aa",oldlace:"#fdf5e6",paleturquoise:"#afeeee",mediumturquoise:"#48d1cc",mediumorchid:"#ba55d3",rebeccapurple:"#663399",lightsteelblue:"#b0c4de",mediumslateblue:"#7b68ee",thistle:"#d8bfd8",tan:"#d2b48c",orchid:"#da70d6",mediumpurple:"#9370db",purple:"#800080",pink:"#ffc0cb",skyblue:"#87ceeb",springgreen:"#00ff7f",palegreen:"#98fb98",red:"#ff0000",yellow:"#ffff00",slateblue:"#6a5acd",lavenderblush:"#fff0f5",peru:"#cd853f",palevioletred:"#db7093",violet:"#ee82ee",teal:"#008080",slategray:"#708090",slategrey:"#708090",aliceblue:"#f0f8ff",darkseagreen:"#8fbc8f",darkolivegreen:"#556b2f",greenyellow:"#adff2f",seagreen:"#2e8b57",seashell:"#fff5ee",tomato:"#ff6347",silver:"#c0c0c0",sienna:"#a0522d",lavender:"#e6e6fa",lightgreen:"#90ee90",orange:"#ffa500",orangered:"#ff4500",steelblue:"#4682b4",royalblue:"#4169e1",turquoise:"#40e0d0",yellowgreen:"#9acd32",salmon:"#fa8072",saddlebrown:"#8b4513",sandybrown:"#f4a460",rosybrown:"#bc8f8f",darksalmon:"#e9967a",lightgoldenrodyellow:"#fafad2",snow:"#fffafa",lightgrey:"#d3d3d3",lightgray:"#d3d3d3",dimgray:"#696969",dimgrey:"#696969",olivedrab:"#6b8e23",olive:"#808000"},r={};for(var s in i)r[i[s]]=s;var n={};t.prototype.toName=function(e){if(!(this.rgba.a||this.rgba.r||this.rgba.g||this.rgba.b))return"transparent";var s,o,a=r[this.toHex()];if(a)return a;if(null==e?void 0:e.closest){var l=this.toRgb(),h=1/0,u="black";if(!n.length)for(var c in i)n[c]=new t(i[c]).toRgb();for(var d in i){var p=(s=l,o=n[d],Math.pow(s.r-o.r,2)+Math.pow(s.g-o.g,2)+Math.pow(s.b-o.b,2));p<h&&(h=p,u=d)}return u}},e.string.push([function(e){var r=e.toLowerCase(),s="transparent"===r?"#0000":i[r];return s?new t(s).toRgb():null},"name"])}]);const Hx=class t{constructor(t=16777215){this._value=null,this._components=new Float32Array(4),this._components.fill(1),this._int=16777215,this.value=t}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(t){return this.value=t,this}set value(e){if(e instanceof t)this._value=this.cloneSource(e._value),this._int=e._int,this._components.set(e._components);else{if(null===e)throw new Error("Cannot set PIXI.Color#value to null");(null===this._value||!this.isSourceEqual(this._value,e))&&(this.normalize(e),this._value=this.cloneSource(e))}}get value(){return this._value}cloneSource(t){return"string"==typeof t||"number"==typeof t||t instanceof Number||null===t?t:Array.isArray(t)||ArrayBuffer.isView(t)?t.slice(0):"object"==typeof t&&null!==t?{...t}:t}isSourceEqual(t,e){const i=typeof t;if(i!==typeof e)return!1;if("number"===i||"string"===i||t instanceof Number)return t===e;if(Array.isArray(t)&&Array.isArray(e)||ArrayBuffer.isView(t)&&ArrayBuffer.isView(e))return t.length===e.length&&t.every((t,i)=>t===e[i]);if(null!==t&&null!==e){const i=Object.keys(t),r=Object.keys(e);return i.length===r.length&&i.every(i=>t[i]===e[i])}return t===e}toRgba(){const[t,e,i,r]=this._components;return{r:t,g:e,b:i,a:r}}toRgb(){const[t,e,i]=this._components;return{r:t,g:e,b:i}}toRgbaString(){const[t,e,i]=this.toUint8RgbArray();return`rgba(${t},${e},${i},${this.alpha})`}toUint8RgbArray(t){const[e,i,r]=this._components;return(t=t??[])[0]=Math.round(255*e),t[1]=Math.round(255*i),t[2]=Math.round(255*r),t}toRgbArray(t){t=t??[];const[e,i,r]=this._components;return t[0]=e,t[1]=i,t[2]=r,t}toNumber(){return this._int}toLittleEndianNumber(){const t=this._int;return(t>>16)+(65280&t)+((255&t)<<16)}multiply(e){const[i,r,s,n]=t.temp.setValue(e)._components;return this._components[0]*=i,this._components[1]*=r,this._components[2]*=s,this._components[3]*=n,this.refreshInt(),this._value=null,this}premultiply(t,e=!0){return e&&(this._components[0]*=t,this._components[1]*=t,this._components[2]*=t),this._components[3]=t,this.refreshInt(),this._value=null,this}toPremultiplied(t,e=!0){if(1===t)return(255<<24)+this._int;if(0===t)return e?0:this._int;let i=this._int>>16&255,r=this._int>>8&255,s=255&this._int;return e&&(i=i*t+.5|0,r=r*t+.5|0,s=s*t+.5|0),(255*t<<24)+(i<<16)+(r<<8)+s}toHex(){const t=this._int.toString(16);return`#${"000000".substring(0,6-t.length)+t}`}toHexa(){const t=Math.round(255*this._components[3]).toString(16);return this.toHex()+"00".substring(0,2-t.length)+t}setAlpha(t){return this._components[3]=this._clamp(t),this}round(t){const[e,i,r]=this._components;return this._components[0]=Math.round(e*t)/t,this._components[1]=Math.round(i*t)/t,this._components[2]=Math.round(r*t)/t,this.refreshInt(),this._value=null,this}toArray(t){t=t??[];const[e,i,r,s]=this._components;return t[0]=e,t[1]=i,t[2]=r,t[3]=s,t}normalize(e){let i,r,s,n;if(("number"==typeof e||e instanceof Number)&&e>=0&&e<=16777215){i=(e>>16&255)/255,r=(e>>8&255)/255,s=(255&e)/255,n=1}else if((Array.isArray(e)||e instanceof Float32Array)&&e.length>=3&&e.length<=4)e=this._clamp(e),[i,r,s,n=1]=e;else if((e instanceof Uint8Array||e instanceof Uint8ClampedArray)&&e.length>=3&&e.length<=4)e=this._clamp(e,0,255),[i,r,s,n=255]=e,i/=255,r/=255,s/=255,n/=255;else if("string"==typeof e||"object"==typeof e){if("string"==typeof e){const i=t.HEX_PATTERN.exec(e);i&&(e=`#${i[2]}`)}const o=Wx(e);o.isValid()&&(({r:i,g:r,b:s,a:n}=o.rgba),i/=255,r/=255,s/=255)}if(void 0===i)throw new Error(`Unable to convert color ${e}`);this._components[0]=i,this._components[1]=r,this._components[2]=s,this._components[3]=n,this.refreshInt()}refreshInt(){this._clamp(this._components);const[t,e,i]=this._components;this._int=(255*t<<16)+(255*e<<8)+(255*i|0)}_clamp(t,e=0,i=1){return"number"==typeof t?Math.min(Math.max(t,e),i):(t.forEach((r,s)=>{t[s]=Math.min(Math.max(r,e),i)}),t)}};Hx.shared=new Hx,Hx.temp=new Hx,Hx.HEX_PATTERN=/^(#|0x)?(([a-f0-9]{3}){1,2}([a-f0-9]{2})?)$/i;let $x=Hx;class jx{constructor({position:t,color:e,size:i,floorPlan:r}){this.position=t,this.color=e,this.size=i,this.floorPlan=r,this.id=O(),this.draw()}draw(){const t=this.size/4e3;this.layer=this.floorPlan.addLayer({id:"fpe-markers"});let e=[{type:"curve:composite",segments:[{type:"curve:arc",position:[0,-27.8],radius:12.4,startAngle:-25,endAngle:205},{type:"curve:line",end:[0,0],start:[-11.2,-22.5]}],style:{fill:new $x(this.color).toNumber(),stroke:6710886,strokeWidth:.5/t}},{type:"curve:circle",position:[0,-28],radius:5,style:{fill:1,fillOpacity:.2}}];this.graphic=this.layer.addGraphic({shapes:e,position:this.position,id:"marker_"+this.id,scale:t,scaleOnZoom:!0})}remove(){this.off("click"),this.layer.deleteGraphic(this.graphic),delete this.floorPlan,0===this.layer.graphics.size&&this.layer.destroy()}on(t="click",e,i){this.graphic.gfx.eventMode="static",this.graphic.gfx.on(t,e,i)}off(t="click",e){this.graphic.gfx.off(t,e)}set(t){let e=["position","color","size"];Object.keys(t).forEach(i=>{e.includes(i)&&(this[i]=t[i])}),this.draw()}}const zx=t=>{if(t?.children)for(var e=t.children.length-1;e>=0;e--)t.children[e].destroy({children:!0}),t.removeChild(t.children[e])};function Vx(t,e,i){const r=new Rg(t);return r.x=0,r.y=0,r.anchor.x=.5,r.anchor.y=.5,r.rotation=0,e&&(r.width=e),i&&(r.height=i),r}function qx(t=[]){return(t=t.sort((t,e)=>K(t)>K(e)?-1:1))&&t.length?[{type:"curve:polygonWithHoles",polygons:t}]:[]}function Jx(t,e,i=!1,r=16,s=8){let n=[];for(let m=0;m<e.length-1;m+=2)n.push({x:e[m],y:e[m+1]});let o,a,l,h=0,u=0,c=i?1:0;for(o=0;o<n.length-c;o++){a=n[o],l=o==n.length-1?n[0]:n[o+1];let e=l.x-a.x,i=l.y-a.y;var d=Math.sqrt(e*e+i*i),p={x:e/d,y:i/d},f=0;for(t.moveTo(a.x+u*p.x,a.y+u*p.y);f<=d;)f+=u,(f+=h>0?h:r)>d?(h=f-d,f=d):h=0,t.lineTo(a.x+f*p.x,a.y+f*p.y),(f+=s)>d&&0==h?u=f-d:(u=0,t.moveTo(a.x+f*p.x,a.y+f*p.y))}}function Kx(t){return t.stroke?{alpha:t.strokeOpacity||1,color:Dl(t.stroke),native:"native"===t.strokeWidth,width:"number"==typeof t.strokeWidth?t.strokeWidth:1,alignment:"number"==typeof t.alignment?t.alignment:.5}:{}}function Zx({shape:t,settings:e,gfx:i,style:r={}}){if(!i||!i.lineStyle)return;let s={...r,...t.style||{}};const n=ox,o=!["curve:line","curve:polyline","curve:arc"].includes(t.type)&&!!s.fill;if("string"==typeof s?.fill&&s.fill.startsWith("url("))!function({shape:t,settings:e,style:i,gfx:r}){if(Bp.defaultOptions.scaleMode=rh.NEAREST,"string"!=typeof i.fill||"curve:rectangle"!==t.type&&"curve:polygon"!==t.type)return;let s,n,o=[0,0],a=i.fill.match(/url\((.*?)\)/)?.[1];if(!a||!a.startsWith("data:image")&&!a.startsWith("https://"))return;let l=Rg.from(a);if("curve:polygon"===t.type){let{min:i,max:a}=W([t.points]);s=a[0]-i[0],n=a[1]-i[1],o=i;let h=new ay;Zx({shape:{type:"curve:polygon",points:t.points,style:{fill:16777215}},settings:e,gfx:h}),r.addChild(h),l.mask=h}else s=t.dimensions[0],n=t.dimensions[1],o=t.position;l.width=s*ox,l.height=n*ox,l.x=o[0]*ox,l.y=o[1]*ox,l.anchor.set(0),r.addChild(l)}({shape:t,settings:e,style:s,gfx:i});else{if(o&&s.fill&&i.beginFill(Dl(s.fill),s.fillOpacity),i.lineStyle(Kx(s)),"curve:rectangle"===t.type){let{position:e,dimensions:r}=t;i.drawRect(e[0]*n,e[1]*n,r[0]*n,r[1]*n)}else if("curve:circle"===t.type||"curve:composite"===t.type){Qx((t=>{const e={type:"curve:polygon",points:[]};switch(t.type){case"curve:circle":const i=t.radius,r=Hl(2*Math.PI,i),s=t.position,n=2*Math.PI/r;let o=0;for(let t=0;t<r;t++)e.points.push([i*Math.cos(o)+s[0],-i*Math.sin(o)+s[1]]),o+=n;break;case"curve:polygon":e.points=t.points;break;case"curve:rectangle":const a=t.dimensions,[l,h]=t.position||[0,0];e.points=[[l,h],[l,h+a[1]],[l+a[0],h+a[1]],[l+a[0],h]];break;case"curve:composite":for(const u of t.segments){let t=$l(u);e.points.push(...t.points)}}return e})(t).points,[],s,n,i,o)}else if("curve:arc"===t.type||"curve:quadraticBezier"===t.type){$l(t).points.forEach((t,e)=>{0===e?i.moveTo(t[0]*n,t[1]*n):i.lineTo(t[0]*n,t[1]*n)})}else if("curve:polygon"===t.type)Qx(t.points,[],s,n,i,o);else if("curve:polygonWithHoles"===t.type){let{polygons:e}=t;Qx(e[0],e.slice(1),s,n,i,o)}else if("curve:line"===t.type){let{start:e=[],end:r=[]}=t;i.moveTo(e[0]*n,e[1]*n),i.lineTo(r[0]*n,r[1]*n)}else if("curve:polyline"===t.type){let{points:e}=t;s.dash?Jx(i,e.flat().map(t=>t*n),!0):e.forEach((t,e)=>{0===e?i.moveTo(t[0]*n,t[1]*n):i.lineTo(t[0]*n,t[1]*n)})}else if("group"===t.type){let{position:s=[0,0],rotation:o=0}=t,a=new ay;a.x=s[0]*n,a.y=s[1]*n,a.rotation=-Math.PI/180*o,t.children.forEach(t=>Zx({shape:t,settings:e,gfx:a,style:r})),i.addChild(a)}else if("text"===t.type){let r=t.style?.fill?Dl(t.style.fill):0,s=t.style?.stroke?Dl(t.style.stroke):16777215,{position:o=[0,0],rotation:a=0,text:l,alignH:h="center",alignV:u="center",fontSize:c=16}=t;const d=new fy({fontFamily:e?.theme?.fontFamily||ll.theme.fontFamily,fontSize:c,fill:r,align:h,stroke:s,strokeThickness:3});let p=new xy(l,d);p.x=o[0]*n,p.y=o[1]*n,p.rotation=-Math.PI/180*a,p.anchor.x=.5,p.anchor.y="center"===u?.5:"bottom"===u?1:0,i.addChild(p)}o&&i.endFill()}}function Qx(t=[],e=[],i={},r=100,s,n){if(!t||!Array.isArray(t)||!t.length)return s;s.lineStyle(Kx(i));let o=t.flat().map(t=>t*r);if(i.dash?(Jx(s,o),n&&(s.lineStyle(0),s.drawPolygon(o))):s.drawPolygon(o),e.length){n&&s.beginHole();for(const t of e){let e=t.flat().map(t=>t*r);s.drawPolygon(e)}n&&s.endHole()}return s}function tb(t,e){e.on("product-load-texture",({resourceId:i})=>{!function(t,e){let i=t.resources.productJson.get(e);if(!i.boundingBox)return void dl.warn("product boundingBox missing");const{boundingBox:r}=i,s=Tl(r);let n={x:r.min[0],y:r.min[2]},o={x:Math.abs(r.min[0]/s[0]),y:Math.abs(r.min[2]/s[2])},a={x:r.max[0]-s[0]/2,y:r.max[2]-s[2]/2},l=t.resources.texture.get(e);l.offset=a,l.anchor=o,l.position=n}(e,i),eb({view:t,resourceId:i,loader:e})});const i=new ay;i.lineStyle({native:!0,color:3355443}),i.drawCircle(0,0,1),t._dummyTexture=t._renderer.generateTexture(i)}function eb({resourceId:t,loader:e,view:i}){if(!e.resources.texture.has(t))return Promise.reject(`no texture data to load ${t}`);const r=e.resources.texture.get(t);if(r.texture)return Promise.resolve();let{textureUrl:s}=r;return dp(),function(t){return new Promise((e,i)=>{var r=new Image;r.addEventListener("load",()=>{URL.revokeObjectURL(r.src),e(new om(new Bp(r)))}),r.addEventListener("error",()=>{URL.revokeObjectURL(r.src),i("image loading failed: "+t)});const s=t.includes("/storage/get/"),n=t.startsWith("https://")?t:ul+t;r.src=n,r.crossOrigin=s?"use-credentials":"anonymous"})}(s).then(s=>{r.imageData=s,function(t,e,i){const r=e?._renderer;if(!r)return;const s=i.resources.texture.get(t),n=s.error;if(dp(),!s.texture){const e=i.resources.productJson.get(t),o=new Og;let a,l;n||(a=new Rg(s.imageData),a=rb(a,s.applyFilter),o.addChild(a));const h=i.resources.productContour.get(t),u=h?.length?[{type:"curve:polygon",points:h[0],holes:h.slice(1)}]:[];if(u.length&&e?.boundingBox){let t;n?t={strokeWidth:.5,stroke:1,fill:16316664}:(t=Xl({settings:{theme:{showAssetTextures:!0,elements:{}}},elementType:"element:asset"}),t.stroke=Ka),l=ib(u,t);const i=new Rg(l);i.anchor.x=s.anchor.x,i.anchor.y=s.anchor.y;const r=Tl(e.boundingBox);if(!n){let t=a.width/r[0],e=s?.offset||{x:0,y:0};i.scale.x=a.width/i.width,i.scale.y=a.height/i.height,i.x=a.width/2-e.x*t,i.y=a.height/2-e.y*t}o.addChild(i)}s.texture=r.generateTexture(o,{scaleMode:rh.LINEAR,resolution:1.5}),o.destroy(!0),l&&l.destroy(!0)}i.emit("resource-loaded",{resourceId:t})}(t,i,e)}).catch(i=>{dl.warn(i),r.error={message:i},e.emit("resource-loaded",{resourceId:t})})}function ib(t,e){let i,r=new ay;for(const s of t)Zx({shape:s,gfx:r,style:e});return i=r.generateCanvasTexture(rh.LINEAR,2),r.destroy(),i}function rb(t,e){switch(e){case _l.Default:{const e=new by;e.matrix=[.7,0,0,0,.25,0,.7,0,0,.25,0,0,.7,0,.25,0,0,0,1,0],t.filters=[e];break}case _l.Grayscale:{const e=new by;e.blackAndWhite(!0),t.filters=[e];break}case _l.None:}return t}function sb(t,e,i,r,s,n,o){const a=Tl(t.boundingBox),l=Vx(e.texture,a[0]*o,a[2]*o);l.anchor.x=e.anchor.x,l.anchor.y=e.anchor.y,l.zIndex=1,function(t,e,i,r){if(!e.categories?.includes("tables")&&!e.categories?.includes("seating")||!i[0]?.polygons[0])return;const s=new rf(i[0].polygons[0].flatMap(e=>[e[0]*r/t.scale.x,e[1]*r/t.scale.y]));t.hitArea=s,t.eventMode="static"}(l,t,i,o);const h=[];let u=[];if(!n&&(null!=s.fill||null!=s.stroke)&&i?.length){const t=function(t,e,i,r,s){const n=null!=i.fill,o=null!=i.stroke,a=e.fillOpacity??1;if(!n&&!o)return null;if(n&&a<=0&&!o)return null;const l=ib(t,{fill:n?e.fill:void 0,fillOpacity:n?a:0,stroke:o?e.stroke:void 0,strokeWidth:o?e.strokeWidth:void 0,strokeOpacity:o?e.strokeOpacity:void 0}),h=new Rg(l);return h.anchor.x=r,h.anchor.y=s,h.zIndex=2,h.eventMode="none",h}(i,r,s,e.anchor.x,e.anchor.y);t&&h.push(t)}if("selected"===n)h.push(function(t,e,i,r){e.contourTexture||(e.contourTexture=ib(t,{stroke:i.stroke,strokeWidth:i.strokeWidth||1}));const s=new Rg(e.contourTexture);return s.anchor.x=e.anchor.x,s.anchor.y=e.anchor.y,s.zIndex=5,s.eventMode="none",i.fill&&(r.tint=Dl(i.fill)),s}(i,e,r,l));else if(n){const{overlay:t,shapes:e}=function(t){const e=new ay;return e.zIndex=5,e.eventMode="none",{overlay:e,shapes:t||[]}}(i);h.push(t),u=e}return{gfx:l,overlays:h,shapes:u}}function nb(t,e,i,r){!function(t,e){const i=t.product?.id,{loader:r}=e,s=r.resources.nodes.get(i);if(i&&!s?.has(t))pl(e.loader,t).catch(t=>dl.warn(t))}(t,i);const{view:s,settings:n,loader:o}=i,{theme:a,showCeilingLamps:l}=n;let h,u=[];const c=[],d=t.product?.id,p=o.resources.productJson.get(d)||{subCategories:[]},f="product:component"===t.product?.type,m=o.resources.productContour.get(d),g=o.resources.texture.get(d),y=qx(m);if(p?.subCategories.includes("ceilingLight")&&!l)return[];const v=function(t,e,i){if(!i)return zl(e);let r=0;for(const s of t.elements){if("element:asset"!==s.type||!s.product)continue;const t=zl(s.product.attributes);t>r&&(r=t)}return r}(t,p,f),x=Rl(t.type,v);e.zIndex=x||0;let b=Xl({element:t,settings:n,style:r});if(m||f||!p.boundingBox)if(a.showAssetTextures&&!g?.error||!m)if(a.showAssetTextures&&g?.texture){const e=sb(p,g,y,b,Ul({settings:n,element:t,elementType:t.type}),r,100);h=e.gfx,c.push(...e.overlays),u=e.shapes}else h=new Rg(s._dummyTexture);else{const e={...a,showAssetTextures:!1};b=Xl({element:t,settings:{...n,theme:e},style:r}),u=y,h=new ay}else{u=qx(function(t){const e=t;if(e){let t;return t=[[e.min[0],e.min[2]],[e.min[0],e.max[2]],[e.max[0],e.max[2]],[e.max[0],e.min[2]]],[t]}return[]}(p.boundingBox)),h=new ay}const _=c.length>0?c[c.length-1]:h;for(const w of u)Zx({shape:w,settings:n,gfx:_,style:b});return[h,...c].filter(Boolean)}function ob(t,e){const i=[];if("element:wall"===t.type)i.push(...function(t){let{valid:e,points:i}=t.geometryProfile,r=[];if(t.layout?.debugIds){for(let t of i)r.push({type:"curve:circle",radius:.02,position:t,style:{stroke:0,fill:e?32768:16711680,fillOpacity:.2}});let s=Xl({element:t});e||(s.stroke=16711680),r.push({type:"curve:polygon",points:i,style:s})}else r.push({type:"curve:polygon",points:i});return r}(t));else if("element:opening"===t.type)i.push(...Al(t));else if("spatialGraph:edge"===t.type)i.push(...function(t,e={}){let[i,r]=t.vertices,s="selected"===e,n=[{type:"curve:line",start:i.position,end:r.position}];if(t.layout.debugIds){let e,s=za(t.id)?t.id.substring(0,4):t.id;t.element&&(e=za(t.element.id)?t.element.id.substring(0,4):t.element.id);let o=t.element?`${s} (${e})`:s;n.push({type:"text",position:ii(i.position,ci(di(r.position,i.position),.5)),text:o,fontSize:10})}if(null===t.element||"element:spaceDivider"===t.element.type){let t=hi(ui(di(r.position,i.position))),e=.02,o=ii(i.position,ci(t,-e)),a=ii(i.position,ci(t,e)),l=ii(r.position,ci(t,e)),h=ii(r.position,ci(t,-e));n.unshift({type:"curve:polygon",points:[o,a,l,h],style:{stroke:null,fill:s?nl:rl,fillOpacity:.1}})}return n}(t));else if("layout:space"===t.type){const e=t.geometry.polygons;e.length>0&&i.push({type:"curve:polygonWithHoles",polygons:e})}else if("geometries"in t&&t.geometries.length){const{shapes:r,maxY:s}=function(t){const e=$a(t).sort((t,e)=>t.boundingBox.max[1]<e.boundingBox.max[1]?-1:1);"element:door"!==t.type&&"element:window"!==t.type||e.pop();let i=e.length?e[e.length-1].boundingBox.max[1]:0,r=[];for(let s of e)for(let t=0;t<s.outlines.length;t++)r.push({type:"curve:polygonWithHoles",polygons:[s.outlines[t],...s.holes[t]||[]]});return{shapes:r,maxY:i}}(t);i.push(...r),e.zIndex=e.zIndex+s}return i}function ab(t,e,i,r,s,n){if(!e||e.destroyed)return void dl.warn(`graphic container for node ${t.id} is missing`);let o,a,l=[];const{view:h}=i;if("element:asset"!==t.type||t.isComponentInstance)if("annotation:floorPlanImage"===t.type){const r=function(t,e,i){const{view:r,settings:s,loader:n}=i,o=ox;let a,l;e.x=t.position[0]*o,e.y=t.position[2]*o,e.rotation=-Math.PI/180*t.rotation||0;const{uri:h,length:u,width:c}=t.parameters,d=t.id,p=s.theme.elements?.floorPlan?.grayscale?_l.Grayscale:_l.None,f=n.resources.texture.get(d);return f?.texture?(a=Vx(f.texture,u*o,c*o),a=rb(a,p),l=new ay,a.zIndex=1,l.zIndex=5):(n.resources.nodes.set(d,/* @__PURE__ */new Set([t])),n.resources.texture.set(d,{textureUrl:h,applyFilter:p}),eb({loader:n,view:r,resourceId:d}),a=new ay),[a,l]}(t,e,i);o=r[0],a=r[1]}else o=function(t,e,i,r){const{settings:s}=i,n=ob(t,e),o=Nl(t);n.push(...o);const a=new ay,l=Xl({element:t,settings:s,style:r});for(const h of n)Zx({shape:h,settings:s,gfx:a,style:l});return a}(t,e,i,r);else{const s=nb(t,e,i,r);o=s[0],l=s.slice(1)}!function(t,e,i){if(!function(t){var e;return null==(e=null==t?void 0:t.type)?void 0:e.startsWith("element")}(t))return;const r=t.parent&&t.parent.id!==i?.name?t.getWorldTransform():t.getTransform();e.x=r.position[0]*ox,e.y=r.position[2]*ox,e.rotation=-Math.PI/180*r.rotation||0}(t,e,n),!s&&o&&function(t,e,i,r){r.gfxNodes[t.id]=e,i.eventMode="static";let s=t.id;"element"in t&&t.element&&(s=t.element.id),i._nodeId=s}(t,e,o,h),o&&e.addChild(o),a&&e.addChild(a);for(const u of l)u&&e.addChild(u)}function lb(t,e,{ctx:i,style:r,container:s,preview:n}){const{view:o,settings:a}=e;if(!t?.spaceGraph)return;let l;n||(r?o.styleCache[t.id]=r:!1===r?delete o.styleCache[t.id]:r=o.styleCache[t.id]),s?(l=s,zx(l)):l=new Og;const h=a.hideElements.includes(t.type)||"spatialGraph:edge"===t.type&&!a.showSpaceDividers||"element:spaceDivider"===t.type||"annotation:floorPlanImage"===t.type&&!a.showFloorPlan||"element:asset"===t.type&&"product"in t&&t.product?.attributes?.subCategories?.includes("ceilingLight")&&!a.showCeilingLamps||"space"in t||("element:window"===t.type||"element:door"===t.type)&&!t.parent||e.computed.wallContours.length&&["element:wall","element:boundaryWall","element:column","spatialGraph:edge"].includes(t.type),u=Rl(t.type);if(l.zIndex=u||0,l.name=t.id,h||ab(t,l,e,r,n,i),t&&"elements"in t){t.elements.length&&(l.sortableChildren=!0);for(const i of t.elements)lb(i,e,{ctx:l,style:r,preview:n})}s||i.addChild(l),o.viewportNeedsUpdate=!0}function hb(t,e){const i=e.getChildByName(t);i?.destroy(!0)}function ub(t,e,i,r){if(hb(t.id,e),r.hideElements.includes("roomStamp"))return;const{text:s,textOutline:n=!0}=r.theme.elements?.roomStamp||{},o=r.theme.background.color,a="transparent"!==o?o:"#eee",l=s?(h=s.map(t=>t/255),"#"+((255*h[0]<<16)+(255*h[1]<<8)+(255*h[2]|0)).toString(16).padStart(6,"0")):"#333333";var h;const u=new fy({fontFamily:r.theme.fontFamily||ll.theme.fontFamily,fontSize:16,align:"center",fill:l,stroke:a,strokeThickness:n?3:0});let c=t.geometry.polygons;if(0===c.length)return;let p=Ei(c),f=function(t,e){let i=t.getArea(),r=t.attributes.usage;if("void"===Ll(r))return[];let{roomStampDisplay:s}=e.theme.elements?.roomStamp||{};const n=e.spaceLabelMapping||{};let o,a;void 0!==n[r]&&(o=n[r]),void 0!==n[t.id]&&(o=n[t.id]),a="area"===e.units.roomDimensions?d(i,e.units.system,e.units.areaDecimals):"";let l="";l||"undefined"===r||(l=(r||"").replace(/([A-Z])/g,t=>` ${t}`).replace(/^./,t=>t.toUpperCase()).trim()),void 0!==o&&("string"!=typeof o?dl.warn("space label mapping has to be a string"):o.length>50?dl.warn("space label mapping has to be less than 50 characters"):l=o),s||(s=[],!1!==e.theme.elements?.roomStamp&&(t.layout.debugIds?s.push("id"):s.push("usage","area")));const h=[];return s.forEach(e=>{switch(e){case"id":let i=za(t.id)?t.id.substring(0,4):t.id;h.push(i);break;case"name":t.name&&h.push(t.name);break;case"customId":t.customId&&h.push(t.customId);break;case"usage":h.push(l);break;case"area":h.push(a);break;default:Array.isArray(e)&&"customAttribute"===e[0]&&t.customAttributes[e[1]]&&h.push(String(t.customAttributes[e[1]]))}}),h}(t,r),m=f.join("\n");const g=new xy(m,u);g.x=p[0]*ox,g.y=p[1]*ox,g.anchor.x=.5,g.anchor.y=.5,cb(g,i,t),g.name=t.id,g.eventMode="none",e.addChild(g)}function cb(t,e,i){let r=Math.min(1/e,2);t.scale.x=r,t.scale.y=r,t.visible=i.getArea()>1.5*r}function db(t="linear"){return Ty[t]}function pb({bb:t,animate:e=!1,view:i}){const r=i._viewport;if(!r)throw new Error("no viewport");return r.destroyed||!r.transform?Promise.resolve(!1):(i.viewportPaused&&i.startAnimationLoop(),new Promise(s=>{Number.isFinite(t.min?.[0])||s(!1);const{min:n,max:o}=t;let a=n[0],l=n[1];let h=o[0]-a,u=o[1]-l;a*=ox,l*=ox,h*=ox,u*=ox;let c=0;"number"==typeof e&&Number.isFinite(e)?c=e:!0===e&&(c=500);let d={x:a+h/2,y:l+u/2,width:h,height:u};if(c){let t={x:r.center.x,y:r.center.y,width:r.worldScreenWidth,height:r.worldScreenHeight},e={x:t.x-d.x,y:t.y-d.y,width:t.width-d.width,height:t.height-d.height};i._zoomTarget={delta:e,start:t,target:d,time:0,duration:c,destroy:()=>{i.ticker.remove("animateView"),delete i._zoomTarget,s(!0)},ease:db("easeInOutQuad"),updateViewport:mb.bind(i)},i.ticker.add("animateView",fb,i)}else r.fit(!1,d.width,d.height).moveCenter(d.x,d.y),mb.bind(i)({type:"animation"}),i.viewportNeedsUpdate=!0,s(!0)}))}function fb(t){if(!this._viewport||this._viewport.destroyed||!this._viewport.transform)return void this._zoomTarget?.destroy();let e=this._zoomTarget,i=!1;e.time+=t;let r=e.ease(e.time,0,1,e.duration),s={x:e.start.x-e.delta.x*r,y:e.start.y-e.delta.y*r,width:e.start.width-e.delta.width*r,height:e.start.height-e.delta.height*r};e.time>e.duration&&(s=e.target,i=!0),this._viewport.fit(!1,s.width,s.height).moveCenter(s.x,s.y),this.viewportNeedsUpdate=!0,e.updateViewport({type:"animation"});const n=0!==this._viewport.input.count();(i||n)&&e.destroy()}function mb(t){this.viewportNeedsUpdate=!0,this.viewportPaused&&this.startAnimationLoop(),"animation"!==t.type&&this._zoomTarget&&this._zoomTarget.destroy();const e=this._viewport,i=ox,r=e.scale._x,s=e.left,n=e.top,o=e.worldScreenWidth,a=e.worldScreenHeight;this.viewbox={min:[s/i,n/i],max:[(s+o)/i,(n+a)/i]},this.client=[e.screenWidth,e.screenHeight];const l=this.zoom!==r;this.zoom=r;const h={sourceEvent:{type:t.type},viewbox:this.viewbox,zoom:this.zoom};l?this.emit("zoom",h):this.emit("pan",h),this.emit("viewbox",h)}function gb({position:t,nodeId:e}){yb(this.interaction,{cursor:t,cursorTarget:e&&this.layout&&(this.layout.elementsById[e]||this.layout.spacesById[e])})}function yb(t,e){for(const i in e)t[i]=e[i],"cursorAction"===i&&vb(e[i])}function vb(t){let e="";switch(t){case"split-wall":e="var(--fpe-split-cursor) 16 16, pointer";break;case"duplicate":e="var(--fpe-duplicate-cursor) 16 16, pointer";break;case"move":e="move";break;default:e="default"}document.body.style.cursor=e}function xb(t){if(2===t?.data?.originalEvent?.button)return;if(!this||!this.view)throw new Error("Viewport context is missing");let e=this.interaction._dragStart||{x:0,y:0},i=t.data.global||{x:0,y:0},r=Math.abs(i.x-e.x),s=Math.abs(i.y-e.y);if(!(r<5&&s<5))return;let n,o=/* @__PURE__ */(new Date).getTime();if(this.interaction.lastClick){let t=o-this.interaction.lastClick.time,e=this.interaction.lastClick.position&&Math.max(Math.abs(i.x-this.interaction.lastClick.position.x),Math.abs(i.y-this.interaction.lastClick.position.y));n=t<400&&e<10}this.interaction.lastClick={time:o,position:{...i}};const a=n?"dblclick":"click",l=t.target?._nodeId,{x:h,y:u}=t.data?.global||{},c=this.getPlanPosition([h,u]);yb(this.interaction,{cursor:[c[0],c[1]]});let d={sourceEvent:t,nodeId:l,position:c,isDoubleClick:!!n};this.emit(a,d)}function bb(t){const{x:e,y:i}=t.data.global;this.view.windowPos=[e,i];const r=this.getPlanPosition(this.view.windowPos);this.interaction.lastSceneClick=r;const s=t.target?._nodeId;this.emit("context-menu",{sourceEvent:t,nodeId:s,position:r})}function _b(t){t.drag().pinch({percent:4}).wheel()}function wb(t){t.plugins.remove("wheel"),t.plugins.remove("pinch"),t.plugins.remove("drag")}function Pb(t){const{settings:e,view:i}=t;e.panZoom&&_b(i._viewport),i._viewport.on("pointerdown",Eb,t).on("pointerup",Tb,t).on("pointerup",xb,t).on("rightup",bb,t).on("pointerupoutside",Tb,t).on("pointermove",Ab,t).on("moved",mb,i).on("zoomed",mb,i);const r=Ib(t),s=(t=>{const{view:e,interaction:i}=t,r=(r,s)=>{e.viewportInFocus&&("Alt"===r.key&&"keyup"===s&&i.preventFocusoutOnAltKeyup&&r.preventDefault(),i.shiftKey=r.shiftKey,i.ctrlKey=r.ctrlKey,i.altKey=r.altKey,i.metaKey=r.metaKey,t.emit(s,{key:r.key,lowerCaseKey:r.key&&r.key.toLowerCase(),sourceEvent:r}))},s=t=>r(t,"keyup"),n=t=>r(t,"key");return document.addEventListener("keydown",n),document.addEventListener("keyup",s),()=>{document.removeEventListener("keydown",n),document.removeEventListener("keyup",s)}})(t);return t.on("mousemove",gb,t),()=>{e.panZoom&&wb(i._viewport),i._viewport.destroyed||i._viewport.off("pointerdown",Eb).off("pointerup",Tb).off("pointerup",xb).off("rightup",bb).off("pointerupoutside",Tb).off("pointermove",Ab).off("moved",mb).off("zoomed",mb),r?.(),s?.(),t.off("mousemove",gb)}}function Eb(t){this.interaction._dragStart={x:t.data.global.x,y:t.data.global.y};const e=t.data.getLocalPosition(this.view._viewport);this.emit("drag-start",{position:this.interaction.cursor,sourceEvent:t,screenPos:[e.x,e.y]})}function Tb(t){this.view.resume("drag");const e=t.data.getLocalPosition(this.view._viewport);this.emit("drag-end",{position:this.interaction.cursor,sourceEvent:t,screenPos:[e.x,e.y]}),this.interaction.isDragging=!1,this.interaction.dragOffset=null}function Ab(t){const{srcElement:e}=t?.data?.originalEvent||{};if(!e||!this.view._renderer)return;if(!(e===this.view._renderer.view))return;const i=t.data.getLocalPosition(this.view._viewport);let r=[i.x/ox,i.y/ox];const s=t.target&&t.target._nodeId;if(this.interaction.cursor=r,this.interaction.isDragging){const e=[i.x,i.y];this.emit("drag-move",{position:this.interaction.cursor,screenPos:e,sourceEvent:t})}this.emit("mousemove",{sourceEvent:t,nodeId:s,position:r})}const Ib=t=>{const e=document.querySelector(`#${t.fpeId} .fpe__plan`);if(!e)return()=>{};const i=()=>t.view.emit("focus",!1,t.view),r=()=>t.view.emit("focus",!0,t.view),s=()=>t.view.emit("focus","visible"===document.visibilityState,t.view),n=t=>(t.preventDefault(),!1);return e.addEventListener("mouseleave",i),e.addEventListener("mouseenter",r),document.addEventListener("visibilitychange",s),e.addEventListener("contextmenu",n,!1),()=>{e.removeEventListener("mouseleave",i),e.removeEventListener("mouseenter",r),document.removeEventListener("visibilitychange",s),e.removeEventListener("contextmenu",n,!1)}};function Sb({floorPlan:t,update:e=!1}){const{layout:i,view:r,settings:s}=t,{_renderer:n,_viewport:o}=r;if(!n)return;let a=s.theme.background.color;4===a.length&&(a=a[0]+a[1]+a[1]+a[2]+a[2]+a[3]+a[3]),n.background.color=new $x(a).toNumber();const l=r.gfxLayers.scene;zx(l);let h={ctx:l};e||(r.styleCache={});for(let u of i.spaces)lb(u,t,h);for(let u of i.elements)lb(u,t,h);for(let u of i.annotations)lb(u,t,h);for(let u of i.spatialGraph.edges)lb(u,t,h);t.computed.wallContours.length&&function(t,e){const{ctx:i,style:r}=e,{wallContours:s}=t.computed,n="wallContours",o=s.map(t=>({type:"curve:polygonWithHoles",polygons:t}));let a=i.getChildByName(n);a?zx(a):(a=new Og,a.name=n);const l=Rl("element:wall");a.zIndex=l||0;const h=Xl({style:r,settings:t.settings,elementType:"element:wall"}),u=new ay;for(const c of o)Zx({shape:c,gfx:u,style:h});a.addChild(u),i.addChild(a)}(t,h),Cb(t,!0),r.emit("scene-rendered",{update:e}),r.viewportNeedsUpdate=!0,e&&(s.panZoom?_b(o):wb(o)),r.viewportPaused&&r.startAnimationLoop()}function Cb(t,e=!1){const{view:i,layout:r,settings:s}=t,n=t.addLayer({id:"fpe-room-stamp",baseLayer:"annotation"});e?(zx(n.container),r.spaces.forEach(t=>ub(t,n.container,i.zoom,s))):n.container.children.forEach(t=>{let e=r.spaces.find(e=>e.id===t.name);cb(t,i.zoom,e)})}function Mb(t){const{shapeLayers:e}=t.settings;for(const i in e){const r=e[i];t.addLayer({id:i}).addGraphic({shapes:r})}}Ep.add(jf),Ep.add(Wy),Ep.add(rv),Ep.add(xv),Ep.add(_v);class Ob extends nx{}const Nb=(t,e,i)=>{const r=t.getChildByName(e);if(r)return zx(r),r;{const r=new Og;return r.sortableChildren=!0,r.zIndex=i,r.name=e,t.addChild(r),r}},Lb={top:0,left:0,center:.5,right:1,bottom:1};class Rb{constructor(){this.methods={},this.add=(t,e,i)=>{this.methods[t]={fn:e,ctx:i}},this.remove=t=>{delete this.methods[t]}}}class kb extends hx.TinyEmitter{constructor(t,e,i){super(),this.windowPos=[0,0],this.zoom=1,this.client=[0,0],this.layers=/* @__PURE__ */new Map,this.viewbox={min:[0,0],max:[0,0]},this.styleCache={},this.viewportNeedsUpdate=!1,this.viewportPaused=!1,this.viewportInFocus=!1,this.wallNodesToUpdate=[],this.wallNodeUpdateInProgress=!1,this.gfxNodes={},this._canvasMargin={x:0,y:0},this.ticker=new Rb,this._oldTime=Date.now(),this.parentEl=i;const r=this.parentEl.querySelector(".fpe__canvas");let s=this.parentEl.clientWidth,n=this.parentEl.clientHeight;this._settings=e;const o=window.devicePixelRatio||1;let a=e.theme.background.color;const l="transparent"===a;4===a.length&&(a=a[0]+a[1]+a[1]+a[2]+a[2]+a[3]+a[3]),this._renderer=function(t){for(const e of hg)if(e.test(t))return new e(t);throw new Error("Unable to auto-detect a suitable renderer.")}({width:s,height:n,view:r,antialias:!0,hello:!1,backgroundAlpha:l?0:1,autoDensity:!0,resolution:o,powerPreference:"high-performance",preserveDrawingBuffer:!0,backgroundColor:l?new $x(a).toNumber():void 0}),this.parentEl.appendChild(this._renderer.view),4===a.length&&(a=a[0]+a[1]+a[1]+a[2]+a[2]+a[3]+a[3]),l||(this._renderer.background.color=new $x(a).toNumber()),this._stage=new Og,this._stage.sortableChildren=!0,this._viewport=new Ob({screenWidth:s,screenHeight:n,worldWidth:s,worldHeight:n,events:this._renderer.events,noTicker:!0,passiveWheel:!1}),ag?.system&&ag.system.stop(),this.startAnimationLoop(),this.watchResize(),this._stage.addChild(this._viewport),this.on("focus",t=>{t&&this.viewportPaused?this.startAnimationLoop():t||this.stopAnimationLoop(),this.viewportInFocus=t}),this.gfxLayers=Bb(this._viewport),tb(this,t)}draw(){if(this.parentEl&&!this.parentEl.isConnected)return void this.destroy();if(!this._viewport||this._viewport?.destroyed||!this._renderer)return;const t=Date.now();let e=t-this._oldTime;this._oldTime=t,e<0&&(e=0),e>1e3&&(e=1e3);let i=Object.keys(this.ticker.methods).length;(this.viewportNeedsUpdate||i)&&(this.ticker?.methods&&Object.values(this.ticker.methods).forEach(({fn:t,ctx:i})=>{"function"==typeof t&&(i?t.call(i,e):t(e))}),this._viewport.update(e),this._renderer.render(this._stage)),this.viewportPaused||requestAnimationFrame(()=>this.draw()),this.viewportNeedsUpdate=!1}startAnimationLoop(){this._oldTime=Date.now(),this.viewportNeedsUpdate=!0,this.viewportPaused=!1,requestAnimationFrame(()=>this.draw())}stopAnimationLoop(){this.viewportPaused=!0}updateView(){if(this._viewport?.destroyed||!this._renderer)return;if(!this.parentEl.clientWidth||!this.parentEl.clientHeight)return;const t=this._viewport,e=this._renderer,i=ox,r=t.screenWidth,s=t.screenHeight,n=this.parentEl.clientWidth-this._canvasMargin.x,o=this.parentEl.clientHeight-this._canvasMargin.y;e.resize(n,o),t.resize(n,o);const a=r-n,l=s-o,h=this._settings.preserveViewbox,[u=.5,c=.5]=h.split("-").map(t=>Lb[t]),d=u*a,p=c*l;t.position.set(t.x-d,t.y-p),t.plugins.get("clamp-zoom")||t.clampZoom({minHeight:this._settings.zoomRange[0]*i,maxHeight:this._settings.zoomRange[1]*i}),e.render(this._stage);let f=t.left,m=t.top,g=t.worldScreenWidth,y=t.worldScreenHeight;this.viewbox={min:[f/i,m/i],max:[(f+g)/i,(m+y)/i]},this.client=[t.screenWidth,t.screenHeight]}async watchResize(){this._canvasMargin.x=this.parentEl.clientWidth-this._viewport.screenWidth,this._canvasMargin.y=this.parentEl.clientHeight-this._viewport.screenHeight,this._resizeObserver=new ResizeObserver(()=>{this.updateView(),this.emit("resize-canvas",this.viewbox)}),this._resizeObserver.observe(this.parentEl)}get gfxNodeCount(){return Object.keys(this.gfxNodes).length}reset(){this.styleCache={},this.gfxNodes={},this.gfxLayers=Bb(this._viewport)}pause(t="drag"){this._viewport.plugins.pause(t)}resume(t="drag"){this._viewport.plugins.resume(t)}destroy(){this.stopAnimationLoop(),this._resizeObserver?.disconnect(),this._viewport&&!this._viewport.destroyed&&this._viewport.destroy(),this._renderer?.destroy(!0),this._renderer=void 0}}const Bb=t=>{t.sortableChildren=!0;return{base:Nb(t,"base",0),scene:Nb(t,"scene",1),preview:Nb(t,"preview",2),annotation:Nb(t,"annotation",3),helper:Nb(t,"helper",4)}};function Fb(t,e,i){e=e||this;const{view:r,settings:s}=e,n=r.gfxNodes[t.id];if(n&&!n.destroyed){if("layout:space"===t.type){const e=r.layers.get("fpe-room-stamp");e&&ub(t,e.container,r.zoom,s)}lb(t,e,{ctx:n.parent,container:n,...i}),r.viewportNeedsUpdate=!0,r.viewportPaused&&r.startAnimationLoop()}}class Db{constructor({shapes:t=[],position:e=[0,0],alpha:i=1,scale:r=1,clearLayer:s=!1,interactive:n=!1,id:o,isHandler:a=!1,scaleOnZoom:l=!1,updatePositionOnDrag:h=!1,baseLayer:u,container:c,floorPlan:d}){if(this.shapes=t,this.gfxScale=r,this.scaleOnZoom=l,this.container=c,this.floorPlan=d,!this.container)return;s&&zx(this.container);let p=new ay;this.gfx=p,p.alpha=i;const f=Math.min(1/this.floorPlan.view.zoom)*this.gfxScale;e&&(p.x=e[0]*ox,p.y=e[1]*ox),p.eventMode=n?"static":"none",p._nodeId=o,a&&(p._isHandler=!0),h&&this.on("drag",this.doUpdatePositionOnDrag,this),f&&l&&(p.scale.x=p.scale.y=f),u.addChild(this.container),this.container.addChild(p),t.forEach(t=>Zx({shape:t,settings:this.floorPlan.settings,gfx:p})),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}set({position:t,rotation:e,style:i,shapes:r}={}){const s=Math.min(1/this.floorPlan.view.zoom)*this.gfxScale,n=this.gfx;if(function(t,{position:e,rotation:i}){e&&(t.x=e[0]*ox,t.y=e[1]*ox),i&&(t.rotation=-Math.PI/180*i)}(n,{position:t,rotation:e}),r&&(this.shapes=r,n.clear(),zx(n),r.forEach(t=>Zx({shape:t,settings:this.floorPlan.settings,gfx:n}))),s&&this.scaleOnZoom&&(n.scale.x=n.scale.y=s),i){const t=Kx(i);i.fill&&(n.geometry.graphicsData[0].fillStyle.color=Dl(i.fill)),n.geometry.graphicsData[0].lineStyle.color=Number(t.color),n.geometry.graphicsData[0].lineStyle.width=t.width,n.geometry.graphicsData[0].lineStyle.native=t.native,n.geometry.invalidate()}this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}doUpdatePositionOnDrag({position:t}){this.set({position:t})}on(t,e,i){return this.gfx.eventMode="static","drag"===t?this.addDragEvent(e,i):this.gfx.on(t,e,i),this}off(t,e){return"drag"===t?this.removeDragEvent():this.gfx.off(t,e),this}destroy(){this.off("drag"),this.gfx.destroy(),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}addDragEvent(t,e){function i(){this.floorPlan.interaction.isDragging=!1,this.floorPlan.view.resume("drag"),this.floorPlan.off("mousemove",t)}this.on("pointerdown",function(){this.floorPlan.interaction.isDragging=!0,this.floorPlan.view.pause("drag"),this.floorPlan.on("mousemove",t,e)},this),this.on("pointerup",i,this),this.on("pointerupoutside",i,this),this.on("pointercancel",i,this)}removeDragEvent(){this.off("pointerdown"),this.off("pointerup"),this.off("pointerupoutside"),this.off("pointercancel")}}class Ub{constructor(t,e,i){this.graphics=/* @__PURE__ */new Set,this.container=new Og,this.id=i,this.baseLayer=t.view.gfxLayers[e]||t.view.gfxLayers.helper,this.floorPlan=t,this.baseLayer.addChild(this.container)}addGraphic(t){const e=new Db({...t,floorPlan:this.floorPlan,baseLayer:this.baseLayer,container:this.container});return this.graphics.add(e),e}findGraphic(t){return this.container.getChildByName(t)}deleteGraphic(t){this.graphics.delete(t),t.destroy()}clear(){zx(this.container),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop()}destroy(){this.container&&(this.floorPlan.view.layers.delete(this.id),this.container.destroy({children:!0,texture:!0,baseTexture:!0}),this.floorPlan.view.viewportNeedsUpdate=!0,this.floorPlan.view.viewportPaused&&this.floorPlan.view.startAnimationLoop(),delete this.container,delete this.floorPlan)}}function Gb(t,{format:e,fileName:i,quality:r}={}){if("svg"===e)return;const s=new Image;s.src=t,s.onload=function(){const t=document.createElement("canvas");t.width=s.naturalWidth,t.height=s.naturalHeight;const n=t.getContext("2d");n.imageSmoothingEnabled=!1,n.drawImage(s,0,0),function(t,{format:e="png",fileName:i="floorplan",quality:r=.95}){let s="png"===e?"image/png":"image/jpeg";t.toBlob(function(t){!function({fileName:t,href:e,ext:i}){const r=document.createElement("a");Object.assign(r,{href:e,download:p(t,i),target:"_blank",rel:"noopener",style:"display:none;"}),document.body.appendChild(r),r.click(),document.body.removeChild(r)}({fileName:i,href:URL.createObjectURL(t),ext:e})},s,r)}(t,{format:e,fileName:i,quality:r})}}const Xb=nl,Wb=nl,Yb=sl,Hb=nl,$b=nl,jb=qa;class zb extends ux{constructor({floorPlan:t,helperId:e,mode:i="distance"}){super({floorPlan:t,helperId:e}),this.drawing=!1,this.polygonsOrPolylines=[],this.floorPlan=t,this.mode=i,this.floorPlan.on("mousemove",this.handlePointerMove,this),this.floorPlan.on("click",this.handlePointerDown,this),this.floorPlan.on("dblclick",this.handlePointerDown,this),this.floorPlan.on("update-settings",this.draw,this),this.startDrawing()}get isInAreaMode(){return"area"===this.mode}get isDrawing(){return this.drawing}set({mode:t}){this.mode=t,this.draw()}handlePointerMove(t){this.setSnapCursor(t)}handlePointerDown(t){this.setSnapCursor(t),this.drawPoint(t)}setSnapCursor({position:t}){this._snapCursor??=this.floorPlan.addHelper("snapCursor",{position:t});const{snapPoints:e,snapMargin:i}=this.floorPlan.computed;if(!e.length)return this._snapCursor.set({position:t}),void this.draw();const r=jl(t,e,i);this._snapCursor.isSnapping=!!r,this._snapCursor.set({position:r||t}),this.draw()}stopDrawing(){this.polygonsOrPolylines[this.polygonsOrPolylines.length-1].points.length>1&&this.drawing&&this.polygonDone()}cancelDrawing(){this.destroy()}startDrawing(){this.drawing=!0,this.polygonsOrPolylines.push({points:[],isClosed:!1,length:0,area:0,areaDisplay:"",lengthDisplay:"",contour:null,label:null,pointGraphics:[]})}removeLastPoint(){const t=this.polygonsOrPolylines[this.polygonsOrPolylines.length-1];if(t?.points.length>0){t.points.pop();const e=t.pointGraphics.pop();e&&this.layer.deleteGraphic(e),t.points.length<=1&&(t.contour&&(this.layer?.deleteGraphic(t.contour),t.contour=null),t.label&&(this.layer?.deleteGraphic(t.label),t.label=null)),0===t.points.length?(this.polygonsOrPolylines.pop(),this.drawing=!1):this.draw()}}polygonDone(){this.drawing=!1,this.emit("polygon-done",{}),this.draw()}drawPoint(t){this.drawing||this.startDrawing();const e=this.polygonsOrPolylines.length-1,i=this.polygonsOrPolylines[e],r=t.nodeId?.startsWith(`point/${e}/`);if(r||t.isDoubleClick){const r=t.nodeId===`point/${e}/0`;return"distance"===this.mode&&r&&(i.isClosed=!0),void this.polygonDone()}const{position:s}=this._snapCursor;i.points.push([...s]);const n=i.points.length-1,o=`point/${e}/${n}`;this.layer||(this.layer=this.floorPlan.addLayer());const a=this.layer.addGraphic({shapes:[{type:"curve:circle",position:[0,0],radius:.15,style:{fill:Hb,fillOpacity:.1}},{type:"curve:circle",position:[0,0],radius:.05,style:{stroke:$b,fill:jb,strokeWidth:1.5}}],position:s,scaleOnZoom:!0,id:o,isHandler:!0});i.pointGraphics[n]=a,a.on("drag",function(){this.updatePolygon(e,n,this.floorPlan.interaction.cursor),a.set({position:i.points[n]})},this)}updatePolygon(t,e,i){const r=i,{snapPoints:s,snapMargin:n}=this.floorPlan.computed,o=s.length&&jl(r,s,n);this.polygonsOrPolylines[t].points[e]=o||r,this.draw()}getLengthText(t){const{units:e}=this.floorPlan.settings;return c(t,e.system,e.lengthDecimals)}getAreaText(t){const{units:e}=this.floorPlan.settings;return d(t,e.system,e.areaDecimals)}reset(){this.drawing=!1,this.polygonsOrPolylines=[],this.floorPlan.removeHelper("snapCursor"),this._snapCursor=null,this.layer&&(this.layer.destroy(),this.layer=null)}draw(){this.polygonsOrPolylines.length&&(this.layer||(this.layer=this.floorPlan.addLayer()),this.polygonsOrPolylines.forEach((t,e)=>{if(!t.points.length)return;const i=this.drawing&&this._snapCursor&&e===this.polygonsOrPolylines.length-1?[...t.points,this._snapCursor.position]:t.points;if(i.length<2)return;t.length=function(t,e=!0){let i=0,r=e?t.length:t.length-1;for(var s=0;s<r;s++){let e=s,r=s<t.length-1?s+1:0;i+=ai(t[e],t[r])}return i}(i,t.isClosed),t.lengthDisplay=this.getLengthText(t.length);const r=i.length<2?0:180*yi(i[0],i[1])/Math.PI,s=i.map(t=>t.map(t=>Number(t.toFixed(10)))).slice(0,this.isInAreaMode?void 0:2),n=this.isInAreaMode?Ei([s]):[s[0][0]+(s[1][0]-s[0][0])/2,s[0][1]+(s[1][1]-s[0][1])/2];t.area=Math.abs(J(i)),t.areaDisplay=this.getAreaText(t.area);const o=this.isInAreaMode||t.isClosed?"curve:polygon":"curve:polyline",a={stroke:Yb,dash:!0,strokeWidth:"native"};let l=t.lengthDisplay,h=r;this.isInAreaMode&&(a.fill=Wb,a.fillOpacity=.04,l=t.areaDisplay,h=0);const u=[{type:o,points:i,style:a}],c={shapes:[{type:"text",text:l,position:[0,0],rotation:h,alignV:"bottom",fontSize:15,style:{fill:Xb}}],id:"text",position:n,scaleOnZoom:!0};t.contour?t.contour.set({shapes:u}):t.contour=this.layer.addGraphic({shapes:u}),t.label?t.label.set(c):t.label=this.layer.addGraphic(c);const d=this.isInAreaMode?{area:t.area}:{distance:t.length};this.emit("polygon-draw",d)}))}destroy(){this.reset(),this.floorPlan.off("mousemove",this.handlePointerMove),this.floorPlan.off("click",this.handlePointerDown),this.floorPlan.off("dblclick",this.handlePointerDown),this.floorPlan.off("update-settings",this.draw),super.destroy()}}class Vb extends ux{constructor({floorPlan:t,helperId:e,position:i}){super({floorPlan:t,helperId:e}),this.position=[0,0],this.floorPlan.on("mousemove",this.draw,this),this.isSnapping=!1,this.isEdge=!1,this.isError=!1,i&&(this.position=i)}draw(){if(this.floorPlan)if(this.layer||(this.layer=this.floorPlan.addLayer({id:"fpe-snap-cursor"})),this.cursor){let t=Ka;this.isError?t=al:this.isSnapping&&(t=nl);const e=this.isSnapping?2:1.5;this.cursor.set({position:this.position,style:{stroke:t,strokeWidth:e}})}else this.cursor=this.layer.addGraphic({shapes:[{type:"curve:circle",position:[0,0],radius:.06,style:{stroke:nl,strokeWidth:1.5}}],position:this.position,scaleOnZoom:!0})}set({position:t,isSnapping:e,isEdge:i,isError:r}){this.position=t,this.isSnapping=e,this.isEdge=i,this.isError=r,this.draw()}snapState(){return this.isSnapping?this.isEdge?"edge":"point":""}destroy(){this.floorPlan?.off("mousemove",this.draw),this.layer&&this.layer.destroy(),this.layer=void 0,this.cursor=null,super.destroy()}}function qb(t,e){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: node ID change, type ${t.type}, previous ID ${e}`),this.drawNodeUpdate(t.id))}function Jb(t,e){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: node property change, type ${t.type}, property name ${e}`),this.drawNodeUpdate(t.id))}function Kb(t){this.preventUpdateOnSpaceGraphEvent||dl.debug(`${t.id}: vertex create`)}function Zb(t){this.preventUpdateOnSpaceGraphEvent||dl.debug(`${t.id}: vertex delete`)}function Qb(t){if(!this.preventUpdateOnSpaceGraphEvent){dl.debug(`${t.id}: vertex set position`);for(let e of t.edges)this.drawNodeUpdate(e.id)}}function t_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: edge create`),this.drawNodeUpdate(t.id))}function e_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: edge delete`),this.drawNodeUpdate(t.id))}function i_(t,e){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: edge set vertices`),this.drawNodeUpdate(t.id))}function r_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: space create`),this.drawNodeUpdate(t.id))}function s_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: space delete`),this.drawNodeUpdate(t.id))}function n_(t,e){this.preventUpdateOnSpaceGraphEvent||dl.debug(`${t.id}: space split into ${e[0].id} and ${e[1].id}`)}function o_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: space attributes change`),this.drawNodeUpdate(t.id))}function a_(t){this.preventUpdateOnSpaceGraphEvent||"layout:space"!==t.type||(dl.debug(`${t.id}: custom attributes change`),this.drawNodeUpdate(t.id))}function l_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: element create, type ${t.type}`),this.drawNodeUpdate(t.id))}function h_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: element delete, type ${t.type}`),this.drawNodeUpdate(t.id))}function u_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: element transform change, type ${t.type}`),this.drawNodeUpdate(t.id))}function c_(t){if(!this.preventUpdateOnSpaceGraphEvent)if(dl.debug(`${t.id}: element parameters change, type ${t.type}`),"element:wall"===t.type){let e=t.getAdjacentElementsByVertex().flat();if(this.view.wallNodesToUpdate.push(t.id,...e.map(t=>t.id)),this.view.wallNodeUpdateInProgress)return;this.view.wallNodeUpdateInProgress=!0,setTimeout(()=>{const t=new Set(this.view.wallNodesToUpdate);Pa(this.layout);for(const e of t)this.drawNodeUpdate(e);this.view.wallNodeUpdateInProgress=!1,this.view.wallNodesToUpdate=[]})}else ks(t),this.drawNodeUpdate(t.id)}function d_(t){this.preventUpdateOnSpaceGraphEvent||queueMicrotask(()=>this.drawNodeUpdate(t.id))}function p_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: annotation change, type ${t.type}`),this.drawNodeUpdate(t.id))}function f_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: geometry profile update`),this.drawNodeUpdate(t.id))}function m_(t){this.preventUpdateOnSpaceGraphEvent||(dl.debug(`${t.id}: geometry update`),["element:boundaryWall","element:generic"].includes(t.type)&&this.drawNodeUpdate(t.id))}function g_(t){const e=t.addLayer({id:"fpe-grid-lines",baseLayer:"base"});let i;function r(t,e,r=!1){const s=ox;if(!t)return;let n;if(n=e.view.zoom>2?.1:e.view.zoom>.25?1:(e.view.zoom,10),!r&&n===i)return;if(zx(t),!e.settings.theme.background.showGrid)return;const o=new ay;let a=Dl(il);o.lineStyle({width:1,color:a,native:!0});for(let i=-100;i<100;i+=n)Math.round(100*i)/100==0?o.lineStyle({width:2,color:a,native:!0}):(Math.round(100*i)/100%10==0||Math.round(100*i),o.lineStyle({width:1,color:a,native:!0})),o.moveTo(-1e4,i*s),o.lineTo(1e4,i*s),o.moveTo(i*s,-1e4),o.lineTo(i*s,1e4);t.addChild(o),i=n}return r(e?.container,t),{update:i=>r(e.container,t,i)}}function y_(t,e="Floor plan engine couldn't load properly on this page. For technical details check the browser console."){const i=t.querySelector(".fpe-err")??function(t){const e=document.createElement("div"),i=document.createElement("div"),r=document.createElement("div"),s=document.createElement("div");return e.classList.add("fpe-err"),i.classList.add("fpe-err__box"),r.classList.add("fpe-err__title"),s.classList.add("fpe-err__msg"),t.append(e),e.append(i),i.append(r),i.append(s),r.textContent="Something went wrong",t.append(e),t}(t);i.querySelector(".fpe-err__msg").textContent=e}const v_={lastSceneClick:[0,0],cursor:[0,0],cursorTarget:null,isDragging:!1,altKey:!1,shiftKey:!1,metaKey:!1,ctrlKey:!1,dragOffset:null,cursorAction:"none",isPanning:!1,lastClick:{time:null,position:{x:0,y:0}},_dragStart:{x:0,y:0},preventFocusoutOnAltKeyup:!1};class x_ extends Ml{constructor({container:t,options:e={}}={}){let i;super({options:e}),this.interaction=v_,this.availableHelpers={cursorCoordinates:cx,scaleBar:dx},this.helper={},this.preventUpdateOnSpaceGraphEvent=!1,this.#t=ll.theme.fontFamily,i=t instanceof Element?t:document.body,this.mountFloorPlan(i),this.availableHelpers.polygonHelper=zb,this.availableHelpers.snapCursor=Vb,this.on("space-api-floor-error",(t,e)=>{y_(this.fpeNode,e)}),this.on("space-api-floor-loaded",()=>{!function(t){t.querySelector(".fpe-err")?.remove()}(this.fpeNode)})}#t;#e;prevent(t){t.preventDefault()}on(t,e,i){return this._emitter.on(t,e,i),this}once(t,e,i){return this._emitter.once(t,e,i),this}off(t,e,i){return this._emitter.off(t,e),this}emit(t,...e){return this._emitter.emit(t,...e),this}handleDrop(t){t.preventDefault(),t.stopPropagation();const e=[t.offsetX,t.offsetY],i=this.getPlanPosition(e);this.interaction.cursor=[...i];const{spaces:r}=this.getResourcesFromPosition(i),s=r[0]?.slabs.find(t=>"element:floor"===t.type),n=s?.parameters.elevation||0;this.emit("drop",{position:i,sourceEvent:t,verticalPos:n,screenPos:e})}set(t){super.set(t),this.view&&(Sb({floorPlan:this,update:!0}),Mb(this),g_(this))}drawNodePreview(t,e,i,r){lb(e?.elementsById[t]||e?.spacesById[t]||e?.spatialGraph.edgesById[t],this,{preview:!0,style:r,ctx:i.container})}drawNodeUpdate(t,e){if(!this.layout)return;let i=this.layout?.elementsById[t]||this.layout?.spacesById[t]||this.layout?.annotationsById[t]||this.layout?.spatialGraph.edgesById[t];if(i)if(this.view.gfxNodes[t]&&!this.view.gfxNodes[t].destroyed)Fb(i,this,{style:e});else{let t=this.view.gfxLayers.scene;"parent"in i&&this.view.gfxNodes[i.parent?.id]&&(t=this.view.gfxNodes[i.parent.id]),lb(i,this,{ctx:t,style:e})}else!function(t,e){const i=e.view.gfxNodes[t];i&&(i.parent.removeChild(i),i.destroy({children:!0})),delete e.view.gfxNodes[t],delete e.view.styleCache[t],hb(t,e.getLayer("fpe-room-stamp").container),e.view.viewportNeedsUpdate=!0,e.view.viewportPaused&&e.view.startAnimationLoop()}(t,this);if(i&&"getEdges"in i)for(const r of i.getEdges())this.drawNodeUpdate(r.id,e)}drawResourceUpdate({resourceId:t}){let e=this.loader.resources.nodes.get(t);for(let i of e)Fb(i,this,{})}mountFloorPlan(t){const e=t.querySelector(".fpe");e&&e.remove();const i=document.createElement("div");i.id=this.fpeId,i.classList.add("fpe"),t.appendChild(i);const r=document.createElement("div");r.classList.add("fpe__plan");const s=document.createElement("canvas");s.setAttribute("alt","fpe-canvas"),s.classList.add("fpe__canvas"),i.appendChild(r),r.appendChild(s),this.fpeNode=i;try{i.style.setProperty("--fpe-font-family",this.settings.theme.fontFamily)}catch(n){console.warn("Failed to set font-family",n)}this.view=new kb(this.loader,this.settings,r),this.loader.on("resource-loaded",this.drawResourceUpdate,this),this.loader.on("spaces-loaded",this.initDrawing,this),s.addEventListener("drop",this.handleDrop.bind(this)),s.addEventListener("gesturestart",this.prevent),s.addEventListener("gesturechange",this.prevent),s.addEventListener("gestureend",this.prevent),s.addEventListener("dragover",this.prevent),this.settings.destroyOnDomRemove&&function(t,e,i){const r=new MutationObserver(()=>{(function t(i){return i.parentNode!==e&&(null===i.parentNode||t(i.parentNode))})(t)&&(r.disconnect(),i())});r.observe(e,{childList:!0,subtree:!0})}(i,t,()=>this.destroy()),this.#e=Pb(this),this.view.on("scene-rendered",({update:t})=>{t||this.zoomExtents(1,0)}),this.view.on("zoom",()=>{this.view.layers.forEach(t=>{t.graphics.forEach(t=>{t.scaleOnZoom&&!t.gfx.destroyed&&t.set()})}),Cb(this),g_(this)}),this.view&&g_(this),this.#i(this.settings.theme.fontFamily),this.on("update-settings",t=>{this.#i(t.theme.fontFamily)}),this.generateUi()}initDrawing(){!this.loader.initialLoading&&this.view.gfxLayers?.scene&&zx(this.view.gfxLayers.scene),Sb({floorPlan:this}),Mb(this),this.initDrawingEvents()}initDrawingEvents(){this.spaceGraph&&(this.spaceGraph.on("node-id-change",qb,this),this.spaceGraph.on("node-property-change",Jb,this),this.spaceGraph.on("node-custom-attributes-change",a_,this),this.spaceGraph.on("vertex-create",Kb,this),this.spaceGraph.on("vertex-delete",Zb,this),this.spaceGraph.on("vertex-set-position",Qb,this),this.spaceGraph.on("edge-create",t_,this),this.spaceGraph.on("edge-delete",e_,this),this.spaceGraph.on("edge-set-vertices",i_,this),this.spaceGraph.on("space-create",r_,this),this.spaceGraph.on("space-delete",s_,this),this.spaceGraph.on("space-split",n_,this),this.spaceGraph.on("space-attributes-change",o_,this),this.spaceGraph.on("element-create",l_,this),this.spaceGraph.on("element-delete",h_,this),this.spaceGraph.on("element-transform-change",u_,this),this.spaceGraph.on("element-parameters-change",c_,this),this.spaceGraph.on("element-edges-change",d_,this),this.spaceGraph.on("geometry-profile-update",f_,this),this.spaceGraph.on("geometry-update",m_,this),this.spaceGraph.on("annotation-transform-change",p_,this),this.spaceGraph.on("annotation-parameters-change",p_,this))}freeDrawingEvents(){this.spaceGraph&&(this.spaceGraph.off("node-id-change",qb),this.spaceGraph.off("node-property-change",Jb),this.spaceGraph.off("vertex-create",Kb),this.spaceGraph.off("vertex-delete",Zb),this.spaceGraph.off("vertex-set-position",Qb),this.spaceGraph.off("edge-create",t_),this.spaceGraph.off("edge-delete",e_),this.spaceGraph.off("edge-set-vertices",i_),this.spaceGraph.off("space-create",r_),this.spaceGraph.off("space-delete",s_),this.spaceGraph.off("space-split",n_),this.spaceGraph.off("space-attributes-change",o_),this.spaceGraph.off("element-create",l_),this.spaceGraph.off("element-delete",h_),this.spaceGraph.off("element-transform-change",u_),this.spaceGraph.off("element-parameters-change",c_),this.spaceGraph.off("geometry-profile-update",f_),this.spaceGraph.off("geometry-update",m_),this.spaceGraph.off("annotation-transform-change",p_),this.spaceGraph.off("annotation-parameters-change",p_))}generateUi(){this.settings.ui.coordinates?this.addHelper("cursorCoordinates",{parentEl:this.fpeNode}):this.helper.cursorCoordinates&&this.removeHelper("cursorCoordinates"),this.settings.ui.scale?this.addHelper("scaleBar",{parentEl:this.fpeNode}):this.helper.scaleBar&&this.removeHelper("scaleBar")}getZoomExtentsBoundingBox(t,e,i,r,s,n,o){return function({layoutBoundingBox:t,rectLeft:e,rectTop:i,rectRight:r,rectBottom:s,viewportWidth:n,viewportHeight:o}){if([e,i,r,s].some(t=>t>0)&&n&&o){const a=r-e,l=s-i,h=function(t,e,i){const{min:r,max:s}=t;let n=r[0],o=r[1],a=s[0],l=s[1],h=a-n,u=l-o;const c=e/i;if(h/u>c){const t=u;u=h/c;const e=(t-u)/2;o+=e,l-=e}else{const t=h;h=u*c;const e=(t-h)/2;n+=e,a-=e}return{min:[n,o],max:[a,l]}}(t,a,l);let{min:u,max:c}=h,d=u[0],p=u[1],f=c[0]-d,m=c[1]-p;return f*=n/a,m*=o/l,d-=e/n*f,p-=i/o*m,{min:[d,p],max:[d+f,p+m]}}return t}({layoutBoundingBox:t,rectLeft:e,rectTop:i,rectRight:r,rectBottom:s,viewportWidth:n,viewportHeight:o})}zoomExtents(t=1,e=!1,i=null){return function({margin:t=0,animate:e,floorPlan:i,boundingBox:r}){return i.view.gfxLayers.scene?pb(r?{bb:r,animate:e,view:i.view}:{bb:i.getBoundingBox(t),animate:e,view:i.view}):Promise.resolve(!1)}({margin:t,animate:e,floorPlan:this,boundingBox:i})}zoomToElement(t,e=1,i){let r;if("string"==typeof t){const e=t;r=this.layout.elementsById[e]||this.layout.spacesById[e]||this.layout.spatialGraph.edgesById[e]||null}else r=t;if(!r)return Promise.resolve(!0);const{min:[s,n,o],max:[a,l,h]}=r.getAxisAlignedBoundingBox();return pb({bb:{min:[s-e,o-e],max:[a+e,h+e]},animate:i,view:this.view})}setZoom(t,e=!0){return pb({bb:t,animate:e,view:this.view})}zoomByFactor(t,e=!0){if(!Number.isFinite(t)||t<=0)return Promise.reject("factor is not a positive number");let{min:i,max:r}=this.view.viewbox,s=i[0],n=i[1],o=r[0]-s,a=r[1]-n;s-=(o/t-o)/2,n-=(a/t-a)/2;const l=s+o,h=n+a;return this.setZoom({min:[s,n],max:[l,h]},e)}addInfoWindow(t={}){return new mx({...t,floorPlan:this})}addHtmlMarker(t={}){return new gx({...t,floorPlan:this})}addMarker({position:t=[0,0],color:e="#669cff",size:i=40}={}){return new jx({position:t,color:e,size:i,floorPlan:this})}getPlanPosition(t){if(!this.view._viewport||this.view._viewport.destroyed)throw Error("No viewport present");const e=this.view._viewport.toWorld(t[0],t[1]);return[e.x/ox,e.y/ox]}getScreenPosition(t){if(!this.view._viewport||this.view._viewport.destroyed)throw Error("No viewport present");const e=t.map(t=>t*ox),i=this.view._viewport.toScreen(e[0],e[1]);return[i.x,i.y]}addLayer({id:t,baseLayer:e}={}){if(!this.view?.layers)return;if(t||(t=O()),this.view.layers.has(t)){const e=this.view.layers.get(t);if(e?.container)return e}const i=new Ub(this,e,t);return this.view.layers.set(t,i),i}getLayer(t){return this.view.layers.get(t)}addPlanGraphic(){return new Ub(this)}addHelper(t,e={}){let i=e?.helperId;return i||(i="string"==typeof t?t:O()),this.helper[i]&&this.removeHelper(i),"string"==typeof t?this.availableHelpers[t]?this.helper[i]=new this.availableHelpers[t]({floorPlan:this,helperId:i,...e}):dl.warn(`No helper registered for: ${t}`):this.helper[i]=new t({floorPlan:this,helperId:i,...e}),this.helper[i]}removeHelper(t){this.helper[t]?.destroy?.(),delete this.helper[t]}async exportImage({format:t="png",fileName:e,quality:i=90,output:r="base64",maxWidth:s,download:n=!1}={}){let o={format:t,quality:i};n&&(o.format="png");const a=document.querySelector("#"+this.fpeId+" canvas"),l=await function(t,{format:e="png",quality:i=.95}){return new Promise(r=>{let s;s="jpg"===e?t.toDataURL("image/jpeg",i):t.toDataURL(),r(s)})}(a,o).catch(t=>t);if(!n)return l;Gb(l,{format:t,fileName:e,quality:i})}#i(t){if(t!==this.#t){this.#t=t;try{this.fpeNode.style.setProperty("--fpe-font-family",t)}catch(e){console.warn("Failed to set font-family",e)}}}destroy(){this.#e?.(),this.view.destroy(),this.loader.reset(),this.freeDrawingEvents(),delete this.layout,delete this.utils,this.fpeNode&&this.fpeNode.remove(),delete this.fpeNode}}export{x_ as FloorPlanEngine,cl as setApiUrls};