@thatopen/components 3.4.2 → 3.4.4

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.
@@ -1,4 +1,4 @@
1
- var t=Object.defineProperty,e=(e,i,n)=>(((e,i,n)=>{i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[i]=n})(e,"symbol"!=typeof i?i+"":i,n),n);import*as i from"@thatopen/fragments";import{DataMap as n,FragmentsModels as s,DataSet as r}from"@thatopen/fragments";import*as o from"three";import{Box3 as a,Matrix4 as l,BufferAttribute as c,Vector3 as h,Line3 as d,Plane as u,Vector2 as p,Triangle as f,BackSide as m,DoubleSide as g,REVISION as w,Ray as y,FrontSide as _,Mesh as b,LineSegments as v,LineLoop as x,Line as S,Points as T,Sphere as C,BatchedMesh as A,OrthographicCamera as E,WebGLRenderTarget as M,Scene as P,Color as z,ShaderMaterial as I,Vector4 as D,NoBlending as k,GLSL3 as B,MathUtils as O,BufferGeometry as V}from"three";import*as L from"three/webgpu";import{instancedArray as N,Fn as F,instanceIndex as R,mat4 as U,Loop as j,int as $,vec3 as W,vec4 as G,float as H,cross as q,If as Z,Continue as Y,max as X,min as K,normalize as Q,select as J,abs as tt,mix as et,uint as it,atomicAdd as nt}from"three/tsl";import*as st from"web-ifc";import rt from"camera-controls";import{TransformControls as ot}from"three/examples/jsm/controls/TransformControls.js";class at{constructor(){e(this,"enabled",!0),e(this,"trigger",t=>{if(!this.enabled)return;const e=this.handlers.slice(0);for(const i of e)i(t)}),e(this,"handlers",[])}add(t){this.handlers.push(t)}remove(t){this.handlers=this.handlers.filter(e=>e!==t)}reset(){this.handlers.length=0}}class lt{constructor(){e(this,"enabled",!0),e(this,"trigger",async t=>{if(!this.enabled)return;const e=this.handlers.slice(0);for(const i of e)await i(t)}),e(this,"handlers",[])}add(t){this.handlers.push(t)}remove(t){this.handlers=this.handlers.filter(e=>e!==t)}reset(){this.handlers.length=0}}class ct{constructor(t){e(this,"isDisposeable",()=>"dispose"in this&&"onDisposed"in this),e(this,"isResizeable",()=>"resize"in this&&"getSize"in this),e(this,"isUpdateable",()=>"onAfterUpdate"in this&&"onBeforeUpdate"in this&&"update"in this),e(this,"isHideable",()=>"visible"in this),e(this,"isConfigurable",()=>"setup"in this&&"config"in this&&"onSetup"in this),e(this,"isSerializable",()=>"import"in this&&"export"in this),this.components=t}}class ht extends ct{}class dt extends ct{constructor(t){super(t),e(this,"worlds",new n),e(this,"onWorldChanged",new at),e(this,"_currentWorld",null),this.onWorldChanged.add(({world:t,action:e})=>{"removed"===e&&this.worlds.delete(t.uuid)})}set currentWorld(t){this._currentWorld=t}get currentWorld(){return this._currentWorld}}class ut extends dt{constructor(){super(...arguments),e(this,"hasCameraControls",()=>"controls"in this)}}class pt extends dt{constructor(){super(...arguments),e(this,"onAfterUpdate",new at),e(this,"onBeforeUpdate",new at),e(this,"onDisposed",new at),e(this,"onResize",new at),e(this,"onClippingPlanesUpdated",new at),e(this,"clippingPlanes",[])}updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(t,e,i){e.isLocal=i;const n=this.clippingPlanes.indexOf(e);t&&-1===n?this.clippingPlanes.push(e):!t&&n>-1&&this.clippingPlanes.splice(n,1),this.three.clippingPlanes=this.clippingPlanes.filter(t=>!t.isLocal)}}const ft=class t extends ht{constructor(i){super(i),e(this,"_disposedComponents",new Set),e(this,"enabled",!0),i.add(t.uuid,this)}get(){return this._disposedComponents}destroy(t,e=!0,i=!0){t.removeFromParent();const n=t;n.dispose&&n.dispose(),this.disposeGeometryAndMaterials(t,e),i&&n.children&&n.children.length&&this.disposeChildren(n),t.children.length=0}disposeGeometry(t){t.boundsTree&&t.disposeBoundsTree&&t.disposeBoundsTree(),t.dispose()}disposeGeometryAndMaterials(e,i){const n=e;n.geometry&&this.disposeGeometry(n.geometry),i&&n.material&&t.disposeMaterial(n),n.material=[],n.geometry=null}disposeChildren(t){for(const e of t.children)this.destroy(e)}static disposeMaterial(t){if(t.material)if(Array.isArray(t.material))for(const e of t.material)e.dispose();else t.material.dispose()}};e(ft,"uuid","76e9cd8e-ad8f-4753-9ef6-cbc60f7247fe");let mt=ft;class gt extends dt{constructor(t){super(t),e(this,"onDisposed",new at),e(this,"directionalLights",new Map),e(this,"ambientLights",new Map)}dispose(){const t=this.components.get(mt);for(const e of this.three.children){const i=e;i.geometry&&t.destroy(i)}this.deleteAllLights(),this.three.children=[],this.onDisposed.trigger(),this.onDisposed.reset()}deleteAllLights(){for(const[,t]of this.directionalLights)t.removeFromParent(),t.target.removeFromParent(),t.dispose();this.directionalLights.clear();for(const[,t]of this.ambientLights)t.removeFromParent(),t.dispose();this.ambientLights.clear()}}class wt extends Set{constructor(t){super(t),e(this,"onItemAdded",new at),e(this,"onItemDeleted",new at),e(this,"onCleared",new at),e(this,"guard",()=>!0)}clear(){super.clear(),this.onCleared.trigger()}add(...t){for(const e of t){if(this.has(e))continue;this.guard(e)&&(super.add(e),this.onItemAdded||(this.onItemAdded=new at),this.onItemAdded.trigger(e))}return this}delete(t){const e=super.delete(t);return e&&this.onItemDeleted.trigger(),e}dispose(){this.clear(),this.onItemAdded.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}const yt=class t{static create(){const e=4294967295*Math.random()|0,i=4294967295*Math.random()|0,n=4294967295*Math.random()|0,s=4294967295*Math.random()|0;return`${t._lut[255&e]+t._lut[e>>8&255]+t._lut[e>>16&255]+t._lut[e>>24&255]}-${t._lut[255&i]}${t._lut[i>>8&255]}-${t._lut[i>>16&15|64]}${t._lut[i>>24&255]}-${t._lut[63&n|128]}${t._lut[n>>8&255]}-${t._lut[n>>16&255]}${t._lut[n>>24&255]}${t._lut[255&s]}${t._lut[s>>8&255]}${t._lut[s>>16&255]}${t._lut[s>>24&255]}`.toLowerCase()}static validate(e){if(!t._pattern.test(e))throw new Error(`${e} is not a valid UUID v4.\n\n- If you're the tool creator, you can take one from https://www.uuidgenerator.net/.\n\n- If you're using a platform tool, verify the uuid isn't misspelled or contact the tool creator.`)}};e(yt,"_pattern",/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/),e(yt,"_lut",["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"]);let _t=yt;const bt=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",vt=new RegExp("^"+("["+bt+"]["+(bt+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*")+"$");function xt(t,e){const i=[];let n=e.exec(t);for(;n;){const s=[];s.startIndex=e.lastIndex-n[0].length;const r=n.length;for(let t=0;t<r;t++)s.push(n[t]);i.push(s),n=e.exec(t)}return i}const St=function(t){const e=vt.exec(t);return!(null==e)};const Tt={allowBooleanAttributes:!1,unpairedTags:[]};function Ct(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function At(t,e){const i=e;for(;e<t.length;e++)if("?"==t[e]||" "==t[e]){const n=t.substr(i,e-i);if(e>5&&"xml"===n)return Bt("InvalidXml","XML declaration allowed only at the start of the document.",Lt(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function Et(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e<t.length;e++)if("-"===t[e]&&"-"===t[e+1]&&">"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let i=1;for(e+=8;e<t.length;e++)if("<"===t[e])i++;else if(">"===t[e]&&(i--,0===i))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e<t.length;e++)if("]"===t[e]&&"]"===t[e+1]&&">"===t[e+2]){e+=2;break}return e}const Mt='"',Pt="'";function zt(t,e){let i="",n="",s=!1;for(;e<t.length;e++){if(t[e]===Mt||t[e]===Pt)""===n?n=t[e]:n!==t[e]||(n="");else if(">"===t[e]&&""===n){s=!0;break}i+=t[e]}return""===n&&{value:i,index:e,tagClosed:s}}const It=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function Dt(t,e){const i=xt(t,It),n={};for(let t=0;t<i.length;t++){if(0===i[t][1].length)return Bt("InvalidAttr","Attribute '"+i[t][2]+"' has no space in starting.",Nt(i[t]));if(void 0!==i[t][3]&&void 0===i[t][4])return Bt("InvalidAttr","Attribute '"+i[t][2]+"' is without value.",Nt(i[t]));if(void 0===i[t][3]&&!e.allowBooleanAttributes)return Bt("InvalidAttr","boolean attribute '"+i[t][2]+"' is not allowed.",Nt(i[t]));const s=i[t][2];if(!Ot(s))return Bt("InvalidAttr","Attribute '"+s+"' is an invalid name.",Nt(i[t]));if(n.hasOwnProperty(s))return Bt("InvalidAttr","Attribute '"+s+"' is repeated.",Nt(i[t]));n[s]=1}return!0}function kt(t,e){if(";"===t[++e])return-1;if("#"===t[e])return function(t,e){let i=/\d/;for("x"===t[e]&&(e++,i=/[\da-fA-F]/);e<t.length;e++){if(";"===t[e])return e;if(!t[e].match(i))break}return-1}(t,++e);let i=0;for(;e<t.length;e++,i++)if(!(t[e].match(/\w/)&&i<20)){if(";"===t[e])break;return-1}return e}function Bt(t,e,i){return{err:{code:t,msg:e,line:i.line||i,col:i.col}}}function Ot(t){return St(t)}function Vt(t){return St(t)}function Lt(t,e){const i=t.substring(0,e).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function Nt(t){return t.startIndex+t[1].length}const Ft={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,i){return t},captureMetaData:!1};function Rt(t){return"boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:10,maxTotalExpansions:1e3,maxExpandedLength:1e5,allowedTags:null,tagFilter:null}:"object"==typeof t&&null!==t?{enabled:!1!==t.enabled,maxEntitySize:t.maxEntitySize??1e4,maxExpansionDepth:t.maxExpansionDepth??10,maxTotalExpansions:t.maxTotalExpansions??1e3,maxExpandedLength:t.maxExpandedLength??1e5,allowedTags:t.allowedTags??null,tagFilter:t.tagFilter??null}:Rt(!0)}const Ut=function(t){const e=Object.assign({},Ft,t);return e.processEntities=Rt(e.processEntities),e};let jt;jt="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class $t{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][jt]={startIndex:e})}static getMetaDataSymbol(){return jt}}class Wt{constructor(t){this.suppressValidationErr=!t,this.options=t}readDocType(t,e){const i={};if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let n=1,s=!1,r=!1,o="";for(;e<t.length;e++)if("<"!==t[e]||r)if(">"===t[e]){if(r?"-"===t[e-1]&&"-"===t[e-2]&&(r=!1,n--):n--,0===n)break}else"["===t[e]?s=!0:o+=t[e];else{if(s&&Ht(t,"!ENTITY",e)){let n,s;if(e+=7,[n,s,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===s.indexOf("&")){const t=n.replace(/[.\-+*:]/g,"\\.");i[n]={regx:RegExp(`&${t};`,"g"),val:s}}}else if(s&&Ht(t,"!ELEMENT",e)){e+=8;const{index:i}=this.readElementExp(t,e+1);e=i}else if(s&&Ht(t,"!ATTLIST",e))e+=8;else if(s&&Ht(t,"!NOTATION",e)){e+=9;const{index:i}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=i}else{if(!Ht(t,"!--",e))throw new Error("Invalid DOCTYPE");r=!0}n++,o=""}if(0!==n)throw new Error("Unclosed DOCTYPE")}return{entities:i,i:e}}readEntityExp(t,e){e=Gt(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)i+=t[e],e++;if(qt(i),e=Gt(t,e),!this.suppressValidationErr){if("SYSTEM"===t.substring(e,e+6).toUpperCase())throw new Error("External entities are not supported");if("%"===t[e])throw new Error("Parameter entities are not supported")}let n="";if([e,n]=this.readIdentifierVal(t,e,"entity"),!1!==this.options.enabled&&this.options.maxEntitySize&&n.length>this.options.maxEntitySize)throw new Error(`Entity "${i}" size (${n.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[i,n,--e]}readNotationExp(t,e){e=Gt(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e]);)i+=t[e],e++;!this.suppressValidationErr&&qt(i),e=Gt(t,e);const n=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==n&&"PUBLIC"!==n)throw new Error(`Expected SYSTEM or PUBLIC, found "${n}"`);e+=n.length,e=Gt(t,e);let s=null,r=null;if("PUBLIC"===n)[e,s]=this.readIdentifierVal(t,e,"publicIdentifier"),'"'!==t[e=Gt(t,e)]&&"'"!==t[e]||([e,r]=this.readIdentifierVal(t,e,"systemIdentifier"));else if("SYSTEM"===n&&([e,r]=this.readIdentifierVal(t,e,"systemIdentifier"),!this.suppressValidationErr&&!r))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:i,publicIdentifier:s,systemIdentifier:r,index:--e}}readIdentifierVal(t,e,i){let n="";const s=t[e];if('"'!==s&&"'"!==s)throw new Error(`Expected quoted string, found "${s}"`);for(e++;e<t.length&&t[e]!==s;)n+=t[e],e++;if(t[e]!==s)throw new Error(`Unterminated ${i} value`);return[++e,n]}readElementExp(t,e){e=Gt(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e]);)i+=t[e],e++;if(!this.suppressValidationErr&&!St(i))throw new Error(`Invalid element name: "${i}"`);let n="";if("E"===t[e=Gt(t,e)]&&Ht(t,"MPTY",e))e+=4;else if("A"===t[e]&&Ht(t,"NY",e))e+=2;else if("("===t[e]){for(e++;e<t.length&&")"!==t[e];)n+=t[e],e++;if(")"!==t[e])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[e]}"`);return{elementName:i,contentModel:n.trim(),index:e}}readAttlistExp(t,e){e=Gt(t,e);let i="";for(;e<t.length&&!/\s/.test(t[e]);)i+=t[e],e++;qt(i),e=Gt(t,e);let n="";for(;e<t.length&&!/\s/.test(t[e]);)n+=t[e],e++;if(!qt(n))throw new Error(`Invalid attribute name: "${n}"`);e=Gt(t,e);let s="";if("NOTATION"===t.substring(e,e+8).toUpperCase()){if(s="NOTATION","("!==t[e=Gt(t,e+=8)])throw new Error(`Expected '(', found "${t[e]}"`);e++;let i=[];for(;e<t.length&&")"!==t[e];){let n="";for(;e<t.length&&"|"!==t[e]&&")"!==t[e];)n+=t[e],e++;if(n=n.trim(),!qt(n))throw new Error(`Invalid notation name: "${n}"`);i.push(n),"|"===t[e]&&(e++,e=Gt(t,e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++,s+=" ("+i.join("|")+")"}else{for(;e<t.length&&!/\s/.test(t[e]);)s+=t[e],e++;const i=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!i.includes(s.toUpperCase()))throw new Error(`Invalid attribute type: "${s}"`)}e=Gt(t,e);let r="";return"#REQUIRED"===t.substring(e,e+8).toUpperCase()?(r="#REQUIRED",e+=8):"#IMPLIED"===t.substring(e,e+7).toUpperCase()?(r="#IMPLIED",e+=7):[e,r]=this.readIdentifierVal(t,e,"ATTLIST"),{elementName:i,attributeName:n,attributeType:s,defaultValue:r,index:e}}}const Gt=(t,e)=>{for(;e<t.length&&/\s/.test(t[e]);)e++;return e};function Ht(t,e,i){for(let n=0;n<e.length;n++)if(e[n]!==t[i+n+1])return!1;return!0}function qt(t){if(St(t))return t;throw new Error(`Invalid entity name ${t}`)}const Zt=/^[-+]?0x[a-fA-F0-9]+$/,Yt=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Xt={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function Kt(t,e={}){if(e=Object.assign({},Xt,e),!t||"string"!=typeof t)return t;let i=t.trim();if(void 0!==e.skipLike&&e.skipLike.test(i))return t;if("0"===t)return 0;if(e.hex&&Zt.test(i))return function(t,e){if(parseInt)return parseInt(t,e);if(Number.parseInt)return Number.parseInt(t,e);if(window&&window.parseInt)return window.parseInt(t,e);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(i,16);if(i.includes("e")||i.includes("E"))return function(t,e,i){if(!i.eNotation)return t;const n=e.match(Qt);if(n){let s=n[1]||"";const r=-1===n[3].indexOf("e")?"E":"e",o=n[2],a=s?t[o.length+1]===r:t[o.length]===r;return o.length>1&&a?t:1!==o.length||!n[3].startsWith(`.${r}`)&&n[3][0]!==r?i.leadingZeros&&!a?(e=(n[1]||"")+n[3],Number(e)):t:Number(e)}return t}(t,i,e);{const n=Yt.exec(i);if(n){const s=n[1]||"",r=n[2];let o=function(t){if(t&&-1!==t.indexOf("."))return"."===(t=t.replace(/0+$/,""))?t="0":"."===t[0]?t="0"+t:"."===t[t.length-1]&&(t=t.substring(0,t.length-1)),t;return t}(n[3]);const a=s?"."===t[r.length+1]:"."===t[r.length];if(!e.leadingZeros&&(r.length>1||1===r.length&&!a))return t;{const n=Number(i),a=String(n);if(0===n)return n;if(-1!==a.search(/[eE]/))return e.eNotation?n:t;if(-1!==i.indexOf("."))return"0"===a||a===o||a===`${s}${o}`?n:t;let l=r?o:i;return r?l===a||s+l===a?n:t:l===a||l===s+a?n:t}}return t}}const Qt=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function Jt(t){return"function"==typeof t?t:Array.isArray(t)?e=>{for(const i of t){if("string"==typeof i&&e===i)return!0;if(i instanceof RegExp&&i.test(e))return!0}}:()=>!1}class te{constructor(t){if(this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(t,e)=>me(e,10,"&#")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(t,e)=>me(e,16,"&#x")}},this.addExternalEntities=ee,this.parseXml=oe,this.parseTextData=ie,this.resolveNameSpace=ne,this.buildAttributesMap=re,this.isItStopNode=he,this.replaceEntitiesValue=le,this.readStopNodeData=pe,this.saveTextToParentTag=ce,this.addChild=ae,this.ignoreAttributesFn=Jt(this.options.ignoreAttributes),this.entityExpansionCount=0,this.currentExpandedLength=0,this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodesExact=new Set,this.stopNodesWildcard=new Set;for(let t=0;t<this.options.stopNodes.length;t++){const e=this.options.stopNodes[t];"string"==typeof e&&(e.startsWith("*.")?this.stopNodesWildcard.add(e.substring(2)):this.stopNodesExact.add(e))}}}}function ee(t){const e=Object.keys(t);for(let i=0;i<e.length;i++){const n=e[i],s=n.replace(/[.\-+*:]/g,"\\.");this.lastEntities[n]={regex:new RegExp("&"+s+";","g"),val:t[n]}}}function ie(t,e,i,n,s,r,o){if(void 0!==t&&(this.options.trimValues&&!n&&(t=t.trim()),t.length>0)){o||(t=this.replaceEntitiesValue(t,e,i));const n=this.options.tagValueProcessor(e,t,i,s,r);if(null==n)return t;if(typeof n!=typeof t||n!==t)return n;if(this.options.trimValues)return fe(t,this.options.parseTagValue,this.options.numberParseOptions);return t.trim()===t?fe(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function ne(t){if(this.options.removeNSPrefix){const e=t.split(":"),i="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=i+e[1])}return t}const se=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function re(t,e,i){if(!0!==this.options.ignoreAttributes&&"string"==typeof t){const n=xt(t,se),s=n.length,r={};for(let t=0;t<s;t++){const s=this.resolveNameSpace(n[t][1]);if(this.ignoreAttributesFn(s,e))continue;let o=n[t][4],a=this.options.attributeNamePrefix+s;if(s.length)if(this.options.transformAttributeName&&(a=this.options.transformAttributeName(a)),"__proto__"===a&&(a="#__proto__"),void 0!==o){this.options.trimValues&&(o=o.trim()),o=this.replaceEntitiesValue(o,i,e);const t=this.options.attributeValueProcessor(s,o,e);r[a]=null==t?o:typeof t!=typeof o||t!==o?t:fe(o,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(r[a]=!0)}if(!Object.keys(r).length)return;if(this.options.attributesGroupName){const t={};return t[this.options.attributesGroupName]=r,t}return r}}const oe=function(t){t=t.replace(/\r\n?/g,"\n");const e=new $t("!xml");let i=e,n="",s="";this.entityExpansionCount=0,this.currentExpandedLength=0;const r=new Wt(this.options.processEntities);for(let o=0;o<t.length;o++){if("<"===t[o])if("/"===t[o+1]){const e=de(t,">",o,"Closing Tag is not closed.");let r=t.substring(o+2,e).trim();if(this.options.removeNSPrefix){const t=r.indexOf(":");-1!==t&&(r=r.substr(t+1))}this.options.transformTagName&&(r=this.options.transformTagName(r)),i&&(n=this.saveTextToParentTag(n,i,s));const a=s.substring(s.lastIndexOf(".")+1);if(r&&-1!==this.options.unpairedTags.indexOf(r))throw new Error(`Unpaired tag can not be used as closing tag: </${r}>`);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=s.lastIndexOf(".",s.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=s.lastIndexOf("."),s=s.substring(0,l),i=this.tagsNodeStack.pop(),n="",o=e}else if("?"===t[o+1]){let e=ue(t,o,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,i,s),this.options.ignoreDeclaration&&"?xml"===e.tagName||this.options.ignorePiTags);else{const t=new $t(e.tagName);t.add(this.options.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,s,e.tagName)),this.addChild(i,t,s,o)}o=e.closeIndex+1}else if("!--"===t.substr(o+1,3)){const e=de(t,"--\x3e",o+4,"Comment is not closed.");if(this.options.commentPropName){const r=t.substring(o+4,e-2);n=this.saveTextToParentTag(n,i,s),i.add(this.options.commentPropName,[{[this.options.textNodeName]:r}])}o=e}else if("!D"===t.substr(o+1,2)){const e=r.readDocType(t,o);this.docTypeEntities=e.entities,o=e.i}else if("!["===t.substr(o+1,2)){const e=de(t,"]]>",o,"CDATA is not closed.")-2,r=t.substring(o+9,e);n=this.saveTextToParentTag(n,i,s);let a=this.parseTextData(r,i.tagname,s,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?i.add(this.options.cdataPropName,[{[this.options.textNodeName]:r}]):i.add(this.options.textNodeName,a),o=e+2}else{let r=ue(t,o,this.options.removeNSPrefix),a=r.tagName;const l=r.rawTagName;let c=r.tagExp,h=r.attrExpPresent,d=r.closeIndex;if(this.options.transformTagName){const t=this.options.transformTagName(a);c===a&&(c=t),a=t}i&&n&&"!xml"!==i.tagname&&(n=this.saveTextToParentTag(n,i,s,!1));const u=i;u&&-1!==this.options.unpairedTags.indexOf(u.tagname)&&(i=this.tagsNodeStack.pop(),s=s.substring(0,s.lastIndexOf("."))),a!==e.tagname&&(s+=s?"."+a:a);const p=o;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,s,a)){let e="";if(c.length>0&&c.lastIndexOf("/")===c.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),c=a):c=c.substr(0,c.length-1),o=r.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))o=r.closeIndex;else{const i=this.readStopNodeData(t,l,d+1);if(!i)throw new Error(`Unexpected end of ${l}`);o=i.i,e=i.tagContent}const n=new $t(a);a!==c&&h&&(n[":@"]=this.buildAttributesMap(c,s,a)),e&&(e=this.parseTextData(e,a,s,!0,h,!0,!0)),s=s.substr(0,s.lastIndexOf(".")),n.add(this.options.textNodeName,e),this.addChild(i,n,s,p)}else{if(c.length>0&&c.lastIndexOf("/")===c.length-1){if("/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),c=a):c=c.substr(0,c.length-1),this.options.transformTagName){const t=this.options.transformTagName(a);c===a&&(c=t),a=t}const t=new $t(a);a!==c&&h&&(t[":@"]=this.buildAttributesMap(c,s,a)),this.addChild(i,t,s,p),s=s.substr(0,s.lastIndexOf("."))}else{const t=new $t(a);this.tagsNodeStack.push(i),a!==c&&h&&(t[":@"]=this.buildAttributesMap(c,s,a)),this.addChild(i,t,s,p),i=t}n="",o=d}}else n+=t[o]}return e.child};function ae(t,e,i,n){this.options.captureMetaData||(n=void 0);const s=this.options.updateTag(e.tagname,i,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e,n)):t.addChild(e,n))}const le=function(t,e,i){if(-1===t.indexOf("&"))return t;const n=this.options.processEntities;if(!n.enabled)return t;if(n.allowedTags&&!n.allowedTags.includes(e))return t;if(n.tagFilter&&!n.tagFilter(e,i))return t;for(let e in this.docTypeEntities){const i=this.docTypeEntities[e],s=t.match(i.regx);if(s){if(this.entityExpansionCount+=s.length,n.maxTotalExpansions&&this.entityExpansionCount>n.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n.maxTotalExpansions}`);const e=t.length;if(t=t.replace(i.regx,i.val),n.maxExpandedLength&&(this.currentExpandedLength+=t.length-e,this.currentExpandedLength>n.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${n.maxExpandedLength}`)}}if(-1===t.indexOf("&"))return t;for(let e in this.lastEntities){const i=this.lastEntities[e];t=t.replace(i.regex,i.val)}if(-1===t.indexOf("&"))return t;if(this.options.htmlEntities)for(let e in this.htmlEntities){const i=this.htmlEntities[e];t=t.replace(i.regex,i.val)}return t=t.replace(this.ampEntity.regex,this.ampEntity.val)};function ce(t,e,i,n){return t&&(void 0===n&&(n=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,i,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,n))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function he(t,e,i,n){return!(!e||!e.has(n))||!(!t||!t.has(i))}function de(t,e,i,n){const s=t.indexOf(e,i);if(-1===s)throw new Error(n);return s+e.length-1}function ue(t,e,i,n=">"){const s=function(t,e,i=">"){let n,s="";for(let r=e;r<t.length;r++){let e=t[r];if(n)e===n&&(n="");else if('"'===e||"'"===e)n=e;else if(e===i[0]){if(!i[1])return{data:s,index:r};if(t[r+1]===i[1])return{data:s,index:r}}else"\t"===e&&(e=" ");s+=e}}(t,e+1,n);if(!s)return;let r=s.data;const o=s.index,a=r.search(/\s/);let l=r,c=!0;-1!==a&&(l=r.substring(0,a),r=r.substring(a+1).trimStart());const h=l;if(i){const t=l.indexOf(":");-1!==t&&(l=l.substr(t+1),c=l!==s.data.substr(t+1))}return{tagName:l,tagExp:r,closeIndex:o,attrExpPresent:c,rawTagName:h}}function pe(t,e,i){const n=i;let s=1;for(;i<t.length;i++)if("<"===t[i])if("/"===t[i+1]){const r=de(t,">",i,`${e} is not closed`);if(t.substring(i+2,r).trim()===e&&(s--,0===s))return{tagContent:t.substring(n,i),i:r};i=r}else if("?"===t[i+1]){i=de(t,"?>",i+1,"StopNode is not closed.")}else if("!--"===t.substr(i+1,3)){i=de(t,"--\x3e",i+3,"StopNode is not closed.")}else if("!["===t.substr(i+1,2)){i=de(t,"]]>",i,"StopNode is not closed.")-2}else{const n=ue(t,i,">");if(n){(n&&n.tagName)===e&&"/"!==n.tagExp[n.tagExp.length-1]&&s++,i=n.closeIndex}}}function fe(t,e,i){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&Kt(t,i)}return void 0!==t?t:""}function me(t,e,i){const n=Number.parseInt(t,e);return n>=0&&n<=1114111?String.fromCodePoint(n):i+t+";"}const ge=$t.getMetaDataSymbol();function we(t,e){return ye(t,e)}function ye(t,e,i){let n;const s={};for(let r=0;r<t.length;r++){const o=t[r],a=_e(o);let l="";if(l=void 0===i?a:i+"."+a,a===e.textNodeName)void 0===n?n=o[a]:n+=""+o[a];else{if(void 0===a)continue;if(o[a]){let t=ye(o[a],e,l);const i=ve(t,e);void 0!==o[ge]&&(t[ge]=o[ge]),o[":@"]?be(t,o[":@"],l,e):1!==Object.keys(t).length||void 0===t[e.textNodeName]||e.alwaysCreateTextNode?0===Object.keys(t).length&&(e.alwaysCreateTextNode?t[e.textNodeName]="":t=""):t=t[e.textNodeName],void 0!==s[a]&&s.hasOwnProperty(a)?(Array.isArray(s[a])||(s[a]=[s[a]]),s[a].push(t)):e.isArray(a,l,i)?s[a]=[t]:s[a]=t}}}return"string"==typeof n?n.length>0&&(s[e.textNodeName]=n):void 0!==n&&(s[e.textNodeName]=n),s}function _e(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const i=e[t];if(":@"!==i)return i}}function be(t,e,i,n){if(e){const s=Object.keys(e),r=s.length;for(let o=0;o<r;o++){const r=s[o];n.isArray(r,i+"."+r,!0,!0)?t[r]=[e[r]]:t[r]=e[r]}}}function ve(t,e){const{textNodeName:i}=e,n=Object.keys(t).length;return 0===n||!(1!==n||!t[i]&&"boolean"!=typeof t[i]&&0!==t[i])}class xe{constructor(t){this.externalEntities={},this.options=Ut(t)}parse(t,e){if("string"!=typeof t&&t.toString)t=t.toString();else if("string"!=typeof t)throw new Error("XML data is accepted in String or Bytes[] form.");if(e){!0===e&&(e={});const i=function(t,e){e=Object.assign({},Tt,e);const i=[];let n=!1,s=!1;"\ufeff"===t[0]&&(t=t.substr(1));for(let r=0;r<t.length;r++)if("<"===t[r]&&"?"===t[r+1]){if(r+=2,r=At(t,r),r.err)return r}else{if("<"!==t[r]){if(Ct(t[r]))continue;return Bt("InvalidChar","char '"+t[r]+"' is not expected.",Lt(t,r))}{let o=r;if(r++,"!"===t[r]){r=Et(t,r);continue}{let a=!1;"/"===t[r]&&(a=!0,r++);let l="";for(;r<t.length&&">"!==t[r]&&" "!==t[r]&&"\t"!==t[r]&&"\n"!==t[r]&&"\r"!==t[r];r++)l+=t[r];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),r--),!Vt(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",Bt("InvalidTag",e,Lt(t,r))}const c=zt(t,r);if(!1===c)return Bt("InvalidAttr","Attributes for '"+l+"' have open quote.",Lt(t,r));let h=c.value;if(r=c.index,"/"===h[h.length-1]){const i=r-h.length;h=h.substring(0,h.length-1);const s=Dt(h,e);if(!0!==s)return Bt(s.err.code,s.err.msg,Lt(t,i+s.err.line));n=!0}else if(a){if(!c.tagClosed)return Bt("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",Lt(t,r));if(h.trim().length>0)return Bt("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",Lt(t,o));if(0===i.length)return Bt("InvalidTag","Closing tag '"+l+"' has not been opened.",Lt(t,o));{const e=i.pop();if(l!==e.tagName){let i=Lt(t,e.tagStartPos);return Bt("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",Lt(t,o))}0==i.length&&(s=!0)}}else{const a=Dt(h,e);if(!0!==a)return Bt(a.err.code,a.err.msg,Lt(t,r-h.length+a.err.line));if(!0===s)return Bt("InvalidXml","Multiple possible root nodes found.",Lt(t,r));-1!==e.unpairedTags.indexOf(l)||i.push({tagName:l,tagStartPos:o}),n=!0}for(r++;r<t.length;r++)if("<"===t[r]){if("!"===t[r+1]){r++,r=Et(t,r);continue}if("?"!==t[r+1])break;if(r=At(t,++r),r.err)return r}else if("&"===t[r]){const e=kt(t,r);if(-1==e)return Bt("InvalidChar","char '&' is not expected.",Lt(t,r));r=e}else if(!0===s&&!Ct(t[r]))return Bt("InvalidXml","Extra text at the end",Lt(t,r));"<"===t[r]&&r--}}}return n?1==i.length?Bt("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",Lt(t,i[0].tagStartPos)):!(i.length>0)||Bt("InvalidXml","Invalid '"+JSON.stringify(i.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):Bt("InvalidXml","Start tag expected.",1)}(t,e);if(!0!==i)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const i=new te(this.options);i.addExternalEntities(this.externalEntities);const n=i.parseXml(t);return this.options.preserveOrder||void 0===n?n:we(n,this.options)}addEntity(t,e){if(-1!==e.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==t.indexOf("&")||-1!==t.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return $t.getMetaDataSymbol()}}function Se(t,e){let i="";return e.format&&e.indentBy.length>0&&(i="\n"),Te(t,e,"",i)}function Te(t,e,i,n){let s="",r=!1;for(let o=0;o<t.length;o++){const a=t[o],l=Ce(a);if(void 0===l)continue;let c="";if(c=0===i.length?l:`${i}.${l}`,l===e.textNodeName){let t=a[l];Ee(c,e)||(t=e.tagValueProcessor(l,t),t=Me(t,e)),r&&(s+=n),s+=t,r=!1;continue}if(l===e.cdataPropName){r&&(s+=n),s+=`<![CDATA[${a[l][0][e.textNodeName]}]]>`,r=!1;continue}if(l===e.commentPropName){s+=n+`\x3c!--${a[l][0][e.textNodeName]}--\x3e`,r=!0;continue}if("?"===l[0]){const t=Ae(a[":@"],e),i="?xml"===l?"":n;let o=a[l][0][e.textNodeName];o=0!==o.length?" "+o:"",s+=i+`<${l}${o}${t}?>`,r=!0;continue}let h=n;""!==h&&(h+=e.indentBy);const d=n+`<${l}${Ae(a[":@"],e)}`,u=Te(a[l],e,c,h);-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?s+=d+">":s+=d+"/>":u&&0!==u.length||!e.suppressEmptyNode?u&&u.endsWith(">")?s+=d+`>${u}${n}</${l}>`:(s+=d+">",u&&""!==n&&(u.includes("/>")||u.includes("</"))?s+=n+e.indentBy+u+n:s+=u,s+=`</${l}>`):s+=d+"/>",r=!0}return s}function Ce(t){const e=Object.keys(t);for(let i=0;i<e.length;i++){const n=e[i];if(t.hasOwnProperty(n)&&":@"!==n)return n}}function Ae(t,e){let i="";if(t&&!e.ignoreAttributes)for(let n in t){if(!t.hasOwnProperty(n))continue;let s=e.attributeValueProcessor(n,t[n]);s=Me(s,e),!0===s&&e.suppressBooleanAttributes?i+=` ${n.substr(e.attributeNamePrefix.length)}`:i+=` ${n.substr(e.attributeNamePrefix.length)}="${s}"`}return i}function Ee(t,e){let i=(t=t.substr(0,t.length-e.textNodeName.length-1)).substr(t.lastIndexOf(".")+1);for(let n in e.stopNodes)if(e.stopNodes[n]===t||e.stopNodes[n]==="*."+i)return!0;return!1}function Me(t,e){if(t&&t.length>0&&e.processEntities)for(let i=0;i<e.entities.length;i++){const n=e.entities[i];t=t.replace(n.regex,n.val)}return t}const Pe={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function ze(t){this.options=Object.assign({},Pe,t),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=Jt(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=ke),this.processTextOrObjNode=Ie,this.options.format?(this.indentate=De,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function Ie(t,e,i,n){const s=this.j2x(t,i+1,n.concat(e));return void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,s.attrStr,i):this.buildObjectNode(s.val,e,s.attrStr,i)}function De(t){return this.options.indentBy.repeat(t)}function ke(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}ze.prototype.build=function(t){return this.options.preserveOrder?Se(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0,[]).val)},ze.prototype.j2x=function(t,e,i){let n="",s="";const r=i.join(".");for(let o in t)if(Object.prototype.hasOwnProperty.call(t,o))if(void 0===t[o])this.isAttribute(o)&&(s+="");else if(null===t[o])this.isAttribute(o)||o===this.options.cdataPropName?s+="":"?"===o[0]?s+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if(t[o]instanceof Date)s+=this.buildTextValNode(t[o],o,"",e);else if("object"!=typeof t[o]){const i=this.isAttribute(o);if(i&&!this.ignoreAttributesFn(i,r))n+=this.buildAttrPairStr(i,""+t[o]);else if(!i)if(o===this.options.textNodeName){let e=this.options.tagValueProcessor(o,""+t[o]);s+=this.replaceEntitiesValue(e)}else s+=this.buildTextValNode(t[o],o,"",e)}else if(Array.isArray(t[o])){const n=t[o].length;let r="",a="";for(let l=0;l<n;l++){const n=t[o][l];if(void 0===n);else if(null===n)"?"===o[0]?s+=this.indentate(e)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+o+"/"+this.tagEndChar;else if("object"==typeof n)if(this.options.oneListGroup){const t=this.j2x(n,e+1,i.concat(o));r+=t.val,this.options.attributesGroupName&&n.hasOwnProperty(this.options.attributesGroupName)&&(a+=t.attrStr)}else r+=this.processTextOrObjNode(n,o,e,i);else if(this.options.oneListGroup){let t=this.options.tagValueProcessor(o,n);t=this.replaceEntitiesValue(t),r+=t}else r+=this.buildTextValNode(n,o,"",e)}this.options.oneListGroup&&(r=this.buildObjectNode(r,o,a,e)),s+=r}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){const e=Object.keys(t[o]),i=e.length;for(let s=0;s<i;s++)n+=this.buildAttrPairStr(e[s],""+t[o][e[s]])}else s+=this.processTextOrObjNode(t[o],o,e,i);return{attrStr:n,val:s}},ze.prototype.buildAttrPairStr=function(t,e){return e=this.options.attributeValueProcessor(t,""+e),e=this.replaceEntitiesValue(e),this.options.suppressBooleanAttributes&&"true"===e?" "+t:" "+t+'="'+e+'"'},ze.prototype.buildObjectNode=function(t,e,i,n){if(""===t)return"?"===e[0]?this.indentate(n)+"<"+e+i+"?"+this.tagEndChar:this.indentate(n)+"<"+e+i+this.closeTag(e)+this.tagEndChar;{let s="</"+e+this.tagEndChar,r="";return"?"===e[0]&&(r="?",s=""),!i&&""!==i||-1!==t.indexOf("<")?!1!==this.options.commentPropName&&e===this.options.commentPropName&&0===r.length?this.indentate(n)+`\x3c!--${t}--\x3e`+this.newLine:this.indentate(n)+"<"+e+i+r+this.tagEndChar+t+this.indentate(n)+s:this.indentate(n)+"<"+e+i+r+">"+t+s}},ze.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`></${t}`,e},ze.prototype.buildTextValNode=function(t,e,i,n){if(!1!==this.options.cdataPropName&&e===this.options.cdataPropName)return this.indentate(n)+`<![CDATA[${t}]]>`+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(n)+`\x3c!--${t}--\x3e`+this.newLine;if("?"===e[0])return this.indentate(n)+"<"+e+i+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(e,t);return s=this.replaceEntitiesValue(s),""===s?this.indentate(n)+"<"+e+i+this.closeTag(e)+this.tagEndChar:this.indentate(n)+"<"+e+i+">"+s+"</"+e+this.tagEndChar}},ze.prototype.replaceEntitiesValue=function(t){if(t&&t.length>0&&this.options.processEntities)for(let e=0;e<this.options.entities.length;e++){const i=this.options.entities[e];t=t.replace(i.regex,i.val)}return t};class Be{}e(Be,"parser",new xe({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0})),e(Be,"builder",new ze({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1}));class Oe extends ht{constructor(t,i){super(t),e(this,"onDisposed",new at),e(this,"onVertexFound",new at),e(this,"onVertexLost",new at),e(this,"onEnabled",new at),e(this,"components"),e(this,"workingPlane",null),e(this,"_pickedPoint",null),e(this,"_config"),e(this,"_enabled",!1),this.components=t,this.config={snapDistance:.25,showOnlyVertex:!1,...i},this.enabled=!1}set enabled(t){this._enabled=t,t||(this._pickedPoint=null),this.onEnabled.trigger(t)}get enabled(){return this._enabled}set config(t){this._config={...this._config,...t}}get config(){return this._config}dispose(){this.onVertexFound.reset(),this.onVertexLost.reset(),this.components=null,this.onDisposed.trigger(),this.onDisposed.reset()}async get(t){if(!this.enabled)return this._pickedPoint;const e=this.components.get(Co).get(t),i=await e.castRay();if(!i)return null!==this._pickedPoint&&(this.onVertexLost.trigger(),this._pickedPoint=null),this._pickedPoint;const n=i.point;return null!==this._pickedPoint&&this._pickedPoint.equals(n)||(this._pickedPoint=n.clone(),this.onVertexFound.trigger(this._pickedPoint)),this._pickedPoint}}class Ve{static join(t){const e={};for(const i of t)for(const t in i)if(e[t])for(const n of i[t])e[t].add(n);else e[t]=new Set(i[t]);return e}static intersect(t){if(0===t.length)return{};let e=Ve.clone(t[0]);for(let i=1;i<t.length;i++){const n=t[i],s={};for(const t in e)if(n[t]){const i=new Set;for(const s of e[t])n[t].has(s)&&i.add(s);i.size>0&&(s[t]=i)}e=s}return e}static clone(t){const e={};for(const i in t)e[i]=new Set(t[i]);return e}static remove(t,e,i=!1){i&&(t=Ve.clone(t));for(const i in e)if(t[i]){for(const n of e[i])t[i].delete(n);0===t[i].size&&delete t[i]}}static add(t,e,i=!1){i&&(t=Ve.clone(t));for(const i in e)if(t[i])for(const n of e[i])t[i].add(n);else t[i]=new Set(e[i])}static append(t,e,...i){let n=t[e];n||(n=new Set,t[e]=n);for(const t of i)n.add(t)}static isEqual(t,e){const i=Object.keys(t),n=Object.keys(e);if(i.length!==n.length)return!1;for(const n of i){if(!e[n])return!1;if(t[n].size!==e[n].size)return!1;for(const i of t[n])if(!e[n].has(i))return!1}return!0}static isEmpty(t){return 0===Object.values(t).reduce((t,e)=>t+e.size,0)}static toRaw(t){const e={};for(const i in t)e[i]=Array.from(t[i]);return e}static fromRaw(t){const e={};for(const i in t)e[i]=new Set(t[i]);return e}}class Le extends Map{constructor(t){super(t),e(this,"onItemSet",new at),e(this,"onItemUpdated",new at),e(this,"onItemDeleted",new at),e(this,"onCleared",new at),e(this,"guard",()=>!0)}clear(){super.clear(),this.onCleared.trigger()}set(t,e){const i=this.has(t);if(!(this.guard??(()=>!0))(t,e))return this;const n=super.set(t,e);return i?(this.onItemUpdated||(this.onItemUpdated=new at),this.onItemUpdated.trigger({key:t,value:e})):(this.onItemSet||(this.onItemSet=new at),this.onItemSet.trigger({key:t,value:e})),n}add(t){const e=_t.create();return this.set(e,t),e}delete(t){const e=super.delete(t);return e&&this.onItemDeleted.trigger(t),e}dispose(){this.clear(),this.onItemSet.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}class Ne{static isEntry(t){return new Set(["Boolean","Color","Text","Number","Select","Vector3","TextSet","None"]).has(t.type)}static copySchema(t,e={}){for(const i in t){const n=t[i];this.isEntry(n)?e[i]=this.copyEntry(n):(e[i]={},this.copySchema(n,e[i]))}return e}static copyEntry(t){if("Boolean"===t.type){const e=t;return{type:e.type,value:e.value}}if("Color"===t.type){const e=t;return{type:e.type,value:e.value.clone()}}if("Text"===t.type){const e=t;return{type:e.type,value:e.value}}if("Number"===t.type){const e=t;return{type:e.type,value:e.value,min:e.min,max:e.max,interpolable:e.interpolable}}if("Select"===t.type){const e=t;return{type:e.type,value:e.value,multiple:e.multiple,options:new Set(e.options)}}if("Vector3"===t.type){const e=t;return{type:e.type,value:e.value.clone()}}if("TextSet"===t.type){const e=t;return{type:e.type,value:new Set(e.value)}}if("None"===t.type){const e=t;return{type:e.type,value:e.value}}throw new Error("Invalid entry!")}}class Fe{constructor(){e(this,"list",new Set)}add(t){for(const e of t)this.list.add(e)}remove(t){for(const e of t)this.list.delete(e)}set(t){for(const e of this.list)e.enabled=t}reset(){for(const t of this.list)t.reset()}}class Re{constructor(t,i,n,s){e(this,"_component"),e(this,"name"),e(this,"uuid"),this._component=t,this.name=n,this.uuid=s??_t.create();i.get(je).list.set(this.uuid,this)}get controls(){return Ne.copySchema(this._config)}set(t){for(const e in t)if(e in this){this[e]=t[e].value}}export(t=this._config,e={}){for(const i in t){const n=t[i];if(Ne.isEntry(n))if("Color"===n.type){const{r:t,g:s,b:r}=n.value;e[i]={...n,value:{r:t,g:s,b:r}}}else if("Vector3"===n.type){const{x:t,y:s,z:r}=n.value;e[i]={...n,value:{x:t,y:s,z:r}}}else if("TextSet"===n.type){const t=Array.from(n.value);e[i]={...n,value:t}}else if("Select"===n.type){const t=Array.from(n.options);e[i]={...n,options:t}}else e[i]={...n};else e[i]={},this.export(n,e[i])}return e}import(t,e={},i=!0){for(const i in t){const n=t[i];if(Ne.isEntry(n))if("Color"===n.type){const{r:t,g:s,b:r}=n.value;e[i]={...n,value:new o.Color(t,s,r)}}else if("Vector3"===n.type){const{x:t,y:s,z:r}=n.value;e[i]={...n,value:new o.Vector3(t,s,r)}}else"TextSet"===n.type?e[i]={...n,value:new Set(n.value)}:"Select"===n.type?e[i]={...n,options:new Set(n.options)}:e[i]={...n};else e[i]={},this.import(n,e[i],!1)}i&&this.set(e)}}const Ue=class t extends ht{constructor(i){super(i),e(this,"list",new n),e(this,"enabled",!0),i.add(t.uuid,this)}};e(Ue,"uuid","b8c764e0-6b24-4e77-9a32-35fa728ee5b4");let je=Ue;class $e{constructor(t){e(this,"_event"),e(this,"_position",new o.Vector2),e(this,"onDisposed",new at),e(this,"updateMouseInfo",t=>{this._event=t}),this.dom=t,this.setupEvents(!0)}get position(){return this.updatePosition(!1),this._position.clone()}get rawPosition(){return this.updatePosition(!0),this._position.clone()}dispose(){this.setupEvents(!1),this.onDisposed.trigger(),this.onDisposed.reset()}updatePosition(t){if(this._event){const e=this.dom.getBoundingClientRect();this._position.x=this.getPositionX(e,this._event,t),this._position.y=this.getPositionY(e,this._event,t)}}getPositionY(t,e,i){const n=this.getDataObject(e);return i?n.clientY:-(n.clientY-t.top)/(t.bottom-t.top)*2+1}getPositionX(t,e,i){const n=this.getDataObject(e);return i?n.clientX:(n.clientX-t.left)/(t.right-t.left)*2-1}getDataObject(t){return t instanceof MouseEvent?t:t.touches[0]}setupEvents(t){t?(this.dom.addEventListener("pointermove",this.updateMouseInfo),this.dom.addEventListener("touchstart",this.updateMouseInfo)):(this.dom.removeEventListener("pointermove",this.updateMouseInfo),this.dom.removeEventListener("touchstart",this.updateMouseInfo))}}const We=1.25,Ge=32,He=Math.pow(2,-24),qe=Symbol("SKIP_GENERATION"),Ze={strategy:0,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[qe]:!1};function Ye(t,e,i){return i.min.x=e[t],i.min.y=e[t+1],i.min.z=e[t+2],i.max.x=e[t+3],i.max.y=e[t+4],i.max.z=e[t+5],i}function Xe(t){let e=-1,i=-1/0;for(let n=0;n<3;n++){const s=t[n+3]-t[n];s>i&&(i=s,e=n)}return e}function Ke(t,e){e.set(t)}function Qe(t,e,i){let n,s;for(let r=0;r<3;r++){const o=r+3;n=t[r],s=e[r],i[r]=n<s?n:s,n=t[o],s=e[o],i[o]=n>s?n:s}}function Je(t,e,i){for(let n=0;n<3;n++){const s=e[t+2*n],r=e[t+2*n+1],o=s-r,a=s+r;o<i[n]&&(i[n]=o),a>i[n+3]&&(i[n+3]=a)}}function ti(t){const e=t[3]-t[0],i=t[4]-t[1],n=t[5]-t[2];return 2*(e*i+i*n+n*e)}function ei(t,e){return 65535===e[t+15]}function ii(t,e){return e[t+6]}function ni(t,e){return e[t+14]}function si(t){return t+8}function ri(t,e){return t+8*e[t+6]}function oi(t,e){return e[t+7]}function ai(t){return t}function li(t,e,i,n,s){let r=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,h=-1/0,d=1/0,u=1/0,p=1/0,f=-1/0,m=-1/0,g=-1/0;const w=t.offset||0;for(let n=6*(e-w),s=6*(e+i-w);n<s;n+=6){const e=t[n+0],i=t[n+1],s=e-i,w=e+i;s<r&&(r=s),w>l&&(l=w),e<d&&(d=e),e>f&&(f=e);const y=t[n+2],_=t[n+3],b=y-_,v=y+_;b<o&&(o=b),v>c&&(c=v),y<u&&(u=y),y>m&&(m=y);const x=t[n+4],S=t[n+5],T=x-S,C=x+S;T<a&&(a=T),C>h&&(h=C),x<p&&(p=x),x>g&&(g=x)}n[0]=r,n[1]=o,n[2]=a,n[3]=l,n[4]=c,n[5]=h,s[0]=d,s[1]=u,s[2]=p,s[3]=f,s[4]=m,s[5]=g}const ci=32,hi=(t,e)=>t.candidate-e.candidate,di=new Array(ci).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),ui=new Float32Array(6);class pi{constructor(){this.boundingData=new Float32Array(6)}}let fi,mi,gi,wi;const yi=Math.pow(2,32);function _i(t){return"count"in t?1:1+_i(t.left)+_i(t.right)}function bi(t,e,i){return fi=new Float32Array(i),mi=new Uint32Array(i),gi=new Uint16Array(i),wi=new Uint8Array(i),vi(t,e)}function vi(t,e){const i=t/4,n=t/2,s="count"in e,r=e.boundingData;for(let t=0;t<6;t++)fi[i+t]=r[t];if(s)return e.buffer?(wi.set(new Uint8Array(e.buffer),t),t+e.buffer.byteLength):(mi[i+6]=e.offset,gi[n+14]=e.count,gi[n+15]=65535,t+Ge);{const{left:n,right:s,splitAxis:r}=e;let o=vi(t+Ge,n);const a=o/Ge-t/Ge;if(a>yi)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return mi[i+6]=a,mi[i+7]=r,vi(o,s)}}function xi(t,e,i,n,s,r){const{maxDepth:o,verbose:a,maxLeafSize:l,strategy:c,onProgress:h}=s,d=t.primitiveBuffer,u=t.primitiveBufferStride,p=new Float32Array(6);let f=!1;const m=new pi;return li(e,i,n,m.boundingData,p),function t(i,n,s,r=null,h=0){!f&&h>=o&&(f=!0,a&&console.warn(`BVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`));if(s<=l||h>=o)return g(n+s),i.offset=n,i.count=s,i;const m=function(t,e,i,n,s,r){let o=-1,a=0;if(0===r)o=Xe(e),-1!==o&&(a=(e[o]+e[o+3])/2);else if(1===r)o=Xe(t),-1!==o&&(a=function(t,e,i,n){let s=0;const r=t.offset;for(let o=e,a=e+i;o<a;o++)s+=t[6*(o-r)+2*n];return s/i}(i,n,s,o));else if(2===r){const r=ti(t);let l=We*s;const c=i.offset||0,h=6*(n-c),d=6*(n+s-c);for(let t=0;t<3;t++){const n=e[t],c=(e[t+3]-n)/ci;if(s<8){const e=[...di];e.length=s;let n=0;for(let s=h;s<d;s+=6,n++){const r=e[n];r.candidate=i[s+2*t],r.count=0;const{bounds:o,leftCacheBounds:a,rightCacheBounds:l}=r;for(let t=0;t<3;t++)l[t]=1/0,l[t+3]=-1/0,a[t]=1/0,a[t+3]=-1/0,o[t]=1/0,o[t+3]=-1/0;Je(s,i,o)}e.sort(hi);let c=s;for(let t=0;t<c;t++){const i=e[t];for(;t+1<c&&e[t+1].candidate===i.candidate;)e.splice(t+1,1),c--}for(let n=h;n<d;n+=6){const s=i[n+2*t];for(let t=0;t<c;t++){const r=e[t];s>=r.candidate?Je(n,i,r.rightCacheBounds):(Je(n,i,r.leftCacheBounds),r.count++)}}for(let i=0;i<c;i++){const n=e[i],c=n.count,h=s-n.count,d=n.leftCacheBounds,u=n.rightCacheBounds;let p=0;0!==c&&(p=ti(d)/r);let f=0;0!==h&&(f=ti(u)/r);const m=1+We*(p*c+f*h);m<l&&(o=t,l=m,a=n.candidate)}}else{for(let t=0;t<ci;t++){const e=di[t];e.count=0,e.candidate=n+c+t*c;const i=e.bounds;for(let t=0;t<3;t++)i[t]=1/0,i[t+3]=-1/0}for(let e=h;e<d;e+=6){let s=~~((i[e+2*t]-n)/c);s>=ci&&(s=31);const r=di[s];r.count++,Je(e,i,r.bounds)}const e=di[31];Ke(e.bounds,e.rightCacheBounds);for(let t=30;t>=0;t--){const e=di[t],i=di[t+1];Qe(e.bounds,i.rightCacheBounds,e.rightCacheBounds)}let u=0;for(let e=0;e<31;e++){const i=di[e],n=i.count,c=i.bounds,h=di[e+1].rightCacheBounds;0!==n&&(0===u?Ke(c,ui):Qe(c,ui,ui)),u+=n;let d=0,p=0;0!==u&&(d=ti(ui)/r);const f=s-u;0!==f&&(p=ti(h)/r);const m=1+We*(d*u+p*f);m<l&&(o=t,l=m,a=i.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}(i.boundingData,r,e,n,s,c);if(-1===m.axis)return g(n+s),i.offset=n,i.count=s,i;const w=function(t,e,i,n,s,r){let o=n,a=n+s-1;const l=r.pos,c=2*r.axis,h=i.offset||0;for(;;){for(;o<=a&&i[6*(o-h)+c]<l;)o++;for(;o<=a&&i[6*(a-h)+c]>=l;)a--;if(!(o<a))return o;for(let i=0;i<e;i++){let n=t[o*e+i];t[o*e+i]=t[a*e+i],t[a*e+i]=n}for(let t=0;t<6;t++){const e=o-h,n=a-h,s=i[6*e+t];i[6*e+t]=i[6*n+t],i[6*n+t]=s}o++,a--}}(d,u,e,n,s,m);if(w===n||w===n+s)g(n+s),i.offset=n,i.count=s;else{i.splitAxis=m.axis;const r=new pi,o=n,a=w-n;i.left=r,li(e,o,a,r.boundingData,p),t(r,o,a,p,h+1);const l=new pi,c=w,d=s-a;i.right=l,li(e,c,d,l.boundingData,p),t(l,c,d,p,h+1)}return i}(m,i,n,p),m;function g(t){h&&h((t-r.offset)/r.count)}}function Si(t,e){const i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=t.getRootRanges(e.range),s=n[0],r=n[n.length-1],o={offset:s.offset,count:r.offset+r.count-s.offset},a=new Float32Array(6*o.count);a.offset=o.offset,t.computePrimitiveBounds(o.offset,o.count,a),t._roots=n.map(n=>{const s=xi(t,a,n.offset,n.count,e,o),r=_i(s),l=new i(Ge*r);return bi(0,s,l),l})}class Ti{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return 0===t.length?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class Ci{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,0!==t.length&&this.setBuffer(t.pop())}}}const Ai=new Ci;let Ei,Mi;const Pi=[],zi=new Ti(()=>new a);function Ii(t,e,i,n,s,r){Ei=zi.getPrimitive(),Mi=zi.getPrimitive(),Pi.push(Ei,Mi),Ai.setBuffer(t._roots[e]);const o=Di(0,t.geometry,i,n,s,r);Ai.clearBuffer(),zi.releasePrimitive(Ei),zi.releasePrimitive(Mi),Pi.pop(),Pi.pop();const a=Pi.length;return a>0&&(Mi=Pi[a-1],Ei=Pi[a-2]),o}function Di(t,e,i,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=Ai;let h=2*t;if(ei(h,l)){const e=ii(t,c),i=ni(h,l);return Ye(t,a,Ei),n(e,i,!1,o,r+t/8,Ei)}{let h=function(t){const{uint16Array:e,uint32Array:i}=Ai;let n=2*t;for(;!ei(n,e);)n=2*(t=si(t));return ii(t,i)},d=function(t){const{uint16Array:e,uint32Array:i}=Ai;let n=2*t;for(;!ei(n,e);)n=2*(t=ri(t,i));return ii(t,i)+ni(n,e)};const u=si(t),p=ri(t,c);let f,m,g,w,y=u,_=p;if(s&&(g=Ei,w=Mi,Ye(y,a,g),Ye(_,a,w),f=s(g),m=s(w),m<f)){y=p,_=u;const t=f;f=m,m=t,g=w}g||(g=Ei,Ye(y,a,g));const b=i(g,ei(2*y,l),f,o+1,r+y/8);let v;if(2===b){const t=h(y);v=n(t,d(y)-t,!0,o+1,r+y/8,g)}else v=b&&Di(y,e,i,n,s,r,o+1);if(v)return!0;w=Mi,Ye(_,a,w);const x=i(w,ei(2*_,l),m,o+1,r+_/8);let S;if(2===x){const t=h(_);S=n(t,d(_)-t,!0,o+1,r+_/8,w)}else S=x&&Di(_,e,i,n,s,r,o+1);return!!S}}const ki=new Ai.constructor,Bi=new Ai.constructor,Oi=new Ti(()=>new a),Vi=new a,Li=new a,Ni=new a,Fi=new a;let Ri=!1;function Ui(t,e,i,n,s,r=0,o=0,a=0,l=0,c=null,h=!1){let d,u;h?(d=Bi,u=ki):(d=ki,u=Bi);const p=d.float32Array,f=d.uint32Array,m=d.uint16Array,g=u.float32Array,w=u.uint32Array,y=u.uint16Array,_=2*e,b=ei(2*t,m),v=ei(_,y);let x=!1;if(v&&b)x=h?s(ii(e,w),ni(2*e,y),ii(t,f),ni(2*t,m),l,o+e/8,a,r+t/8):s(ii(t,f),ni(2*t,m),ii(e,w),ni(2*e,y),a,r+t/8,l,o+e/8);else if(v){const c=Oi.getPrimitive();Ye(e,g,c),c.applyMatrix4(i);const d=si(t),u=ri(t,f);Ye(d,p,Vi),Ye(u,p,Li);const m=c.intersectsBox(Vi),w=c.intersectsBox(Li);x=m&&Ui(e,d,n,i,s,o,r,l,a+1,c,!h)||w&&Ui(e,u,n,i,s,o,r,l,a+1,c,!h),Oi.releasePrimitive(c)}else{const d=si(e),u=ri(e,w);Ye(d,g,Ni),Ye(u,g,Fi);const m=c.intersectsBox(Ni),y=c.intersectsBox(Fi);if(m&&y)x=Ui(t,d,i,n,s,r,o,a,l+1,c,h)||Ui(t,u,i,n,s,r,o,a,l+1,c,h);else if(m)if(b)x=Ui(t,d,i,n,s,r,o,a,l+1,c,h);else{const e=Oi.getPrimitive();e.copy(Ni).applyMatrix4(i);const c=si(t),u=ri(t,f);Ye(c,p,Vi),Ye(u,p,Li);const m=e.intersectsBox(Vi),g=e.intersectsBox(Li);x=m&&Ui(d,c,n,i,s,o,r,l,a+1,e,!h)||g&&Ui(d,u,n,i,s,o,r,l,a+1,e,!h),Oi.releasePrimitive(e)}else if(y)if(b)x=Ui(t,u,i,n,s,r,o,a,l+1,c,h);else{const e=Oi.getPrimitive();e.copy(Fi).applyMatrix4(i);const c=si(t),d=ri(t,f);Ye(c,p,Vi),Ye(d,p,Li);const m=e.intersectsBox(Vi),g=e.intersectsBox(Li);x=m&&Ui(u,c,n,i,s,o,r,l,a+1,e,!h)||g&&Ui(u,d,n,i,s,o,r,l,a+1,e,!h),Oi.releasePrimitive(e)}}return x}const ji=new a,$i=new Float32Array(6);class Wi{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){Si(this,t={...Ze,...t})}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,i,n){let s=1/0,r=1/0,o=1/0,a=-1/0,l=-1/0,c=-1/0;for(let i=t,n=t+e;i<n;i++){this.writePrimitiveBounds(i,$i,0);const[t,e,n,h,d,u]=$i;t<s&&(s=t),h>a&&(a=h),e<r&&(r=e),d>l&&(l=d),n<o&&(o=n),u>c&&(c=u)}return i[n+0]=s,i[n+1]=r,i[n+2]=o,i[n+3]=a,i[n+4]=l,i[n+5]=c,i}computePrimitiveBounds(t,e,i){const n=i.offset||0;for(let s=t,r=t+e;s<r;s++){this.writePrimitiveBounds(s,$i,0);const[t,e,r,o,a,l]=$i,c=(t+o)/2,h=(e+a)/2,d=(r+l)/2,u=(o-t)/2,p=(a-e)/2,f=(l-r)/2,m=6*(s-n);i[m+0]=c,i[m+1]=u+(Math.abs(c)+u)*He,i[m+2]=h,i[m+3]=p+(Math.abs(h)+p)*He,i[m+4]=d,i[m+5]=f+(Math.abs(d)+f)*He}return i}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let i=0,n=e.length;i<n;i++)e[i]+=t;else{const e=this._roots;for(let i=0;i<e.length;i++){const n=e[i],s=new Uint32Array(n),r=new Uint16Array(n),o=n.byteLength/Ge;for(let e=0;e<o;e++){const i=8*e;ei(2*i,r)&&(s[i+6]+=t)}}}}traverse(t,e=0){const i=this._roots[e],n=new Uint32Array(i),s=new Uint16Array(i);!function e(r,o=0){const a=2*r,l=ei(a,s);if(l){const e=n[r+6],c=s[a+14];t(o,l,new Float32Array(i,4*r,6),e,c)}else{const s=si(r),a=ri(r,n),c=oi(r,n);t(o,l,new Float32Array(i,4*r,6),c)||(e(s,o+1),e(a,o+1))}}(0)}refit(){const t=this._roots;for(let e=0,i=t.length;e<i;e++){const i=t[e],n=new Uint32Array(i),s=new Uint16Array(i),r=new Float32Array(i);for(let t=i.byteLength/Ge-1;t>=0;t--){const e=8*t,i=2*e;if(ei(i,s)){const t=ii(e,n),o=ni(i,s);this.writePrimitiveRangeBounds(t,o,$i,0),r.set($i,e)}else{const t=si(e),i=ri(e,n);for(let n=0;n<3;n++){const s=r[t+n],o=r[t+n+3],a=r[i+n],l=r[i+n+3];r[e+n]=s<a?s:a,r[e+n+3]=o>l?o:l}}}}}getBoundingBox(t){t.makeEmpty();return this._roots.forEach(e=>{Ye(0,new Float32Array(e),ji),t.union(ji)}),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:i,intersectsRange:n,intersectsPrimitive:s,scratchPrimitive:r,iterate:o}=t;if(n&&s){const t=n;n=(e,i,n,a,l)=>!!t(e,i,n,a,l)||o(e,i,this,s,n,a,r)}else n||(n=s?(t,e,i,n)=>o(t,e,this,s,i,n,r):(t,e,i)=>i);let a=!1,l=0;const c=this._roots;for(let t=0,s=c.length;t<s;t++){const s=c[t];if(a=Ii(this,t,i,n,e,l),a)break;l+=s.byteLength/Ge}return a}bvhcast(t,e,i){let{intersectsRanges:n}=i;return function(t,e,i,n){if(Ri)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Ri=!0;const s=t._roots,r=e._roots;let o,a=0,c=0;const h=(new l).copy(i).invert();for(let t=0,e=s.length;t<e;t++){ki.setBuffer(s[t]),c=0;const e=Oi.getPrimitive();Ye(ai(0),ki.float32Array,e),e.applyMatrix4(h);for(let t=0,s=r.length;t<s&&(Bi.setBuffer(r[t]),o=Ui(0,0,i,h,n,a,c,0,0,e),Bi.clearBuffer(),c+=r[t].byteLength/Ge,!o);t++);if(Oi.releasePrimitive(e),ki.clearBuffer(),a+=s[t].byteLength/Ge,o)break}return Ri=!1,o}(this,t,e,n)}}function Gi(t){return t.index?t.index.count:t.attributes.position.count}function Hi(t){return Gi(t)/3}function qi(t,e){if(!t.index){const i=t.attributes.position.count,n=function(t,e=ArrayBuffer){return t>65535?new Uint32Array(new e(4*t)):new Uint16Array(new e(2*t))}(i,e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer);t.setIndex(new c(n,1));for(let t=0;t<i;t++)n[t]=t}}function Zi(t,e,i){const n=function(t,e,i){const n=Gi(t)/i,s=e||t.drawRange,r=s.start/i,o=(s.start+s.count)/i,a=Math.max(0,r),l=Math.min(n,o)-a;return{offset:Math.floor(a),count:Math.floor(l)}}(t,e,i),s=function(t,e){return t.groups.map(t=>({offset:t.start/e,count:t.count/e}))}(t,i);if(!s.length)return[n];const r=[],o=n.offset,a=n.offset+n.count,l=Gi(t)/i,c=[];for(const t of s){const{offset:e,count:i}=t,n=e,s=e+(isFinite(i)?i:l-e);n<a&&s>o&&(c.push({pos:Math.max(o,n),isStart:!0}),c.push({pos:Math.min(a,s),isStart:!1}))}c.sort((t,e)=>t.pos!==e.pos?t.pos-e.pos:"end"===t.type?-1:1);let h=0,d=null;for(const t of c){const e=t.pos;0!==h&&e!==d&&r.push({offset:d,count:e-d}),h+=t.isStart?1:-1,d=e}return r}class Yi extends Wi{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(!t.isBufferGeometry)throw new Error("BVH: Only BufferGeometries are supported.");if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.");if(e.useSharedArrayBuffer&&"undefined"==typeof SharedArrayBuffer)throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?t=>this._indirectBuffer[t]:t=>t,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,(e={...Ze,...e})[qe]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const n=function(t,e){const i=t[t.length-1],n=i.offset+i.count>65536,s=t.reduce((t,e)=>t+e.count,0),r=n?4:2,o=e?new SharedArrayBuffer(s*r):new ArrayBuffer(s*r),a=n?new Uint32Array(o):new Uint16Array(o);let l=0;for(let e=0;e<t.length;e++){const{offset:i,count:n}=t[e];for(let t=0;t<n;t++)a[l+t]=i+t;l+=n}return a}(Zi(e,t.range,i),t.useSharedArrayBuffer);this._indirectBuffer=n}else qi(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new a))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:Zi(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Xi{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,n=-1/0;for(let s=0,r=t.length;s<r;s++){const r=t[s][e];i=r<i?r:i,n=r>n?r:n}this.min=i,this.max=n}setFromPoints(t,e){let i=1/0,n=-1/0;for(let s=0,r=e.length;s<r;s++){const r=e[s],o=t.dot(r);i=o<i?o:i,n=o>n?o:n}this.min=i,this.max=n}isSeparated(t){return this.min>t.max||t.min>this.max}}Xi.prototype.setFromBox=function(){const t=new h;return function(e,i){const n=i.min,s=i.max;let r=1/0,o=-1/0;for(let i=0;i<=1;i++)for(let a=0;a<=1;a++)for(let l=0;l<=1;l++){t.x=n.x*i+s.x*(1-i),t.y=n.y*a+s.y*(1-a),t.z=n.z*l+s.z*(1-l);const c=e.dot(t);r=Math.min(c,r),o=Math.max(c,o)}this.min=r,this.max=o}}();const Ki=function(){const t=new h,e=new h,i=new h;return function(n,s,r){const o=n.start,a=t,l=s.start,c=e;i.subVectors(o,l),t.subVectors(n.end,n.start),e.subVectors(s.end,s.start);const h=i.dot(c),d=c.dot(a),u=c.dot(c),p=i.dot(a),f=a.dot(a)*u-d*d;let m,g;m=0!==f?(h*d-p*u)/f:0,g=(h+m*d)/u,r.x=m,r.y=g}}(),Qi=function(){const t=new p,e=new h,i=new h;return function(n,s,r,o){Ki(n,s,t);let a=t.x,l=t.y;if(a>=0&&a<=1&&l>=0&&l<=1)return n.at(a,r),void s.at(l,o);if(a>=0&&a<=1)return l<0?s.at(0,o):s.at(1,o),void n.closestPointToPoint(o,!0,r);if(l>=0&&l<=1)return a<0?n.at(0,r):n.at(1,r),void s.closestPointToPoint(r,!0,o);{let t,c;t=a<0?n.start:n.end,c=l<0?s.start:s.end;const h=e,d=i;return n.closestPointToPoint(c,!0,e),s.closestPointToPoint(t,!0,i),h.distanceToSquared(c)<=d.distanceToSquared(t)?(r.copy(h),void o.copy(c)):(r.copy(t),void o.copy(d))}}}(),Ji=function(){const t=new h,e=new h,i=new u,n=new d;return function(s,r){const{radius:o,center:a}=s,{a:l,b:c,c:h}=r;n.start=l,n.end=c;if(n.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;n.start=l,n.end=h;if(n.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;n.start=c,n.end=h;if(n.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;const d=r.getPlane(i);if(Math.abs(d.distanceToPoint(a))<=o){const t=d.projectPoint(a,e);if(r.containsPoint(t))return!0}return!1}}(),tn=["x","y","z"],en=1e-15;function nn(t){return Math.abs(t)<en}class sn extends f{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new h),this.satBounds=new Array(4).fill().map(()=>new Xi),this.points=[this.a,this.b,this.c],this.plane=new u,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new d,this.needsUpdate=!0}intersectsSphere(t){return Ji(t,this)}update(){const t=this.a,e=this.b,i=this.c,n=this.points,s=this.satAxes,r=this.satBounds,o=s[0],a=r[0];this.getNormal(o),a.setFromPoints(o,n);const l=s[1],c=r[1];l.subVectors(t,e),c.setFromPoints(l,n);const h=s[2],d=r[2];h.subVectors(e,i),d.setFromPoints(h,n);const u=s[3],p=r[3];u.subVectors(i,t),p.setFromPoints(u,n);const f=l.length(),m=h.length(),g=u.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,f<en?m<en||g<en?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):m<en?g<en?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):g<en&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(o,t),this.needsUpdate=!1}}sn.prototype.closestPointToSegment=function(){const t=new h,e=new h,i=new d;return function(n,s=null,r=null){const{start:o,end:a}=n,l=this.points;let c,h=1/0;for(let o=0;o<3;o++){const a=(o+1)%3;i.start.copy(l[o]),i.end.copy(l[a]),Qi(i,n,t,e),c=t.distanceToSquared(e),c<h&&(h=c,s&&s.copy(t),r&&r.copy(e))}return this.closestPointToPoint(o,t),c=o.distanceToSquared(t),c<h&&(h=c,s&&s.copy(t),r&&r.copy(o)),this.closestPointToPoint(a,t),c=a.distanceToSquared(t),c<h&&(h=c,s&&s.copy(t),r&&r.copy(a)),Math.sqrt(h)}}(),sn.prototype.intersectsTriangle=function(){const t=new sn,e=new Xi,i=new Xi,n=new h,s=new h,r=new h,o=new h,a=new d,l=new d,c=new h,u=new p,f=new p;function m(t,s,r,a){const l=n;t.isDegenerateIntoPoint||t.isDegenerateIntoSegment?l.copy(s.plane.normal):l.copy(t.plane.normal);const c=t.satBounds,h=t.satAxes;for(let n=1;n<4;n++){const r=c[n],a=h[n];if(e.setFromPoints(a,s.points),r.isSeparated(e))return!1;if(o.copy(l).cross(a),e.setFromPoints(o,t.points),i.setFromPoints(o,s.points),e.isSeparated(i))return!1}const d=s.satBounds,u=s.satAxes;for(let n=1;n<4;n++){const r=d[n],a=u[n];if(e.setFromPoints(a,t.points),r.isSeparated(e))return!1;if(o.crossVectors(l,a),e.setFromPoints(o,t.points),i.setFromPoints(o,s.points),e.isSeparated(i))return!1}return r&&(a||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),r.start.set(0,0,0),r.end.set(0,0,0)),!0}function g(t,e,i,n,s,r,o,a,l,c,h){let d=o/(o-a);c.x=n+(s-n)*d,h.start.subVectors(e,t).multiplyScalar(d).add(t),d=o/(o-l),c.y=n+(r-n)*d,h.end.subVectors(i,t).multiplyScalar(d).add(t)}function w(t,e,i,n,s,r,o,a,l,c,h){if(s>0)g(t.c,t.a,t.b,n,e,i,l,o,a,c,h);else if(r>0)g(t.b,t.a,t.c,i,e,n,a,o,l,c,h);else if(a*l>0||0!=o)g(t.a,t.b,t.c,e,i,n,o,a,l,c,h);else if(0!=a)g(t.b,t.a,t.c,i,e,n,a,o,l,c,h);else{if(0==l)return!0;g(t.c,t.a,t.b,n,e,i,l,o,a,c,h)}return!1}function y(t,e,i,s){const r=e.degenerateSegment,o=t.plane.distanceToPoint(r.start),a=t.plane.distanceToPoint(r.end);return nn(o)?nn(a)?m(t,e,i,s):(i&&(i.start.copy(r.start),i.end.copy(r.start)),t.containsPoint(r.start)):nn(a)?(i&&(i.start.copy(r.end),i.end.copy(r.end)),t.containsPoint(r.end)):null!=t.plane.intersectLine(r,n)&&(i&&(i.start.copy(n),i.end.copy(n)),t.containsPoint(n))}function _(t,e,i){const n=e.a;return!(!nn(t.plane.distanceToPoint(n))||!t.containsPoint(n))&&(i&&(i.start.copy(n),i.end.copy(n)),!0)}function b(t,e,i){const s=t.degenerateSegment,r=e.a;return s.closestPointToPoint(r,!0,n),r.distanceToSquared(n)<1e-30&&(i&&(i.start.copy(r),i.end.copy(r)),!0)}return function(e,i=null,o=!1){this.needsUpdate&&this.update(),e.isExtendedTriangle?e.needsUpdate&&e.update():(t.copy(e),t.update(),e=t);const h=function(t,e,i,o){if(t.isDegenerateIntoSegment){if(e.isDegenerateIntoSegment){const o=t.degenerateSegment,a=e.degenerateSegment,l=s,c=r;o.delta(l),a.delta(c);const h=n.subVectors(a.start,o.start),d=l.x*c.y-l.y*c.x;if(nn(d))return!1;const u=(h.x*c.y-h.y*c.x)/d,p=-(l.x*h.y-l.y*h.x)/d;return!(u<0||u>1||p<0||p>1)&&(!!nn(o.start.z+l.z*u-(a.start.z+c.z*p))&&(i&&(i.start.copy(o.start).addScaledVector(l,u),i.end.copy(o.start).addScaledVector(l,u)),!0))}return e.isDegenerateIntoPoint?b(t,e,i):y(e,t,i,o)}return t.isDegenerateIntoPoint?e.isDegenerateIntoPoint?e.a.distanceToSquared(t.a)<1e-30&&(i&&(i.start.copy(t.a),i.end.copy(t.a)),!0):e.isDegenerateIntoSegment?b(e,t,i):_(e,t,i):e.isDegenerateIntoPoint?_(t,e,i):e.isDegenerateIntoSegment?y(t,e,i,o):void 0}(this,e,i,o);if(void 0!==h)return h;const d=this.plane,p=e.plane;let g=p.distanceToPoint(this.a),v=p.distanceToPoint(this.b),x=p.distanceToPoint(this.c);nn(g)&&(g=0),nn(v)&&(v=0),nn(x)&&(x=0);const S=g*v,T=g*x;if(S>0&&T>0)return!1;let C=d.distanceToPoint(e.a),A=d.distanceToPoint(e.b),E=d.distanceToPoint(e.c);nn(C)&&(C=0),nn(A)&&(A=0),nn(E)&&(E=0);const M=C*A,P=C*E;if(M>0&&P>0)return!1;s.copy(d.normal),r.copy(p.normal);const z=s.cross(r);let I=0,D=Math.abs(z.x);const k=Math.abs(z.y);k>D&&(D=k,I=1);Math.abs(z.z)>D&&(I=2);const B=tn[I],O=this.a[B],V=this.b[B],L=this.c[B],N=e.a[B],F=e.b[B],R=e.c[B];if(w(this,O,V,L,S,T,g,v,x,u,a))return m(this,e,i,o);if(w(e,N,F,R,M,P,C,A,E,f,l))return m(this,e,i,o);if(u.y<u.x){const t=u.y;u.y=u.x,u.x=t,c.copy(a.start),a.start.copy(a.end),a.end.copy(c)}if(f.y<f.x){const t=f.y;f.y=f.x,f.x=t,c.copy(l.start),l.start.copy(l.end),l.end.copy(c)}return!(u.y<f.x||f.y<u.x)&&(i&&(f.x>u.x?i.start.copy(l.start):i.start.copy(a.start),f.y<u.y?i.end.copy(l.end):i.end.copy(a.end)),!0)}}(),sn.prototype.distanceToPoint=function(){const t=new h;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),sn.prototype.distanceToTriangle=function(){const t=new h,e=new h,i=["a","b","c"],n=new d,s=new d;return function(r,o=null,a=null){const l=o||a?n:null;if(this.intersectsTriangle(r,l))return(o||a)&&(o&&l.getCenter(o),a&&l.getCenter(a)),0;let c=1/0;for(let e=0;e<3;e++){let n;const s=i[e],l=r[s];this.closestPointToPoint(l,t),n=l.distanceToSquared(t),n<c&&(c=n,o&&o.copy(t),a&&a.copy(l));const h=this[s];r.closestPointToPoint(h,t),n=h.distanceToSquared(t),n<c&&(c=n,o&&o.copy(h),a&&a.copy(t))}for(let l=0;l<3;l++){const h=i[l],d=i[(l+1)%3];n.set(this[h],this[d]);for(let l=0;l<3;l++){const h=i[l],d=i[(l+1)%3];s.set(r[h],r[d]),Qi(n,s,t,e);const u=t.distanceToSquared(e);u<c&&(c=u,o&&o.copy(t),a&&a.copy(e))}}return Math.sqrt(c)}}();class rn{constructor(t,e,i){this.isOrientedBox=!0,this.min=new h,this.max=new h,this.matrix=new l,this.invMatrix=new l,this.points=new Array(8).fill().map(()=>new h),this.satAxes=new Array(3).fill().map(()=>new h),this.satBounds=new Array(3).fill().map(()=>new Xi),this.alignedSatBounds=new Array(3).fill().map(()=>new Xi),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}rn.prototype.update=function(){return function(){const t=this.matrix,e=this.min,i=this.max,n=this.points;for(let s=0;s<=1;s++)for(let r=0;r<=1;r++)for(let o=0;o<=1;o++){const a=n[1*s|2*r|4*o];a.x=s?i.x:e.x,a.y=r?i.y:e.y,a.z=o?i.z:e.z,a.applyMatrix4(t)}const s=this.satBounds,r=this.satAxes,o=n[0];for(let t=0;t<3;t++){const e=r[t],i=s[t],a=n[1<<t];e.subVectors(o,a),i.setFromPoints(e,n)}const a=this.alignedSatBounds;a[0].setFromPointsField(n,"x"),a[1].setFromPointsField(n,"y"),a[2].setFromPointsField(n,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}(),rn.prototype.intersectsBox=function(){const t=new Xi;return function(e){this.needsUpdate&&this.update();const i=e.min,n=e.max,s=this.satBounds,r=this.satAxes,o=this.alignedSatBounds;if(t.min=i.x,t.max=n.x,o[0].isSeparated(t))return!1;if(t.min=i.y,t.max=n.y,o[1].isSeparated(t))return!1;if(t.min=i.z,t.max=n.z,o[2].isSeparated(t))return!1;for(let i=0;i<3;i++){const n=r[i],o=s[i];if(t.setFromBox(n,e),o.isSeparated(t))return!1}return!0}}(),rn.prototype.intersectsTriangle=function(){const t=new sn,e=new Array(3),i=new Xi,n=new Xi,s=new h;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(t.copy(r),t.update(),r=t);const o=this.satBounds,a=this.satAxes;e[0]=r.a,e[1]=r.b,e[2]=r.c;for(let t=0;t<3;t++){const n=o[t],s=a[t];if(i.setFromPoints(s,e),n.isSeparated(i))return!1}const l=r.satBounds,c=r.satAxes,h=this.points;for(let t=0;t<3;t++){const e=l[t],n=c[t];if(i.setFromPoints(n,h),e.isSeparated(i))return!1}for(let t=0;t<3;t++){const r=a[t];for(let t=0;t<4;t++){const o=c[t];if(s.crossVectors(r,o),i.setFromPoints(s,e),n.setFromPoints(s,h),i.isSeparated(n))return!1}}return!0}}(),rn.prototype.closestPointToPoint=function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}}(),rn.prototype.distanceToPoint=function(){const t=new h;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),rn.prototype.distanceToBox=function(){const t=["x","y","z"],e=new Array(12).fill().map(()=>new d),i=new Array(12).fill().map(()=>new d),n=new h,s=new h;return function(r,o=0,a=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(a||l)&&(r.getCenter(s),this.closestPointToPoint(s,n),r.closestPointToPoint(n,s),a&&a.copy(n),l&&l.copy(s)),0;const c=o*o,h=r.min,d=r.max,u=this.points;let p=1/0;for(let t=0;t<8;t++){const e=u[t];s.copy(e).clamp(h,d);const i=e.distanceToSquared(s);if(i<p&&(p=i,a&&a.copy(e),l&&l.copy(s),i<c))return Math.sqrt(i)}let f=0;for(let n=0;n<3;n++)for(let s=0;s<=1;s++)for(let r=0;r<=1;r++){const o=(n+1)%3,a=(n+2)%3,l=1<<n|s<<o|r<<a,c=u[s<<o|r<<a],p=u[l];e[f].set(c,p);const m=t[n],g=t[o],w=t[a],y=i[f],_=y.start,b=y.end;_[m]=h[m],_[g]=s?h[g]:d[g],_[w]=r?h[w]:d[g],b[m]=d[m],b[g]=s?h[g]:d[g],b[w]=r?h[w]:d[g],f++}for(let t=0;t<=1;t++)for(let e=0;e<=1;e++)for(let i=0;i<=1;i++){s.x=t?d.x:h.x,s.y=e?d.y:h.y,s.z=i?d.z:h.z,this.closestPointToPoint(s,n);const r=s.distanceToSquared(n);if(r<p&&(p=r,a&&a.copy(n),l&&l.copy(s),r<c))return Math.sqrt(r)}for(let t=0;t<12;t++){const r=e[t];for(let t=0;t<12;t++){const e=i[t];Qi(r,e,n,s);const o=n.distanceToSquared(s);if(o<p&&(p=o,a&&a.copy(n),l&&l.copy(s),o<c))return Math.sqrt(o)}}return Math.sqrt(p)}}();class on extends Ti{constructor(){super(()=>new sn)}}const an=new on,ln=new h,cn=new h;const hn=parseInt(w)>=169,dn=parseInt(w)<=161,un=new h,pn=new h,fn=new h,mn=new p,gn=new p,wn=new p,yn=new h,_n=new h,bn=new h,vn=new h;function xn(t,e,i,n,s,r,o,a,l,c,d){un.fromBufferAttribute(e,r),pn.fromBufferAttribute(e,o),fn.fromBufferAttribute(e,a);const u=function(t,e,i,n,s,r,o,a){let l;if(l=r===m?t.intersectTriangle(n,i,e,!0,s):t.intersectTriangle(e,i,n,r!==g,s),null===l)return null;const c=t.origin.distanceTo(s);return c<o||c>a?null:{distance:c,point:s.clone()}}(t,un,pn,fn,vn,l,c,d);if(u){if(n){mn.fromBufferAttribute(n,r),gn.fromBufferAttribute(n,o),wn.fromBufferAttribute(n,a),u.uv=new p;const t=f.getInterpolation(vn,un,pn,fn,mn,gn,wn,u.uv);hn||(u.uv=t)}if(s){mn.fromBufferAttribute(s,r),gn.fromBufferAttribute(s,o),wn.fromBufferAttribute(s,a),u.uv1=new p;const t=f.getInterpolation(vn,un,pn,fn,mn,gn,wn,u.uv1);hn||(u.uv1=t),dn&&(u.uv2=u.uv1)}if(i){yn.fromBufferAttribute(i,r),_n.fromBufferAttribute(i,o),bn.fromBufferAttribute(i,a),u.normal=new h;const e=f.getInterpolation(vn,un,pn,fn,yn,_n,bn,u.normal);u.normal.dot(t.direction)>0&&u.normal.multiplyScalar(-1),hn||(u.normal=e)}const e={a:r,b:o,c:a,normal:new h,materialIndex:0};if(f.getNormal(un,pn,fn,e.normal),u.face=e,u.faceIndex=r,hn){const t=new h;f.getBarycoord(vn,un,pn,fn,t),u.barycoord=t}}return u}function Sn(t){return t&&t.isMaterial?t.side:t}function Tn(t,e,i,n,s,r,o){const a=3*n;let l=a+0,c=a+1,h=a+2;const{index:d,groups:u}=t;t.index&&(l=d.getX(l),c=d.getX(c),h=d.getX(h));const{position:p,normal:f,uv:m,uv1:g}=t.attributes;if(Array.isArray(e)){const t=3*n;for(let a=0,d=u.length;a<d;a++){const{start:d,count:w,materialIndex:y}=u[a];if(t>=d&&t<d+w){const t=xn(i,p,f,m,g,l,c,h,Sn(e[y]),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=y,!s)return t;s.push(t)}}}}else{const t=xn(i,p,f,m,g,l,c,h,Sn(e),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=0,!s)return t;s.push(t)}}return null}function Cn(t,e,i,n){const s=t.a,r=t.b,o=t.c;let a=e,l=e+1,c=e+2;i&&(a=i.getX(a),l=i.getX(l),c=i.getX(c)),s.x=n.getX(a),s.y=n.getY(a),s.z=n.getZ(a),r.x=n.getX(l),r.y=n.getY(l),r.z=n.getZ(l),o.x=n.getX(c),o.y=n.getY(c),o.z=n.getZ(c)}function An(t,e,i,n,s,r,o){const{geometry:a}=i,{index:l}=a,c=a.attributes.position;for(let i=t,a=e+t;i<a;i++){let t;if(t=i,Cn(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}function En(t,e=null){e&&Array.isArray(e)&&(e=new Set(e));const i=t.geometry,n=i.index?i.index.array:null,s=i.attributes.position;let r,o,a,l,c=0;const h=t._roots;for(let t=0,e=h.length;t<e;t++)r=h[t],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),d(0,c),c+=r.byteLength;function d(t,i,r=!1){const c=2*t;if(ei(c,a)){const e=ii(t,o);let i=1/0,r=1/0,h=1/0,d=-1/0,u=-1/0,p=-1/0;for(let t=3*e,o=3*(e+ni(c,a));t<o;t++){let e=n[t];const o=s.getX(e),a=s.getY(e),l=s.getZ(e);o<i&&(i=o),o>d&&(d=o),a<r&&(r=a),a>u&&(u=a),l<h&&(h=l),l>p&&(p=l)}return(l[t+0]!==i||l[t+1]!==r||l[t+2]!==h||l[t+3]!==d||l[t+4]!==u||l[t+5]!==p)&&(l[t+0]=i,l[t+1]=r,l[t+2]=h,l[t+3]=d,l[t+4]=u,l[t+5]=p,!0)}{const n=si(t),s=ri(t,o);let a=r,c=!1,h=!1;if(e){if(!a){const t=n/8+i/Ge,r=s/8+i/Ge;c=e.has(t),h=e.has(r),a=!c&&!h}}else c=!0,h=!0;const u=a||h;let p=!1;(a||c)&&(p=d(n,i,a));let f=!1;u&&(f=d(s,i,a));const m=p||f;if(m)for(let e=0;e<3;e++){const i=n+e,r=s+e,o=l[i],a=l[i+3],c=l[r],h=l[r+3];l[t+e]=o<c?o:c,l[t+e+3]=a>h?a:h}return m}}}function Mn(t,e,i,n,s){let r,o,a,l,c,h;const d=1/i.direction.x,u=1/i.direction.y,p=1/i.direction.z,f=i.origin.x,m=i.origin.y,g=i.origin.z;let w=e[t],y=e[t+3],_=e[t+1],b=e[t+3+1],v=e[t+2],x=e[t+3+2];return d>=0?(r=(w-f)*d,o=(y-f)*d):(r=(y-f)*d,o=(w-f)*d),u>=0?(a=(_-m)*u,l=(b-m)*u):(a=(b-m)*u,l=(_-m)*u),!(r>l||a>o)&&((a>r||isNaN(r))&&(r=a),(l<o||isNaN(o))&&(o=l),p>=0?(c=(v-g)*p,h=(x-g)*p):(c=(x-g)*p,h=(v-g)*p),!(r>h||c>o)&&((c>r||r!=r)&&(r=c),(h<o||o!=o)&&(o=h),r<=s&&o>=n))}function Pn(t,e,i,n,s,r,o){const{geometry:a}=i,{index:l}=a,c=a.attributes.position;for(let a=t,h=e+t;a<h;a++){let t;if(t=i.resolveTriangleIndex(a),Cn(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}function zn(t,e,i,n,s,r,o){Ai.setBuffer(t._roots[e]),In(0,t,i,n,s,r,o),Ai.clearBuffer()}function In(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Ai,h=2*t;if(ei(h,l)){!function(t,e,i,n,s,r,o,a){const{geometry:l,_indirectBuffer:c}=t;for(let t=n,c=n+s;t<c;t++)Tn(l,e,i,t,r,o,a)}(e,i,n,ii(t,c),ni(h,l),s,r,o)}else{const l=si(t);Mn(l,a,n,r,o)&&In(l,e,i,n,s,r,o);const h=ri(t,c);Mn(h,a,n,r,o)&&In(h,e,i,n,s,r,o)}}const Dn=["x","y","z"];function kn(t,e,i,n,s,r){Ai.setBuffer(t._roots[e]);const o=Bn(0,t,i,n,s,r);return Ai.clearBuffer(),o}function Bn(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Ai;let c=2*t;if(ei(c,a)){return function(t,e,i,n,s,r,o){const{geometry:a,_indirectBuffer:l}=t;let c=1/0,h=null;for(let t=n,l=n+s;t<l;t++){let n;n=Tn(a,e,i,t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,ii(t,l),ni(c,a),s,r)}{const a=oi(t,l),c=Dn[a],h=n.direction[c]>=0;let d,u;h?(d=si(t),u=ri(t,l)):(d=ri(t,l),u=si(t));const p=Mn(d,o,n,s,r)?Bn(d,e,i,n,s,r):null;if(p){const t=p.point[c];if(h?t<=o[u+a]:t>=o[u+a+3])return p}const f=Mn(u,o,n,s,r)?Bn(u,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const On=new a,Vn=new sn,Ln=new sn,Nn=new l,Fn=new rn,Rn=new rn;function Un(t,e,i,n){Ai.setBuffer(t._roots[e]);const s=jn(0,t,i,n);return Ai.clearBuffer(),s}function jn(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Ai;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),Fn.set(i.boundingBox.min,i.boundingBox.max,n),s=Fn);if(!ei(l,o)){const o=si(t),l=ri(t,a);Ye(o,r,On);if(s.intersectsBox(On)&&jn(o,e,i,n,s))return!0;Ye(l,r,On);return!!(s.intersectsBox(On)&&jn(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,d=i.index,u=i.attributes.position,p=ii(t,a),f=ni(l,o);if(Nn.copy(n).invert(),i.boundsTree){Ye(t,r,Rn),Rn.matrix.copy(Nn),Rn.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>Rn.intersectsBox(t),intersectsTriangle:t=>{t.a.applyMatrix4(n),t.b.applyMatrix4(n),t.c.applyMatrix4(n),t.needsUpdate=!0;for(let e=3*p,i=3*(f+p);e<i;e+=3)if(Cn(Ln,e,c,h),Ln.needsUpdate=!0,t.intersectsTriangle(Ln))return!0;return!1}})}{const t=Hi(i);for(let e=3*p,i=3*(f+p);e<i;e+=3){Cn(Vn,e,c,h),Vn.a.applyMatrix4(Nn),Vn.b.applyMatrix4(Nn),Vn.c.applyMatrix4(Nn),Vn.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(Cn(Ln,e,d,u),Ln.needsUpdate=!0,Vn.intersectsTriangle(Ln))return!0}}}}const $n=new l,Wn=new rn,Gn=new rn,Hn=new h,qn=new h,Zn=new h,Yn=new h;function Xn(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Wn.set(e.boundingBox.min,e.boundingBox.max,i),Wn.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,u=an.getPrimitive(),p=an.getPrimitive();let f=Hn,m=qn,g=null,w=null;s&&(g=Zn,w=Yn);let y=1/0,_=null,b=null;return $n.copy(i).invert(),Gn.matrix.copy($n),t.shapecast({boundsTraverseOrder:t=>Wn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(Gn.min.copy(t.min),Gn.max.copy(t.max),Gn.needsUpdate=!0),!0),intersectsRange:(t,n)=>{if(e.boundsTree){return e.boundsTree.shapecast({boundsTraverseOrder:t=>Gn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,s)=>{for(let o=e,a=e+s;o<a;o++){Cn(p,3*o,d,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=t,i=t+n;e<i;e++){Cn(u,3*e,c,l),u.needsUpdate=!0;const t=u.distanceToTriangle(p,f,g);if(t<y&&(m.copy(f),w&&w.copy(g),y=t,_=e,b=o),t<r)return!0}}}})}for(let s=0,o=Hi(e);s<o;s++){Cn(p,3*s,d,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=t,i=t+n;e<i;e++){Cn(u,3*e,c,l),u.needsUpdate=!0;const t=u.distanceToTriangle(p,f,g);if(t<y&&(m.copy(f),w&&w.copy(g),y=t,_=e,b=s),t<r)return!0}}}}),an.releasePrimitive(u),an.releasePrimitive(p),y===1/0?null:(n.point?n.point.copy(m):n.point=m.clone(),n.distance=y,n.faceIndex=_,s&&(s.point?s.point.copy(w):s.point=w.clone(),s.point.applyMatrix4($n),m.applyMatrix4($n),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function Kn(t,e=null){e&&Array.isArray(e)&&(e=new Set(e));const i=t.geometry,n=i.index?i.index.array:null,s=i.attributes.position;let r,o,a,l,c=0;const h=t._roots;for(let t=0,e=h.length;t<e;t++)r=h[t],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),d(0,c),c+=r.byteLength;function d(i,r,c=!1){const h=2*i;if(ei(h,a)){const e=ii(i,o);let r=1/0,c=1/0,d=1/0,u=-1/0,p=-1/0,f=-1/0;for(let i=e,o=e+ni(h,a);i<o;i++){const e=3*t.resolveTriangleIndex(i);for(let t=0;t<3;t++){let i=e+t;i=n?n[i]:i;const o=s.getX(i),a=s.getY(i),l=s.getZ(i);o<r&&(r=o),o>u&&(u=o),a<c&&(c=a),a>p&&(p=a),l<d&&(d=l),l>f&&(f=l)}}return(l[i+0]!==r||l[i+1]!==c||l[i+2]!==d||l[i+3]!==u||l[i+4]!==p||l[i+5]!==f)&&(l[i+0]=r,l[i+1]=c,l[i+2]=d,l[i+3]=u,l[i+4]=p,l[i+5]=f,!0)}{const t=si(i),n=ri(i,o);let s=c,a=!1,h=!1;if(e){if(!s){const i=t/8+r/Ge,o=n/8+r/Ge;a=e.has(i),h=e.has(o),s=!a&&!h}}else a=!0,h=!0;const u=s||h;let p=!1;(s||a)&&(p=d(t,r,s));let f=!1;u&&(f=d(n,r,s));const m=p||f;if(m)for(let e=0;e<3;e++){const s=t+e,r=n+e,o=l[s],a=l[s+3],c=l[r],h=l[r+3];l[i+e]=o<c?o:c,l[i+e+3]=a>h?a:h}return m}}}function Qn(t,e,i,n,s,r,o){Ai.setBuffer(t._roots[e]),Jn(0,t,i,n,s,r,o),Ai.clearBuffer()}function Jn(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Ai,h=2*t;if(ei(h,l)){!function(t,e,i,n,s,r,o,a){const{geometry:l,_indirectBuffer:c}=t;for(let t=n,h=n+s;t<h;t++)Tn(l,e,i,c?c[t]:t,r,o,a)}(e,i,n,ii(t,c),ni(h,l),s,r,o)}else{const l=si(t);Mn(l,a,n,r,o)&&Jn(l,e,i,n,s,r,o);const h=ri(t,c);Mn(h,a,n,r,o)&&Jn(h,e,i,n,s,r,o)}}const ts=["x","y","z"];function es(t,e,i,n,s,r){Ai.setBuffer(t._roots[e]);const o=is(0,t,i,n,s,r);return Ai.clearBuffer(),o}function is(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Ai;let c=2*t;if(ei(c,a)){return function(t,e,i,n,s,r,o){const{geometry:a,_indirectBuffer:l}=t;let c=1/0,h=null;for(let t=n,d=n+s;t<d;t++){let n;n=Tn(a,e,i,l?l[t]:t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,ii(t,l),ni(c,a),s,r)}{const a=oi(t,l),c=ts[a],h=n.direction[c]>=0;let d,u;h?(d=si(t),u=ri(t,l)):(d=ri(t,l),u=si(t));const p=Mn(d,o,n,s,r)?is(d,e,i,n,s,r):null;if(p){const t=p.point[c];if(h?t<=o[u+a]:t>=o[u+a+3])return p}const f=Mn(u,o,n,s,r)?is(u,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const ns=new a,ss=new sn,rs=new sn,os=new l,as=new rn,ls=new rn;function cs(t,e,i,n){Ai.setBuffer(t._roots[e]);const s=hs(0,t,i,n);return Ai.clearBuffer(),s}function hs(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Ai;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),as.set(i.boundingBox.min,i.boundingBox.max,n),s=as);if(!ei(l,o)){const o=si(t),l=ri(t,a);Ye(o,r,ns);if(s.intersectsBox(ns)&&hs(o,e,i,n,s))return!0;Ye(l,r,ns);return!!(s.intersectsBox(ns)&&hs(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,d=i.index,u=i.attributes.position,p=ii(t,a),f=ni(l,o);if(os.copy(n).invert(),i.boundsTree){Ye(t,r,ls),ls.matrix.copy(os),ls.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>ls.intersectsBox(t),intersectsTriangle:t=>{t.a.applyMatrix4(n),t.b.applyMatrix4(n),t.c.applyMatrix4(n),t.needsUpdate=!0;for(let i=p,n=f+p;i<n;i++)if(Cn(rs,3*e.resolveTriangleIndex(i),c,h),rs.needsUpdate=!0,t.intersectsTriangle(rs))return!0;return!1}})}{const t=Hi(i);for(let i=p,n=f+p;i<n;i++){const n=e.resolveTriangleIndex(i);Cn(ss,3*n,c,h),ss.a.applyMatrix4(os),ss.b.applyMatrix4(os),ss.c.applyMatrix4(os),ss.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(Cn(rs,e,d,u),rs.needsUpdate=!0,ss.intersectsTriangle(rs))return!0}}}}const ds=new l,us=new rn,ps=new rn,fs=new h,ms=new h,gs=new h,ws=new h;function ys(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),us.set(e.boundingBox.min,e.boundingBox.max,i),us.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,d=e.index,u=an.getPrimitive(),p=an.getPrimitive();let f=fs,m=ms,g=null,w=null;s&&(g=gs,w=ws);let y=1/0,_=null,b=null;return ds.copy(i).invert(),ps.matrix.copy(ds),t.shapecast({boundsTraverseOrder:t=>us.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(ps.min.copy(t.min),ps.max.copy(t.max),ps.needsUpdate=!0),!0),intersectsRange:(n,s)=>{if(e.boundsTree){const a=e.boundsTree;return a.shapecast({boundsTraverseOrder:t=>ps.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,o)=>{for(let v=e,x=e+o;v<x;v++){const e=a.resolveTriangleIndex(v);Cn(p,3*e,d,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=n,i=n+s;e<i;e++){const i=t.resolveTriangleIndex(e);Cn(u,3*i,c,l),u.needsUpdate=!0;const n=u.distanceToTriangle(p,f,g);if(n<y&&(m.copy(f),w&&w.copy(g),y=n,_=e,b=v),n<r)return!0}}}})}for(let o=0,a=Hi(e);o<a;o++){Cn(p,3*o,d,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=n,i=n+s;e<i;e++){const i=t.resolveTriangleIndex(e);Cn(u,3*i,c,l),u.needsUpdate=!0;const n=u.distanceToTriangle(p,f,g);if(n<y&&(m.copy(f),w&&w.copy(g),y=n,_=e,b=o),n<r)return!0}}}}),an.releasePrimitive(u),an.releasePrimitive(p),y===1/0?null:(n.point?n.point.copy(m):n.point=m.clone(),n.distance=y,n.faceIndex=_,s&&(s.point?s.point.copy(w):s.point=w.clone(),s.point.applyMatrix4(ds),m.applyMatrix4(ds),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function _s(t,e,i){return null===t?null:(t.point.applyMatrix4(e.matrixWorld),t.distance=t.point.distanceTo(i.ray.origin),t.object=e,t)}const bs=new rn,vs=new y,xs=new h,Ss=new l,Ts=new h,Cs=["getX","getY","getZ"];class As extends Yi{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,n=t._roots,s=t._indirectBuffer,r=i.getIndex(),o={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(o.roots=n.map(t=>t.slice()),o.index=r?r.array.slice():null,o.indirectBuffer=s?s.slice():null):(o.roots=n,o.index=r?r.array:null,o.indirectBuffer=s),o}static deserialize(t,e,i={}){i={setIndex:!0,indirect:Boolean(t.indirectBuffer),...i};const{index:n,roots:s,indirectBuffer:r}=t;t.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),function(t){for(let e=0;e<t.length;e++){const i=t[e],n=new Uint32Array(i),s=new Uint16Array(i);for(let t=0,e=i.byteLength/Ge;t<e;t++){const e=8*t;ei(2*e,s)||(n[e+6]=n[e+6]/8-t)}}}(s));const o=new As(e,{...i,[qe]:!0});if(o._roots=s,o._indirectBuffer=r||null,i.setIndex){const i=e.getIndex();if(null===i){const i=new c(t.index,1,!1);e.setIndex(i)}else i.array!==n&&(i.array.set(n),i.needsUpdate=!0)}return o}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use maxLeafSize, instead.'),e={...e,maxLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,o=n.index?n.index.array:null,a=3*(s?s[t]:t);let l=a+0,c=a+1,h=a+2;o&&(l=o[l],c=o[c],h=o[h]);for(let t=0;t<3;t++){const n=r[Cs[t]](l),s=r[Cs[t]](c),o=r[Cs[t]](h);let a=n;s<a&&(a=s),o<a&&(a=o);let d=n;s>d&&(d=s),o>d&&(d=o),e[i+t]=a,e[i+t+3]=d}return e}computePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,o=n.index?n.index.array:null,a=r.normalized;if(t<0||e+t-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=r.array,c=r.offset||0;let h=3;r.isInterleavedBufferAttribute&&(h=r.data.stride);const d=["getX","getY","getZ"],u=i.offset;for(let n=t,p=t+e;n<p;n++){const t=3*(s?s[n]:n),e=6*(n-u);let p=t+0,f=t+1,m=t+2;o&&(p=o[p],f=o[f],m=o[m]),a||(p=p*h+c,f=f*h+c,m=m*h+c);for(let t=0;t<3;t++){let n,s,o;a?(n=r[d[t]](p),s=r[d[t]](f),o=r[d[t]](m)):(n=l[p+t],s=l[f+t],o=l[m+t]);let c=n;s<c&&(c=s),o<c&&(c=o);let h=n;s>h&&(h=s),o>h&&(h=o);const u=(h-c)/2,g=2*t;i[e+g+0]=c+u,i[e+g+1]=u+(Math.abs(c)+u)*He}}return i}raycastObject3D(t,e,i=[]){const{material:n}=t;if(void 0===n)return;Ss.copy(t.matrixWorld).invert(),vs.copy(e.ray).applyMatrix4(Ss),Ts.setFromMatrixScale(t.matrixWorld),xs.copy(vs.direction).multiply(Ts);const s=xs.length(),r=e.near/s,o=e.far/s;if(!0===e.firstHitOnly){let s=this.raycastFirst(vs,n,r,o);s=_s(s,t,e),s&&i.push(s)}else{const s=this.raycast(vs,n,r,o);for(let n=0,r=s.length;n<r;n++){const r=_s(s[n],t,e);r&&i.push(r)}}return i}refit(t=null){return(this.indirect?Kn:En)(this,t)}raycast(t,e=_,i=0,n=1/0){const s=this._roots,r=[],o=this.indirect?Qn:zn;for(let a=0,l=s.length;a<l;a++)o(this,a,e,t,r,i,n);return r}raycastFirst(t,e=_,i=0,n=1/0){const s=this._roots;let r=null;const o=this.indirect?es:kn;for(let a=0,l=s.length;a<l;a++){const s=o(this,a,e,t,i,n);null!=s&&(null==r||s.distance<r.distance)&&(r=s)}return r}intersectsGeometry(t,e){let i=!1;const n=this._roots,s=this.indirect?cs:Un;for(let r=0,o=n.length;r<o&&(i=s(this,r,t,e),!i);r++);return i}shapecast(t){const e=an.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?Pn:An});return an.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=an.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?t=>{const e=this.resolveTriangleIndex(t);Cn(r,3*e,o,a)}:t=>{Cn(r,3*t,o,a)},c=an.getPrimitive(),h=t.geometry.index,d=t.geometry.attributes.position,u=t.indirect?e=>{const i=t.resolveTriangleIndex(e);Cn(c,3*i,h,d)}:t=>{Cn(c,3*t,h,d)};if(s){if(!(t instanceof As))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const i=(t,i,n,o,a,h,d,p)=>{for(let f=n,m=n+o;f<m;f++){u(f),c.a.applyMatrix4(e),c.b.applyMatrix4(e),c.c.applyMatrix4(e),c.needsUpdate=!0;for(let e=t,n=t+i;e<n;e++)if(l(e),r.needsUpdate=!0,s(r,c,e,f,a,h,d,p))return!0}return!1};if(n){const t=n;n=function(e,n,s,r,o,a,l,c){return!!t(e,n,s,r,o,a,l,c)||i(e,n,s,r,o,a,l,c)}}else n=i}return super.bvhcast(t,e,{intersectsRanges:n})}intersectsBox(t,e){return bs.set(t.min,t.max,e),bs.needsUpdate=!0,this.shapecast({intersectsBounds:t=>bs.intersectsBox(t),intersectsTriangle:t=>bs.intersectsTriangle(t)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},n={},s=0,r=1/0){return(this.indirect?ys:Xn)(this,t,e,i,n,s,r)}closestPointToPoint(t,e={},i=0,n=1/0){return function(t,e,i={},n=0,s=1/0){const r=n*n,o=s*s;let a=1/0,l=null;if(t.shapecast({boundsTraverseOrder:t=>(ln.copy(e).clamp(t.min,t.max),ln.distanceToSquared(e)),intersectsBounds:(t,e,i)=>i<a&&i<o,intersectsTriangle:(t,i)=>{t.closestPointToPoint(e,ln);const n=e.distanceToSquared(ln);return n<a&&(cn.copy(ln),a=n,l=i),n<r}}),a===1/0)return null;const c=Math.sqrt(a);return i.point?i.point.copy(cn):i.point=cn.clone(),i.distance=c,i.faceIndex=l,i}(this,t,e,i,n)}}const Es=new l,Ms=new y,Ps=new Ti(()=>new d),zs=new h,Is=new h,Ds=new a,ks=["getX","getY","getZ"];class Bs extends Yi{get primitiveStride(){return 2}writePrimitiveBounds(t,e,i){const n=this._indirectBuffer,{geometry:s,primitiveStride:r}=this,o=s.attributes.position,a=s.index,l=a?a.count:o.count;let c=(n?n[t]:t)*r,h=(c+1)%l;a&&(c=a.getX(c),h=a.getX(h));for(let t=0;t<3;t++){const n=o[ks[t]](c),s=o[ks[t]](h),r=n<s?n:s,a=n>s?n:s;e[i+t]=r,e[i+t+3]=a}return e}shapecast(t){const e=Ps.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsLine,scratchPrimitive:e,iterate:Os});return Ps.releasePrimitive(e),i}raycastObject3D(t,e,i=[]){const{matrixWorld:n}=t,{firstHitOnly:s}=e;Es.copy(n).invert(),Ms.copy(e.ray).applyMatrix4(Es);const r=e.params.Line.threshold/((t.scale.x+t.scale.y+t.scale.z)/3),o=r*r;let a=null,l=1/0;return this.shapecast({boundsTraverseOrder:t=>t.distanceToPoint(Ms.origin),intersectsBounds:t=>(Ds.copy(t).expandByScalar(Math.abs(r)),Ms.intersectsBox(Ds)?1:0),intersectsLine:(r,c)=>{if(Ms.distanceSqToSegment(r.start,r.end,zs,Is)>o)return;zs.applyMatrix4(t.matrixWorld);const h=e.ray.origin.distanceTo(zs);h<e.near||h>e.far||s&&h>=l||(l=h,c=this.resolvePrimitiveIndex(c),a={distance:h,point:Is.clone().applyMatrix4(n),index:c*this.primitiveStride,face:null,faceIndex:null,barycoord:null,object:t},s||i.push(a))}}),s&&a&&i.push(a),i}}function Os(t,e,i,n,s,r,o){const{geometry:a,primitiveStride:l}=i,{index:c}=a,h=a.attributes.position,d=c?c.count:h.count;for(let a=t,u=e+t;a<u;a++){let t=i.resolvePrimitiveIndex(a)*l,e=(t+1)%d;if(c&&(t=c.getX(t),e=c.getX(e)),o.start.fromBufferAttribute(h,t),o.end.fromBufferAttribute(h,e),n(o,a,s,r))return!0}return!1}const Vs={Mesh:b.prototype.raycast,Line:S.prototype.raycast,LineSegments:v.prototype.raycast,LineLoop:x.prototype.raycast,Points:T.prototype.raycast,BatchedMesh:A.prototype.raycast},Ls=new b,Ns=[];function Fs(t,e){if(this.isBatchedMesh)Rs.call(this,t,e);else{const{geometry:i}=this;if(i.boundsTree)i.boundsTree.raycastObject3D(this,t,e);else{let i;if(this instanceof b)i=Vs.Mesh;else if(this instanceof v)i=Vs.LineSegments;else if(this instanceof x)i=Vs.LineLoop;else if(this instanceof S)i=Vs.Line;else{if(!(this instanceof T))throw new Error("BVH: Fallback raycast function not found.");i=Vs.Points}i.call(this,t,e)}}}function Rs(t,e){if(this.boundsTrees){const i=this.boundsTrees,n=this._drawInfo||this._instanceInfo,s=this._drawRanges||this._geometryInfo,r=this.matrixWorld;Ls.material=this.material,Ls.geometry=this.geometry;const o=Ls.geometry.boundsTree,a=Ls.geometry.drawRange;null===Ls.geometry.boundingSphere&&(Ls.geometry.boundingSphere=new C);for(let o=0,a=n.length;o<a;o++){if(!this.getVisibleAt(o))continue;const a=n[o].geometryIndex;if(Ls.geometry.boundsTree=i[a],this.getMatrixAt(o,Ls.matrixWorld).premultiply(r),!Ls.geometry.boundsTree){this.getBoundingBoxAt(a,Ls.geometry.boundingBox),this.getBoundingSphereAt(a,Ls.geometry.boundingSphere);const t=s[a];Ls.geometry.setDrawRange(t.start,t.count)}Ls.raycast(t,Ns);for(let t=0,i=Ns.length;t<i;t++){const i=Ns[t];i.object=this,i.batchId=o,e.push(i)}Ns.length=0}Ls.geometry.boundsTree=o,Ls.geometry.drawRange=a,Ls.material=null,Ls.geometry=null}else Vs.BatchedMesh.call(this,t,e)}function Us(t={}){const{type:e=As}=t;return this.boundsTree=new e(this,t),this.boundsTree}function js(){this.boundsTree=null}const $s=class t extends ht{constructor(i){super(i),e(this,"onDisposed",new at),e(this,"onBeforeDispose",new at),e(this,"onFragmentsLoaded",new at),e(this,"baseCoordinationModel",""),e(this,"baseCoordinationMatrix",new o.Matrix4),e(this,"enabled",!0),e(this,"_core"),this.components.add(t.uuid,this)}static getWorker(){return s.getWorker()}get initialized(){return!!this._core}get list(){return this.core.models.list}get core(){if(!this._core)throw new Error("FragmentsManager not initialized. Call init() first.");return this._core}get _hasCoordinationModel(){return""!==this.baseCoordinationModel}dispose(){this.onBeforeDispose.trigger(),this._core&&(this.core.dispose(),this._core=void 0),this.baseCoordinationModel="",this.onFragmentsLoaded.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}init(t,e){this._core=new s(t,e),this.core.onModelLoaded.add(async()=>{if(this._hasCoordinationModel)return;const t=[...this.list.values()][0];t&&(this.baseCoordinationModel=t.modelId,this.baseCoordinationMatrix=await t.getCoordinationMatrix())}),this.list.onItemDeleted.add(()=>{this.list.size>0||(this.baseCoordinationModel="",this.baseCoordinationMatrix=new o.Matrix4)})}async raycast(t){const e=[];for(const i of this.core.models.list.values())if(t.snappingClasses&&t.snappingClasses.length>0){const n=await i.raycastWithSnapping(t);if(n&&n.length>0)e.push(n[0]);else{const n=await i.raycast(t);n&&e.push(n)}}else{const n=await i.raycast(t);n&&e.push(n)}if(await Promise.all(e),0===e.length)return;let i=e[0],n=i.distance;for(let t=1;t<e.length;t++)e[t].distance<n&&(n=e[t].distance,i=e[t]);return i}async getPositions(t){const e=[],i=async(t,i)=>{const n=await t.getPositions(i);for(const t of n)e.push(t)},n=[];for(const e in t){const s=this.core.models.list.get(e);s&&n.push(i(s,Array.from(t[e])))}return await Promise.all(n),e}async getBBoxes(t){const e=[],i=async(t,i)=>{const n=await t.getBoxes(i);if(n)for(const t of n)e.push(t)},n=[];for(const e in t){const s=this.core.models.list.get(e);s&&n.push(i(s,Array.from(t[e])))}return await Promise.all(n),e}async highlight(t,e){await this.forEachModel(e,"highlight",t)}async getData(t,e){const i={};for(const[n,s]of Object.entries(t)){const t=this.list.get(n);if(!t)continue;if(0===s.size){i[n]=[];continue}const r=await t.getItemsData([...s],e);i[n]=r}return i}async resetHighlight(t){await this.forEachModel(t,"resetHighlight")}async forEachModel(t,e,...i){const n={};if(t)for(const e in t){const i=t[e];n[e]=Array.from(i)}else for(const t of this.core.models.list.keys())n[t]=void 0;const s=[];for(const t in n){const r=this.core.models.list.get(t);if(r){const o=n[t],a=r[e](o,...i);s.push(a)}}await Promise.all(s)}async guidsToModelIdMap(t){const e={};for(const[i,n]of this.list){const s=(await n.getLocalIdsByGuids([...t])).filter(t=>null!==t);e[i]=new Set(s)}return e}async modelIdMapToGuids(t){const e=[];for(const[i,n]of Object.entries(t)){const t=this.list.get(i);if(!t)continue;const s=(await t.getGuidsByLocalIds([...n])).filter(t=>null!==t);e.push(...s)}return e}applyBaseCoordinateSystem(t,e){const i=new o.Matrix4;return e&&i.copy(e.clone()).invert(),i.multiply(this.baseCoordinationMatrix),t.applyMatrix4(i),i}};e($s,"uuid","fef46874-46a3-461b-8c44-2922ab77c806");let Ws=$s;function Gs(t,e){return t[e]|t[e+1]<<8|t[e+2]<<16}class Hs{constructor(t,e={}){const{pixelsPerMeter:i=.1}=e;this.pixelsPerMeter=i,this.renderer=t}async cull(t){t=function(t){const e=new Set;return t.traverse(t=>{t.isMesh&&e.add(t)}),Array.from(e)}(t);const{renderer:e,pixelsPerMeter:i}=this,n=new h,s=new E,r=new a,o=new M(1,1);r.makeEmpty(),t.forEach(t=>{r.expandByObject(t)}),r.getSize(n);const l=Math.min(e.capabilities.maxTextureSize,8192),c=Math.ceil(n.x/i),d=Math.ceil(n.z/i),u=Math.ceil(c/l),p=Math.ceil(d/l);o.setSize(Math.ceil(c/u),Math.ceil(d/p)),s.rotation.x=-Math.PI/2,s.far=r.max.y-r.min.y+s.near,s.position.y=r.max.y+s.near;const f=new P,m=new Map,g=new Map,w=[];for(let e=0;e<t.length;e++){const i=t[e];m.set(i,i.material),g.set(i,i.parent);const n=new qs;n.objectId=e,w.push(n),i.material=n,f.add(i)}const y=e.getClearColor(new z),_=e.getClearAlpha(),b=e.getRenderTarget(),v=e.autoClear;e.autoClear=!0,e.setClearColor(0,0),e.setRenderTarget(o);const x=new Uint8Array(o.width*o.height*4),S=new Set,T=n.x/u,C=n.z/p;for(let i=0;i<u;i++)for(let n=0;n<p;n++){const a=r.min.x+T*i,l=a+T,c=r.min.z+C*n,h=(a+l)/2,d=(c+(c+C))/2;s.position.set(h,r.max.y,d);const u=T/2,p=C/2;s.left=-u,s.right=u,s.top=p,s.bottom=-p,s.updateProjectionMatrix(),e.render(f,s);const m=await e.readRenderTargetPixelsAsync(o,0,0,o.width,o.height,x);for(let e=0,i=m.length;e<i;e+=4){if(0===m[e+3])continue;const i=Gs(m,e);S.add(t[i])}}for(const e of t){e.material=m.get(e);const t=g.get(e);t?t.add(e):f.remove(e)}e.setClearColor(y,_),e.setRenderTarget(b),e.autoClear=v;for(const t of w)t.dispose();return o.dispose(),Array.from(S)}}class qs extends I{get objectId(){return this._objectId}set objectId(t){var e,i;this._objectId=t,e=t,(i=this.uniforms.objectId.value).x=(255&e)/255,i.y=(e>>8&255)/255,i.z=(e>>16&255)/255,i.w=1}constructor(t){super({glslVersion:B,blending:k,uniforms:{objectId:{value:new D}},vertexShader:"\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\t\t\t\tlayout(location = 0) out vec4 out_id;\n\t\t\t\tuniform vec4 objectId;\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tout_id = objectId;\n\n\t\t\t\t}\n\t\t\t"}),this._objectId=0,this.setValues(t)}}const Zs=1e-16,Ys=new h(0,1,0),Xs=new h;function Ks(t){return t.delta(Xs).normalize(),Math.abs(Xs.dot(Ys))>=1-Zs}function Qs(t,e){const{start:i,end:n}=e,s=t.points;let r=!1,o=!1;for(let t=0;t<3;t++){const e=s[t];if(!r&&i.distanceToSquared(e)<=Zs&&(r=!0),!o&&n.distanceToSquared(e)<=Zs&&(o=!0),r&&o)return!0}return r&&o}const Js=new d;function tr(t,e,i=!1,n=[]){let s=[[0,1]];for(let t=0,i=e.length;t<i;t++){const i=s[t],n=e[t];i[1]=n[0],s.push([n[1],1])}i&&([e,s]=[s,e]);for(let e=0,i=s.length;e<i;e++){const{start:i,end:r}=t;Js.start.lerpVectors(i,r,s[e][0]),Js.end.lerpVectors(i,r,s[e][1]),n.push(new Float32Array([Js.start.x,Js.start.y,Js.start.z,Js.end.x,Js.end.y,Js.end.z]))}return n}const er=new h(0,1,0),ir=new h,nr=new h,sr=new h,rr=new f;function*or(t,e=[],i={}){const{projectionDirection:n=er,thresholdAngle:s=1,iterationTime:r=30}=i,o=Math.pow(10,4),a=Math.cos(O.DEG2RAD*s),l=t.getIndex(),c=t.getAttribute("position"),h=l?l.count:c.count,u=[0,0,0],p=["a","b","c"],f=new Array(3),m={};let g=performance.now();for(let t=0;t<h;t+=3){performance.now()-g>r&&(yield,g=performance.now()),l?(u[0]=l.getX(t),u[1]=l.getX(t+1),u[2]=l.getX(t+2)):(u[0]=t,u[1]=t+1,u[2]=t+2);const{a:i,b:s,c:h}=rr;if(i.fromBufferAttribute(c,u[0]),s.fromBufferAttribute(c,u[1]),h.fromBufferAttribute(c,u[2]),rr.getNormal(sr),f[0]=`${Math.round(i.x*o)},${Math.round(i.y*o)},${Math.round(i.z*o)}`,f[1]=`${Math.round(s.x*o)},${Math.round(s.y*o)},${Math.round(s.z*o)}`,f[2]=`${Math.round(h.x*o)},${Math.round(h.y*o)},${Math.round(h.z*o)}`,f[0]!==f[1]&&f[1]!==f[2]&&f[2]!==f[0])for(let t=0;t<3;t++){const i=(t+1)%3,s=f[t],r=f[i],o=rr[p[t]],l=rr[p[i]],c=`${s}_${r}`,h=`${r}_${s}`;if(h in m&&m[h]){const t=m[h].normal,i=sr.dot(t)<=a;let s=!1;if(null!==n){let e=n.dot(sr);e=Math.abs(e)<1e-10?0:e;let i=n.dot(t);i=Math.abs(i)<1e-10?0:i,s=Math.sign(e)!==Math.sign(i)}if(i||s){const t=new d;t.start.copy(o),t.end.copy(l),e.push(t)}m[h]=null}else c in m||(m[c]={index0:u[t],index1:u[i],normal:sr.clone()})}}for(const t in m)if(m[t]){const{index0:i,index1:n}=m[t];ir.fromBufferAttribute(c,i),nr.fromBufferAttribute(c,n);const s=new d;s.start.copy(ir),s.end.copy(nr),e.push(s)}return e}const ar=new d;function lr(t,e,i,n=[]){return t.bvhcast(e,i,{intersectsTriangles:(t,e)=>!function(t,e){const i=["a","b","c"];let n=0;for(let s=0;s<3;s++)for(let r=0;r<3;r++){cr(t[i[s]],e[i[r]])&&n++}return n>=2}(t,e)&&(t.needsUpdate&&t.update(),e.needsUpdate&&e.update(),!(Math.abs(t.plane.normal.dot(e.plane.normal))>.999999)&&void(!t.intersectsTriangle(e,ar,!0)||Qs(t,ar)||Qs(e,ar)||n.push(ar.clone())))}),n}function cr(t,e){return t.distanceTo(e)<1e-10}function hr(t){dr(t);let e=[];return t.traverse(t=>{t.geometry&&t.visible&&e.push(t)}),e}const dr=t=>{if(void 0===t)return;const e=[...t.children];for(const i of e)void 0===i?t.children.splice(t.children.indexOf(i),1):dr(i)},ur=new l,pr=new l;class fr{constructor(){this.projectionDirection=new h(0,1,0),this.thresholdAngle=50,this.iterationTime=30}getEdges(...t){const e=this.iterationTime;this.iterationTime=1/0;const i=this.getEdgesGenerator(...t).next().value;return this.iterationTime=e,i}*getEdgesGenerator(t,e=[],i=null){const{projectionDirection:n,thresholdAngle:s,iterationTime:r}=this;if(t.isObject3D){const o=hr(t);let a=null;n&&(a=new h);let l=performance.now();for(let t=0;t<o.length;t++){l-performance.now()>r&&(yield);const c=o[t];a&&(pr.copy(c.matrixWorld).invert(),a.copy(n).transformDirection(pr).normalize());const h=yield*or(c.geometry,[],{projectionDirection:a,thresholdAngle:s,iterationTime:r});mr(h,c.matrixWorld);for(let t=0;t<h.length;t++)e.push(h[t]);if(null!==i)for(let t=0;t<h.length;t++)i.push(c)}return e}return yield*or(t,e,{projectionDirection:n,thresholdAngle:s,iterationTime:r})}getIntersectionEdges(...t){const e=this.iterationTime;this.iterationTime=1/0;const i=this.getIntersectionEdgesGenerator(...t).next().value;return this.iterationTime=e,i}*getIntersectionEdgesGenerator(t,e=[],i=null){const{iterationTime:n}=this;if(t.isObject3D){const s=hr(t),r=new Map;let o=performance.now();for(let t=0;t<s.length;t++){performance.now()-o>n&&(yield,o=performance.now());const e=s[t].geometry;if(!r.has(e)){const t=e.boundsTree||new As(e,{maxLeafSize:1});r.set(e,t)}}o=performance.now();for(let t=0;t<s.length;t++)for(let a=t;a<s.length;a++){performance.now()-o>n&&(yield,o=performance.now());const l=s[t],c=s[a],h=r.get(l.geometry),d=r.get(c.geometry);ur.copy(l.matrixWorld).invert().multiply(c.matrixWorld);const u=lr(h,d,ur,[]);mr(u,l.matrixWorld);for(let t=0;t<u.length;t++)e.push(u[t]);if(null!==i)for(let t=0;t<u.length;t++)i.push(l)}return e}{let i;return t.isBufferGeometry?i=t.boundsTree||new As(t,{maxLeafSize:1}):(i=t,t=i.geometry),ur.identity(),lr(i,i,ur,e)}}}function mr(t,e,i=1e-6){for(let n=0;n<t.length;n++){const s=t[n];s.applyMatrix4(e),s.start.y+=i,s.end.y+=i}}class gr extends Wi{get lines(){return this.primitiveBuffer}constructor(t,e){super(e),this.primitiveBuffer=t,this.primitiveBufferStride=1,this.heightOffset=e.heightOffset??1e3,this.init(e)}writePrimitiveBounds(t,e,i){const{primitiveBuffer:n,heightOffset:s}=this,{start:r,end:o}=n[t];e[i+0]=Math.min(r.x,o.x),e[i+1]=Math.min(r.y,o.y),e[i+2]=Math.min(r.z,o.z),e[i+3]=Math.max(r.x,o.x),e[i+4]=Math.max(r.y,o.y)+s,e[i+5]=Math.max(r.z,o.z)}getRootRanges(){return[{offset:0,count:this.primitiveBuffer.length}]}}const wr=new h(0,1,0),yr=new u,_r=new h,br=new h;function vr(t,e,i){t.needsUpdate&&t.update(),yr.copy(t.plane),yr.normal.dot(wr)<0&&(yr.normal.multiplyScalar(-1),yr.constant*=-1);const n=yr.distanceToPoint(e.start),s=yr.distanceToPoint(e.end),r=Math.abs(n)<1e-16,o=n<0,a=s<0;if(e.delta(br).normalize(),Math.abs(yr.normal.dot(br))<1e-16)return!(r||!o)&&(i.copy(e),!0);if(o&&a)return i.copy(e),!0;if(!o&&!a)return!1;{const t=O.mapLinear(0,n,s,0,1);if(e.at(t,_r),o)return i.start.copy(e.start),i.end.copy(_r),!0;if(a)return i.end.copy(e.end),i.start.copy(_r),!0}return!1}const xr=new u,Sr=new h,Tr=new h,Cr=new sn,Ar=new d,Er=new d,Mr=new h,Pr=new h,zr=new h;function Ir(t,e,i=new d){if(Cr.copy(e),Cr.a.y=0,Cr.b.y=0,Cr.c.y=0,Cr.update(),Ar.copy(t),Ar.start.y=0,Ar.end.y=0,Cr.getArea()<=1e-16)return null;const n=Ar.distance();Ar.delta(Mr).divideScalar(n),Pr.copy(Mr).cross(Cr.plane.normal).normalize(),xr.setFromNormalAndCoplanarPoint(Pr,Ar.start);let s=0;const{points:r}=Cr;for(let t=0;t<3;t++){const e=r[t],i=r[(t+1)%3],n=xr.distanceToPoint(e),o=xr.distanceToPoint(i),a=Math.abs(n)<1e-16,l=Math.abs(o)<1e-16;let c=!1;if(!a&&!l&&n*o<0){const t=n/(n-o);Sr.lerpVectors(e,i,t),c=!0}if((c&&!l||a)&&(a&&!c&&Sr.copy(e),0===s?Er.start.copy(Sr):Er.end.copy(Sr),s++,2===s))break}if(2===s){if(Er.delta(zr).normalize(),Mr.dot(zr)<0){const t=Er.start;Er.start=Er.end,Er.end=t}const e=0,s=Tr.subVectors(Ar.end,Ar.start).dot(Mr),r=Tr.subVectors(Er.start,Ar.start).dot(Mr),o=Tr.subVectors(Er.end,Ar.start).dot(Mr);return s<=r||o<=e?null:(t.at(Math.max(e,r)/n,i.start),t.at(Math.min(s,o)/n,i.end),i)}return null}const Dr=new h,kr=new h,Br=new h;function Or(t,e,i){const n=function(t,e){t.delta(Dr),kr.subVectors(e.start,t.start),Br.subVectors(e.end,t.start);const i=Dr.length();let n=kr.length()/i,s=Br.length()/i;if(n=Math.min(Math.max(n,0),1),s=Math.min(Math.max(s,0),1),Math.abs(n-s)<=1e-16)return null;return[n,s]}(t,e);return!!n&&(Vr(n,i),!0)}function Vr(t,e){let[i,n]=t,s=0,r=e.length;for(;s<r;){const t=s+r>>>1;e[t][0]<=i?s=t+1:r=t}let o=Math.max(0,s-1),a=0;for(let t=o,s=e.length;t<s;t++){const[s,r]=e[t];if(i<=r&&n>=s)i=Math.min(s,i),n=Math.max(r,n),a++;else{if(!(i>=s))break;o=t+1}}e.splice(o,a,[i,n])}const Lr=new h(0,1,0),Nr=new d,Fr=new d,Rr=new sn;function Ur(t,e,i,n,s=null){const{geometry:r,matrixWorld:o,material:a}=i,l=a.side,c=o.determinant()<0,h=t.lines;t.bvhcast(e,o,{intersectsRanges:(t,e,i,a)=>{s&&(s.candidates+=e*a);for(let d=i,u=a+i;d<u;d++){let i=3*d+0,a=3*d+1,u=3*d+2;r.index&&(i=r.index.getX(i),a=r.index.getX(a),u=r.index.getX(u));const{a:p,b:f,c:w}=Rr;if(p.fromBufferAttribute(r.attributes.position,i).applyMatrix4(o),f.fromBufferAttribute(r.attributes.position,a).applyMatrix4(o),w.fromBufferAttribute(r.attributes.position,u).applyMatrix4(o),Rr.needsUpdate=!0,Rr.update(),l!==g){if(Rr.plane.normal.dot(Lr)!==c===(l===m)){s&&(s.backFaceCulled+=e);continue}}const y=Math.max(p.y,f.y,w.y),_=Math.min(p.y,f.y,w.y),b=Rr.plane.normal;let v=b.x,x=b.y,S=b.z,T=Rr.plane.constant;x<0&&(v=-v,x=-x,S=-S,T=-T);for(let i=t,r=e+t;i<r;i++){const t=h[i],e=Math.min(t.start.y,t.end.y),r=Math.max(t.start.y,t.end.y);if(y<=e){s&&s.yBoundsCulled++;continue}const o=t.end.x-t.start.x,a=t.end.z-t.start.z,l=o*o+a*a;if(l>1e-20){const e=1/Math.sqrt(l),i=o*e,n=a*e,r=-n,c=i,h=p.x-t.start.x,d=p.z-t.start.z,u=f.x-t.start.x,m=f.z-t.start.z,g=w.x-t.start.x,y=w.z-t.start.z,_=h*i+d*n,b=u*i+m*n,v=g*i+y*n,x=1/e,S=Math.min(_,b,v);if(Math.max(_,b,v)<0||S>x){s&&s.xzBoundsCulled++;continue}const T=h*r+d*c,C=u*r+m*c,A=g*r+y*c,E=Math.min(T,C,A),M=Math.max(T,C,A);if(E>0||M<0){s&&s.xzBoundsCulled++;continue}}const c=v*t.start.x+x*t.start.y+S*t.start.z+T,d=v*t.end.x+x*t.end.y+S*t.end.z+T;if(c>=0&&d>=0)s&&s.planeTrimCulled++;else if(Qs(Rr,t))s&&s.triangleEdgeCulled++;else{if(r<_)Nr.copy(t);else if(!vr(Rr,t,Nr)){s&&s.planeTrimCulled++;continue}Nr.distance()<1e-10?s&&s.distThresholdCulled++:Ir(Nr,Rr,Fr)?(s&&s.used++,Or(t,Fr,n[i])):s&&s.noOverlapCulled++}}}}})}Rr.update=()=>{Rr.plane.setFromCoplanarPoints(...Rr.points)};let jr=!1;const $r={},Wr={};let Gr=null,Hr=0,qr=0;const Zr={get enabled(){return jr},set enabled(t){jr=t},reset(){for(const t in $r)delete $r[t];for(const t in Wr)delete Wr[t];Gr=null,Hr=0,qr=0},setStat(t,e){Wr[t]=e},startTotal(){jr&&(qr=performance.now())},startStep(t){jr&&(null!==Gr&&this.endStep(),Gr=t,Hr=performance.now())},endStep(){if(!jr||null===Gr)return;const t=performance.now()-Hr;$r[Gr]=t,Gr=null},printSummary(){if(!jr)return;null!==Gr&&this.endStep();const t=performance.now()-qr;console.log("\n=== Projection Summary ==="),console.log(`Total time: ${t.toFixed(1)}ms\n`);for(const[e,i]of Object.entries($r)){const n=(i/t*100).toFixed(1);console.log(` ${e}: ${i.toFixed(1)}ms (${n}%)`)}if(Object.keys(Wr).length>0){console.log("\n--- Stats ---");for(const[t,e]of Object.entries(Wr))console.log(` ${t}: ${e}`)}console.log("")}},Yr=1e-5,Xr=1e-16,Kr=1e-16;function Qr(t,e,i,n,s){t.bvhcast(e,i.matrixWorld,{intersectsRanges:(t,e,i,r)=>{n._edgeOffsets.push(t),n._edgeCounts.push(e),n._meshOffsets.push(i),n._meshCounts.push(r),n._meshIndex.push(s),n.groupCount++}})}let Jr=null;async function to(t,e,i,n,s=null){const r=await async function(){return null===Jr&&(Jr=new L.WebGPURenderer,await Jr.init()),Jr}();t._edgeOffsets&&(t.edgeOffsets=new Uint32Array(t._edgeOffsets),t.edgeCounts=new Uint32Array(t._edgeCounts),t.meshOffsets=new Uint32Array(t._meshOffsets),t.meshCounts=new Uint32Array(t._meshCounts),t.meshIndex=new Uint32Array(t._meshIndex),t._edgeOffsets=null,t._edgeCounts=null,t._meshOffsets=null,t._meshCounts=null,t._meshIndex=null);const o=N(function(t){const e=new Float32Array(6*t.length);for(let i=0;i<t.length;i++){const n=t[i];e[6*i+0]=n.start.x,e[6*i+1]=n.start.y,e[6*i+2]=n.start.z,e[6*i+3]=n.end.x,e[6*i+4]=n.end.y,e[6*i+5]=n.end.z}return e}(i.lines),"float");Zr.enabled&&console.log("Number of meshes:",e.length),Zr.enabled&&console.log("Group count:",t.groupCount);const a=[];{let t=0;for(;t<e.length;){let i=t,n=0;for(;i<e.length;){const s=e[i].geometry,r=s.index?s.index.count/3:s.attributes.position.count/3;if(i>t&&(i-t>=1e3||n+r>1e5))break;n+=r,i++}a.push({start:t,end:i}),t=i}}Zr.enabled&&console.log(`Split ${e.length} meshes into ${a.length} batches`);let l=0,c=0,h=0,d=0,u=0;for(let i=0;i<a.length;i++){const{start:p,end:f}=a[i],m=f-p;Zr.enabled&&console.log(`Processing batch ${i+1}/${a.length} (meshes ${p}-${f-1})`);let g=0,w=0;const y=[];for(let t=p;t<f;t++){const i=e[t].geometry;y.push(w/3),g+=i.attributes.position.array.length,w+=i.index.array.length}const _=new Float32Array(g),b=new Uint32Array(w);let v=0,x=0,S=0;for(let t=p;t<f;t++){const i=e[t].geometry,n=i.attributes.position.array,s=i.index.array;_.set(n,v),v+=n.length;for(let t=0;t<s.length;t++)b[x+t]=s[t]+S;x+=s.length,S+=i.attributes.position.count}const T=new Float32Array(16*m);for(let t=p;t<f;t++){const i=t-p;T.set(e[t].matrixWorld.elements,16*i)}const C=[];for(let e=0;e<t.groupCount;e++){const i=t.meshIndex[e];if(i>=p&&i<f){const n=i-p,s=y[n]+t.meshOffsets[e];C.push({edgeOffset:t.edgeOffsets[e],edgeCount:t.edgeCounts[e],triOffset:s,triCount:t.meshCounts[e],meshIdx:n})}}if(0===C.length){Zr.enabled&&console.log(` Batch ${i+1}: no groups, skipping`);continue}const A=new Uint32Array(5*C.length);for(let t=0;t<C.length;t++){const e=C[t],i=5*t;A[i+0]=e.edgeOffset,A[i+1]=e.edgeCount,A[i+2]=e.triOffset,A[i+3]=e.triCount,A[i+4]=e.meshIdx}let E=0;for(let t=0;t<C.length;t++)E+=C[t].edgeCount*C[t].triCount;s&&(s.candidates+=E);let M=Math.min(Math.ceil(.1*E),2e6),P=Math.max(M,1e4);Zr.enabled&&console.log(` Batch ${i+1}: ${C.length} groups, ${g/3} vertices, ${w/3} triangles, ${E} pairs, buffer for ${P} overlaps`);const z=performance.now(),I=N(_,"float"),D=N(b,"uint"),k=N(T,"float"),B=N(A,"uint");let O=N(new Uint32Array([0]),"uint").toAtomic(),V=N(new Float32Array(3*P),"float");d+=performance.now()-z;const L=performance.now(),st=F(()=>{const t=R.mul(5),e=B.element(t),i=B.element(t.add(1)),n=B.element(t.add(2)),s=B.element(t.add(3)),r=B.element(t.add(4)).mul(16),a=U(k.element(r),k.element(r.add(1)),k.element(r.add(2)),k.element(r.add(3)),k.element(r.add(4)),k.element(r.add(5)),k.element(r.add(6)),k.element(r.add(7)),k.element(r.add(8)),k.element(r.add(9)),k.element(r.add(10)),k.element(r.add(11)),k.element(r.add(12)),k.element(r.add(13)),k.element(r.add(14)),k.element(r.add(15)));j({start:$(0),end:s.toInt(),type:"int",condition:"<",name:"triIdx"},({triIdx:t})=>{const s=n.add(t.toUint()).mul(3),r=D.element(s),l=D.element(s.add(1)),c=D.element(s.add(2)),h=W(I.element(r.mul(3)),I.element(r.mul(3).add(1)),I.element(r.mul(3).add(2))),d=W(I.element(l.mul(3)),I.element(l.mul(3).add(1)),I.element(l.mul(3).add(2))),u=W(I.element(c.mul(3)),I.element(c.mul(3).add(1)),I.element(c.mul(3).add(2))),p=a.mul(G(h,H(1))).xyz,f=a.mul(G(d,H(1))).xyz,m=a.mul(G(u,H(1))).xyz,g=f.sub(p),w=m.sub(p),y=q(g,w),_=y.dot(y);Z(_.lessThan(H(4e-16*Xr)),()=>{Y()}),Z(y.y.lessThan(0),()=>{Y()});const b=X(p.y,X(f.y,m.y));j({start:$(0),end:i.toInt(),type:"int",condition:"<",name:"edgeIdx"},({edgeIdx:t})=>{const i=e.add(t.toUint()),n=i.mul(6),s=W(o.element(n),o.element(n.add(1)),o.element(n.add(2))),r=W(o.element(n.add(3)),o.element(n.add(4)),o.element(n.add(5))),a=K(s.y,r.y);Z(b.lessThanEqual(a),()=>{Y()});const l=Q(y),c=l.dot(p).negate(),h=l.y.lessThan(0),d=J(h,l.negate(),l),u=J(h,c.negate(),c),g=d.dot(s).add(u),w=d.dot(r).add(u),_=g.lessThan(0),v=w.lessThan(0),x=tt(g).lessThan(H(Yr)),S=_.not().and(v.not()),T=w.sub(g),C=tt(T).lessThan(H(Yr)),A=C.and(x.or(_.not()));Z(A,()=>{Y()}),Z(S.and(C.not()),()=>{Y()});const E=g.negate().div(T),M=et(s,r,E),z=W(J(C.or(_),s.x,M.x),J(C.or(_),s.y,M.y),J(C.or(_),s.z,M.z)),I=W(J(C.or(v),r.x,M.x),J(C.or(v),r.y,M.y),J(C.or(v),r.z,M.z)),D=I.sub(z),k=D.dot(D);Z(k.lessThan(H(Yr)),()=>{Y()});const B=s.sub(p),L=s.sub(f),N=s.sub(m),F=r.sub(p),R=r.sub(f),U=r.sub(m),j=B.dot(B).lessThanEqual(H(Yr)),$=L.dot(L).lessThanEqual(H(Yr)),G=N.dot(N).lessThanEqual(H(Yr)),st=F.dot(F).lessThanEqual(H(Yr)),rt=R.dot(R).lessThanEqual(H(Yr)),ot=U.dot(U).lessThanEqual(H(Yr)),at=j.or($).or(G),lt=st.or(rt).or(ot),ct=at.and(lt);Z(ct,()=>{Y()});const ht=W(p.x,H(0),p.z),dt=W(f.x,H(0),f.z),ut=W(m.x,H(0),m.z),pt=W(z.x,H(0),z.z),ft=W(I.x,H(0),I.z),mt=W(s.x,H(0),s.z),gt=W(r.x,H(0),r.z).sub(mt),wt=gt.dot(gt);Z(wt.lessThan(H(Yr)),()=>{Y()});const yt=wt.sqrt(),_t=dt.sub(ht),bt=ut.sub(ht),vt=q(_t,bt),xt=vt.dot(vt);Z(xt.lessThanEqual(H(4e-16*Xr)),()=>{Y()});const St=ft.sub(pt),Tt=St.dot(St);Z(Tt.lessThan(H(Yr)),()=>{Y()});const Ct=Tt.sqrt(),At=St.div(Ct),Et=gt.div(yt),Mt=Q(vt),Pt=q(At,Mt),zt=H(0).toVar(),It=H(0).toVar(),Dt=H(0).toVar(),kt=H(0).toVar(),Bt=it(0).toVar(),Ot=Pt.dot(ht.sub(pt)),Vt=Pt.dot(dt.sub(pt)),Lt=tt(Ot).lessThan(H(Kr)),Nt=tt(Vt).lessThan(H(Kr)),Ft=Lt.not().and(Nt.not()).and(Ot.mul(Vt).lessThan(0));Z(Ft,()=>{const t=Ot.div(Ot.sub(Vt)),e=et(ht.x,dt.x,t),i=et(ht.z,dt.z,t);Z(Bt.equal(0),()=>{zt.assign(e),It.assign(i)}).Else(()=>{Dt.assign(e),kt.assign(i)}),Bt.addAssign(1)}).ElseIf(Lt,()=>{Z(Bt.equal(0),()=>{zt.assign(ht.x),It.assign(ht.z)}).Else(()=>{Dt.assign(ht.x),kt.assign(ht.z)}),Bt.addAssign(1)});const Rt=Vt,Ut=Pt.dot(ut.sub(pt)),jt=Nt,$t=tt(Ut).lessThan(H(Kr)),Wt=jt.not().and($t.not()).and(Rt.mul(Ut).lessThan(0));Z(Bt.lessThan(2),()=>{Z(Wt,()=>{const t=Rt.div(Rt.sub(Ut)),e=et(dt.x,ut.x,t),i=et(dt.z,ut.z,t);Z(Bt.equal(0),()=>{zt.assign(e),It.assign(i)}).Else(()=>{Dt.assign(e),kt.assign(i)}),Bt.addAssign(1)}).ElseIf(jt.and(Ft.not()).and(Lt.not()),()=>{Z(Bt.equal(0),()=>{zt.assign(dt.x),It.assign(dt.z)}).Else(()=>{Dt.assign(dt.x),kt.assign(dt.z)}),Bt.addAssign(1)})});const Gt=Ut,Ht=Ot,qt=$t,Zt=Lt,Yt=qt.not().and(Zt.not()).and(Gt.mul(Ht).lessThan(0));Z(Bt.lessThan(2),()=>{Z(Yt,()=>{const t=Gt.div(Gt.sub(Ht)),e=et(ut.x,ht.x,t),i=et(ut.z,ht.z,t);Z(Bt.equal(0),()=>{zt.assign(e),It.assign(i)}).Else(()=>{Dt.assign(e),kt.assign(i)}),Bt.addAssign(1)}).ElseIf(qt.and(Wt.not()).and(jt.not()),()=>{Z(Bt.equal(0),()=>{zt.assign(ut.x),It.assign(ut.z)}).Else(()=>{Dt.assign(ut.x),kt.assign(ut.z)}),Bt.addAssign(1)})}),Z(Bt.notEqual(2),()=>{Y()});const Xt=W(zt,H(0),It),Kt=W(Dt,H(0),kt).sub(Xt).dot(At),Qt=W(zt,H(0),It).toVar(),Jt=W(Dt,H(0),kt).toVar();Z(Kt.lessThan(0),()=>{const t=zt,e=It;Qt.x.assign(Dt),Qt.z.assign(kt),Jt.x.assign(t),Jt.z.assign(e)});const te=H(0),ee=Ct,ie=Qt.sub(pt).dot(At),ne=Jt.sub(pt).dot(At),se=ee.lessThanEqual(ie).or(ne.lessThanEqual(te));Z(se,()=>{Y()});const re=X(te,ie),oe=K(ee,ne),ae=pt.add(At.mul(re)),le=pt.add(At.mul(oe)),ce=ae.sub(mt).dot(Et).div(yt),he=le.sub(mt).dot(Et).div(yt),de=X(H(0),K(H(1),ce)),ue=X(H(0),K(H(1),he)),pe=tt(ue.sub(de));Z(pe.lessThanEqual(H(Kr)),()=>{Y()});const fe=nt(O.element(0),1);Z(fe.lessThan(it(P)),()=>{const t=fe.mul(3);V.element(t).assign(i.toFloat()),V.element(t.add(1)).assign(de),V.element(t.add(2)).assign(ue)})})})})().compute(C.length);u+=performance.now()-L;const rt=performance.now();await r.computeAsync(st),l+=performance.now()-rt;const ot=performance.now(),at=await r.getArrayBufferAsync(O.value),lt=new Uint32Array(at)[0];if(s&&(s.used+=Math.min(lt,P)),Zr.enabled&&console.log(` Batch ${i+1}: ${lt} overlaps found (capacity: ${P})`),lt>P&&Zr.enabled&&console.warn(` WARNING: Overlap buffer overflow! ${lt} > ${P}. Some occlusion data lost.`),lt>0){const t=await r.getArrayBufferAsync(V.value),e=new Float32Array(t);c+=performance.now()-ot;const i=performance.now(),s=Math.min(lt,P);for(let t=0;t<s;t++){const i=3*t,s=Math.round(e[i]);Vr([e[i+1],e[i+2]],n[s])}h+=performance.now()-i,Zr.enabled&&console.log(` Processed ${s} overlaps into hiddenOverlapMap`)}else c+=performance.now()-ot}r.dispose(),Jr=null;const p=d+u+l+c+h;Zr.enabled&&(console.log(`WebGPU timing breakdown (total: ${p.toFixed(1)}ms):`),console.log(` Buffer creation: ${d.toFixed(1)}ms`),console.log(` Shader build: ${u.toFixed(1)}ms`),console.log(` GPU compute: ${l.toFixed(1)}ms`),console.log(` Readback: ${c.toFixed(1)}ms`),console.log(` CPU merge: ${h.toFixed(1)}ms`))}const eo=new h(0,1,0);function io(t,e=null){const i=new Float32Array(6*t.length);let n=0;for(let e=0,s=t.length;e<s;e++){const s=t[e];i[n++]=s[0],i[n++]=0,i[n++]=s[2],i[n++]=s[3],i[n++]=0,i[n++]=s[5]}const s=new V,r=new c(i,3,!0);if(s.setAttribute("position",r),e){const i=new Float32Array(2*t.length);for(let t=0,n=e.length;t<n;t++)i[2*t]=e[t],i[2*t+1]=e[t];s.setAttribute("group",new c(i,1))}return s}class no{constructor(t,e=!0){this.meshes=hr(t),this.bvhs=new Map,this.visibleEdges=[],this.hiddenEdges=[],this.visibleGroupIndices=[],this.hiddenGroupIndices=[],this.groupKeyToIndex=null,this.hasGroups=!1,this.iterationTime=30,this.useWebGPU=e}reset(){this.visibleEdges.length=0,this.hiddenEdges.length=0,this.visibleGroupIndices.length=0,this.hiddenGroupIndices.length=0,this.groupKeyToIndex=null,this.hasGroups=!1}getVisibleLineGeometry(){return io(this.visibleEdges,this.groupKeyToIndex?this.visibleGroupIndices:null)}getHiddenLineGeometry(){return io(this.hiddenEdges,this.groupKeyToIndex?this.hiddenGroupIndices:null)}getGroupKeys(){return this.groupKeyToIndex?Object.fromEntries(this.groupKeyToIndex):{}}addEdges(...t){const e=this.iterationTime;this.iterationTime=1/0;const i=this.addEdgesGenerator(...t).next().value;return this.iterationTime=e,i}*addEdgesGenerator(t,e={}){const{meshes:i,bvhs:n,visibleEdges:s,hiddenEdges:r,iterationTime:o}=this;let a=performance.now();Zr.startStep("Building mesh BVH");for(let t=0;t<i.length;t++){performance.now()-a>o&&(yield,a=performance.now());const e=i[t].geometry;if(!n.has(e)){const t=e.boundsTree||new As(e);n.set(e,t)}}let l=0;for(let t=0;t<i.length;t++){const e=i[t].geometry;l+=e.index?e.index.count/3:e.attributes.position.count/3}const c={};for(let e=0;e<t.length;e++)c[e]=[];Zr.startStep("Building line BVH");const h=new gr(t,{maxLeafSize:2,strategy:2});Zr.startStep("BVHcast overlaps"),a=performance.now();const d={candidates:0,backFaceCulled:0,yBoundsCulled:0,xzBoundsCulled:0,triangleEdgeCulled:0,planeTrimCulled:0,distThresholdCulled:0,noOverlapCulled:0,used:0,totalEdges:t.length,totalTriangles:l},u=this.useWebGPU,p={};u&&(p._edgeOffsets=[],p._edgeCounts=[],p._meshOffsets=[],p._meshCounts=[],p._meshIndex=[],p.groupCount=0);for(let t=0;t<i.length;t++){performance.now()-a>o&&(e.onProgress&&e.onProgress(t,i.length),yield,a=performance.now());const s=i[t];u?Qr(h,n.get(s.geometry),s,p,t):Ur(h,n.get(s.geometry),s,c,d)}if(u){let t=!1;for(to(p,i,h,c,d).then(()=>{t=!0});!t;)yield}const f=d.totalEdges*d.totalTriangles;if(Zr.setStat("Total edges",d.totalEdges.toLocaleString()),Zr.setStat("Total triangles",d.totalTriangles.toLocaleString()),Zr.setStat("Brute-force pairs (edges × triangles)",f.toLocaleString()),Zr.setStat("BVH candidate pairs",d.candidates.toLocaleString()),f>0&&Zr.setStat("BVH reduction",(d.candidates/f*100).toFixed(3)+"% of brute-force"),d.candidates>0){const t=d.candidates,e=e=>(e/t*100).toFixed(2)+"%";u||(Zr.setStat("Rejected: back-face culling",d.backFaceCulled.toLocaleString()+" ("+e(d.backFaceCulled)+")"),Zr.setStat("Rejected: Y-bounds (tri below edge)",d.yBoundsCulled.toLocaleString()+" ("+e(d.yBoundsCulled)+")"),Zr.setStat("Rejected: XZ-bounds (no 2D overlap)",d.xzBoundsCulled.toLocaleString()+" ("+e(d.xzBoundsCulled)+")"),Zr.setStat("Rejected: edge lies on triangle",d.triangleEdgeCulled.toLocaleString()+" ("+e(d.triangleEdgeCulled)+")"),Zr.setStat("Rejected: line above tri plane",d.planeTrimCulled.toLocaleString()+" ("+e(d.planeTrimCulled)+")"),Zr.setStat("Rejected: trimmed edge too small",d.distThresholdCulled.toLocaleString()+" ("+e(d.distThresholdCulled)+")"),Zr.setStat("Rejected: no projected overlap",d.noOverlapCulled.toLocaleString()+" ("+e(d.noOverlapCulled)+")")),Zr.setStat("Producing overlaps",d.used.toLocaleString()+" ("+e(d.used)+")")}Zr.startStep("Converting overlaps to lines");const m=this.hasGroups;for(let e=0;e<t.length;e++){performance.now()-a>o&&(yield,a=performance.now());const i=t[e],n=c[e],l=s.length,h=r.length;if(tr(i,n,!1,s),tr(i,n,!0,r),m){const t=i.groupIndex;for(let e=l;e<s.length;e++)this.visibleGroupIndices.push(t);for(let e=h;e<r.length;e++)this.hiddenGroupIndices.push(t)}}}}class so{constructor(){this.iterationTime=30,this.angleThreshold=50,this.includeIntersectionEdges=!0,this.useWebGPU=!0}generateAsync(t,e={}){return new Promise((i,n)=>{const{signal:s}=e,r=this.generate(t,e);!function t(){if(s&&s.aborted)return void n(new Error("ProjectionGenerator: Process aborted via AbortSignal."));const e=r.next();e.done?i(e.value):requestAnimationFrame(t)}()})}*generate(t,e){const{iterationTime:i,angleThreshold:n,includeIntersectionEdges:s}=this,{onProgress:r=()=>{},visibilityCuller:o=null,groupFn:a=null}=e;if(Zr.reset(),Zr.startTotal(),t.isBufferGeometry&&(t=new b(t)),o){Zr.startStep("Visibility culling");let e=!1;for(o.cull(t).then(i=>{(t=new P).children=i,e=!0});!e;)yield}const l=new fr;l.iterationTime=i,l.thresholdAngle=n,l.projectionDirection.copy(eo),Zr.startStep("Generating candidate edges"),r("Generating candidate edges");let c=[],h=a?[]:null;if(yield*l.getEdgesGenerator(t,c,h),s&&(Zr.startStep("Generating intersection edges"),r("Generating intersection edges"),yield*l.getIntersectionEdgesGenerator(t,c,h)),Zr.startStep("Pre-filtering edges"),r("Pre-filtering edges"),h){const t=[],e=[];for(let i=0;i<c.length;i++)Ks(c[i])||(t.push(c[i]),e.push(h[i]));c=t,h=e}else c=c.filter(t=>!Ks(t));yield;const d=new no(t,this.useWebGPU);if(d.iterationTime=i,a&&h){const t=new Map;for(let e=0;e<c.length;e++){const i=a(h[e]);t.has(i)||t.set(i,t.size),c[e].groupIndex=t.get(i)}d.groupKeyToIndex=t,d.hasGroups=!0}return r("Building BVH & computing overlaps"),yield*d.addEdgesGenerator(c,{onProgress:r?(t,e)=>{r("Building BVH & computing overlaps",t/e,d)}:null}),Zr.printSummary(),d}}new d,new d,new h;const ro=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new at),e(this,"generator",new so),e(this,"cullerPixelsPerMeter",.05),e(this,"projectionDirection",new o.Vector3(0,-1,0)),e(this,"nearPlane",-1/0),e(this,"farPlane",1/0),this.components.add(t.uuid,this),this.generator.includeIntersectionEdges=!1}async get(t,e,i){const n=this.components.get(Ws),s=new o.Group,r=new Map;for(const[e,i]of Object.entries(t)){const t=n.list.get(e);if(!t)continue;const a=(await t.getItemsIdsWithGeometry()).filter(t=>i.has(t));if(0===a.length)continue;const l=await t.getItemsGeometry(a);for(const i in l){const n=l[i];for(const i of n){if(!(i.positions&&i.indices&&i.transform&&i.representationId))continue;const n=i.representationId;if(!r.has(n)){const t=new o.BufferGeometry;t.setAttribute("position",new o.Float32BufferAttribute(i.positions,3)),i.normals&&t.setAttribute("normal",new o.Float32BufferAttribute(i.normals,3)),t.setIndex(Array.from(i.indices)),r.set(n,t)}const a=r.get(n),l=new o.Mesh(a);l.applyMatrix4(i.transform),l.applyMatrix4(t.object.matrixWorld),l.updateWorldMatrix(!0,!0),l.userData._edgeProjectorModelId=e,l.userData._edgeProjectorLocalId=i.localId,s.add(l)}}}const a=this.projectionDirection.clone().normalize(),l=new o.Vector3(0,-1,0),c=(new o.Quaternion).setFromUnitVectors(a,l),h=(new o.Matrix4).makeRotationFromQuaternion(c),d=h.clone().invert();for(const t of s.children)t.applyMatrix4(h),t.updateWorldMatrix(!1,!1);if(s.traverse(t=>{const e=t;if(e.geometry&&!e.geometry.boundsTree){const t=e.geometry.index?e.geometry.index.count:e.geometry.attributes.position.count;e.geometry.groups.forEach(e=>{e.count===1/0&&(e.count=t-e.start)}),e.geometry.boundsTree=new As(e.geometry,{maxLeafSize:1,strategy:2})}}),this.nearPlane!==-1/0||this.farPlane!==1/0){const t=new o.Box3,e=[];for(const i of s.children){const n=i;n.geometry&&(t.setFromObject(n),(t.max.y<this.nearPlane||t.min.y>this.farPlane)&&e.push(n))}for(const t of e)s.remove(t)}const u=e.renderer.three,p=new Hs(u,{pixelsPerMeter:this.cullerPixelsPerMeter}),f=await this.generator.generateAsync(s,{visibilityCuller:p,groupFn:t=>`${t.userData._edgeProjectorModelId??"unknown"}:${t.userData._edgeProjectorLocalId??0}`,onProgress:null==i?void 0:i.onProgress}),m=f.getVisibleLineGeometry(),g=f.getHiddenLineGeometry();m.applyMatrix4(d),g.applyMatrix4(d);const w=f.getGroupKeys(),y={};for(const[t,e]of Object.entries(w)){const i=t.lastIndexOf(":"),n=t.substring(0,i),s=Number(t.substring(i+1));y[e]={modelId:n,localId:s}}for(const t of r.values())t.dispose();return{visible:m,hidden:g,groups:y}}dispose(){this.onDisposed.trigger(t.uuid),this.onDisposed.reset()}};e(ro,"uuid","f2e76c3a-8b1d-4d5e-9a3f-7c6b2d4e8f1a");let oo=ro;class ao{constructor(){e(this,"wasm",{path:"",absolute:!1,logLevel:st.LogLevel.LOG_LEVEL_OFF}),e(this,"webIfc",{COORDINATE_TO_ORIGIN:!0}),e(this,"autoSetWasm",!0),e(this,"customLocateFileHandler",null)}}const lo=class t extends ht{constructor(i){super(i),e(this,"onDisposed",new at),e(this,"onIfcStartedLoading",new at),e(this,"onIfcImporterInitialized",new at),e(this,"onSetup",new at),e(this,"settings",new ao),e(this,"webIfc",new st.IfcAPI),e(this,"enabled",!0),this.components.add(t.uuid,this)}dispose(){this.webIfc=null,this.onDisposed.trigger(t.uuid),this.onDisposed.reset()}async setup(t){this.settings={...this.settings,...t},this.settings.autoSetWasm&&await this.autoSetWasm(),this.onSetup.trigger()}async load(t,e,n,s){const r=this.components.get(Ws);if(!r.initialized)throw new Error("You need to initialize fragments first.");this.settings.autoSetWasm&&await this.autoSetWasm(),r.core.settings.autoCoordinate=e;const o=new i.IfcImporter;o.wasm.path=this.settings.wasm.path,o.wasm.absolute=this.settings.wasm.absolute,o.webIfcSettings=this.settings.webIfc,this.onIfcImporterInitialized.trigger(o),(null==s?void 0:s.instanceCallback)&&s.instanceCallback(o);const a=await o.process({...null==s?void 0:s.processData,bytes:t});return await r.core.load(a,{modelId:n,userData:null==s?void 0:s.userData})}async readIfcFile(t){const{path:e,absolute:i,logLevel:n}=this.settings.wasm;return this.webIfc.SetWasmPath(e,i),await this.webIfc.Init(this.settings.customLocateFileHandler||void 0),n&&this.webIfc.SetLogLevel(n),this.webIfc.OpenModel(t,this.settings.webIfc)}cleanUp(){try{this.webIfc.Dispose()}catch(t){console.log("Web-ifc wasn't disposed.")}this.webIfc=null,this.webIfc=new st.IfcAPI}async autoSetWasm(){const t=await fetch(`https://unpkg.com/@thatopen/components@${Uo.release}/package.json`);if(!t.ok)return void console.warn("Couldn't get openbim-components package.json. Set wasm settings manually.");const e=await t.json();if("web-ifc"in e.peerDependencies){const t=e.peerDependencies["web-ifc"];this.settings.wasm.path=`https://unpkg.com/web-ifc@${t}/`,this.settings.wasm.absolute=!0}else console.warn("Couldn't get web-ifc from peer dependencies in openbim-components. Set wasm settings manually.")}};e(lo,"uuid","a659add7-1418-4771-a0d6-7d4d438e4624");let co=lo;const ho=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),this.components.add(t.uuid,this)}async set(t,e){const i=this.components.get(Ws),n=[];if(e)for(const[s,r]of Object.entries(e)){const e=i.list.get(s);e&&n.push(e.setVisible([...r],t))}else for(const e of i.list.values())n.push(e.setVisible(void 0,t));await Promise.all(n),await i.core.update(!0)}async isolate(t){await Promise.all([this.set(!1),this.set(!0,t)])}async toggle(t){const e=[],i=this.components.get(Ws);for(const[n,s]of Object.entries(t)){const t=i.list.get(n);t&&e.push(t.toggleVisible([...s]))}await Promise.all(e),await i.core.update(!0)}async getVisibilityMap(t,e){const i=[],n=[],s=this.components.get(Ws);if(e)for(const r of e){const e=s.list.get(r);e&&(i.push(e.modelId),n.push(e.getItemsByVisibility(t)))}else for(const e of s.list.values())i.push(e.modelId),n.push(e.getItemsByVisibility(t));const r=await Promise.all(n),o={};for(const[t,e]of i.entries())o[e]=r[t];return o}};e(ho,"uuid","dd9ccf2d-8a21-4821-b7f6-2949add16a29");let uo=ho;const po=class t extends ht{constructor(n){super(n),e(this,"enabled",!0),e(this,"onDisposed",new at),e(this,"list",new i.DataSet),this.components.add(t.uuid,this)}dispose(e=!0){this.list.clear(),this.onDisposed.trigger(t.uuid),e&&(this.onDisposed.reset(),this.list.eventsEnabled=!1,this.list.dispose())}get(){const t=new o.Box3;for(const e of this.list)t.union(e);return t}async addFromModelIdMap(t){const e=this.components.get(Ws),i=new o.Box3;for(const[n,s]of Object.entries(t)){const t=e.list.get(n);if(!t)continue;const r=await t.getMergedBox([...s]);i.union(r)}this.list.add(i)}addFromModels(t){const e=this.components.get(Ws);for(const[i,n]of e.list)t&&!t.some(t=>t.test(i))||this.list.add(n.box)}async getCenter(t){this.list.clear(),await this.addFromModelIdMap(t);const e=this.get();this.list.clear();const i=new o.Vector3;return e.getCenter(i),i}async getCameraOrientation(t,e=1){const i=this.components.get(Ws);this.list.clear();for(const[t,e]of i.list)this.list.add(e.box);const n=this.get();this.list.clear();const s=new o.Vector3;n.getCenter(s);const r=new o.Vector3;n.getSize(r);const a=Math.max(r.x,r.y,r.z)*e,l=new o.Vector3;switch(t){case"front":default:l.set(s.x,s.y,s.z+a);break;case"back":l.set(s.x,s.y,s.z-a);break;case"left":l.set(s.x-a,s.y,s.z);break;case"right":l.set(s.x+a,s.y,s.z);break;case"top":l.set(s.x,s.y+a,s.z);break;case"bottom":l.set(s.x,s.y-a,s.z)}return{position:l,target:s}}};e(po,"uuid","d1444724-dba6-4cdd-a0c7-68ee1450d166");let fo=po;class mo{constructor(t,i){e(this,"name","Query"),e(this,"customData",{}),e(this,"_components"),e(this,"_queries",[]),e(this,"_aggregation","exclusive"),e(this,"result",null),e(this,"cache",!0),e(this,"serializeQueryParameters",t=>{var e;return{categories:null==(e=t.categories)?void 0:e.map(t=>t.source),attributes:t.attributes?{aggregation:t.attributes.aggregation,queries:t.attributes.queries.map(this.serializeAttributeQuery)}:void 0,relation:t.relation?{name:t.relation.name,query:t.relation.query?this.serializeQueryParameters(t.relation.query):void 0}:void 0}}),e(this,"deserializeQueryParameters",t=>{var e;return{categories:null==(e=t.categories)?void 0:e.map(t=>new RegExp(t)),attributes:t.attributes?{aggregation:t.attributes.aggregation,queries:t.attributes.queries.map(this.deserializeAttributeQuery)}:void 0,relation:t.relation?{name:t.relation.name,query:t.relation.query?this.deserializeQueryParameters(t.relation.query):void 0}:void 0}}),this._components=t,this.queries=i}set queries(t){this._queries=t,this.clearCache()}get queries(){return this._queries}set aggregation(t){t!==this._aggregation&&this.clearCache(),this._aggregation=t}get aggregation(){return this._aggregation}async test(t){const{modelIds:e,force:i}={force:!1,...t};if(this.result&&!i)return this.result;const n=this._components.get(wo),s=await n.getItems(this.queries,{modelIds:e,aggregation:this.aggregation});return this.cache&&(this.result=s),s}clearCache(){this.result=null}serializeAttributeQuery(t){let e;e=Array.isArray(t.value)?t.value.map(t=>t.source):t.value instanceof RegExp?t.value.source:t.value;return{name:t.name.source,value:e,type:t.type instanceof RegExp?t.type.source:t.type,negate:t.negate,itemIds:t.itemIds}}toJSON(){return{guid:this._components.get(wo).list.getKey(this)??_t.create(),name:this.name,customData:this.customData,queries:this.queries.map(this.serializeQueryParameters),aggregation:this.aggregation,cache:this.cache}}deserializeAttributeQuery(t){let e;e=Array.isArray(t.value)?t.value.map(t=>new RegExp(t)):"string"==typeof t.value?new RegExp(t.value):t.value;return{name:new RegExp(t.name),value:e,type:t.type?new RegExp(t.type):void 0,negate:t.negate,itemIds:t.itemIds}}fromJSON(t){return this.name=t.name,this.customData=t.customData,this.aggregation=t.aggregation,this.cache=t.cache,this.queries=t.queries.map(this.deserializeQueryParameters),this}}const go=class t extends ht{constructor(n){super(n),e(this,"enabled",!0),e(this,"list",new i.DataMap),n.add(t.uuid,this)}async getItems(t,e){let i;if(e){const{modelIds:t,items:n}=e;if(n){const t=Object.keys(n);t.length>0&&(i=t.map(t=>new RegExp(`^${t}$`)))}else t&&(i=t)}const n=(null==e?void 0:e.aggregation)??"exclusive",s=this.components.get(Ws),r=await Promise.all(t.map(async t=>{const n={};return await Promise.all(Array.from(s.list).map(async([s,r])=>{var o;if(i&&!i.some(t=>t.test(s)))return;const a=null==(o=null==e?void 0:e.items)?void 0:o[s],l=await r.getItemsByQuery(t,{localIds:a?[...a]:void 0});n[s]=new Set(l)})),n}));return"inclusive"===n?Ve.join(r):Ve.intersect(r)}create(t,e){const i=new mo(this.components,e);return this.list.set(t,i),i}async addFromCategories(t){const e=new Set,i=this.components.get(Ws);for(const[n,s]of i.list){if(t&&!t.some(t=>t.test(n)))continue;const i=(await s.getItemsWithGeometryCategories()).filter(t=>null!==t),r=new Set(i);for(const t of r)this.list.has(t)||(this.create(t,[{categories:[new RegExp(`^${t}$`)]}]),e.add(t))}return[...e]}import(t){const{data:e}=t,i=[];if(!e)return i;for(const t of e){const e=this.create(t.guid,[]);e.fromJSON(t),i.push(e)}return i}export(){const t=[];for(const[e,i]of this.list.entries()){const n={...i.toJSON(),name:e};t.push(n)}return{data:t}}};e(go,"uuid","0da7ad77-f734-42ca-942f-a074adfd1e3a");let wo=go;const yo=class t extends ht{constructor(n){super(n),e(this,"enabled",!0),e(this,"onDisposed",new at),e(this,"list",new i.DataMap),e(this,"defaultSaveFunction",t=>"value"in t.Name?t.Name.value:null),e(this,"onBeforeFragmentsDispose",async t=>{const{key:e,value:i}=t,n=await i.getLocalIds(),s={[e]:new Set(n)};this.removeItems(s)}),n.add(t.uuid,this),this.setupEvents();n.get(Ws).list.onBeforeDelete.add(this.onBeforeFragmentsDispose)}setupEvents(){this.list.onBeforeDelete.add(({value:t})=>t.dispose())}getClassificationGroups(t){let e=this.list.get(t);return e||(e=new i.DataMap,this.list.set(t,e)),e}getModelItems(t,e,i){const{map:n}=this.getGroupData(t,e);let s=n[i];return s||(s=new Set,n[i]=s),s}getGroupData(t,e){const i=this.components.get(wo),n=this.getClassificationGroups(t);let s=n.get(e);return s||(s={map:{},get:()=>new Promise(t=>{if(s)if(s.query){const{name:e,config:n}=s.query,r=i.list.get(e);if(!r)throw new Error("Classifier: the query name associated with the group doesn't exist in the ItemsFinder component");r.test(n).then(e=>{if(!s)return void t({});const i=Ve.join([e,s.map]);t(i)})}else t(s.map);else t({})})},n.set(e,s)),s}async aggregateItems(t,e,i){const n=(null==i?void 0:i.data)??void 0,s=(null==i?void 0:i.aggregationCallback)??this.defaultSaveFunction,r=this.components.get(Ws),o=this.components.get(wo),a=await o.getItems([e],{modelIds:null==i?void 0:i.modelIds});for(const[e,i]of Object.entries(a)){const o=r.list.get(e);if(!o)continue;const a=(i,...n)=>{const s=this.getModelItems(t,i,e);for(const t of n)s.add(t)},l=await o.getItemsData([...i],n);for(const t of l)s(t,a)}}addGroupItems(t,e,i){const{map:n}=this.getGroupData(t,e);Ve.add(n,i)}setGroupQuery(t,e,i){this.getGroupData(t,e).query=i}async find(t){const e=[];for(const[i,n]of Object.entries(t)){const t=[],s=this.list.get(i);if(!s)continue;for(const e of n){const i=s.get(e);if(!i)continue;const n=await i.get();t.push(n)}const r=Ve.join(t);e.push(r)}return Ve.intersect(e)}async aggregateItemRelations(t,e,i,n){const s=(null==n?void 0:n.attribute)??"Name",r={relations:{[i]:{attributes:!0,relations:!1}}};await this.aggregateItems(t,e,{modelIds:null==n?void 0:n.modelIds,data:r,aggregationCallback:(t,e)=>{if(!(null==t?void 0:t[s]))return;const n=t[s];if(!("value"in n))return;const r=t[i];if(Array.isArray(r))for(const t of r)"value"in t._localId&&e(n.value,t._localId.value)}})}async byIfcBuildingStorey(t){await this.aggregateItemRelations((null==t?void 0:t.classificationName)??"Storeys",{categories:[/BUILDINGSTOREY/]},"ContainsElements",{modelIds:null==t?void 0:t.modelIds})}async byCategory(t){const e=this.components.get(wo),i=await e.addFromCategories(null==t?void 0:t.modelIds);for(const e of i)this.setGroupQuery((null==t?void 0:t.classificationName)??"Categories",e,{name:e})}dispose(){this.list.clear();this.components.get(Ws).list.onBeforeDelete.remove(this.onBeforeFragmentsDispose),this.onDisposed.trigger()}removeItems(t,e){if(e&&e.classificationName){const i=this.list.get(e.classificationName);if(!i)return;if(e.groupName){if(!i.get(e.groupName))return}for(const[,e]of i)Ve.remove(e.map,t);return}for(const[,e]of this.list.entries())for(const[,i]of e)Ve.remove(i.map,t)}async byModel(t){const e=this.components.get(Ws),i=(null==t?void 0:t.classificationName)??"Models";for(const[n,s]of e.list){if(t&&t.modelIds&&!t.modelIds.some(t=>t.test(n)))continue;const e=await s.getItemsIdsWithGeometry(),r={[n]:new Set(e)};this.getGroupData(i,n),this.addGroupItems(i,n,r)}}};e(yo,"uuid","e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7");let _o=yo;class bo{constructor(t,i){e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new at),e(this,"mouse"),e(this,"world"),e(this,"debugMode",!1),e(this,"colorToModelId",new Map),e(this,"modelIdToColor",new Map),e(this,"renderTarget"),e(this,"renderTargetSize",new o.Vector2),e(this,"debugCanvas"),e(this,"debugContainer"),e(this,"colorMaterials",new Map),e(this,"originalMaterials",new Map),e(this,"originalLodColors",new Map),e(this,"colorsNeedUpdate",!0);const n=i.renderer;if(!n)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=i,this.mouse=new $e(n.three.domElement),this.components=t,this.setupRenderTarget(),this.setupFragmentListeners()}setupFragmentListeners(){const t=this.components.get(Ws);t.list.onItemSet.add(()=>{this.colorsNeedUpdate=!0}),t.list.onItemDeleted.add(()=>{this.colorsNeedUpdate=!0})}setupRenderTarget(){const t=this.world.renderer.three.getSize(new o.Vector2);this.renderTargetSize.copy(t),this.renderTarget=new o.WebGLRenderTarget(t.x,t.y),this.renderTarget.texture.format=o.RGBAFormat,this.renderTarget.texture.type=o.UnsignedByteType,this.debugMode&&this.setupDebugCanvas(),this.world.renderer.onResize.add(t=>{this.renderTargetSize.copy(t),this.renderTarget.setSize(t.x,t.y),this.debugCanvas&&(this.debugCanvas.width=t.x,this.debugCanvas.height=t.y)})}setupDebugCanvas(){if(this.debugCanvas)return;const t=this.world.renderer.three.getSize(new o.Vector2);this.debugContainer=document.createElement("div"),this.debugContainer.style.position="fixed",this.debugContainer.style.top="10px",this.debugContainer.style.right="10px",this.debugContainer.style.width="300px",this.debugContainer.style.height="300px",this.debugContainer.style.border="2px solid #fff",this.debugContainer.style.backgroundColor="#000",this.debugContainer.style.zIndex="10000",this.debugContainer.style.pointerEvents="none",this.debugCanvas=document.createElement("canvas"),this.debugCanvas.width=t.x,this.debugCanvas.height=t.y,this.debugCanvas.style.width="100%",this.debugCanvas.style.height="100%",this.debugCanvas.style.imageRendering="pixelated",this.debugContainer.appendChild(this.debugCanvas),document.body.appendChild(this.debugContainer)}generateColorForModel(t){let e=0;for(let i=0;i<t.length;i++)e=(e<<5)-e+t.charCodeAt(i),e&=e;let i=Math.abs(e)%16777215;0===i&&(i=1);const n=i>>16&255||1,s=i>>8&255||1,r=255&i||1;return new o.Color(n/255,s/255,r/255)}colorToId(t){return Math.round(255*t.r)<<16|Math.round(255*t.g)<<8|Math.round(255*t.b)}assignColors(){const t=this.components.get(Ws);if(t.initialized){if(!this.colorsNeedUpdate){const e=new Set(t.list.keys()),i=new Set(this.modelIdToColor.keys());(e.size!==i.size||[...e].some(t=>!i.has(t)))&&(this.colorsNeedUpdate=!0)}if(this.colorsNeedUpdate){this.colorToModelId.clear(),this.modelIdToColor.clear();for(const t of this.colorMaterials.values())t.dispose();this.colorMaterials.clear();for(const[e]of t.list){const t=this.generateColorForModel(e),i=this.colorToId(t);this.colorToModelId.set(i,e),this.modelIdToColor.set(e,t);const n=new o.MeshBasicMaterial({color:t,depthTest:!0,depthWrite:!0});this.colorMaterials.set(e,n)}this.colorsNeedUpdate=!1}}}applyColorMaterials(){const t=this.components.get(Ws);if(t.initialized)for(const[e,i]of t.list){const t=this.colorMaterials.get(e);t&&i.object.traverse(e=>{if(e instanceof o.Mesh){if("isLODGeometry"in e.geometry){const i=e.material[0].uniforms.lodColor;return this.originalLodColors.has(i)||this.originalLodColors.set(i,i.value),void(i.value=t.color)}this.originalMaterials.has(e)||this.originalMaterials.set(e,e.material),e.material=t}})}}restoreOriginalMaterials(){for(const[t,e]of this.originalMaterials)t.material=e;for(const[t,e]of this.originalLodColors)t.value=e;this.originalMaterials.clear()}renderColorCoded(){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const t=this.world.renderer.three,e=this.world.scene.three,i=this.world.camera.three,n=t.getRenderTarget(),s=t.autoClear,r=new o.Color,a=t.getClearAlpha();t.getClearColor(r),this.applyColorMaterials(),t.setRenderTarget(this.renderTarget),t.autoClear=!0,t.setClearColor(0,1),t.clear(!0,!0,!1),t.render(e,i),t.setRenderTarget(n),t.autoClear=s,t.setClearColor(r,a),this.restoreOriginalMaterials(),this.debugMode&&this.debugCanvas&&this.updateDebugCanvas()}updateDebugCanvas(){if(!this.debugCanvas||!this.renderTarget||!this.world.renderer)return;const t=this.world.renderer.three,e=this.renderTargetSize,i=new Uint8Array(e.x*e.y*4);t.readRenderTargetPixels(this.renderTarget,0,0,e.x,e.y,i);const n=this.debugCanvas.getContext("2d");if(!n)return;const s=n.createImageData(e.x,e.y),r=4*e.x;for(let t=0;t<e.y;t++){const n=t*r,o=(e.y-1-t)*r;s.data.set(i.subarray(n,n+r),o)}n.putImageData(s,0,0)}async getModelAt(t){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const e=this.components.get(Ws);if(!e.initialized||0===e.list.size)return null;this.assignColors(),this.renderColorCoded();const i=t||this.mouse.position,n=this.renderTargetSize,s=Math.floor(.5*(i.x+1)*n.x),r=Math.floor(.5*(i.y+1)*(n.y-1)),o=Math.max(0,Math.min(n.x-1,s)),a=Math.max(0,Math.min(n.y-1,r)),l=this.world.renderer.three,c=new Uint8Array(4);l.readRenderTargetPixels(this.renderTarget,o,a,1,1,c);const h=c[0]<<16|c[1]<<8|c[2];return this.colorToModelId.get(h)||null}setDebugMode(t){this.debugMode=t,t?this.setupDebugCanvas():this.removeDebugCanvas()}removeDebugCanvas(){this.debugContainer&&(this.debugContainer.remove(),this.debugContainer=void 0,this.debugCanvas=void 0)}dispose(){this.mouse.dispose(),this.removeDebugCanvas();for(const t of this.colorMaterials.values())t.dispose();this.colorMaterials.clear(),this.renderTarget&&this.renderTarget.dispose(),this.colorToModelId.clear(),this.modelIdToColor.clear(),this.originalMaterials.clear(),this.originalLodColors.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}}const vo=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new Map),e(this,"onDisposed",new at),i.add(t.uuid,this)}get(t){if(this.list.has(t.uuid))return this.list.get(t.uuid);const e=new bo(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add(()=>{this.delete(t)}),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}};e(vo,"uuid","4a82430c-7ff2-49ea-9401-60807502dad6");let xo=vo;class So{constructor(t,i){e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new at),e(this,"mouse"),e(this,"three",new o.Raycaster),e(this,"world"),e(this,"useFastModelPicking",!1);const n=i.renderer;if(!n)throw new Error("A renderer is needed for the raycaster to work!");this.world=i,this.mouse=new $e(n.three.domElement),this.components=t}dispose(){this.mouse.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}castRayToObjects(t=Array.from(this.world.meshes),e=this.mouse.position){if(!this.world)throw new Error("A world is needed to cast rays!");const i=this.world.camera.three;return this.three.setFromCamera(e,i),this.intersect(t)}async castRay(t){const e=null==t?void 0:t.snappingClasses,i=(null==t?void 0:t.items)??Array.from(this.world.meshes),n=(null==t?void 0:t.position)??this.mouse.position;if(!this.world)throw new Error("A world is needed to cast rays!");const s=this.world.camera.three,r=this.components.get(Ws),o=this.world.renderer.three.domElement,a=this.mouse.rawPosition;let l=null;if(r.initialized){if(this.useFastModelPicking){const t=this.components.get(xo).get(this.world),i=await t.getModelAt(n);if(i){const t=r.list.get(i);if(t)if(e&&e.length>0){const i=await t.raycastWithSnapping({camera:s,dom:o,mouse:a,snappingClasses:e});l=i&&i.length>0?i[0]:await t.raycast({camera:s,dom:o,mouse:a})}else l=await t.raycast({camera:s,dom:o,mouse:a})}}else l=await r.raycast({camera:s,dom:o,mouse:a,snappingClasses:e});if(0===i.length)return l}this.three.setFromCamera(n,s);const c=this.intersect(i);return l?c&&c.distance<l.distance?c:l:c}castRayFromVector(t,e,i=Array.from(this.world.meshes)){return this.three.set(t,e),this.intersect(i)}intersect(t=Array.from(this.world.meshes)){const e=this.three.intersectObjects(t),i=this.filterClippingPlanes(e);return i.length>0?i[0]:null}filterClippingPlanes(t){if(!this.world.renderer)throw new Error("Renderer not found!");const e=this.world.renderer.three;if(!e.clippingPlanes)return t;const i=e.clippingPlanes;return t.length<=0||!i||(null==i?void 0:i.length)<=0?t:t.filter(t=>i.every(e=>e.distanceToPoint(t.point)>0))}}const To=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new Map),e(this,"onDisposed",new at),i.add(t.uuid,this)}get(t){if(this.list.has(t.uuid))return this.list.get(t.uuid);const e=new So(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add(()=>{this.delete(t)}),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}};e(To,"uuid","d5d8bdf0-db25-4952-b951-b643af207ace");let Co=To;class Ao extends ct{constructor(){super(...arguments),e(this,"onCameraChanged",new at),e(this,"meshes",new Set),e(this,"onAfterUpdate",new at),e(this,"onBeforeUpdate",new at),e(this,"onDisposed",new at),e(this,"isDisposing",!1),e(this,"enabled",!0),e(this,"_dynamicAnchor",!1),e(this,"uuid",_t.create()),e(this,"name"),e(this,"_scene"),e(this,"_camera"),e(this,"_renderer",null),e(this,"onPointerDown",async t=>{if(!this.camera.hasCameraControls())throw new Error("World: can't set dynamic anchor if the camera doesn't have controls.");const e=this.components.get(Co).get(this),i=await e.castRay();i&&i.point&&0===t.button&&this.camera.controls.setOrbitPoint(i.point.x,i.point.y,i.point.z)}),e(this,"_defaultCamera")}set dynamicAnchor(t){var e;const i=null==(e=this.renderer)?void 0:e.three.domElement.parentElement;if(!i)throw new Error("World: the renderer must have a parentElement to set dynamic anchoring.");t?(this.camera.controls&&(this.camera.controls.minDistance=.01),i.addEventListener("pointerdown",this.onPointerDown)):i.removeEventListener("pointerdown",this.onPointerDown)}get dynamicAnchor(){return this._dynamicAnchor}get defaultCamera(){if(!this._defaultCamera)throw new Error("World: there is no default camera defined.");return this._defaultCamera}set defaultCamera(t){this._defaultCamera=t}get scene(){if(!this._scene)throw new Error("No scene initialized!");return this._scene}set scene(t){this._scene=t,t.worlds.set(this.uuid,this),t.currentWorld=this,t.onWorldChanged.trigger({world:this,action:"added"})}get camera(){if(!this._camera)throw new Error("No camera initialized!");return this._camera}set camera(t){this._camera||(this.defaultCamera=t),this._camera=t,t.currentWorld=this,this.onCameraChanged.trigger(t)}get renderer(){return this._renderer}set renderer(t){this._renderer=t,t&&(t.worlds.set(this.uuid,this),t.currentWorld=this,t.onWorldChanged.trigger({world:this,action:"added"}))}useDefaultCamera(){this.camera=this.defaultCamera}update(t){this.enabled&&this._scene&&this._camera&&(this.scene.currentWorld=this,this.camera.currentWorld=this,this.renderer&&(this.renderer.currentWorld=this),this.onBeforeUpdate.trigger(),this.scene.isUpdateable()&&this.scene.update(t),this.camera.isUpdateable()&&this.camera.update(t),this.renderer&&this.renderer.update(t),this.onAfterUpdate.trigger())}dispose(t=!0){if(this.enabled=!1,this.isDisposing=!0,this.scene.onWorldChanged.trigger({world:this,action:"removed"}),this.camera.onWorldChanged.trigger({world:this,action:"removed"}),this.renderer&&this.renderer.onWorldChanged.trigger({world:this,action:"removed"}),t){const t=this.components.get(mt);this.scene.dispose(),this.camera.isDisposeable()&&this.camera.dispose(),this.renderer&&this.renderer.dispose();for(const e of this.meshes)t.destroy(e);this.meshes.clear()}this._scene=null,this._camera=null,this._renderer=null;this.components.get(Oo).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class Eo{constructor(t,i){e(this,"_list"),e(this,"_scene"),this._list=t,this._scene=i}get color(){return this._list.directionalLight.color.value}set color(t){this._list.directionalLight.color.value=t;for(const[,e]of this._scene.directionalLights)e.color.copy(t)}get intensity(){return this._list.directionalLight.intensity.value}set intensity(t){this._list.directionalLight.intensity.value=t;for(const[,e]of this._scene.directionalLights)e.intensity=t}get position(){return this._list.directionalLight.position.value.clone()}set position(t){this._list.directionalLight.position.value=t;for(const[,e]of this._scene.directionalLights)e.position.copy(t)}}class Mo{constructor(t,i){e(this,"_list"),e(this,"_scene"),this._list=t,this._scene=i}get color(){return this._list.ambientLight.color.value}set color(t){this._list.ambientLight.color.value=t;for(const[,e]of this._scene.ambientLights)e.color.copy(t)}get intensity(){return this._list.ambientLight.intensity.value}set intensity(t){this._list.ambientLight.intensity.value=t;for(const[,e]of this._scene.ambientLights)e.intensity=t}}class Po extends Re{constructor(){super(...arguments),e(this,"_config",{backgroundColor:{value:new o.Color,type:"Color"},ambientLight:{color:{type:"Color",value:new o.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2}},directionalLight:{color:{type:"Color",value:new o.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2},position:{type:"Vector3",value:new o.Vector3}}}),e(this,"ambientLight",new Mo(this._config,this._component)),e(this,"directionalLight",new Eo(this._config,this._component))}get backgroundColor(){return this._config.backgroundColor.value}set backgroundColor(t){this._config.backgroundColor.value=t,this._component.three.background=t}}class zo extends gt{constructor(t){super(t),e(this,"onSetup",new at),e(this,"isSetup",!1),e(this,"three"),e(this,"config",new Po(this,this.components,"Scene")),e(this,"_defaultConfig",{backgroundColor:new o.Color(2107698),directionalLight:{color:new o.Color("white"),intensity:1.5,position:new o.Vector3(5,10,3)},ambientLight:{color:new o.Color("white"),intensity:1}}),this.three=new o.Scene,this.three.background=new o.Color(2107698)}setup(t){const e={...this._defaultConfig,...t};this.config.backgroundColor=e.backgroundColor;const i=e.ambientLight;this.config.ambientLight.color=i.color,this.config.ambientLight.intensity=i.intensity;const n=e.directionalLight;this.config.directionalLight.color=n.color,this.config.directionalLight.intensity=n.intensity,this.config.directionalLight.position=n.position,this.deleteAllLights();const{color:s,intensity:r}=this.config.directionalLight,a=new o.DirectionalLight(s,r);a.position.copy(n.position);const{color:l,intensity:c}=this.config.directionalLight,h=new o.AmbientLight(l,c);this.three.add(a,h),this.directionalLights.set(a.uuid,a),this.ambientLights.set(h.uuid,h),this.isSetup=!0,this.onSetup.trigger()}dispose(){super.dispose();this.components.get(je).list.delete(this.config.uuid)}}var Io=(t=>(t[t.MANUAL=0]="MANUAL",t[t.AUTO=1]="AUTO",t))(Io||{});class Do extends pt{constructor(t,i,n){super(t),e(this,"enabled",!0),e(this,"container"),e(this,"three"),e(this,"mode",1),e(this,"needsUpdate",!1),e(this,"_canvas"),e(this,"_parameters"),e(this,"_resizeObserver",null),e(this,"onContainerUpdated",new at),e(this,"_resizing",!1),e(this,"resize",t=>{if(this._resizing)return;this._resizing=!0,this.onContainerUpdated.trigger();const e=t?t.x:this.container.clientWidth,i=t?t.y:this.container.clientHeight;this.three.setSize(e,i),this.onResize.trigger(new o.Vector2(e,i)),this._resizing=!1}),e(this,"resizeEvent",()=>{this.resize()}),e(this,"onContextLost",t=>{t.preventDefault(),this.enabled=!1}),e(this,"onContextBack",()=>{this.three.setRenderTarget(null),this.three.dispose(),this.three=new o.WebGLRenderer({canvas:this._canvas,antialias:!0,alpha:!0,...this._parameters}),this.enabled=!0}),this.container=i,this._parameters=n,this.three=new o.WebGLRenderer({antialias:!0,alpha:!0,...n}),this.three.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.setupRenderer(),this.setupEvents(!0),this.resize(),this._canvas=this.three.domElement;const s=this.three.getContext(),{canvas:r}=s;r.addEventListener("webglcontextlost",this.onContextLost,!1),r.addEventListener("webglcontextrestored",this.onContextBack,!1)}update(){if(!this.enabled||!this.currentWorld)return;if(0===this.mode&&!this.needsUpdate)return;this.needsUpdate=!1,this.onBeforeUpdate.trigger(this);const t=this.currentWorld.scene.three,e=this.currentWorld.camera.three;this.three.render(t,e),this.onAfterUpdate.trigger(this)}dispose(){this.enabled=!1,this.setupEvents(!1),this.three.domElement.remove(),this.three.forceContextLoss(),this.three.dispose(),this.onResize.reset(),this.onAfterUpdate.reset(),this.onBeforeUpdate.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}getSize(){return new o.Vector2(this.three.domElement.clientWidth,this.three.domElement.clientHeight)}setupEvents(t){const e=this.three.domElement.parentElement;if(!e)throw new Error("This renderer needs to have an HTML container!");this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),window.removeEventListener("resize",this.resizeEvent),t&&(this._resizeObserver=new ResizeObserver(this.resizeEvent),this._resizeObserver.observe(e),window.addEventListener("resize",this.resizeEvent))}setupRenderer(){this.three.localClippingEnabled=!0,this.container&&this.container.appendChild(this.three.domElement),this.onContainerUpdated.trigger()}}class ko extends ut{constructor(t){super(t),e(this,"onBeforeUpdate",new at),e(this,"onAfterUpdate",new at),e(this,"onAspectUpdated",new at),e(this,"onDisposed",new at),e(this,"three"),e(this,"_resizeObserver",null),e(this,"_allControls",new Map),e(this,"updateAspect",()=>{var t;if(this.currentWorld&&this.currentWorld.renderer)if(this.three instanceof o.OrthographicCamera)this.onAspectUpdated.trigger();else if(null==(t=this.currentWorld.renderer)?void 0:t.isResizeable()){const t=this.currentWorld.renderer.getSize();this.three.aspect=t.width/t.height,this.three.updateProjectionMatrix(),this.onAspectUpdated.trigger()}}),this.three=this.setupCamera(),this.worlds.onItemSet.add(({value:t})=>{const e=this.newCameraControls();this.setupEvents(!0),this._allControls.set(t.uuid,e)}),this.worlds.onBeforeDelete.add(({value:t})=>{var e;const i=this._allControls.get(t.uuid);i&&(i.dispose(),this._allControls.delete(t.uuid)),null==(e=this._resizeObserver)||e.disconnect()})}get controls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");const t=this._allControls.get(this.currentWorld.uuid);if(!t)throw new Error("Controls not found!");return t}get enabled(){return null!==this.currentWorld&&this.controls.enabled}set enabled(t){null!==this.currentWorld&&(this.controls.enabled=t)}set currentWorld(t){if(super.currentWorld=t,!t)return;this.worlds.get(t.uuid)||this.worlds.set(t.uuid,t)}get currentWorld(){return this._currentWorld}dispose(){this.setupEvents(!1),this.onAspectUpdated.reset(),this.onBeforeUpdate.reset(),this.onAfterUpdate.reset(),this.three.removeFromParent(),this.onDisposed.trigger(),this.onDisposed.reset();for(const[t,e]of this._allControls)e.dispose();this.worlds.clear()}async fitToItems(t){const e=await this.getItemsBounding(t);await this.controls.fitToSphere(e,!0)}async setOrbitToItems(t){const e=await this.getItemsBounding(t);this.controls.setOrbitPoint(e.center.x,e.center.y,e.center.z)}update(t){this.enabled&&(this.onBeforeUpdate.trigger(this),this.controls.update(t),this.onAfterUpdate.trigger(this))}async getItemsBounding(t){const e=this.components.get(Ws),i=this.components.get(fo);i.list.clear();const n=new o.Sphere;if(t)await i.addFromModelIdMap(t);else for(const[,t]of e.list)i.list.add(t.box);return i.get().getBoundingSphere(n),i.list.clear(),n}setupCamera(){const t=window.innerWidth/window.innerHeight,e=new o.PerspectiveCamera(60,t,1,1e3);return e.position.set(50,50,50),e.lookAt(new o.Vector3(0,0,0)),e}newCameraControls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");if(!this.currentWorld.renderer)throw new Error("This camera needs a renderer to work!");rt.install({THREE:ko.getSubsetOfThree()});const{domElement:t}=this.currentWorld.renderer.three,e=new rt(this.three,t);return e.smoothTime=.2,e.dollyToCursor=!0,e.infinityDolly=!0,e.minDistance=6,e}setupEvents(t){if(this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),t){if(!this.currentWorld)throw new Error("This camera needs a world to work!");if(!this.currentWorld.renderer)throw new Error("This camera needs a renderer to work!");const{domElement:t}=this.currentWorld.renderer.three;this._resizeObserver=new ResizeObserver(this.updateAspect),this._resizeObserver.observe(t)}}static getSubsetOfThree(){return{MOUSE:o.MOUSE,Vector2:o.Vector2,Vector3:o.Vector3,Vector4:o.Vector4,Quaternion:o.Quaternion,Matrix4:o.Matrix4,Spherical:o.Spherical,Box3:o.Box3,Sphere:o.Sphere,Raycaster:o.Raycaster,MathUtils:o.MathUtils}}}const Bo=class t extends ht{constructor(i){super(i),e(this,"onAfterUpdate",new at),e(this,"onBeforeUpdate",new at),e(this,"onDisposed",new at),e(this,"list",new n),e(this,"enabled",!0),i.add(t.uuid,this)}create(){const t=new Ao(this.components),e=t.uuid;if(this.list.has(e))throw new Error("There is already a world with this name!");return this.list.set(e,t),t}delete(t){if(!this.list.has(t.uuid))throw new Error("The provided world is not found in the list!");this.list.delete(t.uuid),t.dispose()}dispose(){this.enabled=!1;for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}update(t){if(this.enabled)for(const[e,i]of this.list)i.update(t)}};e(Bo,"uuid","fdb61dc4-2ec1-4966-b83d-54ea795fad4a");let Oo=Bo;class Vo extends Re{constructor(){super(...arguments),e(this,"_config",{visible:{value:!0,type:"Boolean"},color:{value:new o.Color,type:"Color"},primarySize:{type:"Number",interpolable:!0,value:1,min:0,max:1e3},secondarySize:{type:"Number",interpolable:!0,value:10,min:0,max:1e3},distance:{type:"Number",interpolable:!0,value:500,min:0,max:500}})}get visible(){return this._config.visible.value}set visible(t){this._config.visible.value=t,this._component.visible=t}get color(){return this._config.color.value}set color(t){this._config.color.value=t,this._component.material.uniforms.uColor.value=t,this._component.material.uniformsNeedUpdate=!0}get primarySize(){return this._config.primarySize.value}set primarySize(t){this._config.primarySize.value=t,this._component.material.uniforms.uSize1.value=t,this._component.material.uniformsNeedUpdate=!0}get secondarySize(){return this._config.secondarySize.value}set secondarySize(t){this._config.secondarySize.value=t,this._component.material.uniforms.uSize2.value=t,this._component.material.uniformsNeedUpdate=!0}get distance(){return this._config.distance.value}set distance(t){this._config.distance.value=t,this._component.material.uniforms.uDistance.value=t,this._component.material.uniformsNeedUpdate=!0}}class Lo{constructor(t,i){e(this,"onDisposed",new at),e(this,"onSetup",new at),e(this,"isSetup",!1),e(this,"world"),e(this,"components"),e(this,"config"),e(this,"_defaultConfig",{visible:!0,color:new o.Color(12303291),primarySize:1,secondarySize:10,distance:500}),e(this,"three"),e(this,"_fade",3),e(this,"updateZoom",()=>{this.world.camera instanceof ko&&(this.material.uniforms.uZoom.value=this.world.camera.three.zoom)}),this.world=i;const{color:n,primarySize:s,secondarySize:r,distance:a}=this._defaultConfig;this.components=t,this.config=new Vo(this,this.components,"Grid");const l=new o.PlaneGeometry(2,2,1,1),c=new o.ShaderMaterial({side:o.DoubleSide,uniforms:{uSize1:{value:s},uSize2:{value:r},uColor:{value:n},uDistance:{value:a},uFade:{value:this._fade},uZoom:{value:1}},transparent:!0,vertexShader:"\n \n varying vec3 worldPosition;\n \n uniform float uDistance;\n \n void main() {\n \n vec3 pos = position.xzy * uDistance;\n pos.xz += cameraPosition.xz;\n \n worldPosition = pos;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);\n \n }\n ",fragmentShader:"\n \n varying vec3 worldPosition;\n \n uniform float uZoom;\n uniform float uFade;\n uniform float uSize1;\n uniform float uSize2;\n uniform vec3 uColor;\n uniform float uDistance;\n \n \n \n float getGrid(float size) {\n \n vec2 r = worldPosition.xz / size;\n \n \n vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);\n float line = min(grid.x, grid.y);\n \n \n return 1.0 - min(line, 1.0);\n }\n \n void main() {\n \n \n float d = 1.0 - min(distance(cameraPosition.xz, worldPosition.xz) / uDistance, 1.0);\n \n float g1 = getGrid(uSize1);\n float g2 = getGrid(uSize2);\n \n // Ortho camera fades the grid away when zooming out\n float minZoom = step(0.2, uZoom);\n float zoomFactor = pow(min(uZoom, 1.), 2.) * minZoom;\n \n gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, uFade));\n gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2) * zoomFactor;\n \n if ( gl_FragColor.a <= 0.0 ) discard;\n \n \n }\n \n ",extensions:{derivatives:!0}});this.three=new o.Mesh(l,c),this.three.frustumCulled=!1,i.scene.three.add(this.three),this.setupEvents(!0)}get visible(){return this.three.visible}set visible(t){if(this.three.visible=t,t){this.world.scene.three.add(this.three)}else this.three.removeFromParent()}get material(){return this.three.material}get fade(){return 3===this._fade}set fade(t){this._fade=t?3:0,this.material.uniforms.uFade.value=this._fade}setup(t){const e={...this._defaultConfig,...t};this.config.visible=!0,this.config.color=e.color,this.config.primarySize=e.primarySize,this.config.secondarySize=e.secondarySize,this.config.distance=e.distance,this.isSetup=!0,this.onSetup.trigger()}dispose(){this.setupEvents(!1);this.components.get(je).list.delete(this.config.uuid);this.components.get(mt).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset(),this.world=null,this.components=null}setupEvents(t){if(this.world.isDisposing)return;if(!(this.world.camera instanceof ko))return;const e=this.world.camera.controls;t?e.addEventListener("update",this.updateZoom):e.removeEventListener("update",this.updateZoom)}}const No=class t extends ht{constructor(i){super(i),e(this,"list",new Map),e(this,"onDisposed",new at),e(this,"enabled",!0),i.add(t.uuid,this)}create(t){if(this.list.has(t.uuid))throw new Error("This world already has a grid!");const e=new Lo(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add(()=>{this.delete(t)}),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};e(No,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");let Fo=No;const Ro=class t{constructor(){e(this,"onDisposed",new at),e(this,"list",new n),e(this,"enabled",!1),e(this,"_clock"),e(this,"onInit",new at),e(this,"update",()=>{if(!this.enabled)return;const t=this._clock.getDelta();for(const[e,i]of this.list)i.enabled&&i.isUpdateable()&&i.update(t);requestAnimationFrame(this.update)}),this._clock=new o.Clock,t.setupBVH()}add(t,e){if(this.list.has(t))throw new Error("You're trying to add a component that already exists in the components instance. Use Components.get() instead.");_t.validate(t),this.list.set(t,e)}get(t){var e;const i=t.uuid;if(!this.list.has(i)){const n=new t(this);return(null==(e=n.isDisposeable)?void 0:e.call(n))&&n.onDisposed.add(()=>this.list.delete(i)),this.list.has(i)||this.add(i,n),n}return this.list.get(i)}init(){this.enabled=!0;for(const[t,e]of this.list.entries())e.enabled=!0;this._clock.start(),this.update(),this.onInit.trigger()}dispose(){let t;this.enabled=!1;for(const[e,i]of this.list)i.enabled=!1,e!==Ws.uuid?i.isDisposeable()&&i.dispose():t=i;null==t||t.dispose(),this._clock.stop(),this.onDisposed.trigger()}static setupBVH(){o.BufferGeometry.prototype.computeBoundsTree=Us,o.BufferGeometry.prototype.disposeBoundsTree=js,o.Mesh.prototype.raycast=Fs,o.LineSegments.prototype.raycast=Fs}};e(Ro,"release","2.4.3");let Uo=Ro;class jo{constructor(t){e(this,"enabled",!1),e(this,"id","FirstPerson"),this.camera=t}set(t){if(this.enabled=t,t){if("Perspective"!==this.camera.projection.current)return void this.camera.set("Orbit");this.setupFirstPersonCamera()}}setupFirstPersonCamera(){const t=this.camera.controls,e=new o.Vector3;t.distance--,t.getPosition(e),t.minDistance=1,t.maxDistance=1,t.distance=1,t.moveTo(e.x,e.y,e.z),t.truckSpeed=50,t.mouseButtons.wheel=rt.ACTION.DOLLY,t.touches.two=rt.ACTION.TOUCH_ZOOM_TRUCK}}class $o{constructor(t){e(this,"enabled",!0),e(this,"id","Orbit"),this.camera=t,this.activateOrbitControls()}set(t){this.enabled=t,t&&this.activateOrbitControls()}activateOrbitControls(){const t=this.camera.controls;t.minDistance=1,t.maxDistance=300;const e=new o.Vector3;t.getPosition(e);const i=e.length();t.distance=i,t.truckSpeed=2;const{rotation:n}=this.camera.three,s=new o.Vector3(0,0,-1).applyEuler(n),r=e.addScaledVector(s,i);t.moveTo(r.x,r.y,r.z)}}class Wo{constructor(t){e(this,"enabled",!1),e(this,"id","Plan"),e(this,"mouseAction1"),e(this,"mouseAction2"),e(this,"mouseInitialized",!1),e(this,"defaultAzimuthSpeed"),e(this,"defaultPolarSpeed"),this.camera=t,this.defaultAzimuthSpeed=t.controls.azimuthRotateSpeed,this.defaultPolarSpeed=t.controls.polarRotateSpeed}set(t){this.enabled=t;const e=this.camera.controls;e.azimuthRotateSpeed=t?0:this.defaultAzimuthSpeed,e.polarRotateSpeed=t?0:this.defaultPolarSpeed,this.mouseInitialized||(this.mouseAction1=e.touches.one,this.mouseAction2=e.touches.two,this.mouseInitialized=!0),t?(e.mouseButtons.left=rt.ACTION.TRUCK,e.touches.one=rt.ACTION.TOUCH_TRUCK,e.touches.two=rt.ACTION.TOUCH_ZOOM):(e.mouseButtons.left=rt.ACTION.ROTATE,e.touches.one=this.mouseAction1,e.touches.two=this.mouseAction2)}}class Go{constructor(t){e(this,"onChanged",new at),e(this,"current","Perspective"),e(this,"camera"),e(this,"matchOrthoDistanceEnabled",!1),e(this,"_component"),e(this,"_previousDistance",-1),this._component=t,this.camera=t.three}async set(t){this.current!==t&&("Orthographic"===t?this.setOrthoCamera():await this.setPerspectiveCamera(),this.onChanged.trigger(this.camera))}async toggle(){const t="Perspective"===this.current?"Orthographic":"Perspective";await this.set(t)}setOrthoCamera(){if(null===this._component.mode)return;if("FirstPerson"===this._component.mode.id)return;this._previousDistance=this._component.controls.distance,this._component.controls.distance=200;const t=this.getPerspectiveDims();if(!t)return;const{width:e,height:i}=t;this.setupOrthoCamera(i,e),this.camera=this._component.threeOrtho,this.current="Orthographic"}getPerspectiveDims(){const t=this._component.currentWorld;if(!t||!t.renderer)return null;const e=new o.Vector3;this._component.threePersp.getWorldDirection(e);const i=new o.Vector3;this._component.controls.getTarget(i);const n=i.clone().sub(this._component.threePersp.position).dot(e),s=t.renderer.getSize(),r=s.x/s.y,a=this._component.threePersp,l=2*n*Math.atan(a.fov*(Math.PI/180)/2);return{width:l*r,height:l}}setupOrthoCamera(t,e){this._component.controls.mouseButtons.wheel=rt.ACTION.ZOOM,this._component.controls.mouseButtons.middle=rt.ACTION.ZOOM;const i=this._component.threePersp,n=this._component.threeOrtho;n.zoom=1,n.left=e/-2,n.right=e/2,n.top=t/2,n.bottom=t/-2,n.updateProjectionMatrix(),n.position.copy(i.position),n.quaternion.copy(i.quaternion),this._component.controls.camera=n}getDistance(){const t=this._component.threePersp,e=this._component.threeOrtho;return(e.top-e.bottom)/e.zoom/(2*Math.atan(t.fov*(Math.PI/180)/2))}async setPerspectiveCamera(){this._component.controls.mouseButtons.wheel=rt.ACTION.DOLLY,this._component.controls.mouseButtons.middle=rt.ACTION.DOLLY;const t=this._component.threePersp,e=this._component.threeOrtho;t.position.copy(e.position),t.quaternion.copy(e.quaternion),this._component.controls.mouseButtons.wheel=rt.ACTION.DOLLY,this.matchOrthoDistanceEnabled?this._component.controls.distance=this.getDistance():this._component.controls.distance=this._previousDistance,await this._component.controls.zoomTo(1),t.updateProjectionMatrix(),this._component.controls.camera=t,this.camera=t,this.current="Perspective"}}class Ho extends ko{constructor(t){super(t),e(this,"projection"),e(this,"threeOrtho"),e(this,"threePersp"),e(this,"_userInputButtons",{}),e(this,"_frustumSize",50),e(this,"_navigationModes",new Map),e(this,"_mode",null),e(this,"previousSize",null),this.threePersp=this.three,this.threeOrtho=this.newOrthoCamera(),this.projection=new Go(this),this.onAspectUpdated.add(()=>{this.setOrthoPerspCameraAspect()}),this.projection.onChanged.add(t=>{this.three=t,this.updateAspect()}),this.worlds.onItemSet.add(()=>{this._navigationModes.clear(),this._navigationModes.set("Orbit",new $o(this)),this._navigationModes.set("FirstPerson",new jo(this)),this._navigationModes.set("Plan",new Wo(this)),this._mode=this._navigationModes.get("Orbit"),this.mode.set(!0,{preventTargetAdjustment:!0}),this.currentWorld&&this.currentWorld.renderer&&(this.previousSize=this.currentWorld.renderer.getSize().clone())}),this.worlds.onItemDeleted.add(()=>{this._navigationModes.clear()})}get mode(){if(!this._mode)throw new Error("Mode not found, camera not initialized");return this._mode}dispose(){super.dispose(),this.threeOrtho.removeFromParent()}set(t){if(null!==this.mode&&this.mode.id!==t){if(this.mode.set(!1),!this._navigationModes.has(t))throw new Error("The specified mode does not exist!");this._mode=this._navigationModes.get(t),this.mode.set(!0)}}async fit(t,e=1.5){if(!this.enabled)return;const i=Number.MAX_VALUE,n=Number.MIN_VALUE,s=new o.Vector3(i,i,i),r=new o.Vector3(n,n,n);for(const e of t){const t=(new o.Box3).setFromObject(e);t.min.x<s.x&&(s.x=t.min.x),t.min.y<s.y&&(s.y=t.min.y),t.min.z<s.z&&(s.z=t.min.z),t.max.x>r.x&&(r.x=t.max.x),t.max.y>r.y&&(r.y=t.max.y),t.max.z>r.z&&(r.z=t.max.z)}const a=new o.Box3(s,r),l=this.components.get(Ws);if(l.initialized)for(const[,t]of l.list){const e=t.box;e.min.x<s.x&&(s.x=e.min.x),e.min.y<s.y&&(s.y=e.min.y),e.min.z<s.z&&(s.z=e.min.z),e.max.x>r.x&&(r.x=e.max.x),e.max.y>r.y&&(r.y=e.max.y),e.max.z>r.z&&(r.z=e.max.z)}const c=new o.Vector3;a.getSize(c);const h=new o.Vector3;a.getCenter(h);const d=Math.max(c.x,c.y,c.z)*e,u=new o.Sphere(h,d);await this.controls.fitToSphere(u,!0)}setUserInput(t){t?this.enableUserInput():this.disableUserInput()}addCustomNavigationMode(t){this._navigationModes.set(t.id,t)}disableUserInput(){this._userInputButtons.left=this.controls.mouseButtons.left,this._userInputButtons.right=this.controls.mouseButtons.right,this._userInputButtons.middle=this.controls.mouseButtons.middle,this._userInputButtons.wheel=this.controls.mouseButtons.wheel,this.controls.mouseButtons.left=0,this.controls.mouseButtons.right=0,this.controls.mouseButtons.middle=0,this.controls.mouseButtons.wheel=0}enableUserInput(){0!==Object.keys(this._userInputButtons).length&&(this.controls.mouseButtons.left=this._userInputButtons.left,this.controls.mouseButtons.right=this._userInputButtons.right,this.controls.mouseButtons.middle=this._userInputButtons.middle,this.controls.mouseButtons.wheel=this._userInputButtons.wheel)}newOrthoCamera(){const t=window.innerWidth/window.innerHeight;return new o.OrthographicCamera(this._frustumSize*t/-2,this._frustumSize*t/2,this._frustumSize/2,this._frustumSize/-2,.1,1e3)}setOrthoPerspCameraAspect(){if(!this.currentWorld||!this.currentWorld.renderer)return;if(!this.previousSize)return;const t=this.currentWorld.renderer.getSize(),e=this.threeOrtho.top,i=this.threeOrtho.right,n=e*(t.y/this.previousSize.y),s=i*(t.x/this.previousSize.x);this.threeOrtho.left=-s,this.threeOrtho.right=s,this.threeOrtho.top=n,this.threeOrtho.bottom=-n,this.threeOrtho.updateProjectionMatrix(),this.previousSize.copy(t)}}var qo="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Zo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Yo(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Xo={exports:{}};
1
+ var t=Object.defineProperty,e=(e,i,n)=>(((e,i,n)=>{i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[i]=n})(e,"symbol"!=typeof i?i+"":i,n),n);import*as i from"@thatopen/fragments";import{DataMap as n,FragmentsModels as s,DataSet as r}from"@thatopen/fragments";import*as o from"three";import{Box3 as a,Matrix4 as l,BufferAttribute as c,Vector3 as h,Vector2 as u,Plane as d,Line3 as p,Triangle as f,REVISION as m,BackSide as g,DoubleSide as w,FrontSide as y,Ray as _,Mesh as b,Line as v,LineSegments as x,LineLoop as C,Points as S,BatchedMesh as A,Sphere as P,OrthographicCamera as T,WebGLRenderTarget as E,Scene as M,Color as I,ShaderMaterial as z,GLSL3 as D,NoBlending as k,Vector4 as B,MathUtils as O,BufferGeometry as N}from"three";import*as V from"three/webgpu";import{instancedArray as L,Fn as F,mat4 as R,Loop as U,int as j,vec3 as $,vec4 as W,float as G,cross as H,If as Z,Continue as q,max as Y,min as X,normalize as K,select as Q,abs as J,mix as tt,uint as et,atomicAdd as it,instanceIndex as nt}from"three/tsl";import*as st from"web-ifc";import rt from"camera-controls";import{TransformControls as ot}from"three/examples/jsm/controls/TransformControls.js";class at{constructor(){e(this,"enabled",!0),e(this,"trigger",(t=>{if(!this.enabled)return;const e=this.handlers.slice(0);for(const i of e)i(t)})),e(this,"handlers",[])}add(t){this.handlers.push(t)}remove(t){this.handlers=this.handlers.filter((e=>e!==t))}reset(){this.handlers.length=0}}class lt{constructor(){e(this,"enabled",!0),e(this,"trigger",(async t=>{if(!this.enabled)return;const e=this.handlers.slice(0);for(const i of e)await i(t)})),e(this,"handlers",[])}add(t){this.handlers.push(t)}remove(t){this.handlers=this.handlers.filter((e=>e!==t))}reset(){this.handlers.length=0}}class ct{constructor(t){e(this,"isDisposeable",(()=>"dispose"in this&&"onDisposed"in this)),e(this,"isResizeable",(()=>"resize"in this&&"getSize"in this)),e(this,"isUpdateable",(()=>"onAfterUpdate"in this&&"onBeforeUpdate"in this&&"update"in this)),e(this,"isHideable",(()=>"visible"in this)),e(this,"isConfigurable",(()=>"setup"in this&&"config"in this&&"onSetup"in this)),e(this,"isSerializable",(()=>"import"in this&&"export"in this)),this.components=t}}class ht extends ct{}class ut extends ct{constructor(t){super(t),e(this,"worlds",new n),e(this,"onWorldChanged",new at),e(this,"_currentWorld",null),this.onWorldChanged.add((({world:t,action:e})=>{"removed"===e&&this.worlds.delete(t.uuid)}))}set currentWorld(t){this._currentWorld=t}get currentWorld(){return this._currentWorld}}class dt extends ut{constructor(){super(...arguments),e(this,"hasCameraControls",(()=>"controls"in this))}}class pt extends ut{constructor(){super(...arguments),e(this,"onAfterUpdate",new at),e(this,"onBeforeUpdate",new at),e(this,"onDisposed",new at),e(this,"onResize",new at),e(this,"onClippingPlanesUpdated",new at),e(this,"clippingPlanes",[])}updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(t,e,i){e.isLocal=i;const n=this.clippingPlanes.indexOf(e);t&&-1===n?this.clippingPlanes.push(e):!t&&n>-1&&this.clippingPlanes.splice(n,1),this.three.clippingPlanes=this.clippingPlanes.filter((t=>!t.isLocal))}}const ft=class t extends ht{constructor(i){super(i),e(this,"_disposedComponents",new Set),e(this,"enabled",!0),i.add(t.uuid,this)}get(){return this._disposedComponents}destroy(t,e=!0,i=!0){t.removeFromParent();const n=t;n.dispose&&n.dispose(),this.disposeGeometryAndMaterials(t,e),i&&n.children&&n.children.length&&this.disposeChildren(n),t.children.length=0}disposeGeometry(t){t.boundsTree&&t.disposeBoundsTree&&t.disposeBoundsTree(),t.dispose()}disposeGeometryAndMaterials(e,i){const n=e;n.geometry&&this.disposeGeometry(n.geometry),i&&n.material&&t.disposeMaterial(n),n.material=[],n.geometry=null}disposeChildren(t){for(const e of t.children)this.destroy(e)}static disposeMaterial(t){if(t.material)if(Array.isArray(t.material))for(const e of t.material)e.dispose();else t.material.dispose()}};e(ft,"uuid","76e9cd8e-ad8f-4753-9ef6-cbc60f7247fe");let mt=ft;class gt extends ut{constructor(t){super(t),e(this,"onDisposed",new at),e(this,"directionalLights",new Map),e(this,"ambientLights",new Map)}dispose(){const t=this.components.get(mt);for(const e of this.three.children){const i=e;i.geometry&&t.destroy(i)}this.deleteAllLights(),this.three.children=[],this.onDisposed.trigger(),this.onDisposed.reset()}deleteAllLights(){for(const[,t]of this.directionalLights)t.removeFromParent(),t.target.removeFromParent(),t.dispose();this.directionalLights.clear();for(const[,t]of this.ambientLights)t.removeFromParent(),t.dispose();this.ambientLights.clear()}}class wt extends Set{constructor(t){super(t),e(this,"onItemAdded",new at),e(this,"onItemDeleted",new at),e(this,"onCleared",new at),e(this,"guard",(()=>!0))}clear(){super.clear(),this.onCleared.trigger()}add(...t){for(const e of t){if(this.has(e))continue;this.guard(e)&&(super.add(e),this.onItemAdded||(this.onItemAdded=new at),this.onItemAdded.trigger(e))}return this}delete(t){const e=super.delete(t);return e&&this.onItemDeleted.trigger(),e}dispose(){this.clear(),this.onItemAdded.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}const yt=class t{static create(){const e=4294967295*Math.random()|0,i=4294967295*Math.random()|0,n=4294967295*Math.random()|0,s=4294967295*Math.random()|0;return`${t._lut[255&e]+t._lut[e>>8&255]+t._lut[e>>16&255]+t._lut[e>>24&255]}-${t._lut[255&i]}${t._lut[i>>8&255]}-${t._lut[i>>16&15|64]}${t._lut[i>>24&255]}-${t._lut[63&n|128]}${t._lut[n>>8&255]}-${t._lut[n>>16&255]}${t._lut[n>>24&255]}${t._lut[255&s]}${t._lut[s>>8&255]}${t._lut[s>>16&255]}${t._lut[s>>24&255]}`.toLowerCase()}static validate(e){if(!t._pattern.test(e))throw new Error(`${e} is not a valid UUID v4.\n\n- If you're the tool creator, you can take one from https://www.uuidgenerator.net/.\n\n- If you're using a platform tool, verify the uuid isn't misspelled or contact the tool creator.`)}};e(yt,"_pattern",/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/),e(yt,"_lut",["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"]);let _t=yt;const bt=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",vt=new RegExp("^"+("["+bt+"]["+(bt+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*")+"$");function xt(t,e){const i=[];let n=e.exec(t);for(;n;){const s=[];s.startIndex=e.lastIndex-n[0].length;const r=n.length;for(let t=0;t<r;t++)s.push(n[t]);i.push(s),n=e.exec(t)}return i}const Ct=function(t){const e=vt.exec(t);return!(null==e)};const St=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],At=["__proto__","constructor","prototype"],Pt={allowBooleanAttributes:!1,unpairedTags:[]};function Tt(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function Et(t,e){const i=e;for(;e<t.length;e++)if("?"!=t[e]&&" "!=t[e]);else{const n=t.substr(i,e-i);if(e>5&&"xml"===n)return Nt("InvalidXml","XML declaration allowed only at the start of the document.",Lt(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}}return e}function Mt(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e<t.length;e++)if("-"===t[e]&&"-"===t[e+1]&&">"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let i=1;for(e+=8;e<t.length;e++)if("<"===t[e])i++;else if(">"===t[e]&&(i--,0===i))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e<t.length;e++)if("]"===t[e]&&"]"===t[e+1]&&">"===t[e+2]){e+=2;break}return e}const It='"',zt="'";function Dt(t,e){let i="",n="",s=!1;for(;e<t.length;e++){if(t[e]===It||t[e]===zt)""===n?n=t[e]:n!==t[e]||(n="");else if(">"===t[e]&&""===n){s=!0;break}i+=t[e]}return""===n&&{value:i,index:e,tagClosed:s}}const kt=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function Bt(t,e){const i=xt(t,kt),n={};for(let t=0;t<i.length;t++){if(0===i[t][1].length)return Nt("InvalidAttr","Attribute '"+i[t][2]+"' has no space in starting.",Ft(i[t]));if(void 0!==i[t][3]&&void 0===i[t][4])return Nt("InvalidAttr","Attribute '"+i[t][2]+"' is without value.",Ft(i[t]));if(void 0===i[t][3]&&!e.allowBooleanAttributes)return Nt("InvalidAttr","boolean attribute '"+i[t][2]+"' is not allowed.",Ft(i[t]));const s=i[t][2];if(!Vt(s))return Nt("InvalidAttr","Attribute '"+s+"' is an invalid name.",Ft(i[t]));if(Object.prototype.hasOwnProperty.call(n,s))return Nt("InvalidAttr","Attribute '"+s+"' is repeated.",Ft(i[t]));n[s]=1}return!0}function Ot(t,e){if(";"===t[++e])return-1;if("#"===t[e])return function(t,e){let i=/\d/;for("x"===t[e]&&(e++,i=/[\da-fA-F]/);e<t.length;e++){if(";"===t[e])return e;if(!t[e].match(i))break}return-1}(t,++e);let i=0;for(;e<t.length;e++,i++)if(!(t[e].match(/\w/)&&i<20)){if(";"===t[e])break;return-1}return e}function Nt(t,e,i){return{err:{code:t,msg:e,line:i.line||i,col:i.col}}}function Vt(t){return Ct(t)}function Lt(t,e){const i=t.substring(0,e).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function Ft(t){return t.startIndex+t[1].length}const Rt={cent:"¢",pound:"£",curren:"¤",yen:"¥",euro:"€",dollar:"$",euro:"€",fnof:"ƒ",inr:"₹",af:"؋",birr:"ብር",peso:"₱",rub:"₽",won:"₩",yuan:"¥",cedil:"¸"},Ut={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},jt={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},$t=new Set("!?\\\\/[]$%{}^&*()<>|+");function Wt(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if($t.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function Gt(...t){const e=Object.create(null);for(const i of t)if(i)for(const t of Object.keys(i)){const n=i[t];if("string"==typeof n)e[t]=n;else if(n&&"object"==typeof n&&void 0!==n.val){const i=n.val;"string"==typeof i&&(e[t]=i)}}return e}const Ht="external",Zt="base",qt="all";const Yt=Object.freeze({allow:0,leave:1,remove:2,throw:3}),Xt=new Set([9,10,13]);class Kt{constructor(t={}){var e;this._limit=t.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof t.postCheck?t.postCheck:t=>t,this._limitTiers=(e=this._limit.applyLimitsTo??Ht)&&e!==Ht?e===qt?new Set([qt]):e===Zt?new Set([Zt]):Array.isArray(e)?new Set(e):new Set([Ht]):new Set([Ht]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=Gt(Ut,t.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(t.remove&&Array.isArray(t.remove)?t.remove:[]),this._leaveSet=new Set(t.leave&&Array.isArray(t.leave)?t.leave:[]);const i=function(t){if(!t)return{xmlVersion:1,onLevel:Yt.allow,nullLevel:Yt.remove};const e=1.1===t.xmlVersion?1.1:1,i=Yt[t.onNCR]??Yt.allow,n=Yt[t.nullNCR]??Yt.remove;return{xmlVersion:e,onLevel:i,nullLevel:Math.max(n,Yt.remove)}}(t.ncr);this._ncrXmlVersion=i.xmlVersion,this._ncrOnLevel=i.onLevel,this._ncrNullLevel=i.nullLevel}setExternalEntities(t){if(t)for(const e of Object.keys(t))Wt(e);this._externalMap=Gt(t)}addExternalEntity(t,e){Wt(t),"string"==typeof e&&-1===e.indexOf("&")&&(this._externalMap[t]=e)}addInputEntities(t){this._totalExpansions=0,this._expandedLength=0,this._inputMap=Gt(t)}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(t){this._ncrXmlVersion=1.1===t?1.1:1}decode(t){if("string"!=typeof t||0===t.length)return t;const e=t,i=[],n=t.length;let s=0,r=0;const o=this._maxTotalExpansions>0,a=this._maxExpandedLength>0,l=o||a;for(;r<n;){if(38!==t.charCodeAt(r)){r++;continue}let e=r+1;for(;e<n&&59!==t.charCodeAt(e)&&e-r<=32;)e++;if(e>=n||59!==t.charCodeAt(e)){r++;continue}const c=t.slice(r+1,e);if(0===c.length){r++;continue}let h,u;if(this._removeSet.has(c))h="",void 0===u&&(u=Ht);else{if(this._leaveSet.has(c)){r++;continue}if(35===c.charCodeAt(0)){const t=this._resolveNCR(c);if(void 0===t){r++;continue}h=t,u=Zt}else{const t=this._resolveName(c);h=null==t?void 0:t.value,u=null==t?void 0:t.tier}}if(void 0!==h){if(r>s&&i.push(t.slice(s,r)),i.push(h),s=e+1,r=s,l&&this._tierCounts(u)){if(o&&(this._totalExpansions++,this._totalExpansions>this._maxTotalExpansions))throw new Error(`[EntityReplacer] Entity expansion count limit exceeded: ${this._totalExpansions} > ${this._maxTotalExpansions}`);if(a){const t=h.length-(c.length+2);if(t>0&&(this._expandedLength+=t,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else r++}s<n&&i.push(t.slice(s));const c=0===i.length?t:i.join("");return this._postCheck(c,e)}_tierCounts(t){return!!this._limitTiers.has(qt)||this._limitTiers.has(t)}_resolveName(t){return t in this._inputMap?{value:this._inputMap[t],tier:Ht}:t in this._externalMap?{value:this._externalMap[t],tier:Ht}:t in this._baseMap?{value:this._baseMap[t],tier:Zt}:void 0}_classifyNCR(t){return 0===t?this._ncrNullLevel:t>=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!Xt.has(t)?Yt.remove:-1}_applyNCRAction(t,e,i){switch(t){case Yt.allow:return String.fromCodePoint(i);case Yt.remove:return"";case Yt.leave:return;case Yt.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${e}; (U+${i.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(i)}}_resolveNCR(t){const e=t.charCodeAt(1);let i;if(i=120===e||88===e?parseInt(t.slice(2),16):parseInt(t.slice(1),10),Number.isNaN(i)||i<0||i>1114111)return;const n=this._classifyNCR(i);if(!this._numericAllowed&&n<Yt.remove)return;const s=-1===n?this._ncrOnLevel:Math.max(this._ncrOnLevel,n);return this._applyNCRAction(s,t,i)}}const Qt=t=>St.includes(t)?"__"+t:t,Jt={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,entityDecoder:null,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,i){return t},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:Qt};function te(t,e){if("string"!=typeof t)return;const i=t.toLowerCase();if(St.some((t=>i===t.toLowerCase())))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);if(At.some((t=>i===t.toLowerCase())))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`)}function ee(t,e){return"boolean"==typeof t?{enabled:t,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:"object"==typeof t&&null!==t?{enabled:!1!==t.enabled,maxEntitySize:Math.max(1,t.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,t.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,t.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,t.maxExpandedLength??1e5),maxEntityCount:Math.max(1,t.maxEntityCount??1e3),allowedTags:t.allowedTags??null,tagFilter:t.tagFilter??null,appliesTo:t.appliesTo??"all"}:ee(!0)}const ie=function(t){const e=Object.assign({},Jt,t),i=[{value:e.attributeNamePrefix,name:"attributeNamePrefix"},{value:e.attributesGroupName,name:"attributesGroupName"},{value:e.textNodeName,name:"textNodeName"},{value:e.cdataPropName,name:"cdataPropName"},{value:e.commentPropName,name:"commentPropName"}];for(const{value:t,name:e}of i)t&&te(t,e);return null===e.onDangerousProperty&&(e.onDangerousProperty=Qt),e.processEntities=ee(e.processEntities,e.htmlEntities),e.unpairedTagsSet=new Set(e.unpairedTags),e.stopNodes&&Array.isArray(e.stopNodes)&&(e.stopNodes=e.stopNodes.map((t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t))),e};let ne;ne="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class se{constructor(t){this.tagname=t,this.child=[],this[":@"]=Object.create(null)}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t,e){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child}),void 0!==e&&(this.child[this.child.length-1][ne]={startIndex:e})}static getMetaDataSymbol(){return ne}}class re{constructor(t){this.suppressValidationErr=!t,this.options=t}readDocType(t,e){const i=Object.create(null);let n=0;if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let s=1,r=!1,o=!1,a="";for(;e<t.length;e++)if("<"!==t[e]||o)if(">"===t[e]){if(o?"-"===t[e-1]&&"-"===t[e-2]&&(o=!1,s--):s--,0===s)break}else"["===t[e]?r=!0:a+=t[e];else{if(r&&ae(t,"!ENTITY",e)){let s,r;if(e+=7,[s,r,e]=this.readEntityExp(t,e+1,this.suppressValidationErr),-1===r.indexOf("&")){if(!1!==this.options.enabled&&null!=this.options.maxEntityCount&&n>=this.options.maxEntityCount)throw new Error(`Entity count (${n+1}) exceeds maximum allowed (${this.options.maxEntityCount})`);i[s]=r,n++}}else if(r&&ae(t,"!ELEMENT",e)){e+=8;const{index:i}=this.readElementExp(t,e+1);e=i}else if(r&&ae(t,"!ATTLIST",e))e+=8;else if(r&&ae(t,"!NOTATION",e)){e+=9;const{index:i}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=i}else{if(!ae(t,"!--",e))throw new Error("Invalid DOCTYPE");o=!0}s++,a=""}if(0!==s)throw new Error("Unclosed DOCTYPE")}return{entities:i,i:e}}readEntityExp(t,e){const i=e=oe(t,e);for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;let n=t.substring(i,e);if(le(n),e=oe(t,e),!this.suppressValidationErr){if("SYSTEM"===t.substring(e,e+6).toUpperCase())throw new Error("External entities are not supported");if("%"===t[e])throw new Error("Parameter entities are not supported")}let s="";if([e,s]=this.readIdentifierVal(t,e,"entity"),!1!==this.options.enabled&&null!=this.options.maxEntitySize&&s.length>this.options.maxEntitySize)throw new Error(`Entity "${n}" size (${s.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[n,s,--e]}readNotationExp(t,e){const i=e=oe(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let n=t.substring(i,e);!this.suppressValidationErr&&le(n),e=oe(t,e);const s=t.substring(e,e+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==s&&"PUBLIC"!==s)throw new Error(`Expected SYSTEM or PUBLIC, found "${s}"`);e+=s.length,e=oe(t,e);let r=null,o=null;if("PUBLIC"===s)[e,r]=this.readIdentifierVal(t,e,"publicIdentifier"),'"'!==t[e=oe(t,e)]&&"'"!==t[e]||([e,o]=this.readIdentifierVal(t,e,"systemIdentifier"));else if("SYSTEM"===s&&([e,o]=this.readIdentifierVal(t,e,"systemIdentifier"),!this.suppressValidationErr&&!o))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:n,publicIdentifier:r,systemIdentifier:o,index:--e}}readIdentifierVal(t,e,i){let n="";const s=t[e];if('"'!==s&&"'"!==s)throw new Error(`Expected quoted string, found "${s}"`);const r=++e;for(;e<t.length&&t[e]!==s;)e++;if(n=t.substring(r,e),t[e]!==s)throw new Error(`Unterminated ${i} value`);return[++e,n]}readElementExp(t,e){const i=e=oe(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let n=t.substring(i,e);if(!this.suppressValidationErr&&!Ct(n))throw new Error(`Invalid element name: "${n}"`);let s="";if("E"===t[e=oe(t,e)]&&ae(t,"MPTY",e))e+=4;else if("A"===t[e]&&ae(t,"NY",e))e+=2;else if("("===t[e]){const i=++e;for(;e<t.length&&")"!==t[e];)e++;if(s=t.substring(i,e),")"!==t[e])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${t[e]}"`);return{elementName:n,contentModel:s.trim(),index:e}}readAttlistExp(t,e){let i=e=oe(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let n=t.substring(i,e);for(le(n),i=e=oe(t,e);e<t.length&&!/\s/.test(t[e]);)e++;let s=t.substring(i,e);if(!le(s))throw new Error(`Invalid attribute name: "${s}"`);e=oe(t,e);let r="";if("NOTATION"===t.substring(e,e+8).toUpperCase()){if(r="NOTATION","("!==t[e=oe(t,e+=8)])throw new Error(`Expected '(', found "${t[e]}"`);e++;let i=[];for(;e<t.length&&")"!==t[e];){const n=e;for(;e<t.length&&"|"!==t[e]&&")"!==t[e];)e++;let s=t.substring(n,e);if(s=s.trim(),!le(s))throw new Error(`Invalid notation name: "${s}"`);i.push(s),"|"===t[e]&&(e++,e=oe(t,e))}if(")"!==t[e])throw new Error("Unterminated list of notations");e++,r+=" ("+i.join("|")+")"}else{const i=e;for(;e<t.length&&!/\s/.test(t[e]);)e++;r+=t.substring(i,e);const n=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!n.includes(r.toUpperCase()))throw new Error(`Invalid attribute type: "${r}"`)}e=oe(t,e);let o="";return"#REQUIRED"===t.substring(e,e+8).toUpperCase()?(o="#REQUIRED",e+=8):"#IMPLIED"===t.substring(e,e+7).toUpperCase()?(o="#IMPLIED",e+=7):[e,o]=this.readIdentifierVal(t,e,"ATTLIST"),{elementName:n,attributeName:s,attributeType:r,defaultValue:o,index:e}}}const oe=(t,e)=>{for(;e<t.length&&/\s/.test(t[e]);)e++;return e};function ae(t,e,i){for(let n=0;n<e.length;n++)if(e[n]!==t[i+n+1])return!1;return!0}function le(t){if(Ct(t))return t;throw new Error(`Invalid entity name ${t}`)}const ce=/^[-+]?0x[a-fA-F0-9]+$/,he=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,ue={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original"};function de(t,e={}){if(e=Object.assign({},ue,e),!t||"string"!=typeof t)return t;let i=t.trim();if(0===i.length)return t;if(void 0!==e.skipLike&&e.skipLike.test(i))return t;if("0"===i)return 0;if(e.hex&&ce.test(i))return function(t,e){if(parseInt)return parseInt(t,e);if(Number.parseInt)return Number.parseInt(t,e);if(window&&window.parseInt)return window.parseInt(t,e);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(i,16);if(isFinite(i)){if(i.includes("e")||i.includes("E"))return function(t,e,i){if(!i.eNotation)return t;const n=e.match(pe);if(n){let s=n[1]||"";const r=-1===n[3].indexOf("e")?"E":"e",o=n[2],a=s?t[o.length+1]===r:t[o.length]===r;return o.length>1&&a?t:(1!==o.length||!n[3].startsWith(`.${r}`)&&n[3][0]!==r)&&o.length>0?i.leadingZeros&&!a?(e=(n[1]||"")+n[3],Number(e)):t:Number(e)}return t}(t,i,e);{const n=he.exec(i);if(n){const s=n[1]||"",r=n[2];let o=function(t){if(t&&-1!==t.indexOf("."))return"."===(t=t.replace(/0+$/,""))?t="0":"."===t[0]?t="0"+t:"."===t[t.length-1]&&(t=t.substring(0,t.length-1)),t;return t}(n[3]);const a=s?"."===t[r.length+1]:"."===t[r.length];if(!e.leadingZeros&&(r.length>1||1===r.length&&!a))return t;{const n=Number(i),a=String(n);if(0===n)return n;if(-1!==a.search(/[eE]/))return e.eNotation?n:t;if(-1!==i.indexOf("."))return"0"===a||a===o||a===`${s}${o}`?n:t;let l=r?o:i;return r?l===a||s+l===a?n:t:l===a||l===s+a?n:t}}return t}}return function(t,e,i){const n=e===1/0;switch(i.infinity.toLowerCase()){case"null":return null;case"infinity":return e;case"string":return n?"Infinity":"-Infinity";default:return t}}(t,Number(i),e)}const pe=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;class fe{constructor(t,e={},i){this.pattern=t,this.separator=e.separator||".",this.segments=this._parse(t),this.data=i,this._hasDeepWildcard=this.segments.some((t=>"deep-wildcard"===t.type)),this._hasAttributeCondition=this.segments.some((t=>void 0!==t.attrName)),this._hasPositionSelector=this.segments.some((t=>void 0!==t.position))}_parse(t){const e=[];let i=0,n="";for(;i<t.length;)t[i]===this.separator?i+1<t.length&&t[i+1]===this.separator?(n.trim()&&(e.push(this._parseSegment(n.trim())),n=""),e.push({type:"deep-wildcard"}),i+=2):(n.trim()&&e.push(this._parseSegment(n.trim())),n="",i++):(n+=t[i],i++);return n.trim()&&e.push(this._parseSegment(n.trim())),e}_parseSegment(t){const e={type:"tag"};let i=null,n=t;const s=t.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(s&&(n=s[1]+s[3],s[2])){const t=s[2].slice(1,-1);t&&(i=t)}let r,o,a=n;if(n.includes("::")){const e=n.indexOf("::");if(r=n.substring(0,e).trim(),a=n.substring(e+2).trim(),!r)throw new Error(`Invalid namespace in pattern: ${t}`)}let l=null;if(a.includes(":")){const t=a.lastIndexOf(":"),e=a.substring(0,t).trim(),i=a.substring(t+1).trim();["first","last","odd","even"].includes(i)||/^nth\(\d+\)$/.test(i)?(o=e,l=i):o=a}else o=a;if(!o)throw new Error(`Invalid segment pattern: ${t}`);if(e.tag=o,r&&(e.namespace=r),i)if(i.includes("=")){const t=i.indexOf("=");e.attrName=i.substring(0,t).trim(),e.attrValue=i.substring(t+1).trim()}else e.attrName=i.trim();if(l){const t=l.match(/^nth\((\d+)\)$/);t?(e.position="nth",e.positionValue=parseInt(t[1],10)):e.position=l}return e}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}}class me{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._patterns=new Set,this._sealed=!1}add(t){if(this._sealed)throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(t.pattern))return this;if(this._patterns.add(t.pattern),t.hasDeepWildcard())return this._deepWildcards.push(t),this;const e=t.length,i=t.segments[t.segments.length-1],n=null==i?void 0:i.tag;if(n&&"*"!==n){const i=`${e}:${n}`;this._byDepthAndTag.has(i)||this._byDepthAndTag.set(i,[]),this._byDepthAndTag.get(i).push(t)}else this._wildcardByDepth.has(e)||this._wildcardByDepth.set(e,[]),this._wildcardByDepth.get(e).push(t);return this}addAll(t){for(const e of t)this.add(e);return this}has(t){return this._patterns.has(t.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(t){return null!==this.findMatch(t)}findMatch(t){const e=t.getDepth(),i=`${e}:${t.getCurrentTag()}`,n=this._byDepthAndTag.get(i);if(n)for(let e=0;e<n.length;e++)if(t.matches(n[e]))return n[e];const s=this._wildcardByDepth.get(e);if(s)for(let e=0;e<s.length;e++)if(t.matches(s[e]))return s[e];for(let e=0;e<this._deepWildcards.length;e++)if(t.matches(this._deepWildcards[e]))return this._deepWildcards[e];return null}}class ge{constructor(t){this._matcher=t}get separator(){return this._matcher.separator}getCurrentTag(){const t=this._matcher.path;return t.length>0?t[t.length-1].tag:void 0}getCurrentNamespace(){const t=this._matcher.path;return t.length>0?t[t.length-1].namespace:void 0}getAttrValue(t){var e;const i=this._matcher.path;if(0!==i.length)return null==(e=i[i.length-1].values)?void 0:e[t]}hasAttr(t){const e=this._matcher.path;if(0===e.length)return!1;const i=e[e.length-1];return void 0!==i.values&&t in i.values}getPosition(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].position??0}getCounter(){const t=this._matcher.path;return 0===t.length?-1:t[t.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(t,e=!0){return this._matcher.toString(t,e)}toArray(){return this._matcher.path.map((t=>t.tag))}matches(t){return this._matcher.matches(t)}matchesAny(t){return t.matchesAny(this._matcher)}}class we{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new ge(this)}push(t,e=null,i=null){this._pathStringCache=null,this.path.length>0&&(this.path[this.path.length-1].values=void 0);const n=this.path.length;this.siblingStacks[n]||(this.siblingStacks[n]=new Map);const s=this.siblingStacks[n],r=i?`${i}:${t}`:t,o=s.get(r)||0;let a=0;for(const t of s.values())a+=t;s.set(r,o+1);const l={tag:t,position:a,counter:o};null!=i&&(l.namespace=i),null!=e&&(l.values=e),this.path.push(l)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const t=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),t}updateCurrent(t){if(this.path.length>0){const e=this.path[this.path.length-1];null!=t&&(e.values=t)}}getCurrentTag(){return this.path.length>0?this.path[this.path.length-1].tag:void 0}getCurrentNamespace(){return this.path.length>0?this.path[this.path.length-1].namespace:void 0}getAttrValue(t){var e;if(0!==this.path.length)return null==(e=this.path[this.path.length-1].values)?void 0:e[t]}hasAttr(t){if(0===this.path.length)return!1;const e=this.path[this.path.length-1];return void 0!==e.values&&t in e.values}getPosition(){return 0===this.path.length?-1:this.path[this.path.length-1].position??0}getCounter(){return 0===this.path.length?-1:this.path[this.path.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this.path.length}toString(t,e=!0){const i=t||this.separator;if(i===this.separator&&!0===e){if(null!==this._pathStringCache)return this._pathStringCache;const t=this.path.map((t=>t.namespace?`${t.namespace}:${t.tag}`:t.tag)).join(i);return this._pathStringCache=t,t}return this.path.map((t=>e&&t.namespace?`${t.namespace}:${t.tag}`:t.tag)).join(i)}toArray(){return this.path.map((t=>t.tag))}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(t){const e=t.segments;return 0!==e.length&&(t.hasDeepWildcard()?this._matchWithDeepWildcard(e):this._matchSimple(e))}_matchSimple(t){if(this.path.length!==t.length)return!1;for(let e=0;e<t.length;e++)if(!this._matchSegment(t[e],this.path[e],e===this.path.length-1))return!1;return!0}_matchWithDeepWildcard(t){let e=this.path.length-1,i=t.length-1;for(;i>=0&&e>=0;){const n=t[i];if("deep-wildcard"===n.type){if(i--,i<0)return!0;const n=t[i];let s=!1;for(let t=e;t>=0;t--)if(this._matchSegment(n,this.path[t],t===this.path.length-1)){e=t-1,i--,s=!0;break}if(!s)return!1}else{if(!this._matchSegment(n,this.path[e],e===this.path.length-1))return!1;e--,i--}}return i<0}_matchSegment(t,e,i){if("*"!==t.tag&&t.tag!==e.tag)return!1;if(void 0!==t.namespace&&"*"!==t.namespace&&t.namespace!==e.namespace)return!1;if(void 0!==t.attrName){if(!i)return!1;if(!e.values||!(t.attrName in e.values))return!1;if(void 0!==t.attrValue&&String(e.values[t.attrName])!==String(t.attrValue))return!1}if(void 0!==t.position){if(!i)return!1;const n=e.counter??0;if("first"===t.position&&0!==n)return!1;if("odd"===t.position&&n%2!=1)return!1;if("even"===t.position&&n%2!=0)return!1;if("nth"===t.position&&n!==t.positionValue)return!1}return!0}matchesAny(t){return t.matchesAny(this)}snapshot(){return{path:this.path.map((t=>({...t}))),siblingStacks:this.siblingStacks.map((t=>new Map(t)))}}restore(t){this._pathStringCache=null,this.path=t.path.map((t=>({...t}))),this.siblingStacks=t.siblingStacks.map((t=>new Map(t)))}readOnly(){return this._view}}function ye(t,e){if(!t)return{};const i=e.attributesGroupName?t[e.attributesGroupName]:t;if(!i)return{};const n={};for(const t in i)if(t.startsWith(e.attributeNamePrefix)){n[t.substring(e.attributeNamePrefix.length)]=i[t]}else n[t]=i[t];return n}function _e(t){if(!t||"string"!=typeof t)return;const e=t.indexOf(":");if(-1!==e&&e>0){const i=t.substring(0,e);if("xmlns"!==i)return i}}class be{constructor(t,e){var i;this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=Ae,this.parseTextData=ve,this.resolveNameSpace=xe,this.buildAttributesMap=Se,this.isItStopNode=Me,this.replaceEntitiesValue=Te,this.readStopNodeData=ke,this.saveTextToParentTag=Ee,this.addChild=Pe,this.ignoreAttributesFn="function"==typeof(i=this.options.ignoreAttributes)?i:Array.isArray(i)?t=>{for(const e of i){if("string"==typeof e&&t===e)return!0;if(e instanceof RegExp&&e.test(t))return!0}}:()=>!1,this.entityExpansionCount=0,this.currentExpandedLength=0;let n={...Ut};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?n=this.options.htmlEntities:!0===this.options.htmlEntities&&(n={...jt,...Rt}),this.entityDecoder=new Kt({namedEntities:{...n,...e},numericAllowed:this.options.htmlEntities,limit:{maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:this.options.processEntities.appliesTo}})),this.matcher=new we,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new me;const s=this.options.stopNodes;if(s&&s.length>0){for(let t=0;t<s.length;t++){const e=s[t];"string"==typeof e?this.stopNodeExpressionsSet.add(new fe(e)):e instanceof fe&&this.stopNodeExpressionsSet.add(e)}this.stopNodeExpressionsSet.seal()}}}function ve(t,e,i,n,s,r,o){const a=this.options;if(void 0!==t&&(a.trimValues&&!n&&(t=t.trim()),t.length>0)){o||(t=this.replaceEntitiesValue(t,e,i));const n=a.jPath?i.toString():i,l=a.tagValueProcessor(e,t,n,s,r);if(null==l)return t;if(typeof l!=typeof t||l!==t)return l;if(a.trimValues)return Be(t,a.parseTagValue,a.numberParseOptions);return t.trim()===t?Be(t,a.parseTagValue,a.numberParseOptions):t}}function xe(t){if(this.options.removeNSPrefix){const e=t.split(":"),i="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=i+e[1])}return t}const Ce=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function Se(t,e,i,n=!1){const s=this.options;if(!0===n||!0!==s.ignoreAttributes&&"string"==typeof t){const n=xt(t,Ce),r=n.length,o={},a=new Array(r);let l=!1;const c={};for(let t=0;t<r;t++){const e=this.resolveNameSpace(n[t][1]),r=n[t][4];if(e.length&&void 0!==r){let n=r;s.trimValues&&(n=n.trim()),n=this.replaceEntitiesValue(n,i,this.readonlyMatcher),a[t]=n,c[e]=n,l=!0}}l&&"object"==typeof e&&e.updateCurrent&&e.updateCurrent(c);const h=s.jPath?e.toString():this.readonlyMatcher;let u=!1;for(let t=0;t<r;t++){const e=this.resolveNameSpace(n[t][1]);if(this.ignoreAttributesFn(e,h))continue;let i=s.attributeNamePrefix+e;if(e.length)if(s.transformAttributeName&&(i=s.transformAttributeName(i)),i=Ne(i,s),void 0!==n[t][4]){const n=a[t],r=s.attributeValueProcessor(e,n,h);o[i]=null==r?n:typeof r!=typeof n||r!==n?r:Be(n,s.parseAttributeValue,s.numberParseOptions),u=!0}else s.allowBooleanAttributes&&(o[i]=!0,u=!0)}if(!u)return;if(s.attributesGroupName&&!s.preserveOrder){const t={};return t[s.attributesGroupName]=o,t}return o}}const Ae=function(t){t=t.replace(/\r\n?/g,"\n");const e=new se("!xml");let i=e,n="";this.matcher.reset(),this.entityDecoder.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;const s=this.options,r=new re(s.processEntities),o=t.length;for(let a=0;a<o;a++){if("<"===t[a]){const l=t.charCodeAt(a+1);if(47===l){const e=Ie(t,">",a,"Closing Tag is not closed.");let r=t.substring(a+2,e).trim();if(s.removeNSPrefix){const t=r.indexOf(":");-1!==t&&(r=r.substr(t+1))}r=Oe(s.transformTagName,r,"",s).tagName,i&&(n=this.saveTextToParentTag(n,i,this.readonlyMatcher));const o=this.matcher.getCurrentTag();if(r&&s.unpairedTagsSet.has(r))throw new Error(`Unpaired tag can not be used as closing tag: </${r}>`);o&&s.unpairedTagsSet.has(o)&&(this.matcher.pop(),this.tagsNodeStack.pop()),this.matcher.pop(),this.isCurrentNodeStopNode=!1,i=this.tagsNodeStack.pop(),n="",a=e}else if(63===l){let e=De(t,a,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");n=this.saveTextToParentTag(n,i,this.readonlyMatcher);const r=this.buildAttributesMap(e.tagExp,this.matcher,e.tagName,!0);if(r){const t=r[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(t)||1)}if(s.ignoreDeclaration&&"?xml"===e.tagName||s.ignorePiTags);else{const t=new se(e.tagName);t.add(s.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&!0!==s.ignoreAttributes&&(t[":@"]=r),this.addChild(i,t,this.readonlyMatcher,a)}a=e.closeIndex+1}else if(33===l&&45===t.charCodeAt(a+2)&&45===t.charCodeAt(a+3)){const e=Ie(t,"--\x3e",a+4,"Comment is not closed.");if(s.commentPropName){const r=t.substring(a+4,e-2);n=this.saveTextToParentTag(n,i,this.readonlyMatcher),i.add(s.commentPropName,[{[s.textNodeName]:r}])}a=e}else if(33===l&&68===t.charCodeAt(a+2)){const e=r.readDocType(t,a);this.entityDecoder.addInputEntities(e.entities),a=e.i}else if(33===l&&91===t.charCodeAt(a+2)){const e=Ie(t,"]]>",a,"CDATA is not closed.")-2,r=t.substring(a+9,e);n=this.saveTextToParentTag(n,i,this.readonlyMatcher);let o=this.parseTextData(r,i.tagname,this.readonlyMatcher,!0,!1,!0,!0);null==o&&(o=""),s.cdataPropName?i.add(s.cdataPropName,[{[s.textNodeName]:r}]):i.add(s.textNodeName,o),a=e+2}else{let r=De(t,a,s.removeNSPrefix);if(!r){const e=t.substring(Math.max(0,a-50),Math.min(o,a+50));throw new Error(`readTagExp returned undefined at position ${a}. Context: "${e}"`)}let l=r.tagName;const c=r.rawTagName;let h=r.tagExp,u=r.attrExpPresent,d=r.closeIndex;if(({tagName:l,tagExp:h}=Oe(s.transformTagName,l,h,s)),s.strictReservedNames&&(l===s.commentPropName||l===s.cdataPropName||l===s.textNodeName||l===s.attributesGroupName))throw new Error(`Invalid tag name: ${l}`);i&&n&&"!xml"!==i.tagname&&(n=this.saveTextToParentTag(n,i,this.readonlyMatcher,!1));const p=i;p&&s.unpairedTagsSet.has(p.tagname)&&(i=this.tagsNodeStack.pop(),this.matcher.pop());let f=!1;h.length>0&&h.lastIndexOf("/")===h.length-1&&(f=!0,"/"===l[l.length-1]?(l=l.substr(0,l.length-1),h=l):h=h.substr(0,h.length-1),u=l!==h);let m,g=null;m=_e(c),l!==e.tagname&&this.matcher.push(l,{},m),l!==h&&u&&(g=this.buildAttributesMap(h,this.matcher,l),g&&ye(g,s)),l!==e.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());const w=a;if(this.isCurrentNodeStopNode){let e="";if(f)a=r.closeIndex;else if(s.unpairedTagsSet.has(l))a=r.closeIndex;else{const i=this.readStopNodeData(t,c,d+1);if(!i)throw new Error(`Unexpected end of ${c}`);a=i.i,e=i.tagContent}const n=new se(l);g&&(n[":@"]=g),n.add(s.textNodeName,e),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(i,n,this.readonlyMatcher,w)}else{if(f){({tagName:l,tagExp:h}=Oe(s.transformTagName,l,h,s));const t=new se(l);g&&(t[":@"]=g),this.addChild(i,t,this.readonlyMatcher,w),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else{if(s.unpairedTagsSet.has(l)){const t=new se(l);g&&(t[":@"]=g),this.addChild(i,t,this.readonlyMatcher,w),this.matcher.pop(),this.isCurrentNodeStopNode=!1,a=r.closeIndex;continue}{const t=new se(l);if(this.tagsNodeStack.length>s.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(i),g&&(t[":@"]=g),this.addChild(i,t,this.readonlyMatcher,w),i=t}}n="",a=d}}}else n+=t[a]}return e.child};function Pe(t,e,i,n){this.options.captureMetaData||(n=void 0);const s=this.options.jPath?i.toString():i,r=this.options.updateTag(e.tagname,s,e[":@"]);!1===r||("string"==typeof r?(e.tagname=r,t.addChild(e,n)):t.addChild(e,n))}function Te(t,e,i){const n=this.options.processEntities;if(!n||!n.enabled)return t;if(n.allowedTags){const s=this.options.jPath?i.toString():i;if(!(Array.isArray(n.allowedTags)?n.allowedTags.includes(e):n.allowedTags(e,s)))return t}if(n.tagFilter){const s=this.options.jPath?i.toString():i;if(!n.tagFilter(e,s))return t}return this.entityDecoder.decode(t)}function Ee(t,e,i,n){return t&&(void 0===n&&(n=0===e.child.length),void 0!==(t=this.parseTextData(t,e.tagname,i,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,n))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function Me(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function Ie(t,e,i,n){const s=t.indexOf(e,i);if(-1===s)throw new Error(n);return s+e.length-1}function ze(t,e,i,n){const s=t.indexOf(e,i);if(-1===s)throw new Error(n);return s}function De(t,e,i,n=">"){const s=function(t,e,i=">"){let n=0;const s=t.length,r=i.charCodeAt(0),o=i.length>1?i.charCodeAt(1):-1;let a="",l=e;for(let i=e;i<s;i++){const e=t.charCodeAt(i);if(n)e===n&&(n=0);else if(34===e||39===e)n=e;else if(e===r){if(-1===o)return a+=t.substring(l,i),{data:a,index:i};if(t.charCodeAt(i+1)===o)return a+=t.substring(l,i),{data:a,index:i}}else 9!==e||n||(a+=t.substring(l,i)+" ",l=i+1)}}(t,e+1,n);if(!s)return;let r=s.data;const o=s.index,a=r.search(/\s/);let l=r,c=!0;-1!==a&&(l=r.substring(0,a),r=r.substring(a+1).trimStart());const h=l;if(i){const t=l.indexOf(":");-1!==t&&(l=l.substr(t+1),c=l!==s.data.substr(t+1))}return{tagName:l,tagExp:r,closeIndex:o,attrExpPresent:c,rawTagName:h}}function ke(t,e,i){const n=i;let s=1;const r=t.length;for(;i<r;i++)if("<"===t[i]){const r=t.charCodeAt(i+1);if(47===r){const r=ze(t,">",i,`${e} is not closed`);if(t.substring(i+2,r).trim()===e&&(s--,0===s))return{tagContent:t.substring(n,i),i:r};i=r}else if(63===r){i=Ie(t,"?>",i+1,"StopNode is not closed.")}else if(33===r&&45===t.charCodeAt(i+2)&&45===t.charCodeAt(i+3)){i=Ie(t,"--\x3e",i+3,"StopNode is not closed.")}else if(33===r&&91===t.charCodeAt(i+2)){i=Ie(t,"]]>",i,"StopNode is not closed.")-2}else{const n=De(t,i,">");if(n){(n&&n.tagName)===e&&"/"!==n.tagExp[n.tagExp.length-1]&&s++,i=n.closeIndex}}}}function Be(t,e,i){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&de(t,i)}return void 0!==t?t:""}function Oe(t,e,i,n){if(t){const n=t(e);i===e&&(i=n),e=n}return{tagName:e=Ne(e,n),tagExp:i}}function Ne(t,e){if(At.includes(t))throw new Error(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);return St.includes(t)?e.onDangerousProperty(t):t}const Ve=se.getMetaDataSymbol();function Le(t,e){if(!t||"object"!=typeof t)return{};if(!e)return t;const i={};for(const n in t)if(n.startsWith(e)){i[n.substring(e.length)]=t[n]}else i[n]=t[n];return i}function Fe(t,e,i,n){return Re(t,e,i,n)}function Re(t,e,i,n){let s;const r={};for(let o=0;o<t.length;o++){const a=t[o],l=Ue(a);if(void 0!==l&&l!==e.textNodeName){const t=Le(a[":@"]||{},e.attributeNamePrefix);i.push(l,t)}if(l===e.textNodeName)void 0===s?s=a[l]:s+=""+a[l];else{if(void 0===l)continue;if(a[l]){let t=Re(a[l],e,i,n);const s=$e(t,e);if(a[":@"]?je(t,a[":@"],n,e):1!==Object.keys(t).length||void 0===t[e.textNodeName]||e.alwaysCreateTextNode?0===Object.keys(t).length&&(e.alwaysCreateTextNode?t[e.textNodeName]="":t=""):t=t[e.textNodeName],void 0!==a[Ve]&&"object"==typeof t&&null!==t&&(t[Ve]=a[Ve]),void 0!==r[l]&&Object.prototype.hasOwnProperty.call(r,l))Array.isArray(r[l])||(r[l]=[r[l]]),r[l].push(t);else{const i=e.jPath?n.toString():n;e.isArray(l,i,s)?r[l]=[t]:r[l]=t}void 0!==l&&l!==e.textNodeName&&i.pop()}}}return"string"==typeof s?s.length>0&&(r[e.textNodeName]=s):void 0!==s&&(r[e.textNodeName]=s),r}function Ue(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const i=e[t];if(":@"!==i)return i}}function je(t,e,i,n){if(e){const s=Object.keys(e),r=s.length;for(let o=0;o<r;o++){const r=s[o],a=r.startsWith(n.attributeNamePrefix)?r.substring(n.attributeNamePrefix.length):r,l=n.jPath?i.toString()+"."+a:i;n.isArray(r,l,!0,!0)?t[r]=[e[r]]:t[r]=e[r]}}}function $e(t,e){const{textNodeName:i}=e,n=Object.keys(t).length;return 0===n||!(1!==n||!t[i]&&"boolean"!=typeof t[i]&&0!==t[i])}class We{constructor(t){this.externalEntities={},this.options=ie(t)}parse(t,e){if("string"!=typeof t&&t.toString)t=t.toString();else if("string"!=typeof t)throw new Error("XML data is accepted in String or Bytes[] form.");if(e){!0===e&&(e={});const i=function(t,e){e=Object.assign({},Pt,e);const i=[];let n=!1,s=!1;"\ufeff"===t[0]&&(t=t.substr(1));for(let r=0;r<t.length;r++)if("<"===t[r]&&"?"===t[r+1]){if(r+=2,r=Et(t,r),r.err)return r}else{if("<"!==t[r]){if(Tt(t[r]))continue;return Nt("InvalidChar","char '"+t[r]+"' is not expected.",Lt(t,r))}{let o=r;if(r++,"!"===t[r]){r=Mt(t,r);continue}{let a=!1;"/"===t[r]&&(a=!0,r++);let l="";for(;r<t.length&&">"!==t[r]&&" "!==t[r]&&"\t"!==t[r]&&"\n"!==t[r]&&"\r"!==t[r];r++)l+=t[r];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),r--),!Ct(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",Nt("InvalidTag",e,Lt(t,r))}const c=Dt(t,r);if(!1===c)return Nt("InvalidAttr","Attributes for '"+l+"' have open quote.",Lt(t,r));let h=c.value;if(r=c.index,"/"===h[h.length-1]){const i=r-h.length;h=h.substring(0,h.length-1);const s=Bt(h,e);if(!0!==s)return Nt(s.err.code,s.err.msg,Lt(t,i+s.err.line));n=!0}else if(a){if(!c.tagClosed)return Nt("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",Lt(t,r));if(h.trim().length>0)return Nt("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",Lt(t,o));if(0===i.length)return Nt("InvalidTag","Closing tag '"+l+"' has not been opened.",Lt(t,o));{const e=i.pop();if(l!==e.tagName){let i=Lt(t,e.tagStartPos);return Nt("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",Lt(t,o))}0==i.length&&(s=!0)}}else{const a=Bt(h,e);if(!0!==a)return Nt(a.err.code,a.err.msg,Lt(t,r-h.length+a.err.line));if(!0===s)return Nt("InvalidXml","Multiple possible root nodes found.",Lt(t,r));-1!==e.unpairedTags.indexOf(l)||i.push({tagName:l,tagStartPos:o}),n=!0}for(r++;r<t.length;r++)if("<"===t[r]){if("!"===t[r+1]){r++,r=Mt(t,r);continue}if("?"!==t[r+1])break;if(r=Et(t,++r),r.err)return r}else if("&"===t[r]){const e=Ot(t,r);if(-1==e)return Nt("InvalidChar","char '&' is not expected.",Lt(t,r));r=e}else if(!0===s&&!Tt(t[r]))return Nt("InvalidXml","Extra text at the end",Lt(t,r));"<"===t[r]&&r--}}}return n?1==i.length?Nt("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",Lt(t,i[0].tagStartPos)):!(i.length>0)||Nt("InvalidXml","Invalid '"+JSON.stringify(i.map((t=>t.tagName)),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):Nt("InvalidXml","Start tag expected.",1)}(t,e);if(!0!==i)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const i=new be(this.options,this.externalEntities),n=i.parseXml(t);return this.options.preserveOrder||void 0===n?n:Fe(n,this.options,i.matcher,i.readonlyMatcher)}addEntity(t,e){if(-1!==e.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==t.indexOf("&")||-1!==t.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return se.getMetaDataSymbol()}}function Ge(t,e){let i="";e.format&&e.indentBy.length>0&&(i="\n");const n=[];if(e.stopNodes&&Array.isArray(e.stopNodes))for(let t=0;t<e.stopNodes.length;t++){const i=e.stopNodes[t];"string"==typeof i?n.push(new fe(i)):i instanceof fe&&n.push(i)}return He(t,e,i,new we,n)}function He(t,e,i,n,s){let r="",o=!1;if(e.maxNestedTags&&n.getDepth()>e.maxNestedTags)throw new Error("Maximum nested tags exceeded");if(!Array.isArray(t)){if(null!=t){let i=t.toString();return i=Je(i,e),i}return""}for(let a=0;a<t.length;a++){const l=t[a],c=Xe(l);if(void 0===c)continue;const h=Ze(l[":@"],e);n.push(c,h);const u=Qe(n,s);if(c===e.textNodeName){let t=l[c];u||(t=e.tagValueProcessor(c,t),t=Je(t,e)),o&&(r+=i),r+=t,o=!1,n.pop();continue}if(c===e.cdataPropName){o&&(r+=i);const t=l[c][0][e.textNodeName];r+=`<![CDATA[${String(t).replace(/\]\]>/g,"]]]]><![CDATA[>")}]]>`,o=!1,n.pop();continue}if(c===e.commentPropName){const t=l[c][0][e.textNodeName];r+=i+`\x3c!--${String(t).replace(/--/g,"- -").replace(/-$/,"- ")}--\x3e`,o=!0,n.pop();continue}if("?"===c[0]){const t=Ke(l[":@"],e,u),s="?xml"===c?"":i;let a=l[c][0][e.textNodeName];a=0!==a.length?" "+a:"",r+=s+`<${c}${a}${t}?>`,o=!0,n.pop();continue}let d=i;""!==d&&(d+=e.indentBy);const p=i+`<${c}${Ke(l[":@"],e,u)}`;let f;f=u?qe(l[c],e):He(l[c],e,d,n,s),-1!==e.unpairedTags.indexOf(c)?e.suppressUnpairedNode?r+=p+">":r+=p+"/>":f&&0!==f.length||!e.suppressEmptyNode?f&&f.endsWith(">")?r+=p+`>${f}${i}</${c}>`:(r+=p+">",f&&""!==i&&(f.includes("/>")||f.includes("</"))?r+=i+e.indentBy+f+i:r+=f,r+=`</${c}>`):r+=p+"/>",o=!0,n.pop()}return r}function Ze(t,e){if(!t||e.ignoreAttributes)return null;const i={};let n=!1;for(let s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;i[s.startsWith(e.attributeNamePrefix)?s.substr(e.attributeNamePrefix.length):s]=t[s],n=!0}return n?i:null}function qe(t,e){if(!Array.isArray(t))return null!=t?t.toString():"";let i="";for(let n=0;n<t.length;n++){const s=t[n],r=Xe(s);if(r===e.textNodeName)i+=s[r];else if(r===e.cdataPropName)i+=s[r][0][e.textNodeName];else if(r===e.commentPropName)i+=s[r][0][e.textNodeName];else{if(r&&"?"===r[0])continue;if(r){const t=Ye(s[":@"],e),n=qe(s[r],e);n&&0!==n.length?i+=`<${r}${t}>${n}</${r}>`:i+=`<${r}${t}/>`}}}return i}function Ye(t,e){let i="";if(t&&!e.ignoreAttributes)for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;let s=t[n];!0===s&&e.suppressBooleanAttributes?i+=` ${n.substr(e.attributeNamePrefix.length)}`:i+=` ${n.substr(e.attributeNamePrefix.length)}="${s}"`}return i}function Xe(t){const e=Object.keys(t);for(let i=0;i<e.length;i++){const n=e[i];if(Object.prototype.hasOwnProperty.call(t,n)&&":@"!==n)return n}}function Ke(t,e,i){let n="";if(t&&!e.ignoreAttributes)for(let s in t){if(!Object.prototype.hasOwnProperty.call(t,s))continue;let r;i?r=t[s]:(r=e.attributeValueProcessor(s,t[s]),r=Je(r,e)),!0===r&&e.suppressBooleanAttributes?n+=` ${s.substr(e.attributeNamePrefix.length)}`:n+=` ${s.substr(e.attributeNamePrefix.length)}="${r}"`}return n}function Qe(t,e){if(!e||0===e.length)return!1;for(let i=0;i<e.length;i++)if(t.matches(e[i]))return!0;return!1}function Je(t,e){if(t&&t.length>0&&e.processEntities)for(let i=0;i<e.entities.length;i++){const n=e.entities[i];t=t.replace(n.regex,n.val)}return t}const ti={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1,maxNestedTags:100,jPath:!0};function ei(t){if(this.options=Object.assign({},ti,t),this.options.stopNodes&&Array.isArray(this.options.stopNodes)&&(this.options.stopNodes=this.options.stopNodes.map((t=>"string"==typeof t&&t.startsWith("*.")?".."+t.substring(2):t))),this.stopNodeExpressions=[],this.options.stopNodes&&Array.isArray(this.options.stopNodes))for(let t=0;t<this.options.stopNodes.length;t++){const e=this.options.stopNodes[t];"string"==typeof e?this.stopNodeExpressions.push(new fe(e)):e instanceof fe&&this.stopNodeExpressions.push(e)}var e;!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn="function"==typeof(e=this.options.ignoreAttributes)?e:Array.isArray(e)?t=>{for(const i of e){if("string"==typeof i&&t===i)return!0;if(i instanceof RegExp&&i.test(t))return!0}}:()=>!1,this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=si),this.processTextOrObjNode=ii,this.options.format?(this.indentate=ni,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function ii(t,e,i,n){const s=this.extractAttributes(t);n.push(e,s);if(this.checkStopNode(n)){const s=this.buildRawContent(t),r=this.buildAttributesForStopNode(t);return n.pop(),this.buildObjectNode(s,e,r,i)}const r=this.j2x(t,i+1,n);return n.pop(),void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,r.attrStr,i,n):this.buildObjectNode(r.val,e,r.attrStr,i)}function ni(t){return this.options.indentBy.repeat(t)}function si(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}ei.prototype.build=function(t){if(this.options.preserveOrder)return Ge(t,this.options);{Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t});const e=new we;return this.j2x(t,0,e).val}},ei.prototype.j2x=function(t,e,i){let n="",s="";if(this.options.maxNestedTags&&i.getDepth()>=this.options.maxNestedTags)throw new Error("Maximum nested tags exceeded");const r=this.options.jPath?i.toString():i,o=this.checkStopNode(i);for(let a in t)if(Object.prototype.hasOwnProperty.call(t,a))if(void 0===t[a])this.isAttribute(a)&&(s+="");else if(null===t[a])this.isAttribute(a)||a===this.options.cdataPropName?s+="":"?"===a[0]?s+=this.indentate(e)+"<"+a+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+a+"/"+this.tagEndChar;else if(t[a]instanceof Date)s+=this.buildTextValNode(t[a],a,"",e,i);else if("object"!=typeof t[a]){const l=this.isAttribute(a);if(l&&!this.ignoreAttributesFn(l,r))n+=this.buildAttrPairStr(l,""+t[a],o);else if(!l)if(a===this.options.textNodeName){let e=this.options.tagValueProcessor(a,""+t[a]);s+=this.replaceEntitiesValue(e)}else{i.push(a);const n=this.checkStopNode(i);if(i.pop(),n){const i=""+t[a];s+=""===i?this.indentate(e)+"<"+a+this.closeTag(a)+this.tagEndChar:this.indentate(e)+"<"+a+">"+i+"</"+a+this.tagEndChar}else s+=this.buildTextValNode(t[a],a,"",e,i)}}else if(Array.isArray(t[a])){const n=t[a].length;let r="",o="";for(let l=0;l<n;l++){const n=t[a][l];if(void 0===n);else if(null===n)"?"===a[0]?s+=this.indentate(e)+"<"+a+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+a+"/"+this.tagEndChar;else if("object"==typeof n)if(this.options.oneListGroup){i.push(a);const t=this.j2x(n,e+1,i);i.pop(),r+=t.val,this.options.attributesGroupName&&n.hasOwnProperty(this.options.attributesGroupName)&&(o+=t.attrStr)}else r+=this.processTextOrObjNode(n,a,e,i);else if(this.options.oneListGroup){let t=this.options.tagValueProcessor(a,n);t=this.replaceEntitiesValue(t),r+=t}else{i.push(a);const t=this.checkStopNode(i);if(i.pop(),t){const t=""+n;r+=""===t?this.indentate(e)+"<"+a+this.closeTag(a)+this.tagEndChar:this.indentate(e)+"<"+a+">"+t+"</"+a+this.tagEndChar}else r+=this.buildTextValNode(n,a,"",e,i)}}this.options.oneListGroup&&(r=this.buildObjectNode(r,a,o,e)),s+=r}else if(this.options.attributesGroupName&&a===this.options.attributesGroupName){const e=Object.keys(t[a]),i=e.length;for(let s=0;s<i;s++)n+=this.buildAttrPairStr(e[s],""+t[a][e[s]],o)}else s+=this.processTextOrObjNode(t[a],a,e,i);return{attrStr:n,val:s}},ei.prototype.buildAttrPairStr=function(t,e,i){return i||(e=this.options.attributeValueProcessor(t,""+e),e=this.replaceEntitiesValue(e)),this.options.suppressBooleanAttributes&&"true"===e?" "+t:" "+t+'="'+e+'"'},ei.prototype.extractAttributes=function(t){if(!t||"object"!=typeof t)return null;const e={};let i=!1;if(this.options.attributesGroupName&&t[this.options.attributesGroupName]){const n=t[this.options.attributesGroupName];for(let t in n){if(!Object.prototype.hasOwnProperty.call(n,t))continue;e[t.startsWith(this.options.attributeNamePrefix)?t.substring(this.options.attributeNamePrefix.length):t]=n[t],i=!0}}else for(let n in t){if(!Object.prototype.hasOwnProperty.call(t,n))continue;const s=this.isAttribute(n);s&&(e[s]=t[n],i=!0)}return i?e:null},ei.prototype.buildRawContent=function(t){if("string"==typeof t)return t;if("object"!=typeof t||null===t)return String(t);if(void 0!==t[this.options.textNodeName])return t[this.options.textNodeName];let e="";for(let i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;if(this.isAttribute(i))continue;if(this.options.attributesGroupName&&i===this.options.attributesGroupName)continue;const n=t[i];if(i===this.options.textNodeName)e+=n;else if(Array.isArray(n)){for(let t of n)if("string"==typeof t||"number"==typeof t)e+=`<${i}>${t}</${i}>`;else if("object"==typeof t&&null!==t){const n=this.buildRawContent(t),s=this.buildAttributesForStopNode(t);e+=""===n?`<${i}${s}/>`:`<${i}${s}>${n}</${i}>`}}else if("object"==typeof n&&null!==n){const t=this.buildRawContent(n),s=this.buildAttributesForStopNode(n);e+=""===t?`<${i}${s}/>`:`<${i}${s}>${t}</${i}>`}else e+=`<${i}>${n}</${i}>`}return e},ei.prototype.buildAttributesForStopNode=function(t){if(!t||"object"!=typeof t)return"";let e="";if(this.options.attributesGroupName&&t[this.options.attributesGroupName]){const i=t[this.options.attributesGroupName];for(let t in i){if(!Object.prototype.hasOwnProperty.call(i,t))continue;const n=t.startsWith(this.options.attributeNamePrefix)?t.substring(this.options.attributeNamePrefix.length):t,s=i[t];!0===s&&this.options.suppressBooleanAttributes?e+=" "+n:e+=" "+n+'="'+s+'"'}}else for(let i in t){if(!Object.prototype.hasOwnProperty.call(t,i))continue;const n=this.isAttribute(i);if(n){const s=t[i];!0===s&&this.options.suppressBooleanAttributes?e+=" "+n:e+=" "+n+'="'+s+'"'}}return e},ei.prototype.buildObjectNode=function(t,e,i,n){if(""===t)return"?"===e[0]?this.indentate(n)+"<"+e+i+"?"+this.tagEndChar:this.indentate(n)+"<"+e+i+this.closeTag(e)+this.tagEndChar;{let s="</"+e+this.tagEndChar,r="";return"?"===e[0]&&(r="?",s=""),!i&&""!==i||-1!==t.indexOf("<")?!1!==this.options.commentPropName&&e===this.options.commentPropName&&0===r.length?this.indentate(n)+`\x3c!--${t}--\x3e`+this.newLine:this.indentate(n)+"<"+e+i+r+this.tagEndChar+t+this.indentate(n)+s:this.indentate(n)+"<"+e+i+r+">"+t+s}},ei.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`></${t}`,e},ei.prototype.checkStopNode=function(t){if(!this.stopNodeExpressions||0===this.stopNodeExpressions.length)return!1;for(let e=0;e<this.stopNodeExpressions.length;e++)if(t.matches(this.stopNodeExpressions[e]))return!0;return!1},ei.prototype.buildTextValNode=function(t,e,i,n,s){if(!1!==this.options.cdataPropName&&e===this.options.cdataPropName){const e=String(t).replace(/\]\]>/g,"]]]]><![CDATA[>");return this.indentate(n)+`<![CDATA[${e}]]>`+this.newLine}if(!1!==this.options.commentPropName&&e===this.options.commentPropName){const e=String(t).replace(/--/g,"- -").replace(/-$/,"- ");return this.indentate(n)+`\x3c!--${e}--\x3e`+this.newLine}if("?"===e[0])return this.indentate(n)+"<"+e+i+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(e,t);return s=this.replaceEntitiesValue(s),""===s?this.indentate(n)+"<"+e+i+this.closeTag(e)+this.tagEndChar:this.indentate(n)+"<"+e+i+">"+s+"</"+e+this.tagEndChar}},ei.prototype.replaceEntitiesValue=function(t){if(t&&t.length>0&&this.options.processEntities)for(let e=0;e<this.options.entities.length;e++){const i=this.options.entities[e];t=t.replace(i.regex,i.val)}return t};class ri{}e(ri,"parser",new We({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0})),e(ri,"builder",new ei({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1}));class oi extends ht{constructor(t,i){super(t),e(this,"onDisposed",new at),e(this,"onVertexFound",new at),e(this,"onVertexLost",new at),e(this,"onEnabled",new at),e(this,"components"),e(this,"workingPlane",null),e(this,"_pickedPoint",null),e(this,"_config"),e(this,"_enabled",!1),this.components=t,this.config={snapDistance:.25,showOnlyVertex:!1,...i},this.enabled=!1}set enabled(t){this._enabled=t,t||(this._pickedPoint=null),this.onEnabled.trigger(t)}get enabled(){return this._enabled}set config(t){this._config={...this._config,...t}}get config(){return this._config}dispose(){this.onVertexFound.reset(),this.onVertexLost.reset(),this.components=null,this.onDisposed.trigger(),this.onDisposed.reset()}async get(t){if(!this.enabled)return this._pickedPoint;const e=this.components.get(pa).get(t),i=await e.castRay();if(!i)return null!==this._pickedPoint&&(this.onVertexLost.trigger(),this._pickedPoint=null),this._pickedPoint;const n=i.point;return null!==this._pickedPoint&&this._pickedPoint.equals(n)||(this._pickedPoint=n.clone(),this.onVertexFound.trigger(this._pickedPoint)),this._pickedPoint}}class ai{static join(t){const e={};for(const i of t)for(const t in i)if(e[t])for(const n of i[t])e[t].add(n);else e[t]=new Set(i[t]);return e}static intersect(t){if(0===t.length)return{};let e=ai.clone(t[0]);for(let i=1;i<t.length;i++){const n=t[i],s={};for(const t in e)if(n[t]){const i=new Set;for(const s of e[t])n[t].has(s)&&i.add(s);i.size>0&&(s[t]=i)}e=s}return e}static clone(t){const e={};for(const i in t)e[i]=new Set(t[i]);return e}static remove(t,e,i=!1){i&&(t=ai.clone(t));for(const i in e)if(t[i]){for(const n of e[i])t[i].delete(n);0===t[i].size&&delete t[i]}}static add(t,e,i=!1){i&&(t=ai.clone(t));for(const i in e)if(t[i])for(const n of e[i])t[i].add(n);else t[i]=new Set(e[i])}static append(t,e,...i){let n=t[e];n||(n=new Set,t[e]=n);for(const t of i)n.add(t)}static isEqual(t,e){const i=Object.keys(t),n=Object.keys(e);if(i.length!==n.length)return!1;for(const n of i){if(!e[n])return!1;if(t[n].size!==e[n].size)return!1;for(const i of t[n])if(!e[n].has(i))return!1}return!0}static isEmpty(t){return 0===Object.values(t).reduce(((t,e)=>t+e.size),0)}static toRaw(t){const e={};for(const i in t)e[i]=Array.from(t[i]);return e}static fromRaw(t){const e={};for(const i in t)e[i]=new Set(t[i]);return e}}class li extends Map{constructor(t){super(t),e(this,"onItemSet",new at),e(this,"onItemUpdated",new at),e(this,"onItemDeleted",new at),e(this,"onCleared",new at),e(this,"guard",(()=>!0))}clear(){super.clear(),this.onCleared.trigger()}set(t,e){const i=this.has(t);if(!(this.guard??(()=>!0))(t,e))return this;const n=super.set(t,e);return i?(this.onItemUpdated||(this.onItemUpdated=new at),this.onItemUpdated.trigger({key:t,value:e})):(this.onItemSet||(this.onItemSet=new at),this.onItemSet.trigger({key:t,value:e})),n}add(t){const e=_t.create();return this.set(e,t),e}delete(t){const e=super.delete(t);return e&&this.onItemDeleted.trigger(t),e}dispose(){this.clear(),this.onItemSet.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}class ci{static isEntry(t){return new Set(["Boolean","Color","Text","Number","Select","Vector3","TextSet","None"]).has(t.type)}static copySchema(t,e={}){for(const i in t){const n=t[i];this.isEntry(n)?e[i]=this.copyEntry(n):(e[i]={},this.copySchema(n,e[i]))}return e}static copyEntry(t){if("Boolean"===t.type){const e=t;return{type:e.type,value:e.value}}if("Color"===t.type){const e=t;return{type:e.type,value:e.value.clone()}}if("Text"===t.type){const e=t;return{type:e.type,value:e.value}}if("Number"===t.type){const e=t;return{type:e.type,value:e.value,min:e.min,max:e.max,interpolable:e.interpolable}}if("Select"===t.type){const e=t;return{type:e.type,value:e.value,multiple:e.multiple,options:new Set(e.options)}}if("Vector3"===t.type){const e=t;return{type:e.type,value:e.value.clone()}}if("TextSet"===t.type){const e=t;return{type:e.type,value:new Set(e.value)}}if("None"===t.type){const e=t;return{type:e.type,value:e.value}}throw new Error("Invalid entry!")}}class hi{constructor(){e(this,"list",new Set)}add(t){for(const e of t)this.list.add(e)}remove(t){for(const e of t)this.list.delete(e)}set(t){for(const e of this.list)e.enabled=t}reset(){for(const t of this.list)t.reset()}}class ui{constructor(t,i,n,s){e(this,"_component"),e(this,"name"),e(this,"uuid"),this._component=t,this.name=n,this.uuid=s??_t.create();i.get(pi).list.set(this.uuid,this)}get controls(){return ci.copySchema(this._config)}set(t){for(const e in t)if(e in this){this[e]=t[e].value}}export(t=this._config,e={}){for(const i in t){const n=t[i];if(ci.isEntry(n))if("Color"===n.type){const{r:t,g:s,b:r}=n.value;e[i]={...n,value:{r:t,g:s,b:r}}}else if("Vector3"===n.type){const{x:t,y:s,z:r}=n.value;e[i]={...n,value:{x:t,y:s,z:r}}}else if("TextSet"===n.type){const t=Array.from(n.value);e[i]={...n,value:t}}else if("Select"===n.type){const t=Array.from(n.options);e[i]={...n,options:t}}else e[i]={...n};else e[i]={},this.export(n,e[i])}return e}import(t,e={},i=!0){for(const i in t){const n=t[i];if(ci.isEntry(n))if("Color"===n.type){const{r:t,g:s,b:r}=n.value;e[i]={...n,value:new o.Color(t,s,r)}}else if("Vector3"===n.type){const{x:t,y:s,z:r}=n.value;e[i]={...n,value:new o.Vector3(t,s,r)}}else"TextSet"===n.type?e[i]={...n,value:new Set(n.value)}:"Select"===n.type?e[i]={...n,options:new Set(n.options)}:e[i]={...n};else e[i]={},this.import(n,e[i],!1)}i&&this.set(e)}}const di=class t extends ht{constructor(i){super(i),e(this,"list",new n),e(this,"enabled",!0),i.add(t.uuid,this)}};e(di,"uuid","b8c764e0-6b24-4e77-9a32-35fa728ee5b4");let pi=di;class fi{constructor(t){e(this,"_event"),e(this,"_position",new o.Vector2),e(this,"onDisposed",new at),e(this,"updateMouseInfo",(t=>{this._event=t})),this.dom=t,this.setupEvents(!0)}get position(){return this.updatePosition(!1),this._position.clone()}get rawPosition(){return this.updatePosition(!0),this._position.clone()}dispose(){this.setupEvents(!1),this.onDisposed.trigger(),this.onDisposed.reset()}updatePosition(t){if(this._event){const e=this.dom.getBoundingClientRect();this._position.x=this.getPositionX(e,this._event,t),this._position.y=this.getPositionY(e,this._event,t)}}getPositionY(t,e,i){const n=this.getDataObject(e);return i?n.clientY:-(n.clientY-t.top)/(t.bottom-t.top)*2+1}getPositionX(t,e,i){const n=this.getDataObject(e);return i?n.clientX:(n.clientX-t.left)/(t.right-t.left)*2-1}getDataObject(t){return t instanceof MouseEvent?t:t.touches[0]}setupEvents(t){t?(this.dom.addEventListener("pointermove",this.updateMouseInfo),this.dom.addEventListener("touchstart",this.updateMouseInfo)):(this.dom.removeEventListener("pointermove",this.updateMouseInfo),this.dom.removeEventListener("touchstart",this.updateMouseInfo))}}const mi=1.25,gi=32,wi=Math.pow(2,-24),yi=Symbol("SKIP_GENERATION"),_i={strategy:0,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[yi]:!1};function bi(t,e,i){return i.min.x=e[t],i.min.y=e[t+1],i.min.z=e[t+2],i.max.x=e[t+3],i.max.y=e[t+4],i.max.z=e[t+5],i}function vi(t){let e=-1,i=-1/0;for(let n=0;n<3;n++){const s=t[n+3]-t[n];s>i&&(i=s,e=n)}return e}function xi(t,e){e.set(t)}function Ci(t,e,i){let n,s;for(let r=0;r<3;r++){const o=r+3;n=t[r],s=e[r],i[r]=n<s?n:s,n=t[o],s=e[o],i[o]=n>s?n:s}}function Si(t,e,i){for(let n=0;n<3;n++){const s=e[t+2*n],r=e[t+2*n+1],o=s-r,a=s+r;o<i[n]&&(i[n]=o),a>i[n+3]&&(i[n+3]=a)}}function Ai(t){const e=t[3]-t[0],i=t[4]-t[1],n=t[5]-t[2];return 2*(e*i+i*n+n*e)}function Pi(t,e){return 65535===e[t+15]}function Ti(t,e){return e[t+6]}function Ei(t,e){return e[t+14]}function Mi(t){return t+8}function Ii(t,e){return t+8*e[t+6]}function zi(t,e){return e[t+7]}function Di(t,e,i,n,s){let r=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,h=-1/0,u=1/0,d=1/0,p=1/0,f=-1/0,m=-1/0,g=-1/0;const w=t.offset||0;for(let n=6*(e-w),s=6*(e+i-w);n<s;n+=6){const e=t[n+0],i=t[n+1],s=e-i,w=e+i;s<r&&(r=s),w>l&&(l=w),e<u&&(u=e),e>f&&(f=e);const y=t[n+2],_=t[n+3],b=y-_,v=y+_;b<o&&(o=b),v>c&&(c=v),y<d&&(d=y),y>m&&(m=y);const x=t[n+4],C=t[n+5],S=x-C,A=x+C;S<a&&(a=S),A>h&&(h=A),x<p&&(p=x),x>g&&(g=x)}n[0]=r,n[1]=o,n[2]=a,n[3]=l,n[4]=c,n[5]=h,s[0]=u,s[1]=d,s[2]=p,s[3]=f,s[4]=m,s[5]=g}const ki=32,Bi=(t,e)=>t.candidate-e.candidate,Oi=new Array(ki).fill().map((()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0}))),Ni=new Float32Array(6);class Vi{constructor(){this.boundingData=new Float32Array(6)}}let Li,Fi,Ri,Ui;const ji=Math.pow(2,32);function $i(t){return"count"in t?1:1+$i(t.left)+$i(t.right)}function Wi(t,e,i){return Li=new Float32Array(i),Fi=new Uint32Array(i),Ri=new Uint16Array(i),Ui=new Uint8Array(i),Gi(t,e)}function Gi(t,e){const i=t/4,n=t/2,s="count"in e,r=e.boundingData;for(let t=0;t<6;t++)Li[i+t]=r[t];if(s)return e.buffer?(Ui.set(new Uint8Array(e.buffer),t),t+e.buffer.byteLength):(Fi[i+6]=e.offset,Ri[n+14]=e.count,Ri[n+15]=65535,t+gi);{const{left:n,right:s,splitAxis:r}=e;let o=Gi(t+gi,n);const a=o/gi-t/gi;if(a>ji)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return Fi[i+6]=a,Fi[i+7]=r,Gi(o,s)}}function Hi(t,e,i,n,s,r){const{maxDepth:o,verbose:a,maxLeafSize:l,strategy:c,onProgress:h}=s,u=t.primitiveBuffer,d=t.primitiveBufferStride,p=new Float32Array(6);let f=!1;const m=new Vi;return Di(e,i,n,m.boundingData,p),function t(i,n,s,r=null,h=0){!f&&h>=o&&(f=!0,a&&console.warn(`BVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`));if(s<=l||h>=o)return g(n+s),i.offset=n,i.count=s,i;const m=function(t,e,i,n,s,r){let o=-1,a=0;if(0===r)o=vi(e),-1!==o&&(a=(e[o]+e[o+3])/2);else if(1===r)o=vi(t),-1!==o&&(a=function(t,e,i,n){let s=0;const r=t.offset;for(let o=e,a=e+i;o<a;o++)s+=t[6*(o-r)+2*n];return s/i}(i,n,s,o));else if(2===r){const r=Ai(t);let l=mi*s;const c=i.offset||0,h=6*(n-c),u=6*(n+s-c);for(let t=0;t<3;t++){const n=e[t],c=(e[t+3]-n)/ki;if(s<8){const e=[...Oi];e.length=s;let n=0;for(let s=h;s<u;s+=6,n++){const r=e[n];r.candidate=i[s+2*t],r.count=0;const{bounds:o,leftCacheBounds:a,rightCacheBounds:l}=r;for(let t=0;t<3;t++)l[t]=1/0,l[t+3]=-1/0,a[t]=1/0,a[t+3]=-1/0,o[t]=1/0,o[t+3]=-1/0;Si(s,i,o)}e.sort(Bi);let c=s;for(let t=0;t<c;t++){const i=e[t];for(;t+1<c&&e[t+1].candidate===i.candidate;)e.splice(t+1,1),c--}for(let n=h;n<u;n+=6){const s=i[n+2*t];for(let t=0;t<c;t++){const r=e[t];s>=r.candidate?Si(n,i,r.rightCacheBounds):(Si(n,i,r.leftCacheBounds),r.count++)}}for(let i=0;i<c;i++){const n=e[i],c=n.count,h=s-n.count,u=n.leftCacheBounds,d=n.rightCacheBounds;let p=0;0!==c&&(p=Ai(u)/r);let f=0;0!==h&&(f=Ai(d)/r);const m=1+mi*(p*c+f*h);m<l&&(o=t,l=m,a=n.candidate)}}else{for(let t=0;t<ki;t++){const e=Oi[t];e.count=0,e.candidate=n+c+t*c;const i=e.bounds;for(let t=0;t<3;t++)i[t]=1/0,i[t+3]=-1/0}for(let e=h;e<u;e+=6){let s=~~((i[e+2*t]-n)/c);s>=ki&&(s=31);const r=Oi[s];r.count++,Si(e,i,r.bounds)}const e=Oi[31];xi(e.bounds,e.rightCacheBounds);for(let t=30;t>=0;t--){const e=Oi[t],i=Oi[t+1];Ci(e.bounds,i.rightCacheBounds,e.rightCacheBounds)}let d=0;for(let e=0;e<31;e++){const i=Oi[e],n=i.count,c=i.bounds,h=Oi[e+1].rightCacheBounds;0!==n&&(0===d?xi(c,Ni):Ci(c,Ni,Ni)),d+=n;let u=0,p=0;0!==d&&(u=Ai(Ni)/r);const f=s-d;0!==f&&(p=Ai(h)/r);const m=1+mi*(u*d+p*f);m<l&&(o=t,l=m,a=i.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}(i.boundingData,r,e,n,s,c);if(-1===m.axis)return g(n+s),i.offset=n,i.count=s,i;const w=function(t,e,i,n,s,r){let o=n,a=n+s-1;const l=r.pos,c=2*r.axis,h=i.offset||0;for(;;){for(;o<=a&&i[6*(o-h)+c]<l;)o++;for(;o<=a&&i[6*(a-h)+c]>=l;)a--;if(!(o<a))return o;for(let i=0;i<e;i++){let n=t[o*e+i];t[o*e+i]=t[a*e+i],t[a*e+i]=n}for(let t=0;t<6;t++){const e=o-h,n=a-h,s=i[6*e+t];i[6*e+t]=i[6*n+t],i[6*n+t]=s}o++,a--}}(u,d,e,n,s,m);if(w===n||w===n+s)g(n+s),i.offset=n,i.count=s;else{i.splitAxis=m.axis;const r=new Vi,o=n,a=w-n;i.left=r,Di(e,o,a,r.boundingData,p),t(r,o,a,p,h+1);const l=new Vi,c=w,u=s-a;i.right=l,Di(e,c,u,l.boundingData,p),t(l,c,u,p,h+1)}return i}(m,i,n,p),m;function g(t){h&&h((t-r.offset)/r.count)}}function Zi(t,e){const i=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=t.getRootRanges(e.range),s=n[0],r=n[n.length-1],o={offset:s.offset,count:r.offset+r.count-s.offset},a=new Float32Array(6*o.count);a.offset=o.offset,t.computePrimitiveBounds(o.offset,o.count,a),t._roots=n.map((n=>{const s=Hi(t,a,n.offset,n.count,e,o),r=$i(s),l=new i(gi*r);return Wi(0,s,l),l}))}class qi{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return 0===t.length?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class Yi{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,0!==t.length&&this.setBuffer(t.pop())}}}const Xi=new Yi;let Ki,Qi;const Ji=[],tn=new qi((()=>new a));function en(t,e,i,n,s,r){Ki=tn.getPrimitive(),Qi=tn.getPrimitive(),Ji.push(Ki,Qi),Xi.setBuffer(t._roots[e]);const o=nn(0,t.geometry,i,n,s,r);Xi.clearBuffer(),tn.releasePrimitive(Ki),tn.releasePrimitive(Qi),Ji.pop(),Ji.pop();const a=Ji.length;return a>0&&(Qi=Ji[a-1],Ki=Ji[a-2]),o}function nn(t,e,i,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=Xi;let h=2*t;if(Pi(h,l)){const e=Ti(t,c),i=Ei(h,l);return bi(t,a,Ki),n(e,i,!1,o,r+t/8,Ki)}{let h=function(t){const{uint16Array:e,uint32Array:i}=Xi;let n=2*t;for(;!Pi(n,e);)n=2*(t=Mi(t));return Ti(t,i)},u=function(t){const{uint16Array:e,uint32Array:i}=Xi;let n=2*t;for(;!Pi(n,e);)n=2*(t=Ii(t,i));return Ti(t,i)+Ei(n,e)};const d=Mi(t),p=Ii(t,c);let f,m,g,w,y=d,_=p;if(s&&(g=Ki,w=Qi,bi(y,a,g),bi(_,a,w),f=s(g),m=s(w),m<f)){y=p,_=d;const t=f;f=m,m=t,g=w}g||(g=Ki,bi(y,a,g));const b=i(g,Pi(2*y,l),f,o+1,r+y/8);let v;if(2===b){const t=h(y);v=n(t,u(y)-t,!0,o+1,r+y/8,g)}else v=b&&nn(y,e,i,n,s,r,o+1);if(v)return!0;w=Qi,bi(_,a,w);const x=i(w,Pi(2*_,l),m,o+1,r+_/8);let C;if(2===x){const t=h(_);C=n(t,u(_)-t,!0,o+1,r+_/8,w)}else C=x&&nn(_,e,i,n,s,r,o+1);return!!C}}const sn=new Xi.constructor,rn=new Xi.constructor,on=new qi((()=>new a)),an=new a,ln=new a,cn=new a,hn=new a;let un=!1;function dn(t,e,i,n,s,r=0,o=0,a=0,l=0,c=null,h=!1){let u,d;h?(u=rn,d=sn):(u=sn,d=rn);const p=u.float32Array,f=u.uint32Array,m=u.uint16Array,g=d.float32Array,w=d.uint32Array,y=d.uint16Array,_=2*e,b=Pi(2*t,m),v=Pi(_,y);let x=!1;if(v&&b)x=h?s(Ti(e,w),Ei(2*e,y),Ti(t,f),Ei(2*t,m),l,o+e/8,a,r+t/8):s(Ti(t,f),Ei(2*t,m),Ti(e,w),Ei(2*e,y),a,r+t/8,l,o+e/8);else if(v){const c=on.getPrimitive();bi(e,g,c),c.applyMatrix4(i);const u=Mi(t),d=Ii(t,f);bi(u,p,an),bi(d,p,ln);const m=c.intersectsBox(an),w=c.intersectsBox(ln);x=m&&dn(e,u,n,i,s,o,r,l,a+1,c,!h)||w&&dn(e,d,n,i,s,o,r,l,a+1,c,!h),on.releasePrimitive(c)}else{const u=Mi(e),d=Ii(e,w);bi(u,g,cn),bi(d,g,hn);const m=c.intersectsBox(cn),y=c.intersectsBox(hn);if(m&&y)x=dn(t,u,i,n,s,r,o,a,l+1,c,h)||dn(t,d,i,n,s,r,o,a,l+1,c,h);else if(m)if(b)x=dn(t,u,i,n,s,r,o,a,l+1,c,h);else{const e=on.getPrimitive();e.copy(cn).applyMatrix4(i);const c=Mi(t),d=Ii(t,f);bi(c,p,an),bi(d,p,ln);const m=e.intersectsBox(an),g=e.intersectsBox(ln);x=m&&dn(u,c,n,i,s,o,r,l,a+1,e,!h)||g&&dn(u,d,n,i,s,o,r,l,a+1,e,!h),on.releasePrimitive(e)}else if(y)if(b)x=dn(t,d,i,n,s,r,o,a,l+1,c,h);else{const e=on.getPrimitive();e.copy(hn).applyMatrix4(i);const c=Mi(t),u=Ii(t,f);bi(c,p,an),bi(u,p,ln);const m=e.intersectsBox(an),g=e.intersectsBox(ln);x=m&&dn(d,c,n,i,s,o,r,l,a+1,e,!h)||g&&dn(d,u,n,i,s,o,r,l,a+1,e,!h),on.releasePrimitive(e)}}return x}const pn=new a,fn=new Float32Array(6);class mn{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){Zi(this,t={..._i,...t})}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(t,e,i,n){let s=1/0,r=1/0,o=1/0,a=-1/0,l=-1/0,c=-1/0;for(let i=t,n=t+e;i<n;i++){this.writePrimitiveBounds(i,fn,0);const[t,e,n,h,u,d]=fn;t<s&&(s=t),h>a&&(a=h),e<r&&(r=e),u>l&&(l=u),n<o&&(o=n),d>c&&(c=d)}return i[n+0]=s,i[n+1]=r,i[n+2]=o,i[n+3]=a,i[n+4]=l,i[n+5]=c,i}computePrimitiveBounds(t,e,i){const n=i.offset||0;for(let s=t,r=t+e;s<r;s++){this.writePrimitiveBounds(s,fn,0);const[t,e,r,o,a,l]=fn,c=(t+o)/2,h=(e+a)/2,u=(r+l)/2,d=(o-t)/2,p=(a-e)/2,f=(l-r)/2,m=6*(s-n);i[m+0]=c,i[m+1]=d+(Math.abs(c)+d)*wi,i[m+2]=h,i[m+3]=p+(Math.abs(h)+p)*wi,i[m+4]=u,i[m+5]=f+(Math.abs(u)+f)*wi}return i}shiftPrimitiveOffsets(t){const e=this._indirectBuffer;if(e)for(let i=0,n=e.length;i<n;i++)e[i]+=t;else{const e=this._roots;for(let i=0;i<e.length;i++){const n=e[i],s=new Uint32Array(n),r=new Uint16Array(n),o=n.byteLength/gi;for(let e=0;e<o;e++){const i=8*e;Pi(2*i,r)&&(s[i+6]+=t)}}}}traverse(t,e=0){const i=this._roots[e],n=new Uint32Array(i),s=new Uint16Array(i);!function e(r,o=0){const a=2*r,l=Pi(a,s);if(l){const e=n[r+6],c=s[a+14];t(o,l,new Float32Array(i,4*r,6),e,c)}else{const s=Mi(r),a=Ii(r,n),c=zi(r,n);t(o,l,new Float32Array(i,4*r,6),c)||(e(s,o+1),e(a,o+1))}}(0)}refit(){const t=this._roots;for(let e=0,i=t.length;e<i;e++){const i=t[e],n=new Uint32Array(i),s=new Uint16Array(i),r=new Float32Array(i);for(let t=i.byteLength/gi-1;t>=0;t--){const e=8*t,i=2*e;if(Pi(i,s)){const t=Ti(e,n),o=Ei(i,s);this.writePrimitiveRangeBounds(t,o,fn,0),r.set(fn,e)}else{const t=Mi(e),i=Ii(e,n);for(let n=0;n<3;n++){const s=r[t+n],o=r[t+n+3],a=r[i+n],l=r[i+n+3];r[e+n]=s<a?s:a,r[e+n+3]=o>l?o:l}}}}}getBoundingBox(t){t.makeEmpty();return this._roots.forEach((e=>{bi(0,new Float32Array(e),pn),t.union(pn)})),t}shapecast(t){let{boundsTraverseOrder:e,intersectsBounds:i,intersectsRange:n,intersectsPrimitive:s,scratchPrimitive:r,iterate:o}=t;if(n&&s){const t=n;n=(e,i,n,a,l)=>!!t(e,i,n,a,l)||o(e,i,this,s,n,a,r)}else n||(n=s?(t,e,i,n)=>o(t,e,this,s,i,n,r):(t,e,i)=>i);let a=!1,l=0;const c=this._roots;for(let t=0,s=c.length;t<s;t++){const s=c[t];if(a=en(this,t,i,n,e,l),a)break;l+=s.byteLength/gi}return a}bvhcast(t,e,i){let{intersectsRanges:n}=i;return function(t,e,i,n){if(un)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");un=!0;const s=t._roots,r=e._roots;let o,a=0,c=0;const h=(new l).copy(i).invert();for(let t=0,e=s.length;t<e;t++){sn.setBuffer(s[t]),c=0;const e=on.getPrimitive();bi(0,sn.float32Array,e),e.applyMatrix4(h);for(let t=0,s=r.length;t<s&&(rn.setBuffer(r[t]),o=dn(0,0,i,h,n,a,c,0,0,e),rn.clearBuffer(),c+=r[t].byteLength/gi,!o);t++);if(on.releasePrimitive(e),sn.clearBuffer(),a+=s[t].byteLength/gi,o)break}return un=!1,o}(this,t,e,n)}}function gn(t){return t.index?t.index.count:t.attributes.position.count}function wn(t){return gn(t)/3}function yn(t,e){if(!t.index){const i=t.attributes.position.count,n=function(t,e=ArrayBuffer){return t>65535?new Uint32Array(new e(4*t)):new Uint16Array(new e(2*t))}(i,e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer);t.setIndex(new c(n,1));for(let t=0;t<i;t++)n[t]=t}}function _n(t,e,i){const n=function(t,e,i){const n=gn(t)/i,s=e||t.drawRange,r=s.start/i,o=(s.start+s.count)/i,a=Math.max(0,r),l=Math.min(n,o)-a;return{offset:Math.floor(a),count:Math.floor(l)}}(t,e,i),s=function(t,e){return t.groups.map((t=>({offset:t.start/e,count:t.count/e})))}(t,i);if(!s.length)return[n];const r=[],o=n.offset,a=n.offset+n.count,l=gn(t)/i,c=[];for(const t of s){const{offset:e,count:i}=t,n=e,s=e+(isFinite(i)?i:l-e);n<a&&s>o&&(c.push({pos:Math.max(o,n),isStart:!0}),c.push({pos:Math.min(a,s),isStart:!1}))}c.sort(((t,e)=>t.pos!==e.pos?t.pos-e.pos:"end"===t.type?-1:1));let h=0,u=null;for(const t of c){const e=t.pos;0!==h&&e!==u&&r.push({offset:u,count:e-u}),h+=t.isStart?1:-1,u=e}return r}class bn extends mn{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(t){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(t){}constructor(t,e={}){if(!t.isBufferGeometry)throw new Error("BVH: Only BufferGeometries are supported.");if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.");if(e.useSharedArrayBuffer&&"undefined"==typeof SharedArrayBuffer)throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=t,this.resolvePrimitiveIndex=e.indirect?t=>this._indirectBuffer[t]:t=>t,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,(e={..._i,...e})[yi]||this.init(e)}init(t){const{geometry:e,primitiveStride:i}=this;if(t.indirect){const n=function(t,e){const i=t[t.length-1],n=i.offset+i.count>65536,s=t.reduce(((t,e)=>t+e.count),0),r=n?4:2,o=e?new SharedArrayBuffer(s*r):new ArrayBuffer(s*r),a=n?new Uint32Array(o):new Uint16Array(o);let l=0;for(let e=0;e<t.length;e++){const{offset:i,count:n}=t[e];for(let t=0;t<n;t++)a[l+t]=i+t;l+=n}return a}(_n(e,t.range,i),t.useSharedArrayBuffer);this._indirectBuffer=n}else yn(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new a))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:_n(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class vn{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,n=-1/0;for(let s=0,r=t.length;s<r;s++){const r=t[s][e];i=r<i?r:i,n=r>n?r:n}this.min=i,this.max=n}setFromPoints(t,e){let i=1/0,n=-1/0;for(let s=0,r=e.length;s<r;s++){const r=e[s],o=t.dot(r);i=o<i?o:i,n=o>n?o:n}this.min=i,this.max=n}isSeparated(t){return this.min>t.max||t.min>this.max}}vn.prototype.setFromBox=function(){const t=new h;return function(e,i){const n=i.min,s=i.max;let r=1/0,o=-1/0;for(let i=0;i<=1;i++)for(let a=0;a<=1;a++)for(let l=0;l<=1;l++){t.x=n.x*i+s.x*(1-i),t.y=n.y*a+s.y*(1-a),t.z=n.z*l+s.z*(1-l);const c=e.dot(t);r=Math.min(c,r),o=Math.max(c,o)}this.min=r,this.max=o}}();const xn=function(){const t=new h,e=new h,i=new h;return function(n,s,r){const o=n.start,a=t,l=s.start,c=e;i.subVectors(o,l),t.subVectors(n.end,n.start),e.subVectors(s.end,s.start);const h=i.dot(c),u=c.dot(a),d=c.dot(c),p=i.dot(a),f=a.dot(a)*d-u*u;let m,g;m=0!==f?(h*u-p*d)/f:0,g=(h+m*u)/d,r.x=m,r.y=g}}(),Cn=function(){const t=new u,e=new h,i=new h;return function(n,s,r,o){xn(n,s,t);let a=t.x,l=t.y;if(a>=0&&a<=1&&l>=0&&l<=1)return n.at(a,r),void s.at(l,o);if(a>=0&&a<=1)return l<0?s.at(0,o):s.at(1,o),void n.closestPointToPoint(o,!0,r);if(l>=0&&l<=1)return a<0?n.at(0,r):n.at(1,r),void s.closestPointToPoint(r,!0,o);{let t,c;t=a<0?n.start:n.end,c=l<0?s.start:s.end;const h=e,u=i;return n.closestPointToPoint(c,!0,e),s.closestPointToPoint(t,!0,i),h.distanceToSquared(c)<=u.distanceToSquared(t)?(r.copy(h),void o.copy(c)):(r.copy(t),void o.copy(u))}}}(),Sn=function(){const t=new h,e=new h,i=new d,n=new p;return function(s,r){const{radius:o,center:a}=s,{a:l,b:c,c:h}=r;n.start=l,n.end=c;if(n.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;n.start=l,n.end=h;if(n.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;n.start=c,n.end=h;if(n.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;const u=r.getPlane(i);if(Math.abs(u.distanceToPoint(a))<=o){const t=u.projectPoint(a,e);if(r.containsPoint(t))return!0}return!1}}(),An=["x","y","z"],Pn=1e-15;function Tn(t){return Math.abs(t)<Pn}class En extends f{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map((()=>new h)),this.satBounds=new Array(4).fill().map((()=>new vn)),this.points=[this.a,this.b,this.c],this.plane=new d,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new p,this.needsUpdate=!0}intersectsSphere(t){return Sn(t,this)}update(){const t=this.a,e=this.b,i=this.c,n=this.points,s=this.satAxes,r=this.satBounds,o=s[0],a=r[0];this.getNormal(o),a.setFromPoints(o,n);const l=s[1],c=r[1];l.subVectors(t,e),c.setFromPoints(l,n);const h=s[2],u=r[2];h.subVectors(e,i),u.setFromPoints(h,n);const d=s[3],p=r[3];d.subVectors(i,t),p.setFromPoints(d,n);const f=l.length(),m=h.length(),g=d.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,f<Pn?m<Pn||g<Pn?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):m<Pn?g<Pn?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):g<Pn&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(o,t),this.needsUpdate=!1}}En.prototype.closestPointToSegment=function(){const t=new h,e=new h,i=new p;return function(n,s=null,r=null){const{start:o,end:a}=n,l=this.points;let c,h=1/0;for(let o=0;o<3;o++){const a=(o+1)%3;i.start.copy(l[o]),i.end.copy(l[a]),Cn(i,n,t,e),c=t.distanceToSquared(e),c<h&&(h=c,s&&s.copy(t),r&&r.copy(e))}return this.closestPointToPoint(o,t),c=o.distanceToSquared(t),c<h&&(h=c,s&&s.copy(t),r&&r.copy(o)),this.closestPointToPoint(a,t),c=a.distanceToSquared(t),c<h&&(h=c,s&&s.copy(t),r&&r.copy(a)),Math.sqrt(h)}}(),En.prototype.intersectsTriangle=function(){const t=new En,e=new vn,i=new vn,n=new h,s=new h,r=new h,o=new h,a=new p,l=new p,c=new h,d=new u,f=new u;function m(t,s,r,a){const l=n;t.isDegenerateIntoPoint||t.isDegenerateIntoSegment?l.copy(s.plane.normal):l.copy(t.plane.normal);const c=t.satBounds,h=t.satAxes;for(let n=1;n<4;n++){const r=c[n],a=h[n];if(e.setFromPoints(a,s.points),r.isSeparated(e))return!1;if(o.copy(l).cross(a),e.setFromPoints(o,t.points),i.setFromPoints(o,s.points),e.isSeparated(i))return!1}const u=s.satBounds,d=s.satAxes;for(let n=1;n<4;n++){const r=u[n],a=d[n];if(e.setFromPoints(a,t.points),r.isSeparated(e))return!1;if(o.crossVectors(l,a),e.setFromPoints(o,t.points),i.setFromPoints(o,s.points),e.isSeparated(i))return!1}return r&&(a||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),r.start.set(0,0,0),r.end.set(0,0,0)),!0}function g(t,e,i,n,s,r,o,a,l,c,h){let u=o/(o-a);c.x=n+(s-n)*u,h.start.subVectors(e,t).multiplyScalar(u).add(t),u=o/(o-l),c.y=n+(r-n)*u,h.end.subVectors(i,t).multiplyScalar(u).add(t)}function w(t,e,i,n,s,r,o,a,l,c,h){if(s>0)g(t.c,t.a,t.b,n,e,i,l,o,a,c,h);else if(r>0)g(t.b,t.a,t.c,i,e,n,a,o,l,c,h);else if(a*l>0||0!=o)g(t.a,t.b,t.c,e,i,n,o,a,l,c,h);else if(0!=a)g(t.b,t.a,t.c,i,e,n,a,o,l,c,h);else{if(0==l)return!0;g(t.c,t.a,t.b,n,e,i,l,o,a,c,h)}return!1}function y(t,e,i,s){const r=e.degenerateSegment,o=t.plane.distanceToPoint(r.start),a=t.plane.distanceToPoint(r.end);return Tn(o)?Tn(a)?m(t,e,i,s):(i&&(i.start.copy(r.start),i.end.copy(r.start)),t.containsPoint(r.start)):Tn(a)?(i&&(i.start.copy(r.end),i.end.copy(r.end)),t.containsPoint(r.end)):null!=t.plane.intersectLine(r,n)&&(i&&(i.start.copy(n),i.end.copy(n)),t.containsPoint(n))}function _(t,e,i){const n=e.a;return!(!Tn(t.plane.distanceToPoint(n))||!t.containsPoint(n))&&(i&&(i.start.copy(n),i.end.copy(n)),!0)}function b(t,e,i){const s=t.degenerateSegment,r=e.a;return s.closestPointToPoint(r,!0,n),r.distanceToSquared(n)<1e-30&&(i&&(i.start.copy(r),i.end.copy(r)),!0)}return function(e,i=null,o=!1){this.needsUpdate&&this.update(),e.isExtendedTriangle?e.needsUpdate&&e.update():(t.copy(e),t.update(),e=t);const h=function(t,e,i,o){if(t.isDegenerateIntoSegment){if(e.isDegenerateIntoSegment){const o=t.degenerateSegment,a=e.degenerateSegment,l=s,c=r;o.delta(l),a.delta(c);const h=n.subVectors(a.start,o.start),u=l.x*c.y-l.y*c.x;if(Tn(u))return!1;const d=(h.x*c.y-h.y*c.x)/u,p=-(l.x*h.y-l.y*h.x)/u;return!(d<0||d>1||p<0||p>1)&&(!!Tn(o.start.z+l.z*d-(a.start.z+c.z*p))&&(i&&(i.start.copy(o.start).addScaledVector(l,d),i.end.copy(o.start).addScaledVector(l,d)),!0))}return e.isDegenerateIntoPoint?b(t,e,i):y(e,t,i,o)}return t.isDegenerateIntoPoint?e.isDegenerateIntoPoint?e.a.distanceToSquared(t.a)<1e-30&&(i&&(i.start.copy(t.a),i.end.copy(t.a)),!0):e.isDegenerateIntoSegment?b(e,t,i):_(e,t,i):e.isDegenerateIntoPoint?_(t,e,i):e.isDegenerateIntoSegment?y(t,e,i,o):void 0}(this,e,i,o);if(void 0!==h)return h;const u=this.plane,p=e.plane;let g=p.distanceToPoint(this.a),v=p.distanceToPoint(this.b),x=p.distanceToPoint(this.c);Tn(g)&&(g=0),Tn(v)&&(v=0),Tn(x)&&(x=0);const C=g*v,S=g*x;if(C>0&&S>0)return!1;let A=u.distanceToPoint(e.a),P=u.distanceToPoint(e.b),T=u.distanceToPoint(e.c);Tn(A)&&(A=0),Tn(P)&&(P=0),Tn(T)&&(T=0);const E=A*P,M=A*T;if(E>0&&M>0)return!1;s.copy(u.normal),r.copy(p.normal);const I=s.cross(r);let z=0,D=Math.abs(I.x);const k=Math.abs(I.y);k>D&&(D=k,z=1);Math.abs(I.z)>D&&(z=2);const B=An[z],O=this.a[B],N=this.b[B],V=this.c[B],L=e.a[B],F=e.b[B],R=e.c[B];if(w(this,O,N,V,C,S,g,v,x,d,a))return m(this,e,i,o);if(w(e,L,F,R,E,M,A,P,T,f,l))return m(this,e,i,o);if(d.y<d.x){const t=d.y;d.y=d.x,d.x=t,c.copy(a.start),a.start.copy(a.end),a.end.copy(c)}if(f.y<f.x){const t=f.y;f.y=f.x,f.x=t,c.copy(l.start),l.start.copy(l.end),l.end.copy(c)}return!(d.y<f.x||f.y<d.x)&&(i&&(f.x>d.x?i.start.copy(l.start):i.start.copy(a.start),f.y<d.y?i.end.copy(l.end):i.end.copy(a.end)),!0)}}(),En.prototype.distanceToPoint=function(){const t=new h;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),En.prototype.distanceToTriangle=function(){const t=new h,e=new h,i=["a","b","c"],n=new p,s=new p;return function(r,o=null,a=null){const l=o||a?n:null;if(this.intersectsTriangle(r,l))return(o||a)&&(o&&l.getCenter(o),a&&l.getCenter(a)),0;let c=1/0;for(let e=0;e<3;e++){let n;const s=i[e],l=r[s];this.closestPointToPoint(l,t),n=l.distanceToSquared(t),n<c&&(c=n,o&&o.copy(t),a&&a.copy(l));const h=this[s];r.closestPointToPoint(h,t),n=h.distanceToSquared(t),n<c&&(c=n,o&&o.copy(h),a&&a.copy(t))}for(let l=0;l<3;l++){const h=i[l],u=i[(l+1)%3];n.set(this[h],this[u]);for(let l=0;l<3;l++){const h=i[l],u=i[(l+1)%3];s.set(r[h],r[u]),Cn(n,s,t,e);const d=t.distanceToSquared(e);d<c&&(c=d,o&&o.copy(t),a&&a.copy(e))}}return Math.sqrt(c)}}();class Mn{constructor(t,e,i){this.isOrientedBox=!0,this.min=new h,this.max=new h,this.matrix=new l,this.invMatrix=new l,this.points=new Array(8).fill().map((()=>new h)),this.satAxes=new Array(3).fill().map((()=>new h)),this.satBounds=new Array(3).fill().map((()=>new vn)),this.alignedSatBounds=new Array(3).fill().map((()=>new vn)),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}Mn.prototype.update=function(){return function(){const t=this.matrix,e=this.min,i=this.max,n=this.points;for(let s=0;s<=1;s++)for(let r=0;r<=1;r++)for(let o=0;o<=1;o++){const a=n[1*s|2*r|4*o];a.x=s?i.x:e.x,a.y=r?i.y:e.y,a.z=o?i.z:e.z,a.applyMatrix4(t)}const s=this.satBounds,r=this.satAxes,o=n[0];for(let t=0;t<3;t++){const e=r[t],i=s[t],a=n[1<<t];e.subVectors(o,a),i.setFromPoints(e,n)}const a=this.alignedSatBounds;a[0].setFromPointsField(n,"x"),a[1].setFromPointsField(n,"y"),a[2].setFromPointsField(n,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}(),Mn.prototype.intersectsBox=function(){const t=new vn;return function(e){this.needsUpdate&&this.update();const i=e.min,n=e.max,s=this.satBounds,r=this.satAxes,o=this.alignedSatBounds;if(t.min=i.x,t.max=n.x,o[0].isSeparated(t))return!1;if(t.min=i.y,t.max=n.y,o[1].isSeparated(t))return!1;if(t.min=i.z,t.max=n.z,o[2].isSeparated(t))return!1;for(let i=0;i<3;i++){const n=r[i],o=s[i];if(t.setFromBox(n,e),o.isSeparated(t))return!1}return!0}}(),Mn.prototype.intersectsTriangle=function(){const t=new En,e=new Array(3),i=new vn,n=new vn,s=new h;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(t.copy(r),t.update(),r=t);const o=this.satBounds,a=this.satAxes;e[0]=r.a,e[1]=r.b,e[2]=r.c;for(let t=0;t<3;t++){const n=o[t],s=a[t];if(i.setFromPoints(s,e),n.isSeparated(i))return!1}const l=r.satBounds,c=r.satAxes,h=this.points;for(let t=0;t<3;t++){const e=l[t],n=c[t];if(i.setFromPoints(n,h),e.isSeparated(i))return!1}for(let t=0;t<3;t++){const r=a[t];for(let t=0;t<4;t++){const o=c[t];if(s.crossVectors(r,o),i.setFromPoints(s,e),n.setFromPoints(s,h),i.isSeparated(n))return!1}}return!0}}(),Mn.prototype.closestPointToPoint=function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}}(),Mn.prototype.distanceToPoint=function(){const t=new h;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),Mn.prototype.distanceToBox=function(){const t=["x","y","z"],e=new Array(12).fill().map((()=>new p)),i=new Array(12).fill().map((()=>new p)),n=new h,s=new h;return function(r,o=0,a=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(a||l)&&(r.getCenter(s),this.closestPointToPoint(s,n),r.closestPointToPoint(n,s),a&&a.copy(n),l&&l.copy(s)),0;const c=o*o,h=r.min,u=r.max,d=this.points;let p=1/0;for(let t=0;t<8;t++){const e=d[t];s.copy(e).clamp(h,u);const i=e.distanceToSquared(s);if(i<p&&(p=i,a&&a.copy(e),l&&l.copy(s),i<c))return Math.sqrt(i)}let f=0;for(let n=0;n<3;n++)for(let s=0;s<=1;s++)for(let r=0;r<=1;r++){const o=(n+1)%3,a=(n+2)%3,l=1<<n|s<<o|r<<a,c=d[s<<o|r<<a],p=d[l];e[f].set(c,p);const m=t[n],g=t[o],w=t[a],y=i[f],_=y.start,b=y.end;_[m]=h[m],_[g]=s?h[g]:u[g],_[w]=r?h[w]:u[g],b[m]=u[m],b[g]=s?h[g]:u[g],b[w]=r?h[w]:u[g],f++}for(let t=0;t<=1;t++)for(let e=0;e<=1;e++)for(let i=0;i<=1;i++){s.x=t?u.x:h.x,s.y=e?u.y:h.y,s.z=i?u.z:h.z,this.closestPointToPoint(s,n);const r=s.distanceToSquared(n);if(r<p&&(p=r,a&&a.copy(n),l&&l.copy(s),r<c))return Math.sqrt(r)}for(let t=0;t<12;t++){const r=e[t];for(let t=0;t<12;t++){const e=i[t];Cn(r,e,n,s);const o=n.distanceToSquared(s);if(o<p&&(p=o,a&&a.copy(n),l&&l.copy(s),o<c))return Math.sqrt(o)}}return Math.sqrt(p)}}();class In extends qi{constructor(){super((()=>new En))}}const zn=new In,Dn=new h,kn=new h;const Bn=parseInt(m)>=169,On=parseInt(m)<=161,Nn=new h,Vn=new h,Ln=new h,Fn=new u,Rn=new u,Un=new u,jn=new h,$n=new h,Wn=new h,Gn=new h;function Hn(t,e,i,n,s,r,o,a,l,c,d){Nn.fromBufferAttribute(e,r),Vn.fromBufferAttribute(e,o),Ln.fromBufferAttribute(e,a);const p=function(t,e,i,n,s,r,o,a){let l;if(l=r===g?t.intersectTriangle(n,i,e,!0,s):t.intersectTriangle(e,i,n,r!==w,s),null===l)return null;const c=t.origin.distanceTo(s);return c<o||c>a?null:{distance:c,point:s.clone()}}(t,Nn,Vn,Ln,Gn,l,c,d);if(p){if(n){Fn.fromBufferAttribute(n,r),Rn.fromBufferAttribute(n,o),Un.fromBufferAttribute(n,a),p.uv=new u;const t=f.getInterpolation(Gn,Nn,Vn,Ln,Fn,Rn,Un,p.uv);Bn||(p.uv=t)}if(s){Fn.fromBufferAttribute(s,r),Rn.fromBufferAttribute(s,o),Un.fromBufferAttribute(s,a),p.uv1=new u;const t=f.getInterpolation(Gn,Nn,Vn,Ln,Fn,Rn,Un,p.uv1);Bn||(p.uv1=t),On&&(p.uv2=p.uv1)}if(i){jn.fromBufferAttribute(i,r),$n.fromBufferAttribute(i,o),Wn.fromBufferAttribute(i,a),p.normal=new h;const e=f.getInterpolation(Gn,Nn,Vn,Ln,jn,$n,Wn,p.normal);p.normal.dot(t.direction)>0&&p.normal.multiplyScalar(-1),Bn||(p.normal=e)}const e={a:r,b:o,c:a,normal:new h,materialIndex:0};if(f.getNormal(Nn,Vn,Ln,e.normal),p.face=e,p.faceIndex=r,Bn){const t=new h;f.getBarycoord(Gn,Nn,Vn,Ln,t),p.barycoord=t}}return p}function Zn(t){return t&&t.isMaterial?t.side:t}function qn(t,e,i,n,s,r,o){const a=3*n;let l=a+0,c=a+1,h=a+2;const{index:u,groups:d}=t;t.index&&(l=u.getX(l),c=u.getX(c),h=u.getX(h));const{position:p,normal:f,uv:m,uv1:g}=t.attributes;if(Array.isArray(e)){const t=3*n;for(let a=0,u=d.length;a<u;a++){const{start:u,count:w,materialIndex:y}=d[a];if(t>=u&&t<u+w){const t=Hn(i,p,f,m,g,l,c,h,Zn(e[y]),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=y,!s)return t;s.push(t)}}}}else{const t=Hn(i,p,f,m,g,l,c,h,Zn(e),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=0,!s)return t;s.push(t)}}return null}function Yn(t,e,i,n){const s=t.a,r=t.b,o=t.c;let a=e,l=e+1,c=e+2;i&&(a=i.getX(a),l=i.getX(l),c=i.getX(c)),s.x=n.getX(a),s.y=n.getY(a),s.z=n.getZ(a),r.x=n.getX(l),r.y=n.getY(l),r.z=n.getZ(l),o.x=n.getX(c),o.y=n.getY(c),o.z=n.getZ(c)}function Xn(t,e,i,n,s,r,o){const{geometry:a}=i,{index:l}=a,c=a.attributes.position;for(let i=t,a=e+t;i<a;i++){let t;if(t=i,Yn(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}function Kn(t,e=null){e&&Array.isArray(e)&&(e=new Set(e));const i=t.geometry,n=i.index?i.index.array:null,s=i.attributes.position;let r,o,a,l,c=0;const h=t._roots;for(let t=0,e=h.length;t<e;t++)r=h[t],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),u(0,c),c+=r.byteLength;function u(t,i,r=!1){const c=2*t;if(Pi(c,a)){const e=Ti(t,o);let i=1/0,r=1/0,h=1/0,u=-1/0,d=-1/0,p=-1/0;for(let t=3*e,o=3*(e+Ei(c,a));t<o;t++){let e=n[t];const o=s.getX(e),a=s.getY(e),l=s.getZ(e);o<i&&(i=o),o>u&&(u=o),a<r&&(r=a),a>d&&(d=a),l<h&&(h=l),l>p&&(p=l)}return(l[t+0]!==i||l[t+1]!==r||l[t+2]!==h||l[t+3]!==u||l[t+4]!==d||l[t+5]!==p)&&(l[t+0]=i,l[t+1]=r,l[t+2]=h,l[t+3]=u,l[t+4]=d,l[t+5]=p,!0)}{const n=Mi(t),s=Ii(t,o);let a=r,c=!1,h=!1;if(e){if(!a){const t=n/8+i/gi,r=s/8+i/gi;c=e.has(t),h=e.has(r),a=!c&&!h}}else c=!0,h=!0;const d=a||h;let p=!1;(a||c)&&(p=u(n,i,a));let f=!1;d&&(f=u(s,i,a));const m=p||f;if(m)for(let e=0;e<3;e++){const i=n+e,r=s+e,o=l[i],a=l[i+3],c=l[r],h=l[r+3];l[t+e]=o<c?o:c,l[t+e+3]=a>h?a:h}return m}}}function Qn(t,e,i,n,s){let r,o,a,l,c,h;const u=1/i.direction.x,d=1/i.direction.y,p=1/i.direction.z,f=i.origin.x,m=i.origin.y,g=i.origin.z;let w=e[t],y=e[t+3],_=e[t+1],b=e[t+3+1],v=e[t+2],x=e[t+3+2];return u>=0?(r=(w-f)*u,o=(y-f)*u):(r=(y-f)*u,o=(w-f)*u),d>=0?(a=(_-m)*d,l=(b-m)*d):(a=(b-m)*d,l=(_-m)*d),!(r>l||a>o)&&((a>r||isNaN(r))&&(r=a),(l<o||isNaN(o))&&(o=l),p>=0?(c=(v-g)*p,h=(x-g)*p):(c=(x-g)*p,h=(v-g)*p),!(r>h||c>o)&&((c>r||r!=r)&&(r=c),(h<o||o!=o)&&(o=h),r<=s&&o>=n))}function Jn(t,e,i,n,s,r,o){const{geometry:a}=i,{index:l}=a,c=a.attributes.position;for(let a=t,h=e+t;a<h;a++){let t;if(t=i.resolveTriangleIndex(a),Yn(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}function ts(t,e,i,n,s,r,o){Xi.setBuffer(t._roots[e]),es(0,t,i,n,s,r,o),Xi.clearBuffer()}function es(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Xi,h=2*t;if(Pi(h,l)){!function(t,e,i,n,s,r,o,a){const{geometry:l,_indirectBuffer:c}=t;for(let t=n,c=n+s;t<c;t++)qn(l,e,i,t,r,o,a)}(e,i,n,Ti(t,c),Ei(h,l),s,r,o)}else{const l=Mi(t);Qn(l,a,n,r,o)&&es(l,e,i,n,s,r,o);const h=Ii(t,c);Qn(h,a,n,r,o)&&es(h,e,i,n,s,r,o)}}const is=["x","y","z"];function ns(t,e,i,n,s,r){Xi.setBuffer(t._roots[e]);const o=ss(0,t,i,n,s,r);return Xi.clearBuffer(),o}function ss(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Xi;let c=2*t;if(Pi(c,a)){return function(t,e,i,n,s,r,o){const{geometry:a,_indirectBuffer:l}=t;let c=1/0,h=null;for(let t=n,l=n+s;t<l;t++){let n;n=qn(a,e,i,t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,Ti(t,l),Ei(c,a),s,r)}{const a=zi(t,l),c=is[a],h=n.direction[c]>=0;let u,d;h?(u=Mi(t),d=Ii(t,l)):(u=Ii(t,l),d=Mi(t));const p=Qn(u,o,n,s,r)?ss(u,e,i,n,s,r):null;if(p){const t=p.point[c];if(h?t<=o[d+a]:t>=o[d+a+3])return p}const f=Qn(d,o,n,s,r)?ss(d,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const rs=new a,os=new En,as=new En,ls=new l,cs=new Mn,hs=new Mn;function us(t,e,i,n){Xi.setBuffer(t._roots[e]);const s=ds(0,t,i,n);return Xi.clearBuffer(),s}function ds(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Xi;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),cs.set(i.boundingBox.min,i.boundingBox.max,n),s=cs);if(!Pi(l,o)){const o=Mi(t),l=Ii(t,a);bi(o,r,rs);if(s.intersectsBox(rs)&&ds(o,e,i,n,s))return!0;bi(l,r,rs);return!!(s.intersectsBox(rs)&&ds(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,u=i.index,d=i.attributes.position,p=Ti(t,a),f=Ei(l,o);if(ls.copy(n).invert(),i.boundsTree){bi(t,r,hs),hs.matrix.copy(ls),hs.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>hs.intersectsBox(t),intersectsTriangle:t=>{t.a.applyMatrix4(n),t.b.applyMatrix4(n),t.c.applyMatrix4(n),t.needsUpdate=!0;for(let e=3*p,i=3*(f+p);e<i;e+=3)if(Yn(as,e,c,h),as.needsUpdate=!0,t.intersectsTriangle(as))return!0;return!1}})}{const t=wn(i);for(let e=3*p,i=3*(f+p);e<i;e+=3){Yn(os,e,c,h),os.a.applyMatrix4(ls),os.b.applyMatrix4(ls),os.c.applyMatrix4(ls),os.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(Yn(as,e,u,d),as.needsUpdate=!0,os.intersectsTriangle(as))return!0}}}}const ps=new l,fs=new Mn,ms=new Mn,gs=new h,ws=new h,ys=new h,_s=new h;function bs(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),fs.set(e.boundingBox.min,e.boundingBox.max,i),fs.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,u=e.index,d=zn.getPrimitive(),p=zn.getPrimitive();let f=gs,m=ws,g=null,w=null;s&&(g=ys,w=_s);let y=1/0,_=null,b=null;return ps.copy(i).invert(),ms.matrix.copy(ps),t.shapecast({boundsTraverseOrder:t=>fs.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(ms.min.copy(t.min),ms.max.copy(t.max),ms.needsUpdate=!0),!0),intersectsRange:(t,n)=>{if(e.boundsTree){return e.boundsTree.shapecast({boundsTraverseOrder:t=>ms.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,s)=>{for(let o=e,a=e+s;o<a;o++){Yn(p,3*o,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=t,i=t+n;e<i;e++){Yn(d,3*e,c,l),d.needsUpdate=!0;const t=d.distanceToTriangle(p,f,g);if(t<y&&(m.copy(f),w&&w.copy(g),y=t,_=e,b=o),t<r)return!0}}}})}for(let s=0,o=wn(e);s<o;s++){Yn(p,3*s,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=t,i=t+n;e<i;e++){Yn(d,3*e,c,l),d.needsUpdate=!0;const t=d.distanceToTriangle(p,f,g);if(t<y&&(m.copy(f),w&&w.copy(g),y=t,_=e,b=s),t<r)return!0}}}}),zn.releasePrimitive(d),zn.releasePrimitive(p),y===1/0?null:(n.point?n.point.copy(m):n.point=m.clone(),n.distance=y,n.faceIndex=_,s&&(s.point?s.point.copy(w):s.point=w.clone(),s.point.applyMatrix4(ps),m.applyMatrix4(ps),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function vs(t,e=null){e&&Array.isArray(e)&&(e=new Set(e));const i=t.geometry,n=i.index?i.index.array:null,s=i.attributes.position;let r,o,a,l,c=0;const h=t._roots;for(let t=0,e=h.length;t<e;t++)r=h[t],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),u(0,c),c+=r.byteLength;function u(i,r,c=!1){const h=2*i;if(Pi(h,a)){const e=Ti(i,o);let r=1/0,c=1/0,u=1/0,d=-1/0,p=-1/0,f=-1/0;for(let i=e,o=e+Ei(h,a);i<o;i++){const e=3*t.resolveTriangleIndex(i);for(let t=0;t<3;t++){let i=e+t;i=n?n[i]:i;const o=s.getX(i),a=s.getY(i),l=s.getZ(i);o<r&&(r=o),o>d&&(d=o),a<c&&(c=a),a>p&&(p=a),l<u&&(u=l),l>f&&(f=l)}}return(l[i+0]!==r||l[i+1]!==c||l[i+2]!==u||l[i+3]!==d||l[i+4]!==p||l[i+5]!==f)&&(l[i+0]=r,l[i+1]=c,l[i+2]=u,l[i+3]=d,l[i+4]=p,l[i+5]=f,!0)}{const t=Mi(i),n=Ii(i,o);let s=c,a=!1,h=!1;if(e){if(!s){const i=t/8+r/gi,o=n/8+r/gi;a=e.has(i),h=e.has(o),s=!a&&!h}}else a=!0,h=!0;const d=s||h;let p=!1;(s||a)&&(p=u(t,r,s));let f=!1;d&&(f=u(n,r,s));const m=p||f;if(m)for(let e=0;e<3;e++){const s=t+e,r=n+e,o=l[s],a=l[s+3],c=l[r],h=l[r+3];l[i+e]=o<c?o:c,l[i+e+3]=a>h?a:h}return m}}}function xs(t,e,i,n,s,r,o){Xi.setBuffer(t._roots[e]),Cs(0,t,i,n,s,r,o),Xi.clearBuffer()}function Cs(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Xi,h=2*t;if(Pi(h,l)){!function(t,e,i,n,s,r,o,a){const{geometry:l,_indirectBuffer:c}=t;for(let t=n,h=n+s;t<h;t++)qn(l,e,i,c?c[t]:t,r,o,a)}(e,i,n,Ti(t,c),Ei(h,l),s,r,o)}else{const l=Mi(t);Qn(l,a,n,r,o)&&Cs(l,e,i,n,s,r,o);const h=Ii(t,c);Qn(h,a,n,r,o)&&Cs(h,e,i,n,s,r,o)}}const Ss=["x","y","z"];function As(t,e,i,n,s,r){Xi.setBuffer(t._roots[e]);const o=Ps(0,t,i,n,s,r);return Xi.clearBuffer(),o}function Ps(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Xi;let c=2*t;if(Pi(c,a)){return function(t,e,i,n,s,r,o){const{geometry:a,_indirectBuffer:l}=t;let c=1/0,h=null;for(let t=n,u=n+s;t<u;t++){let n;n=qn(a,e,i,l?l[t]:t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,Ti(t,l),Ei(c,a),s,r)}{const a=zi(t,l),c=Ss[a],h=n.direction[c]>=0;let u,d;h?(u=Mi(t),d=Ii(t,l)):(u=Ii(t,l),d=Mi(t));const p=Qn(u,o,n,s,r)?Ps(u,e,i,n,s,r):null;if(p){const t=p.point[c];if(h?t<=o[d+a]:t>=o[d+a+3])return p}const f=Qn(d,o,n,s,r)?Ps(d,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const Ts=new a,Es=new En,Ms=new En,Is=new l,zs=new Mn,Ds=new Mn;function ks(t,e,i,n){Xi.setBuffer(t._roots[e]);const s=Bs(0,t,i,n);return Xi.clearBuffer(),s}function Bs(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Xi;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),zs.set(i.boundingBox.min,i.boundingBox.max,n),s=zs);if(!Pi(l,o)){const o=Mi(t),l=Ii(t,a);bi(o,r,Ts);if(s.intersectsBox(Ts)&&Bs(o,e,i,n,s))return!0;bi(l,r,Ts);return!!(s.intersectsBox(Ts)&&Bs(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,u=i.index,d=i.attributes.position,p=Ti(t,a),f=Ei(l,o);if(Is.copy(n).invert(),i.boundsTree){bi(t,r,Ds),Ds.matrix.copy(Is),Ds.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>Ds.intersectsBox(t),intersectsTriangle:t=>{t.a.applyMatrix4(n),t.b.applyMatrix4(n),t.c.applyMatrix4(n),t.needsUpdate=!0;for(let i=p,n=f+p;i<n;i++)if(Yn(Ms,3*e.resolveTriangleIndex(i),c,h),Ms.needsUpdate=!0,t.intersectsTriangle(Ms))return!0;return!1}})}{const t=wn(i);for(let i=p,n=f+p;i<n;i++){const n=e.resolveTriangleIndex(i);Yn(Es,3*n,c,h),Es.a.applyMatrix4(Is),Es.b.applyMatrix4(Is),Es.c.applyMatrix4(Is),Es.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(Yn(Ms,e,u,d),Ms.needsUpdate=!0,Es.intersectsTriangle(Ms))return!0}}}}const Os=new l,Ns=new Mn,Vs=new Mn,Ls=new h,Fs=new h,Rs=new h,Us=new h;function js(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Ns.set(e.boundingBox.min,e.boundingBox.max,i),Ns.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,u=e.index,d=zn.getPrimitive(),p=zn.getPrimitive();let f=Ls,m=Fs,g=null,w=null;s&&(g=Rs,w=Us);let y=1/0,_=null,b=null;return Os.copy(i).invert(),Vs.matrix.copy(Os),t.shapecast({boundsTraverseOrder:t=>Ns.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(Vs.min.copy(t.min),Vs.max.copy(t.max),Vs.needsUpdate=!0),!0),intersectsRange:(n,s)=>{if(e.boundsTree){const a=e.boundsTree;return a.shapecast({boundsTraverseOrder:t=>Vs.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,o)=>{for(let v=e,x=e+o;v<x;v++){const e=a.resolveTriangleIndex(v);Yn(p,3*e,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=n,i=n+s;e<i;e++){const i=t.resolveTriangleIndex(e);Yn(d,3*i,c,l),d.needsUpdate=!0;const n=d.distanceToTriangle(p,f,g);if(n<y&&(m.copy(f),w&&w.copy(g),y=n,_=e,b=v),n<r)return!0}}}})}for(let o=0,a=wn(e);o<a;o++){Yn(p,3*o,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=n,i=n+s;e<i;e++){const i=t.resolveTriangleIndex(e);Yn(d,3*i,c,l),d.needsUpdate=!0;const n=d.distanceToTriangle(p,f,g);if(n<y&&(m.copy(f),w&&w.copy(g),y=n,_=e,b=o),n<r)return!0}}}}),zn.releasePrimitive(d),zn.releasePrimitive(p),y===1/0?null:(n.point?n.point.copy(m):n.point=m.clone(),n.distance=y,n.faceIndex=_,s&&(s.point?s.point.copy(w):s.point=w.clone(),s.point.applyMatrix4(Os),m.applyMatrix4(Os),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function $s(t,e,i){return null===t?null:(t.point.applyMatrix4(e.matrixWorld),t.distance=t.point.distanceTo(i.ray.origin),t.object=e,t)}const Ws=new Mn,Gs=new _,Hs=new h,Zs=new l,qs=new h,Ys=["getX","getY","getZ"];class Xs extends bn{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,n=t._roots,s=t._indirectBuffer,r=i.getIndex(),o={version:1,roots:null,index:null,indirectBuffer:null};return e.cloneBuffers?(o.roots=n.map((t=>t.slice())),o.index=r?r.array.slice():null,o.indirectBuffer=s?s.slice():null):(o.roots=n,o.index=r?r.array:null,o.indirectBuffer=s),o}static deserialize(t,e,i={}){i={setIndex:!0,indirect:Boolean(t.indirectBuffer),...i};const{index:n,roots:s,indirectBuffer:r}=t;t.version||(console.warn("MeshBVH.deserialize: Serialization format has been changed and will be fixed up. It is recommended to regenerate any stored serialized data."),function(t){for(let e=0;e<t.length;e++){const i=t[e],n=new Uint32Array(i),s=new Uint16Array(i);for(let t=0,e=i.byteLength/gi;t<e;t++){const e=8*t;Pi(2*e,s)||(n[e+6]=n[e+6]/8-t)}}}(s));const o=new Xs(e,{...i,[yi]:!0});if(o._roots=s,o._indirectBuffer=r||null,i.setIndex){const i=e.getIndex();if(null===i){const i=new c(t.index,1,!1);e.setIndex(i)}else i.array!==n&&(i.array.set(n),i.needsUpdate=!0)}return o}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(t,e={}){e.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use maxLeafSize, instead.'),e={...e,maxLeafSize:e.maxLeafTris}),super(t,e)}shiftTriangleOffsets(t){return super.shiftPrimitiveOffsets(t)}writePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,o=n.index?n.index.array:null,a=3*(s?s[t]:t);let l=a+0,c=a+1,h=a+2;o&&(l=o[l],c=o[c],h=o[h]);for(let t=0;t<3;t++){const n=r[Ys[t]](l),s=r[Ys[t]](c),o=r[Ys[t]](h);let a=n;s<a&&(a=s),o<a&&(a=o);let u=n;s>u&&(u=s),o>u&&(u=o),e[i+t]=a,e[i+t+3]=u}return e}computePrimitiveBounds(t,e,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,o=n.index?n.index.array:null,a=r.normalized;if(t<0||e+t-i.offset>i.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=r.array,c=r.offset||0;let h=3;r.isInterleavedBufferAttribute&&(h=r.data.stride);const u=["getX","getY","getZ"],d=i.offset;for(let n=t,p=t+e;n<p;n++){const t=3*(s?s[n]:n),e=6*(n-d);let p=t+0,f=t+1,m=t+2;o&&(p=o[p],f=o[f],m=o[m]),a||(p=p*h+c,f=f*h+c,m=m*h+c);for(let t=0;t<3;t++){let n,s,o;a?(n=r[u[t]](p),s=r[u[t]](f),o=r[u[t]](m)):(n=l[p+t],s=l[f+t],o=l[m+t]);let c=n;s<c&&(c=s),o<c&&(c=o);let h=n;s>h&&(h=s),o>h&&(h=o);const d=(h-c)/2,g=2*t;i[e+g+0]=c+d,i[e+g+1]=d+(Math.abs(c)+d)*wi}}return i}raycastObject3D(t,e,i=[]){const{material:n}=t;if(void 0===n)return;Zs.copy(t.matrixWorld).invert(),Gs.copy(e.ray).applyMatrix4(Zs),qs.setFromMatrixScale(t.matrixWorld),Hs.copy(Gs.direction).multiply(qs);const s=Hs.length(),r=e.near/s,o=e.far/s;if(!0===e.firstHitOnly){let s=this.raycastFirst(Gs,n,r,o);s=$s(s,t,e),s&&i.push(s)}else{const s=this.raycast(Gs,n,r,o);for(let n=0,r=s.length;n<r;n++){const r=$s(s[n],t,e);r&&i.push(r)}}return i}refit(t=null){return(this.indirect?vs:Kn)(this,t)}raycast(t,e=y,i=0,n=1/0){const s=this._roots,r=[],o=this.indirect?xs:ts;for(let a=0,l=s.length;a<l;a++)o(this,a,e,t,r,i,n);return r}raycastFirst(t,e=y,i=0,n=1/0){const s=this._roots;let r=null;const o=this.indirect?As:ns;for(let a=0,l=s.length;a<l;a++){const s=o(this,a,e,t,i,n);null!=s&&(null==r||s.distance<r.distance)&&(r=s)}return r}intersectsGeometry(t,e){let i=!1;const n=this._roots,s=this.indirect?ks:us;for(let r=0,o=n.length;r<o&&(i=s(this,r,t,e),!i);r++);return i}shapecast(t){const e=zn.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?Jn:Xn});return zn.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=zn.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?t=>{const e=this.resolveTriangleIndex(t);Yn(r,3*e,o,a)}:t=>{Yn(r,3*t,o,a)},c=zn.getPrimitive(),h=t.geometry.index,u=t.geometry.attributes.position,d=t.indirect?e=>{const i=t.resolveTriangleIndex(e);Yn(c,3*i,h,u)}:t=>{Yn(c,3*t,h,u)};if(s){if(!(t instanceof Xs))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const i=(t,i,n,o,a,h,u,p)=>{for(let f=n,m=n+o;f<m;f++){d(f),c.a.applyMatrix4(e),c.b.applyMatrix4(e),c.c.applyMatrix4(e),c.needsUpdate=!0;for(let e=t,n=t+i;e<n;e++)if(l(e),r.needsUpdate=!0,s(r,c,e,f,a,h,u,p))return!0}return!1};if(n){const t=n;n=function(e,n,s,r,o,a,l,c){return!!t(e,n,s,r,o,a,l,c)||i(e,n,s,r,o,a,l,c)}}else n=i}return super.bvhcast(t,e,{intersectsRanges:n})}intersectsBox(t,e){return Ws.set(t.min,t.max,e),Ws.needsUpdate=!0,this.shapecast({intersectsBounds:t=>Ws.intersectsBox(t),intersectsTriangle:t=>Ws.intersectsTriangle(t)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},n={},s=0,r=1/0){return(this.indirect?js:bs)(this,t,e,i,n,s,r)}closestPointToPoint(t,e={},i=0,n=1/0){return function(t,e,i={},n=0,s=1/0){const r=n*n,o=s*s;let a=1/0,l=null;if(t.shapecast({boundsTraverseOrder:t=>(Dn.copy(e).clamp(t.min,t.max),Dn.distanceToSquared(e)),intersectsBounds:(t,e,i)=>i<a&&i<o,intersectsTriangle:(t,i)=>{t.closestPointToPoint(e,Dn);const n=e.distanceToSquared(Dn);return n<a&&(kn.copy(Dn),a=n,l=i),n<r}}),a===1/0)return null;const c=Math.sqrt(a);return i.point?i.point.copy(kn):i.point=kn.clone(),i.distance=c,i.faceIndex=l,i}(this,t,e,i,n)}}const Ks=new l,Qs=new _,Js=new qi((()=>new p)),tr=new h,er=new h,ir=new a,nr=["getX","getY","getZ"];class sr extends bn{get primitiveStride(){return 2}writePrimitiveBounds(t,e,i){const n=this._indirectBuffer,{geometry:s,primitiveStride:r}=this,o=s.attributes.position,a=s.index,l=a?a.count:o.count;let c=(n?n[t]:t)*r,h=(c+1)%l;a&&(c=a.getX(c),h=a.getX(h));for(let t=0;t<3;t++){const n=o[nr[t]](c),s=o[nr[t]](h),r=n<s?n:s,a=n>s?n:s;e[i+t]=r,e[i+t+3]=a}return e}shapecast(t){const e=Js.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsLine,scratchPrimitive:e,iterate:rr});return Js.releasePrimitive(e),i}raycastObject3D(t,e,i=[]){const{matrixWorld:n}=t,{firstHitOnly:s}=e;Ks.copy(n).invert(),Qs.copy(e.ray).applyMatrix4(Ks);const r=e.params.Line.threshold/((t.scale.x+t.scale.y+t.scale.z)/3),o=r*r;let a=null,l=1/0;return this.shapecast({boundsTraverseOrder:t=>t.distanceToPoint(Qs.origin),intersectsBounds:t=>(ir.copy(t).expandByScalar(Math.abs(r)),Qs.intersectsBox(ir)?1:0),intersectsLine:(r,c)=>{if(Qs.distanceSqToSegment(r.start,r.end,tr,er)>o)return;tr.applyMatrix4(t.matrixWorld);const h=e.ray.origin.distanceTo(tr);h<e.near||h>e.far||s&&h>=l||(l=h,c=this.resolvePrimitiveIndex(c),a={distance:h,point:er.clone().applyMatrix4(n),index:c*this.primitiveStride,face:null,faceIndex:null,barycoord:null,object:t},s||i.push(a))}}),s&&a&&i.push(a),i}}function rr(t,e,i,n,s,r,o){const{geometry:a,primitiveStride:l}=i,{index:c}=a,h=a.attributes.position,u=c?c.count:h.count;for(let a=t,d=e+t;a<d;a++){let t=i.resolvePrimitiveIndex(a)*l,e=(t+1)%u;if(c&&(t=c.getX(t),e=c.getX(e)),o.start.fromBufferAttribute(h,t),o.end.fromBufferAttribute(h,e),n(o,a,s,r))return!0}return!1}const or={Mesh:b.prototype.raycast,Line:v.prototype.raycast,LineSegments:x.prototype.raycast,LineLoop:C.prototype.raycast,Points:S.prototype.raycast,BatchedMesh:A.prototype.raycast},ar=new b,lr=[];function cr(t,e){if(this.isBatchedMesh)hr.call(this,t,e);else{const{geometry:i}=this;if(i.boundsTree)i.boundsTree.raycastObject3D(this,t,e);else{let i;if(this instanceof b)i=or.Mesh;else if(this instanceof x)i=or.LineSegments;else if(this instanceof C)i=or.LineLoop;else if(this instanceof v)i=or.Line;else{if(!(this instanceof S))throw new Error("BVH: Fallback raycast function not found.");i=or.Points}i.call(this,t,e)}}}function hr(t,e){if(this.boundsTrees){const i=this.boundsTrees,n=this._drawInfo||this._instanceInfo,s=this._drawRanges||this._geometryInfo,r=this.matrixWorld;ar.material=this.material,ar.geometry=this.geometry;const o=ar.geometry.boundsTree,a=ar.geometry.drawRange;null===ar.geometry.boundingSphere&&(ar.geometry.boundingSphere=new P);for(let o=0,a=n.length;o<a;o++){if(!this.getVisibleAt(o))continue;const a=n[o].geometryIndex;if(ar.geometry.boundsTree=i[a],this.getMatrixAt(o,ar.matrixWorld).premultiply(r),!ar.geometry.boundsTree){this.getBoundingBoxAt(a,ar.geometry.boundingBox),this.getBoundingSphereAt(a,ar.geometry.boundingSphere);const t=s[a];ar.geometry.setDrawRange(t.start,t.count)}ar.raycast(t,lr);for(let t=0,i=lr.length;t<i;t++){const i=lr[t];i.object=this,i.batchId=o,e.push(i)}lr.length=0}ar.geometry.boundsTree=o,ar.geometry.drawRange=a,ar.material=null,ar.geometry=null}else or.BatchedMesh.call(this,t,e)}function ur(t={}){const{type:e=Xs}=t;return this.boundsTree=new e(this,t),this.boundsTree}function dr(){this.boundsTree=null}const pr=class t extends ht{constructor(i){super(i),e(this,"onDisposed",new at),e(this,"onBeforeDispose",new at),e(this,"onFragmentsLoaded",new at),e(this,"baseCoordinationModel",""),e(this,"baseCoordinationMatrix",new o.Matrix4),e(this,"enabled",!0),e(this,"_core"),this.components.add(t.uuid,this)}static getWorker(){return s.getWorker()}get initialized(){return!!this._core}get list(){return this.core.models.list}get core(){if(!this._core)throw new Error("FragmentsManager not initialized. Call init() first.");return this._core}get _hasCoordinationModel(){return""!==this.baseCoordinationModel}dispose(){this.onBeforeDispose.trigger(),this._core&&(this.core.dispose(),this._core=void 0),this.baseCoordinationModel="",this.onFragmentsLoaded.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}init(t,e){this._core=new s(t,e),this.core.onModelLoaded.add((async()=>{if(this._hasCoordinationModel)return;const t=[...this.list.values()][0];t&&(this.baseCoordinationModel=t.modelId,this.baseCoordinationMatrix=await t.getCoordinationMatrix())})),this.list.onItemDeleted.add((()=>{this.list.size>0||(this.baseCoordinationModel="",this.baseCoordinationMatrix=new o.Matrix4)}))}async raycast(t){const e=[];for(const i of this.core.models.list.values())if(t.snappingClasses&&t.snappingClasses.length>0){const n=await i.raycastWithSnapping(t);if(n&&n.length>0)e.push(n[0]);else{const n=await i.raycast(t);n&&e.push(n)}}else{const n=await i.raycast(t);n&&e.push(n)}if(await Promise.all(e),0===e.length)return;let i=e[0],n=i.distance;for(let t=1;t<e.length;t++)e[t].distance<n&&(n=e[t].distance,i=e[t]);return i}async getPositions(t){const e=[],i=async(t,i)=>{const n=await t.getPositions(i);for(const t of n)e.push(t)},n=[];for(const e in t){const s=this.core.models.list.get(e);s&&n.push(i(s,Array.from(t[e])))}return await Promise.all(n),e}async getBBoxes(t){const e=[],i=async(t,i)=>{const n=await t.getBoxes(i);if(n)for(const t of n)e.push(t)},n=[];for(const e in t){const s=this.core.models.list.get(e);s&&n.push(i(s,Array.from(t[e])))}return await Promise.all(n),e}async highlight(t,e){await this.forEachModel(e,"highlight",t)}async getData(t,e){const i={};for(const[n,s]of Object.entries(t)){const t=this.list.get(n);if(!t)continue;if(0===s.size){i[n]=[];continue}const r=await t.getItemsData([...s],e);i[n]=r}return i}async resetHighlight(t){await this.forEachModel(t,"resetHighlight")}async forEachModel(t,e,...i){const n={};if(t)for(const e in t){const i=t[e];n[e]=Array.from(i)}else for(const t of this.core.models.list.keys())n[t]=void 0;const s=[];for(const t in n){const r=this.core.models.list.get(t);if(r){const o=n[t],a=r[e](o,...i);s.push(a)}}await Promise.all(s)}async guidsToModelIdMap(t){const e={};for(const[i,n]of this.list){const s=(await n.getLocalIdsByGuids([...t])).filter((t=>null!==t));e[i]=new Set(s)}return e}async modelIdMapToGuids(t){const e=[];for(const[i,n]of Object.entries(t)){const t=this.list.get(i);if(!t)continue;const s=(await t.getGuidsByLocalIds([...n])).filter((t=>null!==t));e.push(...s)}return e}applyBaseCoordinateSystem(t,e){const i=new o.Matrix4;return e&&i.copy(e.clone()).invert(),i.multiply(this.baseCoordinationMatrix),t.applyMatrix4(i),i}};e(pr,"uuid","fef46874-46a3-461b-8c44-2922ab77c806");let fr=pr;function mr(t,e){return t[e]|t[e+1]<<8|t[e+2]<<16}class gr{constructor(t,e={}){const{pixelsPerMeter:i=.1}=e;this.pixelsPerMeter=i,this.renderer=t}async cull(t){t=function(t){const e=new Set;return t.traverse((t=>{t.isMesh&&e.add(t)})),Array.from(e)}(t);const{renderer:e,pixelsPerMeter:i}=this,n=new h,s=new T,r=new a,o=new E(1,1);r.makeEmpty(),t.forEach((t=>{r.expandByObject(t)})),r.getSize(n);const l=Math.min(e.capabilities.maxTextureSize,8192),c=Math.ceil(n.x/i),u=Math.ceil(n.z/i),d=Math.ceil(c/l),p=Math.ceil(u/l);o.setSize(Math.ceil(c/d),Math.ceil(u/p)),s.rotation.x=-Math.PI/2,s.far=r.max.y-r.min.y+s.near,s.position.y=r.max.y+s.near;const f=new M,m=new Map,g=new Map,w=[];for(let e=0;e<t.length;e++){const i=t[e];m.set(i,i.material),g.set(i,i.parent);const n=new wr;n.objectId=e,w.push(n),i.material=n,f.add(i)}const y=e.getClearColor(new I),_=e.getClearAlpha(),b=e.getRenderTarget(),v=e.autoClear;e.autoClear=!0,e.setClearColor(0,0),e.setRenderTarget(o);const x=new Uint8Array(o.width*o.height*4),C=new Set,S=n.x/d,A=n.z/p;for(let i=0;i<d;i++)for(let n=0;n<p;n++){const a=r.min.x+S*i,l=a+S,c=r.min.z+A*n,h=(a+l)/2,u=(c+(c+A))/2;s.position.set(h,r.max.y,u);const d=S/2,p=A/2;s.left=-d,s.right=d,s.top=p,s.bottom=-p,s.updateProjectionMatrix(),e.render(f,s);const m=await e.readRenderTargetPixelsAsync(o,0,0,o.width,o.height,x);for(let e=0,i=m.length;e<i;e+=4){if(0===m[e+3])continue;const i=mr(m,e);C.add(t[i])}}for(const e of t){e.material=m.get(e);const t=g.get(e);t?t.add(e):f.remove(e)}e.setClearColor(y,_),e.setRenderTarget(b),e.autoClear=v;for(const t of w)t.dispose();return o.dispose(),Array.from(C)}}class wr extends z{get objectId(){return this._objectId}set objectId(t){var e,i;this._objectId=t,e=t,(i=this.uniforms.objectId.value).x=(255&e)/255,i.y=(e>>8&255)/255,i.z=(e>>16&255)/255,i.w=1}constructor(t){super({glslVersion:D,blending:k,uniforms:{objectId:{value:new B}},vertexShader:"\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\t\t\t\tlayout(location = 0) out vec4 out_id;\n\t\t\t\tuniform vec4 objectId;\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tout_id = objectId;\n\n\t\t\t\t}\n\t\t\t"}),this._objectId=0,this.setValues(t)}}const yr=1e-16,_r=new h(0,1,0),br=new h;function vr(t){return t.delta(br).normalize(),Math.abs(br.dot(_r))>=1-yr}function xr(t,e){const{start:i,end:n}=e,s=t.points;let r=!1,o=!1;for(let t=0;t<3;t++){const e=s[t];if(!r&&i.distanceToSquared(e)<=yr&&(r=!0),!o&&n.distanceToSquared(e)<=yr&&(o=!0),r&&o)return!0}return r&&o}const Cr=new p;function Sr(t,e,i=!1,n=[]){let s=[[0,1]];for(let t=0,i=e.length;t<i;t++){const i=s[t],n=e[t];i[1]=n[0],s.push([n[1],1])}i&&([e,s]=[s,e]);for(let e=0,i=s.length;e<i;e++){const{start:i,end:r}=t;Cr.start.lerpVectors(i,r,s[e][0]),Cr.end.lerpVectors(i,r,s[e][1]),n.push(new Float32Array([Cr.start.x,Cr.start.y,Cr.start.z,Cr.end.x,Cr.end.y,Cr.end.z]))}return n}const Ar=new h(0,1,0),Pr=new h,Tr=new h,Er=new h,Mr=new f;function*Ir(t,e=[],i={}){const{projectionDirection:n=Ar,thresholdAngle:s=1,iterationTime:r=30}=i,o=Math.pow(10,4),a=Math.cos(O.DEG2RAD*s),l=t.getIndex(),c=t.getAttribute("position"),h=l?l.count:c.count,u=[0,0,0],d=["a","b","c"],f=new Array(3),m={};let g=performance.now();for(let t=0;t<h;t+=3){performance.now()-g>r&&(yield,g=performance.now()),l?(u[0]=l.getX(t),u[1]=l.getX(t+1),u[2]=l.getX(t+2)):(u[0]=t,u[1]=t+1,u[2]=t+2);const{a:i,b:s,c:h}=Mr;if(i.fromBufferAttribute(c,u[0]),s.fromBufferAttribute(c,u[1]),h.fromBufferAttribute(c,u[2]),Mr.getNormal(Er),f[0]=`${Math.round(i.x*o)},${Math.round(i.y*o)},${Math.round(i.z*o)}`,f[1]=`${Math.round(s.x*o)},${Math.round(s.y*o)},${Math.round(s.z*o)}`,f[2]=`${Math.round(h.x*o)},${Math.round(h.y*o)},${Math.round(h.z*o)}`,f[0]!==f[1]&&f[1]!==f[2]&&f[2]!==f[0])for(let t=0;t<3;t++){const i=(t+1)%3,s=f[t],r=f[i],o=Mr[d[t]],l=Mr[d[i]],c=`${s}_${r}`,h=`${r}_${s}`;if(h in m&&m[h]){const t=m[h].normal,i=Er.dot(t)<=a;let s=!1;if(null!==n){let e=n.dot(Er);e=Math.abs(e)<1e-10?0:e;let i=n.dot(t);i=Math.abs(i)<1e-10?0:i,s=Math.sign(e)!==Math.sign(i)}if(i||s){const t=new p;t.start.copy(o),t.end.copy(l),e.push(t)}m[h]=null}else c in m||(m[c]={index0:u[t],index1:u[i],normal:Er.clone()})}}for(const t in m)if(m[t]){const{index0:i,index1:n}=m[t];Pr.fromBufferAttribute(c,i),Tr.fromBufferAttribute(c,n);const s=new p;s.start.copy(Pr),s.end.copy(Tr),e.push(s)}return e}const zr=new p;function Dr(t,e,i,n=[]){return t.bvhcast(e,i,{intersectsTriangles:(t,e)=>!function(t,e){const i=["a","b","c"];let n=0;for(let s=0;s<3;s++)for(let r=0;r<3;r++){kr(t[i[s]],e[i[r]])&&n++}return n>=2}(t,e)&&(t.needsUpdate&&t.update(),e.needsUpdate&&e.update(),!(Math.abs(t.plane.normal.dot(e.plane.normal))>.999999)&&void(!t.intersectsTriangle(e,zr,!0)||xr(t,zr)||xr(e,zr)||n.push(zr.clone())))}),n}function kr(t,e){return t.distanceTo(e)<1e-10}function Br(t){Or(t);let e=[];return t.traverse((t=>{t.geometry&&t.visible&&e.push(t)})),e}const Or=t=>{if(void 0===t)return;const e=[...t.children];for(const i of e)void 0===i?t.children.splice(t.children.indexOf(i),1):Or(i)},Nr=new l,Vr=new l;class Lr{constructor(){this.projectionDirection=new h(0,1,0),this.thresholdAngle=50,this.iterationTime=30}getEdges(...t){const e=this.iterationTime;this.iterationTime=1/0;const i=this.getEdgesGenerator(...t).next().value;return this.iterationTime=e,i}*getEdgesGenerator(t,e=[],i=null){const{projectionDirection:n,thresholdAngle:s,iterationTime:r}=this;if(t.isObject3D){const o=Br(t);let a=null;n&&(a=new h);let l=performance.now();for(let t=0;t<o.length;t++){l-performance.now()>r&&(yield);const c=o[t];a&&(Vr.copy(c.matrixWorld).invert(),a.copy(n).transformDirection(Vr).normalize());const h=yield*Ir(c.geometry,[],{projectionDirection:a,thresholdAngle:s,iterationTime:r});Fr(h,c.matrixWorld);for(let t=0;t<h.length;t++)e.push(h[t]);if(null!==i)for(let t=0;t<h.length;t++)i.push(c)}return e}return yield*Ir(t,e,{projectionDirection:n,thresholdAngle:s,iterationTime:r})}getIntersectionEdges(...t){const e=this.iterationTime;this.iterationTime=1/0;const i=this.getIntersectionEdgesGenerator(...t).next().value;return this.iterationTime=e,i}*getIntersectionEdgesGenerator(t,e=[],i=null){const{iterationTime:n}=this;if(t.isObject3D){const s=Br(t),r=new Map;let o=performance.now();for(let t=0;t<s.length;t++){performance.now()-o>n&&(yield,o=performance.now());const e=s[t].geometry;if(!r.has(e)){const t=e.boundsTree||new Xs(e,{maxLeafSize:1});r.set(e,t)}}o=performance.now();for(let t=0;t<s.length;t++)for(let a=t;a<s.length;a++){performance.now()-o>n&&(yield,o=performance.now());const l=s[t],c=s[a],h=r.get(l.geometry),u=r.get(c.geometry);Nr.copy(l.matrixWorld).invert().multiply(c.matrixWorld);const d=Dr(h,u,Nr,[]);Fr(d,l.matrixWorld);for(let t=0;t<d.length;t++)e.push(d[t]);if(null!==i)for(let t=0;t<d.length;t++)i.push(l)}return e}{let i;return t.isBufferGeometry?i=t.boundsTree||new Xs(t,{maxLeafSize:1}):(i=t,t=i.geometry),Nr.identity(),Dr(i,i,Nr,e)}}}function Fr(t,e,i=1e-6){for(let n=0;n<t.length;n++){const s=t[n];s.applyMatrix4(e),s.start.y+=i,s.end.y+=i}}class Rr extends mn{get lines(){return this.primitiveBuffer}constructor(t,e){super(e),this.primitiveBuffer=t,this.primitiveBufferStride=1,this.heightOffset=e.heightOffset??1e3,this.init(e)}writePrimitiveBounds(t,e,i){const{primitiveBuffer:n,heightOffset:s}=this,{start:r,end:o}=n[t];e[i+0]=Math.min(r.x,o.x),e[i+1]=Math.min(r.y,o.y),e[i+2]=Math.min(r.z,o.z),e[i+3]=Math.max(r.x,o.x),e[i+4]=Math.max(r.y,o.y)+s,e[i+5]=Math.max(r.z,o.z)}getRootRanges(){return[{offset:0,count:this.primitiveBuffer.length}]}}const Ur=new h(0,1,0),jr=new d,$r=new h,Wr=new h;function Gr(t,e,i){t.needsUpdate&&t.update(),jr.copy(t.plane),jr.normal.dot(Ur)<0&&(jr.normal.multiplyScalar(-1),jr.constant*=-1);const n=jr.distanceToPoint(e.start),s=jr.distanceToPoint(e.end),r=Math.abs(n)<1e-16,o=n<0,a=s<0;if(e.delta(Wr).normalize(),Math.abs(jr.normal.dot(Wr))<1e-16)return!(r||!o)&&(i.copy(e),!0);if(o&&a)return i.copy(e),!0;if(!o&&!a)return!1;{const t=O.mapLinear(0,n,s,0,1);if(e.at(t,$r),o)return i.start.copy(e.start),i.end.copy($r),!0;if(a)return i.end.copy(e.end),i.start.copy($r),!0}return!1}const Hr=new d,Zr=new h,qr=new h,Yr=new En,Xr=new p,Kr=new p,Qr=new h,Jr=new h,to=new h;function eo(t,e,i=new p){if(Yr.copy(e),Yr.a.y=0,Yr.b.y=0,Yr.c.y=0,Yr.update(),Xr.copy(t),Xr.start.y=0,Xr.end.y=0,Yr.getArea()<=1e-16)return null;const n=Xr.distance();Xr.delta(Qr).divideScalar(n),Jr.copy(Qr).cross(Yr.plane.normal).normalize(),Hr.setFromNormalAndCoplanarPoint(Jr,Xr.start);let s=0;const{points:r}=Yr;for(let t=0;t<3;t++){const e=r[t],i=r[(t+1)%3],n=Hr.distanceToPoint(e),o=Hr.distanceToPoint(i),a=Math.abs(n)<1e-16,l=Math.abs(o)<1e-16;let c=!1;if(!a&&!l&&n*o<0){const t=n/(n-o);Zr.lerpVectors(e,i,t),c=!0}if((c&&!l||a)&&(a&&!c&&Zr.copy(e),0===s?Kr.start.copy(Zr):Kr.end.copy(Zr),s++,2===s))break}if(2===s){if(Kr.delta(to).normalize(),Qr.dot(to)<0){const t=Kr.start;Kr.start=Kr.end,Kr.end=t}const e=0,s=qr.subVectors(Xr.end,Xr.start).dot(Qr),r=qr.subVectors(Kr.start,Xr.start).dot(Qr),o=qr.subVectors(Kr.end,Xr.start).dot(Qr);return s<=r||o<=e?null:(t.at(Math.max(e,r)/n,i.start),t.at(Math.min(s,o)/n,i.end),i)}return null}const io=new h,no=new h,so=new h;function ro(t,e,i){const n=function(t,e){t.delta(io),no.subVectors(e.start,t.start),so.subVectors(e.end,t.start);const i=io.length();let n=no.length()/i,s=so.length()/i;if(n=Math.min(Math.max(n,0),1),s=Math.min(Math.max(s,0),1),Math.abs(n-s)<=1e-16)return null;return[n,s]}(t,e);return!!n&&(oo(n,i),!0)}function oo(t,e){let[i,n]=t,s=0,r=e.length;for(;s<r;){const t=s+r>>>1;e[t][0]<=i?s=t+1:r=t}let o=Math.max(0,s-1),a=0;for(let t=o,s=e.length;t<s;t++){const[s,r]=e[t];if(i<=r&&n>=s)i=Math.min(s,i),n=Math.max(r,n),a++;else{if(!(i>=s))break;o=t+1}}e.splice(o,a,[i,n])}const ao=new h(0,1,0),lo=new p,co=new p,ho=new En;function uo(t,e,i,n,s=null){const{geometry:r,matrixWorld:o,material:a}=i,l=a.side,c=o.determinant()<0,h=t.lines;t.bvhcast(e,o,{intersectsRanges:(t,e,i,a)=>{s&&(s.candidates+=e*a);for(let u=i,d=a+i;u<d;u++){let i=3*u+0,a=3*u+1,d=3*u+2;r.index&&(i=r.index.getX(i),a=r.index.getX(a),d=r.index.getX(d));const{a:p,b:f,c:m}=ho;if(p.fromBufferAttribute(r.attributes.position,i).applyMatrix4(o),f.fromBufferAttribute(r.attributes.position,a).applyMatrix4(o),m.fromBufferAttribute(r.attributes.position,d).applyMatrix4(o),ho.needsUpdate=!0,ho.update(),l!==w){if(ho.plane.normal.dot(ao)!==c===(l===g)){s&&(s.backFaceCulled+=e);continue}}const y=Math.max(p.y,f.y,m.y),_=Math.min(p.y,f.y,m.y),b=ho.plane.normal;let v=b.x,x=b.y,C=b.z,S=ho.plane.constant;x<0&&(v=-v,x=-x,C=-C,S=-S);for(let i=t,r=e+t;i<r;i++){const t=h[i],e=Math.min(t.start.y,t.end.y),r=Math.max(t.start.y,t.end.y);if(y<=e){s&&s.yBoundsCulled++;continue}const o=t.end.x-t.start.x,a=t.end.z-t.start.z,l=o*o+a*a;if(l>1e-20){const e=1/Math.sqrt(l),i=o*e,n=a*e,r=-n,c=i,h=p.x-t.start.x,u=p.z-t.start.z,d=f.x-t.start.x,g=f.z-t.start.z,w=m.x-t.start.x,y=m.z-t.start.z,_=h*i+u*n,b=d*i+g*n,v=w*i+y*n,x=1/e,C=Math.min(_,b,v);if(Math.max(_,b,v)<0||C>x){s&&s.xzBoundsCulled++;continue}const S=h*r+u*c,A=d*r+g*c,P=w*r+y*c,T=Math.min(S,A,P),E=Math.max(S,A,P);if(T>0||E<0){s&&s.xzBoundsCulled++;continue}}const c=v*t.start.x+x*t.start.y+C*t.start.z+S,u=v*t.end.x+x*t.end.y+C*t.end.z+S;if(c>=0&&u>=0)s&&s.planeTrimCulled++;else if(xr(ho,t))s&&s.triangleEdgeCulled++;else{if(r<_)lo.copy(t);else if(!Gr(ho,t,lo)){s&&s.planeTrimCulled++;continue}lo.distance()<1e-10?s&&s.distThresholdCulled++:eo(lo,ho,co)?(s&&s.used++,ro(t,co,n[i])):s&&s.noOverlapCulled++}}}}})}ho.update=()=>{ho.plane.setFromCoplanarPoints(...ho.points)};let po=!1;const fo={},mo={};let go=null,wo=0,yo=0;const _o={get enabled(){return po},set enabled(t){po=t},reset(){for(const t in fo)delete fo[t];for(const t in mo)delete mo[t];go=null,wo=0,yo=0},setStat(t,e){mo[t]=e},startTotal(){po&&(yo=performance.now())},startStep(t){po&&(null!==go&&this.endStep(),go=t,wo=performance.now())},endStep(){if(!po||null===go)return;const t=performance.now()-wo;fo[go]=t,go=null},printSummary(){if(!po)return;null!==go&&this.endStep();const t=performance.now()-yo;console.log("\n=== Projection Summary ==="),console.log(`Total time: ${t.toFixed(1)}ms\n`);for(const[e,i]of Object.entries(fo)){const n=(i/t*100).toFixed(1);console.log(` ${e}: ${i.toFixed(1)}ms (${n}%)`)}if(Object.keys(mo).length>0){console.log("\n--- Stats ---");for(const[t,e]of Object.entries(mo))console.log(` ${t}: ${e}`)}console.log("")}},bo=1e-5,vo=1e-16,xo=1e-16;function Co(t,e,i,n,s){t.bvhcast(e,i.matrixWorld,{intersectsRanges:(t,e,i,r)=>{n._edgeOffsets.push(t),n._edgeCounts.push(e),n._meshOffsets.push(i),n._meshCounts.push(r),n._meshIndex.push(s),n.groupCount++}})}let So=null;async function Ao(t,e,i,n,s=null){const r=await async function(){return null===So&&(So=new V.WebGPURenderer,await So.init()),So}();t._edgeOffsets&&(t.edgeOffsets=new Uint32Array(t._edgeOffsets),t.edgeCounts=new Uint32Array(t._edgeCounts),t.meshOffsets=new Uint32Array(t._meshOffsets),t.meshCounts=new Uint32Array(t._meshCounts),t.meshIndex=new Uint32Array(t._meshIndex),t._edgeOffsets=null,t._edgeCounts=null,t._meshOffsets=null,t._meshCounts=null,t._meshIndex=null);const o=L(function(t){const e=new Float32Array(6*t.length);for(let i=0;i<t.length;i++){const n=t[i];e[6*i+0]=n.start.x,e[6*i+1]=n.start.y,e[6*i+2]=n.start.z,e[6*i+3]=n.end.x,e[6*i+4]=n.end.y,e[6*i+5]=n.end.z}return e}(i.lines),"float");_o.enabled&&console.log("Number of meshes:",e.length),_o.enabled&&console.log("Group count:",t.groupCount);const a=[];{let t=0;for(;t<e.length;){let i=t,n=0;for(;i<e.length;){const s=e[i].geometry,r=s.index?s.index.count/3:s.attributes.position.count/3;if(i>t&&(i-t>=1e3||n+r>1e5))break;n+=r,i++}a.push({start:t,end:i}),t=i}}_o.enabled&&console.log(`Split ${e.length} meshes into ${a.length} batches`);let l=0,c=0,h=0,u=0,d=0;for(let i=0;i<a.length;i++){const{start:p,end:f}=a[i],m=f-p;_o.enabled&&console.log(`Processing batch ${i+1}/${a.length} (meshes ${p}-${f-1})`);let g=0,w=0;const y=[];for(let t=p;t<f;t++){const i=e[t].geometry;y.push(w/3),g+=i.attributes.position.array.length,w+=i.index.array.length}const _=new Float32Array(g),b=new Uint32Array(w);let v=0,x=0,C=0;for(let t=p;t<f;t++){const i=e[t].geometry,n=i.attributes.position.array,s=i.index.array;_.set(n,v),v+=n.length;for(let t=0;t<s.length;t++)b[x+t]=s[t]+C;x+=s.length,C+=i.attributes.position.count}const S=new Float32Array(16*m);for(let t=p;t<f;t++){const i=t-p;S.set(e[t].matrixWorld.elements,16*i)}const A=[];for(let e=0;e<t.groupCount;e++){const i=t.meshIndex[e];if(i>=p&&i<f){const n=i-p,s=y[n]+t.meshOffsets[e];A.push({edgeOffset:t.edgeOffsets[e],edgeCount:t.edgeCounts[e],triOffset:s,triCount:t.meshCounts[e],meshIdx:n})}}if(0===A.length){_o.enabled&&console.log(` Batch ${i+1}: no groups, skipping`);continue}const P=new Uint32Array(5*A.length);for(let t=0;t<A.length;t++){const e=A[t],i=5*t;P[i+0]=e.edgeOffset,P[i+1]=e.edgeCount,P[i+2]=e.triOffset,P[i+3]=e.triCount,P[i+4]=e.meshIdx}let T=0;for(let t=0;t<A.length;t++)T+=A[t].edgeCount*A[t].triCount;s&&(s.candidates+=T);let E=Math.min(Math.ceil(.1*T),2e6),M=Math.max(E,1e4);_o.enabled&&console.log(` Batch ${i+1}: ${A.length} groups, ${g/3} vertices, ${w/3} triangles, ${T} pairs, buffer for ${M} overlaps`);const I=performance.now(),z=L(_,"float"),D=L(b,"uint"),k=L(S,"float"),B=L(P,"uint");let O=L(new Uint32Array([0]),"uint").toAtomic(),N=L(new Float32Array(3*M),"float");u+=performance.now()-I;const V=performance.now(),st=F((()=>{const t=nt.mul(5),e=B.element(t),i=B.element(t.add(1)),n=B.element(t.add(2)),s=B.element(t.add(3)),r=B.element(t.add(4)).mul(16),a=R(k.element(r),k.element(r.add(1)),k.element(r.add(2)),k.element(r.add(3)),k.element(r.add(4)),k.element(r.add(5)),k.element(r.add(6)),k.element(r.add(7)),k.element(r.add(8)),k.element(r.add(9)),k.element(r.add(10)),k.element(r.add(11)),k.element(r.add(12)),k.element(r.add(13)),k.element(r.add(14)),k.element(r.add(15)));U({start:j(0),end:s.toInt(),type:"int",condition:"<",name:"triIdx"},(({triIdx:t})=>{const s=n.add(t.toUint()).mul(3),r=D.element(s),l=D.element(s.add(1)),c=D.element(s.add(2)),h=$(z.element(r.mul(3)),z.element(r.mul(3).add(1)),z.element(r.mul(3).add(2))),u=$(z.element(l.mul(3)),z.element(l.mul(3).add(1)),z.element(l.mul(3).add(2))),d=$(z.element(c.mul(3)),z.element(c.mul(3).add(1)),z.element(c.mul(3).add(2))),p=a.mul(W(h,G(1))).xyz,f=a.mul(W(u,G(1))).xyz,m=a.mul(W(d,G(1))).xyz,g=f.sub(p),w=m.sub(p),y=H(g,w),_=y.dot(y);Z(_.lessThan(G(4e-16*vo)),(()=>{q()})),Z(y.y.lessThan(0),(()=>{q()}));const b=Y(p.y,Y(f.y,m.y));U({start:j(0),end:i.toInt(),type:"int",condition:"<",name:"edgeIdx"},(({edgeIdx:t})=>{const i=e.add(t.toUint()),n=i.mul(6),s=$(o.element(n),o.element(n.add(1)),o.element(n.add(2))),r=$(o.element(n.add(3)),o.element(n.add(4)),o.element(n.add(5))),a=X(s.y,r.y);Z(b.lessThanEqual(a),(()=>{q()}));const l=K(y),c=l.dot(p).negate(),h=l.y.lessThan(0),u=Q(h,l.negate(),l),d=Q(h,c.negate(),c),g=u.dot(s).add(d),w=u.dot(r).add(d),_=g.lessThan(0),v=w.lessThan(0),x=J(g).lessThan(G(bo)),C=_.not().and(v.not()),S=w.sub(g),A=J(S).lessThan(G(bo)),P=A.and(x.or(_.not()));Z(P,(()=>{q()})),Z(C.and(A.not()),(()=>{q()}));const T=g.negate().div(S),E=tt(s,r,T),I=$(Q(A.or(_),s.x,E.x),Q(A.or(_),s.y,E.y),Q(A.or(_),s.z,E.z)),z=$(Q(A.or(v),r.x,E.x),Q(A.or(v),r.y,E.y),Q(A.or(v),r.z,E.z)),D=z.sub(I),k=D.dot(D);Z(k.lessThan(G(bo)),(()=>{q()}));const B=s.sub(p),V=s.sub(f),L=s.sub(m),F=r.sub(p),R=r.sub(f),U=r.sub(m),j=B.dot(B).lessThanEqual(G(bo)),W=V.dot(V).lessThanEqual(G(bo)),nt=L.dot(L).lessThanEqual(G(bo)),st=F.dot(F).lessThanEqual(G(bo)),rt=R.dot(R).lessThanEqual(G(bo)),ot=U.dot(U).lessThanEqual(G(bo)),at=j.or(W).or(nt),lt=st.or(rt).or(ot),ct=at.and(lt);Z(ct,(()=>{q()}));const ht=$(p.x,G(0),p.z),ut=$(f.x,G(0),f.z),dt=$(m.x,G(0),m.z),pt=$(I.x,G(0),I.z),ft=$(z.x,G(0),z.z),mt=$(s.x,G(0),s.z),gt=$(r.x,G(0),r.z).sub(mt),wt=gt.dot(gt);Z(wt.lessThan(G(bo)),(()=>{q()}));const yt=wt.sqrt(),_t=ut.sub(ht),bt=dt.sub(ht),vt=H(_t,bt),xt=vt.dot(vt);Z(xt.lessThanEqual(G(4e-16*vo)),(()=>{q()}));const Ct=ft.sub(pt),St=Ct.dot(Ct);Z(St.lessThan(G(bo)),(()=>{q()}));const At=St.sqrt(),Pt=Ct.div(At),Tt=gt.div(yt),Et=K(vt),Mt=H(Pt,Et),It=G(0).toVar(),zt=G(0).toVar(),Dt=G(0).toVar(),kt=G(0).toVar(),Bt=et(0).toVar(),Ot=Mt.dot(ht.sub(pt)),Nt=Mt.dot(ut.sub(pt)),Vt=J(Ot).lessThan(G(xo)),Lt=J(Nt).lessThan(G(xo)),Ft=Vt.not().and(Lt.not()).and(Ot.mul(Nt).lessThan(0));Z(Ft,(()=>{const t=Ot.div(Ot.sub(Nt)),e=tt(ht.x,ut.x,t),i=tt(ht.z,ut.z,t);Z(Bt.equal(0),(()=>{It.assign(e),zt.assign(i)})).Else((()=>{Dt.assign(e),kt.assign(i)})),Bt.addAssign(1)})).ElseIf(Vt,(()=>{Z(Bt.equal(0),(()=>{It.assign(ht.x),zt.assign(ht.z)})).Else((()=>{Dt.assign(ht.x),kt.assign(ht.z)})),Bt.addAssign(1)}));const Rt=Nt,Ut=Mt.dot(dt.sub(pt)),jt=Lt,$t=J(Ut).lessThan(G(xo)),Wt=jt.not().and($t.not()).and(Rt.mul(Ut).lessThan(0));Z(Bt.lessThan(2),(()=>{Z(Wt,(()=>{const t=Rt.div(Rt.sub(Ut)),e=tt(ut.x,dt.x,t),i=tt(ut.z,dt.z,t);Z(Bt.equal(0),(()=>{It.assign(e),zt.assign(i)})).Else((()=>{Dt.assign(e),kt.assign(i)})),Bt.addAssign(1)})).ElseIf(jt.and(Ft.not()).and(Vt.not()),(()=>{Z(Bt.equal(0),(()=>{It.assign(ut.x),zt.assign(ut.z)})).Else((()=>{Dt.assign(ut.x),kt.assign(ut.z)})),Bt.addAssign(1)}))}));const Gt=Ut,Ht=Ot,Zt=$t,qt=Vt,Yt=Zt.not().and(qt.not()).and(Gt.mul(Ht).lessThan(0));Z(Bt.lessThan(2),(()=>{Z(Yt,(()=>{const t=Gt.div(Gt.sub(Ht)),e=tt(dt.x,ht.x,t),i=tt(dt.z,ht.z,t);Z(Bt.equal(0),(()=>{It.assign(e),zt.assign(i)})).Else((()=>{Dt.assign(e),kt.assign(i)})),Bt.addAssign(1)})).ElseIf(Zt.and(Wt.not()).and(jt.not()),(()=>{Z(Bt.equal(0),(()=>{It.assign(dt.x),zt.assign(dt.z)})).Else((()=>{Dt.assign(dt.x),kt.assign(dt.z)})),Bt.addAssign(1)}))})),Z(Bt.notEqual(2),(()=>{q()}));const Xt=$(It,G(0),zt),Kt=$(Dt,G(0),kt).sub(Xt).dot(Pt),Qt=$(It,G(0),zt).toVar(),Jt=$(Dt,G(0),kt).toVar();Z(Kt.lessThan(0),(()=>{const t=It,e=zt;Qt.x.assign(Dt),Qt.z.assign(kt),Jt.x.assign(t),Jt.z.assign(e)}));const te=G(0),ee=At,ie=Qt.sub(pt).dot(Pt),ne=Jt.sub(pt).dot(Pt),se=ee.lessThanEqual(ie).or(ne.lessThanEqual(te));Z(se,(()=>{q()}));const re=Y(te,ie),oe=X(ee,ne),ae=pt.add(Pt.mul(re)),le=pt.add(Pt.mul(oe)),ce=ae.sub(mt).dot(Tt).div(yt),he=le.sub(mt).dot(Tt).div(yt),ue=Y(G(0),X(G(1),ce)),de=Y(G(0),X(G(1),he)),pe=J(de.sub(ue));Z(pe.lessThanEqual(G(xo)),(()=>{q()}));const fe=it(O.element(0),1);Z(fe.lessThan(et(M)),(()=>{const t=fe.mul(3);N.element(t).assign(i.toFloat()),N.element(t.add(1)).assign(ue),N.element(t.add(2)).assign(de)}))}))}))}))().compute(A.length);d+=performance.now()-V;const rt=performance.now();await r.computeAsync(st),l+=performance.now()-rt;const ot=performance.now(),at=await r.getArrayBufferAsync(O.value),lt=new Uint32Array(at)[0];if(s&&(s.used+=Math.min(lt,M)),_o.enabled&&console.log(` Batch ${i+1}: ${lt} overlaps found (capacity: ${M})`),lt>M&&_o.enabled&&console.warn(` WARNING: Overlap buffer overflow! ${lt} > ${M}. Some occlusion data lost.`),lt>0){const t=await r.getArrayBufferAsync(N.value),e=new Float32Array(t);c+=performance.now()-ot;const i=performance.now(),s=Math.min(lt,M);for(let t=0;t<s;t++){const i=3*t,s=Math.round(e[i]);oo([e[i+1],e[i+2]],n[s])}h+=performance.now()-i,_o.enabled&&console.log(` Processed ${s} overlaps into hiddenOverlapMap`)}else c+=performance.now()-ot}r.dispose(),So=null;const p=u+d+l+c+h;_o.enabled&&(console.log(`WebGPU timing breakdown (total: ${p.toFixed(1)}ms):`),console.log(` Buffer creation: ${u.toFixed(1)}ms`),console.log(` Shader build: ${d.toFixed(1)}ms`),console.log(` GPU compute: ${l.toFixed(1)}ms`),console.log(` Readback: ${c.toFixed(1)}ms`),console.log(` CPU merge: ${h.toFixed(1)}ms`))}const Po=new h(0,1,0);function To(t,e=null){const i=new Float32Array(6*t.length);let n=0;for(let e=0,s=t.length;e<s;e++){const s=t[e];i[n++]=s[0],i[n++]=0,i[n++]=s[2],i[n++]=s[3],i[n++]=0,i[n++]=s[5]}const s=new N,r=new c(i,3,!0);if(s.setAttribute("position",r),e){const i=new Float32Array(2*t.length);for(let t=0,n=e.length;t<n;t++)i[2*t]=e[t],i[2*t+1]=e[t];s.setAttribute("group",new c(i,1))}return s}class Eo{constructor(t,e=!0){this.meshes=Br(t),this.bvhs=new Map,this.visibleEdges=[],this.hiddenEdges=[],this.visibleGroupIndices=[],this.hiddenGroupIndices=[],this.groupKeyToIndex=null,this.hasGroups=!1,this.iterationTime=30,this.useWebGPU=e}reset(){this.visibleEdges.length=0,this.hiddenEdges.length=0,this.visibleGroupIndices.length=0,this.hiddenGroupIndices.length=0,this.groupKeyToIndex=null,this.hasGroups=!1}getVisibleLineGeometry(){return To(this.visibleEdges,this.groupKeyToIndex?this.visibleGroupIndices:null)}getHiddenLineGeometry(){return To(this.hiddenEdges,this.groupKeyToIndex?this.hiddenGroupIndices:null)}getGroupKeys(){return this.groupKeyToIndex?Object.fromEntries(this.groupKeyToIndex):{}}addEdges(...t){const e=this.iterationTime;this.iterationTime=1/0;const i=this.addEdgesGenerator(...t).next().value;return this.iterationTime=e,i}*addEdgesGenerator(t,e={}){const{meshes:i,bvhs:n,visibleEdges:s,hiddenEdges:r,iterationTime:o}=this;let a=performance.now();_o.startStep("Building mesh BVH");for(let t=0;t<i.length;t++){performance.now()-a>o&&(yield,a=performance.now());const e=i[t].geometry;if(!n.has(e)){const t=e.boundsTree||new Xs(e);n.set(e,t)}}let l=0;for(let t=0;t<i.length;t++){const e=i[t].geometry;l+=e.index?e.index.count/3:e.attributes.position.count/3}const c={};for(let e=0;e<t.length;e++)c[e]=[];_o.startStep("Building line BVH");const h=new Rr(t,{maxLeafSize:2,strategy:2});_o.startStep("BVHcast overlaps"),a=performance.now();const u={candidates:0,backFaceCulled:0,yBoundsCulled:0,xzBoundsCulled:0,triangleEdgeCulled:0,planeTrimCulled:0,distThresholdCulled:0,noOverlapCulled:0,used:0,totalEdges:t.length,totalTriangles:l},d=this.useWebGPU,p={};d&&(p._edgeOffsets=[],p._edgeCounts=[],p._meshOffsets=[],p._meshCounts=[],p._meshIndex=[],p.groupCount=0);for(let t=0;t<i.length;t++){performance.now()-a>o&&(e.onProgress&&e.onProgress(t,i.length),yield,a=performance.now());const s=i[t];d?Co(h,n.get(s.geometry),s,p,t):uo(h,n.get(s.geometry),s,c,u)}if(d){let t=!1;for(Ao(p,i,h,c,u).then((()=>{t=!0}));!t;)yield}const f=u.totalEdges*u.totalTriangles;if(_o.setStat("Total edges",u.totalEdges.toLocaleString()),_o.setStat("Total triangles",u.totalTriangles.toLocaleString()),_o.setStat("Brute-force pairs (edges × triangles)",f.toLocaleString()),_o.setStat("BVH candidate pairs",u.candidates.toLocaleString()),f>0&&_o.setStat("BVH reduction",(u.candidates/f*100).toFixed(3)+"% of brute-force"),u.candidates>0){const t=u.candidates,e=e=>(e/t*100).toFixed(2)+"%";d||(_o.setStat("Rejected: back-face culling",u.backFaceCulled.toLocaleString()+" ("+e(u.backFaceCulled)+")"),_o.setStat("Rejected: Y-bounds (tri below edge)",u.yBoundsCulled.toLocaleString()+" ("+e(u.yBoundsCulled)+")"),_o.setStat("Rejected: XZ-bounds (no 2D overlap)",u.xzBoundsCulled.toLocaleString()+" ("+e(u.xzBoundsCulled)+")"),_o.setStat("Rejected: edge lies on triangle",u.triangleEdgeCulled.toLocaleString()+" ("+e(u.triangleEdgeCulled)+")"),_o.setStat("Rejected: line above tri plane",u.planeTrimCulled.toLocaleString()+" ("+e(u.planeTrimCulled)+")"),_o.setStat("Rejected: trimmed edge too small",u.distThresholdCulled.toLocaleString()+" ("+e(u.distThresholdCulled)+")"),_o.setStat("Rejected: no projected overlap",u.noOverlapCulled.toLocaleString()+" ("+e(u.noOverlapCulled)+")")),_o.setStat("Producing overlaps",u.used.toLocaleString()+" ("+e(u.used)+")")}_o.startStep("Converting overlaps to lines");const m=this.hasGroups;for(let e=0;e<t.length;e++){performance.now()-a>o&&(yield,a=performance.now());const i=t[e],n=c[e],l=s.length,h=r.length;if(Sr(i,n,!1,s),Sr(i,n,!0,r),m){const t=i.groupIndex;for(let e=l;e<s.length;e++)this.visibleGroupIndices.push(t);for(let e=h;e<r.length;e++)this.hiddenGroupIndices.push(t)}}}}class Mo{constructor(){this.iterationTime=30,this.angleThreshold=50,this.includeIntersectionEdges=!0,this.useWebGPU=!0}generateAsync(t,e={}){return new Promise(((i,n)=>{const{signal:s}=e,r=this.generate(t,e);!function t(){if(s&&s.aborted)return void n(new Error("ProjectionGenerator: Process aborted via AbortSignal."));const e=r.next();e.done?i(e.value):requestAnimationFrame(t)}()}))}*generate(t,e){const{iterationTime:i,angleThreshold:n,includeIntersectionEdges:s}=this,{onProgress:r=()=>{},visibilityCuller:o=null,groupFn:a=null}=e;if(_o.reset(),_o.startTotal(),t.isBufferGeometry&&(t=new b(t)),o){_o.startStep("Visibility culling");let e=!1;for(o.cull(t).then((i=>{(t=new M).children=i,e=!0}));!e;)yield}const l=new Lr;l.iterationTime=i,l.thresholdAngle=n,l.projectionDirection.copy(Po),_o.startStep("Generating candidate edges"),r("Generating candidate edges");let c=[],h=a?[]:null;if(yield*l.getEdgesGenerator(t,c,h),s&&(_o.startStep("Generating intersection edges"),r("Generating intersection edges"),yield*l.getIntersectionEdgesGenerator(t,c,h)),_o.startStep("Pre-filtering edges"),r("Pre-filtering edges"),h){const t=[],e=[];for(let i=0;i<c.length;i++)vr(c[i])||(t.push(c[i]),e.push(h[i]));c=t,h=e}else c=c.filter((t=>!vr(t)));yield;const u=new Eo(t,this.useWebGPU);if(u.iterationTime=i,a&&h){const t=new Map;for(let e=0;e<c.length;e++){const i=a(h[e]);t.has(i)||t.set(i,t.size),c[e].groupIndex=t.get(i)}u.groupKeyToIndex=t,u.hasGroups=!0}return r("Building BVH & computing overlaps"),yield*u.addEdgesGenerator(c,{onProgress:r?(t,e)=>{r("Building BVH & computing overlaps",t/e,u)}:null}),_o.printSummary(),u}}new p,new p,new h;const Io=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new at),e(this,"generator",new Mo),e(this,"cullerPixelsPerMeter",.05),e(this,"projectionDirection",new o.Vector3(0,-1,0)),e(this,"nearPlane",-1/0),e(this,"farPlane",1/0),this.components.add(t.uuid,this),this.generator.includeIntersectionEdges=!1}async get(t,e,i){const n=this.components.get(fr),s=new o.Group,r=new Map;for(const[e,i]of Object.entries(t)){const t=n.list.get(e);if(!t)continue;const a=(await t.getItemsIdsWithGeometry()).filter((t=>i.has(t)));if(0===a.length)continue;const l=await t.getItemsGeometry(a);for(const i in l){const n=l[i];for(const i of n){if(!(i.positions&&i.indices&&i.transform&&i.representationId))continue;const n=i.representationId;if(!r.has(n)){const t=new o.BufferGeometry;t.setAttribute("position",new o.Float32BufferAttribute(i.positions,3)),i.normals&&t.setAttribute("normal",new o.Float32BufferAttribute(i.normals,3)),t.setIndex(Array.from(i.indices)),r.set(n,t)}const a=r.get(n),l=new o.Mesh(a);l.applyMatrix4(i.transform),l.applyMatrix4(t.object.matrixWorld),l.updateWorldMatrix(!0,!0),l.userData._edgeProjectorModelId=e,l.userData._edgeProjectorLocalId=i.localId,s.add(l)}}}const a=this.projectionDirection.clone().normalize(),l=new o.Vector3(0,-1,0),c=(new o.Quaternion).setFromUnitVectors(a,l),h=(new o.Matrix4).makeRotationFromQuaternion(c),u=h.clone().invert();for(const t of s.children)t.applyMatrix4(h),t.updateWorldMatrix(!1,!1);if(s.traverse((t=>{const e=t;if(e.geometry&&!e.geometry.boundsTree){const t=e.geometry.index?e.geometry.index.count:e.geometry.attributes.position.count;e.geometry.groups.forEach((e=>{e.count===1/0&&(e.count=t-e.start)})),e.geometry.boundsTree=new Xs(e.geometry,{maxLeafSize:1,strategy:2})}})),this.nearPlane!==-1/0||this.farPlane!==1/0){const t=new o.Box3,e=[];for(const i of s.children){const n=i;n.geometry&&(t.setFromObject(n),(t.max.y<this.nearPlane||t.min.y>this.farPlane)&&e.push(n))}for(const t of e)s.remove(t)}const d=e.renderer.three,p=new gr(d,{pixelsPerMeter:this.cullerPixelsPerMeter}),f=await this.generator.generateAsync(s,{visibilityCuller:p,groupFn:t=>`${t.userData._edgeProjectorModelId??"unknown"}:${t.userData._edgeProjectorLocalId??0}`,onProgress:null==i?void 0:i.onProgress}),m=f.getVisibleLineGeometry(),g=f.getHiddenLineGeometry();m.applyMatrix4(u),g.applyMatrix4(u);const w=f.getGroupKeys(),y={};for(const[t,e]of Object.entries(w)){const i=t.lastIndexOf(":"),n=t.substring(0,i),s=Number(t.substring(i+1));y[e]={modelId:n,localId:s}}for(const t of r.values())t.dispose();return{visible:m,hidden:g,groups:y}}dispose(){this.onDisposed.trigger(t.uuid),this.onDisposed.reset()}};e(Io,"uuid","f2e76c3a-8b1d-4d5e-9a3f-7c6b2d4e8f1a");let zo=Io;class Do{constructor(){e(this,"wasm",{path:"",absolute:!1,logLevel:st.LogLevel.LOG_LEVEL_OFF}),e(this,"webIfc",{COORDINATE_TO_ORIGIN:!0}),e(this,"autoSetWasm",!0),e(this,"customLocateFileHandler",null)}}const ko=class t extends ht{constructor(i){super(i),e(this,"onDisposed",new at),e(this,"onIfcStartedLoading",new at),e(this,"onIfcImporterInitialized",new at),e(this,"onSetup",new at),e(this,"settings",new Do),e(this,"webIfc",new st.IfcAPI),e(this,"enabled",!0),this.components.add(t.uuid,this)}dispose(){this.webIfc=null,this.onDisposed.trigger(t.uuid),this.onDisposed.reset()}async setup(t){this.settings={...this.settings,...t},this.settings.autoSetWasm&&await this.autoSetWasm(),this.onSetup.trigger()}async load(t,e,n,s){const r=this.components.get(fr);if(!r.initialized)throw new Error("You need to initialize fragments first.");this.settings.autoSetWasm&&await this.autoSetWasm(),r.core.settings.autoCoordinate=e;const o=new i.IfcImporter;o.wasm.path=this.settings.wasm.path,o.wasm.absolute=this.settings.wasm.absolute,o.webIfcSettings=this.settings.webIfc,this.onIfcImporterInitialized.trigger(o),(null==s?void 0:s.instanceCallback)&&s.instanceCallback(o);const a=await o.process({...null==s?void 0:s.processData,bytes:t});return await r.core.load(a,{modelId:n,userData:null==s?void 0:s.userData})}async readIfcFile(t){const{path:e,absolute:i,logLevel:n}=this.settings.wasm;return this.webIfc.SetWasmPath(e,i),await this.webIfc.Init(this.settings.customLocateFileHandler||void 0),n&&this.webIfc.SetLogLevel(n),this.webIfc.OpenModel(t,this.settings.webIfc)}cleanUp(){try{this.webIfc.Dispose()}catch(t){console.log("Web-ifc wasn't disposed.")}this.webIfc=null,this.webIfc=new st.IfcAPI}async autoSetWasm(){const t=await fetch(`https://unpkg.com/@thatopen/components@${Ia.release}/package.json`);if(!t.ok)return void console.warn("Couldn't get openbim-components package.json. Set wasm settings manually.");const e=await t.json();if("web-ifc"in e.peerDependencies){const t=e.peerDependencies["web-ifc"];this.settings.wasm.path=`https://unpkg.com/web-ifc@${t}/`,this.settings.wasm.absolute=!0}else console.warn("Couldn't get web-ifc from peer dependencies in openbim-components. Set wasm settings manually.")}};e(ko,"uuid","a659add7-1418-4771-a0d6-7d4d438e4624");let Bo=ko;const Oo=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),this.components.add(t.uuid,this)}async set(t,e){const i=this.components.get(fr),n=[];if(e)for(const[s,r]of Object.entries(e)){const e=i.list.get(s);e&&n.push(e.setVisible([...r],t))}else for(const e of i.list.values())n.push(e.setVisible(void 0,t));await Promise.all(n),await i.core.update(!0)}async isolate(t){await Promise.all([this.set(!1),this.set(!0,t)])}async toggle(t){const e=[],i=this.components.get(fr);for(const[n,s]of Object.entries(t)){const t=i.list.get(n);t&&e.push(t.toggleVisible([...s]))}await Promise.all(e),await i.core.update(!0)}async getVisibilityMap(t,e){const i=[],n=[],s=this.components.get(fr);if(e)for(const r of e){const e=s.list.get(r);e&&(i.push(e.modelId),n.push(e.getItemsByVisibility(t)))}else for(const e of s.list.values())i.push(e.modelId),n.push(e.getItemsByVisibility(t));const r=await Promise.all(n),o={};for(const[t,e]of i.entries())o[e]=r[t];return o}};e(Oo,"uuid","dd9ccf2d-8a21-4821-b7f6-2949add16a29");let No=Oo;const Vo=class t extends ht{constructor(n){super(n),e(this,"enabled",!0),e(this,"onDisposed",new at),e(this,"list",new i.DataSet),this.components.add(t.uuid,this)}dispose(e=!0){this.list.clear(),this.onDisposed.trigger(t.uuid),e&&(this.onDisposed.reset(),this.list.eventsEnabled=!1,this.list.dispose())}get(){const t=new o.Box3;for(const e of this.list)t.union(e);return t}async addFromModelIdMap(t){const e=this.components.get(fr),i=new o.Box3;for(const[n,s]of Object.entries(t)){const t=e.list.get(n);if(!t)continue;const r=await t.getMergedBox([...s]);i.union(r)}this.list.add(i)}addFromModels(t){const e=this.components.get(fr);for(const[i,n]of e.list)t&&!t.some((t=>t.test(i)))||this.list.add(n.box)}async getCenter(t){this.list.clear(),await this.addFromModelIdMap(t);const e=this.get();this.list.clear();const i=new o.Vector3;return e.getCenter(i),i}async getCameraOrientation(t,e=1){const i=this.components.get(fr);this.list.clear();for(const[t,e]of i.list)this.list.add(e.box);const n=this.get();this.list.clear();const s=new o.Vector3;n.getCenter(s);const r=new o.Vector3;n.getSize(r);const a=Math.max(r.x,r.y,r.z)*e,l=new o.Vector3;switch(t){case"front":default:l.set(s.x,s.y,s.z+a);break;case"back":l.set(s.x,s.y,s.z-a);break;case"left":l.set(s.x-a,s.y,s.z);break;case"right":l.set(s.x+a,s.y,s.z);break;case"top":l.set(s.x,s.y+a,s.z);break;case"bottom":l.set(s.x,s.y-a,s.z)}return{position:l,target:s}}};e(Vo,"uuid","d1444724-dba6-4cdd-a0c7-68ee1450d166");let Lo=Vo;class Fo{constructor(t,i){e(this,"name","Query"),e(this,"customData",{}),e(this,"_components"),e(this,"_queries",[]),e(this,"_aggregation","exclusive"),e(this,"result",null),e(this,"cache",!0),e(this,"serializeQueryParameters",(t=>{var e;return{categories:null==(e=t.categories)?void 0:e.map((t=>t.source)),attributes:t.attributes?{aggregation:t.attributes.aggregation,queries:t.attributes.queries.map(this.serializeAttributeQuery)}:void 0,relation:t.relation?{name:t.relation.name,query:t.relation.query?this.serializeQueryParameters(t.relation.query):void 0}:void 0}})),e(this,"deserializeQueryParameters",(t=>{var e;return{categories:null==(e=t.categories)?void 0:e.map((t=>new RegExp(t))),attributes:t.attributes?{aggregation:t.attributes.aggregation,queries:t.attributes.queries.map(this.deserializeAttributeQuery)}:void 0,relation:t.relation?{name:t.relation.name,query:t.relation.query?this.deserializeQueryParameters(t.relation.query):void 0}:void 0}})),this._components=t,this.queries=i}set queries(t){this._queries=t,this.clearCache()}get queries(){return this._queries}set aggregation(t){t!==this._aggregation&&this.clearCache(),this._aggregation=t}get aggregation(){return this._aggregation}async test(t){const{modelIds:e,force:i}={force:!1,...t};if(this.result&&!i)return this.result;const n=this._components.get(Uo),s=await n.getItems(this.queries,{modelIds:e,aggregation:this.aggregation});return this.cache&&(this.result=s),s}clearCache(){this.result=null}serializeAttributeQuery(t){let e;e=Array.isArray(t.value)?t.value.map((t=>t.source)):t.value instanceof RegExp?t.value.source:t.value;return{name:t.name.source,value:e,type:t.type instanceof RegExp?t.type.source:t.type,negate:t.negate,itemIds:t.itemIds}}toJSON(){return{guid:this._components.get(Uo).list.getKey(this)??_t.create(),name:this.name,customData:this.customData,queries:this.queries.map(this.serializeQueryParameters),aggregation:this.aggregation,cache:this.cache}}deserializeAttributeQuery(t){let e;e=Array.isArray(t.value)?t.value.map((t=>new RegExp(t))):"string"==typeof t.value?new RegExp(t.value):t.value;return{name:new RegExp(t.name),value:e,type:t.type?new RegExp(t.type):void 0,negate:t.negate,itemIds:t.itemIds}}fromJSON(t){return this.name=t.name,this.customData=t.customData,this.aggregation=t.aggregation,this.cache=t.cache,this.queries=t.queries.map(this.deserializeQueryParameters),this}}const Ro=class t extends ht{constructor(n){super(n),e(this,"enabled",!0),e(this,"list",new i.DataMap),n.add(t.uuid,this)}async getItems(t,e){let i;if(e){const{modelIds:t,items:n}=e;if(n){const t=Object.keys(n);t.length>0&&(i=t.map((t=>new RegExp(`^${t}$`))))}else t&&(i=t)}const n=(null==e?void 0:e.aggregation)??"exclusive",s=this.components.get(fr),r=await Promise.all(t.map((async t=>{const n={};return await Promise.all(Array.from(s.list).map((async([s,r])=>{var o;if(i&&!i.some((t=>t.test(s))))return;const a=null==(o=null==e?void 0:e.items)?void 0:o[s],l=await r.getItemsByQuery(t,{localIds:a?[...a]:void 0});n[s]=new Set(l)}))),n})));return"inclusive"===n?ai.join(r):ai.intersect(r)}create(t,e){const i=new Fo(this.components,e);return this.list.set(t,i),i}async addFromCategories(t){const e=new Set,i=this.components.get(fr);for(const[n,s]of i.list){if(t&&!t.some((t=>t.test(n))))continue;const i=(await s.getItemsWithGeometryCategories()).filter((t=>null!==t)),r=new Set(i);for(const t of r)this.list.has(t)||(this.create(t,[{categories:[new RegExp(`^${t}$`)]}]),e.add(t))}return[...e]}import(t){const{data:e}=t,i=[];if(!e)return i;for(const t of e){const e=this.create(t.guid,[]);e.fromJSON(t),i.push(e)}return i}export(){const t=[];for(const[e,i]of this.list.entries()){const n={...i.toJSON(),name:e};t.push(n)}return{data:t}}};e(Ro,"uuid","0da7ad77-f734-42ca-942f-a074adfd1e3a");let Uo=Ro;const jo=class t extends ht{constructor(n){super(n),e(this,"enabled",!0),e(this,"onDisposed",new at),e(this,"list",new i.DataMap),e(this,"defaultSaveFunction",(t=>"value"in t.Name?t.Name.value:null)),e(this,"onBeforeFragmentsDispose",(async t=>{const{key:e,value:i}=t,n=await i.getLocalIds(),s={[e]:new Set(n)};this.removeItems(s)})),n.add(t.uuid,this),this.setupEvents();n.get(fr).list.onBeforeDelete.add(this.onBeforeFragmentsDispose)}setupEvents(){this.list.onBeforeDelete.add((({value:t})=>t.dispose()))}getClassificationGroups(t){let e=this.list.get(t);return e||(e=new i.DataMap,this.list.set(t,e)),e}getModelItems(t,e,i){const{map:n}=this.getGroupData(t,e);let s=n[i];return s||(s=new Set,n[i]=s),s}getGroupData(t,e){const i=this.components.get(Uo),n=this.getClassificationGroups(t);let s=n.get(e);return s||(s={map:{},get:()=>new Promise((t=>{if(s)if(s.query){const{name:e,config:n}=s.query,r=i.list.get(e);if(!r)throw new Error("Classifier: the query name associated with the group doesn't exist in the ItemsFinder component");r.test(n).then((e=>{if(!s)return void t({});const i=ai.join([e,s.map]);t(i)}))}else t(s.map);else t({})}))},n.set(e,s)),s}async aggregateItems(t,e,i){const n=(null==i?void 0:i.data)??void 0,s=(null==i?void 0:i.aggregationCallback)??this.defaultSaveFunction,r=this.components.get(fr),o=this.components.get(Uo),a=await o.getItems([e],{modelIds:null==i?void 0:i.modelIds});for(const[e,i]of Object.entries(a)){const o=r.list.get(e);if(!o)continue;const a=(i,...n)=>{const s=this.getModelItems(t,i,e);for(const t of n)s.add(t)},l=await o.getItemsData([...i],n);for(const t of l)s(t,a)}}addGroupItems(t,e,i){const{map:n}=this.getGroupData(t,e);ai.add(n,i)}setGroupQuery(t,e,i){this.getGroupData(t,e).query=i}async find(t){const e=[];for(const[i,n]of Object.entries(t)){const t=[],s=this.list.get(i);if(!s)continue;for(const e of n){const i=s.get(e);if(!i)continue;const n=await i.get();t.push(n)}const r=ai.join(t);e.push(r)}return ai.intersect(e)}async aggregateItemRelations(t,e,i,n){const s=(null==n?void 0:n.attribute)??"Name",r={relations:{[i]:{attributes:!0,relations:!1}}};await this.aggregateItems(t,e,{modelIds:null==n?void 0:n.modelIds,data:r,aggregationCallback:(t,e)=>{if(!(null==t?void 0:t[s]))return;const n=t[s];if(!("value"in n))return;const r=t[i];if(Array.isArray(r))for(const t of r)"value"in t._localId&&e(n.value,t._localId.value)}})}async byIfcBuildingStorey(t){await this.aggregateItemRelations((null==t?void 0:t.classificationName)??"Storeys",{categories:[/BUILDINGSTOREY/]},"ContainsElements",{modelIds:null==t?void 0:t.modelIds})}async byCategory(t){const e=this.components.get(Uo),i=await e.addFromCategories(null==t?void 0:t.modelIds);for(const e of i)this.setGroupQuery((null==t?void 0:t.classificationName)??"Categories",e,{name:e})}dispose(){this.list.clear();this.components.get(fr).list.onBeforeDelete.remove(this.onBeforeFragmentsDispose),this.onDisposed.trigger()}removeItems(t,e){if(e&&e.classificationName){const i=this.list.get(e.classificationName);if(!i)return;if(e.groupName){if(!i.get(e.groupName))return}for(const[,e]of i)ai.remove(e.map,t)}else for(const[,e]of this.list.entries())for(const[,i]of e)ai.remove(i.map,t)}async byModel(t){const e=this.components.get(fr),i=(null==t?void 0:t.classificationName)??"Models";for(const[n,s]of e.list){if(t&&t.modelIds&&!t.modelIds.some((t=>t.test(n))))continue;const e=await s.getItemsIdsWithGeometry(),r={[n]:new Set(e)};this.getGroupData(i,n),this.addGroupItems(i,n,r)}}};e(jo,"uuid","e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7");let $o=jo;const Wo=class t{constructor(t,i){if(e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new at),e(this,"mouse"),e(this,"world"),e(this,"debugMode",!1),e(this,"_renderTarget"),e(this,"_renderTargetSize",new o.Vector2),e(this,"_debugCanvas"),e(this,"_debugContainer"),e(this,"_idMaterial"),e(this,"_depthMaterial"),e(this,"_normalMaterial"),e(this,"_originalMaterials",new Map),e(this,"_hiddenLods",[]),!i.renderer)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=i,this.mouse=new fi(i.renderer.three.domElement),this.components=t,this._idMaterial=this.buildIdMaterial(),this._depthMaterial=this.buildDepthMaterial(),this._normalMaterial=this.buildNormalMaterial(),this.setupRenderTarget()}async getModelAt(t){const e=await this.runIdPass(t);return e?e.modelId:null}async getItemAt(t){const e=await this.runIdPass(t);if(!e)return null;const i=this.components.get(fr).list.get(e.modelId);if(!i)return null;const n=await i.getLocalIdsFromItemIds([e.itemId]),s=null==n?void 0:n[0];return null==s?null:{modelId:e.modelId,localId:s,itemId:e.itemId}}async getPointAt(t){if(!this.enabled)return null;if(!this._renderTarget||!this.world.renderer)return null;const e=this.components.get(fr);if(!e.initialized||0===e.list.size)return null;this.renderDepthPass();const i=t??this.mouse.position,n=this.readPixelAt(i);if(!n)return null;if(0===n[0]&&0===n[1]&&0===n[2]&&0===n[3])return null;const s=function(t){const e=t[0]/255,i=t[1]/255,n=t[2]/255,s=t[3]/255;return 255/256*(e/16777216+i/65536+n/256+s)}(n);return s>=.999999?null:function(t,e,i){const n=new o.Vector3(t.x,t.y,2*e-1);return n.unproject(i),n}(i,s,this.world.camera.three)}async getNormalAt(t){if(!this.enabled)return null;if(!this._renderTarget||!this.world.renderer)return null;const e=this.components.get(fr);if(!e.initialized||0===e.list.size)return null;this.renderNormalPass();const i=t??this.mouse.position,n=this.readPixelAt(i);if(!n)return null;if(0===n[3])return null;const s=n[0]/255*2-1,r=n[1]/255*2-1,a=n[2]/255*2-1,l=new o.Vector3(s,r,a);return l.lengthSq()<1e-8?null:l.normalize()}async getFullPick(t){const e=await this.getItemAt(t);if(!e)return null;const i=await this.getPointAt(t);if(!i)return null;const n=await this.getNormalAt(t),s=i.distanceTo(this.world.camera.three.position);return{...e,point:i,normal:n,distance:s}}setDebugMode(t){this.debugMode=t,t?this.setupDebugCanvas():this.removeDebugCanvas()}dispose(){this.mouse.dispose(),this.removeDebugCanvas(),this._idMaterial.dispose(),this._depthMaterial.dispose(),this._normalMaterial.dispose(),this._renderTarget&&this._renderTarget.dispose(),this._renderTarget=void 0,this._originalMaterials.clear(),this._hiddenLods.length=0,this.onDisposed.trigger(),this.onDisposed.reset()}async runIdPass(t){if(!this.enabled)return null;if(!this._renderTarget)return null;if(!this.world.renderer)return null;const e=this.components.get(fr);if(!e.initialized||0===e.list.size)return null;const i=this.applyIdMaterial();if(0===i.size)return this.restoreOriginalMaterials(),null;const n=t??this.mouse.position;this.renderIdPass(i,n),this.restoreOriginalMaterials(),this.debugMode&&this._debugCanvas&&this.updateDebugCanvas();const s=this.readPixelAt(this._renderTarget,n);if(!s)return null;const r=s[0];if(0===r)return null;const o=i.get(r);if(!o)return null;const a=s[1]<<16|s[2]<<8|s[3];if(0===a)return null;return{modelId:o,itemId:a-1}}applyIdMaterial(){const e=this.components.get(fr),i=new Map;let n=1;for(const[s,r]of e.list){if(n>t.MAX_MODELS)break;const e=n;n+=1;let a=!1;r.object.traverse((t=>{if(!(t instanceof o.Mesh))return;const e=t.geometry;e&&(e.attributes&&e.attributes.id?(this._originalMaterials.set(t,t.material),t.material=this._idMaterial,a=!0):t.visible&&(this._hiddenLods.push(t),t.visible=!1))})),a&&i.set(e,s)}return i}renderIdPass(t,e){this.renderPickPass(t,this._renderTarget,this._idMaterial,e)}renderPickPass(t,e,i,n){const s=this.world.renderer.three,r=this.world.scene.three,a=this.world.camera.three,l=this.components.get(fr),c=s.clippingPlanes??[];i.clippingPlanes=c,i.clipping=c.length>0;const h=s.getRenderTarget(),u=s.autoClear,d=s.getClearColor(new o.Color),p=s.getClearAlpha(),f=s.getScissorTest(),m=s.getScissor(new o.Vector4);s.setRenderTarget(e),s.setClearColor(0,0),s.autoClear=!1,s.setScissorTest(!1),s.clear(!0,!0,!1);const g=e.width,w=e.height,y=Math.floor(.5*(n.x+1)*g),_=Math.floor(.5*(n.y+1)*(w-1)),b=Math.max(0,Math.min(g-4,y-2)),v=Math.max(0,Math.min(w-4,_-2)),x=s.getPixelRatio();s.setScissor(b/x,v/x,4/x,4/x),s.setScissorTest(!0);const C=new Map;for(const[t,e]of l.list)C.set(t,e.object);const S=new Set(C.values()),A=new Map;r.traverse((t=>{t!==r&&t.isMesh&&((t=>{let e=t;for(;e;){if(S.has(e))return!0;e=e.parent}return!1})(t)||(A.set(t,t.visible),t.visible=!1))}));const P=new Map;for(const t of C.values())P.set(t,t.visible),t.visible=!1;for(const[e,n]of t){const t=C.get(n);t&&(t.visible=!0,i.uniforms.modelByte.value=e,s.render(r,a),t.visible=!1)}for(const[t,e]of P)t.visible=e;for(const[t,e]of A)t.visible=e;s.setScissorTest(f),s.setScissor(m),s.setRenderTarget(h),s.autoClear=u,s.setClearColor(d,p)}renderWithTileMaterial(t){const e=this.world.renderer.three,i=this.world.scene.three,n=this.world.camera.three,s=this.components.get(fr),r=e.clippingPlanes??[];t.clippingPlanes=r,t.clipping=r.length>0;const a=e.getRenderTarget(),l=e.autoClear,c=e.getClearColor(new o.Color),h=e.getClearAlpha(),u=new Map,d=[];for(const[,e]of s.list)e.object.traverse((e=>{if(!(e instanceof o.Mesh))return;const i=e.geometry;i&&(i.attributes&&i.attributes.id?e.visible&&(u.set(e,e.material),e.material=t):e.visible&&(d.push(e),e.visible=!1))}));const p=new Set;for(const[,t]of s.list)p.add(t.object);const f=new Map;i.traverse((t=>{t!==i&&t.isMesh&&((t=>{let e=t;for(;e;){if(p.has(e))return!0;e=e.parent}return!1})(t)||(f.set(t,t.visible),t.visible=!1))})),e.setRenderTarget(this._renderTarget),e.setClearColor(0,0),e.autoClear=!1,e.clear(!0,!0,!1),e.render(i,n);for(const[t,e]of u)t.material=e;for(const t of d)t.visible=!0;for(const[t,e]of f)t.visible=e;e.setRenderTarget(a),e.autoClear=l,e.setClearColor(c,h)}renderDepthPass(){this.renderWithTileMaterial(this._depthMaterial)}renderNormalPass(){this.renderWithTileMaterial(this._normalMaterial)}restoreOriginalMaterials(){for(const[t,e]of this._originalMaterials)t.material=e;this._originalMaterials.clear();for(const t of this._hiddenLods)t.visible=!0;this._hiddenLods.length=0}readPixelAt(t,e){let i,n;t instanceof o.WebGLRenderTarget?(i=t,n=e):(i=this._renderTarget,n=t);const s=this.world.renderer.three,r=this._renderTargetSize,a=Math.floor(.5*(n.x+1)*r.x),l=Math.floor(.5*(n.y+1)*(r.y-1)),c=Math.max(0,Math.min(r.x-1,a)),h=Math.max(0,Math.min(r.y-1,l)),u=new Uint8Array(4);return s.readRenderTargetPixels(i,c,h,1,1,u),u}buildIdMaterial(){return new o.ShaderMaterial({uniforms:{modelByte:{value:1}},vertexShader:"\n attribute vec4 id;\n varying vec4 vId;\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n #endif\n void main() {\n vId = id;\n vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);\n #if NUM_CLIPPING_PLANES > 0\n vClipPosition = -mvPosition.xyz;\n #endif\n gl_Position = projectionMatrix * mvPosition;\n }\n ",fragmentShader:"\n precision highp float;\n uniform float modelByte;\n varying vec4 vId;\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n uniform vec4 clippingPlanes[NUM_CLIPPING_PLANES];\n #endif\n void main() {\n #if NUM_CLIPPING_PLANES > 0\n for (int i = 0; i < NUM_CLIPPING_PLANES; i++) {\n vec4 plane = clippingPlanes[i];\n if (dot(vClipPosition, plane.xyz) > plane.w) discard;\n }\n #endif\n gl_FragColor = vec4(modelByte / 255.0, vId.y / 255.0, vId.z / 255.0, vId.w / 255.0);\n }\n ",side:o.DoubleSide})}buildDepthMaterial(){return new o.ShaderMaterial({uniforms:{},vertexShader:"\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n #endif\n void main() {\n vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);\n #if NUM_CLIPPING_PLANES > 0\n vClipPosition = -mvPosition.xyz;\n #endif\n gl_Position = projectionMatrix * mvPosition;\n }\n ",fragmentShader:"\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n uniform vec4 clippingPlanes[NUM_CLIPPING_PLANES];\n #endif\n void main() {\n #if NUM_CLIPPING_PLANES > 0\n for (int i = 0; i < NUM_CLIPPING_PLANES; i++) {\n vec4 plane = clippingPlanes[i];\n if (dot(vClipPosition, plane.xyz) > plane.w) discard;\n }\n #endif\n float v = gl_FragCoord.z;\n vec4 r = vec4(\n fract(v * 16777216.0),\n fract(v * 65536.0),\n fract(v * 256.0),\n v\n );\n r.yzw -= r.xyz * (1.0 / 256.0);\n gl_FragColor = r * (256.0 / 255.0);\n }\n ",side:o.DoubleSide})}buildNormalMaterial(){return new o.ShaderMaterial({uniforms:{},vertexShader:"\n varying vec3 vWorldNormal;\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n #endif\n void main() {\n vWorldNormal = normalize(\n (modelMatrix * vec4(normal, 0.0)).xyz\n );\n vec4 mvPosition = modelViewMatrix * vec4(position, 1.0);\n #if NUM_CLIPPING_PLANES > 0\n vClipPosition = -mvPosition.xyz;\n #endif\n gl_Position = projectionMatrix * mvPosition;\n }\n ",fragmentShader:"\n varying vec3 vWorldNormal;\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n uniform vec4 clippingPlanes[NUM_CLIPPING_PLANES];\n #endif\n void main() {\n #if NUM_CLIPPING_PLANES > 0\n for (int i = 0; i < NUM_CLIPPING_PLANES; i++) {\n vec4 plane = clippingPlanes[i];\n if (dot(vClipPosition, plane.xyz) > plane.w) discard;\n }\n #endif\n vec3 n = normalize(vWorldNormal);\n if (!gl_FrontFacing) n = -n;\n gl_FragColor = vec4(n * 0.5 + 0.5, 1.0);\n }\n ",side:o.DoubleSide})}setupRenderTarget(){const t=this.world.renderer.three.getSize(new o.Vector2);this._renderTargetSize.copy(t);const e={format:o.RGBAFormat,type:o.UnsignedByteType,minFilter:o.NearestFilter,magFilter:o.NearestFilter,depthBuffer:!0};this._renderTarget=new o.WebGLRenderTarget(t.x,t.y,e),this.debugMode&&this.setupDebugCanvas(),this.world.renderer.onResize.add((t=>{this._renderTargetSize.copy(t),this._renderTarget.setSize(t.x,t.y),this._debugCanvas&&(this._debugCanvas.width=t.x,this._debugCanvas.height=t.y)}))}setupDebugCanvas(){if(this._debugCanvas)return;const t=this.world.renderer.three.getSize(new o.Vector2);this._debugContainer=document.createElement("div"),this._debugContainer.style.position="fixed",this._debugContainer.style.top="10px",this._debugContainer.style.right="10px",this._debugContainer.style.width="300px",this._debugContainer.style.height="300px",this._debugContainer.style.border="2px solid #fff",this._debugContainer.style.backgroundColor="#000",this._debugContainer.style.zIndex="10000",this._debugContainer.style.pointerEvents="none",this._debugCanvas=document.createElement("canvas"),this._debugCanvas.width=t.x,this._debugCanvas.height=t.y,this._debugCanvas.style.width="100%",this._debugCanvas.style.height="100%",this._debugCanvas.style.imageRendering="pixelated",this._debugContainer.appendChild(this._debugCanvas),document.body.appendChild(this._debugContainer)}removeDebugCanvas(){this._debugContainer&&(this._debugContainer.remove(),this._debugContainer=void 0,this._debugCanvas=void 0)}updateDebugCanvas(){if(!this._debugCanvas||!this._renderTarget||!this.world.renderer)return;const t=this.world.renderer.three,e=this._renderTargetSize,i=new Uint8Array(e.x*e.y*4);t.readRenderTargetPixels(this._renderTarget,0,0,e.x,e.y,i);const n=this._debugCanvas.getContext("2d");if(!n)return;const s=n.createImageData(e.x,e.y),r=4*e.x;for(let t=0;t<e.y;t++){const n=t*r,o=(e.y-1-t)*r;s.data.set(i.subarray(n,n+r),o)}n.putImageData(s,0,0)}};e(Wo,"MAX_MODELS",254);let Go=Wo;const Ho=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new Map),e(this,"onDisposed",new at),i.add(t.uuid,this)}get(t){if(this.list.has(t.uuid))return this.list.get(t.uuid);const e=new Go(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add((()=>{this.delete(t)})),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}};e(Ho,"uuid","4a82430c-7ff2-49ea-9401-60807502dad6");let Zo=Ho;var qo=(t=>(t[t.POINT=0]="POINT",t[t.LINE=1]="LINE",t[t.FACE=2]="FACE",t))(qo||{});const Yo=1e3;class Xo{constructor(t){e(this,"onDisposed",new at),e(this,"maxDistance",1),e(this,"maxCacheSize",1e3),e(this,"components"),e(this,"cache",new Map),this.components=t}dispose(){this.cache.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}async resolve(t,e,i,n){const s=Xo.keyOf(e,i);let r=this.cache.get(s);if(r)this.cache.delete(s),this.cache.set(s,r);else{if(r=await this.fetchItemSnapData(e,i),!r)return null;this.storeWithLRU(s,r)}const o=this.snap(t,r,2),a=new Set(n),l=[0,1,2];let c=null;for(const e of l){if(!a.has(e))continue;const i=this.snap(t,r,e);if(i){c=i.result;break}}if(!c)return o?o.result:null;if(o&&2!==c.snappingClass){const t=o.result;!c.normal&&t.normal&&(c.normal=t.normal),!c.facePoints&&t.facePoints&&(c.facePoints=t.facePoints),!c.faceIndices&&t.faceIndices&&(c.faceIndices=t.faceIndices)}return c}async prefetch(t,e){const i=Xo.keyOf(t,e);if(this.cache.has(i))return;const n=await this.fetchItemSnapData(t,e);n&&this.storeWithLRU(i,n)}invalidate(t,e){const i=Xo.keyOf(t,e);this.cache.delete(i)}clear(){this.cache.clear()}static keyOf(t,e){return`${t}:${e}`}storeWithLRU(t,e){for(this.cache.set(t,e);this.cache.size>this.maxCacheSize;){const t=this.cache.keys().next().value;if(void 0===t)break;this.cache.delete(t)}}async fetchItemSnapData(t,e){const i=this.components.get(fr).list.get(t);if(!i)return null;const n=await i._getItemSnapData(e);if(!n)return null;const s=i.object.matrixWorld,r=[];for(const t of Object.keys(n.samples??{})){const e=n.samples[Number(t)],i=n.representations[e.representation];if(!i||1!==i.representationClass)continue;const o=i.geometry;if(!o)continue;const a=n.localTransforms[e.localTransform],l=sa(s,n.globalTransforms[e.item],a);this.collectPolygonsFromShell(o,l,r)}if(0===r.length)return null;return{faces:r,edges:function(t){const e=new Set,i=[];for(const n of t){const t=n.points,s=t.length/3;for(let n=0;n<s;n++){const r=(n+1)%s,o=t[3*n],a=t[3*n+1],l=t[3*n+2],c=t[3*r],h=t[3*r+1],u=t[3*r+2],d=aa(o,a,l,c,h,u);e.has(d)||(e.add(d),i.push(o,a,l,c,h,u))}}return new Float32Array(i)}(r),vertices:function(t){const e=new Set,i=[];for(const n of t){const t=n.points,s=t.length/3;for(let n=0;n<s;n++){const s=t[3*n],r=t[3*n+1],o=t[3*n+2],a=oa(s,r,o);e.has(a)||(e.add(a),i.push(s,r,o))}}return new Float32Array(i)}(r)}}collectPolygonsFromShell(t,e,i){const n=t.points,s=t.profiles??new Map,r=t.bigProfiles??new Map,a=new o.Vector3,l=t=>{if(t.length<3)return;const s=new Float32Array(3*t.length);for(let i=0;i<t.length;i++){const r=n[t[i]];a.set(r[0],r[1],r[2]).applyMatrix4(e),s[3*i]=a.x,s[3*i+1]=a.y,s[3*i+2]=a.z}const r=function(t){const e=new o.Vector3,i=t.length/3;for(let n=0;n<i;n++){const s=(n+1)%i,r=t[3*n],o=t[3*n+1],a=t[3*n+2],l=t[3*s],c=t[3*s+1],h=t[3*s+2];e.x+=(o-c)*(a+h),e.y+=(a-h)*(r+l),e.z+=(r-l)*(o+c)}const n=e.length();return n<1e-10?null:e.divideScalar(n)}(s);if(!r)return;const l=r.x*s[0]+r.y*s[1]+r.z*s[2];i.push({points:s,normal:r,d:l})};for(const t of s.values())l(t);for(const t of r.values())l(t)}snap(t,e,i){return 0===i?this.snapToPoint(t,e):1===i?this.snapToLine(t,e):2===i?this.snapToFace(t,e):null}snapToPoint(t,e){const i=e.vertices;if(0===i.length)return null;const n=this.maxDistance*this.maxDistance;let s=-1,r=1/0;for(let e=0;e<i.length;e+=3){const o=i[e]-t.x,a=i[e+1]-t.y,l=i[e+2]-t.z,c=o*o+a*a+l*l;c<=n&&c<r&&(r=c,s=e)}return s<0?null:{result:{point:new o.Vector3(i[s],i[s+1],i[s+2]),snappingClass:0}}}snapToLine(t,e){const i=e.edges;if(0===i.length)return null;const n=this.maxDistance*this.maxDistance,s=new o.Vector3,r=new o.Vector3;let a=1/0,l=-1;for(let e=0;e<i.length;e+=6){const o=la(t,i[e],i[e+1],i[e+2],i[e+3],i[e+4],i[e+5],r);o<=n&&o<a&&(a=o,l=e,s.copy(r))}return l<0?null:{result:{point:s.clone(),snappingClass:1,snappedEdgeP1:new o.Vector3(i[l],i[l+1],i[l+2]),snappedEdgeP2:new o.Vector3(i[l+3],i[l+4],i[l+5])}}}snapToFace(t,e){const i=e.faces;if(0===i.length)return null;let n=null,s=1/0;for(const e of i){const i=e.normal.x*t.x+e.normal.y*t.y+e.normal.z*t.z-e.d,r=Math.abs(i);r<=this.maxDistance&&r<s&&(s=r,n=e)}if(!n)return null;return{result:{point:t.clone().sub(n.normal.clone().multiplyScalar(n.normal.x*t.x+n.normal.y*t.y+n.normal.z*t.z-n.d)),normal:n.normal.clone(),snappingClass:2,facePoints:n.points,faceIndices:ra(n.points.length/3)}}}}const Ko=new o.Matrix4,Qo=new o.Vector3,Jo=new o.Vector3,ta=new o.Vector3;function ea(t,e){if(!t)return e.identity();const i=t.position[0],n=t.position[1],s=t.position[2];return Qo.set(t.xDirection[0],t.xDirection[1],t.xDirection[2]),Jo.set(t.yDirection[0],t.yDirection[1],t.yDirection[2]),ta.crossVectors(Qo,Jo),e.set(Qo.x,Jo.x,ta.x,i,Qo.y,Jo.y,ta.y,n,Qo.z,Jo.z,ta.z,s,0,0,0,1),e}const ia=new o.Matrix4,na=new o.Matrix4;function sa(t,e,i){return ea(e,ia),ea(i,na),Ko.copy(t).multiply(ia).multiply(na).clone()}function ra(t){if(t<3)return new Uint32Array(0);const e=t-2,i=new Uint32Array(3*e);for(let t=0;t<e;t++)i[3*t]=0,i[3*t+1]=t+1,i[3*t+2]=t+2;return i}function oa(t,e,i){return`${Math.round(t*Yo)},${Math.round(e*Yo)},${Math.round(i*Yo)}`}function aa(t,e,i,n,s,r){const o=oa(t,e,i),a=oa(n,s,r);return o<a?`${o}|${a}`:`${a}|${o}`}function la(t,e,i,n,s,r,o,a){const l=s-e,c=r-i,h=o-n,u=l*l+c*c+h*h;let d=0;u>0&&(d=((t.x-e)*l+(t.y-i)*c+(t.z-n)*h)/u,d<0?d=0:d>1&&(d=1));const p=e+d*l,f=i+d*c,m=n+d*h;a.set(p,f,m);const g=t.x-p,w=t.y-f,y=t.z-m;return g*g+w*w+y*y}const ca=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new at),e(this,"_resolver"),i.add(t.uuid,this),this._resolver=new Xo(i)}get(){return this._resolver}dispose(){this._resolver.dispose(),this.onDisposed.trigger()}};e(ca,"uuid","be9b8e6c-7f5b-4a36-8e7e-3a1f5e2a6c9d");let ha=ca;class ua{constructor(t,i){e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new at),e(this,"mouse"),e(this,"three",new o.Raycaster),e(this,"world");const n=i.renderer;if(!n)throw new Error("A renderer is needed for the raycaster to work!");this.world=i,this.mouse=new fi(n.three.domElement),this.components=t}dispose(){this.mouse.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}castRayToObjects(t=Array.from(this.world.meshes),e=this.mouse.position){if(!this.world)throw new Error("A world is needed to cast rays!");const i=this.world.camera.three;return this.three.setFromCamera(e,i),this.intersect(t)}async castRay(t){const e=null==t?void 0:t.snappingClasses,i=(null==t?void 0:t.items)??Array.from(this.world.meshes),n=(null==t?void 0:t.position)??this.mouse.position;if(!this.world)throw new Error("A world is needed to cast rays!");const s=this.world.camera.three,r=this.components.get(fr);let o=null;if(r.initialized){const t=this.components.get(Zo).get(this.world),a=await t.getFullPick(n);if(a){const t=r.list.get(a.modelId);if(o={localId:a.localId,point:a.point,normal:a.normal,distance:a.distance,fragments:t,object:null==t?void 0:t.object,ray:void 0,frustum:void 0},e&&e.length>0){const t=await this.components.get(ha).get().resolve(a.point,a.modelId,a.itemId,e);t&&(o.point=t.point,t.normal&&(o.normal=t.normal),o.snappingClass=t.snappingClass,t.facePoints&&(o.facePoints=t.facePoints),t.faceIndices&&(o.faceIndices=t.faceIndices),t.snappedEdgeP1&&(o.snappedEdgeP1=t.snappedEdgeP1),t.snappedEdgeP2&&(o.snappedEdgeP2=t.snappedEdgeP2),o.distance=t.point.distanceTo(s.position))}}if(0===i.length)return o}this.three.setFromCamera(n,s);const a=this.intersect(i);return o?a&&a.distance<o.distance?a:o:a}castRayFromVector(t,e,i=Array.from(this.world.meshes)){return this.three.set(t,e),this.intersect(i)}intersect(t=Array.from(this.world.meshes)){const e=this.three.intersectObjects(t),i=this.filterClippingPlanes(e);return i.length>0?i[0]:null}filterClippingPlanes(t){if(!this.world.renderer)throw new Error("Renderer not found!");const e=this.world.renderer.three;if(!e.clippingPlanes)return t;const i=e.clippingPlanes;return t.length<=0||!i||(null==i?void 0:i.length)<=0?t:t.filter((t=>i.every((e=>e.distanceToPoint(t.point)>0))))}}const da=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new Map),e(this,"onDisposed",new at),i.add(t.uuid,this)}get(t){if(this.list.has(t.uuid))return this.list.get(t.uuid);const e=new ua(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add((()=>{this.delete(t)})),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}};e(da,"uuid","d5d8bdf0-db25-4952-b951-b643af207ace");let pa=da;class fa extends ct{constructor(){super(...arguments),e(this,"onCameraChanged",new at),e(this,"meshes",new Set),e(this,"onAfterUpdate",new at),e(this,"onBeforeUpdate",new at),e(this,"onDisposed",new at),e(this,"isDisposing",!1),e(this,"enabled",!0),e(this,"_dynamicAnchor",!1),e(this,"uuid",_t.create()),e(this,"name"),e(this,"_scene"),e(this,"_camera"),e(this,"_renderer",null),e(this,"onPointerDown",(async t=>{if(!this.camera.hasCameraControls())throw new Error("World: can't set dynamic anchor if the camera doesn't have controls.");const e=this.components.get(pa).get(this),i=await e.castRay();i&&i.point&&0===t.button&&this.camera.controls.setOrbitPoint(i.point.x,i.point.y,i.point.z)})),e(this,"_defaultCamera")}set dynamicAnchor(t){var e;const i=null==(e=this.renderer)?void 0:e.three.domElement.parentElement;if(!i)throw new Error("World: the renderer must have a parentElement to set dynamic anchoring.");t?(this.camera.controls&&(this.camera.controls.minDistance=.01),i.addEventListener("pointerdown",this.onPointerDown)):i.removeEventListener("pointerdown",this.onPointerDown)}get dynamicAnchor(){return this._dynamicAnchor}get defaultCamera(){if(!this._defaultCamera)throw new Error("World: there is no default camera defined.");return this._defaultCamera}set defaultCamera(t){this._defaultCamera=t}get scene(){if(!this._scene)throw new Error("No scene initialized!");return this._scene}set scene(t){this._scene=t,t.worlds.set(this.uuid,this),t.currentWorld=this,t.onWorldChanged.trigger({world:this,action:"added"})}get camera(){if(!this._camera)throw new Error("No camera initialized!");return this._camera}set camera(t){this._camera||(this.defaultCamera=t),this._camera=t,t.currentWorld=this,this.onCameraChanged.trigger(t)}get renderer(){return this._renderer}set renderer(t){this._renderer=t,t&&(t.worlds.set(this.uuid,this),t.currentWorld=this,t.onWorldChanged.trigger({world:this,action:"added"}))}useDefaultCamera(){this.camera=this.defaultCamera}update(t){this.enabled&&this._scene&&this._camera&&(this.scene.currentWorld=this,this.camera.currentWorld=this,this.renderer&&(this.renderer.currentWorld=this),this.onBeforeUpdate.trigger(),this.scene.isUpdateable()&&this.scene.update(t),this.camera.isUpdateable()&&this.camera.update(t),this.renderer&&this.renderer.update(t),this.onAfterUpdate.trigger())}dispose(t=!0){if(this.enabled=!1,this.isDisposing=!0,this.scene.onWorldChanged.trigger({world:this,action:"removed"}),this.camera.onWorldChanged.trigger({world:this,action:"removed"}),this.renderer&&this.renderer.onWorldChanged.trigger({world:this,action:"removed"}),t){const t=this.components.get(mt);this.scene.dispose(),this.camera.isDisposeable()&&this.camera.dispose(),this.renderer&&this.renderer.dispose();for(const e of this.meshes)t.destroy(e);this.meshes.clear()}this._scene=null,this._camera=null,this._renderer=null;this.components.get(Sa).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class ma{constructor(t,i){e(this,"_list"),e(this,"_scene"),this._list=t,this._scene=i}get color(){return this._list.directionalLight.color.value}set color(t){this._list.directionalLight.color.value=t;for(const[,e]of this._scene.directionalLights)e.color.copy(t)}get intensity(){return this._list.directionalLight.intensity.value}set intensity(t){this._list.directionalLight.intensity.value=t;for(const[,e]of this._scene.directionalLights)e.intensity=t}get position(){return this._list.directionalLight.position.value.clone()}set position(t){this._list.directionalLight.position.value=t;for(const[,e]of this._scene.directionalLights)e.position.copy(t)}}class ga{constructor(t,i){e(this,"_list"),e(this,"_scene"),this._list=t,this._scene=i}get color(){return this._list.ambientLight.color.value}set color(t){this._list.ambientLight.color.value=t;for(const[,e]of this._scene.ambientLights)e.color.copy(t)}get intensity(){return this._list.ambientLight.intensity.value}set intensity(t){this._list.ambientLight.intensity.value=t;for(const[,e]of this._scene.ambientLights)e.intensity=t}}class wa extends ui{constructor(){super(...arguments),e(this,"_config",{backgroundColor:{value:new o.Color,type:"Color"},ambientLight:{color:{type:"Color",value:new o.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2}},directionalLight:{color:{type:"Color",value:new o.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2},position:{type:"Vector3",value:new o.Vector3}}}),e(this,"ambientLight",new ga(this._config,this._component)),e(this,"directionalLight",new ma(this._config,this._component))}get backgroundColor(){return this._config.backgroundColor.value}set backgroundColor(t){this._config.backgroundColor.value=t,this._component.three.background=t}}class ya extends gt{constructor(t){super(t),e(this,"onSetup",new at),e(this,"isSetup",!1),e(this,"three"),e(this,"config",new wa(this,this.components,"Scene")),e(this,"_defaultConfig",{backgroundColor:new o.Color(2107698),directionalLight:{color:new o.Color("white"),intensity:1.5,position:new o.Vector3(5,10,3)},ambientLight:{color:new o.Color("white"),intensity:1}}),this.three=new o.Scene,this.three.background=new o.Color(2107698)}setup(t){const e={...this._defaultConfig,...t};this.config.backgroundColor=e.backgroundColor;const i=e.ambientLight;this.config.ambientLight.color=i.color,this.config.ambientLight.intensity=i.intensity;const n=e.directionalLight;this.config.directionalLight.color=n.color,this.config.directionalLight.intensity=n.intensity,this.config.directionalLight.position=n.position,this.deleteAllLights();const{color:s,intensity:r}=this.config.directionalLight,a=new o.DirectionalLight(s,r);a.position.copy(n.position);const{color:l,intensity:c}=this.config.directionalLight,h=new o.AmbientLight(l,c);this.three.add(a,h),this.directionalLights.set(a.uuid,a),this.ambientLights.set(h.uuid,h),this.isSetup=!0,this.onSetup.trigger()}dispose(){super.dispose();this.components.get(pi).list.delete(this.config.uuid)}}const _a='\n<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 120 40" fill="none" aria-label="That Open Company">\n<path d="M42.2856 19.6517V8.4048H38.8676V7.14978H46.998V8.40976H43.6131V19.6566L42.2856 19.6517Z" fill="#BCF124"/>\n<path d="M48.459 19.6516V7.14978H49.7032V12.404L49.4204 12.3371C49.6285 11.7727 50.0095 11.2904 50.5078 10.9607C51.0285 10.6201 51.638 10.4449 52.2578 10.4577C52.853 10.4483 53.44 10.5988 53.9589 10.8938C54.456 11.1789 54.8687 11.5934 55.1541 12.0943C55.449 12.6164 55.6 13.2089 55.5913 13.8102V19.6516H54.3495V14.2958C54.3637 13.8139 54.2611 13.3359 54.0507 12.9033C53.8646 12.537 53.5797 12.2315 53.229 12.0224C52.8685 11.8121 52.4584 11.7046 52.0423 11.7115C51.624 11.7054 51.2117 11.8128 50.8483 12.0224C50.4912 12.2324 50.2006 12.541 50.0106 12.912C49.7956 13.3401 49.6899 13.8158 49.7032 14.2958V19.6516H48.459Z" fill="#BCF124"/>\n<path d="M60.5388 19.8524C60.0174 19.8619 59.5007 19.75 59.0289 19.5253C58.6071 19.3259 58.2459 19.0157 57.983 18.6271C57.7263 18.2403 57.593 17.7833 57.6009 17.3175C57.5959 16.8715 57.6984 16.4309 57.8997 16.034C58.1173 15.6285 58.4383 15.2892 58.8292 15.0516C59.3232 14.7561 59.8701 14.5624 60.4384 14.4817L63.9188 13.8932V15.0355L60.7348 15.5744C60.0931 15.6867 59.6314 15.8932 59.3497 16.1938C59.0735 16.4811 58.9212 16.8673 58.926 17.268C58.9244 17.4635 58.9661 17.657 59.0481 17.8341C59.1301 18.0112 59.2503 18.1674 59.3999 18.2913C59.7416 18.5818 60.1787 18.7318 60.6246 18.7113C61.1803 18.7244 61.7296 18.5884 62.2166 18.3173C62.6597 18.066 63.0268 17.6972 63.2784 17.2506C63.535 16.7959 63.6669 16.2801 63.6604 15.7565V13.4744C63.6679 13.2259 63.6196 12.979 63.519 12.7521C63.4185 12.5253 63.2684 12.3245 63.08 12.1649C62.693 11.8287 62.1897 11.6607 61.57 11.6607C61.0801 11.6502 60.5978 11.7845 60.1822 12.047C59.7665 12.3095 59.4355 12.6888 59.2297 13.1387L58.1018 12.5192C58.2839 12.117 58.553 11.7614 58.8892 11.4785C59.2572 11.162 59.6754 10.9107 60.1261 10.7352C60.5858 10.5517 61.0758 10.4579 61.57 10.4589C62.1703 10.4448 62.7654 10.5748 63.3065 10.838C63.7888 11.077 64.1965 11.4462 64.4846 11.9047C64.7683 12.3771 64.912 12.9219 64.8986 13.4744V19.6517H63.658V17.8552L63.8405 18.0398C63.6702 18.3954 63.4238 18.7081 63.1191 18.9554C62.7772 19.238 62.3899 19.4593 61.9741 19.6095C61.5136 19.7756 61.0277 19.8578 60.5388 19.8524Z" fill="#BCF124"/>\n<path d="M70.6935 19.752C69.8975 19.752 69.2852 19.517 68.8566 19.0471C68.428 18.5771 68.2108 17.9056 68.2051 17.0326V11.9122H66.5616V10.6534H66.9804C67.1477 10.662 67.3148 10.6332 67.4697 10.5689C67.6247 10.5047 67.7637 10.4066 67.8769 10.2818C68.1017 10.0195 68.2202 9.68094 68.2088 9.33398V8.57825H69.453V10.6596H71.4124V11.9184H69.453V17.0388C69.4478 17.3107 69.4926 17.5813 69.5853 17.8366C69.6729 18.065 69.8337 18.2569 70.042 18.3818C70.3083 18.5292 70.6096 18.5991 70.9128 18.5837C71.0009 18.5837 71.1063 18.5775 71.2287 18.5664C71.3512 18.5552 71.4553 18.5441 71.5434 18.5329V19.6578C71.396 19.6937 71.2462 19.7189 71.0952 19.7334C70.9262 19.7433 70.7927 19.752 70.6935 19.752Z" fill="#BCF124"/>\n<path d="M82.2003 19.8523C81.3145 19.8603 80.4355 19.6954 79.6114 19.3666C78.4307 18.8928 77.4197 18.068 76.7118 17.001C76.0038 15.9341 75.6323 14.6751 75.646 13.3901C75.6376 12.5147 75.8043 11.6466 76.1359 10.838C76.453 10.0681 76.9213 9.37141 77.5123 8.79004C78.1118 8.20273 78.819 7.73977 79.5942 7.42723C81.2715 6.778 83.1266 6.778 84.8039 7.42723C85.5794 7.73911 86.2867 8.20215 86.8857 8.79004C87.4768 9.3717 87.9454 10.0683 88.2635 10.838C88.5945 11.6468 88.7611 12.5148 88.7533 13.3901C88.7674 14.6752 88.396 15.9343 87.688 17.0013C86.98 18.0683 85.9688 18.8931 84.7879 19.3666C83.9642 19.6952 83.0857 19.8601 82.2003 19.8523ZM82.2003 17.4984C82.7378 17.5032 83.2709 17.4005 83.769 17.1961C84.2425 16.9994 84.6735 16.7111 85.0378 16.3474C85.4069 15.9786 85.6952 15.5354 85.884 15.0465C86.0882 14.5173 86.1896 13.9532 86.1828 13.3852C86.1898 12.8203 86.0883 12.2594 85.884 11.7337C85.6922 11.2464 85.4043 10.8038 85.0378 10.4328C84.6764 10.0659 84.2446 9.77748 83.769 9.58542C82.7594 9.19396 81.6424 9.19396 80.6327 9.58542C80.1568 9.77745 79.7246 10.0658 79.3628 10.4328C78.9967 10.8041 78.7088 11.2467 78.5166 11.7337C78.3119 12.2602 78.2104 12.8219 78.2177 13.3876C78.2109 13.9557 78.3123 14.5198 78.5166 15.049C78.7058 15.5377 78.994 15.9808 79.3628 16.3499C79.7275 16.7136 80.1589 17.0019 80.6327 17.1985C81.1302 17.4038 81.663 17.5074 82.2003 17.5033V17.4984Z" fill="#BCF124"/>\n<path d="M90.398 23.2209V10.4861H92.7248V12.2293L92.5081 11.7251C92.8117 11.2627 93.2354 10.8941 93.7327 10.6596C94.2857 10.3994 94.8901 10.2702 95.4999 10.2817C96.3233 10.271 97.1335 10.4919 97.8401 10.9198C98.5312 11.3384 99.1029 11.9314 99.4995 12.6406C99.9126 13.38 100.124 14.2172 100.112 15.0664C100.122 15.9116 99.913 16.7448 99.5069 17.4835C99.1168 18.1988 98.5469 18.7971 97.8548 19.218C97.1376 19.6483 96.3164 19.8688 95.4827 19.8548C94.894 19.8605 94.3104 19.7437 93.7682 19.5116C93.2614 19.2967 92.8226 18.9454 92.4995 18.4957L92.8975 17.9754V23.2234L90.398 23.2209ZM95.1741 17.5863C95.6033 17.5949 96.0268 17.4848 96.3987 17.268C96.7521 17.0559 97.0394 16.7477 97.2278 16.3784C97.4328 15.9736 97.5355 15.5237 97.5266 15.0689C97.5364 14.6168 97.4337 14.1694 97.2278 13.768C97.0366 13.4007 96.7499 13.0932 96.3987 12.8785C96.0288 12.6556 95.6046 12.5419 95.1741 12.5502C94.7569 12.5434 94.3461 12.6541 93.9874 12.8698C93.6387 13.0826 93.3568 13.391 93.1743 13.7593C92.9832 14.1688 92.8841 14.6161 92.8841 15.0689C92.8841 15.5217 92.9832 15.9689 93.1743 16.3784C93.3571 16.7465 93.639 17.0548 93.9874 17.268C94.3469 17.4837 94.7586 17.594 95.1766 17.5863H95.1741Z" fill="#BCF124"/>\n<path d="M105.924 19.8524C104.961 19.8524 104.126 19.6372 103.418 19.2069C102.724 18.7915 102.156 18.1916 101.776 17.4724C101.384 16.7291 101.184 15.8977 101.194 15.0553C101.179 14.1986 101.388 13.3532 101.801 12.6047C102.189 11.9046 102.753 11.3198 103.434 10.9087C104.139 10.4899 104.944 10.2756 105.761 10.2892C106.414 10.277 107.062 10.394 107.67 10.6336C108.202 10.8483 108.68 11.1777 109.073 11.5987C109.454 12.0141 109.75 12.5023 109.943 13.0346C110.147 13.6019 110.248 14.2016 110.242 14.805C110.242 14.9847 110.234 15.1606 110.218 15.334C110.205 15.4855 110.174 15.6349 110.126 15.7788H103.34V13.9266H108.716L107.538 14.8001C107.65 14.3786 107.645 13.9339 107.522 13.5153C107.411 13.1561 107.186 12.8437 106.883 12.6258C106.553 12.4 106.161 12.2855 105.762 12.2987C105.368 12.2877 104.981 12.3993 104.652 12.6184C104.327 12.8492 104.083 13.1779 103.955 13.5574C103.79 14.0428 103.728 14.5577 103.772 15.0689C103.719 15.5315 103.782 16.0001 103.955 16.4317C104.108 16.81 104.375 17.1302 104.718 17.3473C105.08 17.5514 105.486 17.6634 105.901 17.6736C106.316 17.6837 106.727 17.5917 107.098 17.4055C107.407 17.2317 107.661 16.9743 107.833 16.6622L109.824 17.6186C109.643 18.0737 109.355 18.4776 108.986 18.7956C108.59 19.1398 108.132 19.4046 107.638 19.5761C107.087 19.766 106.507 19.8594 105.924 19.8524Z" fill="#BCF124"/>\n<path d="M111.703 19.6516V10.4837H114.03V12.2962L113.898 11.8935C114.081 11.3764 114.443 10.944 114.918 10.6769C115.425 10.404 115.994 10.2679 116.569 10.2817C117.196 10.2676 117.816 10.4179 118.369 10.7178C118.875 11.0011 119.293 11.4232 119.573 11.9357C119.87 12.4948 120.018 13.1223 120.004 13.7569V19.6491H117.515V14.2958C117.524 13.9753 117.452 13.6579 117.307 13.3728C117.173 13.1206 116.972 12.9112 116.727 12.7682C116.459 12.625 116.162 12.5502 115.859 12.5502C115.557 12.5502 115.26 12.625 114.992 12.7682C114.743 12.9091 114.539 13.1188 114.403 13.3728C114.259 13.658 114.188 13.9754 114.196 14.2958V19.6516H111.703Z" fill="#BCF124"/>\n<path d="M45.7329 35.9372C44.8875 35.9451 44.0493 35.7794 43.269 35.4503C42.525 35.134 41.851 34.6707 41.2863 34.0875C40.7178 33.4992 40.2696 32.8033 39.9673 32.0396C39.6453 31.2229 39.4843 30.3504 39.4934 29.4713C39.4848 28.5902 39.6427 27.7155 39.9588 26.8943C40.2511 26.1324 40.6939 25.4388 41.2601 24.8558C41.8262 24.2727 42.504 23.8126 43.2518 23.5034C44.039 23.178 44.8826 23.015 45.7329 23.024C46.5598 23.0107 47.3809 23.1649 48.1479 23.4774C48.8259 23.756 49.443 24.1669 49.9641 24.6866C50.4412 25.1559 50.8045 25.7304 51.0258 26.3653L48.7529 27.4729C48.5362 26.8433 48.1263 26.3001 47.5831 25.9226C47.0399 25.5451 46.3917 25.3529 45.7329 25.3742C45.0556 25.3604 44.3882 25.5408 43.8078 25.8945C43.2553 26.2426 42.8099 26.74 42.5219 27.3304C42.2056 27.9978 42.0495 28.7313 42.0664 29.4713C42.0503 30.2135 42.2063 30.9493 42.5219 31.6196C42.8077 32.2136 43.2534 32.7139 43.8078 33.0629C44.3879 33.4172 45.0555 33.5976 45.7329 33.5832C46.3917 33.6045 47.0399 33.4124 47.5831 33.0348C48.1263 32.6573 48.5362 32.1142 48.7529 31.4845L51.0258 32.5933C50.8056 33.2316 50.4422 33.8096 49.9641 34.282C49.4426 34.8009 48.8256 35.2113 48.1479 35.4899C47.3805 35.8004 46.5594 35.9524 45.7329 35.9372Z" fill="#BCF124"/>\n<path d="M56.8159 35.9372C55.9603 35.9485 55.1164 35.735 54.3667 35.3177C53.6426 34.9153 53.0357 34.3274 52.6069 33.613C52.1777 32.8648 51.9517 32.0151 51.9517 31.15C51.9517 30.285 52.1777 29.4353 52.6069 28.6871C53.0376 27.9762 53.6442 27.3911 54.3667 26.9898C55.118 26.5823 55.9573 26.3691 56.8098 26.3691C57.6623 26.3691 58.5016 26.5823 59.253 26.9898C59.9716 27.3928 60.5749 27.9771 61.0042 28.6858C61.4334 29.4341 61.6594 30.2837 61.6594 31.1488C61.6594 32.0139 61.4334 32.8635 61.0042 33.6118C60.577 34.3244 59.9733 34.912 59.253 35.3165C58.5078 35.7343 57.6678 35.9482 56.8159 35.9372ZM56.8159 33.6712C57.2335 33.681 57.6451 33.5701 58.0026 33.3516C58.3443 33.1354 58.6199 32.8274 58.7986 32.462C58.9985 32.0556 59.0985 31.6064 59.0901 31.1525C59.099 30.7014 58.9989 30.2548 58.7986 29.8517C58.6161 29.4889 58.3414 29.1818 58.0026 28.9621C57.6468 28.739 57.2345 28.6254 56.8159 28.635C56.3952 28.6261 55.9807 28.7396 55.6219 28.9621C55.2792 29.18 55.0008 29.4873 54.8161 29.8517C54.6162 30.2549 54.5166 30.7015 54.5259 31.1525C54.517 31.6063 54.6166 32.0555 54.8161 32.462C54.997 32.8291 55.2762 33.1373 55.6219 33.3516C55.9824 33.5695 56.3962 33.6803 56.8159 33.6712Z" fill="#BCF124"/>\n<path d="M63.1228 35.7364V26.5685H65.4496V28.7985L65.2047 28.4269C65.337 27.7223 65.6574 27.202 66.1661 26.8658C66.7124 26.5198 67.3477 26.3448 67.992 26.3628C68.6955 26.3487 69.3867 26.5504 69.9747 26.9414C70.2455 27.1163 70.4794 27.3435 70.6631 27.6102C70.8468 27.8768 70.9766 28.1775 71.045 28.495L70.3311 28.5619C70.6299 27.8128 71.056 27.2586 71.6096 26.8993C72.1912 26.5332 72.8658 26.3468 73.5506 26.3628C74.1566 26.3506 74.755 26.5011 75.2847 26.7989C75.7839 27.0856 76.1947 27.5068 76.4714 28.0155C76.7686 28.5772 76.9163 29.2073 76.9 29.8442V35.7364H74.4067V30.3806C74.4151 30.0621 74.3496 29.746 74.2156 29.4576C74.0956 29.2086 73.9084 28.999 73.6756 28.853C73.4175 28.71 73.1279 28.635 72.8336 28.635C72.5393 28.635 72.2498 28.71 71.9917 28.853C71.7556 28.9972 71.5655 29.2071 71.4443 29.4576C71.3103 29.746 71.2448 30.0621 71.2532 30.3806V35.7364H68.7648V30.3806C68.7731 30.0621 68.7077 29.746 68.5737 29.4576C68.4538 29.2089 68.267 28.9994 68.0349 28.853C67.7765 28.71 67.4868 28.635 67.1923 28.635C66.8978 28.635 66.6081 28.71 66.3498 28.853C66.1137 28.9972 65.9236 29.2071 65.8023 29.4576C65.6683 29.746 65.6029 30.0621 65.6113 30.3806V35.7364H63.1228Z" fill="#BCF124"/>\n<path d="M78.5374 39.3107V26.5697H80.8642V28.3166L80.6486 27.8123C80.9522 27.35 81.376 26.9813 81.8733 26.7469C82.4266 26.4883 83.0311 26.3611 83.6404 26.3752C84.464 26.3639 85.2743 26.5848 85.9807 27.0132C86.6715 27.4323 87.2431 28.0251 87.6401 28.7341C88.0532 29.473 88.2645 30.3098 88.2524 31.1586C88.2623 32.0044 88.0533 32.8381 87.6462 33.577C87.2571 34.2926 86.6875 34.8911 85.9954 35.3115C85.2785 35.7427 84.4572 35.9636 83.6233 35.9495C83.0345 35.9548 82.4509 35.8376 81.9088 35.6051C81.4019 35.391 80.963 35.04 80.6401 34.5904L81.0381 34.0701V39.3231L78.5374 39.3107ZM83.3134 33.6712C83.7428 33.6796 84.1663 33.5691 84.5381 33.3515C84.892 33.1399 85.1798 32.8316 85.3684 32.462C85.573 32.057 85.6757 31.6072 85.6672 31.1524C85.6761 30.7004 85.5734 30.2533 85.3684 29.8516C85.176 29.4847 84.8891 29.1774 84.5381 28.962C84.1679 28.7398 83.7438 28.6266 83.3134 28.635C82.8964 28.6281 82.4856 28.7383 82.1268 28.9534C81.778 29.1666 81.496 29.4755 81.3136 29.8442C81.1225 30.2534 81.0233 30.7004 81.0233 31.1531C81.0233 31.6057 81.1225 32.0527 81.3136 32.462C81.4954 32.8308 81.7775 33.1394 82.1268 33.3515C82.4863 33.5682 82.8986 33.679 83.3171 33.6712H83.3134Z" fill="#BCF124"/>\n<path d="M92.5093 35.9371C91.9294 35.9511 91.353 35.8427 90.8168 35.6187C90.3699 35.4306 89.9887 35.1118 89.722 34.7032C89.4607 34.2804 89.3278 33.7893 89.3399 33.2908C89.3319 32.8129 89.4525 32.3418 89.689 31.928C89.9498 31.5033 90.3197 31.1581 90.7593 30.9295C91.3217 30.6339 91.931 30.4406 92.5595 30.3583L95.3296 29.9049V31.7521L93.0028 32.1708C92.7069 32.2127 92.4268 32.3314 92.1897 32.5153C92.0938 32.6024 92.0186 32.7102 91.9696 32.8307C91.9207 32.9513 91.8992 33.0814 91.9068 33.2115C91.9015 33.3387 91.9277 33.4652 91.9828 33.5796C92.038 33.6941 92.1204 33.7928 92.2227 33.8669C92.4503 34.0296 92.7243 34.1123 93.0028 34.1023C93.3792 34.1101 93.7509 34.0174 94.0805 33.8335C94.3832 33.6617 94.6332 33.4087 94.803 33.1025C94.9751 32.7929 95.0638 32.443 95.0602 32.0878V29.698C95.062 29.5308 95.0264 29.3654 94.956 29.2141C94.8855 29.0628 94.7822 28.9296 94.6536 28.8245C94.3818 28.5891 94.0144 28.4714 93.5515 28.4714C93.1318 28.4645 92.7212 28.5949 92.3807 28.8431C92.0467 29.0873 91.7912 29.4256 91.6459 29.8157L89.6547 28.8592C89.826 28.354 90.1169 27.8989 90.5021 27.5336C90.9038 27.1547 91.3782 26.8634 91.8958 26.6775C92.4648 26.471 93.0657 26.3686 93.6702 26.3752C94.3679 26.3612 95.0599 26.5046 95.6958 26.7952C96.2502 27.0473 96.724 27.4511 97.0637 27.961C97.3951 28.4765 97.5658 29.0807 97.5536 29.6955V35.7389H95.2268V34.2584L95.7913 34.1581C95.5497 34.5339 95.2533 34.8706 94.912 35.1566C94.5921 35.4193 94.2261 35.6185 93.8331 35.7439C93.4044 35.877 92.9578 35.9422 92.5093 35.9371Z" fill="#BCF124"/>\n<path d="M99.3795 35.7365V26.5685H101.706V28.3823L101.573 27.9796C101.757 27.4626 102.119 27.0301 102.593 26.7618C103.101 26.4898 103.67 26.3542 104.245 26.3678C104.872 26.3532 105.493 26.5034 106.045 26.8039C106.551 27.0867 106.968 27.5085 107.248 28.0205C107.545 28.5801 107.693 29.208 107.679 29.8429V35.7352H105.189V30.3806C105.197 30.0603 105.126 29.743 104.982 29.4576C104.848 29.2051 104.646 28.9957 104.401 28.8531C104.135 28.7035 103.834 28.6282 103.53 28.635C103.23 28.6314 102.935 28.7065 102.673 28.8531C102.423 28.9936 102.219 29.2034 102.084 29.4576C101.939 29.7428 101.868 30.0603 101.877 30.3806V35.7365H99.3795Z" fill="#BCF124"/>\n<path d="M110.563 39.4631C110.304 39.4633 110.046 39.4405 109.791 39.3949C109.563 39.3571 109.342 39.2835 109.136 39.1769V37.1128C109.316 37.1628 109.499 37.2017 109.684 37.2293C109.875 37.2621 110.07 37.2791 110.264 37.2801C110.754 37.2801 111.099 37.1562 111.31 36.9282C111.522 36.6884 111.696 36.4162 111.824 36.1217L112.437 34.6945L112.404 36.7932L108.421 26.5697H111.093L113.731 33.8384H112.735L115.373 26.5697H118.048L114.165 36.5925C113.955 37.1702 113.652 37.7089 113.269 38.187C112.942 38.5905 112.531 38.9169 112.066 39.1434C111.594 39.3617 111.081 39.4709 110.563 39.4631Z" fill="#BCF124"/>\n<path d="M7.00861 16.1097H0C0.00583172 11.8399 1.68502 7.74676 4.66939 4.7276C7.65377 1.70844 11.6998 0.00968387 15.9203 0.00378418V7.09408C13.558 7.09801 11.2935 8.04913 9.62308 9.73902C7.95266 11.4289 7.0125 13.7198 7.00861 16.1097Z" fill="#BCF124"/>\n<path d="M15.9243 39.3094C11.7037 39.3035 7.65771 37.6047 4.67333 34.5856C1.68896 31.5664 0.00976849 27.4732 0.00393677 23.2035H7.01255C7.01255 24.9874 7.53543 26.7311 8.51506 28.2144C9.4947 29.6976 10.8871 30.8536 12.5162 31.5362C14.1452 32.2189 15.9378 32.3975 17.6672 32.0495C19.3966 31.7015 20.9852 30.8425 22.2321 29.5811C23.4789 28.3197 24.328 26.7127 24.672 24.9631C25.016 23.2135 24.8394 21.4 24.1647 19.752C23.4899 18.1039 22.3472 16.6953 20.881 15.7042C19.4149 14.7132 17.6912 14.1842 15.9279 14.1842V7.09021C20.1512 7.09021 24.2016 8.78747 27.1879 11.8086C30.1742 14.8297 31.8519 18.9273 31.8519 23.1998C31.8519 27.4723 30.1742 31.5699 27.1879 34.591C24.2016 37.6121 20.1512 39.3094 15.9279 39.3094H15.9243Z" fill="#BCF124"/>\n</svg>\n'.trim();var ba=(t=>(t[t.MANUAL=0]="MANUAL",t[t.AUTO=1]="AUTO",t))(ba||{});class va extends pt{constructor(t,i,n){super(t),e(this,"enabled",!0),e(this,"container"),e(this,"three"),e(this,"mode",1),e(this,"needsUpdate",!1),e(this,"_canvas"),e(this,"_parameters"),e(this,"_resizeObserver",null),e(this,"onContainerUpdated",new at),e(this,"_resizing",!1),e(this,"_logo",null),e(this,"_showLogo",!0),e(this,"resize",(t=>{if(this._resizing)return;this._resizing=!0,this.onContainerUpdated.trigger();const e=t?t.x:this.container.clientWidth,i=t?t.y:this.container.clientHeight;this.three.setSize(e,i),this.onResize.trigger(new o.Vector2(e,i)),this._resizing=!1})),e(this,"resizeEvent",(()=>{this.resize()})),e(this,"onContextLost",(t=>{t.preventDefault(),this.enabled=!1})),e(this,"onContextBack",(()=>{this.three.setRenderTarget(null),this.three.dispose(),this.three=new o.WebGLRenderer({canvas:this._canvas,antialias:!0,alpha:!0,...this._parameters}),this.enabled=!0})),this.container=i,this._parameters=n,this.three=new o.WebGLRenderer({antialias:!0,alpha:!0,...n}),this.three.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.setupRenderer(),this.setupEvents(!0),this.resize(),this._canvas=this.three.domElement;const s=this.three.getContext(),{canvas:r}=s;r.addEventListener("webglcontextlost",this.onContextLost,!1),r.addEventListener("webglcontextrestored",this.onContextBack,!1)}get showLogo(){return this._showLogo}set showLogo(t){this._showLogo=t,this._logo&&(this._logo.style.display=t?"":"none")}get logo(){return this._logo}update(){if(!this.enabled||!this.currentWorld)return;if(0===this.mode&&!this.needsUpdate)return;this.needsUpdate=!1,this.onBeforeUpdate.trigger(this);const t=this.currentWorld.scene.three,e=this.currentWorld.camera.three;this.three.render(t,e),this.onAfterUpdate.trigger(this)}dispose(){this.enabled=!1,this.setupEvents(!1),this.three.domElement.remove(),this._logo&&(this._logo.remove(),this._logo=null),this.three.forceContextLoss(),this.three.dispose(),this.onResize.reset(),this.onAfterUpdate.reset(),this.onBeforeUpdate.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}getSize(){return new o.Vector2(this.three.domElement.clientWidth,this.three.domElement.clientHeight)}setupEvents(t){const e=this.three.domElement.parentElement;if(!e)throw new Error("This renderer needs to have an HTML container!");this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),window.removeEventListener("resize",this.resizeEvent),t&&(this._resizeObserver=new ResizeObserver(this.resizeEvent),this._resizeObserver.observe(e),window.addEventListener("resize",this.resizeEvent))}setupRenderer(){this.three.localClippingEnabled=!0,this.container&&(this.container.appendChild(this.three.domElement),this.setupLogo()),this.onContainerUpdated.trigger()}setupLogo(){if(this._logo||!this.container)return;"static"===window.getComputedStyle(this.container).position&&(this.container.style.position="relative"),this._logo=function(){const t=document.createElement("div");t.setAttribute("data-thatopen-logo",""),t.innerHTML=_a,t.style.cssText=["position: absolute","left: 0.75rem","bottom: 0.75rem","width: 6rem","height: auto","pointer-events: none","user-select: none","opacity: 0.85","z-index: 1"].join("; ");const e=t.firstElementChild;return e&&(e.setAttribute("width","100%"),e.setAttribute("height","100%")),t}(),this._logo.style.display=this._showLogo?"":"none",this.container.appendChild(this._logo)}}class xa extends dt{constructor(t){super(t),e(this,"onBeforeUpdate",new at),e(this,"onAfterUpdate",new at),e(this,"onAspectUpdated",new at),e(this,"onDisposed",new at),e(this,"three"),e(this,"_resizeObserver",null),e(this,"_allControls",new Map),e(this,"updateAspect",(()=>{var t;if(this.currentWorld&&this.currentWorld.renderer)if(this.three instanceof o.OrthographicCamera)this.onAspectUpdated.trigger();else if(null==(t=this.currentWorld.renderer)?void 0:t.isResizeable()){const t=this.currentWorld.renderer.getSize();this.three.aspect=t.width/t.height,this.three.updateProjectionMatrix(),this.onAspectUpdated.trigger()}})),this.three=this.setupCamera(),this.worlds.onItemSet.add((({value:t})=>{const e=this.newCameraControls();this.setupEvents(!0),this._allControls.set(t.uuid,e)})),this.worlds.onBeforeDelete.add((({value:t})=>{var e;const i=this._allControls.get(t.uuid);i&&(i.dispose(),this._allControls.delete(t.uuid)),null==(e=this._resizeObserver)||e.disconnect()}))}get controls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");const t=this._allControls.get(this.currentWorld.uuid);if(!t)throw new Error("Controls not found!");return t}get enabled(){return null!==this.currentWorld&&this.controls.enabled}set enabled(t){null!==this.currentWorld&&(this.controls.enabled=t)}set currentWorld(t){if(super.currentWorld=t,!t)return;this.worlds.get(t.uuid)||this.worlds.set(t.uuid,t)}get currentWorld(){return this._currentWorld}dispose(){this.setupEvents(!1),this.onAspectUpdated.reset(),this.onBeforeUpdate.reset(),this.onAfterUpdate.reset(),this.three.removeFromParent(),this.onDisposed.trigger(),this.onDisposed.reset();for(const[t,e]of this._allControls)e.dispose();this.worlds.clear()}async fitToItems(t){const e=await this.getItemsBounding(t);await this.controls.fitToSphere(e,!0)}async setOrbitToItems(t){const e=await this.getItemsBounding(t);this.controls.setOrbitPoint(e.center.x,e.center.y,e.center.z)}update(t){this.enabled&&(this.onBeforeUpdate.trigger(this),this.controls.update(t),this.onAfterUpdate.trigger(this))}async getItemsBounding(t){const e=this.components.get(fr),i=this.components.get(Lo);i.list.clear();const n=new o.Sphere;if(t)await i.addFromModelIdMap(t);else for(const[,t]of e.list)i.list.add(t.box);return i.get().getBoundingSphere(n),i.list.clear(),n}setupCamera(){const t=window.innerWidth/window.innerHeight,e=new o.PerspectiveCamera(60,t,1,1e3);return e.position.set(50,50,50),e.lookAt(new o.Vector3(0,0,0)),e}newCameraControls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");if(!this.currentWorld.renderer)throw new Error("This camera needs a renderer to work!");rt.install({THREE:xa.getSubsetOfThree()});const{domElement:t}=this.currentWorld.renderer.three,e=new rt(this.three,t);return e.smoothTime=.2,e.dollyToCursor=!0,e.infinityDolly=!0,e.minDistance=6,e}setupEvents(t){if(this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),t){if(!this.currentWorld)throw new Error("This camera needs a world to work!");if(!this.currentWorld.renderer)throw new Error("This camera needs a renderer to work!");const{domElement:t}=this.currentWorld.renderer.three;this._resizeObserver=new ResizeObserver(this.updateAspect),this._resizeObserver.observe(t)}}static getSubsetOfThree(){return{MOUSE:o.MOUSE,Vector2:o.Vector2,Vector3:o.Vector3,Vector4:o.Vector4,Quaternion:o.Quaternion,Matrix4:o.Matrix4,Spherical:o.Spherical,Box3:o.Box3,Sphere:o.Sphere,Raycaster:o.Raycaster,MathUtils:o.MathUtils}}}const Ca=class t extends ht{constructor(i){super(i),e(this,"onAfterUpdate",new at),e(this,"onBeforeUpdate",new at),e(this,"onDisposed",new at),e(this,"list",new n),e(this,"enabled",!0),i.add(t.uuid,this)}create(){const t=new fa(this.components),e=t.uuid;if(this.list.has(e))throw new Error("There is already a world with this name!");return this.list.set(e,t),t}delete(t){if(!this.list.has(t.uuid))throw new Error("The provided world is not found in the list!");this.list.delete(t.uuid),t.dispose()}dispose(){this.enabled=!1;for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}update(t){if(this.enabled)for(const[e,i]of this.list)i.update(t)}};e(Ca,"uuid","fdb61dc4-2ec1-4966-b83d-54ea795fad4a");let Sa=Ca;class Aa extends ui{constructor(){super(...arguments),e(this,"_config",{visible:{value:!0,type:"Boolean"},color:{value:new o.Color,type:"Color"},primarySize:{type:"Number",interpolable:!0,value:1,min:0,max:1e3},secondarySize:{type:"Number",interpolable:!0,value:10,min:0,max:1e3},distance:{type:"Number",interpolable:!0,value:500,min:0,max:500}})}get visible(){return this._config.visible.value}set visible(t){this._config.visible.value=t,this._component.visible=t}get color(){return this._config.color.value}set color(t){this._config.color.value=t,this._component.material.uniforms.uColor.value=t,this._component.material.uniformsNeedUpdate=!0}get primarySize(){return this._config.primarySize.value}set primarySize(t){this._config.primarySize.value=t,this._component.material.uniforms.uSize1.value=t,this._component.material.uniformsNeedUpdate=!0}get secondarySize(){return this._config.secondarySize.value}set secondarySize(t){this._config.secondarySize.value=t,this._component.material.uniforms.uSize2.value=t,this._component.material.uniformsNeedUpdate=!0}get distance(){return this._config.distance.value}set distance(t){this._config.distance.value=t,this._component.material.uniforms.uDistance.value=t,this._component.material.uniformsNeedUpdate=!0}}class Pa{constructor(t,i){e(this,"onDisposed",new at),e(this,"onSetup",new at),e(this,"isSetup",!1),e(this,"world"),e(this,"components"),e(this,"config"),e(this,"_defaultConfig",{visible:!0,color:new o.Color(12303291),primarySize:1,secondarySize:10,distance:500}),e(this,"three"),e(this,"_fade",3),e(this,"updateZoom",(()=>{this.world.camera instanceof xa&&(this.material.uniforms.uZoom.value=this.world.camera.three.zoom)})),this.world=i;const{color:n,primarySize:s,secondarySize:r,distance:a}=this._defaultConfig;this.components=t,this.config=new Aa(this,this.components,"Grid");const l=new o.PlaneGeometry(2,2,1,1),c=new o.ShaderMaterial({side:o.DoubleSide,uniforms:{uSize1:{value:s},uSize2:{value:r},uColor:{value:n},uDistance:{value:a},uFade:{value:this._fade},uZoom:{value:1}},transparent:!0,vertexShader:"\n \n varying vec3 worldPosition;\n \n uniform float uDistance;\n \n void main() {\n \n vec3 pos = position.xzy * uDistance;\n pos.xz += cameraPosition.xz;\n \n worldPosition = pos;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);\n \n }\n ",fragmentShader:"\n \n varying vec3 worldPosition;\n \n uniform float uZoom;\n uniform float uFade;\n uniform float uSize1;\n uniform float uSize2;\n uniform vec3 uColor;\n uniform float uDistance;\n \n \n \n float getGrid(float size) {\n \n vec2 r = worldPosition.xz / size;\n \n \n vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);\n float line = min(grid.x, grid.y);\n \n \n return 1.0 - min(line, 1.0);\n }\n \n void main() {\n \n \n float d = 1.0 - min(distance(cameraPosition.xz, worldPosition.xz) / uDistance, 1.0);\n \n float g1 = getGrid(uSize1);\n float g2 = getGrid(uSize2);\n \n // Ortho camera fades the grid away when zooming out\n float minZoom = step(0.2, uZoom);\n float zoomFactor = pow(min(uZoom, 1.), 2.) * minZoom;\n \n gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, uFade));\n gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2) * zoomFactor;\n \n if ( gl_FragColor.a <= 0.0 ) discard;\n \n \n }\n \n ",extensions:{derivatives:!0}});this.three=new o.Mesh(l,c),this.three.frustumCulled=!1,i.scene.three.add(this.three),this.setupEvents(!0)}get visible(){return this.three.visible}set visible(t){if(this.three.visible=t,t){this.world.scene.three.add(this.three)}else this.three.removeFromParent()}get material(){return this.three.material}get fade(){return 3===this._fade}set fade(t){this._fade=t?3:0,this.material.uniforms.uFade.value=this._fade}setup(t){const e={...this._defaultConfig,...t};this.config.visible=!0,this.config.color=e.color,this.config.primarySize=e.primarySize,this.config.secondarySize=e.secondarySize,this.config.distance=e.distance,this.isSetup=!0,this.onSetup.trigger()}dispose(){this.setupEvents(!1);this.components.get(pi).list.delete(this.config.uuid);this.components.get(mt).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset(),this.world=null,this.components=null}setupEvents(t){if(this.world.isDisposing)return;if(!(this.world.camera instanceof xa))return;const e=this.world.camera.controls;t?e.addEventListener("update",this.updateZoom):e.removeEventListener("update",this.updateZoom)}}const Ta=class t extends ht{constructor(i){super(i),e(this,"list",new Map),e(this,"onDisposed",new at),e(this,"enabled",!0),i.add(t.uuid,this)}create(t){if(this.list.has(t.uuid))throw new Error("This world already has a grid!");const e=new Pa(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add((()=>{this.delete(t)})),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};e(Ta,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");let Ea=Ta;const Ma=class t{constructor(){e(this,"onDisposed",new at),e(this,"list",new n),e(this,"enabled",!1),e(this,"_timer"),e(this,"onInit",new at),e(this,"update",(()=>{if(!this.enabled)return;this._timer.update();const t=this._timer.getDelta();for(const[e,i]of this.list)i.enabled&&i.isUpdateable()&&i.update(t);requestAnimationFrame(this.update)})),this._timer=new o.Timer,t.setupBVH()}add(t,e){if(this.list.has(t))throw new Error("You're trying to add a component that already exists in the components instance. Use Components.get() instead.");_t.validate(t),this.list.set(t,e)}get(t){var e;const i=t.uuid;if(!this.list.has(i)){const n=new t(this);return(null==(e=n.isDisposeable)?void 0:e.call(n))&&n.onDisposed.add((()=>this.list.delete(i))),this.list.has(i)||this.add(i,n),n}return this.list.get(i)}init(){this.enabled=!0;for(const[t,e]of this.list.entries())e.enabled=!0;this._timer.reset(),this.update(),this.onInit.trigger()}dispose(){let t;this.enabled=!1;for(const[e,i]of this.list)i.enabled=!1,e!==fr.uuid?i.isDisposeable()&&i.dispose():t=i;null==t||t.dispose(),this._timer.dispose(),this.onDisposed.trigger()}static setupBVH(){o.BufferGeometry.prototype.computeBoundsTree=ur,o.BufferGeometry.prototype.disposeBoundsTree=dr,o.Mesh.prototype.raycast=cr,o.LineSegments.prototype.raycast=cr}};e(Ma,"release","2.4.3");let Ia=Ma;class za{constructor(t){e(this,"enabled",!1),e(this,"id","FirstPerson"),this.camera=t}set(t){if(this.enabled=t,t){if("Perspective"!==this.camera.projection.current)return void this.camera.set("Orbit");this.setupFirstPersonCamera()}}setupFirstPersonCamera(){const t=this.camera.controls,e=new o.Vector3;t.distance--,t.getPosition(e),t.minDistance=1,t.maxDistance=1,t.distance=1,t.moveTo(e.x,e.y,e.z),t.truckSpeed=50,t.mouseButtons.wheel=rt.ACTION.DOLLY,t.touches.two=rt.ACTION.TOUCH_ZOOM_TRUCK}}class Da{constructor(t){e(this,"enabled",!0),e(this,"id","Orbit"),this.camera=t,this.activateOrbitControls()}set(t){this.enabled=t,t&&this.activateOrbitControls()}activateOrbitControls(){const t=this.camera.controls;t.minDistance=1,t.maxDistance=300;const e=new o.Vector3;t.getPosition(e);const i=e.length();t.distance=i,t.truckSpeed=2;const{rotation:n}=this.camera.three,s=new o.Vector3(0,0,-1).applyEuler(n),r=e.addScaledVector(s,i);t.moveTo(r.x,r.y,r.z)}}class ka{constructor(t){e(this,"enabled",!1),e(this,"id","Plan"),e(this,"mouseAction1"),e(this,"mouseAction2"),e(this,"mouseInitialized",!1),e(this,"defaultAzimuthSpeed"),e(this,"defaultPolarSpeed"),this.camera=t,this.defaultAzimuthSpeed=t.controls.azimuthRotateSpeed,this.defaultPolarSpeed=t.controls.polarRotateSpeed}set(t){this.enabled=t;const e=this.camera.controls;e.azimuthRotateSpeed=t?0:this.defaultAzimuthSpeed,e.polarRotateSpeed=t?0:this.defaultPolarSpeed,this.mouseInitialized||(this.mouseAction1=e.touches.one,this.mouseAction2=e.touches.two,this.mouseInitialized=!0),t?(e.mouseButtons.left=rt.ACTION.TRUCK,e.touches.one=rt.ACTION.TOUCH_TRUCK,e.touches.two=rt.ACTION.TOUCH_ZOOM):(e.mouseButtons.left=rt.ACTION.ROTATE,e.touches.one=this.mouseAction1,e.touches.two=this.mouseAction2)}}class Ba{constructor(t){e(this,"onChanged",new at),e(this,"current","Perspective"),e(this,"camera"),e(this,"matchOrthoDistanceEnabled",!1),e(this,"_component"),e(this,"_previousDistance",-1),this._component=t,this.camera=t.three}async set(t){this.current!==t&&("Orthographic"===t?this.setOrthoCamera():await this.setPerspectiveCamera(),this.onChanged.trigger(this.camera))}async toggle(){const t="Perspective"===this.current?"Orthographic":"Perspective";await this.set(t)}setOrthoCamera(){if(null===this._component.mode)return;if("FirstPerson"===this._component.mode.id)return;this._previousDistance=this._component.controls.distance,this._component.controls.distance=200;const t=this.getPerspectiveDims();if(!t)return;const{width:e,height:i}=t;this.setupOrthoCamera(i,e),this.camera=this._component.threeOrtho,this.current="Orthographic"}getPerspectiveDims(){const t=this._component.currentWorld;if(!t||!t.renderer)return null;const e=new o.Vector3;this._component.threePersp.getWorldDirection(e);const i=new o.Vector3;this._component.controls.getTarget(i);const n=i.clone().sub(this._component.threePersp.position).dot(e),s=t.renderer.getSize(),r=s.x/s.y,a=this._component.threePersp,l=2*n*Math.atan(a.fov*(Math.PI/180)/2);return{width:l*r,height:l}}setupOrthoCamera(t,e){this._component.controls.mouseButtons.wheel=rt.ACTION.ZOOM,this._component.controls.mouseButtons.middle=rt.ACTION.ZOOM;const i=this._component.threePersp,n=this._component.threeOrtho;n.zoom=1,n.left=e/-2,n.right=e/2,n.top=t/2,n.bottom=t/-2,n.updateProjectionMatrix(),n.position.copy(i.position),n.quaternion.copy(i.quaternion),this._component.controls.camera=n}getDistance(){const t=this._component.threePersp,e=this._component.threeOrtho;return(e.top-e.bottom)/e.zoom/(2*Math.atan(t.fov*(Math.PI/180)/2))}async setPerspectiveCamera(){this._component.controls.mouseButtons.wheel=rt.ACTION.DOLLY,this._component.controls.mouseButtons.middle=rt.ACTION.DOLLY;const t=this._component.threePersp,e=this._component.threeOrtho;t.position.copy(e.position),t.quaternion.copy(e.quaternion),this._component.controls.mouseButtons.wheel=rt.ACTION.DOLLY,this.matchOrthoDistanceEnabled?this._component.controls.distance=this.getDistance():this._component.controls.distance=this._previousDistance,await this._component.controls.zoomTo(1),t.updateProjectionMatrix(),this._component.controls.camera=t,this.camera=t,this.current="Perspective"}}class Oa extends xa{constructor(t){super(t),e(this,"projection"),e(this,"threeOrtho"),e(this,"threePersp"),e(this,"_userInputButtons",{}),e(this,"_frustumSize",50),e(this,"_navigationModes",new Map),e(this,"_mode",null),e(this,"previousSize",null),this.threePersp=this.three,this.threeOrtho=this.newOrthoCamera(),this.projection=new Ba(this),this.onAspectUpdated.add((()=>{this.setOrthoPerspCameraAspect()})),this.projection.onChanged.add((t=>{this.three=t,this.updateAspect()})),this.worlds.onItemSet.add((()=>{this._navigationModes.clear(),this._navigationModes.set("Orbit",new Da(this)),this._navigationModes.set("FirstPerson",new za(this)),this._navigationModes.set("Plan",new ka(this)),this._mode=this._navigationModes.get("Orbit"),this.mode.set(!0,{preventTargetAdjustment:!0}),this.currentWorld&&this.currentWorld.renderer&&(this.previousSize=this.currentWorld.renderer.getSize().clone())})),this.worlds.onItemDeleted.add((()=>{this._navigationModes.clear()}))}get mode(){if(!this._mode)throw new Error("Mode not found, camera not initialized");return this._mode}dispose(){super.dispose(),this.threeOrtho.removeFromParent()}set(t){if(null!==this.mode&&this.mode.id!==t){if(this.mode.set(!1),!this._navigationModes.has(t))throw new Error("The specified mode does not exist!");this._mode=this._navigationModes.get(t),this.mode.set(!0)}}async fit(t,e=1.5){if(!this.enabled)return;const i=Number.MAX_VALUE,n=Number.MIN_VALUE,s=new o.Vector3(i,i,i),r=new o.Vector3(n,n,n);for(const e of t){const t=(new o.Box3).setFromObject(e);t.min.x<s.x&&(s.x=t.min.x),t.min.y<s.y&&(s.y=t.min.y),t.min.z<s.z&&(s.z=t.min.z),t.max.x>r.x&&(r.x=t.max.x),t.max.y>r.y&&(r.y=t.max.y),t.max.z>r.z&&(r.z=t.max.z)}const a=new o.Box3(s,r),l=this.components.get(fr);if(l.initialized)for(const[,t]of l.list){const e=t.box;e.min.x<s.x&&(s.x=e.min.x),e.min.y<s.y&&(s.y=e.min.y),e.min.z<s.z&&(s.z=e.min.z),e.max.x>r.x&&(r.x=e.max.x),e.max.y>r.y&&(r.y=e.max.y),e.max.z>r.z&&(r.z=e.max.z)}const c=new o.Vector3;a.getSize(c);const h=new o.Vector3;a.getCenter(h);const u=Math.max(c.x,c.y,c.z)*e,d=new o.Sphere(h,u);await this.controls.fitToSphere(d,!0)}setUserInput(t){t?this.enableUserInput():this.disableUserInput()}addCustomNavigationMode(t){this._navigationModes.set(t.id,t)}disableUserInput(){this._userInputButtons.left=this.controls.mouseButtons.left,this._userInputButtons.right=this.controls.mouseButtons.right,this._userInputButtons.middle=this.controls.mouseButtons.middle,this._userInputButtons.wheel=this.controls.mouseButtons.wheel,this.controls.mouseButtons.left=0,this.controls.mouseButtons.right=0,this.controls.mouseButtons.middle=0,this.controls.mouseButtons.wheel=0}enableUserInput(){0!==Object.keys(this._userInputButtons).length&&(this.controls.mouseButtons.left=this._userInputButtons.left,this.controls.mouseButtons.right=this._userInputButtons.right,this.controls.mouseButtons.middle=this._userInputButtons.middle,this.controls.mouseButtons.wheel=this._userInputButtons.wheel)}newOrthoCamera(){const t=window.innerWidth/window.innerHeight;return new o.OrthographicCamera(this._frustumSize*t/-2,this._frustumSize*t/2,this._frustumSize/2,this._frustumSize/-2,.1,1e3)}setOrthoPerspCameraAspect(){if(!this.currentWorld||!this.currentWorld.renderer)return;if(!this.previousSize)return;const t=this.currentWorld.renderer.getSize(),e=this.threeOrtho.top,i=this.threeOrtho.right,n=e*(t.y/this.previousSize.y),s=i*(t.x/this.previousSize.x);this.threeOrtho.left=-s,this.threeOrtho.right=s,this.threeOrtho.top=n,this.threeOrtho.bottom=-n,this.threeOrtho.updateProjectionMatrix(),this.previousSize.copy(t)}}var Na="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Va(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function La(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Fa={exports:{}};
2
2
  /*!
3
3
 
4
4
  JSZip v3.10.1 - A JavaScript class for generating and reading zip files
@@ -9,4 +9,4 @@ Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/js
9
9
 
10
10
  JSZip uses the library pako released under the MIT license :
11
11
  https://github.com/nodeca/pako/blob/main/LICENSE
12
- */const Ko=Zo(Xo.exports=function t(e,i,n){function s(o,a){if(!i[o]){if(!e[o]){if(!a&&Yo)return Yo(o);if(r)return r(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var c=i[o]={exports:{}};e[o][0].call(c.exports,function(t){return s(e[o][1][t]||t)},c,c.exports,t,e,i,n)}return i[o].exports}for(var r=Yo,o=0;o<n.length;o++)s(n[o]);return s}({1:[function(t,e,i){var n=t("./utils"),s=t("./support"),r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(t){for(var e,i,s,o,a,l,c,h=[],d=0,u=t.length,p=u,f="string"!==n.getTypeOf(t);d<t.length;)p=u-d,s=f?(e=t[d++],i=d<u?t[d++]:0,d<u?t[d++]:0):(e=t.charCodeAt(d++),i=d<u?t.charCodeAt(d++):0,d<u?t.charCodeAt(d++):0),o=e>>2,a=(3&e)<<4|i>>4,l=1<p?(15&i)<<2|s>>6:64,c=2<p?63&s:64,h.push(r.charAt(o)+r.charAt(a)+r.charAt(l)+r.charAt(c));return h.join("")},i.decode=function(t){var e,i,n,o,a,l,c=0,h=0,d="data:";if(t.substr(0,d.length)===d)throw new Error("Invalid base64 input, it looks like a data url.");var u,p=3*(t=t.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(t.charAt(t.length-1)===r.charAt(64)&&p--,t.charAt(t.length-2)===r.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(u=s.uint8array?new Uint8Array(0|p):new Array(0|p);c<t.length;)e=r.indexOf(t.charAt(c++))<<2|(o=r.indexOf(t.charAt(c++)))>>4,i=(15&o)<<4|(a=r.indexOf(t.charAt(c++)))>>2,n=(3&a)<<6|(l=r.indexOf(t.charAt(c++))),u[h++]=e,64!==a&&(u[h++]=i),64!==l&&(u[h++]=n);return u}},{"./support":30,"./utils":32}],2:[function(t,e,i){var n=t("./external"),s=t("./stream/DataWorker"),r=t("./stream/Crc32Probe"),o=t("./stream/DataLengthProbe");function a(t,e,i,n,s){this.compressedSize=t,this.uncompressedSize=e,this.crc32=i,this.compression=n,this.compressedContent=s}a.prototype={getContentWorker:function(){var t=new s(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o("data_length")),e=this;return t.on("end",function(){if(this.streamInfo.data_length!==e.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),t},getCompressedWorker:function(){return new s(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(t,e,i){return t.pipe(new r).pipe(new o("uncompressedSize")).pipe(e.compressWorker(i)).pipe(new o("compressedSize")).withStreamInfo("compression",e)},e.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,e,i){var n=t("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new n("STORE compression")},uncompressWorker:function(){return new n("STORE decompression")}},i.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,e,i){var n=t("./utils"),s=function(){for(var t,e=[],i=0;i<256;i++){t=i;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e}();e.exports=function(t,e){return void 0!==t&&t.length?"string"!==n.getTypeOf(t)?function(t,e,i,n){var r=s,o=n+i;t^=-1;for(var a=n;a<o;a++)t=t>>>8^r[255&(t^e[a])];return-1^t}(0|e,t,t.length,0):function(t,e,i,n){var r=s,o=n+i;t^=-1;for(var a=n;a<o;a++)t=t>>>8^r[255&(t^e.charCodeAt(a))];return-1^t}(0|e,t,t.length,0):0}},{"./utils":32}],5:[function(t,e,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(t,e,i){var n=null;n="undefined"!=typeof Promise?Promise:t("lie"),e.exports={Promise:n}},{lie:37}],7:[function(t,e,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,s=t("pako"),r=t("./utils"),o=t("./stream/GenericWorker"),a=n?"uint8array":"array";function l(t,e){o.call(this,"FlateWorker/"+t),this._pako=null,this._pakoAction=t,this._pakoOptions=e,this.meta={}}i.magic="\b\0",r.inherits(l,o),l.prototype.processChunk=function(t){this.meta=t.meta,null===this._pako&&this._createPako(),this._pako.push(r.transformTo(a,t.data),!1)},l.prototype.flush=function(){o.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},l.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this._pako=null},l.prototype._createPako=function(){this._pako=new s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var t=this;this._pako.onData=function(e){t.push({data:e,meta:t.meta})}},i.compressWorker=function(t){return new l("Deflate",t)},i.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(t,e,i){function n(t,e){var i,n="";for(i=0;i<e;i++)n+=String.fromCharCode(255&t),t>>>=8;return n}function s(t,e,i,s,o,h){var d,u,p=t.file,f=t.compression,m=h!==a.utf8encode,g=r.transformTo("string",h(p.name)),w=r.transformTo("string",a.utf8encode(p.name)),y=p.comment,_=r.transformTo("string",h(y)),b=r.transformTo("string",a.utf8encode(y)),v=w.length!==p.name.length,x=b.length!==y.length,S="",T="",C="",A=p.dir,E=p.date,M={crc32:0,compressedSize:0,uncompressedSize:0};e&&!i||(M.crc32=t.crc32,M.compressedSize=t.compressedSize,M.uncompressedSize=t.uncompressedSize);var P=0;e&&(P|=8),m||!v&&!x||(P|=2048);var z,I,D,k=0,B=0;A&&(k|=16),"UNIX"===o?(B=798,k|=(z=p.unixPermissions,I=A,D=z,z||(D=I?16893:33204),(65535&D)<<16)):(B=20,k|=function(t){return 63&(t||0)}(p.dosPermissions)),d=E.getUTCHours(),d<<=6,d|=E.getUTCMinutes(),d<<=5,d|=E.getUTCSeconds()/2,u=E.getUTCFullYear()-1980,u<<=4,u|=E.getUTCMonth()+1,u<<=5,u|=E.getUTCDate(),v&&(T=n(1,1)+n(l(g),4)+w,S+="up"+n(T.length,2)+T),x&&(C=n(1,1)+n(l(_),4)+b,S+="uc"+n(C.length,2)+C);var O="";return O+="\n\0",O+=n(P,2),O+=f.magic,O+=n(d,2),O+=n(u,2),O+=n(M.crc32,4),O+=n(M.compressedSize,4),O+=n(M.uncompressedSize,4),O+=n(g.length,2),O+=n(S.length,2),{fileRecord:c.LOCAL_FILE_HEADER+O+g+S,dirRecord:c.CENTRAL_FILE_HEADER+n(B,2)+O+n(_.length,2)+"\0\0\0\0"+n(k,4)+n(s,4)+g+S+_}}var r=t("../utils"),o=t("../stream/GenericWorker"),a=t("../utf8"),l=t("../crc32"),c=t("../signature");function h(t,e,i,n){o.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=e,this.zipPlatform=i,this.encodeFileName=n,this.streamFiles=t,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}r.inherits(h,o),h.prototype.push=function(t){var e=t.meta.percent||0,i=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(t):(this.bytesWritten+=t.data.length,o.prototype.push.call(this,{data:t.data,meta:{currentFile:this.currentFile,percent:i?(e+100*(i-n-1))/i:100}}))},h.prototype.openedSource=function(t){this.currentSourceOffset=this.bytesWritten,this.currentFile=t.file.name;var e=this.streamFiles&&!t.file.dir;if(e){var i=s(t,e,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0},h.prototype.closedSource=function(t){this.accumulate=!1;var e,i=this.streamFiles&&!t.file.dir,r=s(t,i,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),i)this.push({data:(e=t,c.DATA_DESCRIPTOR+n(e.crc32,4)+n(e.compressedSize,4)+n(e.uncompressedSize,4)),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},h.prototype.flush=function(){for(var t=this.bytesWritten,e=0;e<this.dirRecords.length;e++)this.push({data:this.dirRecords[e],meta:{percent:100}});var i,s,o,a,l,h,d=this.bytesWritten-t,u=(i=this.dirRecords.length,s=d,o=t,a=this.zipComment,l=this.encodeFileName,h=r.transformTo("string",l(a)),c.CENTRAL_DIRECTORY_END+"\0\0\0\0"+n(i,2)+n(i,2)+n(s,4)+n(o,4)+n(h.length,2)+h);this.push({data:u,meta:{percent:100}})},h.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},h.prototype.registerPrevious=function(t){this._sources.push(t);var e=this;return t.on("data",function(t){e.processChunk(t)}),t.on("end",function(){e.closedSource(e.previous.streamInfo),e._sources.length?e.prepareNextSource():e.end()}),t.on("error",function(t){e.error(t)}),this},h.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},h.prototype.error=function(t){var e=this._sources;if(!o.prototype.error.call(this,t))return!1;for(var i=0;i<e.length;i++)try{e[i].error(t)}catch(t){}return!0},h.prototype.lock=function(){o.prototype.lock.call(this);for(var t=this._sources,e=0;e<t.length;e++)t[e].lock()},e.exports=h},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(t,e,i){var n=t("../compressions"),s=t("./ZipFileWorker");i.generateWorker=function(t,e,i){var r=new s(e.streamFiles,i,e.platform,e.encodeFileName),o=0;try{t.forEach(function(t,i){o++;var s=function(t,e){var i=t||e,s=n[i];if(!s)throw new Error(i+" is not a valid compression method !");return s}(i.options.compression,e.compression),a=i.options.compressionOptions||e.compressionOptions||{},l=i.dir,c=i.date;i._compressWorker(s,a).withStreamInfo("file",{name:t,dir:l,date:c,comment:i.comment||"",unixPermissions:i.unixPermissions,dosPermissions:i.dosPermissions}).pipe(r)}),r.entriesCount=o}catch(t){r.error(t)}return r}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(t,e,i){function n(){if(!(this instanceof n))return new n;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var t=new n;for(var e in this)"function"!=typeof this[e]&&(t[e]=this[e]);return t}}(n.prototype=t("./object")).loadAsync=t("./load"),n.support=t("./support"),n.defaults=t("./defaults"),n.version="3.10.1",n.loadAsync=function(t,e){return(new n).loadAsync(t,e)},n.external=t("./external"),e.exports=n},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(t,e,i){var n=t("./utils"),s=t("./external"),r=t("./utf8"),o=t("./zipEntries"),a=t("./stream/Crc32Probe"),l=t("./nodejsUtils");function c(t){return new s.Promise(function(e,i){var n=t.decompressed.getContentWorker().pipe(new a);n.on("error",function(t){i(t)}).on("end",function(){n.streamInfo.crc32!==t.decompressed.crc32?i(new Error("Corrupted zip : CRC32 mismatch")):e()}).resume()})}e.exports=function(t,e){var i=this;return e=n.extend(e||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:r.utf8decode}),l.isNode&&l.isStream(t)?s.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):n.prepareContent("the loaded zip file",t,!0,e.optimizedBinaryString,e.base64).then(function(t){var i=new o(e);return i.load(t),i}).then(function(t){var i=[s.Promise.resolve(t)],n=t.files;if(e.checkCRC32)for(var r=0;r<n.length;r++)i.push(c(n[r]));return s.Promise.all(i)}).then(function(t){for(var s=t.shift(),r=s.files,o=0;o<r.length;o++){var a=r[o],l=a.fileNameStr,c=n.resolve(a.fileNameStr);i.file(c,a.decompressed,{binary:!0,optimizedBinaryString:!0,date:a.date,dir:a.dir,comment:a.fileCommentStr.length?a.fileCommentStr:null,unixPermissions:a.unixPermissions,dosPermissions:a.dosPermissions,createFolders:e.createFolders}),a.dir||(i.file(c).unsafeOriginalName=l)}return s.zipComment.length&&(i.comment=s.zipComment),i})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(t,e,i){var n=t("../utils"),s=t("../stream/GenericWorker");function r(t,e){s.call(this,"Nodejs stream input adapter for "+t),this._upstreamEnded=!1,this._bindStream(e)}n.inherits(r,s),r.prototype._bindStream=function(t){var e=this;(this._stream=t).pause(),t.on("data",function(t){e.push({data:t,meta:{percent:0}})}).on("error",function(t){e.isPaused?this.generatedError=t:e.error(t)}).on("end",function(){e.isPaused?e._upstreamEnded=!0:e.end()})},r.prototype.pause=function(){return!!s.prototype.pause.call(this)&&(this._stream.pause(),!0)},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},e.exports=r},{"../stream/GenericWorker":28,"../utils":32}],13:[function(t,e,i){var n=t("readable-stream").Readable;function s(t,e,i){n.call(this,e),this._helper=t;var s=this;t.on("data",function(t,e){s.push(t)||s._helper.pause(),i&&i(e)}).on("error",function(t){s.emit("error",t)}).on("end",function(){s.push(null)})}t("../utils").inherits(s,n),s.prototype._read=function(){this._helper.resume()},e.exports=s},{"../utils":32,"readable-stream":16}],14:[function(t,e,i){e.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(t,e){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(t,e);if("number"==typeof t)throw new Error('The "data" argument must not be a number');return new Buffer(t,e)},allocBuffer:function(t){if(Buffer.alloc)return Buffer.alloc(t);var e=new Buffer(t);return e.fill(0),e},isBuffer:function(t){return Buffer.isBuffer(t)},isStream:function(t){return t&&"function"==typeof t.on&&"function"==typeof t.pause&&"function"==typeof t.resume}}},{}],15:[function(t,e,i){function n(t,e,i){var n,s=r.getTypeOf(e),a=r.extend(i||{},l);a.date=a.date||new Date,null!==a.compression&&(a.compression=a.compression.toUpperCase()),"string"==typeof a.unixPermissions&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&16384&a.unixPermissions&&(a.dir=!0),a.dosPermissions&&16&a.dosPermissions&&(a.dir=!0),a.dir&&(t=m(t)),a.createFolders&&(n=f(t))&&g.call(this,n,!0);var d="string"===s&&!1===a.binary&&!1===a.base64;i&&void 0!==i.binary||(a.binary=!d),(e instanceof c&&0===e.uncompressedSize||a.dir||!e||0===e.length)&&(a.base64=!1,a.binary=!0,e="",a.compression="STORE",s="string");var w=null;w=e instanceof c||e instanceof o?e:u.isNode&&u.isStream(e)?new p(t,e):r.prepareContent(t,e,a.binary,a.optimizedBinaryString,a.base64);var y=new h(t,w,a);this.files[t]=y}var s=t("./utf8"),r=t("./utils"),o=t("./stream/GenericWorker"),a=t("./stream/StreamHelper"),l=t("./defaults"),c=t("./compressedObject"),h=t("./zipObject"),d=t("./generate"),u=t("./nodejsUtils"),p=t("./nodejs/NodejsStreamInputAdapter"),f=function(t){"/"===t.slice(-1)&&(t=t.substring(0,t.length-1));var e=t.lastIndexOf("/");return 0<e?t.substring(0,e):""},m=function(t){return"/"!==t.slice(-1)&&(t+="/"),t},g=function(t,e){return e=void 0!==e?e:l.createFolders,t=m(t),this.files[t]||n.call(this,t,null,{dir:!0,createFolders:e}),this.files[t]};function w(t){return"[object RegExp]"===Object.prototype.toString.call(t)}var y={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(t){var e,i,n;for(e in this.files)n=this.files[e],(i=e.slice(this.root.length,e.length))&&e.slice(0,this.root.length)===this.root&&t(i,n)},filter:function(t){var e=[];return this.forEach(function(i,n){t(i,n)&&e.push(n)}),e},file:function(t,e,i){if(1!==arguments.length)return t=this.root+t,n.call(this,t,e,i),this;if(w(t)){var s=t;return this.filter(function(t,e){return!e.dir&&s.test(t)})}var r=this.files[this.root+t];return r&&!r.dir?r:null},folder:function(t){if(!t)return this;if(w(t))return this.filter(function(e,i){return i.dir&&t.test(e)});var e=this.root+t,i=g.call(this,e),n=this.clone();return n.root=i.name,n},remove:function(t){t=this.root+t;var e=this.files[t];if(e||("/"!==t.slice(-1)&&(t+="/"),e=this.files[t]),e&&!e.dir)delete this.files[t];else for(var i=this.filter(function(e,i){return i.name.slice(0,t.length)===t}),n=0;n<i.length;n++)delete this.files[i[n].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(t){var e,i={};try{if((i=r.extend(t||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:s.utf8encode})).type=i.type.toLowerCase(),i.compression=i.compression.toUpperCase(),"binarystring"===i.type&&(i.type="string"),!i.type)throw new Error("No output type specified.");r.checkSupport(i.type),"darwin"!==i.platform&&"freebsd"!==i.platform&&"linux"!==i.platform&&"sunos"!==i.platform||(i.platform="UNIX"),"win32"===i.platform&&(i.platform="DOS");var n=i.comment||this.comment||"";e=d.generateWorker(this,i,n)}catch(t){(e=new o("error")).error(t)}return new a(e,i.type||"string",i.mimeType)},generateAsync:function(t,e){return this.generateInternalStream(t).accumulate(e)},generateNodeStream:function(t,e){return(t=t||{}).type||(t.type="nodebuffer"),this.generateInternalStream(t).toNodejsStream(e)}};e.exports=y},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(t,e,i){e.exports=t("stream")},{stream:void 0}],17:[function(t,e,i){var n=t("./DataReader");function s(t){n.call(this,t);for(var e=0;e<this.data.length;e++)t[e]=255&t[e]}t("../utils").inherits(s,n),s.prototype.byteAt=function(t){return this.data[this.zero+t]},s.prototype.lastIndexOfSignature=function(t){for(var e=t.charCodeAt(0),i=t.charCodeAt(1),n=t.charCodeAt(2),s=t.charCodeAt(3),r=this.length-4;0<=r;--r)if(this.data[r]===e&&this.data[r+1]===i&&this.data[r+2]===n&&this.data[r+3]===s)return r-this.zero;return-1},s.prototype.readAndCheckSignature=function(t){var e=t.charCodeAt(0),i=t.charCodeAt(1),n=t.charCodeAt(2),s=t.charCodeAt(3),r=this.readData(4);return e===r[0]&&i===r[1]&&n===r[2]&&s===r[3]},s.prototype.readData=function(t){if(this.checkOffset(t),0===t)return[];var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=s},{"../utils":32,"./DataReader":18}],18:[function(t,e,i){var n=t("../utils");function s(t){this.data=t,this.length=t.length,this.index=0,this.zero=0}s.prototype={checkOffset:function(t){this.checkIndex(this.index+t)},checkIndex:function(t){if(this.length<this.zero+t||t<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+t+"). Corrupted zip ?")},setIndex:function(t){this.checkIndex(t),this.index=t},skip:function(t){this.setIndex(this.index+t)},byteAt:function(){},readInt:function(t){var e,i=0;for(this.checkOffset(t),e=this.index+t-1;e>=this.index;e--)i=(i<<8)+this.byteAt(e);return this.index+=t,i},readString:function(t){return n.transformTo("string",this.readData(t))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var t=this.readInt(4);return new Date(Date.UTC(1980+(t>>25&127),(t>>21&15)-1,t>>16&31,t>>11&31,t>>5&63,(31&t)<<1))}},e.exports=s},{"../utils":32}],19:[function(t,e,i){var n=t("./Uint8ArrayReader");function s(t){n.call(this,t)}t("../utils").inherits(s,n),s.prototype.readData=function(t){this.checkOffset(t);var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=s},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(t,e,i){var n=t("./DataReader");function s(t){n.call(this,t)}t("../utils").inherits(s,n),s.prototype.byteAt=function(t){return this.data.charCodeAt(this.zero+t)},s.prototype.lastIndexOfSignature=function(t){return this.data.lastIndexOf(t)-this.zero},s.prototype.readAndCheckSignature=function(t){return t===this.readData(4)},s.prototype.readData=function(t){this.checkOffset(t);var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=s},{"../utils":32,"./DataReader":18}],21:[function(t,e,i){var n=t("./ArrayReader");function s(t){n.call(this,t)}t("../utils").inherits(s,n),s.prototype.readData=function(t){if(this.checkOffset(t),0===t)return new Uint8Array(0);var e=this.data.subarray(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=s},{"../utils":32,"./ArrayReader":17}],22:[function(t,e,i){var n=t("../utils"),s=t("../support"),r=t("./ArrayReader"),o=t("./StringReader"),a=t("./NodeBufferReader"),l=t("./Uint8ArrayReader");e.exports=function(t){var e=n.getTypeOf(t);return n.checkSupport(e),"string"!==e||s.uint8array?"nodebuffer"===e?new a(t):s.uint8array?new l(n.transformTo("uint8array",t)):new r(n.transformTo("array",t)):new o(t)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(t,e,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\b"},{}],24:[function(t,e,i){var n=t("./GenericWorker"),s=t("../utils");function r(t){n.call(this,"ConvertWorker to "+t),this.destType=t}s.inherits(r,n),r.prototype.processChunk=function(t){this.push({data:s.transformTo(this.destType,t.data),meta:t.meta})},e.exports=r},{"../utils":32,"./GenericWorker":28}],25:[function(t,e,i){var n=t("./GenericWorker"),s=t("../crc32");function r(){n.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}t("../utils").inherits(r,n),r.prototype.processChunk=function(t){this.streamInfo.crc32=s(t.data,this.streamInfo.crc32||0),this.push(t)},e.exports=r},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(t,e,i){var n=t("../utils"),s=t("./GenericWorker");function r(t){s.call(this,"DataLengthProbe for "+t),this.propName=t,this.withStreamInfo(t,0)}n.inherits(r,s),r.prototype.processChunk=function(t){if(t){var e=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=e+t.data.length}s.prototype.processChunk.call(this,t)},e.exports=r},{"../utils":32,"./GenericWorker":28}],27:[function(t,e,i){var n=t("../utils"),s=t("./GenericWorker");function r(t){s.call(this,"DataWorker");var e=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,t.then(function(t){e.dataIsReady=!0,e.data=t,e.max=t&&t.length||0,e.type=n.getTypeOf(t),e.isPaused||e._tickAndRepeat()},function(t){e.error(t)})}n.inherits(r,s),r.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this.data=null},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,n.delay(this._tickAndRepeat,[],this)),!0)},r.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(n.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},r.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var t=null,e=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":t=this.data.substring(this.index,e);break;case"uint8array":t=this.data.subarray(this.index,e);break;case"array":case"nodebuffer":t=this.data.slice(this.index,e)}return this.index=e,this.push({data:t,meta:{percent:this.max?this.index/this.max*100:0}})},e.exports=r},{"../utils":32,"./GenericWorker":28}],28:[function(t,e,i){function n(t){this.name=t||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}n.prototype={push:function(t){this.emit("data",t)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(t){this.emit("error",t)}return!0},error:function(t){return!this.isFinished&&(this.isPaused?this.generatedError=t:(this.isFinished=!0,this.emit("error",t),this.previous&&this.previous.error(t),this.cleanUp()),!0)},on:function(t,e){return this._listeners[t].push(e),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(t,e){if(this._listeners[t])for(var i=0;i<this._listeners[t].length;i++)this._listeners[t][i].call(this,e)},pipe:function(t){return t.registerPrevious(this)},registerPrevious:function(t){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=t.streamInfo,this.mergeStreamInfo(),this.previous=t;var e=this;return t.on("data",function(t){e.processChunk(t)}),t.on("end",function(){e.end()}),t.on("error",function(t){e.error(t)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var t=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),t=!0),this.previous&&this.previous.resume(),!t},flush:function(){},processChunk:function(t){this.push(t)},withStreamInfo:function(t,e){return this.extraStreamInfo[t]=e,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var t in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,t)&&(this.streamInfo[t]=this.extraStreamInfo[t])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var t="Worker "+this.name;return this.previous?this.previous+" -> "+t:t}},e.exports=n},{}],29:[function(t,e,i){var n=t("../utils"),s=t("./ConvertWorker"),r=t("./GenericWorker"),o=t("../base64"),a=t("../support"),l=t("../external"),c=null;if(a.nodestream)try{c=t("../nodejs/NodejsStreamOutputAdapter")}catch(t){}function h(t,e){return new l.Promise(function(i,s){var r=[],a=t._internalType,l=t._outputType,c=t._mimeType;t.on("data",function(t,i){r.push(t),e&&e(i)}).on("error",function(t){r=[],s(t)}).on("end",function(){try{var t=function(t,e,i){switch(t){case"blob":return n.newBlob(n.transformTo("arraybuffer",e),i);case"base64":return o.encode(e);default:return n.transformTo(t,e)}}(l,function(t,e){var i,n=0,s=null,r=0;for(i=0;i<e.length;i++)r+=e[i].length;switch(t){case"string":return e.join("");case"array":return Array.prototype.concat.apply([],e);case"uint8array":for(s=new Uint8Array(r),i=0;i<e.length;i++)s.set(e[i],n),n+=e[i].length;return s;case"nodebuffer":return Buffer.concat(e);default:throw new Error("concat : unsupported type '"+t+"'")}}(a,r),c);i(t)}catch(t){s(t)}r=[]}).resume()})}function d(t,e,i){var o=e;switch(e){case"blob":case"arraybuffer":o="uint8array";break;case"base64":o="string"}try{this._internalType=o,this._outputType=e,this._mimeType=i,n.checkSupport(o),this._worker=t.pipe(new s(o)),t.lock()}catch(t){this._worker=new r("error"),this._worker.error(t)}}d.prototype={accumulate:function(t){return h(this,t)},on:function(t,e){var i=this;return"data"===t?this._worker.on(t,function(t){e.call(i,t.data,t.meta)}):this._worker.on(t,function(){n.delay(e,arguments,i)}),this},resume:function(){return n.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(t){if(n.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new c(this,{objectMode:"nodebuffer"!==this._outputType},t)}},e.exports=d},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(t,e,i){if(i.base64=!0,i.array=!0,i.string=!0,i.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,i.nodebuffer="undefined"!=typeof Buffer,i.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)i.blob=!1;else{var n=new ArrayBuffer(0);try{i.blob=0===new Blob([n],{type:"application/zip"}).size}catch(t){try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);s.append(n),i.blob=0===s.getBlob("application/zip").size}catch(t){i.blob=!1}}}try{i.nodestream=!!t("readable-stream").Readable}catch(t){i.nodestream=!1}},{"readable-stream":16}],31:[function(t,e,i){for(var n=t("./utils"),s=t("./support"),r=t("./nodejsUtils"),o=t("./stream/GenericWorker"),a=new Array(256),l=0;l<256;l++)a[l]=252<=l?6:248<=l?5:240<=l?4:224<=l?3:192<=l?2:1;function c(){o.call(this,"utf-8 decode"),this.leftOver=null}function h(){o.call(this,"utf-8 encode")}a[254]=a[254]=1,i.utf8encode=function(t){return s.nodebuffer?r.newBufferFrom(t,"utf-8"):function(t){var e,i,n,r,o,a=t.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(e=s.uint8array?new Uint8Array(l):new Array(l),r=o=0;o<l;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),i<128?e[o++]=i:(i<2048?e[o++]=192|i>>>6:(i<65536?e[o++]=224|i>>>12:(e[o++]=240|i>>>18,e[o++]=128|i>>>12&63),e[o++]=128|i>>>6&63),e[o++]=128|63&i);return e}(t)},i.utf8decode=function(t){return s.nodebuffer?n.transformTo("nodebuffer",t).toString("utf-8"):function(t){var e,i,s,r,o=t.length,l=new Array(2*o);for(e=i=0;e<o;)if((s=t[e++])<128)l[i++]=s;else if(4<(r=a[s]))l[i++]=65533,e+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&e<o;)s=s<<6|63&t[e++],r--;1<r?l[i++]=65533:s<65536?l[i++]=s:(s-=65536,l[i++]=55296|s>>10&1023,l[i++]=56320|1023&s)}return l.length!==i&&(l.subarray?l=l.subarray(0,i):l.length=i),n.applyFromCharCode(l)}(t=n.transformTo(s.uint8array?"uint8array":"array",t))},n.inherits(c,o),c.prototype.processChunk=function(t){var e=n.transformTo(s.uint8array?"uint8array":"array",t.data);if(this.leftOver&&this.leftOver.length){if(s.uint8array){var r=e;(e=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),e.set(r,this.leftOver.length)}else e=this.leftOver.concat(e);this.leftOver=null}var o=function(t,e){var i;for((e=e||t.length)>t.length&&(e=t.length),i=e-1;0<=i&&128==(192&t[i]);)i--;return i<0||0===i?e:i+a[t[i]]>e?i:e}(e),l=e;o!==e.length&&(s.uint8array?(l=e.subarray(0,o),this.leftOver=e.subarray(o,e.length)):(l=e.slice(0,o),this.leftOver=e.slice(o,e.length))),this.push({data:i.utf8decode(l),meta:t.meta})},c.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=c,n.inherits(h,o),h.prototype.processChunk=function(t){this.push({data:i.utf8encode(t.data),meta:t.meta})},i.Utf8EncodeWorker=h},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(t,e,i){var n=t("./support"),s=t("./base64"),r=t("./nodejsUtils"),o=t("./external");function a(t){return t}function l(t,e){for(var i=0;i<t.length;++i)e[i]=255&t.charCodeAt(i);return e}t("setimmediate"),i.newBlob=function(t,e){i.checkSupport("blob");try{return new Blob([t],{type:e})}catch(i){try{var n=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return n.append(t),n.getBlob(e)}catch(t){throw new Error("Bug : can't construct the Blob.")}}};var c={stringifyByChunk:function(t,e,i){var n=[],s=0,r=t.length;if(r<=i)return String.fromCharCode.apply(null,t);for(;s<r;)"array"===e||"nodebuffer"===e?n.push(String.fromCharCode.apply(null,t.slice(s,Math.min(s+i,r)))):n.push(String.fromCharCode.apply(null,t.subarray(s,Math.min(s+i,r)))),s+=i;return n.join("")},stringifyByChar:function(t){for(var e="",i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},applyCanBeUsed:{uint8array:function(){try{return n.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(t){return!1}}(),nodebuffer:function(){try{return n.nodebuffer&&1===String.fromCharCode.apply(null,r.allocBuffer(1)).length}catch(t){return!1}}()}};function h(t){var e=65536,n=i.getTypeOf(t),s=!0;if("uint8array"===n?s=c.applyCanBeUsed.uint8array:"nodebuffer"===n&&(s=c.applyCanBeUsed.nodebuffer),s)for(;1<e;)try{return c.stringifyByChunk(t,n,e)}catch(t){e=Math.floor(e/2)}return c.stringifyByChar(t)}function d(t,e){for(var i=0;i<t.length;i++)e[i]=t[i];return e}i.applyFromCharCode=h;var u={};u.string={string:a,array:function(t){return l(t,new Array(t.length))},arraybuffer:function(t){return u.string.uint8array(t).buffer},uint8array:function(t){return l(t,new Uint8Array(t.length))},nodebuffer:function(t){return l(t,r.allocBuffer(t.length))}},u.array={string:h,array:a,arraybuffer:function(t){return new Uint8Array(t).buffer},uint8array:function(t){return new Uint8Array(t)},nodebuffer:function(t){return r.newBufferFrom(t)}},u.arraybuffer={string:function(t){return h(new Uint8Array(t))},array:function(t){return d(new Uint8Array(t),new Array(t.byteLength))},arraybuffer:a,uint8array:function(t){return new Uint8Array(t)},nodebuffer:function(t){return r.newBufferFrom(new Uint8Array(t))}},u.uint8array={string:h,array:function(t){return d(t,new Array(t.length))},arraybuffer:function(t){return t.buffer},uint8array:a,nodebuffer:function(t){return r.newBufferFrom(t)}},u.nodebuffer={string:h,array:function(t){return d(t,new Array(t.length))},arraybuffer:function(t){return u.nodebuffer.uint8array(t).buffer},uint8array:function(t){return d(t,new Uint8Array(t.length))},nodebuffer:a},i.transformTo=function(t,e){if(e=e||"",!t)return e;i.checkSupport(t);var n=i.getTypeOf(e);return u[n][t](e)},i.resolve=function(t){for(var e=t.split("/"),i=[],n=0;n<e.length;n++){var s=e[n];"."===s||""===s&&0!==n&&n!==e.length-1||(".."===s?i.pop():i.push(s))}return i.join("/")},i.getTypeOf=function(t){return"string"==typeof t?"string":"[object Array]"===Object.prototype.toString.call(t)?"array":n.nodebuffer&&r.isBuffer(t)?"nodebuffer":n.uint8array&&t instanceof Uint8Array?"uint8array":n.arraybuffer&&t instanceof ArrayBuffer?"arraybuffer":void 0},i.checkSupport=function(t){if(!n[t.toLowerCase()])throw new Error(t+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(t){var e,i,n="";for(i=0;i<(t||"").length;i++)n+="\\x"+((e=t.charCodeAt(i))<16?"0":"")+e.toString(16).toUpperCase();return n},i.delay=function(t,e,i){setImmediate(function(){t.apply(i||null,e||[])})},i.inherits=function(t,e){function i(){}i.prototype=e.prototype,t.prototype=new i},i.extend=function(){var t,e,i={};for(t=0;t<arguments.length;t++)for(e in arguments[t])Object.prototype.hasOwnProperty.call(arguments[t],e)&&void 0===i[e]&&(i[e]=arguments[t][e]);return i},i.prepareContent=function(t,e,r,a,c){return o.Promise.resolve(e).then(function(t){return n.blob&&(t instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(t)))&&"undefined"!=typeof FileReader?new o.Promise(function(e,i){var n=new FileReader;n.onload=function(t){e(t.target.result)},n.onerror=function(t){i(t.target.error)},n.readAsArrayBuffer(t)}):t}).then(function(e){var h,d=i.getTypeOf(e);return d?("arraybuffer"===d?e=i.transformTo("uint8array",e):"string"===d&&(c?e=s.decode(e):r&&!0!==a&&(e=l(h=e,n.uint8array?new Uint8Array(h.length):new Array(h.length)))),e):o.Promise.reject(new Error("Can't read the data of '"+t+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(t,e,i){var n=t("./reader/readerFor"),s=t("./utils"),r=t("./signature"),o=t("./zipEntry"),a=t("./support");function l(t){this.files=[],this.loadOptions=t}l.prototype={checkSignature:function(t){if(!this.reader.readAndCheckSignature(t)){this.reader.index-=4;var e=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+s.pretty(e)+", expected "+s.pretty(t)+")")}},isSignature:function(t,e){var i=this.reader.index;this.reader.setIndex(t);var n=this.reader.readString(4)===e;return this.reader.setIndex(i),n},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var t=this.reader.readData(this.zipCommentLength),e=a.uint8array?"uint8array":"array",i=s.transformTo(e,t);this.zipComment=this.loadOptions.decodeFileName(i)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var t,e,i,n=this.zip64EndOfCentralSize-44;0<n;)t=this.reader.readInt(2),e=this.reader.readInt(4),i=this.reader.readData(e),this.zip64ExtensibleData[t]={id:t,length:e,value:i}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var t,e;for(t=0;t<this.files.length;t++)e=this.files[t],this.reader.setIndex(e.localHeaderOffset),this.checkSignature(r.LOCAL_FILE_HEADER),e.readLocalPart(this.reader),e.handleUTF8(),e.processAttributes()},readCentralDir:function(){var t;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(r.CENTRAL_FILE_HEADER);)(t=new o({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(t);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var t=this.reader.lastIndexOfSignature(r.CENTRAL_DIRECTORY_END);if(t<0)throw this.isSignature(0,r.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(t);var e=t;if(this.checkSignature(r.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===s.MAX_VALUE_16BITS||this.diskWithCentralDirStart===s.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===s.MAX_VALUE_16BITS||this.centralDirRecords===s.MAX_VALUE_16BITS||this.centralDirSize===s.MAX_VALUE_32BITS||this.centralDirOffset===s.MAX_VALUE_32BITS){if(this.zip64=!0,(t=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(t),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,r.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var i=this.centralDirOffset+this.centralDirSize;this.zip64&&(i+=20,i+=12+this.zip64EndOfCentralSize);var n=e-i;if(0<n)this.isSignature(e,r.CENTRAL_FILE_HEADER)||(this.reader.zero=n);else if(n<0)throw new Error("Corrupted zip: missing "+Math.abs(n)+" bytes.")},prepareReader:function(t){this.reader=n(t)},load:function(t){this.prepareReader(t),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},e.exports=l},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(t,e,i){var n=t("./reader/readerFor"),s=t("./utils"),r=t("./compressedObject"),o=t("./crc32"),a=t("./utf8"),l=t("./compressions"),c=t("./support");function h(t,e){this.options=t,this.loadOptions=e}h.prototype={isEncrypted:function(){return!(1&~this.bitFlag)},useUTF8:function(){return!(2048&~this.bitFlag)},readLocalPart:function(t){var e,i;if(t.skip(22),this.fileNameLength=t.readInt(2),i=t.readInt(2),this.fileName=t.readData(this.fileNameLength),t.skip(i),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(e=function(t){for(var e in l)if(Object.prototype.hasOwnProperty.call(l,e)&&l[e].magic===t)return l[e];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+s.pretty(this.compressionMethod)+" unknown (inner file : "+s.transformTo("string",this.fileName)+")");this.decompressed=new r(this.compressedSize,this.uncompressedSize,this.crc32,e,t.readData(this.compressedSize))},readCentralPart:function(t){this.versionMadeBy=t.readInt(2),t.skip(2),this.bitFlag=t.readInt(2),this.compressionMethod=t.readString(2),this.date=t.readDate(),this.crc32=t.readInt(4),this.compressedSize=t.readInt(4),this.uncompressedSize=t.readInt(4);var e=t.readInt(2);if(this.extraFieldsLength=t.readInt(2),this.fileCommentLength=t.readInt(2),this.diskNumberStart=t.readInt(2),this.internalFileAttributes=t.readInt(2),this.externalFileAttributes=t.readInt(4),this.localHeaderOffset=t.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");t.skip(e),this.readExtraFields(t),this.parseZIP64ExtraField(t),this.fileComment=t.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var t=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==t&&(this.dosPermissions=63&this.externalFileAttributes),3==t&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var t=n(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=t.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=t.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=t.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=t.readInt(4))}},readExtraFields:function(t){var e,i,n,s=t.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});t.index+4<s;)e=t.readInt(2),i=t.readInt(2),n=t.readData(i),this.extraFields[e]={id:e,length:i,value:n};t.setIndex(s)},handleUTF8:function(){var t=c.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var e=this.findExtraFieldUnicodePath();if(null!==e)this.fileNameStr=e;else{var i=s.transformTo(t,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(i)}var n=this.findExtraFieldUnicodeComment();if(null!==n)this.fileCommentStr=n;else{var r=s.transformTo(t,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(r)}}},findExtraFieldUnicodePath:function(){var t=this.extraFields[28789];if(t){var e=n(t.value);return 1!==e.readInt(1)||o(this.fileName)!==e.readInt(4)?null:a.utf8decode(e.readData(t.length-5))}return null},findExtraFieldUnicodeComment:function(){var t=this.extraFields[25461];if(t){var e=n(t.value);return 1!==e.readInt(1)||o(this.fileComment)!==e.readInt(4)?null:a.utf8decode(e.readData(t.length-5))}return null}},e.exports=h},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(t,e,i){function n(t,e,i){this.name=t,this.dir=i.dir,this.date=i.date,this.comment=i.comment,this.unixPermissions=i.unixPermissions,this.dosPermissions=i.dosPermissions,this._data=e,this._dataBinary=i.binary,this.options={compression:i.compression,compressionOptions:i.compressionOptions}}var s=t("./stream/StreamHelper"),r=t("./stream/DataWorker"),o=t("./utf8"),a=t("./compressedObject"),l=t("./stream/GenericWorker");n.prototype={internalStream:function(t){var e=null,i="string";try{if(!t)throw new Error("No output type specified.");var n="string"===(i=t.toLowerCase())||"text"===i;"binarystring"!==i&&"text"!==i||(i="string"),e=this._decompressWorker();var r=!this._dataBinary;r&&!n&&(e=e.pipe(new o.Utf8EncodeWorker)),!r&&n&&(e=e.pipe(new o.Utf8DecodeWorker))}catch(t){(e=new l("error")).error(t)}return new s(e,i,"")},async:function(t,e){return this.internalStream(t).accumulate(e)},nodeStream:function(t,e){return this.internalStream(t||"nodebuffer").toNodejsStream(e)},_compressWorker:function(t,e){if(this._data instanceof a&&this._data.compression.magic===t.magic)return this._data.getCompressedWorker();var i=this._decompressWorker();return this._dataBinary||(i=i.pipe(new o.Utf8EncodeWorker)),a.createWorkerFrom(i,t,e)},_decompressWorker:function(){return this._data instanceof a?this._data.getContentWorker():this._data instanceof l?this._data:new r(this._data)}};for(var c=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],h=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},d=0;d<c.length;d++)n.prototype[c[d]]=h;e.exports=n},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(t,e,i){(function(t){var i,n,s=t.MutationObserver||t.WebKitMutationObserver;if(s){var r=0,o=new s(h),a=t.document.createTextNode("");o.observe(a,{characterData:!0}),i=function(){a.data=r=++r%2}}else if(t.setImmediate||void 0===t.MessageChannel)i="document"in t&&"onreadystatechange"in t.document.createElement("script")?function(){var e=t.document.createElement("script");e.onreadystatechange=function(){h(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},t.document.documentElement.appendChild(e)}:function(){setTimeout(h,0)};else{var l=new t.MessageChannel;l.port1.onmessage=h,i=function(){l.port2.postMessage(0)}}var c=[];function h(){var t,e;n=!0;for(var i=c.length;i;){for(e=c,c=[],t=-1;++t<i;)e[t]();i=c.length}n=!1}e.exports=function(t){1!==c.push(t)||n||i()}}).call(this,void 0!==qo?qo:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(t,e,i){var n=t("immediate");function s(){}var r={},o=["REJECTED"],a=["FULFILLED"],l=["PENDING"];function c(t){if("function"!=typeof t)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,t!==s&&p(this,t)}function h(t,e,i){this.promise=t,"function"==typeof e&&(this.onFulfilled=e,this.callFulfilled=this.otherCallFulfilled),"function"==typeof i&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}function d(t,e,i){n(function(){var n;try{n=e(i)}catch(e){return r.reject(t,e)}n===t?r.reject(t,new TypeError("Cannot resolve promise with itself")):r.resolve(t,n)})}function u(t){var e=t&&t.then;if(t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof e)return function(){e.apply(t,arguments)}}function p(t,e){var i=!1;function n(e){i||(i=!0,r.reject(t,e))}function s(e){i||(i=!0,r.resolve(t,e))}var o=f(function(){e(s,n)});"error"===o.status&&n(o.value)}function f(t,e){var i={};try{i.value=t(e),i.status="success"}catch(t){i.status="error",i.value=t}return i}(e.exports=c).prototype.finally=function(t){if("function"!=typeof t)return this;var e=this.constructor;return this.then(function(i){return e.resolve(t()).then(function(){return i})},function(i){return e.resolve(t()).then(function(){throw i})})},c.prototype.catch=function(t){return this.then(null,t)},c.prototype.then=function(t,e){if("function"!=typeof t&&this.state===a||"function"!=typeof e&&this.state===o)return this;var i=new this.constructor(s);return this.state!==l?d(i,this.state===a?t:e,this.outcome):this.queue.push(new h(i,t,e)),i},h.prototype.callFulfilled=function(t){r.resolve(this.promise,t)},h.prototype.otherCallFulfilled=function(t){d(this.promise,this.onFulfilled,t)},h.prototype.callRejected=function(t){r.reject(this.promise,t)},h.prototype.otherCallRejected=function(t){d(this.promise,this.onRejected,t)},r.resolve=function(t,e){var i=f(u,e);if("error"===i.status)return r.reject(t,i.value);var n=i.value;if(n)p(t,n);else{t.state=a,t.outcome=e;for(var s=-1,o=t.queue.length;++s<o;)t.queue[s].callFulfilled(e)}return t},r.reject=function(t,e){t.state=o,t.outcome=e;for(var i=-1,n=t.queue.length;++i<n;)t.queue[i].callRejected(e);return t},c.resolve=function(t){return t instanceof this?t:r.resolve(new this(s),t)},c.reject=function(t){var e=new this(s);return r.reject(e,t)},c.all=function(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,n=!1;if(!i)return this.resolve([]);for(var o=new Array(i),a=0,l=-1,c=new this(s);++l<i;)h(t[l],l);return c;function h(t,s){e.resolve(t).then(function(t){o[s]=t,++a!==i||n||(n=!0,r.resolve(c,o))},function(t){n||(n=!0,r.reject(c,t))})}},c.race=function(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,n=!1;if(!i)return this.resolve([]);for(var o,a=-1,l=new this(s);++a<i;)o=t[a],e.resolve(o).then(function(t){n||(n=!0,r.resolve(l,t))},function(t){n||(n=!0,r.reject(l,t))});return l}},{immediate:36}],38:[function(t,e,i){var n={};(0,t("./lib/utils/common").assign)(n,t("./lib/deflate"),t("./lib/inflate"),t("./lib/zlib/constants")),e.exports=n},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(t,e,i){var n=t("./zlib/deflate"),s=t("./utils/common"),r=t("./utils/strings"),o=t("./zlib/messages"),a=t("./zlib/zstream"),l=Object.prototype.toString,c=0,h=-1,d=0,u=8;function p(t){if(!(this instanceof p))return new p(t);this.options=s.assign({level:h,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:d,to:""},t||{});var e=this.options;e.raw&&0<e.windowBits?e.windowBits=-e.windowBits:e.gzip&&0<e.windowBits&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var i=n.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==c)throw new Error(o[i]);if(e.header&&n.deflateSetHeader(this.strm,e.header),e.dictionary){var f;if(f="string"==typeof e.dictionary?r.string2buf(e.dictionary):"[object ArrayBuffer]"===l.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,(i=n.deflateSetDictionary(this.strm,f))!==c)throw new Error(o[i]);this._dict_set=!0}}function f(t,e){var i=new p(e);if(i.push(t,!0),i.err)throw i.msg||o[i.err];return i.result}p.prototype.push=function(t,e){var i,o,a=this.strm,h=this.options.chunkSize;if(this.ended)return!1;o=e===~~e?e:!0===e?4:0,"string"==typeof t?a.input=r.string2buf(t):"[object ArrayBuffer]"===l.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new s.Buf8(h),a.next_out=0,a.avail_out=h),1!==(i=n.deflate(a,o))&&i!==c)return this.onEnd(i),!(this.ended=!0);0!==a.avail_out&&(0!==a.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(r.buf2binstring(s.shrinkBuf(a.output,a.next_out))):this.onData(s.shrinkBuf(a.output,a.next_out)))}while((0<a.avail_in||0===a.avail_out)&&1!==i);return 4===o?(i=n.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===c):2!==o||(this.onEnd(c),!(a.avail_out=0))},p.prototype.onData=function(t){this.chunks.push(t)},p.prototype.onEnd=function(t){t===c&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},i.Deflate=p,i.deflate=f,i.deflateRaw=function(t,e){return(e=e||{}).raw=!0,f(t,e)},i.gzip=function(t,e){return(e=e||{}).gzip=!0,f(t,e)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(t,e,i){var n=t("./zlib/inflate"),s=t("./utils/common"),r=t("./utils/strings"),o=t("./zlib/constants"),a=t("./zlib/messages"),l=t("./zlib/zstream"),c=t("./zlib/gzheader"),h=Object.prototype.toString;function d(t){if(!(this instanceof d))return new d(t);this.options=s.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&0<=e.windowBits&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(0<=e.windowBits&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),15<e.windowBits&&e.windowBits<48&&!(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var i=n.inflateInit2(this.strm,e.windowBits);if(i!==o.Z_OK)throw new Error(a[i]);this.header=new c,n.inflateGetHeader(this.strm,this.header)}function u(t,e){var i=new d(e);if(i.push(t,!0),i.err)throw i.msg||a[i.err];return i.result}d.prototype.push=function(t,e){var i,a,l,c,d,u,p=this.strm,f=this.options.chunkSize,m=this.options.dictionary,g=!1;if(this.ended)return!1;a=e===~~e?e:!0===e?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof t?p.input=r.binstring2buf(t):"[object ArrayBuffer]"===h.call(t)?p.input=new Uint8Array(t):p.input=t,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new s.Buf8(f),p.next_out=0,p.avail_out=f),(i=n.inflate(p,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&m&&(u="string"==typeof m?r.string2buf(m):"[object ArrayBuffer]"===h.call(m)?new Uint8Array(m):m,i=n.inflateSetDictionary(this.strm,u)),i===o.Z_BUF_ERROR&&!0===g&&(i=o.Z_OK,g=!1),i!==o.Z_STREAM_END&&i!==o.Z_OK)return this.onEnd(i),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&i!==o.Z_STREAM_END&&(0!==p.avail_in||a!==o.Z_FINISH&&a!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(l=r.utf8border(p.output,p.next_out),c=p.next_out-l,d=r.buf2string(p.output,l),p.next_out=c,p.avail_out=f-c,c&&s.arraySet(p.output,p.output,l,c,0),this.onData(d)):this.onData(s.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((0<p.avail_in||0===p.avail_out)&&i!==o.Z_STREAM_END);return i===o.Z_STREAM_END&&(a=o.Z_FINISH),a===o.Z_FINISH?(i=n.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===o.Z_OK):a!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),!(p.avail_out=0))},d.prototype.onData=function(t){this.chunks.push(t)},d.prototype.onEnd=function(t){t===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},i.Inflate=d,i.inflate=u,i.inflateRaw=function(t,e){return(e=e||{}).raw=!0,u(t,e)},i.ungzip=u},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(t,e,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;i.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var n in i)i.hasOwnProperty(n)&&(t[n]=i[n])}}return t},i.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var s={arraySet:function(t,e,i,n,s){if(e.subarray&&t.subarray)t.set(e.subarray(i,i+n),s);else for(var r=0;r<n;r++)t[s+r]=e[i+r]},flattenChunks:function(t){var e,i,n,s,r,o;for(e=n=0,i=t.length;e<i;e++)n+=t[e].length;for(o=new Uint8Array(n),e=s=0,i=t.length;e<i;e++)r=t[e],o.set(r,s),s+=r.length;return o}},r={arraySet:function(t,e,i,n,s){for(var r=0;r<n;r++)t[s+r]=e[i+r]},flattenChunks:function(t){return[].concat.apply([],t)}};i.setTyped=function(t){t?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,s)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,r))},i.setTyped(n)},{}],42:[function(t,e,i){var n=t("./common"),s=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch(t){s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){r=!1}for(var o=new n.Buf8(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function l(t,e){if(e<65537&&(t.subarray&&r||!t.subarray&&s))return String.fromCharCode.apply(null,n.shrinkBuf(t,e));for(var i="",o=0;o<e;o++)i+=String.fromCharCode(t[o]);return i}o[254]=o[254]=1,i.string2buf=function(t){var e,i,s,r,o,a=t.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(e=new n.Buf8(l),r=o=0;o<l;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),i<128?e[o++]=i:(i<2048?e[o++]=192|i>>>6:(i<65536?e[o++]=224|i>>>12:(e[o++]=240|i>>>18,e[o++]=128|i>>>12&63),e[o++]=128|i>>>6&63),e[o++]=128|63&i);return e},i.buf2binstring=function(t){return l(t,t.length)},i.binstring2buf=function(t){for(var e=new n.Buf8(t.length),i=0,s=e.length;i<s;i++)e[i]=t.charCodeAt(i);return e},i.buf2string=function(t,e){var i,n,s,r,a=e||t.length,c=new Array(2*a);for(i=n=0;i<a;)if((s=t[i++])<128)c[n++]=s;else if(4<(r=o[s]))c[n++]=65533,i+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&i<a;)s=s<<6|63&t[i++],r--;1<r?c[n++]=65533:s<65536?c[n++]=s:(s-=65536,c[n++]=55296|s>>10&1023,c[n++]=56320|1023&s)}return l(c,n)},i.utf8border=function(t,e){var i;for((e=e||t.length)>t.length&&(e=t.length),i=e-1;0<=i&&128==(192&t[i]);)i--;return i<0||0===i?e:i+o[t[i]]>e?i:e}},{"./common":41}],43:[function(t,e,i){e.exports=function(t,e,i,n){for(var s=65535&t,r=t>>>16&65535,o=0;0!==i;){for(i-=o=2e3<i?2e3:i;r=r+(s=s+e[n++]|0)|0,--o;);s%=65521,r%=65521}return s|r<<16}},{}],44:[function(t,e,i){e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(t,e,i){var n=function(){for(var t,e=[],i=0;i<256;i++){t=i;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e}();e.exports=function(t,e,i,s){var r=n,o=s+i;t^=-1;for(var a=s;a<o;a++)t=t>>>8^r[255&(t^e[a])];return-1^t}},{}],46:[function(t,e,i){var n,s=t("../utils/common"),r=t("./trees"),o=t("./adler32"),a=t("./crc32"),l=t("./messages"),c=0,h=4,d=0,u=-2,p=-1,f=4,m=2,g=8,w=9,y=286,_=30,b=19,v=2*y+1,x=15,S=3,T=258,C=T+S+1,A=42,E=113,M=1,P=2,z=3,I=4;function D(t,e){return t.msg=l[e],e}function k(t){return(t<<1)-(4<t?9:0)}function B(t){for(var e=t.length;0<=--e;)t[e]=0}function O(t){var e=t.state,i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(s.arraySet(t.output,e.pending_buf,e.pending_out,i,t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))}function V(t,e){r._tr_flush_block(t,0<=t.block_start?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,O(t.strm)}function L(t,e){t.pending_buf[t.pending++]=e}function N(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function F(t,e){var i,n,s=t.max_chain_length,r=t.strstart,o=t.prev_length,a=t.nice_match,l=t.strstart>t.w_size-C?t.strstart-(t.w_size-C):0,c=t.window,h=t.w_mask,d=t.prev,u=t.strstart+T,p=c[r+o-1],f=c[r+o];t.prev_length>=t.good_match&&(s>>=2),a>t.lookahead&&(a=t.lookahead);do{if(c[(i=e)+o]===f&&c[i+o-1]===p&&c[i]===c[r]&&c[++i]===c[r+1]){r+=2,i++;do{}while(c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&r<u);if(n=T-(u-r),r=u-T,o<n){if(t.match_start=e,a<=(o=n))break;p=c[r+o-1],f=c[r+o]}}}while((e=d[e&h])>l&&0!=--s);return o<=t.lookahead?o:t.lookahead}function R(t){var e,i,n,r,l,c,h,d,u,p,f=t.w_size;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=f+(f-C)){for(s.arraySet(t.window,t.window,f,f,0),t.match_start-=f,t.strstart-=f,t.block_start-=f,e=i=t.hash_size;n=t.head[--e],t.head[e]=f<=n?n-f:0,--i;);for(e=i=f;n=t.prev[--e],t.prev[e]=f<=n?n-f:0,--i;);r+=f}if(0===t.strm.avail_in)break;if(c=t.strm,h=t.window,d=t.strstart+t.lookahead,p=void 0,(u=r)<(p=c.avail_in)&&(p=u),i=0===p?0:(c.avail_in-=p,s.arraySet(h,c.input,c.next_in,p,d),1===c.state.wrap?c.adler=o(c.adler,h,p,d):2===c.state.wrap&&(c.adler=a(c.adler,h,p,d)),c.next_in+=p,c.total_in+=p,p),t.lookahead+=i,t.lookahead+t.insert>=S)for(l=t.strstart-t.insert,t.ins_h=t.window[l],t.ins_h=(t.ins_h<<t.hash_shift^t.window[l+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[l+S-1])&t.hash_mask,t.prev[l&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=l,l++,t.insert--,!(t.lookahead+t.insert<S)););}while(t.lookahead<C&&0!==t.strm.avail_in)}function U(t,e){for(var i,n;;){if(t.lookahead<C){if(R(t),t.lookahead<C&&e===c)return M;if(0===t.lookahead)break}if(i=0,t.lookahead>=S&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+S-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-C&&(t.match_length=F(t,i)),t.match_length>=S)if(n=r._tr_tally(t,t.strstart-t.match_start,t.match_length-S),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=S){for(t.match_length--;t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+S-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart,0!=--t.match_length;);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else n=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(n&&(V(t,!1),0===t.strm.avail_out))return M}return t.insert=t.strstart<S-1?t.strstart:S-1,e===h?(V(t,!0),0===t.strm.avail_out?z:I):t.last_lit&&(V(t,!1),0===t.strm.avail_out)?M:P}function j(t,e){for(var i,n,s;;){if(t.lookahead<C){if(R(t),t.lookahead<C&&e===c)return M;if(0===t.lookahead)break}if(i=0,t.lookahead>=S&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+S-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=S-1,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-C&&(t.match_length=F(t,i),t.match_length<=5&&(1===t.strategy||t.match_length===S&&4096<t.strstart-t.match_start)&&(t.match_length=S-1)),t.prev_length>=S&&t.match_length<=t.prev_length){for(s=t.strstart+t.lookahead-S,n=r._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-S),t.lookahead-=t.prev_length-1,t.prev_length-=2;++t.strstart<=s&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+S-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!=--t.prev_length;);if(t.match_available=0,t.match_length=S-1,t.strstart++,n&&(V(t,!1),0===t.strm.avail_out))return M}else if(t.match_available){if((n=r._tr_tally(t,0,t.window[t.strstart-1]))&&V(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return M}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(n=r._tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<S-1?t.strstart:S-1,e===h?(V(t,!0),0===t.strm.avail_out?z:I):t.last_lit&&(V(t,!1),0===t.strm.avail_out)?M:P}function $(t,e,i,n,s){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=n,this.func=s}function W(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=g,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new s.Buf16(2*v),this.dyn_dtree=new s.Buf16(2*(2*_+1)),this.bl_tree=new s.Buf16(2*(2*b+1)),B(this.dyn_ltree),B(this.dyn_dtree),B(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new s.Buf16(x+1),this.heap=new s.Buf16(2*y+1),B(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new s.Buf16(2*y+1),B(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function G(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=m,(e=t.state).pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?A:E,t.adler=2===e.wrap?0:1,e.last_flush=c,r._tr_init(e),d):D(t,u)}function H(t){var e,i=G(t);return i===d&&((e=t.state).window_size=2*e.w_size,B(e.head),e.max_lazy_match=n[e.level].max_lazy,e.good_match=n[e.level].good_length,e.nice_match=n[e.level].nice_length,e.max_chain_length=n[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=S-1,e.match_available=0,e.ins_h=0),i}function q(t,e,i,n,r,o){if(!t)return u;var a=1;if(e===p&&(e=6),n<0?(a=0,n=-n):15<n&&(a=2,n-=16),r<1||w<r||i!==g||n<8||15<n||e<0||9<e||o<0||f<o)return D(t,u);8===n&&(n=9);var l=new W;return(t.state=l).strm=t,l.wrap=a,l.gzhead=null,l.w_bits=n,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=r+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+S-1)/S),l.window=new s.Buf8(2*l.w_size),l.head=new s.Buf16(l.hash_size),l.prev=new s.Buf16(l.w_size),l.lit_bufsize=1<<r+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new s.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=e,l.strategy=o,l.method=i,H(t)}n=[new $(0,0,0,0,function(t,e){var i=65535;for(i>t.pending_buf_size-5&&(i=t.pending_buf_size-5);;){if(t.lookahead<=1){if(R(t),0===t.lookahead&&e===c)return M;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+i;if((0===t.strstart||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,V(t,!1),0===t.strm.avail_out))return M;if(t.strstart-t.block_start>=t.w_size-C&&(V(t,!1),0===t.strm.avail_out))return M}return t.insert=0,e===h?(V(t,!0),0===t.strm.avail_out?z:I):(t.strstart>t.block_start&&(V(t,!1),t.strm.avail_out),M)}),new $(4,4,8,4,U),new $(4,5,16,8,U),new $(4,6,32,32,U),new $(4,4,16,16,j),new $(8,16,32,32,j),new $(8,16,128,128,j),new $(8,32,128,256,j),new $(32,128,258,1024,j),new $(32,258,258,4096,j)],i.deflateInit=function(t,e){return q(t,e,g,15,8,0)},i.deflateInit2=q,i.deflateReset=H,i.deflateResetKeep=G,i.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?u:(t.state.gzhead=e,d):u},i.deflate=function(t,e){var i,s,o,l;if(!t||!t.state||5<e||e<0)return t?D(t,u):u;if(s=t.state,!t.output||!t.input&&0!==t.avail_in||666===s.status&&e!==h)return D(t,0===t.avail_out?-5:u);if(s.strm=t,i=s.last_flush,s.last_flush=e,s.status===A)if(2===s.wrap)t.adler=0,L(s,31),L(s,139),L(s,8),s.gzhead?(L(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),L(s,255&s.gzhead.time),L(s,s.gzhead.time>>8&255),L(s,s.gzhead.time>>16&255),L(s,s.gzhead.time>>24&255),L(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),L(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(L(s,255&s.gzhead.extra.length),L(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(t.adler=a(t.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69):(L(s,0),L(s,0),L(s,0),L(s,0),L(s,0),L(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),L(s,3),s.status=E);else{var p=g+(s.w_bits-8<<4)<<8;p|=(2<=s.strategy||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(p|=32),p+=31-p%31,s.status=E,N(s,p),0!==s.strstart&&(N(s,t.adler>>>16),N(s,65535&t.adler)),t.adler=1}if(69===s.status)if(s.gzhead.extra){for(o=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),O(t),o=s.pending,s.pending!==s.pending_buf_size));)L(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=73)}else s.status=73;if(73===s.status)if(s.gzhead.name){o=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),O(t),o=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,L(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),0===l&&(s.gzindex=0,s.status=91)}else s.status=91;if(91===s.status)if(s.gzhead.comment){o=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),O(t),o=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,L(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),0===l&&(s.status=103)}else s.status=103;if(103===s.status&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&O(t),s.pending+2<=s.pending_buf_size&&(L(s,255&t.adler),L(s,t.adler>>8&255),t.adler=0,s.status=E)):s.status=E),0!==s.pending){if(O(t),0===t.avail_out)return s.last_flush=-1,d}else if(0===t.avail_in&&k(e)<=k(i)&&e!==h)return D(t,-5);if(666===s.status&&0!==t.avail_in)return D(t,-5);if(0!==t.avail_in||0!==s.lookahead||e!==c&&666!==s.status){var f=2===s.strategy?function(t,e){for(var i;;){if(0===t.lookahead&&(R(t),0===t.lookahead)){if(e===c)return M;break}if(t.match_length=0,i=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(V(t,!1),0===t.strm.avail_out))return M}return t.insert=0,e===h?(V(t,!0),0===t.strm.avail_out?z:I):t.last_lit&&(V(t,!1),0===t.strm.avail_out)?M:P}(s,e):3===s.strategy?function(t,e){for(var i,n,s,o,a=t.window;;){if(t.lookahead<=T){if(R(t),t.lookahead<=T&&e===c)return M;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=S&&0<t.strstart&&(n=a[s=t.strstart-1])===a[++s]&&n===a[++s]&&n===a[++s]){o=t.strstart+T;do{}while(n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&s<o);t.match_length=T-(o-s),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=S?(i=r._tr_tally(t,1,t.match_length-S),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(V(t,!1),0===t.strm.avail_out))return M}return t.insert=0,e===h?(V(t,!0),0===t.strm.avail_out?z:I):t.last_lit&&(V(t,!1),0===t.strm.avail_out)?M:P}(s,e):n[s.level].func(s,e);if(f!==z&&f!==I||(s.status=666),f===M||f===z)return 0===t.avail_out&&(s.last_flush=-1),d;if(f===P&&(1===e?r._tr_align(s):5!==e&&(r._tr_stored_block(s,0,0,!1),3===e&&(B(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),O(t),0===t.avail_out))return s.last_flush=-1,d}return e!==h?d:s.wrap<=0?1:(2===s.wrap?(L(s,255&t.adler),L(s,t.adler>>8&255),L(s,t.adler>>16&255),L(s,t.adler>>24&255),L(s,255&t.total_in),L(s,t.total_in>>8&255),L(s,t.total_in>>16&255),L(s,t.total_in>>24&255)):(N(s,t.adler>>>16),N(s,65535&t.adler)),O(t),0<s.wrap&&(s.wrap=-s.wrap),0!==s.pending?d:1)},i.deflateEnd=function(t){var e;return t&&t.state?(e=t.state.status)!==A&&69!==e&&73!==e&&91!==e&&103!==e&&e!==E&&666!==e?D(t,u):(t.state=null,e===E?D(t,-3):d):u},i.deflateSetDictionary=function(t,e){var i,n,r,a,l,c,h,p,f=e.length;if(!t||!t.state)return u;if(2===(a=(i=t.state).wrap)||1===a&&i.status!==A||i.lookahead)return u;for(1===a&&(t.adler=o(t.adler,e,f,0)),i.wrap=0,f>=i.w_size&&(0===a&&(B(i.head),i.strstart=0,i.block_start=0,i.insert=0),p=new s.Buf8(i.w_size),s.arraySet(p,e,f-i.w_size,i.w_size,0),e=p,f=i.w_size),l=t.avail_in,c=t.next_in,h=t.input,t.avail_in=f,t.next_in=0,t.input=e,R(i);i.lookahead>=S;){for(n=i.strstart,r=i.lookahead-(S-1);i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+S-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++,--r;);i.strstart=n,i.lookahead=S-1,R(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=S-1,i.match_available=0,t.next_in=c,t.input=h,t.avail_in=l,i.wrap=a,d},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(t,e,i){e.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(t,e,i){e.exports=function(t,e){var i,n,s,r,o,a,l,c,h,d,u,p,f,m,g,w,y,_,b,v,x,S,T,C,A;i=t.state,n=t.next_in,C=t.input,s=n+(t.avail_in-5),r=t.next_out,A=t.output,o=r-(e-t.avail_out),a=r+(t.avail_out-257),l=i.dmax,c=i.wsize,h=i.whave,d=i.wnext,u=i.window,p=i.hold,f=i.bits,m=i.lencode,g=i.distcode,w=(1<<i.lenbits)-1,y=(1<<i.distbits)-1;t:do{f<15&&(p+=C[n++]<<f,f+=8,p+=C[n++]<<f,f+=8),_=m[p&w];e:for(;;){if(p>>>=b=_>>>24,f-=b,0==(b=_>>>16&255))A[r++]=65535&_;else{if(!(16&b)){if(!(64&b)){_=m[(65535&_)+(p&(1<<b)-1)];continue e}if(32&b){i.mode=12;break t}t.msg="invalid literal/length code",i.mode=30;break t}v=65535&_,(b&=15)&&(f<b&&(p+=C[n++]<<f,f+=8),v+=p&(1<<b)-1,p>>>=b,f-=b),f<15&&(p+=C[n++]<<f,f+=8,p+=C[n++]<<f,f+=8),_=g[p&y];i:for(;;){if(p>>>=b=_>>>24,f-=b,!(16&(b=_>>>16&255))){if(!(64&b)){_=g[(65535&_)+(p&(1<<b)-1)];continue i}t.msg="invalid distance code",i.mode=30;break t}if(x=65535&_,f<(b&=15)&&(p+=C[n++]<<f,(f+=8)<b&&(p+=C[n++]<<f,f+=8)),l<(x+=p&(1<<b)-1)){t.msg="invalid distance too far back",i.mode=30;break t}if(p>>>=b,f-=b,(b=r-o)<x){if(h<(b=x-b)&&i.sane){t.msg="invalid distance too far back",i.mode=30;break t}if(T=u,(S=0)===d){if(S+=c-b,b<v){for(v-=b;A[r++]=u[S++],--b;);S=r-x,T=A}}else if(d<b){if(S+=c+d-b,(b-=d)<v){for(v-=b;A[r++]=u[S++],--b;);if(S=0,d<v){for(v-=b=d;A[r++]=u[S++],--b;);S=r-x,T=A}}}else if(S+=d-b,b<v){for(v-=b;A[r++]=u[S++],--b;);S=r-x,T=A}for(;2<v;)A[r++]=T[S++],A[r++]=T[S++],A[r++]=T[S++],v-=3;v&&(A[r++]=T[S++],1<v&&(A[r++]=T[S++]))}else{for(S=r-x;A[r++]=A[S++],A[r++]=A[S++],A[r++]=A[S++],2<(v-=3););v&&(A[r++]=A[S++],1<v&&(A[r++]=A[S++]))}break}}break}}while(n<s&&r<a);n-=v=f>>3,p&=(1<<(f-=v<<3))-1,t.next_in=n,t.next_out=r,t.avail_in=n<s?s-n+5:5-(n-s),t.avail_out=r<a?a-r+257:257-(r-a),i.hold=p,i.bits=f}},{}],49:[function(t,e,i){var n=t("../utils/common"),s=t("./adler32"),r=t("./crc32"),o=t("./inffast"),a=t("./inftrees"),l=1,c=2,h=0,d=-2,u=1,p=852,f=592;function m(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new n.Buf16(320),this.work=new n.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function w(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=u,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new n.Buf32(p),e.distcode=e.distdyn=new n.Buf32(f),e.sane=1,e.back=-1,h):d}function y(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,w(t)):d}function _(t,e){var i,n;return t&&t.state?(n=t.state,e<0?(i=0,e=-e):(i=1+(e>>4),e<48&&(e&=15)),e&&(e<8||15<e)?d:(null!==n.window&&n.wbits!==e&&(n.window=null),n.wrap=i,n.wbits=e,y(t))):d}function b(t,e){var i,n;return t?(n=new g,(t.state=n).window=null,(i=_(t,e))!==h&&(t.state=null),i):d}var v,x,S=!0;function T(t){if(S){var e;for(v=new n.Buf32(512),x=new n.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(a(l,t.lens,0,288,v,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;a(c,t.lens,0,32,x,0,t.work,{bits:5}),S=!1}t.lencode=v,t.lenbits=9,t.distcode=x,t.distbits=5}function C(t,e,i,s){var r,o=t.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new n.Buf8(o.wsize)),s>=o.wsize?(n.arraySet(o.window,e,i-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(s<(r=o.wsize-o.wnext)&&(r=s),n.arraySet(o.window,e,i-s,r,o.wnext),(s-=r)?(n.arraySet(o.window,e,i-s,s,0),o.wnext=s,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=r))),0}i.inflateReset=y,i.inflateReset2=_,i.inflateResetKeep=w,i.inflateInit=function(t){return b(t,15)},i.inflateInit2=b,i.inflate=function(t,e){var i,p,f,g,w,y,_,b,v,x,S,A,E,M,P,z,I,D,k,B,O,V,L,N,F=0,R=new n.Buf8(4),U=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return d;12===(i=t.state).mode&&(i.mode=13),w=t.next_out,f=t.output,_=t.avail_out,g=t.next_in,p=t.input,y=t.avail_in,b=i.hold,v=i.bits,x=y,S=_,V=h;t:for(;;)switch(i.mode){case u:if(0===i.wrap){i.mode=13;break}for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(2&i.wrap&&35615===b){R[i.check=0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0),v=b=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&b)<<8)+(b>>8))%31){t.msg="incorrect header check",i.mode=30;break}if(8!=(15&b)){t.msg="unknown compression method",i.mode=30;break}if(v-=4,O=8+(15&(b>>>=4)),0===i.wbits)i.wbits=O;else if(O>i.wbits){t.msg="invalid window size",i.mode=30;break}i.dmax=1<<O,t.adler=i.check=1,i.mode=512&b?10:12,v=b=0;break;case 2:for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(i.flags=b,8!=(255&i.flags)){t.msg="unknown compression method",i.mode=30;break}if(57344&i.flags){t.msg="unknown header flags set",i.mode=30;break}i.head&&(i.head.text=b>>8&1),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0,i.mode=3;case 3:for(;v<32;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.head&&(i.head.time=b),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,R[2]=b>>>16&255,R[3]=b>>>24&255,i.check=r(i.check,R,4,0)),v=b=0,i.mode=4;case 4:for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.head&&(i.head.xflags=255&b,i.head.os=b>>8),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0,i.mode=5;case 5:if(1024&i.flags){for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.length=b,i.head&&(i.head.extra_len=b),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(y<(A=i.length)&&(A=y),A&&(i.head&&(O=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),n.arraySet(i.head.extra,p,g,A,O)),512&i.flags&&(i.check=r(i.check,p,A,g)),y-=A,g+=A,i.length-=A),i.length))break t;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===y)break t;for(A=0;O=p[g+A++],i.head&&O&&i.length<65536&&(i.head.name+=String.fromCharCode(O)),O&&A<y;);if(512&i.flags&&(i.check=r(i.check,p,A,g)),y-=A,g+=A,O)break t}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===y)break t;for(A=0;O=p[g+A++],i.head&&O&&i.length<65536&&(i.head.comment+=String.fromCharCode(O)),O&&A<y;);if(512&i.flags&&(i.check=r(i.check,p,A,g)),y-=A,g+=A,O)break t}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(b!==(65535&i.check)){t.msg="header crc mismatch",i.mode=30;break}v=b=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),t.adler=i.check=0,i.mode=12;break;case 10:for(;v<32;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}t.adler=i.check=m(b),v=b=0,i.mode=11;case 11:if(0===i.havedict)return t.next_out=w,t.avail_out=_,t.next_in=g,t.avail_in=y,i.hold=b,i.bits=v,2;t.adler=i.check=1,i.mode=12;case 12:if(5===e||6===e)break t;case 13:if(i.last){b>>>=7&v,v-=7&v,i.mode=27;break}for(;v<3;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}switch(i.last=1&b,v-=1,3&(b>>>=1)){case 0:i.mode=14;break;case 1:if(T(i),i.mode=20,6!==e)break;b>>>=2,v-=2;break t;case 2:i.mode=17;break;case 3:t.msg="invalid block type",i.mode=30}b>>>=2,v-=2;break;case 14:for(b>>>=7&v,v-=7&v;v<32;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if((65535&b)!=(b>>>16^65535)){t.msg="invalid stored block lengths",i.mode=30;break}if(i.length=65535&b,v=b=0,i.mode=15,6===e)break t;case 15:i.mode=16;case 16:if(A=i.length){if(y<A&&(A=y),_<A&&(A=_),0===A)break t;n.arraySet(f,p,g,A,w),y-=A,g+=A,_-=A,w+=A,i.length-=A;break}i.mode=12;break;case 17:for(;v<14;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(i.nlen=257+(31&b),b>>>=5,v-=5,i.ndist=1+(31&b),b>>>=5,v-=5,i.ncode=4+(15&b),b>>>=4,v-=4,286<i.nlen||30<i.ndist){t.msg="too many length or distance symbols",i.mode=30;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;v<3;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.lens[U[i.have++]]=7&b,b>>>=3,v-=3}for(;i.have<19;)i.lens[U[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,L={bits:i.lenbits},V=a(0,i.lens,0,19,i.lencode,0,i.work,L),i.lenbits=L.bits,V){t.msg="invalid code lengths set",i.mode=30;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;z=(F=i.lencode[b&(1<<i.lenbits)-1])>>>16&255,I=65535&F,!((P=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(I<16)b>>>=P,v-=P,i.lens[i.have++]=I;else{if(16===I){for(N=P+2;v<N;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(b>>>=P,v-=P,0===i.have){t.msg="invalid bit length repeat",i.mode=30;break}O=i.lens[i.have-1],A=3+(3&b),b>>>=2,v-=2}else if(17===I){for(N=P+3;v<N;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}v-=P,O=0,A=3+(7&(b>>>=P)),b>>>=3,v-=3}else{for(N=P+7;v<N;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}v-=P,O=0,A=11+(127&(b>>>=P)),b>>>=7,v-=7}if(i.have+A>i.nlen+i.ndist){t.msg="invalid bit length repeat",i.mode=30;break}for(;A--;)i.lens[i.have++]=O}}if(30===i.mode)break;if(0===i.lens[256]){t.msg="invalid code -- missing end-of-block",i.mode=30;break}if(i.lenbits=9,L={bits:i.lenbits},V=a(l,i.lens,0,i.nlen,i.lencode,0,i.work,L),i.lenbits=L.bits,V){t.msg="invalid literal/lengths set",i.mode=30;break}if(i.distbits=6,i.distcode=i.distdyn,L={bits:i.distbits},V=a(c,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,L),i.distbits=L.bits,V){t.msg="invalid distances set",i.mode=30;break}if(i.mode=20,6===e)break t;case 20:i.mode=21;case 21:if(6<=y&&258<=_){t.next_out=w,t.avail_out=_,t.next_in=g,t.avail_in=y,i.hold=b,i.bits=v,o(t,S),w=t.next_out,f=t.output,_=t.avail_out,g=t.next_in,p=t.input,y=t.avail_in,b=i.hold,v=i.bits,12===i.mode&&(i.back=-1);break}for(i.back=0;z=(F=i.lencode[b&(1<<i.lenbits)-1])>>>16&255,I=65535&F,!((P=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(z&&!(240&z)){for(D=P,k=z,B=I;z=(F=i.lencode[B+((b&(1<<D+k)-1)>>D)])>>>16&255,I=65535&F,!(D+(P=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}b>>>=D,v-=D,i.back+=D}if(b>>>=P,v-=P,i.back+=P,i.length=I,0===z){i.mode=26;break}if(32&z){i.back=-1,i.mode=12;break}if(64&z){t.msg="invalid literal/length code",i.mode=30;break}i.extra=15&z,i.mode=22;case 22:if(i.extra){for(N=i.extra;v<N;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.length+=b&(1<<i.extra)-1,b>>>=i.extra,v-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;z=(F=i.distcode[b&(1<<i.distbits)-1])>>>16&255,I=65535&F,!((P=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(!(240&z)){for(D=P,k=z,B=I;z=(F=i.distcode[B+((b&(1<<D+k)-1)>>D)])>>>16&255,I=65535&F,!(D+(P=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}b>>>=D,v-=D,i.back+=D}if(b>>>=P,v-=P,i.back+=P,64&z){t.msg="invalid distance code",i.mode=30;break}i.offset=I,i.extra=15&z,i.mode=24;case 24:if(i.extra){for(N=i.extra;v<N;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.offset+=b&(1<<i.extra)-1,b>>>=i.extra,v-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){t.msg="invalid distance too far back",i.mode=30;break}i.mode=25;case 25:if(0===_)break t;if(A=S-_,i.offset>A){if((A=i.offset-A)>i.whave&&i.sane){t.msg="invalid distance too far back",i.mode=30;break}E=A>i.wnext?(A-=i.wnext,i.wsize-A):i.wnext-A,A>i.length&&(A=i.length),M=i.window}else M=f,E=w-i.offset,A=i.length;for(_<A&&(A=_),_-=A,i.length-=A;f[w++]=M[E++],--A;);0===i.length&&(i.mode=21);break;case 26:if(0===_)break t;f[w++]=i.length,_--,i.mode=21;break;case 27:if(i.wrap){for(;v<32;){if(0===y)break t;y--,b|=p[g++]<<v,v+=8}if(S-=_,t.total_out+=S,i.total+=S,S&&(t.adler=i.check=i.flags?r(i.check,f,S,w-S):s(i.check,f,S,w-S)),S=_,(i.flags?b:m(b))!==i.check){t.msg="incorrect data check",i.mode=30;break}v=b=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;v<32;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(b!==(4294967295&i.total)){t.msg="incorrect length check",i.mode=30;break}v=b=0}i.mode=29;case 29:V=1;break t;case 30:V=-3;break t;case 31:return-4;default:return d}return t.next_out=w,t.avail_out=_,t.next_in=g,t.avail_in=y,i.hold=b,i.bits=v,(i.wsize||S!==t.avail_out&&i.mode<30&&(i.mode<27||4!==e))&&C(t,t.output,t.next_out,S-t.avail_out)?(i.mode=31,-4):(x-=t.avail_in,S-=t.avail_out,t.total_in+=x,t.total_out+=S,i.total+=S,i.wrap&&S&&(t.adler=i.check=i.flags?r(i.check,f,S,t.next_out-S):s(i.check,f,S,t.next_out-S)),t.data_type=i.bits+(i.last?64:0)+(12===i.mode?128:0)+(20===i.mode||15===i.mode?256:0),(0==x&&0===S||4===e)&&V===h&&(V=-5),V)},i.inflateEnd=function(t){if(!t||!t.state)return d;var e=t.state;return e.window&&(e.window=null),t.state=null,h},i.inflateGetHeader=function(t,e){var i;return t&&t.state&&2&(i=t.state).wrap?((i.head=e).done=!1,h):d},i.inflateSetDictionary=function(t,e){var i,n=e.length;return t&&t.state?0!==(i=t.state).wrap&&11!==i.mode?d:11===i.mode&&s(1,e,n,0)!==i.check?-3:C(t,e,n,n)?(i.mode=31,-4):(i.havedict=1,h):d},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(t,e,i){var n=t("../utils/common"),s=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],r=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],o=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];e.exports=function(t,e,i,l,c,h,d,u){var p,f,m,g,w,y,_,b,v,x=u.bits,S=0,T=0,C=0,A=0,E=0,M=0,P=0,z=0,I=0,D=0,k=null,B=0,O=new n.Buf16(16),V=new n.Buf16(16),L=null,N=0;for(S=0;S<=15;S++)O[S]=0;for(T=0;T<l;T++)O[e[i+T]]++;for(E=x,A=15;1<=A&&0===O[A];A--);if(A<E&&(E=A),0===A)return c[h++]=20971520,c[h++]=20971520,u.bits=1,0;for(C=1;C<A&&0===O[C];C++);for(E<C&&(E=C),S=z=1;S<=15;S++)if(z<<=1,(z-=O[S])<0)return-1;if(0<z&&(0===t||1!==A))return-1;for(V[1]=0,S=1;S<15;S++)V[S+1]=V[S]+O[S];for(T=0;T<l;T++)0!==e[i+T]&&(d[V[e[i+T]]++]=T);if(y=0===t?(k=L=d,19):1===t?(k=s,B-=257,L=r,N-=257,256):(k=o,L=a,-1),S=C,w=h,P=T=D=0,m=-1,g=(I=1<<(M=E))-1,1===t&&852<I||2===t&&592<I)return 1;for(;;){for(_=S-P,v=d[T]<y?(b=0,d[T]):d[T]>y?(b=L[N+d[T]],k[B+d[T]]):(b=96,0),p=1<<S-P,C=f=1<<M;c[w+(D>>P)+(f-=p)]=_<<24|b<<16|v,0!==f;);for(p=1<<S-1;D&p;)p>>=1;if(0!==p?(D&=p-1,D+=p):D=0,T++,0==--O[S]){if(S===A)break;S=e[i+d[T]]}if(E<S&&(D&g)!==m){for(0===P&&(P=E),w+=C,z=1<<(M=S-P);M+P<A&&!((z-=O[M+P])<=0);)M++,z<<=1;if(I+=1<<M,1===t&&852<I||2===t&&592<I)return 1;c[m=D&g]=E<<24|M<<16|w-h}}return 0!==D&&(c[w+D]=S-P<<24|64<<16),u.bits=E,0}},{"../utils/common":41}],51:[function(t,e,i){e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(t,e,i){var n=t("../utils/common"),s=0,r=1;function o(t){for(var e=t.length;0<=--e;)t[e]=0}var a=0,l=29,c=256,h=c+1+l,d=30,u=19,p=2*h+1,f=15,m=16,g=7,w=256,y=16,_=17,b=18,v=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],x=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],S=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],T=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],C=new Array(2*(h+2));o(C);var A=new Array(2*d);o(A);var E=new Array(512);o(E);var M=new Array(256);o(M);var P=new Array(l);o(P);var z,I,D,k=new Array(d);function B(t,e,i,n,s){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=n,this.max_length=s,this.has_stree=t&&t.length}function O(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function V(t){return t<256?E[t]:E[256+(t>>>7)]}function L(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function N(t,e,i){t.bi_valid>m-i?(t.bi_buf|=e<<t.bi_valid&65535,L(t,t.bi_buf),t.bi_buf=e>>m-t.bi_valid,t.bi_valid+=i-m):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)}function F(t,e,i){N(t,i[2*e],i[2*e+1])}function R(t,e){for(var i=0;i|=1&t,t>>>=1,i<<=1,0<--e;);return i>>>1}function U(t,e,i){var n,s,r=new Array(f+1),o=0;for(n=1;n<=f;n++)r[n]=o=o+i[n-1]<<1;for(s=0;s<=e;s++){var a=t[2*s+1];0!==a&&(t[2*s]=R(r[a]++,a))}}function j(t){var e;for(e=0;e<h;e++)t.dyn_ltree[2*e]=0;for(e=0;e<d;e++)t.dyn_dtree[2*e]=0;for(e=0;e<u;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*w]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function $(t){8<t.bi_valid?L(t,t.bi_buf):0<t.bi_valid&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function W(t,e,i,n){var s=2*e,r=2*i;return t[s]<t[r]||t[s]===t[r]&&n[e]<=n[i]}function G(t,e,i){for(var n=t.heap[i],s=i<<1;s<=t.heap_len&&(s<t.heap_len&&W(e,t.heap[s+1],t.heap[s],t.depth)&&s++,!W(e,n,t.heap[s],t.depth));)t.heap[i]=t.heap[s],i=s,s<<=1;t.heap[i]=n}function H(t,e,i){var n,s,r,o,a=0;if(0!==t.last_lit)for(;n=t.pending_buf[t.d_buf+2*a]<<8|t.pending_buf[t.d_buf+2*a+1],s=t.pending_buf[t.l_buf+a],a++,0===n?F(t,s,e):(F(t,(r=M[s])+c+1,e),0!==(o=v[r])&&N(t,s-=P[r],o),F(t,r=V(--n),i),0!==(o=x[r])&&N(t,n-=k[r],o)),a<t.last_lit;);F(t,w,e)}function q(t,e){var i,n,s,r=e.dyn_tree,o=e.stat_desc.static_tree,a=e.stat_desc.has_stree,l=e.stat_desc.elems,c=-1;for(t.heap_len=0,t.heap_max=p,i=0;i<l;i++)0!==r[2*i]?(t.heap[++t.heap_len]=c=i,t.depth[i]=0):r[2*i+1]=0;for(;t.heap_len<2;)r[2*(s=t.heap[++t.heap_len]=c<2?++c:0)]=1,t.depth[s]=0,t.opt_len--,a&&(t.static_len-=o[2*s+1]);for(e.max_code=c,i=t.heap_len>>1;1<=i;i--)G(t,r,i);for(s=l;i=t.heap[1],t.heap[1]=t.heap[t.heap_len--],G(t,r,1),n=t.heap[1],t.heap[--t.heap_max]=i,t.heap[--t.heap_max]=n,r[2*s]=r[2*i]+r[2*n],t.depth[s]=(t.depth[i]>=t.depth[n]?t.depth[i]:t.depth[n])+1,r[2*i+1]=r[2*n+1]=s,t.heap[1]=s++,G(t,r,1),2<=t.heap_len;);t.heap[--t.heap_max]=t.heap[1],function(t,e){var i,n,s,r,o,a,l=e.dyn_tree,c=e.max_code,h=e.stat_desc.static_tree,d=e.stat_desc.has_stree,u=e.stat_desc.extra_bits,m=e.stat_desc.extra_base,g=e.stat_desc.max_length,w=0;for(r=0;r<=f;r++)t.bl_count[r]=0;for(l[2*t.heap[t.heap_max]+1]=0,i=t.heap_max+1;i<p;i++)g<(r=l[2*l[2*(n=t.heap[i])+1]+1]+1)&&(r=g,w++),l[2*n+1]=r,c<n||(t.bl_count[r]++,o=0,m<=n&&(o=u[n-m]),a=l[2*n],t.opt_len+=a*(r+o),d&&(t.static_len+=a*(h[2*n+1]+o)));if(0!==w){do{for(r=g-1;0===t.bl_count[r];)r--;t.bl_count[r]--,t.bl_count[r+1]+=2,t.bl_count[g]--,w-=2}while(0<w);for(r=g;0!==r;r--)for(n=t.bl_count[r];0!==n;)c<(s=t.heap[--i])||(l[2*s+1]!==r&&(t.opt_len+=(r-l[2*s+1])*l[2*s],l[2*s+1]=r),n--)}}(t,e),U(r,c,t.bl_count)}function Z(t,e,i){var n,s,r=-1,o=e[1],a=0,l=7,c=4;for(0===o&&(l=138,c=3),e[2*(i+1)+1]=65535,n=0;n<=i;n++)s=o,o=e[2*(n+1)+1],++a<l&&s===o||(a<c?t.bl_tree[2*s]+=a:0!==s?(s!==r&&t.bl_tree[2*s]++,t.bl_tree[2*y]++):a<=10?t.bl_tree[2*_]++:t.bl_tree[2*b]++,r=s,c=(a=0)===o?(l=138,3):s===o?(l=6,3):(l=7,4))}function Y(t,e,i){var n,s,r=-1,o=e[1],a=0,l=7,c=4;for(0===o&&(l=138,c=3),n=0;n<=i;n++)if(s=o,o=e[2*(n+1)+1],!(++a<l&&s===o)){if(a<c)for(;F(t,s,t.bl_tree),0!=--a;);else 0!==s?(s!==r&&(F(t,s,t.bl_tree),a--),F(t,y,t.bl_tree),N(t,a-3,2)):a<=10?(F(t,_,t.bl_tree),N(t,a-3,3)):(F(t,b,t.bl_tree),N(t,a-11,7));r=s,c=(a=0)===o?(l=138,3):s===o?(l=6,3):(l=7,4)}}o(k);var X=!1;function K(t,e,i,s){var r,o,l;N(t,(a<<1)+(s?1:0),3),o=e,l=i,$(r=t),L(r,l),L(r,~l),n.arraySet(r.pending_buf,r.window,o,l,r.pending),r.pending+=l}i._tr_init=function(t){X||(function(){var t,e,i,n,s,r=new Array(f+1);for(n=i=0;n<l-1;n++)for(P[n]=i,t=0;t<1<<v[n];t++)M[i++]=n;for(M[i-1]=n,n=s=0;n<16;n++)for(k[n]=s,t=0;t<1<<x[n];t++)E[s++]=n;for(s>>=7;n<d;n++)for(k[n]=s<<7,t=0;t<1<<x[n]-7;t++)E[256+s++]=n;for(e=0;e<=f;e++)r[e]=0;for(t=0;t<=143;)C[2*t+1]=8,t++,r[8]++;for(;t<=255;)C[2*t+1]=9,t++,r[9]++;for(;t<=279;)C[2*t+1]=7,t++,r[7]++;for(;t<=287;)C[2*t+1]=8,t++,r[8]++;for(U(C,h+1,r),t=0;t<d;t++)A[2*t+1]=5,A[2*t]=R(t,5);z=new B(C,v,c+1,h,f),I=new B(A,x,0,d,f),D=new B(new Array(0),S,0,u,g)}(),X=!0),t.l_desc=new O(t.dyn_ltree,z),t.d_desc=new O(t.dyn_dtree,I),t.bl_desc=new O(t.bl_tree,D),t.bi_buf=0,t.bi_valid=0,j(t)},i._tr_stored_block=K,i._tr_flush_block=function(t,e,i,n){var o,a,l=0;0<t.level?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return s;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return r;for(e=32;e<c;e++)if(0!==t.dyn_ltree[2*e])return r;return s}(t)),q(t,t.l_desc),q(t,t.d_desc),l=function(t){var e;for(Z(t,t.dyn_ltree,t.l_desc.max_code),Z(t,t.dyn_dtree,t.d_desc.max_code),q(t,t.bl_desc),e=u-1;3<=e&&0===t.bl_tree[2*T[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),o=t.opt_len+3+7>>>3,(a=t.static_len+3+7>>>3)<=o&&(o=a)):o=a=i+5,i+4<=o&&-1!==e?K(t,e,i,n):4===t.strategy||a===o?(N(t,2+(n?1:0),3),H(t,C,A)):(N(t,4+(n?1:0),3),function(t,e,i,n){var s;for(N(t,e-257,5),N(t,i-1,5),N(t,n-4,4),s=0;s<n;s++)N(t,t.bl_tree[2*T[s]+1],3);Y(t,t.dyn_ltree,e-1),Y(t,t.dyn_dtree,i-1)}(t,t.l_desc.max_code+1,t.d_desc.max_code+1,l+1),H(t,t.dyn_ltree,t.dyn_dtree)),j(t),n&&$(t)},i._tr_tally=function(t,e,i){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&i,t.last_lit++,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(M[i]+c+1)]++,t.dyn_dtree[2*V(e)]++),t.last_lit===t.lit_bufsize-1},i._tr_align=function(t){var e;N(t,2,3),F(t,w,C),16===(e=t).bi_valid?(L(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}},{"../utils/common":41}],53:[function(t,e,i){e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(t,e,i){(function(t){!function(t,e){if(!t.setImmediate){var i,n,s,r,o=1,a={},l=!1,c=t.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(t);h=h&&h.setTimeout?h:t,i="[object process]"==={}.toString.call(t.process)?function(t){process.nextTick(function(){u(t)})}:function(){if(t.postMessage&&!t.importScripts){var e=!0,i=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=i,e}}()?(r="setImmediate$"+Math.random()+"$",t.addEventListener?t.addEventListener("message",p,!1):t.attachEvent("onmessage",p),function(e){t.postMessage(r+e,"*")}):t.MessageChannel?((s=new MessageChannel).port1.onmessage=function(t){u(t.data)},function(t){s.port2.postMessage(t)}):c&&"onreadystatechange"in c.createElement("script")?(n=c.documentElement,function(t){var e=c.createElement("script");e.onreadystatechange=function(){u(t),e.onreadystatechange=null,n.removeChild(e),e=null},n.appendChild(e)}):function(t){setTimeout(u,0,t)},h.setImmediate=function(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),n=0;n<e.length;n++)e[n]=arguments[n+1];var s={callback:t,args:e};return a[o]=s,i(o),o++},h.clearImmediate=d}function d(t){delete a[t]}function u(t){if(l)setTimeout(u,0,t);else{var i=a[t];if(i){l=!0;try{!function(t){var i=t.callback,n=t.args;switch(n.length){case 0:i();break;case 1:i(n[0]);break;case 2:i(n[0],n[1]);break;case 3:i(n[0],n[1],n[2]);break;default:i.apply(e,n)}}(i)}finally{d(t),l=!1}}}}function p(e){e.source===t&&"string"==typeof e.data&&0===e.data.indexOf(r)&&u(+e.data.slice(r.length))}}("undefined"==typeof self?void 0===t?this:t:self)}).call(this,void 0!==qo?qo:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10));class Qo{constructor(t,i){e(this,"date",new Date),e(this,"author"),e(this,"guid",_t.create()),e(this,"viewpoint"),e(this,"modifiedAuthor"),e(this,"modifiedDate"),e(this,"topic"),e(this,"_components"),e(this,"_comment",""),this._components=t,this._comment=i;const n=this._components.get(sa);this.author=n.config.author}set comment(t){var e;const i=this._components.get(sa);this._comment=t,this.modifiedDate=new Date,this.modifiedAuthor=i.config.author,null==(e=this.topic)||e.comments.set(this.guid,this)}get comment(){return this._comment}toJSON(){var t,e;const i={guid:this.guid,date:this.date.toISOString(),author:this.author,comment:this.comment,topic_guid:null==(t=this.topic)?void 0:t.guid,viewpoint_guid:this.viewpoint,modified_date:null==(e=this.modifiedDate)?void 0:e.toISOString(),modified_author:this.modifiedAuthor};for(const[t,e]of Object.entries(i))void 0===e&&delete i[t];return i}}const Jo=class t{constructor(i){e(this,"guid",_t.create()),e(this,"title",t.default.title),e(this,"creationDate",new Date),e(this,"creationAuthor",""),e(this,"viewpoints",new r),e(this,"relatedTopics",new r),e(this,"comments",new n),e(this,"documentReferences",new r),e(this,"customData",{}),e(this,"description"),e(this,"serverAssignedId"),e(this,"dueDate"),e(this,"modifiedAuthor"),e(this,"modifiedDate"),e(this,"index"),e(this,"_type",t.default.type),e(this,"_status",t.default.status),e(this,"_priority",t.default.priority),e(this,"_stage",t.default.stage),e(this,"_assignedTo",t.default.assignedTo),e(this,"_labels",t.default.labels??new Set),e(this,"_components"),this._components=i;const s=i.get(sa);this.creationAuthor=s.config.author,this.relatedTopics.guard=t=>t!==this.guid}set type(t){const e=this._components.get(sa),{strict:i,types:n}=e.config;(!i||n.has(t))&&(this._type=t)}get type(){return this._type}set status(t){const e=this._components.get(sa),{strict:i,statuses:n}=e.config;(!i||n.has(t))&&(this._status=t)}get status(){return this._status}set priority(t){const e=this._components.get(sa);if(t){const{strict:i,priorities:n}=e.config;if(!(!i||n.has(t)))return;this._priority=t}else this._priority=t}get priority(){return this._priority}set stage(t){const e=this._components.get(sa);if(t){const{strict:i,stages:n}=e.config;if(!(!i||n.has(t)))return;this._stage=t}else this._stage=t}get stage(){return this._stage}set assignedTo(t){const e=this._components.get(sa);if(t){const{strict:i,users:n}=e.config;if(!(!i||n.has(t)))return;this._assignedTo=t}else this._assignedTo=t}get assignedTo(){return this._assignedTo}set labels(t){const e=this._components.get(sa),{strict:i,labels:n}=e.config;if(i){const e=new Set;for(const s of t){(!i||n.has(s))&&e.add(s)}this._labels=e}else this._labels=t}get labels(){return this._labels}get _managerVersion(){return this._components.get(sa).config.version}set(t){const e=t,i=this;for(const n in t){if("guid"===n)continue;const t=e[n];n in this&&(i[n]=t)}return this._components.get(sa).list.set(this.guid,this),this}createComment(t,e){const i=new Qo(this._components,t);return i.viewpoint=e,i.topic=this,this.comments.set(i.guid,i),i}createLabelTags(){const t=[...this.labels];if(this._components.get(sa).config.exportCustomDataAsLabels)for(const e in this.customData){const i=this.customData[e];"string"==typeof i&&t.push(i)}return t}createCommentTags(){return[...this.comments.values()].map(t=>{var e;return{$Guid:t.guid,Date:t.date.toISOString(),Author:t.author,Comment:t.comment,ModifiedAuthor:t.modifiedAuthor,ModifiedDate:null==(e=t.modifiedDate)?void 0:e.toISOString(),Viewpoint:t.viewpoint?{$Guid:t.viewpoint}:void 0}})}createViewpointTags(){const t=this._components.get(ua);return[...this.viewpoints].map(e=>t.list.get(e)).filter(t=>t).map(e=>{const i={$Guid:e.guid,Viewpoint:`${e.title??e.guid}.bcfv`};if(t.snapshots.get(e.snapshot)){const n=t.getSnapshotExtension(e.snapshot);i.Snapshot=`${e.snapshot}.${n}`}return i})}createRelatedTopicTags(){return[...this.relatedTopics].map(t=>({$Guid:t}))}createDocumentReferencesTag(t=this._managerVersion){const e=[];if("3"!==t&&"2.1"!==t)return e;const i=this._components.get(sa);for(const n of this.documentReferences){const s=i.documents.get(n);if(!s)continue;let r={$Guid:_t.create(),Description:s.description};"2.1"===t&&(r={...r,$isExternal:"external"===s.type||void 0,ReferencedDocument:"external"===s.type?s.url:`../${s.fileName}`}),"3"===t&&(r={...r,DocumentGuid:"internal"===s.type?n:void 0,Url:"external"===s.type?s.url:void 0}),Object.keys(r).length>0&&e.push(r)}return e}toJSON(){var t,e;const i={guid:this.guid,server_assigned_id:this.serverAssignedId,topic_type:this.type,topic_status:this.status,title:this.title,priority:this.priority,index:this.index,labels:[...this.labels],creation_date:this.creationDate.toISOString(),creation_author:this.creationAuthor,modified_date:null==(t=this.modifiedDate)?void 0:t.toISOString(),modified_author:this.modifiedAuthor,assigned_to:this.assignedTo,stage:this.stage,description:this.description,due_date:null==(e=this.dueDate)?void 0:e.toISOString(),comments:[...this.comments].map(([t,e])=>e.toJSON()),relatedTopics:[...this.relatedTopics].map(t=>({related_topic_guid:t}))},n=this._components.get(ua);for(const t of this.viewpoints){const e=n.list.get(t);e&&(i.viewpoints||(i.viewpoints=[]),i.viewpoints.push(e.toJSON()))}const s=this._components.get(sa);for(const t of this.documentReferences){const e=s.documents.get(t);e&&(i.document_references||(i.document_references=[]),"external"===e.type?i.document_references.push({guid:_t.create(),description:e.description,url:e.url}):i.document_references.push({guid:_t.create(),description:e.description,document_guid:t}))}for(const[t,e]of Object.entries(i))(void 0===e||Array.isArray(e)&&0===e.length)&&delete i[t];return i}serialize(){var t,e;const i=this._managerVersion,n={$Guid:this.guid,$TopicType:this.type,$TopicStatus:this.status,$ServerAssignedId:this.serverAssignedId,Title:this.title,CreationAuthor:this.creationAuthor,CreationDate:this.creationDate.toISOString(),Priority:this.priority,Index:"2.1"===i?this.index:void 0,ModifiedDate:null==(t=this.modifiedDate)?void 0:t.toISOString(),ModifiedAuthor:this.modifiedAuthor,DueDate:null==(e=this.dueDate)?void 0:e.toISOString(),AssignedTo:this.assignedTo,Description:this.description,Stage:this.stage,DocumentReferences:"3"===i?{DocumentReference:this.createDocumentReferencesTag(i)}:void 0,RelatedTopics:"3"===i?{RelatedTopic:this.createRelatedTopicTags()}:void 0,RelatedTopic:"2.1"===i?this.createRelatedTopicTags():void 0,Labels:"3"===i?{Label:this.createLabelTags()}:void 0,Viewpoints:"3"===i?{ViewPoint:this.createViewpointTags()}:void 0,Comments:"3"===i?{Comment:this.createCommentTags()}:void 0};"2.1"===i&&(n.Labels=this.createLabelTags(),n.DocumentReference=this.createDocumentReferencesTag(i));const s={Markup:{Topic:n}};return"2.1"===i&&(s.Markup.Viewpoints=this.createViewpointTags(),s.Markup.Comment=this.createCommentTags()),`<?xml version="1.0" encoding="UTF-8"?>\n ${Be.builder.build(s)}`}};e(Jo,"default",{title:"BCF Topic",type:"Issue",status:"Active"});let ta=Jo;const ea=(t,e)=>{if(""===e.trim())return;const i=sa.xmlParser.parse(e).Extensions;if(!i)return;const{Priorities:n,TopicStatuses:s,TopicTypes:r,Users:o}=i;if(n&&n.Priority){const e=Array.isArray(n.Priority)?n.Priority:[n.Priority];for(const i of e)t.config.priorities.add(i)}if(s&&s.TopicStatus){const e=Array.isArray(s.TopicStatus)?s.TopicStatus:[s.TopicStatus];for(const i of e)t.config.statuses.add(i)}if(r&&r.TopicType){const e=Array.isArray(r.TopicType)?r.TopicType:[r.TopicType];for(const i of e)t.config.types.add(i)}if(o&&o.User){const e=Array.isArray(o.User)?o.User:[o.User];for(const i of e)t.config.users.add(i)}};class ia extends Re{constructor(){super(...arguments),e(this,"_config",{version:{type:"Select",options:new Set(["2.1","3"]),multiple:!1,value:""},author:{type:"Text",value:""},types:{type:"TextSet",value:new Set},statuses:{type:"TextSet",value:new Set},priorities:{type:"TextSet",value:new Set},labels:{type:"TextSet",value:new Set},stages:{type:"TextSet",value:new Set},users:{type:"TextSet",value:new Set},includeSelectionTag:{type:"Boolean",value:!1},updateExtensionsOnImport:{type:"Boolean",value:!1},strict:{type:"Boolean",value:!1},includeAllExtensionsOnExport:{type:"Boolean",value:!1},fallbackVersionOnImport:{type:"Select",multiple:!1,options:new Set(["2.1","3"]),value:""},ignoreIncompleteTopicsOnImport:{type:"Boolean",value:!1},exportCustomDataAsLabels:{type:"Boolean",value:!1}})}get version(){return this._config.version.value}set version(t){this._config.version.value=t}get author(){return this._config.author.value}set author(t){this._config.author.value=t}get types(){return this._config.types.value}set types(t){this._config.types.value=t}get statuses(){return this._config.statuses.value}set statuses(t){this._config.statuses.value=t}get priorities(){return this._config.priorities.value}set priorities(t){this._config.priorities.value=t}get labels(){return this._config.labels.value}set labels(t){this._config.labels.value=t}get stages(){return this._config.stages.value}set stages(t){this._config.stages.value=t}get users(){return this._config.users.value}set users(t){this._config.users.value=t}get includeSelectionTag(){return this._config.includeSelectionTag.value}set includeSelectionTag(t){this._config.includeSelectionTag.value=t}get updateExtensionsOnImport(){return this._config.updateExtensionsOnImport.value}set updateExtensionsOnImport(t){this._config.updateExtensionsOnImport.value=t}get strict(){return this._config.strict.value}set strict(t){this._config.strict.value=t}get includeAllExtensionsOnExport(){return this._config.includeAllExtensionsOnExport.value}set includeAllExtensionsOnExport(t){this._config.includeAllExtensionsOnExport.value=t}get fallbackVersionOnImport(){return this._config.fallbackVersionOnImport.value}set fallbackVersionOnImport(t){this._config.fallbackVersionOnImport.value=t}get ignoreIncompleteTopicsOnImport(){return this._config.ignoreIncompleteTopicsOnImport.value}set ignoreIncompleteTopicsOnImport(t){this._config.ignoreIncompleteTopicsOnImport.value=t}get exportCustomDataAsLabels(){return this._config.exportCustomDataAsLabels.value}set exportCustomDataAsLabels(t){this._config.exportCustomDataAsLabels.value=t}}const na=class t extends ht{constructor(){super(...arguments),e(this,"enabled",!1),e(this,"_defaultConfig",{author:"jhon.doe@example.com",version:"2.1",types:new Set(["Clash","Failure","Fault","Inquiry","Issue","Remark","Request"]),statuses:new Set(["Active","In Progress","Done","In Review","Closed"]),priorities:new Set(["On hold","Minor","Normal","Major","Critical"]),labels:new Set,stages:new Set,users:new Set,includeSelectionTag:!1,updateExtensionsOnImport:!0,strict:!1,includeAllExtensionsOnExport:!0,fallbackVersionOnImport:"2.1",ignoreIncompleteTopicsOnImport:!1,exportCustomDataAsLabels:!1}),e(this,"config",new ia(this,this.components,"BCF Topics",t.uuid)),e(this,"list",new n),e(this,"documents",new n),e(this,"onSetup",new at),e(this,"isSetup",!1),e(this,"onBCFImported",new at),e(this,"onDisposed",new at)}setup(t){if(this.isSetup)return;const e={...this._defaultConfig,...t};this.config.version=e.version,this.config.author=e.author,this.config.types=e.types,this.config.statuses=e.statuses,this.config.priorities=e.priorities,this.config.labels=e.labels,this.config.stages=e.stages,this.config.users=e.users,this.config.includeSelectionTag=e.includeSelectionTag,this.config.updateExtensionsOnImport=e.updateExtensionsOnImport,this.config.strict=e.strict,this.config.includeAllExtensionsOnExport=e.includeAllExtensionsOnExport,this.config.fallbackVersionOnImport=e.fallbackVersionOnImport||"",this.config.ignoreIncompleteTopicsOnImport=e.ignoreIncompleteTopicsOnImport,this.isSetup=!0,this.enabled=!0,this.onSetup.trigger()}create(t){const e=new ta(this.components);return t?(e.guid=t.guid??e.guid,e.set(t)):this.list.set(e.guid,e),e}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}get usedTypes(){const t=[...this.list].map(([t,e])=>e.type);return new Set(t)}get usedStatuses(){const t=[...this.list].map(([t,e])=>e.status);return new Set(t)}get usedPriorities(){const t=[...this.list].map(([t,e])=>e.priority).filter(t=>t);return new Set(t)}get usedStages(){const t=[...this.list].map(([t,e])=>e.stage).filter(t=>t);return new Set(t)}get usedUsers(){const t=[];for(const[e,i]of this.list){t.push(i.creationAuthor),i.assignedTo&&t.push(i.assignedTo),i.modifiedAuthor&&t.push(i.modifiedAuthor);for(const[e,n]of i.comments)t.push(n.author),n.modifiedAuthor&&t.push(n.modifiedAuthor)}return new Set(t)}get usedLabels(){const t=[];for(const[e,i]of this.list)t.push(...i.labels);return new Set(t)}updateExtensions(){for(const[t,e]of this.list){for(const t of e.labels)this.config.labels.add(t);this.config.types.add(e.type),e.priority&&this.config.priorities.add(e.priority),e.stage&&this.config.stages.add(e.stage),this.config.statuses.add(e.status),this.config.users.add(e.creationAuthor),e.assignedTo&&this.config.users.add(e.assignedTo),e.modifiedAuthor&&this.config.users.add(e.modifiedAuthor);for(const[t,i]of e.comments)this.config.users.add(i.author),i.modifiedAuthor&&this.config.users.add(i.modifiedAuthor)}}updateViewpointReferences(){const t=this.components.get(ua);for(const[e,i]of this.list)for(const e of i.viewpoints){t.list.has(e)||i.viewpoints.delete(e)}}async export(t=this.list.values()){const e=new Ko;e.file("bcf.version",`<?xml version="1.0" encoding="UTF-8"?>\n <Version VersionId="${this.config.version}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/release_3_0/Schemas/version.xsd"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n </Version>`);for(const[t,i]of this.documents.entries())"external"!==i.type&&e.file("2.1"===this.config.version?i.fileName:`documents/${t}`,i.data);if("3"===this.config.version){const t=[];for(const[e,i]of this.documents.entries()){const{type:n,description:s}=i;"external"!==n&&t.push(`<Document Guid="${e}">\n <Filename>${i.fileName}</Filename>\n ${s?`<Description>${s}</Description>`:""}\n </Document>`)}t.length>0&&e.file("documents.xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n <DocumentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="documents.xsd">\n <Documents>\n ${t.join("\n")}\n </Documents>\n </DocumentInfo>`)}e.file("bcf.extensions",this.serializeExtensions());const i=this.components.get(ua);for(const n of t){const t=e.folder(n.guid);t.file("markup.bcf",n.serialize());for(const e of n.viewpoints){const n=i.list.get(e);if(!n)continue;const s=n.title??n.guid;t.file(`${s}.bcfv`,await n.serialize());const r=i.snapshots.get(n.snapshot);if(!r)continue;const o=r?n.snapshot:n.guid,a=i.getSnapshotExtension(n.snapshot);t.file(`${o}.${a}`,r,{binary:!0})}}return await e.generateAsync({type:"blob"})}serializeExtensions(){const t=[...this.config.types].map(t=>`<TopicType>${t}</TopicType>`).join("\n"),e=[...this.config.statuses].map(t=>`<TopicStatus>${t}</TopicStatus>`).join("\n"),i=[...this.config.priorities].map(t=>`<Priority>${t}</Priority>`).join("\n"),n=[...this.config.labels].map(t=>`<TopicLabel>${t}</TopicLabel>`).join("\n"),s=[...this.config.stages].map(t=>`<Stage>${t}</Stage>`).join("\n"),r=[...this.config.users].map(t=>`<User>${t}</User>`).join("\n");return`\n <?xml version="1.0" encoding="UTF-8"?>\n <Extensions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-schema-location.xsd">\n ${0!==t.length?`<TopicTypes>\n${t}\n</TopicTypes>`:""}\n ${0!==e.length?`<TopicStatuses>\n${e}\n</TopicStatuses>`:""}\n ${0!==i.length?`<Priorities>\n${i}\n</Priorities>`:""}\n ${0!==n.length?`<TopicLabels>\n${n}\n</TopicLabels>`:""}\n ${0!==s.length?`<Stages>\n${s}\n</Stages>`:""}\n ${0!==r.length?`<Users>\n${r}\n</Users>`:""}\n </Extensions>\n `}processMarkupComment(t){const{Guid:e,Date:i,Author:n,Comment:s,Viewpoint:r}=t;if(!(e&&i&&n&&(Qo||r)))return null;const o=new Qo(this.components,s??"");return o.guid=e,o.date=new Date(i),o.author=n,o.viewpoint=null==r?void 0:r.Guid,o.modifiedAuthor=t.ModifiedAuthor,o.modifiedDate=t.ModifiedDate?new Date(t.ModifiedDate):void 0,o}getMarkupComments(t,e){var i;let n;if("2.1"===e&&(n=t.Comment),"3"===e&&(n=null==(i=t.Topic.Comments)?void 0:i.Comment),!n)return[];n=Array.isArray(n)?n:[n];const s=n.map(t=>this.processMarkupComment(t)).filter(t=>t);return Array.isArray(s)?s:[s]}getMarkupLabels(t,e){var i;let n;if("2.1"===e&&(n=t.Topic.Labels),"3"===e&&(n=null==(i=t.Topic.Labels)?void 0:i.Label),!n)return[];return Array.isArray(n)?n:[n]}getMarkupViewpoints(t,e){var i;let n;return"2.1"===e&&(n=t.Viewpoints),"3"===e&&(n=null==(i=t.Topic.Viewpoints)?void 0:i.ViewPoint),n?(n=Array.isArray(n)?n:[n],n):[]}getMarkupRelatedTopics(t,e){var i;let n;if("2.1"===e&&(n=t.Topic.RelatedTopic),"3"===e&&(n=null==(i=t.Topic.RelatedTopics)?void 0:i.RelatedTopic),!n)return[];return(Array.isArray(n)?n:[n]).map(t=>t.Guid)}getMarkupDocumentReferences(t,e){var i;let n;if("2.1"===e&&(n=t.Topic.DocumentReference),"3"===e&&(n=null==(i=t.Topic.DocumentReferences)?void 0:i.DocumentReference),!n)return[];return Array.isArray(n)?n:[n]}async load(e){var i,n,s;const{fallbackVersionOnImport:r,ignoreIncompleteTopicsOnImport:a,updateExtensionsOnImport:l}=this.config,c=new Ko;await c.loadAsync(e);const h=Object.values(c.files);let d=r;const u=h.find(t=>t.name.endsWith(".version"));if(u){const e=await u.async("string"),i=t.xmlParser.parse(e).Version.VersionId;d=String(i)}if(!d||"2.1"!==d&&"3"!==d)throw new Error(`BCFTopics: ${d} is not supported.`);const p=h.find(t=>t.name.endsWith(".extensions"));if(l&&p){const t=await p.async("string");ea(this,t)}const f=[],m=this.components.get(ua),g=h.filter(t=>t.name.endsWith(".bcfv"));for(const e of g){const n=await e.async("string"),s=t.xmlParser.parse(n).VisualizationInfo;if(!s){console.warn("Missing VisualizationInfo in Viewpoint");continue}const r={},{Guid:a,ClippingPlanes:l,Components:c,OrthogonalCamera:h,PerspectiveCamera:u}=s;if(a&&(r.guid=a),c){const t={selection:[],coloring:[],visibility:{default_visibility:!1,exceptions:[],view_setup_hints:{spaces_visible:!1,space_boundaries_visible:!1,openings_visible:!1}}};r.components=t;const{Selection:e,Visibility:n}=c;if(e&&e.Component){const i=Array.isArray(e.Component)?e.Component:[e.Component];t.selection=i.map(t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null).filter(t=>null!==t)}if(n&&"DefaultVisibility"in n&&(t.visibility.default_visibility=n.DefaultVisibility),n&&n.Exceptions&&"Component"in n.Exceptions){const{Component:e}=n.Exceptions,i=Array.isArray(e)?e:[e];t.visibility.exceptions=i.map(t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null).filter(t=>null!==t)}let s;"2.1"===d&&(s=c.ViewSetupHints),"3"===d&&(s=null==(i=c.Visibility)?void 0:i.ViewSetupHints),s&&("OpeningsVisible"in s&&(t.visibility.view_setup_hints.openings_visible=s.OpeningsVisible),"SpacesVisible"in s&&(t.visibility.view_setup_hints.spaces_visible=s.SpacesVisible),"SpaceBoundariesVisible"in s&&(t.visibility.view_setup_hints.space_boundaries_visible=s.SpaceBoundariesVisible));const{Coloring:o}=c;if(o&&o.Color){const e=Array.isArray(o.Color)?o.Color:[o.Color];for(const i of e){const{Color:e,Component:n}=i;if(6!==e.length&&8!==e.length)continue;const s=6===e.length?e:e.slice(2),r=(Array.isArray(n)?n:[n]).map(t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null).filter(t=>null!==t);t.coloring.push({color:s,components:r})}}}if(h||u){const t=s.PerspectiveCamera??s.OrthogonalCamera,{CameraViewPoint:e,CameraDirection:i}=t,n=new o.Vector3(Number(e.X),Number(e.Z),Number(-e.Y)),a=new o.Vector3(Number(i.X),Number(i.Z),Number(-i.Y)),l={camera_view_point:{x:n.x,y:n.y,z:n.z},camera_direction:{x:a.x,y:a.y,z:a.z},aspect_ratio:"AspectRatio"in t?t.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in t&&(r.orthogonal_camera={...l,view_to_world_scale:t.ViewToWorldScale}),"FieldOfView"in t&&(r.perspective_camera={...l,field_of_view:t.FieldOfView})}if(l){const t=(Array.isArray(l.ClippingPlane)?l.ClippingPlane:[l.ClippingPlane]).map(({Location:t,Direction:e})=>({location:{x:t.x,y:t.y,z:t.z},direction:{x:e.x,y:e.y,z:e.z}}));r.clipping_planes=t}const p=new ca(this.components,r);f.push(p)}const w={},y=[],_=h.filter(t=>t.name.endsWith(".bcf"));for(const e of _){const i=await e.async("string"),r=t.xmlParser.parse(i).Markup,o=r.Topic,{Guid:l,TopicType:c,TopicStatus:u,Title:p,CreationDate:f,CreationAuthor:g}=o;if(a&&!(l&&c&&u&&p&&f&&g))continue;const _=new ta(this.components);_.guid=l??_.guid;const b=this.getMarkupRelatedTopics(r,d);w[_.guid]=new Set(b),_.type=c??_.type,_.status=u??_.status,_.title=p??_.title,_.creationDate=f?new Date(f):_.creationDate,_.creationAuthor=g??_.creationAuthor,_.serverAssignedId=o.ServerAssignedId,_.priority=o.Priority,_.index=o.Index,_.modifiedDate=o.ModifiedDate?new Date(o.ModifiedDate):void 0,_.modifiedAuthor=o.ModifiedAuthor,_.dueDate=o.DueDate?new Date(o.DueDate):void 0,_.assignedTo=o.AssignedTo,_.description=o.Description,_.stage=o.Stage;const v=this.getMarkupLabels(r,d);for(const t of v)_.labels.add(t);const x=this.getMarkupComments(r,d);for(const t of x)_.comments.set(t.guid,t);const S=this.getMarkupViewpoints(r,d);for(const t of S){if(!t||!t.Guid)continue;const e=m.list.get(t.Guid);if(!e)continue;_.viewpoints.add(e.guid);const i=`${_.guid}/${t.Snapshot}`,n=h.find(({name:t})=>t===i);if(n){const t=await n.async("arraybuffer"),i=new Uint8Array(t);m.snapshots.set(e.guid,i),e.snapshot=e.guid??null}}const T=this.getMarkupDocumentReferences(r,d),C=h.find(t=>"documents.xml"===t.name);let A=[];const E=await(null==C?void 0:C.async("string"));if(E){const t=null==(s=null==(n=Be.parser.parse(E).DocumentInfo)?void 0:n.Documents)?void 0:s.Document;A=Array.isArray(t)?t:[t]}for(const t of T){const{Description:e,DocumentGuid:i,Url:n,isExternal:s,ReferencedDocument:r}=t;if(i&&A.length>0){const t=A.find(({Guid:t})=>t===i),e=h.find(t=>t.name.endsWith(i)),n=await(null==e?void 0:e.async("uint8array"));if(!t||!n)continue;const{Description:s,Filename:r}=t;this.documents.set(i,{type:"internal",fileName:r,description:s,data:n}),_.documentReferences.add(i)}if(n){const t=this.documents.add({type:"external",url:n,description:e});_.documentReferences.add(t)}if(r){let t=null;if(s)t=this.documents.add({type:"external",url:r,description:e});else{const i=r.split("/"),n=i[i.length-1],s=h.find(t=>t.name.endsWith(n)),o=await(null==s?void 0:s.async("uint8array"));if(!o)continue;t=this.documents.add({type:"internal",fileName:n,data:o,description:e})}_.documentReferences.add(t)}}this.list.set(_.guid,_),y.push(_)}for(const t in w){const e=this.list.get(t);if(!e)continue;const i=w[t];for(const t of i)e.relatedTopics.add(t)}return this.onBCFImported.trigger(y),{viewpoints:f,topics:y}}};e(na,"uuid","de977976-e4f6-4e4f-a01a-204727839802"),e(na,"xmlParser",new xe({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let sa=na;class ra{constructor(t,i,n,s,r,a=5,l=!0){var c;if(e(this,"onDraggingStarted",new at),e(this,"onDraggingEnded",new at),e(this,"onDisposed",new at),e(this,"normal"),e(this,"origin"),e(this,"three",new o.Plane),e(this,"components"),e(this,"world"),e(this,"type","default"),e(this,"_title","Clipping Plane"),e(this,"_helper"),e(this,"_visible",!0),e(this,"_enabled",!0),e(this,"_controlsActive",!1),e(this,"_arrowBoundBox",new o.Mesh),e(this,"_planeMesh"),e(this,"_controls"),e(this,"_hiddenMaterial",new o.MeshBasicMaterial({visible:!1})),e(this,"_sizeMultiplier",5),e(this,"_autoScale",!0),e(this,"_visibilityBeforeDisabled",!0),e(this,"notifyManager",()=>{const t=this.components.get(la),e=t.list.getKey(this);e&&t.list.set(e,this)}),e(this,"update",()=>{this._enabled&&(this.three.setFromNormalAndCoplanarPoint(this.normal,this._helper.position),this.updateScale())}),e(this,"updateScale",()=>{var t;if(!this.autoScale)return;const e=null==(t=this.world.camera)?void 0:t.three;if(!e)return;if(!(e instanceof o.PerspectiveCamera))return;const i=new o.Vector3;e.getWorldPosition(i);const n=i.distanceTo(this._helper.position)/7*this._sizeMultiplier;this._planeMesh.scale.set(n,n,n)}),e(this,"changeDrag",t=>{this._visible=!t.value,this.preventCameraMovement(),this.notifyDraggingChanged(t)}),this.components=t,this.world=i,!i.renderer)throw new Error("The given world must have a renderer!");this.normal=s,this.origin=n,this._sizeMultiplier=a,i.renderer.setPlane(!0,this.three),this._planeMesh=ra.newPlaneMesh(a,r),this._helper=this.newHelper(),this._controls=this.newTransformControls(),this.three.setFromNormalAndCoplanarPoint(s,n),l&&this.toggleControls(!0),this.updateScale(),(null==(c=i.camera)?void 0:c.controls)&&i.camera.controls.addEventListener("update",this.updateScale)}set title(t){this._title=t,this.notifyManager()}get title(){return this._title}get autoScale(){return this._autoScale}set autoScale(t){this._autoScale=t,t&&this.updateScale()}get enabled(){return this._enabled}set enabled(t){if(!this.world.isDisposing){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");this._enabled=t,t?this.visible=this._visibilityBeforeDisabled:(this._visibilityBeforeDisabled=this.visible,this.visible=!1),this.world.renderer.setPlane(t,this.three),this.notifyManager()}}get visible(){return this._visible}set visible(t){this._visible=t,this._controls.getHelper().visible=t,this._helper.visible=t,this.toggleControls(t),this.notifyManager()}get meshes(){return[this._planeMesh,this._arrowBoundBox]}get planeMaterial(){return this._planeMesh.material}set planeMaterial(t){this._planeMesh.material=t}get size(){return this._sizeMultiplier}set size(t){this._sizeMultiplier=t,this.autoScale?this.updateScale():this._planeMesh.scale.set(t,t,t)}get helper(){return this._helper}get controls(){return this._controls}setFromNormalAndCoplanarPoint(t,e){this.reset(),this.normal.equals(t)||(this.normal.copy(t),this._helper.lookAt(t)),this.origin.copy(e),this._helper.position.copy(e),this._helper.updateMatrix(),this.update()}dispose(){var t;this._enabled=!1,(null==(t=this.world.camera)?void 0:t.controls)&&this.world.camera.controls.removeEventListener("update",this.updateScale),this.onDraggingStarted.reset(),this.onDraggingEnded.reset(),this._helper.removeFromParent(),this.world.renderer&&this.world.renderer.setPlane(!1,this.three),this._arrowBoundBox.removeFromParent(),this._arrowBoundBox.geometry.dispose(),this._planeMesh.geometry.dispose(),this._controls.getHelper().removeFromParent(),this._controls.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}reset(){const t=new o.Vector3(1,0,0),e=new o.Vector3;this.normal.equals(t)||(this.normal.copy(t),this._helper.lookAt(t)),this.origin.copy(e),this._helper.position.copy(e),this._helper.updateMatrix()}toggleControls(t){if(t){if(this._controlsActive)return;this._controls.addEventListener("change",this.update),this._controls.addEventListener("dragging-changed",this.changeDrag)}else this._controls.removeEventListener("change",this.update),this._controls.removeEventListener("dragging-changed",this.changeDrag);this._controlsActive=t}newTransformControls(){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");const t=this.world.camera.three,e=this.world.renderer.three.domElement,i=new ot(t,e);return this.initializeControls(i),this.world.scene.three.add(i.getHelper()),i}initializeControls(t){t.attach(this._helper),t.showX=!1,t.showY=!1,t.setSpace("local"),this.createArrowBoundingBox(),t.getHelper().children[0].children[0].add(this._arrowBoundBox)}createArrowBoundingBox(){this._arrowBoundBox.geometry=new o.CylinderGeometry(.18,.18,1.2),this._arrowBoundBox.material=this._hiddenMaterial,this._arrowBoundBox.rotateX(Math.PI/2),this._arrowBoundBox.updateMatrix(),this._arrowBoundBox.geometry.applyMatrix4(this._arrowBoundBox.matrix)}notifyDraggingChanged(t){t.value?this.onDraggingStarted.trigger():this.onDraggingEnded.trigger()}preventCameraMovement(){this.world.camera.enabled=this._visible}newHelper(){const t=new o.Object3D;return t.lookAt(this.normal),t.position.copy(this.origin),this._planeMesh.position.z+=.01,t.add(this._planeMesh),this.world.scene.three.add(t),t}static newPlaneMesh(t,e){const i=new o.PlaneGeometry(1),n=new o.Mesh(i,e);return n.scale.set(t,t,t),n}}class oa extends Re{constructor(){super(...arguments),e(this,"_config",{enabled:{value:!0,type:"Boolean"},visible:{value:!0,type:"Boolean"},color:{value:new o.Color,type:"Color"},opacity:{type:"Number",interpolable:!0,value:1,min:0,max:1},size:{type:"Number",interpolable:!0,value:2,min:0,max:100}})}get enabled(){return this._config.enabled.value}set enabled(t){this._config.enabled.value=t,this._component.enabled=t}get visible(){return this._config.visible.value}set visible(t){this._config.visible.value=t,this._component.visible=t}get color(){return this._config.color.value}set color(t){this._config.color.value=t,this._component.material.color.copy(t)}get opacity(){return this._config.opacity.value}set opacity(t){this._config.opacity.value=t,this._component.material.opacity=t}get size(){return this._config.size.value}set size(t){this._config.size.value=t,this._component.size=t}}const aa=class t extends ht{constructor(n){super(n),e(this,"onSetup",new at),e(this,"onBeforeDrag",new at),e(this,"onAfterDrag",new at),e(this,"onBeforeCreate",new at),e(this,"onBeforeCancel",new at),e(this,"onAfterCancel",new at),e(this,"onBeforeDelete",new at),e(this,"onAfterCreate",new at),e(this,"onAfterDelete",new at),e(this,"onDisposed",new at),e(this,"isSetup",!1),e(this,"orthogonalY",!1),e(this,"toleranceOrthogonalY",.7),e(this,"autoScalePlanes",!0),e(this,"Type",ra),e(this,"list",new i.DataMap),e(this,"config",new oa(this,this.components,"Clipper",t.uuid)),e(this,"_defaultConfig",{color:new o.Color(12255487),opacity:.2,size:2}),e(this,"_material",new o.MeshBasicMaterial({color:12255487,side:o.DoubleSide,transparent:!0,opacity:.2})),e(this,"_size",5),e(this,"_enabled",!1),e(this,"_visible",!0),e(this,"onStateChanged",new at),this.components.add(t.uuid,this),this.setEvents()}get enabled(){return this._enabled}set enabled(t){this._enabled=t,this.onStateChanged.trigger(["enabled"])}get visible(){return this._visible}set visible(t){this._visible=t;for(const[e,i]of this.list)i.visible=t;this.onStateChanged.trigger(["visibility"])}get material(){return this._material}set material(t){this._material=t;for(const[e,i]of this.list)i.planeMaterial=t;this.onStateChanged.trigger(["material"])}get size(){return this._size}set size(t){this._size=t;for(const[e,i]of this.list)i.size=t;this.onStateChanged.trigger(["size"])}setEvents(){this.list.onBeforeDelete.add(({value:t})=>{if(!t.world.renderer)throw new Error("Renderer not found for this plane's world!");t.world.renderer.setPlane(!1,t.three),t.dispose(),this.updateMaterialsAndPlanes(),this.onAfterDelete.trigger(t)})}dispose(){this._enabled=!1;this.components.get(je).list.delete(this.config.uuid),this.list.clear(),this._material.dispose(),this.onBeforeCreate.reset(),this.onBeforeCancel.reset(),this.onBeforeDelete.reset(),this.onBeforeDrag.reset(),this.onAfterCreate.reset(),this.onAfterCancel.reset(),this.onAfterDelete.reset(),this.onAfterDrag.reset(),this.onDisposed.trigger(t.uuid),this.onDisposed.reset()}async create(t){const e=this.components.get(Co).get(t),i=await e.castRay();return i?this.createPlaneFromIntersection(t,i):null}createFromNormalAndCoplanarPoint(t,e,i){const n=this.newPlane(t,i,e);return this.updateMaterialsAndPlanes(),n}async delete(t,e){if(!e){const i=await this.pickPlane(t);if(!i)return;e=this.list.getKey(i)}e&&this.list.delete(e)}deleteAll(t){for(const[e,i]of this.list)t&&!t.has(i.type)||this.list.delete(e)}setup(t){const e={...this._defaultConfig,...t};this.config.color=e.color,this.config.opacity=e.opacity,this.config.size=e.size,this.isSetup=!0,this.onSetup.trigger()}pickPlane(t){const e=this.components.get(Co).get(t),i=this.getAllPlaneMeshes(),n=e.castRayToObjects(i);if(n){const t=n.object;return[...this.list.values()].find(e=>e.meshes.includes(t))}}getAllPlaneMeshes(){const t=[];for(const[e,i]of this.list)t.push(...i.meshes);return t}createPlaneFromIntersection(t,e){var i;if(!t.renderer)throw new Error("The given world must have a renderer!");const n=e.point.distanceTo(new o.Vector3(0,0,0)),s=e.normal||(null==(i=e.face)?void 0:i.normal);if(!n||!s)return null;const r=this.getWorldNormal(e,s),a=this.newPlane(t,e.point,r.negate()),l=this.list.get(a);return l.visible=this._visible,l.size=this._size,t.renderer.setPlane(!0,l.three),this.updateMaterialsAndPlanes(),l}getWorldNormal(t,e){const i=t.object;let n=t.object.matrixWorld.clone();if(i instanceof o.InstancedMesh&&void 0!==t.instanceId){const e=new o.Matrix4;i.getMatrixAt(t.instanceId,e),n=e.multiply(n)}const s=(new o.Matrix3).getNormalMatrix(n),r=e.clone().applyMatrix3(s).normalize();return this.normalizePlaneDirectionY(r),r}normalizePlaneDirectionY(t){this.orthogonalY&&(t.y>this.toleranceOrthogonalY&&(t.x=0,t.y=1,t.z=0),t.y<-this.toleranceOrthogonalY&&(t.x=0,t.y=-1,t.z=0))}newPlane(t,e,i){const n=new this.Type(this.components,t,e,i,this._material);n.autoScale=this.autoScalePlanes,n.onDraggingStarted.add(()=>this.onBeforeDrag.trigger(n)),n.onDraggingEnded.add(()=>this.onAfterDrag.trigger(n));const s=_t.create();return this.list.set(s,n),this.onAfterCreate.trigger(n),s}updateMaterialsAndPlanes(){const t=this.components.get(Oo);for(const[e,i]of t.list){if(!i.renderer)continue;i.renderer.updateClippingPlanes();const{clippingPlanes:t}=i.renderer;for(const e of i.meshes)if(e.material)if(Array.isArray(e.material))for(const i of e.material)i.clippingPlanes=t;else e.material.clippingPlanes=t}}};e(aa,"uuid","66290bc5-18c4-4cd1-9379-2e17a0617611");let la=aa;class ca{constructor(t,n){e(this,"title"),e(this,"guid",_t.create()),e(this,"clippingPlanes",new i.DataSet),e(this,"camera",{aspect_ratio:1,field_of_view:60,camera_direction:{x:0,y:0,z:0},camera_view_point:{x:0,y:0,z:0},camera_up_vector:{x:0,y:1,z:0}}),e(this,"customData",{}),e(this,"exceptionComponents",new i.DataSet),e(this,"selectionComponents",new i.DataSet),e(this,"componentColors",new i.DataMap),e(this,"spacesVisible",!1),e(this,"spaceBoundariesVisible",!1),e(this,"openingsVisible",!1),e(this,"defaultVisibility",!0),e(this,"snapshot",this.guid),e(this,"_components"),e(this,"_world",null),e(this,"notifyUpdate",()=>{this._components.get(ua).list.set(this.guid,this)}),this._components=t,n&&(this.guid=n.guid??this.guid,this.set(n)),this.setEvents()}async getSelectionMap(){const t=this._components.get(Ws);return await t.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const t=this._components.get(Ws);return await t.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const t=this._components.get(Ws),{camera_view_point:e}=this.camera,{x:i,y:n,z:s}=e,r=new o.Vector3(i,n,s);return t.applyBaseCoordinateSystem(r,new o.Matrix4),r}set position(t){const e=t.clone(),i=this._components.get(Ws);t.clone().applyMatrix4(i.baseCoordinationMatrix.clone().invert()),this.camera.camera_view_point={x:e.x,y:e.y,z:e.z}}get direction(){const{camera_direction:t}=this.camera,{x:e,y:i,z:n}=t;return new o.Vector3(e,i,n)}set world(t){this._world=t}get world(){return this._world}get _managerVersion(){return this._components.get(sa).config.version}get topics(){return[...this._components.get(sa).list.values()].filter(t=>t.viewpoints.has(this.guid))}setEvents(){this.selectionComponents.onUpdated.add(this.notifyUpdate),this.exceptionComponents.onUpdated.add(this.notifyUpdate),this.clippingPlanes.onUpdated.add(this.notifyUpdate),this.componentColors.onItemSet.add(this.notifyUpdate),this.componentColors.onItemDeleted.add(this.notifyUpdate),this.componentColors.onItemUpdated.add(this.notifyUpdate),this.componentColors.onCleared.add(this.notifyUpdate)}set(t){this.title=t.title;const{components:e,perspective_camera:i,orthogonal_camera:n,clipping_planes:s}=t;if(e){const{selection:t,visibility:i,coloring:n}=e;if(t){this.selectionComponents.clear();for(const{ifc_guid:e}of t)e&&this.selectionComponents.add(e)}if(i){const{default_visibility:t,exceptions:e,view_setup_hints:n}=i;if(void 0!==t&&(this.defaultVisibility=t),e){this.exceptionComponents.clear();for(const{ifc_guid:t}of e)t&&this.exceptionComponents.add(t)}if(n){const{spaces_visible:t,space_boundaries_visible:e,openings_visible:i}=n;void 0!==t&&(this.spacesVisible=t),void 0!==e&&(this.spaceBoundariesVisible=e),void 0!==i&&(this.openingsVisible=i)}}if(n){this.componentColors.clear();for(const t of n){const{color:e,components:i}=t,n=i.map(t=>t.ifc_guid).filter(t=>null!==t);this.componentColors.set(e,n)}}}if((i||n)&&(this.camera=i??n),s&&this.world){const t=this._components.get(la);for(const e of s){const{location:i,direction:n}=e,s=new o.Vector3(i.x,i.z,-i.y),r=new o.Vector3(n.x,n.z,-n.y),a=t.createFromNormalAndCoplanarPoint(this.world,r,s);this.clippingPlanes.add(a),t.list.get(a).enabled=!1,t.list.get(a).visible=!1}}this.notifyUpdate()}async go(t){if(!this.world)return;const{camera:e}=this.world;if(!(e instanceof Ho))throw new Error("Viewpoint: the world's camera component must be of type OrthoPerspectiveCamera to switch between perspective and orthographic projections.");const{transition:i,applyClippings:n,applyVisibility:s,clippingsVisibility:r}={transition:!0,applyClippings:!0,applyVisibility:!0,clippingsVisibility:!0,...t};e.projection.set(this.projection);const a=new o.Vector3(this.camera.camera_view_point.x,this.camera.camera_view_point.y,this.camera.camera_view_point.z),l=new o.Vector3(this.camera.camera_direction.x,this.camera.camera_direction.y,this.camera.camera_direction.z);if(a.equals(new o.Vector3)&&l.equals(new o.Vector3))return;const c=this.position,h=this.direction,d={x:c.x+80*h.x,y:c.y+80*h.y,z:c.z+80*h.z},u=[];n&&this.setClippingState(!0),s&&u.push(this.applyVisibility()),this.setClippingVisibility(r),u.push(e.controls.setLookAt(c.x,c.y,c.z,d.x,d.y,d.z,i)),await Promise.all(u)}async updateCamera(t=!0){return new Promise(e=>{if(!this.world)return void e(!1);const{camera:i,renderer:n}=this.world;if(!n)throw new Error("Viewpoint: the world needs to have a renderer!");if(!i.hasCameraControls())throw new Error("Viewpoint: world's camera need camera controls!");const s=new o.Vector3;i.controls.getPosition(s);const r=i.three,a=new o.Vector3(0,0,-1).applyEuler(r.rotation),{width:l,height:c}=n.getSize();let h=l/c;Number.isNaN(h)&&(h=1);const d=this._components.get(Ws);s.applyMatrix4(d.baseCoordinationMatrix.clone().invert());const u={aspect_ratio:h,camera_view_point:{x:s.x,y:s.y,z:s.z},camera_direction:{x:a.x,y:a.y,z:a.z},camera_up_vector:{x:0,y:1,z:0}};if(r instanceof o.PerspectiveCamera?this.camera={...u,field_of_view:r.fov}:r instanceof o.OrthographicCamera&&(this.camera={...u,view_to_world_scale:r.top-r.bottom}),t){const t=this._components.get(ua),s=n.three.domElement;n.three.render(this.world.scene.three,i.three),s.toBlob(async i=>{if(i){const e=await i.arrayBuffer(),n=new Uint8Array(e);t.snapshots.set(this.guid,n)}this.notifyUpdate(),e(!0)})}else this.notifyUpdate(),e(!0)})}takeSnapshot(){return new Promise(t=>{if(!this.world)return void t(!1);const{camera:e,renderer:i}=this.world;if(!i)throw new Error("Viewpoint: the world needs to have a renderer!");const n=this._components.get(ua),s=i.three.domElement;i.three.render(this.world.scene.three,e.three),s.toBlob(async e=>{if(e){const t=await e.arrayBuffer(),i=new Uint8Array(t);n.snapshots.set(this.guid,i)}this.notifyUpdate(),t(!0)})})}updateClippingPlanes(){this.clippingPlanes.clear();const t=this._components.get(la);for(const[e,i]of t.list)i.enabled&&this.clippingPlanes.add(e)}async applyVisibility(){const t=this._components.get(uo);t.set(this.defaultVisibility);const e=await this.getExceptionMap();t.set(!this.defaultVisibility,e);const i=await this.getSelectionMap();t.set(!0,i)}async setColorizationState(t){const e=this._components.get(Ws),n=[];if(t)for(const[t,s]of this.componentColors){const r=`#${t}`,a=await e.guidsToModelIdMap(s);for(const[t,s]of Object.entries(a)){const a=e.list.get(t);a&&n.push(a.highlight([...s],{customId:r,color:new o.Color(r),renderedFaces:i.RenderedFaces.ONE,opacity:1,transparent:!1}))}}else for(const[t,i]of this.componentColors){const t=await e.guidsToModelIdMap(i);for(const[i,s]of Object.entries(t)){const t=e.list.get(i);t&&n.push(t.resetHighlight([...s]))}}n.push(e.core.update(!0)),await Promise.all(n)}setClippingState(t){const e=this._components.get(la);for(const[i,n]of e.list)n.enabled=t&&this.clippingPlanes.has(i)}setClippingVisibility(t){const e=this._components.get(la);for(const i of this.clippingPlanes){const n=e.list.get(i);n&&(n.visible=t)}}async createComponentTags(t){var e;const i=this._components.get(Ws);let n="";if(this._components.get(sa).config.includeSelectionTag){const s="selection"===t?await this.getSelectionMap():await this.getExceptionMap();for(const t in s){const r=i.list.get(t);if(!r)continue;const o=s[t];for(const t of o){const i=r.getItem(t),s=await i.getGuid();if(!s)continue;const o=null==(e=await i.getAttributes())?void 0:e.getValue("Tag");let a=null;o&&(a=`AuthoringToolId="${o}"`),n+=`\n<Component IfcGuid="${s}" ${a??""} />`}}}else n=[...this.selectionComponents].map(t=>`<Component IfcGuid="${t}" />`).join("\n");return n}createColorTags(){let t="";for(const[e,i]of this.componentColors.entries()){t+=`<Color Color="${e}">\n${i.map(t=>`\n<Component IfcGuid="${t}" />`).join("\n")}\n</Color>`}return 0!==t.length?`<Coloring>\n${t}\n</Coloring>`:"<Coloring />"}toJSON(){const t=this._components.get(la),e={guid:this.guid,components:{selection:[...this.selectionComponents].map(t=>({ifc_guid:t,authoring_tool_id:null})),coloring:[...this.componentColors].map(([t,e])=>({color:t,components:e.map(t=>({ifc_guid:t,authoring_tool_id:null}))})),visibility:{default_visibility:this.defaultVisibility,exceptions:[...this.exceptionComponents].map(t=>({ifc_guid:t,authoring_tool_id:null})),view_setup_hints:{spaces_visible:this.spacesVisible,space_boundaries_visible:this.spaceBoundariesVisible,openings_visible:this.openingsVisible}}},clipping_planes:[...this.clippingPlanes].map(e=>{const i=t.list.get(e);if(!i)return null;const n=i._controls.worldPosition??i.origin,{normal:s}=i;return{location:{x:n.x,y:-n.z,z:n.y},direction:{x:s.x,y:-s.z,z:s.y}}}).filter(t=>null!==t)};"field_of_view"in this.camera?e.perspective_camera=this.camera:e.orthogonal_camera=this.camera;const i=this._components.get(ua),n=i.snapshots.get(this.snapshot);if(n){const t=n.toString(),s=btoa(t),r=i.getSnapshotExtension(this.snapshot);e.snapshot={snapshot_type:r,snapshot_data:s}}return e}async serialize(t=this._managerVersion){const e=this._components.get(Ws),i=this.position;i.applyMatrix4(e.baseCoordinationMatrix.clone().invert());const n=this.direction;n.normalize();const s=(new o.Matrix4).makeRotationX(Math.PI/2),r=n.clone().applyMatrix4(s);r.normalize();const a=`<CameraViewPoint>\n <X>${i.x}</X>\n <Y>${-i.z}</Y>\n <Z>${i.y}</Z>\n </CameraViewPoint>`,l=`<CameraDirection>\n <X>${n.x}</X>\n <Y>${-n.z}</Y>\n <Z>${n.y}</Z>\n </CameraDirection>`,c=`<CameraUpVector>\n <X>${r.x}</X>\n <Y>${-r.z}</Y>\n <Z>${r.y}</Z>\n </CameraUpVector>`,h=`<AspectRatio>${this.camera.aspect_ratio}</AspectRatio>`;let d="";"view_to_world_scale"in this.camera?d=`<OrthogonalCamera>\n ${a}\n ${l}\n ${c}\n ${h}\n <ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>\n </OrthogonalCamera>`:"field_of_view"in this.camera&&(d=`<PerspectiveCamera>\n ${a}\n ${l}\n ${c}\n ${h}\n <FieldOfView>${this.camera.field_of_view}</FieldOfView>\n </PerspectiveCamera>`);const u=`<ViewSetupHints SpacesVisible="${this.spacesVisible??!1}" SpaceBoundariesVisible="${this.spaceBoundariesVisible??!1}" OpeningsVisible="${this.openingsVisible??!1}" />`,p=(await this.createComponentTags("selection")).trim(),f=(await this.createComponentTags("exception")).trim(),m=this.createColorTags();return`<?xml version="1.0" encoding="UTF-8"?>\n <VisualizationInfo Guid="${this.guid}">\n <Components>\n ${"2.1"===t?u:""}\n ${0!==p.length?`<Selection>${p}</Selection>`:""}\n <Visibility DefaultVisibility="${this.defaultVisibility}">\n ${"3"===t?u:""}\n ${0!==f.length?`<Exceptions>${f}</Exceptions>`:""}\n </Visibility>\n ${m}\n </Components>\n ${d}\n </VisualizationInfo>`}}class ha extends Re{constructor(){super(...arguments),e(this,"_config",{overwriteColors:{value:!1,type:"Boolean"}})}get overwriteColors(){return this._config.overwriteColors.value}set overwriteColors(t){this._config.overwriteColors.value=t}}const da=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"world",null),e(this,"list",new n),e(this,"snapshots",new n),e(this,"isSetup",!1),e(this,"onSetup",new at),e(this,"config",new ha(this,this.components,"Viewpoints",t.uuid)),e(this,"onDisposed",new at),i.add(t.uuid,this)}create(t){const e=new ca(this.components,t);return e.world=this.world,t||this.list.set(e.guid,e),e}getSnapshotExtension(t){let e="jpeg";const i=this.snapshots.get(t);if(!i)return e;const n=i.subarray(0,4);let s="";for(let t=0;t<n.length;t++)s+=n[t].toString(16);return s.startsWith("89504e47")&&(e="png"),s.startsWith("ffd8ffe")&&(e="jpeg"),e}setup(){}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}};e(da,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");let ua=da;class pa{constructor(t,i){e(this,"_components"),e(this,"_cameraOffset",10),e(this,"_planeHelper"),e(this,"_farPlaneHelper"),e(this,"_cameraHelper"),e(this,"onStateChanged",new at),e(this,"onUpdated",new at),e(this,"onDisposed",new at),e(this,"camera"),e(this,"plane",new o.Plane),e(this,"farPlane",new o.Plane),e(this,"id",_t.create()),e(this,"_open",!1),e(this,"_range",ma.defaultRange),e(this,"_world",null),e(this,"_helpersVisible",!1),e(this,"_planesEnabled",!1),this._components=t,this.camera=new Ho(this._components);const{threeOrtho:n}=this.camera;if((null==i?void 0:i.id)&&(this.id=i.id),(null==i?void 0:i.normal)&&(null==i?void 0:i.point)){const{normal:t,point:e}=i;this.plane.setFromNormalAndCoplanarPoint(t,e)}this._cameraHelper=new o.CameraHelper(n),this._planeHelper=new o.PlaneHelper(this.plane,50),this._farPlaneHelper=new o.PlaneHelper(this.farPlane,50),this.farPlaneHelperColor=new o.Color("blue"),this.update()}get _planeNormalOpposite(){return this.plane.normal.clone().negate()}get _planePosition(){return this.plane.normal.clone().multiplyScalar(-this.plane.constant)}get _cameraPosition(){return this._planePosition.addScaledVector(this._planeNormalOpposite,this._cameraOffset)}set open(t){this._open=t,this.onStateChanged.trigger(["open"])}get open(){return this._open}set planeHelperColor(t){!Array.isArray(this._planeHelper.material)&&"color"in this._planeHelper.material&&this._planeHelper.material.color instanceof o.Color&&(this._planeHelper.material.color=t)}set farPlaneHelperColor(t){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof o.Color&&(this._farPlaneHelper.material.color=t)}set range(t){this._range=t,this.update()}get range(){return this._range}set distance(t){this.plane.constant=t,this.update()}get distance(){return this.plane.constant}set world(t){this._world=t,this.camera.currentWorld=t,t&&(this.camera.projection.set("Orthographic"),this.camera.set("Plan"),this.camera.controls.dollySpeed=6,this.camera.controls.restThreshold=.005,this.update())}get world(){return this._world}set helpersVisible(t){if(!t)return this._helpersVisible=t,this._planeHelper.removeFromParent(),this._farPlaneHelper.removeFromParent(),void this._cameraHelper.removeFromParent();this.world&&(this._helpersVisible=t,this.world.scene.three.add(this._planeHelper,this._farPlaneHelper))}get helpersVisible(){return this._helpersVisible}set planesEnabled(t){const{world:e}=this;if(!e)return;const{renderer:i}=e;i&&(i.setPlane(t,this.plane),i.setPlane(t,this.farPlane),this._planesEnabled=t)}get planesEnabled(){return this._planesEnabled}dispose(){this.helpersVisible=!1;const t=this._components.get(mt);t.destroy(this._planeHelper),t.destroy(this._farPlaneHelper),t.destroy(this._cameraHelper),this.camera.dispose(),this.onDisposed.trigger()}update(){if(this.world){const t=this._cameraPosition,e=this._planePosition;this.camera.controls.setLookAt(t.x,t.y,t.z,e.x,e.y,e.z,!1)}this.farPlane.normal.copy(this._planeNormalOpposite),this.farPlane.constant=this.range-this.plane.constant,this.onUpdated.trigger()}flip(){this.plane.normal.negate(),this.update()}}const fa=class t extends ht{constructor(i){super(i),e(this,"list",new n),e(this,"enabled",!0),e(this,"world",null),e(this,"_fragmentsUpdateEvent",()=>{this.components.get(Ws).core.update(!0)}),i.add(t.uuid,this),this.setupEvents()}get hasOpenViews(){return[...this.list.values()].some(t=>t.open)}setupEvents(){this.list.onBeforeDelete.add(({key:t,value:e})=>{e.open&&this.close(t),e.dispose()})}create(t,e,i){const n=new pa(this.components,{id:null==i?void 0:i.id,normal:t,point:e});return n.world=(null==i?void 0:i.world)??this.world,this.list.set(n.id,n),n}createFromPlane(t,e){const i=new pa(this.components,{id:null==e?void 0:e.id});return i.plane.copy(t),i.update(),i.world=(null==e?void 0:e.world)??this.world,this.list.set(i.id,i),i}async createFromIfcStoreys(t){const e=[],i=this.components.get(Ws),n=void 0===(null==t?void 0:t.offset)?.25:t.offset;for(const[s,r]of i.list){if(t&&t.modelIds&&!t.modelIds.some(t=>t.test(s)))continue;const i=Object.values(await r.getItemsOfCategories([/BUILDINGSTOREY/])).flat();if(0===i.length)continue;const a=await r.getItemsData(i),[,l]=await r.getCoordinates(),c=new o.Vector3(0,-1,0);for(const i of a){if(!("value"in i.Name)||!("value"in i.Elevation))continue;const{value:s}=i.Name;if((null==t?void 0:t.storeyNames)&&!t.storeyNames.some(t=>t.test(s)))continue;const r=i.Elevation.value+l+n,a=new o.Plane(c,r),h=this.createFromPlane(a,{id:s,world:null==t?void 0:t.world});e.push(h)}}return e}createElevations(t){const e=[],i=this.components.get(Ws),n=void 0!==(null==t?void 0:t.combine)&&t.combine,s=(null==t?void 0:t.namingCallback)??(t=>({front:""+(n?"Front":`${t}: Front`),back:""+(n?"Back":`${t}: Back`),left:""+(n?"Left":`${t}: Left`),right:""+(n?"Right":`${t}: Right`)}));let r=[];for(const[e,n]of i.list)t&&t.modelIds&&!t.modelIds.some(t=>t.test(e))||r.push({id:e,box:n.box});if(0===r.length)return e;if(n){const t=this.components.get(fo);t.list.clear(),t.list.add(...r.map(t=>t.box));r=[{id:"combined",box:t.get()}]}for(const{id:i,box:n}of r){const{min:r,max:a}=n,l=Math.abs(a.x-r.x),c=Math.abs(a.z-r.z),h=new o.Vector3;n.getCenter(h);const d=new o.Plane(new o.Vector3(0,0,-1),a.z),u=new o.Plane(new o.Vector3(0,0,1),-r.z),p=new o.Plane(new o.Vector3(-1,0,0),a.x),f=new o.Plane(new o.Vector3(1,0,0),-r.x),{front:m,back:g,left:w,right:y}=s(i),_=this.createFromPlane(d,{id:m,world:null==t?void 0:t.world});_.range=c;const b=this.createFromPlane(u,{id:g,world:null==t?void 0:t.world});b.range=c;const v=this.createFromPlane(p,{id:w,world:null==t?void 0:t.world});v.range=l;const x=this.createFromPlane(f,{id:y,world:null==t?void 0:t.world});x.range=l,e.push(_,b,v,x)}return e}open(t){const e=this.list.get(t);if(!e)throw new Error(`Views: the view with id ${t} doesn't exist.`);if(e.open)return;const{world:i}=e;if(!i)throw new Error(`Views: no world found for view with id ${t}.`);const{renderer:n}=i;if(!n)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);for(const[,t]of this.list)t.world===i&&this.close(t.id);n.setPlane(!0,e.plane),n.setPlane(!0,e.farPlane),e.camera.controls.addEventListener("rest",this._fragmentsUpdateEvent),i.camera=e.camera,e.open=!0}close(t){let e;if(e=t?this.list.get(t):[...this.list.values()].find(t=>t.open),t&&!e)throw new Error(`Views: the view with id ${t} doesn't exist.`);if(!e)return;if(!e.open)return;const{world:i}=e;if(!i)throw new Error(`Views: no world found for view with id ${t}.`);const{renderer:n}=i;if(!n)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);n.setPlane(!1,e.plane),n.setPlane(!1,e.farPlane),e.camera.controls.removeEventListener("rest",this._fragmentsUpdateEvent),i.useDefaultCamera(),e.open=!1}};e(fa,"uuid","fb22f1f5-6598-4664-a11d-de8963ae420f"),e(fa,"defaultRange",15);let ma=fa;async function ga(t,e,i,n,s,r,o){const a=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),await function(t,e,i,n){return new Promise((s,r)=>{!function o(){const a=t.clientWaitSync(e,i,0);a!==t.WAIT_FAILED?a!==t.TIMEOUT_EXPIRED?s():setTimeout(o,n):r()}()})}(t,a,0,10),t.deleteSync(a),t.bindBuffer(e,i),t.getBufferSubData(e,n,s,r,o),t.bindBuffer(e,null)}class wa{constructor(t,i){if(e(this,"onDisposed",new at),e(this,"onDistanceComputed",new at),e(this,"excludedObjects",new Set),e(this,"enabled",!0),e(this,"renderDebugFrame",!1),e(this,"components"),e(this,"scene",new o.Scene),e(this,"camera",new o.OrthographicCamera(-1,1,1,-1,0,1)),e(this,"depthMaterial"),e(this,"world"),e(this,"worker"),e(this,"_width",512),e(this,"_height",512),e(this,"_postQuad"),e(this,"tempRT"),e(this,"resultRT"),e(this,"bufferSize"),e(this,"_buffer"),e(this,"_isWorkerBusy",!1),e(this,"compute",async()=>{if(!this.enabled||this.world.isDisposing)return;if(this._isWorkerBusy)return;this._isWorkerBusy=!0,this.world.camera.three.updateMatrix();const t=this.world.renderer.three;t.setRenderTarget(this.tempRT);const e="visibilityBeforeDistanceCheck";for(const t of this.excludedObjects)t.userData[e]=t.visible,t.visible=!1;t.render(this.world.scene.three,this.world.camera.three);for(const t of this.excludedObjects)void 0!==t.userData[e]&&(t.visible=t.userData[e]);this.depthMaterial.uniforms.tDiffuse.value=this.tempRT.texture,this.depthMaterial.uniforms.tDepth.value=this.tempRT.depthTexture,t.setRenderTarget(this.resultRT),t.render(this.scene,this.camera);const i=t.getContext();try{await async function(t,e,i,n,s,r,o,a){const l=t.createBuffer();return t.bindBuffer(t.PIXEL_PACK_BUFFER,l),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(e,i,n,s,r,o,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),await ga(t,t.PIXEL_PACK_BUFFER,l,0,a),t.deleteBuffer(l),a}(i,0,0,this._width,this._height,i.RGBA,i.UNSIGNED_BYTE,this._buffer)}catch(e){return t.setRenderTarget(null),void(this._isWorkerBusy=!1)}t.setRenderTarget(null),this.renderDebugFrame&&t.render(this.scene,this.camera),this.worker.postMessage({buffer:this._buffer})}),e(this,"handleWorkerMessage",t=>{if(!this.enabled||this.world.isDisposing)return;const e=t.data.colors;let i=Number.MAX_VALUE;for(const t of e)0!==t&&t<i&&(i=t);const n=this.world.camera.three||o.OrthographicCamera,s=-1*(i/255-1)*(n.far-n.near),r=Math.min(s,n.far);this.onDistanceComputed.trigger(r),this._isWorkerBusy=!1}),!i.renderer)throw new Error("The given world must have a renderer!");this.components=t,this.world=i;const n=i.camera.three;this.tempRT=new o.WebGLRenderTarget(this._width,this._height),this.bufferSize=this._width*this._height*4,this._buffer=new Uint8Array(this.bufferSize),this.tempRT.texture.minFilter=o.NearestFilter,this.tempRT.texture.magFilter=o.NearestFilter,this.tempRT.stencilBuffer=!1,this.tempRT.samples=0,this.tempRT.depthTexture=new o.DepthTexture(this._width,this._height),this.tempRT.depthTexture.format=o.DepthFormat,this.tempRT.depthTexture.type=o.UnsignedShortType,this.resultRT=new o.WebGLRenderTarget(this._width,this._height),this.depthMaterial=new o.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n ",fragmentShader:"\n#include <packing>\n\nvarying vec2 vUv;\nuniform sampler2D tDiffuse;\nuniform sampler2D tDepth;\nuniform float cameraNear;\nuniform float cameraFar;\n\n\nfloat readDepth( sampler2D depthSampler, vec2 coord ) {\n float fragCoordZ = texture2D( depthSampler, coord ).x;\n float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );\n return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );\n}\n\nvoid main() {\n //vec3 diffuse = texture2D( tDiffuse, vUv ).rgb;\n float depth = readDepth( tDepth, vUv );\n\n gl_FragColor.rgb = 1.0 - vec3( depth );\n gl_FragColor.a = 1.0;\n}\n ",uniforms:{cameraNear:{value:n.near},cameraFar:{value:n.far},tDiffuse:{value:null},tDepth:{value:null}}});const s=new o.PlaneGeometry(2,2);this._postQuad=new o.Mesh(s,this.depthMaterial),this.scene.add(this._postQuad);const r=new Blob(['\n addEventListener("message", (event) => {\n const { buffer } = event.data;\n const colors = new Set();\n for (let i = 0; i < buffer.length; i += 4) {\n const r = buffer[i];\n colors.add(r);\n }\n postMessage({ colors });\n });\n '],{type:"application/javascript"});this.worker=new Worker(URL.createObjectURL(r)),this.worker.addEventListener("message",this.handleWorkerMessage)}dispose(){this.enabled=!1,this.onDistanceComputed.reset(),this.worker.terminate(),this.tempRT.dispose(),this.resultRT.dispose();const t=[...this.scene.children];this.excludedObjects.clear();for(const e of t)e.removeFromParent();this._postQuad.geometry.dispose(),this._postQuad.removeFromParent(),this._buffer=null,this.onDisposed.reset()}}class ya extends zo{constructor(){super(...arguments),e(this,"_distanceRenderer"),e(this,"autoBias",!0),e(this,"_defaultShadowConfig",{cascade:1,resolution:512}),e(this,"_lightsWithShadow",new Map),e(this,"_isComputingShadows",!1),e(this,"_shadowsEnabled",!0),e(this,"_bias",0),e(this,"recomputeShadows",t=>{if(!this._shadowsEnabled)return;this.autoBias&&(this.bias=-.005);if(t*=1.5,!this.currentWorld)throw new Error("A world needs to be assigned to the scene before computing shadows!");if(!this._lightsWithShadow.size)throw new Error("No shadows found!");const e=this.currentWorld.camera.three;if(!(e instanceof o.PerspectiveCamera||e instanceof o.OrthographicCamera))throw new Error("Invalid camera type!");const i=new o.Vector3;e.getWorldDirection(i);let n=t;const s=new o.Vector3;s.copy(this.config.directionalLight.position),s.normalize();for(const[t,r]of this._lightsWithShadow){const a=this.directionalLights.get(r);if(!a)throw new Error("Light not found.");const l=new o.Vector3;l.copy(i);const c=t===this._lightsWithShadow.size-1,h=c?n/2:2*n/3;l.multiplyScalar(h),l.add(e.position);const d=n-h,u=new o.Vector3;u.copy(s),u.multiplyScalar(d),a.target.position.copy(l),a.position.copy(l),a.position.add(u),a.shadow.camera.right=d,a.shadow.camera.left=-d,a.shadow.camera.top=d,a.shadow.camera.bottom=-d,a.shadow.camera.far=2*d,a.shadow.camera.updateProjectionMatrix(),a.shadow.camera.updateMatrix(),c||(n/=3)}this._isComputingShadows=!1})}get bias(){return this._bias}set bias(t){this._bias=t;for(const[,e]of this._lightsWithShadow){const i=this.directionalLights.get(e);i&&(i.shadow.bias=t)}}get shadowsEnabled(){return this._shadowsEnabled}set shadowsEnabled(t){this._shadowsEnabled=t;for(const[,e]of this.directionalLights)e.castShadow=t}get distanceRenderer(){if(!this._distanceRenderer)throw new Error("You must set up this component before accessing the distance renderer!");return this._distanceRenderer}setup(t){super.setup(t);const e={...this._defaultConfig,...this._defaultShadowConfig,...t};if(e.cascade<=0)throw new Error("Config.shadows.cascade must be a natural number greater than 0!");if(e.cascade>1)throw new Error("Multiple shadows not supported yet!");if(!this.currentWorld)throw new Error("A world needs to be assigned to the scene before setting it up!");for(const[,t]of this.directionalLights)t.target.removeFromParent(),t.removeFromParent(),t.dispose();this.directionalLights.clear(),this._distanceRenderer||(this._distanceRenderer=new wa(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let t=0;t<e.cascade;t++){const i=new o.DirectionalLight;i.intensity=this.config.directionalLight.intensity,i.color=this.config.directionalLight.color,i.position.copy(this.config.directionalLight.position),i.shadow.mapSize.width=e.resolution,i.shadow.mapSize.height=e.resolution,this.three.add(i,i.target),this.directionalLights.set(i.uuid,i),this._lightsWithShadow.set(t,i.uuid),i.castShadow=!0,i.shadow.bias=this._bias}}dispose(){super.dispose(),this._distanceRenderer&&this._distanceRenderer.dispose(),this._lightsWithShadow.clear()}async updateShadows(){!this._isComputingShadows&&this._shadowsEnabled&&(this._isComputingShadows=!0,await this.distanceRenderer.compute())}}class _a{constructor(t){e(this,"cardinality","required"),e(this,"instructions"),e(this,"evalRequirement",(t,e,i,n)=>{const s={parameter:i,currentValue:t,requiredValue:e,pass:!1};n&&this.addCheckResult(s,n);let r=!1;if("simple"===e.type&&(r=t===e.parameter),"enumeration"===e.type&&(r=e.parameter.includes(t)),"pattern"===e.type){r=new RegExp(e.parameter).test(String(t))}if("length"===e.type){const{min:i,length:n,max:s}=e.parameter;void 0!==n&&(r=String(t).length===n),void 0!==i&&(r=String(t).length>=i),void 0!==s&&(r=String(t).length<=s)}if("bounds"===e.type&&"number"==typeof t){const{min:i,minInclusive:n,max:s,maxInclusive:o}=e.parameter;let a=!0,l=!0;void 0!==i&&(a=n?t>=i:t>i),void 0!==s&&(l=o?t<=s:t<s),r=a&&l}return"prohibited"===this.cardinality&&(r=!r),"optional"===this.cardinality&&(r=!0),s.pass=r,s.pass}),this._components=t}addCheckResult(t,e){const i=e.findIndex(({parameter:e})=>e===t.parameter);-1!==i?e[i]=t:e.push(t)}getItemChecks(t,e,n,s){if(!("value"in n._localId)||"number"!=typeof n._localId.value)return null;let r=t.get(e);r||(r=new i.DataMap,t.set(e,r));let o=r.get(n._localId.value);if(o&&s&&!o.pass)return null;if(!o){const t=[];o={guid:Array.isArray(n._guid)?void 0:n._guid.value,pass:!1,checks:t},Object.defineProperty(o,"pass",{get:()=>t.every(({pass:t})=>t)}),r.set(n._localId.value,o)}const a=[],l={facetType:this.facetType,cardinality:this.cardinality,checks:a,pass:!1};return Object.defineProperty(l,"pass",{get:()=>a.every(({pass:t})=>t)}),o.checks.push(l),l.checks}}const ba=(t,e)=>{let i="";if(!e)return i;if("simple"===e.type&&(i=`<simpleValue>${e.parameter}</simpleValue>`),"enumeration"===e.type){i=`<xs:restriction base="xs:string">\n ${e.parameter.map(t=>`<xs:enumeration value="${t}" />`).join("\n")}\n </xs:restriction>`}if("pattern"===e.type){i=`<xs:restriction base="xs:string">\n <xs:pattern value="${e.parameter}" />\n </xs:restriction>`}if("bounds"===e.type){const{min:t,minInclusive:n,max:s,maxInclusive:r}=e.parameter;let o="";void 0!==t&&(o=`<xs:min${n?"Inclusive":"Exclusive"} value="${t}">`);let a="";void 0!==s&&(a=`<xs:max${r?"Inclusive":"Exclusive"} value="${s}">`),i=`<xs:restriction base="xs:double">\n ${o}\n ${a}\n </xs:restriction>`}if("length"===e.type){const{length:t,min:n,max:s}=e.parameter;let r="";void 0!==t&&void 0===n&&void 0===s&&(r=`<xs:length value="${t}" />`);let o="";void 0!==n&&void 0===t&&(o=`<xs:minLength value="${n}" />`);let a="";void 0!==s&&void 0===t&&(a=`<xs:maxLength value="${s}" />`),i=`<xs:restriction base="xs:string">\n ${r}\n ${o}\n ${a}\n </xs:restriction>`}return`<${t[0].toLowerCase()+t.slice(1)}>\n ${i}\n </${t[0].toLowerCase()+t.slice(1)}>`};class va extends _a{constructor(t,i){super(t),e(this,"facetType","Attribute"),e(this,"name"),e(this,"value"),this.name=i}serialize(t){const e=ba("Name",this.name),i=ba("Value",this.value);let n="";return"requirement"===t&&(n+=`cardinality="${this.cardinality}"`,n+=this.instructions?`instructions="${this.instructions}"`:""),`<attribute ${n}>\n ${e}\n ${i}\n</attribute>`}async getEntities(){}async test(t,e,i={skipIfFails:!0}){const n=this._components.get(Ws);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([...r]);for(const t of o){const n=this.getItemChecks(e,s,t,i.skipIfFails);if(!n)continue;const r=Object.keys(t).filter(e=>{const i=this.evalRequirement(e,this.name,"Name");if(!i)return!1;const n=t[e];return!!Array.isArray(n)||(null===n||null===n.value?"optional"===this.cardinality||"prohibited"===this.cardinality:(!Array.isArray(n.value)||0!==n.value.length)&&(("string"!=typeof n.value||""!==n.value.trim())&&i))}),o=r.length>0;if(n.push({parameter:"Name",currentValue:o?r[0]:null,requiredValue:this.name,pass:"prohibited"===this.cardinality?!o:o}),this.value)if(r[0]){const e=t[r[0]];if(Array.isArray(e))n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality});else{Array.isArray(e.value)?n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality}):this.evalRequirement(e.value,this.value,"Value",n)}}else n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality})}}}}class xa extends _a{constructor(t,i){super(t),e(this,"facetType","Classification"),e(this,"system"),e(this,"value"),e(this,"uri"),this.system=i}serialize(t){const e=ba("System",this.system),i=ba("Value",this.value);let n="";return"requirement"===t&&(n+=`cardinality="${this.cardinality}"`,n+=this.uri?`uri=${this.uri}`:"",n+=this.instructions?`instructions="${this.instructions}"`:""),`<classification ${n}>\n ${e}\n ${i}\n</classification>`}async getEntities(t,e){}async test(t,e){}}class Sa extends _a{constructor(t,i){super(t),e(this,"facetType","Entity"),e(this,"name"),e(this,"predefinedType"),this.name=i}serialize(t){const e=ba("Name",this.name),i=ba("Name",this.predefinedType);let n="";return"requirement"===t&&(n+=`cardinality="${this.cardinality}"`,n+=this.instructions?`instructions="${this.instructions}"`:""),`<entity ${n}>\n ${e}\n ${i}\n</entity>`}async getEntities(t,e){const i=this._components.get(Ws),n=new Map;for(const[e,s]of i.list){if(!t.find(t=>t.test(e)))continue;const i=await s.getCategories();for(const t of i){if(!await this.evalName(t))continue;let i=n.get(e);i||(i=[],n.set(e,i)),i.push(t)}}const s={};if(await Promise.all(Array.from(n.entries()).map(async([t,e])=>{const n=i.list.get(t);if(!n)return;const r=e.map(t=>new RegExp(`^${t}$`)),o=await n.getItemsOfCategories(r),a=Object.values(o).flat();s[t]=new Set(a)})),this.predefinedType)for(const[t,n]of Object.entries(s)){const s=i.list.get(t);if(!s)continue;const r=await s.getItemsData([...n]);for(const i of r){if(!("value"in i._localId))continue;await this.evalPredefinedType(t,i)&&Ve.append(e,t,i._localId.value)}}else Ve.add(e,s)}async test(t,e,i){const n=this._components.get(Ws);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([...r]);for(const t of o){if(!("value"in t._category))continue;const n=this.getItemChecks(e,s,t,i.skipIfFails);n&&(await this.evalName(t._category.value,n),await this.evalPredefinedType(s,t,n))}}}async evalName(t,e){return this.evalRequirement(t,this.name,"Name",e)}async evalPredefinedType(t,e,i){if(!this.predefinedType)return null;if(!("value"in e.PredefinedType))return null;const n="string"==typeof this.predefinedType.parameter&&"USERDEFINED"===this.predefinedType.parameter;let s=e.PredefinedType.value;if("USERDEFINED"===s&&!n){const t=Object.keys(e).find(t=>/^((?!Predefined).)*Type$/.test(t));if(t){const i=e[t];"value"in i&&(s=i.value)}else s="USERDEFINED"}if(!s){const i=this._components.get(Ws).list.get(t);if(i&&"value"in e._localId){const[t]=await i.getItemsData([e._localId.value],{relations:{IsTypedBy:{attributes:!0,relations:!1}}});if(Array.isArray(t.IsTypedBy)){const e=t.IsTypedBy[0];if(e&&"value"in e.PredefinedType&&(s=e.PredefinedType.value,"USERDEFINED"===s&&!n)){const t=Object.keys(e).find(t=>/^((?!Predefined).)*Type$/.test(t));if(t){const i=e[t];"value"in i&&(s=i.value)}else s="USERDEFINED"}}}}return this.evalRequirement(s,this.predefinedType,"PredefinedType",i)}}class Ta extends _a{constructor(t,i,n){super(t),e(this,"facetType","Property"),e(this,"propertySet"),e(this,"baseName"),e(this,"value"),e(this,"dataType"),e(this,"uri"),e(this,"_unsupportedTypes",["IFCCOMPLEXPROPERTY","IFCPHYSICALCOMPLEXQUANTITY"]),this.propertySet=i,this.baseName=n}serialize(t){const e=ba("PropertySet",this.propertySet),i=ba("BaseName",this.baseName),n=ba("Value",this.value),s=this.dataType?`dataType=${this.dataType}`:"";let r="";return"requirement"===t&&(r+=`cardinality="${this.cardinality}"`,r+=this.uri?`uri=${this.uri}`:"",r+=this.instructions?`instructions="${this.instructions}"`:""),`<property ${s} ${r}>\n ${e}\n ${i}\n ${n}\n</property>`}async getEntities(t,e){const i=this._components.get(Ws);for(const[n,s]of i.list){if(!t.find(t=>t.test(n)))continue;const i=await s.getItemsOfCategories([/PROPERTYSET/,/ELEMENTQUANTITY/]),r=Object.values(i).flat();if(0===r.length)continue;const o=await s.getItemsData(r,{relations:{HasProperties:{attributes:!0,relations:!1},DefinesOcurrence:{attributes:!0,relations:!1}}});for(const t of o){if(!("value"in t._localId&&"value"in t._category&&"value"in t.Name&&Array.isArray(t.DefinesOcurrence)))continue;if(!this.evalRequirement(t.Name.value,this.propertySet,"PropertySet"))continue;let i;if("IFCPROPERTYSET"===t._category.value&&(i="HasProperties"),"IFCELEMENTQUANTITY"===t._category.value&&(i="Quantities"),!i)continue;const s=t[i];if(Array.isArray(s))for(const i of s){const s=Object.keys(i),r=s.find(t=>/Name/.test(t));if(!r||!("value"in i[r]))continue;const o=i[r];if(!("value"in o))continue;if(!this.evalRequirement(o.value,this.baseName,"BaseName"))continue;if(this.value){const t=s.find(t=>/Value/.test(t));if(!t)continue;const e=i[t];if(!("value"in e))continue;if(!this.evalRequirement(e.value,this.value,"Value"))continue}const a=t.DefinesOcurrence.map(t=>"value"in t._localId&&"number"==typeof t._localId.value?t._localId.value:null).filter(t=>null!==t);Ve.append(e,n,...a)}}}}async test(t,e,i={skipIfFails:!0}){const n=this._components.get(Ws);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([...r],{relations:{IsDefinedBy:{attributes:!0,relations:!0},IsTypedBy:{attributes:!0,relations:!1},HasPropertySets:{attributes:!0,relations:!0},DefinesOcurrence:{attributes:!1,relations:!1}}});for(const t of o){const n=this.getItemChecks(e,s,t,i.skipIfFails);if(!n)continue;const r=(await this.getPsets(t)).filter(t=>{if(!("value"in t.Name))return!1;return!!this.evalRequirement(t.Name.value,this.propertySet,"PropertySet")&&(n.push({currentValue:t.Name.value,parameter:"PropertySet",pass:!0,requiredValue:this.propertySet}),!0)});if(0!==r.length)for(const t of r){const e=this.getPropertyListName(t);if(!e)continue;const i=t[e];if(!Array.isArray(i)){n.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}const s=i.filter(t=>{if(!("value"in t._category)||!("value"in t.Name))return!1;if(this._unsupportedTypes.includes(t._category.value))return!1;return!!this.evalRequirement(t.Name.value,this.baseName,"BaseName")&&(n.push({currentValue:t.Name.value,parameter:"BaseName",pass:!0,requiredValue:this.baseName}),!0)});if(0!==s.length)for(const t of s)this.evalValue(t,n),this.evalDataType(t,n),this.evalURI();else n.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName})}else n.push({currentValue:null,parameter:"PropertySet",pass:!1,requiredValue:this.propertySet})}}}getPropertyListName(t){let e;return"value"in t._category?("IFCPROPERTYSET"===t._category.value&&(e="HasProperties"),"IFCELEMENTQUANTITY"===t._category.value&&(e="Quantities"),e):e}getValueKey(t){return Object.keys(t).find(t=>/Value/.test(t)||/Values/.test(t))}getTypePsets(t){if(!Array.isArray(t.IsTypedBy))return[];const[e]=t.IsTypedBy;return e&&Array.isArray(e.HasPropertySets)?e.HasPropertySets:[]}async getPsets(t){const e=this.getTypePsets(t);if(!Array.isArray(t.IsDefinedBy))return e;const i=[];for(const n of t.IsDefinedBy){if(!("value"in n.Name))continue;const t=n.Name.value,s=this.getPropertyListName(n);if(!t||!s)continue;const r=e.find(e=>"value"in e.Name&&e.Name.value===t);if(r&&Array.isArray(r.HasProperties)&&Array.isArray(n.HasProperties))for(const t of r.HasProperties){if(!("value"in t.Name))continue;const e=t.Name.value;n.HasProperties.find(t=>"value"in t.Name&&t.Name.value===e)||n.HasProperties.push(t)}i.push(n)}return i}evalValue(t,e){const i=this.getValueKey(t),n=t[i];if(!("value"in n))return!1;if(this.value){if(!i)return null==e||e.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;const t=structuredClone(this.value);"IFCLABEL"===n.type&&"simple"===t.type&&(t.parameter=String(t.parameter));return this.evalRequirement(n.value,t,"Value",e)}return!i||("string"!=typeof n.value||""!==n.value.trim()||(null==e||e.push({parameter:"Value",currentValue:"",pass:!1,requiredValue:this.value}),!1))}evalDataType(t,e){if(!this.dataType)return!0;const i=this.getValueKey(t);if(!i||!("value"in t[i]))return null==e||e.push({parameter:"DataType",currentValue:null,pass:!1,requiredValue:this.dataType}),!1;const n=t[i];return this.evalRequirement(n.type??null,{type:"simple",parameter:this.dataType},"DataType",e)}evalURI(){return!0}}class Ca extends _a{constructor(){super(...arguments),e(this,"_ifcMaterialEntities",[/^IFCMATERIALLAYERSETUSAGE$/,/^IFCMATERIALCONSTITUENTSET$/,/^IFCMATERIAL$/,/^IFCMATERIALLIST$/]),e(this,"facetType","Material"),e(this,"value"),e(this,"uri")}serialize(t){if(!this.value||!this.uri)return"<material />";const e=ba("Value",this.value);let i="";return"requirement"===t&&(i+=`cardinality="${this.cardinality}"`,i+=this.uri?`uri=${this.uri}`:"",i+=this.instructions?`instructions="${this.instructions}"`:""),`<material ${i}>\n ${e}\n</material>`}async getEntities(t,e){const i=this._components.get(Ws);for(const[n,s]of i.list){if(!t.find(t=>t.test(n)))continue;const i=await s.getItemsOfCategories(this._ifcMaterialEntities),r=Object.values(i).flat();if(0===r.length)continue;const o=await s.getItemsData(r,{relations:{AssociatedTo:{attributes:!0,relations:!1},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const t of o){if(!("value"in t._localId&&"value"in t._category&&Array.isArray(t.AssociatedTo)))continue;if(!this.hasValidMaterial(t))continue;const i=t.AssociatedTo.map(t=>"value"in t._localId&&t._localId.value?t._localId.value:null).filter(t=>null!==t);Ve.append(e,n,...i)}}}async test(t,e,i={skipIfFails:!0}){const n=this._components.get(Ws);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([[...r][0]],{relations:{AssociatedTo:{attributes:!1,relations:!1},HasAssociations:{attributes:!0,relations:!0},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const t of o){const n=this.getItemChecks(e,s,t,i.skipIfFails);if(n)if(Array.isArray(t.HasAssociations))for(const e of t.HasAssociations){if(!this._ifcMaterialEntities.some(t=>"value"in e._category&&t.test(e._category.value)))continue;if(this.hasValidMaterial(e,n))break}else n.push({parameter:null,currentValue:null,requiredValue:this.value,pass:!1})}}}hasValidMaterial(t,e){let i=!1;if("value"in t._category&&"IFCMATERIAL"===t._category.value){this.evalValue(t,e)&&(i=!0)}else for(const[n,s]of Object.entries(t))if(["ForLayerSet","MaterialLayers","Material","MaterialConstituents","Materials"].includes(n)&&Array.isArray(s))for(const t of s){if("value"in t._category&&"IFCMATERIAL"===t._category.value){if(this.evalValue(t,e)){i=!0;break}}else{if(this.hasValidMaterial(t)){i=!0;break}}}return i}evalValue(t,e){if(!this.value)return null==e||e.push({parameter:null,currentValue:t.Name&&"value"in t.Name?t.Name.value:null,pass:!0}),!0;if(!("value"in t._category)||"IFCMATERIAL"!==t._category.value)return null;let i=!1;return t.Name&&"value"in t.Name&&(i=this.evalRequirement(t.Name.value,this.value,"Value",e)),i||(t.Category&&"value"in t.Category&&(i=this.evalRequirement(t.Category.value,this.value,"Value",e)),i)}}class Aa extends _a{constructor(t,i){super(t),e(this,"facetType","PartOf"),e(this,"_entityFacet"),e(this,"_entity"),e(this,"relation"),e(this,"cardinality","required"),this._entity=i,this._entityFacet=new Sa(t,i.name),this._entityFacet.predefinedType=i.predefinedType}set entity(t){this._entity=t;const{name:e,predefinedType:i}=t;this._entityFacet=new Sa(this._components,e),this._entityFacet.predefinedType=i}get entity(){return this._entity}serialize(){return""}async getEntities(t,e){}async test(t){}}class Ea{constructor(t,n,s){e(this,"name"),e(this,"ifcVersion",new Set),e(this,"identifier",_t.create()),e(this,"description"),e(this,"instructions"),e(this,"requirementsDescription"),e(this,"applicability",new i.DataSet),e(this,"requirements",new i.DataSet),e(this,"components"),this.components=t,this.name=n;for(const t of s)this.ifcVersion.add(t)}set(t){const e=t,i=this;for(const n in t){if("identifier"===n)continue;const t=e[n];n in this&&(i[n]=t)}return this.components.get(Va).list.set(this.identifier,this),this}async test(t,e={skipIfFails:!0}){const n=new i.DataMap;if(0===this.requirements.size)return n;const s={},r=[];for(const e of this.applicability)r.push(e.getEntities(t,s));await Promise.all(r);const o=[];for(const t of this.requirements)o.push(t.test(s,n,e));return await Promise.all(o),n}serialize(){const t=`name="${this.name}"`,e=this.identifier?`identifier="${this.identifier}"`:"",i=this.description?`description="${this.description}"`:"",n=this.instructions?`instructions="${this.instructions}"`:"";return`<specification ifcVersion="${[...this.ifcVersion].join(" ")}" ${t} ${e} ${i} ${n}>\n <applicability minOccurs="1" maxOccurs="unbounded">\n ${[...this.applicability].map(t=>t.serialize("applicability")).join("\n")}\n </applicability>\n <requirements>\n ${[...this.requirements].map(t=>t.serialize("requirement")).join("\n")}\n </requirements>\n </specification>`}}const Ma=t=>{if(!t)return;const e={};if("simpleValue"in t&&(e.type="simple",e.parameter=t.simpleValue),"restriction"in t){const i=t.restriction,n=Object.keys(i);if("pattern"in i&&(e.type="pattern",e.parameter=i.pattern.value),"enumeration"in i){e.type="enumeration";const t=i.enumeration.map(({value:t})=>i.base.includes("string")?String(t):i.base.includes("integer")||i.base.includes("double")?Number(t):t);e.parameter=t}if(n.some(t=>["minInclusive","minExclusive","maxInclusive","maxExclusive"].includes(t))){e.type="bounds";const t={},s=n.find(t=>t.includes("min")),r=n.find(t=>t.includes("max"));s&&(t.minInclusive="minInclusive"===s,t.min=i[s].value),r&&(t.maxInclusive="maxInclusive"===r,t.max=i[r].value),e.parameter=t}if(n.some(t=>["minLength","length","maxLength"].includes(t))){e.type="length";const t={};void 0!==i.length&&(t.length=i.length.value),void 0!==i.minLength&&(t.min=i.minLength.value),void 0!==i.maxLength&&(t.max=i.maxLength.value),e.parameter=t}}return void 0!==e.parameter?e:void 0},Pa=(t,e)=>{const i=[];for(const n of e){const e=n.name,s=Ma(e);if(!s)continue;const r=new Sa(t,s);n.cardinality&&(r.cardinality=n.cardinality),r.predefinedType=Ma(n.predefinedType),r.instructions=n.instructions,i.push(r)}return i},za=(t,e)=>{const i=[];for(const n of e){const e=n.name,s=Ma(e);if(!s)continue;const r=new va(t,s);n.cardinality&&(r.cardinality=n.cardinality),r.value=Ma(n.value),r.instructions=n.instructions,i.push(r)}return i},Ia=(t,e)=>{const i=[];for(const n of e){const e=new Ca(t);n.cardinality&&(e.cardinality=n.cardinality);const s=Ma(n.value);"enumeration"===(null==s?void 0:s.type)&&Array.isArray(s.parameter)&&(s.parameter=s.parameter.map(String)),e.value=s,e.uri=n.uri,e.instructions=n.instructions,i.push(e)}return i},Da=(t,e)=>{const i=[];for(const n of e){const e=n.propertySet,s=n.baseName,r=Ma(e),o=Ma(s);if(!o||!r)continue;const a=new Ta(t,r,o);n.cardinality&&(a.cardinality=n.cardinality);const l=Ma(n.value);a.value=l,a.dataType=n.dataType,a.uri=n.uri,a.instructions=n.instructions,i.push(a)}return i},ka=(t,e)=>{const i=[];for(const n of e){const e=n.system,s=Ma(e);if(!s)continue;const r=new xa(t,s);n.cardinality&&(r.cardinality=n.cardinality);const o=Ma(n.value);"simple"===(null==o?void 0:o.type)&&(o.parameter=String(o.parameter)),"enumeration"===(null==o?void 0:o.type)&&Array.isArray(o.parameter)&&(o.parameter=o.parameter.map(String)),r.value=o,r.uri=n.uri,r.instructions=n.instructions,i.push(r)}return i},Ba=(t,e)=>{const i=[];for(const n of e){const e=Ma(n.entity.name);if(!e)continue;const s=Ma(n.entity.predefinedType),r=new Aa(t,{name:e,predefinedType:s});r.relation=n.relation,n.cardinality&&(r.cardinality=n.cardinality),r.instructions=n.instructions,i.push(r)}return i},Oa=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"IDSInfo"),e(this,"list",new n),i.add(t.uuid,this)}getModelIdMap(t){const e={},i={};for(const[n,s]of t){const t=[...s].filter(([,t])=>t.pass).map(([t])=>t);Ve.append(e,n,...t);const r=[...s].filter(([,t])=>!t.pass).map(([t])=>t);Ve.append(i,n,...r)}return{pass:e,fail:i}}create(t,e,i){const n=new Ea(this.components,t,e);return i&&(n.identifier=i),this.list.set(n.identifier,n),n}load(e){const i=[],n=t.xmlParser.parse(e).ids,{specifications:s,info:r}=n;if(this.IDSInfo={...r},s&&s.specification){const t=Array.isArray(s.specification)?s.specification:[s.specification];for(const e of t){const{name:t,ifcVersion:n,description:s,instructions:r,identifier:o}=e;if(!t||!n)continue;const a=[],l=[],{applicability:c,requirements:h}=e;if(c){const{maxOccurs:t,...e}=c,i=Array.isArray(e)?e:[e];for(const t of i)for(const e in t){const i=Array.isArray(t[e])?t[e]:[t[e]];if("entity"===e){const t=Pa(this.components,i);a.push(...t)}if("attribute"===e){const t=za(this.components,i);a.push(...t)}if("material"===e){const t=Ia(this.components,i);a.push(...t)}if("classification"===e){const t=ka(this.components,i);a.push(...t)}if("property"===e){const t=Da(this.components,i);a.push(...t)}if("partOf"===e){const t=Ba(this.components,i);a.push(...t)}}}let d;if(h){const{maxOccurs:t,...e}=h;d=h.description;const i=Array.isArray(e)?e:[e];for(const t of i)for(const e in t){const i=Array.isArray(t[e])?t[e]:[t[e]];if("entity"===e){const t=Pa(this.components,i);l.push(...t)}if("attribute"===e){const t=za(this.components,i);l.push(...t)}if("material"===e){const t=Ia(this.components,i);l.push(...t)}if("classification"===e){const t=ka(this.components,i);l.push(...t)}if("property"===e){const t=Da(this.components,i);l.push(...t)}if("partOf"===e){const t=Ba(this.components,i);l.push(...t)}}}const u=this.create(t,n.split(/\s+/),o);u.description=s,u.instructions=r,u.requirementsDescription=d,u.applicability.add(...a),u.requirements.add(...l),i.push(u)}}return i}export(t,e=this.list.values()){const i=e??this.list;return`<ids xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://standards.buildingsmart.org/IDS http://standards.buildingsmart.org/IDS/1.0/ids.xsd" xmlns:ids="http://standards.buildingsmart.org/IDS">\n \x3c!-- Made with That Open Engine ${Uo.release} (https://github.com/thatopen/engine_components) --\x3e\n <info>\n <title>${t.title}</title>\n ${t.copyright?`<copyright>${t.copyright}</copyright>`:""}\n ${t.version?`<version>${t.version}</version>`:""}\n ${t.description?`<description>${t.description}</description>`:""}\n ${t.author?`<author>${t.author}</author>`:""}\n ${t.date?`<date>${t.date.toISOString().split("T")[0]}</date>`:""}\n ${t.purpose?`<purpose>${t.purpose}</purpose>`:""}\n ${t.milestone?`<milestone>${t.milestone}</milestone>`:""}\n </info>\n <specifications>\n ${[...i].map(t=>t.serialize()).join("\n")}\n </specifications>\n</ids>`}};e(Oa,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c"),e(Oa,"xmlParser",new xe({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let Va=Oa;const La=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),i.add(t.uuid,this)}static distanceFromPointToLine(t,e,i,n=!1){const s=new o.Line3,r=new o.Vector3;return s.set(e,i),s.closestPointToPoint(t,n,r),r.distanceTo(t)}round(t){const e=1e3;t.x=Math.trunc(t.x*e)/e,t.y=Math.trunc(t.y*e)/e,t.z=Math.trunc(t.z*e)/e}async getVolumeFromFragments(t){return console.warn("getVolumeFromFragments is deprecated. Use getItemsVolume instead."),this.getItemsVolume(t)}async getItemsVolume(t){let e=0;const i=this.components.get(Ws);for(const[n,s]of Object.entries(t)){const t=i.list.get(n);t&&(e+=await t.getItemsVolume([...s]))}return e}static convertUnits(t,e,i,n=2){const s={m:1,cm:.01,mm:.001,km:1e3,m2:1,cm2:1e-4,mm2:1e-6,km2:1e6,m3:1,cm3:1e-6,mm3:1e-9,km3:1e9};if(!s[e]||!s[i])throw new Error("Invalid units provided for conversion.");if(!Number.isInteger(n)||n<0||n>5)throw new Error("Precision must be an integer between 0 and 5.");const r=t*(s[e]/s[i]),o=10**n;return Math.round(r*o)/o}};e(La,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");let Na=La;const Fa=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=new o.Vector3(e.x+n.x,0,e.z+n.z).normalize().multiplyScalar(i/2);return[t.x+s.x,t.y,t.z+s.z,t.x-s.x,t.y,t.z-s.z]},Ra=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=t.x-e.x*i+n.x*i*.4,r=t.z-e.z*i+n.z*i*.4,a=t.x-e.x*i-n.x*i*.4,l=t.z-e.z*i-n.z*i*.4;return[t.x,t.y,t.z,s,t.y,r,t.x,t.y,t.z,a,t.y,l,s,t.y,r,a,t.y,l]},Ua=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=t.x-e.x*i+n.x*i*.4,r=t.z-e.z*i+n.z*i*.4,a=t.x-e.x*i-n.x*i*.4,l=t.z-e.z*i-n.z*i*.4;return[t.x,t.y,t.z,s,t.y,r,t.x,t.y,t.z,a,t.y,l]},ja=()=>[],$a=(t,e,i)=>{const n=.4*i,s=[];for(let e=0;e<12;e++){const i=e/12*Math.PI*2,r=(e+1)/12*Math.PI*2;s.push(t.x+Math.cos(i)*n,t.y,t.z+Math.sin(i)*n,t.x+Math.cos(r)*n,t.y,t.z+Math.sin(r)*n)}return s},Wa=(t,e,i)=>{const n=.4*i,s=[];for(let e=0;e<16;e++){const i=e/16*Math.PI*2,r=(e+1)/16*Math.PI*2;s.push(t.x,t.y,t.z,t.x+Math.cos(i)*n,t.y,t.z+Math.sin(i)*n,t.x+Math.cos(r)*n,t.y,t.z+Math.sin(r)*n)}return s},Ga=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=.4*i,r=t.clone().addScaledVector(e,s).addScaledVector(n,s),a=t.clone().addScaledVector(e,s).addScaledVector(n,-s),l=t.clone().addScaledVector(e,-s).addScaledVector(n,-s),c=t.clone().addScaledVector(e,-s).addScaledVector(n,s);return[r.x,r.y,r.z,a.x,a.y,a.z,l.x,l.y,l.z,r.x,r.y,r.z,l.x,l.y,l.z,c.x,c.y,c.z]},Ha=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=t.clone().addScaledVector(e,-i),r=s.clone().addScaledVector(n,.4*i),a=s.clone().addScaledVector(n,.4*-i);return[t.x,t.y,t.z,r.x,r.y,r.z,a.x,a.y,a.z]};class qa extends i.DataMap{constructor(){super()}getBySystem(t){const e=new Map;for(const[i,n]of this)n.system===t&&e.set(i,n.data);return e}}class Za extends i.DataMap{constructor(t){super(),e(this,"_container"),this._container=t,this.deleteGuard=t=>"0"!==t,this.set("0",{name:"0",visible:!0,material:new o.LineBasicMaterial({color:0})})}create(t,e){if(!this.has(t)){const i={name:t,visible:(null==e?void 0:e.visible)??!0,material:(null==e?void 0:e.material)??new o.LineBasicMaterial({color:0})};this.set(t,i)}return this.get(t)}setColor(t,e){const i=this.get(t);i&&(i.material.color.setHex(e),this.set(t,i))}setMaterial(t,e){const i=this.get(t);if(!i)return;const n=i.material;i.material=e,this._container.traverse(i=>{i.userData.layer===t&&(i.userData.isDimension||i.isLineSegments&&(i.material=e))}),n.dispose(),this.set(t,i)}setVisibility(t,e){const i=this.get(t);i&&(i.visible=e,this._container.traverse(i=>{i.userData.layer===t&&(i.visible=e)}),this.set(t,i))}assign(t,e){const i=this.get(e);i&&(t.userData.layer=e,i.visible||(t.visible=!1),t.isLineSegments&&(t.material=i.material))}resolveColor(t){const e=this.get(t);if(e)return e.material.color.getHex()}}const Ya=class t extends o.Group{constructor(i){super(),e(this,"_viewport"),e(this,"_border"),e(this,"_handles",[]),e(this,"_raycaster",new o.Raycaster),e(this,"_resizable",!1),e(this,"_movable",!1),e(this,"_dragHandle",null),e(this,"_dragConstraints",[]),e(this,"_hoveredHandle",null),e(this,"_moveDrag",null),e(this,"_hoveringBorder",!1),e(this,"_normalMat"),e(this,"_hoverMat"),e(this,"_borderMat"),this._viewport=i,this._borderMat=new o.LineBasicMaterial({color:t._BORDER_COLOR,depthTest:!1});const n=new o.BufferGeometry;n.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._border=new o.LineSegments(n,this._borderMat),this._border.renderOrder=999,this._border.frustumCulled=!1,this._border.userData.isDimension=!0,this.add(this._border),this._normalMat=new o.MeshBasicMaterial({color:t._BORDER_COLOR}),this._hoverMat=new o.MeshBasicMaterial({color:t._BORDER_HOVER_COLOR});const s=new o.SphereGeometry(.05,8,6);for(const e of t._HANDLE_DEFS){const t=new o.Mesh(s,this._normalMat);t.renderOrder=1e3,t.visible=!1,t.userData.constraints=e.constraints,t.userData.isDimension=!0,this.add(t),this._handles.push(t)}this.update()}get resizable(){return this._resizable}set resizable(t){this._resizable=t;for(const e of this._handles)e.visible=t;t||(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat,this._hoveredHandle=null),this._dragHandle=null,this._dragConstraints=[])}get movable(){return this._movable}set movable(t){this._movable=t,t||(this._moveDrag=null,this._setBorderHover(!1))}get isDragging(){return null!==this._dragHandle||null!==this._moveDrag}update(){const t=this._viewport,e=t.left,i=t.right,n=-t.top,s=-t.bottom,r=.005,o=this._border.geometry.attributes.position;o.setXYZ(0,e,r,n),o.setXYZ(1,i,r,n),o.setXYZ(2,i,r,n),o.setXYZ(3,i,r,s),o.setXYZ(4,i,r,s),o.setXYZ(5,e,r,s),o.setXYZ(6,e,r,s),o.setXYZ(7,e,r,n),o.needsUpdate=!0,this._border.geometry.computeBoundingSphere();const a=(e+i)/2,l=(n+s)/2,c=.01,h=[[e,c,n],[i,c,n],[i,c,s],[e,c,s],[a,c,n],[i,c,l],[a,c,s],[e,c,l]];for(let t=0;t<this._handles.length;t++)this._handles[t].position.set(...h[t])}onPointerMove(e){if(this._dragHandle){const t=this._projectToLocal(e);if(!t)return;for(const e of this._dragConstraints)switch(e){case"left":this._viewport.left=t.x;break;case"right":this._viewport.right=t.x;break;case"top":this._viewport.top=-t.z;break;case"bottom":this._viewport.bottom=-t.z}return this._viewport.right<this._viewport.left&&([this._viewport.left,this._viewport.right]=[this._viewport.right,this._viewport.left],this._dragConstraints=this._dragConstraints.map(t=>"right"===t?"left":"left"===t?"right":t)),this._viewport.top<this._viewport.bottom&&([this._viewport.top,this._viewport.bottom]=[this._viewport.bottom,this._viewport.top],this._dragConstraints=this._dragConstraints.map(t=>"top"===t?"bottom":"bottom"===t?"top":t)),void this.update()}if(this._moveDrag){const t=this._projectToLocal(e);if(!t)return;const i=t.x-this._moveDrag.origin.x,n=t.z-this._moveDrag.origin.z;return this._viewport.left=this._moveDrag.left0+i,this._viewport.right=this._moveDrag.right0+i,this._viewport.top=this._moveDrag.top0-n,this._viewport.bottom=this._moveDrag.bottom0-n,void this.update()}if(!this._resizable&&!this._movable)return;this._raycaster.set(e.origin,e.direction);let i=null;if(this._resizable){const t=this._handles.filter(t=>t.visible),e=this._raycaster.intersectObjects(t,!1);i=e.length>0?e[0].object:null}if(i!==this._hoveredHandle&&(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat),i&&(i.material=this._hoverMat),this._hoveredHandle=i),this._movable&&!this._hoveredHandle){this._raycaster.params.Line={threshold:t._LINE_THRESHOLD};const e=this._raycaster.intersectObject(this._border,!1).length>0;this._setBorderHover(e)}else this._setBorderHover(!1)}onPointerDown(e){if(this._resizable||this._movable){if(this._raycaster.set(e.origin,e.direction),this._resizable){const t=this._handles.filter(t=>t.visible),e=this._raycaster.intersectObjects(t,!1);if(e.length>0)return this._dragHandle=e[0].object,void(this._dragConstraints=[...this._dragHandle.userData.constraints])}if(this._movable){this._raycaster.params.Line={threshold:t._LINE_THRESHOLD};if(this._raycaster.intersectObject(this._border,!1).length>0){const t=this._projectToLocal(e);if(!t)return;this._moveDrag={origin:t,left0:this._viewport.left,right0:this._viewport.right,top0:this._viewport.top,bottom0:this._viewport.bottom}}}}}onPointerUp(){this._dragHandle=null,this._dragConstraints=[],this._moveDrag=null}dispose(){this._border.geometry.dispose(),this._borderMat.dispose(),this._normalMat.dispose(),this._hoverMat.dispose(),this._handles.length>0&&this._handles[0].geometry.dispose(),this.removeFromParent()}_projectToLocal(t){this.updateWorldMatrix(!0,!1);const e=new o.Vector3(0,1,0).transformDirection(this.matrixWorld),i=(new o.Vector3).setFromMatrixPosition(this.matrixWorld),n=(new o.Plane).setFromNormalAndCoplanarPoint(e,i),s=new o.Vector3;return t.intersectPlane(n,s)?this.worldToLocal(s):null}_setBorderHover(e){e!==this._hoveringBorder&&(this._hoveringBorder=e,this._borderMat.color.setHex(e?t._BORDER_HOVER_COLOR:t._BORDER_COLOR))}};e(Ya,"_BORDER_COLOR",22015),e(Ya,"_BORDER_HOVER_COLOR",16746496),e(Ya,"_LINE_THRESHOLD",.06),e(Ya,"_HANDLE_DEFS",[{constraints:["left","top"]},{constraints:["right","top"]},{constraints:["right","bottom"]},{constraints:["left","bottom"]},{constraints:["top"]},{constraints:["right"]},{constraints:["bottom"]},{constraints:["left"]}]);let Xa=Ya;class Ka{constructor(t){e(this,"uuid",o.MathUtils.generateUUID()),e(this,"name"),e(this,"camera"),e(this,"onDisposed",new at),e(this,"_left"),e(this,"_right"),e(this,"_top"),e(this,"_bottom"),e(this,"_drawingScale"),e(this,"_container",null),e(this,"_helper",null),e(this,"_helperVisible",!1),this._left=t.left,this._right=t.right,this._top=t.top,this._bottom=t.bottom,this._drawingScale=t.scale??100,this.name=t.name??"Drawing Viewport",this.camera=new o.OrthographicCamera(this._left,this._right,this._top,this._bottom,.1,30),this.camera.up.set(0,0,-1),this.camera.position.set(0,10,0),this.camera.lookAt(0,0,0),this.camera.layers.set(1)}get left(){return this._left}set left(t){var e;this._left=t,this.camera.left=t,this.camera.updateProjectionMatrix(),null==(e=this._helper)||e.update()}get right(){return this._right}set right(t){var e;this._right=t,this.camera.right=t,this.camera.updateProjectionMatrix(),null==(e=this._helper)||e.update()}get top(){return this._top}set top(t){var e;this._top=t,this.camera.top=t,this.camera.updateProjectionMatrix(),null==(e=this._helper)||e.update()}get bottom(){return this._bottom}set bottom(t){var e;this._bottom=t,this.camera.bottom=t,this.camera.updateProjectionMatrix(),null==(e=this._helper)||e.update()}get drawingScale(){return this._drawingScale}set drawingScale(t){this._drawingScale=t}get helper(){return this._helper||(this._helper=new Xa(this)),this._helper}get helperVisible(){return this._helperVisible}set helperVisible(t){var e,i;this._helperVisible=t,t?null==(e=this._container)||e.add(this.helper):null==(i=this._helper)||i.removeFromParent()}get bbox(){const t=new o.Vector3(this._left,0,-this._top),e=new o.Vector3(this._right,0,-this._bottom);return new o.Box3(t,e)}get size(){const t=new o.Vector3;return this.bbox.getSize(t),new o.Vector2(1e3*t.x,1e3*t.z)}get localXAxis(){return new o.Vector3(1,0,0)}get localYAxis(){return new o.Vector3(0,0,-1)}get normal(){return new o.Vector3(0,1,0)}setContainer(t){this._container=t,this._helperVisible&&this._helper&&t.add(this._helper)}clipLine(t){const e=this.bbox,{start:i,end:n}=t,s=e.containsPoint(i),r=e.containsPoint(n);if(s&&r)return t;if(!s&&!r){const e=this.getPlaneIntersections(t);return e.length<2?null:new o.Line3(e[0],e[1])}const a=this.getPlaneIntersections(t);return 0===a.length?null:s?new o.Line3(i,a[0]):new o.Line3(a[0],n)}dispose(){var t;null==(t=this._helper)||t.dispose(),this._helper=null,this.onDisposed.trigger(),this.onDisposed.reset()}get bboxPlanes(){const t=this.bbox;return[new o.Plane(new o.Vector3(1,0,0),-t.min.x),new o.Plane(new o.Vector3(-1,0,0),t.max.x),new o.Plane(new o.Vector3(0,0,1),-t.min.z),new o.Plane(new o.Vector3(0,0,-1),t.max.z)]}getPlaneIntersections(t){const e=[];for(const i of this.bboxPlanes){const n=new o.Vector3;i.intersectLine(t,n)&&this.bbox.containsPoint(n)&&e.push(n)}return e}}class Qa extends i.DataMap{constructor(t){super(),e(this,"_container"),this._container=t,this.onBeforeDelete.add(({value:t})=>{this._container.remove(t.camera),t.dispose()})}create(t){const e=new Ka(t);return this._container.add(e.camera),e.setContainer(this._container),this.set(e.uuid,e),e}}const Ja=class t extends o.Group{constructor(i){super(),e(this,"_drawing"),e(this,"_topFrame"),e(this,"_pillars"),e(this,"_bottomFrame"),e(this,"_topPlane"),e(this,"_bottomPlane"),e(this,"_frameMat"),e(this,"_depthMat"),e(this,"_planeMat"),e(this,"width",10),e(this,"height",10),e(this,"farHandle",new o.Object3D),e(this,"widthHandle",new o.Object3D),e(this,"heightHandle",new o.Object3D),this._drawing=i,this._frameMat=new o.LineBasicMaterial({color:t._FRAME_COLOR,depthTest:!1}),this._depthMat=new o.LineBasicMaterial({color:t._DEPTH_COLOR,depthTest:!1,transparent:!0,opacity:.4}),this._planeMat=new o.MeshBasicMaterial({color:t._FRAME_COLOR,transparent:!0,opacity:.07,side:o.DoubleSide,depthTest:!1});const n=()=>{const t=new o.BufferGeometry;return t.setAttribute("position",new o.BufferAttribute(new Float32Array(12),3)),t.setIndex([0,1,2,0,2,3]),t};this._topPlane=new o.Mesh(n(),this._planeMat),this._topPlane.renderOrder=998,this._topPlane.frustumCulled=!1,this._topPlane.userData.isDimension=!0,this._bottomPlane=new o.Mesh(n(),this._planeMat),this._bottomPlane.renderOrder=998,this._bottomPlane.frustumCulled=!1,this._bottomPlane.userData.isDimension=!0;const s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._topFrame=new o.LineSegments(s,this._frameMat),this._topFrame.renderOrder=999,this._topFrame.frustumCulled=!1,this._topFrame.userData.isDimension=!0;const r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._pillars=new o.LineSegments(r,this._depthMat),this._pillars.renderOrder=999,this._pillars.frustumCulled=!1,this._pillars.userData.isDimension=!0;const a=new o.BufferGeometry;a.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._bottomFrame=new o.LineSegments(a,this._depthMat),this._bottomFrame.renderOrder=999,this._bottomFrame.frustumCulled=!1,this._bottomFrame.userData.isDimension=!0,this.add(this._topPlane,this._bottomPlane),this.add(this._topFrame,this._pillars,this._bottomFrame),this.add(this.farHandle,this.widthHandle,this.heightHandle),this.farHandle.rotation.x=Math.PI,this.update()}update(){const t=this.width/2,e=this.height/2,i=-this._drawing.far,n=.005,s=-t,r=t,o=-e,a=e,l=this._topFrame.geometry.attributes.position;l.setXYZ(0,s,n,o),l.setXYZ(1,r,n,o),l.setXYZ(2,r,n,o),l.setXYZ(3,r,n,a),l.setXYZ(4,r,n,a),l.setXYZ(5,s,n,a),l.setXYZ(6,s,n,a),l.setXYZ(7,s,n,o),l.needsUpdate=!0,this._topFrame.geometry.computeBoundingSphere();const c=this._pillars.geometry.attributes.position;c.setXYZ(0,s,n,o),c.setXYZ(1,s,i,o),c.setXYZ(2,r,n,o),c.setXYZ(3,r,i,o),c.setXYZ(4,r,n,a),c.setXYZ(5,r,i,a),c.setXYZ(6,s,n,a),c.setXYZ(7,s,i,a),c.needsUpdate=!0,this._pillars.geometry.computeBoundingSphere();const h=this._bottomFrame.geometry.attributes.position;h.setXYZ(0,s,i,o),h.setXYZ(1,r,i,o),h.setXYZ(2,r,i,o),h.setXYZ(3,r,i,a),h.setXYZ(4,r,i,a),h.setXYZ(5,s,i,a),h.setXYZ(6,s,i,a),h.setXYZ(7,s,i,o),h.needsUpdate=!0,this._bottomFrame.geometry.computeBoundingSphere();const d=(t,e)=>{const i=t.geometry.attributes.position;i.setXYZ(0,s,e,o),i.setXYZ(1,r,e,o),i.setXYZ(2,r,e,a),i.setXYZ(3,s,e,a),i.needsUpdate=!0,t.geometry.computeBoundingSphere()};d(this._topPlane,n),d(this._bottomPlane,i),this.farHandle.position.set(0,i,0),this.widthHandle.position.set(r,n,0),this.heightHandle.position.set(0,n,a)}attachFarGizmo(t){t.attach(this.farHandle),t.setSpace("local"),t.showX=!1,t.showZ=!1,t.addEventListener("objectChange",()=>{this.farHandle.position.x=0,this.farHandle.position.z=0;const t=Math.max(.1,-this.farHandle.position.y);this._drawing.far=t,this.farHandle.position.y=-t,this.update()})}attachWidthGizmo(t){t.attach(this.widthHandle),t.setSpace("local"),t.showY=!1,t.showZ=!1,t.addEventListener("objectChange",()=>{this.widthHandle.position.y=.005,this.widthHandle.position.z=0,this.width=Math.max(.1,2*this.widthHandle.position.x),this.widthHandle.position.x=this.width/2,this.update()})}attachHeightGizmo(t){t.attach(this.heightHandle),t.setSpace("local"),t.showX=!1,t.showY=!1,t.addEventListener("objectChange",()=>{this.heightHandle.position.x=0,this.heightHandle.position.y=.005,this.height=Math.max(.1,2*this.heightHandle.position.z),this.heightHandle.position.z=this.height/2,this.update()})}dispose(){this._topPlane.geometry.dispose(),this._bottomPlane.geometry.dispose(),this._topFrame.geometry.dispose(),this._pillars.geometry.dispose(),this._bottomFrame.geometry.dispose(),this._planeMat.dispose(),this._frameMat.dispose(),this._depthMat.dispose(),this.removeFromParent()}};e(Ja,"_FRAME_COLOR",22015),e(Ja,"_DEPTH_COLOR",22015);let tl=Ja;function el(t,e){if(3!==t.length||3!==e.length)throw new Error("computeAlignmentMatrix requires exactly 3 point pairs.");const i=(t,e)=>{const i=(new o.Vector3).subVectors(t[1],t[0]),n=(new o.Vector3).subVectors(t[2],t[0]);if((new o.Vector3).crossVectors(i,n).length()<1e-6)throw new Error(`${e} points are collinear — three non-collinear points are required to define a plane.`)};i(t,"Drawing"),i(e,"World");const n=(t,e,i)=>{const n=(new o.Vector3).subVectors(e,t),s=(new o.Vector3).subVectors(i,t),r=n.clone().normalize(),a=(new o.Vector3).crossVectors(n,s).normalize(),l=(new o.Vector3).crossVectors(r,a).normalize();return(new o.Matrix4).makeBasis(r,a,l)},s=n(t[0],t[1],t[2]),r=n(e[0],e[1],e[2]).clone().multiply(s.clone().invert()),a=t[0].distanceTo(t[1]);if(a<1e-10)throw new Error("The first two drawing points are coincident — cannot compute scale.");const l=e[0].distanceTo(e[1])/a,c=t[0].clone().multiplyScalar(l).applyMatrix4(r),h=(new o.Vector3).subVectors(e[0],c),d=(new o.Quaternion).setFromRotationMatrix(r),u=new o.Matrix4;return u.compose(h,d,new o.Vector3(l,l,l)),u}class il{constructor(t){e(this,"uuid",o.MathUtils.generateUUID()),e(this,"_raycaster",new o.Raycaster),e(this,"_components"),e(this,"world",null),e(this,"three",new o.Group),e(this,"annotations",new qa),e(this,"layers",new Za(this.three)),e(this,"activeLayer","0"),e(this,"far",10),e(this,"viewports",new Qa(this.three)),e(this,"onDisposed",new at),this._components=t}raycast(t,e=null){this._raycaster.set(t.origin,t.direction),this._raycaster.layers.set(1),this._raycaster.params.Line&&(this._raycaster.params.Line.threshold=.1);const i=[];this.three.traverse(t=>{t instanceof o.LineSegments&&!t.userData.isDimension&&i.push(t)});const n=this._raycaster.intersectObjects(i,!1);if(0===n.length)return null;const s=n[0],r=this.three.worldToLocal(s.point.clone());let a=null;if(s.object instanceof o.LineSegments&&void 0!==s.index){const t=s.object.geometry.attributes.position,e=s.index,i=new o.Vector3(t.getX(e),t.getY(e),t.getZ(e)),n=new o.Vector3(t.getX(e+1),t.getY(e+1),t.getZ(e+1));i.applyMatrix4(s.object.matrixWorld),this.three.worldToLocal(i),n.applyMatrix4(s.object.matrixWorld),this.three.worldToLocal(n),a=new o.Line3(i,n)}return{point:r,object:s.object,viewport:e,line:a}}alignTo(t,e){el(t,e).decompose(this.three.position,this.three.quaternion,this.three.scale)}static toDrawingSpace(t,e){t.updateWorldMatrix(!0,!1),e.three.updateWorldMatrix(!0,!1);const i=(new o.Matrix4).copy(e.three.matrixWorld).invert().multiply(t.matrixWorld),n=t.geometry.attributes.position,s=n.count,r=new Float32Array(3*s),a=new o.Vector3;for(let t=0;t<s;t++)a.fromBufferAttribute(n,t).applyMatrix4(i),r[3*t]=a.x,r[3*t+1]=0,r[3*t+2]=a.z;const l=new o.BufferGeometry;return l.setAttribute("position",new o.BufferAttribute(r,3)),new o.LineSegments(l)}addProjectionLines(t,e="0"){return this.layers.has(e)||(console.warn(`[TechnicalDrawing] Layer "${e}" does not exist. Falling back to "0".`),e="0"),this.layers.assign(t,e),t.layers.set(1),t.material instanceof o.LineDashedMaterial&&t.computeLineDistances(),t.geometry.computeBoundsTree({strategy:0,indirect:!0,type:Bs}),this.three.add(t),t}async addProjectionFromItems(t,e){if(!this.world)return void console.warn("[TechnicalDrawing] addProjectionFromItems: drawing has no world assigned.");for(const t of[e.layers.visible,e.layers.hidden])if(!this.layers.has(t))return void console.warn(`[TechnicalDrawing] Layer "${t}" does not exist — create it before calling addProjectionFromItems.`);const i=this._components.get(oo),n=i.projectionDirection.clone(),s=i.nearPlane,r=i.farPlane;try{this.three.updateWorldMatrix(!0,!1);const n=new o.Vector3(0,-1,0).transformDirection(this.three.matrixWorld).normalize();i.projectionDirection.copy(n);const s=(new o.Matrix4).makeRotationFromQuaternion((new o.Quaternion).setFromUnitVectors(n,new o.Vector3(0,-1,0))),r=(new o.Vector3).setFromMatrixPosition(this.three.matrixWorld).applyMatrix4(s).y;i.farPlane=r,i.nearPlane=r-this.far;const a=await i.get(t,this.world,{onProgress:e.onProgress}),l=t=>il.toDrawingSpace(new o.LineSegments(t),this);this.addProjectionLines(l(a.visible),e.layers.visible),this.addProjectionLines(l(a.hidden),e.layers.hidden)}finally{i.projectionDirection.copy(n),i.nearPlane=s,i.farPlane=r}}orientTo(t){const e=t.clone().normalize(),i=Math.SQRT1_2;e.x>.999?this.three.quaternion.set(.5,-.5,.5,.5):e.x<-.999?this.three.quaternion.set(.5,.5,-.5,.5):e.y>.999?this.three.quaternion.set(0,0,1,0):e.y<-.999?this.three.quaternion.set(0,0,0,1):e.z>.999?this.three.quaternion.set(0,i,-i,0):e.z<-.999?this.three.quaternion.set(i,0,0,i):console.warn("[TechnicalDrawing] orientTo: direction does not match any of the 6 standard axes.")}dispose(){this.viewports.clear(),this.layers.clear(),this.annotations.clear();this._components.get(mt).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset()}}const nl={m:{factor:1,suffix:"m"},cm:{factor:100,suffix:"cm"},mm:{factor:1e3,suffix:"mm"},ft:{factor:3.28084,suffix:"ft"},in:{factor:39.3701,suffix:"in"}};class sl{constructor(t){e(this,"styles",new i.DataMap),e(this,"activeStyle","default"),e(this,"onCommit",new at),e(this,"onUpdate",new at),e(this,"onDelete",new at),e(this,"onDisposed",new at),e(this,"_knownDrawings",new Set),e(this,"_previewMaterial",new o.LineBasicMaterial({color:16737894,depthTest:!1})),e(this,"_previewObject",null),e(this,"_previewDrawing",null),e(this,"_materialCache",new i.DataMap),e(this,"_meshMaterialCache",new i.DataMap),e(this,"_ownsChildGeometry",!0),this._components=t,this.styles.onItemUpdated.add(({key:t})=>{const e=this._materialCache.get(t);e&&e.color.setHex(this._resolveStyle(t).color);const i=this._meshMaterialCache.get(t);i&&i.color.setHex(this._resolveStyle(t).color);const n=this._components.get($l),s=n?[...n.list.values()]:[...this._knownDrawings];for(const e of s){const i=[...e.annotations.getBySystem(this)].filter(([,e])=>e.style===t).map(([t])=>t);i.length>0&&this.update(e,i,{})}})}_onAfterPersist(t,e){}_onDispose(){}_updatePreview(){}get(t){const e=new i.DataMap;for(const i of t)for(const[t,n]of i.annotations.getBySystem(this))e.set(t,{drawingUuid:i.uuid,item:n});return e}add(t,e){const i={uuid:o.MathUtils.generateUUID(),style:this.activeStyle,...e},n=this._persist(t,i);return this.onCommit.trigger([n]),i}update(t,e,i){for(const n of e){const e=t.annotations.get(n);if(!e||e.system!==this)continue;const s=e.data;Object.assign(s,i),this._redraw(s,e.three),this.onUpdate.trigger({item:s,group:e.three})}}pick(t,e=.05){const i=new o.Raycaster;i.ray.copy(t),i.params.Line={threshold:e},i.params.LineSegments={threshold:e};const n=o.Line.prototype.raycast;let s=null,r=1/0;for(const t of this._knownDrawings)for(const[e,a]of t.annotations){if(a.system!==this)continue;const t=a.three;t.updateWorldMatrix(!0,!0),t.traverse(a=>{if(a===t)return;const l=[];if(a instanceof o.LineSegments&&a.userData.isDimension)n.call(a,i,l),l.length>0&&l[0].distance<r&&(r=l[0].distance,s=e);else if(a instanceof o.Mesh){const t=(new o.Box3).setFromObject(a),n=new o.Vector3;if(i.ray.intersectBox(t,n)){const t=i.ray.origin.distanceTo(n);t<r&&(r=t,s=e)}}})}return s}delete(t,e){const i=[];for(const n of e){const e=t.annotations.get(n);e&&e.system===this&&(this._disposeGroup(e.three),t.annotations.delete(n),i.push(n))}i.length&&this.onDelete.trigger(i)}clear(t){const e=t??[...this._knownDrawings];for(const t of e){const e=[];for(const[i,n]of t.annotations)n.system===this&&e.push(i);for(const i of e){const e=t.annotations.get(i);this._disposeGroup(e.three),t.annotations.delete(i)}}}dispose(){this._clearPreview(),this._onDispose(),this.clear();for(const t of this._materialCache.values())t.dispose();this._materialCache.clear();for(const t of this._meshMaterialCache.values())t.dispose();this._meshMaterialCache.clear(),this._previewMaterial.dispose(),this.onCommit.reset(),this.onUpdate.reset(),this.onDelete.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}_trackDrawing(t){this._knownDrawings.has(t)||(this._knownDrawings.add(t),t.onDisposed.add(()=>this._knownDrawings.delete(t)))}_resolveStyle(t){return this.styles.get(t)??this.styles.get("default")}_getMaterial(t){const e=this._materialCache.get(t);if(e)return e;const i=new o.LineBasicMaterial({color:this._resolveStyle(t).color});return this._materialCache.set(t,i),i}_getMeshMaterial(t){const e=this._meshMaterialCache.get(t);if(e)return e;const i=new o.MeshBasicMaterial({color:this._resolveStyle(t).color,side:o.DoubleSide});return this._meshMaterialCache.set(t,i),i}_disposeGroup(t){if(t.removeFromParent(),this._ownsChildGeometry)t.traverse(t=>{t.geometry instanceof o.BufferGeometry&&t.geometry.dispose()});else for(;t.children.length>0;)t.remove(t.children[0])}_clearPreview(){this._previewObject&&(this._previewObject.removeFromParent(),this._previewObject.geometry.dispose(),this._previewObject=null)}_persist(t,e){this._trackDrawing(t);const i=this._resolveStyle(e.style),n=this._buildGroup(e,i);return n.userData.isDimension=!0,n.userData.annotationUuid=e.uuid,n.userData.layer=t.activeLayer,t.three.add(n),t.annotations.set(e.uuid,{system:this,data:e,three:n}),this._onAfterPersist(e,n),{drawing:t,item:e,group:n}}_redraw(t,e){for(;e.children.length>0;){const t=e.children[0];this._ownsChildGeometry&&t.geometry instanceof o.BufferGeometry&&t.geometry.dispose(),e.remove(t)}const i=this._resolveStyle(t.style),n=this._buildGroup(t,i);for(;n.children.length>0;)e.add(n.children[0]);this._onAfterPersist(t,e)}}function rl(t,e){const i=t[0],n=t[t.length-1],s=(new o.Vector3).subVectors(n,i);if(s.lengthSq()<1e-10)return 0;s.normalize();const r=new o.Vector3(-s.z,0,s.x);return e.clone().sub(i).dot(r)}function ol(t,e){const i=[];for(let n=0;n<t.length-1;n++)i.push({uuid:o.MathUtils.generateUUID(),pointA:t[n].clone(),pointB:t[n+1].clone(),offset:e,style:""});return i}function al(t,e){switch(t.kind){case"awaitingFirstPoint":if("CLICK"===e.type){if(!e.line)return t;const i=(new o.Vector3).subVectors(e.line.end,e.line.start).normalize();return{kind:"placingPoints",points:[e.point.clone()],cursor:null,lineDir:i,firstLine:e.line.clone()}}return"SELECT_LINE"===e.type?{kind:"positioningOffset",points:[e.line.start.clone(),e.line.end.clone()],cursor:null}:t;case"placingPoints":if("MOUSE_MOVE"===e.type){const i=new o.Vector3(-t.lineDir.z,0,t.lineDir.x),n=t.points[t.points.length-1],s=e.point.clone().sub(n).dot(i),r=n.clone().addScaledVector(i,s);return{...t,cursor:r}}if("CLICK"===e.type){if(!e.line)return t;if(function(t,e){const i=1e-6;return t.start.distanceTo(e.start)<i&&t.end.distanceTo(e.end)<i||t.start.distanceTo(e.end)<i&&t.end.distanceTo(e.start)<i}(e.line,t.firstLine))return t;const s=(new o.Vector3).subVectors(e.line.end,e.line.start).normalize();if(i=s,n=t.lineDir,!(Math.abs(i.dot(n))>.999))return t;const r=function(t,e,i){const n=t.clone().sub(e.start).dot(i);return e.start.clone().addScaledVector(i,n)}(t.points[0],e.line,t.lineDir),a=[...t.points,r];return{...t,points:a,cursor:t.cursor}}return"CONFIRM"===e.type&&t.points.length>=2?{kind:"positioningOffset",points:t.points,cursor:null}:"ESCAPE"===e.type?{kind:"awaitingFirstPoint"}:t;case"positioningOffset":if("MOUSE_MOVE"===e.type)return{...t,cursor:e.point.clone()};if("CLICK"===e.type){const i=rl(t.points,e.point);return{kind:"committed",dimensions:ol(t.points,i)}}return"ESCAPE"===e.type?{kind:"awaitingFirstPoint"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingFirstPoint"}:t}var i,n}function ll(t){const{pointA:e,pointB:i,offset:n}=t,s=(new o.Vector3).subVectors(i,e),r=new o.Vector3(-s.z,0,s.x).normalize(),a=e.clone().addScaledVector(r,n),l=i.clone().addScaledVector(r,n),c=(new o.Vector3).subVectors(l,a).normalize();return[{tip:a,dir:c},{tip:l,dir:c.clone().negate()}]}function cl(t,e){const{pointA:i,pointB:n,offset:s}=t,r=(new o.Vector3).subVectors(n,i),a=new o.Vector3(-r.z,0,r.x).normalize(),l=s>=0?1:-1,c=Math.abs(s),h=i.clone().addScaledVector(a,e.extensionGap*l),d=i.clone().addScaledVector(a,(c+e.extensionOvershoot)*l),u=n.clone().addScaledVector(a,e.extensionGap*l),p=n.clone().addScaledVector(a,(c+e.extensionOvershoot)*l),f=i.clone().addScaledVector(a,s),m=n.clone().addScaledVector(a,s),g=(new o.Vector3).subVectors(m,f).normalize(),w=e.lineTick(f,g,e.tickSize),y=e.lineTick(m,g.clone().negate(),e.tickSize);return[h.x,h.y,h.z,d.x,d.y,d.z,u.x,u.y,u.z,p.x,p.y,p.z,f.x,f.y,f.z,m.x,m.y,m.z,...w,...y]}function hl(t,e,i,n){if("placingPoints"===t){const t=[];for(let i=0;i<e.length-1;i++){const n=e[i],s=e[i+1];t.push(n.x,n.y,n.z,s.x,s.y,s.z)}if(i){const n=e[e.length-1];t.push(n.x,n.y,n.z,i.x,i.y,i.z)}return t}if(!i||e.length<2)return[];const s=rl(e,i),r=[];for(let t=0;t<e.length-1;t++)r.push(...cl({pointA:e[t],pointB:e[t+1],offset:s},n));return r}class dl extends sl{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingFirstPoint"}),e(this,"onMachineStateChanged",new at),this.styles.set("default",{lineTick:Fa,tickSize:.4,extensionGap:.05,extensionOvershoot:.2,color:0,textOffset:.4,fontSize:.45})}pickHandle(t,e,i=.1){const n=(new o.Matrix4).copy(t.three.matrixWorld).invert(),s=e.origin.clone().applyMatrix4(n),r=e.direction.clone().transformDirection(n).normalize(),a=new o.Ray(s,r),l=new o.Plane(new o.Vector3(0,1,0),0),c=a.intersectPlane(l,new o.Vector3);if(!c)return null;let h=null,d=i;for(const[e,i]of t.annotations.getBySystem(this)){const t=(new o.Vector3).subVectors(i.pointB,i.pointA),n=new o.Vector3(-t.z,0,t.x).normalize(),s=(new o.Vector3).addVectors(i.pointA,i.pointB).multiplyScalar(.5).addScaledVector(n,i.offset);for(const[t,n]of[["pointA",i.pointA],["pointB",i.pointB],["offset",s]]){const i=Math.hypot(c.x-n.x,c.z-n.z);i<d&&(d=i,h={uuid:e,handle:t})}}return h}sendMachineEvent(t){const e=t.drawing??null;e&&(this._previewDrawing=e);const i=al(this.machineState,t);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("LinearAnnotations: no drawing context — send a CLICK or SELECT_LINE with `drawing` first. Skipping."),void this._resetMachine();for(const t of i.dimensions)t.style=this.activeStyle;const t=i.dimensions.map(t=>this._persist(this._previewDrawing,t));this.onCommit.trigger(t)}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(t,e){const i=new o.Group,n=cl(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick)for(const{tip:n,dir:s}of ll(t)){const r=e.meshTick(n,s,e.tickSize),a=new o.BufferGeometry;a.setAttribute("position",new o.BufferAttribute(new Float32Array(r),3));const l=new o.Mesh(a,this._getMeshMaterial(t.style));l.layers.set(1),l.userData.isMeshTick=!0,i.add(l)}return i}_updatePreview(){const t=this.machineState;if("placingPoints"!==t.kind&&"positioningOffset"!==t.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const e=this._resolveStyle(this.activeStyle);this._previewMaterial.color.setHex(e.color);const i=hl(t.kind,t.points,t.cursor,e);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewObject=new o.LineSegments(t,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const t=this._previewObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingFirstPoint"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}}const ul=Math.PI/180;function pl(t,e,i,n){const s=function(t,e,i){const n=(new o.Vector3).subVectors(t,e).normalize(),s=(new o.Vector3).subVectors(i,e).normalize();return(new o.Vector3).addVectors(n,s).normalize()}(t,e,i);return(new o.Vector3).subVectors(n,e).setY(0).dot(s)}function fl(t,e,i,n){return pl(t,e,i,n)<0}function ml(t,e){switch(t.kind){case"awaitingFirstLine":return"CLICK"===e.type&&e.line?{kind:"awaitingSecondLine",line1:e.line.clone(),pointA:e.point.clone()}:t;case"awaitingSecondLine":if("CLICK"===e.type&&e.line){const i=(new o.Vector3).subVectors(t.line1.end,t.line1.start).normalize(),n=(new o.Vector3).subVectors(e.line.end,e.line.start).normalize();if(Math.abs(i.dot(n))>Math.cos(ul))return t;const s=function(t,e,i,n){const s=e.x*n.z-e.z*n.x;if(Math.abs(s)<1e-10)return null;const r=(new o.Vector3).subVectors(i,t),a=(r.x*n.z-r.z*n.x)/s;return new o.Vector3(t.x+e.x*a,0,t.z+e.z*a)}(t.line1.start,i,e.line.start,n);return s?{kind:"positioningArc",pointA:t.pointA.clone(),vertex:s,pointB:e.point.clone(),cursor:null,flipped:!1}:t}return"ESCAPE"===e.type?{kind:"awaitingFirstLine"}:t;case"positioningArc":if("MOUSE_MOVE"===e.type){const i=fl(t.pointA,t.vertex,t.pointB,e.point);return{...t,cursor:e.point.clone(),flipped:i}}if("CLICK"===e.type){const i=fl(t.pointA,t.vertex,t.pointB,e.point),n=Math.max(.05,Math.abs(pl(t.pointA,t.vertex,t.pointB,e.point)));return{kind:"committed",dimension:{uuid:o.MathUtils.generateUUID(),pointA:t.pointA.clone(),vertex:t.vertex.clone(),pointB:t.pointB.clone(),arcRadius:n,flipped:i,style:""}}}return"ESCAPE"===e.type?{kind:"awaitingFirstLine"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingFirstLine"}:t}}function gl(t){const e=(new o.Vector3).subVectors(t.pointA,t.vertex).normalize(),i=(new o.Vector3).subVectors(t.pointB,t.vertex).normalize(),n=Math.atan2(e.z,e.x);let s=Math.atan2(i.z,i.x)-n;for(;s>Math.PI;)s-=2*Math.PI;for(;s<-Math.PI;)s+=2*Math.PI;t.flipped&&(s-=2*Math.sign(s)*Math.PI);const r=new o.Vector3(t.vertex.x+Math.cos(n)*t.arcRadius,0,t.vertex.z+Math.sin(n)*t.arcRadius),a=n+s,l=new o.Vector3(t.vertex.x+Math.cos(a)*t.arcRadius,0,t.vertex.z+Math.sin(a)*t.arcRadius),c=Math.sign(s);return[{tip:r,dir:new o.Vector3(-Math.sin(n)*c,0,Math.cos(n)*c)},{tip:l,dir:new o.Vector3(Math.sin(a)*c,0,-Math.cos(a)*c)}]}function wl(t){const e=(new o.Vector3).subVectors(t.pointA,t.vertex).normalize(),i=(new o.Vector3).subVectors(t.pointB,t.vertex).normalize(),n=Math.acos(o.MathUtils.clamp(e.dot(i),-1,1));return t.flipped?2*Math.PI-n:n}function yl(t){const e=(new o.Vector3).subVectors(t.pointA,t.vertex).normalize(),i=(new o.Vector3).subVectors(t.pointB,t.vertex).normalize(),n=Math.atan2(e.z,e.x);let s=Math.atan2(i.z,i.x)-n;for(;s>Math.PI;)s-=2*Math.PI;for(;s<-Math.PI;)s+=2*Math.PI;const r=n+s/2;return t.flipped?r+Math.PI:r}function _l(t,e,i,n,s,r=!1){const a=Math.atan2(e.z,e.x);let l=Math.atan2(i.z,i.x)-a;for(;l>Math.PI;)l-=2*Math.PI;for(;l<-Math.PI;)l+=2*Math.PI;r&&(l-=2*Math.sign(l)*Math.PI);const c=[];for(let e=0;e<8;e++){const i=a+l*(e/8),s=a+l*((e+1)/8);c.push(t.x+Math.cos(i)*n,0,t.z+Math.sin(i)*n,t.x+Math.cos(s)*n,0,t.z+Math.sin(s)*n)}const h=new o.Vector3(t.x+Math.cos(a)*n,0,t.z+Math.sin(a)*n),d=new o.Vector3(t.x+Math.cos(a+l)*n,0,t.z+Math.sin(a+l)*n),u=t.clone().addScaledVector(e,s.extensionGap),p=t.clone().addScaledVector(i,s.extensionGap);c.push(u.x,u.y,u.z,h.x,h.y,h.z,p.x,p.y,p.z,d.x,d.y,d.z);const f=Math.sign(l),m=new o.Vector3(-Math.sin(a)*f,0,Math.cos(a)*f),g=a+l,w=new o.Vector3(Math.sin(g)*f,0,-Math.cos(g)*f);return c.push(...s.lineTick(h,m,s.tickSize),...s.lineTick(d,w,s.tickSize)),c}function bl(t,e){const i=(new o.Vector3).subVectors(t.pointA,t.vertex).normalize(),n=(new o.Vector3).subVectors(t.pointB,t.vertex).normalize();return _l(t.vertex,i,n,t.arcRadius,e,t.flipped??!1)}function vl(t,e,i,n,s,r=!1){if(!n)return[];const a=Math.max(.05,(new o.Vector3).subVectors(n,e).setY(0).length());return _l(e,(new o.Vector3).subVectors(t,e).normalize(),(new o.Vector3).subVectors(i,e).normalize(),a,s,r)}class xl extends sl{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingFirstLine"}),e(this,"onMachineStateChanged",new at),e(this,"_secondLinePreviewObject",null),this.styles.set("default",{lineTick:Fa,tickSize:.4,extensionGap:.05,color:0,textOffset:.25,fontSize:.45})}pickHandle(t,e,i){return null}sendMachineEvent(t){const e=t.drawing??null;if("awaitingSecondLine"===this.machineState.kind&&"MOUSE_MOVE"===t.type)return e&&(this._previewDrawing=e),void this._updateSecondLinePreview(t.point,t.line??null);const i=ml(this.machineState,t);if(i!==this.machineState){if("awaitingSecondLine"===this.machineState.kind&&this._clearSecondLinePreview(),this.machineState=i,e&&(this._previewDrawing=e),this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("AngleAnnotations: CLICK that commits must include `drawing`. Skipping."),void this._resetMachine();i.dimension.style=this.activeStyle;const t=this._persist(this._previewDrawing,i.dimension);this.onCommit.trigger([t])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(t,e){const i=new o.Group,n=bl(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick)for(const{tip:n,dir:s}of gl(t)){const r=e.meshTick(n,s,e.tickSize),a=new o.BufferGeometry;a.setAttribute("position",new o.BufferAttribute(new Float32Array(r),3));const l=new o.Mesh(a,this._getMeshMaterial(t.style));l.layers.set(1),l.userData.isMeshTick=!0,i.add(l)}return i}_updatePreview(){const t=this.machineState;if("positioningArc"!==t.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const e=this._resolveStyle(this.activeStyle),i=vl(t.pointA,t.vertex,t.pointB,t.cursor,e,t.flipped);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewObject=new o.LineSegments(t,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const t=this._previewObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}}_onDispose(){this._clearSecondLinePreview()}_resetMachine(){this.machineState={kind:"awaitingFirstLine"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearSecondLinePreview(){this._secondLinePreviewObject&&(this._secondLinePreviewObject.removeFromParent(),this._secondLinePreviewObject.geometry.dispose(),this._secondLinePreviewObject=null)}_updateSecondLinePreview(t,e){if("awaitingSecondLine"!==this.machineState.kind)return void this._clearSecondLinePreview();if(!this._previewDrawing)return void this._clearSecondLinePreview();const i=this.machineState,n=(new o.Vector3).subVectors(i.line1.end,i.line1.start).normalize();if(!e)return void this._clearSecondLinePreview();const s=(new o.Vector3).subVectors(e.end,e.start).normalize(),r=function(t,e,i,n){const s=e.x*n.z-e.z*n.x;if(Math.abs(s)<1e-6)return null;const r=i.x-t.x,a=i.z-t.z,l=(r*n.z-a*n.x)/s;return new o.Vector3(t.x+l*e.x,0,t.z+l*e.z)}(i.line1.start,n,e.start,s);if(!r)return void this._clearSecondLinePreview();const a=t.clone(),l=(new o.Vector3).subVectors(a,r).setY(0);if(l.length()<.01)return void this._clearSecondLinePreview();const c=(new o.Vector3).subVectors(i.pointA,r).normalize(),h=l.normalize(),d=Math.atan2(c.z,c.x);let u=Math.atan2(h.z,h.x)-d;for(;u>Math.PI;)u-=2*Math.PI;for(;u<-Math.PI;)u+=2*Math.PI;const p=d+u/2,f=Math.max(.1,.4*Math.min(i.pointA.distanceTo(r),a.distanceTo(r))),m=new o.Vector3(r.x+Math.cos(p)*f,0,r.z+Math.sin(p)*f),g=this._resolveStyle(this.activeStyle),w=vl(i.pointA,r,a,m,g);if(0===w.length)return void this._clearSecondLinePreview();const y=w.length/3;if(!this._secondLinePreviewObject||this._secondLinePreviewObject.geometry.attributes.position.count!==y){this._clearSecondLinePreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(w),3)),this._secondLinePreviewObject=new o.LineSegments(t,this._previewMaterial),this._secondLinePreviewObject.layers.set(1),this._secondLinePreviewObject.renderOrder=1,this._secondLinePreviewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._secondLinePreviewObject)}else{const t=this._secondLinePreviewObject.geometry.attributes.position;t.set(w),t.needsUpdate=!0}}}function Sl(t,e){const i=e.x-t.x,n=e.z-t.z,s=Math.sqrt(i*i+n*n);if(0===s)return t.clone();const r=Math.atan2(n,i),a=Math.round(r/(Math.PI/4))*(Math.PI/4);return new o.Vector3(t.x+Math.cos(a)*s,0,t.z+Math.sin(a)*s)}function Tl(t,e){switch(t.kind){case"awaitingArrowTip":return"CLICK"===e.type?{kind:"placingElbow",arrowTip:e.point.clone(),cursor:null}:t;case"placingElbow":return"MOUSE_MOVE"===e.type?{...t,cursor:e.point.clone()}:"CLICK"===e.type?{kind:"placingExtension",arrowTip:t.arrowTip,elbow:e.point.clone(),cursor:null}:"ESCAPE"===e.type?{kind:"awaitingArrowTip"}:t;case"placingExtension":return"MOUSE_MOVE"===e.type?{...t,cursor:Sl(t.elbow,e.point)}:"CLICK"===e.type?{kind:"enteringText",arrowTip:t.arrowTip,elbow:t.elbow,extensionEnd:Sl(t.elbow,e.point)}:"ESCAPE"===e.type?{kind:"awaitingArrowTip"}:t;case"enteringText":if("SUBMIT_TEXT"===e.type&&e.text.trim().length>0){return{kind:"committed",annotation:{uuid:o.MathUtils.generateUUID(),arrowTip:t.arrowTip.clone(),elbow:t.elbow.clone(),extensionEnd:t.extensionEnd.clone(),text:e.text.trim(),style:""}}}return"ESCAPE"===e.type?{kind:"awaitingArrowTip"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingArrowTip"}:t}}function Cl(t,e,i,n){return"curved"===n.leaderShape?function(t,e,i,n){const s=new o.QuadraticBezierCurve3(t,e,i).getPoints(24),r=[];for(let t=0;t<s.length-1;t++){const e=s[t],i=s[t+1];r.push(e.x,e.y,e.z,i.x,i.y,i.z)}if(n.lineTick){const i=(new o.Vector3).subVectors(t,e);i.lengthSq()>1e-10&&r.push(...n.lineTick(t,i.normalize(),n.tickSize))}return r}(t,e,i,n):function(t,e,i,n){const s=[t.x,t.y,t.z,e.x,e.y,e.z,e.x,e.y,e.z,i.x,i.y,i.z];if(n.lineTick){const i=(new o.Vector3).subVectors(t,e);i.lengthSq()>1e-10&&s.push(...n.lineTick(t,i.normalize(),n.tickSize))}return s}(t,e,i,n)}function Al(t,e){return Cl(t.arrowTip,t.elbow,t.extensionEnd,e)}function El(t,e,i,n,s){return n?Cl(e,"placingElbow"===t?n:i,n,s):[]}class Ml extends sl{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingArrowTip"}),e(this,"onMachineStateChanged",new at),e(this,"_previewMeshMaterial",new o.MeshBasicMaterial({color:16737894,side:o.DoubleSide,depthTest:!1})),e(this,"_previewMeshObject",null),this.styles.set("default",{tickSize:.4,color:0,textOffset:.1,fontSize:.45,lineTick:Ua})}pickHandle(t,e,i=.1){const n=(new o.Matrix4).copy(t.three.matrixWorld).invert(),s=e.origin.clone().applyMatrix4(n),r=e.direction.clone().transformDirection(n).normalize(),a=new o.Ray(s,r),l=new o.Plane(new o.Vector3(0,1,0),0),c=a.intersectPlane(l,new o.Vector3);if(!c)return null;let h=null,d=i;for(const[e,i]of t.annotations.getBySystem(this))for(const[t,n]of[["elbow",i.elbow],["extensionEnd",i.extensionEnd]]){const i=Math.hypot(c.x-n.x,c.z-n.z);i<d&&(d=i,h={uuid:e,handle:t})}return h}sendMachineEvent(t){const e=t.drawing??null;e&&(this._previewDrawing=e);const i=Tl(this.machineState,t);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("LeaderAnnotations: commit requires a drawing. Skipping."),void this._resetMachine();i.annotation.style=this.activeStyle;const t=this._persist(this._previewDrawing,i.annotation);this.onCommit.trigger([t])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(t,e){const i=new o.Group,n=Al(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick){const n=(new o.Vector3).subVectors(t.arrowTip,t.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=e.meshTick(t.arrowTip,n,e.tickSize),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3));const a=new o.Mesh(r,this._getMeshMaterial(t.style));a.layers.set(1),a.userData.isMeshArrow=!0,i.add(a)}}return i}_updatePreview(){const t=this.machineState;if("placingElbow"!==t.kind&&"placingExtension"!==t.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const e=this._resolveStyle(this.activeStyle),i="placingElbow"===t.kind?El("placingElbow",t.arrowTip,null,t.cursor,e):El("placingExtension",t.arrowTip,t.elbow,t.cursor,e);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewObject=new o.LineSegments(t,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const t=this._previewObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}if(e.meshTick){const i="placingElbow"===t.kind?t.cursor:t.elbow,n=i?(new o.Vector3).subVectors(t.arrowTip,i):null;if(n&&n.lengthSq()>1e-10){n.normalize();const i=e.meshTick(t.arrowTip,n,e.tickSize);if(this._previewMeshObject){const t=this._previewMeshObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}else{const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewMeshObject=new o.Mesh(t,this._previewMeshMaterial),this._previewMeshObject.layers.set(1),this._previewMeshObject.renderOrder=1,this._previewMeshObject.frustumCulled=!1,this._previewDrawing.three.add(this._previewMeshObject)}}else this._clearPreviewMesh()}else this._clearPreviewMesh()}_clearPreview(){super._clearPreview(),this._clearPreviewMesh()}_onDispose(){this._clearPreviewMesh(),this._previewMeshMaterial.dispose()}_resetMachine(){this.machineState={kind:"awaitingArrowTip"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearPreviewMesh(){this._previewMeshObject&&(this._previewMeshObject.removeFromParent(),this._previewMeshObject.geometry.dispose(),this._previewMeshObject=null)}}class Pl extends sl{constructor(t){super(t),e(this,"enabled",!0),e(this,"_ownsChildGeometry",!1),e(this,"definitions",new i.DataMap),this.styles.set("default",{color:0,textOffset:0,fontSize:0})}pickHandle(t,e,i){return null}pick(t,e=.05){const i=new o.Raycaster;i.ray.copy(t),i.params.Line={threshold:e},i.params.LineSegments={threshold:e};let n=null,s=1/0;for(const t of this._knownDrawings)for(const[e,r]of t.annotations){if(r.system!==this)continue;const t=r.three;t.updateWorldMatrix(!0,!0),t.traverse(r=>{if(r===t)return;if(!(r instanceof o.LineSegments))return;const a=[];r.raycast(i,a),a.length>0&&a[0].distance<s&&(s=a[0].distance,n=e)})}return n}define(t,e){this.definitions.set(t,e)}_buildGroup(t,e){const i=this.definitions.get(t.blockName);if(!i)throw new Error(`BlockAnnotations: block "${t.blockName}" is not defined.`);const n=new o.Group;if(i.lines){const e=new o.LineSegments(i.lines,this._getMaterial(t.style));e.layers.set(1),e.userData.isDimension=!0,n.add(e)}if(i.mesh){const e=new o.Mesh(i.mesh,this._getMeshMaterial(t.style));e.layers.set(1),e.userData.isBlockMesh=!0,n.add(e)}return n}_onAfterPersist(t,e){e.position.set(t.position.x,0,t.position.z),e.rotation.set(0,t.rotation,0),e.scale.setScalar(t.scale)}_onDispose(){var t,e;for(const i of this.definitions.values())null==(t=i.lines)||t.dispose(),null==(e=i.mesh)||e.dispose();this.definitions.clear()}}function zl(t,e){const{position:i,direction:n}=t,{length:s}=e,r=new o.Vector3(i.x+n.x*s,0,i.z+n.z*s),a=new o.Vector3(n.x,0,n.z),l=e.lineTick(r,a,e.tickSize),c=[i.x,0,i.z,r.x,0,r.z];return new Float32Array([...c,...l])}function Il(t,e){return new o.Vector3(t.position.x+t.direction.x*e,0,t.position.z+t.direction.z*e)}function Dl(t,e){switch(e){case"percentage":return`${(100*t).toFixed(2)} %`;case"ratio":return 0===t?"1:∞":`1:${(1/t).toFixed(2)}`;case"degrees":return`${(180*Math.atan(t)/Math.PI).toFixed(2)}°`}}class kl extends sl{constructor(t){super(t),e(this,"enabled",!0),this.styles.set("default",{lineTick:ja,meshTick:Ha,tickSize:.4,length:3,color:0,textOffset:.1,fontSize:.45,format:"percentage"})}pickHandle(t,e,i){return null}_buildGroup(t,e){const i=new o.Group,n=zl(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(n,3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick){const n=Il(t,e.length),s=e.meshTick(n,t.direction,e.tickSize),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3));const a=new o.Mesh(r,this._getMeshMaterial(t.style));a.layers.set(1),a.userData.isDimension=!0,i.add(a)}return i}}function Bl(t,e){const i=e.x-t.x,n=e.z-t.z,s=Math.sqrt(i*i+n*n);if(0===s)return t.clone();const r=Math.atan2(n,i),a=Math.round(r/(Math.PI/4))*(Math.PI/4);return new o.Vector3(t.x+Math.cos(a)*s,0,t.z+Math.sin(a)*s)}function Ol(t,e){switch(t.kind){case"awaitingCenter":return"CLICK"===e.type?{kind:"awaitingRadius",center:e.point.clone(),cursor:null}:t;case"awaitingRadius":if("MOUSE_MOVE"===e.type)return{...t,cursor:e.point.clone()};if("CLICK"===e.type){const i=Math.max(.1,Math.abs(e.point.x-t.center.x)),n=Math.max(.1,Math.abs(e.point.z-t.center.z));return{kind:"awaitingElbow",center:t.center,halfW:i,halfH:n,cursor:null}}return"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"awaitingElbow":return"MOUSE_MOVE"===e.type?{...t,cursor:e.point.clone()}:"CLICK"===e.type?{kind:"awaitingExtension",center:t.center,halfW:t.halfW,halfH:t.halfH,elbow:e.point.clone(),cursor:null}:"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"awaitingExtension":return"MOUSE_MOVE"===e.type?{...t,cursor:Bl(t.elbow,e.point)}:"CLICK"===e.type?{kind:"enteringText",center:t.center,halfW:t.halfW,halfH:t.halfH,elbow:t.elbow,extensionEnd:Bl(t.elbow,e.point)}:"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"enteringText":if("SUBMIT_TEXT"===e.type&&e.text.trim().length>0){return{kind:"committed",annotation:{uuid:o.MathUtils.generateUUID(),center:t.center.clone(),halfW:t.halfW,halfH:t.halfH,elbow:t.elbow.clone(),extensionEnd:t.extensionEnd.clone(),text:e.text.trim(),style:""}}}return"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingCenter"}:t}}function Vl(t,e){const i=[];i.push(...e.enclosure.buildGeometry(t.center,t.halfW,t.halfH));const n=(new o.Vector3).subVectors(t.elbow,t.center),s=n.lengthSq()>1e-10?n.clone().normalize():new o.Vector3(1,0,0),r=e.enclosure.getAttachmentPoint(t.center,t.halfW,t.halfH,s);if(i.push(r.x,r.y,r.z,t.elbow.x,t.elbow.y,t.elbow.z,t.elbow.x,t.elbow.y,t.elbow.z,t.extensionEnd.x,t.extensionEnd.y,t.extensionEnd.z),e.lineTick){const n=(new o.Vector3).subVectors(t.extensionEnd,t.elbow);n.lengthSq()>1e-10&&i.push(...e.lineTick(t.extensionEnd,n.normalize(),e.tickSize))}return i}function Ll(t,e,i,n,s,r,a){const l="awaitingRadius"===t?r?Math.max(.05,Math.abs(r.x-e.x)):0:i,c="awaitingRadius"===t?r?Math.max(.05,Math.abs(r.z-e.z)):0:n;if(l<1e-10||c<1e-10)return[];const h=[];if(h.push(...a.enclosure.buildGeometry(e,l,c)),"awaitingRadius"===t)return h;const d="awaitingElbow"===t?r:s;if(!d)return h;const u=(new o.Vector3).subVectors(d,e),p=u.lengthSq()>1e-10?u.clone().normalize():new o.Vector3(1,0,0),f=a.enclosure.getAttachmentPoint(e,l,c,p);return"awaitingElbow"===t?(h.push(f.x,0,f.z,d.x,0,d.z),h):r?(h.push(f.x,0,f.z,s.x,0,s.z,s.x,0,s.z,r.x,0,r.z),h):h}const Nl={buildGeometry(t,e,i){const n=.25*Math.min(e,i),s=new o.Vector3(t.x-e,0,t.z-i),r=new o.Vector3(t.x+e,0,t.z-i),a=new o.Vector3(t.x+e,0,t.z+i),l=new o.Vector3(t.x-e,0,t.z+i),c=[[s,r,new o.Vector3(0,0,-1)],[r,a,new o.Vector3(1,0,0)],[a,l,new o.Vector3(0,0,1)],[l,s,new o.Vector3(-1,0,0)]],h=[];for(const[t,e,i]of c){const s=t.distanceTo(e),r=Math.max(1,Math.round(s/(2*n))),a=s/r,l=a/2,c=(new o.Vector3).subVectors(e,t).normalize();for(let e=0;e<r;e++){const n=t.clone().addScaledVector(c,(e+.5)*a),s=t.clone().addScaledVector(c,e*a),r=(new o.Vector3).subVectors(s,n);let d=s.clone();for(let t=1;t<=8;t++){const e=t/8*Math.PI,s=n.x+r.x*Math.cos(e)+i.x*l*Math.sin(e),a=n.z+r.z*Math.cos(e)+i.z*l*Math.sin(e),c=new o.Vector3(s,0,a);h.push(d.x,0,d.z,c.x,0,c.z),d=c}}}return h},getAttachmentPoint(t,e,i,n){const s=Math.abs(n.x)>1e-10?e/Math.abs(n.x):1/0,r=Math.abs(n.z)>1e-10?i/Math.abs(n.z):1/0,a=Math.min(s,r);return new o.Vector3(t.x+n.x*a,0,t.z+n.z*a)}},Fl={buildGeometry(t,e,i){const n=new o.Vector3(t.x-e,0,t.z-i),s=new o.Vector3(t.x+e,0,t.z-i),r=new o.Vector3(t.x+e,0,t.z+i),a=new o.Vector3(t.x-e,0,t.z+i);return[n.x,0,n.z,s.x,0,s.z,s.x,0,s.z,r.x,0,r.z,r.x,0,r.z,a.x,0,a.z,a.x,0,a.z,n.x,0,n.z]},getAttachmentPoint(t,e,i,n){const s=Math.abs(n.x)>1e-10?e/Math.abs(n.x):1/0,r=Math.abs(n.z)>1e-10?i/Math.abs(n.z):1/0,a=Math.min(s,r);return new o.Vector3(t.x+n.x*a,0,t.z+n.z*a)}},Rl={buildGeometry(t,e,i){const n=[];for(let s=0;s<32;s++){const r=s/32*Math.PI*2,o=(s+1)/32*Math.PI*2;n.push(t.x+Math.cos(r)*e,0,t.z+Math.sin(r)*i,t.x+Math.cos(o)*e,0,t.z+Math.sin(o)*i)}return n},getAttachmentPoint(t,e,i,n){const s=n.x/e,r=n.z/i,a=Math.sqrt(s*s+r*r),l=a>1e-10?1/a:e;return new o.Vector3(t.x+n.x*l,0,t.z+n.z*l)}};class Ul extends sl{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingCenter"}),e(this,"onMachineStateChanged",new at),this.styles.set("default",{enclosure:Nl,lineTick:Ua,tickSize:.4,color:22015,textOffset:.1,fontSize:.45})}pickHandle(t,e,i){return null}sendMachineEvent(t){const e=t.drawing??null;e&&(this._previewDrawing=e);const i=Ol(this.machineState,t);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("CalloutAnnotations: commit requires a drawing. Pass `drawing` on the first CLICK."),void this._resetMachine();i.annotation.style=this.activeStyle;const t=this._persist(this._previewDrawing,i.annotation);this.onCommit.trigger([t])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(t,e){const i=new o.Group,n=Vl(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick){const n=(new o.Vector3).subVectors(t.extensionEnd,t.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=e.meshTick(t.extensionEnd,n,e.tickSize),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3));const a=new o.Mesh(r,this._getMeshMaterial(t.style));a.layers.set(1),a.userData.isMeshArrow=!0,i.add(a)}}return i}_updatePreview(){const t=this.machineState;if("awaitingRadius"!==t.kind&&"awaitingElbow"!==t.kind&&"awaitingExtension"!==t.kind)return void this._clearPreview();if(!this._previewDrawing)return;const e=this._resolveStyle(this.activeStyle),i=(()=>{switch(t.kind){case"awaitingRadius":return Ll("awaitingRadius",t.center,0,0,null,t.cursor,e);case"awaitingElbow":return Ll("awaitingElbow",t.center,t.halfW,t.halfH,null,t.cursor,e);case"awaitingExtension":return Ll("awaitingExtension",t.center,t.halfW,t.halfH,t.elbow,t.cursor,e)}})();if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewObject=new o.LineSegments(t,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const t=this._previewObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingCenter"},this._clearPreview(),this._previewDrawing=null,this.onMachineStateChanged.trigger(this.machineState)}}const jl=class t extends ht{constructor(n){super(n),e(this,"enabled",!0),e(this,"list",new i.DataMap),e(this,"systems",new i.DataMap),e(this,"onDisposed",new at),n.add(t.uuid,this),this.list.onBeforeDelete.add(({value:t})=>t.dispose()),this.systems.onBeforeDelete.add(({value:t})=>t.dispose())}use(t){if(this.systems.has(t))return this.systems.get(t);const e=new t(this.components);return this.systems.set(t,e),e}create(t){const e=new il(this.components);e.world=t,t.scene.three.add(e.three),t.onDisposed.add(()=>this.list.delete(e.uuid));const i=t.camera;return i.three.layers.enable(1),i instanceof Ho&&(i.threePersp.layers.enable(1),i.threeOrtho.layers.enable(1)),this.list.set(e.uuid,e),e}dispose(){this.list.clear(),this.systems.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};e(jl,"uuid","5c7d3b9a-4e8f-4a2b-9c1d-0e3f2a5b7c8d");let $l=jl;const Wl=[[16711680,1],[16776960,2],[65280,3],[65535,4],[255,5],[16711935,6],[16777215,7],[0,7]];function Gl(t){const e=t>>16&255,i=t>>8&255,n=255&t;let s=7,r=1/0;for(const[t,o]of Wl){const a=(e-(t>>16&255))**2+(i-(t>>8&255))**2+(n-(255&t))**2;a<r&&(r=a,s=o)}return s}class Hl{constructor(){e(this,"_lines",[]),e(this,"_handleCounter",1)}p(t,e){return this._lines.push(String(t),String(e)),this}n(t,e,i=6){return this._lines.push(String(t),e.toFixed(i)),this}handle(){return(this._handleCounter++).toString(16).toUpperCase()}build(){return this._lines.join("\n")+"\n"}}class ql{constructor(t){e(this,"precision",2),e(this,"config",{trueColor:!1}),e(this,"_viewport",null),e(this,"_paperSlot",null),e(this,"_annotationLayers",new Map),e(this,"_systemExporters",new Map),this._components=t}registerSystemExporter(t,e){this._systemExporters.set(t,e)}export(t,e){const i=!!e,n=new Hl,s=new Map;for(const e of t)for(const t of e.drawing.layers.values())s.has(t.name)||s.set(t.name,t);const r=[...s.values()],o=this._components.get($l).systems.get(Pl),a=o?[...o.definitions.keys()]:[];this._writeHeader(n,i),this._writeTables(n,r,a),this._writeBlocks(n,o??null),n.p(0,"SECTION").p(2,"ENTITIES"),i&&e&&this._writePaperBorders(n,e);for(const s of t){s.drawing.three.traverse(t=>{t.userData.isDimension&&t.userData.annotationUuid&&this._annotationLayers.set(t.userData.annotationUuid,t.userData.layer??"0")});for(const t of s.viewports){if(this._viewport=t.viewport??null,i&&t.viewport){const i=t.viewport,n=e.heightMm-2*e.margin;this._paperSlot={x:t.x??0,y:n-(t.y??0),mmPerUnit:1e3/i.drawingScale,vpLeft:i.left,vpTop:i.top}}else this._paperSlot=null;this._writeViewportBorder(n),this._writeRawLines(n,s.drawing),this._writeLinearAnnotations(n,s.drawing),this._writeAngleAnnotations(n,s.drawing),this._writeLeaderAnnotations(n,s.drawing),this._writeSlopeAnnotations(n,s.drawing),this._writeCalloutAnnotations(n,s.drawing),this._writeBlockInsertions(n,s.drawing),this._writeCustomSystems(n,s.drawing)}this._annotationLayers.clear()}return n.p(0,"ENDSEC"),this._writeObjects(n),n.p(0,"EOF"),this._viewport=null,this._paperSlot=null,n.build()}_writeHeader(t,e){t.p(0,"SECTION").p(2,"HEADER"),t.p(9,"$ACADVER").p(1,this.config.trueColor?"AC1018":"AC1015"),t.p(9,"$INSUNITS").p(70,e?4:6),t.p(0,"ENDSEC")}_writeTables(t,e,i){t.p(0,"SECTION").p(2,"TABLES"),t.p(0,"TABLE").p(2,"VPORT").p(70,0).p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"LTYPE").p(70,1),t.p(0,"LTYPE").p(2,"CONTINUOUS").p(70,0).p(3,"Solid line").p(72,65).p(73,0).n(40,0),t.p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"LAYER").p(70,e.length);for(const i of e){const e=Gl(i.material.color.getHex());t.p(0,"LAYER").p(2,i.name).p(70,0).p(62,e).p(6,"CONTINUOUS")}t.p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"STYLE").p(70,1),t.p(0,"STYLE").p(2,"STANDARD").p(70,0).n(40,0).n(41,1).n(50,0).p(71,0).n(42,.2).p(3,"txt").p(4,""),t.p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"VIEW").p(70,0).p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"UCS").p(70,0).p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"APPID").p(70,1),t.p(0,"APPID").p(2,"ACAD").p(70,0),t.p(0,"ENDTAB"),t.p(0,"TABLE").p(2,"DIMSTYLE").p(70,0).p(0,"ENDTAB");const n=["*Model_Space","*Paper_Space",...i];t.p(0,"TABLE").p(2,"BLOCK_RECORD").p(70,n.length);for(const e of n)t.p(0,"BLOCK_RECORD").p(5,t.handle()).p(2,e);t.p(0,"ENDTAB"),t.p(0,"ENDSEC")}_writeBlocks(t,e){if(t.p(0,"SECTION").p(2,"BLOCKS"),this._writeBlock(t,"*Model_Space",null),this._writeBlock(t,"*Paper_Space",null),e)for(const[i,n]of e.definitions)this._writeBlock(t,i,n.lines??null);t.p(0,"ENDSEC")}_writeBlock(t,e,i){if(t.p(0,"BLOCK").p(5,t.handle()).p(8,"0").p(2,e).p(70,0).n(10,0).n(20,0).n(30,0).p(3,e).p(1,""),i){const e=this._viewport,n=this._paperSlot;this._viewport=null,this._paperSlot=null,this._writeGeoAsLines(t,i,"0"),this._viewport=e,this._paperSlot=n}t.p(0,"ENDBLK").p(5,t.handle()).p(8,"0")}_writeViewportBorder(t){if(!this._viewport)return;const e=this._viewport,i=this._tx(e.left),n=this._tx(e.right),s=this._ty(-e.bottom),r=this._ty(-e.top);this._writeRawLine(t,i,s,n,s,"0",7),this._writeRawLine(t,n,s,n,r,"0",7),this._writeRawLine(t,n,r,i,r,"0",7),this._writeRawLine(t,i,r,i,s,"0",7)}_writePaperBorders(t,e){const{margin:i,widthMm:n,heightMm:s}=e,r=n-2*i,o=s-2*i;this._writeRawLine(t,0,0,r,0,"0",7),this._writeRawLine(t,r,0,r,o,"0",7),this._writeRawLine(t,r,o,0,o,"0",7),this._writeRawLine(t,0,o,0,0,"0",7),this._writeRawLine(t,-i,-i,r+i,-i,"0",7),this._writeRawLine(t,r+i,-i,r+i,o+i,"0",7),this._writeRawLine(t,r+i,o+i,-i,o+i,"0",7),this._writeRawLine(t,-i,o+i,-i,-i,"0",7)}_writeObjects(t){t.p(0,"SECTION").p(2,"OBJECTS"),t.p(0,"DICTIONARY").p(5,t.handle()).p(330,0).p(100,"AcDbRootDictionary"),t.p(0,"ENDSEC")}_writeRawLines(t,e){e.three.traverse(e=>{var i;if(!(e instanceof o.LineSegments))return;if(e.userData.isDimension)return;if(null==(i=e.parent)?void 0:i.userData.blockUuid)return;if(!e.visible)return;const n=e.userData.layer??"0",s=e.material.color.getHex();this._writeGeoAsLines(t,e.geometry,n,Gl(s),s)})}_writeLinearAnnotations(t,e){var i;const n=this._components.get($l).systems.get(dl);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Gl(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=cl(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick)for(const{tip:e,dir:i}of ll(s))this._writeMeshTriangles(t,r.meshTick(e,i,r.tickSize),l,a,r.color);const h=(new o.Vector3).subVectors(s.pointB,s.pointA),d=new o.Vector3(-h.z,0,h.x).normalize(),u=s.offset>=0?1:-1,p=s.pointA.clone().addScaledVector(d,s.offset),f=s.pointB.clone().addScaledVector(d,s.offset),m=p.clone().add(f).multiplyScalar(.5).addScaledVector(d,(r.textOffset+.5*r.fontSize)*u),g=r.unit??{factor:1,suffix:"m"},w=`${(s.pointA.distanceTo(s.pointB)*g.factor).toFixed(this.precision)} ${g.suffix}`;this._writeText(t,w,m.x,m.z,r.fontSize,l,a,this._textAngle(h.x,h.z),1,2,r.color)}}_writeAngleAnnotations(t,e){var i;const n=this._components.get($l).systems.get(xl);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Gl(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=bl(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick)for(const{tip:e,dir:i}of gl(s))this._writeMeshTriangles(t,r.meshTick(e,i,r.tickSize),l,a,r.color);const h=yl(s),d=s.arcRadius+r.textOffset,u=s.vertex.x+Math.cos(h)*d,p=s.vertex.z+Math.sin(h)*d,f=o.MathUtils.radToDeg(wl(s));this._writeText(t,`${f.toFixed(this.precision)}°`,u,p,r.fontSize,l,a,0,1,0,r.color)}}_writeLeaderAnnotations(t,e){var i;const n=this._components.get($l).systems.get(Ml);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Gl(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=Al(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick){const e=(new o.Vector3).subVectors(s.arrowTip,s.elbow);e.lengthSq()>1e-10&&this._writeMeshTriangles(t,r.meshTick(s.arrowTip,e.normalize(),r.tickSize),l,a,r.color)}const h=(new o.Vector3).subVectors(s.extensionEnd,s.elbow).setY(0).normalize(),d=h.x<-.1?2:h.x>.1?0:1,u=1===d?.5*r.fontSize:0,p=s.extensionEnd.clone().addScaledVector(h,r.textOffset+u);this._writeText(t,s.text,p.x,p.z,r.fontSize,l,a,0,d,2,r.color)}}_writeSlopeAnnotations(t,e){var i;const n=this._components.get($l).systems.get(kl);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Gl(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=zl(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick){const e=Il(s,r.length);this._writeMeshTriangles(t,r.meshTick(e,s.direction,r.tickSize),l,a,r.color)}const h=new o.Vector3(s.position.x+s.direction.x*r.length,0,s.position.z+s.direction.z*r.length),d=s.position.clone().add(h).multiplyScalar(.5).addScaledVector(new o.Vector3(-s.direction.z,0,s.direction.x),r.textOffset+r.fontSize);this._writeText(t,Dl(s.slope,r.format),d.x,d.z,r.fontSize,l,a,this._textAngle(s.direction.x,s.direction.z),1,0,r.color)}}_writeCalloutAnnotations(t,e){var i;const n=this._components.get($l).systems.get(Ul);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Gl(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=Vl(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick){const e=(new o.Vector3).subVectors(s.extensionEnd,s.elbow);e.lengthSq()>1e-10&&this._writeMeshTriangles(t,r.meshTick(s.extensionEnd,e.normalize(),r.tickSize),l,a,r.color)}const h=(new o.Vector3).subVectors(s.extensionEnd,s.elbow).setY(0).normalize(),d=h.x<-.1?2:h.x>.1?0:1,u=1===d?.5*r.fontSize:0,p=s.extensionEnd.clone().addScaledVector(h,r.textOffset+u);this._writeText(t,s.text,p.x,p.z,r.fontSize,l,a,0,d,2,r.color)}}_writeBlockInsertions(t,e){const i=this._components.get($l).systems.get(Pl);if(i)for(const[,n]of e.annotations.getBySystem(i)){if(!this._inViewport(n.position.x,n.position.z))continue;const e=i.styles.get(n.style)??i.styles.get("default"),s=Gl(e.color),r=-o.MathUtils.radToDeg(n.rotation),a=n.scale*this._scale();t.p(0,"INSERT").p(5,t.handle()).p(8,"0").p(62,s),this._emitTrueColor(t,e.color),t.p(2,n.blockName).n(10,this._tx(n.position.x)).n(20,this._ty(n.position.z)).n(30,0).n(41,a).n(42,a).n(43,a).n(50,r)}}_writeGeoAsLines(t,e,i,n=7,s){const r=e.attributes.position;if(r)for(let e=0;e+1<r.count;e+=2){const a=this._clipSegment(new o.Vector3(r.getX(e),0,r.getZ(e)),new o.Vector3(r.getX(e+1),0,r.getZ(e+1)));a&&this._writeLine(t,a.start.x,a.start.z,a.end.x,a.end.z,i,n,s)}}_writePairsAsLines(t,e,i,n=7,s){for(let r=0;r+5<e.length;r+=6){const a=this._clipSegment(new o.Vector3(e[r],0,e[r+2]),new o.Vector3(e[r+3],0,e[r+5]));a&&this._writeLine(t,a.start.x,a.start.z,a.end.x,a.end.z,i,n,s)}}_emitTrueColor(t,e){this.config.trueColor&&void 0!==e&&t.p(420,e)}_writeLine(t,e,i,n,s,r,o,a){t.p(0,"LINE").p(5,t.handle()).p(8,r).p(62,o),this._emitTrueColor(t,a),t.n(10,this._tx(e)).n(20,this._ty(i)).n(30,0).n(11,this._tx(n)).n(21,this._ty(s)).n(31,0)}_writeRawLine(t,e,i,n,s,r,o){t.p(0,"LINE").p(5,t.handle()).p(8,r).p(62,o).n(10,e).n(20,i).n(30,0).n(11,n).n(21,s).n(31,0)}_writeSolid(t,e,i,n,s,r,o,a,l,c){t.p(0,"SOLID").p(5,t.handle()).p(8,a).p(62,l),this._emitTrueColor(t,c),t.n(10,this._tx(e)).n(20,this._ty(i)).n(30,0).n(11,this._tx(n)).n(21,this._ty(s)).n(31,0).n(12,this._tx(r)).n(22,this._ty(o)).n(32,0).n(13,this._tx(r)).n(23,this._ty(o)).n(33,0)}_writeMeshTriangles(t,e,i,n,s){for(let r=0;r+8<e.length;r+=9)this._writeSolid(t,e[r],e[r+2],e[r+3],e[r+5],e[r+6],e[r+8],i,n,s)}_writeText(t,e,i,n,s,r,o,a=0,l=0,c=0,h){const d=this._tx(i),u=this._ty(n);t.p(0,"TEXT").p(5,t.handle()).p(8,r).p(62,o),this._emitTrueColor(t,h),t.n(10,d).n(20,u).n(30,0).n(40,s*this._scale()).n(50,a).p(1,e),0===l&&0===c||(0!==l&&t.p(72,l),0!==c&&t.p(73,c),t.n(11,d).n(21,u).n(31,0))}_tx(t){return this._paperSlot?this._paperSlot.x+(t-this._paperSlot.vpLeft)*this._paperSlot.mmPerUnit:this._viewport?t-this._viewport.left:t}_ty(t){return this._paperSlot?this._paperSlot.y-(t+this._paperSlot.vpTop)*this._paperSlot.mmPerUnit:this._viewport?-t-this._viewport.bottom:-t}_scale(){return this._paperSlot?this._paperSlot.mmPerUnit:1}_clipSegment(t,e){return this._viewport?this._viewport.clipLine(new o.Line3(t,e)):new o.Line3(t,e)}_inViewport(t,e){return!this._viewport||this._viewport.bbox.containsPoint(new o.Vector3(t,0,e))}_bboxFromPositions(t){const e=new o.Box3;for(let i=0;i+2<t.length;i+=3)e.expandByPoint(new o.Vector3(t[i],0,t[i+2]));return e}_fullyInViewport(t){return!this._viewport||this._viewport.bbox.containsBox(t)}_textAngle(t,e){let i=Math.atan2(-e,t);return(i>Math.PI/2||i<=-Math.PI/2)&&(i+=Math.PI),o.MathUtils.radToDeg(i)}_writeCustomSystems(t,e){if(0===this._systemExporters.size)return;const i=this._makeContext(t);for(const[t,e]of this._systemExporters){const n=this._components.get($l).systems.get(t);n&&e(n,i)}}_makeContext(t){return{writeLine:(e,i,n,s,r="0",o=7)=>{this._writeLine(t,e,i,n,s,r,o)},writePairs:(e,i="0",n=7)=>{this._writePairsAsLines(t,e,i,n)},writeMeshTriangles:(e,i="0",n=7)=>{this._writeMeshTriangles(t,e,i,n)},writeText:(e,i,n,s,r={})=>{this._writeText(t,e,i,n,s,r.layer??"0",r.aciColor??7,r.rotDeg??0,r.hAlign??0)},hexToAci:Gl,textAngle:(t,e)=>this._textAngle(t,e)}}}const Zl=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"exporter",new ql(this.components)),i.add(t.uuid,this)}};e(Zl,"uuid","e9a2c3d4-5f67-4b89-a012-1c3d5e7f9b2a");let Yl=Zl;export{xl as AngleAnnotations,sl as AnnotationSystem,Ra as ArrowTick,lt as AsyncEvent,sa as BCFTopics,ia as BCFTopicsConfigManager,ct as Base,ut as BaseCamera,pt as BaseRenderer,gt as BaseScene,dt as BaseWorldItem,Pl as BlockAnnotations,fo as BoundingBoxer,Ul as CalloutAnnotations,Rl as CircleEnclosure,_o as Classifier,la as Clipper,Nl as CloudEnclosure,Qo as Comment,ht as Component,Uo as Components,je as ConfigManager,Re as Configurator,Ne as ControlsUtils,Le as DataMap,wt as DataSet,Fa as DiagonalTick,mt as Disposer,$a as DotTick,qa as DrawingAnnotations,Za as DrawingLayers,sl as DrawingSystem,Ka as DrawingViewport,Xa as DrawingViewportHelper,Qa as DrawingViewports,ql as DxfExporter,Yl as DxfManager,oo as EdgeProjector,at as Event,Fe as EventManager,bo as FastModelPicker,xo as FastModelPickers,Ha as FilledArrowTick,Wa as FilledCircleTick,Ga as FilledSquareTick,mo as FinderQuery,jo as FirstPersonMode,Ws as FragmentsManager,Fo as Grids,uo as Hider,va as IDSAttribute,xa as IDSClassification,Sa as IDSEntity,_a as IDSFacet,Ca as IDSMaterial,Aa as IDSPartOf,Ta as IDSProperty,Ea as IDSSpecification,Va as IDSSpecifications,ao as IfcFragmentSettings,co as IfcLoader,wo as ItemsFinder,Ml as LeaderAnnotations,dl as LinearAnnotations,Na as MeasurementUtils,Ve as ModelIdMapUtils,$e as Mouse,ja as NoTick,Ua as OpenArrowTick,$o as OrbitMode,Ho as OrthoPerspectiveCamera,Wo as PlanMode,Go as ProjectionManager,Co as Raycasters,Fl as RectEnclosure,Io as RendererMode,ya as ShadowedScene,ko as SimpleCamera,Lo as SimpleGrid,Vo as SimpleGridConfigManager,ra as SimplePlane,So as SimpleRaycaster,Do as SimpleRenderer,zo as SimpleScene,Po as SimpleSceneConfigManager,Ao as SimpleWorld,kl as SlopeAnnotations,il as TechnicalDrawing,tl as TechnicalDrawingHelper,$l as TechnicalDrawings,ta as Topic,_t as UUID,nl as Units,Oe as VertexPicker,pa as View,ca as Viewpoint,ua as Viewpoints,ma as Views,Oo as Worlds,Be as XML,ml as angleDimensionMachine,bl as buildAnglePositions,vl as buildAnglePreviewPositions,Vl as buildCalloutPositions,Ll as buildCalloutPreviewPositions,cl as buildDimensionPositions,ol as buildDimensions,Al as buildLeaderPositions,El as buildLeaderPreviewPositions,hl as buildPreviewPositions,zl as buildSlopePositions,Ol as calloutAnnotationMachine,el as computeAlignmentMatrix,wl as computeAngle,yl as computeBisectorAngle,rl as computeOffset,ea as extensionsImporter,Dl as formatSlope,gl as getAngleTickEndpoints,ll as getDimensionTickEndpoints,Il as getSlopeTip,Tl as leaderAnnotationMachine,al as linearDimensionMachine};
12
+ */const Ra=Va(Fa.exports=function t(e,i,n){function s(o,a){if(!i[o]){if(!e[o]){if(!a&&La)return La(o);if(r)return r(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var c=i[o]={exports:{}};e[o][0].call(c.exports,(function(t){return s(e[o][1][t]||t)}),c,c.exports,t,e,i,n)}return i[o].exports}for(var r=La,o=0;o<n.length;o++)s(n[o]);return s}({1:[function(t,e,i){var n=t("./utils"),s=t("./support"),r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(t){for(var e,i,s,o,a,l,c,h=[],u=0,d=t.length,p=d,f="string"!==n.getTypeOf(t);u<t.length;)p=d-u,s=f?(e=t[u++],i=u<d?t[u++]:0,u<d?t[u++]:0):(e=t.charCodeAt(u++),i=u<d?t.charCodeAt(u++):0,u<d?t.charCodeAt(u++):0),o=e>>2,a=(3&e)<<4|i>>4,l=1<p?(15&i)<<2|s>>6:64,c=2<p?63&s:64,h.push(r.charAt(o)+r.charAt(a)+r.charAt(l)+r.charAt(c));return h.join("")},i.decode=function(t){var e,i,n,o,a,l,c=0,h=0,u="data:";if(t.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");var d,p=3*(t=t.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(t.charAt(t.length-1)===r.charAt(64)&&p--,t.charAt(t.length-2)===r.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(d=s.uint8array?new Uint8Array(0|p):new Array(0|p);c<t.length;)e=r.indexOf(t.charAt(c++))<<2|(o=r.indexOf(t.charAt(c++)))>>4,i=(15&o)<<4|(a=r.indexOf(t.charAt(c++)))>>2,n=(3&a)<<6|(l=r.indexOf(t.charAt(c++))),d[h++]=e,64!==a&&(d[h++]=i),64!==l&&(d[h++]=n);return d}},{"./support":30,"./utils":32}],2:[function(t,e,i){var n=t("./external"),s=t("./stream/DataWorker"),r=t("./stream/Crc32Probe"),o=t("./stream/DataLengthProbe");function a(t,e,i,n,s){this.compressedSize=t,this.uncompressedSize=e,this.crc32=i,this.compression=n,this.compressedContent=s}a.prototype={getContentWorker:function(){var t=new s(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o("data_length")),e=this;return t.on("end",(function(){if(this.streamInfo.data_length!==e.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")})),t},getCompressedWorker:function(){return new s(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(t,e,i){return t.pipe(new r).pipe(new o("uncompressedSize")).pipe(e.compressWorker(i)).pipe(new o("compressedSize")).withStreamInfo("compression",e)},e.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,e,i){var n=t("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new n("STORE compression")},uncompressWorker:function(){return new n("STORE decompression")}},i.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,e,i){var n=t("./utils"),s=function(){for(var t,e=[],i=0;i<256;i++){t=i;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e}();e.exports=function(t,e){return void 0!==t&&t.length?"string"!==n.getTypeOf(t)?function(t,e,i,n){var r=s,o=n+i;t^=-1;for(var a=n;a<o;a++)t=t>>>8^r[255&(t^e[a])];return~t}(0|e,t,t.length,0):function(t,e,i,n){var r=s,o=n+i;t^=-1;for(var a=n;a<o;a++)t=t>>>8^r[255&(t^e.charCodeAt(a))];return~t}(0|e,t,t.length,0):0}},{"./utils":32}],5:[function(t,e,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(t,e,i){var n=null;n="undefined"!=typeof Promise?Promise:t("lie"),e.exports={Promise:n}},{lie:37}],7:[function(t,e,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,s=t("pako"),r=t("./utils"),o=t("./stream/GenericWorker"),a=n?"uint8array":"array";function l(t,e){o.call(this,"FlateWorker/"+t),this._pako=null,this._pakoAction=t,this._pakoOptions=e,this.meta={}}i.magic="\b\0",r.inherits(l,o),l.prototype.processChunk=function(t){this.meta=t.meta,null===this._pako&&this._createPako(),this._pako.push(r.transformTo(a,t.data),!1)},l.prototype.flush=function(){o.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},l.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this._pako=null},l.prototype._createPako=function(){this._pako=new s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var t=this;this._pako.onData=function(e){t.push({data:e,meta:t.meta})}},i.compressWorker=function(t){return new l("Deflate",t)},i.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(t,e,i){function n(t,e){var i,n="";for(i=0;i<e;i++)n+=String.fromCharCode(255&t),t>>>=8;return n}function s(t,e,i,s,o,h){var u,d,p=t.file,f=t.compression,m=h!==a.utf8encode,g=r.transformTo("string",h(p.name)),w=r.transformTo("string",a.utf8encode(p.name)),y=p.comment,_=r.transformTo("string",h(y)),b=r.transformTo("string",a.utf8encode(y)),v=w.length!==p.name.length,x=b.length!==y.length,C="",S="",A="",P=p.dir,T=p.date,E={crc32:0,compressedSize:0,uncompressedSize:0};e&&!i||(E.crc32=t.crc32,E.compressedSize=t.compressedSize,E.uncompressedSize=t.uncompressedSize);var M=0;e&&(M|=8),m||!v&&!x||(M|=2048);var I,z,D,k=0,B=0;P&&(k|=16),"UNIX"===o?(B=798,k|=(I=p.unixPermissions,z=P,D=I,I||(D=z?16893:33204),(65535&D)<<16)):(B=20,k|=function(t){return 63&(t||0)}(p.dosPermissions)),u=T.getUTCHours(),u<<=6,u|=T.getUTCMinutes(),u<<=5,u|=T.getUTCSeconds()/2,d=T.getUTCFullYear()-1980,d<<=4,d|=T.getUTCMonth()+1,d<<=5,d|=T.getUTCDate(),v&&(S=n(1,1)+n(l(g),4)+w,C+="up"+n(S.length,2)+S),x&&(A=n(1,1)+n(l(_),4)+b,C+="uc"+n(A.length,2)+A);var O="";return O+="\n\0",O+=n(M,2),O+=f.magic,O+=n(u,2),O+=n(d,2),O+=n(E.crc32,4),O+=n(E.compressedSize,4),O+=n(E.uncompressedSize,4),O+=n(g.length,2),O+=n(C.length,2),{fileRecord:c.LOCAL_FILE_HEADER+O+g+C,dirRecord:c.CENTRAL_FILE_HEADER+n(B,2)+O+n(_.length,2)+"\0\0\0\0"+n(k,4)+n(s,4)+g+C+_}}var r=t("../utils"),o=t("../stream/GenericWorker"),a=t("../utf8"),l=t("../crc32"),c=t("../signature");function h(t,e,i,n){o.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=e,this.zipPlatform=i,this.encodeFileName=n,this.streamFiles=t,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}r.inherits(h,o),h.prototype.push=function(t){var e=t.meta.percent||0,i=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(t):(this.bytesWritten+=t.data.length,o.prototype.push.call(this,{data:t.data,meta:{currentFile:this.currentFile,percent:i?(e+100*(i-n-1))/i:100}}))},h.prototype.openedSource=function(t){this.currentSourceOffset=this.bytesWritten,this.currentFile=t.file.name;var e=this.streamFiles&&!t.file.dir;if(e){var i=s(t,e,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0},h.prototype.closedSource=function(t){this.accumulate=!1;var e,i=this.streamFiles&&!t.file.dir,r=s(t,i,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),i)this.push({data:(e=t,c.DATA_DESCRIPTOR+n(e.crc32,4)+n(e.compressedSize,4)+n(e.uncompressedSize,4)),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},h.prototype.flush=function(){for(var t=this.bytesWritten,e=0;e<this.dirRecords.length;e++)this.push({data:this.dirRecords[e],meta:{percent:100}});var i,s,o,a,l,h,u=this.bytesWritten-t,d=(i=this.dirRecords.length,s=u,o=t,a=this.zipComment,l=this.encodeFileName,h=r.transformTo("string",l(a)),c.CENTRAL_DIRECTORY_END+"\0\0\0\0"+n(i,2)+n(i,2)+n(s,4)+n(o,4)+n(h.length,2)+h);this.push({data:d,meta:{percent:100}})},h.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},h.prototype.registerPrevious=function(t){this._sources.push(t);var e=this;return t.on("data",(function(t){e.processChunk(t)})),t.on("end",(function(){e.closedSource(e.previous.streamInfo),e._sources.length?e.prepareNextSource():e.end()})),t.on("error",(function(t){e.error(t)})),this},h.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},h.prototype.error=function(t){var e=this._sources;if(!o.prototype.error.call(this,t))return!1;for(var i=0;i<e.length;i++)try{e[i].error(t)}catch(t){}return!0},h.prototype.lock=function(){o.prototype.lock.call(this);for(var t=this._sources,e=0;e<t.length;e++)t[e].lock()},e.exports=h},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(t,e,i){var n=t("../compressions"),s=t("./ZipFileWorker");i.generateWorker=function(t,e,i){var r=new s(e.streamFiles,i,e.platform,e.encodeFileName),o=0;try{t.forEach((function(t,i){o++;var s=function(t,e){var i=t||e,s=n[i];if(!s)throw new Error(i+" is not a valid compression method !");return s}(i.options.compression,e.compression),a=i.options.compressionOptions||e.compressionOptions||{},l=i.dir,c=i.date;i._compressWorker(s,a).withStreamInfo("file",{name:t,dir:l,date:c,comment:i.comment||"",unixPermissions:i.unixPermissions,dosPermissions:i.dosPermissions}).pipe(r)})),r.entriesCount=o}catch(t){r.error(t)}return r}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(t,e,i){function n(){if(!(this instanceof n))return new n;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var t=new n;for(var e in this)"function"!=typeof this[e]&&(t[e]=this[e]);return t}}(n.prototype=t("./object")).loadAsync=t("./load"),n.support=t("./support"),n.defaults=t("./defaults"),n.version="3.10.1",n.loadAsync=function(t,e){return(new n).loadAsync(t,e)},n.external=t("./external"),e.exports=n},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(t,e,i){var n=t("./utils"),s=t("./external"),r=t("./utf8"),o=t("./zipEntries"),a=t("./stream/Crc32Probe"),l=t("./nodejsUtils");function c(t){return new s.Promise((function(e,i){var n=t.decompressed.getContentWorker().pipe(new a);n.on("error",(function(t){i(t)})).on("end",(function(){n.streamInfo.crc32!==t.decompressed.crc32?i(new Error("Corrupted zip : CRC32 mismatch")):e()})).resume()}))}e.exports=function(t,e){var i=this;return e=n.extend(e||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:r.utf8decode}),l.isNode&&l.isStream(t)?s.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):n.prepareContent("the loaded zip file",t,!0,e.optimizedBinaryString,e.base64).then((function(t){var i=new o(e);return i.load(t),i})).then((function(t){var i=[s.Promise.resolve(t)],n=t.files;if(e.checkCRC32)for(var r=0;r<n.length;r++)i.push(c(n[r]));return s.Promise.all(i)})).then((function(t){for(var s=t.shift(),r=s.files,o=0;o<r.length;o++){var a=r[o],l=a.fileNameStr,c=n.resolve(a.fileNameStr);i.file(c,a.decompressed,{binary:!0,optimizedBinaryString:!0,date:a.date,dir:a.dir,comment:a.fileCommentStr.length?a.fileCommentStr:null,unixPermissions:a.unixPermissions,dosPermissions:a.dosPermissions,createFolders:e.createFolders}),a.dir||(i.file(c).unsafeOriginalName=l)}return s.zipComment.length&&(i.comment=s.zipComment),i}))}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(t,e,i){var n=t("../utils"),s=t("../stream/GenericWorker");function r(t,e){s.call(this,"Nodejs stream input adapter for "+t),this._upstreamEnded=!1,this._bindStream(e)}n.inherits(r,s),r.prototype._bindStream=function(t){var e=this;(this._stream=t).pause(),t.on("data",(function(t){e.push({data:t,meta:{percent:0}})})).on("error",(function(t){e.isPaused?this.generatedError=t:e.error(t)})).on("end",(function(){e.isPaused?e._upstreamEnded=!0:e.end()}))},r.prototype.pause=function(){return!!s.prototype.pause.call(this)&&(this._stream.pause(),!0)},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},e.exports=r},{"../stream/GenericWorker":28,"../utils":32}],13:[function(t,e,i){var n=t("readable-stream").Readable;function s(t,e,i){n.call(this,e),this._helper=t;var s=this;t.on("data",(function(t,e){s.push(t)||s._helper.pause(),i&&i(e)})).on("error",(function(t){s.emit("error",t)})).on("end",(function(){s.push(null)}))}t("../utils").inherits(s,n),s.prototype._read=function(){this._helper.resume()},e.exports=s},{"../utils":32,"readable-stream":16}],14:[function(t,e,i){e.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(t,e){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(t,e);if("number"==typeof t)throw new Error('The "data" argument must not be a number');return new Buffer(t,e)},allocBuffer:function(t){if(Buffer.alloc)return Buffer.alloc(t);var e=new Buffer(t);return e.fill(0),e},isBuffer:function(t){return Buffer.isBuffer(t)},isStream:function(t){return t&&"function"==typeof t.on&&"function"==typeof t.pause&&"function"==typeof t.resume}}},{}],15:[function(t,e,i){function n(t,e,i){var n,s=r.getTypeOf(e),a=r.extend(i||{},l);a.date=a.date||new Date,null!==a.compression&&(a.compression=a.compression.toUpperCase()),"string"==typeof a.unixPermissions&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&16384&a.unixPermissions&&(a.dir=!0),a.dosPermissions&&16&a.dosPermissions&&(a.dir=!0),a.dir&&(t=m(t)),a.createFolders&&(n=f(t))&&g.call(this,n,!0);var u="string"===s&&!1===a.binary&&!1===a.base64;i&&void 0!==i.binary||(a.binary=!u),(e instanceof c&&0===e.uncompressedSize||a.dir||!e||0===e.length)&&(a.base64=!1,a.binary=!0,e="",a.compression="STORE",s="string");var w=null;w=e instanceof c||e instanceof o?e:d.isNode&&d.isStream(e)?new p(t,e):r.prepareContent(t,e,a.binary,a.optimizedBinaryString,a.base64);var y=new h(t,w,a);this.files[t]=y}var s=t("./utf8"),r=t("./utils"),o=t("./stream/GenericWorker"),a=t("./stream/StreamHelper"),l=t("./defaults"),c=t("./compressedObject"),h=t("./zipObject"),u=t("./generate"),d=t("./nodejsUtils"),p=t("./nodejs/NodejsStreamInputAdapter"),f=function(t){"/"===t.slice(-1)&&(t=t.substring(0,t.length-1));var e=t.lastIndexOf("/");return 0<e?t.substring(0,e):""},m=function(t){return"/"!==t.slice(-1)&&(t+="/"),t},g=function(t,e){return e=void 0!==e?e:l.createFolders,t=m(t),this.files[t]||n.call(this,t,null,{dir:!0,createFolders:e}),this.files[t]};function w(t){return"[object RegExp]"===Object.prototype.toString.call(t)}var y={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(t){var e,i,n;for(e in this.files)n=this.files[e],(i=e.slice(this.root.length,e.length))&&e.slice(0,this.root.length)===this.root&&t(i,n)},filter:function(t){var e=[];return this.forEach((function(i,n){t(i,n)&&e.push(n)})),e},file:function(t,e,i){if(1!==arguments.length)return t=this.root+t,n.call(this,t,e,i),this;if(w(t)){var s=t;return this.filter((function(t,e){return!e.dir&&s.test(t)}))}var r=this.files[this.root+t];return r&&!r.dir?r:null},folder:function(t){if(!t)return this;if(w(t))return this.filter((function(e,i){return i.dir&&t.test(e)}));var e=this.root+t,i=g.call(this,e),n=this.clone();return n.root=i.name,n},remove:function(t){t=this.root+t;var e=this.files[t];if(e||("/"!==t.slice(-1)&&(t+="/"),e=this.files[t]),e&&!e.dir)delete this.files[t];else for(var i=this.filter((function(e,i){return i.name.slice(0,t.length)===t})),n=0;n<i.length;n++)delete this.files[i[n].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(t){var e,i={};try{if((i=r.extend(t||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:s.utf8encode})).type=i.type.toLowerCase(),i.compression=i.compression.toUpperCase(),"binarystring"===i.type&&(i.type="string"),!i.type)throw new Error("No output type specified.");r.checkSupport(i.type),"darwin"!==i.platform&&"freebsd"!==i.platform&&"linux"!==i.platform&&"sunos"!==i.platform||(i.platform="UNIX"),"win32"===i.platform&&(i.platform="DOS");var n=i.comment||this.comment||"";e=u.generateWorker(this,i,n)}catch(t){(e=new o("error")).error(t)}return new a(e,i.type||"string",i.mimeType)},generateAsync:function(t,e){return this.generateInternalStream(t).accumulate(e)},generateNodeStream:function(t,e){return(t=t||{}).type||(t.type="nodebuffer"),this.generateInternalStream(t).toNodejsStream(e)}};e.exports=y},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(t,e,i){e.exports=t("stream")},{stream:void 0}],17:[function(t,e,i){var n=t("./DataReader");function s(t){n.call(this,t);for(var e=0;e<this.data.length;e++)t[e]=255&t[e]}t("../utils").inherits(s,n),s.prototype.byteAt=function(t){return this.data[this.zero+t]},s.prototype.lastIndexOfSignature=function(t){for(var e=t.charCodeAt(0),i=t.charCodeAt(1),n=t.charCodeAt(2),s=t.charCodeAt(3),r=this.length-4;0<=r;--r)if(this.data[r]===e&&this.data[r+1]===i&&this.data[r+2]===n&&this.data[r+3]===s)return r-this.zero;return-1},s.prototype.readAndCheckSignature=function(t){var e=t.charCodeAt(0),i=t.charCodeAt(1),n=t.charCodeAt(2),s=t.charCodeAt(3),r=this.readData(4);return e===r[0]&&i===r[1]&&n===r[2]&&s===r[3]},s.prototype.readData=function(t){if(this.checkOffset(t),0===t)return[];var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=s},{"../utils":32,"./DataReader":18}],18:[function(t,e,i){var n=t("../utils");function s(t){this.data=t,this.length=t.length,this.index=0,this.zero=0}s.prototype={checkOffset:function(t){this.checkIndex(this.index+t)},checkIndex:function(t){if(this.length<this.zero+t||t<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+t+"). Corrupted zip ?")},setIndex:function(t){this.checkIndex(t),this.index=t},skip:function(t){this.setIndex(this.index+t)},byteAt:function(){},readInt:function(t){var e,i=0;for(this.checkOffset(t),e=this.index+t-1;e>=this.index;e--)i=(i<<8)+this.byteAt(e);return this.index+=t,i},readString:function(t){return n.transformTo("string",this.readData(t))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var t=this.readInt(4);return new Date(Date.UTC(1980+(t>>25&127),(t>>21&15)-1,t>>16&31,t>>11&31,t>>5&63,(31&t)<<1))}},e.exports=s},{"../utils":32}],19:[function(t,e,i){var n=t("./Uint8ArrayReader");function s(t){n.call(this,t)}t("../utils").inherits(s,n),s.prototype.readData=function(t){this.checkOffset(t);var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=s},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(t,e,i){var n=t("./DataReader");function s(t){n.call(this,t)}t("../utils").inherits(s,n),s.prototype.byteAt=function(t){return this.data.charCodeAt(this.zero+t)},s.prototype.lastIndexOfSignature=function(t){return this.data.lastIndexOf(t)-this.zero},s.prototype.readAndCheckSignature=function(t){return t===this.readData(4)},s.prototype.readData=function(t){this.checkOffset(t);var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=s},{"../utils":32,"./DataReader":18}],21:[function(t,e,i){var n=t("./ArrayReader");function s(t){n.call(this,t)}t("../utils").inherits(s,n),s.prototype.readData=function(t){if(this.checkOffset(t),0===t)return new Uint8Array(0);var e=this.data.subarray(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=s},{"../utils":32,"./ArrayReader":17}],22:[function(t,e,i){var n=t("../utils"),s=t("../support"),r=t("./ArrayReader"),o=t("./StringReader"),a=t("./NodeBufferReader"),l=t("./Uint8ArrayReader");e.exports=function(t){var e=n.getTypeOf(t);return n.checkSupport(e),"string"!==e||s.uint8array?"nodebuffer"===e?new a(t):s.uint8array?new l(n.transformTo("uint8array",t)):new r(n.transformTo("array",t)):new o(t)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(t,e,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\b"},{}],24:[function(t,e,i){var n=t("./GenericWorker"),s=t("../utils");function r(t){n.call(this,"ConvertWorker to "+t),this.destType=t}s.inherits(r,n),r.prototype.processChunk=function(t){this.push({data:s.transformTo(this.destType,t.data),meta:t.meta})},e.exports=r},{"../utils":32,"./GenericWorker":28}],25:[function(t,e,i){var n=t("./GenericWorker"),s=t("../crc32");function r(){n.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}t("../utils").inherits(r,n),r.prototype.processChunk=function(t){this.streamInfo.crc32=s(t.data,this.streamInfo.crc32||0),this.push(t)},e.exports=r},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(t,e,i){var n=t("../utils"),s=t("./GenericWorker");function r(t){s.call(this,"DataLengthProbe for "+t),this.propName=t,this.withStreamInfo(t,0)}n.inherits(r,s),r.prototype.processChunk=function(t){if(t){var e=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=e+t.data.length}s.prototype.processChunk.call(this,t)},e.exports=r},{"../utils":32,"./GenericWorker":28}],27:[function(t,e,i){var n=t("../utils"),s=t("./GenericWorker");function r(t){s.call(this,"DataWorker");var e=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,t.then((function(t){e.dataIsReady=!0,e.data=t,e.max=t&&t.length||0,e.type=n.getTypeOf(t),e.isPaused||e._tickAndRepeat()}),(function(t){e.error(t)}))}n.inherits(r,s),r.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this.data=null},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,n.delay(this._tickAndRepeat,[],this)),!0)},r.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(n.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},r.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var t=null,e=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":t=this.data.substring(this.index,e);break;case"uint8array":t=this.data.subarray(this.index,e);break;case"array":case"nodebuffer":t=this.data.slice(this.index,e)}return this.index=e,this.push({data:t,meta:{percent:this.max?this.index/this.max*100:0}})},e.exports=r},{"../utils":32,"./GenericWorker":28}],28:[function(t,e,i){function n(t){this.name=t||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}n.prototype={push:function(t){this.emit("data",t)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(t){this.emit("error",t)}return!0},error:function(t){return!this.isFinished&&(this.isPaused?this.generatedError=t:(this.isFinished=!0,this.emit("error",t),this.previous&&this.previous.error(t),this.cleanUp()),!0)},on:function(t,e){return this._listeners[t].push(e),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(t,e){if(this._listeners[t])for(var i=0;i<this._listeners[t].length;i++)this._listeners[t][i].call(this,e)},pipe:function(t){return t.registerPrevious(this)},registerPrevious:function(t){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=t.streamInfo,this.mergeStreamInfo(),this.previous=t;var e=this;return t.on("data",(function(t){e.processChunk(t)})),t.on("end",(function(){e.end()})),t.on("error",(function(t){e.error(t)})),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var t=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),t=!0),this.previous&&this.previous.resume(),!t},flush:function(){},processChunk:function(t){this.push(t)},withStreamInfo:function(t,e){return this.extraStreamInfo[t]=e,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var t in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,t)&&(this.streamInfo[t]=this.extraStreamInfo[t])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var t="Worker "+this.name;return this.previous?this.previous+" -> "+t:t}},e.exports=n},{}],29:[function(t,e,i){var n=t("../utils"),s=t("./ConvertWorker"),r=t("./GenericWorker"),o=t("../base64"),a=t("../support"),l=t("../external"),c=null;if(a.nodestream)try{c=t("../nodejs/NodejsStreamOutputAdapter")}catch(t){}function h(t,e){return new l.Promise((function(i,s){var r=[],a=t._internalType,l=t._outputType,c=t._mimeType;t.on("data",(function(t,i){r.push(t),e&&e(i)})).on("error",(function(t){r=[],s(t)})).on("end",(function(){try{var t=function(t,e,i){switch(t){case"blob":return n.newBlob(n.transformTo("arraybuffer",e),i);case"base64":return o.encode(e);default:return n.transformTo(t,e)}}(l,function(t,e){var i,n=0,s=null,r=0;for(i=0;i<e.length;i++)r+=e[i].length;switch(t){case"string":return e.join("");case"array":return Array.prototype.concat.apply([],e);case"uint8array":for(s=new Uint8Array(r),i=0;i<e.length;i++)s.set(e[i],n),n+=e[i].length;return s;case"nodebuffer":return Buffer.concat(e);default:throw new Error("concat : unsupported type '"+t+"'")}}(a,r),c);i(t)}catch(t){s(t)}r=[]})).resume()}))}function u(t,e,i){var o=e;switch(e){case"blob":case"arraybuffer":o="uint8array";break;case"base64":o="string"}try{this._internalType=o,this._outputType=e,this._mimeType=i,n.checkSupport(o),this._worker=t.pipe(new s(o)),t.lock()}catch(t){this._worker=new r("error"),this._worker.error(t)}}u.prototype={accumulate:function(t){return h(this,t)},on:function(t,e){var i=this;return"data"===t?this._worker.on(t,(function(t){e.call(i,t.data,t.meta)})):this._worker.on(t,(function(){n.delay(e,arguments,i)})),this},resume:function(){return n.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(t){if(n.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new c(this,{objectMode:"nodebuffer"!==this._outputType},t)}},e.exports=u},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(t,e,i){if(i.base64=!0,i.array=!0,i.string=!0,i.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,i.nodebuffer="undefined"!=typeof Buffer,i.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)i.blob=!1;else{var n=new ArrayBuffer(0);try{i.blob=0===new Blob([n],{type:"application/zip"}).size}catch(t){try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);s.append(n),i.blob=0===s.getBlob("application/zip").size}catch(t){i.blob=!1}}}try{i.nodestream=!!t("readable-stream").Readable}catch(t){i.nodestream=!1}},{"readable-stream":16}],31:[function(t,e,i){for(var n=t("./utils"),s=t("./support"),r=t("./nodejsUtils"),o=t("./stream/GenericWorker"),a=new Array(256),l=0;l<256;l++)a[l]=252<=l?6:248<=l?5:240<=l?4:224<=l?3:192<=l?2:1;function c(){o.call(this,"utf-8 decode"),this.leftOver=null}function h(){o.call(this,"utf-8 encode")}a[254]=a[254]=1,i.utf8encode=function(t){return s.nodebuffer?r.newBufferFrom(t,"utf-8"):function(t){var e,i,n,r,o,a=t.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(e=s.uint8array?new Uint8Array(l):new Array(l),r=o=0;o<l;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),i<128?e[o++]=i:(i<2048?e[o++]=192|i>>>6:(i<65536?e[o++]=224|i>>>12:(e[o++]=240|i>>>18,e[o++]=128|i>>>12&63),e[o++]=128|i>>>6&63),e[o++]=128|63&i);return e}(t)},i.utf8decode=function(t){return s.nodebuffer?n.transformTo("nodebuffer",t).toString("utf-8"):function(t){var e,i,s,r,o=t.length,l=new Array(2*o);for(e=i=0;e<o;)if((s=t[e++])<128)l[i++]=s;else if(4<(r=a[s]))l[i++]=65533,e+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&e<o;)s=s<<6|63&t[e++],r--;1<r?l[i++]=65533:s<65536?l[i++]=s:(s-=65536,l[i++]=55296|s>>10&1023,l[i++]=56320|1023&s)}return l.length!==i&&(l.subarray?l=l.subarray(0,i):l.length=i),n.applyFromCharCode(l)}(t=n.transformTo(s.uint8array?"uint8array":"array",t))},n.inherits(c,o),c.prototype.processChunk=function(t){var e=n.transformTo(s.uint8array?"uint8array":"array",t.data);if(this.leftOver&&this.leftOver.length){if(s.uint8array){var r=e;(e=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),e.set(r,this.leftOver.length)}else e=this.leftOver.concat(e);this.leftOver=null}var o=function(t,e){var i;for((e=e||t.length)>t.length&&(e=t.length),i=e-1;0<=i&&128==(192&t[i]);)i--;return i<0||0===i?e:i+a[t[i]]>e?i:e}(e),l=e;o!==e.length&&(s.uint8array?(l=e.subarray(0,o),this.leftOver=e.subarray(o,e.length)):(l=e.slice(0,o),this.leftOver=e.slice(o,e.length))),this.push({data:i.utf8decode(l),meta:t.meta})},c.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=c,n.inherits(h,o),h.prototype.processChunk=function(t){this.push({data:i.utf8encode(t.data),meta:t.meta})},i.Utf8EncodeWorker=h},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(t,e,i){var n=t("./support"),s=t("./base64"),r=t("./nodejsUtils"),o=t("./external");function a(t){return t}function l(t,e){for(var i=0;i<t.length;++i)e[i]=255&t.charCodeAt(i);return e}t("setimmediate"),i.newBlob=function(t,e){i.checkSupport("blob");try{return new Blob([t],{type:e})}catch(i){try{var n=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return n.append(t),n.getBlob(e)}catch(t){throw new Error("Bug : can't construct the Blob.")}}};var c={stringifyByChunk:function(t,e,i){var n=[],s=0,r=t.length;if(r<=i)return String.fromCharCode.apply(null,t);for(;s<r;)"array"===e||"nodebuffer"===e?n.push(String.fromCharCode.apply(null,t.slice(s,Math.min(s+i,r)))):n.push(String.fromCharCode.apply(null,t.subarray(s,Math.min(s+i,r)))),s+=i;return n.join("")},stringifyByChar:function(t){for(var e="",i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},applyCanBeUsed:{uint8array:function(){try{return n.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(t){return!1}}(),nodebuffer:function(){try{return n.nodebuffer&&1===String.fromCharCode.apply(null,r.allocBuffer(1)).length}catch(t){return!1}}()}};function h(t){var e=65536,n=i.getTypeOf(t),s=!0;if("uint8array"===n?s=c.applyCanBeUsed.uint8array:"nodebuffer"===n&&(s=c.applyCanBeUsed.nodebuffer),s)for(;1<e;)try{return c.stringifyByChunk(t,n,e)}catch(t){e=Math.floor(e/2)}return c.stringifyByChar(t)}function u(t,e){for(var i=0;i<t.length;i++)e[i]=t[i];return e}i.applyFromCharCode=h;var d={};d.string={string:a,array:function(t){return l(t,new Array(t.length))},arraybuffer:function(t){return d.string.uint8array(t).buffer},uint8array:function(t){return l(t,new Uint8Array(t.length))},nodebuffer:function(t){return l(t,r.allocBuffer(t.length))}},d.array={string:h,array:a,arraybuffer:function(t){return new Uint8Array(t).buffer},uint8array:function(t){return new Uint8Array(t)},nodebuffer:function(t){return r.newBufferFrom(t)}},d.arraybuffer={string:function(t){return h(new Uint8Array(t))},array:function(t){return u(new Uint8Array(t),new Array(t.byteLength))},arraybuffer:a,uint8array:function(t){return new Uint8Array(t)},nodebuffer:function(t){return r.newBufferFrom(new Uint8Array(t))}},d.uint8array={string:h,array:function(t){return u(t,new Array(t.length))},arraybuffer:function(t){return t.buffer},uint8array:a,nodebuffer:function(t){return r.newBufferFrom(t)}},d.nodebuffer={string:h,array:function(t){return u(t,new Array(t.length))},arraybuffer:function(t){return d.nodebuffer.uint8array(t).buffer},uint8array:function(t){return u(t,new Uint8Array(t.length))},nodebuffer:a},i.transformTo=function(t,e){if(e=e||"",!t)return e;i.checkSupport(t);var n=i.getTypeOf(e);return d[n][t](e)},i.resolve=function(t){for(var e=t.split("/"),i=[],n=0;n<e.length;n++){var s=e[n];"."===s||""===s&&0!==n&&n!==e.length-1||(".."===s?i.pop():i.push(s))}return i.join("/")},i.getTypeOf=function(t){return"string"==typeof t?"string":"[object Array]"===Object.prototype.toString.call(t)?"array":n.nodebuffer&&r.isBuffer(t)?"nodebuffer":n.uint8array&&t instanceof Uint8Array?"uint8array":n.arraybuffer&&t instanceof ArrayBuffer?"arraybuffer":void 0},i.checkSupport=function(t){if(!n[t.toLowerCase()])throw new Error(t+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(t){var e,i,n="";for(i=0;i<(t||"").length;i++)n+="\\x"+((e=t.charCodeAt(i))<16?"0":"")+e.toString(16).toUpperCase();return n},i.delay=function(t,e,i){setImmediate((function(){t.apply(i||null,e||[])}))},i.inherits=function(t,e){function i(){}i.prototype=e.prototype,t.prototype=new i},i.extend=function(){var t,e,i={};for(t=0;t<arguments.length;t++)for(e in arguments[t])Object.prototype.hasOwnProperty.call(arguments[t],e)&&void 0===i[e]&&(i[e]=arguments[t][e]);return i},i.prepareContent=function(t,e,r,a,c){return o.Promise.resolve(e).then((function(t){return n.blob&&(t instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(t)))&&"undefined"!=typeof FileReader?new o.Promise((function(e,i){var n=new FileReader;n.onload=function(t){e(t.target.result)},n.onerror=function(t){i(t.target.error)},n.readAsArrayBuffer(t)})):t})).then((function(e){var h,u=i.getTypeOf(e);return u?("arraybuffer"===u?e=i.transformTo("uint8array",e):"string"===u&&(c?e=s.decode(e):r&&!0!==a&&(e=l(h=e,n.uint8array?new Uint8Array(h.length):new Array(h.length)))),e):o.Promise.reject(new Error("Can't read the data of '"+t+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))}))}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(t,e,i){var n=t("./reader/readerFor"),s=t("./utils"),r=t("./signature"),o=t("./zipEntry"),a=t("./support");function l(t){this.files=[],this.loadOptions=t}l.prototype={checkSignature:function(t){if(!this.reader.readAndCheckSignature(t)){this.reader.index-=4;var e=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+s.pretty(e)+", expected "+s.pretty(t)+")")}},isSignature:function(t,e){var i=this.reader.index;this.reader.setIndex(t);var n=this.reader.readString(4)===e;return this.reader.setIndex(i),n},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var t=this.reader.readData(this.zipCommentLength),e=a.uint8array?"uint8array":"array",i=s.transformTo(e,t);this.zipComment=this.loadOptions.decodeFileName(i)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var t,e,i,n=this.zip64EndOfCentralSize-44;0<n;)t=this.reader.readInt(2),e=this.reader.readInt(4),i=this.reader.readData(e),this.zip64ExtensibleData[t]={id:t,length:e,value:i}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var t,e;for(t=0;t<this.files.length;t++)e=this.files[t],this.reader.setIndex(e.localHeaderOffset),this.checkSignature(r.LOCAL_FILE_HEADER),e.readLocalPart(this.reader),e.handleUTF8(),e.processAttributes()},readCentralDir:function(){var t;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(r.CENTRAL_FILE_HEADER);)(t=new o({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(t);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var t=this.reader.lastIndexOfSignature(r.CENTRAL_DIRECTORY_END);if(t<0)throw this.isSignature(0,r.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(t);var e=t;if(this.checkSignature(r.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===s.MAX_VALUE_16BITS||this.diskWithCentralDirStart===s.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===s.MAX_VALUE_16BITS||this.centralDirRecords===s.MAX_VALUE_16BITS||this.centralDirSize===s.MAX_VALUE_32BITS||this.centralDirOffset===s.MAX_VALUE_32BITS){if(this.zip64=!0,(t=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(t),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,r.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var i=this.centralDirOffset+this.centralDirSize;this.zip64&&(i+=20,i+=12+this.zip64EndOfCentralSize);var n=e-i;if(0<n)this.isSignature(e,r.CENTRAL_FILE_HEADER)||(this.reader.zero=n);else if(n<0)throw new Error("Corrupted zip: missing "+Math.abs(n)+" bytes.")},prepareReader:function(t){this.reader=n(t)},load:function(t){this.prepareReader(t),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},e.exports=l},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(t,e,i){var n=t("./reader/readerFor"),s=t("./utils"),r=t("./compressedObject"),o=t("./crc32"),a=t("./utf8"),l=t("./compressions"),c=t("./support");function h(t,e){this.options=t,this.loadOptions=e}h.prototype={isEncrypted:function(){return!(1&~this.bitFlag)},useUTF8:function(){return!(2048&~this.bitFlag)},readLocalPart:function(t){var e,i;if(t.skip(22),this.fileNameLength=t.readInt(2),i=t.readInt(2),this.fileName=t.readData(this.fileNameLength),t.skip(i),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(e=function(t){for(var e in l)if(Object.prototype.hasOwnProperty.call(l,e)&&l[e].magic===t)return l[e];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+s.pretty(this.compressionMethod)+" unknown (inner file : "+s.transformTo("string",this.fileName)+")");this.decompressed=new r(this.compressedSize,this.uncompressedSize,this.crc32,e,t.readData(this.compressedSize))},readCentralPart:function(t){this.versionMadeBy=t.readInt(2),t.skip(2),this.bitFlag=t.readInt(2),this.compressionMethod=t.readString(2),this.date=t.readDate(),this.crc32=t.readInt(4),this.compressedSize=t.readInt(4),this.uncompressedSize=t.readInt(4);var e=t.readInt(2);if(this.extraFieldsLength=t.readInt(2),this.fileCommentLength=t.readInt(2),this.diskNumberStart=t.readInt(2),this.internalFileAttributes=t.readInt(2),this.externalFileAttributes=t.readInt(4),this.localHeaderOffset=t.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");t.skip(e),this.readExtraFields(t),this.parseZIP64ExtraField(t),this.fileComment=t.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var t=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==t&&(this.dosPermissions=63&this.externalFileAttributes),3==t&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var t=n(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=t.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=t.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=t.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=t.readInt(4))}},readExtraFields:function(t){var e,i,n,s=t.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});t.index+4<s;)e=t.readInt(2),i=t.readInt(2),n=t.readData(i),this.extraFields[e]={id:e,length:i,value:n};t.setIndex(s)},handleUTF8:function(){var t=c.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var e=this.findExtraFieldUnicodePath();if(null!==e)this.fileNameStr=e;else{var i=s.transformTo(t,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(i)}var n=this.findExtraFieldUnicodeComment();if(null!==n)this.fileCommentStr=n;else{var r=s.transformTo(t,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(r)}}},findExtraFieldUnicodePath:function(){var t=this.extraFields[28789];if(t){var e=n(t.value);return 1!==e.readInt(1)||o(this.fileName)!==e.readInt(4)?null:a.utf8decode(e.readData(t.length-5))}return null},findExtraFieldUnicodeComment:function(){var t=this.extraFields[25461];if(t){var e=n(t.value);return 1!==e.readInt(1)||o(this.fileComment)!==e.readInt(4)?null:a.utf8decode(e.readData(t.length-5))}return null}},e.exports=h},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(t,e,i){function n(t,e,i){this.name=t,this.dir=i.dir,this.date=i.date,this.comment=i.comment,this.unixPermissions=i.unixPermissions,this.dosPermissions=i.dosPermissions,this._data=e,this._dataBinary=i.binary,this.options={compression:i.compression,compressionOptions:i.compressionOptions}}var s=t("./stream/StreamHelper"),r=t("./stream/DataWorker"),o=t("./utf8"),a=t("./compressedObject"),l=t("./stream/GenericWorker");n.prototype={internalStream:function(t){var e=null,i="string";try{if(!t)throw new Error("No output type specified.");var n="string"===(i=t.toLowerCase())||"text"===i;"binarystring"!==i&&"text"!==i||(i="string"),e=this._decompressWorker();var r=!this._dataBinary;r&&!n&&(e=e.pipe(new o.Utf8EncodeWorker)),!r&&n&&(e=e.pipe(new o.Utf8DecodeWorker))}catch(t){(e=new l("error")).error(t)}return new s(e,i,"")},async:function(t,e){return this.internalStream(t).accumulate(e)},nodeStream:function(t,e){return this.internalStream(t||"nodebuffer").toNodejsStream(e)},_compressWorker:function(t,e){if(this._data instanceof a&&this._data.compression.magic===t.magic)return this._data.getCompressedWorker();var i=this._decompressWorker();return this._dataBinary||(i=i.pipe(new o.Utf8EncodeWorker)),a.createWorkerFrom(i,t,e)},_decompressWorker:function(){return this._data instanceof a?this._data.getContentWorker():this._data instanceof l?this._data:new r(this._data)}};for(var c=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],h=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},u=0;u<c.length;u++)n.prototype[c[u]]=h;e.exports=n},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(t,e,i){(function(t){var i,n,s=t.MutationObserver||t.WebKitMutationObserver;if(s){var r=0,o=new s(h),a=t.document.createTextNode("");o.observe(a,{characterData:!0}),i=function(){a.data=r=++r%2}}else if(t.setImmediate||void 0===t.MessageChannel)i="document"in t&&"onreadystatechange"in t.document.createElement("script")?function(){var e=t.document.createElement("script");e.onreadystatechange=function(){h(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},t.document.documentElement.appendChild(e)}:function(){setTimeout(h,0)};else{var l=new t.MessageChannel;l.port1.onmessage=h,i=function(){l.port2.postMessage(0)}}var c=[];function h(){var t,e;n=!0;for(var i=c.length;i;){for(e=c,c=[],t=-1;++t<i;)e[t]();i=c.length}n=!1}e.exports=function(t){1!==c.push(t)||n||i()}}).call(this,void 0!==Na?Na:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(t,e,i){var n=t("immediate");function s(){}var r={},o=["REJECTED"],a=["FULFILLED"],l=["PENDING"];function c(t){if("function"!=typeof t)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,t!==s&&p(this,t)}function h(t,e,i){this.promise=t,"function"==typeof e&&(this.onFulfilled=e,this.callFulfilled=this.otherCallFulfilled),"function"==typeof i&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}function u(t,e,i){n((function(){var n;try{n=e(i)}catch(e){return r.reject(t,e)}n===t?r.reject(t,new TypeError("Cannot resolve promise with itself")):r.resolve(t,n)}))}function d(t){var e=t&&t.then;if(t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof e)return function(){e.apply(t,arguments)}}function p(t,e){var i=!1;function n(e){i||(i=!0,r.reject(t,e))}function s(e){i||(i=!0,r.resolve(t,e))}var o=f((function(){e(s,n)}));"error"===o.status&&n(o.value)}function f(t,e){var i={};try{i.value=t(e),i.status="success"}catch(t){i.status="error",i.value=t}return i}(e.exports=c).prototype.finally=function(t){if("function"!=typeof t)return this;var e=this.constructor;return this.then((function(i){return e.resolve(t()).then((function(){return i}))}),(function(i){return e.resolve(t()).then((function(){throw i}))}))},c.prototype.catch=function(t){return this.then(null,t)},c.prototype.then=function(t,e){if("function"!=typeof t&&this.state===a||"function"!=typeof e&&this.state===o)return this;var i=new this.constructor(s);return this.state!==l?u(i,this.state===a?t:e,this.outcome):this.queue.push(new h(i,t,e)),i},h.prototype.callFulfilled=function(t){r.resolve(this.promise,t)},h.prototype.otherCallFulfilled=function(t){u(this.promise,this.onFulfilled,t)},h.prototype.callRejected=function(t){r.reject(this.promise,t)},h.prototype.otherCallRejected=function(t){u(this.promise,this.onRejected,t)},r.resolve=function(t,e){var i=f(d,e);if("error"===i.status)return r.reject(t,i.value);var n=i.value;if(n)p(t,n);else{t.state=a,t.outcome=e;for(var s=-1,o=t.queue.length;++s<o;)t.queue[s].callFulfilled(e)}return t},r.reject=function(t,e){t.state=o,t.outcome=e;for(var i=-1,n=t.queue.length;++i<n;)t.queue[i].callRejected(e);return t},c.resolve=function(t){return t instanceof this?t:r.resolve(new this(s),t)},c.reject=function(t){var e=new this(s);return r.reject(e,t)},c.all=function(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,n=!1;if(!i)return this.resolve([]);for(var o=new Array(i),a=0,l=-1,c=new this(s);++l<i;)h(t[l],l);return c;function h(t,s){e.resolve(t).then((function(t){o[s]=t,++a!==i||n||(n=!0,r.resolve(c,o))}),(function(t){n||(n=!0,r.reject(c,t))}))}},c.race=function(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,n=!1;if(!i)return this.resolve([]);for(var o,a=-1,l=new this(s);++a<i;)o=t[a],e.resolve(o).then((function(t){n||(n=!0,r.resolve(l,t))}),(function(t){n||(n=!0,r.reject(l,t))}));return l}},{immediate:36}],38:[function(t,e,i){var n={};(0,t("./lib/utils/common").assign)(n,t("./lib/deflate"),t("./lib/inflate"),t("./lib/zlib/constants")),e.exports=n},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(t,e,i){var n=t("./zlib/deflate"),s=t("./utils/common"),r=t("./utils/strings"),o=t("./zlib/messages"),a=t("./zlib/zstream"),l=Object.prototype.toString,c=0,h=-1,u=0,d=8;function p(t){if(!(this instanceof p))return new p(t);this.options=s.assign({level:h,method:d,chunkSize:16384,windowBits:15,memLevel:8,strategy:u,to:""},t||{});var e=this.options;e.raw&&0<e.windowBits?e.windowBits=-e.windowBits:e.gzip&&0<e.windowBits&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var i=n.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==c)throw new Error(o[i]);if(e.header&&n.deflateSetHeader(this.strm,e.header),e.dictionary){var f;if(f="string"==typeof e.dictionary?r.string2buf(e.dictionary):"[object ArrayBuffer]"===l.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,(i=n.deflateSetDictionary(this.strm,f))!==c)throw new Error(o[i]);this._dict_set=!0}}function f(t,e){var i=new p(e);if(i.push(t,!0),i.err)throw i.msg||o[i.err];return i.result}p.prototype.push=function(t,e){var i,o,a=this.strm,h=this.options.chunkSize;if(this.ended)return!1;o=e===~~e?e:!0===e?4:0,"string"==typeof t?a.input=r.string2buf(t):"[object ArrayBuffer]"===l.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new s.Buf8(h),a.next_out=0,a.avail_out=h),1!==(i=n.deflate(a,o))&&i!==c)return this.onEnd(i),!(this.ended=!0);0!==a.avail_out&&(0!==a.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(r.buf2binstring(s.shrinkBuf(a.output,a.next_out))):this.onData(s.shrinkBuf(a.output,a.next_out)))}while((0<a.avail_in||0===a.avail_out)&&1!==i);return 4===o?(i=n.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===c):2!==o||(this.onEnd(c),!(a.avail_out=0))},p.prototype.onData=function(t){this.chunks.push(t)},p.prototype.onEnd=function(t){t===c&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},i.Deflate=p,i.deflate=f,i.deflateRaw=function(t,e){return(e=e||{}).raw=!0,f(t,e)},i.gzip=function(t,e){return(e=e||{}).gzip=!0,f(t,e)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(t,e,i){var n=t("./zlib/inflate"),s=t("./utils/common"),r=t("./utils/strings"),o=t("./zlib/constants"),a=t("./zlib/messages"),l=t("./zlib/zstream"),c=t("./zlib/gzheader"),h=Object.prototype.toString;function u(t){if(!(this instanceof u))return new u(t);this.options=s.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&0<=e.windowBits&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(0<=e.windowBits&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),15<e.windowBits&&e.windowBits<48&&!(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var i=n.inflateInit2(this.strm,e.windowBits);if(i!==o.Z_OK)throw new Error(a[i]);this.header=new c,n.inflateGetHeader(this.strm,this.header)}function d(t,e){var i=new u(e);if(i.push(t,!0),i.err)throw i.msg||a[i.err];return i.result}u.prototype.push=function(t,e){var i,a,l,c,u,d,p=this.strm,f=this.options.chunkSize,m=this.options.dictionary,g=!1;if(this.ended)return!1;a=e===~~e?e:!0===e?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof t?p.input=r.binstring2buf(t):"[object ArrayBuffer]"===h.call(t)?p.input=new Uint8Array(t):p.input=t,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new s.Buf8(f),p.next_out=0,p.avail_out=f),(i=n.inflate(p,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&m&&(d="string"==typeof m?r.string2buf(m):"[object ArrayBuffer]"===h.call(m)?new Uint8Array(m):m,i=n.inflateSetDictionary(this.strm,d)),i===o.Z_BUF_ERROR&&!0===g&&(i=o.Z_OK,g=!1),i!==o.Z_STREAM_END&&i!==o.Z_OK)return this.onEnd(i),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&i!==o.Z_STREAM_END&&(0!==p.avail_in||a!==o.Z_FINISH&&a!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(l=r.utf8border(p.output,p.next_out),c=p.next_out-l,u=r.buf2string(p.output,l),p.next_out=c,p.avail_out=f-c,c&&s.arraySet(p.output,p.output,l,c,0),this.onData(u)):this.onData(s.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((0<p.avail_in||0===p.avail_out)&&i!==o.Z_STREAM_END);return i===o.Z_STREAM_END&&(a=o.Z_FINISH),a===o.Z_FINISH?(i=n.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===o.Z_OK):a!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),!(p.avail_out=0))},u.prototype.onData=function(t){this.chunks.push(t)},u.prototype.onEnd=function(t){t===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},i.Inflate=u,i.inflate=d,i.inflateRaw=function(t,e){return(e=e||{}).raw=!0,d(t,e)},i.ungzip=d},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(t,e,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;i.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var n in i)i.hasOwnProperty(n)&&(t[n]=i[n])}}return t},i.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var s={arraySet:function(t,e,i,n,s){if(e.subarray&&t.subarray)t.set(e.subarray(i,i+n),s);else for(var r=0;r<n;r++)t[s+r]=e[i+r]},flattenChunks:function(t){var e,i,n,s,r,o;for(e=n=0,i=t.length;e<i;e++)n+=t[e].length;for(o=new Uint8Array(n),e=s=0,i=t.length;e<i;e++)r=t[e],o.set(r,s),s+=r.length;return o}},r={arraySet:function(t,e,i,n,s){for(var r=0;r<n;r++)t[s+r]=e[i+r]},flattenChunks:function(t){return[].concat.apply([],t)}};i.setTyped=function(t){t?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,s)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,r))},i.setTyped(n)},{}],42:[function(t,e,i){var n=t("./common"),s=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch(t){s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){r=!1}for(var o=new n.Buf8(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function l(t,e){if(e<65537&&(t.subarray&&r||!t.subarray&&s))return String.fromCharCode.apply(null,n.shrinkBuf(t,e));for(var i="",o=0;o<e;o++)i+=String.fromCharCode(t[o]);return i}o[254]=o[254]=1,i.string2buf=function(t){var e,i,s,r,o,a=t.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(e=new n.Buf8(l),r=o=0;o<l;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),i<128?e[o++]=i:(i<2048?e[o++]=192|i>>>6:(i<65536?e[o++]=224|i>>>12:(e[o++]=240|i>>>18,e[o++]=128|i>>>12&63),e[o++]=128|i>>>6&63),e[o++]=128|63&i);return e},i.buf2binstring=function(t){return l(t,t.length)},i.binstring2buf=function(t){for(var e=new n.Buf8(t.length),i=0,s=e.length;i<s;i++)e[i]=t.charCodeAt(i);return e},i.buf2string=function(t,e){var i,n,s,r,a=e||t.length,c=new Array(2*a);for(i=n=0;i<a;)if((s=t[i++])<128)c[n++]=s;else if(4<(r=o[s]))c[n++]=65533,i+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&i<a;)s=s<<6|63&t[i++],r--;1<r?c[n++]=65533:s<65536?c[n++]=s:(s-=65536,c[n++]=55296|s>>10&1023,c[n++]=56320|1023&s)}return l(c,n)},i.utf8border=function(t,e){var i;for((e=e||t.length)>t.length&&(e=t.length),i=e-1;0<=i&&128==(192&t[i]);)i--;return i<0||0===i?e:i+o[t[i]]>e?i:e}},{"./common":41}],43:[function(t,e,i){e.exports=function(t,e,i,n){for(var s=65535&t,r=t>>>16&65535,o=0;0!==i;){for(i-=o=2e3<i?2e3:i;r=r+(s=s+e[n++]|0)|0,--o;);s%=65521,r%=65521}return s|r<<16}},{}],44:[function(t,e,i){e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(t,e,i){var n=function(){for(var t,e=[],i=0;i<256;i++){t=i;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e}();e.exports=function(t,e,i,s){var r=n,o=s+i;t^=-1;for(var a=s;a<o;a++)t=t>>>8^r[255&(t^e[a])];return~t}},{}],46:[function(t,e,i){var n,s=t("../utils/common"),r=t("./trees"),o=t("./adler32"),a=t("./crc32"),l=t("./messages"),c=0,h=4,u=0,d=-2,p=-1,f=4,m=2,g=8,w=9,y=286,_=30,b=19,v=2*y+1,x=15,C=3,S=258,A=S+C+1,P=42,T=113,E=1,M=2,I=3,z=4;function D(t,e){return t.msg=l[e],e}function k(t){return(t<<1)-(4<t?9:0)}function B(t){for(var e=t.length;0<=--e;)t[e]=0}function O(t){var e=t.state,i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(s.arraySet(t.output,e.pending_buf,e.pending_out,i,t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))}function N(t,e){r._tr_flush_block(t,0<=t.block_start?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,O(t.strm)}function V(t,e){t.pending_buf[t.pending++]=e}function L(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function F(t,e){var i,n,s=t.max_chain_length,r=t.strstart,o=t.prev_length,a=t.nice_match,l=t.strstart>t.w_size-A?t.strstart-(t.w_size-A):0,c=t.window,h=t.w_mask,u=t.prev,d=t.strstart+S,p=c[r+o-1],f=c[r+o];t.prev_length>=t.good_match&&(s>>=2),a>t.lookahead&&(a=t.lookahead);do{if(c[(i=e)+o]===f&&c[i+o-1]===p&&c[i]===c[r]&&c[++i]===c[r+1]){r+=2,i++;do{}while(c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&r<d);if(n=S-(d-r),r=d-S,o<n){if(t.match_start=e,a<=(o=n))break;p=c[r+o-1],f=c[r+o]}}}while((e=u[e&h])>l&&0!=--s);return o<=t.lookahead?o:t.lookahead}function R(t){var e,i,n,r,l,c,h,u,d,p,f=t.w_size;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=f+(f-A)){for(s.arraySet(t.window,t.window,f,f,0),t.match_start-=f,t.strstart-=f,t.block_start-=f,e=i=t.hash_size;n=t.head[--e],t.head[e]=f<=n?n-f:0,--i;);for(e=i=f;n=t.prev[--e],t.prev[e]=f<=n?n-f:0,--i;);r+=f}if(0===t.strm.avail_in)break;if(c=t.strm,h=t.window,u=t.strstart+t.lookahead,p=void 0,(d=r)<(p=c.avail_in)&&(p=d),i=0===p?0:(c.avail_in-=p,s.arraySet(h,c.input,c.next_in,p,u),1===c.state.wrap?c.adler=o(c.adler,h,p,u):2===c.state.wrap&&(c.adler=a(c.adler,h,p,u)),c.next_in+=p,c.total_in+=p,p),t.lookahead+=i,t.lookahead+t.insert>=C)for(l=t.strstart-t.insert,t.ins_h=t.window[l],t.ins_h=(t.ins_h<<t.hash_shift^t.window[l+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[l+C-1])&t.hash_mask,t.prev[l&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=l,l++,t.insert--,!(t.lookahead+t.insert<C)););}while(t.lookahead<A&&0!==t.strm.avail_in)}function U(t,e){for(var i,n;;){if(t.lookahead<A){if(R(t),t.lookahead<A&&e===c)return E;if(0===t.lookahead)break}if(i=0,t.lookahead>=C&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+C-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-A&&(t.match_length=F(t,i)),t.match_length>=C)if(n=r._tr_tally(t,t.strstart-t.match_start,t.match_length-C),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=C){for(t.match_length--;t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+C-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart,0!=--t.match_length;);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else n=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(n&&(N(t,!1),0===t.strm.avail_out))return E}return t.insert=t.strstart<C-1?t.strstart:C-1,e===h?(N(t,!0),0===t.strm.avail_out?I:z):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?E:M}function j(t,e){for(var i,n,s;;){if(t.lookahead<A){if(R(t),t.lookahead<A&&e===c)return E;if(0===t.lookahead)break}if(i=0,t.lookahead>=C&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+C-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=C-1,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-A&&(t.match_length=F(t,i),t.match_length<=5&&(1===t.strategy||t.match_length===C&&4096<t.strstart-t.match_start)&&(t.match_length=C-1)),t.prev_length>=C&&t.match_length<=t.prev_length){for(s=t.strstart+t.lookahead-C,n=r._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-C),t.lookahead-=t.prev_length-1,t.prev_length-=2;++t.strstart<=s&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+C-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!=--t.prev_length;);if(t.match_available=0,t.match_length=C-1,t.strstart++,n&&(N(t,!1),0===t.strm.avail_out))return E}else if(t.match_available){if((n=r._tr_tally(t,0,t.window[t.strstart-1]))&&N(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return E}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(n=r._tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<C-1?t.strstart:C-1,e===h?(N(t,!0),0===t.strm.avail_out?I:z):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?E:M}function $(t,e,i,n,s){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=n,this.func=s}function W(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=g,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new s.Buf16(2*v),this.dyn_dtree=new s.Buf16(2*(2*_+1)),this.bl_tree=new s.Buf16(2*(2*b+1)),B(this.dyn_ltree),B(this.dyn_dtree),B(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new s.Buf16(x+1),this.heap=new s.Buf16(2*y+1),B(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new s.Buf16(2*y+1),B(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function G(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=m,(e=t.state).pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?P:T,t.adler=2===e.wrap?0:1,e.last_flush=c,r._tr_init(e),u):D(t,d)}function H(t){var e,i=G(t);return i===u&&((e=t.state).window_size=2*e.w_size,B(e.head),e.max_lazy_match=n[e.level].max_lazy,e.good_match=n[e.level].good_length,e.nice_match=n[e.level].nice_length,e.max_chain_length=n[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=C-1,e.match_available=0,e.ins_h=0),i}function Z(t,e,i,n,r,o){if(!t)return d;var a=1;if(e===p&&(e=6),n<0?(a=0,n=-n):15<n&&(a=2,n-=16),r<1||w<r||i!==g||n<8||15<n||e<0||9<e||o<0||f<o)return D(t,d);8===n&&(n=9);var l=new W;return(t.state=l).strm=t,l.wrap=a,l.gzhead=null,l.w_bits=n,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=r+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+C-1)/C),l.window=new s.Buf8(2*l.w_size),l.head=new s.Buf16(l.hash_size),l.prev=new s.Buf16(l.w_size),l.lit_bufsize=1<<r+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new s.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=e,l.strategy=o,l.method=i,H(t)}n=[new $(0,0,0,0,(function(t,e){var i=65535;for(i>t.pending_buf_size-5&&(i=t.pending_buf_size-5);;){if(t.lookahead<=1){if(R(t),0===t.lookahead&&e===c)return E;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var n=t.block_start+i;if((0===t.strstart||t.strstart>=n)&&(t.lookahead=t.strstart-n,t.strstart=n,N(t,!1),0===t.strm.avail_out))return E;if(t.strstart-t.block_start>=t.w_size-A&&(N(t,!1),0===t.strm.avail_out))return E}return t.insert=0,e===h?(N(t,!0),0===t.strm.avail_out?I:z):(t.strstart>t.block_start&&(N(t,!1),t.strm.avail_out),E)})),new $(4,4,8,4,U),new $(4,5,16,8,U),new $(4,6,32,32,U),new $(4,4,16,16,j),new $(8,16,32,32,j),new $(8,16,128,128,j),new $(8,32,128,256,j),new $(32,128,258,1024,j),new $(32,258,258,4096,j)],i.deflateInit=function(t,e){return Z(t,e,g,15,8,0)},i.deflateInit2=Z,i.deflateReset=H,i.deflateResetKeep=G,i.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?d:(t.state.gzhead=e,u):d},i.deflate=function(t,e){var i,s,o,l;if(!t||!t.state||5<e||e<0)return t?D(t,d):d;if(s=t.state,!t.output||!t.input&&0!==t.avail_in||666===s.status&&e!==h)return D(t,0===t.avail_out?-5:d);if(s.strm=t,i=s.last_flush,s.last_flush=e,s.status===P)if(2===s.wrap)t.adler=0,V(s,31),V(s,139),V(s,8),s.gzhead?(V(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),V(s,255&s.gzhead.time),V(s,s.gzhead.time>>8&255),V(s,s.gzhead.time>>16&255),V(s,s.gzhead.time>>24&255),V(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),V(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(V(s,255&s.gzhead.extra.length),V(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(t.adler=a(t.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69):(V(s,0),V(s,0),V(s,0),V(s,0),V(s,0),V(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),V(s,3),s.status=T);else{var p=g+(s.w_bits-8<<4)<<8;p|=(2<=s.strategy||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(p|=32),p+=31-p%31,s.status=T,L(s,p),0!==s.strstart&&(L(s,t.adler>>>16),L(s,65535&t.adler)),t.adler=1}if(69===s.status)if(s.gzhead.extra){for(o=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),O(t),o=s.pending,s.pending!==s.pending_buf_size));)V(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=73)}else s.status=73;if(73===s.status)if(s.gzhead.name){o=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),O(t),o=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,V(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),0===l&&(s.gzindex=0,s.status=91)}else s.status=91;if(91===s.status)if(s.gzhead.comment){o=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),O(t),o=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,V(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>o&&(t.adler=a(t.adler,s.pending_buf,s.pending-o,o)),0===l&&(s.status=103)}else s.status=103;if(103===s.status&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&O(t),s.pending+2<=s.pending_buf_size&&(V(s,255&t.adler),V(s,t.adler>>8&255),t.adler=0,s.status=T)):s.status=T),0!==s.pending){if(O(t),0===t.avail_out)return s.last_flush=-1,u}else if(0===t.avail_in&&k(e)<=k(i)&&e!==h)return D(t,-5);if(666===s.status&&0!==t.avail_in)return D(t,-5);if(0!==t.avail_in||0!==s.lookahead||e!==c&&666!==s.status){var f=2===s.strategy?function(t,e){for(var i;;){if(0===t.lookahead&&(R(t),0===t.lookahead)){if(e===c)return E;break}if(t.match_length=0,i=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(N(t,!1),0===t.strm.avail_out))return E}return t.insert=0,e===h?(N(t,!0),0===t.strm.avail_out?I:z):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?E:M}(s,e):3===s.strategy?function(t,e){for(var i,n,s,o,a=t.window;;){if(t.lookahead<=S){if(R(t),t.lookahead<=S&&e===c)return E;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=C&&0<t.strstart&&(n=a[s=t.strstart-1])===a[++s]&&n===a[++s]&&n===a[++s]){o=t.strstart+S;do{}while(n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&s<o);t.match_length=S-(o-s),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=C?(i=r._tr_tally(t,1,t.match_length-C),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(N(t,!1),0===t.strm.avail_out))return E}return t.insert=0,e===h?(N(t,!0),0===t.strm.avail_out?I:z):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?E:M}(s,e):n[s.level].func(s,e);if(f!==I&&f!==z||(s.status=666),f===E||f===I)return 0===t.avail_out&&(s.last_flush=-1),u;if(f===M&&(1===e?r._tr_align(s):5!==e&&(r._tr_stored_block(s,0,0,!1),3===e&&(B(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),O(t),0===t.avail_out))return s.last_flush=-1,u}return e!==h?u:s.wrap<=0?1:(2===s.wrap?(V(s,255&t.adler),V(s,t.adler>>8&255),V(s,t.adler>>16&255),V(s,t.adler>>24&255),V(s,255&t.total_in),V(s,t.total_in>>8&255),V(s,t.total_in>>16&255),V(s,t.total_in>>24&255)):(L(s,t.adler>>>16),L(s,65535&t.adler)),O(t),0<s.wrap&&(s.wrap=-s.wrap),0!==s.pending?u:1)},i.deflateEnd=function(t){var e;return t&&t.state?(e=t.state.status)!==P&&69!==e&&73!==e&&91!==e&&103!==e&&e!==T&&666!==e?D(t,d):(t.state=null,e===T?D(t,-3):u):d},i.deflateSetDictionary=function(t,e){var i,n,r,a,l,c,h,p,f=e.length;if(!t||!t.state)return d;if(2===(a=(i=t.state).wrap)||1===a&&i.status!==P||i.lookahead)return d;for(1===a&&(t.adler=o(t.adler,e,f,0)),i.wrap=0,f>=i.w_size&&(0===a&&(B(i.head),i.strstart=0,i.block_start=0,i.insert=0),p=new s.Buf8(i.w_size),s.arraySet(p,e,f-i.w_size,i.w_size,0),e=p,f=i.w_size),l=t.avail_in,c=t.next_in,h=t.input,t.avail_in=f,t.next_in=0,t.input=e,R(i);i.lookahead>=C;){for(n=i.strstart,r=i.lookahead-(C-1);i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+C-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++,--r;);i.strstart=n,i.lookahead=C-1,R(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=C-1,i.match_available=0,t.next_in=c,t.input=h,t.avail_in=l,i.wrap=a,u},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(t,e,i){e.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(t,e,i){e.exports=function(t,e){var i,n,s,r,o,a,l,c,h,u,d,p,f,m,g,w,y,_,b,v,x,C,S,A,P;i=t.state,n=t.next_in,A=t.input,s=n+(t.avail_in-5),r=t.next_out,P=t.output,o=r-(e-t.avail_out),a=r+(t.avail_out-257),l=i.dmax,c=i.wsize,h=i.whave,u=i.wnext,d=i.window,p=i.hold,f=i.bits,m=i.lencode,g=i.distcode,w=(1<<i.lenbits)-1,y=(1<<i.distbits)-1;t:do{f<15&&(p+=A[n++]<<f,f+=8,p+=A[n++]<<f,f+=8),_=m[p&w];e:for(;;){if(p>>>=b=_>>>24,f-=b,0==(b=_>>>16&255))P[r++]=65535&_;else{if(!(16&b)){if(!(64&b)){_=m[(65535&_)+(p&(1<<b)-1)];continue e}if(32&b){i.mode=12;break t}t.msg="invalid literal/length code",i.mode=30;break t}v=65535&_,(b&=15)&&(f<b&&(p+=A[n++]<<f,f+=8),v+=p&(1<<b)-1,p>>>=b,f-=b),f<15&&(p+=A[n++]<<f,f+=8,p+=A[n++]<<f,f+=8),_=g[p&y];i:for(;;){if(p>>>=b=_>>>24,f-=b,!(16&(b=_>>>16&255))){if(!(64&b)){_=g[(65535&_)+(p&(1<<b)-1)];continue i}t.msg="invalid distance code",i.mode=30;break t}if(x=65535&_,f<(b&=15)&&(p+=A[n++]<<f,(f+=8)<b&&(p+=A[n++]<<f,f+=8)),l<(x+=p&(1<<b)-1)){t.msg="invalid distance too far back",i.mode=30;break t}if(p>>>=b,f-=b,(b=r-o)<x){if(h<(b=x-b)&&i.sane){t.msg="invalid distance too far back",i.mode=30;break t}if(S=d,(C=0)===u){if(C+=c-b,b<v){for(v-=b;P[r++]=d[C++],--b;);C=r-x,S=P}}else if(u<b){if(C+=c+u-b,(b-=u)<v){for(v-=b;P[r++]=d[C++],--b;);if(C=0,u<v){for(v-=b=u;P[r++]=d[C++],--b;);C=r-x,S=P}}}else if(C+=u-b,b<v){for(v-=b;P[r++]=d[C++],--b;);C=r-x,S=P}for(;2<v;)P[r++]=S[C++],P[r++]=S[C++],P[r++]=S[C++],v-=3;v&&(P[r++]=S[C++],1<v&&(P[r++]=S[C++]))}else{for(C=r-x;P[r++]=P[C++],P[r++]=P[C++],P[r++]=P[C++],2<(v-=3););v&&(P[r++]=P[C++],1<v&&(P[r++]=P[C++]))}break}}break}}while(n<s&&r<a);n-=v=f>>3,p&=(1<<(f-=v<<3))-1,t.next_in=n,t.next_out=r,t.avail_in=n<s?s-n+5:5-(n-s),t.avail_out=r<a?a-r+257:257-(r-a),i.hold=p,i.bits=f}},{}],49:[function(t,e,i){var n=t("../utils/common"),s=t("./adler32"),r=t("./crc32"),o=t("./inffast"),a=t("./inftrees"),l=1,c=2,h=0,u=-2,d=1,p=852,f=592;function m(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new n.Buf16(320),this.work=new n.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function w(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=d,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new n.Buf32(p),e.distcode=e.distdyn=new n.Buf32(f),e.sane=1,e.back=-1,h):u}function y(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,w(t)):u}function _(t,e){var i,n;return t&&t.state?(n=t.state,e<0?(i=0,e=-e):(i=1+(e>>4),e<48&&(e&=15)),e&&(e<8||15<e)?u:(null!==n.window&&n.wbits!==e&&(n.window=null),n.wrap=i,n.wbits=e,y(t))):u}function b(t,e){var i,n;return t?(n=new g,(t.state=n).window=null,(i=_(t,e))!==h&&(t.state=null),i):u}var v,x,C=!0;function S(t){if(C){var e;for(v=new n.Buf32(512),x=new n.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(a(l,t.lens,0,288,v,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;a(c,t.lens,0,32,x,0,t.work,{bits:5}),C=!1}t.lencode=v,t.lenbits=9,t.distcode=x,t.distbits=5}function A(t,e,i,s){var r,o=t.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new n.Buf8(o.wsize)),s>=o.wsize?(n.arraySet(o.window,e,i-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(s<(r=o.wsize-o.wnext)&&(r=s),n.arraySet(o.window,e,i-s,r,o.wnext),(s-=r)?(n.arraySet(o.window,e,i-s,s,0),o.wnext=s,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=r))),0}i.inflateReset=y,i.inflateReset2=_,i.inflateResetKeep=w,i.inflateInit=function(t){return b(t,15)},i.inflateInit2=b,i.inflate=function(t,e){var i,p,f,g,w,y,_,b,v,x,C,P,T,E,M,I,z,D,k,B,O,N,V,L,F=0,R=new n.Buf8(4),U=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return u;12===(i=t.state).mode&&(i.mode=13),w=t.next_out,f=t.output,_=t.avail_out,g=t.next_in,p=t.input,y=t.avail_in,b=i.hold,v=i.bits,x=y,C=_,N=h;t:for(;;)switch(i.mode){case d:if(0===i.wrap){i.mode=13;break}for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(2&i.wrap&&35615===b){R[i.check=0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0),v=b=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&b)<<8)+(b>>8))%31){t.msg="incorrect header check",i.mode=30;break}if(8!=(15&b)){t.msg="unknown compression method",i.mode=30;break}if(v-=4,O=8+(15&(b>>>=4)),0===i.wbits)i.wbits=O;else if(O>i.wbits){t.msg="invalid window size",i.mode=30;break}i.dmax=1<<O,t.adler=i.check=1,i.mode=512&b?10:12,v=b=0;break;case 2:for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(i.flags=b,8!=(255&i.flags)){t.msg="unknown compression method",i.mode=30;break}if(57344&i.flags){t.msg="unknown header flags set",i.mode=30;break}i.head&&(i.head.text=b>>8&1),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0,i.mode=3;case 3:for(;v<32;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.head&&(i.head.time=b),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,R[2]=b>>>16&255,R[3]=b>>>24&255,i.check=r(i.check,R,4,0)),v=b=0,i.mode=4;case 4:for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.head&&(i.head.xflags=255&b,i.head.os=b>>8),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0,i.mode=5;case 5:if(1024&i.flags){for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.length=b,i.head&&(i.head.extra_len=b),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(y<(P=i.length)&&(P=y),P&&(i.head&&(O=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),n.arraySet(i.head.extra,p,g,P,O)),512&i.flags&&(i.check=r(i.check,p,P,g)),y-=P,g+=P,i.length-=P),i.length))break t;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===y)break t;for(P=0;O=p[g+P++],i.head&&O&&i.length<65536&&(i.head.name+=String.fromCharCode(O)),O&&P<y;);if(512&i.flags&&(i.check=r(i.check,p,P,g)),y-=P,g+=P,O)break t}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===y)break t;for(P=0;O=p[g+P++],i.head&&O&&i.length<65536&&(i.head.comment+=String.fromCharCode(O)),O&&P<y;);if(512&i.flags&&(i.check=r(i.check,p,P,g)),y-=P,g+=P,O)break t}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;v<16;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(b!==(65535&i.check)){t.msg="header crc mismatch",i.mode=30;break}v=b=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),t.adler=i.check=0,i.mode=12;break;case 10:for(;v<32;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}t.adler=i.check=m(b),v=b=0,i.mode=11;case 11:if(0===i.havedict)return t.next_out=w,t.avail_out=_,t.next_in=g,t.avail_in=y,i.hold=b,i.bits=v,2;t.adler=i.check=1,i.mode=12;case 12:if(5===e||6===e)break t;case 13:if(i.last){b>>>=7&v,v-=7&v,i.mode=27;break}for(;v<3;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}switch(i.last=1&b,v-=1,3&(b>>>=1)){case 0:i.mode=14;break;case 1:if(S(i),i.mode=20,6!==e)break;b>>>=2,v-=2;break t;case 2:i.mode=17;break;case 3:t.msg="invalid block type",i.mode=30}b>>>=2,v-=2;break;case 14:for(b>>>=7&v,v-=7&v;v<32;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if((65535&b)!=(b>>>16^65535)){t.msg="invalid stored block lengths",i.mode=30;break}if(i.length=65535&b,v=b=0,i.mode=15,6===e)break t;case 15:i.mode=16;case 16:if(P=i.length){if(y<P&&(P=y),_<P&&(P=_),0===P)break t;n.arraySet(f,p,g,P,w),y-=P,g+=P,_-=P,w+=P,i.length-=P;break}i.mode=12;break;case 17:for(;v<14;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(i.nlen=257+(31&b),b>>>=5,v-=5,i.ndist=1+(31&b),b>>>=5,v-=5,i.ncode=4+(15&b),b>>>=4,v-=4,286<i.nlen||30<i.ndist){t.msg="too many length or distance symbols",i.mode=30;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;v<3;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.lens[U[i.have++]]=7&b,b>>>=3,v-=3}for(;i.have<19;)i.lens[U[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,V={bits:i.lenbits},N=a(0,i.lens,0,19,i.lencode,0,i.work,V),i.lenbits=V.bits,N){t.msg="invalid code lengths set",i.mode=30;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;I=(F=i.lencode[b&(1<<i.lenbits)-1])>>>16&255,z=65535&F,!((M=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(z<16)b>>>=M,v-=M,i.lens[i.have++]=z;else{if(16===z){for(L=M+2;v<L;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(b>>>=M,v-=M,0===i.have){t.msg="invalid bit length repeat",i.mode=30;break}O=i.lens[i.have-1],P=3+(3&b),b>>>=2,v-=2}else if(17===z){for(L=M+3;v<L;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}v-=M,O=0,P=3+(7&(b>>>=M)),b>>>=3,v-=3}else{for(L=M+7;v<L;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}v-=M,O=0,P=11+(127&(b>>>=M)),b>>>=7,v-=7}if(i.have+P>i.nlen+i.ndist){t.msg="invalid bit length repeat",i.mode=30;break}for(;P--;)i.lens[i.have++]=O}}if(30===i.mode)break;if(0===i.lens[256]){t.msg="invalid code -- missing end-of-block",i.mode=30;break}if(i.lenbits=9,V={bits:i.lenbits},N=a(l,i.lens,0,i.nlen,i.lencode,0,i.work,V),i.lenbits=V.bits,N){t.msg="invalid literal/lengths set",i.mode=30;break}if(i.distbits=6,i.distcode=i.distdyn,V={bits:i.distbits},N=a(c,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,V),i.distbits=V.bits,N){t.msg="invalid distances set",i.mode=30;break}if(i.mode=20,6===e)break t;case 20:i.mode=21;case 21:if(6<=y&&258<=_){t.next_out=w,t.avail_out=_,t.next_in=g,t.avail_in=y,i.hold=b,i.bits=v,o(t,C),w=t.next_out,f=t.output,_=t.avail_out,g=t.next_in,p=t.input,y=t.avail_in,b=i.hold,v=i.bits,12===i.mode&&(i.back=-1);break}for(i.back=0;I=(F=i.lencode[b&(1<<i.lenbits)-1])>>>16&255,z=65535&F,!((M=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(I&&!(240&I)){for(D=M,k=I,B=z;I=(F=i.lencode[B+((b&(1<<D+k)-1)>>D)])>>>16&255,z=65535&F,!(D+(M=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}b>>>=D,v-=D,i.back+=D}if(b>>>=M,v-=M,i.back+=M,i.length=z,0===I){i.mode=26;break}if(32&I){i.back=-1,i.mode=12;break}if(64&I){t.msg="invalid literal/length code",i.mode=30;break}i.extra=15&I,i.mode=22;case 22:if(i.extra){for(L=i.extra;v<L;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.length+=b&(1<<i.extra)-1,b>>>=i.extra,v-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;I=(F=i.distcode[b&(1<<i.distbits)-1])>>>16&255,z=65535&F,!((M=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(!(240&I)){for(D=M,k=I,B=z;I=(F=i.distcode[B+((b&(1<<D+k)-1)>>D)])>>>16&255,z=65535&F,!(D+(M=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}b>>>=D,v-=D,i.back+=D}if(b>>>=M,v-=M,i.back+=M,64&I){t.msg="invalid distance code",i.mode=30;break}i.offset=z,i.extra=15&I,i.mode=24;case 24:if(i.extra){for(L=i.extra;v<L;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}i.offset+=b&(1<<i.extra)-1,b>>>=i.extra,v-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){t.msg="invalid distance too far back",i.mode=30;break}i.mode=25;case 25:if(0===_)break t;if(P=C-_,i.offset>P){if((P=i.offset-P)>i.whave&&i.sane){t.msg="invalid distance too far back",i.mode=30;break}T=P>i.wnext?(P-=i.wnext,i.wsize-P):i.wnext-P,P>i.length&&(P=i.length),E=i.window}else E=f,T=w-i.offset,P=i.length;for(_<P&&(P=_),_-=P,i.length-=P;f[w++]=E[T++],--P;);0===i.length&&(i.mode=21);break;case 26:if(0===_)break t;f[w++]=i.length,_--,i.mode=21;break;case 27:if(i.wrap){for(;v<32;){if(0===y)break t;y--,b|=p[g++]<<v,v+=8}if(C-=_,t.total_out+=C,i.total+=C,C&&(t.adler=i.check=i.flags?r(i.check,f,C,w-C):s(i.check,f,C,w-C)),C=_,(i.flags?b:m(b))!==i.check){t.msg="incorrect data check",i.mode=30;break}v=b=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;v<32;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(b!==(4294967295&i.total)){t.msg="incorrect length check",i.mode=30;break}v=b=0}i.mode=29;case 29:N=1;break t;case 30:N=-3;break t;case 31:return-4;default:return u}return t.next_out=w,t.avail_out=_,t.next_in=g,t.avail_in=y,i.hold=b,i.bits=v,(i.wsize||C!==t.avail_out&&i.mode<30&&(i.mode<27||4!==e))&&A(t,t.output,t.next_out,C-t.avail_out)?(i.mode=31,-4):(x-=t.avail_in,C-=t.avail_out,t.total_in+=x,t.total_out+=C,i.total+=C,i.wrap&&C&&(t.adler=i.check=i.flags?r(i.check,f,C,t.next_out-C):s(i.check,f,C,t.next_out-C)),t.data_type=i.bits+(i.last?64:0)+(12===i.mode?128:0)+(20===i.mode||15===i.mode?256:0),(0==x&&0===C||4===e)&&N===h&&(N=-5),N)},i.inflateEnd=function(t){if(!t||!t.state)return u;var e=t.state;return e.window&&(e.window=null),t.state=null,h},i.inflateGetHeader=function(t,e){var i;return t&&t.state&&2&(i=t.state).wrap?((i.head=e).done=!1,h):u},i.inflateSetDictionary=function(t,e){var i,n=e.length;return t&&t.state?0!==(i=t.state).wrap&&11!==i.mode?u:11===i.mode&&s(1,e,n,0)!==i.check?-3:A(t,e,n,n)?(i.mode=31,-4):(i.havedict=1,h):u},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(t,e,i){var n=t("../utils/common"),s=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],r=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],o=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];e.exports=function(t,e,i,l,c,h,u,d){var p,f,m,g,w,y,_,b,v,x=d.bits,C=0,S=0,A=0,P=0,T=0,E=0,M=0,I=0,z=0,D=0,k=null,B=0,O=new n.Buf16(16),N=new n.Buf16(16),V=null,L=0;for(C=0;C<=15;C++)O[C]=0;for(S=0;S<l;S++)O[e[i+S]]++;for(T=x,P=15;1<=P&&0===O[P];P--);if(P<T&&(T=P),0===P)return c[h++]=20971520,c[h++]=20971520,d.bits=1,0;for(A=1;A<P&&0===O[A];A++);for(T<A&&(T=A),C=I=1;C<=15;C++)if(I<<=1,(I-=O[C])<0)return-1;if(0<I&&(0===t||1!==P))return-1;for(N[1]=0,C=1;C<15;C++)N[C+1]=N[C]+O[C];for(S=0;S<l;S++)0!==e[i+S]&&(u[N[e[i+S]]++]=S);if(y=0===t?(k=V=u,19):1===t?(k=s,B-=257,V=r,L-=257,256):(k=o,V=a,-1),C=A,w=h,M=S=D=0,m=-1,g=(z=1<<(E=T))-1,1===t&&852<z||2===t&&592<z)return 1;for(;;){for(_=C-M,v=u[S]<y?(b=0,u[S]):u[S]>y?(b=V[L+u[S]],k[B+u[S]]):(b=96,0),p=1<<C-M,A=f=1<<E;c[w+(D>>M)+(f-=p)]=_<<24|b<<16|v,0!==f;);for(p=1<<C-1;D&p;)p>>=1;if(0!==p?(D&=p-1,D+=p):D=0,S++,0==--O[C]){if(C===P)break;C=e[i+u[S]]}if(T<C&&(D&g)!==m){for(0===M&&(M=T),w+=A,I=1<<(E=C-M);E+M<P&&!((I-=O[E+M])<=0);)E++,I<<=1;if(z+=1<<E,1===t&&852<z||2===t&&592<z)return 1;c[m=D&g]=T<<24|E<<16|w-h}}return 0!==D&&(c[w+D]=C-M<<24|64<<16),d.bits=T,0}},{"../utils/common":41}],51:[function(t,e,i){e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(t,e,i){var n=t("../utils/common"),s=0,r=1;function o(t){for(var e=t.length;0<=--e;)t[e]=0}var a=0,l=29,c=256,h=c+1+l,u=30,d=19,p=2*h+1,f=15,m=16,g=7,w=256,y=16,_=17,b=18,v=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],x=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],C=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],A=new Array(2*(h+2));o(A);var P=new Array(2*u);o(P);var T=new Array(512);o(T);var E=new Array(256);o(E);var M=new Array(l);o(M);var I,z,D,k=new Array(u);function B(t,e,i,n,s){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=n,this.max_length=s,this.has_stree=t&&t.length}function O(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function N(t){return t<256?T[t]:T[256+(t>>>7)]}function V(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function L(t,e,i){t.bi_valid>m-i?(t.bi_buf|=e<<t.bi_valid&65535,V(t,t.bi_buf),t.bi_buf=e>>m-t.bi_valid,t.bi_valid+=i-m):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)}function F(t,e,i){L(t,i[2*e],i[2*e+1])}function R(t,e){for(var i=0;i|=1&t,t>>>=1,i<<=1,0<--e;);return i>>>1}function U(t,e,i){var n,s,r=new Array(f+1),o=0;for(n=1;n<=f;n++)r[n]=o=o+i[n-1]<<1;for(s=0;s<=e;s++){var a=t[2*s+1];0!==a&&(t[2*s]=R(r[a]++,a))}}function j(t){var e;for(e=0;e<h;e++)t.dyn_ltree[2*e]=0;for(e=0;e<u;e++)t.dyn_dtree[2*e]=0;for(e=0;e<d;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*w]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function $(t){8<t.bi_valid?V(t,t.bi_buf):0<t.bi_valid&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function W(t,e,i,n){var s=2*e,r=2*i;return t[s]<t[r]||t[s]===t[r]&&n[e]<=n[i]}function G(t,e,i){for(var n=t.heap[i],s=i<<1;s<=t.heap_len&&(s<t.heap_len&&W(e,t.heap[s+1],t.heap[s],t.depth)&&s++,!W(e,n,t.heap[s],t.depth));)t.heap[i]=t.heap[s],i=s,s<<=1;t.heap[i]=n}function H(t,e,i){var n,s,r,o,a=0;if(0!==t.last_lit)for(;n=t.pending_buf[t.d_buf+2*a]<<8|t.pending_buf[t.d_buf+2*a+1],s=t.pending_buf[t.l_buf+a],a++,0===n?F(t,s,e):(F(t,(r=E[s])+c+1,e),0!==(o=v[r])&&L(t,s-=M[r],o),F(t,r=N(--n),i),0!==(o=x[r])&&L(t,n-=k[r],o)),a<t.last_lit;);F(t,w,e)}function Z(t,e){var i,n,s,r=e.dyn_tree,o=e.stat_desc.static_tree,a=e.stat_desc.has_stree,l=e.stat_desc.elems,c=-1;for(t.heap_len=0,t.heap_max=p,i=0;i<l;i++)0!==r[2*i]?(t.heap[++t.heap_len]=c=i,t.depth[i]=0):r[2*i+1]=0;for(;t.heap_len<2;)r[2*(s=t.heap[++t.heap_len]=c<2?++c:0)]=1,t.depth[s]=0,t.opt_len--,a&&(t.static_len-=o[2*s+1]);for(e.max_code=c,i=t.heap_len>>1;1<=i;i--)G(t,r,i);for(s=l;i=t.heap[1],t.heap[1]=t.heap[t.heap_len--],G(t,r,1),n=t.heap[1],t.heap[--t.heap_max]=i,t.heap[--t.heap_max]=n,r[2*s]=r[2*i]+r[2*n],t.depth[s]=(t.depth[i]>=t.depth[n]?t.depth[i]:t.depth[n])+1,r[2*i+1]=r[2*n+1]=s,t.heap[1]=s++,G(t,r,1),2<=t.heap_len;);t.heap[--t.heap_max]=t.heap[1],function(t,e){var i,n,s,r,o,a,l=e.dyn_tree,c=e.max_code,h=e.stat_desc.static_tree,u=e.stat_desc.has_stree,d=e.stat_desc.extra_bits,m=e.stat_desc.extra_base,g=e.stat_desc.max_length,w=0;for(r=0;r<=f;r++)t.bl_count[r]=0;for(l[2*t.heap[t.heap_max]+1]=0,i=t.heap_max+1;i<p;i++)g<(r=l[2*l[2*(n=t.heap[i])+1]+1]+1)&&(r=g,w++),l[2*n+1]=r,c<n||(t.bl_count[r]++,o=0,m<=n&&(o=d[n-m]),a=l[2*n],t.opt_len+=a*(r+o),u&&(t.static_len+=a*(h[2*n+1]+o)));if(0!==w){do{for(r=g-1;0===t.bl_count[r];)r--;t.bl_count[r]--,t.bl_count[r+1]+=2,t.bl_count[g]--,w-=2}while(0<w);for(r=g;0!==r;r--)for(n=t.bl_count[r];0!==n;)c<(s=t.heap[--i])||(l[2*s+1]!==r&&(t.opt_len+=(r-l[2*s+1])*l[2*s],l[2*s+1]=r),n--)}}(t,e),U(r,c,t.bl_count)}function q(t,e,i){var n,s,r=-1,o=e[1],a=0,l=7,c=4;for(0===o&&(l=138,c=3),e[2*(i+1)+1]=65535,n=0;n<=i;n++)s=o,o=e[2*(n+1)+1],++a<l&&s===o||(a<c?t.bl_tree[2*s]+=a:0!==s?(s!==r&&t.bl_tree[2*s]++,t.bl_tree[2*y]++):a<=10?t.bl_tree[2*_]++:t.bl_tree[2*b]++,r=s,c=(a=0)===o?(l=138,3):s===o?(l=6,3):(l=7,4))}function Y(t,e,i){var n,s,r=-1,o=e[1],a=0,l=7,c=4;for(0===o&&(l=138,c=3),n=0;n<=i;n++)if(s=o,o=e[2*(n+1)+1],!(++a<l&&s===o)){if(a<c)for(;F(t,s,t.bl_tree),0!=--a;);else 0!==s?(s!==r&&(F(t,s,t.bl_tree),a--),F(t,y,t.bl_tree),L(t,a-3,2)):a<=10?(F(t,_,t.bl_tree),L(t,a-3,3)):(F(t,b,t.bl_tree),L(t,a-11,7));r=s,c=(a=0)===o?(l=138,3):s===o?(l=6,3):(l=7,4)}}o(k);var X=!1;function K(t,e,i,s){var r,o,l;L(t,(a<<1)+(s?1:0),3),o=e,l=i,$(r=t),V(r,l),V(r,~l),n.arraySet(r.pending_buf,r.window,o,l,r.pending),r.pending+=l}i._tr_init=function(t){X||(function(){var t,e,i,n,s,r=new Array(f+1);for(n=i=0;n<l-1;n++)for(M[n]=i,t=0;t<1<<v[n];t++)E[i++]=n;for(E[i-1]=n,n=s=0;n<16;n++)for(k[n]=s,t=0;t<1<<x[n];t++)T[s++]=n;for(s>>=7;n<u;n++)for(k[n]=s<<7,t=0;t<1<<x[n]-7;t++)T[256+s++]=n;for(e=0;e<=f;e++)r[e]=0;for(t=0;t<=143;)A[2*t+1]=8,t++,r[8]++;for(;t<=255;)A[2*t+1]=9,t++,r[9]++;for(;t<=279;)A[2*t+1]=7,t++,r[7]++;for(;t<=287;)A[2*t+1]=8,t++,r[8]++;for(U(A,h+1,r),t=0;t<u;t++)P[2*t+1]=5,P[2*t]=R(t,5);I=new B(A,v,c+1,h,f),z=new B(P,x,0,u,f),D=new B(new Array(0),C,0,d,g)}(),X=!0),t.l_desc=new O(t.dyn_ltree,I),t.d_desc=new O(t.dyn_dtree,z),t.bl_desc=new O(t.bl_tree,D),t.bi_buf=0,t.bi_valid=0,j(t)},i._tr_stored_block=K,i._tr_flush_block=function(t,e,i,n){var o,a,l=0;0<t.level?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return s;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return r;for(e=32;e<c;e++)if(0!==t.dyn_ltree[2*e])return r;return s}(t)),Z(t,t.l_desc),Z(t,t.d_desc),l=function(t){var e;for(q(t,t.dyn_ltree,t.l_desc.max_code),q(t,t.dyn_dtree,t.d_desc.max_code),Z(t,t.bl_desc),e=d-1;3<=e&&0===t.bl_tree[2*S[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),o=t.opt_len+3+7>>>3,(a=t.static_len+3+7>>>3)<=o&&(o=a)):o=a=i+5,i+4<=o&&-1!==e?K(t,e,i,n):4===t.strategy||a===o?(L(t,2+(n?1:0),3),H(t,A,P)):(L(t,4+(n?1:0),3),function(t,e,i,n){var s;for(L(t,e-257,5),L(t,i-1,5),L(t,n-4,4),s=0;s<n;s++)L(t,t.bl_tree[2*S[s]+1],3);Y(t,t.dyn_ltree,e-1),Y(t,t.dyn_dtree,i-1)}(t,t.l_desc.max_code+1,t.d_desc.max_code+1,l+1),H(t,t.dyn_ltree,t.dyn_dtree)),j(t),n&&$(t)},i._tr_tally=function(t,e,i){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&i,t.last_lit++,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(E[i]+c+1)]++,t.dyn_dtree[2*N(e)]++),t.last_lit===t.lit_bufsize-1},i._tr_align=function(t){var e;L(t,2,3),F(t,w,A),16===(e=t).bi_valid?(V(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}},{"../utils/common":41}],53:[function(t,e,i){e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(t,e,i){(function(t){!function(t,e){if(!t.setImmediate){var i,n,s,r,o=1,a={},l=!1,c=t.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(t);h=h&&h.setTimeout?h:t,i="[object process]"==={}.toString.call(t.process)?function(t){process.nextTick((function(){d(t)}))}:function(){if(t.postMessage&&!t.importScripts){var e=!0,i=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=i,e}}()?(r="setImmediate$"+Math.random()+"$",t.addEventListener?t.addEventListener("message",p,!1):t.attachEvent("onmessage",p),function(e){t.postMessage(r+e,"*")}):t.MessageChannel?((s=new MessageChannel).port1.onmessage=function(t){d(t.data)},function(t){s.port2.postMessage(t)}):c&&"onreadystatechange"in c.createElement("script")?(n=c.documentElement,function(t){var e=c.createElement("script");e.onreadystatechange=function(){d(t),e.onreadystatechange=null,n.removeChild(e),e=null},n.appendChild(e)}):function(t){setTimeout(d,0,t)},h.setImmediate=function(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),n=0;n<e.length;n++)e[n]=arguments[n+1];var s={callback:t,args:e};return a[o]=s,i(o),o++},h.clearImmediate=u}function u(t){delete a[t]}function d(t){if(l)setTimeout(d,0,t);else{var i=a[t];if(i){l=!0;try{!function(t){var i=t.callback,n=t.args;switch(n.length){case 0:i();break;case 1:i(n[0]);break;case 2:i(n[0],n[1]);break;case 3:i(n[0],n[1],n[2]);break;default:i.apply(e,n)}}(i)}finally{u(t),l=!1}}}}function p(e){e.source===t&&"string"==typeof e.data&&0===e.data.indexOf(r)&&d(+e.data.slice(r.length))}}("undefined"==typeof self?void 0===t?this:t:self)}).call(this,void 0!==Na?Na:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10));class Ua{constructor(t,i){e(this,"date",new Date),e(this,"author"),e(this,"guid",_t.create()),e(this,"viewpoint"),e(this,"modifiedAuthor"),e(this,"modifiedDate"),e(this,"topic"),e(this,"_components"),e(this,"_comment",""),this._components=t,this._comment=i;const n=this._components.get(Za);this.author=n.config.author}set comment(t){var e;const i=this._components.get(Za);this._comment=t,this.modifiedDate=new Date,this.modifiedAuthor=i.config.author,null==(e=this.topic)||e.comments.set(this.guid,this)}get comment(){return this._comment}toJSON(){var t,e;const i={guid:this.guid,date:this.date.toISOString(),author:this.author,comment:this.comment,topic_guid:null==(t=this.topic)?void 0:t.guid,viewpoint_guid:this.viewpoint,modified_date:null==(e=this.modifiedDate)?void 0:e.toISOString(),modified_author:this.modifiedAuthor};for(const[t,e]of Object.entries(i))void 0===e&&delete i[t];return i}}const ja=class t{constructor(i){e(this,"guid",_t.create()),e(this,"title",t.default.title),e(this,"creationDate",new Date),e(this,"creationAuthor",""),e(this,"viewpoints",new r),e(this,"relatedTopics",new r),e(this,"comments",new n),e(this,"documentReferences",new r),e(this,"customData",{}),e(this,"description"),e(this,"serverAssignedId"),e(this,"dueDate"),e(this,"modifiedAuthor"),e(this,"modifiedDate"),e(this,"index"),e(this,"_type",t.default.type),e(this,"_status",t.default.status),e(this,"_priority",t.default.priority),e(this,"_stage",t.default.stage),e(this,"_assignedTo",t.default.assignedTo),e(this,"_labels",t.default.labels??new Set),e(this,"_components"),this._components=i;const s=i.get(Za);this.creationAuthor=s.config.author,this.relatedTopics.guard=t=>t!==this.guid}set type(t){const e=this._components.get(Za),{strict:i,types:n}=e.config;(!i||n.has(t))&&(this._type=t)}get type(){return this._type}set status(t){const e=this._components.get(Za),{strict:i,statuses:n}=e.config;(!i||n.has(t))&&(this._status=t)}get status(){return this._status}set priority(t){const e=this._components.get(Za);if(t){const{strict:i,priorities:n}=e.config;if(!(!i||n.has(t)))return;this._priority=t}else this._priority=t}get priority(){return this._priority}set stage(t){const e=this._components.get(Za);if(t){const{strict:i,stages:n}=e.config;if(!(!i||n.has(t)))return;this._stage=t}else this._stage=t}get stage(){return this._stage}set assignedTo(t){const e=this._components.get(Za);if(t){const{strict:i,users:n}=e.config;if(!(!i||n.has(t)))return;this._assignedTo=t}else this._assignedTo=t}get assignedTo(){return this._assignedTo}set labels(t){const e=this._components.get(Za),{strict:i,labels:n}=e.config;if(i){const e=new Set;for(const s of t){(!i||n.has(s))&&e.add(s)}this._labels=e}else this._labels=t}get labels(){return this._labels}get _managerVersion(){return this._components.get(Za).config.version}set(t){const e=t,i=this;for(const n in t){if("guid"===n)continue;const t=e[n];n in this&&(i[n]=t)}return this._components.get(Za).list.set(this.guid,this),this}createComment(t,e){const i=new Ua(this._components,t);return i.viewpoint=e,i.topic=this,this.comments.set(i.guid,i),i}createLabelTags(){const t=[...this.labels];if(this._components.get(Za).config.exportCustomDataAsLabels)for(const e in this.customData){const i=this.customData[e];"string"==typeof i&&t.push(i)}return t}createCommentTags(){return[...this.comments.values()].map((t=>{var e;return{$Guid:t.guid,Date:t.date.toISOString(),Author:t.author,Comment:t.comment,ModifiedAuthor:t.modifiedAuthor,ModifiedDate:null==(e=t.modifiedDate)?void 0:e.toISOString(),Viewpoint:t.viewpoint?{$Guid:t.viewpoint}:void 0}}))}createViewpointTags(){const t=this._components.get(el);return[...this.viewpoints].map((e=>t.list.get(e))).filter((t=>t)).map((e=>{const i={$Guid:e.guid,Viewpoint:`${e.title??e.guid}.bcfv`};if(t.snapshots.get(e.snapshot)){const n=t.getSnapshotExtension(e.snapshot);i.Snapshot=`${e.snapshot}.${n}`}return i}))}createRelatedTopicTags(){return[...this.relatedTopics].map((t=>({$Guid:t})))}createDocumentReferencesTag(t=this._managerVersion){const e=[];if("3"!==t&&"2.1"!==t)return e;const i=this._components.get(Za);for(const n of this.documentReferences){const s=i.documents.get(n);if(!s)continue;let r={$Guid:_t.create(),Description:s.description};"2.1"===t&&(r={...r,$isExternal:"external"===s.type||void 0,ReferencedDocument:"external"===s.type?s.url:`../${s.fileName}`}),"3"===t&&(r={...r,DocumentGuid:"internal"===s.type?n:void 0,Url:"external"===s.type?s.url:void 0}),Object.keys(r).length>0&&e.push(r)}return e}toJSON(){var t,e;const i={guid:this.guid,server_assigned_id:this.serverAssignedId,topic_type:this.type,topic_status:this.status,title:this.title,priority:this.priority,index:this.index,labels:[...this.labels],creation_date:this.creationDate.toISOString(),creation_author:this.creationAuthor,modified_date:null==(t=this.modifiedDate)?void 0:t.toISOString(),modified_author:this.modifiedAuthor,assigned_to:this.assignedTo,stage:this.stage,description:this.description,due_date:null==(e=this.dueDate)?void 0:e.toISOString(),comments:[...this.comments].map((([t,e])=>e.toJSON())),relatedTopics:[...this.relatedTopics].map((t=>({related_topic_guid:t})))},n=this._components.get(el);for(const t of this.viewpoints){const e=n.list.get(t);e&&(i.viewpoints||(i.viewpoints=[]),i.viewpoints.push(e.toJSON()))}const s=this._components.get(Za);for(const t of this.documentReferences){const e=s.documents.get(t);e&&(i.document_references||(i.document_references=[]),"external"===e.type?i.document_references.push({guid:_t.create(),description:e.description,url:e.url}):i.document_references.push({guid:_t.create(),description:e.description,document_guid:t}))}for(const[t,e]of Object.entries(i))(void 0===e||Array.isArray(e)&&0===e.length)&&delete i[t];return i}serialize(){var t,e;const i=this._managerVersion,n={$Guid:this.guid,$TopicType:this.type,$TopicStatus:this.status,$ServerAssignedId:this.serverAssignedId,Title:this.title,CreationAuthor:this.creationAuthor,CreationDate:this.creationDate.toISOString(),Priority:this.priority,Index:"2.1"===i?this.index:void 0,ModifiedDate:null==(t=this.modifiedDate)?void 0:t.toISOString(),ModifiedAuthor:this.modifiedAuthor,DueDate:null==(e=this.dueDate)?void 0:e.toISOString(),AssignedTo:this.assignedTo,Description:this.description,Stage:this.stage,DocumentReferences:"3"===i?{DocumentReference:this.createDocumentReferencesTag(i)}:void 0,RelatedTopics:"3"===i?{RelatedTopic:this.createRelatedTopicTags()}:void 0,RelatedTopic:"2.1"===i?this.createRelatedTopicTags():void 0,Labels:"3"===i?{Label:this.createLabelTags()}:void 0,Viewpoints:"3"===i?{ViewPoint:this.createViewpointTags()}:void 0,Comments:"3"===i?{Comment:this.createCommentTags()}:void 0};"2.1"===i&&(n.Labels=this.createLabelTags(),n.DocumentReference=this.createDocumentReferencesTag(i));const s={Markup:{Topic:n}};return"2.1"===i&&(s.Markup.Viewpoints=this.createViewpointTags(),s.Markup.Comment=this.createCommentTags()),`<?xml version="1.0" encoding="UTF-8"?>\n ${ri.builder.build(s)}`}};e(ja,"default",{title:"BCF Topic",type:"Issue",status:"Active"});let $a=ja;const Wa=(t,e)=>{if(""===e.trim())return;const i=Za.xmlParser.parse(e).Extensions;if(!i)return;const{Priorities:n,TopicStatuses:s,TopicTypes:r,Users:o}=i;if(n&&n.Priority){const e=Array.isArray(n.Priority)?n.Priority:[n.Priority];for(const i of e)t.config.priorities.add(i)}if(s&&s.TopicStatus){const e=Array.isArray(s.TopicStatus)?s.TopicStatus:[s.TopicStatus];for(const i of e)t.config.statuses.add(i)}if(r&&r.TopicType){const e=Array.isArray(r.TopicType)?r.TopicType:[r.TopicType];for(const i of e)t.config.types.add(i)}if(o&&o.User){const e=Array.isArray(o.User)?o.User:[o.User];for(const i of e)t.config.users.add(i)}};class Ga extends ui{constructor(){super(...arguments),e(this,"_config",{version:{type:"Select",options:new Set(["2.1","3"]),multiple:!1,value:""},author:{type:"Text",value:""},types:{type:"TextSet",value:new Set},statuses:{type:"TextSet",value:new Set},priorities:{type:"TextSet",value:new Set},labels:{type:"TextSet",value:new Set},stages:{type:"TextSet",value:new Set},users:{type:"TextSet",value:new Set},includeSelectionTag:{type:"Boolean",value:!1},updateExtensionsOnImport:{type:"Boolean",value:!1},strict:{type:"Boolean",value:!1},includeAllExtensionsOnExport:{type:"Boolean",value:!1},fallbackVersionOnImport:{type:"Select",multiple:!1,options:new Set(["2.1","3"]),value:""},ignoreIncompleteTopicsOnImport:{type:"Boolean",value:!1},exportCustomDataAsLabels:{type:"Boolean",value:!1}})}get version(){return this._config.version.value}set version(t){this._config.version.value=t}get author(){return this._config.author.value}set author(t){this._config.author.value=t}get types(){return this._config.types.value}set types(t){this._config.types.value=t}get statuses(){return this._config.statuses.value}set statuses(t){this._config.statuses.value=t}get priorities(){return this._config.priorities.value}set priorities(t){this._config.priorities.value=t}get labels(){return this._config.labels.value}set labels(t){this._config.labels.value=t}get stages(){return this._config.stages.value}set stages(t){this._config.stages.value=t}get users(){return this._config.users.value}set users(t){this._config.users.value=t}get includeSelectionTag(){return this._config.includeSelectionTag.value}set includeSelectionTag(t){this._config.includeSelectionTag.value=t}get updateExtensionsOnImport(){return this._config.updateExtensionsOnImport.value}set updateExtensionsOnImport(t){this._config.updateExtensionsOnImport.value=t}get strict(){return this._config.strict.value}set strict(t){this._config.strict.value=t}get includeAllExtensionsOnExport(){return this._config.includeAllExtensionsOnExport.value}set includeAllExtensionsOnExport(t){this._config.includeAllExtensionsOnExport.value=t}get fallbackVersionOnImport(){return this._config.fallbackVersionOnImport.value}set fallbackVersionOnImport(t){this._config.fallbackVersionOnImport.value=t}get ignoreIncompleteTopicsOnImport(){return this._config.ignoreIncompleteTopicsOnImport.value}set ignoreIncompleteTopicsOnImport(t){this._config.ignoreIncompleteTopicsOnImport.value=t}get exportCustomDataAsLabels(){return this._config.exportCustomDataAsLabels.value}set exportCustomDataAsLabels(t){this._config.exportCustomDataAsLabels.value=t}}const Ha=class t extends ht{constructor(){super(...arguments),e(this,"enabled",!1),e(this,"_defaultConfig",{author:"jhon.doe@example.com",version:"2.1",types:new Set(["Clash","Failure","Fault","Inquiry","Issue","Remark","Request"]),statuses:new Set(["Active","In Progress","Done","In Review","Closed"]),priorities:new Set(["On hold","Minor","Normal","Major","Critical"]),labels:new Set,stages:new Set,users:new Set,includeSelectionTag:!1,updateExtensionsOnImport:!0,strict:!1,includeAllExtensionsOnExport:!0,fallbackVersionOnImport:"2.1",ignoreIncompleteTopicsOnImport:!1,exportCustomDataAsLabels:!1}),e(this,"config",new Ga(this,this.components,"BCF Topics",t.uuid)),e(this,"list",new n),e(this,"documents",new n),e(this,"onSetup",new at),e(this,"isSetup",!1),e(this,"onBCFImported",new at),e(this,"onDisposed",new at)}setup(t){if(this.isSetup)return;const e={...this._defaultConfig,...t};this.config.version=e.version,this.config.author=e.author,this.config.types=e.types,this.config.statuses=e.statuses,this.config.priorities=e.priorities,this.config.labels=e.labels,this.config.stages=e.stages,this.config.users=e.users,this.config.includeSelectionTag=e.includeSelectionTag,this.config.updateExtensionsOnImport=e.updateExtensionsOnImport,this.config.strict=e.strict,this.config.includeAllExtensionsOnExport=e.includeAllExtensionsOnExport,this.config.fallbackVersionOnImport=e.fallbackVersionOnImport||"",this.config.ignoreIncompleteTopicsOnImport=e.ignoreIncompleteTopicsOnImport,this.isSetup=!0,this.enabled=!0,this.onSetup.trigger()}create(t){const e=new $a(this.components);return t?(e.guid=t.guid??e.guid,e.set(t)):this.list.set(e.guid,e),e}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}get usedTypes(){const t=[...this.list].map((([t,e])=>e.type));return new Set(t)}get usedStatuses(){const t=[...this.list].map((([t,e])=>e.status));return new Set(t)}get usedPriorities(){const t=[...this.list].map((([t,e])=>e.priority)).filter((t=>t));return new Set(t)}get usedStages(){const t=[...this.list].map((([t,e])=>e.stage)).filter((t=>t));return new Set(t)}get usedUsers(){const t=[];for(const[e,i]of this.list){t.push(i.creationAuthor),i.assignedTo&&t.push(i.assignedTo),i.modifiedAuthor&&t.push(i.modifiedAuthor);for(const[e,n]of i.comments)t.push(n.author),n.modifiedAuthor&&t.push(n.modifiedAuthor)}return new Set(t)}get usedLabels(){const t=[];for(const[e,i]of this.list)t.push(...i.labels);return new Set(t)}updateExtensions(){for(const[t,e]of this.list){for(const t of e.labels)this.config.labels.add(t);this.config.types.add(e.type),e.priority&&this.config.priorities.add(e.priority),e.stage&&this.config.stages.add(e.stage),this.config.statuses.add(e.status),this.config.users.add(e.creationAuthor),e.assignedTo&&this.config.users.add(e.assignedTo),e.modifiedAuthor&&this.config.users.add(e.modifiedAuthor);for(const[t,i]of e.comments)this.config.users.add(i.author),i.modifiedAuthor&&this.config.users.add(i.modifiedAuthor)}}updateViewpointReferences(){const t=this.components.get(el);for(const[e,i]of this.list)for(const e of i.viewpoints){t.list.has(e)||i.viewpoints.delete(e)}}async export(t=this.list.values()){const e=new Ra;e.file("bcf.version",`<?xml version="1.0" encoding="UTF-8"?>\n <Version VersionId="${this.config.version}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/release_3_0/Schemas/version.xsd"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n </Version>`);for(const[t,i]of this.documents.entries())"external"!==i.type&&e.file("2.1"===this.config.version?i.fileName:`documents/${t}`,i.data);if("3"===this.config.version){const t=[];for(const[e,i]of this.documents.entries()){const{type:n,description:s}=i;"external"!==n&&t.push(`<Document Guid="${e}">\n <Filename>${i.fileName}</Filename>\n ${s?`<Description>${s}</Description>`:""}\n </Document>`)}t.length>0&&e.file("documents.xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n <DocumentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="documents.xsd">\n <Documents>\n ${t.join("\n")}\n </Documents>\n </DocumentInfo>`)}e.file("bcf.extensions",this.serializeExtensions());const i=this.components.get(el);for(const n of t){const t=e.folder(n.guid);t.file("markup.bcf",n.serialize());for(const e of n.viewpoints){const n=i.list.get(e);if(!n)continue;const s=n.title??n.guid;t.file(`${s}.bcfv`,await n.serialize());const r=i.snapshots.get(n.snapshot);if(!r)continue;const o=r?n.snapshot:n.guid,a=i.getSnapshotExtension(n.snapshot);t.file(`${o}.${a}`,r,{binary:!0})}}return await e.generateAsync({type:"blob"})}serializeExtensions(){const t=[...this.config.types].map((t=>`<TopicType>${t}</TopicType>`)).join("\n"),e=[...this.config.statuses].map((t=>`<TopicStatus>${t}</TopicStatus>`)).join("\n"),i=[...this.config.priorities].map((t=>`<Priority>${t}</Priority>`)).join("\n"),n=[...this.config.labels].map((t=>`<TopicLabel>${t}</TopicLabel>`)).join("\n"),s=[...this.config.stages].map((t=>`<Stage>${t}</Stage>`)).join("\n"),r=[...this.config.users].map((t=>`<User>${t}</User>`)).join("\n");return`\n <?xml version="1.0" encoding="UTF-8"?>\n <Extensions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-schema-location.xsd">\n ${0!==t.length?`<TopicTypes>\n${t}\n</TopicTypes>`:""}\n ${0!==e.length?`<TopicStatuses>\n${e}\n</TopicStatuses>`:""}\n ${0!==i.length?`<Priorities>\n${i}\n</Priorities>`:""}\n ${0!==n.length?`<TopicLabels>\n${n}\n</TopicLabels>`:""}\n ${0!==s.length?`<Stages>\n${s}\n</Stages>`:""}\n ${0!==r.length?`<Users>\n${r}\n</Users>`:""}\n </Extensions>\n `}processMarkupComment(t){const{Guid:e,Date:i,Author:n,Comment:s,Viewpoint:r}=t;if(!(e&&i&&n&&Ua))return null;const o=new Ua(this.components,s??"");return o.guid=e,o.date=new Date(i),o.author=n,o.viewpoint=null==r?void 0:r.Guid,o.modifiedAuthor=t.ModifiedAuthor,o.modifiedDate=t.ModifiedDate?new Date(t.ModifiedDate):void 0,o}getMarkupComments(t,e){var i;let n;if("2.1"===e&&(n=t.Comment),"3"===e&&(n=null==(i=t.Topic.Comments)?void 0:i.Comment),!n)return[];n=Array.isArray(n)?n:[n];const s=n.map((t=>this.processMarkupComment(t))).filter((t=>t));return Array.isArray(s)?s:[s]}getMarkupLabels(t,e){var i;let n;if("2.1"===e&&(n=t.Topic.Labels),"3"===e&&(n=null==(i=t.Topic.Labels)?void 0:i.Label),!n)return[];return Array.isArray(n)?n:[n]}getMarkupViewpoints(t,e){var i;let n;return"2.1"===e&&(n=t.Viewpoints),"3"===e&&(n=null==(i=t.Topic.Viewpoints)?void 0:i.ViewPoint),n?(n=Array.isArray(n)?n:[n],n):[]}getMarkupRelatedTopics(t,e){var i;let n;if("2.1"===e&&(n=t.Topic.RelatedTopic),"3"===e&&(n=null==(i=t.Topic.RelatedTopics)?void 0:i.RelatedTopic),!n)return[];return(Array.isArray(n)?n:[n]).map((t=>t.Guid))}getMarkupDocumentReferences(t,e){var i;let n;if("2.1"===e&&(n=t.Topic.DocumentReference),"3"===e&&(n=null==(i=t.Topic.DocumentReferences)?void 0:i.DocumentReference),!n)return[];return Array.isArray(n)?n:[n]}async load(e){var i,n,s;const{fallbackVersionOnImport:r,ignoreIncompleteTopicsOnImport:a,updateExtensionsOnImport:l}=this.config,c=new Ra;await c.loadAsync(e);const h=Object.values(c.files);let u=r;const d=h.find((t=>t.name.endsWith(".version")));if(d){const e=await d.async("string"),i=t.xmlParser.parse(e).Version.VersionId;u=String(i)}if(!u||"2.1"!==u&&"3"!==u)throw new Error(`BCFTopics: ${u} is not supported.`);const p=h.find((t=>t.name.endsWith(".extensions")));if(l&&p){const t=await p.async("string");Wa(this,t)}const f=[],m=this.components.get(el),g=h.filter((t=>t.name.endsWith(".bcfv")));for(const e of g){const n=await e.async("string"),s=t.xmlParser.parse(n).VisualizationInfo;if(!s){console.warn("Missing VisualizationInfo in Viewpoint");continue}const r={},{Guid:a,ClippingPlanes:l,Components:c,OrthogonalCamera:h,PerspectiveCamera:d}=s;if(a&&(r.guid=a),c){const t={selection:[],coloring:[],visibility:{default_visibility:!1,exceptions:[],view_setup_hints:{spaces_visible:!1,space_boundaries_visible:!1,openings_visible:!1}}};r.components=t;const{Selection:e,Visibility:n}=c;if(e&&e.Component){const i=Array.isArray(e.Component)?e.Component:[e.Component];t.selection=i.map((t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null)).filter((t=>null!==t))}if(n&&"DefaultVisibility"in n&&(t.visibility.default_visibility=n.DefaultVisibility),n&&n.Exceptions&&"Component"in n.Exceptions){const{Component:e}=n.Exceptions,i=Array.isArray(e)?e:[e];t.visibility.exceptions=i.map((t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null)).filter((t=>null!==t))}let s;"2.1"===u&&(s=c.ViewSetupHints),"3"===u&&(s=null==(i=c.Visibility)?void 0:i.ViewSetupHints),s&&("OpeningsVisible"in s&&(t.visibility.view_setup_hints.openings_visible=s.OpeningsVisible),"SpacesVisible"in s&&(t.visibility.view_setup_hints.spaces_visible=s.SpacesVisible),"SpaceBoundariesVisible"in s&&(t.visibility.view_setup_hints.space_boundaries_visible=s.SpaceBoundariesVisible));const{Coloring:o}=c;if(o&&o.Color){const e=Array.isArray(o.Color)?o.Color:[o.Color];for(const i of e){const{Color:e,Component:n}=i;if(6!==e.length&&8!==e.length)continue;const s=6===e.length?e:e.slice(2),r=(Array.isArray(n)?n:[n]).map((t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null)).filter((t=>null!==t));t.coloring.push({color:s,components:r})}}}if(h||d){const t=s.PerspectiveCamera??s.OrthogonalCamera,{CameraViewPoint:e,CameraDirection:i}=t,n=new o.Vector3(Number(e.X),Number(e.Z),Number(-e.Y)),a=new o.Vector3(Number(i.X),Number(i.Z),Number(-i.Y)),l={camera_view_point:{x:n.x,y:n.y,z:n.z},camera_direction:{x:a.x,y:a.y,z:a.z},aspect_ratio:"AspectRatio"in t?t.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in t&&(r.orthogonal_camera={...l,view_to_world_scale:t.ViewToWorldScale}),"FieldOfView"in t&&(r.perspective_camera={...l,field_of_view:t.FieldOfView})}if(l){const t=(Array.isArray(l.ClippingPlane)?l.ClippingPlane:[l.ClippingPlane]).map((({Location:t,Direction:e})=>({location:{x:t.x,y:t.y,z:t.z},direction:{x:e.x,y:e.y,z:e.z}})));r.clipping_planes=t}const p=new Qa(this.components,r);f.push(p)}const w={},y=[],_=h.filter((t=>t.name.endsWith(".bcf")));for(const e of _){const i=await e.async("string"),r=t.xmlParser.parse(i).Markup,o=r.Topic,{Guid:l,TopicType:c,TopicStatus:d,Title:p,CreationDate:f,CreationAuthor:g}=o;if(a&&!(l&&c&&d&&p&&f&&g))continue;const _=new $a(this.components);_.guid=l??_.guid;const b=this.getMarkupRelatedTopics(r,u);w[_.guid]=new Set(b),_.type=c??_.type,_.status=d??_.status,_.title=p??_.title,_.creationDate=f?new Date(f):_.creationDate,_.creationAuthor=g??_.creationAuthor,_.serverAssignedId=o.ServerAssignedId,_.priority=o.Priority,_.index=o.Index,_.modifiedDate=o.ModifiedDate?new Date(o.ModifiedDate):void 0,_.modifiedAuthor=o.ModifiedAuthor,_.dueDate=o.DueDate?new Date(o.DueDate):void 0,_.assignedTo=o.AssignedTo,_.description=o.Description,_.stage=o.Stage;const v=this.getMarkupLabels(r,u);for(const t of v)_.labels.add(t);const x=this.getMarkupComments(r,u);for(const t of x)_.comments.set(t.guid,t);const C=this.getMarkupViewpoints(r,u);for(const t of C){if(!t||!t.Guid)continue;const e=m.list.get(t.Guid);if(!e)continue;_.viewpoints.add(e.guid);const i=`${_.guid}/${t.Snapshot}`,n=h.find((({name:t})=>t===i));if(n){const t=await n.async("arraybuffer"),i=new Uint8Array(t);m.snapshots.set(e.guid,i),e.snapshot=e.guid??null}}const S=this.getMarkupDocumentReferences(r,u),A=h.find((t=>"documents.xml"===t.name));let P=[];const T=await(null==A?void 0:A.async("string"));if(T){const t=null==(s=null==(n=ri.parser.parse(T).DocumentInfo)?void 0:n.Documents)?void 0:s.Document;P=Array.isArray(t)?t:[t]}for(const t of S){const{Description:e,DocumentGuid:i,Url:n,isExternal:s,ReferencedDocument:r}=t;if(i&&P.length>0){const t=P.find((({Guid:t})=>t===i)),e=h.find((t=>t.name.endsWith(i))),n=await(null==e?void 0:e.async("uint8array"));if(!t||!n)continue;const{Description:s,Filename:r}=t;this.documents.set(i,{type:"internal",fileName:r,description:s,data:n}),_.documentReferences.add(i)}if(n){const t=this.documents.add({type:"external",url:n,description:e});_.documentReferences.add(t)}if(r){let t=null;if(s)t=this.documents.add({type:"external",url:r,description:e});else{const i=r.split("/"),n=i[i.length-1],s=h.find((t=>t.name.endsWith(n))),o=await(null==s?void 0:s.async("uint8array"));if(!o)continue;t=this.documents.add({type:"internal",fileName:n,data:o,description:e})}_.documentReferences.add(t)}}this.list.set(_.guid,_),y.push(_)}for(const t in w){const e=this.list.get(t);if(!e)continue;const i=w[t];for(const t of i)e.relatedTopics.add(t)}return this.onBCFImported.trigger(y),{viewpoints:f,topics:y}}};e(Ha,"uuid","de977976-e4f6-4e4f-a01a-204727839802"),e(Ha,"xmlParser",new We({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let Za=Ha;class qa{constructor(t,i,n,s,r,a=5,l=!0){var c;if(e(this,"onDraggingStarted",new at),e(this,"onDraggingEnded",new at),e(this,"onDisposed",new at),e(this,"normal"),e(this,"origin"),e(this,"three",new o.Plane),e(this,"components"),e(this,"world"),e(this,"type","default"),e(this,"_title","Clipping Plane"),e(this,"_helper"),e(this,"_visible",!0),e(this,"_enabled",!0),e(this,"_controlsActive",!1),e(this,"_arrowBoundBox",new o.Mesh),e(this,"_planeMesh"),e(this,"_controls"),e(this,"_hiddenMaterial",new o.MeshBasicMaterial({visible:!1})),e(this,"_sizeMultiplier",5),e(this,"_autoScale",!0),e(this,"_visibilityBeforeDisabled",!0),e(this,"notifyManager",(()=>{const t=this.components.get(Ka),e=t.list.getKey(this);e&&t.list.set(e,this)})),e(this,"update",(()=>{this._enabled&&(this.three.setFromNormalAndCoplanarPoint(this.normal,this._helper.position),this.updateScale())})),e(this,"updateScale",(()=>{var t;if(!this.autoScale)return;const e=null==(t=this.world.camera)?void 0:t.three;if(!e)return;if(!(e instanceof o.PerspectiveCamera))return;const i=new o.Vector3;e.getWorldPosition(i);const n=i.distanceTo(this._helper.position)/7*this._sizeMultiplier;this._planeMesh.scale.set(n,n,n)})),e(this,"changeDrag",(t=>{this._visible=!t.value,this.preventCameraMovement(),this.notifyDraggingChanged(t)})),this.components=t,this.world=i,!i.renderer)throw new Error("The given world must have a renderer!");this.normal=s,this.origin=n,this._sizeMultiplier=a;const h=t.get(Ka);i.renderer.setPlane(!0,this.three,h.localClippingPlanes),this._planeMesh=qa.newPlaneMesh(a,r),this._helper=this.newHelper(),this._controls=this.newTransformControls(),this.three.setFromNormalAndCoplanarPoint(s,n),l&&this.toggleControls(!0),this.updateScale(),(null==(c=i.camera)?void 0:c.controls)&&i.camera.controls.addEventListener("update",this.updateScale)}set title(t){this._title=t,this.notifyManager()}get title(){return this._title}get autoScale(){return this._autoScale}set autoScale(t){this._autoScale=t,t&&this.updateScale()}get enabled(){return this._enabled}set enabled(t){if(this.world.isDisposing)return;if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");this._enabled=t,t?this.visible=this._visibilityBeforeDisabled:(this._visibilityBeforeDisabled=this.visible,this.visible=!1);const e=this.components.get(Ka);this.world.renderer.setPlane(t,this.three,e.localClippingPlanes),this.notifyManager()}get visible(){return this._visible}set visible(t){this._visible=t,this._controls.getHelper().visible=t,this._helper.visible=t,this.toggleControls(t),this.notifyManager()}get meshes(){return[this._planeMesh,this._arrowBoundBox]}get planeMaterial(){return this._planeMesh.material}set planeMaterial(t){this._planeMesh.material=t}get size(){return this._sizeMultiplier}set size(t){this._sizeMultiplier=t,this.autoScale?this.updateScale():this._planeMesh.scale.set(t,t,t)}get helper(){return this._helper}get controls(){return this._controls}setFromNormalAndCoplanarPoint(t,e){this.reset(),this.normal.equals(t)||(this.normal.copy(t),this._helper.lookAt(t)),this.origin.copy(e),this._helper.position.copy(e),this._helper.updateMatrix(),this.update()}dispose(){var t;this._enabled=!1,(null==(t=this.world.camera)?void 0:t.controls)&&this.world.camera.controls.removeEventListener("update",this.updateScale),this.onDraggingStarted.reset(),this.onDraggingEnded.reset(),this._helper.removeFromParent(),this.world.renderer&&this.world.renderer.setPlane(!1,this.three),this._arrowBoundBox.removeFromParent(),this._arrowBoundBox.geometry.dispose(),this._planeMesh.geometry.dispose(),this._controls.getHelper().removeFromParent(),this._controls.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}reset(){const t=new o.Vector3(1,0,0),e=new o.Vector3;this.normal.equals(t)||(this.normal.copy(t),this._helper.lookAt(t)),this.origin.copy(e),this._helper.position.copy(e),this._helper.updateMatrix()}toggleControls(t){if(t){if(this._controlsActive)return;this._controls.addEventListener("change",this.update),this._controls.addEventListener("dragging-changed",this.changeDrag)}else this._controls.removeEventListener("change",this.update),this._controls.removeEventListener("dragging-changed",this.changeDrag);this._controlsActive=t}newTransformControls(){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");const t=this.world.camera.three,e=this.world.renderer.three.domElement,i=new ot(t,e);return this.initializeControls(i),this.world.scene.three.add(i.getHelper()),i}initializeControls(t){t.attach(this._helper),t.showX=!1,t.showY=!1,t.setSpace("local"),this.createArrowBoundingBox(),t.getHelper().children[0].children[0].add(this._arrowBoundBox)}createArrowBoundingBox(){this._arrowBoundBox.geometry=new o.CylinderGeometry(.18,.18,1.2),this._arrowBoundBox.material=this._hiddenMaterial,this._arrowBoundBox.rotateX(Math.PI/2),this._arrowBoundBox.updateMatrix(),this._arrowBoundBox.geometry.applyMatrix4(this._arrowBoundBox.matrix)}notifyDraggingChanged(t){t.value?this.onDraggingStarted.trigger():this.onDraggingEnded.trigger()}preventCameraMovement(){this.world.camera.enabled=this._visible}newHelper(){const t=new o.Object3D;return t.lookAt(this.normal),t.position.copy(this.origin),this._planeMesh.position.z+=.01,t.add(this._planeMesh),this.world.scene.three.add(t),t}static newPlaneMesh(t,e){const i=new o.PlaneGeometry(1),n=new o.Mesh(i,e);return n.scale.set(t,t,t),n}}class Ya extends ui{constructor(){super(...arguments),e(this,"_config",{enabled:{value:!0,type:"Boolean"},visible:{value:!0,type:"Boolean"},color:{value:new o.Color,type:"Color"},opacity:{type:"Number",interpolable:!0,value:1,min:0,max:1},size:{type:"Number",interpolable:!0,value:2,min:0,max:100}})}get enabled(){return this._config.enabled.value}set enabled(t){this._config.enabled.value=t,this._component.enabled=t}get visible(){return this._config.visible.value}set visible(t){this._config.visible.value=t,this._component.visible=t}get color(){return this._config.color.value}set color(t){this._config.color.value=t,this._component.material.color.copy(t)}get opacity(){return this._config.opacity.value}set opacity(t){this._config.opacity.value=t,this._component.material.opacity=t}get size(){return this._config.size.value}set size(t){this._config.size.value=t,this._component.size=t}}const Xa=class t extends ht{constructor(n){super(n),e(this,"onSetup",new at),e(this,"onBeforeDrag",new at),e(this,"onAfterDrag",new at),e(this,"onBeforeCreate",new at),e(this,"onBeforeCancel",new at),e(this,"onAfterCancel",new at),e(this,"onBeforeDelete",new at),e(this,"onAfterCreate",new at),e(this,"onAfterDelete",new at),e(this,"onDisposed",new at),e(this,"isSetup",!1),e(this,"orthogonalY",!1),e(this,"toleranceOrthogonalY",.7),e(this,"autoScalePlanes",!0),e(this,"localClippingPlanes",!1),e(this,"Type",qa),e(this,"list",new i.DataMap),e(this,"config",new Ya(this,this.components,"Clipper",t.uuid)),e(this,"_defaultConfig",{color:new o.Color(12255487),opacity:.2,size:2}),e(this,"_material",new o.MeshBasicMaterial({color:12255487,side:o.DoubleSide,transparent:!0,opacity:.2})),e(this,"_size",5),e(this,"_enabled",!1),e(this,"_visible",!0),e(this,"onStateChanged",new at),this.components.add(t.uuid,this),this.setEvents()}get enabled(){return this._enabled}set enabled(t){this._enabled=t,this.onStateChanged.trigger(["enabled"])}get visible(){return this._visible}set visible(t){this._visible=t;for(const[e,i]of this.list)i.visible=t;this.onStateChanged.trigger(["visibility"])}get material(){return this._material}set material(t){this._material=t;for(const[e,i]of this.list)i.planeMaterial=t;this.onStateChanged.trigger(["material"])}get size(){return this._size}set size(t){this._size=t;for(const[e,i]of this.list)i.size=t;this.onStateChanged.trigger(["size"])}setEvents(){this.list.onBeforeDelete.add((({value:t})=>{if(!t.world.renderer)throw new Error("Renderer not found for this plane's world!");t.world.renderer.setPlane(!1,t.three),t.dispose(),this.updateMaterialsAndPlanes(),this.onAfterDelete.trigger(t)}));const t=this.components.get(fr);if(t.initialized)this.subscribeToFragmentMaterials();else{const e=()=>{t.onFragmentsLoaded.remove(e),this.subscribeToFragmentMaterials()};t.onFragmentsLoaded.add(e)}}subscribeToFragmentMaterials(){const t=this.components.get(fr);for(const[,e]of t.core.models.materials.list)this.applyClippingToFragmentMaterial(e);t.core.models.materials.list.onItemSet.add((({value:t})=>{this.applyClippingToFragmentMaterial(t)}))}applyClippingToFragmentMaterial(t){if(!this.localClippingPlanes)return;const e=this.components.get(Sa);for(const[,i]of e.list)if(i.renderer)return void(t.clippingPlanes=i.renderer.clippingPlanes)}dispose(){this._enabled=!1;this.components.get(pi).list.delete(this.config.uuid),this.list.clear(),this._material.dispose(),this.onBeforeCreate.reset(),this.onBeforeCancel.reset(),this.onBeforeDelete.reset(),this.onBeforeDrag.reset(),this.onAfterCreate.reset(),this.onAfterCancel.reset(),this.onAfterDelete.reset(),this.onAfterDrag.reset(),this.onDisposed.trigger(t.uuid),this.onDisposed.reset()}async create(t){const e=this.components.get(pa).get(t),i=await e.castRay();return i?this.createPlaneFromIntersection(t,i):null}createFromNormalAndCoplanarPoint(t,e,i){const n=this.newPlane(t,i,e);return this.updateMaterialsAndPlanes(),n}async delete(t,e){if(!e){const i=await this.pickPlane(t);if(!i)return;e=this.list.getKey(i)}e&&this.list.delete(e)}deleteAll(t){for(const[e,i]of this.list)t&&!t.has(i.type)||this.list.delete(e)}setup(t){const e={...this._defaultConfig,...t};this.config.color=e.color,this.config.opacity=e.opacity,this.config.size=e.size,this.isSetup=!0,this.onSetup.trigger()}pickPlane(t){const e=this.components.get(pa).get(t),i=this.getAllPlaneMeshes(),n=e.castRayToObjects(i);if(n){const t=n.object;return[...this.list.values()].find((e=>e.meshes.includes(t)))}}getAllPlaneMeshes(){const t=[];for(const[e,i]of this.list)t.push(...i.meshes);return t}createPlaneFromIntersection(t,e){var i;if(!t.renderer)throw new Error("The given world must have a renderer!");const n=e.point.distanceTo(new o.Vector3(0,0,0)),s=e.normal||(null==(i=e.face)?void 0:i.normal);if(!n||!s)return null;const r=this.getWorldNormal(e,s),a=this.newPlane(t,e.point,r.negate()),l=this.list.get(a);return l.visible=this._visible,l.size=this._size,t.renderer.setPlane(!0,l.three,this.localClippingPlanes),this.updateMaterialsAndPlanes(),l}getWorldNormal(t,e){const i=t.object;let n=t.object.matrixWorld.clone();if(i instanceof o.InstancedMesh&&void 0!==t.instanceId){const e=new o.Matrix4;i.getMatrixAt(t.instanceId,e),n=e.multiply(n)}const s=(new o.Matrix3).getNormalMatrix(n),r=e.clone().applyMatrix3(s).normalize();return this.normalizePlaneDirectionY(r),r}normalizePlaneDirectionY(t){this.orthogonalY&&(t.y>this.toleranceOrthogonalY&&(t.x=0,t.y=1,t.z=0),t.y<-this.toleranceOrthogonalY&&(t.x=0,t.y=-1,t.z=0))}newPlane(t,e,i){const n=new this.Type(this.components,t,e,i,this._material);n.autoScale=this.autoScalePlanes,n.onDraggingStarted.add((()=>this.onBeforeDrag.trigger(n))),n.onDraggingEnded.add((()=>this.onAfterDrag.trigger(n)));const s=_t.create();return this.list.set(s,n),this.onAfterCreate.trigger(n),s}updateMaterialsAndPlanes(){const t=this.components.get(Sa);for(const[e,i]of t.list){if(!i.renderer)continue;i.renderer.updateClippingPlanes();const{clippingPlanes:t}=i.renderer;for(const e of i.meshes)if(e.material)if(Array.isArray(e.material))for(const i of e.material)i.clippingPlanes=t;else e.material.clippingPlanes=t}}};e(Xa,"uuid","66290bc5-18c4-4cd1-9379-2e17a0617611");let Ka=Xa;class Qa{constructor(t,n){e(this,"title"),e(this,"guid",_t.create()),e(this,"clippingPlanes",new i.DataSet),e(this,"camera",{aspect_ratio:1,field_of_view:60,camera_direction:{x:0,y:0,z:0},camera_view_point:{x:0,y:0,z:0},camera_up_vector:{x:0,y:1,z:0}}),e(this,"customData",{}),e(this,"exceptionComponents",new i.DataSet),e(this,"selectionComponents",new i.DataSet),e(this,"componentColors",new i.DataMap),e(this,"spacesVisible",!1),e(this,"spaceBoundariesVisible",!1),e(this,"openingsVisible",!1),e(this,"defaultVisibility",!0),e(this,"snapshot",this.guid),e(this,"_components"),e(this,"_world",null),e(this,"notifyUpdate",(()=>{this._components.get(el).list.set(this.guid,this)})),this._components=t,n&&(this.guid=n.guid??this.guid,this.set(n)),this.setEvents()}async getSelectionMap(){const t=this._components.get(fr);return await t.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const t=this._components.get(fr);return await t.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const t=this._components.get(fr),{camera_view_point:e}=this.camera,{x:i,y:n,z:s}=e,r=new o.Vector3(i,n,s);return t.applyBaseCoordinateSystem(r,new o.Matrix4),r}set position(t){const e=t.clone(),i=this._components.get(fr);t.clone().applyMatrix4(i.baseCoordinationMatrix.clone().invert()),this.camera.camera_view_point={x:e.x,y:e.y,z:e.z}}get direction(){const{camera_direction:t}=this.camera,{x:e,y:i,z:n}=t;return new o.Vector3(e,i,n)}set world(t){this._world=t}get world(){return this._world}get _managerVersion(){return this._components.get(Za).config.version}get topics(){return[...this._components.get(Za).list.values()].filter((t=>t.viewpoints.has(this.guid)))}setEvents(){this.selectionComponents.onUpdated.add(this.notifyUpdate),this.exceptionComponents.onUpdated.add(this.notifyUpdate),this.clippingPlanes.onUpdated.add(this.notifyUpdate),this.componentColors.onItemSet.add(this.notifyUpdate),this.componentColors.onItemDeleted.add(this.notifyUpdate),this.componentColors.onItemUpdated.add(this.notifyUpdate),this.componentColors.onCleared.add(this.notifyUpdate)}set(t){this.title=t.title;const{components:e,perspective_camera:i,orthogonal_camera:n,clipping_planes:s}=t;if(e){const{selection:t,visibility:i,coloring:n}=e;if(t){this.selectionComponents.clear();for(const{ifc_guid:e}of t)e&&this.selectionComponents.add(e)}if(i){const{default_visibility:t,exceptions:e,view_setup_hints:n}=i;if(void 0!==t&&(this.defaultVisibility=t),e){this.exceptionComponents.clear();for(const{ifc_guid:t}of e)t&&this.exceptionComponents.add(t)}if(n){const{spaces_visible:t,space_boundaries_visible:e,openings_visible:i}=n;void 0!==t&&(this.spacesVisible=t),void 0!==e&&(this.spaceBoundariesVisible=e),void 0!==i&&(this.openingsVisible=i)}}if(n){this.componentColors.clear();for(const t of n){const{color:e,components:i}=t,n=i.map((t=>t.ifc_guid)).filter((t=>null!==t));this.componentColors.set(e,n)}}}if((i||n)&&(this.camera=i??n),s&&this.world){const t=this._components.get(Ka);for(const e of s){const{location:i,direction:n}=e,s=new o.Vector3(i.x,i.z,-i.y),r=new o.Vector3(n.x,n.z,-n.y),a=t.createFromNormalAndCoplanarPoint(this.world,r,s);this.clippingPlanes.add(a),t.list.get(a).enabled=!1,t.list.get(a).visible=!1}}this.notifyUpdate()}async go(t){if(!this.world)return;const{camera:e}=this.world;if(!(e instanceof Oa))throw new Error("Viewpoint: the world's camera component must be of type OrthoPerspectiveCamera to switch between perspective and orthographic projections.");const{transition:i,applyClippings:n,applyVisibility:s,clippingsVisibility:r}={transition:!0,applyClippings:!0,applyVisibility:!0,clippingsVisibility:!0,...t};e.projection.set(this.projection);const a=new o.Vector3(this.camera.camera_view_point.x,this.camera.camera_view_point.y,this.camera.camera_view_point.z),l=new o.Vector3(this.camera.camera_direction.x,this.camera.camera_direction.y,this.camera.camera_direction.z);if(a.equals(new o.Vector3)&&l.equals(new o.Vector3))return;const c=this.position,h=this.direction,u={x:c.x+80*h.x,y:c.y+80*h.y,z:c.z+80*h.z},d=[];n&&this.setClippingState(!0),s&&d.push(this.applyVisibility()),this.setClippingVisibility(r),d.push(e.controls.setLookAt(c.x,c.y,c.z,u.x,u.y,u.z,i)),await Promise.all(d)}async updateCamera(t=!0){return new Promise((e=>{if(!this.world)return void e(!1);const{camera:i,renderer:n}=this.world;if(!n)throw new Error("Viewpoint: the world needs to have a renderer!");if(!i.hasCameraControls())throw new Error("Viewpoint: world's camera need camera controls!");const s=i.three,r=s.getWorldPosition(new o.Vector3),a=s.getWorldDirection(new o.Vector3),{width:l,height:c}=n.getSize();let h=l/c;Number.isNaN(h)&&(h=1);const u=this._components.get(fr);r.applyMatrix4(u.baseCoordinationMatrix.clone().invert());const d={aspect_ratio:h,camera_view_point:{x:r.x,y:r.y,z:r.z},camera_direction:{x:a.x,y:a.y,z:a.z},camera_up_vector:{x:0,y:1,z:0}};if(s instanceof o.PerspectiveCamera?this.camera={...d,field_of_view:s.fov}:s instanceof o.OrthographicCamera&&(this.camera={...d,view_to_world_scale:s.top-s.bottom}),t){const t=this._components.get(el),s=n.three.domElement;n.three.render(this.world.scene.three,i.three),s.toBlob((async i=>{if(i){const e=await i.arrayBuffer(),n=new Uint8Array(e);t.snapshots.set(this.guid,n)}this.notifyUpdate(),e(!0)}))}else this.notifyUpdate(),e(!0)}))}takeSnapshot(){return new Promise((t=>{if(!this.world)return void t(!1);const{camera:e,renderer:i}=this.world;if(!i)throw new Error("Viewpoint: the world needs to have a renderer!");const n=this._components.get(el),s=i.three.domElement;i.three.render(this.world.scene.three,e.three),s.toBlob((async e=>{if(e){const t=await e.arrayBuffer(),i=new Uint8Array(t);n.snapshots.set(this.guid,i)}this.notifyUpdate(),t(!0)}))}))}updateClippingPlanes(){this.clippingPlanes.clear();const t=this._components.get(Ka);for(const[e,i]of t.list)i.enabled&&this.clippingPlanes.add(e)}async applyVisibility(){const t=this._components.get(No);t.set(this.defaultVisibility);const e=await this.getExceptionMap();t.set(!this.defaultVisibility,e);const i=await this.getSelectionMap();t.set(!0,i)}async setColorizationState(t){const e=this._components.get(fr),n=[];if(t)for(const[t,s]of this.componentColors){const r=`#${t}`,a=await e.guidsToModelIdMap(s);for(const[t,s]of Object.entries(a)){const a=e.list.get(t);a&&n.push(a.highlight([...s],{customId:r,color:new o.Color(r),renderedFaces:i.RenderedFaces.ONE,opacity:1,transparent:!1}))}}else for(const[t,i]of this.componentColors){const t=await e.guidsToModelIdMap(i);for(const[i,s]of Object.entries(t)){const t=e.list.get(i);t&&n.push(t.resetHighlight([...s]))}}n.push(e.core.update(!0)),await Promise.all(n)}setClippingState(t){const e=this._components.get(Ka);for(const[i,n]of e.list)n.enabled=t&&this.clippingPlanes.has(i)}setClippingVisibility(t){const e=this._components.get(Ka);for(const i of this.clippingPlanes){const n=e.list.get(i);n&&(n.visible=t)}}async createComponentTags(t){var e;const i=this._components.get(fr);let n="";if(this._components.get(Za).config.includeSelectionTag){const s="selection"===t?await this.getSelectionMap():await this.getExceptionMap();for(const t in s){const r=i.list.get(t);if(!r)continue;const o=s[t];for(const t of o){const i=r.getItem(t),s=await i.getGuid();if(!s)continue;const o=null==(e=await i.getAttributes())?void 0:e.getValue("Tag");let a=null;o&&(a=`AuthoringToolId="${o}"`),n+=`\n<Component IfcGuid="${s}" ${a??""} />`}}}else n=[...this.selectionComponents].map((t=>`<Component IfcGuid="${t}" />`)).join("\n");return n}createColorTags(){let t="";for(const[e,i]of this.componentColors.entries()){t+=`<Color Color="${e}">\n${i.map((t=>`\n<Component IfcGuid="${t}" />`)).join("\n")}\n</Color>`}return 0!==t.length?`<Coloring>\n${t}\n</Coloring>`:"<Coloring />"}toJSON(){const t=this._components.get(Ka),e={guid:this.guid,components:{selection:[...this.selectionComponents].map((t=>({ifc_guid:t,authoring_tool_id:null}))),coloring:[...this.componentColors].map((([t,e])=>({color:t,components:e.map((t=>({ifc_guid:t,authoring_tool_id:null})))}))),visibility:{default_visibility:this.defaultVisibility,exceptions:[...this.exceptionComponents].map((t=>({ifc_guid:t,authoring_tool_id:null}))),view_setup_hints:{spaces_visible:this.spacesVisible,space_boundaries_visible:this.spaceBoundariesVisible,openings_visible:this.openingsVisible}}},clipping_planes:[...this.clippingPlanes].map((e=>{const i=t.list.get(e);if(!i)return null;const n=i._controls.worldPosition??i.origin,{normal:s}=i;return{location:{x:n.x,y:-n.z,z:n.y},direction:{x:s.x,y:-s.z,z:s.y}}})).filter((t=>null!==t))};"field_of_view"in this.camera?e.perspective_camera=this.camera:e.orthogonal_camera=this.camera;const i=this._components.get(el),n=i.snapshots.get(this.snapshot);if(n){const t=n.toString(),s=btoa(t),r=i.getSnapshotExtension(this.snapshot);e.snapshot={snapshot_type:r,snapshot_data:s}}return e}async serialize(t=this._managerVersion){const e=this._components.get(fr),i=this.position;i.applyMatrix4(e.baseCoordinationMatrix.clone().invert());const n=this.direction;n.normalize();const s=(new o.Matrix4).makeRotationX(Math.PI/2),r=n.clone().applyMatrix4(s);r.normalize();const a=`<CameraViewPoint>\n <X>${i.x}</X>\n <Y>${-i.z}</Y>\n <Z>${i.y}</Z>\n </CameraViewPoint>`,l=`<CameraDirection>\n <X>${n.x}</X>\n <Y>${-n.z}</Y>\n <Z>${n.y}</Z>\n </CameraDirection>`,c=`<CameraUpVector>\n <X>${r.x}</X>\n <Y>${-r.z}</Y>\n <Z>${r.y}</Z>\n </CameraUpVector>`,h=`<AspectRatio>${this.camera.aspect_ratio}</AspectRatio>`;let u="";"view_to_world_scale"in this.camera?u=`<OrthogonalCamera>\n ${a}\n ${l}\n ${c}\n ${h}\n <ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>\n </OrthogonalCamera>`:"field_of_view"in this.camera&&(u=`<PerspectiveCamera>\n ${a}\n ${l}\n ${c}\n ${h}\n <FieldOfView>${this.camera.field_of_view}</FieldOfView>\n </PerspectiveCamera>`);const d=`<ViewSetupHints SpacesVisible="${this.spacesVisible??!1}" SpaceBoundariesVisible="${this.spaceBoundariesVisible??!1}" OpeningsVisible="${this.openingsVisible??!1}" />`,p=(await this.createComponentTags("selection")).trim(),f=(await this.createComponentTags("exception")).trim(),m=this.createColorTags();return`<?xml version="1.0" encoding="UTF-8"?>\n <VisualizationInfo Guid="${this.guid}">\n <Components>\n ${"2.1"===t?d:""}\n ${0!==p.length?`<Selection>${p}</Selection>`:""}\n <Visibility DefaultVisibility="${this.defaultVisibility}">\n ${"3"===t?d:""}\n ${0!==f.length?`<Exceptions>${f}</Exceptions>`:""}\n </Visibility>\n ${m}\n </Components>\n ${u}\n </VisualizationInfo>`}}class Ja extends ui{constructor(){super(...arguments),e(this,"_config",{overwriteColors:{value:!1,type:"Boolean"}})}get overwriteColors(){return this._config.overwriteColors.value}set overwriteColors(t){this._config.overwriteColors.value=t}}const tl=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"world",null),e(this,"list",new n),e(this,"snapshots",new n),e(this,"isSetup",!1),e(this,"onSetup",new at),e(this,"config",new Ja(this,this.components,"Viewpoints",t.uuid)),e(this,"onDisposed",new at),i.add(t.uuid,this)}create(t){const e=new Qa(this.components,t);return e.world=this.world,t||this.list.set(e.guid,e),e}getSnapshotExtension(t){let e="jpeg";const i=this.snapshots.get(t);if(!i)return e;const n=i.subarray(0,4);let s="";for(let t=0;t<n.length;t++)s+=n[t].toString(16);return s.startsWith("89504e47")&&(e="png"),s.startsWith("ffd8ffe")&&(e="jpeg"),e}setup(){}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}};e(tl,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");let el=tl;class il{constructor(t,i){e(this,"_components"),e(this,"_cameraOffset",10),e(this,"_planeHelper"),e(this,"_farPlaneHelper"),e(this,"_cameraHelper"),e(this,"onStateChanged",new at),e(this,"onUpdated",new at),e(this,"onDisposed",new at),e(this,"camera"),e(this,"plane",new o.Plane),e(this,"farPlane",new o.Plane),e(this,"id",_t.create()),e(this,"_open",!1),e(this,"_range",sl.defaultRange),e(this,"_world",null),e(this,"_helpersVisible",!1),e(this,"_planesEnabled",!1),this._components=t,this.camera=new Oa(this._components);const{threeOrtho:n}=this.camera;if((null==i?void 0:i.id)&&(this.id=i.id),(null==i?void 0:i.normal)&&(null==i?void 0:i.point)){const{normal:t,point:e}=i;this.plane.setFromNormalAndCoplanarPoint(t,e)}this._cameraHelper=new o.CameraHelper(n),this._planeHelper=new o.PlaneHelper(this.plane,50),this._farPlaneHelper=new o.PlaneHelper(this.farPlane,50),this.farPlaneHelperColor=new o.Color("blue"),this.update()}get _planeNormalOpposite(){return this.plane.normal.clone().negate()}get _planePosition(){return this.plane.normal.clone().multiplyScalar(-this.plane.constant)}get _cameraPosition(){return this._planePosition.addScaledVector(this._planeNormalOpposite,this._cameraOffset)}set open(t){this._open=t,this.onStateChanged.trigger(["open"])}get open(){return this._open}set planeHelperColor(t){!Array.isArray(this._planeHelper.material)&&"color"in this._planeHelper.material&&this._planeHelper.material.color instanceof o.Color&&(this._planeHelper.material.color=t)}set farPlaneHelperColor(t){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof o.Color&&(this._farPlaneHelper.material.color=t)}set range(t){this._range=t,this.update()}get range(){return this._range}set distance(t){this.plane.constant=t,this.update()}get distance(){return this.plane.constant}set world(t){this._world=t,this.camera.currentWorld=t,t&&(this.camera.projection.set("Orthographic"),this.camera.set("Plan"),this.camera.controls.dollySpeed=6,this.camera.controls.restThreshold=.005,this.update())}get world(){return this._world}set helpersVisible(t){if(!t)return this._helpersVisible=t,this._planeHelper.removeFromParent(),this._farPlaneHelper.removeFromParent(),void this._cameraHelper.removeFromParent();this.world&&(this._helpersVisible=t,this.world.scene.three.add(this._planeHelper,this._farPlaneHelper))}get helpersVisible(){return this._helpersVisible}set planesEnabled(t){const{world:e}=this;if(!e)return;const{renderer:i}=e;i&&(i.setPlane(t,this.plane),i.setPlane(t,this.farPlane),this._planesEnabled=t)}get planesEnabled(){return this._planesEnabled}dispose(){this.helpersVisible=!1;const t=this._components.get(mt);t.destroy(this._planeHelper),t.destroy(this._farPlaneHelper),t.destroy(this._cameraHelper),this.camera.dispose(),this.onDisposed.trigger()}update(){if(this.world){const t=this._cameraPosition,e=this._planePosition;this.camera.controls.setLookAt(t.x,t.y,t.z,e.x,e.y,e.z,!1)}this.farPlane.normal.copy(this._planeNormalOpposite),this.farPlane.constant=this.range-this.plane.constant,this.onUpdated.trigger()}flip(){this.plane.normal.negate(),this.update()}}const nl=class t extends ht{constructor(i){super(i),e(this,"list",new n),e(this,"enabled",!0),e(this,"world",null),e(this,"_fragmentsUpdateEvent",(()=>{this.components.get(fr).core.update(!0)})),e(this,"restoreCameraOnClose",!0),e(this,"_restoreState",null),i.add(t.uuid,this),this.setupEvents()}get hasOpenViews(){return[...this.list.values()].some((t=>t.open))}setupEvents(){this.list.onBeforeDelete.add((({key:t,value:e})=>{e.open&&this.close(t),e.dispose()}))}create(t,e,i){const n=new il(this.components,{id:null==i?void 0:i.id,normal:t,point:e});return n.world=(null==i?void 0:i.world)??this.world,this.list.set(n.id,n),n}createFromPlane(t,e){const i=new il(this.components,{id:null==e?void 0:e.id});return i.plane.copy(t),i.update(),i.world=(null==e?void 0:e.world)??this.world,this.list.set(i.id,i),i}async createFromIfcStoreys(t){const e=[],i=this.components.get(fr),n=void 0===(null==t?void 0:t.offset)?.25:t.offset;for(const[s,r]of i.list){if(t&&t.modelIds&&!t.modelIds.some((t=>t.test(s))))continue;const i=Object.values(await r.getItemsOfCategories([/BUILDINGSTOREY/])).flat();if(0===i.length)continue;const a=await r.getItemsData(i),[,l]=await r.getCoordinates(),c=new o.Vector3(0,-1,0);for(const i of a){if(!("value"in i.Name)||!("value"in i.Elevation))continue;const{value:s}=i.Name;if((null==t?void 0:t.storeyNames)&&!t.storeyNames.some((t=>t.test(s))))continue;const r=i.Elevation.value+l+n,a=new o.Plane(c,r),h=this.createFromPlane(a,{id:s,world:null==t?void 0:t.world});e.push(h)}}return e}createElevations(t){const e=[],i=this.components.get(fr),n=void 0!==(null==t?void 0:t.combine)&&t.combine,s=(null==t?void 0:t.namingCallback)??(t=>({front:""+(n?"Front":`${t}: Front`),back:""+(n?"Back":`${t}: Back`),left:""+(n?"Left":`${t}: Left`),right:""+(n?"Right":`${t}: Right`)}));let r=[];for(const[e,n]of i.list)t&&t.modelIds&&!t.modelIds.some((t=>t.test(e)))||r.push({id:e,box:n.box});if(0===r.length)return e;if(n){const t=this.components.get(Lo);t.list.clear(),t.list.add(...r.map((t=>t.box)));r=[{id:"combined",box:t.get()}]}for(const{id:i,box:n}of r){const{min:r,max:a}=n,l=Math.abs(a.x-r.x),c=Math.abs(a.z-r.z),h=new o.Vector3;n.getCenter(h);const u=new o.Plane(new o.Vector3(0,0,-1),a.z),d=new o.Plane(new o.Vector3(0,0,1),-r.z),p=new o.Plane(new o.Vector3(-1,0,0),a.x),f=new o.Plane(new o.Vector3(1,0,0),-r.x),{front:m,back:g,left:w,right:y}=s(i),_=this.createFromPlane(u,{id:m,world:null==t?void 0:t.world});_.range=c;const b=this.createFromPlane(d,{id:g,world:null==t?void 0:t.world});b.range=c;const v=this.createFromPlane(p,{id:w,world:null==t?void 0:t.world});v.range=l;const x=this.createFromPlane(f,{id:y,world:null==t?void 0:t.world});x.range=l,e.push(_,b,v,x)}return e}open(t){const e=this.list.get(t);if(!e)throw new Error(`Views: the view with id ${t} doesn't exist.`);if(e.open)return;const{world:i}=e;if(!i)throw new Error(`Views: no world found for view with id ${t}.`);const{renderer:n}=i;if(!n)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);for(const[,t]of this.list)t.world===i&&this.close(t.id);this.restoreCameraOnClose&&i.camera!==e.camera&&!this._restoreState&&i.camera.controls&&(this._restoreState={camera:i.camera,json:i.camera.controls.toJSON()}),n.setPlane(!0,e.plane),n.setPlane(!0,e.farPlane),this.setOnlyEnabledControls(i,e),e.camera.controls.addEventListener("rest",this._fragmentsUpdateEvent),i.camera=e.camera,e.open=!0}close(t){let e;if(e=t?this.list.get(t):[...this.list.values()].find((t=>t.open)),t&&!e)throw new Error(`Views: the view with id ${t} doesn't exist.`);if(!e)return;if(!e.open)return;const{world:i}=e;if(!i)throw new Error(`Views: no world found for view with id ${t}.`);const{renderer:n}=i;if(!n)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);if(n.setPlane(!1,e.plane),n.setPlane(!1,e.farPlane),e.camera.controls.removeEventListener("rest",this._fragmentsUpdateEvent),i.useDefaultCamera(),e.open=!1,this.setOnlyEnabledControls(i,null),this.restoreCameraOnClose&&this._restoreState){const{camera:t,json:e}=this._restoreState;t===i.camera&&t.controls&&t.controls.fromJSON(e,!1),this._restoreState=null}}setOnlyEnabledControls(t,e){const i=e?e.camera:t.defaultCamera,n=(t,e)=>{t.controls&&(t.controls.enabled=e)};n(i,!0),i!==t.defaultCamera&&n(t.defaultCamera,!1);for(const[,e]of this.list)e.world===t&&e.camera!==i&&n(e.camera,!1)}};e(nl,"uuid","fb22f1f5-6598-4664-a11d-de8963ae420f"),e(nl,"defaultRange",15);let sl=nl;async function rl(t,e,i,n,s,r,o){const a=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),await function(t,e,i,n){return new Promise(((s,r)=>{!function o(){const a=t.clientWaitSync(e,i,0);a!==t.WAIT_FAILED?a!==t.TIMEOUT_EXPIRED?s():setTimeout(o,n):r()}()}))}(t,a,0,10),t.deleteSync(a),t.bindBuffer(e,i),t.getBufferSubData(e,n,s,r,o),t.bindBuffer(e,null)}class ol{constructor(t,i){if(e(this,"onDisposed",new at),e(this,"onDistanceComputed",new at),e(this,"excludedObjects",new Set),e(this,"enabled",!0),e(this,"renderDebugFrame",!1),e(this,"components"),e(this,"scene",new o.Scene),e(this,"camera",new o.OrthographicCamera(-1,1,1,-1,0,1)),e(this,"depthMaterial"),e(this,"world"),e(this,"worker"),e(this,"_width",512),e(this,"_height",512),e(this,"_postQuad"),e(this,"tempRT"),e(this,"resultRT"),e(this,"bufferSize"),e(this,"_buffer"),e(this,"_isWorkerBusy",!1),e(this,"compute",(async()=>{if(!this.enabled||this.world.isDisposing)return;if(this._isWorkerBusy)return;this._isWorkerBusy=!0,this.world.camera.three.updateMatrix();const t=this.world.renderer.three;t.setRenderTarget(this.tempRT);const e="visibilityBeforeDistanceCheck";for(const t of this.excludedObjects)t.userData[e]=t.visible,t.visible=!1;t.render(this.world.scene.three,this.world.camera.three);for(const t of this.excludedObjects)void 0!==t.userData[e]&&(t.visible=t.userData[e]);this.depthMaterial.uniforms.tDiffuse.value=this.tempRT.texture,this.depthMaterial.uniforms.tDepth.value=this.tempRT.depthTexture,t.setRenderTarget(this.resultRT),t.render(this.scene,this.camera);const i=t.getContext();try{await async function(t,e,i,n,s,r,o,a){const l=t.createBuffer();return t.bindBuffer(t.PIXEL_PACK_BUFFER,l),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(e,i,n,s,r,o,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),await rl(t,t.PIXEL_PACK_BUFFER,l,0,a),t.deleteBuffer(l),a}(i,0,0,this._width,this._height,i.RGBA,i.UNSIGNED_BYTE,this._buffer)}catch(e){return t.setRenderTarget(null),void(this._isWorkerBusy=!1)}t.setRenderTarget(null),this.renderDebugFrame&&t.render(this.scene,this.camera),this.worker.postMessage({buffer:this._buffer})})),e(this,"handleWorkerMessage",(t=>{if(!this.enabled||this.world.isDisposing)return;const e=t.data.colors;let i=Number.MAX_VALUE;for(const t of e)0!==t&&t<i&&(i=t);const n=this.world.camera.three||o.OrthographicCamera,s=-1*(i/255-1)*(n.far-n.near),r=Math.min(s,n.far);this.onDistanceComputed.trigger(r),this._isWorkerBusy=!1})),!i.renderer)throw new Error("The given world must have a renderer!");this.components=t,this.world=i;const n=i.camera.three;this.tempRT=new o.WebGLRenderTarget(this._width,this._height),this.bufferSize=this._width*this._height*4,this._buffer=new Uint8Array(this.bufferSize),this.tempRT.texture.minFilter=o.NearestFilter,this.tempRT.texture.magFilter=o.NearestFilter,this.tempRT.stencilBuffer=!1,this.tempRT.samples=0,this.tempRT.depthTexture=new o.DepthTexture(this._width,this._height),this.tempRT.depthTexture.format=o.DepthFormat,this.tempRT.depthTexture.type=o.UnsignedShortType,this.resultRT=new o.WebGLRenderTarget(this._width,this._height),this.depthMaterial=new o.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n ",fragmentShader:"\n#include <packing>\n\nvarying vec2 vUv;\nuniform sampler2D tDiffuse;\nuniform sampler2D tDepth;\nuniform float cameraNear;\nuniform float cameraFar;\n\n\nfloat readDepth( sampler2D depthSampler, vec2 coord ) {\n float fragCoordZ = texture2D( depthSampler, coord ).x;\n float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );\n return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );\n}\n\nvoid main() {\n //vec3 diffuse = texture2D( tDiffuse, vUv ).rgb;\n float depth = readDepth( tDepth, vUv );\n\n gl_FragColor.rgb = 1.0 - vec3( depth );\n gl_FragColor.a = 1.0;\n}\n ",uniforms:{cameraNear:{value:n.near},cameraFar:{value:n.far},tDiffuse:{value:null},tDepth:{value:null}}});const s=new o.PlaneGeometry(2,2);this._postQuad=new o.Mesh(s,this.depthMaterial),this.scene.add(this._postQuad);const r=new Blob(['\n addEventListener("message", (event) => {\n const { buffer } = event.data;\n const colors = new Set();\n for (let i = 0; i < buffer.length; i += 4) {\n const r = buffer[i];\n colors.add(r);\n }\n postMessage({ colors });\n });\n '],{type:"application/javascript"});this.worker=new Worker(URL.createObjectURL(r)),this.worker.addEventListener("message",this.handleWorkerMessage)}dispose(){this.enabled=!1,this.onDistanceComputed.reset(),this.worker.terminate(),this.tempRT.dispose(),this.resultRT.dispose();const t=[...this.scene.children];this.excludedObjects.clear();for(const e of t)e.removeFromParent();this._postQuad.geometry.dispose(),this._postQuad.removeFromParent(),this._buffer=null,this.onDisposed.reset()}}class al extends ya{constructor(){super(...arguments),e(this,"_distanceRenderer"),e(this,"autoBias",!0),e(this,"_defaultShadowConfig",{cascade:1,resolution:512}),e(this,"_lightsWithShadow",new Map),e(this,"_isComputingShadows",!1),e(this,"_shadowsEnabled",!0),e(this,"_bias",0),e(this,"recomputeShadows",(t=>{if(!this._shadowsEnabled)return;this.autoBias&&(this.bias=-.005);if(t*=1.5,!this.currentWorld)throw new Error("A world needs to be assigned to the scene before computing shadows!");if(!this._lightsWithShadow.size)throw new Error("No shadows found!");const e=this.currentWorld.camera.three;if(!(e instanceof o.PerspectiveCamera||e instanceof o.OrthographicCamera))throw new Error("Invalid camera type!");const i=new o.Vector3;e.getWorldDirection(i);let n=t;const s=new o.Vector3;s.copy(this.config.directionalLight.position),s.normalize();for(const[t,r]of this._lightsWithShadow){const a=this.directionalLights.get(r);if(!a)throw new Error("Light not found.");const l=new o.Vector3;l.copy(i);const c=t===this._lightsWithShadow.size-1,h=c?n/2:2*n/3;l.multiplyScalar(h),l.add(e.position);const u=n-h,d=new o.Vector3;d.copy(s),d.multiplyScalar(u),a.target.position.copy(l),a.position.copy(l),a.position.add(d),a.shadow.camera.right=u,a.shadow.camera.left=-u,a.shadow.camera.top=u,a.shadow.camera.bottom=-u,a.shadow.camera.far=2*u,a.shadow.camera.updateProjectionMatrix(),a.shadow.camera.updateMatrix(),c||(n/=3)}this._isComputingShadows=!1}))}get bias(){return this._bias}set bias(t){this._bias=t;for(const[,e]of this._lightsWithShadow){const i=this.directionalLights.get(e);i&&(i.shadow.bias=t)}}get shadowsEnabled(){return this._shadowsEnabled}set shadowsEnabled(t){this._shadowsEnabled=t;for(const[,e]of this.directionalLights)e.castShadow=t}get distanceRenderer(){if(!this._distanceRenderer)throw new Error("You must set up this component before accessing the distance renderer!");return this._distanceRenderer}setup(t){super.setup(t);const e={...this._defaultConfig,...this._defaultShadowConfig,...t};if(e.cascade<=0)throw new Error("Config.shadows.cascade must be a natural number greater than 0!");if(e.cascade>1)throw new Error("Multiple shadows not supported yet!");if(!this.currentWorld)throw new Error("A world needs to be assigned to the scene before setting it up!");for(const[,t]of this.directionalLights)t.target.removeFromParent(),t.removeFromParent(),t.dispose();this.directionalLights.clear(),this._distanceRenderer||(this._distanceRenderer=new ol(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let t=0;t<e.cascade;t++){const i=new o.DirectionalLight;i.intensity=this.config.directionalLight.intensity,i.color=this.config.directionalLight.color,i.position.copy(this.config.directionalLight.position),i.shadow.mapSize.width=e.resolution,i.shadow.mapSize.height=e.resolution,this.three.add(i,i.target),this.directionalLights.set(i.uuid,i),this._lightsWithShadow.set(t,i.uuid),i.castShadow=!0,i.shadow.bias=this._bias}}dispose(){super.dispose(),this._distanceRenderer&&this._distanceRenderer.dispose(),this._lightsWithShadow.clear()}async updateShadows(){!this._isComputingShadows&&this._shadowsEnabled&&(this._isComputingShadows=!0,await this.distanceRenderer.compute())}}class ll{constructor(t){e(this,"cardinality","required"),e(this,"instructions"),e(this,"evalRequirement",((t,e,i,n)=>{const s={parameter:i,currentValue:t,requiredValue:e,pass:!1};n&&this.addCheckResult(s,n);let r=!1;if("simple"===e.type&&(r=t===e.parameter),"enumeration"===e.type&&(r=e.parameter.includes(t)),"pattern"===e.type){r=new RegExp(e.parameter).test(String(t))}if("length"===e.type){const{min:i,length:n,max:s}=e.parameter;void 0!==n&&(r=String(t).length===n),void 0!==i&&(r=String(t).length>=i),void 0!==s&&(r=String(t).length<=s)}if("bounds"===e.type&&"number"==typeof t){const{min:i,minInclusive:n,max:s,maxInclusive:o}=e.parameter;let a=!0,l=!0;void 0!==i&&(a=n?t>=i:t>i),void 0!==s&&(l=o?t<=s:t<s),r=a&&l}return"prohibited"===this.cardinality&&(r=!r),"optional"===this.cardinality&&(r=!0),s.pass=r,s.pass})),this._components=t}addCheckResult(t,e){const i=e.findIndex((({parameter:e})=>e===t.parameter));-1!==i?e[i]=t:e.push(t)}getItemChecks(t,e,n,s){if(!("value"in n._localId)||"number"!=typeof n._localId.value)return null;let r=t.get(e);r||(r=new i.DataMap,t.set(e,r));let o=r.get(n._localId.value);if(o&&s&&!o.pass)return null;if(!o){const t=[];o={guid:Array.isArray(n._guid)?void 0:n._guid.value,pass:!1,checks:t},Object.defineProperty(o,"pass",{get:()=>t.every((({pass:t})=>t))}),r.set(n._localId.value,o)}const a=[],l={facetType:this.facetType,cardinality:this.cardinality,checks:a,pass:!1};return Object.defineProperty(l,"pass",{get:()=>a.every((({pass:t})=>t))}),o.checks.push(l),l.checks}}const cl=(t,e)=>{let i="";if(!e)return i;if("simple"===e.type&&(i=`<simpleValue>${e.parameter}</simpleValue>`),"enumeration"===e.type){i=`<xs:restriction base="xs:string">\n ${e.parameter.map((t=>`<xs:enumeration value="${t}" />`)).join("\n")}\n </xs:restriction>`}if("pattern"===e.type){i=`<xs:restriction base="xs:string">\n <xs:pattern value="${e.parameter}" />\n </xs:restriction>`}if("bounds"===e.type){const{min:t,minInclusive:n,max:s,maxInclusive:r}=e.parameter;let o="";void 0!==t&&(o=`<xs:min${n?"Inclusive":"Exclusive"} value="${t}">`);let a="";void 0!==s&&(a=`<xs:max${r?"Inclusive":"Exclusive"} value="${s}">`),i=`<xs:restriction base="xs:double">\n ${o}\n ${a}\n </xs:restriction>`}if("length"===e.type){const{length:t,min:n,max:s}=e.parameter;let r="";void 0!==t&&void 0===n&&void 0===s&&(r=`<xs:length value="${t}" />`);let o="";void 0!==n&&void 0===t&&(o=`<xs:minLength value="${n}" />`);let a="";void 0!==s&&void 0===t&&(a=`<xs:maxLength value="${s}" />`),i=`<xs:restriction base="xs:string">\n ${r}\n ${o}\n ${a}\n </xs:restriction>`}return`<${t[0].toLowerCase()+t.slice(1)}>\n ${i}\n </${t[0].toLowerCase()+t.slice(1)}>`};class hl extends ll{constructor(t,i){super(t),e(this,"facetType","Attribute"),e(this,"name"),e(this,"value"),this.name=i}serialize(t){const e=cl("Name",this.name),i=cl("Value",this.value);let n="";return"requirement"===t&&(n+=`cardinality="${this.cardinality}"`,n+=this.instructions?`instructions="${this.instructions}"`:""),`<attribute ${n}>\n ${e}\n ${i}\n</attribute>`}async getEntities(){}async test(t,e,i={skipIfFails:!0}){const n=this._components.get(fr);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([...r]);for(const t of o){const n=this.getItemChecks(e,s,t,i.skipIfFails);if(!n)continue;const r=Object.keys(t).filter((e=>{const i=this.evalRequirement(e,this.name,"Name");if(!i)return!1;const n=t[e];return!!Array.isArray(n)||(null===n||null===n.value?"optional"===this.cardinality||"prohibited"===this.cardinality:(!Array.isArray(n.value)||0!==n.value.length)&&(("string"!=typeof n.value||""!==n.value.trim())&&i))})),o=r.length>0;if(n.push({parameter:"Name",currentValue:o?r[0]:null,requiredValue:this.name,pass:"prohibited"===this.cardinality?!o:o}),this.value)if(r[0]){const e=t[r[0]];if(Array.isArray(e))n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality});else{Array.isArray(e.value)?n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality}):this.evalRequirement(e.value,this.value,"Value",n)}}else n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality})}}}}class ul extends ll{constructor(t,i){super(t),e(this,"facetType","Classification"),e(this,"system"),e(this,"value"),e(this,"uri"),this.system=i}serialize(t){const e=cl("System",this.system),i=cl("Value",this.value);let n="";return"requirement"===t&&(n+=`cardinality="${this.cardinality}"`,n+=this.uri?`uri=${this.uri}`:"",n+=this.instructions?`instructions="${this.instructions}"`:""),`<classification ${n}>\n ${e}\n ${i}\n</classification>`}async getEntities(t,e){}async test(t,e){}}class dl extends ll{constructor(t,i){super(t),e(this,"facetType","Entity"),e(this,"name"),e(this,"predefinedType"),this.name=i}serialize(t){const e=cl("Name",this.name),i=cl("Name",this.predefinedType);let n="";return"requirement"===t&&(n+=`cardinality="${this.cardinality}"`,n+=this.instructions?`instructions="${this.instructions}"`:""),`<entity ${n}>\n ${e}\n ${i}\n</entity>`}async getEntities(t,e){const i=this._components.get(fr),n=new Map;for(const[e,s]of i.list){if(!t.find((t=>t.test(e))))continue;const i=await s.getCategories();for(const t of i){if(!await this.evalName(t))continue;let i=n.get(e);i||(i=[],n.set(e,i)),i.push(t)}}const s={};if(await Promise.all(Array.from(n.entries()).map((async([t,e])=>{const n=i.list.get(t);if(!n)return;const r=e.map((t=>new RegExp(`^${t}$`))),o=await n.getItemsOfCategories(r),a=Object.values(o).flat();s[t]=new Set(a)}))),this.predefinedType)for(const[t,n]of Object.entries(s)){const s=i.list.get(t);if(!s)continue;const r=await s.getItemsData([...n]);for(const i of r){if(!("value"in i._localId))continue;await this.evalPredefinedType(t,i)&&ai.append(e,t,i._localId.value)}}else ai.add(e,s)}async test(t,e,i){const n=this._components.get(fr);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([...r]);for(const t of o){if(!("value"in t._category))continue;const n=this.getItemChecks(e,s,t,i.skipIfFails);n&&(await this.evalName(t._category.value,n),await this.evalPredefinedType(s,t,n))}}}async evalName(t,e){return this.evalRequirement(t,this.name,"Name",e)}async evalPredefinedType(t,e,i){if(!this.predefinedType)return null;if(!("value"in e.PredefinedType))return null;const n="string"==typeof this.predefinedType.parameter&&"USERDEFINED"===this.predefinedType.parameter;let s=e.PredefinedType.value;if("USERDEFINED"===s&&!n){const t=Object.keys(e).find((t=>/^((?!Predefined).)*Type$/.test(t)));if(t){const i=e[t];"value"in i&&(s=i.value)}else s="USERDEFINED"}if(!s){const i=this._components.get(fr).list.get(t);if(i&&"value"in e._localId){const[t]=await i.getItemsData([e._localId.value],{relations:{IsTypedBy:{attributes:!0,relations:!1}}});if(Array.isArray(t.IsTypedBy)){const e=t.IsTypedBy[0];if(e&&"value"in e.PredefinedType&&(s=e.PredefinedType.value,"USERDEFINED"===s&&!n)){const t=Object.keys(e).find((t=>/^((?!Predefined).)*Type$/.test(t)));if(t){const i=e[t];"value"in i&&(s=i.value)}else s="USERDEFINED"}}}}return this.evalRequirement(s,this.predefinedType,"PredefinedType",i)}}class pl extends ll{constructor(t,i,n){super(t),e(this,"facetType","Property"),e(this,"propertySet"),e(this,"baseName"),e(this,"value"),e(this,"dataType"),e(this,"uri"),e(this,"_unsupportedTypes",["IFCCOMPLEXPROPERTY","IFCPHYSICALCOMPLEXQUANTITY"]),this.propertySet=i,this.baseName=n}serialize(t){const e=cl("PropertySet",this.propertySet),i=cl("BaseName",this.baseName),n=cl("Value",this.value),s=this.dataType?`dataType=${this.dataType}`:"";let r="";return"requirement"===t&&(r+=`cardinality="${this.cardinality}"`,r+=this.uri?`uri=${this.uri}`:"",r+=this.instructions?`instructions="${this.instructions}"`:""),`<property ${s} ${r}>\n ${e}\n ${i}\n ${n}\n</property>`}async getEntities(t,e){const i=this._components.get(fr);for(const[n,s]of i.list){if(!t.find((t=>t.test(n))))continue;const i=await s.getItemsOfCategories([/PROPERTYSET/,/ELEMENTQUANTITY/]),r=Object.values(i).flat();if(0===r.length)continue;const o=await s.getItemsData(r,{relations:{HasProperties:{attributes:!0,relations:!1},DefinesOcurrence:{attributes:!0,relations:!1}}});for(const t of o){if(!("value"in t._localId&&"value"in t._category&&"value"in t.Name&&Array.isArray(t.DefinesOcurrence)))continue;if(!this.evalRequirement(t.Name.value,this.propertySet,"PropertySet"))continue;let i;if("IFCPROPERTYSET"===t._category.value&&(i="HasProperties"),"IFCELEMENTQUANTITY"===t._category.value&&(i="Quantities"),!i)continue;const s=t[i];if(Array.isArray(s))for(const i of s){const s=Object.keys(i),r=s.find((t=>/Name/.test(t)));if(!r||!("value"in i[r]))continue;const o=i[r];if(!("value"in o))continue;if(!this.evalRequirement(o.value,this.baseName,"BaseName"))continue;if(this.value){const t=s.find((t=>/Value/.test(t)));if(!t)continue;const e=i[t];if(!("value"in e))continue;if(!this.evalRequirement(e.value,this.value,"Value"))continue}const a=t.DefinesOcurrence.map((t=>"value"in t._localId&&"number"==typeof t._localId.value?t._localId.value:null)).filter((t=>null!==t));ai.append(e,n,...a)}}}}async test(t,e,i={skipIfFails:!0}){const n=this._components.get(fr);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([...r],{relations:{IsDefinedBy:{attributes:!0,relations:!0},IsTypedBy:{attributes:!0,relations:!1},HasPropertySets:{attributes:!0,relations:!0},DefinesOcurrence:{attributes:!1,relations:!1}}});for(const t of o){const n=this.getItemChecks(e,s,t,i.skipIfFails);if(!n)continue;const r=(await this.getPsets(t)).filter((t=>{if(!("value"in t.Name))return!1;return!!this.evalRequirement(t.Name.value,this.propertySet,"PropertySet")&&(n.push({currentValue:t.Name.value,parameter:"PropertySet",pass:!0,requiredValue:this.propertySet}),!0)}));if(0!==r.length)for(const t of r){const e=this.getPropertyListName(t);if(!e)continue;const i=t[e];if(!Array.isArray(i)){n.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}const s=i.filter((t=>{if(!("value"in t._category)||!("value"in t.Name))return!1;if(this._unsupportedTypes.includes(t._category.value))return!1;return!!this.evalRequirement(t.Name.value,this.baseName,"BaseName")&&(n.push({currentValue:t.Name.value,parameter:"BaseName",pass:!0,requiredValue:this.baseName}),!0)}));if(0!==s.length)for(const t of s)this.evalValue(t,n),this.evalDataType(t,n),this.evalURI();else n.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName})}else n.push({currentValue:null,parameter:"PropertySet",pass:!1,requiredValue:this.propertySet})}}}getPropertyListName(t){let e;return"value"in t._category?("IFCPROPERTYSET"===t._category.value&&(e="HasProperties"),"IFCELEMENTQUANTITY"===t._category.value&&(e="Quantities"),e):e}getValueKey(t){return Object.keys(t).find((t=>/Value/.test(t)||/Values/.test(t)))}getTypePsets(t){if(!Array.isArray(t.IsTypedBy))return[];const[e]=t.IsTypedBy;return e&&Array.isArray(e.HasPropertySets)?e.HasPropertySets:[]}async getPsets(t){const e=this.getTypePsets(t);if(!Array.isArray(t.IsDefinedBy))return e;const i=[];for(const n of t.IsDefinedBy){if(!("value"in n.Name))continue;const t=n.Name.value,s=this.getPropertyListName(n);if(!t||!s)continue;const r=e.find((e=>"value"in e.Name&&e.Name.value===t));if(r&&Array.isArray(r.HasProperties)&&Array.isArray(n.HasProperties))for(const t of r.HasProperties){if(!("value"in t.Name))continue;const e=t.Name.value;n.HasProperties.find((t=>"value"in t.Name&&t.Name.value===e))||n.HasProperties.push(t)}i.push(n)}return i}evalValue(t,e){const i=this.getValueKey(t),n=t[i];if(!("value"in n))return!1;if(this.value){if(!i)return null==e||e.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;const t=structuredClone(this.value);"IFCLABEL"===n.type&&"simple"===t.type&&(t.parameter=String(t.parameter));return this.evalRequirement(n.value,t,"Value",e)}return!i||("string"!=typeof n.value||""!==n.value.trim()||(null==e||e.push({parameter:"Value",currentValue:"",pass:!1,requiredValue:this.value}),!1))}evalDataType(t,e){if(!this.dataType)return!0;const i=this.getValueKey(t);if(!i||!("value"in t[i]))return null==e||e.push({parameter:"DataType",currentValue:null,pass:!1,requiredValue:this.dataType}),!1;const n=t[i];return this.evalRequirement(n.type??null,{type:"simple",parameter:this.dataType},"DataType",e)}evalURI(){return!0}}class fl extends ll{constructor(){super(...arguments),e(this,"_ifcMaterialEntities",[/^IFCMATERIALLAYERSETUSAGE$/,/^IFCMATERIALCONSTITUENTSET$/,/^IFCMATERIAL$/,/^IFCMATERIALLIST$/]),e(this,"facetType","Material"),e(this,"value"),e(this,"uri")}serialize(t){if(!this.value||!this.uri)return"<material />";const e=cl("Value",this.value);let i="";return"requirement"===t&&(i+=`cardinality="${this.cardinality}"`,i+=this.uri?`uri=${this.uri}`:"",i+=this.instructions?`instructions="${this.instructions}"`:""),`<material ${i}>\n ${e}\n</material>`}async getEntities(t,e){const i=this._components.get(fr);for(const[n,s]of i.list){if(!t.find((t=>t.test(n))))continue;const i=await s.getItemsOfCategories(this._ifcMaterialEntities),r=Object.values(i).flat();if(0===r.length)continue;const o=await s.getItemsData(r,{relations:{AssociatedTo:{attributes:!0,relations:!1},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const t of o){if(!("value"in t._localId&&"value"in t._category&&Array.isArray(t.AssociatedTo)))continue;if(!this.hasValidMaterial(t))continue;const i=t.AssociatedTo.map((t=>"value"in t._localId&&t._localId.value?t._localId.value:null)).filter((t=>null!==t));ai.append(e,n,...i)}}}async test(t,e,i={skipIfFails:!0}){const n=this._components.get(fr);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([[...r][0]],{relations:{AssociatedTo:{attributes:!1,relations:!1},HasAssociations:{attributes:!0,relations:!0},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const t of o){const n=this.getItemChecks(e,s,t,i.skipIfFails);if(n)if(Array.isArray(t.HasAssociations))for(const e of t.HasAssociations){if(!this._ifcMaterialEntities.some((t=>"value"in e._category&&t.test(e._category.value))))continue;if(this.hasValidMaterial(e,n))break}else n.push({parameter:null,currentValue:null,requiredValue:this.value,pass:!1})}}}hasValidMaterial(t,e){let i=!1;if("value"in t._category&&"IFCMATERIAL"===t._category.value){this.evalValue(t,e)&&(i=!0)}else for(const[n,s]of Object.entries(t))if(["ForLayerSet","MaterialLayers","Material","MaterialConstituents","Materials"].includes(n)&&Array.isArray(s))for(const t of s){if("value"in t._category&&"IFCMATERIAL"===t._category.value){if(this.evalValue(t,e)){i=!0;break}}else{if(this.hasValidMaterial(t)){i=!0;break}}}return i}evalValue(t,e){if(!this.value)return null==e||e.push({parameter:null,currentValue:t.Name&&"value"in t.Name?t.Name.value:null,pass:!0}),!0;if(!("value"in t._category)||"IFCMATERIAL"!==t._category.value)return null;let i=!1;return t.Name&&"value"in t.Name&&(i=this.evalRequirement(t.Name.value,this.value,"Value",e)),i||(t.Category&&"value"in t.Category&&(i=this.evalRequirement(t.Category.value,this.value,"Value",e)),i)}}class ml extends ll{constructor(t,i){super(t),e(this,"facetType","PartOf"),e(this,"_entityFacet"),e(this,"_entity"),e(this,"relation"),e(this,"cardinality","required"),this._entity=i,this._entityFacet=new dl(t,i.name),this._entityFacet.predefinedType=i.predefinedType}set entity(t){this._entity=t;const{name:e,predefinedType:i}=t;this._entityFacet=new dl(this._components,e),this._entityFacet.predefinedType=i}get entity(){return this._entity}serialize(){return""}async getEntities(t,e){}async test(t){}}class gl{constructor(t,n,s){e(this,"name"),e(this,"ifcVersion",new Set),e(this,"identifier",_t.create()),e(this,"description"),e(this,"instructions"),e(this,"requirementsDescription"),e(this,"applicability",new i.DataSet),e(this,"requirements",new i.DataSet),e(this,"components"),this.components=t,this.name=n;for(const t of s)this.ifcVersion.add(t)}set(t){const e=t,i=this;for(const n in t){if("identifier"===n)continue;const t=e[n];n in this&&(i[n]=t)}return this.components.get(Al).list.set(this.identifier,this),this}async test(t,e={skipIfFails:!0}){const n=new i.DataMap;if(0===this.requirements.size)return n;const s={},r=[];for(const e of this.applicability)r.push(e.getEntities(t,s));await Promise.all(r);const o=[];for(const t of this.requirements)o.push(t.test(s,n,e));return await Promise.all(o),n}serialize(){const t=`name="${this.name}"`,e=this.identifier?`identifier="${this.identifier}"`:"",i=this.description?`description="${this.description}"`:"",n=this.instructions?`instructions="${this.instructions}"`:"";return`<specification ifcVersion="${[...this.ifcVersion].join(" ")}" ${t} ${e} ${i} ${n}>\n <applicability minOccurs="1" maxOccurs="unbounded">\n ${[...this.applicability].map((t=>t.serialize("applicability"))).join("\n")}\n </applicability>\n <requirements>\n ${[...this.requirements].map((t=>t.serialize("requirement"))).join("\n")}\n </requirements>\n </specification>`}}const wl=t=>{if(!t)return;const e={};if("simpleValue"in t&&(e.type="simple",e.parameter=t.simpleValue),"restriction"in t){const i=t.restriction,n=Object.keys(i);if("pattern"in i&&(e.type="pattern",e.parameter=i.pattern.value),"enumeration"in i){e.type="enumeration";const t=i.enumeration.map((({value:t})=>i.base.includes("string")?String(t):i.base.includes("integer")||i.base.includes("double")?Number(t):t));e.parameter=t}if(n.some((t=>["minInclusive","minExclusive","maxInclusive","maxExclusive"].includes(t)))){e.type="bounds";const t={},s=n.find((t=>t.includes("min"))),r=n.find((t=>t.includes("max")));s&&(t.minInclusive="minInclusive"===s,t.min=i[s].value),r&&(t.maxInclusive="maxInclusive"===r,t.max=i[r].value),e.parameter=t}if(n.some((t=>["minLength","length","maxLength"].includes(t)))){e.type="length";const t={};void 0!==i.length&&(t.length=i.length.value),void 0!==i.minLength&&(t.min=i.minLength.value),void 0!==i.maxLength&&(t.max=i.maxLength.value),e.parameter=t}}return void 0!==e.parameter?e:void 0},yl=(t,e)=>{const i=[];for(const n of e){const e=n.name,s=wl(e);if(!s)continue;const r=new dl(t,s);n.cardinality&&(r.cardinality=n.cardinality),r.predefinedType=wl(n.predefinedType),r.instructions=n.instructions,i.push(r)}return i},_l=(t,e)=>{const i=[];for(const n of e){const e=n.name,s=wl(e);if(!s)continue;const r=new hl(t,s);n.cardinality&&(r.cardinality=n.cardinality),r.value=wl(n.value),r.instructions=n.instructions,i.push(r)}return i},bl=(t,e)=>{const i=[];for(const n of e){const e=new fl(t);n.cardinality&&(e.cardinality=n.cardinality);const s=wl(n.value);"enumeration"===(null==s?void 0:s.type)&&Array.isArray(s.parameter)&&(s.parameter=s.parameter.map(String)),e.value=s,e.uri=n.uri,e.instructions=n.instructions,i.push(e)}return i},vl=(t,e)=>{const i=[];for(const n of e){const e=n.propertySet,s=n.baseName,r=wl(e),o=wl(s);if(!o||!r)continue;const a=new pl(t,r,o);n.cardinality&&(a.cardinality=n.cardinality);const l=wl(n.value);a.value=l,a.dataType=n.dataType,a.uri=n.uri,a.instructions=n.instructions,i.push(a)}return i},xl=(t,e)=>{const i=[];for(const n of e){const e=n.system,s=wl(e);if(!s)continue;const r=new ul(t,s);n.cardinality&&(r.cardinality=n.cardinality);const o=wl(n.value);"simple"===(null==o?void 0:o.type)&&(o.parameter=String(o.parameter)),"enumeration"===(null==o?void 0:o.type)&&Array.isArray(o.parameter)&&(o.parameter=o.parameter.map(String)),r.value=o,r.uri=n.uri,r.instructions=n.instructions,i.push(r)}return i},Cl=(t,e)=>{const i=[];for(const n of e){const e=wl(n.entity.name);if(!e)continue;const s=wl(n.entity.predefinedType),r=new ml(t,{name:e,predefinedType:s});r.relation=n.relation,n.cardinality&&(r.cardinality=n.cardinality),r.instructions=n.instructions,i.push(r)}return i},Sl=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"IDSInfo"),e(this,"list",new n),i.add(t.uuid,this)}getModelIdMap(t){const e={},i={};for(const[n,s]of t){const t=[...s].filter((([,t])=>t.pass)).map((([t])=>t));ai.append(e,n,...t);const r=[...s].filter((([,t])=>!t.pass)).map((([t])=>t));ai.append(i,n,...r)}return{pass:e,fail:i}}create(t,e,i){const n=new gl(this.components,t,e);return i&&(n.identifier=i),this.list.set(n.identifier,n),n}load(e){const i=[],n=t.xmlParser.parse(e).ids,{specifications:s,info:r}=n;if(this.IDSInfo={...r},s&&s.specification){const t=Array.isArray(s.specification)?s.specification:[s.specification];for(const e of t){const{name:t,ifcVersion:n,description:s,instructions:r,identifier:o}=e;if(!t||!n)continue;const a=[],l=[],{applicability:c,requirements:h}=e;if(c){const{maxOccurs:t,...e}=c,i=Array.isArray(e)?e:[e];for(const t of i)for(const e in t){const i=Array.isArray(t[e])?t[e]:[t[e]];if("entity"===e){const t=yl(this.components,i);a.push(...t)}if("attribute"===e){const t=_l(this.components,i);a.push(...t)}if("material"===e){const t=bl(this.components,i);a.push(...t)}if("classification"===e){const t=xl(this.components,i);a.push(...t)}if("property"===e){const t=vl(this.components,i);a.push(...t)}if("partOf"===e){const t=Cl(this.components,i);a.push(...t)}}}let u;if(h){const{maxOccurs:t,...e}=h;u=h.description;const i=Array.isArray(e)?e:[e];for(const t of i)for(const e in t){const i=Array.isArray(t[e])?t[e]:[t[e]];if("entity"===e){const t=yl(this.components,i);l.push(...t)}if("attribute"===e){const t=_l(this.components,i);l.push(...t)}if("material"===e){const t=bl(this.components,i);l.push(...t)}if("classification"===e){const t=xl(this.components,i);l.push(...t)}if("property"===e){const t=vl(this.components,i);l.push(...t)}if("partOf"===e){const t=Cl(this.components,i);l.push(...t)}}}const d=this.create(t,n.split(/\s+/),o);d.description=s,d.instructions=r,d.requirementsDescription=u,d.applicability.add(...a),d.requirements.add(...l),i.push(d)}}return i}export(t,e=this.list.values()){const i=e??this.list;return`<ids xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://standards.buildingsmart.org/IDS http://standards.buildingsmart.org/IDS/1.0/ids.xsd" xmlns:ids="http://standards.buildingsmart.org/IDS">\n \x3c!-- Made with That Open Engine ${Ia.release} (https://github.com/thatopen/engine_components) --\x3e\n <info>\n <title>${t.title}</title>\n ${t.copyright?`<copyright>${t.copyright}</copyright>`:""}\n ${t.version?`<version>${t.version}</version>`:""}\n ${t.description?`<description>${t.description}</description>`:""}\n ${t.author?`<author>${t.author}</author>`:""}\n ${t.date?`<date>${t.date.toISOString().split("T")[0]}</date>`:""}\n ${t.purpose?`<purpose>${t.purpose}</purpose>`:""}\n ${t.milestone?`<milestone>${t.milestone}</milestone>`:""}\n </info>\n <specifications>\n ${[...i].map((t=>t.serialize())).join("\n")}\n </specifications>\n</ids>`}};e(Sl,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c"),e(Sl,"xmlParser",new We({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let Al=Sl;const Pl=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),i.add(t.uuid,this)}static distanceFromPointToLine(t,e,i,n=!1){const s=new o.Line3,r=new o.Vector3;return s.set(e,i),s.closestPointToPoint(t,n,r),r.distanceTo(t)}round(t){const e=1e3;t.x=Math.trunc(t.x*e)/e,t.y=Math.trunc(t.y*e)/e,t.z=Math.trunc(t.z*e)/e}async getVolumeFromFragments(t){return console.warn("getVolumeFromFragments is deprecated. Use getItemsVolume instead."),this.getItemsVolume(t)}async getItemsVolume(t){let e=0;const i=this.components.get(fr);for(const[n,s]of Object.entries(t)){const t=i.list.get(n);t&&(e+=await t.getItemsVolume([...s]))}return e}static convertUnits(t,e,i,n=2){const s={m:1,cm:.01,mm:.001,km:1e3,m2:1,cm2:1e-4,mm2:1e-6,km2:1e6,m3:1,cm3:1e-6,mm3:1e-9,km3:1e9};if(!s[e]||!s[i])throw new Error("Invalid units provided for conversion.");if(!Number.isInteger(n)||n<0||n>5)throw new Error("Precision must be an integer between 0 and 5.");const r=t*(s[e]/s[i]),o=10**n;return Math.round(r*o)/o}};e(Pl,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");let Tl=Pl;const El=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=new o.Vector3(e.x+n.x,0,e.z+n.z).normalize().multiplyScalar(i/2);return[t.x+s.x,t.y,t.z+s.z,t.x-s.x,t.y,t.z-s.z]},Ml=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=t.x-e.x*i+n.x*i*.4,r=t.z-e.z*i+n.z*i*.4,a=t.x-e.x*i-n.x*i*.4,l=t.z-e.z*i-n.z*i*.4;return[t.x,t.y,t.z,s,t.y,r,t.x,t.y,t.z,a,t.y,l,s,t.y,r,a,t.y,l]},Il=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=t.x-e.x*i+n.x*i*.4,r=t.z-e.z*i+n.z*i*.4,a=t.x-e.x*i-n.x*i*.4,l=t.z-e.z*i-n.z*i*.4;return[t.x,t.y,t.z,s,t.y,r,t.x,t.y,t.z,a,t.y,l]},zl=()=>[],Dl=(t,e,i)=>{const n=.4*i,s=[];for(let e=0;e<12;e++){const i=e/12*Math.PI*2,r=(e+1)/12*Math.PI*2;s.push(t.x+Math.cos(i)*n,t.y,t.z+Math.sin(i)*n,t.x+Math.cos(r)*n,t.y,t.z+Math.sin(r)*n)}return s},kl=(t,e,i)=>{const n=.4*i,s=[];for(let e=0;e<16;e++){const i=e/16*Math.PI*2,r=(e+1)/16*Math.PI*2;s.push(t.x,t.y,t.z,t.x+Math.cos(i)*n,t.y,t.z+Math.sin(i)*n,t.x+Math.cos(r)*n,t.y,t.z+Math.sin(r)*n)}return s},Bl=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=.4*i,r=t.clone().addScaledVector(e,s).addScaledVector(n,s),a=t.clone().addScaledVector(e,s).addScaledVector(n,-s),l=t.clone().addScaledVector(e,-s).addScaledVector(n,-s),c=t.clone().addScaledVector(e,-s).addScaledVector(n,s);return[r.x,r.y,r.z,a.x,a.y,a.z,l.x,l.y,l.z,r.x,r.y,r.z,l.x,l.y,l.z,c.x,c.y,c.z]},Ol=(t,e,i)=>{const n=new o.Vector3(-e.z,0,e.x),s=t.clone().addScaledVector(e,-i),r=s.clone().addScaledVector(n,.4*i),a=s.clone().addScaledVector(n,.4*-i);return[t.x,t.y,t.z,r.x,r.y,r.z,a.x,a.y,a.z]};class Nl extends i.DataMap{constructor(){super()}getBySystem(t){const e=new Map;for(const[i,n]of this)n.system===t&&e.set(i,n.data);return e}}class Vl extends i.DataMap{constructor(t){super(),e(this,"_container"),this._container=t,this.deleteGuard=t=>"0"!==t,this.set("0",{name:"0",visible:!0,material:new o.LineBasicMaterial({color:0})})}create(t,e){if(!this.has(t)){const i={name:t,visible:(null==e?void 0:e.visible)??!0,material:(null==e?void 0:e.material)??new o.LineBasicMaterial({color:0})};this.set(t,i)}return this.get(t)}setColor(t,e){const i=this.get(t);i&&(i.material.color.setHex(e),this.set(t,i))}setMaterial(t,e){const i=this.get(t);if(!i)return;const n=i.material;i.material=e,this._container.traverse((i=>{i.userData.layer===t&&(i.userData.isDimension||i.isLineSegments&&(i.material=e))})),n.dispose(),this.set(t,i)}setVisibility(t,e){const i=this.get(t);i&&(i.visible=e,this._container.traverse((i=>{i.userData.layer===t&&(i.visible=e)})),this.set(t,i))}assign(t,e){const i=this.get(e);i&&(t.userData.layer=e,i.visible||(t.visible=!1),t.isLineSegments&&(t.material=i.material))}resolveColor(t){const e=this.get(t);if(e)return e.material.color.getHex()}}const Ll=class t extends o.Group{constructor(i){super(),e(this,"_viewport"),e(this,"_border"),e(this,"_handles",[]),e(this,"_raycaster",new o.Raycaster),e(this,"_resizable",!1),e(this,"_movable",!1),e(this,"_dragHandle",null),e(this,"_dragConstraints",[]),e(this,"_hoveredHandle",null),e(this,"_moveDrag",null),e(this,"_hoveringBorder",!1),e(this,"_normalMat"),e(this,"_hoverMat"),e(this,"_borderMat"),this._viewport=i,this._borderMat=new o.LineBasicMaterial({color:t._BORDER_COLOR,depthTest:!1});const n=new o.BufferGeometry;n.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._border=new o.LineSegments(n,this._borderMat),this._border.renderOrder=999,this._border.frustumCulled=!1,this._border.userData.isDimension=!0,this.add(this._border),this._normalMat=new o.MeshBasicMaterial({color:t._BORDER_COLOR}),this._hoverMat=new o.MeshBasicMaterial({color:t._BORDER_HOVER_COLOR});const s=new o.SphereGeometry(.05,8,6);for(const e of t._HANDLE_DEFS){const t=new o.Mesh(s,this._normalMat);t.renderOrder=1e3,t.visible=!1,t.userData.constraints=e.constraints,t.userData.isDimension=!0,this.add(t),this._handles.push(t)}this.update()}get resizable(){return this._resizable}set resizable(t){this._resizable=t;for(const e of this._handles)e.visible=t;t||(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat,this._hoveredHandle=null),this._dragHandle=null,this._dragConstraints=[])}get movable(){return this._movable}set movable(t){this._movable=t,t||(this._moveDrag=null,this._setBorderHover(!1))}get isDragging(){return null!==this._dragHandle||null!==this._moveDrag}update(){const t=this._viewport,e=t.left,i=t.right,n=-t.top,s=-t.bottom,r=.005,o=this._border.geometry.attributes.position;o.setXYZ(0,e,r,n),o.setXYZ(1,i,r,n),o.setXYZ(2,i,r,n),o.setXYZ(3,i,r,s),o.setXYZ(4,i,r,s),o.setXYZ(5,e,r,s),o.setXYZ(6,e,r,s),o.setXYZ(7,e,r,n),o.needsUpdate=!0,this._border.geometry.computeBoundingSphere();const a=(e+i)/2,l=(n+s)/2,c=.01,h=[[e,c,n],[i,c,n],[i,c,s],[e,c,s],[a,c,n],[i,c,l],[a,c,s],[e,c,l]];for(let t=0;t<this._handles.length;t++)this._handles[t].position.set(...h[t])}onPointerMove(e){if(this._dragHandle){const t=this._projectToLocal(e);if(!t)return;for(const e of this._dragConstraints)switch(e){case"left":this._viewport.left=t.x;break;case"right":this._viewport.right=t.x;break;case"top":this._viewport.top=-t.z;break;case"bottom":this._viewport.bottom=-t.z}return this._viewport.right<this._viewport.left&&([this._viewport.left,this._viewport.right]=[this._viewport.right,this._viewport.left],this._dragConstraints=this._dragConstraints.map((t=>"right"===t?"left":"left"===t?"right":t))),this._viewport.top<this._viewport.bottom&&([this._viewport.top,this._viewport.bottom]=[this._viewport.bottom,this._viewport.top],this._dragConstraints=this._dragConstraints.map((t=>"top"===t?"bottom":"bottom"===t?"top":t))),void this.update()}if(this._moveDrag){const t=this._projectToLocal(e);if(!t)return;const i=t.x-this._moveDrag.origin.x,n=t.z-this._moveDrag.origin.z;return this._viewport.left=this._moveDrag.left0+i,this._viewport.right=this._moveDrag.right0+i,this._viewport.top=this._moveDrag.top0-n,this._viewport.bottom=this._moveDrag.bottom0-n,void this.update()}if(!this._resizable&&!this._movable)return;this._raycaster.set(e.origin,e.direction);let i=null;if(this._resizable){const t=this._handles.filter((t=>t.visible)),e=this._raycaster.intersectObjects(t,!1);i=e.length>0?e[0].object:null}if(i!==this._hoveredHandle&&(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat),i&&(i.material=this._hoverMat),this._hoveredHandle=i),this._movable&&!this._hoveredHandle){this._raycaster.params.Line={threshold:t._LINE_THRESHOLD};const e=this._raycaster.intersectObject(this._border,!1).length>0;this._setBorderHover(e)}else this._setBorderHover(!1)}onPointerDown(e){if(this._resizable||this._movable){if(this._raycaster.set(e.origin,e.direction),this._resizable){const t=this._handles.filter((t=>t.visible)),e=this._raycaster.intersectObjects(t,!1);if(e.length>0)return this._dragHandle=e[0].object,void(this._dragConstraints=[...this._dragHandle.userData.constraints])}if(this._movable){this._raycaster.params.Line={threshold:t._LINE_THRESHOLD};if(this._raycaster.intersectObject(this._border,!1).length>0){const t=this._projectToLocal(e);if(!t)return;this._moveDrag={origin:t,left0:this._viewport.left,right0:this._viewport.right,top0:this._viewport.top,bottom0:this._viewport.bottom}}}}}onPointerUp(){this._dragHandle=null,this._dragConstraints=[],this._moveDrag=null}dispose(){this._border.geometry.dispose(),this._borderMat.dispose(),this._normalMat.dispose(),this._hoverMat.dispose(),this._handles.length>0&&this._handles[0].geometry.dispose(),this.removeFromParent()}_projectToLocal(t){this.updateWorldMatrix(!0,!1);const e=new o.Vector3(0,1,0).transformDirection(this.matrixWorld),i=(new o.Vector3).setFromMatrixPosition(this.matrixWorld),n=(new o.Plane).setFromNormalAndCoplanarPoint(e,i),s=new o.Vector3;return t.intersectPlane(n,s)?this.worldToLocal(s):null}_setBorderHover(e){e!==this._hoveringBorder&&(this._hoveringBorder=e,this._borderMat.color.setHex(e?t._BORDER_HOVER_COLOR:t._BORDER_COLOR))}};e(Ll,"_BORDER_COLOR",22015),e(Ll,"_BORDER_HOVER_COLOR",16746496),e(Ll,"_LINE_THRESHOLD",.06),e(Ll,"_HANDLE_DEFS",[{constraints:["left","top"]},{constraints:["right","top"]},{constraints:["right","bottom"]},{constraints:["left","bottom"]},{constraints:["top"]},{constraints:["right"]},{constraints:["bottom"]},{constraints:["left"]}]);let Fl=Ll;class Rl{constructor(t){e(this,"uuid",o.MathUtils.generateUUID()),e(this,"name"),e(this,"camera"),e(this,"onDisposed",new at),e(this,"_left"),e(this,"_right"),e(this,"_top"),e(this,"_bottom"),e(this,"_drawingScale"),e(this,"_container",null),e(this,"_helper",null),e(this,"_helperVisible",!1),this._left=t.left,this._right=t.right,this._top=t.top,this._bottom=t.bottom,this._drawingScale=t.scale??100,this.name=t.name??"Drawing Viewport",this.camera=new o.OrthographicCamera(this._left,this._right,this._top,this._bottom,.1,30),this.camera.up.set(0,0,-1),this.camera.position.set(0,10,0),this.camera.lookAt(0,0,0),this.camera.layers.set(1)}get left(){return this._left}set left(t){var e;this._left=t,this.camera.left=t,this.camera.updateProjectionMatrix(),null==(e=this._helper)||e.update()}get right(){return this._right}set right(t){var e;this._right=t,this.camera.right=t,this.camera.updateProjectionMatrix(),null==(e=this._helper)||e.update()}get top(){return this._top}set top(t){var e;this._top=t,this.camera.top=t,this.camera.updateProjectionMatrix(),null==(e=this._helper)||e.update()}get bottom(){return this._bottom}set bottom(t){var e;this._bottom=t,this.camera.bottom=t,this.camera.updateProjectionMatrix(),null==(e=this._helper)||e.update()}get drawingScale(){return this._drawingScale}set drawingScale(t){this._drawingScale=t}get helper(){return this._helper||(this._helper=new Fl(this)),this._helper}get helperVisible(){return this._helperVisible}set helperVisible(t){var e,i;this._helperVisible=t,t?null==(e=this._container)||e.add(this.helper):null==(i=this._helper)||i.removeFromParent()}get bbox(){const t=new o.Vector3(this._left,0,-this._top),e=new o.Vector3(this._right,0,-this._bottom);return new o.Box3(t,e)}get size(){const t=new o.Vector3;return this.bbox.getSize(t),new o.Vector2(1e3*t.x,1e3*t.z)}get localXAxis(){return new o.Vector3(1,0,0)}get localYAxis(){return new o.Vector3(0,0,-1)}get normal(){return new o.Vector3(0,1,0)}setContainer(t){this._container=t,this._helperVisible&&this._helper&&t.add(this._helper)}clipLine(t){const e=this.bbox,{start:i,end:n}=t,s=e.containsPoint(i),r=e.containsPoint(n);if(s&&r)return t;if(!s&&!r){const e=this.getPlaneIntersections(t);return e.length<2?null:new o.Line3(e[0],e[1])}const a=this.getPlaneIntersections(t);return 0===a.length?null:s?new o.Line3(i,a[0]):new o.Line3(a[0],n)}dispose(){var t;null==(t=this._helper)||t.dispose(),this._helper=null,this.onDisposed.trigger(),this.onDisposed.reset()}get bboxPlanes(){const t=this.bbox;return[new o.Plane(new o.Vector3(1,0,0),-t.min.x),new o.Plane(new o.Vector3(-1,0,0),t.max.x),new o.Plane(new o.Vector3(0,0,1),-t.min.z),new o.Plane(new o.Vector3(0,0,-1),t.max.z)]}getPlaneIntersections(t){const e=[];for(const i of this.bboxPlanes){const n=new o.Vector3;i.intersectLine(t,n)&&this.bbox.containsPoint(n)&&e.push(n)}return e}}class Ul extends i.DataMap{constructor(t){super(),e(this,"_container"),this._container=t,this.onBeforeDelete.add((({value:t})=>{this._container.remove(t.camera),t.dispose()}))}create(t){const e=new Rl(t);return this._container.add(e.camera),e.setContainer(this._container),this.set(e.uuid,e),e}}const jl=class t extends o.Group{constructor(i){super(),e(this,"_drawing"),e(this,"_topFrame"),e(this,"_pillars"),e(this,"_bottomFrame"),e(this,"_topPlane"),e(this,"_bottomPlane"),e(this,"_frameMat"),e(this,"_depthMat"),e(this,"_planeMat"),e(this,"width",10),e(this,"height",10),e(this,"farHandle",new o.Object3D),e(this,"widthHandle",new o.Object3D),e(this,"heightHandle",new o.Object3D),this._drawing=i,this._frameMat=new o.LineBasicMaterial({color:t._FRAME_COLOR,depthTest:!1}),this._depthMat=new o.LineBasicMaterial({color:t._DEPTH_COLOR,depthTest:!1,transparent:!0,opacity:.4}),this._planeMat=new o.MeshBasicMaterial({color:t._FRAME_COLOR,transparent:!0,opacity:.07,side:o.DoubleSide,depthTest:!1});const n=()=>{const t=new o.BufferGeometry;return t.setAttribute("position",new o.BufferAttribute(new Float32Array(12),3)),t.setIndex([0,1,2,0,2,3]),t};this._topPlane=new o.Mesh(n(),this._planeMat),this._topPlane.renderOrder=998,this._topPlane.frustumCulled=!1,this._topPlane.userData.isDimension=!0,this._bottomPlane=new o.Mesh(n(),this._planeMat),this._bottomPlane.renderOrder=998,this._bottomPlane.frustumCulled=!1,this._bottomPlane.userData.isDimension=!0;const s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._topFrame=new o.LineSegments(s,this._frameMat),this._topFrame.renderOrder=999,this._topFrame.frustumCulled=!1,this._topFrame.userData.isDimension=!0;const r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._pillars=new o.LineSegments(r,this._depthMat),this._pillars.renderOrder=999,this._pillars.frustumCulled=!1,this._pillars.userData.isDimension=!0;const a=new o.BufferGeometry;a.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._bottomFrame=new o.LineSegments(a,this._depthMat),this._bottomFrame.renderOrder=999,this._bottomFrame.frustumCulled=!1,this._bottomFrame.userData.isDimension=!0,this.add(this._topPlane,this._bottomPlane),this.add(this._topFrame,this._pillars,this._bottomFrame),this.add(this.farHandle,this.widthHandle,this.heightHandle),this.farHandle.rotation.x=Math.PI,this.update()}update(){const t=this.width/2,e=this.height/2,i=-this._drawing.far,n=.005,s=-t,r=t,o=-e,a=e,l=this._topFrame.geometry.attributes.position;l.setXYZ(0,s,n,o),l.setXYZ(1,r,n,o),l.setXYZ(2,r,n,o),l.setXYZ(3,r,n,a),l.setXYZ(4,r,n,a),l.setXYZ(5,s,n,a),l.setXYZ(6,s,n,a),l.setXYZ(7,s,n,o),l.needsUpdate=!0,this._topFrame.geometry.computeBoundingSphere();const c=this._pillars.geometry.attributes.position;c.setXYZ(0,s,n,o),c.setXYZ(1,s,i,o),c.setXYZ(2,r,n,o),c.setXYZ(3,r,i,o),c.setXYZ(4,r,n,a),c.setXYZ(5,r,i,a),c.setXYZ(6,s,n,a),c.setXYZ(7,s,i,a),c.needsUpdate=!0,this._pillars.geometry.computeBoundingSphere();const h=this._bottomFrame.geometry.attributes.position;h.setXYZ(0,s,i,o),h.setXYZ(1,r,i,o),h.setXYZ(2,r,i,o),h.setXYZ(3,r,i,a),h.setXYZ(4,r,i,a),h.setXYZ(5,s,i,a),h.setXYZ(6,s,i,a),h.setXYZ(7,s,i,o),h.needsUpdate=!0,this._bottomFrame.geometry.computeBoundingSphere();const u=(t,e)=>{const i=t.geometry.attributes.position;i.setXYZ(0,s,e,o),i.setXYZ(1,r,e,o),i.setXYZ(2,r,e,a),i.setXYZ(3,s,e,a),i.needsUpdate=!0,t.geometry.computeBoundingSphere()};u(this._topPlane,n),u(this._bottomPlane,i),this.farHandle.position.set(0,i,0),this.widthHandle.position.set(r,n,0),this.heightHandle.position.set(0,n,a)}attachFarGizmo(t){t.attach(this.farHandle),t.setSpace("local"),t.showX=!1,t.showZ=!1,t.addEventListener("objectChange",(()=>{this.farHandle.position.x=0,this.farHandle.position.z=0;const t=Math.max(.1,-this.farHandle.position.y);this._drawing.far=t,this.farHandle.position.y=-t,this.update()}))}attachWidthGizmo(t){t.attach(this.widthHandle),t.setSpace("local"),t.showY=!1,t.showZ=!1,t.addEventListener("objectChange",(()=>{this.widthHandle.position.y=.005,this.widthHandle.position.z=0,this.width=Math.max(.1,2*this.widthHandle.position.x),this.widthHandle.position.x=this.width/2,this.update()}))}attachHeightGizmo(t){t.attach(this.heightHandle),t.setSpace("local"),t.showX=!1,t.showY=!1,t.addEventListener("objectChange",(()=>{this.heightHandle.position.x=0,this.heightHandle.position.y=.005,this.height=Math.max(.1,2*this.heightHandle.position.z),this.heightHandle.position.z=this.height/2,this.update()}))}dispose(){this._topPlane.geometry.dispose(),this._bottomPlane.geometry.dispose(),this._topFrame.geometry.dispose(),this._pillars.geometry.dispose(),this._bottomFrame.geometry.dispose(),this._planeMat.dispose(),this._frameMat.dispose(),this._depthMat.dispose(),this.removeFromParent()}};e(jl,"_FRAME_COLOR",22015),e(jl,"_DEPTH_COLOR",22015);let $l=jl;function Wl(t,e){if(3!==t.length||3!==e.length)throw new Error("computeAlignmentMatrix requires exactly 3 point pairs.");const i=(t,e)=>{const i=(new o.Vector3).subVectors(t[1],t[0]),n=(new o.Vector3).subVectors(t[2],t[0]);if((new o.Vector3).crossVectors(i,n).length()<1e-6)throw new Error(`${e} points are collinear — three non-collinear points are required to define a plane.`)};i(t,"Drawing"),i(e,"World");const n=(t,e,i)=>{const n=(new o.Vector3).subVectors(e,t),s=(new o.Vector3).subVectors(i,t),r=n.clone().normalize(),a=(new o.Vector3).crossVectors(n,s).normalize(),l=(new o.Vector3).crossVectors(r,a).normalize();return(new o.Matrix4).makeBasis(r,a,l)},s=n(t[0],t[1],t[2]),r=n(e[0],e[1],e[2]).clone().multiply(s.clone().invert()),a=t[0].distanceTo(t[1]);if(a<1e-10)throw new Error("The first two drawing points are coincident — cannot compute scale.");const l=e[0].distanceTo(e[1])/a,c=t[0].clone().multiplyScalar(l).applyMatrix4(r),h=(new o.Vector3).subVectors(e[0],c),u=(new o.Quaternion).setFromRotationMatrix(r),d=new o.Matrix4;return d.compose(h,u,new o.Vector3(l,l,l)),d}class Gl{constructor(t){e(this,"uuid",o.MathUtils.generateUUID()),e(this,"_raycaster",new o.Raycaster),e(this,"_components"),e(this,"world",null),e(this,"three",new o.Group),e(this,"annotations",new Nl),e(this,"layers",new Vl(this.three)),e(this,"activeLayer","0"),e(this,"far",10),e(this,"viewports",new Ul(this.three)),e(this,"onDisposed",new at),this._components=t}raycast(t,e=null){this._raycaster.set(t.origin,t.direction),this._raycaster.layers.set(1),this._raycaster.params.Line&&(this._raycaster.params.Line.threshold=.1);const i=[];this.three.traverse((t=>{t instanceof o.LineSegments&&!t.userData.isDimension&&i.push(t)}));const n=this._raycaster.intersectObjects(i,!1);if(0===n.length)return null;const s=n[0],r=this.three.worldToLocal(s.point.clone());let a=null;if(s.object instanceof o.LineSegments&&void 0!==s.index){const t=s.object.geometry.attributes.position,e=s.index,i=new o.Vector3(t.getX(e),t.getY(e),t.getZ(e)),n=new o.Vector3(t.getX(e+1),t.getY(e+1),t.getZ(e+1));i.applyMatrix4(s.object.matrixWorld),this.three.worldToLocal(i),n.applyMatrix4(s.object.matrixWorld),this.three.worldToLocal(n),a=new o.Line3(i,n)}return{point:r,object:s.object,viewport:e,line:a}}alignTo(t,e){Wl(t,e).decompose(this.three.position,this.three.quaternion,this.three.scale)}static toDrawingSpace(t,e){t.updateWorldMatrix(!0,!1),e.three.updateWorldMatrix(!0,!1);const i=(new o.Matrix4).copy(e.three.matrixWorld).invert().multiply(t.matrixWorld),n=t.geometry.attributes.position,s=n.count,r=new Float32Array(3*s),a=new o.Vector3;for(let t=0;t<s;t++)a.fromBufferAttribute(n,t).applyMatrix4(i),r[3*t]=a.x,r[3*t+1]=0,r[3*t+2]=a.z;const l=new o.BufferGeometry;return l.setAttribute("position",new o.BufferAttribute(r,3)),new o.LineSegments(l)}addProjectionLines(t,e="0"){return this.layers.has(e)||(console.warn(`[TechnicalDrawing] Layer "${e}" does not exist. Falling back to "0".`),e="0"),this.layers.assign(t,e),t.layers.set(1),t.material instanceof o.LineDashedMaterial&&t.computeLineDistances(),t.geometry.computeBoundsTree({strategy:0,indirect:!0,type:sr}),this.three.add(t),t}async addProjectionFromItems(t,e){if(!this.world)return void console.warn("[TechnicalDrawing] addProjectionFromItems: drawing has no world assigned.");for(const t of[e.layers.visible,e.layers.hidden])if(!this.layers.has(t))return void console.warn(`[TechnicalDrawing] Layer "${t}" does not exist — create it before calling addProjectionFromItems.`);const i=this._components.get(zo),n=i.projectionDirection.clone(),s=i.nearPlane,r=i.farPlane;try{this.three.updateWorldMatrix(!0,!1);const n=new o.Vector3(0,-1,0).transformDirection(this.three.matrixWorld).normalize();i.projectionDirection.copy(n);const s=(new o.Matrix4).makeRotationFromQuaternion((new o.Quaternion).setFromUnitVectors(n,new o.Vector3(0,-1,0))),r=(new o.Vector3).setFromMatrixPosition(this.three.matrixWorld).applyMatrix4(s).y;i.farPlane=r,i.nearPlane=r-this.far;const a=await i.get(t,this.world,{onProgress:e.onProgress}),l=t=>Gl.toDrawingSpace(new o.LineSegments(t),this);this.addProjectionLines(l(a.visible),e.layers.visible),this.addProjectionLines(l(a.hidden),e.layers.hidden)}finally{i.projectionDirection.copy(n),i.nearPlane=s,i.farPlane=r}}orientTo(t){const e=t.clone().normalize(),i=Math.SQRT1_2;e.x>.999?this.three.quaternion.set(.5,-.5,.5,.5):e.x<-.999?this.three.quaternion.set(.5,.5,-.5,.5):e.y>.999?this.three.quaternion.set(0,0,1,0):e.y<-.999?this.three.quaternion.set(0,0,0,1):e.z>.999?this.three.quaternion.set(0,i,-i,0):e.z<-.999?this.three.quaternion.set(i,0,0,i):console.warn("[TechnicalDrawing] orientTo: direction does not match any of the 6 standard axes.")}dispose(){this.viewports.clear(),this.layers.clear(),this.annotations.clear();this._components.get(mt).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset()}}const Hl={m:{factor:1,suffix:"m"},cm:{factor:100,suffix:"cm"},mm:{factor:1e3,suffix:"mm"},ft:{factor:3.28084,suffix:"ft"},in:{factor:39.3701,suffix:"in"}};class Zl{constructor(t){e(this,"styles",new i.DataMap),e(this,"activeStyle","default"),e(this,"onCommit",new at),e(this,"onUpdate",new at),e(this,"onDelete",new at),e(this,"onDisposed",new at),e(this,"_knownDrawings",new Set),e(this,"_previewMaterial",new o.LineBasicMaterial({color:16737894,depthTest:!1})),e(this,"_previewObject",null),e(this,"_previewDrawing",null),e(this,"_materialCache",new i.DataMap),e(this,"_meshMaterialCache",new i.DataMap),e(this,"_ownsChildGeometry",!0),this._components=t,this.styles.onItemUpdated.add((({key:t})=>{const e=this._materialCache.get(t);e&&e.color.setHex(this._resolveStyle(t).color);const i=this._meshMaterialCache.get(t);i&&i.color.setHex(this._resolveStyle(t).color);const n=this._components.get(Dc),s=n?[...n.list.values()]:[...this._knownDrawings];for(const e of s){const i=[...e.annotations.getBySystem(this)].filter((([,e])=>e.style===t)).map((([t])=>t));i.length>0&&this.update(e,i,{})}}))}_onAfterPersist(t,e){}_onDispose(){}_updatePreview(){}get(t){const e=new i.DataMap;for(const i of t)for(const[t,n]of i.annotations.getBySystem(this))e.set(t,{drawingUuid:i.uuid,item:n});return e}add(t,e){const i={uuid:o.MathUtils.generateUUID(),style:this.activeStyle,...e},n=this._persist(t,i);return this.onCommit.trigger([n]),i}update(t,e,i){for(const n of e){const e=t.annotations.get(n);if(!e||e.system!==this)continue;const s=e.data;Object.assign(s,i),this._redraw(s,e.three),this.onUpdate.trigger({item:s,group:e.three})}}pick(t,e=.05){const i=new o.Raycaster;i.ray.copy(t),i.params.Line={threshold:e},i.params.LineSegments={threshold:e};const n=o.Line.prototype.raycast;let s=null,r=1/0;for(const t of this._knownDrawings)for(const[e,a]of t.annotations){if(a.system!==this)continue;const t=a.three;t.updateWorldMatrix(!0,!0),t.traverse((a=>{if(a===t)return;const l=[];if(a instanceof o.LineSegments&&a.userData.isDimension)n.call(a,i,l),l.length>0&&l[0].distance<r&&(r=l[0].distance,s=e);else if(a instanceof o.Mesh){const t=(new o.Box3).setFromObject(a),n=new o.Vector3;if(i.ray.intersectBox(t,n)){const t=i.ray.origin.distanceTo(n);t<r&&(r=t,s=e)}}}))}return s}delete(t,e){const i=[];for(const n of e){const e=t.annotations.get(n);e&&e.system===this&&(this._disposeGroup(e.three),t.annotations.delete(n),i.push(n))}i.length&&this.onDelete.trigger(i)}clear(t){const e=t??[...this._knownDrawings];for(const t of e){const e=[];for(const[i,n]of t.annotations)n.system===this&&e.push(i);for(const i of e){const e=t.annotations.get(i);this._disposeGroup(e.three),t.annotations.delete(i)}}}dispose(){this._clearPreview(),this._onDispose(),this.clear();for(const t of this._materialCache.values())t.dispose();this._materialCache.clear();for(const t of this._meshMaterialCache.values())t.dispose();this._meshMaterialCache.clear(),this._previewMaterial.dispose(),this.onCommit.reset(),this.onUpdate.reset(),this.onDelete.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}_trackDrawing(t){this._knownDrawings.has(t)||(this._knownDrawings.add(t),t.onDisposed.add((()=>this._knownDrawings.delete(t))))}_resolveStyle(t){return this.styles.get(t)??this.styles.get("default")}_getMaterial(t){const e=this._materialCache.get(t);if(e)return e;const i=new o.LineBasicMaterial({color:this._resolveStyle(t).color});return this._materialCache.set(t,i),i}_getMeshMaterial(t){const e=this._meshMaterialCache.get(t);if(e)return e;const i=new o.MeshBasicMaterial({color:this._resolveStyle(t).color,side:o.DoubleSide});return this._meshMaterialCache.set(t,i),i}_disposeGroup(t){if(t.removeFromParent(),this._ownsChildGeometry)t.traverse((t=>{t.geometry instanceof o.BufferGeometry&&t.geometry.dispose()}));else for(;t.children.length>0;)t.remove(t.children[0])}_clearPreview(){this._previewObject&&(this._previewObject.removeFromParent(),this._previewObject.geometry.dispose(),this._previewObject=null)}_persist(t,e){this._trackDrawing(t);const i=this._resolveStyle(e.style),n=this._buildGroup(e,i);return n.userData.isDimension=!0,n.userData.annotationUuid=e.uuid,n.userData.layer=t.activeLayer,t.three.add(n),t.annotations.set(e.uuid,{system:this,data:e,three:n}),this._onAfterPersist(e,n),{drawing:t,item:e,group:n}}_redraw(t,e){for(;e.children.length>0;){const t=e.children[0];this._ownsChildGeometry&&t.geometry instanceof o.BufferGeometry&&t.geometry.dispose(),e.remove(t)}const i=this._resolveStyle(t.style),n=this._buildGroup(t,i);for(;n.children.length>0;)e.add(n.children[0]);this._onAfterPersist(t,e)}}function ql(t,e){const i=t[0],n=t[t.length-1],s=(new o.Vector3).subVectors(n,i);if(s.lengthSq()<1e-10)return 0;s.normalize();const r=new o.Vector3(-s.z,0,s.x);return e.clone().sub(i).dot(r)}function Yl(t,e){const i=[];for(let n=0;n<t.length-1;n++)i.push({uuid:o.MathUtils.generateUUID(),pointA:t[n].clone(),pointB:t[n+1].clone(),offset:e,style:""});return i}function Xl(t,e){switch(t.kind){case"awaitingFirstPoint":if("CLICK"===e.type){if(!e.line)return t;const i=(new o.Vector3).subVectors(e.line.end,e.line.start).normalize();return{kind:"placingPoints",points:[e.point.clone()],cursor:null,lineDir:i,firstLine:e.line.clone()}}return"SELECT_LINE"===e.type?{kind:"positioningOffset",points:[e.line.start.clone(),e.line.end.clone()],cursor:null}:t;case"placingPoints":if("MOUSE_MOVE"===e.type){const i=new o.Vector3(-t.lineDir.z,0,t.lineDir.x),n=t.points[t.points.length-1],s=e.point.clone().sub(n).dot(i),r=n.clone().addScaledVector(i,s);return{...t,cursor:r}}if("CLICK"===e.type){if(!e.line)return t;if(function(t,e){const i=1e-6;return t.start.distanceTo(e.start)<i&&t.end.distanceTo(e.end)<i||t.start.distanceTo(e.end)<i&&t.end.distanceTo(e.start)<i}(e.line,t.firstLine))return t;const s=(new o.Vector3).subVectors(e.line.end,e.line.start).normalize();if(i=s,n=t.lineDir,!(Math.abs(i.dot(n))>.999))return t;const r=function(t,e,i){const n=t.clone().sub(e.start).dot(i);return e.start.clone().addScaledVector(i,n)}(t.points[0],e.line,t.lineDir),a=[...t.points,r];return{...t,points:a,cursor:t.cursor}}return"CONFIRM"===e.type&&t.points.length>=2?{kind:"positioningOffset",points:t.points,cursor:null}:"ESCAPE"===e.type?{kind:"awaitingFirstPoint"}:t;case"positioningOffset":if("MOUSE_MOVE"===e.type)return{...t,cursor:e.point.clone()};if("CLICK"===e.type){const i=ql(t.points,e.point);return{kind:"committed",dimensions:Yl(t.points,i)}}return"ESCAPE"===e.type?{kind:"awaitingFirstPoint"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingFirstPoint"}:t}var i,n}function Kl(t){const{pointA:e,pointB:i,offset:n}=t,s=(new o.Vector3).subVectors(i,e),r=new o.Vector3(-s.z,0,s.x).normalize(),a=e.clone().addScaledVector(r,n),l=i.clone().addScaledVector(r,n),c=(new o.Vector3).subVectors(l,a).normalize();return[{tip:a,dir:c},{tip:l,dir:c.clone().negate()}]}function Ql(t,e){const{pointA:i,pointB:n,offset:s}=t,r=(new o.Vector3).subVectors(n,i),a=new o.Vector3(-r.z,0,r.x).normalize(),l=s>=0?1:-1,c=Math.abs(s),h=i.clone().addScaledVector(a,e.extensionGap*l),u=i.clone().addScaledVector(a,(c+e.extensionOvershoot)*l),d=n.clone().addScaledVector(a,e.extensionGap*l),p=n.clone().addScaledVector(a,(c+e.extensionOvershoot)*l),f=i.clone().addScaledVector(a,s),m=n.clone().addScaledVector(a,s),g=(new o.Vector3).subVectors(m,f).normalize(),w=e.lineTick(f,g,e.tickSize),y=e.lineTick(m,g.clone().negate(),e.tickSize);return[h.x,h.y,h.z,u.x,u.y,u.z,d.x,d.y,d.z,p.x,p.y,p.z,f.x,f.y,f.z,m.x,m.y,m.z,...w,...y]}function Jl(t,e,i,n){if("placingPoints"===t){const t=[];for(let i=0;i<e.length-1;i++){const n=e[i],s=e[i+1];t.push(n.x,n.y,n.z,s.x,s.y,s.z)}if(i){const n=e[e.length-1];t.push(n.x,n.y,n.z,i.x,i.y,i.z)}return t}if(!i||e.length<2)return[];const s=ql(e,i),r=[];for(let t=0;t<e.length-1;t++)r.push(...Ql({uuid:"",pointA:e[t],pointB:e[t+1],offset:s,style:""},n));return r}class tc extends Zl{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingFirstPoint"}),e(this,"onMachineStateChanged",new at),this.styles.set("default",{lineTick:El,tickSize:.4,extensionGap:.05,extensionOvershoot:.2,color:0,textOffset:.4,fontSize:.45})}pickHandle(t,e,i=.1){const n=(new o.Matrix4).copy(t.three.matrixWorld).invert(),s=e.origin.clone().applyMatrix4(n),r=e.direction.clone().transformDirection(n).normalize(),a=new o.Ray(s,r),l=new o.Plane(new o.Vector3(0,1,0),0),c=a.intersectPlane(l,new o.Vector3);if(!c)return null;let h=null,u=i;for(const[e,i]of t.annotations.getBySystem(this)){const t=(new o.Vector3).subVectors(i.pointB,i.pointA),n=new o.Vector3(-t.z,0,t.x).normalize(),s=(new o.Vector3).addVectors(i.pointA,i.pointB).multiplyScalar(.5).addScaledVector(n,i.offset);for(const[t,n]of[["pointA",i.pointA],["pointB",i.pointB],["offset",s]]){const i=Math.hypot(c.x-n.x,c.z-n.z);i<u&&(u=i,h={uuid:e,handle:t})}}return h}sendMachineEvent(t){const e=t.drawing??null;e&&(this._previewDrawing=e);const i=Xl(this.machineState,t);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("LinearAnnotations: no drawing context — send a CLICK or SELECT_LINE with `drawing` first. Skipping."),void this._resetMachine();for(const t of i.dimensions)t.style=this.activeStyle;const t=i.dimensions.map((t=>this._persist(this._previewDrawing,t)));this.onCommit.trigger(t)}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(t,e){const i=new o.Group,n=Ql(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick)for(const{tip:n,dir:s}of Kl(t)){const r=e.meshTick(n,s,e.tickSize),a=new o.BufferGeometry;a.setAttribute("position",new o.BufferAttribute(new Float32Array(r),3));const l=new o.Mesh(a,this._getMeshMaterial(t.style));l.layers.set(1),l.userData.isMeshTick=!0,i.add(l)}return i}_updatePreview(){const t=this.machineState;if("placingPoints"!==t.kind&&"positioningOffset"!==t.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const e=this._resolveStyle(this.activeStyle);this._previewMaterial.color.setHex(e.color);const i=Jl(t.kind,t.points,t.cursor,e);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewObject=new o.LineSegments(t,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const t=this._previewObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingFirstPoint"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}}const ec=Math.PI/180;function ic(t,e,i,n){const s=function(t,e,i){const n=(new o.Vector3).subVectors(t,e).normalize(),s=(new o.Vector3).subVectors(i,e).normalize();return(new o.Vector3).addVectors(n,s).normalize()}(t,e,i);return(new o.Vector3).subVectors(n,e).setY(0).dot(s)}function nc(t,e,i,n){return ic(t,e,i,n)<0}function sc(t,e){switch(t.kind){case"awaitingFirstLine":return"CLICK"===e.type&&e.line?{kind:"awaitingSecondLine",line1:e.line.clone(),pointA:e.point.clone()}:t;case"awaitingSecondLine":if("CLICK"===e.type&&e.line){const i=(new o.Vector3).subVectors(t.line1.end,t.line1.start).normalize(),n=(new o.Vector3).subVectors(e.line.end,e.line.start).normalize();if(Math.abs(i.dot(n))>Math.cos(ec))return t;const s=function(t,e,i,n){const s=e.x*n.z-e.z*n.x;if(Math.abs(s)<1e-10)return null;const r=(new o.Vector3).subVectors(i,t),a=(r.x*n.z-r.z*n.x)/s;return new o.Vector3(t.x+e.x*a,0,t.z+e.z*a)}(t.line1.start,i,e.line.start,n);return s?{kind:"positioningArc",pointA:t.pointA.clone(),vertex:s,pointB:e.point.clone(),cursor:null,flipped:!1}:t}return"ESCAPE"===e.type?{kind:"awaitingFirstLine"}:t;case"positioningArc":if("MOUSE_MOVE"===e.type){const i=nc(t.pointA,t.vertex,t.pointB,e.point);return{...t,cursor:e.point.clone(),flipped:i}}if("CLICK"===e.type){const i=nc(t.pointA,t.vertex,t.pointB,e.point),n=Math.max(.05,Math.abs(ic(t.pointA,t.vertex,t.pointB,e.point)));return{kind:"committed",dimension:{uuid:o.MathUtils.generateUUID(),pointA:t.pointA.clone(),vertex:t.vertex.clone(),pointB:t.pointB.clone(),arcRadius:n,flipped:i,style:""}}}return"ESCAPE"===e.type?{kind:"awaitingFirstLine"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingFirstLine"}:t}}function rc(t){const e=(new o.Vector3).subVectors(t.pointA,t.vertex).normalize(),i=(new o.Vector3).subVectors(t.pointB,t.vertex).normalize(),n=Math.atan2(e.z,e.x);let s=Math.atan2(i.z,i.x)-n;for(;s>Math.PI;)s-=2*Math.PI;for(;s<-Math.PI;)s+=2*Math.PI;t.flipped&&(s-=2*Math.sign(s)*Math.PI);const r=new o.Vector3(t.vertex.x+Math.cos(n)*t.arcRadius,0,t.vertex.z+Math.sin(n)*t.arcRadius),a=n+s,l=new o.Vector3(t.vertex.x+Math.cos(a)*t.arcRadius,0,t.vertex.z+Math.sin(a)*t.arcRadius),c=Math.sign(s);return[{tip:r,dir:new o.Vector3(-Math.sin(n)*c,0,Math.cos(n)*c)},{tip:l,dir:new o.Vector3(Math.sin(a)*c,0,-Math.cos(a)*c)}]}function oc(t){const e=(new o.Vector3).subVectors(t.pointA,t.vertex).normalize(),i=(new o.Vector3).subVectors(t.pointB,t.vertex).normalize(),n=Math.acos(o.MathUtils.clamp(e.dot(i),-1,1));return t.flipped?2*Math.PI-n:n}function ac(t){const e=(new o.Vector3).subVectors(t.pointA,t.vertex).normalize(),i=(new o.Vector3).subVectors(t.pointB,t.vertex).normalize(),n=Math.atan2(e.z,e.x);let s=Math.atan2(i.z,i.x)-n;for(;s>Math.PI;)s-=2*Math.PI;for(;s<-Math.PI;)s+=2*Math.PI;const r=n+s/2;return t.flipped?r+Math.PI:r}function lc(t,e,i,n,s,r=!1){const a=Math.atan2(e.z,e.x);let l=Math.atan2(i.z,i.x)-a;for(;l>Math.PI;)l-=2*Math.PI;for(;l<-Math.PI;)l+=2*Math.PI;r&&(l-=2*Math.sign(l)*Math.PI);const c=[];for(let e=0;e<8;e++){const i=a+l*(e/8),s=a+l*((e+1)/8);c.push(t.x+Math.cos(i)*n,0,t.z+Math.sin(i)*n,t.x+Math.cos(s)*n,0,t.z+Math.sin(s)*n)}const h=new o.Vector3(t.x+Math.cos(a)*n,0,t.z+Math.sin(a)*n),u=new o.Vector3(t.x+Math.cos(a+l)*n,0,t.z+Math.sin(a+l)*n),d=t.clone().addScaledVector(e,s.extensionGap),p=t.clone().addScaledVector(i,s.extensionGap);c.push(d.x,d.y,d.z,h.x,h.y,h.z,p.x,p.y,p.z,u.x,u.y,u.z);const f=Math.sign(l),m=new o.Vector3(-Math.sin(a)*f,0,Math.cos(a)*f),g=a+l,w=new o.Vector3(Math.sin(g)*f,0,-Math.cos(g)*f);return c.push(...s.lineTick(h,m,s.tickSize),...s.lineTick(u,w,s.tickSize)),c}function cc(t,e){const i=(new o.Vector3).subVectors(t.pointA,t.vertex).normalize(),n=(new o.Vector3).subVectors(t.pointB,t.vertex).normalize();return lc(t.vertex,i,n,t.arcRadius,e,t.flipped??!1)}function hc(t,e,i,n,s,r=!1){if(!n)return[];const a=Math.max(.05,(new o.Vector3).subVectors(n,e).setY(0).length());return lc(e,(new o.Vector3).subVectors(t,e).normalize(),(new o.Vector3).subVectors(i,e).normalize(),a,s,r)}class uc extends Zl{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingFirstLine"}),e(this,"onMachineStateChanged",new at),e(this,"_secondLinePreviewObject",null),this.styles.set("default",{lineTick:El,tickSize:.4,extensionGap:.05,color:0,textOffset:.25,fontSize:.45})}pickHandle(t,e,i){return null}sendMachineEvent(t){const e=t.drawing??null;if("awaitingSecondLine"===this.machineState.kind&&"MOUSE_MOVE"===t.type)return e&&(this._previewDrawing=e),void this._updateSecondLinePreview(t.point,t.line??null);const i=sc(this.machineState,t);if(i!==this.machineState){if("awaitingSecondLine"===this.machineState.kind&&this._clearSecondLinePreview(),this.machineState=i,e&&(this._previewDrawing=e),this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("AngleAnnotations: CLICK that commits must include `drawing`. Skipping."),void this._resetMachine();i.dimension.style=this.activeStyle;const t=this._persist(this._previewDrawing,i.dimension);this.onCommit.trigger([t])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(t,e){const i=new o.Group,n=cc(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick)for(const{tip:n,dir:s}of rc(t)){const r=e.meshTick(n,s,e.tickSize),a=new o.BufferGeometry;a.setAttribute("position",new o.BufferAttribute(new Float32Array(r),3));const l=new o.Mesh(a,this._getMeshMaterial(t.style));l.layers.set(1),l.userData.isMeshTick=!0,i.add(l)}return i}_updatePreview(){const t=this.machineState;if("positioningArc"!==t.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const e=this._resolveStyle(this.activeStyle),i=hc(t.pointA,t.vertex,t.pointB,t.cursor,e,t.flipped);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewObject=new o.LineSegments(t,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const t=this._previewObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}}_onDispose(){this._clearSecondLinePreview()}_resetMachine(){this.machineState={kind:"awaitingFirstLine"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearSecondLinePreview(){this._secondLinePreviewObject&&(this._secondLinePreviewObject.removeFromParent(),this._secondLinePreviewObject.geometry.dispose(),this._secondLinePreviewObject=null)}_updateSecondLinePreview(t,e){if("awaitingSecondLine"!==this.machineState.kind)return void this._clearSecondLinePreview();if(!this._previewDrawing)return void this._clearSecondLinePreview();const i=this.machineState,n=(new o.Vector3).subVectors(i.line1.end,i.line1.start).normalize();if(!e)return void this._clearSecondLinePreview();const s=(new o.Vector3).subVectors(e.end,e.start).normalize(),r=function(t,e,i,n){const s=e.x*n.z-e.z*n.x;if(Math.abs(s)<1e-6)return null;const r=i.x-t.x,a=i.z-t.z,l=(r*n.z-a*n.x)/s;return new o.Vector3(t.x+l*e.x,0,t.z+l*e.z)}(i.line1.start,n,e.start,s);if(!r)return void this._clearSecondLinePreview();const a=t.clone(),l=(new o.Vector3).subVectors(a,r).setY(0);if(l.length()<.01)return void this._clearSecondLinePreview();const c=(new o.Vector3).subVectors(i.pointA,r).normalize(),h=l.normalize(),u=Math.atan2(c.z,c.x);let d=Math.atan2(h.z,h.x)-u;for(;d>Math.PI;)d-=2*Math.PI;for(;d<-Math.PI;)d+=2*Math.PI;const p=u+d/2,f=Math.max(.1,.4*Math.min(i.pointA.distanceTo(r),a.distanceTo(r))),m=new o.Vector3(r.x+Math.cos(p)*f,0,r.z+Math.sin(p)*f),g=this._resolveStyle(this.activeStyle),w=hc(i.pointA,r,a,m,g);if(0===w.length)return void this._clearSecondLinePreview();const y=w.length/3;if(!this._secondLinePreviewObject||this._secondLinePreviewObject.geometry.attributes.position.count!==y){this._clearSecondLinePreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(w),3)),this._secondLinePreviewObject=new o.LineSegments(t,this._previewMaterial),this._secondLinePreviewObject.layers.set(1),this._secondLinePreviewObject.renderOrder=1,this._secondLinePreviewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._secondLinePreviewObject)}else{const t=this._secondLinePreviewObject.geometry.attributes.position;t.set(w),t.needsUpdate=!0}}}function dc(t,e){const i=e.x-t.x,n=e.z-t.z,s=Math.sqrt(i*i+n*n);if(0===s)return t.clone();const r=Math.atan2(n,i),a=Math.round(r/(Math.PI/4))*(Math.PI/4);return new o.Vector3(t.x+Math.cos(a)*s,0,t.z+Math.sin(a)*s)}function pc(t,e){switch(t.kind){case"awaitingArrowTip":return"CLICK"===e.type?{kind:"placingElbow",arrowTip:e.point.clone(),cursor:null}:t;case"placingElbow":return"MOUSE_MOVE"===e.type?{...t,cursor:e.point.clone()}:"CLICK"===e.type?{kind:"placingExtension",arrowTip:t.arrowTip,elbow:e.point.clone(),cursor:null}:"ESCAPE"===e.type?{kind:"awaitingArrowTip"}:t;case"placingExtension":return"MOUSE_MOVE"===e.type?{...t,cursor:dc(t.elbow,e.point)}:"CLICK"===e.type?{kind:"enteringText",arrowTip:t.arrowTip,elbow:t.elbow,extensionEnd:dc(t.elbow,e.point)}:"ESCAPE"===e.type?{kind:"awaitingArrowTip"}:t;case"enteringText":if("SUBMIT_TEXT"===e.type&&e.text.trim().length>0){return{kind:"committed",annotation:{uuid:o.MathUtils.generateUUID(),arrowTip:t.arrowTip.clone(),elbow:t.elbow.clone(),extensionEnd:t.extensionEnd.clone(),text:e.text.trim(),style:""}}}return"ESCAPE"===e.type?{kind:"awaitingArrowTip"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingArrowTip"}:t}}function fc(t,e,i,n){return"curved"===n.leaderShape?function(t,e,i,n){const s=new o.QuadraticBezierCurve3(t,e,i).getPoints(24),r=[];for(let t=0;t<s.length-1;t++){const e=s[t],i=s[t+1];r.push(e.x,e.y,e.z,i.x,i.y,i.z)}if(n.lineTick){const i=(new o.Vector3).subVectors(t,e);i.lengthSq()>1e-10&&r.push(...n.lineTick(t,i.normalize(),n.tickSize))}return r}(t,e,i,n):function(t,e,i,n){const s=[t.x,t.y,t.z,e.x,e.y,e.z,e.x,e.y,e.z,i.x,i.y,i.z];if(n.lineTick){const i=(new o.Vector3).subVectors(t,e);i.lengthSq()>1e-10&&s.push(...n.lineTick(t,i.normalize(),n.tickSize))}return s}(t,e,i,n)}function mc(t,e){return fc(t.arrowTip,t.elbow,t.extensionEnd,e)}function gc(t,e,i,n,s){return n?fc(e,"placingElbow"===t?n:i,n,s):[]}class wc extends Zl{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingArrowTip"}),e(this,"onMachineStateChanged",new at),e(this,"_previewMeshMaterial",new o.MeshBasicMaterial({color:16737894,side:o.DoubleSide,depthTest:!1})),e(this,"_previewMeshObject",null),this.styles.set("default",{tickSize:.4,color:0,textOffset:.1,fontSize:.45,lineTick:Il})}pickHandle(t,e,i=.1){const n=(new o.Matrix4).copy(t.three.matrixWorld).invert(),s=e.origin.clone().applyMatrix4(n),r=e.direction.clone().transformDirection(n).normalize(),a=new o.Ray(s,r),l=new o.Plane(new o.Vector3(0,1,0),0),c=a.intersectPlane(l,new o.Vector3);if(!c)return null;let h=null,u=i;for(const[e,i]of t.annotations.getBySystem(this))for(const[t,n]of[["elbow",i.elbow],["extensionEnd",i.extensionEnd]]){const i=Math.hypot(c.x-n.x,c.z-n.z);i<u&&(u=i,h={uuid:e,handle:t})}return h}sendMachineEvent(t){const e=t.drawing??null;e&&(this._previewDrawing=e);const i=pc(this.machineState,t);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("LeaderAnnotations: commit requires a drawing. Skipping."),void this._resetMachine();i.annotation.style=this.activeStyle;const t=this._persist(this._previewDrawing,i.annotation);this.onCommit.trigger([t])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(t,e){const i=new o.Group,n=mc(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick){const n=(new o.Vector3).subVectors(t.arrowTip,t.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=e.meshTick(t.arrowTip,n,e.tickSize),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3));const a=new o.Mesh(r,this._getMeshMaterial(t.style));a.layers.set(1),a.userData.isMeshArrow=!0,i.add(a)}}return i}_updatePreview(){const t=this.machineState;if("placingElbow"!==t.kind&&"placingExtension"!==t.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const e=this._resolveStyle(this.activeStyle),i="placingElbow"===t.kind?gc("placingElbow",t.arrowTip,null,t.cursor,e):gc("placingExtension",t.arrowTip,t.elbow,t.cursor,e);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewObject=new o.LineSegments(t,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const t=this._previewObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}if(e.meshTick){const i="placingElbow"===t.kind?t.cursor:t.elbow,n=i?(new o.Vector3).subVectors(t.arrowTip,i):null;if(n&&n.lengthSq()>1e-10){n.normalize();const i=e.meshTick(t.arrowTip,n,e.tickSize);if(this._previewMeshObject){const t=this._previewMeshObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}else{const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewMeshObject=new o.Mesh(t,this._previewMeshMaterial),this._previewMeshObject.layers.set(1),this._previewMeshObject.renderOrder=1,this._previewMeshObject.frustumCulled=!1,this._previewDrawing.three.add(this._previewMeshObject)}}else this._clearPreviewMesh()}else this._clearPreviewMesh()}_clearPreview(){super._clearPreview(),this._clearPreviewMesh()}_onDispose(){this._clearPreviewMesh(),this._previewMeshMaterial.dispose()}_resetMachine(){this.machineState={kind:"awaitingArrowTip"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearPreviewMesh(){this._previewMeshObject&&(this._previewMeshObject.removeFromParent(),this._previewMeshObject.geometry.dispose(),this._previewMeshObject=null)}}class yc extends Zl{constructor(t){super(t),e(this,"enabled",!0),e(this,"_ownsChildGeometry",!1),e(this,"definitions",new i.DataMap),this.styles.set("default",{color:0,textOffset:0,fontSize:0})}pickHandle(t,e,i){return null}pick(t,e=.05){const i=new o.Raycaster;i.ray.copy(t),i.params.Line={threshold:e},i.params.LineSegments={threshold:e};let n=null,s=1/0;for(const t of this._knownDrawings)for(const[e,r]of t.annotations){if(r.system!==this)continue;const t=r.three;t.updateWorldMatrix(!0,!0),t.traverse((r=>{if(r===t)return;if(!(r instanceof o.LineSegments))return;const a=[];r.raycast(i,a),a.length>0&&a[0].distance<s&&(s=a[0].distance,n=e)}))}return n}define(t,e){this.definitions.set(t,e)}_buildGroup(t,e){const i=this.definitions.get(t.blockName);if(!i)throw new Error(`BlockAnnotations: block "${t.blockName}" is not defined.`);const n=new o.Group;if(i.lines){const e=new o.LineSegments(i.lines,this._getMaterial(t.style));e.layers.set(1),e.userData.isDimension=!0,n.add(e)}if(i.mesh){const e=new o.Mesh(i.mesh,this._getMeshMaterial(t.style));e.layers.set(1),e.userData.isBlockMesh=!0,n.add(e)}return n}_onAfterPersist(t,e){e.position.set(t.position.x,0,t.position.z),e.rotation.set(0,t.rotation,0),e.scale.setScalar(t.scale)}_onDispose(){var t,e;for(const i of this.definitions.values())null==(t=i.lines)||t.dispose(),null==(e=i.mesh)||e.dispose();this.definitions.clear()}}function _c(t,e){const{position:i,direction:n}=t,{length:s}=e,r=new o.Vector3(i.x+n.x*s,0,i.z+n.z*s),a=new o.Vector3(n.x,0,n.z),l=e.lineTick(r,a,e.tickSize),c=[i.x,0,i.z,r.x,0,r.z];return new Float32Array([...c,...l])}function bc(t,e){return new o.Vector3(t.position.x+t.direction.x*e,0,t.position.z+t.direction.z*e)}function vc(t,e){switch(e){case"percentage":return`${(100*t).toFixed(2)} %`;case"ratio":return 0===t?"1:∞":`1:${(1/t).toFixed(2)}`;case"degrees":return`${(180*Math.atan(t)/Math.PI).toFixed(2)}°`}}class xc extends Zl{constructor(t){super(t),e(this,"enabled",!0),this.styles.set("default",{lineTick:zl,meshTick:Ol,tickSize:.4,length:3,color:0,textOffset:.1,fontSize:.45,format:"percentage"})}pickHandle(t,e,i){return null}_buildGroup(t,e){const i=new o.Group,n=_c(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(n,3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick){const n=bc(t,e.length),s=e.meshTick(n,t.direction,e.tickSize),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3));const a=new o.Mesh(r,this._getMeshMaterial(t.style));a.layers.set(1),a.userData.isDimension=!0,i.add(a)}return i}}function Cc(t,e){const i=e.x-t.x,n=e.z-t.z,s=Math.sqrt(i*i+n*n);if(0===s)return t.clone();const r=Math.atan2(n,i),a=Math.round(r/(Math.PI/4))*(Math.PI/4);return new o.Vector3(t.x+Math.cos(a)*s,0,t.z+Math.sin(a)*s)}function Sc(t,e){switch(t.kind){case"awaitingCenter":return"CLICK"===e.type?{kind:"awaitingRadius",center:e.point.clone(),cursor:null}:t;case"awaitingRadius":if("MOUSE_MOVE"===e.type)return{...t,cursor:e.point.clone()};if("CLICK"===e.type){const i=Math.max(.1,Math.abs(e.point.x-t.center.x)),n=Math.max(.1,Math.abs(e.point.z-t.center.z));return{kind:"awaitingElbow",center:t.center,halfW:i,halfH:n,cursor:null}}return"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"awaitingElbow":return"MOUSE_MOVE"===e.type?{...t,cursor:e.point.clone()}:"CLICK"===e.type?{kind:"awaitingExtension",center:t.center,halfW:t.halfW,halfH:t.halfH,elbow:e.point.clone(),cursor:null}:"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"awaitingExtension":return"MOUSE_MOVE"===e.type?{...t,cursor:Cc(t.elbow,e.point)}:"CLICK"===e.type?{kind:"enteringText",center:t.center,halfW:t.halfW,halfH:t.halfH,elbow:t.elbow,extensionEnd:Cc(t.elbow,e.point)}:"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"enteringText":if("SUBMIT_TEXT"===e.type&&e.text.trim().length>0){return{kind:"committed",annotation:{uuid:o.MathUtils.generateUUID(),center:t.center.clone(),halfW:t.halfW,halfH:t.halfH,elbow:t.elbow.clone(),extensionEnd:t.extensionEnd.clone(),text:e.text.trim(),style:""}}}return"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingCenter"}:t}}function Ac(t,e){const i=[];i.push(...e.enclosure.buildGeometry(t.center,t.halfW,t.halfH));const n=(new o.Vector3).subVectors(t.elbow,t.center),s=n.lengthSq()>1e-10?n.clone().normalize():new o.Vector3(1,0,0),r=e.enclosure.getAttachmentPoint(t.center,t.halfW,t.halfH,s);if(i.push(r.x,r.y,r.z,t.elbow.x,t.elbow.y,t.elbow.z,t.elbow.x,t.elbow.y,t.elbow.z,t.extensionEnd.x,t.extensionEnd.y,t.extensionEnd.z),e.lineTick){const n=(new o.Vector3).subVectors(t.extensionEnd,t.elbow);n.lengthSq()>1e-10&&i.push(...e.lineTick(t.extensionEnd,n.normalize(),e.tickSize))}return i}function Pc(t,e,i,n,s,r,a){const l="awaitingRadius"===t?r?Math.max(.05,Math.abs(r.x-e.x)):0:i,c="awaitingRadius"===t?r?Math.max(.05,Math.abs(r.z-e.z)):0:n;if(l<1e-10||c<1e-10)return[];const h=[];if(h.push(...a.enclosure.buildGeometry(e,l,c)),"awaitingRadius"===t)return h;const u="awaitingElbow"===t?r:s;if(!u)return h;const d=(new o.Vector3).subVectors(u,e),p=d.lengthSq()>1e-10?d.clone().normalize():new o.Vector3(1,0,0),f=a.enclosure.getAttachmentPoint(e,l,c,p);return"awaitingElbow"===t?(h.push(f.x,0,f.z,u.x,0,u.z),h):r?(h.push(f.x,0,f.z,s.x,0,s.z,s.x,0,s.z,r.x,0,r.z),h):h}const Tc={buildGeometry(t,e,i){const n=.25*Math.min(e,i),s=new o.Vector3(t.x-e,0,t.z-i),r=new o.Vector3(t.x+e,0,t.z-i),a=new o.Vector3(t.x+e,0,t.z+i),l=new o.Vector3(t.x-e,0,t.z+i),c=[[s,r,new o.Vector3(0,0,-1)],[r,a,new o.Vector3(1,0,0)],[a,l,new o.Vector3(0,0,1)],[l,s,new o.Vector3(-1,0,0)]],h=[];for(const[t,e,i]of c){const s=t.distanceTo(e),r=Math.max(1,Math.round(s/(2*n))),a=s/r,l=a/2,c=(new o.Vector3).subVectors(e,t).normalize();for(let e=0;e<r;e++){const n=t.clone().addScaledVector(c,(e+.5)*a),s=t.clone().addScaledVector(c,e*a),r=(new o.Vector3).subVectors(s,n);let u=s.clone();for(let t=1;t<=8;t++){const e=t/8*Math.PI,s=n.x+r.x*Math.cos(e)+i.x*l*Math.sin(e),a=n.z+r.z*Math.cos(e)+i.z*l*Math.sin(e),c=new o.Vector3(s,0,a);h.push(u.x,0,u.z,c.x,0,c.z),u=c}}}return h},getAttachmentPoint(t,e,i,n){const s=Math.abs(n.x)>1e-10?e/Math.abs(n.x):1/0,r=Math.abs(n.z)>1e-10?i/Math.abs(n.z):1/0,a=Math.min(s,r);return new o.Vector3(t.x+n.x*a,0,t.z+n.z*a)}},Ec={buildGeometry(t,e,i){const n=new o.Vector3(t.x-e,0,t.z-i),s=new o.Vector3(t.x+e,0,t.z-i),r=new o.Vector3(t.x+e,0,t.z+i),a=new o.Vector3(t.x-e,0,t.z+i);return[n.x,0,n.z,s.x,0,s.z,s.x,0,s.z,r.x,0,r.z,r.x,0,r.z,a.x,0,a.z,a.x,0,a.z,n.x,0,n.z]},getAttachmentPoint(t,e,i,n){const s=Math.abs(n.x)>1e-10?e/Math.abs(n.x):1/0,r=Math.abs(n.z)>1e-10?i/Math.abs(n.z):1/0,a=Math.min(s,r);return new o.Vector3(t.x+n.x*a,0,t.z+n.z*a)}},Mc={buildGeometry(t,e,i){const n=[];for(let s=0;s<32;s++){const r=s/32*Math.PI*2,o=(s+1)/32*Math.PI*2;n.push(t.x+Math.cos(r)*e,0,t.z+Math.sin(r)*i,t.x+Math.cos(o)*e,0,t.z+Math.sin(o)*i)}return n},getAttachmentPoint(t,e,i,n){const s=n.x/e,r=n.z/i,a=Math.sqrt(s*s+r*r),l=a>1e-10?1/a:e;return new o.Vector3(t.x+n.x*l,0,t.z+n.z*l)}};class Ic extends Zl{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingCenter"}),e(this,"onMachineStateChanged",new at),this.styles.set("default",{enclosure:Tc,lineTick:Il,tickSize:.4,color:22015,textOffset:.1,fontSize:.45})}pickHandle(t,e,i){return null}sendMachineEvent(t){const e=t.drawing??null;e&&(this._previewDrawing=e);const i=Sc(this.machineState,t);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("CalloutAnnotations: commit requires a drawing. Pass `drawing` on the first CLICK."),void this._resetMachine();i.annotation.style=this.activeStyle;const t=this._persist(this._previewDrawing,i.annotation);this.onCommit.trigger([t])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(t,e){const i=new o.Group,n=Ac(t,e),s=new o.BufferGeometry;s.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const r=new o.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick){const n=(new o.Vector3).subVectors(t.extensionEnd,t.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=e.meshTick(t.extensionEnd,n,e.tickSize),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3));const a=new o.Mesh(r,this._getMeshMaterial(t.style));a.layers.set(1),a.userData.isMeshArrow=!0,i.add(a)}}return i}_updatePreview(){const t=this.machineState;if("awaitingRadius"!==t.kind&&"awaitingElbow"!==t.kind&&"awaitingExtension"!==t.kind)return void this._clearPreview();if(!this._previewDrawing)return;const e=this._resolveStyle(this.activeStyle),i=(()=>{switch(t.kind){case"awaitingRadius":return Pc("awaitingRadius",t.center,0,0,null,t.cursor,e);case"awaitingElbow":return Pc("awaitingElbow",t.center,t.halfW,t.halfH,null,t.cursor,e);case"awaitingExtension":return Pc("awaitingExtension",t.center,t.halfW,t.halfH,t.elbow,t.cursor,e)}})();if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const t=new o.BufferGeometry;t.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3)),this._previewObject=new o.LineSegments(t,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const t=this._previewObject.geometry.attributes.position;t.set(i),t.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingCenter"},this._clearPreview(),this._previewDrawing=null,this.onMachineStateChanged.trigger(this.machineState)}}const zc=class t extends ht{constructor(n){super(n),e(this,"enabled",!0),e(this,"list",new i.DataMap),e(this,"systems",new i.DataMap),e(this,"onDisposed",new at),n.add(t.uuid,this),this.list.onBeforeDelete.add((({value:t})=>t.dispose())),this.systems.onBeforeDelete.add((({value:t})=>t.dispose()))}use(t){if(this.systems.has(t))return this.systems.get(t);const e=new t(this.components);return this.systems.set(t,e),e}create(t){const e=new Gl(this.components);e.world=t,t.scene.three.add(e.three),t.onDisposed.add((()=>this.list.delete(e.uuid)));const i=t.camera;return i.three.layers.enable(1),i instanceof Oa&&(i.threePersp.layers.enable(1),i.threeOrtho.layers.enable(1)),this.list.set(e.uuid,e),e}dispose(){this.list.clear(),this.systems.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};e(zc,"uuid","5c7d3b9a-4e8f-4a2b-9c1d-0e3f2a5b7c8d");let Dc=zc;const kc=[[16711680,1],[16776960,2],[65280,3],[65535,4],[255,5],[16711935,6],[16777215,7],[0,7]];function Bc(t){const e=t>>16&255,i=t>>8&255,n=255&t;let s=7,r=1/0;for(const[t,o]of kc){const a=(e-(t>>16&255))**2+(i-(t>>8&255))**2+(n-(255&t))**2;a<r&&(r=a,s=o)}return s}const Oc="\0HANDSEED\0";class Nc{constructor(){e(this,"_lines",[]),e(this,"_handleCounter",1)}p(t,e){return this._lines.push(String(t),String(e)),this}n(t,e,i=6){return this._lines.push(String(t),e.toFixed(i)),this}handle(){return(this._handleCounter++).toString(16).toUpperCase()}entityHeader(t,e,i){return this._lines.push("0",t,"5",this.handle(),"100","AcDbEntity","8",e,"62",String(i)),this}symbolTable(t,e){return this._lines.push("0","TABLE","2",t,"5",this.handle(),"100","AcDbSymbolTable","70",String(e)),this}symbolRecord(t,e){return this._lines.push("0",t,"5",this.handle(),"100","AcDbSymbolTableRecord","100",e),this}writeHandSeed(){return this._lines.push("9","$HANDSEED","5",Oc),this}build(){return(this._lines.join("\n")+"\n").replace(Oc,this._handleCounter.toString(16).toUpperCase())}}class Vc{constructor(t){e(this,"precision",2),e(this,"config",{trueColor:!1}),e(this,"_viewport",null),e(this,"_paperSlot",null),e(this,"_annotationLayers",new Map),e(this,"_systemExporters",new Map),this._components=t}registerSystemExporter(t,e){this._systemExporters.set(t,e)}export(t,e){const i=!!e,n=new Nc,s=new Map;for(const e of t)for(const t of e.drawing.layers.values())s.has(t.name)||s.set(t.name,t);const r=[...s.values()],o=this._components.get(Dc).systems.get(yc),a=o?[...o.definitions.keys()]:[];this._writeHeader(n,i),this._writeTables(n,r,a),this._writeBlocks(n,o??null),n.p(0,"SECTION").p(2,"ENTITIES"),i&&e&&this._writePaperBorders(n,e);for(const s of t){s.drawing.three.traverse((t=>{t.userData.isDimension&&t.userData.annotationUuid&&this._annotationLayers.set(t.userData.annotationUuid,t.userData.layer??"0")}));for(const t of s.viewports){if(this._viewport=t.viewport??null,i&&t.viewport){const i=t.viewport,n=e.heightMm-2*e.margin;this._paperSlot={x:t.x??0,y:n-(t.y??0),mmPerUnit:1e3/i.drawingScale,vpLeft:i.left,vpTop:i.top}}else this._paperSlot=null;this._writeViewportBorder(n),this._writeRawLines(n,s.drawing),this._writeLinearAnnotations(n,s.drawing),this._writeAngleAnnotations(n,s.drawing),this._writeLeaderAnnotations(n,s.drawing),this._writeSlopeAnnotations(n,s.drawing),this._writeCalloutAnnotations(n,s.drawing),this._writeBlockInsertions(n,s.drawing),this._writeCustomSystems(n,s.drawing)}this._annotationLayers.clear()}return n.p(0,"ENDSEC"),this._writeObjects(n),n.p(0,"EOF"),this._viewport=null,this._paperSlot=null,n.build()}_writeHeader(t,e){t.p(0,"SECTION").p(2,"HEADER"),t.p(9,"$ACADVER").p(1,this.config.trueColor?"AC1018":"AC1015"),t.p(9,"$DWGCODEPAGE").p(3,"ANSI_1252"),t.p(9,"$INSUNITS").p(70,e?4:6),t.writeHandSeed(),t.p(0,"ENDSEC")}_writeTables(t,e,i){t.p(0,"SECTION").p(2,"TABLES"),t.symbolTable("VPORT",0).p(0,"ENDTAB"),t.symbolTable("LTYPE",1),t.symbolRecord("LTYPE","AcDbLinetypeTableRecord").p(2,"CONTINUOUS").p(70,0).p(3,"Solid line").p(72,65).p(73,0).n(40,0),t.p(0,"ENDTAB"),t.symbolTable("LAYER",e.length);for(const i of e){const e=Bc(i.material.color.getHex());t.symbolRecord("LAYER","AcDbLayerTableRecord").p(2,i.name).p(70,0).p(62,e).p(6,"CONTINUOUS")}t.p(0,"ENDTAB"),t.symbolTable("STYLE",1),t.symbolRecord("STYLE","AcDbTextStyleTableRecord").p(2,"STANDARD").p(70,0).n(40,0).n(41,1).n(50,0).p(71,0).n(42,.2).p(3,"txt").p(4,""),t.p(0,"ENDTAB"),t.symbolTable("VIEW",0).p(0,"ENDTAB"),t.symbolTable("UCS",0).p(0,"ENDTAB"),t.symbolTable("APPID",1),t.symbolRecord("APPID","AcDbRegAppTableRecord").p(2,"ACAD").p(70,0),t.p(0,"ENDTAB"),t.symbolTable("DIMSTYLE",0).p(0,"ENDTAB");const n=["*Model_Space","*Paper_Space",...i];t.symbolTable("BLOCK_RECORD",n.length);for(const e of n)t.symbolRecord("BLOCK_RECORD","AcDbBlockTableRecord").p(2,e);t.p(0,"ENDTAB"),t.p(0,"ENDSEC")}_writeBlocks(t,e){if(t.p(0,"SECTION").p(2,"BLOCKS"),this._writeBlock(t,"*Model_Space",null),this._writeBlock(t,"*Paper_Space",null),e)for(const[i,n]of e.definitions)this._writeBlock(t,i,n.lines??null);t.p(0,"ENDSEC")}_writeBlock(t,e,i){if(t.p(0,"BLOCK").p(5,t.handle()).p(100,"AcDbEntity").p(8,"0").p(100,"AcDbBlockBegin").p(2,e).p(70,0).n(10,0).n(20,0).n(30,0).p(3,e).p(1,""),i){const e=this._viewport,n=this._paperSlot;this._viewport=null,this._paperSlot=null,this._writeGeoAsLines(t,i,"0"),this._viewport=e,this._paperSlot=n}t.p(0,"ENDBLK").p(5,t.handle()).p(100,"AcDbEntity").p(8,"0").p(100,"AcDbBlockEnd")}_writeViewportBorder(t){if(!this._viewport)return;const e=this._viewport,i=this._tx(e.left),n=this._tx(e.right),s=this._ty(-e.bottom),r=this._ty(-e.top);this._writeRawLine(t,i,s,n,s,"0",7),this._writeRawLine(t,n,s,n,r,"0",7),this._writeRawLine(t,n,r,i,r,"0",7),this._writeRawLine(t,i,r,i,s,"0",7)}_writePaperBorders(t,e){const{margin:i,widthMm:n,heightMm:s}=e,r=n-2*i,o=s-2*i;this._writeRawLine(t,0,0,r,0,"0",7),this._writeRawLine(t,r,0,r,o,"0",7),this._writeRawLine(t,r,o,0,o,"0",7),this._writeRawLine(t,0,o,0,0,"0",7),this._writeRawLine(t,-i,-i,r+i,-i,"0",7),this._writeRawLine(t,r+i,-i,r+i,o+i,"0",7),this._writeRawLine(t,r+i,o+i,-i,o+i,"0",7),this._writeRawLine(t,-i,o+i,-i,-i,"0",7)}_writeObjects(t){t.p(0,"SECTION").p(2,"OBJECTS"),t.p(0,"DICTIONARY").p(5,t.handle()).p(330,0).p(100,"AcDbDictionary").p(281,1),t.p(0,"ENDSEC")}_writeRawLines(t,e){e.three.traverse((e=>{var i;if(!(e instanceof o.LineSegments))return;if(e.userData.isDimension)return;if(null==(i=e.parent)?void 0:i.userData.blockUuid)return;if(!e.visible)return;const n=e.userData.layer??"0",s=e.material.color.getHex();this._writeGeoAsLines(t,e.geometry,n,Bc(s),s)}))}_writeLinearAnnotations(t,e){var i;const n=this._components.get(Dc).systems.get(tc);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Bc(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=Ql(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick)for(const{tip:e,dir:i}of Kl(s))this._writeMeshTriangles(t,r.meshTick(e,i,r.tickSize),l,a,r.color);const h=(new o.Vector3).subVectors(s.pointB,s.pointA),u=new o.Vector3(-h.z,0,h.x).normalize(),d=s.offset>=0?1:-1,p=s.pointA.clone().addScaledVector(u,s.offset),f=s.pointB.clone().addScaledVector(u,s.offset),m=p.clone().add(f).multiplyScalar(.5).addScaledVector(u,(r.textOffset+.5*r.fontSize)*d),g=r.unit??{factor:1,suffix:"m"},w=`${(s.pointA.distanceTo(s.pointB)*g.factor).toFixed(this.precision)} ${g.suffix}`;this._writeText(t,w,m.x,m.z,r.fontSize,l,a,this._textAngle(h.x,h.z),1,2,r.color)}}_writeAngleAnnotations(t,e){var i;const n=this._components.get(Dc).systems.get(uc);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Bc(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=cc(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick)for(const{tip:e,dir:i}of rc(s))this._writeMeshTriangles(t,r.meshTick(e,i,r.tickSize),l,a,r.color);const h=ac(s),u=s.arcRadius+r.textOffset,d=s.vertex.x+Math.cos(h)*u,p=s.vertex.z+Math.sin(h)*u,f=o.MathUtils.radToDeg(oc(s));this._writeText(t,`${f.toFixed(this.precision)}°`,d,p,r.fontSize,l,a,0,1,0,r.color)}}_writeLeaderAnnotations(t,e){var i;const n=this._components.get(Dc).systems.get(wc);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Bc(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=mc(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick){const e=(new o.Vector3).subVectors(s.arrowTip,s.elbow);e.lengthSq()>1e-10&&this._writeMeshTriangles(t,r.meshTick(s.arrowTip,e.normalize(),r.tickSize),l,a,r.color)}const h=(new o.Vector3).subVectors(s.extensionEnd,s.elbow).setY(0).normalize(),u=h.x<-.1?2:h.x>.1?0:1,d=1===u?.5*r.fontSize:0,p=s.extensionEnd.clone().addScaledVector(h,r.textOffset+d);this._writeText(t,s.text,p.x,p.z,r.fontSize,l,a,0,u,2,r.color)}}_writeSlopeAnnotations(t,e){var i;const n=this._components.get(Dc).systems.get(xc);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Bc(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=_c(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick){const e=bc(s,r.length);this._writeMeshTriangles(t,r.meshTick(e,s.direction,r.tickSize),l,a,r.color)}const h=new o.Vector3(s.position.x+s.direction.x*r.length,0,s.position.z+s.direction.z*r.length),u=s.position.clone().add(h).multiplyScalar(.5).addScaledVector(new o.Vector3(-s.direction.z,0,s.direction.x),r.textOffset+r.fontSize);this._writeText(t,vc(s.slope,r.format),u.x,u.z,r.fontSize,l,a,this._textAngle(s.direction.x,s.direction.z),1,0,r.color)}}_writeCalloutAnnotations(t,e){var i;const n=this._components.get(Dc).systems.get(Ic);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),a=Bc(r.color),l=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(l))?void 0:i.visible))continue;const c=Ac(s,r);if(!this._fullyInViewport(this._bboxFromPositions(c)))continue;if(this._writePairsAsLines(t,c,l,a,r.color),r.meshTick){const e=(new o.Vector3).subVectors(s.extensionEnd,s.elbow);e.lengthSq()>1e-10&&this._writeMeshTriangles(t,r.meshTick(s.extensionEnd,e.normalize(),r.tickSize),l,a,r.color)}const h=(new o.Vector3).subVectors(s.extensionEnd,s.elbow).setY(0).normalize(),u=h.x<-.1?2:h.x>.1?0:1,d=1===u?.5*r.fontSize:0,p=s.extensionEnd.clone().addScaledVector(h,r.textOffset+d);this._writeText(t,s.text,p.x,p.z,r.fontSize,l,a,0,u,2,r.color)}}_writeBlockInsertions(t,e){const i=this._components.get(Dc).systems.get(yc);if(i)for(const[,n]of e.annotations.getBySystem(i)){if(!this._inViewport(n.position.x,n.position.z))continue;const e=i.styles.get(n.style)??i.styles.get("default"),s=Bc(e.color),r=-o.MathUtils.radToDeg(n.rotation),a=n.scale*this._scale();t.entityHeader("INSERT","0",s),this._emitTrueColor(t,e.color),t.p(100,"AcDbBlockReference").p(2,n.blockName).n(10,this._tx(n.position.x)).n(20,this._ty(n.position.z)).n(30,0).n(41,a).n(42,a).n(43,a).n(50,r)}}_writeGeoAsLines(t,e,i,n=7,s){const r=e.attributes.position;if(r)for(let e=0;e+1<r.count;e+=2){const a=this._clipSegment(new o.Vector3(r.getX(e),0,r.getZ(e)),new o.Vector3(r.getX(e+1),0,r.getZ(e+1)));a&&this._writeLine(t,a.start.x,a.start.z,a.end.x,a.end.z,i,n,s)}}_writePairsAsLines(t,e,i,n=7,s){for(let r=0;r+5<e.length;r+=6){const a=this._clipSegment(new o.Vector3(e[r],0,e[r+2]),new o.Vector3(e[r+3],0,e[r+5]));a&&this._writeLine(t,a.start.x,a.start.z,a.end.x,a.end.z,i,n,s)}}_emitTrueColor(t,e){this.config.trueColor&&void 0!==e&&t.p(420,e)}_writeLine(t,e,i,n,s,r,o,a){t.entityHeader("LINE",r,o),this._emitTrueColor(t,a),t.p(100,"AcDbLine").n(10,this._tx(e)).n(20,this._ty(i)).n(30,0).n(11,this._tx(n)).n(21,this._ty(s)).n(31,0)}_writeRawLine(t,e,i,n,s,r,o){t.entityHeader("LINE",r,o).p(100,"AcDbLine").n(10,e).n(20,i).n(30,0).n(11,n).n(21,s).n(31,0)}_writeSolid(t,e,i,n,s,r,o,a,l,c){t.entityHeader("SOLID",a,l),this._emitTrueColor(t,c),t.p(100,"AcDbTrace").n(10,this._tx(e)).n(20,this._ty(i)).n(30,0).n(11,this._tx(n)).n(21,this._ty(s)).n(31,0).n(12,this._tx(r)).n(22,this._ty(o)).n(32,0).n(13,this._tx(r)).n(23,this._ty(o)).n(33,0)}_writeMeshTriangles(t,e,i,n,s){for(let r=0;r+8<e.length;r+=9)this._writeSolid(t,e[r],e[r+2],e[r+3],e[r+5],e[r+6],e[r+8],i,n,s)}_writeText(t,e,i,n,s,r,o,a=0,l=0,c=0,h){const u=this._tx(i),d=this._ty(n);t.entityHeader("TEXT",r,o),this._emitTrueColor(t,h),t.p(100,"AcDbText").n(10,u).n(20,d).n(30,0).n(40,s*this._scale()).n(50,a).p(1,e),0===l&&0===c||(0!==l&&t.p(72,l),0!==c&&t.p(73,c),t.n(11,u).n(21,d).n(31,0))}_tx(t){return this._paperSlot?this._paperSlot.x+(t-this._paperSlot.vpLeft)*this._paperSlot.mmPerUnit:this._viewport?t-this._viewport.left:t}_ty(t){return this._paperSlot?this._paperSlot.y-(t+this._paperSlot.vpTop)*this._paperSlot.mmPerUnit:this._viewport?-t-this._viewport.bottom:-t}_scale(){return this._paperSlot?this._paperSlot.mmPerUnit:1}_clipSegment(t,e){return this._viewport?this._viewport.clipLine(new o.Line3(t,e)):new o.Line3(t,e)}_inViewport(t,e){return!this._viewport||this._viewport.bbox.containsPoint(new o.Vector3(t,0,e))}_bboxFromPositions(t){const e=new o.Box3;for(let i=0;i+2<t.length;i+=3)e.expandByPoint(new o.Vector3(t[i],0,t[i+2]));return e}_fullyInViewport(t){return!this._viewport||this._viewport.bbox.containsBox(t)}_textAngle(t,e){let i=Math.atan2(-e,t);return(i>Math.PI/2||i<=-Math.PI/2)&&(i+=Math.PI),o.MathUtils.radToDeg(i)}_writeCustomSystems(t,e){if(0===this._systemExporters.size)return;const i=this._makeContext(t);for(const[t,e]of this._systemExporters){const n=this._components.get(Dc).systems.get(t);n&&e(n,i)}}_makeContext(t){return{writeLine:(e,i,n,s,r="0",o=7)=>{this._writeLine(t,e,i,n,s,r,o)},writePairs:(e,i="0",n=7)=>{this._writePairsAsLines(t,e,i,n)},writeMeshTriangles:(e,i="0",n=7)=>{this._writeMeshTriangles(t,e,i,n)},writeText:(e,i,n,s,r={})=>{this._writeText(t,e,i,n,s,r.layer??"0",r.aciColor??7,r.rotDeg??0,r.hAlign??0)},hexToAci:Bc,textAngle:(t,e)=>this._textAngle(t,e)}}}const Lc=class t extends ht{constructor(i){super(i),e(this,"enabled",!0),e(this,"exporter",new Vc(this.components)),i.add(t.uuid,this)}};e(Lc,"uuid","e9a2c3d4-5f67-4b89-a012-1c3d5e7f9b2a");let Fc=Lc;export{uc as AngleAnnotations,Zl as AnnotationSystem,Ml as ArrowTick,lt as AsyncEvent,Za as BCFTopics,Ga as BCFTopicsConfigManager,ct as Base,dt as BaseCamera,pt as BaseRenderer,gt as BaseScene,ut as BaseWorldItem,yc as BlockAnnotations,Lo as BoundingBoxer,Ic as CalloutAnnotations,Mc as CircleEnclosure,$o as Classifier,Ka as Clipper,Tc as CloudEnclosure,Ua as Comment,ht as Component,Ia as Components,pi as ConfigManager,ui as Configurator,ci as ControlsUtils,li as DataMap,wt as DataSet,El as DiagonalTick,mt as Disposer,Dl as DotTick,Nl as DrawingAnnotations,Vl as DrawingLayers,Zl as DrawingSystem,Rl as DrawingViewport,Fl as DrawingViewportHelper,Ul as DrawingViewports,Vc as DxfExporter,Fc as DxfManager,zo as EdgeProjector,at as Event,hi as EventManager,Go as FastModelPicker,Zo as FastModelPickers,Ol as FilledArrowTick,kl as FilledCircleTick,Bl as FilledSquareTick,Fo as FinderQuery,za as FirstPersonMode,fr as FragmentsManager,Ea as Grids,No as Hider,hl as IDSAttribute,ul as IDSClassification,dl as IDSEntity,ll as IDSFacet,fl as IDSMaterial,ml as IDSPartOf,pl as IDSProperty,gl as IDSSpecification,Al as IDSSpecifications,Do as IfcFragmentSettings,Bo as IfcLoader,Uo as ItemsFinder,wc as LeaderAnnotations,tc as LinearAnnotations,Tl as MeasurementUtils,ai as ModelIdMapUtils,fi as Mouse,zl as NoTick,Il as OpenArrowTick,Da as OrbitMode,Oa as OrthoPerspectiveCamera,ka as PlanMode,Ba as ProjectionManager,pa as Raycasters,Ec as RectEnclosure,ba as RendererMode,al as ShadowedScene,xa as SimpleCamera,Pa as SimpleGrid,Aa as SimpleGridConfigManager,qa as SimplePlane,ua as SimpleRaycaster,va as SimpleRenderer,ya as SimpleScene,wa as SimpleSceneConfigManager,fa as SimpleWorld,xc as SlopeAnnotations,qo as SnapClass,Xo as SnapResolver,ha as SnapResolvers,Gl as TechnicalDrawing,$l as TechnicalDrawingHelper,Dc as TechnicalDrawings,$a as Topic,_t as UUID,Hl as Units,oi as VertexPicker,il as View,Qa as Viewpoint,el as Viewpoints,sl as Views,Sa as Worlds,ri as XML,sc as angleDimensionMachine,cc as buildAnglePositions,hc as buildAnglePreviewPositions,Ac as buildCalloutPositions,Pc as buildCalloutPreviewPositions,Ql as buildDimensionPositions,Yl as buildDimensions,mc as buildLeaderPositions,gc as buildLeaderPreviewPositions,Jl as buildPreviewPositions,_c as buildSlopePositions,Sc as calloutAnnotationMachine,Wl as computeAlignmentMatrix,oc as computeAngle,ac as computeBisectorAngle,ql as computeOffset,Wa as extensionsImporter,vc as formatSlope,rc as getAngleTickEndpoints,Kl as getDimensionTickEndpoints,bc as getSlopeTip,pc as leaderAnnotationMachine,Xl as linearDimensionMachine};