@thatopen/components 3.4.8 → 3.4.9

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,12 +1 @@
1
- "use strict";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);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const i=require("@thatopen/fragments"),n=require("three"),s=require("three/webgpu"),r=require("three/tsl"),o=require("web-ifc"),a=require("camera-controls"),l=require("three/examples/jsm/controls/TransformControls.js");function c(t){const e=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(t)for(const i in t)if("default"!==i){const n=Object.getOwnPropertyDescriptor(t,i);Object.defineProperty(e,i,n.get?n:{enumerable:!0,get:()=>t[i]})}return e.default=t,Object.freeze(e)}const h=c(i),u=c(n),d=c(s),p=c(o);class f{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 m{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 g extends m{}class w extends m{constructor(t){super(t),e(this,"worlds",new i.DataMap),e(this,"onWorldChanged",new f),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 y extends w{constructor(){super(...arguments),e(this,"hasCameraControls",()=>"controls"in this)}}class _ extends w{constructor(){super(...arguments),e(this,"onAfterUpdate",new f),e(this,"onBeforeUpdate",new f),e(this,"onDisposed",new f),e(this,"onResize",new f),e(this,"onClippingPlanesUpdated",new f),e(this,"clippingPlanes",[]),e(this,"localClippingPlanes",!1)}updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(t,e,i=this.localClippingPlanes){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),this.updateClippingPlanes()}}const b=class t extends g{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(b,"uuid","76e9cd8e-ad8f-4753-9ef6-cbc60f7247fe");let v=b;class x extends w{constructor(t){super(t),e(this,"onDisposed",new f),e(this,"directionalLights",new Map),e(this,"ambientLights",new Map)}dispose(){const t=this.components.get(v);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 C extends Set{constructor(t){super(t),e(this,"onItemAdded",new f),e(this,"onItemDeleted",new f),e(this,"onCleared",new f),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 f),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 S=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(S,"_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(S,"_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 A=S;const P=":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",T=new RegExp("^"+("["+P+"]["+(P+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*")+"$");function M(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 E=function(t){const e=T.exec(t);return!(null==e)};const I=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],D=["__proto__","constructor","prototype"],z={allowBooleanAttributes:!1,unpairedTags:[]};function k(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function B(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 j("InvalidXml","XML declaration allowed only at the start of the document.",G(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function O(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 V='"',L="'";function N(t,e){let i="",n="",s=!1;for(;e<t.length;e++){if(t[e]===V||t[e]===L)""===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 F=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function R(t,e){const i=M(t,F),n={};for(let t=0;t<i.length;t++){if(0===i[t][1].length)return j("InvalidAttr","Attribute '"+i[t][2]+"' has no space in starting.",H(i[t]));if(void 0!==i[t][3]&&void 0===i[t][4])return j("InvalidAttr","Attribute '"+i[t][2]+"' is without value.",H(i[t]));if(void 0===i[t][3]&&!e.allowBooleanAttributes)return j("InvalidAttr","boolean attribute '"+i[t][2]+"' is not allowed.",H(i[t]));const s=i[t][2];if(!$(s))return j("InvalidAttr","Attribute '"+s+"' is an invalid name.",H(i[t]));if(Object.prototype.hasOwnProperty.call(n,s))return j("InvalidAttr","Attribute '"+s+"' is repeated.",H(i[t]));n[s]=1}return!0}function U(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 j(t,e,i){return{err:{code:t,msg:e,line:i.line||i,col:i.col}}}function $(t){return E(t)}function W(t){return E(t)}function G(t,e){const i=t.substring(0,e).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function H(t){return t.startIndex+t[1].length}const q={cent:"¢",pound:"£",curren:"¤",yen:"¥",euro:"€",dollar:"$",euro:"€",fnof:"ƒ",inr:"₹",af:"؋",birr:"ብር",peso:"₱",rub:"₽",won:"₩",yuan:"¥",cedil:"¸"},Z={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},Y={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},X=new Set("!?\\\\/[]$%{}^&*()<>|+");function K(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(X.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function Q(...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 J="external",tt="base",et="all";const it=Object.freeze({allow:0,leave:1,remove:2,throw:3}),nt=new Set([9,10,13]);class st{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??J)&&e!==J?e===et?new Set([et]):e===tt?new Set([tt]):Array.isArray(e)?new Set(e):new Set([J]):new Set([J]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=Q(Z,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:it.allow,nullLevel:it.remove};const e=1.1===t.xmlVersion?1.1:1,i=it[t.onNCR]??it.allow,n=it[t.nullNCR]??it.remove;return{xmlVersion:e,onLevel:i,nullLevel:Math.max(n,it.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))K(e);this._externalMap=Q(t)}addExternalEntity(t,e){K(t),"string"==typeof e&&-1===e.indexOf("&")&&(this._externalMap[t]=e)}addInputEntities(t){this._totalExpansions=0,this._expandedLength=0,this._inputMap=Q(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=J);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=tt}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(et)||this._limitTiers.has(t)}_resolveName(t){return t in this._inputMap?{value:this._inputMap[t],tier:J}:t in this._externalMap?{value:this._externalMap[t],tier:J}:t in this._baseMap?{value:this._baseMap[t],tier:tt}:void 0}_classifyNCR(t){return 0===t?this._ncrNullLevel:t>=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!nt.has(t)?it.remove:-1}_applyNCRAction(t,e,i){switch(t){case it.allow:return String.fromCodePoint(i);case it.remove:return"";case it.leave:return;case it.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<it.remove)return;const s=-1===n?this._ncrOnLevel:Math.max(this._ncrOnLevel,n);return this._applyNCRAction(s,t,i)}}const rt=t=>I.includes(t)?"__"+t:t,ot={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:rt};function at(t,e){if("string"!=typeof t)return;const i=t.toLowerCase();if(I.some(t=>i===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);if(D.some(t=>i===t.toLowerCase()))throw new Error(`[SECURITY] Invalid ${e}: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`)}function lt(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"}:lt(!0)}const ct=function(t){const e=Object.assign({},ot,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&&at(t,e);return null===e.onDangerousProperty&&(e.onDangerousProperty=rt),e.processEntities=lt(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 ht;ht="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class ut{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][ht]={startIndex:e})}static getMetaDataSymbol(){return ht}}class dt{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&&ft(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&&ft(t,"!ELEMENT",e)){e+=8;const{index:i}=this.readElementExp(t,e+1);e=i}else if(r&&ft(t,"!ATTLIST",e))e+=8;else if(r&&ft(t,"!NOTATION",e)){e+=9;const{index:i}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=i}else{if(!ft(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=pt(t,e);for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;let n=t.substring(i,e);if(mt(n),e=pt(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=pt(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let n=t.substring(i,e);!this.suppressValidationErr&&mt(n),e=pt(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=pt(t,e);let r=null,o=null;if("PUBLIC"===s)[e,r]=this.readIdentifierVal(t,e,"publicIdentifier"),'"'!==t[e=pt(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=pt(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let n=t.substring(i,e);if(!this.suppressValidationErr&&!E(n))throw new Error(`Invalid element name: "${n}"`);let s="";if("E"===t[e=pt(t,e)]&&ft(t,"MPTY",e))e+=4;else if("A"===t[e]&&ft(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=pt(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let n=t.substring(i,e);for(mt(n),i=e=pt(t,e);e<t.length&&!/\s/.test(t[e]);)e++;let s=t.substring(i,e);if(!mt(s))throw new Error(`Invalid attribute name: "${s}"`);e=pt(t,e);let r="";if("NOTATION"===t.substring(e,e+8).toUpperCase()){if(r="NOTATION","("!==t[e=pt(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(),!mt(s))throw new Error(`Invalid notation name: "${s}"`);i.push(s),"|"===t[e]&&(e++,e=pt(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=pt(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 pt=(t,e)=>{for(;e<t.length&&/\s/.test(t[e]);)e++;return e};function ft(t,e,i){for(let n=0;n<e.length;n++)if(e[n]!==t[i+n+1])return!1;return!0}function mt(t){if(E(t))return t;throw new Error(`Invalid entity name ${t}`)}const gt=/^[-+]?0x[a-fA-F0-9]+$/,wt=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,yt={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original"};function _t(t,e={}){if(e=Object.assign({},yt,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&&gt.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(bt);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=wt.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 bt=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;class vt{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 xt{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 Ct{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 St{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new Ct(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 At(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 Pt(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 Tt{constructor(t,e){var i;this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=zt,this.parseTextData=Mt,this.resolveNameSpace=Et,this.buildAttributesMap=Dt,this.isItStopNode=Vt,this.replaceEntitiesValue=Bt,this.readStopNodeData=Rt,this.saveTextToParentTag=Ot,this.addChild=kt,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={...Z};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?n=this.options.htmlEntities:!0===this.options.htmlEntities&&(n={...Y,...q}),this.entityDecoder=new st({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 St,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new xt;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 vt(e)):e instanceof vt&&this.stopNodeExpressionsSet.add(e)}this.stopNodeExpressionsSet.seal()}}}function Mt(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 Ut(t,a.parseTagValue,a.numberParseOptions);return t.trim()===t?Ut(t,a.parseTagValue,a.numberParseOptions):t}}function Et(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 It=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function Dt(t,e,i,n=!1){const s=this.options;if(!0===n||!0!==s.ignoreAttributes&&"string"==typeof t){const n=M(t,It),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=$t(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:Ut(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 zt=function(t){t=t.replace(/\r\n?/g,"\n");const e=new ut("!xml");let i=e,n="";this.matcher.reset(),this.entityDecoder.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;const s=this.options,r=new dt(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=Lt(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=jt(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=Ft(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 ut(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=Lt(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=Lt(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=Ft(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}=jt(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=Pt(c),l!==e.tagname&&this.matcher.push(l,{},m),l!==h&&u&&(g=this.buildAttributesMap(h,this.matcher,l),g&&At(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 ut(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}=jt(s.transformTagName,l,h,s));const t=new ut(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 ut(l);g&&(t[":@"]=g),this.addChild(i,t,this.readonlyMatcher,w),this.matcher.pop(),this.isCurrentNodeStopNode=!1,a=r.closeIndex;continue}{const t=new ut(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 kt(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 Bt(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 Ot(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 Vt(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function Lt(t,e,i,n){const s=t.indexOf(e,i);if(-1===s)throw new Error(n);return s+e.length-1}function Nt(t,e,i,n){const s=t.indexOf(e,i);if(-1===s)throw new Error(n);return s}function Ft(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 Rt(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=Nt(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=Lt(t,"?>",i+1,"StopNode is not closed.")}else if(33===r&&45===t.charCodeAt(i+2)&&45===t.charCodeAt(i+3)){i=Lt(t,"--\x3e",i+3,"StopNode is not closed.")}else if(33===r&&91===t.charCodeAt(i+2)){i=Lt(t,"]]>",i,"StopNode is not closed.")-2}else{const n=Ft(t,i,">");if(n){(n&&n.tagName)===e&&"/"!==n.tagExp[n.tagExp.length-1]&&s++,i=n.closeIndex}}}}function Ut(t,e,i){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&_t(t,i)}return void 0!==t?t:""}function jt(t,e,i,n){if(t){const n=t(e);i===e&&(i=n),e=n}return{tagName:e=$t(e,n),tagExp:i}}function $t(t,e){if(D.includes(t))throw new Error(`[SECURITY] Invalid name: "${t}" is a reserved JavaScript keyword that could cause prototype pollution`);return I.includes(t)?e.onDangerousProperty(t):t}const Wt=ut.getMetaDataSymbol();function Gt(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 Ht(t,e,i,n){return qt(t,e,i,n)}function qt(t,e,i,n){let s;const r={};for(let o=0;o<t.length;o++){const a=t[o],l=Zt(a);if(void 0!==l&&l!==e.textNodeName){const t=Gt(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=qt(a[l],e,i,n);const s=Xt(t,e);if(a[":@"]?Yt(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[Wt]&&"object"==typeof t&&null!==t&&(t[Wt]=a[Wt]),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 Zt(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const i=e[t];if(":@"!==i)return i}}function Yt(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 Xt(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 Kt{constructor(t){this.externalEntities={},this.options=ct(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({},z,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=B(t,r),r.err)return r}else{if("<"!==t[r]){if(k(t[r]))continue;return j("InvalidChar","char '"+t[r]+"' is not expected.",G(t,r))}{let o=r;if(r++,"!"===t[r]){r=O(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--),!W(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",j("InvalidTag",e,G(t,r))}const c=N(t,r);if(!1===c)return j("InvalidAttr","Attributes for '"+l+"' have open quote.",G(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=R(h,e);if(!0!==s)return j(s.err.code,s.err.msg,G(t,i+s.err.line));n=!0}else if(a){if(!c.tagClosed)return j("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",G(t,r));if(h.trim().length>0)return j("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",G(t,o));if(0===i.length)return j("InvalidTag","Closing tag '"+l+"' has not been opened.",G(t,o));{const e=i.pop();if(l!==e.tagName){let i=G(t,e.tagStartPos);return j("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",G(t,o))}0==i.length&&(s=!0)}}else{const a=R(h,e);if(!0!==a)return j(a.err.code,a.err.msg,G(t,r-h.length+a.err.line));if(!0===s)return j("InvalidXml","Multiple possible root nodes found.",G(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=O(t,r);continue}if("?"!==t[r+1])break;if(r=B(t,++r),r.err)return r}else if("&"===t[r]){const e=U(t,r);if(-1==e)return j("InvalidChar","char '&' is not expected.",G(t,r));r=e}else if(!0===s&&!k(t[r]))return j("InvalidXml","Extra text at the end",G(t,r));"<"===t[r]&&r--}}}return n?1==i.length?j("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",G(t,i[0].tagStartPos)):!(i.length>0)||j("InvalidXml","Invalid '"+JSON.stringify(i.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):j("InvalidXml","Start tag expected.",1)}(t,e);if(!0!==i)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const i=new Tt(this.options,this.externalEntities),n=i.parseXml(t);return this.options.preserveOrder||void 0===n?n:Ht(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 ut.getMetaDataSymbol()}}function Qt(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 vt(i)):i instanceof vt&&n.push(i)}return Jt(t,e,i,new St,n)}function Jt(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=oe(i,e),i}return""}for(let a=0;a<t.length;a++){const l=t[a],c=ne(l);if(void 0===c)continue;const h=te(l[":@"],e);n.push(c,h);const u=re(n,s);if(c===e.textNodeName){let t=l[c];u||(t=e.tagValueProcessor(c,t),t=oe(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=se(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}${se(l[":@"],e,u)}`;let f;f=u?ee(l[c],e):Jt(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 te(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 ee(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=ne(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=ie(s[":@"],e),n=ee(s[r],e);n&&0!==n.length?i+=`<${r}${t}>${n}</${r}>`:i+=`<${r}${t}/>`}}}return i}function ie(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 ne(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 se(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=oe(r,e)),!0===r&&e.suppressBooleanAttributes?n+=` ${s.substr(e.attributeNamePrefix.length)}`:n+=` ${s.substr(e.attributeNamePrefix.length)}="${r}"`}return n}function re(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 oe(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 ae={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 le(t){if(this.options=Object.assign({},ae,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 vt(e)):e instanceof vt&&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=ue),this.processTextOrObjNode=ce,this.options.format?(this.indentate=he,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function ce(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 he(t){return this.options.indentBy.repeat(t)}function ue(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}le.prototype.build=function(t){if(this.options.preserveOrder)return Qt(t,this.options);{Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t});const e=new St;return this.j2x(t,0,e).val}},le.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}},le.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+'"'},le.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},le.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},le.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},le.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}},le.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`></${t}`,e},le.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},le.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}},le.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 de{}e(de,"parser",new Kt({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(de,"builder",new le({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1}));class pe{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=pe.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=pe.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=pe.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 fe extends Map{constructor(t){super(t),e(this,"onItemSet",new f),e(this,"onItemUpdated",new f),e(this,"onItemDeleted",new f),e(this,"onCleared",new f),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 f),this.onItemUpdated.trigger({key:t,value:e})):(this.onItemSet||(this.onItemSet=new f),this.onItemSet.trigger({key:t,value:e})),n}add(t){const e=A.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 me{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 ge{constructor(t,i,n,s){e(this,"_component"),e(this,"name"),e(this,"uuid"),this._component=t,this.name=n,this.uuid=s??A.create();i.get(ye).list.set(this.uuid,this)}get controls(){return me.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(me.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(me.isEntry(n))if("Color"===n.type){const{r:t,g:s,b:r}=n.value;e[i]={...n,value:new u.Color(t,s,r)}}else if("Vector3"===n.type){const{x:t,y:s,z:r}=n.value;e[i]={...n,value:new u.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 we=class t extends g{constructor(n){super(n),e(this,"list",new i.DataMap),e(this,"enabled",!0),n.add(t.uuid,this)}};e(we,"uuid","b8c764e0-6b24-4e77-9a32-35fa728ee5b4");let ye=we;class _e{constructor(t){e(this,"_event"),e(this,"_position",new u.Vector2),e(this,"onDisposed",new f),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 be=1.25,ve=32,xe=Math.pow(2,-24),Ce=Symbol("SKIP_GENERATION"),Se={strategy:0,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Ce]:!1};function Ae(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 Pe(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 Te(t,e){e.set(t)}function Me(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 Ee(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 Ie(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 De(t,e){return 65535===e[t+15]}function ze(t,e){return e[t+6]}function ke(t,e){return e[t+14]}function Be(t){return t+8}function Oe(t,e){return t+8*e[t+6]}function Ve(t,e){return e[t+7]}function Le(t){return t}function Ne(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 Fe=32,Re=(t,e)=>t.candidate-e.candidate,Ue=new Array(Fe).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),je=new Float32Array(6);class $e{constructor(){this.boundingData=new Float32Array(6)}}let We,Ge,He,qe;const Ze=Math.pow(2,32);function Ye(t){return"count"in t?1:1+Ye(t.left)+Ye(t.right)}function Xe(t,e,i){return We=new Float32Array(i),Ge=new Uint32Array(i),He=new Uint16Array(i),qe=new Uint8Array(i),Ke(t,e)}function Ke(t,e){const i=t/4,n=t/2,s="count"in e,r=e.boundingData;for(let t=0;t<6;t++)We[i+t]=r[t];if(s)return e.buffer?(qe.set(new Uint8Array(e.buffer),t),t+e.buffer.byteLength):(Ge[i+6]=e.offset,He[n+14]=e.count,He[n+15]=65535,t+ve);{const{left:n,right:s,splitAxis:r}=e;let o=Ke(t+ve,n);const a=o/ve-t/ve;if(a>Ze)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return Ge[i+6]=a,Ge[i+7]=r,Ke(o,s)}}function Qe(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 $e;return Ne(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=Pe(e),-1!==o&&(a=(e[o]+e[o+3])/2);else if(1===r)o=Pe(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=Ie(t);let l=be*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)/Fe;if(s<8){const e=[...Ue];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;Ee(s,i,o)}e.sort(Re);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?Ee(n,i,r.rightCacheBounds):(Ee(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=Ie(u)/r);let f=0;0!==h&&(f=Ie(d)/r);const m=1+be*(p*c+f*h);m<l&&(o=t,l=m,a=n.candidate)}}else{for(let t=0;t<Fe;t++){const e=Ue[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>=Fe&&(s=31);const r=Ue[s];r.count++,Ee(e,i,r.bounds)}const e=Ue[31];Te(e.bounds,e.rightCacheBounds);for(let t=30;t>=0;t--){const e=Ue[t],i=Ue[t+1];Me(e.bounds,i.rightCacheBounds,e.rightCacheBounds)}let d=0;for(let e=0;e<31;e++){const i=Ue[e],n=i.count,c=i.bounds,h=Ue[e+1].rightCacheBounds;0!==n&&(0===d?Te(c,je):Me(c,je,je)),d+=n;let u=0,p=0;0!==d&&(u=Ie(je)/r);const f=s-d;0!==f&&(p=Ie(h)/r);const m=1+be*(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 $e,o=n,a=w-n;i.left=r,Ne(e,o,a,r.boundingData,p),t(r,o,a,p,h+1);const l=new $e,c=w,u=s-a;i.right=l,Ne(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 Je(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=Qe(t,a,n.offset,n.count,e,o),r=Ye(s),l=new i(ve*r);return Xe(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 ei{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 ii=new ei;let ni,si;const ri=[],oi=new ti(()=>new n.Box3);function ai(t,e,i,n,s,r){ni=oi.getPrimitive(),si=oi.getPrimitive(),ri.push(ni,si),ii.setBuffer(t._roots[e]);const o=li(0,t.geometry,i,n,s,r);ii.clearBuffer(),oi.releasePrimitive(ni),oi.releasePrimitive(si),ri.pop(),ri.pop();const a=ri.length;return a>0&&(si=ri[a-1],ni=ri[a-2]),o}function li(t,e,i,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=ii;let h=2*t;if(De(h,l)){const e=ze(t,c),i=ke(h,l);return Ae(t,a,ni),n(e,i,!1,o,r+t/8,ni)}{let h=function(t){const{uint16Array:e,uint32Array:i}=ii;let n=2*t;for(;!De(n,e);)n=2*(t=Be(t));return ze(t,i)},u=function(t){const{uint16Array:e,uint32Array:i}=ii;let n=2*t;for(;!De(n,e);)n=2*(t=Oe(t,i));return ze(t,i)+ke(n,e)};const d=Be(t),p=Oe(t,c);let f,m,g,w,y=d,_=p;if(s&&(g=ni,w=si,Ae(y,a,g),Ae(_,a,w),f=s(g),m=s(w),m<f)){y=p,_=d;const t=f;f=m,m=t,g=w}g||(g=ni,Ae(y,a,g));const b=i(g,De(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&&li(y,e,i,n,s,r,o+1);if(v)return!0;w=si,Ae(_,a,w);const x=i(w,De(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&&li(_,e,i,n,s,r,o+1);return!!C}}const ci=new ii.constructor,hi=new ii.constructor,ui=new ti(()=>new n.Box3),di=new n.Box3,pi=new n.Box3,fi=new n.Box3,mi=new n.Box3;let gi=!1;function wi(t,e,i,n,s,r=0,o=0,a=0,l=0,c=null,h=!1){let u,d;h?(u=hi,d=ci):(u=ci,d=hi);const p=u.float32Array,f=u.uint32Array,m=u.uint16Array,g=d.float32Array,w=d.uint32Array,y=d.uint16Array,_=2*e,b=De(2*t,m),v=De(_,y);let x=!1;if(v&&b)x=h?s(ze(e,w),ke(2*e,y),ze(t,f),ke(2*t,m),l,o+e/8,a,r+t/8):s(ze(t,f),ke(2*t,m),ze(e,w),ke(2*e,y),a,r+t/8,l,o+e/8);else if(v){const c=ui.getPrimitive();Ae(e,g,c),c.applyMatrix4(i);const u=Be(t),d=Oe(t,f);Ae(u,p,di),Ae(d,p,pi);const m=c.intersectsBox(di),w=c.intersectsBox(pi);x=m&&wi(e,u,n,i,s,o,r,l,a+1,c,!h)||w&&wi(e,d,n,i,s,o,r,l,a+1,c,!h),ui.releasePrimitive(c)}else{const u=Be(e),d=Oe(e,w);Ae(u,g,fi),Ae(d,g,mi);const m=c.intersectsBox(fi),y=c.intersectsBox(mi);if(m&&y)x=wi(t,u,i,n,s,r,o,a,l+1,c,h)||wi(t,d,i,n,s,r,o,a,l+1,c,h);else if(m)if(b)x=wi(t,u,i,n,s,r,o,a,l+1,c,h);else{const e=ui.getPrimitive();e.copy(fi).applyMatrix4(i);const c=Be(t),d=Oe(t,f);Ae(c,p,di),Ae(d,p,pi);const m=e.intersectsBox(di),g=e.intersectsBox(pi);x=m&&wi(u,c,n,i,s,o,r,l,a+1,e,!h)||g&&wi(u,d,n,i,s,o,r,l,a+1,e,!h),ui.releasePrimitive(e)}else if(y)if(b)x=wi(t,d,i,n,s,r,o,a,l+1,c,h);else{const e=ui.getPrimitive();e.copy(mi).applyMatrix4(i);const c=Be(t),u=Oe(t,f);Ae(c,p,di),Ae(u,p,pi);const m=e.intersectsBox(di),g=e.intersectsBox(pi);x=m&&wi(d,c,n,i,s,o,r,l,a+1,e,!h)||g&&wi(d,u,n,i,s,o,r,l,a+1,e,!h),ui.releasePrimitive(e)}}return x}const yi=new n.Box3,_i=new Float32Array(6);class bi{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){Je(this,t={...Se,...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,u,d]=_i;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,_i,0);const[t,e,r,o,a,l]=_i,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)*xe,i[m+2]=h,i[m+3]=p+(Math.abs(h)+p)*xe,i[m+4]=u,i[m+5]=f+(Math.abs(u)+f)*xe}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/ve;for(let e=0;e<o;e++){const i=8*e;De(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=De(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=Be(r),a=Oe(r,n),c=Ve(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/ve-1;t>=0;t--){const e=8*t,i=2*e;if(De(i,s)){const t=ze(e,n),o=ke(i,s);this.writePrimitiveRangeBounds(t,o,_i,0),r.set(_i,e)}else{const t=Be(e),i=Oe(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=>{Ae(0,new Float32Array(e),yi),t.union(yi)}),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=ai(this,t,i,n,e,l),a)break;l+=s.byteLength/ve}return a}bvhcast(t,e,i){let{intersectsRanges:s}=i;return function(t,e,i,s){if(gi)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");gi=!0;const r=t._roots,o=e._roots;let a,l=0,c=0;const h=(new n.Matrix4).copy(i).invert();for(let t=0,e=r.length;t<e;t++){ci.setBuffer(r[t]),c=0;const e=ui.getPrimitive();Ae(Le(0),ci.float32Array,e),e.applyMatrix4(h);for(let t=0,n=o.length;t<n&&(hi.setBuffer(o[t]),a=wi(0,0,i,h,s,l,c,0,0,e),hi.clearBuffer(),c+=o[t].byteLength/ve,!a);t++);if(ui.releasePrimitive(e),ci.clearBuffer(),l+=r[t].byteLength/ve,a)break}return gi=!1,a}(this,t,e,s)}}function vi(t){return t.index?t.index.count:t.attributes.position.count}function xi(t){return vi(t)/3}function Ci(t,e){if(!t.index){const i=t.attributes.position.count,s=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 n.BufferAttribute(s,1));for(let t=0;t<i;t++)s[t]=t}}function Si(t,e,i){const n=function(t,e,i){const n=vi(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=vi(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 Ai extends bi{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={...Se,...e})[Ce]||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}(Si(e,t.range,i),t.useSharedArrayBuffer);this._indirectBuffer=n}else Ci(e,t);super.init(t),!e.boundingBox&&t.setBoundingBox&&(e.boundingBox=this.getBoundingBox(new n.Box3))}getRootRanges(t){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:Si(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Pi{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}}Pi.prototype.setFromBox=function(){const t=new n.Vector3;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 Ti=function(){const t=new n.Vector3,e=new n.Vector3,i=new n.Vector3;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}}(),Mi=function(){const t=new n.Vector2,e=new n.Vector3,i=new n.Vector3;return function(n,s,r,o){Ti(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))}}}(),Ei=function(){const t=new n.Vector3,e=new n.Vector3,i=new n.Plane,s=new n.Line3;return function(n,r){const{radius:o,center:a}=n,{a:l,b:c,c:h}=r;s.start=l,s.end=c;if(s.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;s.start=l,s.end=h;if(s.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;s.start=c,s.end=h;if(s.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}}(),Ii=["x","y","z"],Di=1e-15;function zi(t){return Math.abs(t)<Di}class ki extends n.Triangle{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new n.Vector3),this.satBounds=new Array(4).fill().map(()=>new Pi),this.points=[this.a,this.b,this.c],this.plane=new n.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new n.Line3,this.needsUpdate=!0}intersectsSphere(t){return Ei(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<Di?m<Di||g<Di?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):m<Di?g<Di?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):g<Di&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(o,t),this.needsUpdate=!1}}ki.prototype.closestPointToSegment=function(){const t=new n.Vector3,e=new n.Vector3,i=new n.Line3;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]),Mi(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)}}(),ki.prototype.intersectsTriangle=function(){const t=new ki,e=new Pi,i=new Pi,s=new n.Vector3,r=new n.Vector3,o=new n.Vector3,a=new n.Vector3,l=new n.Line3,c=new n.Line3,h=new n.Vector3,u=new n.Vector2,d=new n.Vector2;function p(t,n,r,o){const l=s;t.isDegenerateIntoPoint||t.isDegenerateIntoSegment?l.copy(n.plane.normal):l.copy(t.plane.normal);const c=t.satBounds,h=t.satAxes;for(let s=1;s<4;s++){const r=c[s],o=h[s];if(e.setFromPoints(o,n.points),r.isSeparated(e))return!1;if(a.copy(l).cross(o),e.setFromPoints(a,t.points),i.setFromPoints(a,n.points),e.isSeparated(i))return!1}const u=n.satBounds,d=n.satAxes;for(let s=1;s<4;s++){const r=u[s],o=d[s];if(e.setFromPoints(o,t.points),r.isSeparated(e))return!1;if(a.crossVectors(l,o),e.setFromPoints(a,t.points),i.setFromPoints(a,n.points),e.isSeparated(i))return!1}return r&&(o||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 f(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 m(t,e,i,n,s,r,o,a,l,c,h){if(s>0)f(t.c,t.a,t.b,n,e,i,l,o,a,c,h);else if(r>0)f(t.b,t.a,t.c,i,e,n,a,o,l,c,h);else if(a*l>0||0!=o)f(t.a,t.b,t.c,e,i,n,o,a,l,c,h);else if(0!=a)f(t.b,t.a,t.c,i,e,n,a,o,l,c,h);else{if(0==l)return!0;f(t.c,t.a,t.b,n,e,i,l,o,a,c,h)}return!1}function g(t,e,i,n){const r=e.degenerateSegment,o=t.plane.distanceToPoint(r.start),a=t.plane.distanceToPoint(r.end);return zi(o)?zi(a)?p(t,e,i,n):(i&&(i.start.copy(r.start),i.end.copy(r.start)),t.containsPoint(r.start)):zi(a)?(i&&(i.start.copy(r.end),i.end.copy(r.end)),t.containsPoint(r.end)):null!=t.plane.intersectLine(r,s)&&(i&&(i.start.copy(s),i.end.copy(s)),t.containsPoint(s))}function w(t,e,i){const n=e.a;return!(!zi(t.plane.distanceToPoint(n))||!t.containsPoint(n))&&(i&&(i.start.copy(n),i.end.copy(n)),!0)}function y(t,e,i){const n=t.degenerateSegment,r=e.a;return n.closestPointToPoint(r,!0,s),r.distanceToSquared(s)<1e-30&&(i&&(i.start.copy(r),i.end.copy(r)),!0)}return function(e,i=null,n=!1){this.needsUpdate&&this.update(),e.isExtendedTriangle?e.needsUpdate&&e.update():(t.copy(e),t.update(),e=t);const a=function(t,e,i,n){if(t.isDegenerateIntoSegment){if(e.isDegenerateIntoSegment){const n=t.degenerateSegment,a=e.degenerateSegment,l=r,c=o;n.delta(l),a.delta(c);const h=s.subVectors(a.start,n.start),u=l.x*c.y-l.y*c.x;if(zi(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)&&(!!zi(n.start.z+l.z*d-(a.start.z+c.z*p))&&(i&&(i.start.copy(n.start).addScaledVector(l,d),i.end.copy(n.start).addScaledVector(l,d)),!0))}return e.isDegenerateIntoPoint?y(t,e,i):g(e,t,i,n)}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?y(e,t,i):w(e,t,i):e.isDegenerateIntoPoint?w(t,e,i):e.isDegenerateIntoSegment?g(t,e,i,n):void 0}(this,e,i,n);if(void 0!==a)return a;const f=this.plane,_=e.plane;let b=_.distanceToPoint(this.a),v=_.distanceToPoint(this.b),x=_.distanceToPoint(this.c);zi(b)&&(b=0),zi(v)&&(v=0),zi(x)&&(x=0);const C=b*v,S=b*x;if(C>0&&S>0)return!1;let A=f.distanceToPoint(e.a),P=f.distanceToPoint(e.b),T=f.distanceToPoint(e.c);zi(A)&&(A=0),zi(P)&&(P=0),zi(T)&&(T=0);const M=A*P,E=A*T;if(M>0&&E>0)return!1;r.copy(f.normal),o.copy(_.normal);const I=r.cross(o);let D=0,z=Math.abs(I.x);const k=Math.abs(I.y);k>z&&(z=k,D=1);Math.abs(I.z)>z&&(D=2);const B=Ii[D],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(m(this,O,V,L,C,S,b,v,x,u,l))return p(this,e,i,n);if(m(e,N,F,R,M,E,A,P,T,d,c))return p(this,e,i,n);if(u.y<u.x){const t=u.y;u.y=u.x,u.x=t,h.copy(l.start),l.start.copy(l.end),l.end.copy(h)}if(d.y<d.x){const t=d.y;d.y=d.x,d.x=t,h.copy(c.start),c.start.copy(c.end),c.end.copy(h)}return!(u.y<d.x||d.y<u.x)&&(i&&(d.x>u.x?i.start.copy(c.start):i.start.copy(l.start),d.y<u.y?i.end.copy(c.end):i.end.copy(l.end)),!0)}}(),ki.prototype.distanceToPoint=function(){const t=new n.Vector3;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),ki.prototype.distanceToTriangle=function(){const t=new n.Vector3,e=new n.Vector3,i=["a","b","c"],s=new n.Line3,r=new n.Line3;return function(n,o=null,a=null){const l=o||a?s:null;if(this.intersectsTriangle(n,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 s;const r=i[e],l=n[r];this.closestPointToPoint(l,t),s=l.distanceToSquared(t),s<c&&(c=s,o&&o.copy(t),a&&a.copy(l));const h=this[r];n.closestPointToPoint(h,t),s=h.distanceToSquared(t),s<c&&(c=s,o&&o.copy(h),a&&a.copy(t))}for(let l=0;l<3;l++){const h=i[l],u=i[(l+1)%3];s.set(this[h],this[u]);for(let l=0;l<3;l++){const h=i[l],u=i[(l+1)%3];r.set(n[h],n[u]),Mi(s,r,t,e);const d=t.distanceToSquared(e);d<c&&(c=d,o&&o.copy(t),a&&a.copy(e))}}return Math.sqrt(c)}}();class Bi{constructor(t,e,i){this.isOrientedBox=!0,this.min=new n.Vector3,this.max=new n.Vector3,this.matrix=new n.Matrix4,this.invMatrix=new n.Matrix4,this.points=new Array(8).fill().map(()=>new n.Vector3),this.satAxes=new Array(3).fill().map(()=>new n.Vector3),this.satBounds=new Array(3).fill().map(()=>new Pi),this.alignedSatBounds=new Array(3).fill().map(()=>new Pi),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}}Bi.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}}(),Bi.prototype.intersectsBox=function(){const t=new Pi;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}}(),Bi.prototype.intersectsTriangle=function(){const t=new ki,e=new Array(3),i=new Pi,s=new Pi,r=new n.Vector3;return function(n){this.needsUpdate&&this.update(),n.isExtendedTriangle?n.needsUpdate&&n.update():(t.copy(n),t.update(),n=t);const o=this.satBounds,a=this.satAxes;e[0]=n.a,e[1]=n.b,e[2]=n.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=n.satBounds,c=n.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 n=a[t];for(let t=0;t<4;t++){const o=c[t];if(r.crossVectors(n,o),i.setFromPoints(r,e),s.setFromPoints(r,h),i.isSeparated(s))return!1}}return!0}}(),Bi.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}}(),Bi.prototype.distanceToPoint=function(){const t=new n.Vector3;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),Bi.prototype.distanceToBox=function(){const t=["x","y","z"],e=new Array(12).fill().map(()=>new n.Line3),i=new Array(12).fill().map(()=>new n.Line3),s=new n.Vector3,r=new n.Vector3;return function(n,o=0,a=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(n))return(a||l)&&(n.getCenter(r),this.closestPointToPoint(r,s),n.closestPointToPoint(s,r),a&&a.copy(s),l&&l.copy(r)),0;const c=o*o,h=n.min,u=n.max,d=this.points;let p=1/0;for(let t=0;t<8;t++){const e=d[t];r.copy(e).clamp(h,u);const i=e.distanceToSquared(r);if(i<p&&(p=i,a&&a.copy(e),l&&l.copy(r),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++){r.x=t?u.x:h.x,r.y=e?u.y:h.y,r.z=i?u.z:h.z,this.closestPointToPoint(r,s);const n=r.distanceToSquared(s);if(n<p&&(p=n,a&&a.copy(s),l&&l.copy(r),n<c))return Math.sqrt(n)}for(let t=0;t<12;t++){const n=e[t];for(let t=0;t<12;t++){const e=i[t];Mi(n,e,s,r);const o=s.distanceToSquared(r);if(o<p&&(p=o,a&&a.copy(s),l&&l.copy(r),o<c))return Math.sqrt(o)}}return Math.sqrt(p)}}();class Oi extends ti{constructor(){super(()=>new ki)}}const Vi=new Oi,Li=new n.Vector3,Ni=new n.Vector3;const Fi=parseInt(n.REVISION)>=169,Ri=parseInt(n.REVISION)<=161,Ui=new n.Vector3,ji=new n.Vector3,$i=new n.Vector3,Wi=new n.Vector2,Gi=new n.Vector2,Hi=new n.Vector2,qi=new n.Vector3,Zi=new n.Vector3,Yi=new n.Vector3,Xi=new n.Vector3;function Ki(t,e,i,s,r,o,a,l,c,h,u){Ui.fromBufferAttribute(e,o),ji.fromBufferAttribute(e,a),$i.fromBufferAttribute(e,l);const d=function(t,e,i,s,r,o,a,l){let c;if(c=o===n.BackSide?t.intersectTriangle(s,i,e,!0,r):t.intersectTriangle(e,i,s,o!==n.DoubleSide,r),null===c)return null;const h=t.origin.distanceTo(r);return h<a||h>l?null:{distance:h,point:r.clone()}}(t,Ui,ji,$i,Xi,c,h,u);if(d){if(s){Wi.fromBufferAttribute(s,o),Gi.fromBufferAttribute(s,a),Hi.fromBufferAttribute(s,l),d.uv=new n.Vector2;const t=n.Triangle.getInterpolation(Xi,Ui,ji,$i,Wi,Gi,Hi,d.uv);Fi||(d.uv=t)}if(r){Wi.fromBufferAttribute(r,o),Gi.fromBufferAttribute(r,a),Hi.fromBufferAttribute(r,l),d.uv1=new n.Vector2;const t=n.Triangle.getInterpolation(Xi,Ui,ji,$i,Wi,Gi,Hi,d.uv1);Fi||(d.uv1=t),Ri&&(d.uv2=d.uv1)}if(i){qi.fromBufferAttribute(i,o),Zi.fromBufferAttribute(i,a),Yi.fromBufferAttribute(i,l),d.normal=new n.Vector3;const e=n.Triangle.getInterpolation(Xi,Ui,ji,$i,qi,Zi,Yi,d.normal);d.normal.dot(t.direction)>0&&d.normal.multiplyScalar(-1),Fi||(d.normal=e)}const e={a:o,b:a,c:l,normal:new n.Vector3,materialIndex:0};if(n.Triangle.getNormal(Ui,ji,$i,e.normal),d.face=e,d.faceIndex=o,Fi){const t=new n.Vector3;n.Triangle.getBarycoord(Xi,Ui,ji,$i,t),d.barycoord=t}}return d}function Qi(t){return t&&t.isMaterial?t.side:t}function Ji(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=Ki(i,p,f,m,g,l,c,h,Qi(e[y]),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=y,!s)return t;s.push(t)}}}}else{const t=Ki(i,p,f,m,g,l,c,h,Qi(e),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=0,!s)return t;s.push(t)}}return null}function tn(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 en(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,tn(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}function nn(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(De(c,a)){const e=ze(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+ke(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=Be(t),s=Oe(t,o);let a=r,c=!1,h=!1;if(e){if(!a){const t=n/8+i/ve,r=s/8+i/ve;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 sn(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 rn(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),tn(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}function on(t,e,i,n,s,r,o){ii.setBuffer(t._roots[e]),an(0,t,i,n,s,r,o),ii.clearBuffer()}function an(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=ii,h=2*t;if(De(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++)Ji(l,e,i,t,r,o,a)}(e,i,n,ze(t,c),ke(h,l),s,r,o)}else{const l=Be(t);sn(l,a,n,r,o)&&an(l,e,i,n,s,r,o);const h=Oe(t,c);sn(h,a,n,r,o)&&an(h,e,i,n,s,r,o)}}const ln=["x","y","z"];function cn(t,e,i,n,s,r){ii.setBuffer(t._roots[e]);const o=hn(0,t,i,n,s,r);return ii.clearBuffer(),o}function hn(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=ii;let c=2*t;if(De(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=Ji(a,e,i,t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,ze(t,l),ke(c,a),s,r)}{const a=Ve(t,l),c=ln[a],h=n.direction[c]>=0;let u,d;h?(u=Be(t),d=Oe(t,l)):(u=Oe(t,l),d=Be(t));const p=sn(u,o,n,s,r)?hn(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=sn(d,o,n,s,r)?hn(d,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const un=new n.Box3,dn=new ki,pn=new ki,fn=new n.Matrix4,mn=new Bi,gn=new Bi;function wn(t,e,i,n){ii.setBuffer(t._roots[e]);const s=yn(0,t,i,n);return ii.clearBuffer(),s}function yn(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=ii;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),mn.set(i.boundingBox.min,i.boundingBox.max,n),s=mn);if(!De(l,o)){const o=Be(t),l=Oe(t,a);Ae(o,r,un);if(s.intersectsBox(un)&&yn(o,e,i,n,s))return!0;Ae(l,r,un);return!!(s.intersectsBox(un)&&yn(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,u=i.index,d=i.attributes.position,p=ze(t,a),f=ke(l,o);if(fn.copy(n).invert(),i.boundsTree){Ae(t,r,gn),gn.matrix.copy(fn),gn.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>gn.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(tn(pn,e,c,h),pn.needsUpdate=!0,t.intersectsTriangle(pn))return!0;return!1}})}{const t=xi(i);for(let e=3*p,i=3*(f+p);e<i;e+=3){tn(dn,e,c,h),dn.a.applyMatrix4(fn),dn.b.applyMatrix4(fn),dn.c.applyMatrix4(fn),dn.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(tn(pn,e,u,d),pn.needsUpdate=!0,dn.intersectsTriangle(pn))return!0}}}}const _n=new n.Matrix4,bn=new Bi,vn=new Bi,xn=new n.Vector3,Cn=new n.Vector3,Sn=new n.Vector3,An=new n.Vector3;function Pn(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),bn.set(e.boundingBox.min,e.boundingBox.max,i),bn.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,u=e.index,d=Vi.getPrimitive(),p=Vi.getPrimitive();let f=xn,m=Cn,g=null,w=null;s&&(g=Sn,w=An);let y=1/0,_=null,b=null;return _n.copy(i).invert(),vn.matrix.copy(_n),t.shapecast({boundsTraverseOrder:t=>bn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(vn.min.copy(t.min),vn.max.copy(t.max),vn.needsUpdate=!0),!0),intersectsRange:(t,n)=>{if(e.boundsTree){return e.boundsTree.shapecast({boundsTraverseOrder:t=>vn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,s)=>{for(let o=e,a=e+s;o<a;o++){tn(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++){tn(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=xi(e);s<o;s++){tn(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++){tn(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}}}}),Vi.releasePrimitive(d),Vi.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 Tn(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(De(h,a)){const e=ze(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+ke(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=Be(i),n=Oe(i,o);let s=c,a=!1,h=!1;if(e){if(!s){const i=t/8+r/ve,o=n/8+r/ve;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 Mn(t,e,i,n,s,r,o){ii.setBuffer(t._roots[e]),En(0,t,i,n,s,r,o),ii.clearBuffer()}function En(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=ii,h=2*t;if(De(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++)Ji(l,e,i,c?c[t]:t,r,o,a)}(e,i,n,ze(t,c),ke(h,l),s,r,o)}else{const l=Be(t);sn(l,a,n,r,o)&&En(l,e,i,n,s,r,o);const h=Oe(t,c);sn(h,a,n,r,o)&&En(h,e,i,n,s,r,o)}}const In=["x","y","z"];function Dn(t,e,i,n,s,r){ii.setBuffer(t._roots[e]);const o=zn(0,t,i,n,s,r);return ii.clearBuffer(),o}function zn(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=ii;let c=2*t;if(De(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=Ji(a,e,i,l?l[t]:t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,ze(t,l),ke(c,a),s,r)}{const a=Ve(t,l),c=In[a],h=n.direction[c]>=0;let u,d;h?(u=Be(t),d=Oe(t,l)):(u=Oe(t,l),d=Be(t));const p=sn(u,o,n,s,r)?zn(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=sn(d,o,n,s,r)?zn(d,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const kn=new n.Box3,Bn=new ki,On=new ki,Vn=new n.Matrix4,Ln=new Bi,Nn=new Bi;function Fn(t,e,i,n){ii.setBuffer(t._roots[e]);const s=Rn(0,t,i,n);return ii.clearBuffer(),s}function Rn(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=ii;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),Ln.set(i.boundingBox.min,i.boundingBox.max,n),s=Ln);if(!De(l,o)){const o=Be(t),l=Oe(t,a);Ae(o,r,kn);if(s.intersectsBox(kn)&&Rn(o,e,i,n,s))return!0;Ae(l,r,kn);return!!(s.intersectsBox(kn)&&Rn(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,u=i.index,d=i.attributes.position,p=ze(t,a),f=ke(l,o);if(Vn.copy(n).invert(),i.boundsTree){Ae(t,r,Nn),Nn.matrix.copy(Vn),Nn.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>Nn.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(tn(On,3*e.resolveTriangleIndex(i),c,h),On.needsUpdate=!0,t.intersectsTriangle(On))return!0;return!1}})}{const t=xi(i);for(let i=p,n=f+p;i<n;i++){const n=e.resolveTriangleIndex(i);tn(Bn,3*n,c,h),Bn.a.applyMatrix4(Vn),Bn.b.applyMatrix4(Vn),Bn.c.applyMatrix4(Vn),Bn.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(tn(On,e,u,d),On.needsUpdate=!0,Bn.intersectsTriangle(On))return!0}}}}const Un=new n.Matrix4,jn=new Bi,$n=new Bi,Wn=new n.Vector3,Gn=new n.Vector3,Hn=new n.Vector3,qn=new n.Vector3;function Zn(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),jn.set(e.boundingBox.min,e.boundingBox.max,i),jn.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,u=e.index,d=Vi.getPrimitive(),p=Vi.getPrimitive();let f=Wn,m=Gn,g=null,w=null;s&&(g=Hn,w=qn);let y=1/0,_=null,b=null;return Un.copy(i).invert(),$n.matrix.copy(Un),t.shapecast({boundsTraverseOrder:t=>jn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&($n.min.copy(t.min),$n.max.copy(t.max),$n.needsUpdate=!0),!0),intersectsRange:(n,s)=>{if(e.boundsTree){const a=e.boundsTree;return a.shapecast({boundsTraverseOrder:t=>$n.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);tn(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);tn(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=xi(e);o<a;o++){tn(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);tn(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}}}}),Vi.releasePrimitive(d),Vi.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(Un),m.applyMatrix4(Un),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function Yn(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 Xn=new Bi,Kn=new n.Ray,Qn=new n.Vector3,Jn=new n.Matrix4,ts=new n.Vector3,es=["getX","getY","getZ"];class is extends Ai{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:s,roots:r,indirectBuffer:o}=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/ve;t<e;t++){const e=8*t;De(2*e,s)||(n[e+6]=n[e+6]/8-t)}}}(r));const a=new is(e,{...i,[Ce]:!0});if(a._roots=r,a._indirectBuffer=o||null,i.setIndex){const i=e.getIndex();if(null===i){const i=new n.BufferAttribute(t.index,1,!1);e.setIndex(i)}else i.array!==s&&(i.array.set(s),i.needsUpdate=!0)}return a}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[es[t]](l),s=r[es[t]](c),o=r[es[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)*xe}}return i}raycastObject3D(t,e,i=[]){const{material:n}=t;if(void 0===n)return;Jn.copy(t.matrixWorld).invert(),Kn.copy(e.ray).applyMatrix4(Jn),ts.setFromMatrixScale(t.matrixWorld),Qn.copy(Kn.direction).multiply(ts);const s=Qn.length(),r=e.near/s,o=e.far/s;if(!0===e.firstHitOnly){let s=this.raycastFirst(Kn,n,r,o);s=Yn(s,t,e),s&&i.push(s)}else{const s=this.raycast(Kn,n,r,o);for(let n=0,r=s.length;n<r;n++){const r=Yn(s[n],t,e);r&&i.push(r)}}return i}refit(t=null){return(this.indirect?Tn:nn)(this,t)}raycast(t,e=n.FrontSide,i=0,s=1/0){const r=this._roots,o=[],a=this.indirect?Mn:on;for(let n=0,l=r.length;n<l;n++)a(this,n,e,t,o,i,s);return o}raycastFirst(t,e=n.FrontSide,i=0,s=1/0){const r=this._roots;let o=null;const a=this.indirect?Dn:cn;for(let n=0,l=r.length;n<l;n++){const r=a(this,n,e,t,i,s);null!=r&&(null==o||r.distance<o.distance)&&(o=r)}return o}intersectsGeometry(t,e){let i=!1;const n=this._roots,s=this.indirect?Fn:wn;for(let r=0,o=n.length;r<o&&(i=s(this,r,t,e),!i);r++);return i}shapecast(t){const e=Vi.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?rn:en});return Vi.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=Vi.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?t=>{const e=this.resolveTriangleIndex(t);tn(r,3*e,o,a)}:t=>{tn(r,3*t,o,a)},c=Vi.getPrimitive(),h=t.geometry.index,u=t.geometry.attributes.position,d=t.indirect?e=>{const i=t.resolveTriangleIndex(e);tn(c,3*i,h,u)}:t=>{tn(c,3*t,h,u)};if(s){if(!(t instanceof is))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 Xn.set(t.min,t.max,e),Xn.needsUpdate=!0,this.shapecast({intersectsBounds:t=>Xn.intersectsBox(t),intersectsTriangle:t=>Xn.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?Zn:Pn)(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=>(Li.copy(e).clamp(t.min,t.max),Li.distanceToSquared(e)),intersectsBounds:(t,e,i)=>i<a&&i<o,intersectsTriangle:(t,i)=>{t.closestPointToPoint(e,Li);const n=e.distanceToSquared(Li);return n<a&&(Ni.copy(Li),a=n,l=i),n<r}}),a===1/0)return null;const c=Math.sqrt(a);return i.point?i.point.copy(Ni):i.point=Ni.clone(),i.distance=c,i.faceIndex=l,i}(this,t,e,i,n)}}const ns=new n.Matrix4,ss=new n.Ray,rs=new ti(()=>new n.Line3),os=new n.Vector3,as=new n.Vector3,ls=new n.Box3,cs=["getX","getY","getZ"];class hs extends Ai{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[cs[t]](c),s=o[cs[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=rs.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsLine,scratchPrimitive:e,iterate:us});return rs.releasePrimitive(e),i}raycastObject3D(t,e,i=[]){const{matrixWorld:n}=t,{firstHitOnly:s}=e;ns.copy(n).invert(),ss.copy(e.ray).applyMatrix4(ns);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(ss.origin),intersectsBounds:t=>(ls.copy(t).expandByScalar(Math.abs(r)),ss.intersectsBox(ls)?1:0),intersectsLine:(r,c)=>{if(ss.distanceSqToSegment(r.start,r.end,os,as)>o)return;os.applyMatrix4(t.matrixWorld);const h=e.ray.origin.distanceTo(os);h<e.near||h>e.far||s&&h>=l||(l=h,c=this.resolvePrimitiveIndex(c),a={distance:h,point:as.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 us(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 ds={Mesh:n.Mesh.prototype.raycast,Line:n.Line.prototype.raycast,LineSegments:n.LineSegments.prototype.raycast,LineLoop:n.LineLoop.prototype.raycast,Points:n.Points.prototype.raycast,BatchedMesh:n.BatchedMesh.prototype.raycast},ps=new n.Mesh,fs=[];function ms(t,e){if(this.isBatchedMesh)gs.call(this,t,e);else{const{geometry:i}=this;if(i.boundsTree)i.boundsTree.raycastObject3D(this,t,e);else{let i;if(this instanceof n.Mesh)i=ds.Mesh;else if(this instanceof n.LineSegments)i=ds.LineSegments;else if(this instanceof n.LineLoop)i=ds.LineLoop;else if(this instanceof n.Line)i=ds.Line;else{if(!(this instanceof n.Points))throw new Error("BVH: Fallback raycast function not found.");i=ds.Points}i.call(this,t,e)}}}function gs(t,e){if(this.boundsTrees){const i=this.boundsTrees,s=this._drawInfo||this._instanceInfo,r=this._drawRanges||this._geometryInfo,o=this.matrixWorld;ps.material=this.material,ps.geometry=this.geometry;const a=ps.geometry.boundsTree,l=ps.geometry.drawRange;null===ps.geometry.boundingSphere&&(ps.geometry.boundingSphere=new n.Sphere);for(let n=0,a=s.length;n<a;n++){if(!this.getVisibleAt(n))continue;const a=s[n].geometryIndex;if(ps.geometry.boundsTree=i[a],this.getMatrixAt(n,ps.matrixWorld).premultiply(o),!ps.geometry.boundsTree){this.getBoundingBoxAt(a,ps.geometry.boundingBox),this.getBoundingSphereAt(a,ps.geometry.boundingSphere);const t=r[a];ps.geometry.setDrawRange(t.start,t.count)}ps.raycast(t,fs);for(let t=0,i=fs.length;t<i;t++){const i=fs[t];i.object=this,i.batchId=n,e.push(i)}fs.length=0}ps.geometry.boundsTree=a,ps.geometry.drawRange=l,ps.material=null,ps.geometry=null}else ds.BatchedMesh.call(this,t,e)}function ws(t={}){const{type:e=is}=t;return this.boundsTree=new e(this,t),this.boundsTree}function ys(){this.boundsTree=null}const _s=class t extends g{constructor(i){super(i),e(this,"onDisposed",new f),e(this,"onBeforeDispose",new f),e(this,"onFragmentsLoaded",new f),e(this,"baseCoordinationModel",""),e(this,"baseCoordinationMatrix",new u.Matrix4),e(this,"enabled",!0),e(this,"_core"),this.components.add(t.uuid,this)}static getWorker(){return i.FragmentsModels.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 i.FragmentsModels(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 u.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 u.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 bs=_s;function vs(t,e){return t[e]|t[e+1]<<8|t[e+2]<<16}class xs{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,s=new n.Vector3,r=new n.OrthographicCamera,o=new n.Box3,a=new n.WebGLRenderTarget(1,1);o.makeEmpty(),t.forEach(t=>{o.expandByObject(t)}),o.getSize(s);const l=Math.min(e.capabilities.maxTextureSize,8192),c=Math.ceil(s.x/i),h=Math.ceil(s.z/i),u=Math.ceil(c/l),d=Math.ceil(h/l);a.setSize(Math.ceil(c/u),Math.ceil(h/d));const p=.01*Math.max(s.y,1);r.rotation.x=-Math.PI/2,r.near=0,r.far=s.y+2*p,r.position.y=o.max.y+p;const f=new n.Scene,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 Cs;n.objectId=e,w.push(n),i.material=n,f.add(i)}const y=e.getClearColor(new n.Color),_=e.getClearAlpha(),b=e.getRenderTarget(),v=e.autoClear;e.autoClear=!0,e.setClearColor(0,0),e.setRenderTarget(a);const x=new Uint8Array(a.width*a.height*4),C=new Set,S=s.x/u,A=s.z/d;for(let i=0;i<u;i++)for(let n=0;n<d;n++){const s=o.min.x+S*i,l=s+S,c=o.min.z+A*n,h=(s+l)/2,u=(c+(c+A))/2;r.position.set(h,o.max.y+p,u);const d=S/2,m=A/2;r.left=-d,r.right=d,r.top=m,r.bottom=-m,r.updateProjectionMatrix(),e.render(f,r);const g=await e.readRenderTargetPixelsAsync(a,0,0,a.width,a.height,x);for(let e=0,i=g.length;e<i;e+=4){if(0===g[e+3])continue;const i=vs(g,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 a.dispose(),Array.from(C)}}class Cs extends n.ShaderMaterial{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:n.GLSL3,blending:n.NoBlending,side:n.DoubleSide,uniforms:{objectId:{value:new n.Vector4}},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 Ss=1e-16,As=new n.Vector3(0,1,0),Ps=new n.Vector3;function Ts(t){return t.delta(Ps).normalize(),Math.abs(Ps.dot(As))>=1-Ss}function Ms(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)<=Ss&&(r=!0),!o&&n.distanceToSquared(e)<=Ss&&(o=!0),r&&o)return!0}return r&&o}const Es=new n.Line3;function Is(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;Es.start.lerpVectors(i,r,s[e][0]),Es.end.lerpVectors(i,r,s[e][1]),n.push(new Float32Array([Es.start.x,Es.start.y,Es.start.z,Es.end.x,Es.end.y,Es.end.z]))}return n}const Ds=new n.Vector3(0,1,0),zs=new n.Vector3,ks=new n.Vector3,Bs=new n.Vector3,Os=new n.Triangle;function*Vs(t,e=[],i={}){const{projectionDirection:s=Ds,thresholdAngle:r=1,iterationTime:o=30}=i,a=Math.pow(10,4),l=Math.cos(n.MathUtils.DEG2RAD*r),c=t.getIndex(),h=t.getAttribute("position"),u=c?c.count:h.count,d=[0,0,0],p=["a","b","c"],f=new Array(3),m={};let g=performance.now();for(let t=0;t<u;t+=3){performance.now()-g>o&&(yield,g=performance.now()),c?(d[0]=c.getX(t),d[1]=c.getX(t+1),d[2]=c.getX(t+2)):(d[0]=t,d[1]=t+1,d[2]=t+2);const{a:i,b:r,c:u}=Os;if(i.fromBufferAttribute(h,d[0]),r.fromBufferAttribute(h,d[1]),u.fromBufferAttribute(h,d[2]),Os.getNormal(Bs),f[0]=`${Math.round(i.x*a)},${Math.round(i.y*a)},${Math.round(i.z*a)}`,f[1]=`${Math.round(r.x*a)},${Math.round(r.y*a)},${Math.round(r.z*a)}`,f[2]=`${Math.round(u.x*a)},${Math.round(u.y*a)},${Math.round(u.z*a)}`,f[0]!==f[1]&&f[1]!==f[2]&&f[2]!==f[0])for(let t=0;t<3;t++){const i=(t+1)%3,r=f[t],o=f[i],a=Os[p[t]],c=Os[p[i]],h=`${r}_${o}`,u=`${o}_${r}`;if(u in m&&m[u]){const t=m[u].normal,i=Bs.dot(t)<=l;let r=!1;if(null!==s){let e=s.dot(Bs);e=Math.abs(e)<1e-10?0:e;let i=s.dot(t);i=Math.abs(i)<1e-10?0:i,r=Math.sign(e)!==Math.sign(i)}if(i||r){const t=new n.Line3;t.start.copy(a),t.end.copy(c),e.push(t)}m[u]=null}else h in m||(m[h]={index0:d[t],index1:d[i],normal:Bs.clone()})}}for(const t in m)if(m[t]){const{index0:i,index1:s}=m[t];zs.fromBufferAttribute(h,i),ks.fromBufferAttribute(h,s);const r=new n.Line3;r.start.copy(zs),r.end.copy(ks),e.push(r)}return e}const Ls=new n.Line3;function Ns(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++){Fs(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,Ls,!0)||Ms(t,Ls)||Ms(e,Ls)||n.push(Ls.clone())))}),n}function Fs(t,e){return t.distanceTo(e)<1e-10}function Rs(t){Us(t);let e=[];return t.traverse(t=>{t.geometry&&t.visible&&e.push(t)}),e}const Us=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):Us(i)},js=new n.Matrix4,$s=new n.Matrix4;class Ws{constructor(){this.projectionDirection=new n.Vector3(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:s,thresholdAngle:r,iterationTime:o}=this;if(t.isObject3D){const a=Rs(t);let l=null;s&&(l=new n.Vector3);let c=performance.now();for(let t=0;t<a.length;t++){c-performance.now()>o&&(yield);const n=a[t];l&&($s.copy(n.matrixWorld).invert(),l.copy(s).transformDirection($s).normalize());const h=yield*Vs(n.geometry,[],{projectionDirection:l,thresholdAngle:r,iterationTime:o});Gs(h,n.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(n)}return e}return yield*Vs(t,e,{projectionDirection:s,thresholdAngle:r,iterationTime:o})}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=Rs(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 is(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);js.copy(l.matrixWorld).invert().multiply(c.matrixWorld);const d=Ns(h,u,js,[]);Gs(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 is(t,{maxLeafSize:1}):(i=t,t=i.geometry),js.identity(),Ns(i,i,js,e)}}}function Gs(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 Hs extends bi{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 qs=new n.Vector3(0,1,0),Zs=new n.Plane,Ys=new n.Vector3,Xs=new n.Vector3;function Ks(t,e,i){t.needsUpdate&&t.update(),Zs.copy(t.plane),Zs.normal.dot(qs)<0&&(Zs.normal.multiplyScalar(-1),Zs.constant*=-1);const s=Zs.distanceToPoint(e.start),r=Zs.distanceToPoint(e.end),o=Math.abs(s)<1e-16,a=s<0,l=r<0;if(e.delta(Xs).normalize(),Math.abs(Zs.normal.dot(Xs))<1e-16)return!(o||!a)&&(i.copy(e),!0);if(a&&l)return i.copy(e),!0;if(!a&&!l)return!1;{const t=n.MathUtils.mapLinear(0,s,r,0,1);if(e.at(t,Ys),a)return i.start.copy(e.start),i.end.copy(Ys),!0;if(l)return i.end.copy(e.end),i.start.copy(Ys),!0}return!1}const Qs=new n.Plane,Js=new n.Vector3,tr=new n.Vector3,er=new ki,ir=new n.Line3,nr=new n.Line3,sr=new n.Vector3,rr=new n.Vector3,or=new n.Vector3;function ar(t,e,i=new n.Line3){if(er.copy(e),er.a.y=0,er.b.y=0,er.c.y=0,er.update(),ir.copy(t),ir.start.y=0,ir.end.y=0,er.getArea()<=1e-16)return null;const s=ir.distance();ir.delta(sr).divideScalar(s),rr.copy(sr).cross(er.plane.normal).normalize(),Qs.setFromNormalAndCoplanarPoint(rr,ir.start);let r=0;const{points:o}=er;for(let t=0;t<3;t++){const e=o[t],i=o[(t+1)%3],n=Qs.distanceToPoint(e),s=Qs.distanceToPoint(i),a=Math.abs(n)<1e-16,l=Math.abs(s)<1e-16;let c=!1;if(!a&&!l&&n*s<0){const t=n/(n-s);Js.lerpVectors(e,i,t),c=!0}if((c&&!l||a)&&(a&&!c&&Js.copy(e),0===r?nr.start.copy(Js):nr.end.copy(Js),r++,2===r))break}if(2===r){if(nr.delta(or).normalize(),sr.dot(or)<0){const t=nr.start;nr.start=nr.end,nr.end=t}const e=0,n=tr.subVectors(ir.end,ir.start).dot(sr),r=tr.subVectors(nr.start,ir.start).dot(sr),o=tr.subVectors(nr.end,ir.start).dot(sr);return n<=r||o<=e?null:(t.at(Math.max(e,r)/s,i.start),t.at(Math.min(n,o)/s,i.end),i)}return null}const lr=new n.Vector3,cr=new n.Vector3,hr=new n.Vector3;function ur(t,e,i){const n=function(t,e){t.delta(lr),cr.subVectors(e.start,t.start),hr.subVectors(e.end,t.start);const i=lr.length();let n=cr.length()/i,s=hr.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&&(dr(n,i),!0)}function dr(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 pr=new n.Vector3(0,1,0),fr=new n.Line3,mr=new n.Line3,gr=new ki;function wr(t,e,i,s,r=null){const{geometry:o,matrixWorld:a,material:l}=i,c=l.side,h=a.determinant()<0,u=t.lines;t.bvhcast(e,a,{intersectsRanges:(t,e,i,l)=>{r&&(r.candidates+=e*l);for(let d=i,p=l+i;d<p;d++){let i=3*d+0,l=3*d+1,p=3*d+2;o.index&&(i=o.index.getX(i),l=o.index.getX(l),p=o.index.getX(p));const{a:f,b:m,c:g}=gr;if(f.fromBufferAttribute(o.attributes.position,i).applyMatrix4(a),m.fromBufferAttribute(o.attributes.position,l).applyMatrix4(a),g.fromBufferAttribute(o.attributes.position,p).applyMatrix4(a),gr.needsUpdate=!0,gr.update(),c!==n.DoubleSide){if(gr.plane.normal.dot(pr)!==h===(c===n.BackSide)){r&&(r.backFaceCulled+=e);continue}}const w=Math.max(f.y,m.y,g.y),y=Math.min(f.y,m.y,g.y),_=gr.plane.normal;let b=_.x,v=_.y,x=_.z,C=gr.plane.constant;v<0&&(b=-b,v=-v,x=-x,C=-C);for(let i=t,n=e+t;i<n;i++){const t=u[i],e=Math.min(t.start.y,t.end.y),n=Math.max(t.start.y,t.end.y);if(w<=e){r&&r.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,s=-n,c=i,h=f.x-t.start.x,u=f.z-t.start.z,d=m.x-t.start.x,p=m.z-t.start.z,w=g.x-t.start.x,y=g.z-t.start.z,_=h*i+u*n,b=d*i+p*n,v=w*i+y*n,x=1/e,C=Math.min(_,b,v);if(Math.max(_,b,v)<0||C>x){r&&r.xzBoundsCulled++;continue}const S=h*s+u*c,A=d*s+p*c,P=w*s+y*c,T=Math.min(S,A,P),M=Math.max(S,A,P);if(T>0||M<0){r&&r.xzBoundsCulled++;continue}}const c=b*t.start.x+v*t.start.y+x*t.start.z+C,h=b*t.end.x+v*t.end.y+x*t.end.z+C;if(c>=0&&h>=0)r&&r.planeTrimCulled++;else if(Ms(gr,t))r&&r.triangleEdgeCulled++;else{if(n<y)fr.copy(t);else if(!Ks(gr,t,fr)){r&&r.planeTrimCulled++;continue}fr.distance()<1e-10?r&&r.distThresholdCulled++:ar(fr,gr,mr)?(r&&r.used++,ur(t,mr,s[i])):r&&r.noOverlapCulled++}}}}})}gr.update=()=>{gr.plane.setFromCoplanarPoints(...gr.points)};let yr=!1;const _r={},br={};let vr=null,xr=0,Cr=0;const Sr={get enabled(){return yr},set enabled(t){yr=t},reset(){for(const t in _r)delete _r[t];for(const t in br)delete br[t];vr=null,xr=0,Cr=0},setStat(t,e){br[t]=e},startTotal(){yr&&(Cr=performance.now())},startStep(t){yr&&(null!==vr&&this.endStep(),vr=t,xr=performance.now())},endStep(){if(!yr||null===vr)return;const t=performance.now()-xr;_r[vr]=t,vr=null},printSummary(){if(!yr)return;null!==vr&&this.endStep();const t=performance.now()-Cr;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(br).length>0){console.log("\n--- Stats ---");for(const[t,e]of Object.entries(br))console.log(` ${t}: ${e}`)}console.log("")}},Ar=1e-5,Pr=1e-16,Tr=1e-16;function Mr(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 Er=null;async function Ir(t,e,i,n,s=null){const o=await async function(){return null===Er&&(Er=new d.WebGPURenderer,await Er.init()),Er}();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 a=r.instancedArray(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");Sr.enabled&&console.log("Number of meshes:",e.length),Sr.enabled&&console.log("Group count:",t.groupCount);const l=[];{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++}l.push({start:t,end:i}),t=i}}Sr.enabled&&console.log(`Split ${e.length} meshes into ${l.length} batches`);let c=0,h=0,u=0,p=0,f=0;for(let i=0;i<l.length;i++){const{start:d,end:m}=l[i],g=m-d;Sr.enabled&&console.log(`Processing batch ${i+1}/${l.length} (meshes ${d}-${m-1})`);let w=0,y=0;const _=[];for(let t=d;t<m;t++){const i=e[t].geometry;_.push(y/3),w+=i.attributes.position.array.length,y+=i.index.array.length}const b=new Float32Array(w),v=new Uint32Array(y);let x=0,C=0,S=0;for(let t=d;t<m;t++){const i=e[t].geometry,n=i.attributes.position.array,s=i.index.array;b.set(n,x),x+=n.length;for(let t=0;t<s.length;t++)v[C+t]=s[t]+S;C+=s.length,S+=i.attributes.position.count}const A=new Float32Array(16*g);for(let t=d;t<m;t++){const i=t-d;A.set(e[t].matrixWorld.elements,16*i)}const P=[];for(let e=0;e<t.groupCount;e++){const i=t.meshIndex[e];if(i>=d&&i<m){const n=i-d,s=_[n]+t.meshOffsets[e];P.push({edgeOffset:t.edgeOffsets[e],edgeCount:t.edgeCounts[e],triOffset:s,triCount:t.meshCounts[e],meshIdx:n})}}if(0===P.length){Sr.enabled&&console.log(` Batch ${i+1}: no groups, skipping`);continue}const T=new Uint32Array(5*P.length);for(let t=0;t<P.length;t++){const e=P[t],i=5*t;T[i+0]=e.edgeOffset,T[i+1]=e.edgeCount,T[i+2]=e.triOffset,T[i+3]=e.triCount,T[i+4]=e.meshIdx}let M=0;for(let t=0;t<P.length;t++)M+=P[t].edgeCount*P[t].triCount;s&&(s.candidates+=M);let E=Math.min(Math.ceil(.1*M),2e6),I=Math.max(E,1e4);Sr.enabled&&console.log(` Batch ${i+1}: ${P.length} groups, ${w/3} vertices, ${y/3} triangles, ${M} pairs, buffer for ${I} overlaps`);const D=performance.now(),z=r.instancedArray(b,"float"),k=r.instancedArray(v,"uint"),B=r.instancedArray(A,"float"),O=r.instancedArray(T,"uint");let V=r.instancedArray(new Uint32Array([0]),"uint").toAtomic(),L=r.instancedArray(new Float32Array(3*I),"float");p+=performance.now()-D;const N=performance.now(),F=r.Fn(()=>{const t=r.instanceIndex.mul(5),e=O.element(t),i=O.element(t.add(1)),n=O.element(t.add(2)),s=O.element(t.add(3)),o=O.element(t.add(4)).mul(16),l=r.mat4(B.element(o),B.element(o.add(1)),B.element(o.add(2)),B.element(o.add(3)),B.element(o.add(4)),B.element(o.add(5)),B.element(o.add(6)),B.element(o.add(7)),B.element(o.add(8)),B.element(o.add(9)),B.element(o.add(10)),B.element(o.add(11)),B.element(o.add(12)),B.element(o.add(13)),B.element(o.add(14)),B.element(o.add(15)));r.Loop({start:r.int(0),end:s.toInt(),type:"int",condition:"<",name:"triIdx"},({triIdx:t})=>{const s=n.add(t.toUint()).mul(3),o=k.element(s),c=k.element(s.add(1)),h=k.element(s.add(2)),u=r.vec3(z.element(o.mul(3)),z.element(o.mul(3).add(1)),z.element(o.mul(3).add(2))),d=r.vec3(z.element(c.mul(3)),z.element(c.mul(3).add(1)),z.element(c.mul(3).add(2))),p=r.vec3(z.element(h.mul(3)),z.element(h.mul(3).add(1)),z.element(h.mul(3).add(2))),f=l.mul(r.vec4(u,r.float(1))).xyz,m=l.mul(r.vec4(d,r.float(1))).xyz,g=l.mul(r.vec4(p,r.float(1))).xyz,w=m.sub(f),y=g.sub(f),_=r.cross(w,y),b=_.dot(_);r.If(b.lessThan(r.float(4e-16*Pr)),()=>{r.Continue()}),r.If(_.y.lessThan(0),()=>{r.Continue()});const v=r.max(f.y,r.max(m.y,g.y));r.Loop({start:r.int(0),end:i.toInt(),type:"int",condition:"<",name:"edgeIdx"},({edgeIdx:t})=>{const i=e.add(t.toUint()),n=i.mul(6),s=r.vec3(a.element(n),a.element(n.add(1)),a.element(n.add(2))),o=r.vec3(a.element(n.add(3)),a.element(n.add(4)),a.element(n.add(5))),l=r.min(s.y,o.y);r.If(v.lessThanEqual(l),()=>{r.Continue()});const c=r.normalize(_),h=c.dot(f).negate(),u=c.y.lessThan(0),d=r.select(u,c.negate(),c),p=r.select(u,h.negate(),h),w=d.dot(s).add(p),y=d.dot(o).add(p),b=w.lessThan(0),x=y.lessThan(0),C=r.abs(w).lessThan(r.float(Ar)),S=b.not().and(x.not()),A=y.sub(w),P=r.abs(A).lessThan(r.float(Ar)),T=P.and(C.or(b.not()));r.If(T,()=>{r.Continue()}),r.If(S.and(P.not()),()=>{r.Continue()});const M=w.negate().div(A),E=r.mix(s,o,M),D=r.vec3(r.select(P.or(b),s.x,E.x),r.select(P.or(b),s.y,E.y),r.select(P.or(b),s.z,E.z)),z=r.vec3(r.select(P.or(x),o.x,E.x),r.select(P.or(x),o.y,E.y),r.select(P.or(x),o.z,E.z)),k=z.sub(D),B=k.dot(k);r.If(B.lessThan(r.float(Ar)),()=>{r.Continue()});const O=s.sub(f),N=s.sub(m),F=s.sub(g),R=o.sub(f),U=o.sub(m),j=o.sub(g),$=O.dot(O).lessThanEqual(r.float(Ar)),W=N.dot(N).lessThanEqual(r.float(Ar)),G=F.dot(F).lessThanEqual(r.float(Ar)),H=R.dot(R).lessThanEqual(r.float(Ar)),q=U.dot(U).lessThanEqual(r.float(Ar)),Z=j.dot(j).lessThanEqual(r.float(Ar)),Y=$.or(W).or(G),X=H.or(q).or(Z),K=Y.and(X);r.If(K,()=>{r.Continue()});const Q=r.vec3(f.x,r.float(0),f.z),J=r.vec3(m.x,r.float(0),m.z),tt=r.vec3(g.x,r.float(0),g.z),et=r.vec3(D.x,r.float(0),D.z),it=r.vec3(z.x,r.float(0),z.z),nt=r.vec3(s.x,r.float(0),s.z),st=r.vec3(o.x,r.float(0),o.z).sub(nt),rt=st.dot(st);r.If(rt.lessThan(r.float(Ar)),()=>{r.Continue()});const ot=rt.sqrt(),at=J.sub(Q),lt=tt.sub(Q),ct=r.cross(at,lt),ht=ct.dot(ct);r.If(ht.lessThanEqual(r.float(4e-16*Pr)),()=>{r.Continue()});const ut=it.sub(et),dt=ut.dot(ut);r.If(dt.lessThan(r.float(Ar)),()=>{r.Continue()});const pt=dt.sqrt(),ft=ut.div(pt),mt=st.div(ot),gt=r.normalize(ct),wt=r.cross(ft,gt),yt=r.float(0).toVar(),_t=r.float(0).toVar(),bt=r.float(0).toVar(),vt=r.float(0).toVar(),xt=r.uint(0).toVar(),Ct=wt.dot(Q.sub(et)),St=wt.dot(J.sub(et)),At=r.abs(Ct).lessThan(r.float(Tr)),Pt=r.abs(St).lessThan(r.float(Tr)),Tt=At.not().and(Pt.not()).and(Ct.mul(St).lessThan(0));r.If(Tt,()=>{const t=Ct.div(Ct.sub(St)),e=r.mix(Q.x,J.x,t),i=r.mix(Q.z,J.z,t);r.If(xt.equal(0),()=>{yt.assign(e),_t.assign(i)}).Else(()=>{bt.assign(e),vt.assign(i)}),xt.addAssign(1)}).ElseIf(At,()=>{r.If(xt.equal(0),()=>{yt.assign(Q.x),_t.assign(Q.z)}).Else(()=>{bt.assign(Q.x),vt.assign(Q.z)}),xt.addAssign(1)});const Mt=St,Et=wt.dot(tt.sub(et)),It=Pt,Dt=r.abs(Et).lessThan(r.float(Tr)),zt=It.not().and(Dt.not()).and(Mt.mul(Et).lessThan(0));r.If(xt.lessThan(2),()=>{r.If(zt,()=>{const t=Mt.div(Mt.sub(Et)),e=r.mix(J.x,tt.x,t),i=r.mix(J.z,tt.z,t);r.If(xt.equal(0),()=>{yt.assign(e),_t.assign(i)}).Else(()=>{bt.assign(e),vt.assign(i)}),xt.addAssign(1)}).ElseIf(It.and(Tt.not()).and(At.not()),()=>{r.If(xt.equal(0),()=>{yt.assign(J.x),_t.assign(J.z)}).Else(()=>{bt.assign(J.x),vt.assign(J.z)}),xt.addAssign(1)})});const kt=Et,Bt=Ct,Ot=Dt,Vt=At,Lt=Ot.not().and(Vt.not()).and(kt.mul(Bt).lessThan(0));r.If(xt.lessThan(2),()=>{r.If(Lt,()=>{const t=kt.div(kt.sub(Bt)),e=r.mix(tt.x,Q.x,t),i=r.mix(tt.z,Q.z,t);r.If(xt.equal(0),()=>{yt.assign(e),_t.assign(i)}).Else(()=>{bt.assign(e),vt.assign(i)}),xt.addAssign(1)}).ElseIf(Ot.and(zt.not()).and(It.not()),()=>{r.If(xt.equal(0),()=>{yt.assign(tt.x),_t.assign(tt.z)}).Else(()=>{bt.assign(tt.x),vt.assign(tt.z)}),xt.addAssign(1)})}),r.If(xt.notEqual(2),()=>{r.Continue()});const Nt=r.vec3(yt,r.float(0),_t),Ft=r.vec3(bt,r.float(0),vt).sub(Nt).dot(ft),Rt=r.vec3(yt,r.float(0),_t).toVar(),Ut=r.vec3(bt,r.float(0),vt).toVar();r.If(Ft.lessThan(0),()=>{const t=yt,e=_t;Rt.x.assign(bt),Rt.z.assign(vt),Ut.x.assign(t),Ut.z.assign(e)});const jt=r.float(0),$t=pt,Wt=Rt.sub(et).dot(ft),Gt=Ut.sub(et).dot(ft),Ht=$t.lessThanEqual(Wt).or(Gt.lessThanEqual(jt));r.If(Ht,()=>{r.Continue()});const qt=r.max(jt,Wt),Zt=r.min($t,Gt),Yt=et.add(ft.mul(qt)),Xt=et.add(ft.mul(Zt)),Kt=Yt.sub(nt).dot(mt).div(ot),Qt=Xt.sub(nt).dot(mt).div(ot),Jt=r.max(r.float(0),r.min(r.float(1),Kt)),te=r.max(r.float(0),r.min(r.float(1),Qt)),ee=r.abs(te.sub(Jt));r.If(ee.lessThanEqual(r.float(Tr)),()=>{r.Continue()});const ie=r.atomicAdd(V.element(0),1);r.If(ie.lessThan(r.uint(I)),()=>{const t=ie.mul(3);L.element(t).assign(i.toFloat()),L.element(t.add(1)).assign(Jt),L.element(t.add(2)).assign(te)})})})})().compute(P.length);f+=performance.now()-N;const R=performance.now();await o.computeAsync(F),c+=performance.now()-R;const U=performance.now(),j=await o.getArrayBufferAsync(V.value),$=new Uint32Array(j)[0];if(s&&(s.used+=Math.min($,I)),Sr.enabled&&console.log(` Batch ${i+1}: ${$} overlaps found (capacity: ${I})`),$>I&&Sr.enabled&&console.warn(` WARNING: Overlap buffer overflow! ${$} > ${I}. Some occlusion data lost.`),$>0){const t=await o.getArrayBufferAsync(L.value),e=new Float32Array(t);h+=performance.now()-U;const i=performance.now(),s=Math.min($,I);for(let t=0;t<s;t++){const i=3*t,s=Math.round(e[i]);dr([e[i+1],e[i+2]],n[s])}u+=performance.now()-i,Sr.enabled&&console.log(` Processed ${s} overlaps into hiddenOverlapMap`)}else h+=performance.now()-U}o.dispose(),Er=null;const m=p+f+c+h+u;Sr.enabled&&(console.log(`WebGPU timing breakdown (total: ${m.toFixed(1)}ms):`),console.log(` Buffer creation: ${p.toFixed(1)}ms`),console.log(` Shader build: ${f.toFixed(1)}ms`),console.log(` GPU compute: ${c.toFixed(1)}ms`),console.log(` Readback: ${h.toFixed(1)}ms`),console.log(` CPU merge: ${u.toFixed(1)}ms`))}const Dr=new n.Vector3(0,1,0);function zr(t,e=null){const i=new Float32Array(6*t.length);let s=0;for(let e=0,n=t.length;e<n;e++){const n=t[e];i[s++]=n[0],i[s++]=0,i[s++]=n[2],i[s++]=n[3],i[s++]=0,i[s++]=n[5]}const r=new n.BufferGeometry,o=new n.BufferAttribute(i,3,!0);if(r.setAttribute("position",o),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];r.setAttribute("group",new n.BufferAttribute(i,1))}return r}class kr{constructor(t,e=!0){this.meshes=Rs(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 zr(this.visibleEdges,this.groupKeyToIndex?this.visibleGroupIndices:null)}getHiddenLineGeometry(){return zr(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();Sr.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 is(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]=[];Sr.startStep("Building line BVH");const h=new Hs(t,{maxLeafSize:2,strategy:2});Sr.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?Mr(h,n.get(s.geometry),s,p,t):wr(h,n.get(s.geometry),s,c,u)}if(d){let t=!1;for(Ir(p,i,h,c,u).then(()=>{t=!0});!t;)yield}const f=u.totalEdges*u.totalTriangles;if(Sr.setStat("Total edges",u.totalEdges.toLocaleString()),Sr.setStat("Total triangles",u.totalTriangles.toLocaleString()),Sr.setStat("Brute-force pairs (edges × triangles)",f.toLocaleString()),Sr.setStat("BVH candidate pairs",u.candidates.toLocaleString()),f>0&&Sr.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||(Sr.setStat("Rejected: back-face culling",u.backFaceCulled.toLocaleString()+" ("+e(u.backFaceCulled)+")"),Sr.setStat("Rejected: Y-bounds (tri below edge)",u.yBoundsCulled.toLocaleString()+" ("+e(u.yBoundsCulled)+")"),Sr.setStat("Rejected: XZ-bounds (no 2D overlap)",u.xzBoundsCulled.toLocaleString()+" ("+e(u.xzBoundsCulled)+")"),Sr.setStat("Rejected: edge lies on triangle",u.triangleEdgeCulled.toLocaleString()+" ("+e(u.triangleEdgeCulled)+")"),Sr.setStat("Rejected: line above tri plane",u.planeTrimCulled.toLocaleString()+" ("+e(u.planeTrimCulled)+")"),Sr.setStat("Rejected: trimmed edge too small",u.distThresholdCulled.toLocaleString()+" ("+e(u.distThresholdCulled)+")"),Sr.setStat("Rejected: no projected overlap",u.noOverlapCulled.toLocaleString()+" ("+e(u.noOverlapCulled)+")")),Sr.setStat("Producing overlaps",u.used.toLocaleString()+" ("+e(u.used)+")")}Sr.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(Is(i,n,!1,s),Is(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 Br{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:s,includeIntersectionEdges:r}=this,{onProgress:o=()=>{},visibilityCuller:a=null,groupFn:l=null}=e;if(Sr.reset(),Sr.startTotal(),t.isBufferGeometry&&(t=new n.Mesh(t)),a){Sr.startStep("Visibility culling");let e=!1;for(a.cull(t).then(i=>{(t=new n.Scene).children=i,e=!0});!e;)yield}const c=new Ws;c.iterationTime=i,c.thresholdAngle=s,c.projectionDirection.copy(Dr),Sr.startStep("Generating candidate edges"),o("Generating candidate edges");let h=[],u=l?[]:null;if(yield*c.getEdgesGenerator(t,h,u),r&&(Sr.startStep("Generating intersection edges"),o("Generating intersection edges"),yield*c.getIntersectionEdgesGenerator(t,h,u)),Sr.startStep("Pre-filtering edges"),o("Pre-filtering edges"),u){const t=[],e=[];for(let i=0;i<h.length;i++)Ts(h[i])||(t.push(h[i]),e.push(u[i]));h=t,u=e}else h=h.filter(t=>!Ts(t));yield;const d=new kr(t,this.useWebGPU);if(d.iterationTime=i,l&&u){const t=new Map;for(let e=0;e<h.length;e++){const i=l(u[e]);t.has(i)||t.set(i,t.size),h[e].groupIndex=t.get(i)}d.groupKeyToIndex=t,d.hasGroups=!0}return o("Building BVH & computing overlaps"),yield*d.addEdgesGenerator(h,{onProgress:o?(t,e)=>{o("Building BVH & computing overlaps",t/e,d)}:null}),Sr.printSummary(),d}}new n.Line3,new n.Line3,new n.Vector3;const Or=class t extends g{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new f),e(this,"generator",new Br),e(this,"cullerPixelsPerMeter",.05),e(this,"projectionDirection",new u.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(bs),s=new u.Group,r=new Map;for(const[e,i]of Object.entries(t)){const t=n.list.get(e);if(!t)continue;const o=(await t.getItemsIdsWithGeometry()).filter(t=>i.has(t));if(0===o.length)continue;const a=await t.getItemsGeometry(o);for(const i in a){const n=a[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 u.BufferGeometry;t.setAttribute("position",new u.Float32BufferAttribute(i.positions,3)),i.normals&&t.setAttribute("normal",new u.Float32BufferAttribute(i.normals,3)),t.setIndex(Array.from(i.indices)),r.set(n,t)}const o=r.get(n),a=new u.Mesh(o);a.applyMatrix4(i.transform),a.applyMatrix4(t.object.matrixWorld),a.updateWorldMatrix(!0,!0),a.userData._edgeProjectorModelId=e,a.userData._edgeProjectorLocalId=i.localId,s.add(a)}}}const o=this.projectionDirection.clone().normalize(),a=new u.Vector3(0,-1,0),l=(new u.Quaternion).setFromUnitVectors(o,a),c=(new u.Matrix4).makeRotationFromQuaternion(l),h=c.clone().invert();for(const t of s.children)t.applyMatrix4(c),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 is(e.geometry,{maxLeafSize:1,strategy:2})}}),this.nearPlane!==-1/0||this.farPlane!==1/0){const t=new u.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 xs(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(h),g.applyMatrix4(h);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(Or,"uuid","f2e76c3a-8b1d-4d5e-9a3f-7c6b2d4e8f1a");let Vr=Or;class Lr{constructor(){e(this,"wasm",{path:"",absolute:!1,logLevel:p.LogLevel.LOG_LEVEL_OFF}),e(this,"webIfc",{COORDINATE_TO_ORIGIN:!0}),e(this,"autoSetWasm",!0),e(this,"customLocateFileHandler",null)}}const Nr=class t extends g{constructor(i){super(i),e(this,"onDisposed",new f),e(this,"onIfcStartedLoading",new f),e(this,"onIfcImporterInitialized",new f),e(this,"onSetup",new f),e(this,"settings",new Lr),e(this,"webIfc",new p.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,i,n){const s=this.components.get(bs);if(!s.initialized)throw new Error("You need to initialize fragments first.");this.settings.autoSetWasm&&await this.autoSetWasm(),s.core.settings.autoCoordinate=e;const r=new h.IfcImporter;r.wasm.path=this.settings.wasm.path,r.wasm.absolute=this.settings.wasm.absolute,r.webIfcSettings=this.settings.webIfc,this.onIfcImporterInitialized.trigger(r),(null==n?void 0:n.instanceCallback)&&n.instanceCallback(r);const o=await r.process({...null==n?void 0:n.processData,bytes:t});return await s.core.load(o,{modelId:i,userData:null==n?void 0:n.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 p.IfcAPI}async autoSetWasm(){const t=await fetch(`https://unpkg.com/@thatopen/components@${Oo.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(Nr,"uuid","a659add7-1418-4771-a0d6-7d4d438e4624");let Fr=Nr;const Rr=class t extends g{constructor(i){super(i),e(this,"enabled",!0),this.components.add(t.uuid,this)}async set(t,e){const i=this.components.get(bs),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(bs);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(bs);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(Rr,"uuid","dd9ccf2d-8a21-4821-b7f6-2949add16a29");let Ur=Rr;const jr=class t extends g{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new f),e(this,"list",new h.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 u.Box3;for(const e of this.list)t.union(e);return t}async addFromModelIdMap(t){const e=this.components.get(bs),i=new u.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(bs);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 u.Vector3;return e.getCenter(i),i}async getCameraOrientation(t,e=1){const i=this.components.get(bs);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 u.Vector3;n.getCenter(s);const r=new u.Vector3;n.getSize(r);const o=Math.max(r.x,r.y,r.z)*e,a=new u.Vector3;switch(t){case"front":default:a.set(s.x,s.y,s.z+o);break;case"back":a.set(s.x,s.y,s.z-o);break;case"left":a.set(s.x-o,s.y,s.z);break;case"right":a.set(s.x+o,s.y,s.z);break;case"top":a.set(s.x,s.y+o,s.z);break;case"bottom":a.set(s.x,s.y-o,s.z)}return{position:a,target:s}}};e(jr,"uuid","d1444724-dba6-4cdd-a0c7-68ee1450d166");let $r=jr;class Wr{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(Hr),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(Hr).list.getKey(this)??A.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 Gr=class t extends g{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new h.DataMap),i.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(bs),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?pe.join(r):pe.intersect(r)}create(t,e){const i=new Wr(this.components,e);return this.list.set(t,i),i}async addFromCategories(t){const e=new Set,i=this.components.get(bs);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(Gr,"uuid","0da7ad77-f734-42ca-942f-a074adfd1e3a");let Hr=Gr;const qr=class t extends g{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new f),e(this,"list",new h.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)}),i.add(t.uuid,this),this.setupEvents();i.get(bs).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 h.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(Hr),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=pe.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(bs),o=this.components.get(Hr),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);pe.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=pe.join(t);e.push(r)}return pe.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(Hr),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(bs).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)pe.remove(e.map,t);return}for(const[,e]of this.list.entries())for(const[,i]of e)pe.remove(i.map,t)}async byModel(t){const e=this.components.get(bs),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(qr,"uuid","e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7");let Zr=qr;const Yr=class t{constructor(t,i){if(e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new f),e(this,"mouse"),e(this,"world"),e(this,"debugMode",!1),e(this,"_renderTarget"),e(this,"_renderTargetSize",new u.Vector2),e(this,"_debugCanvas"),e(this,"_debugContainer"),e(this,"_idMaterial"),e(this,"_depthMaterial"),e(this,"_normalMaterial"),e(this,"_originalMaterials",new Map),e(this,"_hiddenLods",[]),e(this,"_ownMeshes",new Map),!i.renderer)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=i,this.mouse=new _e(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(bs).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(bs);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 u.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(bs);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,o=n[2]/255*2-1,a=new u.Vector3(s,r,o);return a.lengthSq()<1e-8?null:a.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(bs);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(bs),i=new Map,n=this.getModelRoots();this._ownMeshes.clear();let s=1;for(const[r,o]of e.list){if(s>t.MAX_MODELS)break;const e=[];this.traverseOwn(o.object,n,t=>{if(!(t instanceof u.Mesh))return;const i=t.geometry;if(!i)return;if(!i.attributes||!i.attributes.id)return void(t.visible&&(this._hiddenLods.push(t),t.visible=!1));this._originalMaterials.set(t,t.material);const n=t.material,s=Array.isArray(n)?n.length:1;t.material=new Array(s).fill(this._idMaterial),e.push(t)}),e.length&&(this._ownMeshes.set(r,e),i.set(s,r),s+=1)}return i}getModelRoots(){const t=this.components.get(bs),e=new Set;for(const[,i]of t.list)e.add(i.object);return e}traverseOwn(t,e,i){const n=[t];for(;n.length;){const s=n.pop();if(s===t||!e.has(s)){i(s);for(const t of s.children)n.push(t)}}}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,o=this.world.camera.three,a=this.components.get(bs),l=s.clippingPlanes??[];i.clippingPlanes=l,i.clipping=l.length>0;const c=s.getRenderTarget(),h=s.autoClear,d=s.getClearColor(new u.Color),p=s.getClearAlpha(),f=s.getScissorTest(),m=s.getScissor(new u.Vector4),g=r.background;r.background=null,s.setRenderTarget(e),s.setClearColor(0,0),s.autoClear=!1,s.setScissorTest(!1),s.clear(!0,!0,!1);const w=e.width,y=e.height,_=Math.floor(.5*(n.x+1)*w),b=Math.floor(.5*(n.y+1)*(y-1)),v=Math.max(0,Math.min(w-4,_-2)),x=Math.max(0,Math.min(y-4,b-2)),C=s.getPixelRatio();s.setScissor(v/C,x/C,4/C,4/C),s.setScissorTest(!0);const S=new Map;for(const[t,e]of a.list)S.set(t,e.object);const A=new Set(S.values()),P=new Map;r.traverse(t=>{t!==r&&t.isMesh&&((t=>{let e=t;for(;e;){if(A.has(e))return!0;e=e.parent}return!1})(t)||(P.set(t,t.visible),t.visible=!1))});const T=new Map;for(const[t,e]of S){let i=!0,n=e;for(;n;){if(!n.visible){i=!1;break}n=n.parent}T.set(t,i)}const M=new Map;for(const t of S.values())M.set(t,t.visible),t.visible=!0;const E=new Map;for(const t of this._ownMeshes.values())for(const e of t)E.set(e,e.visible),e.visible=!1;for(const[e,n]of t){if(!T.get(n))continue;const t=this._ownMeshes.get(n);if(t){for(const e of t)e.visible=E.get(e);i.uniforms.modelByte.value=e,s.render(r,o);for(const e of t)e.visible=!1}}for(const[t,e]of E)t.visible=e;for(const[t,e]of M)t.visible=e;for(const[t,e]of P)t.visible=e;s.setScissorTest(f),s.setScissor(m),s.setRenderTarget(c),s.autoClear=h,s.setClearColor(d,p),r.background=g}renderWithTileMaterial(t){const e=this.world.renderer.three,i=this.world.scene.three,n=this.world.camera.three,s=this.components.get(bs),r=e.clippingPlanes??[];t.clippingPlanes=r,t.clipping=r.length>0;const o=e.getRenderTarget(),a=e.autoClear,l=e.getClearColor(new u.Color),c=e.getClearAlpha(),h=i.background;i.background=null;const d=new Map,p=[],f=this.getModelRoots();for(const[,e]of s.list)this.traverseOwn(e.object,f,e=>{if(!(e instanceof u.Mesh))return;const i=e.geometry;if(!i)return;if(!i.attributes||!i.attributes.id)return void(e.visible&&(p.push(e),e.visible=!1));if(!e.visible)return;d.set(e,e.material);const n=e.material,s=Array.isArray(n)?n.length:1;e.material=new Array(s).fill(t)});const m=new Set;for(const[,t]of s.list)m.add(t.object);const g=new Map;i.traverse(t=>{t!==i&&t.isMesh&&((t=>{let e=t;for(;e;){if(m.has(e))return!0;e=e.parent}return!1})(t)||(g.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 d)t.material=e;for(const t of p)t.visible=!0;for(const[t,e]of g)t.visible=e;e.setRenderTarget(o),e.autoClear=a,e.setClearColor(l,c),i.background=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(),this._ownMeshes.clear();for(const t of this._hiddenLods)t.visible=!0;this._hiddenLods.length=0}readPixelAt(t,e){let i,n;t instanceof u.WebGLRenderTarget?(i=t,n=e):(i=this._renderTarget,n=t);const s=this.world.renderer.three,r=this._renderTargetSize,o=Math.floor(.5*(n.x+1)*r.x),a=Math.floor(.5*(n.y+1)*(r.y-1)),l=Math.max(0,Math.min(r.x-1,o)),c=Math.max(0,Math.min(r.y-1,a)),h=new Uint8Array(4);return s.readRenderTargetPixels(i,l,c,1,1,h),h}buildIdMaterial(){return new u.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:u.DoubleSide})}buildDepthMaterial(){return new u.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:u.DoubleSide})}buildNormalMaterial(){return new u.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:u.DoubleSide})}setupRenderTarget(){const t=this.world.renderer.three.getSize(new u.Vector2);this._renderTargetSize.copy(t);const e={format:u.RGBAFormat,type:u.UnsignedByteType,minFilter:u.NearestFilter,magFilter:u.NearestFilter,depthBuffer:!0};this._renderTarget=new u.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 u.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(Yr,"MAX_MODELS",254);let Xr=Yr;const Kr=class t extends g{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new Map),e(this,"onDisposed",new f),i.add(t.uuid,this)}get(t){if(this.list.has(t.uuid))return this.list.get(t.uuid);const e=new Xr(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(Kr,"uuid","4a82430c-7ff2-49ea-9401-60807502dad6");let Qr=Kr;var Jr=(t=>(t[t.POINT=0]="POINT",t[t.LINE=1]="LINE",t[t.FACE=2]="FACE",t))(Jr||{});const to=1e3;class eo{constructor(t){e(this,"onDisposed",new f),e(this,"maxDistance",1),e(this,"maxCacheSize",1e3),e(this,"components"),e(this,"_precision","half"),e(this,"cache",new Map),this.components=t}get precision(){return this._precision}set precision(t){t!==this._precision&&(this._precision=t,this.clear())}dispose(){this.cache.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}async resolve(t,e,i,n){const s=eo.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=eo.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=eo.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(bs).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=co(s,n.globalTransforms[e.item],a);this.collectPolygonsFromShell(o,l,r)}if(0===r.length)return null;return{faces:r,edges:function(t,e){const i=new Set,n=[];for(const e of t){const t=e.points,s=t.length/3;for(let e=0;e<s;e++){const r=(e+1)%s,o=t[3*e],a=t[3*e+1],l=t[3*e+2],c=t[3*r],h=t[3*r+1],u=t[3*r+2],d=po(o,a,l,c,h,u);i.has(d)||(i.add(d),n.push(o,a,l,c,h,u))}}return new("full"===e?Float64Array:Float32Array)(n)}(r,this._precision),vertices:function(t,e){const i=new Set,n=[];for(const e of t){const t=e.points,s=t.length/3;for(let e=0;e<s;e++){const s=t[3*e],r=t[3*e+1],o=t[3*e+2],a=uo(s,r,o);i.has(a)||(i.add(a),n.push(s,r,o))}}return new("full"===e?Float64Array:Float32Array)(n)}(r,this._precision)}}collectPolygonsFromShell(t,e,i){const n=t.points,s=t.profiles??new Map,r=t.bigProfiles??new Map,o=new u.Vector3,a=t=>{if(t.length<3)return;const s=new("full"===this._precision?Float64Array:Float32Array)(3*t.length);for(let i=0;i<t.length;i++){const r=n[t[i]];o.set(r[0],r[1],r[2]).applyMatrix4(e),s[3*i]=o.x,s[3*i+1]=o.y,s[3*i+2]=o.z}const r=function(t){const e=new u.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 a=r.x*s[0]+r.y*s[1]+r.z*s[2];i.push({points:s,normal:r,d:a})};for(const t of s.values())a(t);for(const t of r.values())a(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 u.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 u.Vector3,r=new u.Vector3;let o=1/0,a=-1;for(let e=0;e<i.length;e+=6){const l=fo(t,i[e],i[e+1],i[e+2],i[e+3],i[e+4],i[e+5],r);l<=n&&l<o&&(o=l,a=e,s.copy(r))}return a<0?null:{result:{point:s.clone(),snappingClass:1,snappedEdgeP1:new u.Vector3(i[a],i[a+1],i[a+2]),snappedEdgeP2:new u.Vector3(i[a+3],i[a+4],i[a+5])}}}snapToFace(t,e){const i=e.faces;if(0===i.length)return null;let n=null,s=1/0,r=!1;for(const e of i){const i=this.signedDistance(e,t),o=Math.abs(i);if(o>this.maxDistance)continue;const a=this.containsPoint(e,this.projectOntoPlane(t,e,i));r&&!a||(!a||r?o<s&&(s=o,n=e):(r=!0,s=o,n=e))}if(!n)return null;return{result:{point:this.projectOntoPlane(t,n,this.signedDistance(n,t)),normal:n.normal.clone(),snappingClass:2,facePoints:n.points,faceIndices:ho(n.points.length/3)}}}signedDistance(t,e){return t.normal.x*e.x+t.normal.y*e.y+t.normal.z*e.z-t.d}projectOntoPlane(t,e,i){return t.clone().sub(e.normal.clone().multiplyScalar(i))}containsPoint(t,e){const{points:i,normal:n}=t,s=i.length/3;if(s<3)return!1;const r=Math.abs(n.x),o=Math.abs(n.y),a=Math.abs(n.z);let l=0,c=1;r>=o&&r>=a?(l=1,c=2):o>=a&&(l=0,c=2);const h=e.getComponent(l),u=e.getComponent(c);let d=!1;for(let t=0,e=s-1;t<s;e=t,t+=1){const n=i[3*t+l],s=i[3*t+c],r=i[3*e+l],o=i[3*e+c];if(!(s>u!=o>u))continue;h<(r-n)*(u-s)/(o-s)+n&&(d=!d)}return d}}const io=new u.Matrix4,no=new u.Vector3,so=new u.Vector3,ro=new u.Vector3;function oo(t,e){if(!t)return e.identity();const i=t.position[0],n=t.position[1],s=t.position[2];return no.set(t.xDirection[0],t.xDirection[1],t.xDirection[2]),so.set(t.yDirection[0],t.yDirection[1],t.yDirection[2]),ro.crossVectors(no,so),e.set(no.x,so.x,ro.x,i,no.y,so.y,ro.y,n,no.z,so.z,ro.z,s,0,0,0,1),e}const ao=new u.Matrix4,lo=new u.Matrix4;function co(t,e,i){return oo(e,ao),oo(i,lo),io.copy(t).multiply(ao).multiply(lo).clone()}function ho(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 uo(t,e,i){return`${Math.round(t*to)},${Math.round(e*to)},${Math.round(i*to)}`}function po(t,e,i,n,s,r){const o=uo(t,e,i),a=uo(n,s,r);return o<a?`${o}|${a}`:`${a}|${o}`}function fo(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 mo=class t extends g{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new f),e(this,"_resolver"),i.add(t.uuid,this),this._resolver=new eo(i)}get(){return this._resolver}dispose(){this._resolver.dispose(),this.onDisposed.trigger()}};e(mo,"uuid","be9b8e6c-7f5b-4a36-8e7e-3a1f5e2a6c9d");let go=mo;class wo{constructor(t,i){e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new f),e(this,"mouse"),e(this,"three",new u.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 _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(bs);let o=null;if(r.initialized){const t=this.components.get(Qr).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(go).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 yo=class t extends g{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new Map),e(this,"onDisposed",new f),i.add(t.uuid,this)}get(t){if(this.list.has(t.uuid))return this.list.get(t.uuid);const e=new wo(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(yo,"uuid","d5d8bdf0-db25-4952-b951-b643af207ace");let _o=yo;class bo extends m{constructor(){super(...arguments),e(this,"onCameraChanged",new f),e(this,"meshes",new Set),e(this,"onAfterUpdate",new f),e(this,"onBeforeUpdate",new f),e(this,"onDisposed",new f),e(this,"isDisposing",!1),e(this,"enabled",!0),e(this,"_dynamicAnchor",!1),e(this,"_anchorRequestId",0),e(this,"uuid",A.create()),e(this,"name"),e(this,"_scene"),e(this,"_camera"),e(this,"_renderer",null),e(this,"onPointerDown",t=>{if(!this.camera.hasCameraControls())throw new Error("World: can't set dynamic anchor if the camera doesn't have controls.");if(0!==t.button)return;const e=this.getPointerPosition(t);if(!e)return;const i=this.components.get(_o).get(this),n=this.getPlaneAnchor(i,e);n&&this.camera.controls.setOrbitPoint(n.x,n.y,n.z);const s=++this._anchorRequestId;i.castRay({position:e}).then(t=>{if(s!==this._anchorRequestId||this.isDisposing||!this._dynamicAnchor)return;if(!(null==t?void 0:t.point)||!this.camera.hasCameraControls())return;const{x:e,y:i,z:n}=t.point;this.camera.controls.setOrbitPoint(e,i,n)})}),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),this._dynamicAnchor=t}get dynamicAnchor(){return this._dynamicAnchor}getPointerPosition(t){var e;const i=null==(e=this.renderer)?void 0:e.three.domElement;if(!i)return null;const n=i.getBoundingClientRect();return new u.Vector2((t.clientX-n.left)/(n.right-n.left)*2-1,-(t.clientY-n.top)/(n.bottom-n.top)*2+1)}getPlaneAnchor(t,e){if(!this.camera.hasCameraControls())return null;const i=this.camera.three;t.three.setFromCamera(e,i);const n=this.camera.controls.getTarget(new u.Vector3),s=i.getWorldDirection(new u.Vector3),r=(new u.Plane).setFromNormalAndCoplanarPoint(s,n);return t.three.ray.intersectPlane(r,new u.Vector3)}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){var e;if(this.isDisposing)return;this.enabled=!1,this.isDisposing=!0;const i=null==(e=this.renderer)?void 0:e.three.domElement.parentElement;if(i&&i.removeEventListener("pointerdown",this.onPointerDown),this._dynamicAnchor=!1,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(v);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(Eo).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class vo{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 xo{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 Co extends ge{constructor(){super(...arguments),e(this,"_config",{backgroundColor:{value:new u.Color,type:"Color"},ambientLight:{color:{type:"Color",value:new u.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2}},directionalLight:{color:{type:"Color",value:new u.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2},position:{type:"Vector3",value:new u.Vector3}}}),e(this,"ambientLight",new xo(this._config,this._component)),e(this,"directionalLight",new vo(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 So extends x{constructor(t){super(t),e(this,"onSetup",new f),e(this,"isSetup",!1),e(this,"three"),e(this,"config",new Co(this,this.components,"Scene")),e(this,"_defaultConfig",{backgroundColor:new u.Color(2107698),directionalLight:{color:new u.Color("white"),intensity:1.5,position:new u.Vector3(5,10,3)},ambientLight:{color:new u.Color("white"),intensity:1}}),this.three=new u.Scene,this.three.background=new u.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,o=new u.DirectionalLight(s,r);o.position.copy(n.position);const{color:a,intensity:l}=this.config.directionalLight,c=new u.AmbientLight(a,l);this.three.add(o,c),this.directionalLights.set(o.uuid,o),this.ambientLights.set(c.uuid,c),this.isSetup=!0,this.onSetup.trigger()}dispose(){super.dispose();this.components.get(ye).list.delete(this.config.uuid)}}const Ao='\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 Po=(t=>(t[t.MANUAL=0]="MANUAL",t[t.AUTO=1]="AUTO",t))(Po||{});class To extends y{constructor(t){super(t),e(this,"onBeforeUpdate",new f),e(this,"onAfterUpdate",new f),e(this,"onAspectUpdated",new f),e(this,"onDisposed",new f),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 u.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(bs),i=this.components.get($r);i.list.clear();const n=new u.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 u.PerspectiveCamera(60,t,1,1e3);return e.position.set(50,50,50),e.lookAt(new u.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!");a.install({THREE:To.getSubsetOfThree()});const{domElement:t}=this.currentWorld.renderer.three,e=new a(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:u.MOUSE,Vector2:u.Vector2,Vector3:u.Vector3,Vector4:u.Vector4,Quaternion:u.Quaternion,Matrix4:u.Matrix4,Spherical:u.Spherical,Box3:u.Box3,Sphere:u.Sphere,Raycaster:u.Raycaster,MathUtils:u.MathUtils}}}const Mo=class t extends g{constructor(n){super(n),e(this,"onAfterUpdate",new f),e(this,"onBeforeUpdate",new f),e(this,"onDisposed",new f),e(this,"list",new i.DataMap),e(this,"enabled",!0),n.add(t.uuid,this)}create(){const t=new bo(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(Mo,"uuid","fdb61dc4-2ec1-4966-b83d-54ea795fad4a");let Eo=Mo;class Io extends ge{constructor(){super(...arguments),e(this,"_config",{visible:{value:!0,type:"Boolean"},color:{value:new u.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 Do{constructor(t,i){e(this,"onDisposed",new f),e(this,"onSetup",new f),e(this,"isSetup",!1),e(this,"world"),e(this,"components"),e(this,"config"),e(this,"_defaultConfig",{visible:!0,color:new u.Color(12303291),primarySize:1,secondarySize:10,distance:500}),e(this,"three"),e(this,"_fade",3),e(this,"updateZoom",()=>{this.world.camera instanceof To&&(this.material.uniforms.uZoom.value=this.world.camera.three.zoom)}),this.world=i;const{color:n,primarySize:s,secondarySize:r,distance:o}=this._defaultConfig;this.components=t,this.config=new Io(this,this.components,"Grid");const a=new u.PlaneGeometry(2,2,1,1),l=new u.ShaderMaterial({side:u.DoubleSide,uniforms:{uSize1:{value:s},uSize2:{value:r},uColor:{value:n},uDistance:{value:o},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 u.Mesh(a,l),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(ye).list.delete(this.config.uuid);this.components.get(v).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 To))return;const e=this.world.camera.controls;t?e.addEventListener("update",this.updateZoom):e.removeEventListener("update",this.updateZoom)}}const zo=class t extends g{constructor(i){super(i),e(this,"list",new Map),e(this,"onDisposed",new f),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 Do(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(zo,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");let ko=zo;const Bo=class t{constructor(){e(this,"onDisposed",new f),e(this,"list",new i.DataMap),e(this,"enabled",!1),e(this,"_timer"),e(this,"onInit",new f),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 u.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.");A.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,e;this.enabled=!1;for(const[i,n]of this.list)n.enabled=!1,i!==bs.uuid?i!==Eo.uuid?n.isDisposeable()&&n.dispose():e=n:t=n;(null==e?void 0:e.isDisposeable())&&e.dispose(),null==t||t.dispose(),this._timer.dispose(),this.onDisposed.trigger()}static setupBVH(){u.BufferGeometry.prototype.computeBoundsTree=ws,u.BufferGeometry.prototype.disposeBoundsTree=ys,u.Mesh.prototype.raycast=ms,u.LineSegments.prototype.raycast=ms}};e(Bo,"release","2.4.3");let Oo=Bo;class Vo{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 u.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=a.ACTION.DOLLY,t.touches.two=a.ACTION.TOUCH_ZOOM_TRUCK}}class Lo{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 u.Vector3;t.getPosition(e);const i=e.length();t.distance=i,t.truckSpeed=2;const{rotation:n}=this.camera.three,s=new u.Vector3(0,0,-1).applyEuler(n),r=e.addScaledVector(s,i);t.moveTo(r.x,r.y,r.z)}}class No{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=a.ACTION.TRUCK,e.touches.one=a.ACTION.TOUCH_TRUCK,e.touches.two=a.ACTION.TOUCH_ZOOM):(e.mouseButtons.left=a.ACTION.ROTATE,e.touches.one=this.mouseAction1,e.touches.two=this.mouseAction2)}}class Fo{constructor(t){e(this,"onChanged",new f),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 u.Vector3;this._component.threePersp.getWorldDirection(e);const i=new u.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,o=this._component.threePersp,a=2*n*Math.atan(o.fov*(Math.PI/180)/2);return{width:a*r,height:a}}setupOrthoCamera(t,e){this._component.controls.mouseButtons.wheel=a.ACTION.ZOOM,this._component.controls.mouseButtons.middle=a.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=a.ACTION.DOLLY,this._component.controls.mouseButtons.middle=a.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=a.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 Ro extends To{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 Fo(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 Lo(this)),this._navigationModes.set("FirstPerson",new Vo(this)),this._navigationModes.set("Plan",new No(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 u.Vector3(i,i,i),r=new u.Vector3(n,n,n);for(const e of t){const t=(new u.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 o=new u.Box3(s,r),a=this.components.get(bs);if(a.initialized)for(const[,t]of a.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 l=new u.Vector3;o.getSize(l);const c=new u.Vector3;o.getCenter(c);const h=Math.max(l.x,l.y,l.z)*e,d=new u.Sphere(c,h);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 u.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 Uo="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function jo(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function $o(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 Wo={exports:{}};
2
- /*!
3
-
4
- JSZip v3.10.1 - A JavaScript class for generating and reading zip files
5
- <http://stuartk.com/jszip>
6
-
7
- (c) 2009-2016 Stuart Knightley <stuart [at] stuartk.com>
8
- Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/jszip/main/LICENSE.markdown.
9
-
10
- JSZip uses the library pako released under the MIT license :
11
- https://github.com/nodeca/pako/blob/main/LICENSE
12
- */const Go=jo(Wo.exports=function t(e,i,n){function s(o,a){if(!i[o]){if(!e[o]){if(!a&&$o)return $o(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=$o,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-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 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,M={crc32:0,compressedSize:0,uncompressedSize:0};e&&!i||(M.crc32=t.crc32,M.compressedSize=t.compressedSize,M.uncompressedSize=t.uncompressedSize);var E=0;e&&(E|=8),m||!v&&!x||(E|=2048);var I,D,z,k=0,B=0;P&&(k|=16),"UNIX"===o?(B=798,k|=(I=p.unixPermissions,D=P,z=I,I||(z=D?16893:33204),(65535&z)<<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(E,2),O+=f.magic,O+=n(u,2),O+=n(d,2),O+=n(M.crc32,4),O+=n(M.compressedSize,4),O+=n(M.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!==Uo?Uo:"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-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,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,M=1,E=2,I=3,D=4;function z(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-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 M;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&&(V(t,!1),0===t.strm.avail_out))return M}return t.insert=t.strstart<C-1?t.strstart:C-1,e===h?(V(t,!0),0===t.strm.avail_out?I:D):t.last_lit&&(V(t,!1),0===t.strm.avail_out)?M:E}function j(t,e){for(var i,n,s;;){if(t.lookahead<A){if(R(t),t.lookahead<A&&e===c)return M;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&&(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<C-1?t.strstart:C-1,e===h?(V(t,!0),0===t.strm.avail_out?I:D):t.last_lit&&(V(t,!1),0===t.strm.avail_out)?M:E}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):z(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 q(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 z(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 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-A&&(V(t,!1),0===t.strm.avail_out))return M}return t.insert=0,e===h?(V(t,!0),0===t.strm.avail_out?I:D):(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?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?z(t,d):d;if(s=t.state,!t.output||!t.input&&0!==t.avail_in||666===s.status&&e!==h)return z(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,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=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,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=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 z(t,-5);if(666===s.status&&0!==t.avail_in)return z(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?I:D):t.last_lit&&(V(t,!1),0===t.strm.avail_out)?M:E}(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 M;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&&(V(t,!1),0===t.strm.avail_out))return M}return t.insert=0,e===h?(V(t,!0),0===t.strm.avail_out?I:D):t.last_lit&&(V(t,!1),0===t.strm.avail_out)?M:E}(s,e):n[s.level].func(s,e);if(f!==I&&f!==D||(s.status=666),f===M||f===I)return 0===t.avail_out&&(s.last_flush=-1),u;if(f===E&&(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?(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?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?z(t,d):(t.state=null,e===T?z(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,M,E,I,D,z,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 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=_,V=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,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(;I=(F=i.lencode[b&(1<<i.lenbits)-1])>>>16&255,D=65535&F,!((E=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(D<16)b>>>=E,v-=E,i.lens[i.have++]=D;else{if(16===D){for(N=E+2;v<N;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(b>>>=E,v-=E,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===D){for(N=E+3;v<N;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}v-=E,O=0,P=3+(7&(b>>>=E)),b>>>=3,v-=3}else{for(N=E+7;v<N;){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}v-=E,O=0,P=11+(127&(b>>>=E)),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,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,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,D=65535&F,!((E=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(I&&!(240&I)){for(z=E,k=I,B=D;I=(F=i.lencode[B+((b&(1<<z+k)-1)>>z)])>>>16&255,D=65535&F,!(z+(E=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}b>>>=z,v-=z,i.back+=z}if(b>>>=E,v-=E,i.back+=E,i.length=D,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(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(;I=(F=i.distcode[b&(1<<i.distbits)-1])>>>16&255,D=65535&F,!((E=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}if(!(240&I)){for(z=E,k=I,B=D;I=(F=i.distcode[B+((b&(1<<z+k)-1)>>z)])>>>16&255,D=65535&F,!(z+(E=F>>>24)<=v);){if(0===y)break t;y--,b+=p[g++]<<v,v+=8}b>>>=z,v-=z,i.back+=z}if(b>>>=E,v-=E,i.back+=E,64&I){t.msg="invalid distance code",i.mode=30;break}i.offset=D,i.extra=15&I,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(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),M=i.window}else M=f,T=w-i.offset,P=i.length;for(_<P&&(P=_),_-=P,i.length-=P;f[w++]=M[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:V=1;break t;case 30:V=-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)&&V===h&&(V=-5),V)},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,M=0,E=0,I=0,D=0,z=0,k=null,B=0,O=new n.Buf16(16),V=new n.Buf16(16),L=null,N=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(V[1]=0,C=1;C<15;C++)V[C+1]=V[C]+O[C];for(S=0;S<l;S++)0!==e[i+S]&&(u[V[e[i+S]]++]=S);if(y=0===t?(k=L=u,19):1===t?(k=s,B-=257,L=r,N-=257,256):(k=o,L=a,-1),C=A,w=h,E=S=z=0,m=-1,g=(D=1<<(M=T))-1,1===t&&852<D||2===t&&592<D)return 1;for(;;){for(_=C-E,v=u[S]<y?(b=0,u[S]):u[S]>y?(b=L[N+u[S]],k[B+u[S]]):(b=96,0),p=1<<C-E,A=f=1<<M;c[w+(z>>E)+(f-=p)]=_<<24|b<<16|v,0!==f;);for(p=1<<C-1;z&p;)p>>=1;if(0!==p?(z&=p-1,z+=p):z=0,S++,0==--O[C]){if(C===P)break;C=e[i+u[S]]}if(T<C&&(z&g)!==m){for(0===E&&(E=T),w+=A,I=1<<(M=C-E);M+E<P&&!((I-=O[M+E])<=0);)M++,I<<=1;if(D+=1<<M,1===t&&852<D||2===t&&592<D)return 1;c[m=z&g]=T<<24|M<<16|w-h}}return 0!==z&&(c[w+z]=C-E<<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 M=new Array(256);o(M);var E=new Array(l);o(E);var I,D,z,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 V(t){return t<256?T[t]:T[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<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?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-=E[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,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 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(E[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++)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),D=new B(P,x,0,u,f),z=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,D),t.bl_desc=new O(t.bl_tree,z),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=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?(N(t,2+(n?1:0),3),H(t,A,P)):(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*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*(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,A),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(){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!==Uo?Uo:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10));class Ho{constructor(t,i){e(this,"date",new Date),e(this,"author"),e(this,"guid",A.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(Qo);this.author=n.config.author}set comment(t){var e;const i=this._components.get(Qo);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 qo=class t{constructor(n){e(this,"guid",A.create()),e(this,"title",t.default.title),e(this,"creationDate",new Date),e(this,"creationAuthor",""),e(this,"viewpoints",new i.DataSet),e(this,"relatedTopics",new i.DataSet),e(this,"comments",new i.DataMap),e(this,"documentReferences",new i.DataSet),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=n;const s=n.get(Qo);this.creationAuthor=s.config.author,this.relatedTopics.guard=t=>t!==this.guid}set type(t){const e=this._components.get(Qo),{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(Qo),{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(Qo);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(Qo);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(Qo);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(Qo),{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(Qo).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(Qo).list.set(this.guid,this),this}createComment(t,e){const i=new Ho(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(Qo).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(oa);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(Qo);for(const n of this.documentReferences){const s=i.documents.get(n);if(!s)continue;let r={$Guid:A.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(oa);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(Qo);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:A.create(),description:e.description,url:e.url}):i.document_references.push({guid:A.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="3"===i,s={Markup:{Topic:{$Guid:this.guid,$TopicType:this.type,$TopicStatus:this.status,$ServerAssignedId:this.serverAssignedId,Title:this.title,Priority:this.priority,Index:"2.1"===i?this.index:void 0,Labels:n?{Label:this.createLabelTags()}:this.createLabelTags(),CreationDate:this.creationDate.toISOString(),CreationAuthor:this.creationAuthor,ModifiedDate:null==(t=this.modifiedDate)?void 0:t.toISOString(),ModifiedAuthor:this.modifiedAuthor,DueDate:null==(e=this.dueDate)?void 0:e.toISOString(),AssignedTo:this.assignedTo,Stage:this.stage,Description:this.description,DocumentReferences:n?{DocumentReference:this.createDocumentReferencesTag(i)}:void 0,DocumentReference:n?void 0:this.createDocumentReferencesTag(i),RelatedTopics:n?{RelatedTopic:this.createRelatedTopicTags()}:void 0,RelatedTopic:n?void 0:this.createRelatedTopicTags(),Comments:n?{Comment:this.createCommentTags()}:void 0,Viewpoints:n?{ViewPoint:this.createViewpointTags()}:void 0}}};return"2.1"===i&&(s.Markup.Viewpoints=this.createViewpointTags(),s.Markup.Comment=this.createCommentTags()),`<?xml version="1.0" encoding="UTF-8"?>\n ${de.builder.build(s)}`}};e(qo,"default",{title:"BCF Topic",type:"Issue",status:"Active"});let Zo=qo;const Yo=(t,e)=>{if(""===e.trim())return;const i=Qo.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 Xo extends ge{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 Ko=class t extends g{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 Xo(this,this.components,"BCF Topics",t.uuid)),e(this,"list",new i.DataMap),e(this,"documents",new i.DataMap),e(this,"onSetup",new f),e(this,"isSetup",!1),e(this,"onBCFImported",new f),e(this,"onDisposed",new f)}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 Zo(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(oa);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 Go,i="3"===this.config.version,n=i?"3.0":this.config.version,s=i?"release_3_0":"release_2_1";e.file("bcf.version",`<?xml version="1.0" encoding="UTF-8"?>\n <Version VersionId="${n}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/${s}/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("extensions.xml",this.serializeExtensions());const r=this.components.get(oa);for(const i of t){const t=e.folder(i.guid);t.file("markup.bcf",i.serialize());for(const e of i.viewpoints){const i=r.list.get(e);if(!i)continue;const n=i.title??i.guid;t.file(`${n}.bcfv`,await i.serialize());const s=r.snapshots.get(i.snapshot);if(!s)continue;const o=s?i.snapshot:i.guid,a=r.getSnapshotExtension(i.snapshot);t.file(`${o}.${a}`,s,{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&&(Ho||r)))return null;const o=new Ho(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:o,updateExtensionsOnImport:a}=this.config,l=new Go;await l.loadAsync(e);const c=Object.values(l.files);let h=r;const d=c.find(t=>t.name.endsWith(".version"));if(d){const e=await d.async("string"),i=String(t.xmlParser.parse(e).Version.VersionId);h="3.0"===i?"3":i}if(!h||"2.1"!==h&&"3"!==h)throw new Error(`BCFTopics: ${h} is not supported.`);const p=c.find(t=>t.name.endsWith("extensions.xml")||t.name.endsWith(".extensions"));if(a&&p){const t=await p.async("string");Yo(this,t)}const f=[],m=this.components.get(oa),g=c.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:o,ClippingPlanes:a,Components:l,OrthogonalCamera:c,PerspectiveCamera:d}=s;if(o&&(r.guid=o),l){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}=l;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"===h&&(s=l.ViewSetupHints),"3"===h&&(s=null==(i=l.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}=l;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(c||d){const t=s.PerspectiveCamera??s.OrthogonalCamera,{CameraViewPoint:e,CameraDirection:i}=t,n=new u.Vector3(Number(e.X),Number(e.Z),Number(-e.Y)),o=new u.Vector3(Number(i.X),Number(i.Z),Number(-i.Y)),a={camera_view_point:{x:n.x,y:n.y,z:n.z},camera_direction:{x:o.x,y:o.y,z:o.z},aspect_ratio:"AspectRatio"in t?t.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in t&&(r.orthogonal_camera={...a,view_to_world_scale:t.ViewToWorldScale}),"FieldOfView"in t&&(r.perspective_camera={...a,field_of_view:t.FieldOfView})}if(a){const t=(Array.isArray(a.ClippingPlane)?a.ClippingPlane:[a.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 na(this.components,r);f.push(p)}const w={},y=[],_=c.filter(t=>t.name.endsWith(".bcf"));for(const e of _){const i=await e.async("string"),r=t.xmlParser.parse(i).Markup,a=r.Topic,{Guid:l,TopicType:u,TopicStatus:d,Title:p,CreationDate:f,CreationAuthor:g}=a;if(o&&!(l&&u&&d&&p&&f&&g))continue;const _=new Zo(this.components);_.guid=l??_.guid;const b=this.getMarkupRelatedTopics(r,h);w[_.guid]=new Set(b),_.type=u??_.type,_.status=d??_.status,_.title=p??_.title,_.creationDate=f?new Date(f):_.creationDate,_.creationAuthor=g??_.creationAuthor,_.serverAssignedId=a.ServerAssignedId,_.priority=a.Priority,_.index=a.Index,_.modifiedDate=a.ModifiedDate?new Date(a.ModifiedDate):void 0,_.modifiedAuthor=a.ModifiedAuthor,_.dueDate=a.DueDate?new Date(a.DueDate):void 0,_.assignedTo=a.AssignedTo,_.description=a.Description,_.stage=a.Stage;const v=this.getMarkupLabels(r,h);for(const t of v)_.labels.add(t);const x=this.getMarkupComments(r,h);for(const t of x)_.comments.set(t.guid,t);const C=this.getMarkupViewpoints(r,h);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=c.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,h),A=c.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=de.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=c.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=c.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(Ko,"uuid","de977976-e4f6-4e4f-a01a-204727839802"),e(Ko,"xmlParser",new Kt({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 Qo=Ko;class Jo{constructor(t,i,n,s,r,o=5,a=!0){var l;if(e(this,"onDraggingStarted",new f),e(this,"onDraggingEnded",new f),e(this,"onDisposed",new f),e(this,"normal"),e(this,"origin"),e(this,"three",new u.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 u.Mesh),e(this,"_planeMesh"),e(this,"_controls"),e(this,"_hiddenMaterial",new u.MeshBasicMaterial({visible:!1})),e(this,"_sizeMultiplier",5),e(this,"_autoScale",!0),e(this,"_visibilityBeforeDisabled",!0),e(this,"notifyManager",()=>{const t=this.components.get(ia),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 u.PerspectiveCamera))return;const i=new u.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=o;const c=t.get(ia);i.renderer.setPlane(!0,this.three,c.localClippingPlanes),this._planeMesh=Jo.newPlaneMesh(o,r),this._helper=this.newHelper(),this._controls=this.newTransformControls(),this.three.setFromNormalAndCoplanarPoint(s,n),a&&this.toggleControls(!0),this.updateScale(),(null==(l=i.camera)?void 0:l.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(ia);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,!this.world.isDisposing&&(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 u.Vector3(1,0,0),e=new u.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 l.TransformControls(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 u.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 u.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 u.PlaneGeometry(1),n=new u.Mesh(i,e);return n.scale.set(t,t,t),n}}class ta extends ge{constructor(){super(...arguments),e(this,"_config",{enabled:{value:!0,type:"Boolean"},visible:{value:!0,type:"Boolean"},color:{value:new u.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 ea=class t extends g{constructor(i){super(i),e(this,"onSetup",new f),e(this,"onBeforeDrag",new f),e(this,"onAfterDrag",new f),e(this,"onBeforeCreate",new f),e(this,"onBeforeCancel",new f),e(this,"onAfterCancel",new f),e(this,"onBeforeDelete",new f),e(this,"onAfterCreate",new f),e(this,"onAfterDelete",new f),e(this,"onDisposed",new f),e(this,"isSetup",!1),e(this,"orthogonalY",!1),e(this,"toleranceOrthogonalY",.7),e(this,"autoScalePlanes",!0),e(this,"_localClippingPlanes",!1),e(this,"Type",Jo),e(this,"list",new h.DataMap),e(this,"config",new ta(this,this.components,"Clipper",t.uuid)),e(this,"_defaultConfig",{color:new u.Color(12255487),opacity:.2,size:2}),e(this,"_material",new u.MeshBasicMaterial({color:12255487,side:u.DoubleSide,transparent:!0,opacity:.2})),e(this,"_size",5),e(this,"_enabled",!1),e(this,"_visible",!0),e(this,"onStateChanged",new f),this.components.add(t.uuid,this),this.setEvents()}get localClippingPlanes(){return this._localClippingPlanes}set localClippingPlanes(t){this._localClippingPlanes=t;const e=this.components.get(Eo);for(const[,i]of e.list)i.renderer&&(i.renderer.localClippingPlanes=t)}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(bs);if(t.initialized)this.subscribeToFragmentMaterials();else{const e=()=>{t.onFragmentsLoaded.remove(e),this.subscribeToFragmentMaterials()};t.onFragmentsLoaded.add(e)}}subscribeToFragmentMaterials(){const t=this.components.get(bs);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(Eo);for(const[,i]of e.list)if(i.renderer)return void(t.clippingPlanes=i.renderer.clippingPlanes)}dispose(){this._enabled=!1;this.components.get(ye).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(_o).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(_o).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 u.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),o=this.newPlane(t,e.point,r.negate()),a=this.list.get(o);return a.visible=this._visible,a.size=this._size,t.renderer.setPlane(!0,a.three,this.localClippingPlanes),this.updateMaterialsAndPlanes(),a}getWorldNormal(t,e){const i=t.object;let n=t.object.matrixWorld.clone();if(i instanceof u.InstancedMesh&&void 0!==t.instanceId){const e=new u.Matrix4;i.getMatrixAt(t.instanceId,e),n=e.multiply(n)}const s=(new u.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=A.create();return this.list.set(s,n),this.onAfterCreate.trigger(n),s}updateMaterialsAndPlanes(){const t=this.components.get(Eo);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(ea,"uuid","66290bc5-18c4-4cd1-9379-2e17a0617611");let ia=ea;class na{constructor(t,i){e(this,"title"),e(this,"guid",A.create()),e(this,"clippingPlanes",new h.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 h.DataSet),e(this,"selectionComponents",new h.DataSet),e(this,"componentColors",new h.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(oa).list.set(this.guid,this)}),this._components=t,i&&(this.guid=i.guid??this.guid,this.set(i)),this.setEvents()}async getSelectionMap(){const t=this._components.get(bs);return await t.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const t=this._components.get(bs);return await t.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const t=this._components.get(bs),{camera_view_point:e}=this.camera,{x:i,y:n,z:s}=e,r=new u.Vector3(i,n,s);return t.applyBaseCoordinateSystem(r,new u.Matrix4),r}set position(t){const e=t.clone(),i=this._components.get(bs);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 u.Vector3(e,i,n)}set world(t){this._world=t}get world(){return this._world}get _managerVersion(){return this._components.get(Qo).config.version}get topics(){return[...this._components.get(Qo).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(ia);for(const e of s){const{location:i,direction:n}=e,s=new u.Vector3(i.x,i.z,-i.y),r=new u.Vector3(n.x,n.z,-n.y),o=t.createFromNormalAndCoplanarPoint(this.world,r,s);this.clippingPlanes.add(o),t.list.get(o).enabled=!1,t.list.get(o).visible=!1}}this.notifyUpdate()}async go(t){if(!this.world)return;const{camera:e}=this.world;if(!(e instanceof Ro))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 o=new u.Vector3(this.camera.camera_view_point.x,this.camera.camera_view_point.y,this.camera.camera_view_point.z),a=new u.Vector3(this.camera.camera_direction.x,this.camera.camera_direction.y,this.camera.camera_direction.z);if(o.equals(new u.Vector3)&&a.equals(new u.Vector3))return;const l=this.position,c=this.direction,h={x:l.x+80*c.x,y:l.y+80*c.y,z:l.z+80*c.z},d=[];n&&this.setClippingState(!0),s&&d.push(this.applyVisibility()),this.setClippingVisibility(r),d.push(e.controls.setLookAt(l.x,l.y,l.z,h.x,h.y,h.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 u.Vector3),o=s.getWorldDirection(new u.Vector3),{width:a,height:l}=n.getSize();let c=a/l;Number.isNaN(c)&&(c=1);const h=this._components.get(bs);r.applyMatrix4(h.baseCoordinationMatrix.clone().invert());const d={aspect_ratio:c,camera_view_point:{x:r.x,y:r.y,z:r.z},camera_direction:{x:o.x,y:o.y,z:o.z},camera_up_vector:{x:0,y:1,z:0}};if(s instanceof u.PerspectiveCamera?this.camera={...d,field_of_view:s.fov}:s instanceof u.OrthographicCamera&&(this.camera={...d,view_to_world_scale:s.top-s.bottom}),t){const t=this._components.get(oa),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(oa),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(ia);for(const[e,i]of t.list)i.enabled&&this.clippingPlanes.add(e)}async applyVisibility(){const t=this._components.get(Ur);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(bs),i=[];if(t)for(const[t,n]of this.componentColors){const s=`#${t}`,r=await e.guidsToModelIdMap(n);for(const[t,n]of Object.entries(r)){const r=e.list.get(t);r&&i.push(r.highlight([...n],{customId:s,color:new u.Color(s),renderedFaces:h.RenderedFaces.ONE,opacity:1,transparent:!1}))}}else for(const[t,n]of this.componentColors){const t=await e.guidsToModelIdMap(n);for(const[n,s]of Object.entries(t)){const t=e.list.get(n);t&&i.push(t.resetHighlight([...s]))}}i.push(e.core.update(!0)),await Promise.all(i)}setClippingState(t){const e=this._components.get(ia);for(const[i,n]of e.list)n.enabled=t&&this.clippingPlanes.has(i)}setClippingVisibility(t){const e=this._components.get(ia);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(bs);let n="";if(this._components.get(Qo).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(ia),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(oa),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(bs),i=this.position;i.applyMatrix4(e.baseCoordinationMatrix.clone().invert());const n=this.direction;n.normalize();const s=(new u.Matrix4).makeRotationX(Math.PI/2),r=n.clone().applyMatrix4(s);r.normalize();const o=`<CameraViewPoint>\n <X>${i.x}</X>\n <Y>${-i.z}</Y>\n <Z>${i.y}</Z>\n </CameraViewPoint>`,a=`<CameraDirection>\n <X>${n.x}</X>\n <Y>${-n.z}</Y>\n <Z>${n.y}</Z>\n </CameraDirection>`,l=`<CameraUpVector>\n <X>${r.x}</X>\n <Y>${-r.z}</Y>\n <Z>${r.y}</Z>\n </CameraUpVector>`,c=`<AspectRatio>${this.camera.aspect_ratio}</AspectRatio>`;let h="";"view_to_world_scale"in this.camera?h=`<OrthogonalCamera>\n ${o}\n ${a}\n ${l}\n ${c}\n <ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>\n </OrthogonalCamera>`:"field_of_view"in this.camera&&(h=`<PerspectiveCamera>\n ${o}\n ${a}\n ${l}\n ${c}\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 ${h}\n </VisualizationInfo>`}}class sa extends ge{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 ra=class t extends g{constructor(n){super(n),e(this,"enabled",!0),e(this,"world",null),e(this,"list",new i.DataMap),e(this,"snapshots",new i.DataMap),e(this,"isSetup",!1),e(this,"onSetup",new f),e(this,"config",new sa(this,this.components,"Viewpoints",t.uuid)),e(this,"onDisposed",new f),n.add(t.uuid,this)}create(t){const e=new na(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(ra,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");let oa=ra;class aa{constructor(t,i){e(this,"_components"),e(this,"_cameraOffset",10),e(this,"_planeHelper"),e(this,"_farPlaneHelper"),e(this,"_cameraHelper"),e(this,"onStateChanged",new f),e(this,"onUpdated",new f),e(this,"onDisposed",new f),e(this,"camera"),e(this,"plane",new u.Plane),e(this,"farPlane",new u.Plane),e(this,"id",A.create()),e(this,"_open",!1),e(this,"_range",ca.defaultRange),e(this,"_world",null),e(this,"_helpersVisible",!1),e(this,"_planesEnabled",!1),this._components=t,this.camera=new Ro(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 u.CameraHelper(n),this._planeHelper=new u.PlaneHelper(this.plane,50),this._farPlaneHelper=new u.PlaneHelper(this.farPlane,50),this.farPlaneHelperColor=new u.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 u.Color&&(this._planeHelper.material.color=t)}set farPlaneHelperColor(t){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof u.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(v);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 la=class t extends g{constructor(n){super(n),e(this,"list",new i.DataMap),e(this,"enabled",!0),e(this,"world",null),e(this,"_fragmentsUpdateEvent",()=>{this.components.get(bs).core.update(!0)}),e(this,"restoreCameraOnClose",!0),e(this,"_restoreState",null),n.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 aa(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 aa(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(bs),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 o=await r.getItemsData(i),[,a]=await r.getCoordinates(),l=new u.Vector3(0,-1,0);for(const i of o){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+a+n,o=new u.Plane(l,r),c=this.createFromPlane(o,{id:s,world:null==t?void 0:t.world});e.push(c)}}return e}createElevations(t){const e=[],i=this.components.get(bs),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($r);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:o}=n,a=Math.abs(o.x-r.x),l=Math.abs(o.z-r.z),c=new u.Vector3;n.getCenter(c);const h=new u.Plane(new u.Vector3(0,0,-1),o.z),d=new u.Plane(new u.Vector3(0,0,1),-r.z),p=new u.Plane(new u.Vector3(-1,0,0),o.x),f=new u.Plane(new u.Vector3(1,0,0),-r.x),{front:m,back:g,left:w,right:y}=s(i),_=this.createFromPlane(h,{id:m,world:null==t?void 0:t.world});_.range=l;const b=this.createFromPlane(d,{id:g,world:null==t?void 0:t.world});b.range=l;const v=this.createFromPlane(p,{id:w,world:null==t?void 0:t.world});v.range=a;const x=this.createFromPlane(f,{id:y,world:null==t?void 0:t.world});x.range=a,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(la,"uuid","fb22f1f5-6598-4664-a11d-de8963ae420f"),e(la,"defaultRange",15);let ca=la;async function ha(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 ua{constructor(t,i){if(e(this,"onDisposed",new f),e(this,"onDistanceComputed",new f),e(this,"excludedObjects",new Set),e(this,"enabled",!0),e(this,"renderDebugFrame",!1),e(this,"components"),e(this,"scene",new u.Scene),e(this,"camera",new u.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 ha(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||u.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 u.WebGLRenderTarget(this._width,this._height),this.bufferSize=this._width*this._height*4,this._buffer=new Uint8Array(this.bufferSize),this.tempRT.texture.minFilter=u.NearestFilter,this.tempRT.texture.magFilter=u.NearestFilter,this.tempRT.stencilBuffer=!1,this.tempRT.samples=0,this.tempRT.depthTexture=new u.DepthTexture(this._width,this._height),this.tempRT.depthTexture.format=u.DepthFormat,this.tempRT.depthTexture.type=u.UnsignedShortType,this.resultRT=new u.WebGLRenderTarget(this._width,this._height),this.depthMaterial=new u.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 u.PlaneGeometry(2,2);this._postQuad=new u.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 da{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,i,n){if(!("value"in i._localId)||"number"!=typeof i._localId.value)return null;let s=t.get(e);s||(s=new h.DataMap,t.set(e,s));let r=s.get(i._localId.value);if(r&&n&&!r.pass)return null;if(!r){const t=[];r={guid:Array.isArray(i._guid)?void 0:i._guid.value,pass:!1,checks:t},Object.defineProperty(r,"pass",{get:()=>t.every(({pass:t})=>t)}),s.set(i._localId.value,r)}const o=[],a={facetType:this.facetType,cardinality:this.cardinality,checks:o,pass:!1};return Object.defineProperty(a,"pass",{get:()=>o.every(({pass:t})=>t)}),r.checks.push(a),a.checks}}const pa=(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 fa extends da{constructor(t,i){super(t),e(this,"facetType","Attribute"),e(this,"name"),e(this,"value"),this.name=i}serialize(t){const e=pa("Name",this.name),i=pa("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(bs);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 ma extends da{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=pa("System",this.system),i=pa("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 ga extends da{constructor(t,i){super(t),e(this,"facetType","Entity"),e(this,"name"),e(this,"predefinedType"),this.name=i}serialize(t){const e=pa("Name",this.name),i=pa("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(bs),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)&&pe.append(e,t,i._localId.value)}}else pe.add(e,s)}async test(t,e,i){const n=this._components.get(bs);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(bs).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 wa extends da{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=pa("PropertySet",this.propertySet),i=pa("BaseName",this.baseName),n=pa("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(bs);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);pe.append(e,n,...a)}}}}async test(t,e,i={skipIfFails:!0}){const n=this._components.get(bs);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){const e=[...Array.isArray(t.IsTypedBy)?t.IsTypedBy:[],...Array.isArray(t.IsDefinedBy)?t.IsDefinedBy:[]],i=[];for(const t of e)Array.isArray(null==t?void 0:t.HasPropertySets)&&i.push(...t.HasPropertySets);return i}async getPsets(t){const e=this.getTypePsets(t);if(!Array.isArray(t.IsDefinedBy))return e;const i=[],n=new Set;for(const s of t.IsDefinedBy){if(!("value"in s.Name))continue;const t=s.Name.value,r=this.getPropertyListName(s);if(!t||!r)continue;const o=e.find(e=>"value"in e.Name&&e.Name.value===t);if(o&&(n.add(o),Array.isArray(o.HasProperties)&&Array.isArray(s.HasProperties)))for(const t of o.HasProperties){if(!("value"in t.Name))continue;const e=t.Name.value;s.HasProperties.find(t=>"value"in t.Name&&t.Name.value===e)||s.HasProperties.push(t)}i.push(s)}for(const t of e)n.has(t)||i.push(t);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);"string"==typeof n.value&&"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 ya extends da{constructor(){super(...arguments),e(this,"_ifcMaterialEntities",[/^IFCMATERIALLAYERSETUSAGE$/,/^IFCMATERIALLAYERSET$/,/^IFCMATERIALPROFILESETUSAGE$/,/^IFCMATERIALPROFILESET$/,/^IFCMATERIALCONSTITUENTSET$/,/^IFCMATERIAL$/,/^IFCMATERIALLIST$/]),e(this,"_materialParentAttributes",["ForLayerSet","MaterialLayers","ForProfileSet","MaterialProfiles","Material","MaterialConstituents","Materials"]),e(this,"_materialRelations",{MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},ForProfileSet:{attributes:!0,relations:!0},MaterialProfiles:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}),e(this,"facetType","Material"),e(this,"value"),e(this,"uri")}serialize(t){if(!this.value||!this.uri)return"<material />";const e=pa("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(bs);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},...this._materialRelations}});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);pe.append(e,n,...i)}}}async test(t,e,i={skipIfFails:!0}){const n=this._components.get(bs);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},...this._materialRelations}});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(this._materialParentAttributes.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 _a extends da{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 ga(t,i.name),this._entityFacet.predefinedType=i.predefinedType}set entity(t){this._entity=t;const{name:e,predefinedType:i}=t;this._entityFacet=new ga(this._components,e),this._entityFacet.predefinedType=i}get entity(){return this._entity}serialize(){return""}async getEntities(t,e){}async test(t){}}class ba{constructor(t,i,n){e(this,"name"),e(this,"ifcVersion",new Set),e(this,"identifier",A.create()),e(this,"description"),e(this,"instructions"),e(this,"requirementsDescription"),e(this,"applicability",new h.DataSet),e(this,"requirements",new h.DataSet),e(this,"components"),this.components=t,this.name=i;for(const t of n)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(Ea).list.set(this.identifier,this),this}async test(t,e={skipIfFails:!0}){const i=new h.DataMap;if(0===this.requirements.size)return i;const n={},s=[];for(const e of this.applicability)s.push(e.getEntities(t,n));await Promise.all(s);const r=[];for(const t of this.requirements)r.push(t.test(n,i,e));return await Promise.all(r),i}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 va=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},xa=(t,e)=>{const i=[];for(const n of e){const e=n.name,s=va(e);if(!s)continue;const r=new ga(t,s);n.cardinality&&(r.cardinality=n.cardinality),r.predefinedType=va(n.predefinedType),r.instructions=n.instructions,i.push(r)}return i},Ca=(t,e)=>{const i=[];for(const n of e){const e=n.name,s=va(e);if(!s)continue;const r=new fa(t,s);n.cardinality&&(r.cardinality=n.cardinality),r.value=va(n.value),r.instructions=n.instructions,i.push(r)}return i},Sa=(t,e)=>{const i=[];for(const n of e){const e=new ya(t);n.cardinality&&(e.cardinality=n.cardinality);const s=va(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},Aa=(t,e)=>{const i=[];for(const n of e){const e=n.propertySet,s=n.baseName,r=va(e),o=va(s);if(!o||!r)continue;const a=new wa(t,r,o);n.cardinality&&(a.cardinality=n.cardinality);const l=va(n.value);a.value=l,a.dataType=n.dataType,a.uri=n.uri,a.instructions=n.instructions,i.push(a)}return i},Pa=(t,e)=>{const i=[];for(const n of e){const e=n.system,s=va(e);if(!s)continue;const r=new ma(t,s);n.cardinality&&(r.cardinality=n.cardinality);const o=va(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},Ta=(t,e)=>{const i=[];for(const n of e){const e=va(n.entity.name);if(!e)continue;const s=va(n.entity.predefinedType),r=new _a(t,{name:e,predefinedType:s});r.relation=n.relation,n.cardinality&&(r.cardinality=n.cardinality),r.instructions=n.instructions,i.push(r)}return i},Ma=class t extends g{constructor(n){super(n),e(this,"enabled",!0),e(this,"IDSInfo"),e(this,"list",new i.DataMap),n.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);pe.append(e,n,...t);const r=[...s].filter(([,t])=>!t.pass).map(([t])=>t);pe.append(i,n,...r)}return{pass:e,fail:i}}create(t,e,i){const n=new ba(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=xa(this.components,i);a.push(...t)}if("attribute"===e){const t=Ca(this.components,i);a.push(...t)}if("material"===e){const t=Sa(this.components,i);a.push(...t)}if("classification"===e){const t=Pa(this.components,i);a.push(...t)}if("property"===e){const t=Aa(this.components,i);a.push(...t)}if("partOf"===e){const t=Ta(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=xa(this.components,i);l.push(...t)}if("attribute"===e){const t=Ca(this.components,i);l.push(...t)}if("material"===e){const t=Sa(this.components,i);l.push(...t)}if("classification"===e){const t=Pa(this.components,i);l.push(...t)}if("property"===e){const t=Aa(this.components,i);l.push(...t)}if("partOf"===e){const t=Ta(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 ${Oo.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(Ma,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c"),e(Ma,"xmlParser",new Kt({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 Ea=Ma;const Ia=class t extends g{constructor(i){super(i),e(this,"enabled",!0),i.add(t.uuid,this)}static distanceFromPointToLine(t,e,i,n=!1){const s=new u.Line3,r=new u.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(bs);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(Ia,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");let Da=Ia;const za=(t,e,i)=>{const n=new u.Vector3(-e.z,0,e.x),s=new u.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]},ka=(t,e,i)=>{const n=new u.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,o=t.x-e.x*i-n.x*i*.4,a=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,o,t.y,a]},Ba=()=>[],Oa=(t,e,i)=>{const n=new u.Vector3(-e.z,0,e.x),s=t.clone().addScaledVector(e,-i),r=s.clone().addScaledVector(n,.4*i),o=s.clone().addScaledVector(n,.4*-i);return[t.x,t.y,t.z,r.x,r.y,r.z,o.x,o.y,o.z]};class Va extends h.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 La extends h.DataMap{constructor(t){super(),e(this,"_container"),this._container=t,this.deleteGuard=t=>"0"!==t,this.set("0",{name:"0",visible:!0,material:new u.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 u.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 Na=class t extends u.Group{constructor(i){super(),e(this,"_viewport"),e(this,"_border"),e(this,"_handles",[]),e(this,"_raycaster",new u.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 u.LineBasicMaterial({color:t._BORDER_COLOR,depthTest:!1});const n=new u.BufferGeometry;n.setAttribute("position",new u.BufferAttribute(new Float32Array(24),3)),this._border=new u.LineSegments(n,this._borderMat),this._border.renderOrder=999,this._border.frustumCulled=!1,this._border.userData.isDimension=!0,this.add(this._border),this._normalMat=new u.MeshBasicMaterial({color:t._BORDER_COLOR}),this._hoverMat=new u.MeshBasicMaterial({color:t._BORDER_HOVER_COLOR});const s=new u.SphereGeometry(.05,8,6);for(const e of t._HANDLE_DEFS){const t=new u.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 u.Vector3(0,1,0).transformDirection(this.matrixWorld),i=(new u.Vector3).setFromMatrixPosition(this.matrixWorld),n=(new u.Plane).setFromNormalAndCoplanarPoint(e,i),s=new u.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(Na,"_BORDER_COLOR",22015),e(Na,"_BORDER_HOVER_COLOR",16746496),e(Na,"_LINE_THRESHOLD",.06),e(Na,"_HANDLE_DEFS",[{constraints:["left","top"]},{constraints:["right","top"]},{constraints:["right","bottom"]},{constraints:["left","bottom"]},{constraints:["top"]},{constraints:["right"]},{constraints:["bottom"]},{constraints:["left"]}]);let Fa=Na;class Ra{constructor(t){e(this,"uuid",u.MathUtils.generateUUID()),e(this,"name"),e(this,"camera"),e(this,"onDisposed",new f),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 u.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 Fa(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 u.Vector3(this._left,0,-this._top),e=new u.Vector3(this._right,0,-this._bottom);return new u.Box3(t,e)}get size(){const t=new u.Vector3;return this.bbox.getSize(t),new u.Vector2(1e3*t.x,1e3*t.z)}get localXAxis(){return new u.Vector3(1,0,0)}get localYAxis(){return new u.Vector3(0,0,-1)}get normal(){return new u.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 u.Line3(e[0],e[1])}const o=this.getPlaneIntersections(t);return 0===o.length?null:s?new u.Line3(i,o[0]):new u.Line3(o[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 u.Plane(new u.Vector3(1,0,0),-t.min.x),new u.Plane(new u.Vector3(-1,0,0),t.max.x),new u.Plane(new u.Vector3(0,0,1),-t.min.z),new u.Plane(new u.Vector3(0,0,-1),t.max.z)]}getPlaneIntersections(t){const e=[];for(const i of this.bboxPlanes){const n=new u.Vector3;i.intersectLine(t,n)&&this.bbox.containsPoint(n)&&e.push(n)}return e}}class Ua extends h.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 Ra(t);return this._container.add(e.camera),e.setContainer(this._container),this.set(e.uuid,e),e}}const ja=class t extends u.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 u.Object3D),e(this,"widthHandle",new u.Object3D),e(this,"heightHandle",new u.Object3D),this._drawing=i,this._frameMat=new u.LineBasicMaterial({color:t._FRAME_COLOR,depthTest:!1}),this._depthMat=new u.LineBasicMaterial({color:t._DEPTH_COLOR,depthTest:!1,transparent:!0,opacity:.4}),this._planeMat=new u.MeshBasicMaterial({color:t._FRAME_COLOR,transparent:!0,opacity:.07,side:u.DoubleSide,depthTest:!1});const n=()=>{const t=new u.BufferGeometry;return t.setAttribute("position",new u.BufferAttribute(new Float32Array(12),3)),t.setIndex([0,1,2,0,2,3]),t};this._topPlane=new u.Mesh(n(),this._planeMat),this._topPlane.renderOrder=998,this._topPlane.frustumCulled=!1,this._topPlane.userData.isDimension=!0,this._bottomPlane=new u.Mesh(n(),this._planeMat),this._bottomPlane.renderOrder=998,this._bottomPlane.frustumCulled=!1,this._bottomPlane.userData.isDimension=!0;const s=new u.BufferGeometry;s.setAttribute("position",new u.BufferAttribute(new Float32Array(24),3)),this._topFrame=new u.LineSegments(s,this._frameMat),this._topFrame.renderOrder=999,this._topFrame.frustumCulled=!1,this._topFrame.userData.isDimension=!0;const r=new u.BufferGeometry;r.setAttribute("position",new u.BufferAttribute(new Float32Array(24),3)),this._pillars=new u.LineSegments(r,this._depthMat),this._pillars.renderOrder=999,this._pillars.frustumCulled=!1,this._pillars.userData.isDimension=!0;const o=new u.BufferGeometry;o.setAttribute("position",new u.BufferAttribute(new Float32Array(24),3)),this._bottomFrame=new u.LineSegments(o,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(ja,"_FRAME_COLOR",22015),e(ja,"_DEPTH_COLOR",22015);let $a=ja;function Wa(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 u.Vector3).subVectors(t[1],t[0]),n=(new u.Vector3).subVectors(t[2],t[0]);if((new u.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 u.Vector3).subVectors(e,t),s=(new u.Vector3).subVectors(i,t),r=n.clone().normalize(),o=(new u.Vector3).crossVectors(n,s).normalize(),a=(new u.Vector3).crossVectors(r,o).normalize();return(new u.Matrix4).makeBasis(r,o,a)},s=n(t[0],t[1],t[2]),r=n(e[0],e[1],e[2]).clone().multiply(s.clone().invert()),o=t[0].distanceTo(t[1]);if(o<1e-10)throw new Error("The first two drawing points are coincident — cannot compute scale.");const a=e[0].distanceTo(e[1])/o,l=t[0].clone().multiplyScalar(a).applyMatrix4(r),c=(new u.Vector3).subVectors(e[0],l),h=(new u.Quaternion).setFromRotationMatrix(r),d=new u.Matrix4;return d.compose(c,h,new u.Vector3(a,a,a)),d}class Ga{constructor(t){e(this,"uuid",u.MathUtils.generateUUID()),e(this,"_raycaster",new u.Raycaster),e(this,"_components"),e(this,"world",null),e(this,"three",new u.Group),e(this,"annotations",new Va),e(this,"layers",new La(this.three)),e(this,"activeLayer","0"),e(this,"far",10),e(this,"viewports",new Ua(this.three)),e(this,"onDisposed",new f),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 u.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 o=null;if(s.object instanceof u.LineSegments&&void 0!==s.index){const t=s.object.geometry.attributes.position,e=s.index,i=new u.Vector3(t.getX(e),t.getY(e),t.getZ(e)),n=new u.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),o=new u.Line3(i,n)}return{point:r,object:s.object,viewport:e,line:o}}alignTo(t,e){Wa(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 u.Matrix4).copy(e.three.matrixWorld).invert().multiply(t.matrixWorld),n=t.geometry.attributes.position,s=n.count,r=new Float32Array(3*s),o=new u.Vector3;for(let t=0;t<s;t++)o.fromBufferAttribute(n,t).applyMatrix4(i),r[3*t]=o.x,r[3*t+1]=0,r[3*t+2]=o.z;const a=new u.BufferGeometry;return a.setAttribute("position",new u.BufferAttribute(r,3)),new u.LineSegments(a)}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 u.LineDashedMaterial&&t.computeLineDistances(),t.geometry.computeBoundsTree({strategy:0,indirect:!0,type:hs}),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(Vr),n=i.projectionDirection.clone(),s=i.nearPlane,r=i.farPlane;try{this.three.updateWorldMatrix(!0,!1);const n=new u.Vector3(0,-1,0).transformDirection(this.three.matrixWorld).normalize();i.projectionDirection.copy(n);const s=(new u.Matrix4).makeRotationFromQuaternion((new u.Quaternion).setFromUnitVectors(n,new u.Vector3(0,-1,0))),r=(new u.Vector3).setFromMatrixPosition(this.three.matrixWorld).applyMatrix4(s).y;i.farPlane=r,i.nearPlane=r-this.far;const o=await i.get(t,this.world,{onProgress:e.onProgress}),a=t=>Ga.toDrawingSpace(new u.LineSegments(t),this);this.addProjectionLines(a(o.visible),e.layers.visible),this.addProjectionLines(a(o.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(v).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset()}}class Ha{constructor(t){e(this,"styles",new h.DataMap),e(this,"activeStyle","default"),e(this,"onCommit",new f),e(this,"onUpdate",new f),e(this,"onDelete",new f),e(this,"onDisposed",new f),e(this,"_knownDrawings",new Set),e(this,"_previewMaterial",new u.LineBasicMaterial({color:16737894,depthTest:!1})),e(this,"_previewObject",null),e(this,"_previewDrawing",null),e(this,"_materialCache",new h.DataMap),e(this,"_meshMaterialCache",new h.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(Dl),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 h.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:u.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 u.Raycaster;i.ray.copy(t),i.params.Line={threshold:e},i.params.LineSegments={threshold:e};const n=u.Line.prototype.raycast;let s=null,r=1/0;for(const t of this._knownDrawings)for(const[e,o]of t.annotations){if(o.system!==this)continue;const t=o.three;t.updateWorldMatrix(!0,!0),t.traverse(o=>{if(o===t)return;const a=[];if(o instanceof u.LineSegments&&o.userData.isDimension)n.call(o,i,a),a.length>0&&a[0].distance<r&&(r=a[0].distance,s=e);else if(o instanceof u.Mesh){const t=(new u.Box3).setFromObject(o),n=new u.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 u.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 u.MeshBasicMaterial({color:this._resolveStyle(t).color,side:u.DoubleSide});return this._meshMaterialCache.set(t,i),i}_disposeGroup(t){if(t.removeFromParent(),this._ownsChildGeometry)t.traverse(t=>{t.geometry instanceof u.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 u.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 qa(t,e){const i=t[0],n=t[t.length-1],s=(new u.Vector3).subVectors(n,i);if(s.lengthSq()<1e-10)return 0;s.normalize();const r=new u.Vector3(-s.z,0,s.x);return e.clone().sub(i).dot(r)}function Za(t,e){const i=[];for(let n=0;n<t.length-1;n++)i.push({uuid:u.MathUtils.generateUUID(),pointA:t[n].clone(),pointB:t[n+1].clone(),offset:e,style:""});return i}function Ya(t,e){switch(t.kind){case"awaitingFirstPoint":if("CLICK"===e.type){if(!e.line)return t;const i=(new u.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 u.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 u.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),o=[...t.points,r];return{...t,points:o,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=qa(t.points,e.point);return{kind:"committed",dimensions:Za(t.points,i)}}return"ESCAPE"===e.type?{kind:"awaitingFirstPoint"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingFirstPoint"}:t}var i,n}function Xa(t){const{pointA:e,pointB:i,offset:n}=t,s=(new u.Vector3).subVectors(i,e),r=new u.Vector3(-s.z,0,s.x).normalize(),o=e.clone().addScaledVector(r,n),a=i.clone().addScaledVector(r,n),l=(new u.Vector3).subVectors(a,o).normalize();return[{tip:o,dir:l},{tip:a,dir:l.clone().negate()}]}function Ka(t,e){const{pointA:i,pointB:n,offset:s}=t,r=(new u.Vector3).subVectors(n,i),o=new u.Vector3(-r.z,0,r.x).normalize(),a=s>=0?1:-1,l=Math.abs(s),c=i.clone().addScaledVector(o,e.extensionGap*a),h=i.clone().addScaledVector(o,(l+e.extensionOvershoot)*a),d=n.clone().addScaledVector(o,e.extensionGap*a),p=n.clone().addScaledVector(o,(l+e.extensionOvershoot)*a),f=i.clone().addScaledVector(o,s),m=n.clone().addScaledVector(o,s),g=(new u.Vector3).subVectors(m,f).normalize(),w=e.lineTick(f,g,e.tickSize),y=e.lineTick(m,g.clone().negate(),e.tickSize);return[c.x,c.y,c.z,h.x,h.y,h.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 Qa(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=qa(e,i),r=[];for(let t=0;t<e.length-1;t++)r.push(...Ka({pointA:e[t],pointB:e[t+1],offset:s},n));return r}class Ja extends Ha{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingFirstPoint"}),e(this,"onMachineStateChanged",new f),this.styles.set("default",{lineTick:za,tickSize:.4,extensionGap:.05,extensionOvershoot:.2,color:0,textOffset:.4,fontSize:.45})}pickHandle(t,e,i=.1){const n=(new u.Matrix4).copy(t.three.matrixWorld).invert(),s=e.origin.clone().applyMatrix4(n),r=e.direction.clone().transformDirection(n).normalize(),o=new u.Ray(s,r),a=new u.Plane(new u.Vector3(0,1,0),0),l=o.intersectPlane(a,new u.Vector3);if(!l)return null;let c=null,h=i;for(const[e,i]of t.annotations.getBySystem(this)){const t=(new u.Vector3).subVectors(i.pointB,i.pointA),n=new u.Vector3(-t.z,0,t.x).normalize(),s=(new u.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(l.x-n.x,l.z-n.z);i<h&&(h=i,c={uuid:e,handle:t})}}return c}sendMachineEvent(t){const e=t.drawing??null;e&&(this._previewDrawing=e);const i=Ya(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 u.Group,n=Ka(t,e),s=new u.BufferGeometry;s.setAttribute("position",new u.BufferAttribute(new Float32Array(n),3));const r=new u.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 Xa(t)){const r=e.meshTick(n,s,e.tickSize),o=new u.BufferGeometry;o.setAttribute("position",new u.BufferAttribute(new Float32Array(r),3));const a=new u.Mesh(o,this._getMeshMaterial(t.style));a.layers.set(1),a.userData.isMeshTick=!0,i.add(a)}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=Qa(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 u.BufferGeometry;t.setAttribute("position",new u.BufferAttribute(new Float32Array(i),3)),this._previewObject=new u.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 tl=Math.PI/180;function el(t,e,i,n){const s=function(t,e,i){const n=(new u.Vector3).subVectors(t,e).normalize(),s=(new u.Vector3).subVectors(i,e).normalize();return(new u.Vector3).addVectors(n,s).normalize()}(t,e,i);return(new u.Vector3).subVectors(n,e).setY(0).dot(s)}function il(t,e,i,n){return el(t,e,i,n)<0}function nl(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 u.Vector3).subVectors(t.line1.end,t.line1.start).normalize(),n=(new u.Vector3).subVectors(e.line.end,e.line.start).normalize();if(Math.abs(i.dot(n))>Math.cos(tl))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 u.Vector3).subVectors(i,t),o=(r.x*n.z-r.z*n.x)/s;return new u.Vector3(t.x+e.x*o,0,t.z+e.z*o)}(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=il(t.pointA,t.vertex,t.pointB,e.point);return{...t,cursor:e.point.clone(),flipped:i}}if("CLICK"===e.type){const i=il(t.pointA,t.vertex,t.pointB,e.point),n=Math.max(.05,Math.abs(el(t.pointA,t.vertex,t.pointB,e.point)));return{kind:"committed",dimension:{uuid:u.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 sl(t){const e=(new u.Vector3).subVectors(t.pointA,t.vertex).normalize(),i=(new u.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 u.Vector3(t.vertex.x+Math.cos(n)*t.arcRadius,0,t.vertex.z+Math.sin(n)*t.arcRadius),o=n+s,a=new u.Vector3(t.vertex.x+Math.cos(o)*t.arcRadius,0,t.vertex.z+Math.sin(o)*t.arcRadius),l=Math.sign(s);return[{tip:r,dir:new u.Vector3(-Math.sin(n)*l,0,Math.cos(n)*l)},{tip:a,dir:new u.Vector3(Math.sin(o)*l,0,-Math.cos(o)*l)}]}function rl(t){const e=(new u.Vector3).subVectors(t.pointA,t.vertex).normalize(),i=(new u.Vector3).subVectors(t.pointB,t.vertex).normalize(),n=Math.acos(u.MathUtils.clamp(e.dot(i),-1,1));return t.flipped?2*Math.PI-n:n}function ol(t){const e=(new u.Vector3).subVectors(t.pointA,t.vertex).normalize(),i=(new u.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 al(t,e,i,n,s,r=!1){const o=Math.atan2(e.z,e.x);let a=Math.atan2(i.z,i.x)-o;for(;a>Math.PI;)a-=2*Math.PI;for(;a<-Math.PI;)a+=2*Math.PI;r&&(a-=2*Math.sign(a)*Math.PI);const l=[];for(let e=0;e<8;e++){const i=o+a*(e/8),s=o+a*((e+1)/8);l.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 c=new u.Vector3(t.x+Math.cos(o)*n,0,t.z+Math.sin(o)*n),h=new u.Vector3(t.x+Math.cos(o+a)*n,0,t.z+Math.sin(o+a)*n),d=t.clone().addScaledVector(e,s.extensionGap),p=t.clone().addScaledVector(i,s.extensionGap);l.push(d.x,d.y,d.z,c.x,c.y,c.z,p.x,p.y,p.z,h.x,h.y,h.z);const f=Math.sign(a),m=new u.Vector3(-Math.sin(o)*f,0,Math.cos(o)*f),g=o+a,w=new u.Vector3(Math.sin(g)*f,0,-Math.cos(g)*f);return l.push(...s.lineTick(c,m,s.tickSize),...s.lineTick(h,w,s.tickSize)),l}function ll(t,e){const i=(new u.Vector3).subVectors(t.pointA,t.vertex).normalize(),n=(new u.Vector3).subVectors(t.pointB,t.vertex).normalize();return al(t.vertex,i,n,t.arcRadius,e,t.flipped??!1)}function cl(t,e,i,n,s,r=!1){if(!n)return[];const o=Math.max(.05,(new u.Vector3).subVectors(n,e).setY(0).length());return al(e,(new u.Vector3).subVectors(t,e).normalize(),(new u.Vector3).subVectors(i,e).normalize(),o,s,r)}class hl extends Ha{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingFirstLine"}),e(this,"onMachineStateChanged",new f),e(this,"_secondLinePreviewObject",null),this.styles.set("default",{lineTick:za,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=nl(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 u.Group,n=ll(t,e),s=new u.BufferGeometry;s.setAttribute("position",new u.BufferAttribute(new Float32Array(n),3));const r=new u.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 sl(t)){const r=e.meshTick(n,s,e.tickSize),o=new u.BufferGeometry;o.setAttribute("position",new u.BufferAttribute(new Float32Array(r),3));const a=new u.Mesh(o,this._getMeshMaterial(t.style));a.layers.set(1),a.userData.isMeshTick=!0,i.add(a)}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=cl(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 u.BufferGeometry;t.setAttribute("position",new u.BufferAttribute(new Float32Array(i),3)),this._previewObject=new u.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 u.Vector3).subVectors(i.line1.end,i.line1.start).normalize();if(!e)return void this._clearSecondLinePreview();const s=(new u.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,o=i.z-t.z,a=(r*n.z-o*n.x)/s;return new u.Vector3(t.x+a*e.x,0,t.z+a*e.z)}(i.line1.start,n,e.start,s);if(!r)return void this._clearSecondLinePreview();const o=t.clone(),a=(new u.Vector3).subVectors(o,r).setY(0);if(a.length()<.01)return void this._clearSecondLinePreview();const l=(new u.Vector3).subVectors(i.pointA,r).normalize(),c=a.normalize(),h=Math.atan2(l.z,l.x);let d=Math.atan2(c.z,c.x)-h;for(;d>Math.PI;)d-=2*Math.PI;for(;d<-Math.PI;)d+=2*Math.PI;const p=h+d/2,f=Math.max(.1,.4*Math.min(i.pointA.distanceTo(r),o.distanceTo(r))),m=new u.Vector3(r.x+Math.cos(p)*f,0,r.z+Math.sin(p)*f),g=this._resolveStyle(this.activeStyle),w=cl(i.pointA,r,o,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 u.BufferGeometry;t.setAttribute("position",new u.BufferAttribute(new Float32Array(w),3)),this._secondLinePreviewObject=new u.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 ul(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),o=Math.round(r/(Math.PI/4))*(Math.PI/4);return new u.Vector3(t.x+Math.cos(o)*s,0,t.z+Math.sin(o)*s)}function dl(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:ul(t.elbow,e.point)}:"CLICK"===e.type?{kind:"enteringText",arrowTip:t.arrowTip,elbow:t.elbow,extensionEnd:ul(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:u.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 pl(t,e,i,n){return"curved"===n.leaderShape?function(t,e,i,n){const s=new u.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 u.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 u.Vector3).subVectors(t,e);i.lengthSq()>1e-10&&s.push(...n.lineTick(t,i.normalize(),n.tickSize))}return s}(t,e,i,n)}function fl(t,e){return pl(t.arrowTip,t.elbow,t.extensionEnd,e)}function ml(t,e,i,n,s){return n?pl(e,"placingElbow"===t?n:i,n,s):[]}class gl extends Ha{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingArrowTip"}),e(this,"onMachineStateChanged",new f),e(this,"_previewMeshMaterial",new u.MeshBasicMaterial({color:16737894,side:u.DoubleSide,depthTest:!1})),e(this,"_previewMeshObject",null),this.styles.set("default",{tickSize:.4,color:0,textOffset:.1,fontSize:.45,lineTick:ka})}pickHandle(t,e,i=.1){const n=(new u.Matrix4).copy(t.three.matrixWorld).invert(),s=e.origin.clone().applyMatrix4(n),r=e.direction.clone().transformDirection(n).normalize(),o=new u.Ray(s,r),a=new u.Plane(new u.Vector3(0,1,0),0),l=o.intersectPlane(a,new u.Vector3);if(!l)return null;let c=null,h=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(l.x-n.x,l.z-n.z);i<h&&(h=i,c={uuid:e,handle:t})}return c}sendMachineEvent(t){const e=t.drawing??null;e&&(this._previewDrawing=e);const i=dl(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 u.Group,n=fl(t,e),s=new u.BufferGeometry;s.setAttribute("position",new u.BufferAttribute(new Float32Array(n),3));const r=new u.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick){const n=(new u.Vector3).subVectors(t.arrowTip,t.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=e.meshTick(t.arrowTip,n,e.tickSize),r=new u.BufferGeometry;r.setAttribute("position",new u.BufferAttribute(new Float32Array(s),3));const o=new u.Mesh(r,this._getMeshMaterial(t.style));o.layers.set(1),o.userData.isMeshArrow=!0,i.add(o)}}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?ml("placingElbow",t.arrowTip,null,t.cursor,e):ml("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 u.BufferGeometry;t.setAttribute("position",new u.BufferAttribute(new Float32Array(i),3)),this._previewObject=new u.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 u.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 u.BufferGeometry;t.setAttribute("position",new u.BufferAttribute(new Float32Array(i),3)),this._previewMeshObject=new u.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 wl extends Ha{constructor(t){super(t),e(this,"enabled",!0),e(this,"_ownsChildGeometry",!1),e(this,"definitions",new h.DataMap),this.styles.set("default",{color:0,textOffset:0,fontSize:0})}pickHandle(t,e,i){return null}pick(t,e=.05){const i=new u.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 u.LineSegments))return;const o=[];r.raycast(i,o),o.length>0&&o[0].distance<s&&(s=o[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 u.Group;if(i.lines){const e=new u.LineSegments(i.lines,this._getMaterial(t.style));e.layers.set(1),e.userData.isDimension=!0,n.add(e)}if(i.mesh){const e=new u.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 yl(t,e){const{position:i,direction:n}=t,{length:s}=e,r=new u.Vector3(i.x+n.x*s,0,i.z+n.z*s),o=new u.Vector3(n.x,0,n.z),a=e.lineTick(r,o,e.tickSize),l=[i.x,0,i.z,r.x,0,r.z];return new Float32Array([...l,...a])}function _l(t,e){return new u.Vector3(t.position.x+t.direction.x*e,0,t.position.z+t.direction.z*e)}function bl(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 vl extends Ha{constructor(t){super(t),e(this,"enabled",!0),this.styles.set("default",{lineTick:Ba,meshTick:Oa,tickSize:.4,length:3,color:0,textOffset:.1,fontSize:.45,format:"percentage"})}pickHandle(t,e,i){return null}_buildGroup(t,e){const i=new u.Group,n=yl(t,e),s=new u.BufferGeometry;s.setAttribute("position",new u.BufferAttribute(n,3));const r=new u.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick){const n=_l(t,e.length),s=e.meshTick(n,t.direction,e.tickSize),r=new u.BufferGeometry;r.setAttribute("position",new u.BufferAttribute(new Float32Array(s),3));const o=new u.Mesh(r,this._getMeshMaterial(t.style));o.layers.set(1),o.userData.isDimension=!0,i.add(o)}return i}}function xl(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),o=Math.round(r/(Math.PI/4))*(Math.PI/4);return new u.Vector3(t.x+Math.cos(o)*s,0,t.z+Math.sin(o)*s)}function Cl(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:xl(t.elbow,e.point)}:"CLICK"===e.type?{kind:"enteringText",center:t.center,halfW:t.halfW,halfH:t.halfH,elbow:t.elbow,extensionEnd:xl(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:u.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 Sl(t,e){const i=[];i.push(...e.enclosure.buildGeometry(t.center,t.halfW,t.halfH));const n=(new u.Vector3).subVectors(t.elbow,t.center),s=n.lengthSq()>1e-10?n.clone().normalize():new u.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 u.Vector3).subVectors(t.extensionEnd,t.elbow);n.lengthSq()>1e-10&&i.push(...e.lineTick(t.extensionEnd,n.normalize(),e.tickSize))}return i}function Al(t,e,i,n,s,r,o){const a="awaitingRadius"===t?r?Math.max(.05,Math.abs(r.x-e.x)):0:i,l="awaitingRadius"===t?r?Math.max(.05,Math.abs(r.z-e.z)):0:n;if(a<1e-10||l<1e-10)return[];const c=[];if(c.push(...o.enclosure.buildGeometry(e,a,l)),"awaitingRadius"===t)return c;const h="awaitingElbow"===t?r:s;if(!h)return c;const d=(new u.Vector3).subVectors(h,e),p=d.lengthSq()>1e-10?d.clone().normalize():new u.Vector3(1,0,0),f=o.enclosure.getAttachmentPoint(e,a,l,p);return"awaitingElbow"===t?(c.push(f.x,0,f.z,h.x,0,h.z),c):r?(c.push(f.x,0,f.z,s.x,0,s.z,s.x,0,s.z,r.x,0,r.z),c):c}const Pl={buildGeometry(t,e,i){const n=.25*Math.min(e,i),s=new u.Vector3(t.x-e,0,t.z-i),r=new u.Vector3(t.x+e,0,t.z-i),o=new u.Vector3(t.x+e,0,t.z+i),a=new u.Vector3(t.x-e,0,t.z+i),l=[[s,r,new u.Vector3(0,0,-1)],[r,o,new u.Vector3(1,0,0)],[o,a,new u.Vector3(0,0,1)],[a,s,new u.Vector3(-1,0,0)]],c=[];for(const[t,e,i]of l){const s=t.distanceTo(e),r=Math.max(1,Math.round(s/(2*n))),o=s/r,a=o/2,l=(new u.Vector3).subVectors(e,t).normalize();for(let e=0;e<r;e++){const n=t.clone().addScaledVector(l,(e+.5)*o),s=t.clone().addScaledVector(l,e*o),r=(new u.Vector3).subVectors(s,n);let h=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*a*Math.sin(e),o=n.z+r.z*Math.cos(e)+i.z*a*Math.sin(e),l=new u.Vector3(s,0,o);c.push(h.x,0,h.z,l.x,0,l.z),h=l}}}return c},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,o=Math.min(s,r);return new u.Vector3(t.x+n.x*o,0,t.z+n.z*o)}},Tl={buildGeometry(t,e,i){const n=new u.Vector3(t.x-e,0,t.z-i),s=new u.Vector3(t.x+e,0,t.z-i),r=new u.Vector3(t.x+e,0,t.z+i),o=new u.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,o.x,0,o.z,o.x,0,o.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,o=Math.min(s,r);return new u.Vector3(t.x+n.x*o,0,t.z+n.z*o)}},Ml={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,o=Math.sqrt(s*s+r*r),a=o>1e-10?1/o:e;return new u.Vector3(t.x+n.x*a,0,t.z+n.z*a)}};class El extends Ha{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingCenter"}),e(this,"onMachineStateChanged",new f),this.styles.set("default",{enclosure:Pl,lineTick:ka,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=Cl(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 u.Group,n=Sl(t,e),s=new u.BufferGeometry;s.setAttribute("position",new u.BufferAttribute(new Float32Array(n),3));const r=new u.LineSegments(s,this._getMaterial(t.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),e.meshTick){const n=(new u.Vector3).subVectors(t.extensionEnd,t.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=e.meshTick(t.extensionEnd,n,e.tickSize),r=new u.BufferGeometry;r.setAttribute("position",new u.BufferAttribute(new Float32Array(s),3));const o=new u.Mesh(r,this._getMeshMaterial(t.style));o.layers.set(1),o.userData.isMeshArrow=!0,i.add(o)}}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 Al("awaitingRadius",t.center,0,0,null,t.cursor,e);case"awaitingElbow":return Al("awaitingElbow",t.center,t.halfW,t.halfH,null,t.cursor,e);case"awaitingExtension":return Al("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 u.BufferGeometry;t.setAttribute("position",new u.BufferAttribute(new Float32Array(i),3)),this._previewObject=new u.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 Il=class t extends g{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new h.DataMap),e(this,"systems",new h.DataMap),e(this,"onDisposed",new f),i.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 Ga(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 Ro&&(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(Il,"uuid","5c7d3b9a-4e8f-4a2b-9c1d-0e3f2a5b7c8d");let Dl=Il;const zl=[[16711680,1],[16776960,2],[65280,3],[65535,4],[255,5],[16711935,6],[16777215,7],[0,7]];function kl(t){const e=t>>16&255,i=t>>8&255,n=255&t;let s=7,r=1/0;for(const[t,o]of zl){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 Bl="\0HANDSEED\0";class Ol{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",Bl),this}build(){return(this._lines.join("\n")+"\n").replace(Bl,this._handleCounter.toString(16).toUpperCase())}}class Vl{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 Ol,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(Dl).systems.get(wl),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=kl(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 u.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,kl(s),s)})}_writeLinearAnnotations(t,e){var i;const n=this._components.get(Dl).systems.get(Ja);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=kl(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(a))?void 0:i.visible))continue;const l=Ka(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(t,l,a,o,r.color),r.meshTick)for(const{tip:e,dir:i}of Xa(s))this._writeMeshTriangles(t,r.meshTick(e,i,r.tickSize),a,o,r.color);const c=(new u.Vector3).subVectors(s.pointB,s.pointA),h=new u.Vector3(-c.z,0,c.x).normalize(),d=s.offset>=0?1:-1,p=s.pointA.clone().addScaledVector(h,s.offset),f=s.pointB.clone().addScaledVector(h,s.offset),m=p.clone().add(f).multiplyScalar(.5).addScaledVector(h,(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,a,o,this._textAngle(c.x,c.z),1,2,r.color)}}_writeAngleAnnotations(t,e){var i;const n=this._components.get(Dl).systems.get(hl);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=kl(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(a))?void 0:i.visible))continue;const l=ll(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(t,l,a,o,r.color),r.meshTick)for(const{tip:e,dir:i}of sl(s))this._writeMeshTriangles(t,r.meshTick(e,i,r.tickSize),a,o,r.color);const c=ol(s),h=s.arcRadius+r.textOffset,d=s.vertex.x+Math.cos(c)*h,p=s.vertex.z+Math.sin(c)*h,f=u.MathUtils.radToDeg(rl(s));this._writeText(t,`${f.toFixed(this.precision)}°`,d,p,r.fontSize,a,o,0,1,0,r.color)}}_writeLeaderAnnotations(t,e){var i;const n=this._components.get(Dl).systems.get(gl);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=kl(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(a))?void 0:i.visible))continue;const l=fl(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(t,l,a,o,r.color),r.meshTick){const e=(new u.Vector3).subVectors(s.arrowTip,s.elbow);e.lengthSq()>1e-10&&this._writeMeshTriangles(t,r.meshTick(s.arrowTip,e.normalize(),r.tickSize),a,o,r.color)}const c=(new u.Vector3).subVectors(s.extensionEnd,s.elbow).setY(0).normalize(),h=c.x<-.1?2:c.x>.1?0:1,d=1===h?.5*r.fontSize:0,p=s.extensionEnd.clone().addScaledVector(c,r.textOffset+d);this._writeText(t,s.text,p.x,p.z,r.fontSize,a,o,0,h,2,r.color)}}_writeSlopeAnnotations(t,e){var i;const n=this._components.get(Dl).systems.get(vl);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=kl(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(a))?void 0:i.visible))continue;const l=yl(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(t,l,a,o,r.color),r.meshTick){const e=_l(s,r.length);this._writeMeshTriangles(t,r.meshTick(e,s.direction,r.tickSize),a,o,r.color)}const c=new u.Vector3(s.position.x+s.direction.x*r.length,0,s.position.z+s.direction.z*r.length),h=s.position.clone().add(c).multiplyScalar(.5).addScaledVector(new u.Vector3(-s.direction.z,0,s.direction.x),r.textOffset+r.fontSize);this._writeText(t,bl(s.slope,r.format),h.x,h.z,r.fontSize,a,o,this._textAngle(s.direction.x,s.direction.z),1,0,r.color)}}_writeCalloutAnnotations(t,e){var i;const n=this._components.get(Dl).systems.get(El);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=kl(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(a))?void 0:i.visible))continue;const l=Sl(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(t,l,a,o,r.color),r.meshTick){const e=(new u.Vector3).subVectors(s.extensionEnd,s.elbow);e.lengthSq()>1e-10&&this._writeMeshTriangles(t,r.meshTick(s.extensionEnd,e.normalize(),r.tickSize),a,o,r.color)}const c=(new u.Vector3).subVectors(s.extensionEnd,s.elbow).setY(0).normalize(),h=c.x<-.1?2:c.x>.1?0:1,d=1===h?.5*r.fontSize:0,p=s.extensionEnd.clone().addScaledVector(c,r.textOffset+d);this._writeText(t,s.text,p.x,p.z,r.fontSize,a,o,0,h,2,r.color)}}_writeBlockInsertions(t,e){const i=this._components.get(Dl).systems.get(wl);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=kl(e.color),r=-u.MathUtils.radToDeg(n.rotation),o=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,o).n(42,o).n(43,o).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 o=this._clipSegment(new u.Vector3(r.getX(e),0,r.getZ(e)),new u.Vector3(r.getX(e+1),0,r.getZ(e+1)));o&&this._writeLine(t,o.start.x,o.start.z,o.end.x,o.end.z,i,n,s)}}_writePairsAsLines(t,e,i,n=7,s){for(let r=0;r+5<e.length;r+=6){const o=this._clipSegment(new u.Vector3(e[r],0,e[r+2]),new u.Vector3(e[r+3],0,e[r+5]));o&&this._writeLine(t,o.start.x,o.start.z,o.end.x,o.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 u.Line3(t,e)):new u.Line3(t,e)}_inViewport(t,e){return!this._viewport||this._viewport.bbox.containsPoint(new u.Vector3(t,0,e))}_bboxFromPositions(t){const e=new u.Box3;for(let i=0;i+2<t.length;i+=3)e.expandByPoint(new u.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),u.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(Dl).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:kl,textAngle:(t,e)=>this._textAngle(t,e)}}}const Ll=class t extends g{constructor(i){super(i),e(this,"enabled",!0),e(this,"exporter",new Vl(this.components)),i.add(t.uuid,this)}};e(Ll,"uuid","e9a2c3d4-5f67-4b89-a012-1c3d5e7f9b2a");let Nl=Ll;exports.AngleAnnotations=hl,exports.AnnotationSystem=Ha,exports.ArrowTick=(t,e,i)=>{const n=new u.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,o=t.x-e.x*i-n.x*i*.4,a=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,o,t.y,a,s,t.y,r,o,t.y,a]},exports.AsyncEvent=class{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}},exports.BCFTopics=Qo,exports.BCFTopicsConfigManager=Xo,exports.Base=m,exports.BaseCamera=y,exports.BaseRenderer=_,exports.BaseScene=x,exports.BaseWorldItem=w,exports.BlockAnnotations=wl,exports.BoundingBoxer=$r,exports.CalloutAnnotations=El,exports.CircleEnclosure=Ml,exports.Classifier=Zr,exports.Clipper=ia,exports.CloudEnclosure=Pl,exports.Comment=Ho,exports.Component=g,exports.Components=Oo,exports.ConfigManager=ye,exports.Configurator=ge,exports.ControlsUtils=me,exports.DataMap=fe,exports.DataSet=C,exports.DiagonalTick=za,exports.Disposer=v,exports.DotTick=(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},exports.DrawingAnnotations=Va,exports.DrawingLayers=La,exports.DrawingSystem=Ha,exports.DrawingViewport=Ra,exports.DrawingViewportHelper=Fa,exports.DrawingViewports=Ua,exports.DxfExporter=Vl,exports.DxfManager=Nl,exports.EdgeProjector=Vr,exports.Event=f,exports.EventManager=class{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()}},exports.FastModelPicker=Xr,exports.FastModelPickers=Qr,exports.FilledArrowTick=Oa,exports.FilledCircleTick=(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},exports.FilledSquareTick=(t,e,i)=>{const n=new u.Vector3(-e.z,0,e.x),s=.4*i,r=t.clone().addScaledVector(e,s).addScaledVector(n,s),o=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);return[r.x,r.y,r.z,o.x,o.y,o.z,a.x,a.y,a.z,r.x,r.y,r.z,a.x,a.y,a.z,l.x,l.y,l.z]},exports.FinderQuery=Wr,exports.FirstPersonMode=Vo,exports.FragmentsManager=bs,exports.Grids=ko,exports.Hider=Ur,exports.IDSAttribute=fa,exports.IDSClassification=ma,exports.IDSEntity=ga,exports.IDSFacet=da,exports.IDSMaterial=ya,exports.IDSPartOf=_a,exports.IDSProperty=wa,exports.IDSSpecification=ba,exports.IDSSpecifications=Ea,exports.IfcFragmentSettings=Lr,exports.IfcLoader=Fr,exports.ItemsFinder=Hr,exports.LeaderAnnotations=gl,exports.LinearAnnotations=Ja,exports.MeasurementUtils=Da,exports.ModelIdMapUtils=pe,exports.Mouse=_e,exports.NoTick=Ba,exports.OpenArrowTick=ka,exports.OrbitMode=Lo,exports.OrthoPerspectiveCamera=Ro,exports.PlanMode=No,exports.ProjectionManager=Fo,exports.Raycasters=_o,exports.RectEnclosure=Tl,exports.RendererMode=Po,exports.ShadowedScene=class extends So{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 u.PerspectiveCamera||e instanceof u.OrthographicCamera))throw new Error("Invalid camera type!");const i=new u.Vector3;e.getWorldDirection(i);let n=t;const s=new u.Vector3;s.copy(this.config.directionalLight.position),s.normalize();for(const[t,r]of this._lightsWithShadow){const o=this.directionalLights.get(r);if(!o)throw new Error("Light not found.");const a=new u.Vector3;a.copy(i);const l=t===this._lightsWithShadow.size-1,c=l?n/2:2*n/3;a.multiplyScalar(c),a.add(e.position);const h=n-c,d=new u.Vector3;d.copy(s),d.multiplyScalar(h),o.target.position.copy(a),o.position.copy(a),o.position.add(d),o.shadow.camera.right=h,o.shadow.camera.left=-h,o.shadow.camera.top=h,o.shadow.camera.bottom=-h,o.shadow.camera.far=2*h,o.shadow.camera.updateProjectionMatrix(),o.shadow.camera.updateMatrix(),l||(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 ua(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let t=0;t<e.cascade;t++){const i=new u.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())}},exports.SimpleCamera=To,exports.SimpleGrid=Do,exports.SimpleGridConfigManager=Io,exports.SimplePlane=Jo,exports.SimpleRaycaster=wo,exports.SimpleRenderer=class extends _{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 f),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 u.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 u.WebGLRenderer({canvas:this._canvas,antialias:!0,alpha:!0,...this._parameters}),this.enabled=!0}),this.container=i,this._parameters=n,this.three=new u.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 u.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=Ao,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)}},exports.SimpleScene=So,exports.SimpleSceneConfigManager=Co,exports.SimpleWorld=bo,exports.SlopeAnnotations=vl,exports.SnapClass=Jr,exports.SnapResolver=eo,exports.SnapResolvers=go,exports.TechnicalDrawing=Ga,exports.TechnicalDrawingHelper=$a,exports.TechnicalDrawings=Dl,exports.Topic=Zo,exports.UUID=A,exports.Units={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"}},exports.VertexPicker=class extends g{constructor(t,i){super(t),e(this,"onDisposed",new f),e(this,"onVertexFound",new f),e(this,"onVertexLost",new f),e(this,"onEnabled",new f),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(_o).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}},exports.View=aa,exports.Viewpoint=na,exports.Viewpoints=oa,exports.Views=ca,exports.Worlds=Eo,exports.XML=de,exports.angleDimensionMachine=nl,exports.buildAnglePositions=ll,exports.buildAnglePreviewPositions=cl,exports.buildCalloutPositions=Sl,exports.buildCalloutPreviewPositions=Al,exports.buildDimensionPositions=Ka,exports.buildDimensions=Za,exports.buildLeaderPositions=fl,exports.buildLeaderPreviewPositions=ml,exports.buildPreviewPositions=Qa,exports.buildSlopePositions=yl,exports.calloutAnnotationMachine=Cl,exports.computeAlignmentMatrix=Wa,exports.computeAngle=rl,exports.computeBisectorAngle=ol,exports.computeOffset=qa,exports.extensionsImporter=Yo,exports.formatSlope=bl,exports.getAngleTickEndpoints=sl,exports.getDimensionTickEndpoints=Xa,exports.getSlopeTip=_l,exports.leaderAnnotationMachine=dl,exports.linearDimensionMachine=Ya;
1
+ "use strict";Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const e=require("@thatopen/fragments"),t=require("three"),i=require("three/webgpu"),n=require("three/tsl"),s=require("web-ifc"),r=require("camera-controls"),o=require("three/examples/jsm/controls/TransformControls.js");function a(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const i in e)if("default"!==i){const n=Object.getOwnPropertyDescriptor(e,i);Object.defineProperty(t,i,n.get?n:{enumerable:!0,get:()=>e[i]})}return t.default=e,Object.freeze(t)}const l=a(e),c=a(t),h=a(i),u=a(s);class d{enabled=!0;add(e){this.handlers.push(e)}remove(e){this.handlers=this.handlers.filter(t=>t!==e)}trigger=e=>{if(!this.enabled)return;const t=this.handlers.slice(0);for(const i of t)i(e)};reset(){this.handlers.length=0}handlers=[]}class p{constructor(e){this.components=e}components;isDisposeable=()=>"dispose"in this&&"onDisposed"in this;isResizeable=()=>"resize"in this&&"getSize"in this;isUpdateable=()=>"onAfterUpdate"in this&&"onBeforeUpdate"in this&&"update"in this;isHideable=()=>"visible"in this;isConfigurable=()=>"setup"in this&&"config"in this&&"onSetup"in this;isSerializable=()=>"import"in this&&"export"in this}class f extends p{}class m extends p{worlds=new e.DataMap;onWorldChanged=new d;_currentWorld=null;set currentWorld(e){this._currentWorld=e}get currentWorld(){return this._currentWorld}constructor(e){super(e),this.onWorldChanged.add(({world:e,action:t})=>{"removed"===t&&this.worlds.delete(e.uuid)})}}class g extends m{hasCameraControls=()=>"controls"in this}class w extends m{onAfterUpdate=new d;onBeforeUpdate=new d;onDisposed=new d;onResize=new d;onClippingPlanesUpdated=new d;clippingPlanes=[];localClippingPlanes=!1;updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(e,t,i=this.localClippingPlanes){t.isLocal=i;const n=this.clippingPlanes.indexOf(t);e&&-1===n?this.clippingPlanes.push(t):!e&&n>-1&&this.clippingPlanes.splice(n,1),this.three.clippingPlanes=this.clippingPlanes.filter(e=>!e.isLocal),this.updateClippingPlanes()}}class y extends f{_disposedComponents=new Set;enabled=!0;static uuid="76e9cd8e-ad8f-4753-9ef6-cbc60f7247fe";constructor(e){super(e),e.add(y.uuid,this)}get(){return this._disposedComponents}destroy(e,t=!0,i=!0){e.removeFromParent();const n=e;n.dispose&&n.dispose(),this.disposeGeometryAndMaterials(e,t),i&&n.children&&n.children.length&&this.disposeChildren(n),e.children.length=0}disposeGeometry(e){e.boundsTree&&e.disposeBoundsTree&&e.disposeBoundsTree(),e.dispose()}disposeGeometryAndMaterials(e,t){const i=e;i.geometry&&this.disposeGeometry(i.geometry),t&&i.material&&y.disposeMaterial(i),i.material=[],i.geometry=null}disposeChildren(e){for(const t of[...e.children])this.destroy(t)}static disposeMaterial(e){if(e.material)if(Array.isArray(e.material))for(const t of e.material)t.dispose();else e.material.dispose()}}class _ extends m{onDisposed=new d;directionalLights=new Map;ambientLights=new Map;constructor(e){super(e)}dispose(){const e=this.components.get(y);for(const t of this.three.children){const i=t;i.geometry&&e.destroy(i)}this.deleteAllLights(),this.three.children=[],this.onDisposed.trigger(),this.onDisposed.reset()}deleteAllLights(){for(const[,e]of this.directionalLights)e.removeFromParent(),e.target.removeFromParent(),e.dispose();this.directionalLights.clear();for(const[,e]of this.ambientLights)e.removeFromParent(),e.dispose();this.ambientLights.clear()}}class b extends Set{onItemAdded=new d;onItemDeleted=new d;onCleared=new d;constructor(e){super(e)}clear(){super.clear(),this.onCleared.trigger()}add(...e){for(const t of e){if(this.has(t))continue;this.guard(t)&&(super.add(t),this.onItemAdded||(this.onItemAdded=new d),this.onItemAdded.trigger(t))}return this}guard=()=>!0;delete(e){const t=super.delete(e);return t&&this.onItemDeleted.trigger(),t}dispose(){this.clear(),this.onItemAdded.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}class v{static _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}$/;static _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"];static create(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,n=4294967295*Math.random()|0;return`${v._lut[255&e]+v._lut[e>>8&255]+v._lut[e>>16&255]+v._lut[e>>24&255]}-${v._lut[255&t]}${v._lut[t>>8&255]}-${v._lut[t>>16&15|64]}${v._lut[t>>24&255]}-${v._lut[63&i|128]}${v._lut[i>>8&255]}-${v._lut[i>>16&255]}${v._lut[i>>24&255]}${v._lut[255&n]}${v._lut[n>>8&255]}${v._lut[n>>16&255]}${v._lut[n>>24&255]}`.toLowerCase()}static validate(e){if(!v._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.`)}}const x=":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",C=new RegExp("^"+("["+x+"]["+(x+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*")+"$");function S(e,t){const i=[];let n=t.exec(e);for(;n;){const s=[];s.startIndex=t.lastIndex-n[0].length;const r=n.length;for(let e=0;e<r;e++)s.push(n[e]);i.push(s),n=t.exec(e)}return i}const A=function(e){const t=C.exec(e);return!(null==t)};const T=["hasOwnProperty","toString","valueOf","__defineGetter__","__defineSetter__","__lookupGetter__","__lookupSetter__"],P=["__proto__","constructor","prototype"],M={allowBooleanAttributes:!1,unpairedTags:[]};function E(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function I(e,t){const i=t;for(;t<e.length;t++)if("?"==e[t]||" "==e[t]){const n=e.substr(i,t-i);if(t>5&&"xml"===n)return N("InvalidXml","XML declaration allowed only at the start of the document.",U(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}continue}return t}function D(e,t){if(e.length>t+5&&"-"===e[t+1]&&"-"===e[t+2]){for(t+=3;t<e.length;t++)if("-"===e[t]&&"-"===e[t+1]&&">"===e[t+2]){t+=2;break}}else if(e.length>t+8&&"D"===e[t+1]&&"O"===e[t+2]&&"C"===e[t+3]&&"T"===e[t+4]&&"Y"===e[t+5]&&"P"===e[t+6]&&"E"===e[t+7]){let i=1;for(t+=8;t<e.length;t++)if("<"===e[t])i++;else if(">"===e[t]&&(i--,0===i))break}else if(e.length>t+9&&"["===e[t+1]&&"C"===e[t+2]&&"D"===e[t+3]&&"A"===e[t+4]&&"T"===e[t+5]&&"A"===e[t+6]&&"["===e[t+7])for(t+=8;t<e.length;t++)if("]"===e[t]&&"]"===e[t+1]&&">"===e[t+2]){t+=2;break}return t}const z='"',k="'";function B(e,t){let i="",n="",s=!1;for(;t<e.length;t++){if(e[t]===z||e[t]===k)""===n?n=e[t]:n!==e[t]||(n="");else if(">"===e[t]&&""===n){s=!0;break}i+=e[t]}return""===n&&{value:i,index:t,tagClosed:s}}const O=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function V(e,t){const i=S(e,O),n={};for(let e=0;e<i.length;e++){if(0===i[e][1].length)return N("InvalidAttr","Attribute '"+i[e][2]+"' has no space in starting.",j(i[e]));if(void 0!==i[e][3]&&void 0===i[e][4])return N("InvalidAttr","Attribute '"+i[e][2]+"' is without value.",j(i[e]));if(void 0===i[e][3]&&!t.allowBooleanAttributes)return N("InvalidAttr","boolean attribute '"+i[e][2]+"' is not allowed.",j(i[e]));const s=i[e][2];if(!F(s))return N("InvalidAttr","Attribute '"+s+"' is an invalid name.",j(i[e]));if(Object.prototype.hasOwnProperty.call(n,s))return N("InvalidAttr","Attribute '"+s+"' is repeated.",j(i[e]));n[s]=1}return!0}function L(e,t){if(";"===e[++t])return-1;if("#"===e[t])return function(e,t){let i=/\d/;for("x"===e[t]&&(t++,i=/[\da-fA-F]/);t<e.length;t++){if(";"===e[t])return t;if(!e[t].match(i))break}return-1}(e,++t);let i=0;for(;t<e.length;t++,i++)if(!(e[t].match(/\w/)&&i<20)){if(";"===e[t])break;return-1}return t}function N(e,t,i){return{err:{code:e,msg:t,line:i.line||i,col:i.col}}}function F(e){return A(e)}function R(e){return A(e)}function U(e,t){const i=e.substring(0,t).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function j(e){return e.startIndex+e[1].length}const $={cent:"¢",pound:"£",curren:"¤",yen:"¥",euro:"€",dollar:"$",euro:"€",fnof:"ƒ",inr:"₹",af:"؋",birr:"ብር",peso:"₱",rub:"₽",won:"₩",yuan:"¥",cedil:"¸"},W={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},H={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},G=new Set("!?\\\\/[]$%{}^&*()<>|+");function q(e){if("#"===e[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${e}"`);for(const t of e)if(G.has(t))throw new Error(`[EntityReplacer] Invalid character '${t}' in entity name: "${e}"`);return e}function Z(...e){const t=Object.create(null);for(const i of e)if(i)for(const e of Object.keys(i)){const n=i[e];if("string"==typeof n)t[e]=n;else if(n&&"object"==typeof n&&void 0!==n.val){const i=n.val;"string"==typeof i&&(t[e]=i)}}return t}const Y="external",X="base",K="all";const Q=Object.freeze({allow:0,leave:1,remove:2,throw:3}),J=new Set([9,10,13]);class ee{constructor(e={}){var t;this._limit=e.limit||{},this._maxTotalExpansions=this._limit.maxTotalExpansions||0,this._maxExpandedLength=this._limit.maxExpandedLength||0,this._postCheck="function"==typeof e.postCheck?e.postCheck:e=>e,this._limitTiers=(t=this._limit.applyLimitsTo??Y)&&t!==Y?t===K?new Set([K]):t===X?new Set([X]):Array.isArray(t)?new Set(t):new Set([Y]):new Set([Y]),this._numericAllowed=e.numericAllowed??!0,this._baseMap=Z(W,e.namedEntities||null),this._externalMap=Object.create(null),this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this._removeSet=new Set(e.remove&&Array.isArray(e.remove)?e.remove:[]),this._leaveSet=new Set(e.leave&&Array.isArray(e.leave)?e.leave:[]);const i=function(e){if(!e)return{xmlVersion:1,onLevel:Q.allow,nullLevel:Q.remove};const t=1.1===e.xmlVersion?1.1:1,i=Q[e.onNCR]??Q.allow,n=Q[e.nullNCR]??Q.remove;return{xmlVersion:t,onLevel:i,nullLevel:Math.max(n,Q.remove)}}(e.ncr);this._ncrXmlVersion=i.xmlVersion,this._ncrOnLevel=i.onLevel,this._ncrNullLevel=i.nullLevel}setExternalEntities(e){if(e)for(const t of Object.keys(e))q(t);this._externalMap=Z(e)}addExternalEntity(e,t){q(e),"string"==typeof t&&-1===t.indexOf("&")&&(this._externalMap[e]=t)}addInputEntities(e){this._totalExpansions=0,this._expandedLength=0,this._inputMap=Z(e)}reset(){return this._inputMap=Object.create(null),this._totalExpansions=0,this._expandedLength=0,this}setXmlVersion(e){this._ncrXmlVersion=1.1===e?1.1:1}decode(e){if("string"!=typeof e||0===e.length)return e;const t=e,i=[],n=e.length;let s=0,r=0;const o=this._maxTotalExpansions>0,a=this._maxExpandedLength>0,l=o||a;for(;r<n;){if(38!==e.charCodeAt(r)){r++;continue}let t=r+1;for(;t<n&&59!==e.charCodeAt(t)&&t-r<=32;)t++;if(t>=n||59!==e.charCodeAt(t)){r++;continue}const c=e.slice(r+1,t);if(0===c.length){r++;continue}let h,u;if(this._removeSet.has(c))h="",void 0===u&&(u=Y);else{if(this._leaveSet.has(c)){r++;continue}if(35===c.charCodeAt(0)){const e=this._resolveNCR(c);if(void 0===e){r++;continue}h=e,u=X}else{const e=this._resolveName(c);h=e?.value,u=e?.tier}}if(void 0!==h){if(r>s&&i.push(e.slice(s,r)),i.push(h),s=t+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 e=h.length-(c.length+2);if(e>0&&(this._expandedLength+=e,this._expandedLength>this._maxExpandedLength))throw new Error(`[EntityReplacer] Expanded content length limit exceeded: ${this._expandedLength} > ${this._maxExpandedLength}`)}}}else r++}s<n&&i.push(e.slice(s));const c=0===i.length?e:i.join("");return this._postCheck(c,t)}_tierCounts(e){return!!this._limitTiers.has(K)||this._limitTiers.has(e)}_resolveName(e){return e in this._inputMap?{value:this._inputMap[e],tier:Y}:e in this._externalMap?{value:this._externalMap[e],tier:Y}:e in this._baseMap?{value:this._baseMap[e],tier:X}:void 0}_classifyNCR(e){return 0===e?this._ncrNullLevel:e>=55296&&e<=57343||1===this._ncrXmlVersion&&e>=1&&e<=31&&!J.has(e)?Q.remove:-1}_applyNCRAction(e,t,i){switch(e){case Q.allow:return String.fromCodePoint(i);case Q.remove:return"";case Q.leave:return;case Q.throw:throw new Error(`[EntityDecoder] Prohibited numeric character reference &${t}; (U+${i.toString(16).toUpperCase().padStart(4,"0")})`);default:return String.fromCodePoint(i)}}_resolveNCR(e){const t=e.charCodeAt(1);let i;if(i=120===t||88===t?parseInt(e.slice(2),16):parseInt(e.slice(1),10),Number.isNaN(i)||i<0||i>1114111)return;const n=this._classifyNCR(i);if(!this._numericAllowed&&n<Q.remove)return;const s=-1===n?this._ncrOnLevel:Math.max(this._ncrOnLevel,n);return this._applyNCRAction(s,e,i)}}const te=e=>T.includes(e)?"__"+e:e,ie={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(e,t){return t},attributeValueProcessor:function(e,t){return t},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,entityDecoder:null,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,i){return e},captureMetaData:!1,maxNestedTags:100,strictReservedNames:!0,jPath:!0,onDangerousProperty:te};function ne(e,t){if("string"!=typeof e)return;const i=e.toLowerCase();if(T.some(e=>i===e.toLowerCase()))throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`);if(P.some(e=>i===e.toLowerCase()))throw new Error(`[SECURITY] Invalid ${t}: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`)}function se(e,t){return"boolean"==typeof e?{enabled:e,maxEntitySize:1e4,maxExpansionDepth:1e4,maxTotalExpansions:1/0,maxExpandedLength:1e5,maxEntityCount:1e3,allowedTags:null,tagFilter:null,appliesTo:"all"}:"object"==typeof e&&null!==e?{enabled:!1!==e.enabled,maxEntitySize:Math.max(1,e.maxEntitySize??1e4),maxExpansionDepth:Math.max(1,e.maxExpansionDepth??1e4),maxTotalExpansions:Math.max(1,e.maxTotalExpansions??1/0),maxExpandedLength:Math.max(1,e.maxExpandedLength??1e5),maxEntityCount:Math.max(1,e.maxEntityCount??1e3),allowedTags:e.allowedTags??null,tagFilter:e.tagFilter??null,appliesTo:e.appliesTo??"all"}:se(!0)}const re=function(e){const t=Object.assign({},ie,e),i=[{value:t.attributeNamePrefix,name:"attributeNamePrefix"},{value:t.attributesGroupName,name:"attributesGroupName"},{value:t.textNodeName,name:"textNodeName"},{value:t.cdataPropName,name:"cdataPropName"},{value:t.commentPropName,name:"commentPropName"}];for(const{value:e,name:t}of i)e&&ne(e,t);return null===t.onDangerousProperty&&(t.onDangerousProperty=te),t.processEntities=se(t.processEntities,t.htmlEntities),t.unpairedTagsSet=new Set(t.unpairedTags),t.stopNodes&&Array.isArray(t.stopNodes)&&(t.stopNodes=t.stopNodes.map(e=>"string"==typeof e&&e.startsWith("*.")?".."+e.substring(2):e)),t};let oe;oe="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class ae{constructor(e){this.tagname=e,this.child=[],this[":@"]=Object.create(null)}add(e,t){"__proto__"===e&&(e="#__proto__"),this.child.push({[e]:t})}addChild(e,t){"__proto__"===e.tagname&&(e.tagname="#__proto__"),e[":@"]&&Object.keys(e[":@"]).length>0?this.child.push({[e.tagname]:e.child,":@":e[":@"]}):this.child.push({[e.tagname]:e.child}),void 0!==t&&(this.child[this.child.length-1][oe]={startIndex:t})}static getMetaDataSymbol(){return oe}}class le{constructor(e){this.suppressValidationErr=!e,this.options=e}readDocType(e,t){const i=Object.create(null);let n=0;if("O"!==e[t+3]||"C"!==e[t+4]||"T"!==e[t+5]||"Y"!==e[t+6]||"P"!==e[t+7]||"E"!==e[t+8])throw new Error("Invalid Tag instead of DOCTYPE");{t+=9;let s=1,r=!1,o=!1,a="";for(;t<e.length;t++)if("<"!==e[t]||o)if(">"===e[t]){if(o?"-"===e[t-1]&&"-"===e[t-2]&&(o=!1,s--):s--,0===s)break}else"["===e[t]?r=!0:a+=e[t];else{if(r&&he(e,"!ENTITY",t)){let s,r;if(t+=7,[s,r,t]=this.readEntityExp(e,t+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&&he(e,"!ELEMENT",t)){t+=8;const{index:i}=this.readElementExp(e,t+1);t=i}else if(r&&he(e,"!ATTLIST",t))t+=8;else if(r&&he(e,"!NOTATION",t)){t+=9;const{index:i}=this.readNotationExp(e,t+1,this.suppressValidationErr);t=i}else{if(!he(e,"!--",t))throw new Error("Invalid DOCTYPE");o=!0}s++,a=""}if(0!==s)throw new Error("Unclosed DOCTYPE")}return{entities:i,i:t}}readEntityExp(e,t){const i=t=ce(e,t);for(;t<e.length&&!/\s/.test(e[t])&&'"'!==e[t]&&"'"!==e[t];)t++;let n=e.substring(i,t);if(ue(n),t=ce(e,t),!this.suppressValidationErr){if("SYSTEM"===e.substring(t,t+6).toUpperCase())throw new Error("External entities are not supported");if("%"===e[t])throw new Error("Parameter entities are not supported")}let s="";if([t,s]=this.readIdentifierVal(e,t,"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,--t]}readNotationExp(e,t){const i=t=ce(e,t);for(;t<e.length&&!/\s/.test(e[t]);)t++;let n=e.substring(i,t);!this.suppressValidationErr&&ue(n),t=ce(e,t);const s=e.substring(t,t+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==s&&"PUBLIC"!==s)throw new Error(`Expected SYSTEM or PUBLIC, found "${s}"`);t+=s.length,t=ce(e,t);let r=null,o=null;if("PUBLIC"===s)[t,r]=this.readIdentifierVal(e,t,"publicIdentifier"),'"'!==e[t=ce(e,t)]&&"'"!==e[t]||([t,o]=this.readIdentifierVal(e,t,"systemIdentifier"));else if("SYSTEM"===s&&([t,o]=this.readIdentifierVal(e,t,"systemIdentifier"),!this.suppressValidationErr&&!o))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:n,publicIdentifier:r,systemIdentifier:o,index:--t}}readIdentifierVal(e,t,i){let n="";const s=e[t];if('"'!==s&&"'"!==s)throw new Error(`Expected quoted string, found "${s}"`);const r=++t;for(;t<e.length&&e[t]!==s;)t++;if(n=e.substring(r,t),e[t]!==s)throw new Error(`Unterminated ${i} value`);return[++t,n]}readElementExp(e,t){const i=t=ce(e,t);for(;t<e.length&&!/\s/.test(e[t]);)t++;let n=e.substring(i,t);if(!this.suppressValidationErr&&!A(n))throw new Error(`Invalid element name: "${n}"`);let s="";if("E"===e[t=ce(e,t)]&&he(e,"MPTY",t))t+=4;else if("A"===e[t]&&he(e,"NY",t))t+=2;else if("("===e[t]){const i=++t;for(;t<e.length&&")"!==e[t];)t++;if(s=e.substring(i,t),")"!==e[t])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${e[t]}"`);return{elementName:n,contentModel:s.trim(),index:t}}readAttlistExp(e,t){let i=t=ce(e,t);for(;t<e.length&&!/\s/.test(e[t]);)t++;let n=e.substring(i,t);for(ue(n),i=t=ce(e,t);t<e.length&&!/\s/.test(e[t]);)t++;let s=e.substring(i,t);if(!ue(s))throw new Error(`Invalid attribute name: "${s}"`);t=ce(e,t);let r="";if("NOTATION"===e.substring(t,t+8).toUpperCase()){if(r="NOTATION","("!==e[t=ce(e,t+=8)])throw new Error(`Expected '(', found "${e[t]}"`);t++;let i=[];for(;t<e.length&&")"!==e[t];){const n=t;for(;t<e.length&&"|"!==e[t]&&")"!==e[t];)t++;let s=e.substring(n,t);if(s=s.trim(),!ue(s))throw new Error(`Invalid notation name: "${s}"`);i.push(s),"|"===e[t]&&(t++,t=ce(e,t))}if(")"!==e[t])throw new Error("Unterminated list of notations");t++,r+=" ("+i.join("|")+")"}else{const i=t;for(;t<e.length&&!/\s/.test(e[t]);)t++;r+=e.substring(i,t);const n=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!n.includes(r.toUpperCase()))throw new Error(`Invalid attribute type: "${r}"`)}t=ce(e,t);let o="";return"#REQUIRED"===e.substring(t,t+8).toUpperCase()?(o="#REQUIRED",t+=8):"#IMPLIED"===e.substring(t,t+7).toUpperCase()?(o="#IMPLIED",t+=7):[t,o]=this.readIdentifierVal(e,t,"ATTLIST"),{elementName:n,attributeName:s,attributeType:r,defaultValue:o,index:t}}}const ce=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function he(e,t,i){for(let n=0;n<t.length;n++)if(t[n]!==e[i+n+1])return!1;return!0}function ue(e){if(A(e))return e;throw new Error(`Invalid entity name ${e}`)}const de=/^[-+]?0x[a-fA-F0-9]+$/,pe=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,fe={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original"};function me(e,t={}){if(t=Object.assign({},fe,t),!e||"string"!=typeof e)return e;let i=e.trim();if(0===i.length)return e;if(void 0!==t.skipLike&&t.skipLike.test(i))return e;if("0"===i)return 0;if(t.hex&&de.test(i))return function(e,t){if(parseInt)return parseInt(e,t);if(Number.parseInt)return Number.parseInt(e,t);if(window&&window.parseInt)return window.parseInt(e,t);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(e,t,i){if(!i.eNotation)return e;const n=t.match(ge);if(n){let s=n[1]||"";const r=-1===n[3].indexOf("e")?"E":"e",o=n[2],a=s?e[o.length+1]===r:e[o.length]===r;return o.length>1&&a?e:(1!==o.length||!n[3].startsWith(`.${r}`)&&n[3][0]!==r)&&o.length>0?i.leadingZeros&&!a?(t=(n[1]||"")+n[3],Number(t)):e:Number(t)}return e}(e,i,t);{const n=pe.exec(i);if(n){const s=n[1]||"",r=n[2];let o=function(e){if(e&&-1!==e.indexOf("."))return"."===(e=e.replace(/0+$/,""))?e="0":"."===e[0]?e="0"+e:"."===e[e.length-1]&&(e=e.substring(0,e.length-1)),e;return e}(n[3]);const a=s?"."===e[r.length+1]:"."===e[r.length];if(!t.leadingZeros&&(r.length>1||1===r.length&&!a))return e;{const n=Number(i),a=String(n);if(0===n)return n;if(-1!==a.search(/[eE]/))return t.eNotation?n:e;if(-1!==i.indexOf("."))return"0"===a||a===o||a===`${s}${o}`?n:e;let l=r?o:i;return r?l===a||s+l===a?n:e:l===a||l===s+a?n:e}}return e}}return function(e,t,i){const n=t===1/0;switch(i.infinity.toLowerCase()){case"null":return null;case"infinity":return t;case"string":return n?"Infinity":"-Infinity";default:return e}}(e,Number(i),t)}const ge=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;class we{constructor(e,t={},i){this.pattern=e,this.separator=t.separator||".",this.segments=this._parse(e),this.data=i,this._hasDeepWildcard=this.segments.some(e=>"deep-wildcard"===e.type),this._hasAttributeCondition=this.segments.some(e=>void 0!==e.attrName),this._hasPositionSelector=this.segments.some(e=>void 0!==e.position)}_parse(e){const t=[];let i=0,n="";for(;i<e.length;)e[i]===this.separator?i+1<e.length&&e[i+1]===this.separator?(n.trim()&&(t.push(this._parseSegment(n.trim())),n=""),t.push({type:"deep-wildcard"}),i+=2):(n.trim()&&t.push(this._parseSegment(n.trim())),n="",i++):(n+=e[i],i++);return n.trim()&&t.push(this._parseSegment(n.trim())),t}_parseSegment(e){const t={type:"tag"};let i=null,n=e;const s=e.match(/^([^\[]+)(\[[^\]]*\])(.*)$/);if(s&&(n=s[1]+s[3],s[2])){const e=s[2].slice(1,-1);e&&(i=e)}let r,o,a=n;if(n.includes("::")){const t=n.indexOf("::");if(r=n.substring(0,t).trim(),a=n.substring(t+2).trim(),!r)throw new Error(`Invalid namespace in pattern: ${e}`)}let l=null;if(a.includes(":")){const e=a.lastIndexOf(":"),t=a.substring(0,e).trim(),i=a.substring(e+1).trim();["first","last","odd","even"].includes(i)||/^nth\(\d+\)$/.test(i)?(o=t,l=i):o=a}else o=a;if(!o)throw new Error(`Invalid segment pattern: ${e}`);if(t.tag=o,r&&(t.namespace=r),i)if(i.includes("=")){const e=i.indexOf("=");t.attrName=i.substring(0,e).trim(),t.attrValue=i.substring(e+1).trim()}else t.attrName=i.trim();if(l){const e=l.match(/^nth\((\d+)\)$/);e?(t.position="nth",t.positionValue=parseInt(e[1],10)):t.position=l}return t}get length(){return this.segments.length}hasDeepWildcard(){return this._hasDeepWildcard}hasAttributeCondition(){return this._hasAttributeCondition}hasPositionSelector(){return this._hasPositionSelector}toString(){return this.pattern}}class ye{constructor(){this._byDepthAndTag=new Map,this._wildcardByDepth=new Map,this._deepWildcards=[],this._patterns=new Set,this._sealed=!1}add(e){if(this._sealed)throw new TypeError("ExpressionSet is sealed. Create a new ExpressionSet to add more expressions.");if(this._patterns.has(e.pattern))return this;if(this._patterns.add(e.pattern),e.hasDeepWildcard())return this._deepWildcards.push(e),this;const t=e.length,i=e.segments[e.segments.length-1],n=i?.tag;if(n&&"*"!==n){const i=`${t}:${n}`;this._byDepthAndTag.has(i)||this._byDepthAndTag.set(i,[]),this._byDepthAndTag.get(i).push(e)}else this._wildcardByDepth.has(t)||this._wildcardByDepth.set(t,[]),this._wildcardByDepth.get(t).push(e);return this}addAll(e){for(const t of e)this.add(t);return this}has(e){return this._patterns.has(e.pattern)}get size(){return this._patterns.size}seal(){return this._sealed=!0,this}get isSealed(){return this._sealed}matchesAny(e){return null!==this.findMatch(e)}findMatch(e){const t=e.getDepth(),i=`${t}:${e.getCurrentTag()}`,n=this._byDepthAndTag.get(i);if(n)for(let t=0;t<n.length;t++)if(e.matches(n[t]))return n[t];const s=this._wildcardByDepth.get(t);if(s)for(let t=0;t<s.length;t++)if(e.matches(s[t]))return s[t];for(let t=0;t<this._deepWildcards.length;t++)if(e.matches(this._deepWildcards[t]))return this._deepWildcards[t];return null}}class _e{constructor(e){this._matcher=e}get separator(){return this._matcher.separator}getCurrentTag(){const e=this._matcher.path;return e.length>0?e[e.length-1].tag:void 0}getCurrentNamespace(){const e=this._matcher.path;return e.length>0?e[e.length-1].namespace:void 0}getAttrValue(e){const t=this._matcher.path;if(0!==t.length)return t[t.length-1].values?.[e]}hasAttr(e){const t=this._matcher.path;if(0===t.length)return!1;const i=t[t.length-1];return void 0!==i.values&&e in i.values}getPosition(){const e=this._matcher.path;return 0===e.length?-1:e[e.length-1].position??0}getCounter(){const e=this._matcher.path;return 0===e.length?-1:e[e.length-1].counter??0}getIndex(){return this.getPosition()}getDepth(){return this._matcher.path.length}toString(e,t=!0){return this._matcher.toString(e,t)}toArray(){return this._matcher.path.map(e=>e.tag)}matches(e){return this._matcher.matches(e)}matchesAny(e){return e.matchesAny(this._matcher)}}class be{constructor(e={}){this.separator=e.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new _e(this)}push(e,t=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}:${e}`:e,o=s.get(r)||0;let a=0;for(const e of s.values())a+=e;s.set(r,o+1);const l={tag:e,position:a,counter:o};null!=i&&(l.namespace=i),null!=t&&(l.values=t),this.path.push(l)}pop(){if(0===this.path.length)return;this._pathStringCache=null;const e=this.path.pop();return this.siblingStacks.length>this.path.length+1&&(this.siblingStacks.length=this.path.length+1),e}updateCurrent(e){if(this.path.length>0){const t=this.path[this.path.length-1];null!=e&&(t.values=e)}}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(e){if(0!==this.path.length)return this.path[this.path.length-1].values?.[e]}hasAttr(e){if(0===this.path.length)return!1;const t=this.path[this.path.length-1];return void 0!==t.values&&e in t.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(e,t=!0){const i=e||this.separator;if(i===this.separator&&!0===t){if(null!==this._pathStringCache)return this._pathStringCache;const e=this.path.map(e=>e.namespace?`${e.namespace}:${e.tag}`:e.tag).join(i);return this._pathStringCache=e,e}return this.path.map(e=>t&&e.namespace?`${e.namespace}:${e.tag}`:e.tag).join(i)}toArray(){return this.path.map(e=>e.tag)}reset(){this._pathStringCache=null,this.path=[],this.siblingStacks=[]}matches(e){const t=e.segments;return 0!==t.length&&(e.hasDeepWildcard()?this._matchWithDeepWildcard(t):this._matchSimple(t))}_matchSimple(e){if(this.path.length!==e.length)return!1;for(let t=0;t<e.length;t++)if(!this._matchSegment(e[t],this.path[t],t===this.path.length-1))return!1;return!0}_matchWithDeepWildcard(e){let t=this.path.length-1,i=e.length-1;for(;i>=0&&t>=0;){const n=e[i];if("deep-wildcard"===n.type){if(i--,i<0)return!0;const n=e[i];let s=!1;for(let e=t;e>=0;e--)if(this._matchSegment(n,this.path[e],e===this.path.length-1)){t=e-1,i--,s=!0;break}if(!s)return!1}else{if(!this._matchSegment(n,this.path[t],t===this.path.length-1))return!1;t--,i--}}return i<0}_matchSegment(e,t,i){if("*"!==e.tag&&e.tag!==t.tag)return!1;if(void 0!==e.namespace&&"*"!==e.namespace&&e.namespace!==t.namespace)return!1;if(void 0!==e.attrName){if(!i)return!1;if(!t.values||!(e.attrName in t.values))return!1;if(void 0!==e.attrValue&&String(t.values[e.attrName])!==String(e.attrValue))return!1}if(void 0!==e.position){if(!i)return!1;const n=t.counter??0;if("first"===e.position&&0!==n)return!1;if("odd"===e.position&&n%2!=1)return!1;if("even"===e.position&&n%2!=0)return!1;if("nth"===e.position&&n!==e.positionValue)return!1}return!0}matchesAny(e){return e.matchesAny(this)}snapshot(){return{path:this.path.map(e=>({...e})),siblingStacks:this.siblingStacks.map(e=>new Map(e))}}restore(e){this._pathStringCache=null,this.path=e.path.map(e=>({...e})),this.siblingStacks=e.siblingStacks.map(e=>new Map(e))}readOnly(){return this._view}}function ve(e,t){if(!e)return{};const i=t.attributesGroupName?e[t.attributesGroupName]:e;if(!i)return{};const n={};for(const e in i)if(e.startsWith(t.attributeNamePrefix)){n[e.substring(t.attributeNamePrefix.length)]=i[e]}else n[e]=i[e];return n}function xe(e){if(!e||"string"!=typeof e)return;const t=e.indexOf(":");if(-1!==t&&t>0){const i=e.substring(0,t);if("xmlns"!==i)return i}}class Ce{constructor(e,t){var i;this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=Me,this.parseTextData=Se,this.resolveNameSpace=Ae,this.buildAttributesMap=Pe,this.isItStopNode=ze,this.replaceEntitiesValue=Ie,this.readStopNodeData=Ve,this.saveTextToParentTag=De,this.addChild=Ee,this.ignoreAttributesFn="function"==typeof(i=this.options.ignoreAttributes)?i:Array.isArray(i)?e=>{for(const t of i){if("string"==typeof t&&e===t)return!0;if(t instanceof RegExp&&t.test(e))return!0}}:()=>!1,this.entityExpansionCount=0,this.currentExpandedLength=0;let n={...W};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?n=this.options.htmlEntities:!0===this.options.htmlEntities&&(n={...H,...$}),this.entityDecoder=new ee({namedEntities:{...n,...t},numericAllowed:this.options.htmlEntities,limit:{maxTotalExpansions:this.options.processEntities.maxTotalExpansions,maxExpandedLength:this.options.processEntities.maxExpandedLength,applyLimitsTo:this.options.processEntities.appliesTo}})),this.matcher=new be,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new ye;const s=this.options.stopNodes;if(s&&s.length>0){for(let e=0;e<s.length;e++){const t=s[e];"string"==typeof t?this.stopNodeExpressionsSet.add(new we(t)):t instanceof we&&this.stopNodeExpressionsSet.add(t)}this.stopNodeExpressionsSet.seal()}}}function Se(e,t,i,n,s,r,o){const a=this.options;if(void 0!==e&&(a.trimValues&&!n&&(e=e.trim()),e.length>0)){o||(e=this.replaceEntitiesValue(e,t,i));const n=a.jPath?i.toString():i,l=a.tagValueProcessor(t,e,n,s,r);if(null==l)return e;if(typeof l!=typeof e||l!==e)return l;if(a.trimValues)return Le(e,a.parseTagValue,a.numberParseOptions);return e.trim()===e?Le(e,a.parseTagValue,a.numberParseOptions):e}}function Ae(e){if(this.options.removeNSPrefix){const t=e.split(":"),i="/"===e.charAt(0)?"/":"";if("xmlns"===t[0])return"";2===t.length&&(e=i+t[1])}return e}const Te=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function Pe(e,t,i,n=!1){const s=this.options;if(!0===n||!0!==s.ignoreAttributes&&"string"==typeof e){const n=S(e,Te),r=n.length,o={},a=new Array(r);let l=!1;const c={};for(let e=0;e<r;e++){const t=this.resolveNameSpace(n[e][1]),r=n[e][4];if(t.length&&void 0!==r){let n=r;s.trimValues&&(n=n.trim()),n=this.replaceEntitiesValue(n,i,this.readonlyMatcher),a[e]=n,c[t]=n,l=!0}}l&&"object"==typeof t&&t.updateCurrent&&t.updateCurrent(c);const h=s.jPath?t.toString():this.readonlyMatcher;let u=!1;for(let e=0;e<r;e++){const t=this.resolveNameSpace(n[e][1]);if(this.ignoreAttributesFn(t,h))continue;let i=s.attributeNamePrefix+t;if(t.length)if(s.transformAttributeName&&(i=s.transformAttributeName(i)),i=Fe(i,s),void 0!==n[e][4]){const n=a[e],r=s.attributeValueProcessor(t,n,h);o[i]=null==r?n:typeof r!=typeof n||r!==n?r:Le(n,s.parseAttributeValue,s.numberParseOptions),u=!0}else s.allowBooleanAttributes&&(o[i]=!0,u=!0)}if(!u)return;if(s.attributesGroupName&&!s.preserveOrder){const e={};return e[s.attributesGroupName]=o,e}return o}}const Me=function(e){e=e.replace(/\r\n?/g,"\n");const t=new ae("!xml");let i=t,n="";this.matcher.reset(),this.entityDecoder.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;const s=this.options,r=new le(s.processEntities),o=e.length;for(let a=0;a<o;a++){if("<"===e[a]){const l=e.charCodeAt(a+1);if(47===l){const t=ke(e,">",a,"Closing Tag is not closed.");let r=e.substring(a+2,t).trim();if(s.removeNSPrefix){const e=r.indexOf(":");-1!==e&&(r=r.substr(e+1))}r=Ne(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=t}else if(63===l){let t=Oe(e,a,!1,"?>");if(!t)throw new Error("Pi Tag is not closed.");n=this.saveTextToParentTag(n,i,this.readonlyMatcher);const r=this.buildAttributesMap(t.tagExp,this.matcher,t.tagName,!0);if(r){const e=r[this.options.attributeNamePrefix+"version"];this.entityDecoder.setXmlVersion(Number(e)||1)}if(s.ignoreDeclaration&&"?xml"===t.tagName||s.ignorePiTags);else{const e=new ae(t.tagName);e.add(s.textNodeName,""),t.tagName!==t.tagExp&&t.attrExpPresent&&!0!==s.ignoreAttributes&&(e[":@"]=r),this.addChild(i,e,this.readonlyMatcher,a)}a=t.closeIndex+1}else if(33===l&&45===e.charCodeAt(a+2)&&45===e.charCodeAt(a+3)){const t=ke(e,"--\x3e",a+4,"Comment is not closed.");if(s.commentPropName){const r=e.substring(a+4,t-2);n=this.saveTextToParentTag(n,i,this.readonlyMatcher),i.add(s.commentPropName,[{[s.textNodeName]:r}])}a=t}else if(33===l&&68===e.charCodeAt(a+2)){const t=r.readDocType(e,a);this.entityDecoder.addInputEntities(t.entities),a=t.i}else if(33===l&&91===e.charCodeAt(a+2)){const t=ke(e,"]]>",a,"CDATA is not closed.")-2,r=e.substring(a+9,t);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=t+2}else{let r=Oe(e,a,s.removeNSPrefix);if(!r){const t=e.substring(Math.max(0,a-50),Math.min(o,a+50));throw new Error(`readTagExp returned undefined at position ${a}. Context: "${t}"`)}let l=r.tagName;const c=r.rawTagName;let h=r.tagExp,u=r.attrExpPresent,d=r.closeIndex;if(({tagName:l,tagExp:h}=Ne(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=xe(c),l!==t.tagname&&this.matcher.push(l,{},m),l!==h&&u&&(g=this.buildAttributesMap(h,this.matcher,l),g&&ve(g,s)),l!==t.tagname&&(this.isCurrentNodeStopNode=this.isItStopNode());const w=a;if(this.isCurrentNodeStopNode){let t="";if(f)a=r.closeIndex;else if(s.unpairedTagsSet.has(l))a=r.closeIndex;else{const i=this.readStopNodeData(e,c,d+1);if(!i)throw new Error(`Unexpected end of ${c}`);a=i.i,t=i.tagContent}const n=new ae(l);g&&(n[":@"]=g),n.add(s.textNodeName,t),this.matcher.pop(),this.isCurrentNodeStopNode=!1,this.addChild(i,n,this.readonlyMatcher,w)}else{if(f){({tagName:l,tagExp:h}=Ne(s.transformTagName,l,h,s));const e=new ae(l);g&&(e[":@"]=g),this.addChild(i,e,this.readonlyMatcher,w),this.matcher.pop(),this.isCurrentNodeStopNode=!1}else{if(s.unpairedTagsSet.has(l)){const e=new ae(l);g&&(e[":@"]=g),this.addChild(i,e,this.readonlyMatcher,w),this.matcher.pop(),this.isCurrentNodeStopNode=!1,a=r.closeIndex;continue}{const e=new ae(l);if(this.tagsNodeStack.length>s.maxNestedTags)throw new Error("Maximum nested tags exceeded");this.tagsNodeStack.push(i),g&&(e[":@"]=g),this.addChild(i,e,this.readonlyMatcher,w),i=e}}n="",a=d}}}else n+=e[a]}return t.child};function Ee(e,t,i,n){this.options.captureMetaData||(n=void 0);const s=this.options.jPath?i.toString():i,r=this.options.updateTag(t.tagname,s,t[":@"]);!1===r||("string"==typeof r?(t.tagname=r,e.addChild(t,n)):e.addChild(t,n))}function Ie(e,t,i){const n=this.options.processEntities;if(!n||!n.enabled)return e;if(n.allowedTags){const s=this.options.jPath?i.toString():i;if(!(Array.isArray(n.allowedTags)?n.allowedTags.includes(t):n.allowedTags(t,s)))return e}if(n.tagFilter){const s=this.options.jPath?i.toString():i;if(!n.tagFilter(t,s))return e}return this.entityDecoder.decode(e)}function De(e,t,i,n){return e&&(void 0===n&&(n=0===t.child.length),void 0!==(e=this.parseTextData(e,t.tagname,i,!1,!!t[":@"]&&0!==Object.keys(t[":@"]).length,n))&&""!==e&&t.add(this.options.textNodeName,e),e=""),e}function ze(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function ke(e,t,i,n){const s=e.indexOf(t,i);if(-1===s)throw new Error(n);return s+t.length-1}function Be(e,t,i,n){const s=e.indexOf(t,i);if(-1===s)throw new Error(n);return s}function Oe(e,t,i,n=">"){const s=function(e,t,i=">"){let n=0;const s=e.length,r=i.charCodeAt(0),o=i.length>1?i.charCodeAt(1):-1;let a="",l=t;for(let i=t;i<s;i++){const t=e.charCodeAt(i);if(n)t===n&&(n=0);else if(34===t||39===t)n=t;else if(t===r){if(-1===o)return a+=e.substring(l,i),{data:a,index:i};if(e.charCodeAt(i+1)===o)return a+=e.substring(l,i),{data:a,index:i}}else 9!==t||n||(a+=e.substring(l,i)+" ",l=i+1)}}(e,t+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 e=l.indexOf(":");-1!==e&&(l=l.substr(e+1),c=l!==s.data.substr(e+1))}return{tagName:l,tagExp:r,closeIndex:o,attrExpPresent:c,rawTagName:h}}function Ve(e,t,i){const n=i;let s=1;const r=e.length;for(;i<r;i++)if("<"===e[i]){const r=e.charCodeAt(i+1);if(47===r){const r=Be(e,">",i,`${t} is not closed`);if(e.substring(i+2,r).trim()===t&&(s--,0===s))return{tagContent:e.substring(n,i),i:r};i=r}else if(63===r){i=ke(e,"?>",i+1,"StopNode is not closed.")}else if(33===r&&45===e.charCodeAt(i+2)&&45===e.charCodeAt(i+3)){i=ke(e,"--\x3e",i+3,"StopNode is not closed.")}else if(33===r&&91===e.charCodeAt(i+2)){i=ke(e,"]]>",i,"StopNode is not closed.")-2}else{const n=Oe(e,i,">");if(n){(n&&n.tagName)===t&&"/"!==n.tagExp[n.tagExp.length-1]&&s++,i=n.closeIndex}}}}function Le(e,t,i){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&me(e,i)}return void 0!==e?e:""}function Ne(e,t,i,n){if(e){const n=e(t);i===t&&(i=n),t=n}return{tagName:t=Fe(t,n),tagExp:i}}function Fe(e,t){if(P.includes(e))throw new Error(`[SECURITY] Invalid name: "${e}" is a reserved JavaScript keyword that could cause prototype pollution`);return T.includes(e)?t.onDangerousProperty(e):e}const Re=ae.getMetaDataSymbol();function Ue(e,t){if(!e||"object"!=typeof e)return{};if(!t)return e;const i={};for(const n in e)if(n.startsWith(t)){i[n.substring(t.length)]=e[n]}else i[n]=e[n];return i}function je(e,t,i,n){return $e(e,t,i,n)}function $e(e,t,i,n){let s;const r={};for(let o=0;o<e.length;o++){const a=e[o],l=We(a);if(void 0!==l&&l!==t.textNodeName){const e=Ue(a[":@"]||{},t.attributeNamePrefix);i.push(l,e)}if(l===t.textNodeName)void 0===s?s=a[l]:s+=""+a[l];else{if(void 0===l)continue;if(a[l]){let e=$e(a[l],t,i,n);const s=Ge(e,t);if(a[":@"]?He(e,a[":@"],n,t):1!==Object.keys(e).length||void 0===e[t.textNodeName]||t.alwaysCreateTextNode?0===Object.keys(e).length&&(t.alwaysCreateTextNode?e[t.textNodeName]="":e=""):e=e[t.textNodeName],void 0!==a[Re]&&"object"==typeof e&&null!==e&&(e[Re]=a[Re]),void 0!==r[l]&&Object.prototype.hasOwnProperty.call(r,l))Array.isArray(r[l])||(r[l]=[r[l]]),r[l].push(e);else{const i=t.jPath?n.toString():n;t.isArray(l,i,s)?r[l]=[e]:r[l]=e}void 0!==l&&l!==t.textNodeName&&i.pop()}}}return"string"==typeof s?s.length>0&&(r[t.textNodeName]=s):void 0!==s&&(r[t.textNodeName]=s),r}function We(e){const t=Object.keys(e);for(let e=0;e<t.length;e++){const i=t[e];if(":@"!==i)return i}}function He(e,t,i,n){if(t){const s=Object.keys(t),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)?e[r]=[t[r]]:e[r]=t[r]}}}function Ge(e,t){const{textNodeName:i}=t,n=Object.keys(e).length;return 0===n||!(1!==n||!e[i]&&"boolean"!=typeof e[i]&&0!==e[i])}class qe{constructor(e){this.externalEntities={},this.options=re(e)}parse(e,t){if("string"!=typeof e&&e.toString)e=e.toString();else if("string"!=typeof e)throw new Error("XML data is accepted in String or Bytes[] form.");if(t){!0===t&&(t={});const i=function(e,t){t=Object.assign({},M,t);const i=[];let n=!1,s=!1;"\ufeff"===e[0]&&(e=e.substr(1));for(let r=0;r<e.length;r++)if("<"===e[r]&&"?"===e[r+1]){if(r+=2,r=I(e,r),r.err)return r}else{if("<"!==e[r]){if(E(e[r]))continue;return N("InvalidChar","char '"+e[r]+"' is not expected.",U(e,r))}{let o=r;if(r++,"!"===e[r]){r=D(e,r);continue}{let a=!1;"/"===e[r]&&(a=!0,r++);let l="";for(;r<e.length&&">"!==e[r]&&" "!==e[r]&&"\t"!==e[r]&&"\n"!==e[r]&&"\r"!==e[r];r++)l+=e[r];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),r--),!R(l)){let t;return t=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",N("InvalidTag",t,U(e,r))}const c=B(e,r);if(!1===c)return N("InvalidAttr","Attributes for '"+l+"' have open quote.",U(e,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=V(h,t);if(!0!==s)return N(s.err.code,s.err.msg,U(e,i+s.err.line));n=!0}else if(a){if(!c.tagClosed)return N("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",U(e,r));if(h.trim().length>0)return N("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",U(e,o));if(0===i.length)return N("InvalidTag","Closing tag '"+l+"' has not been opened.",U(e,o));{const t=i.pop();if(l!==t.tagName){let i=U(e,t.tagStartPos);return N("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",U(e,o))}0==i.length&&(s=!0)}}else{const a=V(h,t);if(!0!==a)return N(a.err.code,a.err.msg,U(e,r-h.length+a.err.line));if(!0===s)return N("InvalidXml","Multiple possible root nodes found.",U(e,r));-1!==t.unpairedTags.indexOf(l)||i.push({tagName:l,tagStartPos:o}),n=!0}for(r++;r<e.length;r++)if("<"===e[r]){if("!"===e[r+1]){r++,r=D(e,r);continue}if("?"!==e[r+1])break;if(r=I(e,++r),r.err)return r}else if("&"===e[r]){const t=L(e,r);if(-1==t)return N("InvalidChar","char '&' is not expected.",U(e,r));r=t}else if(!0===s&&!E(e[r]))return N("InvalidXml","Extra text at the end",U(e,r));"<"===e[r]&&r--}}}return n?1==i.length?N("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",U(e,i[0].tagStartPos)):!(i.length>0)||N("InvalidXml","Invalid '"+JSON.stringify(i.map(e=>e.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):N("InvalidXml","Start tag expected.",1)}(e,t);if(!0!==i)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const i=new Ce(this.options,this.externalEntities),n=i.parseXml(e);return this.options.preserveOrder||void 0===n?n:je(n,this.options,i.matcher,i.readonlyMatcher)}addEntity(e,t){if(-1!==t.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==e.indexOf("&")||-1!==e.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if("&"===t)throw new Error("An entity with value '&' is not permitted");this.externalEntities[e]=t}static getMetaDataSymbol(){return ae.getMetaDataSymbol()}}function Ze(e,t){let i="";t.format&&t.indentBy.length>0&&(i="\n");const n=[];if(t.stopNodes&&Array.isArray(t.stopNodes))for(let e=0;e<t.stopNodes.length;e++){const i=t.stopNodes[e];"string"==typeof i?n.push(new we(i)):i instanceof we&&n.push(i)}return Ye(e,t,i,new be,n)}function Ye(e,t,i,n,s){let r="",o=!1;if(t.maxNestedTags&&n.getDepth()>t.maxNestedTags)throw new Error("Maximum nested tags exceeded");if(!Array.isArray(e)){if(null!=e){let i=e.toString();return i=it(i,t),i}return""}for(let a=0;a<e.length;a++){const l=e[a],c=Je(l);if(void 0===c)continue;const h=Xe(l[":@"],t);n.push(c,h);const u=tt(n,s);if(c===t.textNodeName){let e=l[c];u||(e=t.tagValueProcessor(c,e),e=it(e,t)),o&&(r+=i),r+=e,o=!1,n.pop();continue}if(c===t.cdataPropName){o&&(r+=i);const e=l[c][0][t.textNodeName];r+=`<![CDATA[${String(e).replace(/\]\]>/g,"]]]]><![CDATA[>")}]]>`,o=!1,n.pop();continue}if(c===t.commentPropName){const e=l[c][0][t.textNodeName];r+=i+`\x3c!--${String(e).replace(/--/g,"- -").replace(/-$/,"- ")}--\x3e`,o=!0,n.pop();continue}if("?"===c[0]){const e=et(l[":@"],t,u),s="?xml"===c?"":i;let a=l[c][0][t.textNodeName];a=0!==a.length?" "+a:"",r+=s+`<${c}${a}${e}?>`,o=!0,n.pop();continue}let d=i;""!==d&&(d+=t.indentBy);const p=i+`<${c}${et(l[":@"],t,u)}`;let f;f=u?Ke(l[c],t):Ye(l[c],t,d,n,s),-1!==t.unpairedTags.indexOf(c)?t.suppressUnpairedNode?r+=p+">":r+=p+"/>":f&&0!==f.length||!t.suppressEmptyNode?f&&f.endsWith(">")?r+=p+`>${f}${i}</${c}>`:(r+=p+">",f&&""!==i&&(f.includes("/>")||f.includes("</"))?r+=i+t.indentBy+f+i:r+=f,r+=`</${c}>`):r+=p+"/>",o=!0,n.pop()}return r}function Xe(e,t){if(!e||t.ignoreAttributes)return null;const i={};let n=!1;for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;i[s.startsWith(t.attributeNamePrefix)?s.substr(t.attributeNamePrefix.length):s]=e[s],n=!0}return n?i:null}function Ke(e,t){if(!Array.isArray(e))return null!=e?e.toString():"";let i="";for(let n=0;n<e.length;n++){const s=e[n],r=Je(s);if(r===t.textNodeName)i+=s[r];else if(r===t.cdataPropName)i+=s[r][0][t.textNodeName];else if(r===t.commentPropName)i+=s[r][0][t.textNodeName];else{if(r&&"?"===r[0])continue;if(r){const e=Qe(s[":@"],t),n=Ke(s[r],t);n&&0!==n.length?i+=`<${r}${e}>${n}</${r}>`:i+=`<${r}${e}/>`}}}return i}function Qe(e,t){let i="";if(e&&!t.ignoreAttributes)for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;let s=e[n];!0===s&&t.suppressBooleanAttributes?i+=` ${n.substr(t.attributeNamePrefix.length)}`:i+=` ${n.substr(t.attributeNamePrefix.length)}="${s}"`}return i}function Je(e){const t=Object.keys(e);for(let i=0;i<t.length;i++){const n=t[i];if(Object.prototype.hasOwnProperty.call(e,n)&&":@"!==n)return n}}function et(e,t,i){let n="";if(e&&!t.ignoreAttributes)for(let s in e){if(!Object.prototype.hasOwnProperty.call(e,s))continue;let r;i?r=e[s]:(r=t.attributeValueProcessor(s,e[s]),r=it(r,t)),!0===r&&t.suppressBooleanAttributes?n+=` ${s.substr(t.attributeNamePrefix.length)}`:n+=` ${s.substr(t.attributeNamePrefix.length)}="${r}"`}return n}function tt(e,t){if(!t||0===t.length)return!1;for(let i=0;i<t.length;i++)if(e.matches(t[i]))return!0;return!1}function it(e,t){if(e&&e.length>0&&t.processEntities)for(let i=0;i<t.entities.length;i++){const n=t.entities[i];e=e.replace(n.regex,n.val)}return e}const nt={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},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 st(e){if(this.options=Object.assign({},nt,e),this.options.stopNodes&&Array.isArray(this.options.stopNodes)&&(this.options.stopNodes=this.options.stopNodes.map(e=>"string"==typeof e&&e.startsWith("*.")?".."+e.substring(2):e)),this.stopNodeExpressions=[],this.options.stopNodes&&Array.isArray(this.options.stopNodes))for(let e=0;e<this.options.stopNodes.length;e++){const t=this.options.stopNodes[e];"string"==typeof t?this.stopNodeExpressions.push(new we(t)):t instanceof we&&this.stopNodeExpressions.push(t)}var t;!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn="function"==typeof(t=this.options.ignoreAttributes)?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,this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=at),this.processTextOrObjNode=rt,this.options.format?(this.indentate=ot,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function rt(e,t,i,n){const s=this.extractAttributes(e);n.push(t,s);if(this.checkStopNode(n)){const s=this.buildRawContent(e),r=this.buildAttributesForStopNode(e);return n.pop(),this.buildObjectNode(s,t,r,i)}const r=this.j2x(e,i+1,n);return n.pop(),void 0!==e[this.options.textNodeName]&&1===Object.keys(e).length?this.buildTextValNode(e[this.options.textNodeName],t,r.attrStr,i,n):this.buildObjectNode(r.val,t,r.attrStr,i)}function ot(e){return this.options.indentBy.repeat(e)}function at(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}st.prototype.build=function(e){if(this.options.preserveOrder)return Ze(e,this.options);{Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e});const t=new be;return this.j2x(e,0,t).val}},st.prototype.j2x=function(e,t,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 e)if(Object.prototype.hasOwnProperty.call(e,a))if(void 0===e[a])this.isAttribute(a)&&(s+="");else if(null===e[a])this.isAttribute(a)||a===this.options.cdataPropName?s+="":"?"===a[0]?s+=this.indentate(t)+"<"+a+"?"+this.tagEndChar:s+=this.indentate(t)+"<"+a+"/"+this.tagEndChar;else if(e[a]instanceof Date)s+=this.buildTextValNode(e[a],a,"",t,i);else if("object"!=typeof e[a]){const l=this.isAttribute(a);if(l&&!this.ignoreAttributesFn(l,r))n+=this.buildAttrPairStr(l,""+e[a],o);else if(!l)if(a===this.options.textNodeName){let t=this.options.tagValueProcessor(a,""+e[a]);s+=this.replaceEntitiesValue(t)}else{i.push(a);const n=this.checkStopNode(i);if(i.pop(),n){const i=""+e[a];s+=""===i?this.indentate(t)+"<"+a+this.closeTag(a)+this.tagEndChar:this.indentate(t)+"<"+a+">"+i+"</"+a+this.tagEndChar}else s+=this.buildTextValNode(e[a],a,"",t,i)}}else if(Array.isArray(e[a])){const n=e[a].length;let r="",o="";for(let l=0;l<n;l++){const n=e[a][l];if(void 0===n);else if(null===n)"?"===a[0]?s+=this.indentate(t)+"<"+a+"?"+this.tagEndChar:s+=this.indentate(t)+"<"+a+"/"+this.tagEndChar;else if("object"==typeof n)if(this.options.oneListGroup){i.push(a);const e=this.j2x(n,t+1,i);i.pop(),r+=e.val,this.options.attributesGroupName&&n.hasOwnProperty(this.options.attributesGroupName)&&(o+=e.attrStr)}else r+=this.processTextOrObjNode(n,a,t,i);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(a,n);e=this.replaceEntitiesValue(e),r+=e}else{i.push(a);const e=this.checkStopNode(i);if(i.pop(),e){const e=""+n;r+=""===e?this.indentate(t)+"<"+a+this.closeTag(a)+this.tagEndChar:this.indentate(t)+"<"+a+">"+e+"</"+a+this.tagEndChar}else r+=this.buildTextValNode(n,a,"",t,i)}}this.options.oneListGroup&&(r=this.buildObjectNode(r,a,o,t)),s+=r}else if(this.options.attributesGroupName&&a===this.options.attributesGroupName){const t=Object.keys(e[a]),i=t.length;for(let s=0;s<i;s++)n+=this.buildAttrPairStr(t[s],""+e[a][t[s]],o)}else s+=this.processTextOrObjNode(e[a],a,t,i);return{attrStr:n,val:s}},st.prototype.buildAttrPairStr=function(e,t,i){return i||(t=this.options.attributeValueProcessor(e,""+t),t=this.replaceEntitiesValue(t)),this.options.suppressBooleanAttributes&&"true"===t?" "+e:" "+e+'="'+t+'"'},st.prototype.extractAttributes=function(e){if(!e||"object"!=typeof e)return null;const t={};let i=!1;if(this.options.attributesGroupName&&e[this.options.attributesGroupName]){const n=e[this.options.attributesGroupName];for(let e in n){if(!Object.prototype.hasOwnProperty.call(n,e))continue;t[e.startsWith(this.options.attributeNamePrefix)?e.substring(this.options.attributeNamePrefix.length):e]=n[e],i=!0}}else for(let n in e){if(!Object.prototype.hasOwnProperty.call(e,n))continue;const s=this.isAttribute(n);s&&(t[s]=e[n],i=!0)}return i?t:null},st.prototype.buildRawContent=function(e){if("string"==typeof e)return e;if("object"!=typeof e||null===e)return String(e);if(void 0!==e[this.options.textNodeName])return e[this.options.textNodeName];let t="";for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;if(this.isAttribute(i))continue;if(this.options.attributesGroupName&&i===this.options.attributesGroupName)continue;const n=e[i];if(i===this.options.textNodeName)t+=n;else if(Array.isArray(n)){for(let e of n)if("string"==typeof e||"number"==typeof e)t+=`<${i}>${e}</${i}>`;else if("object"==typeof e&&null!==e){const n=this.buildRawContent(e),s=this.buildAttributesForStopNode(e);t+=""===n?`<${i}${s}/>`:`<${i}${s}>${n}</${i}>`}}else if("object"==typeof n&&null!==n){const e=this.buildRawContent(n),s=this.buildAttributesForStopNode(n);t+=""===e?`<${i}${s}/>`:`<${i}${s}>${e}</${i}>`}else t+=`<${i}>${n}</${i}>`}return t},st.prototype.buildAttributesForStopNode=function(e){if(!e||"object"!=typeof e)return"";let t="";if(this.options.attributesGroupName&&e[this.options.attributesGroupName]){const i=e[this.options.attributesGroupName];for(let e in i){if(!Object.prototype.hasOwnProperty.call(i,e))continue;const n=e.startsWith(this.options.attributeNamePrefix)?e.substring(this.options.attributeNamePrefix.length):e,s=i[e];!0===s&&this.options.suppressBooleanAttributes?t+=" "+n:t+=" "+n+'="'+s+'"'}}else for(let i in e){if(!Object.prototype.hasOwnProperty.call(e,i))continue;const n=this.isAttribute(i);if(n){const s=e[i];!0===s&&this.options.suppressBooleanAttributes?t+=" "+n:t+=" "+n+'="'+s+'"'}}return t},st.prototype.buildObjectNode=function(e,t,i,n){if(""===e)return"?"===t[0]?this.indentate(n)+"<"+t+i+"?"+this.tagEndChar:this.indentate(n)+"<"+t+i+this.closeTag(t)+this.tagEndChar;{let s="</"+t+this.tagEndChar,r="";return"?"===t[0]&&(r="?",s=""),!i&&""!==i||-1!==e.indexOf("<")?!1!==this.options.commentPropName&&t===this.options.commentPropName&&0===r.length?this.indentate(n)+`\x3c!--${e}--\x3e`+this.newLine:this.indentate(n)+"<"+t+i+r+this.tagEndChar+e+this.indentate(n)+s:this.indentate(n)+"<"+t+i+r+">"+e+s}},st.prototype.closeTag=function(e){let t="";return-1!==this.options.unpairedTags.indexOf(e)?this.options.suppressUnpairedNode||(t="/"):t=this.options.suppressEmptyNode?"/":`></${e}`,t},st.prototype.checkStopNode=function(e){if(!this.stopNodeExpressions||0===this.stopNodeExpressions.length)return!1;for(let t=0;t<this.stopNodeExpressions.length;t++)if(e.matches(this.stopNodeExpressions[t]))return!0;return!1},st.prototype.buildTextValNode=function(e,t,i,n,s){if(!1!==this.options.cdataPropName&&t===this.options.cdataPropName){const t=String(e).replace(/\]\]>/g,"]]]]><![CDATA[>");return this.indentate(n)+`<![CDATA[${t}]]>`+this.newLine}if(!1!==this.options.commentPropName&&t===this.options.commentPropName){const t=String(e).replace(/--/g,"- -").replace(/-$/,"- ");return this.indentate(n)+`\x3c!--${t}--\x3e`+this.newLine}if("?"===t[0])return this.indentate(n)+"<"+t+i+"?"+this.tagEndChar;{let s=this.options.tagValueProcessor(t,e);return s=this.replaceEntitiesValue(s),""===s?this.indentate(n)+"<"+t+i+this.closeTag(t)+this.tagEndChar:this.indentate(n)+"<"+t+i+">"+s+"</"+t+this.tagEndChar}},st.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){const i=this.options.entities[t];e=e.replace(i.regex,i.val)}return e};class lt{static parser=new qe({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0});static builder=new st({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1})}class ct{static join(e){const t={};for(const i of e)for(const e in i)if(t[e])for(const n of i[e])t[e].add(n);else t[e]=new Set(i[e]);return t}static intersect(e){if(0===e.length)return{};let t=ct.clone(e[0]);for(let i=1;i<e.length;i++){const n=e[i],s={};for(const e in t)if(n[e]){const i=new Set;for(const s of t[e])n[e].has(s)&&i.add(s);i.size>0&&(s[e]=i)}t=s}return t}static clone(e){const t={};for(const i in e)t[i]=new Set(e[i]);return t}static remove(e,t,i=!1){i&&(e=ct.clone(e));for(const i in t)if(e[i]){for(const n of t[i])e[i].delete(n);0===e[i].size&&delete e[i]}}static add(e,t,i=!1){i&&(e=ct.clone(e));for(const i in t)if(e[i])for(const n of t[i])e[i].add(n);else e[i]=new Set(t[i])}static append(e,t,...i){let n=e[t];n||(n=new Set,e[t]=n);for(const e of i)n.add(e)}static isEqual(e,t){const i=Object.keys(e),n=Object.keys(t);if(i.length!==n.length)return!1;for(const n of i){if(!t[n])return!1;if(e[n].size!==t[n].size)return!1;for(const i of e[n])if(!t[n].has(i))return!1}return!0}static isEmpty(e){return 0===Object.values(e).reduce((e,t)=>e+t.size,0)}static toRaw(e){const t={};for(const i in e)t[i]=Array.from(e[i]);return t}static fromRaw(e){const t={};for(const i in e)t[i]=new Set(e[i]);return t}}class ht extends Map{onItemSet=new d;onItemUpdated=new d;onItemDeleted=new d;onCleared=new d;constructor(e){super(e)}clear(){super.clear(),this.onCleared.trigger()}set(e,t){const i=this.has(e);if(!(this.guard??(()=>!0))(e,t))return this;const n=super.set(e,t);return i?(this.onItemUpdated||(this.onItemUpdated=new d),this.onItemUpdated.trigger({key:e,value:t})):(this.onItemSet||(this.onItemSet=new d),this.onItemSet.trigger({key:e,value:t})),n}add(e){const t=v.create();return this.set(t,e),t}guard=()=>!0;delete(e){const t=super.delete(e);return t&&this.onItemDeleted.trigger(e),t}dispose(){this.clear(),this.onItemSet.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}class ut{static isEntry(e){return new Set(["Boolean","Color","Text","Number","Select","Vector3","TextSet","None"]).has(e.type)}static copySchema(e,t={}){for(const i in e){const n=e[i];this.isEntry(n)?t[i]=this.copyEntry(n):(t[i]={},this.copySchema(n,t[i]))}return t}static copyEntry(e){if("Boolean"===e.type){const t=e;return{type:t.type,value:t.value}}if("Color"===e.type){const t=e;return{type:t.type,value:t.value.clone()}}if("Text"===e.type){const t=e;return{type:t.type,value:t.value}}if("Number"===e.type){const t=e;return{type:t.type,value:t.value,min:t.min,max:t.max,interpolable:t.interpolable}}if("Select"===e.type){const t=e;return{type:t.type,value:t.value,multiple:t.multiple,options:new Set(t.options)}}if("Vector3"===e.type){const t=e;return{type:t.type,value:t.value.clone()}}if("TextSet"===e.type){const t=e;return{type:t.type,value:new Set(t.value)}}if("None"===e.type){const t=e;return{type:t.type,value:t.value}}throw new Error("Invalid entry!")}}class dt{_component;name;uuid;get controls(){return ut.copySchema(this._config)}constructor(e,t,i,n){this._component=e,this.name=i,this.uuid=n??v.create();t.get(pt).list.set(this.uuid,this)}set(e){for(const t in e)if(t in this){this[t]=e[t].value}}export(e=this._config,t={}){for(const i in e){const n=e[i];if(ut.isEntry(n))if("Color"===n.type){const{r:e,g:s,b:r}=n.value;t[i]={...n,value:{r:e,g:s,b:r}}}else if("Vector3"===n.type){const{x:e,y:s,z:r}=n.value;t[i]={...n,value:{x:e,y:s,z:r}}}else if("TextSet"===n.type){const e=Array.from(n.value);t[i]={...n,value:e}}else if("Select"===n.type){const e=Array.from(n.options);t[i]={...n,options:e}}else t[i]={...n};else t[i]={},this.export(n,t[i])}return t}import(e,t={},i=!0){for(const i in e){const n=e[i];if(ut.isEntry(n))if("Color"===n.type){const{r:e,g:s,b:r}=n.value;t[i]={...n,value:new c.Color(e,s,r)}}else if("Vector3"===n.type){const{x:e,y:s,z:r}=n.value;t[i]={...n,value:new c.Vector3(e,s,r)}}else"TextSet"===n.type?t[i]={...n,value:new Set(n.value)}:"Select"===n.type?t[i]={...n,options:new Set(n.options)}:t[i]={...n};else t[i]={},this.import(n,t[i],!1)}i&&this.set(t)}}class pt extends f{list=new e.DataMap;enabled=!0;static uuid="b8c764e0-6b24-4e77-9a32-35fa728ee5b4";constructor(e){super(e),e.add(pt.uuid,this)}}class ft{constructor(e){this.dom=e,this.setupEvents(!0)}dom;_event;_position=new c.Vector2;onDisposed=new d;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(e){if(this._event){const t=this.dom.getBoundingClientRect();this._position.x=this.getPositionX(t,this._event,e),this._position.y=this.getPositionY(t,this._event,e)}}getPositionY(e,t,i){const n=this.getDataObject(t);return i?n.clientY:-(n.clientY-e.top)/(e.bottom-e.top)*2+1}getPositionX(e,t,i){const n=this.getDataObject(t);return i?n.clientX:(n.clientX-e.left)/(e.right-e.left)*2-1}updateMouseInfo=e=>{this._event=e};getDataObject(e){return e instanceof MouseEvent?e:e.touches[0]}setupEvents(e){e?(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 mt=1.25,gt=32,wt=Math.pow(2,-24),yt=Symbol("SKIP_GENERATION"),_t={strategy:0,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[yt]:!1};function bt(e,t,i){return i.min.x=t[e],i.min.y=t[e+1],i.min.z=t[e+2],i.max.x=t[e+3],i.max.y=t[e+4],i.max.z=t[e+5],i}function vt(e){let t=-1,i=-1/0;for(let n=0;n<3;n++){const s=e[n+3]-e[n];s>i&&(i=s,t=n)}return t}function xt(e,t){t.set(e)}function Ct(e,t,i){let n,s;for(let r=0;r<3;r++){const o=r+3;n=e[r],s=t[r],i[r]=n<s?n:s,n=e[o],s=t[o],i[o]=n>s?n:s}}function St(e,t,i){for(let n=0;n<3;n++){const s=t[e+2*n],r=t[e+2*n+1],o=s-r,a=s+r;o<i[n]&&(i[n]=o),a>i[n+3]&&(i[n+3]=a)}}function At(e){const t=e[3]-e[0],i=e[4]-e[1],n=e[5]-e[2];return 2*(t*i+i*n+n*t)}function Tt(e,t){return 65535===t[e+15]}function Pt(e,t){return t[e+6]}function Mt(e,t){return t[e+14]}function Et(e){return e+8}function It(e,t){return e+8*t[e+6]}function Dt(e,t){return t[e+7]}function zt(e){return e}function kt(e,t,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=e.offset||0;for(let n=6*(t-w),s=6*(t+i-w);n<s;n+=6){const t=e[n+0],i=e[n+1],s=t-i,w=t+i;s<r&&(r=s),w>l&&(l=w),t<u&&(u=t),t>f&&(f=t);const y=e[n+2],_=e[n+3],b=y-_,v=y+_;b<o&&(o=b),v>c&&(c=v),y<d&&(d=y),y>m&&(m=y);const x=e[n+4],C=e[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 Bt=32,Ot=(e,t)=>e.candidate-t.candidate,Vt=new Array(Bt).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),Lt=new Float32Array(6);class Nt{constructor(){this.boundingData=new Float32Array(6)}}let Ft,Rt,Ut,jt;const $t=Math.pow(2,32);function Wt(e){return"count"in e?1:1+Wt(e.left)+Wt(e.right)}function Ht(e,t,i){return Ft=new Float32Array(i),Rt=new Uint32Array(i),Ut=new Uint16Array(i),jt=new Uint8Array(i),Gt(e,t)}function Gt(e,t){const i=e/4,n=e/2,s="count"in t,r=t.boundingData;for(let e=0;e<6;e++)Ft[i+e]=r[e];if(s)return t.buffer?(jt.set(new Uint8Array(t.buffer),e),e+t.buffer.byteLength):(Rt[i+6]=t.offset,Ut[n+14]=t.count,Ut[n+15]=65535,e+gt);{const{left:n,right:s,splitAxis:r}=t;let o=Gt(e+gt,n);const a=o/gt-e/gt;if(a>$t)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return Rt[i+6]=a,Rt[i+7]=r,Gt(o,s)}}function qt(e,t,i,n,s,r){const{maxDepth:o,verbose:a,maxLeafSize:l,strategy:c,onProgress:h}=s,u=e.primitiveBuffer,d=e.primitiveBufferStride,p=new Float32Array(6);let f=!1;const m=new Nt;return kt(t,i,n,m.boundingData,p),function e(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(e,t,i,n,s,r){let o=-1,a=0;if(0===r)o=vt(t),-1!==o&&(a=(t[o]+t[o+3])/2);else if(1===r)o=vt(e),-1!==o&&(a=function(e,t,i,n){let s=0;const r=e.offset;for(let o=t,a=t+i;o<a;o++)s+=e[6*(o-r)+2*n];return s/i}(i,n,s,o));else if(2===r){const r=At(e);let l=mt*s;const c=i.offset||0,h=6*(n-c),u=6*(n+s-c);for(let e=0;e<3;e++){const n=t[e],c=(t[e+3]-n)/Bt;if(s<8){const t=[...Vt];t.length=s;let n=0;for(let s=h;s<u;s+=6,n++){const r=t[n];r.candidate=i[s+2*e],r.count=0;const{bounds:o,leftCacheBounds:a,rightCacheBounds:l}=r;for(let e=0;e<3;e++)l[e]=1/0,l[e+3]=-1/0,a[e]=1/0,a[e+3]=-1/0,o[e]=1/0,o[e+3]=-1/0;St(s,i,o)}t.sort(Ot);let c=s;for(let e=0;e<c;e++){const i=t[e];for(;e+1<c&&t[e+1].candidate===i.candidate;)t.splice(e+1,1),c--}for(let n=h;n<u;n+=6){const s=i[n+2*e];for(let e=0;e<c;e++){const r=t[e];s>=r.candidate?St(n,i,r.rightCacheBounds):(St(n,i,r.leftCacheBounds),r.count++)}}for(let i=0;i<c;i++){const n=t[i],c=n.count,h=s-n.count,u=n.leftCacheBounds,d=n.rightCacheBounds;let p=0;0!==c&&(p=At(u)/r);let f=0;0!==h&&(f=At(d)/r);const m=1+mt*(p*c+f*h);m<l&&(o=e,l=m,a=n.candidate)}}else{for(let e=0;e<Bt;e++){const t=Vt[e];t.count=0,t.candidate=n+c+e*c;const i=t.bounds;for(let e=0;e<3;e++)i[e]=1/0,i[e+3]=-1/0}for(let t=h;t<u;t+=6){let s=~~((i[t+2*e]-n)/c);s>=Bt&&(s=31);const r=Vt[s];r.count++,St(t,i,r.bounds)}const t=Vt[31];xt(t.bounds,t.rightCacheBounds);for(let e=30;e>=0;e--){const t=Vt[e],i=Vt[e+1];Ct(t.bounds,i.rightCacheBounds,t.rightCacheBounds)}let d=0;for(let t=0;t<31;t++){const i=Vt[t],n=i.count,c=i.bounds,h=Vt[t+1].rightCacheBounds;0!==n&&(0===d?xt(c,Lt):Ct(c,Lt,Lt)),d+=n;let u=0,p=0;0!==d&&(u=At(Lt)/r);const f=s-d;0!==f&&(p=At(h)/r);const m=1+mt*(u*d+p*f);m<l&&(o=e,l=m,a=i.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}(i.boundingData,r,t,n,s,c);if(-1===m.axis)return g(n+s),i.offset=n,i.count=s,i;const w=function(e,t,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<t;i++){let n=e[o*t+i];e[o*t+i]=e[a*t+i],e[a*t+i]=n}for(let e=0;e<6;e++){const t=o-h,n=a-h,s=i[6*t+e];i[6*t+e]=i[6*n+e],i[6*n+e]=s}o++,a--}}(u,d,t,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 Nt,o=n,a=w-n;i.left=r,kt(t,o,a,r.boundingData,p),e(r,o,a,p,h+1);const l=new Nt,c=w,u=s-a;i.right=l,kt(t,c,u,l.boundingData,p),e(l,c,u,p,h+1)}return i}(m,i,n,p),m;function g(e){h&&h((e-r.offset)/r.count)}}function Zt(e,t){const i=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,n=e.getRootRanges(t.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,e.computePrimitiveBounds(o.offset,o.count,a),e._roots=n.map(n=>{const s=qt(e,a,n.offset,n.count,t,o),r=Wt(s),l=new i(gt*r);return Ht(0,s,l),l})}class Yt{constructor(e){this._getNewPrimitive=e,this._primitives=[]}getPrimitive(){const e=this._primitives;return 0===e.length?this._getNewPrimitive():e.pop()}releasePrimitive(e){this._primitives.push(e)}}class Xt{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=i=>{t&&e.push(t),t=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,0!==e.length&&this.setBuffer(e.pop())}}}const Kt=new Xt;let Qt,Jt;const ei=[],ti=new Yt(()=>new t.Box3);function ii(e,t,i,n,s,r){Qt=ti.getPrimitive(),Jt=ti.getPrimitive(),ei.push(Qt,Jt),Kt.setBuffer(e._roots[t]);const o=ni(0,e.geometry,i,n,s,r);Kt.clearBuffer(),ti.releasePrimitive(Qt),ti.releasePrimitive(Jt),ei.pop(),ei.pop();const a=ei.length;return a>0&&(Jt=ei[a-1],Qt=ei[a-2]),o}function ni(e,t,i,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=Kt;let h=2*e;if(Tt(h,l)){const t=Pt(e,c),i=Mt(h,l);return bt(e,a,Qt),n(t,i,!1,o,r+e/8,Qt)}{let h=function(e){const{uint16Array:t,uint32Array:i}=Kt;let n=2*e;for(;!Tt(n,t);)n=2*(e=Et(e));return Pt(e,i)},u=function(e){const{uint16Array:t,uint32Array:i}=Kt;let n=2*e;for(;!Tt(n,t);)n=2*(e=It(e,i));return Pt(e,i)+Mt(n,t)};const d=Et(e),p=It(e,c);let f,m,g,w,y=d,_=p;if(s&&(g=Qt,w=Jt,bt(y,a,g),bt(_,a,w),f=s(g),m=s(w),m<f)){y=p,_=d;const e=f;f=m,m=e,g=w}g||(g=Qt,bt(y,a,g));const b=i(g,Tt(2*y,l),f,o+1,r+y/8);let v;if(2===b){const e=h(y);v=n(e,u(y)-e,!0,o+1,r+y/8,g)}else v=b&&ni(y,t,i,n,s,r,o+1);if(v)return!0;w=Jt,bt(_,a,w);const x=i(w,Tt(2*_,l),m,o+1,r+_/8);let C;if(2===x){const e=h(_);C=n(e,u(_)-e,!0,o+1,r+_/8,w)}else C=x&&ni(_,t,i,n,s,r,o+1);return!!C}}const si=new Kt.constructor,ri=new Kt.constructor,oi=new Yt(()=>new t.Box3),ai=new t.Box3,li=new t.Box3,ci=new t.Box3,hi=new t.Box3;let ui=!1;function di(e,t,i,n,s,r=0,o=0,a=0,l=0,c=null,h=!1){let u,d;h?(u=ri,d=si):(u=si,d=ri);const p=u.float32Array,f=u.uint32Array,m=u.uint16Array,g=d.float32Array,w=d.uint32Array,y=d.uint16Array,_=2*t,b=Tt(2*e,m),v=Tt(_,y);let x=!1;if(v&&b)x=h?s(Pt(t,w),Mt(2*t,y),Pt(e,f),Mt(2*e,m),l,o+t/8,a,r+e/8):s(Pt(e,f),Mt(2*e,m),Pt(t,w),Mt(2*t,y),a,r+e/8,l,o+t/8);else if(v){const c=oi.getPrimitive();bt(t,g,c),c.applyMatrix4(i);const u=Et(e),d=It(e,f);bt(u,p,ai),bt(d,p,li);const m=c.intersectsBox(ai),w=c.intersectsBox(li);x=m&&di(t,u,n,i,s,o,r,l,a+1,c,!h)||w&&di(t,d,n,i,s,o,r,l,a+1,c,!h),oi.releasePrimitive(c)}else{const u=Et(t),d=It(t,w);bt(u,g,ci),bt(d,g,hi);const m=c.intersectsBox(ci),y=c.intersectsBox(hi);if(m&&y)x=di(e,u,i,n,s,r,o,a,l+1,c,h)||di(e,d,i,n,s,r,o,a,l+1,c,h);else if(m)if(b)x=di(e,u,i,n,s,r,o,a,l+1,c,h);else{const t=oi.getPrimitive();t.copy(ci).applyMatrix4(i);const c=Et(e),d=It(e,f);bt(c,p,ai),bt(d,p,li);const m=t.intersectsBox(ai),g=t.intersectsBox(li);x=m&&di(u,c,n,i,s,o,r,l,a+1,t,!h)||g&&di(u,d,n,i,s,o,r,l,a+1,t,!h),oi.releasePrimitive(t)}else if(y)if(b)x=di(e,d,i,n,s,r,o,a,l+1,c,h);else{const t=oi.getPrimitive();t.copy(hi).applyMatrix4(i);const c=Et(e),u=It(e,f);bt(c,p,ai),bt(u,p,li);const m=t.intersectsBox(ai),g=t.intersectsBox(li);x=m&&di(d,c,n,i,s,o,r,l,a+1,t,!h)||g&&di(d,u,n,i,s,o,r,l,a+1,t,!h),oi.releasePrimitive(t)}}return x}const pi=new t.Box3,fi=new Float32Array(6);class mi{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){Zt(this,e={..._t,...e})}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,i,n){let s=1/0,r=1/0,o=1/0,a=-1/0,l=-1/0,c=-1/0;for(let i=e,n=e+t;i<n;i++){this.writePrimitiveBounds(i,fi,0);const[e,t,n,h,u,d]=fi;e<s&&(s=e),h>a&&(a=h),t<r&&(r=t),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(e,t,i){const n=i.offset||0;for(let s=e,r=e+t;s<r;s++){this.writePrimitiveBounds(s,fi,0);const[e,t,r,o,a,l]=fi,c=(e+o)/2,h=(t+a)/2,u=(r+l)/2,d=(o-e)/2,p=(a-t)/2,f=(l-r)/2,m=6*(s-n);i[m+0]=c,i[m+1]=d+(Math.abs(c)+d)*wt,i[m+2]=h,i[m+3]=p+(Math.abs(h)+p)*wt,i[m+4]=u,i[m+5]=f+(Math.abs(u)+f)*wt}return i}shiftPrimitiveOffsets(e){const t=this._indirectBuffer;if(t)for(let i=0,n=t.length;i<n;i++)t[i]+=e;else{const t=this._roots;for(let i=0;i<t.length;i++){const n=t[i],s=new Uint32Array(n),r=new Uint16Array(n),o=n.byteLength/gt;for(let t=0;t<o;t++){const i=8*t;Tt(2*i,r)&&(s[i+6]+=e)}}}}traverse(e,t=0){const i=this._roots[t],n=new Uint32Array(i),s=new Uint16Array(i);!function t(r,o=0){const a=2*r,l=Tt(a,s);if(l){const t=n[r+6],c=s[a+14];e(o,l,new Float32Array(i,4*r,6),t,c)}else{const s=Et(r),a=It(r,n),c=Dt(r,n);e(o,l,new Float32Array(i,4*r,6),c)||(t(s,o+1),t(a,o+1))}}(0)}refit(){const e=this._roots;for(let t=0,i=e.length;t<i;t++){const i=e[t],n=new Uint32Array(i),s=new Uint16Array(i),r=new Float32Array(i);for(let e=i.byteLength/gt-1;e>=0;e--){const t=8*e,i=2*t;if(Tt(i,s)){const e=Pt(t,n),o=Mt(i,s);this.writePrimitiveRangeBounds(e,o,fi,0),r.set(fi,t)}else{const e=Et(t),i=It(t,n);for(let n=0;n<3;n++){const s=r[e+n],o=r[e+n+3],a=r[i+n],l=r[i+n+3];r[t+n]=s<a?s:a,r[t+n+3]=o>l?o:l}}}}}getBoundingBox(e){e.makeEmpty();return this._roots.forEach(t=>{bt(0,new Float32Array(t),pi),e.union(pi)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:i,intersectsRange:n,intersectsPrimitive:s,scratchPrimitive:r,iterate:o}=e;if(n&&s){const e=n;n=(t,i,n,a,l)=>!!e(t,i,n,a,l)||o(t,i,this,s,n,a,r)}else n||(n=s?(e,t,i,n)=>o(e,t,this,s,i,n,r):(e,t,i)=>i);let a=!1,l=0;const c=this._roots;for(let e=0,s=c.length;e<s;e++){const s=c[e];if(a=ii(this,e,i,n,t,l),a)break;l+=s.byteLength/gt}return a}bvhcast(e,i,n){let{intersectsRanges:s}=n;return function(e,i,n,s){if(ui)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");ui=!0;const r=e._roots,o=i._roots;let a,l=0,c=0;const h=(new t.Matrix4).copy(n).invert();for(let e=0,t=r.length;e<t;e++){si.setBuffer(r[e]),c=0;const t=oi.getPrimitive();bt(zt(0),si.float32Array,t),t.applyMatrix4(h);for(let e=0,i=o.length;e<i&&(ri.setBuffer(o[e]),a=di(0,0,n,h,s,l,c,0,0,t),ri.clearBuffer(),c+=o[e].byteLength/gt,!a);e++);if(oi.releasePrimitive(t),si.clearBuffer(),l+=r[e].byteLength/gt,a)break}return ui=!1,a}(this,e,i,s)}}function gi(e){return e.index?e.index.count:e.attributes.position.count}function wi(e){return gi(e)/3}function yi(e,i){if(!e.index){const n=e.attributes.position.count,s=function(e,t=ArrayBuffer){return e>65535?new Uint32Array(new t(4*e)):new Uint16Array(new t(2*e))}(n,i.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer);e.setIndex(new t.BufferAttribute(s,1));for(let e=0;e<n;e++)s[e]=e}}function _i(e,t,i){const n=function(e,t,i){const n=gi(e)/i,s=t||e.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)}}(e,t,i),s=function(e,t){return e.groups.map(e=>({offset:e.start/t,count:e.count/t}))}(e,i);if(!s.length)return[n];const r=[],o=n.offset,a=n.offset+n.count,l=gi(e)/i,c=[];for(const e of s){const{offset:t,count:i}=e,n=t,s=t+(isFinite(i)?i:l-t);n<a&&s>o&&(c.push({pos:Math.max(o,n),isStart:!0}),c.push({pos:Math.min(a,s),isStart:!1}))}c.sort((e,t)=>e.pos!==t.pos?e.pos-t.pos:"end"===e.type?-1:1);let h=0,u=null;for(const e of c){const t=e.pos;0!==h&&t!==u&&r.push({offset:u,count:t-u}),h+=e.isStart?1:-1,u=t}return r}class bi extends mi{get indirect(){return!!this._indirectBuffer}get primitiveStride(){return null}get primitiveBufferStride(){return this.indirect?1:this.primitiveStride}set primitiveBufferStride(e){}get primitiveBuffer(){return this.indirect?this._indirectBuffer:this.geometry.index.array}set primitiveBuffer(e){}constructor(e,t={}){if(!e.isBufferGeometry)throw new Error("BVH: Only BufferGeometries are supported.");if(e.index&&e.index.isInterleavedBufferAttribute)throw new Error("BVH: InterleavedBufferAttribute is not supported for the index attribute.");if(t.useSharedArrayBuffer&&"undefined"==typeof SharedArrayBuffer)throw new Error("BVH: SharedArrayBuffer is not available.");super(),this.geometry=e,this.resolvePrimitiveIndex=t.indirect?e=>this._indirectBuffer[e]:e=>e,this.primitiveBuffer=null,this.primitiveBufferStride=null,this._indirectBuffer=null,(t={..._t,...t})[yt]||this.init(t)}init(e){const{geometry:i,primitiveStride:n}=this;if(e.indirect){const t=function(e,t){const i=e[e.length-1],n=i.offset+i.count>65536,s=e.reduce((e,t)=>e+t.count,0),r=n?4:2,o=t?new SharedArrayBuffer(s*r):new ArrayBuffer(s*r),a=n?new Uint32Array(o):new Uint16Array(o);let l=0;for(let t=0;t<e.length;t++){const{offset:i,count:n}=e[t];for(let e=0;e<n;e++)a[l+e]=i+e;l+=n}return a}(_i(i,e.range,n),e.useSharedArrayBuffer);this._indirectBuffer=t}else yi(i,e);super.init(e),!i.boundingBox&&e.setBoundingBox&&(i.boundingBox=this.getBoundingBox(new t.Box3))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:_i(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class vi{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let i=1/0,n=-1/0;for(let s=0,r=e.length;s<r;s++){const r=e[s][t];i=r<i?r:i,n=r>n?r:n}this.min=i,this.max=n}setFromPoints(e,t){let i=1/0,n=-1/0;for(let s=0,r=t.length;s<r;s++){const r=t[s],o=e.dot(r);i=o<i?o:i,n=o>n?o:n}this.min=i,this.max=n}isSeparated(e){return this.min>e.max||e.min>this.max}}vi.prototype.setFromBox=function(){const e=new t.Vector3;return function(t,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++){e.x=n.x*i+s.x*(1-i),e.y=n.y*a+s.y*(1-a),e.z=n.z*l+s.z*(1-l);const c=t.dot(e);r=Math.min(c,r),o=Math.max(c,o)}this.min=r,this.max=o}}();const xi=function(){const e=new t.Vector3,i=new t.Vector3,n=new t.Vector3;return function(t,s,r){const o=t.start,a=e,l=s.start,c=i;n.subVectors(o,l),e.subVectors(t.end,t.start),i.subVectors(s.end,s.start);const h=n.dot(c),u=c.dot(a),d=c.dot(c),p=n.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}}(),Ci=function(){const e=new t.Vector2,i=new t.Vector3,n=new t.Vector3;return function(t,s,r,o){xi(t,s,e);let a=e.x,l=e.y;if(a>=0&&a<=1&&l>=0&&l<=1)return t.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 t.closestPointToPoint(o,!0,r);if(l>=0&&l<=1)return a<0?t.at(0,r):t.at(1,r),void s.closestPointToPoint(r,!0,o);{let e,c;e=a<0?t.start:t.end,c=l<0?s.start:s.end;const h=i,u=n;return t.closestPointToPoint(c,!0,i),s.closestPointToPoint(e,!0,n),h.distanceToSquared(c)<=u.distanceToSquared(e)?(r.copy(h),void o.copy(c)):(r.copy(e),void o.copy(u))}}}(),Si=function(){const e=new t.Vector3,i=new t.Vector3,n=new t.Plane,s=new t.Line3;return function(t,r){const{radius:o,center:a}=t,{a:l,b:c,c:h}=r;s.start=l,s.end=c;if(s.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;s.start=l,s.end=h;if(s.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;s.start=c,s.end=h;if(s.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;const u=r.getPlane(n);if(Math.abs(u.distanceToPoint(a))<=o){const e=u.projectPoint(a,i);if(r.containsPoint(e))return!0}return!1}}(),Ai=["x","y","z"],Ti=1e-15;function Pi(e){return Math.abs(e)<Ti}class Mi extends t.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new t.Vector3),this.satBounds=new Array(4).fill().map(()=>new vi),this.points=[this.a,this.b,this.c],this.plane=new t.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new t.Line3,this.needsUpdate=!0}intersectsSphere(e){return Si(e,this)}update(){const e=this.a,t=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(e,t),c.setFromPoints(l,n);const h=s[2],u=r[2];h.subVectors(t,i),u.setFromPoints(h,n);const d=s[3],p=r[3];d.subVectors(i,e),p.setFromPoints(d,n);const f=l.length(),m=h.length(),g=d.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,f<Ti?m<Ti||g<Ti?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(i)):m<Ti?g<Ti?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):g<Ti&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(o,e),this.needsUpdate=!1}}Mi.prototype.closestPointToSegment=function(){const e=new t.Vector3,i=new t.Vector3,n=new t.Line3;return function(t,s=null,r=null){const{start:o,end:a}=t,l=this.points;let c,h=1/0;for(let o=0;o<3;o++){const a=(o+1)%3;n.start.copy(l[o]),n.end.copy(l[a]),Ci(n,t,e,i),c=e.distanceToSquared(i),c<h&&(h=c,s&&s.copy(e),r&&r.copy(i))}return this.closestPointToPoint(o,e),c=o.distanceToSquared(e),c<h&&(h=c,s&&s.copy(e),r&&r.copy(o)),this.closestPointToPoint(a,e),c=a.distanceToSquared(e),c<h&&(h=c,s&&s.copy(e),r&&r.copy(a)),Math.sqrt(h)}}(),Mi.prototype.intersectsTriangle=function(){const e=new Mi,i=new vi,n=new vi,s=new t.Vector3,r=new t.Vector3,o=new t.Vector3,a=new t.Vector3,l=new t.Line3,c=new t.Line3,h=new t.Vector3,u=new t.Vector2,d=new t.Vector2;function p(e,t,r,o){const l=s;e.isDegenerateIntoPoint||e.isDegenerateIntoSegment?l.copy(t.plane.normal):l.copy(e.plane.normal);const c=e.satBounds,h=e.satAxes;for(let s=1;s<4;s++){const r=c[s],o=h[s];if(i.setFromPoints(o,t.points),r.isSeparated(i))return!1;if(a.copy(l).cross(o),i.setFromPoints(a,e.points),n.setFromPoints(a,t.points),i.isSeparated(n))return!1}const u=t.satBounds,d=t.satAxes;for(let s=1;s<4;s++){const r=u[s],o=d[s];if(i.setFromPoints(o,e.points),r.isSeparated(i))return!1;if(a.crossVectors(l,o),i.setFromPoints(a,e.points),n.setFromPoints(a,t.points),i.isSeparated(n))return!1}return r&&(o||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 f(e,t,i,n,s,r,o,a,l,c,h){let u=o/(o-a);c.x=n+(s-n)*u,h.start.subVectors(t,e).multiplyScalar(u).add(e),u=o/(o-l),c.y=n+(r-n)*u,h.end.subVectors(i,e).multiplyScalar(u).add(e)}function m(e,t,i,n,s,r,o,a,l,c,h){if(s>0)f(e.c,e.a,e.b,n,t,i,l,o,a,c,h);else if(r>0)f(e.b,e.a,e.c,i,t,n,a,o,l,c,h);else if(a*l>0||0!=o)f(e.a,e.b,e.c,t,i,n,o,a,l,c,h);else if(0!=a)f(e.b,e.a,e.c,i,t,n,a,o,l,c,h);else{if(0==l)return!0;f(e.c,e.a,e.b,n,t,i,l,o,a,c,h)}return!1}function g(e,t,i,n){const r=t.degenerateSegment,o=e.plane.distanceToPoint(r.start),a=e.plane.distanceToPoint(r.end);return Pi(o)?Pi(a)?p(e,t,i,n):(i&&(i.start.copy(r.start),i.end.copy(r.start)),e.containsPoint(r.start)):Pi(a)?(i&&(i.start.copy(r.end),i.end.copy(r.end)),e.containsPoint(r.end)):null!=e.plane.intersectLine(r,s)&&(i&&(i.start.copy(s),i.end.copy(s)),e.containsPoint(s))}function w(e,t,i){const n=t.a;return!(!Pi(e.plane.distanceToPoint(n))||!e.containsPoint(n))&&(i&&(i.start.copy(n),i.end.copy(n)),!0)}function y(e,t,i){const n=e.degenerateSegment,r=t.a;return n.closestPointToPoint(r,!0,s),r.distanceToSquared(s)<1e-30&&(i&&(i.start.copy(r),i.end.copy(r)),!0)}return function(t,i=null,n=!1){this.needsUpdate&&this.update(),t.isExtendedTriangle?t.needsUpdate&&t.update():(e.copy(t),e.update(),t=e);const a=function(e,t,i,n){if(e.isDegenerateIntoSegment){if(t.isDegenerateIntoSegment){const n=e.degenerateSegment,a=t.degenerateSegment,l=r,c=o;n.delta(l),a.delta(c);const h=s.subVectors(a.start,n.start),u=l.x*c.y-l.y*c.x;if(Pi(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)&&(!!Pi(n.start.z+l.z*d-(a.start.z+c.z*p))&&(i&&(i.start.copy(n.start).addScaledVector(l,d),i.end.copy(n.start).addScaledVector(l,d)),!0))}return t.isDegenerateIntoPoint?y(e,t,i):g(t,e,i,n)}return e.isDegenerateIntoPoint?t.isDegenerateIntoPoint?t.a.distanceToSquared(e.a)<1e-30&&(i&&(i.start.copy(e.a),i.end.copy(e.a)),!0):t.isDegenerateIntoSegment?y(t,e,i):w(t,e,i):t.isDegenerateIntoPoint?w(e,t,i):t.isDegenerateIntoSegment?g(e,t,i,n):void 0}(this,t,i,n);if(void 0!==a)return a;const f=this.plane,_=t.plane;let b=_.distanceToPoint(this.a),v=_.distanceToPoint(this.b),x=_.distanceToPoint(this.c);Pi(b)&&(b=0),Pi(v)&&(v=0),Pi(x)&&(x=0);const C=b*v,S=b*x;if(C>0&&S>0)return!1;let A=f.distanceToPoint(t.a),T=f.distanceToPoint(t.b),P=f.distanceToPoint(t.c);Pi(A)&&(A=0),Pi(T)&&(T=0),Pi(P)&&(P=0);const M=A*T,E=A*P;if(M>0&&E>0)return!1;r.copy(f.normal),o.copy(_.normal);const I=r.cross(o);let D=0,z=Math.abs(I.x);const k=Math.abs(I.y);k>z&&(z=k,D=1);Math.abs(I.z)>z&&(D=2);const B=Ai[D],O=this.a[B],V=this.b[B],L=this.c[B],N=t.a[B],F=t.b[B],R=t.c[B];if(m(this,O,V,L,C,S,b,v,x,u,l))return p(this,t,i,n);if(m(t,N,F,R,M,E,A,T,P,d,c))return p(this,t,i,n);if(u.y<u.x){const e=u.y;u.y=u.x,u.x=e,h.copy(l.start),l.start.copy(l.end),l.end.copy(h)}if(d.y<d.x){const e=d.y;d.y=d.x,d.x=e,h.copy(c.start),c.start.copy(c.end),c.end.copy(h)}return!(u.y<d.x||d.y<u.x)&&(i&&(d.x>u.x?i.start.copy(c.start):i.start.copy(l.start),d.y<u.y?i.end.copy(c.end):i.end.copy(l.end)),!0)}}(),Mi.prototype.distanceToPoint=function(){const e=new t.Vector3;return function(t){return this.closestPointToPoint(t,e),t.distanceTo(e)}}(),Mi.prototype.distanceToTriangle=function(){const e=new t.Vector3,i=new t.Vector3,n=["a","b","c"],s=new t.Line3,r=new t.Line3;return function(t,o=null,a=null){const l=o||a?s:null;if(this.intersectsTriangle(t,l))return(o||a)&&(o&&l.getCenter(o),a&&l.getCenter(a)),0;let c=1/0;for(let i=0;i<3;i++){let s;const r=n[i],l=t[r];this.closestPointToPoint(l,e),s=l.distanceToSquared(e),s<c&&(c=s,o&&o.copy(e),a&&a.copy(l));const h=this[r];t.closestPointToPoint(h,e),s=h.distanceToSquared(e),s<c&&(c=s,o&&o.copy(h),a&&a.copy(e))}for(let l=0;l<3;l++){const h=n[l],u=n[(l+1)%3];s.set(this[h],this[u]);for(let l=0;l<3;l++){const h=n[l],u=n[(l+1)%3];r.set(t[h],t[u]),Ci(s,r,e,i);const d=e.distanceToSquared(i);d<c&&(c=d,o&&o.copy(e),a&&a.copy(i))}}return Math.sqrt(c)}}();class Ei{constructor(e,i,n){this.isOrientedBox=!0,this.min=new t.Vector3,this.max=new t.Vector3,this.matrix=new t.Matrix4,this.invMatrix=new t.Matrix4,this.points=new Array(8).fill().map(()=>new t.Vector3),this.satAxes=new Array(3).fill().map(()=>new t.Vector3),this.satBounds=new Array(3).fill().map(()=>new vi),this.alignedSatBounds=new Array(3).fill().map(()=>new vi),this.needsUpdate=!1,e&&this.min.copy(e),i&&this.max.copy(i),n&&this.matrix.copy(n)}set(e,t,i){this.min.copy(e),this.max.copy(t),this.matrix.copy(i),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}Ei.prototype.update=function(){return function(){const e=this.matrix,t=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:t.x,a.y=r?i.y:t.y,a.z=o?i.z:t.z,a.applyMatrix4(e)}const s=this.satBounds,r=this.satAxes,o=n[0];for(let e=0;e<3;e++){const t=r[e],i=s[e],a=n[1<<e];t.subVectors(o,a),i.setFromPoints(t,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}}(),Ei.prototype.intersectsBox=function(){const e=new vi;return function(t){this.needsUpdate&&this.update();const i=t.min,n=t.max,s=this.satBounds,r=this.satAxes,o=this.alignedSatBounds;if(e.min=i.x,e.max=n.x,o[0].isSeparated(e))return!1;if(e.min=i.y,e.max=n.y,o[1].isSeparated(e))return!1;if(e.min=i.z,e.max=n.z,o[2].isSeparated(e))return!1;for(let i=0;i<3;i++){const n=r[i],o=s[i];if(e.setFromBox(n,t),o.isSeparated(e))return!1}return!0}}(),Ei.prototype.intersectsTriangle=function(){const e=new Mi,i=new Array(3),n=new vi,s=new vi,r=new t.Vector3;return function(t){this.needsUpdate&&this.update(),t.isExtendedTriangle?t.needsUpdate&&t.update():(e.copy(t),e.update(),t=e);const o=this.satBounds,a=this.satAxes;i[0]=t.a,i[1]=t.b,i[2]=t.c;for(let e=0;e<3;e++){const t=o[e],s=a[e];if(n.setFromPoints(s,i),t.isSeparated(n))return!1}const l=t.satBounds,c=t.satAxes,h=this.points;for(let e=0;e<3;e++){const t=l[e],i=c[e];if(n.setFromPoints(i,h),t.isSeparated(n))return!1}for(let e=0;e<3;e++){const t=a[e];for(let e=0;e<4;e++){const o=c[e];if(r.crossVectors(t,o),n.setFromPoints(r,i),s.setFromPoints(r,h),n.isSeparated(s))return!1}}return!0}}(),Ei.prototype.closestPointToPoint=function(){return function(e,t){return this.needsUpdate&&this.update(),t.copy(e).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),t}}(),Ei.prototype.distanceToPoint=function(){const e=new t.Vector3;return function(t){return this.closestPointToPoint(t,e),t.distanceTo(e)}}(),Ei.prototype.distanceToBox=function(){const e=["x","y","z"],i=new Array(12).fill().map(()=>new t.Line3),n=new Array(12).fill().map(()=>new t.Line3),s=new t.Vector3,r=new t.Vector3;return function(t,o=0,a=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(t))return(a||l)&&(t.getCenter(r),this.closestPointToPoint(r,s),t.closestPointToPoint(s,r),a&&a.copy(s),l&&l.copy(r)),0;const c=o*o,h=t.min,u=t.max,d=this.points;let p=1/0;for(let e=0;e<8;e++){const t=d[e];r.copy(t).clamp(h,u);const i=t.distanceToSquared(r);if(i<p&&(p=i,a&&a.copy(t),l&&l.copy(r),i<c))return Math.sqrt(i)}let f=0;for(let t=0;t<3;t++)for(let s=0;s<=1;s++)for(let r=0;r<=1;r++){const o=(t+1)%3,a=(t+2)%3,l=1<<t|s<<o|r<<a,c=d[s<<o|r<<a],p=d[l];i[f].set(c,p);const m=e[t],g=e[o],w=e[a],y=n[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 e=0;e<=1;e++)for(let t=0;t<=1;t++)for(let i=0;i<=1;i++){r.x=e?u.x:h.x,r.y=t?u.y:h.y,r.z=i?u.z:h.z,this.closestPointToPoint(r,s);const n=r.distanceToSquared(s);if(n<p&&(p=n,a&&a.copy(s),l&&l.copy(r),n<c))return Math.sqrt(n)}for(let e=0;e<12;e++){const t=i[e];for(let e=0;e<12;e++){const i=n[e];Ci(t,i,s,r);const o=s.distanceToSquared(r);if(o<p&&(p=o,a&&a.copy(s),l&&l.copy(r),o<c))return Math.sqrt(o)}}return Math.sqrt(p)}}();class Ii extends Yt{constructor(){super(()=>new Mi)}}const Di=new Ii,zi=new t.Vector3,ki=new t.Vector3;const Bi=parseInt(t.REVISION)>=169,Oi=parseInt(t.REVISION)<=161,Vi=new t.Vector3,Li=new t.Vector3,Ni=new t.Vector3,Fi=new t.Vector2,Ri=new t.Vector2,Ui=new t.Vector2,ji=new t.Vector3,$i=new t.Vector3,Wi=new t.Vector3,Hi=new t.Vector3;function Gi(e,i,n,s,r,o,a,l,c,h,u){Vi.fromBufferAttribute(i,o),Li.fromBufferAttribute(i,a),Ni.fromBufferAttribute(i,l);const d=function(e,i,n,s,r,o,a,l){let c;if(c=o===t.BackSide?e.intersectTriangle(s,n,i,!0,r):e.intersectTriangle(i,n,s,o!==t.DoubleSide,r),null===c)return null;const h=e.origin.distanceTo(r);return h<a||h>l?null:{distance:h,point:r.clone()}}(e,Vi,Li,Ni,Hi,c,h,u);if(d){if(s){Fi.fromBufferAttribute(s,o),Ri.fromBufferAttribute(s,a),Ui.fromBufferAttribute(s,l),d.uv=new t.Vector2;const e=t.Triangle.getInterpolation(Hi,Vi,Li,Ni,Fi,Ri,Ui,d.uv);Bi||(d.uv=e)}if(r){Fi.fromBufferAttribute(r,o),Ri.fromBufferAttribute(r,a),Ui.fromBufferAttribute(r,l),d.uv1=new t.Vector2;const e=t.Triangle.getInterpolation(Hi,Vi,Li,Ni,Fi,Ri,Ui,d.uv1);Bi||(d.uv1=e),Oi&&(d.uv2=d.uv1)}if(n){ji.fromBufferAttribute(n,o),$i.fromBufferAttribute(n,a),Wi.fromBufferAttribute(n,l),d.normal=new t.Vector3;const i=t.Triangle.getInterpolation(Hi,Vi,Li,Ni,ji,$i,Wi,d.normal);d.normal.dot(e.direction)>0&&d.normal.multiplyScalar(-1),Bi||(d.normal=i)}const i={a:o,b:a,c:l,normal:new t.Vector3,materialIndex:0};if(t.Triangle.getNormal(Vi,Li,Ni,i.normal),d.face=i,d.faceIndex=o,Bi){const e=new t.Vector3;t.Triangle.getBarycoord(Hi,Vi,Li,Ni,e),d.barycoord=e}}return d}function qi(e){return e&&e.isMaterial?e.side:e}function Zi(e,t,i,n,s,r,o){const a=3*n;let l=a+0,c=a+1,h=a+2;const{index:u,groups:d}=e;e.index&&(l=u.getX(l),c=u.getX(c),h=u.getX(h));const{position:p,normal:f,uv:m,uv1:g}=e.attributes;if(Array.isArray(t)){const e=3*n;for(let a=0,u=d.length;a<u;a++){const{start:u,count:w,materialIndex:y}=d[a];if(e>=u&&e<u+w){const e=Gi(i,p,f,m,g,l,c,h,qi(t[y]),r,o);if(e){if(e.faceIndex=n,e.face.materialIndex=y,!s)return e;s.push(e)}}}}else{const e=Gi(i,p,f,m,g,l,c,h,qi(t),r,o);if(e){if(e.faceIndex=n,e.face.materialIndex=0,!s)return e;s.push(e)}}return null}function Yi(e,t,i,n){const s=e.a,r=e.b,o=e.c;let a=t,l=t+1,c=t+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 Xi(e,t,i,n,s,r,o){const{geometry:a}=i,{index:l}=a,c=a.attributes.position;for(let i=e,a=t+e;i<a;i++){let e;if(e=i,Yi(o,3*e,l,c),o.needsUpdate=!0,n(o,e,s,r))return!0}return!1}function Ki(e,t=null){t&&Array.isArray(t)&&(t=new Set(t));const i=e.geometry,n=i.index?i.index.array:null,s=i.attributes.position;let r,o,a,l,c=0;const h=e._roots;for(let e=0,t=h.length;e<t;e++)r=h[e],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),u(0,c),c+=r.byteLength;function u(e,i,r=!1){const c=2*e;if(Tt(c,a)){const t=Pt(e,o);let i=1/0,r=1/0,h=1/0,u=-1/0,d=-1/0,p=-1/0;for(let e=3*t,o=3*(t+Mt(c,a));e<o;e++){let t=n[e];const o=s.getX(t),a=s.getY(t),l=s.getZ(t);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[e+0]!==i||l[e+1]!==r||l[e+2]!==h||l[e+3]!==u||l[e+4]!==d||l[e+5]!==p)&&(l[e+0]=i,l[e+1]=r,l[e+2]=h,l[e+3]=u,l[e+4]=d,l[e+5]=p,!0)}{const n=Et(e),s=It(e,o);let a=r,c=!1,h=!1;if(t){if(!a){const e=n/8+i/gt,r=s/8+i/gt;c=t.has(e),h=t.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 t=0;t<3;t++){const i=n+t,r=s+t,o=l[i],a=l[i+3],c=l[r],h=l[r+3];l[e+t]=o<c?o:c,l[e+t+3]=a>h?a:h}return m}}}function Qi(e,t,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=t[e],y=t[e+3],_=t[e+1],b=t[e+3+1],v=t[e+2],x=t[e+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 Ji(e,t,i,n,s,r,o){const{geometry:a}=i,{index:l}=a,c=a.attributes.position;for(let a=e,h=t+e;a<h;a++){let e;if(e=i.resolveTriangleIndex(a),Yi(o,3*e,l,c),o.needsUpdate=!0,n(o,e,s,r))return!0}return!1}function en(e,t,i,n,s,r,o){Kt.setBuffer(e._roots[t]),tn(0,e,i,n,s,r,o),Kt.clearBuffer()}function tn(e,t,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Kt,h=2*e;if(Tt(h,l)){!function(e,t,i,n,s,r,o,a){const{geometry:l,_indirectBuffer:c}=e;for(let e=n,c=n+s;e<c;e++)Zi(l,t,i,e,r,o,a)}(t,i,n,Pt(e,c),Mt(h,l),s,r,o)}else{const l=Et(e);Qi(l,a,n,r,o)&&tn(l,t,i,n,s,r,o);const h=It(e,c);Qi(h,a,n,r,o)&&tn(h,t,i,n,s,r,o)}}const nn=["x","y","z"];function sn(e,t,i,n,s,r){Kt.setBuffer(e._roots[t]);const o=rn(0,e,i,n,s,r);return Kt.clearBuffer(),o}function rn(e,t,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Kt;let c=2*e;if(Tt(c,a)){return function(e,t,i,n,s,r,o){const{geometry:a,_indirectBuffer:l}=e;let c=1/0,h=null;for(let e=n,l=n+s;e<l;e++){let n;n=Zi(a,t,i,e,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(t,i,n,Pt(e,l),Mt(c,a),s,r)}{const a=Dt(e,l),c=nn[a],h=n.direction[c]>=0;let u,d;h?(u=Et(e),d=It(e,l)):(u=It(e,l),d=Et(e));const p=Qi(u,o,n,s,r)?rn(u,t,i,n,s,r):null;if(p){const e=p.point[c];if(h?e<=o[d+a]:e>=o[d+a+3])return p}const f=Qi(d,o,n,s,r)?rn(d,t,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const on=new t.Box3,an=new Mi,ln=new Mi,cn=new t.Matrix4,hn=new Ei,un=new Ei;function dn(e,t,i,n){Kt.setBuffer(e._roots[t]);const s=pn(0,e,i,n);return Kt.clearBuffer(),s}function pn(e,t,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Kt;let l=2*e;null===s&&(i.boundingBox||i.computeBoundingBox(),hn.set(i.boundingBox.min,i.boundingBox.max,n),s=hn);if(!Tt(l,o)){const o=Et(e),l=It(e,a);bt(o,r,on);if(s.intersectsBox(on)&&pn(o,t,i,n,s))return!0;bt(l,r,on);return!!(s.intersectsBox(on)&&pn(l,t,i,n,s))}{const s=t.geometry,c=s.index,h=s.attributes.position,u=i.index,d=i.attributes.position,p=Pt(e,a),f=Mt(l,o);if(cn.copy(n).invert(),i.boundsTree){bt(e,r,un),un.matrix.copy(cn),un.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:e=>un.intersectsBox(e),intersectsTriangle:e=>{e.a.applyMatrix4(n),e.b.applyMatrix4(n),e.c.applyMatrix4(n),e.needsUpdate=!0;for(let t=3*p,i=3*(f+p);t<i;t+=3)if(Yi(ln,t,c,h),ln.needsUpdate=!0,e.intersectsTriangle(ln))return!0;return!1}})}{const e=wi(i);for(let t=3*p,i=3*(f+p);t<i;t+=3){Yi(an,t,c,h),an.a.applyMatrix4(cn),an.b.applyMatrix4(cn),an.c.applyMatrix4(cn),an.needsUpdate=!0;for(let t=0,i=3*e;t<i;t+=3)if(Yi(ln,t,u,d),ln.needsUpdate=!0,an.intersectsTriangle(ln))return!0}}}}const fn=new t.Matrix4,mn=new Ei,gn=new Ei,wn=new t.Vector3,yn=new t.Vector3,_n=new t.Vector3,bn=new t.Vector3;function vn(e,t,i,n={},s={},r=0,o=1/0){t.boundingBox||t.computeBoundingBox(),mn.set(t.boundingBox.min,t.boundingBox.max,i),mn.needsUpdate=!0;const a=e.geometry,l=a.attributes.position,c=a.index,h=t.attributes.position,u=t.index,d=Di.getPrimitive(),p=Di.getPrimitive();let f=wn,m=yn,g=null,w=null;s&&(g=_n,w=bn);let y=1/0,_=null,b=null;return fn.copy(i).invert(),gn.matrix.copy(fn),e.shapecast({boundsTraverseOrder:e=>mn.distanceToBox(e),intersectsBounds:(e,t,i)=>i<y&&i<o&&(t&&(gn.min.copy(e.min),gn.max.copy(e.max),gn.needsUpdate=!0),!0),intersectsRange:(e,n)=>{if(t.boundsTree){return t.boundsTree.shapecast({boundsTraverseOrder:e=>gn.distanceToBox(e),intersectsBounds:(e,t,i)=>i<y&&i<o,intersectsRange:(t,s)=>{for(let o=t,a=t+s;o<a;o++){Yi(p,3*o,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let t=e,i=e+n;t<i;t++){Yi(d,3*t,c,l),d.needsUpdate=!0;const e=d.distanceToTriangle(p,f,g);if(e<y&&(m.copy(f),w&&w.copy(g),y=e,_=t,b=o),e<r)return!0}}}})}for(let s=0,o=wi(t);s<o;s++){Yi(p,3*s,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let t=e,i=e+n;t<i;t++){Yi(d,3*t,c,l),d.needsUpdate=!0;const e=d.distanceToTriangle(p,f,g);if(e<y&&(m.copy(f),w&&w.copy(g),y=e,_=t,b=s),e<r)return!0}}}}),Di.releasePrimitive(d),Di.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(fn),m.applyMatrix4(fn),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function xn(e,t=null){t&&Array.isArray(t)&&(t=new Set(t));const i=e.geometry,n=i.index?i.index.array:null,s=i.attributes.position;let r,o,a,l,c=0;const h=e._roots;for(let e=0,t=h.length;e<t;e++)r=h[e],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(Tt(h,a)){const t=Pt(i,o);let r=1/0,c=1/0,u=1/0,d=-1/0,p=-1/0,f=-1/0;for(let i=t,o=t+Mt(h,a);i<o;i++){const t=3*e.resolveTriangleIndex(i);for(let e=0;e<3;e++){let i=t+e;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 e=Et(i),n=It(i,o);let s=c,a=!1,h=!1;if(t){if(!s){const i=e/8+r/gt,o=n/8+r/gt;a=t.has(i),h=t.has(o),s=!a&&!h}}else a=!0,h=!0;const d=s||h;let p=!1;(s||a)&&(p=u(e,r,s));let f=!1;d&&(f=u(n,r,s));const m=p||f;if(m)for(let t=0;t<3;t++){const s=e+t,r=n+t,o=l[s],a=l[s+3],c=l[r],h=l[r+3];l[i+t]=o<c?o:c,l[i+t+3]=a>h?a:h}return m}}}function Cn(e,t,i,n,s,r,o){Kt.setBuffer(e._roots[t]),Sn(0,e,i,n,s,r,o),Kt.clearBuffer()}function Sn(e,t,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=Kt,h=2*e;if(Tt(h,l)){!function(e,t,i,n,s,r,o,a){const{geometry:l,_indirectBuffer:c}=e;for(let e=n,h=n+s;e<h;e++)Zi(l,t,i,c?c[e]:e,r,o,a)}(t,i,n,Pt(e,c),Mt(h,l),s,r,o)}else{const l=Et(e);Qi(l,a,n,r,o)&&Sn(l,t,i,n,s,r,o);const h=It(e,c);Qi(h,a,n,r,o)&&Sn(h,t,i,n,s,r,o)}}const An=["x","y","z"];function Tn(e,t,i,n,s,r){Kt.setBuffer(e._roots[t]);const o=Pn(0,e,i,n,s,r);return Kt.clearBuffer(),o}function Pn(e,t,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=Kt;let c=2*e;if(Tt(c,a)){return function(e,t,i,n,s,r,o){const{geometry:a,_indirectBuffer:l}=e;let c=1/0,h=null;for(let e=n,u=n+s;e<u;e++){let n;n=Zi(a,t,i,l?l[e]:e,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(t,i,n,Pt(e,l),Mt(c,a),s,r)}{const a=Dt(e,l),c=An[a],h=n.direction[c]>=0;let u,d;h?(u=Et(e),d=It(e,l)):(u=It(e,l),d=Et(e));const p=Qi(u,o,n,s,r)?Pn(u,t,i,n,s,r):null;if(p){const e=p.point[c];if(h?e<=o[d+a]:e>=o[d+a+3])return p}const f=Qi(d,o,n,s,r)?Pn(d,t,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const Mn=new t.Box3,En=new Mi,In=new Mi,Dn=new t.Matrix4,zn=new Ei,kn=new Ei;function Bn(e,t,i,n){Kt.setBuffer(e._roots[t]);const s=On(0,e,i,n);return Kt.clearBuffer(),s}function On(e,t,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Kt;let l=2*e;null===s&&(i.boundingBox||i.computeBoundingBox(),zn.set(i.boundingBox.min,i.boundingBox.max,n),s=zn);if(!Tt(l,o)){const o=Et(e),l=It(e,a);bt(o,r,Mn);if(s.intersectsBox(Mn)&&On(o,t,i,n,s))return!0;bt(l,r,Mn);return!!(s.intersectsBox(Mn)&&On(l,t,i,n,s))}{const s=t.geometry,c=s.index,h=s.attributes.position,u=i.index,d=i.attributes.position,p=Pt(e,a),f=Mt(l,o);if(Dn.copy(n).invert(),i.boundsTree){bt(e,r,kn),kn.matrix.copy(Dn),kn.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:e=>kn.intersectsBox(e),intersectsTriangle:e=>{e.a.applyMatrix4(n),e.b.applyMatrix4(n),e.c.applyMatrix4(n),e.needsUpdate=!0;for(let i=p,n=f+p;i<n;i++)if(Yi(In,3*t.resolveTriangleIndex(i),c,h),In.needsUpdate=!0,e.intersectsTriangle(In))return!0;return!1}})}{const e=wi(i);for(let i=p,n=f+p;i<n;i++){const n=t.resolveTriangleIndex(i);Yi(En,3*n,c,h),En.a.applyMatrix4(Dn),En.b.applyMatrix4(Dn),En.c.applyMatrix4(Dn),En.needsUpdate=!0;for(let t=0,i=3*e;t<i;t+=3)if(Yi(In,t,u,d),In.needsUpdate=!0,En.intersectsTriangle(In))return!0}}}}const Vn=new t.Matrix4,Ln=new Ei,Nn=new Ei,Fn=new t.Vector3,Rn=new t.Vector3,Un=new t.Vector3,jn=new t.Vector3;function $n(e,t,i,n={},s={},r=0,o=1/0){t.boundingBox||t.computeBoundingBox(),Ln.set(t.boundingBox.min,t.boundingBox.max,i),Ln.needsUpdate=!0;const a=e.geometry,l=a.attributes.position,c=a.index,h=t.attributes.position,u=t.index,d=Di.getPrimitive(),p=Di.getPrimitive();let f=Fn,m=Rn,g=null,w=null;s&&(g=Un,w=jn);let y=1/0,_=null,b=null;return Vn.copy(i).invert(),Nn.matrix.copy(Vn),e.shapecast({boundsTraverseOrder:e=>Ln.distanceToBox(e),intersectsBounds:(e,t,i)=>i<y&&i<o&&(t&&(Nn.min.copy(e.min),Nn.max.copy(e.max),Nn.needsUpdate=!0),!0),intersectsRange:(n,s)=>{if(t.boundsTree){const a=t.boundsTree;return a.shapecast({boundsTraverseOrder:e=>Nn.distanceToBox(e),intersectsBounds:(e,t,i)=>i<y&&i<o,intersectsRange:(t,o)=>{for(let v=t,x=t+o;v<x;v++){const t=a.resolveTriangleIndex(v);Yi(p,3*t,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let t=n,i=n+s;t<i;t++){const i=e.resolveTriangleIndex(t);Yi(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,_=t,b=v),n<r)return!0}}}})}for(let o=0,a=wi(t);o<a;o++){Yi(p,3*o,u,h),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let t=n,i=n+s;t<i;t++){const i=e.resolveTriangleIndex(t);Yi(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,_=t,b=o),n<r)return!0}}}}),Di.releasePrimitive(d),Di.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(Vn),m.applyMatrix4(Vn),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function Wn(e,t,i){return null===e?null:(e.point.applyMatrix4(t.matrixWorld),e.distance=e.point.distanceTo(i.ray.origin),e.object=t,e)}const Hn=new Ei,Gn=new t.Ray,qn=new t.Vector3,Zn=new t.Matrix4,Yn=new t.Vector3,Xn=["getX","getY","getZ"];class Kn extends bi{static serialize(e,t={}){t={cloneBuffers:!0,...t};const i=e.geometry,n=e._roots,s=e._indirectBuffer,r=i.getIndex(),o={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(o.roots=n.map(e=>e.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(e,i,n={}){n={setIndex:!0,indirect:Boolean(e.indirectBuffer),...n};const{index:s,roots:r,indirectBuffer:o}=e;e.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(e){for(let t=0;t<e.length;t++){const i=e[t],n=new Uint32Array(i),s=new Uint16Array(i);for(let e=0,t=i.byteLength/gt;e<t;e++){const t=8*e;Tt(2*t,s)||(n[t+6]=n[t+6]/8-e)}}}(r));const a=new Kn(i,{...n,[yt]:!0});if(a._roots=r,a._indirectBuffer=o||null,n.setIndex){const n=i.getIndex();if(null===n){const n=new t.BufferAttribute(e.index,1,!1);i.setIndex(n)}else n.array!==s&&(n.array.set(s),n.needsUpdate=!0)}return a}get primitiveStride(){return 3}get resolveTriangleIndex(){return this.resolvePrimitiveIndex}constructor(e,t={}){t.maxLeafTris&&(console.warn('MeshBVH: "maxLeafTris" option has been deprecated. Use maxLeafSize, instead.'),t={...t,maxLeafSize:t.maxLeafTris}),super(e,t)}shiftTriangleOffsets(e){return super.shiftPrimitiveOffsets(e)}writePrimitiveBounds(e,t,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,o=n.index?n.index.array:null,a=3*(s?s[e]:e);let l=a+0,c=a+1,h=a+2;o&&(l=o[l],c=o[c],h=o[h]);for(let e=0;e<3;e++){const n=r[Xn[e]](l),s=r[Xn[e]](c),o=r[Xn[e]](h);let a=n;s<a&&(a=s),o<a&&(a=o);let u=n;s>u&&(u=s),o>u&&(u=o),t[i+e]=a,t[i+e+3]=u}return t}computePrimitiveBounds(e,t,i){const n=this.geometry,s=this._indirectBuffer,r=n.attributes.position,o=n.index?n.index.array:null,a=r.normalized;if(e<0||t+e-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=e,p=e+t;n<p;n++){const e=3*(s?s[n]:n),t=6*(n-d);let p=e+0,f=e+1,m=e+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 e=0;e<3;e++){let n,s,o;a?(n=r[u[e]](p),s=r[u[e]](f),o=r[u[e]](m)):(n=l[p+e],s=l[f+e],o=l[m+e]);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*e;i[t+g+0]=c+d,i[t+g+1]=d+(Math.abs(c)+d)*wt}}return i}raycastObject3D(e,t,i=[]){const{material:n}=e;if(void 0===n)return;Zn.copy(e.matrixWorld).invert(),Gn.copy(t.ray).applyMatrix4(Zn),Yn.setFromMatrixScale(e.matrixWorld),qn.copy(Gn.direction).multiply(Yn);const s=qn.length(),r=t.near/s,o=t.far/s;if(!0===t.firstHitOnly){let s=this.raycastFirst(Gn,n,r,o);s=Wn(s,e,t),s&&i.push(s)}else{const s=this.raycast(Gn,n,r,o);for(let n=0,r=s.length;n<r;n++){const r=Wn(s[n],e,t);r&&i.push(r)}}return i}refit(e=null){return(this.indirect?xn:Ki)(this,e)}raycast(e,i=t.FrontSide,n=0,s=1/0){const r=this._roots,o=[],a=this.indirect?Cn:en;for(let t=0,l=r.length;t<l;t++)a(this,t,i,e,o,n,s);return o}raycastFirst(e,i=t.FrontSide,n=0,s=1/0){const r=this._roots;let o=null;const a=this.indirect?Tn:sn;for(let t=0,l=r.length;t<l;t++){const r=a(this,t,i,e,n,s);null!=r&&(null==o||r.distance<o.distance)&&(o=r)}return o}intersectsGeometry(e,t){let i=!1;const n=this._roots,s=this.indirect?Bn:dn;for(let r=0,o=n.length;r<o&&(i=s(this,r,e,t),!i);r++);return i}shapecast(e){const t=Di.getPrimitive(),i=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?Ji:Xi});return Di.releasePrimitive(t),i}bvhcast(e,t,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=Di.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?e=>{const t=this.resolveTriangleIndex(e);Yi(r,3*t,o,a)}:e=>{Yi(r,3*e,o,a)},c=Di.getPrimitive(),h=e.geometry.index,u=e.geometry.attributes.position,d=e.indirect?t=>{const i=e.resolveTriangleIndex(t);Yi(c,3*i,h,u)}:e=>{Yi(c,3*e,h,u)};if(s){if(!(e instanceof Kn))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const i=(e,i,n,o,a,h,u,p)=>{for(let f=n,m=n+o;f<m;f++){d(f),c.a.applyMatrix4(t),c.b.applyMatrix4(t),c.c.applyMatrix4(t),c.needsUpdate=!0;for(let t=e,n=e+i;t<n;t++)if(l(t),r.needsUpdate=!0,s(r,c,t,f,a,h,u,p))return!0}return!1};if(n){const e=n;n=function(t,n,s,r,o,a,l,c){return!!e(t,n,s,r,o,a,l,c)||i(t,n,s,r,o,a,l,c)}}else n=i}return super.bvhcast(e,t,{intersectsRanges:n})}intersectsBox(e,t){return Hn.set(e.min,e.max,t),Hn.needsUpdate=!0,this.shapecast({intersectsBounds:e=>Hn.intersectsBox(e),intersectsTriangle:e=>Hn.intersectsTriangle(e)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,i={},n={},s=0,r=1/0){return(this.indirect?$n:vn)(this,e,t,i,n,s,r)}closestPointToPoint(e,t={},i=0,n=1/0){return function(e,t,i={},n=0,s=1/0){const r=n*n,o=s*s;let a=1/0,l=null;if(e.shapecast({boundsTraverseOrder:e=>(zi.copy(t).clamp(e.min,e.max),zi.distanceToSquared(t)),intersectsBounds:(e,t,i)=>i<a&&i<o,intersectsTriangle:(e,i)=>{e.closestPointToPoint(t,zi);const n=t.distanceToSquared(zi);return n<a&&(ki.copy(zi),a=n,l=i),n<r}}),a===1/0)return null;const c=Math.sqrt(a);return i.point?i.point.copy(ki):i.point=ki.clone(),i.distance=c,i.faceIndex=l,i}(this,e,t,i,n)}}const Qn=new t.Matrix4,Jn=new t.Ray,es=new Yt(()=>new t.Line3),ts=new t.Vector3,is=new t.Vector3,ns=new t.Box3,ss=["getX","getY","getZ"];class rs extends bi{get primitiveStride(){return 2}writePrimitiveBounds(e,t,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[e]:e)*r,h=(c+1)%l;a&&(c=a.getX(c),h=a.getX(h));for(let e=0;e<3;e++){const n=o[ss[e]](c),s=o[ss[e]](h),r=n<s?n:s,a=n>s?n:s;t[i+e]=r,t[i+e+3]=a}return t}shapecast(e){const t=es.getPrimitive(),i=super.shapecast({...e,intersectsPrimitive:e.intersectsLine,scratchPrimitive:t,iterate:os});return es.releasePrimitive(t),i}raycastObject3D(e,t,i=[]){const{matrixWorld:n}=e,{firstHitOnly:s}=t;Qn.copy(n).invert(),Jn.copy(t.ray).applyMatrix4(Qn);const r=t.params.Line.threshold/((e.scale.x+e.scale.y+e.scale.z)/3),o=r*r;let a=null,l=1/0;return this.shapecast({boundsTraverseOrder:e=>e.distanceToPoint(Jn.origin),intersectsBounds:e=>(ns.copy(e).expandByScalar(Math.abs(r)),Jn.intersectsBox(ns)?1:0),intersectsLine:(r,c)=>{if(Jn.distanceSqToSegment(r.start,r.end,ts,is)>o)return;ts.applyMatrix4(e.matrixWorld);const h=t.ray.origin.distanceTo(ts);h<t.near||h>t.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:e},s||i.push(a))}}),s&&a&&i.push(a),i}}function os(e,t,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=e,d=t+e;a<d;a++){let e=i.resolvePrimitiveIndex(a)*l,t=(e+1)%u;if(c&&(e=c.getX(e),t=c.getX(t)),o.start.fromBufferAttribute(h,e),o.end.fromBufferAttribute(h,t),n(o,a,s,r))return!0}return!1}const as={Mesh:t.Mesh.prototype.raycast,Line:t.Line.prototype.raycast,LineSegments:t.LineSegments.prototype.raycast,LineLoop:t.LineLoop.prototype.raycast,Points:t.Points.prototype.raycast,BatchedMesh:t.BatchedMesh.prototype.raycast},ls=new t.Mesh,cs=[];function hs(e,i){if(this.isBatchedMesh)us.call(this,e,i);else{const{geometry:n}=this;if(n.boundsTree)n.boundsTree.raycastObject3D(this,e,i);else{let n;if(this instanceof t.Mesh)n=as.Mesh;else if(this instanceof t.LineSegments)n=as.LineSegments;else if(this instanceof t.LineLoop)n=as.LineLoop;else if(this instanceof t.Line)n=as.Line;else{if(!(this instanceof t.Points))throw new Error("BVH: Fallback raycast function not found.");n=as.Points}n.call(this,e,i)}}}function us(e,i){if(this.boundsTrees){const n=this.boundsTrees,s=this._drawInfo||this._instanceInfo,r=this._drawRanges||this._geometryInfo,o=this.matrixWorld;ls.material=this.material,ls.geometry=this.geometry;const a=ls.geometry.boundsTree,l=ls.geometry.drawRange;null===ls.geometry.boundingSphere&&(ls.geometry.boundingSphere=new t.Sphere);for(let t=0,a=s.length;t<a;t++){if(!this.getVisibleAt(t))continue;const a=s[t].geometryIndex;if(ls.geometry.boundsTree=n[a],this.getMatrixAt(t,ls.matrixWorld).premultiply(o),!ls.geometry.boundsTree){this.getBoundingBoxAt(a,ls.geometry.boundingBox),this.getBoundingSphereAt(a,ls.geometry.boundingSphere);const e=r[a];ls.geometry.setDrawRange(e.start,e.count)}ls.raycast(e,cs);for(let e=0,n=cs.length;e<n;e++){const n=cs[e];n.object=this,n.batchId=t,i.push(n)}cs.length=0}ls.geometry.boundsTree=a,ls.geometry.drawRange=l,ls.material=null,ls.geometry=null}else as.BatchedMesh.call(this,e,i)}function ds(e={}){const{type:t=Kn}=e;return this.boundsTree=new t(this,e),this.boundsTree}function ps(){this.boundsTree=null}class fs extends f{static getWorker(){return e.FragmentsModels.getWorker()}static uuid="fef46874-46a3-461b-8c44-2922ab77c806";onDisposed=new d;onBeforeDispose=new d;onFragmentsLoaded=new d;baseCoordinationModel="";baseCoordinationMatrix=new c.Matrix4;enabled=!0;get initialized(){return!!this._core}_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}constructor(e){super(e),this.components.add(fs.uuid,this)}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,i){this._core=new e.FragmentsModels(t,i),this.core.onModelLoaded.add(async()=>{if(this._hasCoordinationModel)return;const e=[...this.list.values()][0];e&&(this.baseCoordinationModel=e.modelId,this.baseCoordinationMatrix=await e.getCoordinationMatrix())}),this.list.onItemDeleted.add(()=>{this.list.size>0||(this.baseCoordinationModel="",this.baseCoordinationMatrix=new c.Matrix4)})}async raycast(e){const t=[];for(const i of this.core.models.list.values())if(e.snappingClasses&&e.snappingClasses.length>0){const n=await i.raycastWithSnapping(e);if(n&&n.length>0)t.push(n[0]);else{const n=await i.raycast(e);n&&t.push(n)}}else{const n=await i.raycast(e);n&&t.push(n)}if(await Promise.all(t),0===t.length)return;let i=t[0],n=i.distance;for(let e=1;e<t.length;e++)t[e].distance<n&&(n=t[e].distance,i=t[e]);return i}async getPositions(e){const t=[],i=async(e,i)=>{const n=await e.getPositions(i);for(const e of n)t.push(e)},n=[];for(const t in e){const s=this.core.models.list.get(t);s&&n.push(i(s,Array.from(e[t])))}return await Promise.all(n),t}async getBBoxes(e){const t=[],i=async(e,i)=>{const n=await e.getBoxes(i);if(n)for(const e of n)t.push(e)},n=[];for(const t in e){const s=this.core.models.list.get(t);s&&n.push(i(s,Array.from(e[t])))}return await Promise.all(n),t}async highlight(e,t){await this.forEachModel(t,"highlight",e)}async getData(e,t){const i={};for(const[n,s]of Object.entries(e)){const e=this.list.get(n);if(!e)continue;if(0===s.size){i[n]=[];continue}const r=await e.getItemsData([...s],t);i[n]=r}return i}async resetHighlight(e){await this.forEachModel(e,"resetHighlight")}async forEachModel(e,t,...i){const n={};if(e)for(const t in e){const i=e[t];n[t]=Array.from(i)}else for(const e of this.core.models.list.keys())n[e]=void 0;const s=[];for(const e in n){const r=this.core.models.list.get(e);if(r){const o=n[e],a=r[t](o,...i);s.push(a)}}await Promise.all(s)}async guidsToModelIdMap(e){const t={};for(const[i,n]of this.list){const s=(await n.getLocalIdsByGuids([...e])).filter(e=>null!==e);t[i]=new Set(s)}return t}async modelIdMapToGuids(e){const t=[];for(const[i,n]of Object.entries(e)){const e=this.list.get(i);if(!e)continue;const s=(await e.getGuidsByLocalIds([...n])).filter(e=>null!==e);t.push(...s)}return t}applyBaseCoordinateSystem(e,t){const i=new c.Matrix4;return t&&i.copy(t.clone()).invert(),i.multiply(this.baseCoordinationMatrix),e.applyMatrix4(i),i}}function ms(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16}function gs(e){if(e&&e.aborted)throw new Error("VisibilityCuller: Process aborted via AbortSignal.")}class ws{constructor(e,t={}){const{pixelsPerMeter:i=.1}=t;this.pixelsPerMeter=i,this.renderer=e}async cull(e,i={}){const{signal:n=null}=i;gs(n),e=function(e){const t=new Set;return e.traverse(e=>{e.isMesh&&t.add(e)}),Array.from(t)}(e);const{renderer:s,pixelsPerMeter:r}=this,o=new t.Vector3,a=new t.OrthographicCamera,l=new t.Box3,c=new t.WebGLRenderTarget(1,1);l.makeEmpty(),e.forEach(e=>{l.expandByObject(e)}),l.getSize(o);const h=Math.min(s.capabilities.maxTextureSize,8192),u=Math.ceil(o.x/r),d=Math.ceil(o.z/r),p=Math.ceil(u/h),f=Math.ceil(d/h);c.setSize(Math.ceil(u/p),Math.ceil(d/f));const m=.01*Math.max(o.y,1);a.rotation.x=-Math.PI/2,a.near=0,a.far=o.y+2*m,a.position.y=l.max.y+m;const g=new t.Scene,w=new Map,y=new Map,_=[];for(let t=0;t<e.length;t++){const i=e[t];w.set(i,i.material),y.set(i,i.parent);const n=new ys;n.objectId=t,_.push(n),i.material=n,g.add(i)}const b=s.getClearColor(new t.Color),v=s.getClearAlpha(),x=s.getRenderTarget(),C=s.autoClear,S=new Uint8Array(c.width*c.height*4),A=new Set,T=o.x/p,P=o.z/f;let M=!1;const E=()=>{if(!M){M=!0,n&&n.removeEventListener("abort",E);for(const t of e){t.material=w.get(t);const e=y.get(t);e?e.add(t):g.remove(t)}s.setClearColor(b,v),s.setRenderTarget(x),s.autoClear=C;for(const e of _)e.dispose();c.dispose()}};n&&n.addEventListener("abort",E);try{s.autoClear=!0,s.setClearColor(0,0),s.setRenderTarget(c);for(let t=0;t<p;t++)for(let i=0;i<f;i++){const r=l.min.x+T*t,o=r+T,h=l.min.z+P*i,u=(r+o)/2,d=(h+(h+P))/2;a.position.set(u,l.max.y+m,d);const p=T/2,f=P/2;a.left=-p,a.right=p,a.top=f,a.bottom=-f,a.updateProjectionMatrix(),gs(n),s.render(g,a);const w=await s.readRenderTargetPixelsAsync(c,0,0,c.width,c.height,S);gs(n);for(let t=0,i=w.length;t<i;t+=4){if(0===w[t+3])continue;const i=ms(w,t);A.add(e[i])}}}finally{E()}return Array.from(A)}}class ys extends t.ShaderMaterial{get objectId(){return this._objectId}set objectId(e){var t,i;this._objectId=e,t=e,(i=this.uniforms.objectId.value).x=(255&t)/255,i.y=(t>>8&255)/255,i.z=(t>>16&255)/255,i.w=1}constructor(e){super({glslVersion:t.GLSL3,blending:t.NoBlending,side:t.DoubleSide,uniforms:{objectId:{value:new t.Vector4}},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(e)}}const _s=1e-16,bs=new t.Vector3(0,1,0),vs=new t.Vector3;function xs(e){return e.delta(vs).normalize(),Math.abs(vs.dot(bs))>=1-_s}function Cs(e,t){const{start:i,end:n}=t,s=e.points;let r=!1,o=!1;for(let e=0;e<3;e++){const t=s[e];if(!r&&i.distanceToSquared(t)<=_s&&(r=!0),!o&&n.distanceToSquared(t)<=_s&&(o=!0),r&&o)return!0}return r&&o}const Ss=new t.Line3;function As(e,t,i=!1,n=[]){let s=[[0,1]];for(let e=0,i=t.length;e<i;e++){const i=s[e],n=t[e];i[1]=n[0],s.push([n[1],1])}i&&([t,s]=[s,t]);for(let t=0,i=s.length;t<i;t++){const{start:i,end:r}=e;Ss.start.lerpVectors(i,r,s[t][0]),Ss.end.lerpVectors(i,r,s[t][1]),n.push(new Float32Array([Ss.start.x,Ss.start.y,Ss.start.z,Ss.end.x,Ss.end.y,Ss.end.z]))}return n}const Ts=new t.Vector3(0,1,0),Ps=new t.Vector3,Ms=new t.Vector3,Es=new t.Vector3,Is=new t.Triangle;function*Ds(e,i=[],n={}){const{projectionDirection:s=Ts,thresholdAngle:r=1,iterationTime:o=30}=n,a=Math.pow(10,4),l=Math.cos(t.MathUtils.DEG2RAD*r),c=e.getIndex(),h=e.getAttribute("position"),u=c?c.count:h.count,d=[0,0,0],p=["a","b","c"],f=new Array(3),m={};let g=performance.now();for(let e=0;e<u;e+=3){performance.now()-g>o&&(yield,g=performance.now()),c?(d[0]=c.getX(e),d[1]=c.getX(e+1),d[2]=c.getX(e+2)):(d[0]=e,d[1]=e+1,d[2]=e+2);const{a:n,b:r,c:u}=Is;if(n.fromBufferAttribute(h,d[0]),r.fromBufferAttribute(h,d[1]),u.fromBufferAttribute(h,d[2]),Is.getNormal(Es),f[0]=`${Math.round(n.x*a)},${Math.round(n.y*a)},${Math.round(n.z*a)}`,f[1]=`${Math.round(r.x*a)},${Math.round(r.y*a)},${Math.round(r.z*a)}`,f[2]=`${Math.round(u.x*a)},${Math.round(u.y*a)},${Math.round(u.z*a)}`,f[0]!==f[1]&&f[1]!==f[2]&&f[2]!==f[0])for(let e=0;e<3;e++){const n=(e+1)%3,r=f[e],o=f[n],a=Is[p[e]],c=Is[p[n]],h=`${r}_${o}`,u=`${o}_${r}`;if(u in m&&m[u]){const e=m[u].normal,n=Es.dot(e)<=l;let r=!1;if(null!==s){let t=s.dot(Es);t=Math.abs(t)<1e-10?0:t;let i=s.dot(e);i=Math.abs(i)<1e-10?0:i,r=Math.sign(t)!==Math.sign(i)}if(n||r){const e=new t.Line3;e.start.copy(a),e.end.copy(c),i.push(e)}m[u]=null}else h in m||(m[h]={index0:d[e],index1:d[n],normal:Es.clone()})}}for(const e in m)if(m[e]){const{index0:n,index1:s}=m[e];Ps.fromBufferAttribute(h,n),Ms.fromBufferAttribute(h,s);const r=new t.Line3;r.start.copy(Ps),r.end.copy(Ms),i.push(r)}return i}const zs=new t.Line3;function ks(e,t,i,n=[]){return e.bvhcast(t,i,{intersectsTriangles:(e,t)=>!function(e,t){const i=["a","b","c"];let n=0;for(let s=0;s<3;s++)for(let r=0;r<3;r++){Bs(e[i[s]],t[i[r]])&&n++}return n>=2}(e,t)&&(e.needsUpdate&&e.update(),t.needsUpdate&&t.update(),!(Math.abs(e.plane.normal.dot(t.plane.normal))>.999999)&&void(!e.intersectsTriangle(t,zs,!0)||Cs(e,zs)||Cs(t,zs)||n.push(zs.clone())))}),n}function Bs(e,t){return e.distanceTo(t)<1e-10}function Os(e){Vs(e);let t=[];return e.traverse(e=>{e.geometry&&e.visible&&t.push(e)}),t}const Vs=e=>{if(void 0===e)return;const t=[...e.children];for(const i of t)void 0===i?e.children.splice(e.children.indexOf(i),1):Vs(i)},Ls=new t.Matrix4,Ns=new t.Matrix4;class Fs{constructor(){this.projectionDirection=new t.Vector3(0,1,0),this.thresholdAngle=50,this.iterationTime=30}getEdges(...e){const t=this.iterationTime;this.iterationTime=1/0;const i=this.getEdgesGenerator(...e).next().value;return this.iterationTime=t,i}*getEdgesGenerator(e,i=[],n=null){const{projectionDirection:s,thresholdAngle:r,iterationTime:o}=this;if(e.isObject3D){const a=Os(e);let l=null;s&&(l=new t.Vector3);let c=performance.now();for(let e=0;e<a.length;e++){performance.now()-c>o&&(yield,c=performance.now());const t=a[e];l&&(Ns.copy(t.matrixWorld).invert(),l.copy(s).transformDirection(Ns).normalize());const h=yield*Ds(t.geometry,[],{projectionDirection:l,thresholdAngle:r,iterationTime:o});Rs(h,t.matrixWorld);for(let e=0;e<h.length;e++)i.push(h[e]);if(null!==n)for(let e=0;e<h.length;e++)n.push(t)}return i}return yield*Ds(e,i,{projectionDirection:s,thresholdAngle:r,iterationTime:o})}getIntersectionEdges(...e){const t=this.iterationTime;this.iterationTime=1/0;const i=this.getIntersectionEdgesGenerator(...e).next().value;return this.iterationTime=t,i}*getIntersectionEdgesGenerator(e,t=[],i=null){const{iterationTime:n}=this;if(e.isObject3D){const s=Os(e),r=new Map;let o=performance.now();for(let e=0;e<s.length;e++){performance.now()-o>n&&(yield,o=performance.now());const t=s[e].geometry;if(!r.has(t)){const e=t.boundsTree||new Kn(t,{maxLeafSize:1});r.set(t,e)}}o=performance.now();for(let e=0;e<s.length;e++)for(let a=e;a<s.length;a++){performance.now()-o>n&&(yield,o=performance.now());const l=s[e],c=s[a],h=r.get(l.geometry),u=r.get(c.geometry);Ls.copy(l.matrixWorld).invert().multiply(c.matrixWorld);const d=ks(h,u,Ls,[]);Rs(d,l.matrixWorld);for(let e=0;e<d.length;e++)t.push(d[e]);if(null!==i)for(let e=0;e<d.length;e++)i.push(l)}return t}{let i;return e.isBufferGeometry?i=e.boundsTree||new Kn(e,{maxLeafSize:1}):(i=e,e=i.geometry),Ls.identity(),ks(i,i,Ls,t)}}}function Rs(e,t,i=1e-6){for(let n=0;n<e.length;n++){const s=e[n];s.applyMatrix4(t),s.start.y+=i,s.end.y+=i}}class Us extends mi{get lines(){return this.primitiveBuffer}constructor(e,t){super(t),this.primitiveBuffer=e,this.primitiveBufferStride=1,this.heightOffset=t.heightOffset??1e3,this.init(t)}writePrimitiveBounds(e,t,i){const{primitiveBuffer:n,heightOffset:s}=this,{start:r,end:o}=n[e];t[i+0]=Math.min(r.x,o.x),t[i+1]=Math.min(r.y,o.y),t[i+2]=Math.min(r.z,o.z),t[i+3]=Math.max(r.x,o.x),t[i+4]=Math.max(r.y,o.y)+s,t[i+5]=Math.max(r.z,o.z)}getRootRanges(){return[{offset:0,count:this.primitiveBuffer.length}]}}const js=new t.Vector3(0,1,0),$s=new t.Plane,Ws=new t.Vector3,Hs=new t.Vector3;function Gs(e,i,n){e.needsUpdate&&e.update(),$s.copy(e.plane),$s.normal.dot(js)<0&&($s.normal.multiplyScalar(-1),$s.constant*=-1);const s=$s.distanceToPoint(i.start),r=$s.distanceToPoint(i.end),o=Math.abs(s)<1e-16,a=s<0,l=r<0;if(i.delta(Hs).normalize(),Math.abs($s.normal.dot(Hs))<1e-16)return!(o||!a)&&(n.copy(i),!0);if(a&&l)return n.copy(i),!0;if(!a&&!l)return!1;{const e=t.MathUtils.mapLinear(0,s,r,0,1);if(i.at(e,Ws),a)return n.start.copy(i.start),n.end.copy(Ws),!0;if(l)return n.end.copy(i.end),n.start.copy(Ws),!0}return!1}const qs=new t.Plane,Zs=new t.Vector3,Ys=new t.Vector3,Xs=new Mi,Ks=new t.Line3,Qs=new t.Line3,Js=new t.Vector3,er=new t.Vector3,tr=new t.Vector3;function ir(e,i,n=new t.Line3){if(Xs.copy(i),Xs.a.y=0,Xs.b.y=0,Xs.c.y=0,Xs.update(),Ks.copy(e),Ks.start.y=0,Ks.end.y=0,Xs.getArea()<=1e-16)return null;const s=Ks.distance();Ks.delta(Js).divideScalar(s),er.copy(Js).cross(Xs.plane.normal).normalize(),qs.setFromNormalAndCoplanarPoint(er,Ks.start);let r=0;const{points:o}=Xs;for(let e=0;e<3;e++){const t=o[e],i=o[(e+1)%3],n=qs.distanceToPoint(t),s=qs.distanceToPoint(i),a=Math.abs(n)<1e-16,l=Math.abs(s)<1e-16;let c=!1;if(!a&&!l&&n*s<0){const e=n/(n-s);Zs.lerpVectors(t,i,e),c=!0}if((c&&!l||a)&&(a&&!c&&Zs.copy(t),0===r?Qs.start.copy(Zs):Qs.end.copy(Zs),r++,2===r))break}if(2===r){if(Qs.delta(tr).normalize(),Js.dot(tr)<0){const e=Qs.start;Qs.start=Qs.end,Qs.end=e}const t=0,i=Ys.subVectors(Ks.end,Ks.start).dot(Js),r=Ys.subVectors(Qs.start,Ks.start).dot(Js),o=Ys.subVectors(Qs.end,Ks.start).dot(Js);return i<=r||o<=t?null:(e.at(Math.max(t,r)/s,n.start),e.at(Math.min(i,o)/s,n.end),n)}return null}const nr=new t.Vector3,sr=new t.Vector3,rr=new t.Vector3;function or(e,t,i){const n=function(e,t){e.delta(nr),sr.subVectors(t.start,e.start),rr.subVectors(t.end,e.start);const i=nr.length();let n=sr.length()/i,s=rr.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]}(e,t);return!!n&&(ar(n,i),!0)}function ar(e,t){let[i,n]=e,s=0,r=t.length;for(;s<r;){const e=s+r>>>1;t[e][0]<=i?s=e+1:r=e}let o=Math.max(0,s-1),a=0;for(let e=o,s=t.length;e<s;e++){const[s,r]=t[e];if(i<=r&&n>=s)i=Math.min(s,i),n=Math.max(r,n),a++;else{if(!(i>=s))break;o=e+1}}t.splice(o,a,[i,n])}const lr=new t.Vector3(0,1,0),cr=new t.Line3,hr=new t.Line3,ur=new Mi;function dr(e,i,n,s,r=null){const{geometry:o,matrixWorld:a,material:l}=n,c=l.side,h=a.determinant()<0,u=e.lines;e.bvhcast(i,a,{intersectsRanges:(e,i,n,l)=>{r&&(r.candidates+=i*l);for(let d=n,p=l+n;d<p;d++){let n=3*d+0,l=3*d+1,p=3*d+2;o.index&&(n=o.index.getX(n),l=o.index.getX(l),p=o.index.getX(p));const{a:f,b:m,c:g}=ur;if(f.fromBufferAttribute(o.attributes.position,n).applyMatrix4(a),m.fromBufferAttribute(o.attributes.position,l).applyMatrix4(a),g.fromBufferAttribute(o.attributes.position,p).applyMatrix4(a),ur.needsUpdate=!0,ur.update(),c!==t.DoubleSide){if(ur.plane.normal.dot(lr)!==h===(c===t.BackSide)){r&&(r.backFaceCulled+=i);continue}}const w=Math.max(f.y,m.y,g.y),y=Math.min(f.y,m.y,g.y),_=ur.plane.normal;let b=_.x,v=_.y,x=_.z,C=ur.plane.constant;v<0&&(b=-b,v=-v,x=-x,C=-C);for(let t=e,n=i+e;t<n;t++){const e=u[t],i=Math.min(e.start.y,e.end.y),n=Math.max(e.start.y,e.end.y);if(w<=i){r&&r.yBoundsCulled++;continue}const o=e.end.x-e.start.x,a=e.end.z-e.start.z,l=o*o+a*a;if(l>1e-20){const t=1/Math.sqrt(l),i=o*t,n=a*t,s=-n,c=i,h=f.x-e.start.x,u=f.z-e.start.z,d=m.x-e.start.x,p=m.z-e.start.z,w=g.x-e.start.x,y=g.z-e.start.z,_=h*i+u*n,b=d*i+p*n,v=w*i+y*n,x=1/t,C=Math.min(_,b,v);if(Math.max(_,b,v)<0||C>x){r&&r.xzBoundsCulled++;continue}const S=h*s+u*c,A=d*s+p*c,T=w*s+y*c,P=Math.min(S,A,T),M=Math.max(S,A,T);if(P>0||M<0){r&&r.xzBoundsCulled++;continue}}const c=b*e.start.x+v*e.start.y+x*e.start.z+C,h=b*e.end.x+v*e.end.y+x*e.end.z+C;if(c>=0&&h>=0)r&&r.planeTrimCulled++;else if(Cs(ur,e))r&&r.triangleEdgeCulled++;else{if(n<y)cr.copy(e);else if(!Gs(ur,e,cr)){r&&r.planeTrimCulled++;continue}cr.distance()<1e-10?r&&r.distThresholdCulled++:ir(cr,ur,hr)?(r&&r.used++,or(e,hr,s[t])):r&&r.noOverlapCulled++}}}}})}ur.update=()=>{ur.plane.setFromCoplanarPoints(...ur.points)};let pr=!1;const fr={},mr={};let gr=null,wr=0,yr=0;const _r={get enabled(){return pr},set enabled(e){pr=e},reset(){for(const e in fr)delete fr[e];for(const e in mr)delete mr[e];gr=null,wr=0,yr=0},setStat(e,t){mr[e]=t},startTotal(){pr&&(yr=performance.now())},startStep(e){pr&&(null!==gr&&this.endStep(),gr=e,wr=performance.now())},endStep(){if(!pr||null===gr)return;const e=performance.now()-wr;fr[gr]=e,gr=null},printSummary(){if(!pr)return;null!==gr&&this.endStep();const e=performance.now()-yr;console.log("\n=== Projection Summary ==="),console.log(`Total time: ${e.toFixed(1)}ms\n`);for(const[t,i]of Object.entries(fr)){const n=(i/e*100).toFixed(1);console.log(` ${t}: ${i.toFixed(1)}ms (${n}%)`)}if(Object.keys(mr).length>0){console.log("\n--- Stats ---");for(const[e,t]of Object.entries(mr))console.log(` ${e}: ${t}`)}console.log("")}},br=1e-5,vr=1e-16,xr=1e-16;function Cr(e,t,i,n,s){e.bvhcast(t,i.matrixWorld,{intersectsRanges:(e,t,i,r)=>{n._edgeOffsets.push(e),n._edgeCounts.push(t),n._meshOffsets.push(i),n._meshCounts.push(r),n._meshIndex.push(s),n.groupCount++}})}let Sr=null;async function Ar(e,t,i,s,r=null){const o=await async function(){return null===Sr&&(Sr=new h.WebGPURenderer,await Sr.init()),Sr}();e._edgeOffsets&&(e.edgeOffsets=new Uint32Array(e._edgeOffsets),e.edgeCounts=new Uint32Array(e._edgeCounts),e.meshOffsets=new Uint32Array(e._meshOffsets),e.meshCounts=new Uint32Array(e._meshCounts),e.meshIndex=new Uint32Array(e._meshIndex),e._edgeOffsets=null,e._edgeCounts=null,e._meshOffsets=null,e._meshCounts=null,e._meshIndex=null);const a=n.instancedArray(function(e){const t=new Float32Array(6*e.length);for(let i=0;i<e.length;i++){const n=e[i];t[6*i+0]=n.start.x,t[6*i+1]=n.start.y,t[6*i+2]=n.start.z,t[6*i+3]=n.end.x,t[6*i+4]=n.end.y,t[6*i+5]=n.end.z}return t}(i.lines),"float");_r.enabled&&console.log("Number of meshes:",t.length),_r.enabled&&console.log("Group count:",e.groupCount);const l=[];{let e=0;for(;e<t.length;){let i=e,n=0;for(;i<t.length;){const s=t[i].geometry,r=s.index?s.index.count/3:s.attributes.position.count/3;if(i>e&&(i-e>=1e3||n+r>1e5))break;n+=r,i++}l.push({start:e,end:i}),e=i}}_r.enabled&&console.log(`Split ${t.length} meshes into ${l.length} batches`);let c=0,u=0,d=0,p=0,f=0;for(let i=0;i<l.length;i++){const{start:h,end:m}=l[i],g=m-h;_r.enabled&&console.log(`Processing batch ${i+1}/${l.length} (meshes ${h}-${m-1})`);let w=0,y=0;const _=[];for(let e=h;e<m;e++){const i=t[e].geometry;_.push(y/3),w+=i.attributes.position.array.length,y+=i.index.array.length}const b=new Float32Array(w),v=new Uint32Array(y);let x=0,C=0,S=0;for(let e=h;e<m;e++){const i=t[e].geometry,n=i.attributes.position.array,s=i.index.array;b.set(n,x),x+=n.length;for(let e=0;e<s.length;e++)v[C+e]=s[e]+S;C+=s.length,S+=i.attributes.position.count}const A=new Float32Array(16*g);for(let e=h;e<m;e++){const i=e-h;A.set(t[e].matrixWorld.elements,16*i)}const T=[];for(let t=0;t<e.groupCount;t++){const i=e.meshIndex[t];if(i>=h&&i<m){const n=i-h,s=_[n]+e.meshOffsets[t];T.push({edgeOffset:e.edgeOffsets[t],edgeCount:e.edgeCounts[t],triOffset:s,triCount:e.meshCounts[t],meshIdx:n})}}if(0===T.length){_r.enabled&&console.log(` Batch ${i+1}: no groups, skipping`);continue}const P=new Uint32Array(5*T.length);for(let e=0;e<T.length;e++){const t=T[e],i=5*e;P[i+0]=t.edgeOffset,P[i+1]=t.edgeCount,P[i+2]=t.triOffset,P[i+3]=t.triCount,P[i+4]=t.meshIdx}let M=0;for(let e=0;e<T.length;e++)M+=T[e].edgeCount*T[e].triCount;r&&(r.candidates+=M);let E=Math.min(Math.ceil(.1*M),2e6),I=Math.max(E,1e4);_r.enabled&&console.log(` Batch ${i+1}: ${T.length} groups, ${w/3} vertices, ${y/3} triangles, ${M} pairs, buffer for ${I} overlaps`);const D=performance.now(),z=n.instancedArray(b,"float"),k=n.instancedArray(v,"uint"),B=n.instancedArray(A,"float"),O=n.instancedArray(P,"uint");let V=n.instancedArray(new Uint32Array([0]),"uint").toAtomic(),L=n.instancedArray(new Float32Array(3*I),"float");p+=performance.now()-D;const N=performance.now(),F=n.Fn(()=>{const e=n.instanceIndex.mul(5),t=O.element(e),i=O.element(e.add(1)),s=O.element(e.add(2)),r=O.element(e.add(3)),o=O.element(e.add(4)).mul(16),l=n.mat4(B.element(o),B.element(o.add(1)),B.element(o.add(2)),B.element(o.add(3)),B.element(o.add(4)),B.element(o.add(5)),B.element(o.add(6)),B.element(o.add(7)),B.element(o.add(8)),B.element(o.add(9)),B.element(o.add(10)),B.element(o.add(11)),B.element(o.add(12)),B.element(o.add(13)),B.element(o.add(14)),B.element(o.add(15)));n.Loop({start:n.int(0),end:r.toInt(),type:"int",condition:"<",name:"triIdx"},({triIdx:e})=>{const r=s.add(e.toUint()).mul(3),o=k.element(r),c=k.element(r.add(1)),h=k.element(r.add(2)),u=n.vec3(z.element(o.mul(3)),z.element(o.mul(3).add(1)),z.element(o.mul(3).add(2))),d=n.vec3(z.element(c.mul(3)),z.element(c.mul(3).add(1)),z.element(c.mul(3).add(2))),p=n.vec3(z.element(h.mul(3)),z.element(h.mul(3).add(1)),z.element(h.mul(3).add(2))),f=l.mul(n.vec4(u,n.float(1))).xyz,m=l.mul(n.vec4(d,n.float(1))).xyz,g=l.mul(n.vec4(p,n.float(1))).xyz,w=m.sub(f),y=g.sub(f),_=n.cross(w,y),b=_.dot(_);n.If(b.lessThan(n.float(4e-16*vr)),()=>{n.Continue()}),n.If(_.y.lessThan(0),()=>{n.Continue()});const v=n.max(f.y,n.max(m.y,g.y));n.Loop({start:n.int(0),end:i.toInt(),type:"int",condition:"<",name:"edgeIdx"},({edgeIdx:e})=>{const i=t.add(e.toUint()),s=i.mul(6),r=n.vec3(a.element(s),a.element(s.add(1)),a.element(s.add(2))),o=n.vec3(a.element(s.add(3)),a.element(s.add(4)),a.element(s.add(5))),l=n.min(r.y,o.y);n.If(v.lessThanEqual(l),()=>{n.Continue()});const c=n.normalize(_),h=c.dot(f).negate(),u=c.y.lessThan(0),d=n.select(u,c.negate(),c),p=n.select(u,h.negate(),h),w=d.dot(r).add(p),y=d.dot(o).add(p),b=w.lessThan(0),x=y.lessThan(0),C=n.abs(w).lessThan(n.float(br)),S=b.not().and(x.not()),A=y.sub(w),T=n.abs(A).lessThan(n.float(br)),P=T.and(C.or(b.not()));n.If(P,()=>{n.Continue()}),n.If(S.and(T.not()),()=>{n.Continue()});const M=w.negate().div(A),E=n.mix(r,o,M),D=n.vec3(n.select(T.or(b),r.x,E.x),n.select(T.or(b),r.y,E.y),n.select(T.or(b),r.z,E.z)),z=n.vec3(n.select(T.or(x),o.x,E.x),n.select(T.or(x),o.y,E.y),n.select(T.or(x),o.z,E.z)),k=z.sub(D),B=k.dot(k);n.If(B.lessThan(n.float(br)),()=>{n.Continue()});const O=r.sub(f),N=r.sub(m),F=r.sub(g),R=o.sub(f),U=o.sub(m),j=o.sub(g),$=O.dot(O).lessThanEqual(n.float(br)),W=N.dot(N).lessThanEqual(n.float(br)),H=F.dot(F).lessThanEqual(n.float(br)),G=R.dot(R).lessThanEqual(n.float(br)),q=U.dot(U).lessThanEqual(n.float(br)),Z=j.dot(j).lessThanEqual(n.float(br)),Y=$.or(W).or(H),X=G.or(q).or(Z),K=Y.and(X);n.If(K,()=>{n.Continue()});const Q=n.vec3(f.x,n.float(0),f.z),J=n.vec3(m.x,n.float(0),m.z),ee=n.vec3(g.x,n.float(0),g.z),te=n.vec3(D.x,n.float(0),D.z),ie=n.vec3(z.x,n.float(0),z.z),ne=n.vec3(r.x,n.float(0),r.z),se=n.vec3(o.x,n.float(0),o.z).sub(ne),re=se.dot(se);n.If(re.lessThan(n.float(br)),()=>{n.Continue()});const oe=re.sqrt(),ae=J.sub(Q),le=ee.sub(Q),ce=n.cross(ae,le),he=ce.dot(ce);n.If(he.lessThanEqual(n.float(4e-16*vr)),()=>{n.Continue()});const ue=ie.sub(te),de=ue.dot(ue);n.If(de.lessThan(n.float(br)),()=>{n.Continue()});const pe=de.sqrt(),fe=ue.div(pe),me=se.div(oe),ge=n.normalize(ce),we=n.cross(fe,ge),ye=n.float(0).toVar(),_e=n.float(0).toVar(),be=n.float(0).toVar(),ve=n.float(0).toVar(),xe=n.uint(0).toVar(),Ce=we.dot(Q.sub(te)),Se=we.dot(J.sub(te)),Ae=n.abs(Ce).lessThan(n.float(xr)),Te=n.abs(Se).lessThan(n.float(xr)),Pe=Ae.not().and(Te.not()).and(Ce.mul(Se).lessThan(0));n.If(Pe,()=>{const e=Ce.div(Ce.sub(Se)),t=n.mix(Q.x,J.x,e),i=n.mix(Q.z,J.z,e);n.If(xe.equal(0),()=>{ye.assign(t),_e.assign(i)}).Else(()=>{be.assign(t),ve.assign(i)}),xe.addAssign(1)}).ElseIf(Ae,()=>{n.If(xe.equal(0),()=>{ye.assign(Q.x),_e.assign(Q.z)}).Else(()=>{be.assign(Q.x),ve.assign(Q.z)}),xe.addAssign(1)});const Me=Se,Ee=we.dot(ee.sub(te)),Ie=Te,De=n.abs(Ee).lessThan(n.float(xr)),ze=Ie.not().and(De.not()).and(Me.mul(Ee).lessThan(0));n.If(xe.lessThan(2),()=>{n.If(ze,()=>{const e=Me.div(Me.sub(Ee)),t=n.mix(J.x,ee.x,e),i=n.mix(J.z,ee.z,e);n.If(xe.equal(0),()=>{ye.assign(t),_e.assign(i)}).Else(()=>{be.assign(t),ve.assign(i)}),xe.addAssign(1)}).ElseIf(Ie.and(Pe.not()).and(Ae.not()),()=>{n.If(xe.equal(0),()=>{ye.assign(J.x),_e.assign(J.z)}).Else(()=>{be.assign(J.x),ve.assign(J.z)}),xe.addAssign(1)})});const ke=Ee,Be=Ce,Oe=De,Ve=Ae,Le=Oe.not().and(Ve.not()).and(ke.mul(Be).lessThan(0));n.If(xe.lessThan(2),()=>{n.If(Le,()=>{const e=ke.div(ke.sub(Be)),t=n.mix(ee.x,Q.x,e),i=n.mix(ee.z,Q.z,e);n.If(xe.equal(0),()=>{ye.assign(t),_e.assign(i)}).Else(()=>{be.assign(t),ve.assign(i)}),xe.addAssign(1)}).ElseIf(Oe.and(ze.not()).and(Ie.not()),()=>{n.If(xe.equal(0),()=>{ye.assign(ee.x),_e.assign(ee.z)}).Else(()=>{be.assign(ee.x),ve.assign(ee.z)}),xe.addAssign(1)})}),n.If(xe.notEqual(2),()=>{n.Continue()});const Ne=n.vec3(ye,n.float(0),_e),Fe=n.vec3(be,n.float(0),ve).sub(Ne).dot(fe),Re=n.vec3(ye,n.float(0),_e).toVar(),Ue=n.vec3(be,n.float(0),ve).toVar();n.If(Fe.lessThan(0),()=>{const e=ye,t=_e;Re.x.assign(be),Re.z.assign(ve),Ue.x.assign(e),Ue.z.assign(t)});const je=n.float(0),$e=pe,We=Re.sub(te).dot(fe),He=Ue.sub(te).dot(fe),Ge=$e.lessThanEqual(We).or(He.lessThanEqual(je));n.If(Ge,()=>{n.Continue()});const qe=n.max(je,We),Ze=n.min($e,He),Ye=te.add(fe.mul(qe)),Xe=te.add(fe.mul(Ze)),Ke=Ye.sub(ne).dot(me).div(oe),Qe=Xe.sub(ne).dot(me).div(oe),Je=n.max(n.float(0),n.min(n.float(1),Ke)),et=n.max(n.float(0),n.min(n.float(1),Qe)),tt=n.abs(et.sub(Je));n.If(tt.lessThanEqual(n.float(xr)),()=>{n.Continue()});const it=n.atomicAdd(V.element(0),1);n.If(it.lessThan(n.uint(I)),()=>{const e=it.mul(3);L.element(e).assign(i.toFloat()),L.element(e.add(1)).assign(Je),L.element(e.add(2)).assign(et)})})})})().compute(T.length);f+=performance.now()-N;const R=performance.now();await o.computeAsync(F),c+=performance.now()-R;const U=performance.now(),j=await o.getArrayBufferAsync(V.value),$=new Uint32Array(j)[0];if(r&&(r.used+=Math.min($,I)),_r.enabled&&console.log(` Batch ${i+1}: ${$} overlaps found (capacity: ${I})`),$>I&&_r.enabled&&console.warn(` WARNING: Overlap buffer overflow! ${$} > ${I}. Some occlusion data lost.`),$>0){const e=await o.getArrayBufferAsync(L.value),t=new Float32Array(e);u+=performance.now()-U;const i=performance.now(),n=Math.min($,I);for(let e=0;e<n;e++){const i=3*e,n=Math.round(t[i]);ar([t[i+1],t[i+2]],s[n])}d+=performance.now()-i,_r.enabled&&console.log(` Processed ${n} overlaps into hiddenOverlapMap`)}else u+=performance.now()-U}o.dispose(),Sr=null;const m=p+f+c+u+d;_r.enabled&&(console.log(`WebGPU timing breakdown (total: ${m.toFixed(1)}ms):`),console.log(` Buffer creation: ${p.toFixed(1)}ms`),console.log(` Shader build: ${f.toFixed(1)}ms`),console.log(` GPU compute: ${c.toFixed(1)}ms`),console.log(` Readback: ${u.toFixed(1)}ms`),console.log(` CPU merge: ${d.toFixed(1)}ms`))}const Tr=new t.Vector3(0,1,0);function Pr(e,i=null){const n=new Float32Array(6*e.length);let s=0;for(let t=0,i=e.length;t<i;t++){const i=e[t];n[s++]=i[0],n[s++]=0,n[s++]=i[2],n[s++]=i[3],n[s++]=0,n[s++]=i[5]}const r=new t.BufferGeometry,o=new t.BufferAttribute(n,3,!0);if(r.setAttribute("position",o),i){const n=new Float32Array(2*e.length);for(let e=0,t=i.length;e<t;e++)n[2*e]=i[e],n[2*e+1]=i[e];r.setAttribute("group",new t.BufferAttribute(n,1))}return r}class Mr{constructor(e,t=!0){this.meshes=Os(e),this.bvhs=new Map,this.visibleEdges=[],this.hiddenEdges=[],this.visibleGroupIndices=[],this.hiddenGroupIndices=[],this.groupKeyToIndex=null,this.hasGroups=!1,this.iterationTime=30,this.useWebGPU=t}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 Pr(this.visibleEdges,this.groupKeyToIndex?this.visibleGroupIndices:null)}getHiddenLineGeometry(){return Pr(this.hiddenEdges,this.groupKeyToIndex?this.hiddenGroupIndices:null)}getGroupKeys(){return this.groupKeyToIndex?Object.fromEntries(this.groupKeyToIndex):{}}addEdges(...e){const t=this.iterationTime;this.iterationTime=1/0;const i=this.addEdgesGenerator(...e).next().value;return this.iterationTime=t,i}*addEdgesGenerator(e,t={}){const{meshes:i,bvhs:n,visibleEdges:s,hiddenEdges:r,iterationTime:o}=this;let a=performance.now();_r.startStep("Building mesh BVH");for(let e=0;e<i.length;e++){performance.now()-a>o&&(yield,a=performance.now());const t=i[e].geometry;if(!n.has(t)){const e=t.boundsTree||new Kn(t);n.set(t,e)}}let l=0;for(let e=0;e<i.length;e++){const t=i[e].geometry;l+=t.index?t.index.count/3:t.attributes.position.count/3}const c={};for(let t=0;t<e.length;t++)c[t]=[];_r.startStep("Building line BVH");const h=new Us(e,{maxLeafSize:2,strategy:2});_r.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:e.length,totalTriangles:l},d=this.useWebGPU,p={};d&&(p._edgeOffsets=[],p._edgeCounts=[],p._meshOffsets=[],p._meshCounts=[],p._meshIndex=[],p.groupCount=0);for(let e=0;e<i.length;e++){performance.now()-a>o&&(t.onProgress&&t.onProgress(e,i.length),yield,a=performance.now());const s=i[e];d?Cr(h,n.get(s.geometry),s,p,e):dr(h,n.get(s.geometry),s,c,u)}if(d){let e=!1,t=null;for(Ar(p,i,h,c,u).then(()=>{e=!0},i=>{t=i,e=!0});!e;)yield;if(t)throw t}const f=u.totalEdges*u.totalTriangles;if(_r.setStat("Total edges",u.totalEdges.toLocaleString()),_r.setStat("Total triangles",u.totalTriangles.toLocaleString()),_r.setStat("Brute-force pairs (edges × triangles)",f.toLocaleString()),_r.setStat("BVH candidate pairs",u.candidates.toLocaleString()),f>0&&_r.setStat("BVH reduction",(u.candidates/f*100).toFixed(3)+"% of brute-force"),u.candidates>0){const e=u.candidates,t=t=>(t/e*100).toFixed(2)+"%";d||(_r.setStat("Rejected: back-face culling",u.backFaceCulled.toLocaleString()+" ("+t(u.backFaceCulled)+")"),_r.setStat("Rejected: Y-bounds (tri below edge)",u.yBoundsCulled.toLocaleString()+" ("+t(u.yBoundsCulled)+")"),_r.setStat("Rejected: XZ-bounds (no 2D overlap)",u.xzBoundsCulled.toLocaleString()+" ("+t(u.xzBoundsCulled)+")"),_r.setStat("Rejected: edge lies on triangle",u.triangleEdgeCulled.toLocaleString()+" ("+t(u.triangleEdgeCulled)+")"),_r.setStat("Rejected: line above tri plane",u.planeTrimCulled.toLocaleString()+" ("+t(u.planeTrimCulled)+")"),_r.setStat("Rejected: trimmed edge too small",u.distThresholdCulled.toLocaleString()+" ("+t(u.distThresholdCulled)+")"),_r.setStat("Rejected: no projected overlap",u.noOverlapCulled.toLocaleString()+" ("+t(u.noOverlapCulled)+")")),_r.setStat("Producing overlaps",u.used.toLocaleString()+" ("+t(u.used)+")")}_r.startStep("Converting overlaps to lines");const m=this.hasGroups;for(let t=0;t<e.length;t++){performance.now()-a>o&&(yield,a=performance.now());const i=e[t],n=c[t],l=s.length,h=r.length;if(As(i,n,!1,s),As(i,n,!0,r),m){const e=i.groupIndex;for(let t=l;t<s.length;t++)this.visibleGroupIndices.push(e);for(let t=h;t<r.length;t++)this.hiddenGroupIndices.push(e)}}}}class Er{constructor(){this.iterationTime=30,this.angleThreshold=50,this.includeIntersectionEdges=!0,this.useWebGPU=!0}generateAsync(e,t={}){return new Promise((i,n)=>{const{signal:s}=t,r=this.generate(e,t);!function e(){if(s&&s.aborted)return void n(new Error("ProjectionGenerator: Process aborted via AbortSignal."));let t;try{t=r.next()}catch(e){return void n(e)}t.done?i(t.value):requestAnimationFrame(e)}()})}*generate(e,i){const{iterationTime:n,angleThreshold:s,includeIntersectionEdges:r}=this,{onProgress:o=()=>{},visibilityCuller:a=null,groupFn:l=null}=i;if(_r.reset(),_r.startTotal(),e.isBufferGeometry&&(e=new t.Mesh(e)),a){_r.startStep("Visibility culling");let n=!1,s=null;for(a.cull(e,{signal:i.signal}).then(i=>{(e=new t.Scene).children=i,n=!0},e=>{s=e,n=!0});!n;)yield;if(s)throw s}const c=new Fs;c.iterationTime=n,c.thresholdAngle=s,c.projectionDirection.copy(Tr),_r.startStep("Generating candidate edges"),o("Generating candidate edges");let h=[],u=l?[]:null;if(yield*c.getEdgesGenerator(e,h,u),r&&(_r.startStep("Generating intersection edges"),o("Generating intersection edges"),yield*c.getIntersectionEdgesGenerator(e,h,u)),_r.startStep("Pre-filtering edges"),o("Pre-filtering edges"),u){const e=[],t=[];for(let i=0;i<h.length;i++)xs(h[i])||(e.push(h[i]),t.push(u[i]));h=e,u=t}else h=h.filter(e=>!xs(e));yield;const d=new Mr(e,this.useWebGPU);if(d.iterationTime=n,l&&u){const e=new Map;for(let t=0;t<h.length;t++){const i=l(u[t]);e.has(i)||e.set(i,e.size),h[t].groupIndex=e.get(i)}d.groupKeyToIndex=e,d.hasGroups=!0}return o("Building BVH & computing overlaps"),yield*d.addEdgesGenerator(h,{onProgress:o?(e,t)=>{o("Building BVH & computing overlaps",e/t,d)}:null}),_r.printSummary(),d}}new t.Line3,new t.Line3,new t.Vector3;class Ir extends f{static uuid="f2e76c3a-8b1d-4d5e-9a3f-7c6b2d4e8f1a";enabled=!0;onDisposed=new d;generator=new Er;cullerPixelsPerMeter=.05;get cullerMetersPerPixel(){return this.cullerPixelsPerMeter}set cullerMetersPerPixel(e){this.cullerPixelsPerMeter=e}projectionDirection=new c.Vector3(0,-1,0);nearPlane=-1/0;farPlane=1/0;constructor(e){super(e),this.components.add(Ir.uuid,this),this.generator.includeIntersectionEdges=!1}async get(e,t,i){const n=this.components.get(fs),s=new c.Group,r=new Map;for(const[t,i]of Object.entries(e)){const e=n.list.get(t);if(!e)continue;const o=(await e.getItemsIdsWithGeometry()).filter(e=>i.has(e));if(0===o.length)continue;const a=await e.getItemsGeometry(o);for(const i in a){const n=a[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 e=new c.BufferGeometry;e.setAttribute("position",new c.Float32BufferAttribute(i.positions,3)),i.normals&&e.setAttribute("normal",new c.Float32BufferAttribute(i.normals,3)),e.setIndex(Array.from(i.indices)),r.set(n,e)}const o=r.get(n),a=new c.Mesh(o);a.applyMatrix4(i.transform),a.applyMatrix4(e.object.matrixWorld),a.updateWorldMatrix(!0,!0),a.userData._edgeProjectorModelId=t,a.userData._edgeProjectorLocalId=i.localId,s.add(a)}}}const o=this.projectionDirection.clone().normalize(),a=new c.Vector3(0,-1,0),l=(new c.Quaternion).setFromUnitVectors(o,a),h=(new c.Matrix4).makeRotationFromQuaternion(l),u=h.clone().invert();for(const e of s.children)e.applyMatrix4(h),e.updateWorldMatrix(!1,!1);if(s.traverse(e=>{const t=e;if(t.geometry&&!t.geometry.boundsTree){const e=t.geometry.index?t.geometry.index.count:t.geometry.attributes.position.count;t.geometry.groups.forEach(t=>{t.count===1/0&&(t.count=e-t.start)}),t.geometry.boundsTree=new Kn(t.geometry,{maxLeafSize:1,strategy:2})}}),this.nearPlane!==-1/0||this.farPlane!==1/0){const e=new c.Box3,t=[];for(const i of s.children){const n=i;n.geometry&&(e.setFromObject(n),(e.max.y<this.nearPlane||e.min.y>this.farPlane)&&t.push(n))}for(const e of t)s.remove(e)}const d=t.renderer.three,p=new ws(d,{pixelsPerMeter:this.cullerPixelsPerMeter});let f;try{f=await this.generator.generateAsync(s,{visibilityCuller:p,groupFn:e=>`${e.userData._edgeProjectorModelId??"unknown"}:${e.userData._edgeProjectorLocalId??0}`,onProgress:i?.onProgress,signal:i?.signal})}catch(e){for(const e of r.values())e.dispose();throw e}const m=f.getVisibleLineGeometry(),g=f.getHiddenLineGeometry();m.applyMatrix4(u),g.applyMatrix4(u);const w=f.getGroupKeys(),y={};for(const[e,t]of Object.entries(w)){const i=e.lastIndexOf(":"),n=e.substring(0,i),s=Number(e.substring(i+1));y[t]={modelId:n,localId:s}}for(const e of r.values())e.dispose();return{visible:m,hidden:g,groups:y}}dispose(){this.onDisposed.trigger(Ir.uuid),this.onDisposed.reset()}}class Dr{wasm={path:"",absolute:!1,logLevel:u.LogLevel.LOG_LEVEL_OFF};webIfc={COORDINATE_TO_ORIGIN:!0};autoSetWasm=!0;customLocateFileHandler=null}class zr extends f{static uuid="a659add7-1418-4771-a0d6-7d4d438e4624";onDisposed=new d;onIfcStartedLoading=new d;onIfcImporterInitialized=new d;onSetup=new d;settings=new Dr;webIfc=new u.IfcAPI;enabled=!0;constructor(e){super(e),this.components.add(zr.uuid,this)}dispose(){this.webIfc=null,this.onDisposed.trigger(zr.uuid),this.onDisposed.reset()}async setup(e){this.settings={...this.settings,...e},this.settings.autoSetWasm&&await this.autoSetWasm(),this.onSetup.trigger()}async load(e,t,i,n){const s=this.components.get(fs);if(!s.initialized)throw new Error("You need to initialize fragments first.");this.settings.autoSetWasm&&await this.autoSetWasm(),s.core.settings.autoCoordinate=t;const r=new l.IfcImporter;r.wasm.path=this.settings.wasm.path,r.wasm.absolute=this.settings.wasm.absolute,r.webIfcSettings=this.settings.webIfc,this.onIfcImporterInitialized.trigger(r),n?.instanceCallback&&n.instanceCallback(r);const o=await r.process({...n?.processData,bytes:e});return await s.core.load(o,{modelId:i,userData:n?.userData})}async readIfcFile(e){const{path:t,absolute:i,logLevel:n}=this.settings.wasm;return this.webIfc.SetWasmPath(t,i),await this.webIfc.Init(this.settings.customLocateFileHandler||void 0),n&&this.webIfc.SetLogLevel(n),this.webIfc.OpenModel(e,this.settings.webIfc)}cleanUp(){try{this.webIfc.Dispose()}catch(e){console.log("Web-ifc wasn't disposed.")}this.webIfc=null,this.webIfc=new u.IfcAPI}async autoSetWasm(){const e=await fetch(`https://unpkg.com/@thatopen/components@${zo.release}/package.json`);if(!e.ok)return void console.warn("Couldn't get openbim-components package.json. Set wasm settings manually.");const t=await e.json();if("web-ifc"in t.peerDependencies){const e=t.peerDependencies["web-ifc"];this.settings.wasm.path=`https://unpkg.com/web-ifc@${e}/`,this.settings.wasm.absolute=!0}else console.warn("Couldn't get web-ifc from peer dependencies in openbim-components. Set wasm settings manually.")}}class kr extends f{static uuid="dd9ccf2d-8a21-4821-b7f6-2949add16a29";enabled=!0;constructor(e){super(e),this.components.add(kr.uuid,this)}async set(e,t){const i=this.components.get(fs),n=[];if(t)for(const[s,r]of Object.entries(t)){const t=i.list.get(s);t&&n.push(t.setVisible([...r],e))}else for(const t of i.list.values())n.push(t.setVisible(void 0,e));await Promise.all(n),await i.core.update(!0)}async isolate(e){await Promise.all([this.set(!1),this.set(!0,e)])}async toggle(e){const t=[],i=this.components.get(fs);for(const[n,s]of Object.entries(e)){const e=i.list.get(n);e&&t.push(e.toggleVisible([...s]))}await Promise.all(t),await i.core.update(!0)}async getVisibilityMap(e,t){const i=[],n=[],s=this.components.get(fs);if(t)for(const r of t){const t=s.list.get(r);t&&(i.push(t.modelId),n.push(t.getItemsByVisibility(e)))}else for(const t of s.list.values())i.push(t.modelId),n.push(t.getItemsByVisibility(e));const r=await Promise.all(n),o={};for(const[e,t]of i.entries())o[t]=r[e];return o}}class Br extends f{static uuid="d1444724-dba6-4cdd-a0c7-68ee1450d166";enabled=!0;onDisposed=new d;list=new l.DataSet;constructor(e){super(e),this.components.add(Br.uuid,this)}dispose(e=!0){this.list.clear(),this.onDisposed.trigger(Br.uuid),e&&(this.onDisposed.reset(),this.list.eventsEnabled=!1,this.list.dispose())}get(){const e=new c.Box3;for(const t of this.list)e.union(t);return e}async addFromModelIdMap(e){const t=this.components.get(fs),i=new c.Box3;for(const[n,s]of Object.entries(e)){const e=t.list.get(n);if(!e)continue;const r=await e.getMergedBox([...s]);i.union(r)}this.list.add(i)}addFromModels(e){const t=this.components.get(fs);for(const[i,n]of t.list)e&&!e.some(e=>e.test(i))||this.list.add(n.box)}async getCenter(e){this.list.clear(),await this.addFromModelIdMap(e);const t=this.get();this.list.clear();const i=new c.Vector3;return t.getCenter(i),i}async getCameraOrientation(e,t=1){const i=this.components.get(fs);this.list.clear();for(const[e,t]of i.list)this.list.add(t.box);const n=this.get();this.list.clear();const s=new c.Vector3;n.getCenter(s);const r=new c.Vector3;n.getSize(r);const o=Math.max(r.x,r.y,r.z)*t,a=new c.Vector3;switch(e){case"front":default:a.set(s.x,s.y,s.z+o);break;case"back":a.set(s.x,s.y,s.z-o);break;case"left":a.set(s.x-o,s.y,s.z);break;case"right":a.set(s.x+o,s.y,s.z);break;case"top":a.set(s.x,s.y+o,s.z);break;case"bottom":a.set(s.x,s.y-o,s.z)}return{position:a,target:s}}}class Or{name="Query";customData={};_components;_queries=[];set queries(e){this._queries=e,this.clearCache()}get queries(){return this._queries}_aggregation="exclusive";set aggregation(e){e!==this._aggregation&&this.clearCache(),this._aggregation=e}get aggregation(){return this._aggregation}result=null;cache=!0;constructor(e,t){this._components=e,this.queries=t}async test(e){const{modelIds:t,force:i}={force:!1,...e};if(this.result&&!i)return this.result;const n=this._components.get(Vr),s=await n.getItems(this.queries,{modelIds:t,aggregation:this.aggregation});return this.cache&&(this.result=s),s}clearCache(){this.result=null}serializeAttributeQuery(e){let t;t=Array.isArray(e.value)?e.value.map(e=>e.source):e.value instanceof RegExp?e.value.source:e.value;return{name:e.name.source,value:t,type:e.type instanceof RegExp?e.type.source:e.type,negate:e.negate,itemIds:e.itemIds}}serializeQueryParameters=e=>({categories:e.categories?.map(e=>e.source),attributes:e.attributes?{aggregation:e.attributes.aggregation,queries:e.attributes.queries.map(this.serializeAttributeQuery)}:void 0,relation:e.relation?{name:e.relation.name,query:e.relation.query?this.serializeQueryParameters(e.relation.query):void 0}:void 0});toJSON(){return{guid:this._components.get(Vr).list.getKey(this)??v.create(),name:this.name,customData:this.customData,queries:this.queries.map(this.serializeQueryParameters),aggregation:this.aggregation,cache:this.cache}}deserializeAttributeQuery(e){let t;t=Array.isArray(e.value)?e.value.map(e=>new RegExp(e)):"string"==typeof e.value?new RegExp(e.value):e.value;return{name:new RegExp(e.name),value:t,type:e.type?new RegExp(e.type):void 0,negate:e.negate,itemIds:e.itemIds}}deserializeQueryParameters=e=>({categories:e.categories?.map(e=>new RegExp(e)),attributes:e.attributes?{aggregation:e.attributes.aggregation,queries:e.attributes.queries.map(this.deserializeAttributeQuery)}:void 0,relation:e.relation?{name:e.relation.name,query:e.relation.query?this.deserializeQueryParameters(e.relation.query):void 0}:void 0});fromJSON(e){return this.name=e.name,this.customData=e.customData,this.aggregation=e.aggregation,this.cache=e.cache,this.queries=e.queries.map(this.deserializeQueryParameters),this}}class Vr extends f{static uuid="0da7ad77-f734-42ca-942f-a074adfd1e3a";enabled=!0;list=new l.DataMap;constructor(e){super(e),e.add(Vr.uuid,this)}async getItems(e,t){let i;if(t){const{modelIds:e,items:n}=t;if(n){const e=Object.keys(n);e.length>0&&(i=e.map(e=>new RegExp(`^${e}$`)))}else e&&(i=e)}const n=t?.aggregation??"exclusive",s=this.components.get(fs),r=await Promise.all(e.map(async e=>{const n={};return await Promise.all(Array.from(s.list).map(async([s,r])=>{if(i&&!i.some(e=>e.test(s)))return;const o=t?.items?.[s],a=await r.getItemsByQuery(e,{localIds:o?[...o]:void 0});n[s]=new Set(a)})),n}));return"inclusive"===n?ct.join(r):ct.intersect(r)}create(e,t){const i=new Or(this.components,t);return this.list.set(e,i),i}async addFromCategories(e){const t=new Set,i=this.components.get(fs);for(const[n,s]of i.list){if(e&&!e.some(e=>e.test(n)))continue;const i=(await s.getItemsWithGeometryCategories()).filter(e=>null!==e),r=new Set(i);for(const e of r)this.list.has(e)||(this.create(e,[{categories:[new RegExp(`^${e}$`)]}]),t.add(e))}return[...t]}import(e){const{data:t}=e,i=[];if(!t)return i;for(const e of t){const t=this.create(e.guid,[]);t.fromJSON(e),i.push(t)}return i}export(){const e=[];for(const[t,i]of this.list.entries()){const n={...i.toJSON(),name:t};e.push(n)}return{data:e}}}class Lr extends f{static uuid="e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7";enabled=!0;onDisposed=new d;list=new l.DataMap;constructor(e){super(e),e.add(Lr.uuid,this),this.setupEvents();e.get(fs).list.onBeforeDelete.add(this.onBeforeFragmentsDispose)}setupEvents(){this.list.onBeforeDelete.add(({value:e})=>e.dispose())}getClassificationGroups(e){let t=this.list.get(e);return t||(t=new l.DataMap,this.list.set(e,t)),t}getModelItems(e,t,i){const{map:n}=this.getGroupData(e,t);let s=n[i];return s||(s=new Set,n[i]=s),s}getGroupData(e,t){const i=this.components.get(Vr),n=this.getClassificationGroups(e);let s=n.get(t);return s||(s={map:{},get:()=>new Promise(e=>{if(s)if(s.query){const{name:t,config:n}=s.query,r=i.list.get(t);if(!r)throw new Error("Classifier: the query name associated with the group doesn't exist in the ItemsFinder component");r.test(n).then(t=>{if(!s)return void e({});const i=ct.join([t,s.map]);e(i)})}else e(s.map);else e({})})},n.set(t,s)),s}defaultSaveFunction=e=>"value"in e.Name?e.Name.value:null;async aggregateItems(e,t,i){const n=i?.data??void 0,s=i?.aggregationCallback??this.defaultSaveFunction,r=this.components.get(fs),o=this.components.get(Vr),a=await o.getItems([t],{modelIds:i?.modelIds});for(const[t,i]of Object.entries(a)){const o=r.list.get(t);if(!o)continue;const a=(i,...n)=>{const s=this.getModelItems(e,i,t);for(const e of n)s.add(e)},l=await o.getItemsData([...i],n);for(const e of l)s(e,a)}}addGroupItems(e,t,i){const{map:n}=this.getGroupData(e,t);ct.add(n,i)}setGroupQuery(e,t,i){this.getGroupData(e,t).query=i}async find(e){const t=[];for(const[i,n]of Object.entries(e)){const e=[],s=this.list.get(i);if(!s)continue;for(const t of n){const i=s.get(t);if(!i)continue;const n=await i.get();e.push(n)}const r=ct.join(e);t.push(r)}return ct.intersect(t)}async aggregateItemRelations(e,t,i,n){const s=n?.attribute??"Name",r={relations:{[i]:{attributes:!0,relations:!1}}};await this.aggregateItems(e,t,{modelIds:n?.modelIds,data:r,aggregationCallback:(e,t)=>{if(!e?.[s])return;const n=e[s];if(!("value"in n))return;const r=e[i];if(Array.isArray(r))for(const e of r)"value"in e._localId&&t(n.value,e._localId.value)}})}async byIfcBuildingStorey(e){await this.aggregateItemRelations(e?.classificationName??"Storeys",{categories:[/BUILDINGSTOREY/]},"ContainsElements",{modelIds:e?.modelIds})}async byCategory(e){const t=this.components.get(Vr),i=await t.addFromCategories(e?.modelIds);for(const t of i)this.setGroupQuery(e?.classificationName??"Categories",t,{name:t})}onBeforeFragmentsDispose=async e=>{const{key:t,value:i}=e,n=await i.getLocalIds(),s={[t]:new Set(n)};this.removeItems(s)};dispose(){this.list.clear();this.components.get(fs).list.onBeforeDelete.remove(this.onBeforeFragmentsDispose),this.onDisposed.trigger()}removeItems(e,t){if(t&&t.classificationName){const i=this.list.get(t.classificationName);if(!i)return;if(t.groupName){if(!i.get(t.groupName))return}for(const[,t]of i)ct.remove(t.map,e);return}for(const[,t]of this.list.entries())for(const[,i]of t)ct.remove(i.map,e)}async byModel(e){const t=this.components.get(fs),i=e?.classificationName??"Models";for(const[n,s]of t.list){if(e&&e.modelIds&&!e.modelIds.some(e=>e.test(n)))continue;const t=await s.getItemsIdsWithGeometry(),r={[n]:new Set(t)};this.getGroupData(i,n),this.addGroupItems(i,n,r)}}}const Nr={id:0,depth:1,normal:2},Fr=Object.keys(Nr),Rr={id:!0},Ur={depth:!0},jr={normal:!0},$r={id:!0,depth:!0,normal:!0},Wr={},Hr=new c.Vector2;class Gr extends c.Camera{updateProjectionMatrix(){}}function qr(e,t){return new c.WebGLRenderTarget(e,t,{count:Fr.length,format:c.RGBAFormat,type:c.UnsignedByteType,minFilter:c.NearestFilter,magFilter:c.NearestFilter,depthBuffer:!0})}function Zr(e){const t=e;return Boolean(t.isMesh||t.isLine||t.isPoints||t.isSprite)}function Yr(e,t){const i=t.get(e[0]);if(!i)return null;const n=e[1]<<16|e[2]<<8|e[3];return 0===n?null:{modelId:i,itemId:n-1}}function Xr(e,t){if(0===e[0]&&0===e[1]&&0===e[2]&&0===e[3])return null;const i=255/256*((n=e)[0]/255/16777216+n[1]/255/65536+n[2]/255/256+n[3]/255);var n;const{reversedDepth:s}=t;return(s?i<=1e-6:i>=.999999)?null:function(e,t,i,n){const s=n?t:2*t-1,r=new c.Vector3(e.x,e.y,s);return r.unproject(i),r}(t.ndc,i,t.camera,s)}async function Kr(e,t,i){const n=e.list.get(t);if(!n)return null;const s=await n.getLocalIdsFromItemIds([i]),r=s?.[0];return r??null}class Qr{enabled=!0;components;onDisposed=new d;mouse;world;debugMode=!1;static MAX_MODELS=254;_pickTarget=qr(1,1);_debugTarget;_pickBuffers={id:new Uint8Array(4),depth:new Uint8Array(4),normal:new Uint8Array(4)};_debugCanvas;_debugContainer;_pickMaterial;_pickCamera=new Gr;_pickMatrix=new c.Matrix4;_pickNdc=new c.Vector2;_viewportSize=new c.Vector2;_clearColor=new c.Color;_cameraPosition=new c.Vector3;_meshBytes=new Map;_byteToModel=new Map;_modelBytes=new Map;_modelRoots=new Map;_hidden=[];_forcedOverrides=[];_walkNodes=[];_walkOwners=[];_localPlanes=[];constructor(e,t){if(!t.renderer)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=t,this.mouse=new ft(t.renderer.three.domElement),this.components=e,this._pickMaterial=this.buildPickMaterial(),this._pickCamera.matrixAutoUpdate=!1,this._pickCamera.matrixWorldAutoUpdate=!1}async getModelAt(e){return this.pick(e,Rr)?.item?.modelId??null}async getItemAt(e){const t=this.pick(e,Rr)?.item;if(!t)return null;const i=this.components.get(fs),n=await Kr(i,t.modelId,t.itemId);return null==n?null:{modelId:t.modelId,localId:n,itemId:t.itemId}}async getPointAt(e){return this.pick(e,Ur)?.surface?.point??null}async getNormalAt(e){return this.pick(e,jr)?.normal??null}async getFullPick(e){const t=this.pick(e,$r);if(!t?.item||!t.surface)return null;const i=this.components.get(fs),{modelId:n,itemId:s}=t.item,r=await Kr(i,n,s);return null==r?null:{modelId:n,itemId:s,localId:r,point:t.surface.point,normal:t.normal,distance:t.surface.distance}}setDebugMode(e){this.debugMode=e,e?this.setupDebugCanvas():this.removeDebugCanvas()}dispose(){this.mouse.dispose(),this.removeDebugCanvas(),this._pickMaterial.dispose(),this._pickTarget?.dispose(),this._pickTarget=void 0,this._debugTarget?.dispose(),this._debugTarget=void 0,this.onDisposed.trigger(),this.onDisposed.reset()}pick(e,t){if(!this._pickTarget)return null;this.debugMode&&this.updateDebugCanvas();const i=e??this.mouse.position,n=this._pickBuffers,s=this.renderPick(i,t,this._pickTarget,n);if(!s)return null;const r=t.depth?Xr(n.depth,s):null;return{item:t.id?Yr(n.id,s.byteToModel):null,surface:r?{point:r,distance:r.distanceTo(this._cameraPosition.setFromMatrixPosition(s.camera.matrixWorld))}:null,normal:t.normal?(o=n.normal,0===o[3]?null:new c.Vector3(o[0]/255*2-1,o[1]/255*2-1,o[2]/255*2-1).normalize()):null};var o}renderPick(e,t,i,n){if(!this.enabled||!this.world.renderer)return null;const s=this.world.scene.three;if(!s.isScene)return null;const r=this.components.get(fs);if(!r.initialized||0===r.list.size)return null;const o=this.world.renderer.three,a=o.getSize(this._viewportSize);if(0===a.x||0===a.y)return null;const l=this.snapshotCamera(e,a,i),c=this._pickMaterial;c.clippingPlanes=this.collectLocalPlanes(this.world.renderer);const h=o.getRenderTarget(),u=o.autoClear,d=o.getClearColor(this._clearColor),p=o.getClearAlpha(),f=s.background,m=s.overrideMaterial,{shadowMap:g}=o,w=g.autoUpdate,y=g.needsUpdate;try{if(this.collectPickables(s,r),0===this._byteToModel.size)return null;s.background=null,s.overrideMaterial=c,g.autoUpdate=!1,g.needsUpdate=!1,o.setRenderTarget(i),o.setClearColor(0,0),o.autoClear=!1,o.clear(!0,!0,!1),o.render(s,l)}finally{this.restorePickables(),g.autoUpdate=w,g.needsUpdate=y,s.overrideMaterial=m,s.background=f,o.setRenderTarget(h),o.autoClear=u,o.setClearColor(d,p)}const _=Math.floor(i.width/2),b=Math.floor(i.height/2);for(const e of Fr){if(!t[e])continue;const s=n[e];s.fill(0);const r=Nr[e];o.readRenderTargetPixels(i,_,b,1,1,s,void 0,r)}this._pickNdc.set((_+.5)/i.width*2-1,(b+.5)/i.height*2-1);const v=o.capabilities;return{byteToModel:this._byteToModel,camera:l,ndc:this._pickNdc,reversedDepth:!0===v?.reversedDepthBuffer}}snapshotCamera(e,t,i){const n=this.world.camera.three;n.updateWorldMatrix(!0,!1);const s=this._pickCamera;s.matrixWorld.copy(n.matrixWorld),s.matrixWorldInverse.copy(n.matrixWorldInverse),s.layers.mask=n.layers.mask;const r=t.x/i.width,o=t.y/i.height;return this._pickMatrix.set(r,0,0,-e.x*r,0,o,0,-e.y*o,0,0,1,0,0,0,0,1),s.projectionMatrix.multiplyMatrices(this._pickMatrix,n.projectionMatrix),s.projectionMatrixInverse.copy(s.projectionMatrix).invert(),s}collectLocalPlanes(e){const t=this._localPlanes;t.length=0;for(const i of e.clippingPlanes)i.isLocal&&t.push(i);return t}collectPickables(e,t){this._byteToModel.clear(),this._modelBytes.clear();for(const[e,i]of t.list)this._modelRoots.set(i.object,e);const i=this._walkNodes,n=this._walkOwners;for(i.push(e),n.push(null);i.length;){const e=i.pop(),t=n.pop();if(!e.visible)continue;const s=this._modelRoots.get(e)??t;if(Zr(e)){const t=null===s?0:this.pickableByte(e,s);if(!t){e.visible=!1,this._hidden.push(e);continue}this._meshBytes.set(e,t)}for(const t of e.children)i.push(t),n.push(s)}}pickableByte(e,t){const i=e;if(!i.isMesh||!i.geometry?.attributes?.id)return 0;let n=this._modelBytes.get(t);if(void 0===n){if(n=this._byteToModel.size+1,n>Qr.MAX_MODELS)return 0;this._modelBytes.set(t,n),this._byteToModel.set(n,t)}return this.allowOverride(i.material),n}allowOverride(e){if(Array.isArray(e))for(const t of e)this.allowOverride(t);else e&&!1===e.allowOverride&&(e.allowOverride=!0,this._forcedOverrides.push(e))}restorePickables(){for(const e of this._hidden)e.visible=!0;for(const e of this._forcedOverrides)e.allowOverride=!1;this._hidden.length=0,this._forcedOverrides.length=0,this._walkNodes.length=0,this._walkOwners.length=0,this._meshBytes.clear(),this._modelRoots.clear()}buildPickMaterial(){const e=new c.ShaderMaterial({glslVersion:c.GLSL3,uniforms:{modelByte:{value:0}},vertexShader:"\n attribute vec4 id;\n varying vec4 vId;\n varying vec3 vWorldNormal;\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n #endif\n void main() {\n vId = id;\n vWorldNormal = normalize((modelMatrix * vec4(normal, 0.0)).xyz);\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 varying vec3 vWorldNormal;\n #if NUM_CLIPPING_PLANES > 0\n varying vec3 vClipPosition;\n uniform vec4 clippingPlanes[NUM_CLIPPING_PLANES];\n #endif\n layout(location = ${Nr.id}) out highp vec4 outId;\n layout(location = ${Nr.depth}) out highp vec4 outDepth;\n layout(location = ${Nr.normal}) out highp vec4 outNormal;\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 outId = vec4(modelByte / 255.0, vId.y / 255.0, vId.z / 255.0, vId.w / 255.0);\n\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 outDepth = r * (256.0 / 255.0);\n\n vec3 n = normalize(vWorldNormal);\n if (!gl_FrontFacing) n = -n;\n outNormal = vec4(n * 0.5 + 0.5, 1.0);\n }\n `,side:c.DoubleSide,clipping:!0});return e.onBeforeRender=(t,i,n,s,r)=>{e.uniforms.modelByte.value=this._meshBytes.get(r)??0,e.uniformsNeedUpdate=!0},e}setupDebugCanvas(){if(this._debugCanvas)return;const e=this.world.renderer.three.getSize(new c.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=e.x,this._debugCanvas.height=e.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.world.renderer)return;const e=this.world.renderer.three,t=e.getSize(new c.Vector2),i=Math.floor(t.x),n=Math.floor(t.y);if(0===i||0===n)return;this._debugTarget??=qr(i,n);const s=this._debugTarget;if(s.setSize(i,n),!this.renderPick(Hr,Wr,s,this._pickBuffers))return;const r=new Uint8Array(i*n*4);e.readRenderTargetPixels(s,0,0,i,n,r,void 0,Nr.id);const o=this._debugCanvas;o.width=i,o.height=n;const a=o.getContext("2d");if(!a)return;const l=a.createImageData(i,n),h=4*i;for(let e=0;e<n;e++){const t=e*h,i=(n-1-e)*h;l.data.set(r.subarray(t,t+h),i)}a.putImageData(l,0,0)}}class Jr extends f{static uuid="4a82430c-7ff2-49ea-9401-60807502dad6";enabled=!0;list=new Map;onDisposed=new d;constructor(e){super(e),e.add(Jr.uuid,this)}get(e){if(this.list.has(e.uuid))return this.list.get(e.uuid);const t=new Qr(this.components,e);return this.list.set(e.uuid,t),e.onDisposed.add(()=>{this.delete(e)}),t}delete(e){const t=this.list.get(e.uuid);t&&t.dispose(),this.list.delete(e.uuid)}dispose(){for(const[e,t]of this.list)t.dispose();this.list.clear(),this.onDisposed.trigger()}}var eo=(e=>(e[e.POINT=0]="POINT",e[e.LINE=1]="LINE",e[e.FACE=2]="FACE",e))(eo||{});const to=1e3;class io{onDisposed=new d;maxDistance=1;maxCacheSize=1e3;get precision(){return this._precision}set precision(e){e!==this._precision&&(this._precision=e,this.clear())}components;_precision="half";cache=new Map;constructor(e){this.components=e}dispose(){this.cache.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}async resolve(e,t,i,n){const s=io.keyOf(t,i);let r=this.cache.get(s);if(r)this.cache.delete(s),this.cache.set(s,r);else{if(r=await this.fetchItemSnapData(t,i),!r)return null;this.storeWithLRU(s,r)}const o=this.snap(e,r,2),a=new Set(n),l=[0,1,2];let c=null;for(const t of l){if(!a.has(t))continue;const i=this.snap(e,r,t);if(i){c=i.result;break}}if(!c)return o?o.result:null;if(o&&2!==c.snappingClass){const e=o.result;!c.normal&&e.normal&&(c.normal=e.normal),!c.facePoints&&e.facePoints&&(c.facePoints=e.facePoints),!c.faceIndices&&e.faceIndices&&(c.faceIndices=e.faceIndices)}return c}async prefetch(e,t){const i=io.keyOf(e,t);if(this.cache.has(i))return;const n=await this.fetchItemSnapData(e,t);n&&this.storeWithLRU(i,n)}invalidate(e,t){const i=io.keyOf(e,t);this.cache.delete(i)}clear(){this.cache.clear()}static keyOf(e,t){return`${e}:${t}`}storeWithLRU(e,t){for(this.cache.set(e,t);this.cache.size>this.maxCacheSize;){const e=this.cache.keys().next().value;if(void 0===e)break;this.cache.delete(e)}}async fetchItemSnapData(e,t){const i=this.components.get(fs).list.get(e);if(!i)return null;const n=await i._getItemSnapData(t);if(!n)return null;const s=i.object.matrixWorld,r=[];for(const e of Object.keys(n.samples??{})){const t=n.samples[Number(e)],i=n.representations[t.representation];if(!i||1!==i.representationClass)continue;const o=i.geometry;if(!o)continue;const a=n.localTransforms[t.localTransform],l=ho(s,n.globalTransforms[t.item],a);this.collectPolygonsFromShell(o,l,r)}if(0===r.length)return null;return{faces:r,edges:function(e,t){const i=new Set,n=[];for(const t of e){const e=t.points,s=e.length/3;for(let t=0;t<s;t++){const r=(t+1)%s,o=e[3*t],a=e[3*t+1],l=e[3*t+2],c=e[3*r],h=e[3*r+1],u=e[3*r+2],d=fo(o,a,l,c,h,u);i.has(d)||(i.add(d),n.push(o,a,l,c,h,u))}}return new("full"===t?Float64Array:Float32Array)(n)}(r,this._precision),vertices:function(e,t){const i=new Set,n=[];for(const t of e){const e=t.points,s=e.length/3;for(let t=0;t<s;t++){const s=e[3*t],r=e[3*t+1],o=e[3*t+2],a=po(s,r,o);i.has(a)||(i.add(a),n.push(s,r,o))}}return new("full"===t?Float64Array:Float32Array)(n)}(r,this._precision)}}collectPolygonsFromShell(e,t,i){const n=e.points,s=e.profiles??new Map,r=e.bigProfiles??new Map,o=new c.Vector3,a=e=>{if(e.length<3)return;const s=new("full"===this._precision?Float64Array:Float32Array)(3*e.length);for(let i=0;i<e.length;i++){const r=n[e[i]];o.set(r[0],r[1],r[2]).applyMatrix4(t),s[3*i]=o.x,s[3*i+1]=o.y,s[3*i+2]=o.z}const r=function(e){const t=new c.Vector3,i=e.length/3;for(let n=0;n<i;n++){const s=(n+1)%i,r=e[3*n],o=e[3*n+1],a=e[3*n+2],l=e[3*s],c=e[3*s+1],h=e[3*s+2];t.x+=(o-c)*(a+h),t.y+=(a-h)*(r+l),t.z+=(r-l)*(o+c)}const n=t.length();return n<1e-10?null:t.divideScalar(n)}(s);if(!r)return;const a=r.x*s[0]+r.y*s[1]+r.z*s[2];i.push({points:s,normal:r,d:a})};for(const e of s.values())a(e);for(const e of r.values())a(e)}snap(e,t,i){return 0===i?this.snapToPoint(e,t):1===i?this.snapToLine(e,t):2===i?this.snapToFace(e,t):null}snapToPoint(e,t){const i=t.vertices;if(0===i.length)return null;const n=this.maxDistance*this.maxDistance;let s=-1,r=1/0;for(let t=0;t<i.length;t+=3){const o=i[t]-e.x,a=i[t+1]-e.y,l=i[t+2]-e.z,c=o*o+a*a+l*l;c<=n&&c<r&&(r=c,s=t)}return s<0?null:{result:{point:new c.Vector3(i[s],i[s+1],i[s+2]),snappingClass:0}}}snapToLine(e,t){const i=t.edges;if(0===i.length)return null;const n=this.maxDistance*this.maxDistance,s=new c.Vector3,r=new c.Vector3;let o=1/0,a=-1;for(let t=0;t<i.length;t+=6){const l=mo(e,i[t],i[t+1],i[t+2],i[t+3],i[t+4],i[t+5],r);l<=n&&l<o&&(o=l,a=t,s.copy(r))}return a<0?null:{result:{point:s.clone(),snappingClass:1,snappedEdgeP1:new c.Vector3(i[a],i[a+1],i[a+2]),snappedEdgeP2:new c.Vector3(i[a+3],i[a+4],i[a+5])}}}snapToFace(e,t){const i=t.faces;if(0===i.length)return null;let n=null,s=1/0,r=!1;for(const t of i){const i=this.signedDistance(t,e),o=Math.abs(i);if(o>this.maxDistance)continue;const a=this.containsPoint(t,this.projectOntoPlane(e,t,i));r&&!a||(!a||r?o<s&&(s=o,n=t):(r=!0,s=o,n=t))}if(!n)return null;return{result:{point:this.projectOntoPlane(e,n,this.signedDistance(n,e)),normal:n.normal.clone(),snappingClass:2,facePoints:n.points,faceIndices:uo(n.points.length/3)}}}signedDistance(e,t){return e.normal.x*t.x+e.normal.y*t.y+e.normal.z*t.z-e.d}projectOntoPlane(e,t,i){return e.clone().sub(t.normal.clone().multiplyScalar(i))}containsPoint(e,t){const{points:i,normal:n}=e,s=i.length/3;if(s<3)return!1;const r=Math.abs(n.x),o=Math.abs(n.y),a=Math.abs(n.z);let l=0,c=1;r>=o&&r>=a?(l=1,c=2):o>=a&&(l=0,c=2);const h=t.getComponent(l),u=t.getComponent(c);let d=!1;for(let e=0,t=s-1;e<s;t=e,e+=1){const n=i[3*e+l],s=i[3*e+c],r=i[3*t+l],o=i[3*t+c];if(!(s>u!=o>u))continue;h<(r-n)*(u-s)/(o-s)+n&&(d=!d)}return d}}const no=new c.Matrix4,so=new c.Vector3,ro=new c.Vector3,oo=new c.Vector3;function ao(e,t){if(!e)return t.identity();const i=e.position[0],n=e.position[1],s=e.position[2];return so.set(e.xDirection[0],e.xDirection[1],e.xDirection[2]),ro.set(e.yDirection[0],e.yDirection[1],e.yDirection[2]),oo.crossVectors(so,ro),t.set(so.x,ro.x,oo.x,i,so.y,ro.y,oo.y,n,so.z,ro.z,oo.z,s,0,0,0,1),t}const lo=new c.Matrix4,co=new c.Matrix4;function ho(e,t,i){return ao(t,lo),ao(i,co),no.copy(e).multiply(lo).multiply(co).clone()}function uo(e){if(e<3)return new Uint32Array(0);const t=e-2,i=new Uint32Array(3*t);for(let e=0;e<t;e++)i[3*e]=0,i[3*e+1]=e+1,i[3*e+2]=e+2;return i}function po(e,t,i){return`${Math.round(e*to)},${Math.round(t*to)},${Math.round(i*to)}`}function fo(e,t,i,n,s,r){const o=po(e,t,i),a=po(n,s,r);return o<a?`${o}|${a}`:`${a}|${o}`}function mo(e,t,i,n,s,r,o,a){const l=s-t,c=r-i,h=o-n,u=l*l+c*c+h*h;let d=0;u>0&&(d=((e.x-t)*l+(e.y-i)*c+(e.z-n)*h)/u,d<0?d=0:d>1&&(d=1));const p=t+d*l,f=i+d*c,m=n+d*h;a.set(p,f,m);const g=e.x-p,w=e.y-f,y=e.z-m;return g*g+w*w+y*y}class go extends f{static uuid="be9b8e6c-7f5b-4a36-8e7e-3a1f5e2a6c9d";enabled=!0;onDisposed=new d;_resolver;constructor(e){super(e),e.add(go.uuid,this),this._resolver=new io(e)}get(){return this._resolver}dispose(){this._resolver.dispose(),this.onDisposed.trigger()}}class wo{enabled=!0;components;onDisposed=new d;mouse;three=new c.Raycaster;world;constructor(e,t){const i=t.renderer;if(!i)throw new Error("A renderer is needed for the raycaster to work!");this.world=t,this.mouse=new ft(i.three.domElement),this.components=e}dispose(){this.mouse.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}castRayToObjects(e=Array.from(this.world.meshes),t=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(t,i),this.intersect(e)}async castRay(e){const t=e?.snappingClasses,i=e?.items??Array.from(this.world.meshes),n=e?.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(fs);let o=null;if(r.initialized){const e=this.components.get(Jr).get(this.world),a=await e.getFullPick(n);if(a){const e=r.list.get(a.modelId);if(o={localId:a.localId,point:a.point,normal:a.normal,distance:a.distance,fragments:e,object:e?.object,ray:void 0,frustum:void 0},t&&t.length>0){const e=await this.components.get(go).get().resolve(a.point,a.modelId,a.itemId,t);e&&(o.point=e.point,e.normal&&(o.normal=e.normal),o.snappingClass=e.snappingClass,e.facePoints&&(o.facePoints=e.facePoints),e.faceIndices&&(o.faceIndices=e.faceIndices),e.snappedEdgeP1&&(o.snappedEdgeP1=e.snappedEdgeP1),e.snappedEdgeP2&&(o.snappedEdgeP2=e.snappedEdgeP2),o.distance=e.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(e,t,i=Array.from(this.world.meshes)){return this.three.set(e,t),this.intersect(i)}intersect(e=Array.from(this.world.meshes)){const t=this.three.intersectObjects(e),i=this.filterClippingPlanes(t);return i.length>0?i[0]:null}filterClippingPlanes(e){if(!this.world.renderer)throw new Error("Renderer not found!");const t=this.world.renderer.three;if(!t.clippingPlanes)return e;const i=t.clippingPlanes;return e.length<=0||!i||i?.length<=0?e:e.filter(e=>i.every(t=>t.distanceToPoint(e.point)>0))}}class yo extends f{static uuid="d5d8bdf0-db25-4952-b951-b643af207ace";enabled=!0;list=new Map;onDisposed=new d;constructor(e){super(e),e.add(yo.uuid,this)}get(e){if(this.list.has(e.uuid))return this.list.get(e.uuid);const t=new wo(this.components,e);return this.list.set(e.uuid,t),e.onDisposed.add(()=>{this.delete(e)}),t}delete(e){const t=this.list.get(e.uuid);t&&t.dispose(),this.list.delete(e.uuid)}dispose(){for(const[e,t]of this.list)t.dispose();this.list.clear(),this.onDisposed.trigger()}}class _o extends p{onCameraChanged=new d;meshes=new Set;onAfterUpdate=new d;onBeforeUpdate=new d;onDisposed=new d;isDisposing=!1;enabled=!0;_dynamicAnchor=!1;_anchorRequestId=0;set dynamicAnchor(e){const t=this.renderer?.three.domElement.parentElement;if(!t)throw new Error("World: the renderer must have a parentElement to set dynamic anchoring.");e?t.addEventListener("pointerdown",this.onPointerDown):t.removeEventListener("pointerdown",this.onPointerDown),this._dynamicAnchor=e}get dynamicAnchor(){return this._dynamicAnchor}uuid=v.create();name;_scene;_camera;_renderer=null;onPointerDown=e=>{if(!this.camera.hasCameraControls())throw new Error("World: can't set dynamic anchor if the camera doesn't have controls.");if(0!==e.button)return;const t=this.getPointerPosition(e);if(!t)return;const i=this.components.get(yo).get(this),n=this.getPlaneAnchor(i,t);n&&To(this.camera.controls,n);const s=++this._anchorRequestId;i.castRay({position:t}).then(e=>{s!==this._anchorRequestId||this.isDisposing||!this._dynamicAnchor||e?.point&&this.camera.hasCameraControls()&&To(this.camera.controls,e.point)})};getPointerPosition(e){const t=this.renderer?.three.domElement;if(!t)return null;const i=t.getBoundingClientRect();return new c.Vector2((e.clientX-i.left)/(i.right-i.left)*2-1,-(e.clientY-i.top)/(i.bottom-i.top)*2+1)}getPlaneAnchor(e,t){if(!this.camera.hasCameraControls())return null;const i=this.camera.three;e.three.setFromCamera(t,i);const n=this.camera.controls.getTarget(new c.Vector3),s=i.getWorldDirection(new c.Vector3),r=(new c.Plane).setFromNormalAndCoplanarPoint(s,n);return e.three.ray.intersectPlane(r,new c.Vector3)}_defaultCamera;get defaultCamera(){if(!this._defaultCamera)throw new Error("World: there is no default camera defined.");return this._defaultCamera}set defaultCamera(e){this._defaultCamera=e}get scene(){if(!this._scene)throw new Error("No scene initialized!");return this._scene}set scene(e){this._scene=e,e.worlds.set(this.uuid,this),e.currentWorld=this,e.onWorldChanged.trigger({world:this,action:"added"})}get camera(){if(!this._camera)throw new Error("No camera initialized!");return this._camera}set camera(e){this._camera||(this.defaultCamera=e),this._camera=e,e.currentWorld=this,this.onCameraChanged.trigger(e)}get renderer(){return this._renderer}set renderer(e){this._renderer=e,e&&(e.worlds.set(this.uuid,this),e.currentWorld=this,e.onWorldChanged.trigger({world:this,action:"added"}))}useDefaultCamera(){this.camera=this.defaultCamera}update(e){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(e),this.camera.isUpdateable()&&this.camera.update(e),this.renderer&&this.renderer.update(e),this.onAfterUpdate.trigger())}dispose(e=!0){if(this.isDisposing)return;this.enabled=!1,this.isDisposing=!0;const t=this.renderer?.three.domElement.parentElement;if(t&&t.removeEventListener("pointerdown",this.onPointerDown),this._dynamicAnchor=!1,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"}),e){const e=this.components.get(y);this.scene.dispose(),this.camera.isDisposeable()&&this.camera.dispose(),this.renderer&&this.renderer.dispose();for(const t of this.meshes)e.destroy(t);this.meshes.clear()}this._scene=null,this._camera=null,this._renderer=null;this.components.get(Mo).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class bo{_list;_scene;constructor(e,t){this._list=e,this._scene=t}get color(){return this._list.directionalLight.color.value}set color(e){this._list.directionalLight.color.value=e;for(const[,t]of this._scene.directionalLights)t.color.copy(e)}get intensity(){return this._list.directionalLight.intensity.value}set intensity(e){this._list.directionalLight.intensity.value=e;for(const[,t]of this._scene.directionalLights)t.intensity=e}get position(){return this._list.directionalLight.position.value.clone()}set position(e){this._list.directionalLight.position.value=e;for(const[,t]of this._scene.directionalLights)t.position.copy(e)}}class vo{_list;_scene;constructor(e,t){this._list=e,this._scene=t}get color(){return this._list.ambientLight.color.value}set color(e){this._list.ambientLight.color.value=e;for(const[,t]of this._scene.ambientLights)t.color.copy(e)}get intensity(){return this._list.ambientLight.intensity.value}set intensity(e){this._list.ambientLight.intensity.value=e;for(const[,t]of this._scene.ambientLights)t.intensity=e}}class xo extends dt{_config={backgroundColor:{value:new c.Color,type:"Color"},ambientLight:{color:{type:"Color",value:new c.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2}},directionalLight:{color:{type:"Color",value:new c.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2},position:{type:"Vector3",value:new c.Vector3}}};ambientLight=new vo(this._config,this._component);directionalLight=new bo(this._config,this._component);get backgroundColor(){return this._config.backgroundColor.value}set backgroundColor(e){this._config.backgroundColor.value=e,this._component.three.background=e}}class Co extends _{onSetup=new d;isSetup=!1;three;config=new xo(this,this.components,"Scene");_defaultConfig={backgroundColor:new c.Color(2107698),directionalLight:{color:new c.Color("white"),intensity:1.5,position:new c.Vector3(5,10,3)},ambientLight:{color:new c.Color("white"),intensity:1}};constructor(e){super(e),this.three=new c.Scene,this.three.background=new c.Color(2107698)}setup(e){const t={...this._defaultConfig,...e};this.config.backgroundColor=t.backgroundColor;const i=t.ambientLight;this.config.ambientLight.color=i.color,this.config.ambientLight.intensity=i.intensity;const n=t.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,o=new c.DirectionalLight(s,r);o.position.copy(n.position);const{color:a,intensity:l}=this.config.directionalLight,h=new c.AmbientLight(a,l);this.three.add(o,h),this.directionalLights.set(o.uuid,o),this.ambientLights.set(h.uuid,h),this.isSetup=!0,this.onSetup.trigger()}dispose(){super.dispose();this.components.get(pt).list.delete(this.config.uuid)}}const So='\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 Ao=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTO=1]="AUTO",e))(Ao||{});function To(e,t){const{minDistance:i}=e;e.minDistance=.01,e.setOrbitPoint(t.x,t.y,t.z),e.minDistance=i}class Po extends g{onBeforeUpdate=new d;onAfterUpdate=new d;onAspectUpdated=new d;onDisposed=new d;three;_resizeObserver=null;_allControls=new Map;get controls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");const e=this._allControls.get(this.currentWorld.uuid);if(!e)throw new Error("Controls not found!");return e}get enabled(){return null!==this.currentWorld&&this.controls.enabled}set enabled(e){null!==this.currentWorld&&(this.controls.enabled=e)}set currentWorld(e){if(super.currentWorld=e,!e)return;this.worlds.get(e.uuid)||this.worlds.set(e.uuid,e)}get currentWorld(){return this._currentWorld}constructor(e){super(e),this.three=this.setupCamera(),this.worlds.onItemSet.add(({value:e})=>{const t=this.newCameraControls();this.setupEvents(!0),this._allControls.set(e.uuid,t)}),this.worlds.onBeforeDelete.add(({value:e})=>{const t=this._allControls.get(e.uuid);t&&(t.dispose(),this._allControls.delete(e.uuid)),this._resizeObserver?.disconnect()})}dispose(){this.setupEvents(!1),this.onAspectUpdated.reset(),this.onBeforeUpdate.reset(),this.onAfterUpdate.reset(),this.three.removeFromParent(),this.onDisposed.trigger(),this.onDisposed.reset();for(const[e,t]of this._allControls)t.dispose();this.worlds.clear()}async fitToItems(e){const t=await this.getItemsBounding(e);await this.controls.fitToSphere(t,!0)}async setOrbitToItems(e){const t=await this.getItemsBounding(e);To(this.controls,t.center)}update(e){this.enabled&&(this.onBeforeUpdate.trigger(this),this.controls.update(e),this.onAfterUpdate.trigger(this))}updateAspect=()=>{if(this.currentWorld&&this.currentWorld.renderer){if(this.currentWorld.renderer?.isResizeable()){const e=this.currentWorld.renderer.getSize();if(0===e.width||0===e.height)return}if(this.three instanceof c.OrthographicCamera)this.onAspectUpdated.trigger();else if(this.currentWorld.renderer?.isResizeable()){const e=this.currentWorld.renderer.getSize();this.three.aspect=e.width/e.height,this.three.updateProjectionMatrix(),this.onAspectUpdated.trigger()}}};async getItemsBounding(e){const t=this.components.get(fs),i=this.components.get(Br);i.list.clear();const n=new c.Sphere;if(e)await i.addFromModelIdMap(e);else for(const[,e]of t.list)i.list.add(e.box);return i.get().getBoundingSphere(n),i.list.clear(),n}setupCamera(){const e=window.innerWidth/window.innerHeight,t=new c.PerspectiveCamera(60,e,1,1e3);return t.position.set(50,50,50),t.lookAt(new c.Vector3(0,0,0)),t}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!");r.install({THREE:Po.getSubsetOfThree()});const{domElement:e}=this.currentWorld.renderer.three,t=new r(this.three,e);return t.smoothTime=.2,t.dollyToCursor=!0,t.infinityDolly=!0,t.minDistance=6,t}setupEvents(e){if(this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),e){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:e}=this.currentWorld.renderer.three;this._resizeObserver=new ResizeObserver(this.updateAspect),this._resizeObserver.observe(e)}}static getSubsetOfThree(){return{MOUSE:c.MOUSE,Vector2:c.Vector2,Vector3:c.Vector3,Vector4:c.Vector4,Quaternion:c.Quaternion,Matrix4:c.Matrix4,Spherical:c.Spherical,Box3:c.Box3,Sphere:c.Sphere,Raycaster:c.Raycaster,MathUtils:c.MathUtils}}}class Mo extends f{static uuid="fdb61dc4-2ec1-4966-b83d-54ea795fad4a";onAfterUpdate=new d;onBeforeUpdate=new d;onDisposed=new d;list=new e.DataMap;enabled=!0;constructor(e){super(e),e.add(Mo.uuid,this)}create(){const e=new _o(this.components),t=e.uuid;if(this.list.has(t))throw new Error("There is already a world with this name!");return this.list.set(t,e),e}delete(e){if(!this.list.has(e.uuid))throw new Error("The provided world is not found in the list!");this.list.delete(e.uuid),e.dispose()}dispose(){this.enabled=!1;for(const[e,t]of this.list)t.dispose();this.list.clear(),this.onDisposed.trigger()}update(e){if(this.enabled)for(const[t,i]of this.list)i.update(e)}}class Eo extends dt{_config={visible:{value:!0,type:"Boolean"},color:{value:new c.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(e){this._config.visible.value=e,this._component.visible=e}get color(){return this._config.color.value}set color(e){this._config.color.value=e,this._component.material.uniforms.uColor.value=e,this._component.material.uniformsNeedUpdate=!0}get primarySize(){return this._config.primarySize.value}set primarySize(e){this._config.primarySize.value=e,this._component.material.uniforms.uSize1.value=e,this._component.material.uniformsNeedUpdate=!0}get secondarySize(){return this._config.secondarySize.value}set secondarySize(e){this._config.secondarySize.value=e,this._component.material.uniforms.uSize2.value=e,this._component.material.uniformsNeedUpdate=!0}get distance(){return this._config.distance.value}set distance(e){this._config.distance.value=e,this._component.material.uniforms.uDistance.value=e,this._component.material.uniformsNeedUpdate=!0}}class Io{onDisposed=new d;onSetup=new d;isSetup=!1;world;components;config;_defaultConfig={visible:!0,color:new c.Color(12303291),primarySize:1,secondarySize:10,distance:500};get visible(){return this.three.visible}set visible(e){if(this.three.visible=e,e){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(e){this._fade=e?3:0,this.material.uniforms.uFade.value=this._fade}three;_fade=3;constructor(e,t){this.world=t;const{color:i,primarySize:n,secondarySize:s,distance:r}=this._defaultConfig;this.components=e,this.config=new Eo(this,this.components,"Grid");const o=new c.PlaneGeometry(2,2,1,1),a=new c.ShaderMaterial({side:c.DoubleSide,uniforms:{uSize1:{value:n},uSize2:{value:s},uColor:{value:i},uDistance:{value:r},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 c.Mesh(o,a),this.three.frustumCulled=!1,t.scene.three.add(this.three),this.setupEvents(!0)}setup(e){const t={...this._defaultConfig,...e};this.config.visible=!0,this.config.color=t.color,this.config.primarySize=t.primarySize,this.config.secondarySize=t.secondarySize,this.config.distance=t.distance,this.isSetup=!0,this.onSetup.trigger()}dispose(){this.setupEvents(!1);this.components.get(pt).list.delete(this.config.uuid);this.components.get(y).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset(),this.world=null,this.components=null}setupEvents(e){if(this.world.isDisposing)return;if(!(this.world.camera instanceof Po))return;const t=this.world.camera.controls;e?t.addEventListener("update",this.updateZoom):t.removeEventListener("update",this.updateZoom)}updateZoom=()=>{this.world.camera instanceof Po&&(this.material.uniforms.uZoom.value=this.world.camera.three.zoom)}}class Do extends f{static uuid="d1e814d5-b81c-4452-87a2-f039375e0489";list=new Map;onDisposed=new d;enabled=!0;constructor(e){super(e),e.add(Do.uuid,this)}create(e){if(this.list.has(e.uuid))throw new Error("This world already has a grid!");const t=new Io(this.components,e);return this.list.set(e.uuid,t),e.onDisposed.add(()=>{this.delete(e)}),t}delete(e){const t=this.list.get(e.uuid);t&&t.dispose(),this.list.delete(e.uuid)}dispose(){for(const[e,t]of this.list)t.dispose();this.list.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}}class zo{static release="2.4.3";onDisposed=new d;list=new e.DataMap;enabled=!1;_timer;onInit=new d;add(e,t){if(this.list.has(e))throw new Error("You're trying to add a component that already exists in the components instance. Use Components.get() instead.");v.validate(e),this.list.set(e,t)}get(e){const t=e.uuid;if(!this.list.has(t)){const i=new e(this);return i.isDisposeable?.()&&i.onDisposed.add(()=>this.list.delete(t)),this.list.has(t)||this.add(t,i),i}return this.list.get(t)}constructor(){this._timer=new c.Timer,zo.setupBVH()}init(){this.enabled=!0;for(const[e,t]of this.list.entries())t.enabled=!0;this._timer.reset(),this.update(),this.onInit.trigger()}dispose(){let e,t;this.enabled=!1;for(const[i,n]of this.list)n.enabled=!1,i!==fs.uuid?i!==Mo.uuid?n.isDisposeable()&&n.dispose():t=n:e=n;t?.isDisposeable()&&t.dispose(),e?.dispose(),this._timer.dispose(),this.onDisposed.trigger()}update=()=>{if(!this.enabled)return;this._timer.update();const e=this._timer.getDelta();for(const[t,i]of this.list)i.enabled&&i.isUpdateable()&&i.update(e);requestAnimationFrame(this.update)};static setupBVH(){c.BufferGeometry.prototype.computeBoundsTree=ds,c.BufferGeometry.prototype.disposeBoundsTree=ps,c.Mesh.prototype.raycast=hs,c.LineSegments.prototype.raycast=hs}}class ko{constructor(e){this.camera=e}camera;enabled=!1;id="FirstPerson";set(e,t){if(this.enabled=e,e){if("Perspective"!==this.camera.projection.current)return void this.camera.set("Orbit");this.setupFirstPersonCamera(t)}}setupFirstPersonCamera(e){const t=this.camera.controls;if(e?.preventTargetAdjustment)t.minDistance=1,t.maxDistance=1,t.distance=1;else{const e=new c.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=r.ACTION.DOLLY,t.touches.two=r.ACTION.TOUCH_ZOOM_TRUCK}}class Bo{constructor(e){this.camera=e,this.activateOrbitControls()}camera;enabled=!0;id="Orbit";set(e,t){this.enabled=e,e&&this.activateOrbitControls(t)}activateOrbitControls(e){const t=this.camera.controls;t.minDistance=1,t.maxDistance=300;const i=new c.Vector3;t.getPosition(i);const n=i.length();if(t.distance=n,t.truckSpeed=2,e?.preventTargetAdjustment)return;const{rotation:s}=this.camera.three,r=new c.Vector3(0,0,-1).applyEuler(s),o=i.addScaledVector(r,n);t.moveTo(o.x,o.y,o.z)}}class Oo{constructor(e){this.camera=e,this.defaultAzimuthSpeed=e.controls.azimuthRotateSpeed,this.defaultPolarSpeed=e.controls.polarRotateSpeed}camera;enabled=!1;id="Plan";mouseAction1;mouseAction2;mouseInitialized=!1;defaultAzimuthSpeed;defaultPolarSpeed;set(e,t){this.enabled=e;const i=this.camera.controls;i.azimuthRotateSpeed=e?0:this.defaultAzimuthSpeed,i.polarRotateSpeed=e?0:this.defaultPolarSpeed,this.mouseInitialized||(this.mouseAction1=i.touches.one,this.mouseAction2=i.touches.two,this.mouseInitialized=!0),e?(i.mouseButtons.left=r.ACTION.TRUCK,i.touches.one=r.ACTION.TOUCH_TRUCK,i.touches.two=r.ACTION.TOUCH_ZOOM):(i.mouseButtons.left=r.ACTION.ROTATE,i.touches.one=this.mouseAction1,i.touches.two=this.mouseAction2)}}class Vo{onChanged=new d;current="Perspective";camera;matchOrthoDistanceEnabled=!1;_component;_previousDistance=-1;constructor(e){this._component=e,this.camera=e.three}async set(e){if(this.current===e)return;let t;"Orthographic"===e?t=this.setOrthoCamera():(await this.setPerspectiveCamera(),t=!0),t&&this.onChanged.trigger(this.camera)}async toggle(){const e="Perspective"===this.current?"Orthographic":"Perspective";await this.set(e)}setOrthoCamera(){if(!this._component.hasMode)return!1;if("FirstPerson"===this._component.mode.id)return!1;const e=this._component.currentWorld;if(!e||!e.renderer)return!1;this._previousDistance=this._component.controls.distance,this._component.controls.distance=200;const t=this.getPerspectiveDims();if(!t)return this._component.controls.distance=this._previousDistance,!1;const{width:i,height:n}=t;return this.setupOrthoCamera(n,i),this.camera=this._component.threeOrtho,this.current="Orthographic",!0}getPerspectiveDims(){const e=this._component.currentWorld;if(!e||!e.renderer)return null;const t=new c.Vector3;this._component.threePersp.getWorldDirection(t);const i=new c.Vector3;this._component.controls.getTarget(i);const n=i.clone().sub(this._component.threePersp.position).dot(t),s=e.renderer.getSize(),r=s.x/s.y,o=this._component.threePersp,a=2*n*Math.tan(o.fov*(Math.PI/180)/2);return{width:a*r,height:a}}setupOrthoCamera(e,t){this._component.controls.mouseButtons.wheel=r.ACTION.ZOOM,this._component.controls.mouseButtons.middle=r.ACTION.ZOOM;const i=this._component.threePersp,n=this._component.threeOrtho;n.zoom=1,n.left=t/-2,n.right=t/2,n.top=e/2,n.bottom=e/-2,n.updateProjectionMatrix(),n.position.copy(i.position),n.quaternion.copy(i.quaternion),this._component.controls.camera=n}getDistance(){const e=this._component.threePersp,t=this._component.threeOrtho;return(t.top-t.bottom)/t.zoom/(2*Math.tan(e.fov*(Math.PI/180)/2))}async setPerspectiveCamera(){this._component.controls.mouseButtons.wheel=r.ACTION.DOLLY,this._component.controls.mouseButtons.middle=r.ACTION.DOLLY;const e=this._component.threePersp,t=this._component.threeOrtho;e.position.copy(t.position),e.quaternion.copy(t.quaternion),this._component.controls.mouseButtons.wheel=r.ACTION.DOLLY,this.matchOrthoDistanceEnabled?this._component.controls.distance=this.getDistance():this._component.controls.distance=this._previousDistance,await this._component.controls.zoomTo(1),e.updateProjectionMatrix(),this._component.controls.camera=e,this.camera=e,this.current="Perspective"}}class Lo extends Po{projection;threeOrtho;threePersp;_userInputButtons={};_frustumSize=50;_navigationModes=new Map;_mode=null;previousSize=null;get mode(){if(!this._mode)throw new Error("Mode not found, camera not initialized");return this._mode}get hasMode(){return null!==this._mode}constructor(e){super(e),this.threePersp=this.three,this.threeOrtho=this.newOrthoCamera(),this.projection=new Vo(this),this.onAspectUpdated.add(()=>{this.setOrthoPerspCameraAspect()}),this.projection.onChanged.add(e=>{this.three=e,this.updateAspect()}),this.worlds.onItemSet.add(()=>{this._navigationModes.clear(),this._navigationModes.set("Orbit",new Bo(this)),this._navigationModes.set("FirstPerson",new ko(this)),this._navigationModes.set("Plan",new Oo(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()})}dispose(){super.dispose(),this.threeOrtho.removeFromParent()}set(e){if(this.hasMode&&this.mode.id!==e){if(this.mode.set(!1),!this._navigationModes.has(e))throw new Error("The specified mode does not exist!");this._mode=this._navigationModes.get(e),this.mode.set(!0)}}async fit(e,t=1.5){if(!this.enabled)return;const i=Number.MAX_VALUE,n=Number.MIN_VALUE,s=new c.Vector3(i,i,i),r=new c.Vector3(n,n,n);for(const t of e){const e=(new c.Box3).setFromObject(t);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 o=new c.Box3(s,r),a=this.components.get(fs);if(a.initialized)for(const[,e]of a.list){const t=e.box;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 l=new c.Vector3;o.getSize(l);const h=new c.Vector3;o.getCenter(h);const u=Math.max(l.x,l.y,l.z)*t,d=new c.Sphere(h,u);await this.controls.fitToSphere(d,!0)}setUserInput(e){e?this.enableUserInput():this.disableUserInput()}addCustomNavigationMode(e){this._navigationModes.set(e.id,e)}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 e=window.innerWidth/window.innerHeight;return new c.OrthographicCamera(this._frustumSize*e/-2,this._frustumSize*e/2,this._frustumSize/2,this._frustumSize/-2,.1,1e3)}setOrthoPerspCameraAspect(){if(!this.currentWorld||!this.currentWorld.renderer)return;if(!this.previousSize)return;const e=this.currentWorld.renderer.getSize();if(0===this.previousSize.x||0===this.previousSize.y)return void this.previousSize.copy(e);const t=this.threeOrtho.top,i=this.threeOrtho.right,n=t*(e.y/this.previousSize.y),s=i*(e.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(e)}}var No="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Fo(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Ro(e){throw new Error('Could not dynamically require "'+e+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Uo,jo={exports:{}};const $o=Fo((Uo||(Uo=1,jo.exports=function e(t,i,n){function s(o,a){if(!i[o]){if(!t[o]){if(!a&&Ro)return Ro(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:{}};t[o][0].call(c.exports,function(e){return s(t[o][1][e]||e)},c,c.exports,e,t,i,n)}return i[o].exports}for(var r=Ro,o=0;o<n.length;o++)s(n[o]);return s}({1:[function(e,t,i){var n=e("./utils"),s=e("./support"),r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(e){for(var t,i,s,o,a,l,c,h=[],u=0,d=e.length,p=d,f="string"!==n.getTypeOf(e);u<e.length;)p=d-u,s=f?(t=e[u++],i=u<d?e[u++]:0,u<d?e[u++]:0):(t=e.charCodeAt(u++),i=u<d?e.charCodeAt(u++):0,u<d?e.charCodeAt(u++):0),o=t>>2,a=(3&t)<<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(e){var t,i,n,o,a,l,c=0,h=0,u="data:";if(e.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");var d,p=3*(e=e.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(e.charAt(e.length-1)===r.charAt(64)&&p--,e.charAt(e.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<e.length;)t=r.indexOf(e.charAt(c++))<<2|(o=r.indexOf(e.charAt(c++)))>>4,i=(15&o)<<4|(a=r.indexOf(e.charAt(c++)))>>2,n=(3&a)<<6|(l=r.indexOf(e.charAt(c++))),d[h++]=t,64!==a&&(d[h++]=i),64!==l&&(d[h++]=n);return d}},{"./support":30,"./utils":32}],2:[function(e,t,i){var n=e("./external"),s=e("./stream/DataWorker"),r=e("./stream/Crc32Probe"),o=e("./stream/DataLengthProbe");function a(e,t,i,n,s){this.compressedSize=e,this.uncompressedSize=t,this.crc32=i,this.compression=n,this.compressedContent=s}a.prototype={getContentWorker:function(){var e=new s(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},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(e,t,i){return e.pipe(new r).pipe(new o("uncompressedSize")).pipe(t.compressWorker(i)).pipe(new o("compressedSize")).withStreamInfo("compression",t)},t.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,i){var n=e("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new n("STORE compression")},uncompressWorker:function(){return new n("STORE decompression")}},i.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,i){var n=e("./utils"),s=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==n.getTypeOf(e)?function(e,t,i,n){var r=s,o=n+i;e^=-1;for(var a=n;a<o;a++)e=e>>>8^r[255&(e^t[a])];return-1^e}(0|t,e,e.length,0):function(e,t,i,n){var r=s,o=n+i;e^=-1;for(var a=n;a<o;a++)e=e>>>8^r[255&(e^t.charCodeAt(a))];return-1^e}(0|t,e,e.length,0):0}},{"./utils":32}],5:[function(e,t,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(e,t,i){var n=null;n="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:n}},{lie:37}],7:[function(e,t,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,s=e("pako"),r=e("./utils"),o=e("./stream/GenericWorker"),a=n?"uint8array":"array";function l(e,t){o.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}i.magic="\b\0",r.inherits(l,o),l.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(r.transformTo(a,e.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 e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},i.compressWorker=function(e){return new l("Deflate",e)},i.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,i){function n(e,t){var i,n="";for(i=0;i<t;i++)n+=String.fromCharCode(255&e),e>>>=8;return n}function s(e,t,i,s,o,h){var u,d,p=e.file,f=e.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="",T=p.dir,P=p.date,M={crc32:0,compressedSize:0,uncompressedSize:0};t&&!i||(M.crc32=e.crc32,M.compressedSize=e.compressedSize,M.uncompressedSize=e.uncompressedSize);var E=0;t&&(E|=8),m||!v&&!x||(E|=2048);var I,D,z,k=0,B=0;T&&(k|=16),"UNIX"===o?(B=798,k|=(I=p.unixPermissions,D=T,z=I,I||(z=D?16893:33204),(65535&z)<<16)):(B=20,k|=function(e){return 63&(e||0)}(p.dosPermissions)),u=P.getUTCHours(),u<<=6,u|=P.getUTCMinutes(),u<<=5,u|=P.getUTCSeconds()/2,d=P.getUTCFullYear()-1980,d<<=4,d|=P.getUTCMonth()+1,d<<=5,d|=P.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(E,2),O+=f.magic,O+=n(u,2),O+=n(d,2),O+=n(M.crc32,4),O+=n(M.compressedSize,4),O+=n(M.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=e("../utils"),o=e("../stream/GenericWorker"),a=e("../utf8"),l=e("../crc32"),c=e("../signature");function h(e,t,i,n){o.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=i,this.encodeFileName=n,this.streamFiles=e,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(e){var t=e.meta.percent||0,i=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,o.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:i?(t+100*(i-n-1))/i:100}}))},h.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var i=s(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0},h.prototype.closedSource=function(e){this.accumulate=!1;var t,i=this.streamFiles&&!e.file.dir,r=s(e,i,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),i)this.push({data:(t=e,c.DATA_DESCRIPTOR+n(t.crc32,4)+n(t.compressedSize,4)+n(t.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 e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var i,s,o,a,l,h,u=this.bytesWritten-e,d=(i=this.dirRecords.length,s=u,o=e,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(e){this._sources.push(e);var t=this;return e.on("data",function(e){t.processChunk(e)}),e.on("end",function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end()}),e.on("error",function(e){t.error(e)}),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(e){var t=this._sources;if(!o.prototype.error.call(this,e))return!1;for(var i=0;i<t.length;i++)try{t[i].error(e)}catch(e){}return!0},h.prototype.lock=function(){o.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock()},t.exports=h},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(e,t,i){var n=e("../compressions"),s=e("./ZipFileWorker");i.generateWorker=function(e,t,i){var r=new s(t.streamFiles,i,t.platform,t.encodeFileName),o=0;try{e.forEach(function(e,i){o++;var s=function(e,t){var i=e||t,s=n[i];if(!s)throw new Error(i+" is not a valid compression method !");return s}(i.options.compression,t.compression),a=i.options.compressionOptions||t.compressionOptions||{},l=i.dir,c=i.date;i._compressWorker(s,a).withStreamInfo("file",{name:e,dir:l,date:c,comment:i.comment||"",unixPermissions:i.unixPermissions,dosPermissions:i.dosPermissions}).pipe(r)}),r.entriesCount=o}catch(e){r.error(e)}return r}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(e,t,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 e=new n;for(var t in this)"function"!=typeof this[t]&&(e[t]=this[t]);return e}}(n.prototype=e("./object")).loadAsync=e("./load"),n.support=e("./support"),n.defaults=e("./defaults"),n.version="3.10.1",n.loadAsync=function(e,t){return(new n).loadAsync(e,t)},n.external=e("./external"),t.exports=n},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(e,t,i){var n=e("./utils"),s=e("./external"),r=e("./utf8"),o=e("./zipEntries"),a=e("./stream/Crc32Probe"),l=e("./nodejsUtils");function c(e){return new s.Promise(function(t,i){var n=e.decompressed.getContentWorker().pipe(new a);n.on("error",function(e){i(e)}).on("end",function(){n.streamInfo.crc32!==e.decompressed.crc32?i(new Error("Corrupted zip : CRC32 mismatch")):t()}).resume()})}t.exports=function(e,t){var i=this;return t=n.extend(t||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:r.utf8decode}),l.isNode&&l.isStream(e)?s.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):n.prepareContent("the loaded zip file",e,!0,t.optimizedBinaryString,t.base64).then(function(e){var i=new o(t);return i.load(e),i}).then(function(e){var i=[s.Promise.resolve(e)],n=e.files;if(t.checkCRC32)for(var r=0;r<n.length;r++)i.push(c(n[r]));return s.Promise.all(i)}).then(function(e){for(var s=e.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:t.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(e,t,i){var n=e("../utils"),s=e("../stream/GenericWorker");function r(e,t){s.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=!1,this._bindStream(t)}n.inherits(r,s),r.prototype._bindStream=function(e){var t=this;(this._stream=e).pause(),e.on("data",function(e){t.push({data:e,meta:{percent:0}})}).on("error",function(e){t.isPaused?this.generatedError=e:t.error(e)}).on("end",function(){t.isPaused?t._upstreamEnded=!0:t.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)},t.exports=r},{"../stream/GenericWorker":28,"../utils":32}],13:[function(e,t,i){var n=e("readable-stream").Readable;function s(e,t,i){n.call(this,t),this._helper=e;var s=this;e.on("data",function(e,t){s.push(e)||s._helper.pause(),i&&i(t)}).on("error",function(e){s.emit("error",e)}).on("end",function(){s.push(null)})}e("../utils").inherits(s,n),s.prototype._read=function(){this._helper.resume()},t.exports=s},{"../utils":32,"readable-stream":16}],14:[function(e,t,i){t.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if("number"==typeof e)throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&"function"==typeof e.on&&"function"==typeof e.pause&&"function"==typeof e.resume}}},{}],15:[function(e,t,i){function n(e,t,i){var n,s=r.getTypeOf(t),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&&(e=m(e)),a.createFolders&&(n=f(e))&&g.call(this,n,!0);var u="string"===s&&!1===a.binary&&!1===a.base64;i&&void 0!==i.binary||(a.binary=!u),(t instanceof c&&0===t.uncompressedSize||a.dir||!t||0===t.length)&&(a.base64=!1,a.binary=!0,t="",a.compression="STORE",s="string");var w=null;w=t instanceof c||t instanceof o?t:d.isNode&&d.isStream(t)?new p(e,t):r.prepareContent(e,t,a.binary,a.optimizedBinaryString,a.base64);var y=new h(e,w,a);this.files[e]=y}var s=e("./utf8"),r=e("./utils"),o=e("./stream/GenericWorker"),a=e("./stream/StreamHelper"),l=e("./defaults"),c=e("./compressedObject"),h=e("./zipObject"),u=e("./generate"),d=e("./nodejsUtils"),p=e("./nodejs/NodejsStreamInputAdapter"),f=function(e){"/"===e.slice(-1)&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return 0<t?e.substring(0,t):""},m=function(e){return"/"!==e.slice(-1)&&(e+="/"),e},g=function(e,t){return t=void 0!==t?t:l.createFolders,e=m(e),this.files[e]||n.call(this,e,null,{dir:!0,createFolders:t}),this.files[e]};function w(e){return"[object RegExp]"===Object.prototype.toString.call(e)}var y={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,i,n;for(t in this.files)n=this.files[t],(i=t.slice(this.root.length,t.length))&&t.slice(0,this.root.length)===this.root&&e(i,n)},filter:function(e){var t=[];return this.forEach(function(i,n){e(i,n)&&t.push(n)}),t},file:function(e,t,i){if(1!==arguments.length)return e=this.root+e,n.call(this,e,t,i),this;if(w(e)){var s=e;return this.filter(function(e,t){return!t.dir&&s.test(e)})}var r=this.files[this.root+e];return r&&!r.dir?r:null},folder:function(e){if(!e)return this;if(w(e))return this.filter(function(t,i){return i.dir&&e.test(t)});var t=this.root+e,i=g.call(this,t),n=this.clone();return n.root=i.name,n},remove:function(e){e=this.root+e;var t=this.files[e];if(t||("/"!==e.slice(-1)&&(e+="/"),t=this.files[e]),t&&!t.dir)delete this.files[e];else for(var i=this.filter(function(t,i){return i.name.slice(0,e.length)===e}),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(e){var t,i={};try{if((i=r.extend(e||{},{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||"";t=u.generateWorker(this,i,n)}catch(e){(t=new o("error")).error(e)}return new a(t,i.type||"string",i.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return(e=e||{}).type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};t.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(e,t,i){t.exports=e("stream")},{stream:void 0}],17:[function(e,t,i){var n=e("./DataReader");function s(e){n.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=255&e[t]}e("../utils").inherits(s,n),s.prototype.byteAt=function(e){return this.data[this.zero+e]},s.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),s=e.charCodeAt(3),r=this.length-4;0<=r;--r)if(this.data[r]===t&&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(e){var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),s=e.charCodeAt(3),r=this.readData(4);return t===r[0]&&i===r[1]&&n===r[2]&&s===r[3]},s.prototype.readData=function(e){if(this.checkOffset(e),0===e)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./DataReader":18}],18:[function(e,t,i){var n=e("../utils");function s(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}s.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e},skip:function(e){this.setIndex(this.index+e)},byteAt:function(){},readInt:function(e){var t,i=0;for(this.checkOffset(e),t=this.index+e-1;t>=this.index;t--)i=(i<<8)+this.byteAt(t);return this.index+=e,i},readString:function(e){return n.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=s},{"../utils":32}],19:[function(e,t,i){var n=e("./Uint8ArrayReader");function s(e){n.call(this,e)}e("../utils").inherits(s,n),s.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,i){var n=e("./DataReader");function s(e){n.call(this,e)}e("../utils").inherits(s,n),s.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},s.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},s.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},s.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./DataReader":18}],21:[function(e,t,i){var n=e("./ArrayReader");function s(e){n.call(this,e)}e("../utils").inherits(s,n),s.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,i){var n=e("../utils"),s=e("../support"),r=e("./ArrayReader"),o=e("./StringReader"),a=e("./NodeBufferReader"),l=e("./Uint8ArrayReader");t.exports=function(e){var t=n.getTypeOf(e);return n.checkSupport(t),"string"!==t||s.uint8array?"nodebuffer"===t?new a(e):s.uint8array?new l(n.transformTo("uint8array",e)):new r(n.transformTo("array",e)):new o(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,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(e,t,i){var n=e("./GenericWorker"),s=e("../utils");function r(e){n.call(this,"ConvertWorker to "+e),this.destType=e}s.inherits(r,n),r.prototype.processChunk=function(e){this.push({data:s.transformTo(this.destType,e.data),meta:e.meta})},t.exports=r},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,i){var n=e("./GenericWorker"),s=e("../crc32");function r(){n.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(r,n),r.prototype.processChunk=function(e){this.streamInfo.crc32=s(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=r},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,i){var n=e("../utils"),s=e("./GenericWorker");function r(e){s.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}n.inherits(r,s),r.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}s.prototype.processChunk.call(this,e)},t.exports=r},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,i){var n=e("../utils"),s=e("./GenericWorker");function r(e){s.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=n.getTypeOf(e),t.isPaused||t._tickAndRepeat()},function(e){t.error(e)})}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 e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=r},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,i){function n(e){this.name=e||"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(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var i=0;i<this._listeners[e].length;i++)this._listeners[e][i].call(this,t)},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",function(e){t.processChunk(e)}),e.on("end",function(){t.end()}),e.on("error",function(e){t.error(e)}),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 e=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),e=!0),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e)},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e])},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 e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}},t.exports=n},{}],29:[function(e,t,i){var n=e("../utils"),s=e("./ConvertWorker"),r=e("./GenericWorker"),o=e("../base64"),a=e("../support"),l=e("../external"),c=null;if(a.nodestream)try{c=e("../nodejs/NodejsStreamOutputAdapter")}catch(e){}function h(e,t){return new l.Promise(function(i,s){var r=[],a=e._internalType,l=e._outputType,c=e._mimeType;e.on("data",function(e,i){r.push(e),t&&t(i)}).on("error",function(e){r=[],s(e)}).on("end",function(){try{var e=function(e,t,i){switch(e){case"blob":return n.newBlob(n.transformTo("arraybuffer",t),i);case"base64":return o.encode(t);default:return n.transformTo(e,t)}}(l,function(e,t){var i,n=0,s=null,r=0;for(i=0;i<t.length;i++)r+=t[i].length;switch(e){case"string":return t.join("");case"array":return Array.prototype.concat.apply([],t);case"uint8array":for(s=new Uint8Array(r),i=0;i<t.length;i++)s.set(t[i],n),n+=t[i].length;return s;case"nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}(a,r),c);i(e)}catch(e){s(e)}r=[]}).resume()})}function u(e,t,i){var o=t;switch(t){case"blob":case"arraybuffer":o="uint8array";break;case"base64":o="string"}try{this._internalType=o,this._outputType=t,this._mimeType=i,n.checkSupport(o),this._worker=e.pipe(new s(o)),e.lock()}catch(e){this._worker=new r("error"),this._worker.error(e)}}u.prototype={accumulate:function(e){return h(this,e)},on:function(e,t){var i=this;return"data"===e?this._worker.on(e,function(e){t.call(i,e.data,e.meta)}):this._worker.on(e,function(){n.delay(t,arguments,i)}),this},resume:function(){return n.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){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},e)}},t.exports=u},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(e,t,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(e){try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);s.append(n),i.blob=0===s.getBlob("application/zip").size}catch(e){i.blob=!1}}}try{i.nodestream=!!e("readable-stream").Readable}catch(e){i.nodestream=!1}},{"readable-stream":16}],31:[function(e,t,i){for(var n=e("./utils"),s=e("./support"),r=e("./nodejsUtils"),o=e("./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(e){return s.nodebuffer?r.newBufferFrom(e,"utf-8"):function(e){var t,i,n,r,o,a=e.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(t=s.uint8array?new Uint8Array(l):new Array(l),r=o=0;o<l;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),i<128?t[o++]=i:(i<2048?t[o++]=192|i>>>6:(i<65536?t[o++]=224|i>>>12:(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63),t[o++]=128|i>>>6&63),t[o++]=128|63&i);return t}(e)},i.utf8decode=function(e){return s.nodebuffer?n.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,i,s,r,o=e.length,l=new Array(2*o);for(t=i=0;t<o;)if((s=e[t++])<128)l[i++]=s;else if(4<(r=a[s]))l[i++]=65533,t+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&t<o;)s=s<<6|63&e[t++],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)}(e=n.transformTo(s.uint8array?"uint8array":"array",e))},n.inherits(c,o),c.prototype.processChunk=function(e){var t=n.transformTo(s.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(s.uint8array){var r=t;(t=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),t.set(r,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var o=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;0<=i&&128==(192&e[i]);)i--;return i<0||0===i?t:i+a[e[i]]>t?i:t}(t),l=t;o!==t.length&&(s.uint8array?(l=t.subarray(0,o),this.leftOver=t.subarray(o,t.length)):(l=t.slice(0,o),this.leftOver=t.slice(o,t.length))),this.push({data:i.utf8decode(l),meta:e.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(e){this.push({data:i.utf8encode(e.data),meta:e.meta})},i.Utf8EncodeWorker=h},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,i){var n=e("./support"),s=e("./base64"),r=e("./nodejsUtils"),o=e("./external");function a(e){return e}function l(e,t){for(var i=0;i<e.length;++i)t[i]=255&e.charCodeAt(i);return t}e("setimmediate"),i.newBlob=function(e,t){i.checkSupport("blob");try{return new Blob([e],{type:t})}catch(i){try{var n=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return n.append(e),n.getBlob(t)}catch(e){throw new Error("Bug : can't construct the Blob.")}}};var c={stringifyByChunk:function(e,t,i){var n=[],s=0,r=e.length;if(r<=i)return String.fromCharCode.apply(null,e);for(;s<r;)"array"===t||"nodebuffer"===t?n.push(String.fromCharCode.apply(null,e.slice(s,Math.min(s+i,r)))):n.push(String.fromCharCode.apply(null,e.subarray(s,Math.min(s+i,r)))),s+=i;return n.join("")},stringifyByChar:function(e){for(var t="",i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t},applyCanBeUsed:{uint8array:function(){try{return n.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(e){return!1}}(),nodebuffer:function(){try{return n.nodebuffer&&1===String.fromCharCode.apply(null,r.allocBuffer(1)).length}catch(e){return!1}}()}};function h(e){var t=65536,n=i.getTypeOf(e),s=!0;if("uint8array"===n?s=c.applyCanBeUsed.uint8array:"nodebuffer"===n&&(s=c.applyCanBeUsed.nodebuffer),s)for(;1<t;)try{return c.stringifyByChunk(e,n,t)}catch(e){t=Math.floor(t/2)}return c.stringifyByChar(e)}function u(e,t){for(var i=0;i<e.length;i++)t[i]=e[i];return t}i.applyFromCharCode=h;var d={};d.string={string:a,array:function(e){return l(e,new Array(e.length))},arraybuffer:function(e){return d.string.uint8array(e).buffer},uint8array:function(e){return l(e,new Uint8Array(e.length))},nodebuffer:function(e){return l(e,r.allocBuffer(e.length))}},d.array={string:h,array:a,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return r.newBufferFrom(e)}},d.arraybuffer={string:function(e){return h(new Uint8Array(e))},array:function(e){return u(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:a,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return r.newBufferFrom(new Uint8Array(e))}},d.uint8array={string:h,array:function(e){return u(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:a,nodebuffer:function(e){return r.newBufferFrom(e)}},d.nodebuffer={string:h,array:function(e){return u(e,new Array(e.length))},arraybuffer:function(e){return d.nodebuffer.uint8array(e).buffer},uint8array:function(e){return u(e,new Uint8Array(e.length))},nodebuffer:a},i.transformTo=function(e,t){if(t=t||"",!e)return t;i.checkSupport(e);var n=i.getTypeOf(t);return d[n][e](t)},i.resolve=function(e){for(var t=e.split("/"),i=[],n=0;n<t.length;n++){var s=t[n];"."===s||""===s&&0!==n&&n!==t.length-1||(".."===s?i.pop():i.push(s))}return i.join("/")},i.getTypeOf=function(e){return"string"==typeof e?"string":"[object Array]"===Object.prototype.toString.call(e)?"array":n.nodebuffer&&r.isBuffer(e)?"nodebuffer":n.uint8array&&e instanceof Uint8Array?"uint8array":n.arraybuffer&&e instanceof ArrayBuffer?"arraybuffer":void 0},i.checkSupport=function(e){if(!n[e.toLowerCase()])throw new Error(e+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(e){var t,i,n="";for(i=0;i<(e||"").length;i++)n+="\\x"+((t=e.charCodeAt(i))<16?"0":"")+t.toString(16).toUpperCase();return n},i.delay=function(e,t,i){setImmediate(function(){e.apply(i||null,t||[])})},i.inherits=function(e,t){function i(){}i.prototype=t.prototype,e.prototype=new i},i.extend=function(){var e,t,i={};for(e=0;e<arguments.length;e++)for(t in arguments[e])Object.prototype.hasOwnProperty.call(arguments[e],t)&&void 0===i[t]&&(i[t]=arguments[e][t]);return i},i.prepareContent=function(e,t,r,a,c){return o.Promise.resolve(t).then(function(e){return n.blob&&(e instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(e)))&&"undefined"!=typeof FileReader?new o.Promise(function(t,i){var n=new FileReader;n.onload=function(e){t(e.target.result)},n.onerror=function(e){i(e.target.error)},n.readAsArrayBuffer(e)}):e}).then(function(t){var h,u=i.getTypeOf(t);return u?("arraybuffer"===u?t=i.transformTo("uint8array",t):"string"===u&&(c?t=s.decode(t):r&&!0!==a&&(t=l(h=t,n.uint8array?new Uint8Array(h.length):new Array(h.length)))),t):o.Promise.reject(new Error("Can't read the data of '"+e+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(e,t,i){var n=e("./reader/readerFor"),s=e("./utils"),r=e("./signature"),o=e("./zipEntry"),a=e("./support");function l(e){this.files=[],this.loadOptions=e}l.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+s.pretty(t)+", expected "+s.pretty(e)+")")}},isSignature:function(e,t){var i=this.reader.index;this.reader.setIndex(e);var n=this.reader.readString(4)===t;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 e=this.reader.readData(this.zipCommentLength),t=a.uint8array?"uint8array":"array",i=s.transformTo(t,e);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 e,t,i,n=this.zip64EndOfCentralSize-44;0<n;)e=this.reader.readInt(2),t=this.reader.readInt(4),i=this.reader.readData(t),this.zip64ExtensibleData[e]={id:e,length:t,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 e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(r.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes()},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(r.CENTRAL_FILE_HEADER);)(e=new o({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(e);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 e=this.reader.lastIndexOfSignature(r.CENTRAL_DIRECTORY_END);if(e<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(e);var t=e;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,(e=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(e),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=t-i;if(0<n)this.isSignature(t,r.CENTRAL_FILE_HEADER)||(this.reader.zero=n);else if(n<0)throw new Error("Corrupted zip: missing "+Math.abs(n)+" bytes.")},prepareReader:function(e){this.reader=n(e)},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},t.exports=l},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(e,t,i){var n=e("./reader/readerFor"),s=e("./utils"),r=e("./compressedObject"),o=e("./crc32"),a=e("./utf8"),l=e("./compressions"),c=e("./support");function h(e,t){this.options=e,this.loadOptions=t}h.prototype={isEncrypted:function(){return!(1&~this.bitFlag)},useUTF8:function(){return!(2048&~this.bitFlag)},readLocalPart:function(e){var t,i;if(e.skip(22),this.fileNameLength=e.readInt(2),i=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.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===(t=function(e){for(var t in l)if(Object.prototype.hasOwnProperty.call(l,t)&&l[t].magic===e)return l[t];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,t,e.readData(this.compressedSize))},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=n(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t,i,n,s=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4<s;)t=e.readInt(2),i=e.readInt(2),n=e.readData(i),this.extraFields[t]={id:t,length:i,value:n};e.setIndex(s)},handleUTF8:function(){var e=c.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var t=this.findExtraFieldUnicodePath();if(null!==t)this.fileNameStr=t;else{var i=s.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(i)}var n=this.findExtraFieldUnicodeComment();if(null!==n)this.fileCommentStr=n;else{var r=s.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(r)}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=n(e.value);return 1!==t.readInt(1)||o(this.fileName)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=n(e.value);return 1!==t.readInt(1)||o(this.fileComment)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null}},t.exports=h},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(e,t,i){function n(e,t,i){this.name=e,this.dir=i.dir,this.date=i.date,this.comment=i.comment,this.unixPermissions=i.unixPermissions,this.dosPermissions=i.dosPermissions,this._data=t,this._dataBinary=i.binary,this.options={compression:i.compression,compressionOptions:i.compressionOptions}}var s=e("./stream/StreamHelper"),r=e("./stream/DataWorker"),o=e("./utf8"),a=e("./compressedObject"),l=e("./stream/GenericWorker");n.prototype={internalStream:function(e){var t=null,i="string";try{if(!e)throw new Error("No output type specified.");var n="string"===(i=e.toLowerCase())||"text"===i;"binarystring"!==i&&"text"!==i||(i="string"),t=this._decompressWorker();var r=!this._dataBinary;r&&!n&&(t=t.pipe(new o.Utf8EncodeWorker)),!r&&n&&(t=t.pipe(new o.Utf8DecodeWorker))}catch(e){(t=new l("error")).error(e)}return new s(t,i,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof a&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var i=this._decompressWorker();return this._dataBinary||(i=i.pipe(new o.Utf8EncodeWorker)),a.createWorkerFrom(i,e,t)},_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;t.exports=n},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(e,t,i){(function(e){var i,n,s=e.MutationObserver||e.WebKitMutationObserver;if(s){var r=0,o=new s(h),a=e.document.createTextNode("");o.observe(a,{characterData:!0}),i=function(){a.data=r=++r%2}}else if(e.setImmediate||void 0===e.MessageChannel)i="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var t=e.document.createElement("script");t.onreadystatechange=function(){h(),t.onreadystatechange=null,t.parentNode.removeChild(t),t=null},e.document.documentElement.appendChild(t)}:function(){setTimeout(h,0)};else{var l=new e.MessageChannel;l.port1.onmessage=h,i=function(){l.port2.postMessage(0)}}var c=[];function h(){var e,t;n=!0;for(var i=c.length;i;){for(t=c,c=[],e=-1;++e<i;)t[e]();i=c.length}n=!1}t.exports=function(e){1!==c.push(e)||n||i()}}).call(this,void 0!==No?No:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(e,t,i){var n=e("immediate");function s(){}var r={},o=["REJECTED"],a=["FULFILLED"],l=["PENDING"];function c(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,e!==s&&p(this,e)}function h(e,t,i){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof i&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}function u(e,t,i){n(function(){var n;try{n=t(i)}catch(t){return r.reject(e,t)}n===e?r.reject(e,new TypeError("Cannot resolve promise with itself")):r.resolve(e,n)})}function d(e){var t=e&&e.then;if(e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof t)return function(){t.apply(e,arguments)}}function p(e,t){var i=!1;function n(t){i||(i=!0,r.reject(e,t))}function s(t){i||(i=!0,r.resolve(e,t))}var o=f(function(){t(s,n)});"error"===o.status&&n(o.value)}function f(e,t){var i={};try{i.value=e(t),i.status="success"}catch(e){i.status="error",i.value=e}return i}(t.exports=c).prototype.finally=function(e){if("function"!=typeof e)return this;var t=this.constructor;return this.then(function(i){return t.resolve(e()).then(function(){return i})},function(i){return t.resolve(e()).then(function(){throw i})})},c.prototype.catch=function(e){return this.then(null,e)},c.prototype.then=function(e,t){if("function"!=typeof e&&this.state===a||"function"!=typeof t&&this.state===o)return this;var i=new this.constructor(s);return this.state!==l?u(i,this.state===a?e:t,this.outcome):this.queue.push(new h(i,e,t)),i},h.prototype.callFulfilled=function(e){r.resolve(this.promise,e)},h.prototype.otherCallFulfilled=function(e){u(this.promise,this.onFulfilled,e)},h.prototype.callRejected=function(e){r.reject(this.promise,e)},h.prototype.otherCallRejected=function(e){u(this.promise,this.onRejected,e)},r.resolve=function(e,t){var i=f(d,t);if("error"===i.status)return r.reject(e,i.value);var n=i.value;if(n)p(e,n);else{e.state=a,e.outcome=t;for(var s=-1,o=e.queue.length;++s<o;)e.queue[s].callFulfilled(t)}return e},r.reject=function(e,t){e.state=o,e.outcome=t;for(var i=-1,n=e.queue.length;++i<n;)e.queue[i].callRejected(t);return e},c.resolve=function(e){return e instanceof this?e:r.resolve(new this(s),e)},c.reject=function(e){var t=new this(s);return r.reject(t,e)},c.all=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.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(e[l],l);return c;function h(e,s){t.resolve(e).then(function(e){o[s]=e,++a!==i||n||(n=!0,r.resolve(c,o))},function(e){n||(n=!0,r.reject(c,e))})}},c.race=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.length,n=!1;if(!i)return this.resolve([]);for(var o,a=-1,l=new this(s);++a<i;)o=e[a],t.resolve(o).then(function(e){n||(n=!0,r.resolve(l,e))},function(e){n||(n=!0,r.reject(l,e))});return l}},{immediate:36}],38:[function(e,t,i){var n={};(0,e("./lib/utils/common").assign)(n,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=n},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(e,t,i){var n=e("./zlib/deflate"),s=e("./utils/common"),r=e("./utils/strings"),o=e("./zlib/messages"),a=e("./zlib/zstream"),l=Object.prototype.toString,c=0,h=-1,u=0,d=8;function p(e){if(!(this instanceof p))return new p(e);this.options=s.assign({level:h,method:d,chunkSize:16384,windowBits:15,memLevel:8,strategy:u,to:""},e||{});var t=this.options;t.raw&&0<t.windowBits?t.windowBits=-t.windowBits:t.gzip&&0<t.windowBits&&t.windowBits<16&&(t.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,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==c)throw new Error(o[i]);if(t.header&&n.deflateSetHeader(this.strm,t.header),t.dictionary){var f;if(f="string"==typeof t.dictionary?r.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=n.deflateSetDictionary(this.strm,f))!==c)throw new Error(o[i]);this._dict_set=!0}}function f(e,t){var i=new p(t);if(i.push(e,!0),i.err)throw i.msg||o[i.err];return i.result}p.prototype.push=function(e,t){var i,o,a=this.strm,h=this.options.chunkSize;if(this.ended)return!1;o=t===~~t?t:!0===t?4:0,"string"==typeof e?a.input=r.string2buf(e):"[object ArrayBuffer]"===l.call(e)?a.input=new Uint8Array(e):a.input=e,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(e){this.chunks.push(e)},p.prototype.onEnd=function(e){e===c&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Deflate=p,i.deflate=f,i.deflateRaw=function(e,t){return(t=t||{}).raw=!0,f(e,t)},i.gzip=function(e,t){return(t=t||{}).gzip=!0,f(e,t)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(e,t,i){var n=e("./zlib/inflate"),s=e("./utils/common"),r=e("./utils/strings"),o=e("./zlib/constants"),a=e("./zlib/messages"),l=e("./zlib/zstream"),c=e("./zlib/gzheader"),h=Object.prototype.toString;function u(e){if(!(this instanceof u))return new u(e);this.options=s.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.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,t.windowBits);if(i!==o.Z_OK)throw new Error(a[i]);this.header=new c,n.inflateGetHeader(this.strm,this.header)}function d(e,t){var i=new u(t);if(i.push(e,!0),i.err)throw i.msg||a[i.err];return i.result}u.prototype.push=function(e,t){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=t===~~t?t:!0===t?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof e?p.input=r.binstring2buf(e):"[object ArrayBuffer]"===h.call(e)?p.input=new Uint8Array(e):p.input=e,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(e){this.chunks.push(e)},u.prototype.onEnd=function(e){e===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Inflate=u,i.inflate=d,i.inflateRaw=function(e,t){return(t=t||{}).raw=!0,d(e,t)},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(e,t,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;i.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var n in i)i.hasOwnProperty(n)&&(e[n]=i[n])}}return e},i.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var s={arraySet:function(e,t,i,n,s){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+n),s);else for(var r=0;r<n;r++)e[s+r]=t[i+r]},flattenChunks:function(e){var t,i,n,s,r,o;for(t=n=0,i=e.length;t<i;t++)n+=e[t].length;for(o=new Uint8Array(n),t=s=0,i=e.length;t<i;t++)r=e[t],o.set(r,s),s+=r.length;return o}},r={arraySet:function(e,t,i,n,s){for(var r=0;r<n;r++)e[s+r]=t[i+r]},flattenChunks:function(e){return[].concat.apply([],e)}};i.setTyped=function(e){e?(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(e,t,i){var n=e("./common"),s=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch(e){s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){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(e,t){if(t<65537&&(e.subarray&&r||!e.subarray&&s))return String.fromCharCode.apply(null,n.shrinkBuf(e,t));for(var i="",o=0;o<t;o++)i+=String.fromCharCode(e[o]);return i}o[254]=o[254]=1,i.string2buf=function(e){var t,i,s,r,o,a=e.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(t=new n.Buf8(l),r=o=0;o<l;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),i<128?t[o++]=i:(i<2048?t[o++]=192|i>>>6:(i<65536?t[o++]=224|i>>>12:(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63),t[o++]=128|i>>>6&63),t[o++]=128|63&i);return t},i.buf2binstring=function(e){return l(e,e.length)},i.binstring2buf=function(e){for(var t=new n.Buf8(e.length),i=0,s=t.length;i<s;i++)t[i]=e.charCodeAt(i);return t},i.buf2string=function(e,t){var i,n,s,r,a=t||e.length,c=new Array(2*a);for(i=n=0;i<a;)if((s=e[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&e[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(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;0<=i&&128==(192&e[i]);)i--;return i<0||0===i?t:i+o[e[i]]>t?i:t}},{"./common":41}],43:[function(e,t,i){t.exports=function(e,t,i,n){for(var s=65535&e,r=e>>>16&65535,o=0;0!==i;){for(i-=o=2e3<i?2e3:i;r=r+(s=s+t[n++]|0)|0,--o;);s%=65521,r%=65521}return s|r<<16}},{}],44:[function(e,t,i){t.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(e,t,i){var n=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,i,s){var r=n,o=s+i;e^=-1;for(var a=s;a<o;a++)e=e>>>8^r[255&(e^t[a])];return-1^e}},{}],46:[function(e,t,i){var n,s=e("../utils/common"),r=e("./trees"),o=e("./adler32"),a=e("./crc32"),l=e("./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,T=42,P=113,M=1,E=2,I=3,D=4;function z(e,t){return e.msg=l[t],t}function k(e){return(e<<1)-(4<e?9:0)}function B(e){for(var t=e.length;0<=--t;)e[t]=0}function O(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(s.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function V(e,t){r._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,O(e.strm)}function L(e,t){e.pending_buf[e.pending++]=t}function N(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function F(e,t){var i,n,s=e.max_chain_length,r=e.strstart,o=e.prev_length,a=e.nice_match,l=e.strstart>e.w_size-A?e.strstart-(e.w_size-A):0,c=e.window,h=e.w_mask,u=e.prev,d=e.strstart+S,p=c[r+o-1],f=c[r+o];e.prev_length>=e.good_match&&(s>>=2),a>e.lookahead&&(a=e.lookahead);do{if(c[(i=t)+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(e.match_start=t,a<=(o=n))break;p=c[r+o-1],f=c[r+o]}}}while((t=u[t&h])>l&&0!=--s);return o<=e.lookahead?o:e.lookahead}function R(e){var t,i,n,r,l,c,h,u,d,p,f=e.w_size;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=f+(f-A)){for(s.arraySet(e.window,e.window,f,f,0),e.match_start-=f,e.strstart-=f,e.block_start-=f,t=i=e.hash_size;n=e.head[--t],e.head[t]=f<=n?n-f:0,--i;);for(t=i=f;n=e.prev[--t],e.prev[t]=f<=n?n-f:0,--i;);r+=f}if(0===e.strm.avail_in)break;if(c=e.strm,h=e.window,u=e.strstart+e.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),e.lookahead+=i,e.lookahead+e.insert>=C)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+C-1])&e.hash_mask,e.prev[l&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=l,l++,e.insert--,!(e.lookahead+e.insert<C)););}while(e.lookahead<A&&0!==e.strm.avail_in)}function U(e,t){for(var i,n;;){if(e.lookahead<A){if(R(e),e.lookahead<A&&t===c)return M;if(0===e.lookahead)break}if(i=0,e.lookahead>=C&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+C-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-A&&(e.match_length=F(e,i)),e.match_length>=C)if(n=r._tr_tally(e,e.strstart-e.match_start,e.match_length-C),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=C){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+C-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart,0!=--e.match_length;);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(V(e,!1),0===e.strm.avail_out))return M}return e.insert=e.strstart<C-1?e.strstart:C-1,t===h?(V(e,!0),0===e.strm.avail_out?I:D):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?M:E}function j(e,t){for(var i,n,s;;){if(e.lookahead<A){if(R(e),e.lookahead<A&&t===c)return M;if(0===e.lookahead)break}if(i=0,e.lookahead>=C&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+C-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=C-1,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-A&&(e.match_length=F(e,i),e.match_length<=5&&(1===e.strategy||e.match_length===C&&4096<e.strstart-e.match_start)&&(e.match_length=C-1)),e.prev_length>=C&&e.match_length<=e.prev_length){for(s=e.strstart+e.lookahead-C,n=r._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-C),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=s&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+C-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!=--e.prev_length;);if(e.match_available=0,e.match_length=C-1,e.strstart++,n&&(V(e,!1),0===e.strm.avail_out))return M}else if(e.match_available){if((n=r._tr_tally(e,0,e.window[e.strstart-1]))&&V(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return M}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=r._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<C-1?e.strstart:C-1,t===h?(V(e,!0),0===e.strm.avail_out?I:D):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?M:E}function $(e,t,i,n,s){this.good_length=e,this.max_lazy=t,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 H(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=m,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?T:P,e.adler=2===t.wrap?0:1,t.last_flush=c,r._tr_init(t),u):z(e,d)}function G(e){var t,i=H(e);return i===u&&((t=e.state).window_size=2*t.w_size,B(t.head),t.max_lazy_match=n[t.level].max_lazy,t.good_match=n[t.level].good_length,t.nice_match=n[t.level].nice_length,t.max_chain_length=n[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=C-1,t.match_available=0,t.ins_h=0),i}function q(e,t,i,n,r,o){if(!e)return d;var a=1;if(t===p&&(t=6),n<0?(a=0,n=-n):15<n&&(a=2,n-=16),r<1||w<r||i!==g||n<8||15<n||t<0||9<t||o<0||f<o)return z(e,d);8===n&&(n=9);var l=new W;return(e.state=l).strm=e,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=t,l.strategy=o,l.method=i,G(e)}n=[new $(0,0,0,0,function(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(R(e),0===e.lookahead&&t===c)return M;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+i;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,V(e,!1),0===e.strm.avail_out))return M;if(e.strstart-e.block_start>=e.w_size-A&&(V(e,!1),0===e.strm.avail_out))return M}return e.insert=0,t===h?(V(e,!0),0===e.strm.avail_out?I:D):(e.strstart>e.block_start&&(V(e,!1),e.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(e,t){return q(e,t,g,15,8,0)},i.deflateInit2=q,i.deflateReset=G,i.deflateResetKeep=H,i.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?d:(e.state.gzhead=t,u):d},i.deflate=function(e,t){var i,s,o,l;if(!e||!e.state||5<t||t<0)return e?z(e,d):d;if(s=e.state,!e.output||!e.input&&0!==e.avail_in||666===s.status&&t!==h)return z(e,0===e.avail_out?-5:d);if(s.strm=e,i=s.last_flush,s.last_flush=t,s.status===T)if(2===s.wrap)e.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&&(e.adler=a(e.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=P);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=P,N(s,p),0!==s.strstart&&(N(s,e.adler>>>16),N(s,65535&e.adler)),e.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&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),O(e),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&&(e.adler=a(e.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&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),O(e),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&&(e.adler=a(e.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&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),O(e),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&&(e.adler=a(e.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(e),s.pending+2<=s.pending_buf_size&&(L(s,255&e.adler),L(s,e.adler>>8&255),e.adler=0,s.status=P)):s.status=P),0!==s.pending){if(O(e),0===e.avail_out)return s.last_flush=-1,u}else if(0===e.avail_in&&k(t)<=k(i)&&t!==h)return z(e,-5);if(666===s.status&&0!==e.avail_in)return z(e,-5);if(0!==e.avail_in||0!==s.lookahead||t!==c&&666!==s.status){var f=2===s.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(R(e),0===e.lookahead)){if(t===c)return M;break}if(e.match_length=0,i=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(V(e,!1),0===e.strm.avail_out))return M}return e.insert=0,t===h?(V(e,!0),0===e.strm.avail_out?I:D):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?M:E}(s,t):3===s.strategy?function(e,t){for(var i,n,s,o,a=e.window;;){if(e.lookahead<=S){if(R(e),e.lookahead<=S&&t===c)return M;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=C&&0<e.strstart&&(n=a[s=e.strstart-1])===a[++s]&&n===a[++s]&&n===a[++s]){o=e.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);e.match_length=S-(o-s),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=C?(i=r._tr_tally(e,1,e.match_length-C),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(V(e,!1),0===e.strm.avail_out))return M}return e.insert=0,t===h?(V(e,!0),0===e.strm.avail_out?I:D):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?M:E}(s,t):n[s.level].func(s,t);if(f!==I&&f!==D||(s.status=666),f===M||f===I)return 0===e.avail_out&&(s.last_flush=-1),u;if(f===E&&(1===t?r._tr_align(s):5!==t&&(r._tr_stored_block(s,0,0,!1),3===t&&(B(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),O(e),0===e.avail_out))return s.last_flush=-1,u}return t!==h?u:s.wrap<=0?1:(2===s.wrap?(L(s,255&e.adler),L(s,e.adler>>8&255),L(s,e.adler>>16&255),L(s,e.adler>>24&255),L(s,255&e.total_in),L(s,e.total_in>>8&255),L(s,e.total_in>>16&255),L(s,e.total_in>>24&255)):(N(s,e.adler>>>16),N(s,65535&e.adler)),O(e),0<s.wrap&&(s.wrap=-s.wrap),0!==s.pending?u:1)},i.deflateEnd=function(e){var t;return e&&e.state?(t=e.state.status)!==T&&69!==t&&73!==t&&91!==t&&103!==t&&t!==P&&666!==t?z(e,d):(e.state=null,t===P?z(e,-3):u):d},i.deflateSetDictionary=function(e,t){var i,n,r,a,l,c,h,p,f=t.length;if(!e||!e.state)return d;if(2===(a=(i=e.state).wrap)||1===a&&i.status!==T||i.lookahead)return d;for(1===a&&(e.adler=o(e.adler,t,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,t,f-i.w_size,i.w_size,0),t=p,f=i.w_size),l=e.avail_in,c=e.next_in,h=e.input,e.avail_in=f,e.next_in=0,e.input=t,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,e.next_in=c,e.input=h,e.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(e,t,i){t.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(e,t,i){t.exports=function(e,t){var i,n,s,r,o,a,l,c,h,u,d,p,f,m,g,w,y,_,b,v,x,C,S,A,T;i=e.state,n=e.next_in,A=e.input,s=n+(e.avail_in-5),r=e.next_out,T=e.output,o=r-(t-e.avail_out),a=r+(e.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;e:do{f<15&&(p+=A[n++]<<f,f+=8,p+=A[n++]<<f,f+=8),_=m[p&w];t:for(;;){if(p>>>=b=_>>>24,f-=b,0==(b=_>>>16&255))T[r++]=65535&_;else{if(!(16&b)){if(!(64&b)){_=m[(65535&_)+(p&(1<<b)-1)];continue t}if(32&b){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}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}e.msg="invalid distance code",i.mode=30;break e}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)){e.msg="invalid distance too far back",i.mode=30;break e}if(p>>>=b,f-=b,(b=r-o)<x){if(h<(b=x-b)&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(S=d,(C=0)===u){if(C+=c-b,b<v){for(v-=b;T[r++]=d[C++],--b;);C=r-x,S=T}}else if(u<b){if(C+=c+u-b,(b-=u)<v){for(v-=b;T[r++]=d[C++],--b;);if(C=0,u<v){for(v-=b=u;T[r++]=d[C++],--b;);C=r-x,S=T}}}else if(C+=u-b,b<v){for(v-=b;T[r++]=d[C++],--b;);C=r-x,S=T}for(;2<v;)T[r++]=S[C++],T[r++]=S[C++],T[r++]=S[C++],v-=3;v&&(T[r++]=S[C++],1<v&&(T[r++]=S[C++]))}else{for(C=r-x;T[r++]=T[C++],T[r++]=T[C++],T[r++]=T[C++],2<(v-=3););v&&(T[r++]=T[C++],1<v&&(T[r++]=T[C++]))}break}}break}}while(n<s&&r<a);n-=v=f>>3,p&=(1<<(f-=v<<3))-1,e.next_in=n,e.next_out=r,e.avail_in=n<s?s-n+5:5-(n-s),e.avail_out=r<a?a-r+257:257-(r-a),i.hold=p,i.bits=f}},{}],49:[function(e,t,i){var n=e("../utils/common"),s=e("./adler32"),r=e("./crc32"),o=e("./inffast"),a=e("./inftrees"),l=1,c=2,h=0,u=-2,d=1,p=852,f=592;function m(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<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(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=d,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new n.Buf32(p),t.distcode=t.distdyn=new n.Buf32(f),t.sane=1,t.back=-1,h):u}function y(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,w(e)):u}function _(e,t){var i,n;return e&&e.state?(n=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?u:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,y(e))):u}function b(e,t){var i,n;return e?(n=new g,(e.state=n).window=null,(i=_(e,t))!==h&&(e.state=null),i):u}var v,x,C=!0;function S(e){if(C){var t;for(v=new n.Buf32(512),x=new n.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(l,e.lens,0,288,v,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(c,e.lens,0,32,x,0,e.work,{bits:5}),C=!1}e.lencode=v,e.lenbits=9,e.distcode=x,e.distbits=5}function A(e,t,i,s){var r,o=e.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,t,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,t,i-s,r,o.wnext),(s-=r)?(n.arraySet(o.window,t,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(e){return b(e,15)},i.inflateInit2=b,i.inflate=function(e,t){var i,p,f,g,w,y,_,b,v,x,C,T,P,M,E,I,D,z,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(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return u;12===(i=e.state).mode&&(i.mode=13),w=e.next_out,f=e.output,_=e.avail_out,g=e.next_in,p=e.input,y=e.avail_in,b=i.hold,v=i.bits,x=y,C=_,V=h;e:for(;;)switch(i.mode){case d:if(0===i.wrap){i.mode=13;break}for(;v<16;){if(0===y)break e;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){e.msg="incorrect header check",i.mode=30;break}if(8!=(15&b)){e.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){e.msg="invalid window size",i.mode=30;break}i.dmax=1<<O,e.adler=i.check=1,i.mode=512&b?10:12,v=b=0;break;case 2:for(;v<16;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(i.flags=b,8!=(255&i.flags)){e.msg="unknown compression method",i.mode=30;break}if(57344&i.flags){e.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 e;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 e;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 e;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<(T=i.length)&&(T=y),T&&(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,T,O)),512&i.flags&&(i.check=r(i.check,p,T,g)),y-=T,g+=T,i.length-=T),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===y)break e;for(T=0;O=p[g+T++],i.head&&O&&i.length<65536&&(i.head.name+=String.fromCharCode(O)),O&&T<y;);if(512&i.flags&&(i.check=r(i.check,p,T,g)),y-=T,g+=T,O)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===y)break e;for(T=0;O=p[g+T++],i.head&&O&&i.length<65536&&(i.head.comment+=String.fromCharCode(O)),O&&T<y;);if(512&i.flags&&(i.check=r(i.check,p,T,g)),y-=T,g+=T,O)break e}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;v<16;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(b!==(65535&i.check)){e.msg="header crc mismatch",i.mode=30;break}v=b=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=12;break;case 10:for(;v<32;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}e.adler=i.check=m(b),v=b=0,i.mode=11;case 11:if(0===i.havedict)return e.next_out=w,e.avail_out=_,e.next_in=g,e.avail_in=y,i.hold=b,i.bits=v,2;e.adler=i.check=1,i.mode=12;case 12:if(5===t||6===t)break e;case 13:if(i.last){b>>>=7&v,v-=7&v,i.mode=27;break}for(;v<3;){if(0===y)break e;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!==t)break;b>>>=2,v-=2;break e;case 2:i.mode=17;break;case 3:e.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 e;y--,b+=p[g++]<<v,v+=8}if((65535&b)!=(b>>>16^65535)){e.msg="invalid stored block lengths",i.mode=30;break}if(i.length=65535&b,v=b=0,i.mode=15,6===t)break e;case 15:i.mode=16;case 16:if(T=i.length){if(y<T&&(T=y),_<T&&(T=_),0===T)break e;n.arraySet(f,p,g,T,w),y-=T,g+=T,_-=T,w+=T,i.length-=T;break}i.mode=12;break;case 17:for(;v<14;){if(0===y)break e;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){e.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 e;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){e.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,D=65535&F,!((E=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(D<16)b>>>=E,v-=E,i.lens[i.have++]=D;else{if(16===D){for(N=E+2;v<N;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(b>>>=E,v-=E,0===i.have){e.msg="invalid bit length repeat",i.mode=30;break}O=i.lens[i.have-1],T=3+(3&b),b>>>=2,v-=2}else if(17===D){for(N=E+3;v<N;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}v-=E,O=0,T=3+(7&(b>>>=E)),b>>>=3,v-=3}else{for(N=E+7;v<N;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}v-=E,O=0,T=11+(127&(b>>>=E)),b>>>=7,v-=7}if(i.have+T>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=30;break}for(;T--;)i.lens[i.have++]=O}}if(30===i.mode)break;if(0===i.lens[256]){e.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){e.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){e.msg="invalid distances set",i.mode=30;break}if(i.mode=20,6===t)break e;case 20:i.mode=21;case 21:if(6<=y&&258<=_){e.next_out=w,e.avail_out=_,e.next_in=g,e.avail_in=y,i.hold=b,i.bits=v,o(e,C),w=e.next_out,f=e.output,_=e.avail_out,g=e.next_in,p=e.input,y=e.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,D=65535&F,!((E=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(I&&!(240&I)){for(z=E,k=I,B=D;I=(F=i.lencode[B+((b&(1<<z+k)-1)>>z)])>>>16&255,D=65535&F,!(z+(E=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}b>>>=z,v-=z,i.back+=z}if(b>>>=E,v-=E,i.back+=E,i.length=D,0===I){i.mode=26;break}if(32&I){i.back=-1,i.mode=12;break}if(64&I){e.msg="invalid literal/length code",i.mode=30;break}i.extra=15&I,i.mode=22;case 22:if(i.extra){for(N=i.extra;v<N;){if(0===y)break e;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,D=65535&F,!((E=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(!(240&I)){for(z=E,k=I,B=D;I=(F=i.distcode[B+((b&(1<<z+k)-1)>>z)])>>>16&255,D=65535&F,!(z+(E=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}b>>>=z,v-=z,i.back+=z}if(b>>>=E,v-=E,i.back+=E,64&I){e.msg="invalid distance code",i.mode=30;break}i.offset=D,i.extra=15&I,i.mode=24;case 24:if(i.extra){for(N=i.extra;v<N;){if(0===y)break e;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){e.msg="invalid distance too far back",i.mode=30;break}i.mode=25;case 25:if(0===_)break e;if(T=C-_,i.offset>T){if((T=i.offset-T)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=30;break}P=T>i.wnext?(T-=i.wnext,i.wsize-T):i.wnext-T,T>i.length&&(T=i.length),M=i.window}else M=f,P=w-i.offset,T=i.length;for(_<T&&(T=_),_-=T,i.length-=T;f[w++]=M[P++],--T;);0===i.length&&(i.mode=21);break;case 26:if(0===_)break e;f[w++]=i.length,_--,i.mode=21;break;case 27:if(i.wrap){for(;v<32;){if(0===y)break e;y--,b|=p[g++]<<v,v+=8}if(C-=_,e.total_out+=C,i.total+=C,C&&(e.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){e.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 e;y--,b+=p[g++]<<v,v+=8}if(b!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=30;break}v=b=0}i.mode=29;case 29:V=1;break e;case 30:V=-3;break e;case 31:return-4;default:return u}return e.next_out=w,e.avail_out=_,e.next_in=g,e.avail_in=y,i.hold=b,i.bits=v,(i.wsize||C!==e.avail_out&&i.mode<30&&(i.mode<27||4!==t))&&A(e,e.output,e.next_out,C-e.avail_out)?(i.mode=31,-4):(x-=e.avail_in,C-=e.avail_out,e.total_in+=x,e.total_out+=C,i.total+=C,i.wrap&&C&&(e.adler=i.check=i.flags?r(i.check,f,C,e.next_out-C):s(i.check,f,C,e.next_out-C)),e.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===t)&&V===h&&(V=-5),V)},i.inflateEnd=function(e){if(!e||!e.state)return u;var t=e.state;return t.window&&(t.window=null),e.state=null,h},i.inflateGetHeader=function(e,t){var i;return e&&e.state&&2&(i=e.state).wrap?((i.head=t).done=!1,h):u},i.inflateSetDictionary=function(e,t){var i,n=t.length;return e&&e.state?0!==(i=e.state).wrap&&11!==i.mode?u:11===i.mode&&s(1,t,n,0)!==i.check?-3:A(e,t,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(e,t,i){var n=e("../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];t.exports=function(e,t,i,l,c,h,u,d){var p,f,m,g,w,y,_,b,v,x=d.bits,C=0,S=0,A=0,T=0,P=0,M=0,E=0,I=0,D=0,z=0,k=null,B=0,O=new n.Buf16(16),V=new n.Buf16(16),L=null,N=0;for(C=0;C<=15;C++)O[C]=0;for(S=0;S<l;S++)O[t[i+S]]++;for(P=x,T=15;1<=T&&0===O[T];T--);if(T<P&&(P=T),0===T)return c[h++]=20971520,c[h++]=20971520,d.bits=1,0;for(A=1;A<T&&0===O[A];A++);for(P<A&&(P=A),C=I=1;C<=15;C++)if(I<<=1,(I-=O[C])<0)return-1;if(0<I&&(0===e||1!==T))return-1;for(V[1]=0,C=1;C<15;C++)V[C+1]=V[C]+O[C];for(S=0;S<l;S++)0!==t[i+S]&&(u[V[t[i+S]]++]=S);if(y=0===e?(k=L=u,19):1===e?(k=s,B-=257,L=r,N-=257,256):(k=o,L=a,-1),C=A,w=h,E=S=z=0,m=-1,g=(D=1<<(M=P))-1,1===e&&852<D||2===e&&592<D)return 1;for(;;){for(_=C-E,v=u[S]<y?(b=0,u[S]):u[S]>y?(b=L[N+u[S]],k[B+u[S]]):(b=96,0),p=1<<C-E,A=f=1<<M;c[w+(z>>E)+(f-=p)]=_<<24|b<<16|v,0!==f;);for(p=1<<C-1;z&p;)p>>=1;if(0!==p?(z&=p-1,z+=p):z=0,S++,0==--O[C]){if(C===T)break;C=t[i+u[S]]}if(P<C&&(z&g)!==m){for(0===E&&(E=P),w+=A,I=1<<(M=C-E);M+E<T&&!((I-=O[M+E])<=0);)M++,I<<=1;if(D+=1<<M,1===e&&852<D||2===e&&592<D)return 1;c[m=z&g]=P<<24|M<<16|w-h}}return 0!==z&&(c[w+z]=C-E<<24|64<<16),d.bits=P,0}},{"../utils/common":41}],51:[function(e,t,i){t.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(e,t,i){var n=e("../utils/common"),s=0,r=1;function o(e){for(var t=e.length;0<=--t;)e[t]=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 T=new Array(2*u);o(T);var P=new Array(512);o(P);var M=new Array(256);o(M);var E=new Array(l);o(E);var I,D,z,k=new Array(u);function B(e,t,i,n,s){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=s,this.has_stree=e&&e.length}function O(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function V(e){return e<256?P[e]:P[256+(e>>>7)]}function L(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function N(e,t,i){e.bi_valid>m-i?(e.bi_buf|=t<<e.bi_valid&65535,L(e,e.bi_buf),e.bi_buf=t>>m-e.bi_valid,e.bi_valid+=i-m):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function F(e,t,i){N(e,i[2*t],i[2*t+1])}function R(e,t){for(var i=0;i|=1&e,e>>>=1,i<<=1,0<--t;);return i>>>1}function U(e,t,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<=t;s++){var a=e[2*s+1];0!==a&&(e[2*s]=R(r[a]++,a))}}function j(e){var t;for(t=0;t<h;t++)e.dyn_ltree[2*t]=0;for(t=0;t<u;t++)e.dyn_dtree[2*t]=0;for(t=0;t<d;t++)e.bl_tree[2*t]=0;e.dyn_ltree[2*w]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function $(e){8<e.bi_valid?L(e,e.bi_buf):0<e.bi_valid&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function W(e,t,i,n){var s=2*t,r=2*i;return e[s]<e[r]||e[s]===e[r]&&n[t]<=n[i]}function H(e,t,i){for(var n=e.heap[i],s=i<<1;s<=e.heap_len&&(s<e.heap_len&&W(t,e.heap[s+1],e.heap[s],e.depth)&&s++,!W(t,n,e.heap[s],e.depth));)e.heap[i]=e.heap[s],i=s,s<<=1;e.heap[i]=n}function G(e,t,i){var n,s,r,o,a=0;if(0!==e.last_lit)for(;n=e.pending_buf[e.d_buf+2*a]<<8|e.pending_buf[e.d_buf+2*a+1],s=e.pending_buf[e.l_buf+a],a++,0===n?F(e,s,t):(F(e,(r=M[s])+c+1,t),0!==(o=v[r])&&N(e,s-=E[r],o),F(e,r=V(--n),i),0!==(o=x[r])&&N(e,n-=k[r],o)),a<e.last_lit;);F(e,w,t)}function q(e,t){var i,n,s,r=t.dyn_tree,o=t.stat_desc.static_tree,a=t.stat_desc.has_stree,l=t.stat_desc.elems,c=-1;for(e.heap_len=0,e.heap_max=p,i=0;i<l;i++)0!==r[2*i]?(e.heap[++e.heap_len]=c=i,e.depth[i]=0):r[2*i+1]=0;for(;e.heap_len<2;)r[2*(s=e.heap[++e.heap_len]=c<2?++c:0)]=1,e.depth[s]=0,e.opt_len--,a&&(e.static_len-=o[2*s+1]);for(t.max_code=c,i=e.heap_len>>1;1<=i;i--)H(e,r,i);for(s=l;i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],H(e,r,1),n=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=n,r[2*s]=r[2*i]+r[2*n],e.depth[s]=(e.depth[i]>=e.depth[n]?e.depth[i]:e.depth[n])+1,r[2*i+1]=r[2*n+1]=s,e.heap[1]=s++,H(e,r,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,n,s,r,o,a,l=t.dyn_tree,c=t.max_code,h=t.stat_desc.static_tree,u=t.stat_desc.has_stree,d=t.stat_desc.extra_bits,m=t.stat_desc.extra_base,g=t.stat_desc.max_length,w=0;for(r=0;r<=f;r++)e.bl_count[r]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<p;i++)g<(r=l[2*l[2*(n=e.heap[i])+1]+1]+1)&&(r=g,w++),l[2*n+1]=r,c<n||(e.bl_count[r]++,o=0,m<=n&&(o=d[n-m]),a=l[2*n],e.opt_len+=a*(r+o),u&&(e.static_len+=a*(h[2*n+1]+o)));if(0!==w){do{for(r=g-1;0===e.bl_count[r];)r--;e.bl_count[r]--,e.bl_count[r+1]+=2,e.bl_count[g]--,w-=2}while(0<w);for(r=g;0!==r;r--)for(n=e.bl_count[r];0!==n;)c<(s=e.heap[--i])||(l[2*s+1]!==r&&(e.opt_len+=(r-l[2*s+1])*l[2*s],l[2*s+1]=r),n--)}}(e,t),U(r,c,e.bl_count)}function Z(e,t,i){var n,s,r=-1,o=t[1],a=0,l=7,c=4;for(0===o&&(l=138,c=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)s=o,o=t[2*(n+1)+1],++a<l&&s===o||(a<c?e.bl_tree[2*s]+=a:0!==s?(s!==r&&e.bl_tree[2*s]++,e.bl_tree[2*y]++):a<=10?e.bl_tree[2*_]++:e.bl_tree[2*b]++,r=s,c=(a=0)===o?(l=138,3):s===o?(l=6,3):(l=7,4))}function Y(e,t,i){var n,s,r=-1,o=t[1],a=0,l=7,c=4;for(0===o&&(l=138,c=3),n=0;n<=i;n++)if(s=o,o=t[2*(n+1)+1],!(++a<l&&s===o)){if(a<c)for(;F(e,s,e.bl_tree),0!=--a;);else 0!==s?(s!==r&&(F(e,s,e.bl_tree),a--),F(e,y,e.bl_tree),N(e,a-3,2)):a<=10?(F(e,_,e.bl_tree),N(e,a-3,3)):(F(e,b,e.bl_tree),N(e,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(e,t,i,s){var r,o,l;N(e,(a<<1)+(s?1:0),3),o=t,l=i,$(r=e),L(r,l),L(r,~l),n.arraySet(r.pending_buf,r.window,o,l,r.pending),r.pending+=l}i._tr_init=function(e){X||(function(){var e,t,i,n,s,r=new Array(f+1);for(n=i=0;n<l-1;n++)for(E[n]=i,e=0;e<1<<v[n];e++)M[i++]=n;for(M[i-1]=n,n=s=0;n<16;n++)for(k[n]=s,e=0;e<1<<x[n];e++)P[s++]=n;for(s>>=7;n<u;n++)for(k[n]=s<<7,e=0;e<1<<x[n]-7;e++)P[256+s++]=n;for(t=0;t<=f;t++)r[t]=0;for(e=0;e<=143;)A[2*e+1]=8,e++,r[8]++;for(;e<=255;)A[2*e+1]=9,e++,r[9]++;for(;e<=279;)A[2*e+1]=7,e++,r[7]++;for(;e<=287;)A[2*e+1]=8,e++,r[8]++;for(U(A,h+1,r),e=0;e<u;e++)T[2*e+1]=5,T[2*e]=R(e,5);I=new B(A,v,c+1,h,f),D=new B(T,x,0,u,f),z=new B(new Array(0),C,0,d,g)}(),X=!0),e.l_desc=new O(e.dyn_ltree,I),e.d_desc=new O(e.dyn_dtree,D),e.bl_desc=new O(e.bl_tree,z),e.bi_buf=0,e.bi_valid=0,j(e)},i._tr_stored_block=K,i._tr_flush_block=function(e,t,i,n){var o,a,l=0;0<e.level?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return s;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return r;for(t=32;t<c;t++)if(0!==e.dyn_ltree[2*t])return r;return s}(e)),q(e,e.l_desc),q(e,e.d_desc),l=function(e){var t;for(Z(e,e.dyn_ltree,e.l_desc.max_code),Z(e,e.dyn_dtree,e.d_desc.max_code),q(e,e.bl_desc),t=d-1;3<=t&&0===e.bl_tree[2*S[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),o=e.opt_len+3+7>>>3,(a=e.static_len+3+7>>>3)<=o&&(o=a)):o=a=i+5,i+4<=o&&-1!==t?K(e,t,i,n):4===e.strategy||a===o?(N(e,2+(n?1:0),3),G(e,A,T)):(N(e,4+(n?1:0),3),function(e,t,i,n){var s;for(N(e,t-257,5),N(e,i-1,5),N(e,n-4,4),s=0;s<n;s++)N(e,e.bl_tree[2*S[s]+1],3);Y(e,e.dyn_ltree,t-1),Y(e,e.dyn_dtree,i-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,l+1),G(e,e.dyn_ltree,e.dyn_dtree)),j(e),n&&$(e)},i._tr_tally=function(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(M[i]+c+1)]++,e.dyn_dtree[2*V(t)]++),e.last_lit===e.lit_bufsize-1},i._tr_align=function(e){var t;N(e,2,3),F(e,w,A),16===(t=e).bi_valid?(L(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):8<=t.bi_valid&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}},{"../utils/common":41}],53:[function(e,t,i){t.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(e,t,i){(function(e){!function(e,t){if(!e.setImmediate){var i,n,s,r,o=1,a={},l=!1,c=e.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(e);h=h&&h.setTimeout?h:e,i="[object process]"==={}.toString.call(e.process)?function(e){process.nextTick(function(){d(e)})}:function(){if(e.postMessage&&!e.importScripts){var t=!0,i=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=i,t}}()?(r="setImmediate$"+Math.random()+"$",e.addEventListener?e.addEventListener("message",p,!1):e.attachEvent("onmessage",p),function(t){e.postMessage(r+t,"*")}):e.MessageChannel?((s=new MessageChannel).port1.onmessage=function(e){d(e.data)},function(e){s.port2.postMessage(e)}):c&&"onreadystatechange"in c.createElement("script")?(n=c.documentElement,function(e){var t=c.createElement("script");t.onreadystatechange=function(){d(e),t.onreadystatechange=null,n.removeChild(t),t=null},n.appendChild(t)}):function(e){setTimeout(d,0,e)},h.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n<t.length;n++)t[n]=arguments[n+1];var s={callback:e,args:t};return a[o]=s,i(o),o++},h.clearImmediate=u}function u(e){delete a[e]}function d(e){if(l)setTimeout(d,0,e);else{var i=a[e];if(i){l=!0;try{!function(e){var i=e.callback,n=e.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(t,n)}}(i)}finally{u(e),l=!1}}}}function p(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(r)&&d(+t.data.slice(r.length))}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,void 0!==No?No:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10)),jo.exports));class Wo{date=new Date;author;guid=v.create();viewpoint;modifiedAuthor;modifiedDate;topic;_components;_comment="";set comment(e){const t=this._components.get(Zo);this._comment=e,this.modifiedDate=new Date,this.modifiedAuthor=t.config.author,this.topic?.comments.set(this.guid,this)}get comment(){return this._comment}constructor(e,t){this._components=e,this._comment=t;const i=this._components.get(Zo);this.author=i.config.author}toJSON(){const e={guid:this.guid,date:this.date.toISOString(),author:this.author,comment:this.comment,topic_guid:this.topic?.guid,viewpoint_guid:this.viewpoint,modified_date:this.modifiedDate?.toISOString(),modified_author:this.modifiedAuthor};for(const[t,i]of Object.entries(e))void 0===i&&delete e[t];return e}}class Ho{static default={title:"BCF Topic",type:"Issue",status:"Active"};guid=v.create();title=Ho.default.title;creationDate=new Date;creationAuthor="";viewpoints=new e.DataSet;relatedTopics=new e.DataSet;comments=new e.DataMap;documentReferences=new e.DataSet;customData={};description;serverAssignedId;dueDate;modifiedAuthor;modifiedDate;index;_type=Ho.default.type;set type(e){const t=this._components.get(Zo),{strict:i,types:n}=t.config;(!i||n.has(e))&&(this._type=e)}get type(){return this._type}_status=Ho.default.status;set status(e){const t=this._components.get(Zo),{strict:i,statuses:n}=t.config;(!i||n.has(e))&&(this._status=e)}get status(){return this._status}_priority=Ho.default.priority;set priority(e){const t=this._components.get(Zo);if(e){const{strict:i,priorities:n}=t.config;if(!(!i||n.has(e)))return;this._priority=e}else this._priority=e}get priority(){return this._priority}_stage=Ho.default.stage;set stage(e){const t=this._components.get(Zo);if(e){const{strict:i,stages:n}=t.config;if(!(!i||n.has(e)))return;this._stage=e}else this._stage=e}get stage(){return this._stage}_assignedTo=Ho.default.assignedTo;set assignedTo(e){const t=this._components.get(Zo);if(e){const{strict:i,users:n}=t.config;if(!(!i||n.has(e)))return;this._assignedTo=e}else this._assignedTo=e}get assignedTo(){return this._assignedTo}_labels=Ho.default.labels??new Set;set labels(e){const t=this._components.get(Zo),{strict:i,labels:n}=t.config;if(i){const t=new Set;for(const s of e){(!i||n.has(s))&&t.add(s)}this._labels=t}else this._labels=e}get labels(){return this._labels}_components;get _managerVersion(){return this._components.get(Zo).config.version}constructor(e){this._components=e;const t=e.get(Zo);this.creationAuthor=t.config.author,this.relatedTopics.guard=e=>e!==this.guid}set(e){const t=e,i=this;for(const n in e){if("guid"===n)continue;const e=t[n];n in this&&(i[n]=e)}return this._components.get(Zo).list.set(this.guid,this),this}createComment(e,t){const i=new Wo(this._components,e);return i.viewpoint=t,i.topic=this,this.comments.set(i.guid,i),i}createLabelTags(){const e=[...this.labels];if(this._components.get(Zo).config.exportCustomDataAsLabels)for(const t in this.customData){const i=this.customData[t];"string"==typeof i&&e.push(i)}return e}createCommentTags(){return[...this.comments.values()].map(e=>({$Guid:e.guid,Date:e.date.toISOString(),Author:e.author,Comment:e.comment,ModifiedAuthor:e.modifiedAuthor,ModifiedDate:e.modifiedDate?.toISOString(),Viewpoint:e.viewpoint?{$Guid:e.viewpoint}:void 0}))}createViewpointTags(){const e=this._components.get(ea);return[...this.viewpoints].map(t=>e.list.get(t)).filter(e=>e).map(t=>{const i={$Guid:t.guid,Viewpoint:`${t.title??t.guid}.bcfv`};if(e.snapshots.get(t.snapshot)){const n=e.getSnapshotExtension(t.snapshot);i.Snapshot=`${t.snapshot}.${n}`}return i})}createRelatedTopicTags(){return[...this.relatedTopics].map(e=>({$Guid:e}))}createDocumentReferencesTag(e=this._managerVersion){const t=[];if("3"!==e&&"2.1"!==e)return t;const i=this._components.get(Zo);for(const n of this.documentReferences){const s=i.documents.get(n);if(!s)continue;let r={$Guid:v.create(),Description:s.description};"2.1"===e&&(r={...r,$isExternal:"external"===s.type||void 0,ReferencedDocument:"external"===s.type?s.url:`../${s.fileName}`}),"3"===e&&(r={...r,DocumentGuid:"internal"===s.type?n:void 0,Url:"external"===s.type?s.url:void 0}),Object.keys(r).length>0&&t.push(r)}return t}toJSON(){const e={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:this.modifiedDate?.toISOString(),modified_author:this.modifiedAuthor,assigned_to:this.assignedTo,stage:this.stage,description:this.description,due_date:this.dueDate?.toISOString(),comments:[...this.comments].map(([e,t])=>t.toJSON()),relatedTopics:[...this.relatedTopics].map(e=>({related_topic_guid:e}))},t=this._components.get(ea);for(const i of this.viewpoints){const n=t.list.get(i);n&&(e.viewpoints||(e.viewpoints=[]),e.viewpoints.push(n.toJSON()))}const i=this._components.get(Zo);for(const t of this.documentReferences){const n=i.documents.get(t);n&&(e.document_references||(e.document_references=[]),"external"===n.type?e.document_references.push({guid:v.create(),description:n.description,url:n.url}):e.document_references.push({guid:v.create(),description:n.description,document_guid:t}))}for(const[t,i]of Object.entries(e))(void 0===i||Array.isArray(i)&&0===i.length)&&delete e[t];return e}serialize(){const e=this._managerVersion,t="3"===e,i={Markup:{Topic:{$Guid:this.guid,$TopicType:this.type,$TopicStatus:this.status,$ServerAssignedId:this.serverAssignedId,Title:this.title,Priority:this.priority,Index:"2.1"===e?this.index:void 0,Labels:t?{Label:this.createLabelTags()}:this.createLabelTags(),CreationDate:this.creationDate.toISOString(),CreationAuthor:this.creationAuthor,ModifiedDate:this.modifiedDate?.toISOString(),ModifiedAuthor:this.modifiedAuthor,DueDate:this.dueDate?.toISOString(),AssignedTo:this.assignedTo,Stage:this.stage,Description:this.description,DocumentReferences:t?{DocumentReference:this.createDocumentReferencesTag(e)}:void 0,DocumentReference:t?void 0:this.createDocumentReferencesTag(e),RelatedTopics:t?{RelatedTopic:this.createRelatedTopicTags()}:void 0,RelatedTopic:t?void 0:this.createRelatedTopicTags(),Comments:t?{Comment:this.createCommentTags()}:void 0,Viewpoints:t?{ViewPoint:this.createViewpointTags()}:void 0}}};return"2.1"===e&&(i.Markup.Viewpoints=this.createViewpointTags(),i.Markup.Comment=this.createCommentTags()),`<?xml version="1.0" encoding="UTF-8"?>\n ${lt.builder.build(i)}`}}const Go=(e,t)=>{if(""===t.trim())return;const i=Zo.xmlParser.parse(t).Extensions;if(!i)return;const{Priorities:n,TopicStatuses:s,TopicTypes:r,Users:o}=i;if(n&&n.Priority){const t=Array.isArray(n.Priority)?n.Priority:[n.Priority];for(const i of t)e.config.priorities.add(i)}if(s&&s.TopicStatus){const t=Array.isArray(s.TopicStatus)?s.TopicStatus:[s.TopicStatus];for(const i of t)e.config.statuses.add(i)}if(r&&r.TopicType){const t=Array.isArray(r.TopicType)?r.TopicType:[r.TopicType];for(const i of t)e.config.types.add(i)}if(o&&o.User){const t=Array.isArray(o.User)?o.User:[o.User];for(const i of t)e.config.users.add(i)}};class qo extends dt{_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(e){this._config.version.value=e}get author(){return this._config.author.value}set author(e){this._config.author.value=e}get types(){return this._config.types.value}set types(e){this._config.types.value=e}get statuses(){return this._config.statuses.value}set statuses(e){this._config.statuses.value=e}get priorities(){return this._config.priorities.value}set priorities(e){this._config.priorities.value=e}get labels(){return this._config.labels.value}set labels(e){this._config.labels.value=e}get stages(){return this._config.stages.value}set stages(e){this._config.stages.value=e}get users(){return this._config.users.value}set users(e){this._config.users.value=e}get includeSelectionTag(){return this._config.includeSelectionTag.value}set includeSelectionTag(e){this._config.includeSelectionTag.value=e}get updateExtensionsOnImport(){return this._config.updateExtensionsOnImport.value}set updateExtensionsOnImport(e){this._config.updateExtensionsOnImport.value=e}get strict(){return this._config.strict.value}set strict(e){this._config.strict.value=e}get includeAllExtensionsOnExport(){return this._config.includeAllExtensionsOnExport.value}set includeAllExtensionsOnExport(e){this._config.includeAllExtensionsOnExport.value=e}get fallbackVersionOnImport(){return this._config.fallbackVersionOnImport.value}set fallbackVersionOnImport(e){this._config.fallbackVersionOnImport.value=e}get ignoreIncompleteTopicsOnImport(){return this._config.ignoreIncompleteTopicsOnImport.value}set ignoreIncompleteTopicsOnImport(e){this._config.ignoreIncompleteTopicsOnImport.value=e}get exportCustomDataAsLabels(){return this._config.exportCustomDataAsLabels.value}set exportCustomDataAsLabels(e){this._config.exportCustomDataAsLabels.value=e}}class Zo extends f{static uuid="de977976-e4f6-4e4f-a01a-204727839802";enabled=!1;static xmlParser=new qe({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0});_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};config=new qo(this,this.components,"BCF Topics",Zo.uuid);list=new e.DataMap;documents=new e.DataMap;onSetup=new d;isSetup=!1;setup(e){if(this.isSetup)return;const t={...this._defaultConfig,...e};this.config.version=t.version,this.config.author=t.author,this.config.types=t.types,this.config.statuses=t.statuses,this.config.priorities=t.priorities,this.config.labels=t.labels,this.config.stages=t.stages,this.config.users=t.users,this.config.includeSelectionTag=t.includeSelectionTag,this.config.updateExtensionsOnImport=t.updateExtensionsOnImport,this.config.strict=t.strict,this.config.includeAllExtensionsOnExport=t.includeAllExtensionsOnExport,this.config.fallbackVersionOnImport=t.fallbackVersionOnImport||"",this.config.ignoreIncompleteTopicsOnImport=t.ignoreIncompleteTopicsOnImport,this.isSetup=!0,this.enabled=!0,this.onSetup.trigger()}onBCFImported=new d;create(e){const t=new Ho(this.components);return e?(t.guid=e.guid??t.guid,t.set(e)):this.list.set(t.guid,t),t}onDisposed=new d;dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}get usedTypes(){const e=[...this.list].map(([e,t])=>t.type);return new Set(e)}get usedStatuses(){const e=[...this.list].map(([e,t])=>t.status);return new Set(e)}get usedPriorities(){const e=[...this.list].map(([e,t])=>t.priority).filter(e=>e);return new Set(e)}get usedStages(){const e=[...this.list].map(([e,t])=>t.stage).filter(e=>e);return new Set(e)}get usedUsers(){const e=[];for(const[t,i]of this.list){e.push(i.creationAuthor),i.assignedTo&&e.push(i.assignedTo),i.modifiedAuthor&&e.push(i.modifiedAuthor);for(const[t,n]of i.comments)e.push(n.author),n.modifiedAuthor&&e.push(n.modifiedAuthor)}return new Set(e)}get usedLabels(){const e=[];for(const[t,i]of this.list)e.push(...i.labels);return new Set(e)}updateExtensions(){for(const[e,t]of this.list){for(const e of t.labels)this.config.labels.add(e);this.config.types.add(t.type),t.priority&&this.config.priorities.add(t.priority),t.stage&&this.config.stages.add(t.stage),this.config.statuses.add(t.status),this.config.users.add(t.creationAuthor),t.assignedTo&&this.config.users.add(t.assignedTo),t.modifiedAuthor&&this.config.users.add(t.modifiedAuthor);for(const[e,i]of t.comments)this.config.users.add(i.author),i.modifiedAuthor&&this.config.users.add(i.modifiedAuthor)}}updateViewpointReferences(){const e=this.components.get(ea);for(const[t,i]of this.list)for(const t of i.viewpoints){e.list.has(t)||i.viewpoints.delete(t)}}async export(e=this.list.values()){const t=new $o,i="3"===this.config.version,n=i?"3.0":this.config.version,s=i?"release_3_0":"release_2_1";t.file("bcf.version",`<?xml version="1.0" encoding="UTF-8"?>\n <Version VersionId="${n}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/${s}/Schemas/version.xsd"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n </Version>`);for(const[e,i]of this.documents.entries())"external"!==i.type&&t.file("2.1"===this.config.version?i.fileName:`documents/${e}`,i.data);if("3"===this.config.version){const e=[];for(const[t,i]of this.documents.entries()){const{type:n,description:s}=i;"external"!==n&&e.push(`<Document Guid="${t}">\n <Filename>${i.fileName}</Filename>\n ${s?`<Description>${s}</Description>`:""}\n </Document>`)}e.length>0&&t.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 ${e.join("\n")}\n </Documents>\n </DocumentInfo>`)}t.file("extensions.xml",this.serializeExtensions());const r=this.components.get(ea);for(const i of e){const e=t.folder(i.guid);e.file("markup.bcf",i.serialize());for(const t of i.viewpoints){const i=r.list.get(t);if(!i)continue;const n=i.title??i.guid;e.file(`${n}.bcfv`,await i.serialize());const s=r.snapshots.get(i.snapshot);if(!s)continue;const o=s?i.snapshot:i.guid,a=r.getSnapshotExtension(i.snapshot);e.file(`${o}.${a}`,s,{binary:!0})}}return await t.generateAsync({type:"blob"})}serializeExtensions(){const e=[...this.config.types].map(e=>`<TopicType>${e}</TopicType>`).join("\n"),t=[...this.config.statuses].map(e=>`<TopicStatus>${e}</TopicStatus>`).join("\n"),i=[...this.config.priorities].map(e=>`<Priority>${e}</Priority>`).join("\n"),n=[...this.config.labels].map(e=>`<TopicLabel>${e}</TopicLabel>`).join("\n"),s=[...this.config.stages].map(e=>`<Stage>${e}</Stage>`).join("\n"),r=[...this.config.users].map(e=>`<User>${e}</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!==e.length?`<TopicTypes>\n${e}\n</TopicTypes>`:""}\n ${0!==t.length?`<TopicStatuses>\n${t}\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(e){const{Guid:t,Date:i,Author:n,Comment:s,Viewpoint:r}=e;if(!(t&&i&&n&&(Wo||r)))return null;const o=new Wo(this.components,s??"");return o.guid=t,o.date=new Date(i),o.author=n,o.viewpoint=r?.Guid,o.modifiedAuthor=e.ModifiedAuthor,o.modifiedDate=e.ModifiedDate?new Date(e.ModifiedDate):void 0,o}getMarkupComments(e,t){let i;if("2.1"===t&&(i=e.Comment),"3"===t&&(i=e.Topic.Comments?.Comment),!i)return[];i=Array.isArray(i)?i:[i];const n=i.map(e=>this.processMarkupComment(e)).filter(e=>e);return Array.isArray(n)?n:[n]}getMarkupLabels(e,t){let i;if("2.1"===t&&(i=e.Topic.Labels),"3"===t&&(i=e.Topic.Labels?.Label),!i)return[];return Array.isArray(i)?i:[i]}getMarkupViewpoints(e,t){let i;return"2.1"===t&&(i=e.Viewpoints),"3"===t&&(i=e.Topic.Viewpoints?.ViewPoint),i?(i=Array.isArray(i)?i:[i],i):[]}getMarkupRelatedTopics(e,t){let i;if("2.1"===t&&(i=e.Topic.RelatedTopic),"3"===t&&(i=e.Topic.RelatedTopics?.RelatedTopic),!i)return[];return(Array.isArray(i)?i:[i]).map(e=>e.Guid)}getMarkupDocumentReferences(e,t){let i;if("2.1"===t&&(i=e.Topic.DocumentReference),"3"===t&&(i=e.Topic.DocumentReferences?.DocumentReference),!i)return[];return Array.isArray(i)?i:[i]}async load(e){const{fallbackVersionOnImport:t,ignoreIncompleteTopicsOnImport:i,updateExtensionsOnImport:n}=this.config,s=new $o;await s.loadAsync(e);const r=Object.values(s.files);let o=t;const a=r.find(e=>e.name.endsWith(".version"));if(a){const e=await a.async("string"),t=String(Zo.xmlParser.parse(e).Version.VersionId);o="3.0"===t?"3":t}if(!o||"2.1"!==o&&"3"!==o)throw new Error(`BCFTopics: ${o} is not supported.`);const l=r.find(e=>e.name.endsWith("extensions.xml")||e.name.endsWith(".extensions"));if(n&&l){const e=await l.async("string");Go(this,e)}const h=[],u=this.components.get(ea),d=r.filter(e=>e.name.endsWith(".bcfv"));for(const e of d){const t=await e.async("string"),i=Zo.xmlParser.parse(t).VisualizationInfo;if(!i){console.warn("Missing VisualizationInfo in Viewpoint");continue}const n={},{Guid:s,ClippingPlanes:r,Components:a,OrthogonalCamera:l,PerspectiveCamera:u}=i;if(s&&(n.guid=s),a){const e={selection:[],coloring:[],visibility:{default_visibility:!1,exceptions:[],view_setup_hints:{spaces_visible:!1,space_boundaries_visible:!1,openings_visible:!1}}};n.components=e;const{Selection:t,Visibility:i}=a;if(t&&t.Component){const i=Array.isArray(t.Component)?t.Component:[t.Component];e.selection=i.map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e)}if(i&&"DefaultVisibility"in i&&(e.visibility.default_visibility=i.DefaultVisibility),i&&i.Exceptions&&"Component"in i.Exceptions){const{Component:t}=i.Exceptions,n=Array.isArray(t)?t:[t];e.visibility.exceptions=n.map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e)}let s;"2.1"===o&&(s=a.ViewSetupHints),"3"===o&&(s=a.Visibility?.ViewSetupHints),s&&("OpeningsVisible"in s&&(e.visibility.view_setup_hints.openings_visible=s.OpeningsVisible),"SpacesVisible"in s&&(e.visibility.view_setup_hints.spaces_visible=s.SpacesVisible),"SpaceBoundariesVisible"in s&&(e.visibility.view_setup_hints.space_boundaries_visible=s.SpaceBoundariesVisible));const{Coloring:r}=a;if(r&&r.Color){const t=Array.isArray(r.Color)?r.Color:[r.Color];for(const i of t){const{Color:t,Component:n}=i;if(6!==t.length&&8!==t.length)continue;const s=6===t.length?t:t.slice(2),r=(Array.isArray(n)?n:[n]).map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e);e.coloring.push({color:s,components:r})}}}if(l||u){const e=i.PerspectiveCamera??i.OrthogonalCamera,{CameraViewPoint:t,CameraDirection:s}=e,r=new c.Vector3(Number(t.X),Number(t.Z),Number(-t.Y)),o=new c.Vector3(Number(s.X),Number(s.Z),Number(-s.Y)),a={camera_view_point:{x:r.x,y:r.y,z:r.z},camera_direction:{x:o.x,y:o.y,z:o.z},aspect_ratio:"AspectRatio"in e?e.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in e&&(n.orthogonal_camera={...a,view_to_world_scale:e.ViewToWorldScale}),"FieldOfView"in e&&(n.perspective_camera={...a,field_of_view:e.FieldOfView})}if(r){const e=(Array.isArray(r.ClippingPlane)?r.ClippingPlane:[r.ClippingPlane]).map(({Location:e,Direction:t})=>({location:{x:e.x,y:e.y,z:e.z},direction:{x:t.x,y:t.y,z:t.z}}));n.clipping_planes=e}const d=new Qo(this.components,n);h.push(d)}const p={},f=[],m=r.filter(e=>e.name.endsWith(".bcf"));for(const e of m){const t=await e.async("string"),n=Zo.xmlParser.parse(t).Markup,s=n.Topic,{Guid:a,TopicType:l,TopicStatus:c,Title:h,CreationDate:d,CreationAuthor:m}=s;if(i&&!(a&&l&&c&&h&&d&&m))continue;const g=new Ho(this.components);g.guid=a??g.guid;const w=this.getMarkupRelatedTopics(n,o);p[g.guid]=new Set(w),g.type=l??g.type,g.status=c??g.status,g.title=h??g.title,g.creationDate=d?new Date(d):g.creationDate,g.creationAuthor=m??g.creationAuthor,g.serverAssignedId=s.ServerAssignedId,g.priority=s.Priority,g.index=s.Index,g.modifiedDate=s.ModifiedDate?new Date(s.ModifiedDate):void 0,g.modifiedAuthor=s.ModifiedAuthor,g.dueDate=s.DueDate?new Date(s.DueDate):void 0,g.assignedTo=s.AssignedTo,g.description=s.Description,g.stage=s.Stage;const y=this.getMarkupLabels(n,o);for(const e of y)g.labels.add(e);const _=this.getMarkupComments(n,o);for(const e of _)g.comments.set(e.guid,e);const b=this.getMarkupViewpoints(n,o);for(const e of b){if(!e||!e.Guid)continue;const t=u.list.get(e.Guid);if(!t)continue;g.viewpoints.add(t.guid);const i=`${g.guid}/${e.Snapshot}`,n=r.find(({name:e})=>e===i);if(n){const e=await n.async("arraybuffer"),i=new Uint8Array(e);u.snapshots.set(t.guid,i),t.snapshot=t.guid??null}}const v=this.getMarkupDocumentReferences(n,o),x=r.find(e=>"documents.xml"===e.name);let C=[];const S=await(x?.async("string"));if(S){const e=lt.parser.parse(S).DocumentInfo?.Documents?.Document;C=Array.isArray(e)?e:[e]}for(const e of v){const{Description:t,DocumentGuid:i,Url:n,isExternal:s,ReferencedDocument:o}=e;if(i&&C.length>0){const e=C.find(({Guid:e})=>e===i),t=r.find(e=>e.name.endsWith(i)),n=await(t?.async("uint8array"));if(!e||!n)continue;const{Description:s,Filename:o}=e;this.documents.set(i,{type:"internal",fileName:o,description:s,data:n}),g.documentReferences.add(i)}if(n){const e=this.documents.add({type:"external",url:n,description:t});g.documentReferences.add(e)}if(o){let e=null;if(s)e=this.documents.add({type:"external",url:o,description:t});else{const i=o.split("/"),n=i[i.length-1],s=r.find(e=>e.name.endsWith(n)),a=await(s?.async("uint8array"));if(!a)continue;e=this.documents.add({type:"internal",fileName:n,data:a,description:t})}g.documentReferences.add(e)}}this.list.set(g.guid,g),f.push(g)}for(const e in p){const t=this.list.get(e);if(!t)continue;const i=p[e];for(const e of i)t.relatedTopics.add(e)}return this.onBCFImported.trigger(f),{viewpoints:h,topics:f}}}class Yo{onDraggingStarted=new d;onDraggingEnded=new d;onDisposed=new d;normal;origin;three=new c.Plane;components;world;type="default";_title="Clipping Plane";set title(e){this._title=e,this.notifyManager()}get title(){return this._title}_helper;_visible=!0;_enabled=!0;_controlsActive=!1;_arrowBoundBox=new c.Mesh;_planeMesh;_controls;_hiddenMaterial=new c.MeshBasicMaterial({visible:!1});_sizeMultiplier=5;_autoScale=!0;get autoScale(){return this._autoScale}set autoScale(e){this._autoScale=e,e&&this.updateScale()}get enabled(){return this._enabled}set enabled(e){if(this.world.isDisposing)return;if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");this._enabled=e,e?this.visible=this._visibilityBeforeDisabled:(this._visibilityBeforeDisabled=this.visible,this.visible=!1);const t=this.components.get(Ko);this.world.renderer.setPlane(e,this.three,t.localClippingPlanes),this.notifyManager()}_visibilityBeforeDisabled=!0;get visible(){return this._visible}set visible(e){this._visible=e,this._controls.getHelper().visible=e,this._helper.visible=e,this.toggleControls(e),this.notifyManager()}get meshes(){return[this._planeMesh,this._arrowBoundBox]}get planeMaterial(){return this._planeMesh.material}set planeMaterial(e){this._planeMesh.material=e}get size(){return this._sizeMultiplier}set size(e){this._sizeMultiplier=e,this.autoScale?this.updateScale():this._planeMesh.scale.set(e,e,e)}get helper(){return this._helper}get controls(){return this._controls}constructor(e,t,i,n,s,r=5,o=!0){if(this.components=e,this.world=t,!t.renderer)throw new Error("The given world must have a renderer!");this.normal=n,this.origin=i,this._sizeMultiplier=r;const a=e.get(Ko);t.renderer.setPlane(!0,this.three,a.localClippingPlanes),this._planeMesh=Yo.newPlaneMesh(r,s),this._helper=this.newHelper(),this._controls=this.newTransformControls(),this.three.setFromNormalAndCoplanarPoint(n,i),o&&this.toggleControls(!0),this.updateScale(),t.camera?.controls&&t.camera.controls.addEventListener("update",this.updateScale)}notifyManager=()=>{const e=this.components.get(Ko),t=e.list.getKey(this);t&&e.list.set(t,this)};setFromNormalAndCoplanarPoint(e,t){this.reset(),this.normal.equals(e)||(this.normal.copy(e),this._helper.lookAt(e)),this.origin.copy(t),this._helper.position.copy(t),this._helper.updateMatrix(),this.update()}update=()=>{this._enabled&&(this.three.setFromNormalAndCoplanarPoint(this.normal,this._helper.position),this.updateScale())};updateScale=()=>{if(!this.autoScale)return;const e=this.world.camera?.three;if(!e)return;if(!(e instanceof c.PerspectiveCamera))return;const t=new c.Vector3;e.getWorldPosition(t);const i=t.distanceTo(this._helper.position)/7*this._sizeMultiplier;this._planeMesh.scale.set(i,i,i)};dispose(){this._enabled=!1,!this.world.isDisposing&&this.world.camera?.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 e=new c.Vector3(1,0,0),t=new c.Vector3;this.normal.equals(e)||(this.normal.copy(e),this._helper.lookAt(e)),this.origin.copy(t),this._helper.position.copy(t),this._helper.updateMatrix()}toggleControls(e){if(e){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=e}newTransformControls(){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");const e=this.world.camera.three,t=this.world.renderer.three.domElement,i=new o.TransformControls(e,t);return this.initializeControls(i),this.world.scene.three.add(i.getHelper()),i}initializeControls(e){e.attach(this._helper),e.showX=!1,e.showY=!1,e.setSpace("local"),this.createArrowBoundingBox(),e.getHelper().children[0].children[0].add(this._arrowBoundBox)}createArrowBoundingBox(){this._arrowBoundBox.geometry=new c.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)}changeDrag=e=>{this._visible=!e.value,this.preventCameraMovement(),this.notifyDraggingChanged(e)};notifyDraggingChanged(e){e.value?this.onDraggingStarted.trigger():this.onDraggingEnded.trigger()}preventCameraMovement(){this.world.camera.enabled=this._visible}newHelper(){const e=new c.Object3D;return e.lookAt(this.normal),e.position.copy(this.origin),this._planeMesh.position.z+=.01,e.add(this._planeMesh),this.world.scene.three.add(e),e}static newPlaneMesh(e,t){const i=new c.PlaneGeometry(1),n=new c.Mesh(i,t);return n.scale.set(e,e,e),n}}class Xo extends dt{_config={enabled:{value:!0,type:"Boolean"},visible:{value:!0,type:"Boolean"},color:{value:new c.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(e){this._config.enabled.value=e,this._component.enabled=e}get visible(){return this._config.visible.value}set visible(e){this._config.visible.value=e,this._component.visible=e}get color(){return this._config.color.value}set color(e){this._config.color.value=e,this._component.material.color.copy(e)}get opacity(){return this._config.opacity.value}set opacity(e){this._config.opacity.value=e,this._component.material.opacity=e}get size(){return this._config.size.value}set size(e){this._config.size.value=e,this._component.size=e}}class Ko extends f{static uuid="66290bc5-18c4-4cd1-9379-2e17a0617611";onSetup=new d;onBeforeDrag=new d;onAfterDrag=new d;onBeforeCreate=new d;onBeforeCancel=new d;onAfterCancel=new d;onBeforeDelete=new d;onAfterCreate=new d;onAfterDelete=new d;onDisposed=new d;isSetup=!1;orthogonalY=!1;toleranceOrthogonalY=.7;autoScalePlanes=!0;_localClippingPlanes=!1;get localClippingPlanes(){return this._localClippingPlanes}set localClippingPlanes(e){this._localClippingPlanes=e;const t=this.components.get(Mo);for(const[,i]of t.list)i.renderer&&(i.renderer.localClippingPlanes=e)}Type=Yo;list=new l.DataMap;_deleting=new Map;config=new Xo(this,this.components,"Clipper",Ko.uuid);_defaultConfig={color:new c.Color(12255487),opacity:.2,size:2};_material=new c.MeshBasicMaterial({color:12255487,side:c.DoubleSide,transparent:!0,opacity:.2});_size=5;_enabled=!1;_visible=!0;onStateChanged=new d;get enabled(){return this._enabled}set enabled(e){this._enabled=e,this.onStateChanged.trigger(["enabled"])}get visible(){return this._visible}set visible(e){this._visible=e;for(const[t,i]of this.list)i.visible=e;this.onStateChanged.trigger(["visibility"])}get material(){return this._material}set material(e){this._material=e;for(const[t,i]of this.list)i.planeMaterial=e;this.onStateChanged.trigger(["material"])}get size(){return this._size}set size(e){this._size=e;for(const[t,i]of this.list)i.size=e;this.onStateChanged.trigger(["size"])}constructor(e){super(e),this.components.add(Ko.uuid,this),this.setEvents()}setEvents(){this.list.onBeforeDelete.add(({key:e,value:t})=>{if(this.onBeforeDelete.trigger(),!t.world.renderer)throw new Error("Renderer not found for this plane's world!");this._deleting.set(e,t),t.world.renderer.setPlane(!1,t.three),t.dispose()}),this.list.onItemDeleted.add(e=>{const t=this._deleting.get(e);this._deleting.delete(e),this.updateMaterialsAndPlanes(),t&&this.onAfterDelete.trigger(t)}),this.list.onCleared.add(()=>{const e=[...this._deleting.values()];this._deleting.clear(),this.updateMaterialsAndPlanes();for(const t of e)this.onAfterDelete.trigger(t)});const e=this.components.get(fs);if(e.initialized)this.subscribeToFragmentMaterials();else{const t=()=>{e.onFragmentsLoaded.remove(t),this.subscribeToFragmentMaterials()};e.onFragmentsLoaded.add(t)}}subscribeToFragmentMaterials(){const e=this.components.get(fs);for(const[,t]of e.core.models.materials.list)this.applyClippingToFragmentMaterial(t);e.core.models.materials.list.onItemSet.add(({value:e})=>{this.applyClippingToFragmentMaterial(e)})}applyClippingToFragmentMaterial(e){if(!this.localClippingPlanes)return;const t=this.components.get(Mo);for(const[,i]of t.list)if(i.renderer)return void(e.clippingPlanes=i.renderer.clippingPlanes)}dispose(){this._enabled=!1;this.components.get(pt).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(Ko.uuid),this.onDisposed.reset()}async create(e){const t=this.components.get(yo).get(e),i=await t.castRay();return i?this.createPlaneFromIntersection(e,i):null}createFromNormalAndCoplanarPoint(e,t,i){const n=this.newPlane(e,i,t);return this.updateMaterialsAndPlanes(),n}async delete(e,t){if(!t){const i=await this.pickPlane(e);if(!i)return;t=this.list.getKey(i)}t&&this.list.delete(t)}deleteAll(e){for(const[t,i]of this.list)e&&!e.has(i.type)||this.list.delete(t)}setup(e){const t={...this._defaultConfig,...e};this.config.color=t.color,this.config.opacity=t.opacity,this.config.size=t.size,this.isSetup=!0,this.onSetup.trigger()}pickPlane(e){const t=this.components.get(yo).get(e),i=this.getAllPlaneMeshes(),n=t.castRayToObjects(i);if(n){const e=n.object;return[...this.list.values()].find(t=>t.meshes.includes(e))}}getAllPlaneMeshes(){const e=[];for(const[t,i]of this.list)e.push(...i.meshes);return e}createPlaneFromIntersection(e,t){if(!e.renderer)throw new Error("The given world must have a renderer!");const i=t.point.distanceTo(new c.Vector3(0,0,0)),n=t.normal||t.face?.normal;if(!i||!n)return null;const s=this.getWorldNormal(t,n),r=this.newPlane(e,t.point,s.negate()),o=this.list.get(r);return o.visible=this._visible,o.size=this._size,e.renderer.setPlane(!0,o.three,this.localClippingPlanes),this.updateMaterialsAndPlanes(),o}getWorldNormal(e,t){const i=e.object;let n=e.object.matrixWorld.clone();if(i instanceof c.InstancedMesh&&void 0!==e.instanceId){const t=new c.Matrix4;i.getMatrixAt(e.instanceId,t),n=t.multiply(n)}const s=(new c.Matrix3).getNormalMatrix(n),r=t.clone().applyMatrix3(s).normalize();return this.normalizePlaneDirectionY(r),r}normalizePlaneDirectionY(e){this.orthogonalY&&(e.y>this.toleranceOrthogonalY&&(e.x=0,e.y=1,e.z=0),e.y<-this.toleranceOrthogonalY&&(e.x=0,e.y=-1,e.z=0))}newPlane(e,t,i){const n=new this.Type(this.components,e,t,i,this._material);n.autoScale=this.autoScalePlanes,n.onDraggingStarted.add(()=>this.onBeforeDrag.trigger(n)),n.onDraggingEnded.add(()=>this.onAfterDrag.trigger(n));const s=v.create();return this.list.set(s,n),this.onAfterCreate.trigger(n),s}updateMaterialsAndPlanes(){const e=this.components.get(Mo);for(const[t,i]of e.list){if(!i.renderer)continue;i.renderer.updateClippingPlanes();const{clippingPlanes:e}=i.renderer;for(const t of i.meshes)if(t.material)if(Array.isArray(t.material))for(const i of t.material)i.clippingPlanes=e;else t.material.clippingPlanes=e}}}class Qo{title;guid=v.create();clippingPlanes=new l.DataSet;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}};customData={};exceptionComponents=new l.DataSet;selectionComponents=new l.DataSet;componentColors=new l.DataMap;spacesVisible=!1;spaceBoundariesVisible=!1;openingsVisible=!1;defaultVisibility=!0;snapshot=this.guid;async getSelectionMap(){const e=this._components.get(fs);return await e.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const e=this._components.get(fs);return await e.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const e=this._components.get(fs),{camera_view_point:t}=this.camera,{x:i,y:n,z:s}=t,r=new c.Vector3(i,n,s);return e.applyBaseCoordinateSystem(r,new c.Matrix4),r}set position(e){const t=e.clone(),i=this._components.get(fs);e.clone().applyMatrix4(i.baseCoordinationMatrix.clone().invert()),this.camera.camera_view_point={x:t.x,y:t.y,z:t.z}}get direction(){const{camera_direction:e}=this.camera,{x:t,y:i,z:n}=e;return new c.Vector3(t,i,n)}_components;_world=null;set world(e){this._world=e}get world(){return this._world}get _managerVersion(){return this._components.get(Zo).config.version}get topics(){return[...this._components.get(Zo).list.values()].filter(e=>e.viewpoints.has(this.guid))}constructor(e,t){this._components=e,t&&(this.guid=t.guid??this.guid,this.set(t)),this.setEvents()}notifyUpdate=()=>{this._components.get(ea).list.set(this.guid,this)};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(e){this.title=e.title;const{components:t,perspective_camera:i,orthogonal_camera:n,clipping_planes:s}=e;if(t){const{selection:e,visibility:i,coloring:n}=t;if(e){this.selectionComponents.clear();for(const{ifc_guid:t}of e)t&&this.selectionComponents.add(t)}if(i){const{default_visibility:e,exceptions:t,view_setup_hints:n}=i;if(void 0!==e&&(this.defaultVisibility=e),t){this.exceptionComponents.clear();for(const{ifc_guid:e}of t)e&&this.exceptionComponents.add(e)}if(n){const{spaces_visible:e,space_boundaries_visible:t,openings_visible:i}=n;void 0!==e&&(this.spacesVisible=e),void 0!==t&&(this.spaceBoundariesVisible=t),void 0!==i&&(this.openingsVisible=i)}}if(n){this.componentColors.clear();for(const e of n){const{color:t,components:i}=e,n=i.map(e=>e.ifc_guid).filter(e=>null!==e);this.componentColors.set(t,n)}}}if((i||n)&&(this.camera=i??n),s&&this.world){const e=this._components.get(Ko);for(const t of s){const{location:i,direction:n}=t,s=new c.Vector3(i.x,i.z,-i.y),r=new c.Vector3(n.x,n.z,-n.y),o=e.createFromNormalAndCoplanarPoint(this.world,r,s);this.clippingPlanes.add(o),e.list.get(o).enabled=!1,e.list.get(o).visible=!1}}this.notifyUpdate()}async go(e){if(!this.world)return;const{camera:t}=this.world;if(!(t instanceof Lo))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,...e};t.projection.set(this.projection);const o=new c.Vector3(this.camera.camera_view_point.x,this.camera.camera_view_point.y,this.camera.camera_view_point.z),a=new c.Vector3(this.camera.camera_direction.x,this.camera.camera_direction.y,this.camera.camera_direction.z);if(o.equals(new c.Vector3)&&a.equals(new c.Vector3))return;const l=this.position,h=this.direction,u={x:l.x+80*h.x,y:l.y+80*h.y,z:l.z+80*h.z},d=[];n&&this.setClippingState(!0),s&&d.push(this.applyVisibility()),this.setClippingVisibility(r),d.push(t.controls.setLookAt(l.x,l.y,l.z,u.x,u.y,u.z,i)),await Promise.all(d)}async updateCamera(e=!0){return new Promise(t=>{if(!this.world)return void t(!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 c.Vector3),o=s.getWorldDirection(new c.Vector3),{width:a,height:l}=n.getSize();let h=a/l;Number.isNaN(h)&&(h=1);const u=this._components.get(fs);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:o.x,y:o.y,z:o.z},camera_up_vector:{x:0,y:1,z:0}};if(s instanceof c.PerspectiveCamera?this.camera={...d,field_of_view:s.fov}:s instanceof c.OrthographicCamera&&(this.camera={...d,view_to_world_scale:s.top-s.bottom}),e){const e=this._components.get(ea),s=n.three.domElement;n.three.render(this.world.scene.three,i.three),s.toBlob(async i=>{if(i){const t=await i.arrayBuffer(),n=new Uint8Array(t);e.snapshots.set(this.guid,n)}this.notifyUpdate(),t(!0)})}else this.notifyUpdate(),t(!0)})}takeSnapshot(){return new Promise(e=>{if(!this.world)return void e(!1);const{camera:t,renderer:i}=this.world;if(!i)throw new Error("Viewpoint: the world needs to have a renderer!");const n=this._components.get(ea),s=i.three.domElement;i.three.render(this.world.scene.three,t.three),s.toBlob(async t=>{if(t){const e=await t.arrayBuffer(),i=new Uint8Array(e);n.snapshots.set(this.guid,i)}this.notifyUpdate(),e(!0)})})}updateClippingPlanes(){this.clippingPlanes.clear();const e=this._components.get(Ko);for(const[t,i]of e.list)i.enabled&&this.clippingPlanes.add(t)}async applyVisibility(){const e=this._components.get(kr);e.set(this.defaultVisibility);const t=await this.getExceptionMap();e.set(!this.defaultVisibility,t);const i=await this.getSelectionMap();e.set(!0,i)}async setColorizationState(e){const t=this._components.get(fs),i=[];if(e)for(const[e,n]of this.componentColors){const s=`#${e}`,r=await t.guidsToModelIdMap(n);for(const[e,n]of Object.entries(r)){const r=t.list.get(e);r&&i.push(r.highlight([...n],{customId:s,color:new c.Color(s),renderedFaces:l.RenderedFaces.ONE,opacity:1,transparent:!1}))}}else for(const[e,n]of this.componentColors){const e=await t.guidsToModelIdMap(n);for(const[n,s]of Object.entries(e)){const e=t.list.get(n);e&&i.push(e.resetHighlight([...s]))}}i.push(t.core.update(!0)),await Promise.all(i)}setClippingState(e){const t=this._components.get(Ko);for(const[i,n]of t.list)n.enabled=e&&this.clippingPlanes.has(i)}setClippingVisibility(e){const t=this._components.get(Ko);for(const i of this.clippingPlanes){const n=t.list.get(i);n&&(n.visible=e)}}async createComponentTags(e){const t=this._components.get(fs);let i="";if(this._components.get(Zo).config.includeSelectionTag){const n="selection"===e?await this.getSelectionMap():await this.getExceptionMap();for(const e in n){const s=t.list.get(e);if(!s)continue;const r=n[e];for(const e of r){const t=s.getItem(e),n=await t.getGuid();if(!n)continue;const r=(await t.getAttributes())?.getValue("Tag");let o=null;r&&(o=`AuthoringToolId="${r}"`),i+=`\n<Component IfcGuid="${n}" ${o??""} />`}}}else i=[...this.selectionComponents].map(e=>`<Component IfcGuid="${e}" />`).join("\n");return i}createColorTags(){let e="";for(const[t,i]of this.componentColors.entries()){e+=`<Color Color="${t}">\n${i.map(e=>`\n<Component IfcGuid="${e}" />`).join("\n")}\n</Color>`}return 0!==e.length?`<Coloring>\n${e}\n</Coloring>`:"<Coloring />"}toJSON(){const e=this._components.get(Ko),t={guid:this.guid,components:{selection:[...this.selectionComponents].map(e=>({ifc_guid:e,authoring_tool_id:null})),coloring:[...this.componentColors].map(([e,t])=>({color:e,components:t.map(e=>({ifc_guid:e,authoring_tool_id:null}))})),visibility:{default_visibility:this.defaultVisibility,exceptions:[...this.exceptionComponents].map(e=>({ifc_guid:e,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(t=>{const i=e.list.get(t);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(e=>null!==e)};"field_of_view"in this.camera?t.perspective_camera=this.camera:t.orthogonal_camera=this.camera;const i=this._components.get(ea),n=i.snapshots.get(this.snapshot);if(n){const e=n.toString(),s=btoa(e),r=i.getSnapshotExtension(this.snapshot);t.snapshot={snapshot_type:r,snapshot_data:s}}return t}async serialize(e=this._managerVersion){const t=this._components.get(fs),i=this.position;i.applyMatrix4(t.baseCoordinationMatrix.clone().invert());const n=this.direction;n.normalize();const s=(new c.Matrix4).makeRotationX(Math.PI/2),r=n.clone().applyMatrix4(s);r.normalize();const o=`<CameraViewPoint>\n <X>${i.x}</X>\n <Y>${-i.z}</Y>\n <Z>${i.y}</Z>\n </CameraViewPoint>`,a=`<CameraDirection>\n <X>${n.x}</X>\n <Y>${-n.z}</Y>\n <Z>${n.y}</Z>\n </CameraDirection>`,l=`<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 ${o}\n ${a}\n ${l}\n ${h}\n <ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>\n </OrthogonalCamera>`:"field_of_view"in this.camera&&(u=`<PerspectiveCamera>\n ${o}\n ${a}\n ${l}\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"===e?d:""}\n ${0!==p.length?`<Selection>${p}</Selection>`:""}\n <Visibility DefaultVisibility="${this.defaultVisibility}">\n ${"3"===e?d:""}\n ${0!==f.length?`<Exceptions>${f}</Exceptions>`:""}\n </Visibility>\n ${m}\n </Components>\n ${u}\n </VisualizationInfo>`}}class Jo extends dt{_config={overwriteColors:{value:!1,type:"Boolean"}};get overwriteColors(){return this._config.overwriteColors.value}set overwriteColors(e){this._config.overwriteColors.value=e}}class ea extends f{static uuid="ee867824-a796-408d-8aa0-4e5962a83c66";enabled=!0;world=null;list=new e.DataMap;snapshots=new e.DataMap;create(e){const t=new Qo(this.components,e);return t.world=this.world,e||this.list.set(t.guid,t),t}constructor(e){super(e),e.add(ea.uuid,this)}getSnapshotExtension(e){let t="jpeg";const i=this.snapshots.get(e);if(!i)return t;const n=i.subarray(0,4);let s="";for(let e=0;e<n.length;e++)s+=n[e].toString(16);return s.startsWith("89504e47")&&(t="png"),s.startsWith("ffd8ffe")&&(t="jpeg"),t}isSetup=!1;setup(){}onSetup=new d;config=new Jo(this,this.components,"Viewpoints",ea.uuid);onDisposed=new d;dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}}class ta{_components;_cameraOffset=10;_planeHelper;_farPlaneHelper;_cameraHelper;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)}onStateChanged=new d;onUpdated=new d;onDisposed=new d;camera;plane=new c.Plane;farPlane=new c.Plane;id=v.create();_open=!1;set open(e){this._open=e,this.onStateChanged.trigger(["open"])}get open(){return this._open}set planeHelperColor(e){!Array.isArray(this._planeHelper.material)&&"color"in this._planeHelper.material&&this._planeHelper.material.color instanceof c.Color&&(this._planeHelper.material.color=e)}set farPlaneHelperColor(e){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof c.Color&&(this._farPlaneHelper.material.color=e)}_range=ia.defaultRange;set range(e){this._range=e,this.update()}get range(){return this._range}set distance(e){this.plane.constant=e,this.update()}get distance(){return this.plane.constant}_world=null;set world(e){this._world=e,this.camera.currentWorld=e,e&&(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}_helpersVisible=!1;set helpersVisible(e){if(!e)return this._helpersVisible=e,this._planeHelper.removeFromParent(),this._farPlaneHelper.removeFromParent(),void this._cameraHelper.removeFromParent();this.world&&(this._helpersVisible=e,this.world.scene.three.add(this._planeHelper,this._farPlaneHelper))}get helpersVisible(){return this._helpersVisible}_planesEnabled=!1;set planesEnabled(e){const{world:t}=this;if(!t)return;const{renderer:i}=t;i&&(i.setPlane(e,this.plane),i.setPlane(e,this.farPlane),this._planesEnabled=e)}get planesEnabled(){return this._planesEnabled}constructor(e,t){this._components=e,this.camera=new Lo(this._components);const{threeOrtho:i}=this.camera;if(t?.id&&(this.id=t.id),t?.normal&&t?.point){const{normal:e,point:i}=t;this.plane.setFromNormalAndCoplanarPoint(e,i)}this._cameraHelper=new c.CameraHelper(i),this._planeHelper=new c.PlaneHelper(this.plane,50),this._farPlaneHelper=new c.PlaneHelper(this.farPlane,50),this.farPlaneHelperColor=new c.Color("blue"),this.update()}dispose(){this.helpersVisible=!1;const e=this._components.get(y);e.destroy(this._planeHelper),e.destroy(this._farPlaneHelper),e.destroy(this._cameraHelper),this.camera.dispose(),this.onDisposed.trigger()}update(){if(this.world){const e=this._cameraPosition,t=this._planePosition;this.camera.controls.setLookAt(e.x,e.y,e.z,t.x,t.y,t.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()}}class ia extends f{static uuid="fb22f1f5-6598-4664-a11d-de8963ae420f";static defaultRange=15;list=new e.DataMap;enabled=!0;world=null;_fragmentsUpdateEvent=()=>{this.components.get(fs).core.update(!0)};restoreCameraOnClose=!0;_restoreState=null;get hasOpenViews(){return[...this.list.values()].some(e=>e.open)}constructor(e){super(e),e.add(ia.uuid,this),this.setupEvents()}setupEvents(){this.list.onBeforeDelete.add(({key:e,value:t})=>{t.open&&this.close(e),t.dispose()})}create(e,t,i){const n=new ta(this.components,{id:i?.id,normal:e,point:t});return n.world=i?.world??this.world,this.list.set(n.id,n),n}createFromPlane(e,t){const i=new ta(this.components,{id:t?.id});return i.plane.copy(e),i.update(),i.world=t?.world??this.world,this.list.set(i.id,i),i}async createFromIfcStoreys(e){const t=[],i=this.components.get(fs),n=void 0===e?.offset?.25:e.offset;for(const[s,r]of i.list){if(e&&e.modelIds&&!e.modelIds.some(e=>e.test(s)))continue;const i=Object.values(await r.getItemsOfCategories([/BUILDINGSTOREY/])).flat();if(0===i.length)continue;const o=await r.getItemsData(i),[,a]=await r.getCoordinates(),l=new c.Vector3(0,-1,0);for(const i of o){if(!(i.Name&&"value"in i.Name&&i.Elevation&&"value"in i.Elevation)){const e=i._localId&&"value"in i._localId?i._localId.value:"unknown";console.warn(`[Views] Storey ${e} of model "${s}" has no Name or no Elevation value. Skipping it: no view will be created for it.`);continue}const{value:r}=i.Name;if(e?.storeyNames&&!e.storeyNames.some(e=>e.test(r)))continue;const o=i.Elevation.value+a+n,h=new c.Plane(l,o),u=this.createFromPlane(h,{id:r,world:e?.world});t.push(u)}}return t}createElevations(e){const t=[],i=this.components.get(fs),n=void 0!==e?.combine&&e.combine,s=e?.namingCallback??(e=>({front:""+(n?"Front":`${e}: Front`),back:""+(n?"Back":`${e}: Back`),left:""+(n?"Left":`${e}: Left`),right:""+(n?"Right":`${e}: Right`)}));let r=[];for(const[t,n]of i.list)e&&e.modelIds&&!e.modelIds.some(e=>e.test(t))||r.push({id:t,box:n.box});if(0===r.length)return t;if(n){const e=this.components.get(Br);e.list.clear(),e.list.add(...r.map(e=>e.box));r=[{id:"combined",box:e.get()}]}for(const{id:i,box:n}of r){const{min:r,max:o}=n,a=Math.abs(o.x-r.x),l=Math.abs(o.z-r.z),h=new c.Vector3;n.getCenter(h);const u=new c.Plane(new c.Vector3(0,0,-1),o.z),d=new c.Plane(new c.Vector3(0,0,1),-r.z),p=new c.Plane(new c.Vector3(-1,0,0),o.x),f=new c.Plane(new c.Vector3(1,0,0),-r.x),{front:m,back:g,left:w,right:y}=s(i),_=this.createFromPlane(u,{id:m,world:e?.world});_.range=l;const b=this.createFromPlane(d,{id:g,world:e?.world});b.range=l;const v=this.createFromPlane(p,{id:w,world:e?.world});v.range=a;const x=this.createFromPlane(f,{id:y,world:e?.world});x.range=a,t.push(_,b,v,x)}return t}open(e){const t=this.list.get(e);if(!t)throw new Error(`Views: the view with id ${e} doesn't exist.`);if(t.open)return;const{world:i}=t;if(!i)throw new Error(`Views: no world found for view with id ${e}.`);const{renderer:n}=i;if(!n)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);for(const[,e]of this.list)e.world===i&&this.close(e.id);this.restoreCameraOnClose&&i.camera!==t.camera&&!this._restoreState&&i.camera.controls&&(this._restoreState={camera:i.camera,json:i.camera.controls.toJSON()}),n.setPlane(!0,t.plane),n.setPlane(!0,t.farPlane),this.setOnlyEnabledControls(i,t),t.camera.controls.addEventListener("rest",this._fragmentsUpdateEvent),i.camera=t.camera,t.open=!0}close(e){let t;if(t=e?this.list.get(e):[...this.list.values()].find(e=>e.open),e&&!t)throw new Error(`Views: the view with id ${e} doesn't exist.`);if(!t)return;if(!t.open)return;const{world:i}=t;if(!i)throw new Error(`Views: no world found for view with id ${e}.`);const{renderer:n}=i;if(!n)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);if(n.setPlane(!1,t.plane),n.setPlane(!1,t.farPlane),t.camera.controls.removeEventListener("rest",this._fragmentsUpdateEvent),i.useDefaultCamera(),t.open=!1,this.setOnlyEnabledControls(i,null),this.restoreCameraOnClose&&this._restoreState){const{camera:e,json:t}=this._restoreState;e===i.camera&&e.controls&&e.controls.fromJSON(t,!1),this._restoreState=null}}setOnlyEnabledControls(e,t){const i=t?t.camera:e.defaultCamera,n=(e,t)=>{e.controls&&(e.controls.enabled=t)};n(i,!0),i!==e.defaultCamera&&n(e.defaultCamera,!1);for(const[,t]of this.list)t.world===e&&t.camera!==i&&n(t.camera,!1)}}async function na(e,t,i,n,s,r,o){const a=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),await function(e,t,i,n){return new Promise((s,r)=>{!function o(){const a=e.clientWaitSync(t,i,0);a!==e.WAIT_FAILED?a!==e.TIMEOUT_EXPIRED?s():setTimeout(o,n):r()}()})}(e,a,0,10),e.deleteSync(a),e.bindBuffer(t,i),e.getBufferSubData(t,n,s,r,o),e.bindBuffer(t,null)}class sa{onDisposed=new d;onDistanceComputed=new d;excludedObjects=new Set;enabled=!0;renderDebugFrame=!1;components;scene=new c.Scene;camera=new c.OrthographicCamera(-1,1,1,-1,0,1);depthMaterial;world;worker;_width=512;_height=512;_postQuad;tempRT;resultRT;bufferSize;_buffer;_isWorkerBusy=!1;constructor(e,t){if(!t.renderer)throw new Error("The given world must have a renderer!");this.components=e,this.world=t;const i=t.camera.three;this.tempRT=new c.WebGLRenderTarget(this._width,this._height),this.bufferSize=this._width*this._height*4,this._buffer=new Uint8Array(this.bufferSize),this.tempRT.texture.minFilter=c.NearestFilter,this.tempRT.texture.magFilter=c.NearestFilter,this.tempRT.stencilBuffer=!1,this.tempRT.samples=0,this.tempRT.depthTexture=new c.DepthTexture(this._width,this._height),this.tempRT.depthTexture.format=c.DepthFormat,this.tempRT.depthTexture.type=c.UnsignedShortType,this.resultRT=new c.WebGLRenderTarget(this._width,this._height),this.depthMaterial=new c.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:i.near},cameraFar:{value:i.far},tDiffuse:{value:null},tDepth:{value:null}}});const n=new c.PlaneGeometry(2,2);this._postQuad=new c.Mesh(n,this.depthMaterial),this.scene.add(this._postQuad);const s=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(s)),this.worker.addEventListener("message",this.handleWorkerMessage)}dispose(){this.enabled=!1,this.onDistanceComputed.reset(),this.worker.terminate(),this.tempRT.dispose(),this.resultRT.dispose();const e=[...this.scene.children];this.excludedObjects.clear();for(const t of e)t.removeFromParent();this._postQuad.geometry.dispose(),this._postQuad.removeFromParent(),this._buffer=null,this.onDisposed.reset()}compute=async()=>{if(!this.enabled||this.world.isDisposing)return;if(this._isWorkerBusy)return;this._isWorkerBusy=!0,this.world.camera.three.updateMatrix();const e=this.world.renderer.three;e.setRenderTarget(this.tempRT);const t="visibilityBeforeDistanceCheck";for(const e of this.excludedObjects)e.userData[t]=e.visible,e.visible=!1;e.render(this.world.scene.three,this.world.camera.three);for(const e of this.excludedObjects)void 0!==e.userData[t]&&(e.visible=e.userData[t]);this.depthMaterial.uniforms.tDiffuse.value=this.tempRT.texture,this.depthMaterial.uniforms.tDepth.value=this.tempRT.depthTexture,e.setRenderTarget(this.resultRT),e.render(this.scene,this.camera);const i=e.getContext();try{await async function(e,t,i,n,s,r,o,a){const l=e.createBuffer();return e.bindBuffer(e.PIXEL_PACK_BUFFER,l),e.bufferData(e.PIXEL_PACK_BUFFER,a.byteLength,e.STREAM_READ),e.readPixels(t,i,n,s,r,o,0),e.bindBuffer(e.PIXEL_PACK_BUFFER,null),await na(e,e.PIXEL_PACK_BUFFER,l,0,a),e.deleteBuffer(l),a}(i,0,0,this._width,this._height,i.RGBA,i.UNSIGNED_BYTE,this._buffer)}catch(t){return e.setRenderTarget(null),void(this._isWorkerBusy=!1)}e.setRenderTarget(null),this.renderDebugFrame&&e.render(this.scene,this.camera),this.worker.postMessage({buffer:this._buffer})};handleWorkerMessage=e=>{if(!this.enabled||this.world.isDisposing)return;const t=e.data.colors;let i=Number.MAX_VALUE;for(const e of t)0!==e&&e<i&&(i=e);const n=this.world.camera.three||c.OrthographicCamera,s=-1*(i/255-1)*(n.far-n.near),r=Math.min(s,n.far);this.onDistanceComputed.trigger(r),this._isWorkerBusy=!1}}class ra{constructor(e){this._components=e}_components;cardinality="required";instructions;addCheckResult(e,t){const i=t.findIndex(({parameter:t})=>t===e.parameter);-1!==i?t[i]=e:t.push(e)}evalRequirement=(e,t,i,n)=>{const s={parameter:i,currentValue:e,requiredValue:t,pass:!1};n&&this.addCheckResult(s,n);let r=!1;if("simple"===t.type&&(r=e===t.parameter),"enumeration"===t.type&&(r=t.parameter.includes(e)),"pattern"===t.type){r=new RegExp(t.parameter).test(String(e))}if("length"===t.type){const{min:i,length:n,max:s}=t.parameter;void 0!==n&&(r=String(e).length===n),void 0!==i&&(r=String(e).length>=i),void 0!==s&&(r=String(e).length<=s)}if("bounds"===t.type&&"number"==typeof e){const{min:i,minInclusive:n,max:s,maxInclusive:o}=t.parameter;let a=!0,l=!0;void 0!==i&&(a=n?e>=i:e>i),void 0!==s&&(l=o?e<=s:e<s),r=a&&l}return"prohibited"===this.cardinality&&(r=!r),"optional"===this.cardinality&&(r=!0),s.pass=r,s.pass};getItemChecks(e,t,i,n){if(!("value"in i._localId)||"number"!=typeof i._localId.value)return null;let s=e.get(t);s||(s=new l.DataMap,e.set(t,s));let r=s.get(i._localId.value);if(r&&n&&!r.pass)return null;if(!r){const e=[];r={guid:Array.isArray(i._guid)?void 0:i._guid.value,pass:!1,checks:e},Object.defineProperty(r,"pass",{get:()=>e.every(({pass:e})=>e)}),s.set(i._localId.value,r)}const o=[],a={facetType:this.facetType,cardinality:this.cardinality,checks:o,pass:!1};return Object.defineProperty(a,"pass",{get:()=>o.every(({pass:e})=>e)}),r.checks.push(a),a.checks}}const oa=(e,t)=>{let i="";if(!t)return i;if("simple"===t.type&&(i=`<simpleValue>${t.parameter}</simpleValue>`),"enumeration"===t.type){i=`<xs:restriction base="xs:string">\n ${t.parameter.map(e=>`<xs:enumeration value="${e}" />`).join("\n")}\n </xs:restriction>`}if("pattern"===t.type){i=`<xs:restriction base="xs:string">\n <xs:pattern value="${t.parameter}" />\n </xs:restriction>`}if("bounds"===t.type){const{min:e,minInclusive:n,max:s,maxInclusive:r}=t.parameter;let o="";void 0!==e&&(o=`<xs:min${n?"Inclusive":"Exclusive"} value="${e}">`);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"===t.type){const{length:e,min:n,max:s}=t.parameter;let r="";void 0!==e&&void 0===n&&void 0===s&&(r=`<xs:length value="${e}" />`);let o="";void 0!==n&&void 0===e&&(o=`<xs:minLength value="${n}" />`);let a="";void 0!==s&&void 0===e&&(a=`<xs:maxLength value="${s}" />`),i=`<xs:restriction base="xs:string">\n ${r}\n ${o}\n ${a}\n </xs:restriction>`}return`<${e[0].toLowerCase()+e.slice(1)}>\n ${i}\n </${e[0].toLowerCase()+e.slice(1)}>`};class aa extends ra{facetType="Attribute";name;value;constructor(e,t){super(e),this.name=t}serialize(e){const t=oa("Name",this.name),i=oa("Value",this.value);let n="";return"requirement"===e&&(n+=`cardinality="${this.cardinality}"`,n+=this.instructions?`instructions="${this.instructions}"`:""),`<attribute ${n}>\n ${t}\n ${i}\n</attribute>`}async getEntities(){}async test(e,t,i={skipIfFails:!0}){const n=this._components.get(fs);for(const[s,r]of Object.entries(e)){const e=n.list.get(s);if(!e)continue;const o=await e.getItemsData([...r]);for(const e of o){const n=this.getItemChecks(t,s,e,i.skipIfFails);if(!n)continue;const r=Object.keys(e).filter(t=>{const i=this.evalRequirement(t,this.name,"Name");if(!i)return!1;const n=e[t];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 t=e[r[0]];if(Array.isArray(t))n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality});else{Array.isArray(t.value)?n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality}):this.evalRequirement(t.value,this.value,"Value",n)}}else n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality})}}}}class la extends ra{facetType="Classification";system;value;uri;constructor(e,t){super(e),this.system=t}serialize(e){const t=oa("System",this.system),i=oa("Value",this.value);let n="";return"requirement"===e&&(n+=`cardinality="${this.cardinality}"`,n+=this.uri?`uri=${this.uri}`:"",n+=this.instructions?`instructions="${this.instructions}"`:""),`<classification ${n}>\n ${t}\n ${i}\n</classification>`}async getEntities(e,t){}async test(e,t){}}class ca extends ra{facetType="Entity";name;predefinedType;constructor(e,t){super(e),this.name=t}serialize(e){const t=oa("Name",this.name),i=oa("Name",this.predefinedType);let n="";return"requirement"===e&&(n+=`cardinality="${this.cardinality}"`,n+=this.instructions?`instructions="${this.instructions}"`:""),`<entity ${n}>\n ${t}\n ${i}\n</entity>`}async getEntities(e,t){const i=this._components.get(fs),n=new Map;for(const[t,s]of i.list){if(!e.find(e=>e.test(t)))continue;const i=await s.getCategories();for(const e of i){if(!await this.evalName(e))continue;let i=n.get(t);i||(i=[],n.set(t,i)),i.push(e)}}const s={};if(await Promise.all(Array.from(n.entries()).map(async([e,t])=>{const n=i.list.get(e);if(!n)return;const r=t.map(e=>new RegExp(`^${e}$`)),o=await n.getItemsOfCategories(r),a=Object.values(o).flat();s[e]=new Set(a)})),this.predefinedType)for(const[e,n]of Object.entries(s)){const s=i.list.get(e);if(!s)continue;const r=await s.getItemsData([...n]);for(const i of r){if(!("value"in i._localId))continue;await this.evalPredefinedType(e,i)&&ct.append(t,e,i._localId.value)}}else ct.add(t,s)}async test(e,t,i){const n=this._components.get(fs);for(const[s,r]of Object.entries(e)){const e=n.list.get(s);if(!e)continue;const o=await e.getItemsData([...r]);for(const e of o){if(!("value"in e._category))continue;const n=this.getItemChecks(t,s,e,i.skipIfFails);n&&(await this.evalName(e._category.value,n),await this.evalPredefinedType(s,e,n))}}}async evalName(e,t){return this.evalRequirement(e,this.name,"Name",t)}async evalPredefinedType(e,t,i){if(!this.predefinedType)return null;if(!("value"in t.PredefinedType))return null;const n="string"==typeof this.predefinedType.parameter&&"USERDEFINED"===this.predefinedType.parameter;let s=t.PredefinedType.value;if("USERDEFINED"===s&&!n){const e=Object.keys(t).find(e=>/^((?!Predefined).)*Type$/.test(e));if(e){const i=t[e];"value"in i&&(s=i.value)}else s="USERDEFINED"}if(!s){const i=this._components.get(fs).list.get(e);if(i&&"value"in t._localId){const[e]=await i.getItemsData([t._localId.value],{relations:{IsTypedBy:{attributes:!0,relations:!1}}});if(Array.isArray(e.IsTypedBy)){const t=e.IsTypedBy[0];if(t&&"value"in t.PredefinedType&&(s=t.PredefinedType.value,"USERDEFINED"===s&&!n)){const e=Object.keys(t).find(e=>/^((?!Predefined).)*Type$/.test(e));if(e){const i=t[e];"value"in i&&(s=i.value)}else s="USERDEFINED"}}}}return this.evalRequirement(s,this.predefinedType,"PredefinedType",i)}}class ha extends ra{facetType="Property";propertySet;baseName;value;dataType;uri;_unsupportedTypes=["IFCCOMPLEXPROPERTY","IFCPHYSICALCOMPLEXQUANTITY"];constructor(e,t,i){super(e),this.propertySet=t,this.baseName=i}serialize(e){const t=oa("PropertySet",this.propertySet),i=oa("BaseName",this.baseName),n=oa("Value",this.value),s=this.dataType?`dataType=${this.dataType}`:"";let r="";return"requirement"===e&&(r+=`cardinality="${this.cardinality}"`,r+=this.uri?`uri=${this.uri}`:"",r+=this.instructions?`instructions="${this.instructions}"`:""),`<property ${s} ${r}>\n ${t}\n ${i}\n ${n}\n</property>`}async getEntities(e,t){const i=this._components.get(fs);for(const[n,s]of i.list){if(!e.find(e=>e.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},DefinesOccurrence:{attributes:!0,relations:!1},DefinesOcurrence:{attributes:!0,relations:!1}}}),a=new Map;for(const e of o){const i=e.DefinesOccurrence??e.DefinesOcurrence;if(!("value"in e._localId&&"value"in e._category&&"value"in e.Name))continue;if(!this.evalRequirement(e.Name.value,this.propertySet,"PropertySet"))continue;let s;if("IFCPROPERTYSET"===e._category.value&&(s="HasProperties"),"IFCELEMENTQUANTITY"===e._category.value&&(s="Quantities"),!s)continue;const r=e[s];if(Array.isArray(r))for(const s of r){const r=Object.keys(s),o=r.find(e=>/Name/.test(e));if(!o||!("value"in s[o]))continue;const l=s[o];if(!("value"in l))continue;if(!this.evalRequirement(l.value,this.baseName,"BaseName"))continue;if(this.value){const e=r.find(e=>/Value/.test(e));if(!e)continue;const t=s[e];if(!("value"in t))continue;if(!this.evalRequirement(t.value,this.value,"Value"))continue}const c=e._localId.value;let h=a.get(c);if(h||(h={name:String(e.Name.value),props:new Set},a.set(c,h)),h.props.add(String(l.value)),!Array.isArray(i))continue;const u=i.map(e=>"value"in e._localId&&"number"==typeof e._localId.value?e._localId.value:null).filter(e=>null!==e);ct.append(t,n,...u)}}a.size>0&&await this.appendTypeInstances(s,n,a,t)}}async appendTypeInstances(e,t,i,n){const s=Object.values(await e.getItemsOfCategories([/TYPE$/,/^IFCTYPE/,/STYLE$/])).flat();if(0===s.length)return;const r={attributes:!0,relations:!1},o=await e.getItemsData(s,{attributesDefault:!1,relations:{HasPropertySets:r,ObjectTypeOf:r,Types:r}}),a=new Map,l=n[t];for(const e of o){if(!Array.isArray(e.HasPropertySets))continue;const t=e.HasPropertySets.flatMap(e=>{const t=e._localId&&"value"in e._localId?e._localId.value:null,n=i.get(t);return n?[n]:[]});if(0===t.length)continue;const n=[...Array.isArray(e.ObjectTypeOf)?e.ObjectTypeOf:[],...Array.isArray(e.Types)?e.Types:[]];for(const e of n){if(!e._localId||!("value"in e._localId))continue;const i=e._localId.value;if("number"!=typeof i||l?.has(i))continue;let n=a.get(i);n||(n=[],a.set(i,n)),n.push(...t)}}if(0===a.size)return;const c=await e.getItemsData([...a.keys()],{relations:{IsDefinedBy:{attributes:!0,relations:!0}}}),h=[];for(const e of c){if(!("value"in e._localId))continue;const t=e._localId.value,i=Array.isArray(e.IsDefinedBy)?e.IsDefinedBy:[],n=(e,t)=>i.some(i=>{if(!i.Name||!("value"in i.Name)||i.Name.value!==e)return!1;const n=this.getPropertyListName(i),s=n?i[n]:void 0;return!!Array.isArray(s)&&s.some(e=>e.Name&&"value"in e.Name&&e.Name.value===t)});a.get(t).some(e=>[...e.props].some(t=>!n(e.name,t)))&&h.push(t)}ct.append(n,t,...h)}async test(e,t,i={skipIfFails:!0}){const n=this._components.get(fs);for(const[s,r]of Object.entries(e)){const e=n.list.get(s);if(!e)continue;const o=await e.getItemsData([...r],{relations:{IsDefinedBy:{attributes:!0,relations:!0},IsTypedBy:{attributes:!0,relations:!1},HasPropertySets:{attributes:!0,relations:!0},DefinesOccurrence:{attributes:!1,relations:!1},DefinesOcurrence:{attributes:!1,relations:!1}}});for(const e of o){const n=this.getItemChecks(t,s,e,i.skipIfFails);if(!n)continue;const r=(await this.getPsets(e)).filter(e=>{if(!("value"in e.Name))return!1;return!!this.evalRequirement(e.Name.value,this.propertySet,"PropertySet")&&(n.push({currentValue:e.Name.value,parameter:"PropertySet",pass:!0,requiredValue:this.propertySet}),!0)});if(0!==r.length)for(const e of r){const t=this.getPropertyListName(e);if(!t)continue;const i=e[t];if(!Array.isArray(i)){n.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}const s=i.filter(e=>{if(!("value"in e._category)||!("value"in e.Name))return!1;if(this._unsupportedTypes.includes(e._category.value))return!1;return!!this.evalRequirement(e.Name.value,this.baseName,"BaseName")&&(n.push({currentValue:e.Name.value,parameter:"BaseName",pass:!0,requiredValue:this.baseName}),!0)});if(0!==s.length)for(const e of s)this.evalValue(e,n),this.evalDataType(e,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(e){let t;return"value"in e._category?("IFCPROPERTYSET"===e._category.value&&(t="HasProperties"),"IFCELEMENTQUANTITY"===e._category.value&&(t="Quantities"),t):t}getValueKey(e){return Object.keys(e).find(e=>/Value/.test(e)||/Values/.test(e))}getTypePsets(e){const t=[...Array.isArray(e.IsTypedBy)?e.IsTypedBy:[],...Array.isArray(e.IsDefinedBy)?e.IsDefinedBy:[]],i=[];for(const e of t)Array.isArray(e?.HasPropertySets)&&i.push(...e.HasPropertySets);return i}async getPsets(e){const t=this.getTypePsets(e);if(!Array.isArray(e.IsDefinedBy))return t;const i=[],n=new Set;for(const s of e.IsDefinedBy){if(!("value"in s.Name))continue;const e=s.Name.value,r=this.getPropertyListName(s);if(!e||!r)continue;const o=t.find(t=>"value"in t.Name&&t.Name.value===e);if(o&&(n.add(o),Array.isArray(o.HasProperties)&&Array.isArray(s.HasProperties)))for(const e of o.HasProperties){if(!("value"in e.Name))continue;const t=e.Name.value;s.HasProperties.find(e=>"value"in e.Name&&e.Name.value===t)||s.HasProperties.push(e)}i.push(s)}for(const e of t)n.has(e)||i.push(e);return i}evalValue(e,t){const i=this.getValueKey(e),n=e[i];if(!("value"in n))return!1;if(this.value){if(!i)return t?.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;const e=structuredClone(this.value);"string"==typeof n.value&&"simple"===e.type&&(e.parameter=String(e.parameter));return this.evalRequirement(n.value,e,"Value",t)}return!i||("string"!=typeof n.value||""!==n.value.trim()||(t?.push({parameter:"Value",currentValue:"",pass:!1,requiredValue:this.value}),!1))}evalDataType(e,t){if(!this.dataType)return!0;const i=this.getValueKey(e);if(!i||!("value"in e[i]))return t?.push({parameter:"DataType",currentValue:null,pass:!1,requiredValue:this.dataType}),!1;const n=e[i];return this.evalRequirement(n.type??null,{type:"simple",parameter:this.dataType},"DataType",t)}evalURI(){return!0}}class ua extends ra{_ifcMaterialEntities=[/^IFCMATERIALLAYERSETUSAGE$/,/^IFCMATERIALLAYERSET$/,/^IFCMATERIALPROFILESETUSAGE$/,/^IFCMATERIALPROFILESET$/,/^IFCMATERIALCONSTITUENTSET$/,/^IFCMATERIAL$/,/^IFCMATERIALLIST$/];_materialParentAttributes=["ForLayerSet","MaterialLayers","ForProfileSet","MaterialProfiles","Material","MaterialConstituents","Materials"];_materialRelations={MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},ForProfileSet:{attributes:!0,relations:!0},MaterialProfiles:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}};facetType="Material";value;uri;serialize(e){if(!this.value||!this.uri)return"<material />";const t=oa("Value",this.value);let i="";return"requirement"===e&&(i+=`cardinality="${this.cardinality}"`,i+=this.uri?`uri=${this.uri}`:"",i+=this.instructions?`instructions="${this.instructions}"`:""),`<material ${i}>\n ${t}\n</material>`}async getEntities(e,t){const i=this._components.get(fs);for(const[n,s]of i.list){if(!e.find(e=>e.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},...this._materialRelations}});for(const e of o){if(!("value"in e._localId&&"value"in e._category&&Array.isArray(e.AssociatedTo)))continue;if(!this.hasValidMaterial(e))continue;const i=e.AssociatedTo.map(e=>"value"in e._localId&&e._localId.value?e._localId.value:null).filter(e=>null!==e);ct.append(t,n,...i)}}}async test(e,t,i={skipIfFails:!0}){const n=this._components.get(fs);for(const[s,r]of Object.entries(e)){const e=n.list.get(s);if(!e)continue;const o=await e.getItemsData([[...r][0]],{relations:{AssociatedTo:{attributes:!1,relations:!1},HasAssociations:{attributes:!0,relations:!0},...this._materialRelations}});for(const e of o){const n=this.getItemChecks(t,s,e,i.skipIfFails);if(n)if(Array.isArray(e.HasAssociations))for(const t of e.HasAssociations){if(!this._ifcMaterialEntities.some(e=>"value"in t._category&&e.test(t._category.value)))continue;if(this.hasValidMaterial(t,n))break}else n.push({parameter:null,currentValue:null,requiredValue:this.value,pass:!1})}}}hasValidMaterial(e,t){let i=!1;if("value"in e._category&&"IFCMATERIAL"===e._category.value){this.evalValue(e,t)&&(i=!0)}else for(const[n,s]of Object.entries(e))if(this._materialParentAttributes.includes(n)&&Array.isArray(s))for(const e of s){if("value"in e._category&&"IFCMATERIAL"===e._category.value){if(this.evalValue(e,t)){i=!0;break}}else{if(this.hasValidMaterial(e)){i=!0;break}}}return i}evalValue(e,t){if(!this.value)return t?.push({parameter:null,currentValue:e.Name&&"value"in e.Name?e.Name.value:null,pass:!0}),!0;if(!("value"in e._category)||"IFCMATERIAL"!==e._category.value)return null;let i=!1;return e.Name&&"value"in e.Name&&(i=this.evalRequirement(e.Name.value,this.value,"Value",t)),i||(e.Category&&"value"in e.Category&&(i=this.evalRequirement(e.Category.value,this.value,"Value",t)),i)}}class da extends ra{facetType="PartOf";_entityFacet;_entity;set entity(e){this._entity=e;const{name:t,predefinedType:i}=e;this._entityFacet=new ca(this._components,t),this._entityFacet.predefinedType=i}get entity(){return this._entity}relation;cardinality="required";constructor(e,t){super(e),this._entity=t,this._entityFacet=new ca(e,t.name),this._entityFacet.predefinedType=t.predefinedType}serialize(){return""}async getEntities(e,t){}async test(e){}}class pa{name;ifcVersion=new Set;identifier=v.create();description;instructions;requirementsDescription;applicability=new l.DataSet;requirements=new l.DataSet;components;constructor(e,t,i){this.components=e,this.name=t;for(const e of i)this.ifcVersion.add(e)}set(e){const t=e,i=this;for(const n in e){if("identifier"===n)continue;const e=t[n];n in this&&(i[n]=e)}return this.components.get(va).list.set(this.identifier,this),this}async test(e,t={skipIfFails:!0}){const i=new l.DataMap;if(0===this.requirements.size)return i;const n={},s=[];for(const t of this.applicability)s.push(t.getEntities(e,n));await Promise.all(s);const r=[];for(const e of this.requirements)r.push(e.test(n,i,t));return await Promise.all(r),i}serialize(){const e=`name="${this.name}"`,t=this.identifier?`identifier="${this.identifier}"`:"",i=this.description?`description="${this.description}"`:"",n=this.instructions?`instructions="${this.instructions}"`:"";return`<specification ifcVersion="${[...this.ifcVersion].join(" ")}" ${e} ${t} ${i} ${n}>\n <applicability minOccurs="1" maxOccurs="unbounded">\n ${[...this.applicability].map(e=>e.serialize("applicability")).join("\n")}\n </applicability>\n <requirements>\n ${[...this.requirements].map(e=>e.serialize("requirement")).join("\n")}\n </requirements>\n </specification>`}}const fa=e=>{if(!e)return;const t={};if("simpleValue"in e&&(t.type="simple",t.parameter=e.simpleValue),"restriction"in e){const i=e.restriction,n=Object.keys(i);if("pattern"in i&&(t.type="pattern",t.parameter=i.pattern.value),"enumeration"in i){t.type="enumeration";const e=i.enumeration.map(({value:e})=>i.base.includes("string")?String(e):i.base.includes("integer")||i.base.includes("double")?Number(e):e);t.parameter=e}if(n.some(e=>["minInclusive","minExclusive","maxInclusive","maxExclusive"].includes(e))){t.type="bounds";const e={},s=n.find(e=>e.includes("min")),r=n.find(e=>e.includes("max"));s&&(e.minInclusive="minInclusive"===s,e.min=i[s].value),r&&(e.maxInclusive="maxInclusive"===r,e.max=i[r].value),t.parameter=e}if(n.some(e=>["minLength","length","maxLength"].includes(e))){t.type="length";const e={};void 0!==i.length&&(e.length=i.length.value),void 0!==i.minLength&&(e.min=i.minLength.value),void 0!==i.maxLength&&(e.max=i.maxLength.value),t.parameter=e}}return void 0!==t.parameter?t:void 0},ma=(e,t)=>{const i=[];for(const n of t){const t=n.name,s=fa(t);if(!s)continue;const r=new ca(e,s);n.cardinality&&(r.cardinality=n.cardinality),r.predefinedType=fa(n.predefinedType),r.instructions=n.instructions,i.push(r)}return i},ga=(e,t)=>{const i=[];for(const n of t){const t=n.name,s=fa(t);if(!s)continue;const r=new aa(e,s);n.cardinality&&(r.cardinality=n.cardinality),r.value=fa(n.value),r.instructions=n.instructions,i.push(r)}return i},wa=(e,t)=>{const i=[];for(const n of t){const t=new ua(e);n.cardinality&&(t.cardinality=n.cardinality);const s=fa(n.value);"enumeration"===s?.type&&Array.isArray(s.parameter)&&(s.parameter=s.parameter.map(String)),t.value=s,t.uri=n.uri,t.instructions=n.instructions,i.push(t)}return i},ya=(e,t)=>{const i=[];for(const n of t){const t=n.propertySet,s=n.baseName,r=fa(t),o=fa(s);if(!o||!r)continue;const a=new ha(e,r,o);n.cardinality&&(a.cardinality=n.cardinality);const l=fa(n.value);a.value=l,a.dataType=n.dataType,a.uri=n.uri,a.instructions=n.instructions,i.push(a)}return i},_a=(e,t)=>{const i=[];for(const n of t){const t=n.system,s=fa(t);if(!s)continue;const r=new la(e,s);n.cardinality&&(r.cardinality=n.cardinality);const o=fa(n.value);"simple"===o?.type&&(o.parameter=String(o.parameter)),"enumeration"===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=(e,t)=>{const i=[];for(const n of t){const t=fa(n.entity.name);if(!t)continue;const s=fa(n.entity.predefinedType),r=new da(e,{name:t,predefinedType:s});r.relation=n.relation,n.cardinality&&(r.cardinality=n.cardinality),r.instructions=n.instructions,i.push(r)}return i};class va extends f{static uuid="9f0b9f78-9b2e-481a-b766-2fbfd01f342c";enabled=!0;static xmlParser=new qe({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0});IDSInfo;constructor(e){super(e),e.add(va.uuid,this)}list=new e.DataMap;getModelIdMap(e){const t={},i={};for(const[n,s]of e){const e=[...s].filter(([,e])=>e.pass).map(([e])=>e);ct.append(t,n,...e);const r=[...s].filter(([,e])=>!e.pass).map(([e])=>e);ct.append(i,n,...r)}return{pass:t,fail:i}}create(e,t,i){const n=new pa(this.components,e,t);return i&&(n.identifier=i),this.list.set(n.identifier,n),n}load(e){const t=[],i=va.xmlParser.parse(e).ids,{specifications:n,info:s}=i;if(this.IDSInfo={...s},n&&n.specification){const e=Array.isArray(n.specification)?n.specification:[n.specification];for(const i of e){const{name:e,ifcVersion:n,description:s,instructions:r,identifier:o}=i;if(!e||!n)continue;const a=[],l=[],{applicability:c,requirements:h}=i;if(c){const{maxOccurs:e,...t}=c,i=Array.isArray(t)?t:[t];for(const e of i)for(const t in e){const i=Array.isArray(e[t])?e[t]:[e[t]];if("entity"===t){const e=ma(this.components,i);a.push(...e)}if("attribute"===t){const e=ga(this.components,i);a.push(...e)}if("material"===t){const e=wa(this.components,i);a.push(...e)}if("classification"===t){const e=_a(this.components,i);a.push(...e)}if("property"===t){const e=ya(this.components,i);a.push(...e)}if("partOf"===t){const e=ba(this.components,i);a.push(...e)}}}let u;if(h){const{maxOccurs:e,...t}=h;u=h.description;const i=Array.isArray(t)?t:[t];for(const e of i)for(const t in e){const i=Array.isArray(e[t])?e[t]:[e[t]];if("entity"===t){const e=ma(this.components,i);l.push(...e)}if("attribute"===t){const e=ga(this.components,i);l.push(...e)}if("material"===t){const e=wa(this.components,i);l.push(...e)}if("classification"===t){const e=_a(this.components,i);l.push(...e)}if("property"===t){const e=ya(this.components,i);l.push(...e)}if("partOf"===t){const e=ba(this.components,i);l.push(...e)}}}const d=this.create(e,n.split(/\s+/),o);d.description=s,d.instructions=r,d.requirementsDescription=u,d.applicability.add(...a),d.requirements.add(...l),t.push(d)}}return t}export(e,t=this.list.values()){const i=t??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 ${zo.release} (https://github.com/thatopen/engine_components) --\x3e\n <info>\n <title>${e.title}</title>\n ${e.copyright?`<copyright>${e.copyright}</copyright>`:""}\n ${e.version?`<version>${e.version}</version>`:""}\n ${e.description?`<description>${e.description}</description>`:""}\n ${e.author?`<author>${e.author}</author>`:""}\n ${e.date?`<date>${e.date.toISOString().split("T")[0]}</date>`:""}\n ${e.purpose?`<purpose>${e.purpose}</purpose>`:""}\n ${e.milestone?`<milestone>${e.milestone}</milestone>`:""}\n </info>\n <specifications>\n ${[...i].map(e=>e.serialize()).join("\n")}\n </specifications>\n</ids>`}}class xa extends f{static uuid="267ca032-672f-4cb0-afa9-d24e904f39d6";enabled=!0;constructor(e){super(e),e.add(xa.uuid,this)}static distanceFromPointToLine(e,t,i,n=!1){const s=new c.Line3,r=new c.Vector3;return s.set(t,i),s.closestPointToPoint(e,n,r),r.distanceTo(e)}round(e){const t=1e3;e.x=Math.trunc(e.x*t)/t,e.y=Math.trunc(e.y*t)/t,e.z=Math.trunc(e.z*t)/t}async getVolumeFromFragments(e){return console.warn("getVolumeFromFragments is deprecated. Use getItemsVolume instead."),this.getItemsVolume(e)}async getItemsVolume(e){let t=0;const i=this.components.get(fs);for(const[n,s]of Object.entries(e)){const e=i.list.get(n);e&&(t+=await e.getItemsVolume([...s]))}return t}static convertUnits(e,t,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[t]||!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=e*(s[t]/s[i]),o=10**n;return Math.round(r*o)/o}}const Ca=(e,t,i)=>{const n=new c.Vector3(-t.z,0,t.x),s=new c.Vector3(t.x+n.x,0,t.z+n.z).normalize().multiplyScalar(i/2);return[e.x+s.x,e.y,e.z+s.z,e.x-s.x,e.y,e.z-s.z]},Sa=(e,t,i)=>{const n=new c.Vector3(-t.z,0,t.x),s=e.x-t.x*i+n.x*i*.4,r=e.z-t.z*i+n.z*i*.4,o=e.x-t.x*i-n.x*i*.4,a=e.z-t.z*i-n.z*i*.4;return[e.x,e.y,e.z,s,e.y,r,e.x,e.y,e.z,o,e.y,a]},Aa=()=>[],Ta=(e,t,i)=>{const n=new c.Vector3(-t.z,0,t.x),s=e.clone().addScaledVector(t,-i),r=s.clone().addScaledVector(n,.4*i),o=s.clone().addScaledVector(n,.4*-i);return[e.x,e.y,e.z,r.x,r.y,r.z,o.x,o.y,o.z]};class Pa extends l.DataMap{constructor(){super()}getBySystem(e){const t=new Map;for(const[i,n]of this)n.system===e&&t.set(i,n.data);return t}}class Ma extends l.DataMap{_container;constructor(e){super(),this._container=e,this.deleteGuard=e=>"0"!==e,this.set("0",{name:"0",visible:!0,material:new c.LineBasicMaterial({color:0})})}create(e,t){if(!this.has(e)){const i={name:e,visible:t?.visible??!0,material:t?.material??new c.LineBasicMaterial({color:0})};this.set(e,i)}return this.get(e)}setColor(e,t){const i=this.get(e);i&&(i.material.color.setHex(t),this.set(e,i))}setMaterial(e,t){const i=this.get(e);if(!i)return;const n=i.material;i.material=t,this._container.traverse(i=>{i.userData.layer===e&&(i.userData.isDimension||i.isLineSegments&&(i.material=t))}),n.dispose(),this.set(e,i)}setVisibility(e,t){const i=this.get(e);i&&(i.visible=t,this._container.traverse(i=>{i.userData.layer===e&&(i.visible=t)}),this.set(e,i))}assign(e,t){const i=this.get(t);i&&(e.userData.layer=t,i.visible||(e.visible=!1),e.isLineSegments&&(e.material=i.material))}resolveColor(e){const t=this.get(e);if(t)return t.material.color.getHex()}}class Ea extends c.Group{_viewport;_border;_handles=[];_raycaster=new c.Raycaster;_resizable=!1;_movable=!1;_dragHandle=null;_dragConstraints=[];_hoveredHandle=null;_moveDrag=null;_hoveringBorder=!1;_normalMat;_hoverMat;_borderMat;static _BORDER_COLOR=22015;static _BORDER_HOVER_COLOR=16746496;static _LINE_THRESHOLD=.06;static _HANDLE_DEFS=[{constraints:["left","top"]},{constraints:["right","top"]},{constraints:["right","bottom"]},{constraints:["left","bottom"]},{constraints:["top"]},{constraints:["right"]},{constraints:["bottom"]},{constraints:["left"]}];get resizable(){return this._resizable}set resizable(e){this._resizable=e;for(const t of this._handles)t.visible=e;e||(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat,this._hoveredHandle=null),this._dragHandle=null,this._dragConstraints=[])}get movable(){return this._movable}set movable(e){this._movable=e,e||(this._moveDrag=null,this._setBorderHover(!1))}get isDragging(){return null!==this._dragHandle||null!==this._moveDrag}constructor(e){super(),this._viewport=e,this._borderMat=new c.LineBasicMaterial({color:Ea._BORDER_COLOR,depthTest:!1});const t=new c.BufferGeometry;t.setAttribute("position",new c.BufferAttribute(new Float32Array(24),3)),this._border=new c.LineSegments(t,this._borderMat),this._border.renderOrder=999,this._border.frustumCulled=!1,this._border.userData.isDimension=!0,this.add(this._border),this._normalMat=new c.MeshBasicMaterial({color:Ea._BORDER_COLOR}),this._hoverMat=new c.MeshBasicMaterial({color:Ea._BORDER_HOVER_COLOR});const i=new c.SphereGeometry(.05,8,6);for(const e of Ea._HANDLE_DEFS){const t=new c.Mesh(i,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()}update(){const e=this._viewport,t=e.left,i=e.right,n=-e.top,s=-e.bottom,r=.005,o=this._border.geometry.attributes.position;o.setXYZ(0,t,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,t,r,s),o.setXYZ(6,t,r,s),o.setXYZ(7,t,r,n),o.needsUpdate=!0,this._border.geometry.computeBoundingSphere();const a=(t+i)/2,l=(n+s)/2,c=.01,h=[[t,c,n],[i,c,n],[i,c,s],[t,c,s],[a,c,n],[i,c,l],[a,c,s],[t,c,l]];for(let e=0;e<this._handles.length;e++)this._handles[e].position.set(...h[e])}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(e=>"right"===e?"left":"left"===e?"right":e)),this._viewport.top<this._viewport.bottom&&([this._viewport.top,this._viewport.bottom]=[this._viewport.bottom,this._viewport.top],this._dragConstraints=this._dragConstraints.map(e=>"top"===e?"bottom":"bottom"===e?"top":e)),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 t=null;if(this._resizable){const e=this._handles.filter(e=>e.visible),i=this._raycaster.intersectObjects(e,!1);t=i.length>0?i[0].object:null}if(t!==this._hoveredHandle&&(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat),t&&(t.material=this._hoverMat),this._hoveredHandle=t),this._movable&&!this._hoveredHandle){this._raycaster.params.Line={threshold:Ea._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 e=this._handles.filter(e=>e.visible),t=this._raycaster.intersectObjects(e,!1);if(t.length>0)return this._dragHandle=t[0].object,void(this._dragConstraints=[...this._dragHandle.userData.constraints])}if(this._movable){this._raycaster.params.Line={threshold:Ea._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(e){this.updateWorldMatrix(!0,!1);const t=new c.Vector3(0,1,0).transformDirection(this.matrixWorld),i=(new c.Vector3).setFromMatrixPosition(this.matrixWorld),n=(new c.Plane).setFromNormalAndCoplanarPoint(t,i),s=new c.Vector3;return e.intersectPlane(n,s)?this.worldToLocal(s):null}_setBorderHover(e){e!==this._hoveringBorder&&(this._hoveringBorder=e,this._borderMat.color.setHex(e?Ea._BORDER_HOVER_COLOR:Ea._BORDER_COLOR))}}class Ia{uuid=c.MathUtils.generateUUID();name;camera;onDisposed=new d;_left;_right;_top;_bottom;_drawingScale;_container=null;_helper=null;_helperVisible=!1;get left(){return this._left}set left(e){this._left=e,this.camera.left=e,this.camera.updateProjectionMatrix(),this._helper?.update()}get right(){return this._right}set right(e){this._right=e,this.camera.right=e,this.camera.updateProjectionMatrix(),this._helper?.update()}get top(){return this._top}set top(e){this._top=e,this.camera.top=e,this.camera.updateProjectionMatrix(),this._helper?.update()}get bottom(){return this._bottom}set bottom(e){this._bottom=e,this.camera.bottom=e,this.camera.updateProjectionMatrix(),this._helper?.update()}get drawingScale(){return this._drawingScale}set drawingScale(e){this._drawingScale=e}get helper(){return this._helper||(this._helper=new Ea(this)),this._helper}get helperVisible(){return this._helperVisible}set helperVisible(e){this._helperVisible=e,e?this._container?.add(this.helper):this._helper?.removeFromParent()}get bbox(){const e=new c.Vector3(this._left,0,-this._top),t=new c.Vector3(this._right,0,-this._bottom);return new c.Box3(e,t)}get size(){const e=new c.Vector3;return this.bbox.getSize(e),new c.Vector2(1e3*e.x,1e3*e.z)}get localXAxis(){return new c.Vector3(1,0,0)}get localYAxis(){return new c.Vector3(0,0,-1)}get normal(){return new c.Vector3(0,1,0)}constructor(e){this._left=e.left,this._right=e.right,this._top=e.top,this._bottom=e.bottom,this._drawingScale=e.scale??100,this.name=e.name??"Drawing Viewport",this.camera=new c.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)}setContainer(e){this._container=e,this._helperVisible&&this._helper&&e.add(this._helper)}clipLine(e){const t=this.bbox,{start:i,end:n}=e,s=t.containsPoint(i),r=t.containsPoint(n);if(s&&r)return e;if(!s&&!r){const t=this.getPlaneIntersections(e);return t.length<2?null:new c.Line3(t[0],t[1])}const o=this.getPlaneIntersections(e);return 0===o.length?null:s?new c.Line3(i,o[0]):new c.Line3(o[0],n)}dispose(){this._helper?.dispose(),this._helper=null,this.onDisposed.trigger(),this.onDisposed.reset()}get bboxPlanes(){const e=this.bbox;return[new c.Plane(new c.Vector3(1,0,0),-e.min.x),new c.Plane(new c.Vector3(-1,0,0),e.max.x),new c.Plane(new c.Vector3(0,0,1),-e.min.z),new c.Plane(new c.Vector3(0,0,-1),e.max.z)]}getPlaneIntersections(e){const t=[];for(const i of this.bboxPlanes){const n=new c.Vector3;i.intersectLine(e,n)&&this.bbox.containsPoint(n)&&t.push(n)}return t}}class Da extends l.DataMap{_container;constructor(e){super(),this._container=e,this.onBeforeDelete.add(({value:e})=>{this._container.remove(e.camera),e.dispose()})}create(e){const t=new Ia(e);return this._container.add(t.camera),t.setContainer(this._container),this.set(t.uuid,t),t}}class za extends c.Group{_drawing;_topFrame;_pillars;_bottomFrame;_topPlane;_bottomPlane;_frameMat;_depthMat;_planeMat;static _FRAME_COLOR=22015;static _DEPTH_COLOR=22015;width=10;height=10;farHandle=new c.Object3D;widthHandle=new c.Object3D;heightHandle=new c.Object3D;constructor(e){super(),this._drawing=e,this._frameMat=new c.LineBasicMaterial({color:za._FRAME_COLOR,depthTest:!1}),this._depthMat=new c.LineBasicMaterial({color:za._DEPTH_COLOR,depthTest:!1,transparent:!0,opacity:.4}),this._planeMat=new c.MeshBasicMaterial({color:za._FRAME_COLOR,transparent:!0,opacity:.07,side:c.DoubleSide,depthTest:!1});const t=()=>{const e=new c.BufferGeometry;return e.setAttribute("position",new c.BufferAttribute(new Float32Array(12),3)),e.setIndex([0,1,2,0,2,3]),e};this._topPlane=new c.Mesh(t(),this._planeMat),this._topPlane.renderOrder=998,this._topPlane.frustumCulled=!1,this._topPlane.userData.isDimension=!0,this._bottomPlane=new c.Mesh(t(),this._planeMat),this._bottomPlane.renderOrder=998,this._bottomPlane.frustumCulled=!1,this._bottomPlane.userData.isDimension=!0;const i=new c.BufferGeometry;i.setAttribute("position",new c.BufferAttribute(new Float32Array(24),3)),this._topFrame=new c.LineSegments(i,this._frameMat),this._topFrame.renderOrder=999,this._topFrame.frustumCulled=!1,this._topFrame.userData.isDimension=!0;const n=new c.BufferGeometry;n.setAttribute("position",new c.BufferAttribute(new Float32Array(24),3)),this._pillars=new c.LineSegments(n,this._depthMat),this._pillars.renderOrder=999,this._pillars.frustumCulled=!1,this._pillars.userData.isDimension=!0;const s=new c.BufferGeometry;s.setAttribute("position",new c.BufferAttribute(new Float32Array(24),3)),this._bottomFrame=new c.LineSegments(s,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 e=this.width/2,t=this.height/2,i=-this._drawing.far,n=.005,s=-e,r=e,o=-t,a=t,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=(e,t)=>{const i=e.geometry.attributes.position;i.setXYZ(0,s,t,o),i.setXYZ(1,r,t,o),i.setXYZ(2,r,t,a),i.setXYZ(3,s,t,a),i.needsUpdate=!0,e.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(e){e.attach(this.farHandle),e.setSpace("local"),e.showX=!1,e.showZ=!1,e.addEventListener("objectChange",()=>{this.farHandle.position.x=0,this.farHandle.position.z=0;const e=Math.max(.1,-this.farHandle.position.y);this._drawing.far=e,this.farHandle.position.y=-e,this.update()})}attachWidthGizmo(e){e.attach(this.widthHandle),e.setSpace("local"),e.showY=!1,e.showZ=!1,e.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(e){e.attach(this.heightHandle),e.setSpace("local"),e.showX=!1,e.showY=!1,e.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()}}function ka(e,t){if(3!==e.length||3!==t.length)throw new Error("computeAlignmentMatrix requires exactly 3 point pairs.");const i=(e,t)=>{const i=(new c.Vector3).subVectors(e[1],e[0]),n=(new c.Vector3).subVectors(e[2],e[0]);if((new c.Vector3).crossVectors(i,n).length()<1e-6)throw new Error(`${t} points are collinear — three non-collinear points are required to define a plane.`)};i(e,"Drawing"),i(t,"World");const n=(e,t,i)=>{const n=(new c.Vector3).subVectors(t,e),s=(new c.Vector3).subVectors(i,e),r=n.clone().normalize(),o=(new c.Vector3).crossVectors(n,s).normalize(),a=(new c.Vector3).crossVectors(r,o).normalize();return(new c.Matrix4).makeBasis(r,o,a)},s=n(e[0],e[1],e[2]),r=n(t[0],t[1],t[2]).clone().multiply(s.clone().invert()),o=e[0].distanceTo(e[1]);if(o<1e-10)throw new Error("The first two drawing points are coincident — cannot compute scale.");const a=t[0].distanceTo(t[1])/o,l=e[0].clone().multiplyScalar(a).applyMatrix4(r),h=(new c.Vector3).subVectors(t[0],l),u=(new c.Quaternion).setFromRotationMatrix(r),d=new c.Matrix4;return d.compose(h,u,new c.Vector3(a,a,a)),d}class Ba{uuid=c.MathUtils.generateUUID();_raycaster=new c.Raycaster;_components;constructor(e){this._components=e}world=null;three=new c.Group;annotations=new Pa;layers=new Ma(this.three);activeLayer="0";far=10;viewports=new Da(this.three);onDisposed=new d;raycast(e,t=null){this._raycaster.set(e.origin,e.direction),this._raycaster.layers.set(1),this._raycaster.params.Line&&(this._raycaster.params.Line.threshold=.1);const i=[];this.three.traverse(e=>{e instanceof c.LineSegments&&!e.userData.isDimension&&i.push(e)});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 o=null;if(s.object instanceof c.LineSegments&&void 0!==s.index){const e=s.object.geometry.attributes.position,t=s.index,i=new c.Vector3(e.getX(t),e.getY(t),e.getZ(t)),n=new c.Vector3(e.getX(t+1),e.getY(t+1),e.getZ(t+1));i.applyMatrix4(s.object.matrixWorld),this.three.worldToLocal(i),n.applyMatrix4(s.object.matrixWorld),this.three.worldToLocal(n),o=new c.Line3(i,n)}return{point:r,object:s.object,viewport:t,line:o}}alignTo(e,t){ka(e,t).decompose(this.three.position,this.three.quaternion,this.three.scale)}static toDrawingSpace(e,t){e.updateWorldMatrix(!0,!1),t.three.updateWorldMatrix(!0,!1);const i=(new c.Matrix4).copy(t.three.matrixWorld).invert().multiply(e.matrixWorld),n=e.geometry.attributes.position,s=n.count,r=new Float32Array(3*s),o=new c.Vector3;for(let e=0;e<s;e++)o.fromBufferAttribute(n,e).applyMatrix4(i),r[3*e]=o.x,r[3*e+1]=0,r[3*e+2]=o.z;const a=new c.BufferGeometry;return a.setAttribute("position",new c.BufferAttribute(r,3)),new c.LineSegments(a)}addProjectionLines(e,t="0"){return this.layers.has(t)||(console.warn(`[TechnicalDrawing] Layer "${t}" does not exist. Falling back to "0".`),t="0"),this.layers.assign(e,t),e.layers.set(1),e.material instanceof c.LineDashedMaterial&&e.computeLineDistances(),e.geometry.computeBoundsTree({strategy:0,indirect:!0,type:rs}),this.three.add(e),e}async addProjectionFromItems(e,t){if(!this.world)return void console.warn("[TechnicalDrawing] addProjectionFromItems: drawing has no world assigned.");for(const e of[t.layers.visible,t.layers.hidden])if(!this.layers.has(e))return void console.warn(`[TechnicalDrawing] Layer "${e}" does not exist — create it before calling addProjectionFromItems.`);const i=this._components.get(Ir),n=i.projectionDirection.clone(),s=i.nearPlane,r=i.farPlane;try{this.three.updateWorldMatrix(!0,!1);const n=new c.Vector3(0,-1,0).transformDirection(this.three.matrixWorld).normalize();i.projectionDirection.copy(n);const s=(new c.Matrix4).makeRotationFromQuaternion((new c.Quaternion).setFromUnitVectors(n,new c.Vector3(0,-1,0))),r=(new c.Vector3).setFromMatrixPosition(this.three.matrixWorld).applyMatrix4(s).y;i.farPlane=r,i.nearPlane=r-this.far;const o=await i.get(e,this.world,{onProgress:t.onProgress}),a=e=>Ba.toDrawingSpace(new c.LineSegments(e),this);this.addProjectionLines(a(o.visible),t.layers.visible),this.addProjectionLines(a(o.hidden),t.layers.hidden)}finally{i.projectionDirection.copy(n),i.nearPlane=s,i.farPlane=r}}orientTo(e){const t=e.clone().normalize(),i=Math.SQRT1_2;t.x>.999?this.three.quaternion.set(.5,-.5,.5,.5):t.x<-.999?this.three.quaternion.set(.5,.5,-.5,.5):t.y>.999?this.three.quaternion.set(0,0,1,0):t.y<-.999?this.three.quaternion.set(0,0,0,1):t.z>.999?this.three.quaternion.set(0,i,-i,0):t.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(y).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset()}}class Oa{constructor(e){this._components=e,this.styles.onItemUpdated.add(({key:e})=>{const t=this._materialCache.get(e);t&&t.color.setHex(this._resolveStyle(e).color);const i=this._meshMaterialCache.get(e);i&&i.color.setHex(this._resolveStyle(e).color);const n=this._components.get(_l),s=n?[...n.list.values()]:[...this._knownDrawings];for(const t of s){const i=[...t.annotations.getBySystem(this)].filter(([,t])=>t.style===e).map(([e])=>e);i.length>0&&this.update(t,i,{})}})}_components;styles=new l.DataMap;activeStyle="default";onCommit=new d;onUpdate=new d;onDelete=new d;onDisposed=new d;_knownDrawings=new Set;_previewMaterial=new c.LineBasicMaterial({color:16737894,depthTest:!1});_previewObject=null;_previewDrawing=null;_materialCache=new l.DataMap;_meshMaterialCache=new l.DataMap;_ownsChildGeometry=!0;_onAfterPersist(e,t){}_onDispose(){}_updatePreview(){}get(e){const t=new l.DataMap;for(const i of e)for(const[e,n]of i.annotations.getBySystem(this))t.set(e,{drawingUuid:i.uuid,item:n});return t}add(e,t){const i={uuid:c.MathUtils.generateUUID(),style:this.activeStyle,...t},n=this._persist(e,i);return this.onCommit.trigger([n]),i}update(e,t,i){for(const n of t){const t=e.annotations.get(n);if(!t||t.system!==this)continue;const s=t.data;Object.assign(s,i),this._redraw(s,t.three),this.onUpdate.trigger({item:s,group:t.three})}}pick(e,t=.05){const i=new c.Raycaster;i.ray.copy(e),i.params.Line={threshold:t},i.params.LineSegments={threshold:t};const n=c.Line.prototype.raycast;let s=null,r=1/0;for(const e of this._knownDrawings)for(const[t,o]of e.annotations){if(o.system!==this)continue;const e=o.three;e.updateWorldMatrix(!0,!0),e.traverse(o=>{if(o===e)return;const a=[];if(o instanceof c.LineSegments&&o.userData.isDimension)n.call(o,i,a),a.length>0&&a[0].distance<r&&(r=a[0].distance,s=t);else if(o instanceof c.Mesh){const e=(new c.Box3).setFromObject(o),n=new c.Vector3;if(i.ray.intersectBox(e,n)){const e=i.ray.origin.distanceTo(n);e<r&&(r=e,s=t)}}})}return s}delete(e,t){const i=[];for(const n of t){const t=e.annotations.get(n);t&&t.system===this&&(this._disposeGroup(t.three),e.annotations.delete(n),i.push(n))}i.length&&this.onDelete.trigger(i)}clear(e){const t=e??[...this._knownDrawings];for(const e of t){const t=[];for(const[i,n]of e.annotations)n.system===this&&t.push(i);for(const i of t){const t=e.annotations.get(i);this._disposeGroup(t.three),e.annotations.delete(i)}}}dispose(){this._clearPreview(),this._onDispose(),this.clear();for(const e of this._materialCache.values())e.dispose();this._materialCache.clear();for(const e of this._meshMaterialCache.values())e.dispose();this._meshMaterialCache.clear(),this._previewMaterial.dispose(),this.onCommit.reset(),this.onUpdate.reset(),this.onDelete.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}_trackDrawing(e){this._knownDrawings.has(e)||(this._knownDrawings.add(e),e.onDisposed.add(()=>this._knownDrawings.delete(e)))}_resolveStyle(e){return this.styles.get(e)??this.styles.get("default")}_getMaterial(e){const t=this._materialCache.get(e);if(t)return t;const i=new c.LineBasicMaterial({color:this._resolveStyle(e).color});return this._materialCache.set(e,i),i}_getMeshMaterial(e){const t=this._meshMaterialCache.get(e);if(t)return t;const i=new c.MeshBasicMaterial({color:this._resolveStyle(e).color,side:c.DoubleSide});return this._meshMaterialCache.set(e,i),i}_disposeGroup(e){if(e.removeFromParent(),this._ownsChildGeometry)e.traverse(e=>{e.geometry instanceof c.BufferGeometry&&e.geometry.dispose()});else for(;e.children.length>0;)e.remove(e.children[0])}_clearPreview(){this._previewObject&&(this._previewObject.removeFromParent(),this._previewObject.geometry.dispose(),this._previewObject=null)}_persist(e,t){this._trackDrawing(e);const i=this._resolveStyle(t.style),n=this._buildGroup(t,i);return n.userData.isDimension=!0,n.userData.annotationUuid=t.uuid,n.userData.layer=e.activeLayer,e.three.add(n),e.annotations.set(t.uuid,{system:this,data:t,three:n}),this._onAfterPersist(t,n),{drawing:e,item:t,group:n}}_redraw(e,t){for(;t.children.length>0;){const e=t.children[0];this._ownsChildGeometry&&e.geometry instanceof c.BufferGeometry&&e.geometry.dispose(),t.remove(e)}const i=this._resolveStyle(e.style),n=this._buildGroup(e,i);for(;n.children.length>0;)t.add(n.children[0]);this._onAfterPersist(e,t)}}function Va(e,t){const i=e[0],n=e[e.length-1],s=(new c.Vector3).subVectors(n,i);if(s.lengthSq()<1e-10)return 0;s.normalize();const r=new c.Vector3(-s.z,0,s.x);return t.clone().sub(i).dot(r)}function La(e,t){const i=[];for(let n=0;n<e.length-1;n++)i.push({uuid:c.MathUtils.generateUUID(),pointA:e[n].clone(),pointB:e[n+1].clone(),offset:t,style:""});return i}function Na(e,t){switch(e.kind){case"awaitingFirstPoint":if("CLICK"===t.type){if(!t.line)return e;const i=(new c.Vector3).subVectors(t.line.end,t.line.start).normalize();return{kind:"placingPoints",points:[t.point.clone()],cursor:null,lineDir:i,firstLine:t.line.clone()}}return"SELECT_LINE"===t.type?{kind:"positioningOffset",points:[t.line.start.clone(),t.line.end.clone()],cursor:null}:e;case"placingPoints":if("MOUSE_MOVE"===t.type){const i=new c.Vector3(-e.lineDir.z,0,e.lineDir.x),n=e.points[e.points.length-1],s=t.point.clone().sub(n).dot(i),r=n.clone().addScaledVector(i,s);return{...e,cursor:r}}if("CLICK"===t.type){if(!t.line)return e;if(function(e,t){const i=1e-6;return e.start.distanceTo(t.start)<i&&e.end.distanceTo(t.end)<i||e.start.distanceTo(t.end)<i&&e.end.distanceTo(t.start)<i}(t.line,e.firstLine))return e;const s=(new c.Vector3).subVectors(t.line.end,t.line.start).normalize();if(i=s,n=e.lineDir,!(Math.abs(i.dot(n))>.999))return e;const r=function(e,t,i){const n=e.clone().sub(t.start).dot(i);return t.start.clone().addScaledVector(i,n)}(e.points[0],t.line,e.lineDir),o=[...e.points,r];return{...e,points:o,cursor:e.cursor}}return"CONFIRM"===t.type&&e.points.length>=2?{kind:"positioningOffset",points:e.points,cursor:null}:"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e;case"positioningOffset":if("MOUSE_MOVE"===t.type)return{...e,cursor:t.point.clone()};if("CLICK"===t.type){const i=Va(e.points,t.point);return{kind:"committed",dimensions:La(e.points,i)}}return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e}var i,n}function Fa(e){const{pointA:t,pointB:i,offset:n}=e,s=(new c.Vector3).subVectors(i,t),r=new c.Vector3(-s.z,0,s.x).normalize(),o=t.clone().addScaledVector(r,n),a=i.clone().addScaledVector(r,n),l=(new c.Vector3).subVectors(a,o).normalize();return[{tip:o,dir:l},{tip:a,dir:l.clone().negate()}]}function Ra(e,t){const{pointA:i,pointB:n,offset:s}=e,r=(new c.Vector3).subVectors(n,i),o=new c.Vector3(-r.z,0,r.x).normalize(),a=s>=0?1:-1,l=Math.abs(s),h=i.clone().addScaledVector(o,t.extensionGap*a),u=i.clone().addScaledVector(o,(l+t.extensionOvershoot)*a),d=n.clone().addScaledVector(o,t.extensionGap*a),p=n.clone().addScaledVector(o,(l+t.extensionOvershoot)*a),f=i.clone().addScaledVector(o,s),m=n.clone().addScaledVector(o,s),g=(new c.Vector3).subVectors(m,f).normalize(),w=t.lineTick(f,g,t.tickSize),y=t.lineTick(m,g.clone().negate(),t.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 Ua(e,t,i,n){if("placingPoints"===e){const e=[];for(let i=0;i<t.length-1;i++){const n=t[i],s=t[i+1];e.push(n.x,n.y,n.z,s.x,s.y,s.z)}if(i){const n=t[t.length-1];e.push(n.x,n.y,n.z,i.x,i.y,i.z)}return e}if(!i||t.length<2)return[];const s=Va(t,i),r=[];for(let e=0;e<t.length-1;e++)r.push(...Ra({pointA:t[e],pointB:t[e+1],offset:s},n));return r}class ja extends Oa{enabled=!0;machineState={kind:"awaitingFirstPoint"};onMachineStateChanged=new d;constructor(e){super(e),this.styles.set("default",{lineTick:Ca,tickSize:.4,extensionGap:.05,extensionOvershoot:.2,color:0,textOffset:.4,fontSize:.45})}pickHandle(e,t,i=.1){const n=(new c.Matrix4).copy(e.three.matrixWorld).invert(),s=t.origin.clone().applyMatrix4(n),r=t.direction.clone().transformDirection(n).normalize(),o=new c.Ray(s,r),a=new c.Plane(new c.Vector3(0,1,0),0),l=o.intersectPlane(a,new c.Vector3);if(!l)return null;let h=null,u=i;for(const[t,i]of e.annotations.getBySystem(this)){const e=(new c.Vector3).subVectors(i.pointB,i.pointA),n=new c.Vector3(-e.z,0,e.x).normalize(),s=(new c.Vector3).addVectors(i.pointA,i.pointB).multiplyScalar(.5).addScaledVector(n,i.offset);for(const[e,n]of[["pointA",i.pointA],["pointB",i.pointB],["offset",s]]){const i=Math.hypot(l.x-n.x,l.z-n.z);i<u&&(u=i,h={uuid:t,handle:e})}}return h}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const i=Na(this.machineState,e);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 e of i.dimensions)e.style=this.activeStyle;const e=i.dimensions.map(e=>this._persist(this._previewDrawing,e));this.onCommit.trigger(e)}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(e,t){const i=new c.Group,n=Ra(e,t),s=new c.BufferGeometry;s.setAttribute("position",new c.BufferAttribute(new Float32Array(n),3));const r=new c.LineSegments(s,this._getMaterial(e.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),t.meshTick)for(const{tip:n,dir:s}of Fa(e)){const r=t.meshTick(n,s,t.tickSize),o=new c.BufferGeometry;o.setAttribute("position",new c.BufferAttribute(new Float32Array(r),3));const a=new c.Mesh(o,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isMeshTick=!0,i.add(a)}return i}_updatePreview(){const e=this.machineState;if("placingPoints"!==e.kind&&"positioningOffset"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle);this._previewMaterial.color.setHex(t.color);const i=Ua(e.kind,e.points,e.cursor,t);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 e=new c.BufferGeometry;e.setAttribute("position",new c.BufferAttribute(new Float32Array(i),3)),this._previewObject=new c.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingFirstPoint"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}}const $a=Math.PI/180;function Wa(e,t,i,n){const s=function(e,t,i){const n=(new c.Vector3).subVectors(e,t).normalize(),s=(new c.Vector3).subVectors(i,t).normalize();return(new c.Vector3).addVectors(n,s).normalize()}(e,t,i);return(new c.Vector3).subVectors(n,t).setY(0).dot(s)}function Ha(e,t,i,n){return Wa(e,t,i,n)<0}function Ga(e,t){switch(e.kind){case"awaitingFirstLine":return"CLICK"===t.type&&t.line?{kind:"awaitingSecondLine",line1:t.line.clone(),pointA:t.point.clone()}:e;case"awaitingSecondLine":if("CLICK"===t.type&&t.line){const i=(new c.Vector3).subVectors(e.line1.end,e.line1.start).normalize(),n=(new c.Vector3).subVectors(t.line.end,t.line.start).normalize();if(Math.abs(i.dot(n))>Math.cos($a))return e;const s=function(e,t,i,n){const s=t.x*n.z-t.z*n.x;if(Math.abs(s)<1e-10)return null;const r=(new c.Vector3).subVectors(i,e),o=(r.x*n.z-r.z*n.x)/s;return new c.Vector3(e.x+t.x*o,0,e.z+t.z*o)}(e.line1.start,i,t.line.start,n);return s?{kind:"positioningArc",pointA:e.pointA.clone(),vertex:s,pointB:t.point.clone(),cursor:null,flipped:!1}:e}return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e;case"positioningArc":if("MOUSE_MOVE"===t.type){const i=Ha(e.pointA,e.vertex,e.pointB,t.point);return{...e,cursor:t.point.clone(),flipped:i}}if("CLICK"===t.type){const i=Ha(e.pointA,e.vertex,e.pointB,t.point),n=Math.max(.05,Math.abs(Wa(e.pointA,e.vertex,e.pointB,t.point)));return{kind:"committed",dimension:{uuid:c.MathUtils.generateUUID(),pointA:e.pointA.clone(),vertex:e.vertex.clone(),pointB:e.pointB.clone(),arcRadius:n,flipped:i,style:""}}}return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e}}function qa(e){const t=(new c.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new c.Vector3).subVectors(e.pointB,e.vertex).normalize(),n=Math.atan2(t.z,t.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;e.flipped&&(s-=2*Math.sign(s)*Math.PI);const r=new c.Vector3(e.vertex.x+Math.cos(n)*e.arcRadius,0,e.vertex.z+Math.sin(n)*e.arcRadius),o=n+s,a=new c.Vector3(e.vertex.x+Math.cos(o)*e.arcRadius,0,e.vertex.z+Math.sin(o)*e.arcRadius),l=Math.sign(s);return[{tip:r,dir:new c.Vector3(-Math.sin(n)*l,0,Math.cos(n)*l)},{tip:a,dir:new c.Vector3(Math.sin(o)*l,0,-Math.cos(o)*l)}]}function Za(e){const t=(new c.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new c.Vector3).subVectors(e.pointB,e.vertex).normalize(),n=Math.acos(c.MathUtils.clamp(t.dot(i),-1,1));return e.flipped?2*Math.PI-n:n}function Ya(e){const t=(new c.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new c.Vector3).subVectors(e.pointB,e.vertex).normalize(),n=Math.atan2(t.z,t.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 e.flipped?r+Math.PI:r}function Xa(e,t,i,n,s,r=!1){const o=Math.atan2(t.z,t.x);let a=Math.atan2(i.z,i.x)-o;for(;a>Math.PI;)a-=2*Math.PI;for(;a<-Math.PI;)a+=2*Math.PI;r&&(a-=2*Math.sign(a)*Math.PI);const l=[];for(let t=0;t<8;t++){const i=o+a*(t/8),s=o+a*((t+1)/8);l.push(e.x+Math.cos(i)*n,0,e.z+Math.sin(i)*n,e.x+Math.cos(s)*n,0,e.z+Math.sin(s)*n)}const h=new c.Vector3(e.x+Math.cos(o)*n,0,e.z+Math.sin(o)*n),u=new c.Vector3(e.x+Math.cos(o+a)*n,0,e.z+Math.sin(o+a)*n),d=e.clone().addScaledVector(t,s.extensionGap),p=e.clone().addScaledVector(i,s.extensionGap);l.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(a),m=new c.Vector3(-Math.sin(o)*f,0,Math.cos(o)*f),g=o+a,w=new c.Vector3(Math.sin(g)*f,0,-Math.cos(g)*f);return l.push(...s.lineTick(h,m,s.tickSize),...s.lineTick(u,w,s.tickSize)),l}function Ka(e,t){const i=(new c.Vector3).subVectors(e.pointA,e.vertex).normalize(),n=(new c.Vector3).subVectors(e.pointB,e.vertex).normalize();return Xa(e.vertex,i,n,e.arcRadius,t,e.flipped??!1)}function Qa(e,t,i,n,s,r=!1){if(!n)return[];const o=Math.max(.05,(new c.Vector3).subVectors(n,t).setY(0).length());return Xa(t,(new c.Vector3).subVectors(e,t).normalize(),(new c.Vector3).subVectors(i,t).normalize(),o,s,r)}class Ja extends Oa{enabled=!0;machineState={kind:"awaitingFirstLine"};onMachineStateChanged=new d;_secondLinePreviewObject=null;constructor(e){super(e),this.styles.set("default",{lineTick:Ca,tickSize:.4,extensionGap:.05,color:0,textOffset:.25,fontSize:.45})}pickHandle(e,t,i){return null}sendMachineEvent(e){const t=e.drawing??null;if("awaitingSecondLine"===this.machineState.kind&&"MOUSE_MOVE"===e.type)return t&&(this._previewDrawing=t),void this._updateSecondLinePreview(e.point,e.line??null);const i=Ga(this.machineState,e);if(i!==this.machineState){if("awaitingSecondLine"===this.machineState.kind&&this._clearSecondLinePreview(),this.machineState=i,t&&(this._previewDrawing=t),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 e=this._persist(this._previewDrawing,i.dimension);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(e,t){const i=new c.Group,n=Ka(e,t),s=new c.BufferGeometry;s.setAttribute("position",new c.BufferAttribute(new Float32Array(n),3));const r=new c.LineSegments(s,this._getMaterial(e.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),t.meshTick)for(const{tip:n,dir:s}of qa(e)){const r=t.meshTick(n,s,t.tickSize),o=new c.BufferGeometry;o.setAttribute("position",new c.BufferAttribute(new Float32Array(r),3));const a=new c.Mesh(o,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isMeshTick=!0,i.add(a)}return i}_updatePreview(){const e=this.machineState;if("positioningArc"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle),i=Qa(e.pointA,e.vertex,e.pointB,e.cursor,t,e.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 e=new c.BufferGeometry;e.setAttribute("position",new c.BufferAttribute(new Float32Array(i),3)),this._previewObject=new c.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(i),e.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(e,t){if("awaitingSecondLine"!==this.machineState.kind)return void this._clearSecondLinePreview();if(!this._previewDrawing)return void this._clearSecondLinePreview();const i=this.machineState,n=(new c.Vector3).subVectors(i.line1.end,i.line1.start).normalize();if(!t)return void this._clearSecondLinePreview();const s=(new c.Vector3).subVectors(t.end,t.start).normalize(),r=function(e,t,i,n){const s=t.x*n.z-t.z*n.x;if(Math.abs(s)<1e-6)return null;const r=i.x-e.x,o=i.z-e.z,a=(r*n.z-o*n.x)/s;return new c.Vector3(e.x+a*t.x,0,e.z+a*t.z)}(i.line1.start,n,t.start,s);if(!r)return void this._clearSecondLinePreview();const o=e.clone(),a=(new c.Vector3).subVectors(o,r).setY(0);if(a.length()<.01)return void this._clearSecondLinePreview();const l=(new c.Vector3).subVectors(i.pointA,r).normalize(),h=a.normalize(),u=Math.atan2(l.z,l.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),o.distanceTo(r))),m=new c.Vector3(r.x+Math.cos(p)*f,0,r.z+Math.sin(p)*f),g=this._resolveStyle(this.activeStyle),w=Qa(i.pointA,r,o,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 e=new c.BufferGeometry;e.setAttribute("position",new c.BufferAttribute(new Float32Array(w),3)),this._secondLinePreviewObject=new c.LineSegments(e,this._previewMaterial),this._secondLinePreviewObject.layers.set(1),this._secondLinePreviewObject.renderOrder=1,this._secondLinePreviewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._secondLinePreviewObject)}else{const e=this._secondLinePreviewObject.geometry.attributes.position;e.set(w),e.needsUpdate=!0}}}function el(e,t){const i=t.x-e.x,n=t.z-e.z,s=Math.sqrt(i*i+n*n);if(0===s)return e.clone();const r=Math.atan2(n,i),o=Math.round(r/(Math.PI/4))*(Math.PI/4);return new c.Vector3(e.x+Math.cos(o)*s,0,e.z+Math.sin(o)*s)}function tl(e,t){switch(e.kind){case"awaitingArrowTip":return"CLICK"===t.type?{kind:"placingElbow",arrowTip:t.point.clone(),cursor:null}:e;case"placingElbow":return"MOUSE_MOVE"===t.type?{...e,cursor:t.point.clone()}:"CLICK"===t.type?{kind:"placingExtension",arrowTip:e.arrowTip,elbow:t.point.clone(),cursor:null}:"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"placingExtension":return"MOUSE_MOVE"===t.type?{...e,cursor:el(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",arrowTip:e.arrowTip,elbow:e.elbow,extensionEnd:el(e.elbow,t.point)}:"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"enteringText":if("SUBMIT_TEXT"===t.type&&t.text.trim().length>0){return{kind:"committed",annotation:{uuid:c.MathUtils.generateUUID(),arrowTip:e.arrowTip.clone(),elbow:e.elbow.clone(),extensionEnd:e.extensionEnd.clone(),text:t.text.trim(),style:""}}}return"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e}}function il(e,t,i,n){return"curved"===n.leaderShape?function(e,t,i,n){const s=new c.QuadraticBezierCurve3(e,t,i).getPoints(24),r=[];for(let e=0;e<s.length-1;e++){const t=s[e],i=s[e+1];r.push(t.x,t.y,t.z,i.x,i.y,i.z)}if(n.lineTick){const i=(new c.Vector3).subVectors(e,t);i.lengthSq()>1e-10&&r.push(...n.lineTick(e,i.normalize(),n.tickSize))}return r}(e,t,i,n):function(e,t,i,n){const s=[e.x,e.y,e.z,t.x,t.y,t.z,t.x,t.y,t.z,i.x,i.y,i.z];if(n.lineTick){const i=(new c.Vector3).subVectors(e,t);i.lengthSq()>1e-10&&s.push(...n.lineTick(e,i.normalize(),n.tickSize))}return s}(e,t,i,n)}function nl(e,t){return il(e.arrowTip,e.elbow,e.extensionEnd,t)}function sl(e,t,i,n,s){return n?il(t,"placingElbow"===e?n:i,n,s):[]}class rl extends Oa{enabled=!0;machineState={kind:"awaitingArrowTip"};onMachineStateChanged=new d;_previewMeshMaterial=new c.MeshBasicMaterial({color:16737894,side:c.DoubleSide,depthTest:!1});_previewMeshObject=null;constructor(e){super(e),this.styles.set("default",{tickSize:.4,color:0,textOffset:.1,fontSize:.45,lineTick:Sa})}pickHandle(e,t,i=.1){const n=(new c.Matrix4).copy(e.three.matrixWorld).invert(),s=t.origin.clone().applyMatrix4(n),r=t.direction.clone().transformDirection(n).normalize(),o=new c.Ray(s,r),a=new c.Plane(new c.Vector3(0,1,0),0),l=o.intersectPlane(a,new c.Vector3);if(!l)return null;let h=null,u=i;for(const[t,i]of e.annotations.getBySystem(this))for(const[e,n]of[["elbow",i.elbow],["extensionEnd",i.extensionEnd]]){const i=Math.hypot(l.x-n.x,l.z-n.z);i<u&&(u=i,h={uuid:t,handle:e})}return h}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const i=tl(this.machineState,e);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 e=this._persist(this._previewDrawing,i.annotation);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(e,t){const i=new c.Group,n=nl(e,t),s=new c.BufferGeometry;s.setAttribute("position",new c.BufferAttribute(new Float32Array(n),3));const r=new c.LineSegments(s,this._getMaterial(e.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),t.meshTick){const n=(new c.Vector3).subVectors(e.arrowTip,e.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=t.meshTick(e.arrowTip,n,t.tickSize),r=new c.BufferGeometry;r.setAttribute("position",new c.BufferAttribute(new Float32Array(s),3));const o=new c.Mesh(r,this._getMeshMaterial(e.style));o.layers.set(1),o.userData.isMeshArrow=!0,i.add(o)}}return i}_updatePreview(){const e=this.machineState;if("placingElbow"!==e.kind&&"placingExtension"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle),i="placingElbow"===e.kind?sl("placingElbow",e.arrowTip,null,e.cursor,t):sl("placingExtension",e.arrowTip,e.elbow,e.cursor,t);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 e=new c.BufferGeometry;e.setAttribute("position",new c.BufferAttribute(new Float32Array(i),3)),this._previewObject=new c.LineSegments(e,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 e=this._previewObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}if(t.meshTick){const i="placingElbow"===e.kind?e.cursor:e.elbow,n=i?(new c.Vector3).subVectors(e.arrowTip,i):null;if(n&&n.lengthSq()>1e-10){n.normalize();const i=t.meshTick(e.arrowTip,n,t.tickSize);if(this._previewMeshObject){const e=this._previewMeshObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}else{const e=new c.BufferGeometry;e.setAttribute("position",new c.BufferAttribute(new Float32Array(i),3)),this._previewMeshObject=new c.Mesh(e,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 ol extends Oa{enabled=!0;_ownsChildGeometry=!1;definitions=new l.DataMap;constructor(e){super(e),this.styles.set("default",{color:0,textOffset:0,fontSize:0})}pickHandle(e,t,i){return null}pick(e,t=.05){const i=new c.Raycaster;i.ray.copy(e),i.params.Line={threshold:t},i.params.LineSegments={threshold:t};let n=null,s=1/0;for(const e of this._knownDrawings)for(const[t,r]of e.annotations){if(r.system!==this)continue;const e=r.three;e.updateWorldMatrix(!0,!0),e.traverse(r=>{if(r===e)return;if(!(r instanceof c.LineSegments))return;const o=[];r.raycast(i,o),o.length>0&&o[0].distance<s&&(s=o[0].distance,n=t)})}return n}define(e,t){this.definitions.set(e,t)}_buildGroup(e,t){const i=this.definitions.get(e.blockName);if(!i)throw new Error(`BlockAnnotations: block "${e.blockName}" is not defined.`);const n=new c.Group;if(i.lines){const t=new c.LineSegments(i.lines,this._getMaterial(e.style));t.layers.set(1),t.userData.isDimension=!0,n.add(t)}if(i.mesh){const t=new c.Mesh(i.mesh,this._getMeshMaterial(e.style));t.layers.set(1),t.userData.isBlockMesh=!0,n.add(t)}return n}_onAfterPersist(e,t){t.position.set(e.position.x,0,e.position.z),t.rotation.set(0,e.rotation,0),t.scale.setScalar(e.scale)}_onDispose(){for(const e of this.definitions.values())e.lines?.dispose(),e.mesh?.dispose();this.definitions.clear()}}function al(e,t){const{position:i,direction:n}=e,{length:s}=t,r=new c.Vector3(i.x+n.x*s,0,i.z+n.z*s),o=new c.Vector3(n.x,0,n.z),a=t.lineTick(r,o,t.tickSize),l=[i.x,0,i.z,r.x,0,r.z];return new Float32Array([...l,...a])}function ll(e,t){return new c.Vector3(e.position.x+e.direction.x*t,0,e.position.z+e.direction.z*t)}function cl(e,t){switch(t){case"percentage":return`${(100*e).toFixed(2)} %`;case"ratio":return 0===e?"1:∞":`1:${(1/e).toFixed(2)}`;case"degrees":return`${(180*Math.atan(e)/Math.PI).toFixed(2)}°`}}class hl extends Oa{enabled=!0;constructor(e){super(e),this.styles.set("default",{lineTick:Aa,meshTick:Ta,tickSize:.4,length:3,color:0,textOffset:.1,fontSize:.45,format:"percentage"})}pickHandle(e,t,i){return null}_buildGroup(e,t){const i=new c.Group,n=al(e,t),s=new c.BufferGeometry;s.setAttribute("position",new c.BufferAttribute(n,3));const r=new c.LineSegments(s,this._getMaterial(e.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),t.meshTick){const n=ll(e,t.length),s=t.meshTick(n,e.direction,t.tickSize),r=new c.BufferGeometry;r.setAttribute("position",new c.BufferAttribute(new Float32Array(s),3));const o=new c.Mesh(r,this._getMeshMaterial(e.style));o.layers.set(1),o.userData.isDimension=!0,i.add(o)}return i}}function ul(e,t){const i=t.x-e.x,n=t.z-e.z,s=Math.sqrt(i*i+n*n);if(0===s)return e.clone();const r=Math.atan2(n,i),o=Math.round(r/(Math.PI/4))*(Math.PI/4);return new c.Vector3(e.x+Math.cos(o)*s,0,e.z+Math.sin(o)*s)}function dl(e,t){switch(e.kind){case"awaitingCenter":return"CLICK"===t.type?{kind:"awaitingRadius",center:t.point.clone(),cursor:null}:e;case"awaitingRadius":if("MOUSE_MOVE"===t.type)return{...e,cursor:t.point.clone()};if("CLICK"===t.type){const i=Math.max(.1,Math.abs(t.point.x-e.center.x)),n=Math.max(.1,Math.abs(t.point.z-e.center.z));return{kind:"awaitingElbow",center:e.center,halfW:i,halfH:n,cursor:null}}return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"awaitingElbow":return"MOUSE_MOVE"===t.type?{...e,cursor:t.point.clone()}:"CLICK"===t.type?{kind:"awaitingExtension",center:e.center,halfW:e.halfW,halfH:e.halfH,elbow:t.point.clone(),cursor:null}:"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"awaitingExtension":return"MOUSE_MOVE"===t.type?{...e,cursor:ul(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",center:e.center,halfW:e.halfW,halfH:e.halfH,elbow:e.elbow,extensionEnd:ul(e.elbow,t.point)}:"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"enteringText":if("SUBMIT_TEXT"===t.type&&t.text.trim().length>0){return{kind:"committed",annotation:{uuid:c.MathUtils.generateUUID(),center:e.center.clone(),halfW:e.halfW,halfH:e.halfH,elbow:e.elbow.clone(),extensionEnd:e.extensionEnd.clone(),text:t.text.trim(),style:""}}}return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e}}function pl(e,t){const i=[];i.push(...t.enclosure.buildGeometry(e.center,e.halfW,e.halfH));const n=(new c.Vector3).subVectors(e.elbow,e.center),s=n.lengthSq()>1e-10?n.clone().normalize():new c.Vector3(1,0,0),r=t.enclosure.getAttachmentPoint(e.center,e.halfW,e.halfH,s);if(i.push(r.x,r.y,r.z,e.elbow.x,e.elbow.y,e.elbow.z,e.elbow.x,e.elbow.y,e.elbow.z,e.extensionEnd.x,e.extensionEnd.y,e.extensionEnd.z),t.lineTick){const n=(new c.Vector3).subVectors(e.extensionEnd,e.elbow);n.lengthSq()>1e-10&&i.push(...t.lineTick(e.extensionEnd,n.normalize(),t.tickSize))}return i}function fl(e,t,i,n,s,r,o){const a="awaitingRadius"===e?r?Math.max(.05,Math.abs(r.x-t.x)):0:i,l="awaitingRadius"===e?r?Math.max(.05,Math.abs(r.z-t.z)):0:n;if(a<1e-10||l<1e-10)return[];const h=[];if(h.push(...o.enclosure.buildGeometry(t,a,l)),"awaitingRadius"===e)return h;const u="awaitingElbow"===e?r:s;if(!u)return h;const d=(new c.Vector3).subVectors(u,t),p=d.lengthSq()>1e-10?d.clone().normalize():new c.Vector3(1,0,0),f=o.enclosure.getAttachmentPoint(t,a,l,p);return"awaitingElbow"===e?(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 ml={buildGeometry(e,t,i){const n=.25*Math.min(t,i),s=new c.Vector3(e.x-t,0,e.z-i),r=new c.Vector3(e.x+t,0,e.z-i),o=new c.Vector3(e.x+t,0,e.z+i),a=new c.Vector3(e.x-t,0,e.z+i),l=[[s,r,new c.Vector3(0,0,-1)],[r,o,new c.Vector3(1,0,0)],[o,a,new c.Vector3(0,0,1)],[a,s,new c.Vector3(-1,0,0)]],h=[];for(const[e,t,i]of l){const s=e.distanceTo(t),r=Math.max(1,Math.round(s/(2*n))),o=s/r,a=o/2,l=(new c.Vector3).subVectors(t,e).normalize();for(let t=0;t<r;t++){const n=e.clone().addScaledVector(l,(t+.5)*o),s=e.clone().addScaledVector(l,t*o),r=(new c.Vector3).subVectors(s,n);let u=s.clone();for(let e=1;e<=8;e++){const t=e/8*Math.PI,s=n.x+r.x*Math.cos(t)+i.x*a*Math.sin(t),o=n.z+r.z*Math.cos(t)+i.z*a*Math.sin(t),l=new c.Vector3(s,0,o);h.push(u.x,0,u.z,l.x,0,l.z),u=l}}}return h},getAttachmentPoint(e,t,i,n){const s=Math.abs(n.x)>1e-10?t/Math.abs(n.x):1/0,r=Math.abs(n.z)>1e-10?i/Math.abs(n.z):1/0,o=Math.min(s,r);return new c.Vector3(e.x+n.x*o,0,e.z+n.z*o)}},gl={buildGeometry(e,t,i){const n=new c.Vector3(e.x-t,0,e.z-i),s=new c.Vector3(e.x+t,0,e.z-i),r=new c.Vector3(e.x+t,0,e.z+i),o=new c.Vector3(e.x-t,0,e.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,o.x,0,o.z,o.x,0,o.z,n.x,0,n.z]},getAttachmentPoint(e,t,i,n){const s=Math.abs(n.x)>1e-10?t/Math.abs(n.x):1/0,r=Math.abs(n.z)>1e-10?i/Math.abs(n.z):1/0,o=Math.min(s,r);return new c.Vector3(e.x+n.x*o,0,e.z+n.z*o)}},wl={buildGeometry(e,t,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(e.x+Math.cos(r)*t,0,e.z+Math.sin(r)*i,e.x+Math.cos(o)*t,0,e.z+Math.sin(o)*i)}return n},getAttachmentPoint(e,t,i,n){const s=n.x/t,r=n.z/i,o=Math.sqrt(s*s+r*r),a=o>1e-10?1/o:t;return new c.Vector3(e.x+n.x*a,0,e.z+n.z*a)}};class yl extends Oa{enabled=!0;machineState={kind:"awaitingCenter"};onMachineStateChanged=new d;constructor(e){super(e),this.styles.set("default",{enclosure:ml,lineTick:Sa,tickSize:.4,color:22015,textOffset:.1,fontSize:.45})}pickHandle(e,t,i){return null}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const i=dl(this.machineState,e);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 e=this._persist(this._previewDrawing,i.annotation);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(e,t){const i=new c.Group,n=pl(e,t),s=new c.BufferGeometry;s.setAttribute("position",new c.BufferAttribute(new Float32Array(n),3));const r=new c.LineSegments(s,this._getMaterial(e.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),t.meshTick){const n=(new c.Vector3).subVectors(e.extensionEnd,e.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=t.meshTick(e.extensionEnd,n,t.tickSize),r=new c.BufferGeometry;r.setAttribute("position",new c.BufferAttribute(new Float32Array(s),3));const o=new c.Mesh(r,this._getMeshMaterial(e.style));o.layers.set(1),o.userData.isMeshArrow=!0,i.add(o)}}return i}_updatePreview(){const e=this.machineState;if("awaitingRadius"!==e.kind&&"awaitingElbow"!==e.kind&&"awaitingExtension"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return;const t=this._resolveStyle(this.activeStyle),i=(()=>{switch(e.kind){case"awaitingRadius":return fl("awaitingRadius",e.center,0,0,null,e.cursor,t);case"awaitingElbow":return fl("awaitingElbow",e.center,e.halfW,e.halfH,null,e.cursor,t);case"awaitingExtension":return fl("awaitingExtension",e.center,e.halfW,e.halfH,e.elbow,e.cursor,t)}})();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 e=new c.BufferGeometry;e.setAttribute("position",new c.BufferAttribute(new Float32Array(i),3)),this._previewObject=new c.LineSegments(e,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 e=this._previewObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingCenter"},this._clearPreview(),this._previewDrawing=null,this.onMachineStateChanged.trigger(this.machineState)}}class _l extends f{static uuid="5c7d3b9a-4e8f-4a2b-9c1d-0e3f2a5b7c8d";enabled=!0;list=new l.DataMap;systems=new l.DataMap;onDisposed=new d;constructor(e){super(e),e.add(_l.uuid,this),this.list.onBeforeDelete.add(({value:e})=>e.dispose()),this.systems.onBeforeDelete.add(({value:e})=>e.dispose())}use(e){if(this.systems.has(e))return this.systems.get(e);const t=new e(this.components);return this.systems.set(e,t),t}create(e){const t=new Ba(this.components);t.world=e,e.scene.three.add(t.three),e.onDisposed.add(()=>this.list.delete(t.uuid));const i=e.camera;return i.three.layers.enable(1),i instanceof Lo&&(i.threePersp.layers.enable(1),i.threeOrtho.layers.enable(1)),this.list.set(t.uuid,t),t}dispose(){this.list.clear(),this.systems.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}}const bl=[[16711680,1],[16776960,2],[65280,3],[65535,4],[255,5],[16711935,6],[16777215,7],[0,7]];function vl(e){const t=e>>16&255,i=e>>8&255,n=255&e;let s=7,r=1/0;for(const[e,o]of bl){const a=(t-(e>>16&255))**2+(i-(e>>8&255))**2+(n-(255&e))**2;a<r&&(r=a,s=o)}return s}const xl="\0HANDSEED\0";class Cl{_lines=[];_handleCounter=1;p(e,t){return this._lines.push(String(e),String(t)),this}n(e,t,i=6){return this._lines.push(String(e),t.toFixed(i)),this}handle(){return(this._handleCounter++).toString(16).toUpperCase()}entityHeader(e,t,i){return this._lines.push("0",e,"5",this.handle(),"100","AcDbEntity","8",t,"62",String(i)),this}symbolTable(e,t){return this._lines.push("0","TABLE","2",e,"5",this.handle(),"100","AcDbSymbolTable","70",String(t)),this}symbolRecord(e,t){return this._lines.push("0",e,"5",this.handle(),"100","AcDbSymbolTableRecord","100",t),this}writeHandSeed(){return this._lines.push("9","$HANDSEED","5",xl),this}build(){return(this._lines.join("\n")+"\n").replace(xl,this._handleCounter.toString(16).toUpperCase())}}class Sl{constructor(e){this._components=e}_components;precision=2;config={trueColor:!1};_viewport=null;_paperSlot=null;_annotationLayers=new Map;_systemExporters=new Map;registerSystemExporter(e,t){this._systemExporters.set(e,t)}export(e,t){const i=!!t,n=new Cl,s=new Map;for(const t of e)for(const e of t.drawing.layers.values())s.has(e.name)||s.set(e.name,e);const r=[...s.values()],o=this._components.get(_l).systems.get(ol),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&&t&&this._writePaperBorders(n,t);for(const s of e){s.drawing.three.traverse(e=>{e.userData.isDimension&&e.userData.annotationUuid&&this._annotationLayers.set(e.userData.annotationUuid,e.userData.layer??"0")});for(const e of s.viewports){if(this._viewport=e.viewport??null,i&&e.viewport){const i=e.viewport,n=t.heightMm-2*t.margin;this._paperSlot={x:e.x??0,y:n-(e.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(e,t){e.p(0,"SECTION").p(2,"HEADER"),e.p(9,"$ACADVER").p(1,this.config.trueColor?"AC1018":"AC1015"),e.p(9,"$DWGCODEPAGE").p(3,"ANSI_1252"),e.p(9,"$INSUNITS").p(70,t?4:6),e.writeHandSeed(),e.p(0,"ENDSEC")}_writeTables(e,t,i){e.p(0,"SECTION").p(2,"TABLES"),e.symbolTable("VPORT",0).p(0,"ENDTAB"),e.symbolTable("LTYPE",1),e.symbolRecord("LTYPE","AcDbLinetypeTableRecord").p(2,"CONTINUOUS").p(70,0).p(3,"Solid line").p(72,65).p(73,0).n(40,0),e.p(0,"ENDTAB"),e.symbolTable("LAYER",t.length);for(const i of t){const t=vl(i.material.color.getHex());e.symbolRecord("LAYER","AcDbLayerTableRecord").p(2,i.name).p(70,0).p(62,t).p(6,"CONTINUOUS")}e.p(0,"ENDTAB"),e.symbolTable("STYLE",1),e.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,""),e.p(0,"ENDTAB"),e.symbolTable("VIEW",0).p(0,"ENDTAB"),e.symbolTable("UCS",0).p(0,"ENDTAB"),e.symbolTable("APPID",1),e.symbolRecord("APPID","AcDbRegAppTableRecord").p(2,"ACAD").p(70,0),e.p(0,"ENDTAB"),e.symbolTable("DIMSTYLE",0).p(0,"ENDTAB");const n=["*Model_Space","*Paper_Space",...i];e.symbolTable("BLOCK_RECORD",n.length);for(const t of n)e.symbolRecord("BLOCK_RECORD","AcDbBlockTableRecord").p(2,t);e.p(0,"ENDTAB"),e.p(0,"ENDSEC")}_writeBlocks(e,t){if(e.p(0,"SECTION").p(2,"BLOCKS"),this._writeBlock(e,"*Model_Space",null),this._writeBlock(e,"*Paper_Space",null),t)for(const[i,n]of t.definitions)this._writeBlock(e,i,n.lines??null);e.p(0,"ENDSEC")}_writeBlock(e,t,i){if(e.p(0,"BLOCK").p(5,e.handle()).p(100,"AcDbEntity").p(8,"0").p(100,"AcDbBlockBegin").p(2,t).p(70,0).n(10,0).n(20,0).n(30,0).p(3,t).p(1,""),i){const t=this._viewport,n=this._paperSlot;this._viewport=null,this._paperSlot=null,this._writeGeoAsLines(e,i,"0"),this._viewport=t,this._paperSlot=n}e.p(0,"ENDBLK").p(5,e.handle()).p(100,"AcDbEntity").p(8,"0").p(100,"AcDbBlockEnd")}_writeViewportBorder(e){if(!this._viewport)return;const t=this._viewport,i=this._tx(t.left),n=this._tx(t.right),s=this._ty(-t.bottom),r=this._ty(-t.top);this._writeRawLine(e,i,s,n,s,"0",7),this._writeRawLine(e,n,s,n,r,"0",7),this._writeRawLine(e,n,r,i,r,"0",7),this._writeRawLine(e,i,r,i,s,"0",7)}_writePaperBorders(e,t){const{margin:i,widthMm:n,heightMm:s}=t,r=n-2*i,o=s-2*i;this._writeRawLine(e,0,0,r,0,"0",7),this._writeRawLine(e,r,0,r,o,"0",7),this._writeRawLine(e,r,o,0,o,"0",7),this._writeRawLine(e,0,o,0,0,"0",7),this._writeRawLine(e,-i,-i,r+i,-i,"0",7),this._writeRawLine(e,r+i,-i,r+i,o+i,"0",7),this._writeRawLine(e,r+i,o+i,-i,o+i,"0",7),this._writeRawLine(e,-i,o+i,-i,-i,"0",7)}_writeObjects(e){e.p(0,"SECTION").p(2,"OBJECTS"),e.p(0,"DICTIONARY").p(5,e.handle()).p(330,0).p(100,"AcDbDictionary").p(281,1),e.p(0,"ENDSEC")}_writeRawLines(e,t){t.three.traverse(t=>{if(!(t instanceof c.LineSegments))return;if(t.userData.isDimension)return;if(t.parent?.userData.blockUuid)return;if(!t.visible)return;const i=t.userData.layer??"0",n=t.material.color.getHex();this._writeGeoAsLines(e,t.geometry,i,vl(n),n)})}_writeLinearAnnotations(e,t){const i=this._components.get(_l).systems.get(ja);if(i)for(const[,n]of t.annotations.getBySystem(i)){const s=i.styles.get(n.style)??i.styles.get("default"),r=vl(s.color),o=this._annotationLayers.get(n.uuid)??"0";if(!1===t.layers.get(o)?.visible)continue;const a=Ra(n,s);if(!this._fullyInViewport(this._bboxFromPositions(a)))continue;if(this._writePairsAsLines(e,a,o,r,s.color),s.meshTick)for(const{tip:t,dir:i}of Fa(n))this._writeMeshTriangles(e,s.meshTick(t,i,s.tickSize),o,r,s.color);const l=(new c.Vector3).subVectors(n.pointB,n.pointA),h=new c.Vector3(-l.z,0,l.x).normalize(),u=n.offset>=0?1:-1,d=n.pointA.clone().addScaledVector(h,n.offset),p=n.pointB.clone().addScaledVector(h,n.offset),f=d.clone().add(p).multiplyScalar(.5).addScaledVector(h,(s.textOffset+.5*s.fontSize)*u),m=s.unit??{factor:1,suffix:"m"},g=`${(n.pointA.distanceTo(n.pointB)*m.factor).toFixed(this.precision)} ${m.suffix}`;this._writeText(e,g,f.x,f.z,s.fontSize,o,r,this._textAngle(l.x,l.z),1,2,s.color)}}_writeAngleAnnotations(e,t){const i=this._components.get(_l).systems.get(Ja);if(i)for(const[,n]of t.annotations.getBySystem(i)){const s=i.styles.get(n.style)??i.styles.get("default"),r=vl(s.color),o=this._annotationLayers.get(n.uuid)??"0";if(!1===t.layers.get(o)?.visible)continue;const a=Ka(n,s);if(!this._fullyInViewport(this._bboxFromPositions(a)))continue;if(this._writePairsAsLines(e,a,o,r,s.color),s.meshTick)for(const{tip:t,dir:i}of qa(n))this._writeMeshTriangles(e,s.meshTick(t,i,s.tickSize),o,r,s.color);const l=Ya(n),h=n.arcRadius+s.textOffset,u=n.vertex.x+Math.cos(l)*h,d=n.vertex.z+Math.sin(l)*h,p=c.MathUtils.radToDeg(Za(n));this._writeText(e,`${p.toFixed(this.precision)}°`,u,d,s.fontSize,o,r,0,1,0,s.color)}}_writeLeaderAnnotations(e,t){const i=this._components.get(_l).systems.get(rl);if(i)for(const[,n]of t.annotations.getBySystem(i)){const s=i.styles.get(n.style)??i.styles.get("default"),r=vl(s.color),o=this._annotationLayers.get(n.uuid)??"0";if(!1===t.layers.get(o)?.visible)continue;const a=nl(n,s);if(!this._fullyInViewport(this._bboxFromPositions(a)))continue;if(this._writePairsAsLines(e,a,o,r,s.color),s.meshTick){const t=(new c.Vector3).subVectors(n.arrowTip,n.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,s.meshTick(n.arrowTip,t.normalize(),s.tickSize),o,r,s.color)}const l=(new c.Vector3).subVectors(n.extensionEnd,n.elbow).setY(0).normalize(),h=l.x<-.1?2:l.x>.1?0:1,u=1===h?.5*s.fontSize:0,d=n.extensionEnd.clone().addScaledVector(l,s.textOffset+u);this._writeText(e,n.text,d.x,d.z,s.fontSize,o,r,0,h,2,s.color)}}_writeSlopeAnnotations(e,t){const i=this._components.get(_l).systems.get(hl);if(i)for(const[,n]of t.annotations.getBySystem(i)){const s=i.styles.get(n.style)??i.styles.get("default"),r=vl(s.color),o=this._annotationLayers.get(n.uuid)??"0";if(!1===t.layers.get(o)?.visible)continue;const a=al(n,s);if(!this._fullyInViewport(this._bboxFromPositions(a)))continue;if(this._writePairsAsLines(e,a,o,r,s.color),s.meshTick){const t=ll(n,s.length);this._writeMeshTriangles(e,s.meshTick(t,n.direction,s.tickSize),o,r,s.color)}const l=new c.Vector3(n.position.x+n.direction.x*s.length,0,n.position.z+n.direction.z*s.length),h=n.position.clone().add(l).multiplyScalar(.5).addScaledVector(new c.Vector3(-n.direction.z,0,n.direction.x),s.textOffset+s.fontSize);this._writeText(e,cl(n.slope,s.format),h.x,h.z,s.fontSize,o,r,this._textAngle(n.direction.x,n.direction.z),1,0,s.color)}}_writeCalloutAnnotations(e,t){const i=this._components.get(_l).systems.get(yl);if(i)for(const[,n]of t.annotations.getBySystem(i)){const s=i.styles.get(n.style)??i.styles.get("default"),r=vl(s.color),o=this._annotationLayers.get(n.uuid)??"0";if(!1===t.layers.get(o)?.visible)continue;const a=pl(n,s);if(!this._fullyInViewport(this._bboxFromPositions(a)))continue;if(this._writePairsAsLines(e,a,o,r,s.color),s.meshTick){const t=(new c.Vector3).subVectors(n.extensionEnd,n.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,s.meshTick(n.extensionEnd,t.normalize(),s.tickSize),o,r,s.color)}const l=(new c.Vector3).subVectors(n.extensionEnd,n.elbow).setY(0).normalize(),h=l.x<-.1?2:l.x>.1?0:1,u=1===h?.5*s.fontSize:0,d=n.extensionEnd.clone().addScaledVector(l,s.textOffset+u);this._writeText(e,n.text,d.x,d.z,s.fontSize,o,r,0,h,2,s.color)}}_writeBlockInsertions(e,t){const i=this._components.get(_l).systems.get(ol);if(i)for(const[,n]of t.annotations.getBySystem(i)){if(!this._inViewport(n.position.x,n.position.z))continue;const t=i.styles.get(n.style)??i.styles.get("default"),s=vl(t.color),r=-c.MathUtils.radToDeg(n.rotation),o=n.scale*this._scale();e.entityHeader("INSERT","0",s),this._emitTrueColor(e,t.color),e.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,o).n(42,o).n(43,o).n(50,r)}}_writeGeoAsLines(e,t,i,n=7,s){const r=t.attributes.position;if(r)for(let t=0;t+1<r.count;t+=2){const o=this._clipSegment(new c.Vector3(r.getX(t),0,r.getZ(t)),new c.Vector3(r.getX(t+1),0,r.getZ(t+1)));o&&this._writeLine(e,o.start.x,o.start.z,o.end.x,o.end.z,i,n,s)}}_writePairsAsLines(e,t,i,n=7,s){for(let r=0;r+5<t.length;r+=6){const o=this._clipSegment(new c.Vector3(t[r],0,t[r+2]),new c.Vector3(t[r+3],0,t[r+5]));o&&this._writeLine(e,o.start.x,o.start.z,o.end.x,o.end.z,i,n,s)}}_emitTrueColor(e,t){this.config.trueColor&&void 0!==t&&e.p(420,t)}_writeLine(e,t,i,n,s,r,o,a){e.entityHeader("LINE",r,o),this._emitTrueColor(e,a),e.p(100,"AcDbLine").n(10,this._tx(t)).n(20,this._ty(i)).n(30,0).n(11,this._tx(n)).n(21,this._ty(s)).n(31,0)}_writeRawLine(e,t,i,n,s,r,o){e.entityHeader("LINE",r,o).p(100,"AcDbLine").n(10,t).n(20,i).n(30,0).n(11,n).n(21,s).n(31,0)}_writeSolid(e,t,i,n,s,r,o,a,l,c){e.entityHeader("SOLID",a,l),this._emitTrueColor(e,c),e.p(100,"AcDbTrace").n(10,this._tx(t)).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(e,t,i,n,s){for(let r=0;r+8<t.length;r+=9)this._writeSolid(e,t[r],t[r+2],t[r+3],t[r+5],t[r+6],t[r+8],i,n,s)}_writeText(e,t,i,n,s,r,o,a=0,l=0,c=0,h){const u=this._tx(i),d=this._ty(n);e.entityHeader("TEXT",r,o),this._emitTrueColor(e,h),e.p(100,"AcDbText").n(10,u).n(20,d).n(30,0).n(40,s*this._scale()).n(50,a).p(1,t),0===l&&0===c||(0!==l&&e.p(72,l),0!==c&&e.p(73,c),e.n(11,u).n(21,d).n(31,0))}_tx(e){return this._paperSlot?this._paperSlot.x+(e-this._paperSlot.vpLeft)*this._paperSlot.mmPerUnit:this._viewport?e-this._viewport.left:e}_ty(e){return this._paperSlot?this._paperSlot.y-(e+this._paperSlot.vpTop)*this._paperSlot.mmPerUnit:this._viewport?-e-this._viewport.bottom:-e}_scale(){return this._paperSlot?this._paperSlot.mmPerUnit:1}_clipSegment(e,t){return this._viewport?this._viewport.clipLine(new c.Line3(e,t)):new c.Line3(e,t)}_inViewport(e,t){return!this._viewport||this._viewport.bbox.containsPoint(new c.Vector3(e,0,t))}_bboxFromPositions(e){const t=new c.Box3;for(let i=0;i+2<e.length;i+=3)t.expandByPoint(new c.Vector3(e[i],0,e[i+2]));return t}_fullyInViewport(e){return!this._viewport||this._viewport.bbox.containsBox(e)}_textAngle(e,t){let i=Math.atan2(-t,e);return(i>Math.PI/2||i<=-Math.PI/2)&&(i+=Math.PI),c.MathUtils.radToDeg(i)}_writeCustomSystems(e,t){if(0===this._systemExporters.size)return;const i=this._makeContext(e);for(const[e,t]of this._systemExporters){const n=this._components.get(_l).systems.get(e);n&&t(n,i)}}_makeContext(e){return{writeLine:(t,i,n,s,r="0",o=7)=>{this._writeLine(e,t,i,n,s,r,o)},writePairs:(t,i="0",n=7)=>{this._writePairsAsLines(e,t,i,n)},writeMeshTriangles:(t,i="0",n=7)=>{this._writeMeshTriangles(e,t,i,n)},writeText:(t,i,n,s,r={})=>{this._writeText(e,t,i,n,s,r.layer??"0",r.aciColor??7,r.rotDeg??0,r.hAlign??0)},hexToAci:vl,textAngle:(e,t)=>this._textAngle(e,t)}}}class Al extends f{static uuid="e9a2c3d4-5f67-4b89-a012-1c3d5e7f9b2a";enabled=!0;exporter=new Sl(this.components);constructor(e){super(e),e.add(Al.uuid,this)}}exports.AngleAnnotations=Ja,exports.AnnotationSystem=Oa,exports.ArrowTick=(e,t,i)=>{const n=new c.Vector3(-t.z,0,t.x),s=e.x-t.x*i+n.x*i*.4,r=e.z-t.z*i+n.z*i*.4,o=e.x-t.x*i-n.x*i*.4,a=e.z-t.z*i-n.z*i*.4;return[e.x,e.y,e.z,s,e.y,r,e.x,e.y,e.z,o,e.y,a,s,e.y,r,o,e.y,a]},exports.AsyncEvent=class{enabled=!0;add(e){this.handlers.push(e)}remove(e){this.handlers=this.handlers.filter(t=>t!==e)}trigger=async e=>{if(!this.enabled)return;const t=this.handlers.slice(0);for(const i of t)await i(e)};reset(){this.handlers.length=0}handlers=[]},exports.BCFTopics=Zo,exports.BCFTopicsConfigManager=qo,exports.Base=p,exports.BaseCamera=g,exports.BaseRenderer=w,exports.BaseScene=_,exports.BaseWorldItem=m,exports.BlockAnnotations=ol,exports.BoundingBoxer=Br,exports.CalloutAnnotations=yl,exports.CircleEnclosure=wl,exports.Classifier=Lr,exports.Clipper=Ko,exports.CloudEnclosure=ml,exports.Comment=Wo,exports.Component=f,exports.Components=zo,exports.ConfigManager=pt,exports.Configurator=dt,exports.ControlsUtils=ut,exports.DataMap=ht,exports.DataSet=b,exports.DiagonalTick=Ca,exports.Disposer=y,exports.DotTick=(e,t,i)=>{const n=.4*i,s=[];for(let t=0;t<12;t++){const i=t/12*Math.PI*2,r=(t+1)/12*Math.PI*2;s.push(e.x+Math.cos(i)*n,e.y,e.z+Math.sin(i)*n,e.x+Math.cos(r)*n,e.y,e.z+Math.sin(r)*n)}return s},exports.DrawingAnnotations=Pa,exports.DrawingLayers=Ma,exports.DrawingSystem=Oa,exports.DrawingViewport=Ia,exports.DrawingViewportHelper=Ea,exports.DrawingViewports=Da,exports.DxfExporter=Sl,exports.DxfManager=Al,exports.EdgeProjector=Ir,exports.Event=d,exports.EventManager=class{list=new Set;add(e){for(const t of e)this.list.add(t)}remove(e){for(const t of e)this.list.delete(t)}set(e){for(const t of this.list)t.enabled=e}reset(){for(const e of this.list)e.reset()}},exports.FastModelPicker=Qr,exports.FastModelPickers=Jr,exports.FilledArrowTick=Ta,exports.FilledCircleTick=(e,t,i)=>{const n=.4*i,s=[];for(let t=0;t<16;t++){const i=t/16*Math.PI*2,r=(t+1)/16*Math.PI*2;s.push(e.x,e.y,e.z,e.x+Math.cos(i)*n,e.y,e.z+Math.sin(i)*n,e.x+Math.cos(r)*n,e.y,e.z+Math.sin(r)*n)}return s},exports.FilledSquareTick=(e,t,i)=>{const n=new c.Vector3(-t.z,0,t.x),s=.4*i,r=e.clone().addScaledVector(t,s).addScaledVector(n,s),o=e.clone().addScaledVector(t,s).addScaledVector(n,-s),a=e.clone().addScaledVector(t,-s).addScaledVector(n,-s),l=e.clone().addScaledVector(t,-s).addScaledVector(n,s);return[r.x,r.y,r.z,o.x,o.y,o.z,a.x,a.y,a.z,r.x,r.y,r.z,a.x,a.y,a.z,l.x,l.y,l.z]},exports.FinderQuery=Or,exports.FirstPersonMode=ko,exports.FragmentsManager=fs,exports.Grids=Do,exports.Hider=kr,exports.IDSAttribute=aa,exports.IDSClassification=la,exports.IDSEntity=ca,exports.IDSFacet=ra,exports.IDSMaterial=ua,exports.IDSPartOf=da,exports.IDSProperty=ha,exports.IDSSpecification=pa,exports.IDSSpecifications=va,exports.IfcFragmentSettings=Dr,exports.IfcLoader=zr,exports.ItemsFinder=Vr,exports.LeaderAnnotations=rl,exports.LinearAnnotations=ja,exports.MeasurementUtils=xa,exports.ModelIdMapUtils=ct,exports.Mouse=ft,exports.NoTick=Aa,exports.OpenArrowTick=Sa,exports.OrbitMode=Bo,exports.OrthoPerspectiveCamera=Lo,exports.PlanMode=Oo,exports.ProjectionManager=Vo,exports.Raycasters=yo,exports.RectEnclosure=gl,exports.RendererMode=Ao,exports.ShadowedScene=class extends Co{_distanceRenderer;autoBias=!0;_defaultShadowConfig={cascade:1,resolution:512};_lightsWithShadow=new Map;_isComputingShadows=!1;_shadowsEnabled=!0;_bias=0;get bias(){return this._bias}set bias(e){this._bias=e;for(const[,t]of this._lightsWithShadow){const i=this.directionalLights.get(t);i&&(i.shadow.bias=e)}}get shadowsEnabled(){return this._shadowsEnabled}set shadowsEnabled(e){this._shadowsEnabled=e;for(const[,t]of this.directionalLights)t.castShadow=e}get distanceRenderer(){if(!this._distanceRenderer)throw new Error("You must set up this component before accessing the distance renderer!");return this._distanceRenderer}setup(e){super.setup(e);const t={...this._defaultConfig,...this._defaultShadowConfig,...e};if(t.cascade<=0)throw new Error("Config.shadows.cascade must be a natural number greater than 0!");if(t.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[,e]of this.directionalLights)e.target.removeFromParent(),e.removeFromParent(),e.dispose();this.directionalLights.clear(),this._distanceRenderer||(this._distanceRenderer=new sa(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let e=0;e<t.cascade;e++){const i=new c.DirectionalLight;i.intensity=this.config.directionalLight.intensity,i.color=this.config.directionalLight.color,i.position.copy(this.config.directionalLight.position),i.shadow.mapSize.width=t.resolution,i.shadow.mapSize.height=t.resolution,this.three.add(i,i.target),this.directionalLights.set(i.uuid,i),this._lightsWithShadow.set(e,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())}recomputeShadows=e=>{if(!this._shadowsEnabled)return;this.autoBias&&(this.bias=-.005);if(e*=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 t=this.currentWorld.camera.three;if(!(t instanceof c.PerspectiveCamera||t instanceof c.OrthographicCamera))throw new Error("Invalid camera type!");const i=new c.Vector3;t.getWorldDirection(i);let n=e;const s=new c.Vector3;s.copy(this.config.directionalLight.position),s.normalize();for(const[e,r]of this._lightsWithShadow){const o=this.directionalLights.get(r);if(!o)throw new Error("Light not found.");const a=new c.Vector3;a.copy(i);const l=e===this._lightsWithShadow.size-1,h=l?n/2:2*n/3;a.multiplyScalar(h),a.add(t.position);const u=n-h,d=new c.Vector3;d.copy(s),d.multiplyScalar(u),o.target.position.copy(a),o.position.copy(a),o.position.add(d),o.shadow.camera.right=u,o.shadow.camera.left=-u,o.shadow.camera.top=u,o.shadow.camera.bottom=-u,o.shadow.camera.far=2*u,o.shadow.camera.updateProjectionMatrix(),o.shadow.camera.updateMatrix(),l||(n/=3)}this._isComputingShadows=!1}},exports.SimpleCamera=Po,exports.SimpleGrid=Io,exports.SimpleGridConfigManager=Eo,exports.SimplePlane=Yo,exports.SimpleRaycaster=wo,exports.SimpleRenderer=class extends w{enabled=!0;container;three;mode=1;needsUpdate=!1;_canvas;_parameters;_resizeObserver=null;onContainerUpdated=new d;_resizing=!1;_logo=null;_showLogo=!0;get showLogo(){return this._showLogo}set showLogo(e){this._showLogo=e,this._logo&&(this._logo.style.display=e?"":"none")}get logo(){return this._logo}constructor(e,t,i){super(e),this.container=t,this._parameters=i,this.three=new c.WebGLRenderer({antialias:!0,alpha:!0,...i}),this.three.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.setupRenderer(),this.setupEvents(!0),this.resize(),this._canvas=this.three.domElement;const n=this.three.getContext(),{canvas:s}=n;s.addEventListener("webglcontextlost",this.onContextLost,!1),s.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 e=this.currentWorld.scene.three,t=this.currentWorld.camera.three;this.three.render(e,t),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 c.Vector2(this.three.domElement.clientWidth,this.three.domElement.clientHeight)}resize=e=>{if(this._resizing)return;this._resizing=!0,this.onContainerUpdated.trigger();const t=e?e.x:this.container.clientWidth,i=e?e.y:this.container.clientHeight;this.three.setSize(t,i),this.onResize.trigger(new c.Vector2(t,i)),this._resizing=!1};setupEvents(e){const t=this.three.domElement.parentElement;if(!t)throw new Error("This renderer needs to have an HTML container!");this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),window.removeEventListener("resize",this.resizeEvent),e&&(this._resizeObserver=new ResizeObserver(this.resizeEvent),this._resizeObserver.observe(t),window.addEventListener("resize",this.resizeEvent))}resizeEvent=()=>{this.resize()};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 e=document.createElement("div");e.setAttribute("data-thatopen-logo",""),e.innerHTML=So,e.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 t=e.firstElementChild;return t&&(t.setAttribute("width","100%"),t.setAttribute("height","100%")),e}(),this._logo.style.display=this._showLogo?"":"none",this.container.appendChild(this._logo)}onContextLost=e=>{e.preventDefault(),this.enabled=!1};onContextBack=()=>{this.three.setRenderTarget(null),this.three.dispose(),this.three=new c.WebGLRenderer({canvas:this._canvas,antialias:!0,alpha:!0,...this._parameters}),this.enabled=!0}},exports.SimpleScene=Co,exports.SimpleSceneConfigManager=xo,exports.SimpleWorld=_o,exports.SlopeAnnotations=hl,exports.SnapClass=eo,exports.SnapResolver=io,exports.SnapResolvers=go,exports.TechnicalDrawing=Ba,exports.TechnicalDrawingHelper=za,exports.TechnicalDrawings=_l,exports.Topic=Ho,exports.UUID=v,exports.Units={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"}},exports.VertexPicker=class extends f{onDisposed=new d;onVertexFound=new d;onVertexLost=new d;onEnabled=new d;components;workingPlane=null;_pickedPoint=null;_config;_enabled=!1;set enabled(e){this._enabled=e,e||(this._pickedPoint=null),this.onEnabled.trigger(e)}get enabled(){return this._enabled}set config(e){this._config={...this._config,...e}}get config(){return this._config}constructor(e,t){super(e),this.components=e,this.config={snapDistance:.25,showOnlyVertex:!1,...t},this.enabled=!1}dispose(){this.onVertexFound.reset(),this.onVertexLost.reset(),this.components=null,this.onDisposed.trigger(),this.onDisposed.reset()}async get(e){if(!this.enabled)return this._pickedPoint;const t=this.components.get(yo).get(e),i=await t.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}},exports.View=ta,exports.Viewpoint=Qo,exports.Viewpoints=ea,exports.Views=ia,exports.Worlds=Mo,exports.XML=lt,exports.angleDimensionMachine=Ga,exports.buildAnglePositions=Ka,exports.buildAnglePreviewPositions=Qa,exports.buildCalloutPositions=pl,exports.buildCalloutPreviewPositions=fl,exports.buildDimensionPositions=Ra,exports.buildDimensions=La,exports.buildLeaderPositions=nl,exports.buildLeaderPreviewPositions=sl,exports.buildPreviewPositions=Ua,exports.buildSlopePositions=al,exports.calloutAnnotationMachine=dl,exports.computeAlignmentMatrix=ka,exports.computeAngle=Za,exports.computeBisectorAngle=Ya,exports.computeOffset=Va,exports.extensionsImporter=Go,exports.formatSlope=cl,exports.getAngleTickEndpoints=qa,exports.getDimensionTickEndpoints=Fa,exports.getSlopeTip=ll,exports.leaderAnnotationMachine=tl,exports.linearDimensionMachine=Na,exports.setOrbitPoint=To;