@thatopen/components 3.4.1 → 3.4.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +3728 -843
- package/dist/index.d.ts +520 -91
- package/dist/index.min.cjs +2 -2
- package/dist/index.min.mjs +2 -2
- package/dist/index.mjs +3730 -845
- package/package.json +5 -5
package/dist/index.min.cjs
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
"use strict";var e=Object.defineProperty,t=(t,i,n)=>(((t,i,n)=>{i in t?e(t,i,{enumerable:!0,configurable:!0,writable:!0,value:n}):t[i]=n})(t,"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(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 h=c(i),d=c(n),u=c(s),p=c(o);class f{constructor(){t(this,"enabled",!0),t(this,"trigger",e=>{if(!this.enabled)return;const t=this.handlers.slice(0);for(const i of t)i(e)}),t(this,"handlers",[])}add(e){this.handlers.push(e)}remove(e){this.handlers=this.handlers.filter(t=>t!==e)}reset(){this.handlers.length=0}}class m{constructor(e){t(this,"isDisposeable",()=>"dispose"in this&&"onDisposed"in this),t(this,"isResizeable",()=>"resize"in this&&"getSize"in this),t(this,"isUpdateable",()=>"onAfterUpdate"in this&&"onBeforeUpdate"in this&&"update"in this),t(this,"isHideable",()=>"visible"in this),t(this,"isConfigurable",()=>"setup"in this&&"config"in this&&"onSetup"in this),t(this,"isSerializable",()=>"import"in this&&"export"in this),this.components=e}}class g extends m{}class w extends m{constructor(e){super(e),t(this,"worlds",new i.DataMap),t(this,"onWorldChanged",new f),t(this,"_currentWorld",null),this.onWorldChanged.add(({world:e,action:t})=>{"removed"===t&&this.worlds.delete(e.uuid)})}set currentWorld(e){this._currentWorld=e}get currentWorld(){return this._currentWorld}}class y extends w{constructor(){super(...arguments),t(this,"hasCameraControls",()=>"controls"in this)}}class _ extends w{constructor(){super(...arguments),t(this,"onAfterUpdate",new f),t(this,"onBeforeUpdate",new f),t(this,"onDisposed",new f),t(this,"onResize",new f),t(this,"onClippingPlanesUpdated",new f),t(this,"clippingPlanes",[])}updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(e,t,i){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)}}const b=class e extends g{constructor(i){super(i),t(this,"_disposedComponents",new Set),t(this,"enabled",!0),i.add(e.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(t,i){const n=t;n.geometry&&this.disposeGeometry(n.geometry),i&&n.material&&e.disposeMaterial(n),n.material=[],n.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()}};t(b,"uuid","76e9cd8e-ad8f-4753-9ef6-cbc60f7247fe");let v=b;class x extends w{constructor(e){super(e),t(this,"onDisposed",new f),t(this,"directionalLights",new Map),t(this,"ambientLights",new Map)}dispose(){const e=this.components.get(v);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 S extends Set{constructor(e){super(e),t(this,"onItemAdded",new f),t(this,"onItemDeleted",new f),t(this,"onCleared",new f),t(this,"guard",()=>!0)}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 f),this.onItemAdded.trigger(t))}return this}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()}}const C=class e{static create(){const t=4294967295*Math.random()|0,i=4294967295*Math.random()|0,n=4294967295*Math.random()|0,s=4294967295*Math.random()|0;return`${e._lut[255&t]+e._lut[t>>8&255]+e._lut[t>>16&255]+e._lut[t>>24&255]}-${e._lut[255&i]}${e._lut[i>>8&255]}-${e._lut[i>>16&15|64]}${e._lut[i>>24&255]}-${e._lut[63&n|128]}${e._lut[n>>8&255]}-${e._lut[n>>16&255]}${e._lut[n>>24&255]}${e._lut[255&s]}${e._lut[s>>8&255]}${e._lut[s>>16&255]}${e._lut[s>>24&255]}`.toLowerCase()}static validate(t){if(!e._pattern.test(t))throw new Error(`${t} 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.`)}};t(C,"_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}$/),t(C,"_lut",["00","01","02","03","04","05","06","07","08","09","0a","0b","0c","0d","0e","0f","10","11","12","13","14","15","16","17","18","19","1a","1b","1c","1d","1e","1f","20","21","22","23","24","25","26","27","28","29","2a","2b","2c","2d","2e","2f","30","31","32","33","34","35","36","37","38","39","3a","3b","3c","3d","3e","3f","40","41","42","43","44","45","46","47","48","49","4a","4b","4c","4d","4e","4f","50","51","52","53","54","55","56","57","58","59","5a","5b","5c","5d","5e","5f","60","61","62","63","64","65","66","67","68","69","6a","6b","6c","6d","6e","6f","70","71","72","73","74","75","76","77","78","79","7a","7b","7c","7d","7e","7f","80","81","82","83","84","85","86","87","88","89","8a","8b","8c","8d","8e","8f","90","91","92","93","94","95","96","97","98","99","9a","9b","9c","9d","9e","9f","a0","a1","a2","a3","a4","a5","a6","a7","a8","a9","aa","ab","ac","ad","ae","af","b0","b1","b2","b3","b4","b5","b6","b7","b8","b9","ba","bb","bc","bd","be","bf","c0","c1","c2","c3","c4","c5","c6","c7","c8","c9","ca","cb","cc","cd","ce","cf","d0","d1","d2","d3","d4","d5","d6","d7","d8","d9","da","db","dc","dd","de","df","e0","e1","e2","e3","e4","e5","e6","e7","e8","e9","ea","eb","ec","ed","ee","ef","f0","f1","f2","f3","f4","f5","f6","f7","f8","f9","fa","fb","fc","fd","fe","ff"]);let T=C;const A=":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",E=new RegExp("^"+("["+A+"]["+(A+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*")+"$");function M(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 P=function(e){const t=E.exec(e);return!(null==t)};const I={allowBooleanAttributes:!1,unpairedTags:[]};function z(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function D(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 R("InvalidXml","XML declaration allowed only at the start of the document.",$(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}continue}return t}function k(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 B='"',O="'";function V(e,t){let i="",n="",s=!1;for(;t<e.length;t++){if(e[t]===B||e[t]===O)""===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 L=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function N(e,t){const i=M(e,L),n={};for(let e=0;e<i.length;e++){if(0===i[e][1].length)return R("InvalidAttr","Attribute '"+i[e][2]+"' has no space in starting.",W(i[e]));if(void 0!==i[e][3]&&void 0===i[e][4])return R("InvalidAttr","Attribute '"+i[e][2]+"' is without value.",W(i[e]));if(void 0===i[e][3]&&!t.allowBooleanAttributes)return R("InvalidAttr","boolean attribute '"+i[e][2]+"' is not allowed.",W(i[e]));const s=i[e][2];if(!U(s))return R("InvalidAttr","Attribute '"+s+"' is an invalid name.",W(i[e]));if(n.hasOwnProperty(s))return R("InvalidAttr","Attribute '"+s+"' is repeated.",W(i[e]));n[s]=1}return!0}function F(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 R(e,t,i){return{err:{code:e,msg:t,line:i.line||i,col:i.col}}}function U(e){return P(e)}function j(e){return P(e)}function $(e,t){const i=e.substring(0,t).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function W(e){return e.startIndex+e[1].length}const G={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,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(e,t,i){return e},captureMetaData:!1};function H(e){return"boolean"==typeof e?{enabled:e,maxEntitySize:1e4,maxExpansionDepth:10,maxTotalExpansions:1e3,maxExpandedLength:1e5,allowedTags:null,tagFilter:null}:"object"==typeof e&&null!==e?{enabled:!1!==e.enabled,maxEntitySize:e.maxEntitySize??1e4,maxExpansionDepth:e.maxExpansionDepth??10,maxTotalExpansions:e.maxTotalExpansions??1e3,maxExpandedLength:e.maxExpandedLength??1e5,allowedTags:e.allowedTags??null,tagFilter:e.tagFilter??null}:H(!0)}const q=function(e){const t=Object.assign({},G,e);return t.processEntities=H(t.processEntities),t};let Z;Z="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class Y{constructor(e){this.tagname=e,this.child=[],this[":@"]={}}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][Z]={startIndex:t})}static getMetaDataSymbol(){return Z}}class X{constructor(e){this.suppressValidationErr=!e,this.options=e}readDocType(e,t){const i={};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 n=1,s=!1,r=!1,o="";for(;t<e.length;t++)if("<"!==e[t]||r)if(">"===e[t]){if(r?"-"===e[t-1]&&"-"===e[t-2]&&(r=!1,n--):n--,0===n)break}else"["===e[t]?s=!0:o+=e[t];else{if(s&&Q(e,"!ENTITY",t)){let n,s;if(t+=7,[n,s,t]=this.readEntityExp(e,t+1,this.suppressValidationErr),-1===s.indexOf("&")){const e=n.replace(/[.\-+*:]/g,"\\.");i[n]={regx:RegExp(`&${e};`,"g"),val:s}}}else if(s&&Q(e,"!ELEMENT",t)){t+=8;const{index:i}=this.readElementExp(e,t+1);t=i}else if(s&&Q(e,"!ATTLIST",t))t+=8;else if(s&&Q(e,"!NOTATION",t)){t+=9;const{index:i}=this.readNotationExp(e,t+1,this.suppressValidationErr);t=i}else{if(!Q(e,"!--",t))throw new Error("Invalid DOCTYPE");r=!0}n++,o=""}if(0!==n)throw new Error("Unclosed DOCTYPE")}return{entities:i,i:t}}readEntityExp(e,t){t=K(e,t);let i="";for(;t<e.length&&!/\s/.test(e[t])&&'"'!==e[t]&&"'"!==e[t];)i+=e[t],t++;if(J(i),t=K(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 n="";if([t,n]=this.readIdentifierVal(e,t,"entity"),!1!==this.options.enabled&&this.options.maxEntitySize&&n.length>this.options.maxEntitySize)throw new Error(`Entity "${i}" size (${n.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[i,n,--t]}readNotationExp(e,t){t=K(e,t);let i="";for(;t<e.length&&!/\s/.test(e[t]);)i+=e[t],t++;!this.suppressValidationErr&&J(i),t=K(e,t);const n=e.substring(t,t+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==n&&"PUBLIC"!==n)throw new Error(`Expected SYSTEM or PUBLIC, found "${n}"`);t+=n.length,t=K(e,t);let s=null,r=null;if("PUBLIC"===n)[t,s]=this.readIdentifierVal(e,t,"publicIdentifier"),'"'!==e[t=K(e,t)]&&"'"!==e[t]||([t,r]=this.readIdentifierVal(e,t,"systemIdentifier"));else if("SYSTEM"===n&&([t,r]=this.readIdentifierVal(e,t,"systemIdentifier"),!this.suppressValidationErr&&!r))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:i,publicIdentifier:s,systemIdentifier:r,index:--t}}readIdentifierVal(e,t,i){let n="";const s=e[t];if('"'!==s&&"'"!==s)throw new Error(`Expected quoted string, found "${s}"`);for(t++;t<e.length&&e[t]!==s;)n+=e[t],t++;if(e[t]!==s)throw new Error(`Unterminated ${i} value`);return[++t,n]}readElementExp(e,t){t=K(e,t);let i="";for(;t<e.length&&!/\s/.test(e[t]);)i+=e[t],t++;if(!this.suppressValidationErr&&!P(i))throw new Error(`Invalid element name: "${i}"`);let n="";if("E"===e[t=K(e,t)]&&Q(e,"MPTY",t))t+=4;else if("A"===e[t]&&Q(e,"NY",t))t+=2;else if("("===e[t]){for(t++;t<e.length&&")"!==e[t];)n+=e[t],t++;if(")"!==e[t])throw new Error("Unterminated content model")}else if(!this.suppressValidationErr)throw new Error(`Invalid Element Expression, found "${e[t]}"`);return{elementName:i,contentModel:n.trim(),index:t}}readAttlistExp(e,t){t=K(e,t);let i="";for(;t<e.length&&!/\s/.test(e[t]);)i+=e[t],t++;J(i),t=K(e,t);let n="";for(;t<e.length&&!/\s/.test(e[t]);)n+=e[t],t++;if(!J(n))throw new Error(`Invalid attribute name: "${n}"`);t=K(e,t);let s="";if("NOTATION"===e.substring(t,t+8).toUpperCase()){if(s="NOTATION","("!==e[t=K(e,t+=8)])throw new Error(`Expected '(', found "${e[t]}"`);t++;let i=[];for(;t<e.length&&")"!==e[t];){let n="";for(;t<e.length&&"|"!==e[t]&&")"!==e[t];)n+=e[t],t++;if(n=n.trim(),!J(n))throw new Error(`Invalid notation name: "${n}"`);i.push(n),"|"===e[t]&&(t++,t=K(e,t))}if(")"!==e[t])throw new Error("Unterminated list of notations");t++,s+=" ("+i.join("|")+")"}else{for(;t<e.length&&!/\s/.test(e[t]);)s+=e[t],t++;const i=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!i.includes(s.toUpperCase()))throw new Error(`Invalid attribute type: "${s}"`)}t=K(e,t);let r="";return"#REQUIRED"===e.substring(t,t+8).toUpperCase()?(r="#REQUIRED",t+=8):"#IMPLIED"===e.substring(t,t+7).toUpperCase()?(r="#IMPLIED",t+=7):[t,r]=this.readIdentifierVal(e,t,"ATTLIST"),{elementName:i,attributeName:n,attributeType:s,defaultValue:r,index:t}}}const K=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function Q(e,t,i){for(let n=0;n<t.length;n++)if(t[n]!==e[i+n+1])return!1;return!0}function J(e){if(P(e))return e;throw new Error(`Invalid entity name ${e}`)}const ee=/^[-+]?0x[a-fA-F0-9]+$/,te=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,ie={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function ne(e,t={}){if(t=Object.assign({},ie,t),!e||"string"!=typeof e)return e;let i=e.trim();if(void 0!==t.skipLike&&t.skipLike.test(i))return e;if("0"===e)return 0;if(t.hex&&ee.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(i.includes("e")||i.includes("E"))return function(e,t,i){if(!i.eNotation)return e;const n=t.match(se);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?i.leadingZeros&&!a?(t=(n[1]||"")+n[3],Number(t)):e:Number(t)}return e}(e,i,t);{const n=te.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}}const se=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function re(e){return"function"==typeof e?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}class oe{constructor(e){if(this.options=e,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(e,t)=>ve(t,10,"&#")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,t)=>ve(t,16,"&#x")}},this.addExternalEntities=ae,this.parseXml=ue,this.parseTextData=le,this.resolveNameSpace=ce,this.buildAttributesMap=de,this.isItStopNode=ge,this.replaceEntitiesValue=fe,this.readStopNodeData=_e,this.saveTextToParentTag=me,this.addChild=pe,this.ignoreAttributesFn=re(this.options.ignoreAttributes),this.entityExpansionCount=0,this.currentExpandedLength=0,this.options.stopNodes&&this.options.stopNodes.length>0){this.stopNodesExact=new Set,this.stopNodesWildcard=new Set;for(let e=0;e<this.options.stopNodes.length;e++){const t=this.options.stopNodes[e];"string"==typeof t&&(t.startsWith("*.")?this.stopNodesWildcard.add(t.substring(2)):this.stopNodesExact.add(t))}}}}function ae(e){const t=Object.keys(e);for(let i=0;i<t.length;i++){const n=t[i],s=n.replace(/[.\-+*:]/g,"\\.");this.lastEntities[n]={regex:new RegExp("&"+s+";","g"),val:e[n]}}}function le(e,t,i,n,s,r,o){if(void 0!==e&&(this.options.trimValues&&!n&&(e=e.trim()),e.length>0)){o||(e=this.replaceEntitiesValue(e,t,i));const n=this.options.tagValueProcessor(t,e,i,s,r);if(null==n)return e;if(typeof n!=typeof e||n!==e)return n;if(this.options.trimValues)return be(e,this.options.parseTagValue,this.options.numberParseOptions);return e.trim()===e?be(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function ce(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 he=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function de(e,t,i){if(!0!==this.options.ignoreAttributes&&"string"==typeof e){const n=M(e,he),s=n.length,r={};for(let e=0;e<s;e++){const s=this.resolveNameSpace(n[e][1]);if(this.ignoreAttributesFn(s,t))continue;let o=n[e][4],a=this.options.attributeNamePrefix+s;if(s.length)if(this.options.transformAttributeName&&(a=this.options.transformAttributeName(a)),"__proto__"===a&&(a="#__proto__"),void 0!==o){this.options.trimValues&&(o=o.trim()),o=this.replaceEntitiesValue(o,i,t);const e=this.options.attributeValueProcessor(s,o,t);r[a]=null==e?o:typeof e!=typeof o||e!==o?e:be(o,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(r[a]=!0)}if(!Object.keys(r).length)return;if(this.options.attributesGroupName){const e={};return e[this.options.attributesGroupName]=r,e}return r}}const ue=function(e){e=e.replace(/\r\n?/g,"\n");const t=new Y("!xml");let i=t,n="",s="";this.entityExpansionCount=0,this.currentExpandedLength=0;const r=new X(this.options.processEntities);for(let o=0;o<e.length;o++){if("<"===e[o])if("/"===e[o+1]){const t=we(e,">",o,"Closing Tag is not closed.");let r=e.substring(o+2,t).trim();if(this.options.removeNSPrefix){const e=r.indexOf(":");-1!==e&&(r=r.substr(e+1))}this.options.transformTagName&&(r=this.options.transformTagName(r)),i&&(n=this.saveTextToParentTag(n,i,s));const a=s.substring(s.lastIndexOf(".")+1);if(r&&-1!==this.options.unpairedTags.indexOf(r))throw new Error(`Unpaired tag can not be used as closing tag: </${r}>`);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=s.lastIndexOf(".",s.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=s.lastIndexOf("."),s=s.substring(0,l),i=this.tagsNodeStack.pop(),n="",o=t}else if("?"===e[o+1]){let t=ye(e,o,!1,"?>");if(!t)throw new Error("Pi Tag is not closed.");if(n=this.saveTextToParentTag(n,i,s),this.options.ignoreDeclaration&&"?xml"===t.tagName||this.options.ignorePiTags);else{const e=new Y(t.tagName);e.add(this.options.textNodeName,""),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[":@"]=this.buildAttributesMap(t.tagExp,s,t.tagName)),this.addChild(i,e,s,o)}o=t.closeIndex+1}else if("!--"===e.substr(o+1,3)){const t=we(e,"--\x3e",o+4,"Comment is not closed.");if(this.options.commentPropName){const r=e.substring(o+4,t-2);n=this.saveTextToParentTag(n,i,s),i.add(this.options.commentPropName,[{[this.options.textNodeName]:r}])}o=t}else if("!D"===e.substr(o+1,2)){const t=r.readDocType(e,o);this.docTypeEntities=t.entities,o=t.i}else if("!["===e.substr(o+1,2)){const t=we(e,"]]>",o,"CDATA is not closed.")-2,r=e.substring(o+9,t);n=this.saveTextToParentTag(n,i,s);let a=this.parseTextData(r,i.tagname,s,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?i.add(this.options.cdataPropName,[{[this.options.textNodeName]:r}]):i.add(this.options.textNodeName,a),o=t+2}else{let r=ye(e,o,this.options.removeNSPrefix),a=r.tagName;const l=r.rawTagName;let c=r.tagExp,h=r.attrExpPresent,d=r.closeIndex;if(this.options.transformTagName){const e=this.options.transformTagName(a);c===a&&(c=e),a=e}i&&n&&"!xml"!==i.tagname&&(n=this.saveTextToParentTag(n,i,s,!1));const u=i;u&&-1!==this.options.unpairedTags.indexOf(u.tagname)&&(i=this.tagsNodeStack.pop(),s=s.substring(0,s.lastIndexOf("."))),a!==t.tagname&&(s+=s?"."+a:a);const p=o;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,s,a)){let t="";if(c.length>0&&c.lastIndexOf("/")===c.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),c=a):c=c.substr(0,c.length-1),o=r.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))o=r.closeIndex;else{const i=this.readStopNodeData(e,l,d+1);if(!i)throw new Error(`Unexpected end of ${l}`);o=i.i,t=i.tagContent}const n=new Y(a);a!==c&&h&&(n[":@"]=this.buildAttributesMap(c,s,a)),t&&(t=this.parseTextData(t,a,s,!0,h,!0,!0)),s=s.substr(0,s.lastIndexOf(".")),n.add(this.options.textNodeName,t),this.addChild(i,n,s,p)}else{if(c.length>0&&c.lastIndexOf("/")===c.length-1){if("/"===a[a.length-1]?(a=a.substr(0,a.length-1),s=s.substr(0,s.length-1),c=a):c=c.substr(0,c.length-1),this.options.transformTagName){const e=this.options.transformTagName(a);c===a&&(c=e),a=e}const e=new Y(a);a!==c&&h&&(e[":@"]=this.buildAttributesMap(c,s,a)),this.addChild(i,e,s,p),s=s.substr(0,s.lastIndexOf("."))}else{const e=new Y(a);this.tagsNodeStack.push(i),a!==c&&h&&(e[":@"]=this.buildAttributesMap(c,s,a)),this.addChild(i,e,s,p),i=e}n="",o=d}}else n+=e[o]}return t.child};function pe(e,t,i,n){this.options.captureMetaData||(n=void 0);const s=this.options.updateTag(t.tagname,i,t[":@"]);!1===s||("string"==typeof s?(t.tagname=s,e.addChild(t,n)):e.addChild(t,n))}const fe=function(e,t,i){if(-1===e.indexOf("&"))return e;const n=this.options.processEntities;if(!n.enabled)return e;if(n.allowedTags&&!n.allowedTags.includes(t))return e;if(n.tagFilter&&!n.tagFilter(t,i))return e;for(let t in this.docTypeEntities){const i=this.docTypeEntities[t],s=e.match(i.regx);if(s){if(this.entityExpansionCount+=s.length,n.maxTotalExpansions&&this.entityExpansionCount>n.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${n.maxTotalExpansions}`);const t=e.length;if(e=e.replace(i.regx,i.val),n.maxExpandedLength&&(this.currentExpandedLength+=e.length-t,this.currentExpandedLength>n.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${n.maxExpandedLength}`)}}if(-1===e.indexOf("&"))return e;for(let t in this.lastEntities){const i=this.lastEntities[t];e=e.replace(i.regex,i.val)}if(-1===e.indexOf("&"))return e;if(this.options.htmlEntities)for(let t in this.htmlEntities){const i=this.htmlEntities[t];e=e.replace(i.regex,i.val)}return e=e.replace(this.ampEntity.regex,this.ampEntity.val)};function me(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 ge(e,t,i,n){return!(!t||!t.has(n))||!(!e||!e.has(i))}function we(e,t,i,n){const s=e.indexOf(t,i);if(-1===s)throw new Error(n);return s+t.length-1}function ye(e,t,i,n=">"){const s=function(e,t,i=">"){let n,s="";for(let r=t;r<e.length;r++){let t=e[r];if(n)t===n&&(n="");else if('"'===t||"'"===t)n=t;else if(t===i[0]){if(!i[1])return{data:s,index:r};if(e[r+1]===i[1])return{data:s,index:r}}else"\t"===t&&(t=" ");s+=t}}(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 _e(e,t,i){const n=i;let s=1;for(;i<e.length;i++)if("<"===e[i])if("/"===e[i+1]){const r=we(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("?"===e[i+1]){i=we(e,"?>",i+1,"StopNode is not closed.")}else if("!--"===e.substr(i+1,3)){i=we(e,"--\x3e",i+3,"StopNode is not closed.")}else if("!["===e.substr(i+1,2)){i=we(e,"]]>",i,"StopNode is not closed.")-2}else{const n=ye(e,i,">");if(n){(n&&n.tagName)===t&&"/"!==n.tagExp[n.tagExp.length-1]&&s++,i=n.closeIndex}}}function be(e,t,i){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&ne(e,i)}return void 0!==e?e:""}function ve(e,t,i){const n=Number.parseInt(e,t);return n>=0&&n<=1114111?String.fromCodePoint(n):i+e+";"}const xe=Y.getMetaDataSymbol();function Se(e,t){return Ce(e,t)}function Ce(e,t,i){let n;const s={};for(let r=0;r<e.length;r++){const o=e[r],a=Te(o);let l="";if(l=void 0===i?a:i+"."+a,a===t.textNodeName)void 0===n?n=o[a]:n+=""+o[a];else{if(void 0===a)continue;if(o[a]){let e=Ce(o[a],t,l);const i=Ee(e,t);void 0!==o[xe]&&(e[xe]=o[xe]),o[":@"]?Ae(e,o[":@"],l,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!==s[a]&&s.hasOwnProperty(a)?(Array.isArray(s[a])||(s[a]=[s[a]]),s[a].push(e)):t.isArray(a,l,i)?s[a]=[e]:s[a]=e}}}return"string"==typeof n?n.length>0&&(s[t.textNodeName]=n):void 0!==n&&(s[t.textNodeName]=n),s}function Te(e){const t=Object.keys(e);for(let e=0;e<t.length;e++){const i=t[e];if(":@"!==i)return i}}function Ae(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];n.isArray(r,i+"."+r,!0,!0)?e[r]=[t[r]]:e[r]=t[r]}}}function Ee(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 Me{constructor(e){this.externalEntities={},this.options=q(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({},I,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=D(e,r),r.err)return r}else{if("<"!==e[r]){if(z(e[r]))continue;return R("InvalidChar","char '"+e[r]+"' is not expected.",$(e,r))}{let o=r;if(r++,"!"===e[r]){r=k(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--),!j(l)){let t;return t=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",R("InvalidTag",t,$(e,r))}const c=V(e,r);if(!1===c)return R("InvalidAttr","Attributes for '"+l+"' have open quote.",$(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=N(h,t);if(!0!==s)return R(s.err.code,s.err.msg,$(e,i+s.err.line));n=!0}else if(a){if(!c.tagClosed)return R("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",$(e,r));if(h.trim().length>0)return R("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",$(e,o));if(0===i.length)return R("InvalidTag","Closing tag '"+l+"' has not been opened.",$(e,o));{const t=i.pop();if(l!==t.tagName){let i=$(e,t.tagStartPos);return R("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",$(e,o))}0==i.length&&(s=!0)}}else{const a=N(h,t);if(!0!==a)return R(a.err.code,a.err.msg,$(e,r-h.length+a.err.line));if(!0===s)return R("InvalidXml","Multiple possible root nodes found.",$(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=k(e,r);continue}if("?"!==e[r+1])break;if(r=D(e,++r),r.err)return r}else if("&"===e[r]){const t=F(e,r);if(-1==t)return R("InvalidChar","char '&' is not expected.",$(e,r));r=t}else if(!0===s&&!z(e[r]))return R("InvalidXml","Extra text at the end",$(e,r));"<"===e[r]&&r--}}}return n?1==i.length?R("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",$(e,i[0].tagStartPos)):!(i.length>0)||R("InvalidXml","Invalid '"+JSON.stringify(i.map(e=>e.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):R("InvalidXml","Start tag expected.",1)}(e,t);if(!0!==i)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const i=new oe(this.options);i.addExternalEntities(this.externalEntities);const n=i.parseXml(e);return this.options.preserveOrder||void 0===n?n:Se(n,this.options)}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 '
'");if("&"===t)throw new Error("An entity with value '&' is not permitted");this.externalEntities[e]=t}static getMetaDataSymbol(){return Y.getMetaDataSymbol()}}function Pe(e,t){let i="";return t.format&&t.indentBy.length>0&&(i="\n"),Ie(e,t,"",i)}function Ie(e,t,i,n){let s="",r=!1;for(let o=0;o<e.length;o++){const a=e[o],l=ze(a);if(void 0===l)continue;let c="";if(c=0===i.length?l:`${i}.${l}`,l===t.textNodeName){let e=a[l];ke(c,t)||(e=t.tagValueProcessor(l,e),e=Be(e,t)),r&&(s+=n),s+=e,r=!1;continue}if(l===t.cdataPropName){r&&(s+=n),s+=`<![CDATA[${a[l][0][t.textNodeName]}]]>`,r=!1;continue}if(l===t.commentPropName){s+=n+`\x3c!--${a[l][0][t.textNodeName]}--\x3e`,r=!0;continue}if("?"===l[0]){const e=De(a[":@"],t),i="?xml"===l?"":n;let o=a[l][0][t.textNodeName];o=0!==o.length?" "+o:"",s+=i+`<${l}${o}${e}?>`,r=!0;continue}let h=n;""!==h&&(h+=t.indentBy);const d=n+`<${l}${De(a[":@"],t)}`,u=Ie(a[l],t,c,h);-1!==t.unpairedTags.indexOf(l)?t.suppressUnpairedNode?s+=d+">":s+=d+"/>":u&&0!==u.length||!t.suppressEmptyNode?u&&u.endsWith(">")?s+=d+`>${u}${n}</${l}>`:(s+=d+">",u&&""!==n&&(u.includes("/>")||u.includes("</"))?s+=n+t.indentBy+u+n:s+=u,s+=`</${l}>`):s+=d+"/>",r=!0}return s}function ze(e){const t=Object.keys(e);for(let i=0;i<t.length;i++){const n=t[i];if(e.hasOwnProperty(n)&&":@"!==n)return n}}function De(e,t){let i="";if(e&&!t.ignoreAttributes)for(let n in e){if(!e.hasOwnProperty(n))continue;let s=t.attributeValueProcessor(n,e[n]);s=Be(s,t),!0===s&&t.suppressBooleanAttributes?i+=` ${n.substr(t.attributeNamePrefix.length)}`:i+=` ${n.substr(t.attributeNamePrefix.length)}="${s}"`}return i}function ke(e,t){let i=(e=e.substr(0,e.length-t.textNodeName.length-1)).substr(e.lastIndexOf(".")+1);for(let n in t.stopNodes)if(t.stopNodes[n]===e||t.stopNodes[n]==="*."+i)return!0;return!1}function Be(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 Oe={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:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1};function Ve(e){this.options=Object.assign({},Oe,e),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=re(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Fe),this.processTextOrObjNode=Le,this.options.format?(this.indentate=Ne,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function Le(e,t,i,n){const s=this.j2x(e,i+1,n.concat(t));return void 0!==e[this.options.textNodeName]&&1===Object.keys(e).length?this.buildTextValNode(e[this.options.textNodeName],t,s.attrStr,i):this.buildObjectNode(s.val,t,s.attrStr,i)}function Ne(e){return this.options.indentBy.repeat(e)}function Fe(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}Ve.prototype.build=function(e){return this.options.preserveOrder?Pe(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},Ve.prototype.j2x=function(e,t,i){let n="",s="";const r=i.join(".");for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o))if(void 0===e[o])this.isAttribute(o)&&(s+="");else if(null===e[o])this.isAttribute(o)||o===this.options.cdataPropName?s+="":"?"===o[0]?s+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(e[o]instanceof Date)s+=this.buildTextValNode(e[o],o,"",t);else if("object"!=typeof e[o]){const i=this.isAttribute(o);if(i&&!this.ignoreAttributesFn(i,r))n+=this.buildAttrPairStr(i,""+e[o]);else if(!i)if(o===this.options.textNodeName){let t=this.options.tagValueProcessor(o,""+e[o]);s+=this.replaceEntitiesValue(t)}else s+=this.buildTextValNode(e[o],o,"",t)}else if(Array.isArray(e[o])){const n=e[o].length;let r="",a="";for(let l=0;l<n;l++){const n=e[o][l];if(void 0===n);else if(null===n)"?"===o[0]?s+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:s+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if("object"==typeof n)if(this.options.oneListGroup){const e=this.j2x(n,t+1,i.concat(o));r+=e.val,this.options.attributesGroupName&&n.hasOwnProperty(this.options.attributesGroupName)&&(a+=e.attrStr)}else r+=this.processTextOrObjNode(n,o,t,i);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(o,n);e=this.replaceEntitiesValue(e),r+=e}else r+=this.buildTextValNode(n,o,"",t)}this.options.oneListGroup&&(r=this.buildObjectNode(r,o,a,t)),s+=r}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){const t=Object.keys(e[o]),i=t.length;for(let s=0;s<i;s++)n+=this.buildAttrPairStr(t[s],""+e[o][t[s]])}else s+=this.processTextOrObjNode(e[o],o,t,i);return{attrStr:n,val:s}},Ve.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&"true"===t?" "+e:" "+e+'="'+t+'"'},Ve.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}},Ve.prototype.closeTag=function(e){let t="";return-1!==this.options.unpairedTags.indexOf(e)?this.options.suppressUnpairedNode||(t="/"):t=this.options.suppressEmptyNode?"/":`></${e}`,t},Ve.prototype.buildTextValNode=function(e,t,i,n){if(!1!==this.options.cdataPropName&&t===this.options.cdataPropName)return this.indentate(n)+`<![CDATA[${e}]]>`+this.newLine;if(!1!==this.options.commentPropName&&t===this.options.commentPropName)return this.indentate(n)+`\x3c!--${e}--\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}},Ve.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 Re{}t(Re,"parser",new Me({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0})),t(Re,"builder",new Ve({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1}));class Ue{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=Ue.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=Ue.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=Ue.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 je extends Map{constructor(e){super(e),t(this,"onItemSet",new f),t(this,"onItemUpdated",new f),t(this,"onItemDeleted",new f),t(this,"onCleared",new f),t(this,"guard",()=>!0)}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 f),this.onItemUpdated.trigger({key:e,value:t})):(this.onItemSet||(this.onItemSet=new f),this.onItemSet.trigger({key:e,value:t})),n}add(e){const t=T.create();return this.set(t,e),t}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 $e{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 We{constructor(e,i,n,s){t(this,"_component"),t(this,"name"),t(this,"uuid"),this._component=e,this.name=n,this.uuid=s??T.create();i.get(He).list.set(this.uuid,this)}get controls(){return $e.copySchema(this._config)}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($e.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($e.isEntry(n))if("Color"===n.type){const{r:e,g:s,b:r}=n.value;t[i]={...n,value:new d.Color(e,s,r)}}else if("Vector3"===n.type){const{x:e,y:s,z:r}=n.value;t[i]={...n,value:new d.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)}}const Ge=class e extends g{constructor(n){super(n),t(this,"list",new i.DataMap),t(this,"enabled",!0),n.add(e.uuid,this)}};t(Ge,"uuid","b8c764e0-6b24-4e77-9a32-35fa728ee5b4");let He=Ge;class qe{constructor(e){t(this,"_event"),t(this,"_position",new d.Vector2),t(this,"onDisposed",new f),t(this,"updateMouseInfo",e=>{this._event=e}),this.dom=e,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(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}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 Ze=1.25,Ye=32,Xe=Math.pow(2,-24),Ke=Symbol("SKIP_GENERATION"),Qe={strategy:0,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Ke]:!1};function Je(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 et(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 tt(e,t){t.set(e)}function it(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 nt(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 st(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 rt(e,t){return 65535===t[e+15]}function ot(e,t){return t[e+6]}function at(e,t){return t[e+14]}function lt(e){return e+8}function ct(e,t){return e+8*t[e+6]}function ht(e,t){return t[e+7]}function dt(e){return e}function ut(e,t,i,n,s){let r=1/0,o=1/0,a=1/0,l=-1/0,c=-1/0,h=-1/0,d=1/0,u=1/0,p=1/0,f=-1/0,m=-1/0,g=-1/0;const w=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<d&&(d=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<u&&(u=y),y>m&&(m=y);const x=e[n+4],S=e[n+5],C=x-S,T=x+S;C<a&&(a=C),T>h&&(h=T),x<p&&(p=x),x>g&&(g=x)}n[0]=r,n[1]=o,n[2]=a,n[3]=l,n[4]=c,n[5]=h,s[0]=d,s[1]=u,s[2]=p,s[3]=f,s[4]=m,s[5]=g}const pt=32,ft=(e,t)=>e.candidate-t.candidate,mt=new Array(pt).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),gt=new Float32Array(6);class wt{constructor(){this.boundingData=new Float32Array(6)}}let yt,_t,bt,vt;const xt=Math.pow(2,32);function St(e){return"count"in e?1:1+St(e.left)+St(e.right)}function Ct(e,t,i){return yt=new Float32Array(i),_t=new Uint32Array(i),bt=new Uint16Array(i),vt=new Uint8Array(i),Tt(e,t)}function Tt(e,t){const i=e/4,n=e/2,s="count"in t,r=t.boundingData;for(let e=0;e<6;e++)yt[i+e]=r[e];if(s)return t.buffer?(vt.set(new Uint8Array(t.buffer),e),e+t.buffer.byteLength):(_t[i+6]=t.offset,bt[n+14]=t.count,bt[n+15]=65535,e+Ye);{const{left:n,right:s,splitAxis:r}=t;let o=Tt(e+Ye,n);const a=o/Ye-e/Ye;if(a>xt)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return _t[i+6]=a,_t[i+7]=r,Tt(o,s)}}function At(e,t,i,n,s,r){const{maxDepth:o,verbose:a,maxLeafSize:l,strategy:c,onProgress:h}=s,d=e.primitiveBuffer,u=e.primitiveBufferStride,p=new Float32Array(6);let f=!1;const m=new wt;return ut(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=et(t),-1!==o&&(a=(t[o]+t[o+3])/2);else if(1===r)o=et(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=st(e);let l=Ze*s;const c=i.offset||0,h=6*(n-c),d=6*(n+s-c);for(let e=0;e<3;e++){const n=t[e],c=(t[e+3]-n)/pt;if(s<8){const t=[...mt];t.length=s;let n=0;for(let s=h;s<d;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;nt(s,i,o)}t.sort(ft);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<d;n+=6){const s=i[n+2*e];for(let e=0;e<c;e++){const r=t[e];s>=r.candidate?nt(n,i,r.rightCacheBounds):(nt(n,i,r.leftCacheBounds),r.count++)}}for(let i=0;i<c;i++){const n=t[i],c=n.count,h=s-n.count,d=n.leftCacheBounds,u=n.rightCacheBounds;let p=0;0!==c&&(p=st(d)/r);let f=0;0!==h&&(f=st(u)/r);const m=1+Ze*(p*c+f*h);m<l&&(o=e,l=m,a=n.candidate)}}else{for(let e=0;e<pt;e++){const t=mt[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<d;t+=6){let s=~~((i[t+2*e]-n)/c);s>=pt&&(s=31);const r=mt[s];r.count++,nt(t,i,r.bounds)}const t=mt[31];tt(t.bounds,t.rightCacheBounds);for(let e=30;e>=0;e--){const t=mt[e],i=mt[e+1];it(t.bounds,i.rightCacheBounds,t.rightCacheBounds)}let u=0;for(let t=0;t<31;t++){const i=mt[t],n=i.count,c=i.bounds,h=mt[t+1].rightCacheBounds;0!==n&&(0===u?tt(c,gt):it(c,gt,gt)),u+=n;let d=0,p=0;0!==u&&(d=st(gt)/r);const f=s-u;0!==f&&(p=st(h)/r);const m=1+Ze*(d*u+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--}}(d,u,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 wt,o=n,a=w-n;i.left=r,ut(t,o,a,r.boundingData,p),e(r,o,a,p,h+1);const l=new wt,c=w,d=s-a;i.right=l,ut(t,c,d,l.boundingData,p),e(l,c,d,p,h+1)}return i}(m,i,n,p),m;function g(e){h&&h((e-r.offset)/r.count)}}function Et(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=At(e,a,n.offset,n.count,t,o),r=St(s),l=new i(Ye*r);return Ct(0,s,l),l})}class Mt{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 Pt{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 It=new Pt;let zt,Dt;const kt=[],Bt=new Mt(()=>new n.Box3);function Ot(e,t,i,n,s,r){zt=Bt.getPrimitive(),Dt=Bt.getPrimitive(),kt.push(zt,Dt),It.setBuffer(e._roots[t]);const o=Vt(0,e.geometry,i,n,s,r);It.clearBuffer(),Bt.releasePrimitive(zt),Bt.releasePrimitive(Dt),kt.pop(),kt.pop();const a=kt.length;return a>0&&(Dt=kt[a-1],zt=kt[a-2]),o}function Vt(e,t,i,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=It;let h=2*e;if(rt(h,l)){const t=ot(e,c),i=at(h,l);return Je(e,a,zt),n(t,i,!1,o,r+e/8,zt)}{let h=function(e){const{uint16Array:t,uint32Array:i}=It;let n=2*e;for(;!rt(n,t);)n=2*(e=lt(e));return ot(e,i)},d=function(e){const{uint16Array:t,uint32Array:i}=It;let n=2*e;for(;!rt(n,t);)n=2*(e=ct(e,i));return ot(e,i)+at(n,t)};const u=lt(e),p=ct(e,c);let f,m,g,w,y=u,_=p;if(s&&(g=zt,w=Dt,Je(y,a,g),Je(_,a,w),f=s(g),m=s(w),m<f)){y=p,_=u;const e=f;f=m,m=e,g=w}g||(g=zt,Je(y,a,g));const b=i(g,rt(2*y,l),f,o+1,r+y/8);let v;if(2===b){const e=h(y);v=n(e,d(y)-e,!0,o+1,r+y/8,g)}else v=b&&Vt(y,t,i,n,s,r,o+1);if(v)return!0;w=Dt,Je(_,a,w);const x=i(w,rt(2*_,l),m,o+1,r+_/8);let S;if(2===x){const e=h(_);S=n(e,d(_)-e,!0,o+1,r+_/8,w)}else S=x&&Vt(_,t,i,n,s,r,o+1);return!!S}}const Lt=new It.constructor,Nt=new It.constructor,Ft=new Mt(()=>new n.Box3),Rt=new n.Box3,Ut=new n.Box3,jt=new n.Box3,$t=new n.Box3;let Wt=!1;function Gt(e,t,i,n,s,r=0,o=0,a=0,l=0,c=null,h=!1){let d,u;h?(d=Nt,u=Lt):(d=Lt,u=Nt);const p=d.float32Array,f=d.uint32Array,m=d.uint16Array,g=u.float32Array,w=u.uint32Array,y=u.uint16Array,_=2*t,b=rt(2*e,m),v=rt(_,y);let x=!1;if(v&&b)x=h?s(ot(t,w),at(2*t,y),ot(e,f),at(2*e,m),l,o+t/8,a,r+e/8):s(ot(e,f),at(2*e,m),ot(t,w),at(2*t,y),a,r+e/8,l,o+t/8);else if(v){const c=Ft.getPrimitive();Je(t,g,c),c.applyMatrix4(i);const d=lt(e),u=ct(e,f);Je(d,p,Rt),Je(u,p,Ut);const m=c.intersectsBox(Rt),w=c.intersectsBox(Ut);x=m&&Gt(t,d,n,i,s,o,r,l,a+1,c,!h)||w&&Gt(t,u,n,i,s,o,r,l,a+1,c,!h),Ft.releasePrimitive(c)}else{const d=lt(t),u=ct(t,w);Je(d,g,jt),Je(u,g,$t);const m=c.intersectsBox(jt),y=c.intersectsBox($t);if(m&&y)x=Gt(e,d,i,n,s,r,o,a,l+1,c,h)||Gt(e,u,i,n,s,r,o,a,l+1,c,h);else if(m)if(b)x=Gt(e,d,i,n,s,r,o,a,l+1,c,h);else{const t=Ft.getPrimitive();t.copy(jt).applyMatrix4(i);const c=lt(e),u=ct(e,f);Je(c,p,Rt),Je(u,p,Ut);const m=t.intersectsBox(Rt),g=t.intersectsBox(Ut);x=m&&Gt(d,c,n,i,s,o,r,l,a+1,t,!h)||g&&Gt(d,u,n,i,s,o,r,l,a+1,t,!h),Ft.releasePrimitive(t)}else if(y)if(b)x=Gt(e,u,i,n,s,r,o,a,l+1,c,h);else{const t=Ft.getPrimitive();t.copy($t).applyMatrix4(i);const c=lt(e),d=ct(e,f);Je(c,p,Rt),Je(d,p,Ut);const m=t.intersectsBox(Rt),g=t.intersectsBox(Ut);x=m&&Gt(u,c,n,i,s,o,r,l,a+1,t,!h)||g&&Gt(u,d,n,i,s,o,r,l,a+1,t,!h),Ft.releasePrimitive(t)}}return x}const Ht=new n.Box3,qt=new Float32Array(6);class Zt{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){Et(this,e={...Qe,...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,qt,0);const[e,t,n,h,d,u]=qt;e<s&&(s=e),h>a&&(a=h),t<r&&(r=t),d>l&&(l=d),n<o&&(o=n),u>c&&(c=u)}return i[n+0]=s,i[n+1]=r,i[n+2]=o,i[n+3]=a,i[n+4]=l,i[n+5]=c,i}computePrimitiveBounds(e,t,i){const n=i.offset||0;for(let s=e,r=e+t;s<r;s++){this.writePrimitiveBounds(s,qt,0);const[e,t,r,o,a,l]=qt,c=(e+o)/2,h=(t+a)/2,d=(r+l)/2,u=(o-e)/2,p=(a-t)/2,f=(l-r)/2,m=6*(s-n);i[m+0]=c,i[m+1]=u+(Math.abs(c)+u)*Xe,i[m+2]=h,i[m+3]=p+(Math.abs(h)+p)*Xe,i[m+4]=d,i[m+5]=f+(Math.abs(d)+f)*Xe}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/Ye;for(let t=0;t<o;t++){const i=8*t;rt(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=rt(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=lt(r),a=ct(r,n),c=ht(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/Ye-1;e>=0;e--){const t=8*e,i=2*t;if(rt(i,s)){const e=ot(t,n),o=at(i,s);this.writePrimitiveRangeBounds(e,o,qt,0),r.set(qt,t)}else{const e=lt(t),i=ct(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=>{Je(0,new Float32Array(t),Ht),e.union(Ht)}),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=Ot(this,e,i,n,t,l),a)break;l+=s.byteLength/Ye}return a}bvhcast(e,t,i){let{intersectsRanges:s}=i;return function(e,t,i,s){if(Wt)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Wt=!0;const r=e._roots,o=t._roots;let a,l=0,c=0;const h=(new n.Matrix4).copy(i).invert();for(let e=0,t=r.length;e<t;e++){Lt.setBuffer(r[e]),c=0;const t=Ft.getPrimitive();Je(dt(0),Lt.float32Array,t),t.applyMatrix4(h);for(let e=0,n=o.length;e<n&&(Nt.setBuffer(o[e]),a=Gt(0,0,i,h,s,l,c,0,0,t),Nt.clearBuffer(),c+=o[e].byteLength/Ye,!a);e++);if(Ft.releasePrimitive(t),Lt.clearBuffer(),l+=r[e].byteLength/Ye,a)break}return Wt=!1,a}(this,e,t,s)}}function Yt(e){return e.index?e.index.count:e.attributes.position.count}function Xt(e){return Yt(e)/3}function Kt(e,t){if(!e.index){const i=e.attributes.position.count,s=function(e,t=ArrayBuffer){return e>65535?new Uint32Array(new t(4*e)):new Uint16Array(new t(2*e))}(i,t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer);e.setIndex(new n.BufferAttribute(s,1));for(let e=0;e<i;e++)s[e]=e}}function Qt(e,t,i){const n=function(e,t,i){const n=Yt(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=Yt(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,d=null;for(const e of c){const t=e.pos;0!==h&&t!==d&&r.push({offset:d,count:t-d}),h+=e.isStart?1:-1,d=t}return r}class Jt extends Zt{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={...Qe,...t})[Ke]||this.init(t)}init(e){const{geometry:t,primitiveStride:i}=this;if(e.indirect){const n=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}(Qt(t,e.range,i),e.useSharedArrayBuffer);this._indirectBuffer=n}else Kt(t,e);super.init(e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new n.Box3))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:Qt(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class ei{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}}ei.prototype.setFromBox=function(){const e=new n.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 ti=function(){const e=new n.Vector3,t=new n.Vector3,i=new n.Vector3;return function(n,s,r){const o=n.start,a=e,l=s.start,c=t;i.subVectors(o,l),e.subVectors(n.end,n.start),t.subVectors(s.end,s.start);const h=i.dot(c),d=c.dot(a),u=c.dot(c),p=i.dot(a),f=a.dot(a)*u-d*d;let m,g;m=0!==f?(h*d-p*u)/f:0,g=(h+m*d)/u,r.x=m,r.y=g}}(),ii=function(){const e=new n.Vector2,t=new n.Vector3,i=new n.Vector3;return function(n,s,r,o){ti(n,s,e);let a=e.x,l=e.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 e,c;e=a<0?n.start:n.end,c=l<0?s.start:s.end;const h=t,d=i;return n.closestPointToPoint(c,!0,t),s.closestPointToPoint(e,!0,i),h.distanceToSquared(c)<=d.distanceToSquared(e)?(r.copy(h),void o.copy(c)):(r.copy(e),void o.copy(d))}}}(),ni=function(){const e=new n.Vector3,t=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,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 d=r.getPlane(i);if(Math.abs(d.distanceToPoint(a))<=o){const e=d.projectPoint(a,t);if(r.containsPoint(e))return!0}return!1}}(),si=["x","y","z"],ri=1e-15;function oi(e){return Math.abs(e)<ri}class ai extends n.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new n.Vector3),this.satBounds=new Array(4).fill().map(()=>new ei),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(e){return ni(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],d=r[2];h.subVectors(t,i),d.setFromPoints(h,n);const u=s[3],p=r[3];u.subVectors(i,e),p.setFromPoints(u,n);const f=l.length(),m=h.length(),g=u.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,f<ri?m<ri||g<ri?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(i)):m<ri?g<ri?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):g<ri&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(o,e),this.needsUpdate=!1}}ai.prototype.closestPointToSegment=function(){const e=new n.Vector3,t=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]),ii(i,n,e,t),c=e.distanceToSquared(t),c<h&&(h=c,s&&s.copy(e),r&&r.copy(t))}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)}}(),ai.prototype.intersectsTriangle=function(){const e=new ai,t=new ei,i=new ei,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,d=new n.Vector2,u=new n.Vector2;function p(e,n,r,o){const l=s;e.isDegenerateIntoPoint||e.isDegenerateIntoSegment?l.copy(n.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(t.setFromPoints(o,n.points),r.isSeparated(t))return!1;if(a.copy(l).cross(o),t.setFromPoints(a,e.points),i.setFromPoints(a,n.points),t.isSeparated(i))return!1}const d=n.satBounds,u=n.satAxes;for(let s=1;s<4;s++){const r=d[s],o=u[s];if(t.setFromPoints(o,e.points),r.isSeparated(t))return!1;if(a.crossVectors(l,o),t.setFromPoints(a,e.points),i.setFromPoints(a,n.points),t.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(e,t,i,n,s,r,o,a,l,c,h){let d=o/(o-a);c.x=n+(s-n)*d,h.start.subVectors(t,e).multiplyScalar(d).add(e),d=o/(o-l),c.y=n+(r-n)*d,h.end.subVectors(i,e).multiplyScalar(d).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 oi(o)?oi(a)?p(e,t,i,n):(i&&(i.start.copy(r.start),i.end.copy(r.start)),e.containsPoint(r.start)):oi(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!(!oi(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),d=l.x*c.y-l.y*c.x;if(oi(d))return!1;const u=(h.x*c.y-h.y*c.x)/d,p=-(l.x*h.y-l.y*h.x)/d;return!(u<0||u>1||p<0||p>1)&&(!!oi(n.start.z+l.z*u-(a.start.z+c.z*p))&&(i&&(i.start.copy(n.start).addScaledVector(l,u),i.end.copy(n.start).addScaledVector(l,u)),!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);oi(b)&&(b=0),oi(v)&&(v=0),oi(x)&&(x=0);const S=b*v,C=b*x;if(S>0&&C>0)return!1;let T=f.distanceToPoint(t.a),A=f.distanceToPoint(t.b),E=f.distanceToPoint(t.c);oi(T)&&(T=0),oi(A)&&(A=0),oi(E)&&(E=0);const M=T*A,P=T*E;if(M>0&&P>0)return!1;r.copy(f.normal),o.copy(_.normal);const I=r.cross(o);let z=0,D=Math.abs(I.x);const k=Math.abs(I.y);k>D&&(D=k,z=1);Math.abs(I.z)>D&&(z=2);const B=si[z],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,S,C,b,v,x,d,l))return p(this,t,i,n);if(m(t,N,F,R,M,P,T,A,E,u,c))return p(this,t,i,n);if(d.y<d.x){const e=d.y;d.y=d.x,d.x=e,h.copy(l.start),l.start.copy(l.end),l.end.copy(h)}if(u.y<u.x){const e=u.y;u.y=u.x,u.x=e,h.copy(c.start),c.start.copy(c.end),c.end.copy(h)}return!(d.y<u.x||u.y<d.x)&&(i&&(u.x>d.x?i.start.copy(c.start):i.start.copy(l.start),u.y<d.y?i.end.copy(c.end):i.end.copy(l.end)),!0)}}(),ai.prototype.distanceToPoint=function(){const e=new n.Vector3;return function(t){return this.closestPointToPoint(t,e),t.distanceTo(e)}}(),ai.prototype.distanceToTriangle=function(){const e=new n.Vector3,t=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 t=0;t<3;t++){let s;const r=i[t],l=n[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];n.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=i[l],d=i[(l+1)%3];s.set(this[h],this[d]);for(let l=0;l<3;l++){const h=i[l],d=i[(l+1)%3];r.set(n[h],n[d]),ii(s,r,e,t);const u=e.distanceToSquared(t);u<c&&(c=u,o&&o.copy(e),a&&a.copy(t))}}return Math.sqrt(c)}}();class li{constructor(e,t,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 ei),this.alignedSatBounds=new Array(3).fill().map(()=>new ei),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),i&&this.matrix.copy(i)}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}}li.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}}(),li.prototype.intersectsBox=function(){const e=new ei;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}}(),li.prototype.intersectsTriangle=function(){const e=new ai,t=new Array(3),i=new ei,s=new ei,r=new n.Vector3;return function(n){this.needsUpdate&&this.update(),n.isExtendedTriangle?n.needsUpdate&&n.update():(e.copy(n),e.update(),n=e);const o=this.satBounds,a=this.satAxes;t[0]=n.a,t[1]=n.b,t[2]=n.c;for(let e=0;e<3;e++){const n=o[e],s=a[e];if(i.setFromPoints(s,t),n.isSeparated(i))return!1}const l=n.satBounds,c=n.satAxes,h=this.points;for(let e=0;e<3;e++){const t=l[e],n=c[e];if(i.setFromPoints(n,h),t.isSeparated(i))return!1}for(let e=0;e<3;e++){const n=a[e];for(let e=0;e<4;e++){const o=c[e];if(r.crossVectors(n,o),i.setFromPoints(r,t),s.setFromPoints(r,h),i.isSeparated(s))return!1}}return!0}}(),li.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}}(),li.prototype.distanceToPoint=function(){const e=new n.Vector3;return function(t){return this.closestPointToPoint(t,e),t.distanceTo(e)}}(),li.prototype.distanceToBox=function(){const e=["x","y","z"],t=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,d=n.max,u=this.points;let p=1/0;for(let e=0;e<8;e++){const t=u[e];r.copy(t).clamp(h,d);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 n=0;n<3;n++)for(let s=0;s<=1;s++)for(let r=0;r<=1;r++){const o=(n+1)%3,a=(n+2)%3,l=1<<n|s<<o|r<<a,c=u[s<<o|r<<a],p=u[l];t[f].set(c,p);const m=e[n],g=e[o],w=e[a],y=i[f],_=y.start,b=y.end;_[m]=h[m],_[g]=s?h[g]:d[g],_[w]=r?h[w]:d[g],b[m]=d[m],b[g]=s?h[g]:d[g],b[w]=r?h[w]:d[g],f++}for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)for(let i=0;i<=1;i++){r.x=e?d.x:h.x,r.y=t?d.y:h.y,r.z=i?d.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 n=t[e];for(let e=0;e<12;e++){const t=i[e];ii(n,t,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 ci extends Mt{constructor(){super(()=>new ai)}}const hi=new ci,di=new n.Vector3,ui=new n.Vector3;const pi=parseInt(n.REVISION)>=169,fi=parseInt(n.REVISION)<=161,mi=new n.Vector3,gi=new n.Vector3,wi=new n.Vector3,yi=new n.Vector2,_i=new n.Vector2,bi=new n.Vector2,vi=new n.Vector3,xi=new n.Vector3,Si=new n.Vector3,Ci=new n.Vector3;function Ti(e,t,i,s,r,o,a,l,c,h,d){mi.fromBufferAttribute(t,o),gi.fromBufferAttribute(t,a),wi.fromBufferAttribute(t,l);const u=function(e,t,i,s,r,o,a,l){let c;if(c=o===n.BackSide?e.intersectTriangle(s,i,t,!0,r):e.intersectTriangle(t,i,s,o!==n.DoubleSide,r),null===c)return null;const h=e.origin.distanceTo(r);return h<a||h>l?null:{distance:h,point:r.clone()}}(e,mi,gi,wi,Ci,c,h,d);if(u){if(s){yi.fromBufferAttribute(s,o),_i.fromBufferAttribute(s,a),bi.fromBufferAttribute(s,l),u.uv=new n.Vector2;const e=n.Triangle.getInterpolation(Ci,mi,gi,wi,yi,_i,bi,u.uv);pi||(u.uv=e)}if(r){yi.fromBufferAttribute(r,o),_i.fromBufferAttribute(r,a),bi.fromBufferAttribute(r,l),u.uv1=new n.Vector2;const e=n.Triangle.getInterpolation(Ci,mi,gi,wi,yi,_i,bi,u.uv1);pi||(u.uv1=e),fi&&(u.uv2=u.uv1)}if(i){vi.fromBufferAttribute(i,o),xi.fromBufferAttribute(i,a),Si.fromBufferAttribute(i,l),u.normal=new n.Vector3;const t=n.Triangle.getInterpolation(Ci,mi,gi,wi,vi,xi,Si,u.normal);u.normal.dot(e.direction)>0&&u.normal.multiplyScalar(-1),pi||(u.normal=t)}const t={a:o,b:a,c:l,normal:new n.Vector3,materialIndex:0};if(n.Triangle.getNormal(mi,gi,wi,t.normal),u.face=t,u.faceIndex=o,pi){const e=new n.Vector3;n.Triangle.getBarycoord(Ci,mi,gi,wi,e),u.barycoord=e}}return u}function Ai(e){return e&&e.isMaterial?e.side:e}function Ei(e,t,i,n,s,r,o){const a=3*n;let l=a+0,c=a+1,h=a+2;const{index:d,groups:u}=e;e.index&&(l=d.getX(l),c=d.getX(c),h=d.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,d=u.length;a<d;a++){const{start:d,count:w,materialIndex:y}=u[a];if(e>=d&&e<d+w){const e=Ti(i,p,f,m,g,l,c,h,Ai(t[y]),r,o);if(e){if(e.faceIndex=n,e.face.materialIndex=y,!s)return e;s.push(e)}}}}else{const e=Ti(i,p,f,m,g,l,c,h,Ai(t),r,o);if(e){if(e.faceIndex=n,e.face.materialIndex=0,!s)return e;s.push(e)}}return null}function Mi(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 Pi(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,Mi(o,3*e,l,c),o.needsUpdate=!0,n(o,e,s,r))return!0}return!1}function Ii(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),d(0,c),c+=r.byteLength;function d(e,i,r=!1){const c=2*e;if(rt(c,a)){const t=ot(e,o);let i=1/0,r=1/0,h=1/0,d=-1/0,u=-1/0,p=-1/0;for(let e=3*t,o=3*(t+at(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>d&&(d=o),a<r&&(r=a),a>u&&(u=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]!==d||l[e+4]!==u||l[e+5]!==p)&&(l[e+0]=i,l[e+1]=r,l[e+2]=h,l[e+3]=d,l[e+4]=u,l[e+5]=p,!0)}{const n=lt(e),s=ct(e,o);let a=r,c=!1,h=!1;if(t){if(!a){const e=n/8+i/Ye,r=s/8+i/Ye;c=t.has(e),h=t.has(r),a=!c&&!h}}else c=!0,h=!0;const u=a||h;let p=!1;(a||c)&&(p=d(n,i,a));let f=!1;u&&(f=d(s,i,a));const m=p||f;if(m)for(let 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 zi(e,t,i,n,s){let r,o,a,l,c,h;const d=1/i.direction.x,u=1/i.direction.y,p=1/i.direction.z,f=i.origin.x,m=i.origin.y,g=i.origin.z;let w=t[e],y=t[e+3],_=t[e+1],b=t[e+3+1],v=t[e+2],x=t[e+3+2];return d>=0?(r=(w-f)*d,o=(y-f)*d):(r=(y-f)*d,o=(w-f)*d),u>=0?(a=(_-m)*u,l=(b-m)*u):(a=(b-m)*u,l=(_-m)*u),!(r>l||a>o)&&((a>r||isNaN(r))&&(r=a),(l<o||isNaN(o))&&(o=l),p>=0?(c=(v-g)*p,h=(x-g)*p):(c=(x-g)*p,h=(v-g)*p),!(r>h||c>o)&&((c>r||r!=r)&&(r=c),(h<o||o!=o)&&(o=h),r<=s&&o>=n))}function Di(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),Mi(o,3*e,l,c),o.needsUpdate=!0,n(o,e,s,r))return!0}return!1}function ki(e,t,i,n,s,r,o){It.setBuffer(e._roots[t]),Bi(0,e,i,n,s,r,o),It.clearBuffer()}function Bi(e,t,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=It,h=2*e;if(rt(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++)Ei(l,t,i,e,r,o,a)}(t,i,n,ot(e,c),at(h,l),s,r,o)}else{const l=lt(e);zi(l,a,n,r,o)&&Bi(l,t,i,n,s,r,o);const h=ct(e,c);zi(h,a,n,r,o)&&Bi(h,t,i,n,s,r,o)}}const Oi=["x","y","z"];function Vi(e,t,i,n,s,r){It.setBuffer(e._roots[t]);const o=Li(0,e,i,n,s,r);return It.clearBuffer(),o}function Li(e,t,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=It;let c=2*e;if(rt(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=Ei(a,t,i,e,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(t,i,n,ot(e,l),at(c,a),s,r)}{const a=ht(e,l),c=Oi[a],h=n.direction[c]>=0;let d,u;h?(d=lt(e),u=ct(e,l)):(d=ct(e,l),u=lt(e));const p=zi(d,o,n,s,r)?Li(d,t,i,n,s,r):null;if(p){const e=p.point[c];if(h?e<=o[u+a]:e>=o[u+a+3])return p}const f=zi(u,o,n,s,r)?Li(u,t,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const Ni=new n.Box3,Fi=new ai,Ri=new ai,Ui=new n.Matrix4,ji=new li,$i=new li;function Wi(e,t,i,n){It.setBuffer(e._roots[t]);const s=Gi(0,e,i,n);return It.clearBuffer(),s}function Gi(e,t,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=It;let l=2*e;null===s&&(i.boundingBox||i.computeBoundingBox(),ji.set(i.boundingBox.min,i.boundingBox.max,n),s=ji);if(!rt(l,o)){const o=lt(e),l=ct(e,a);Je(o,r,Ni);if(s.intersectsBox(Ni)&&Gi(o,t,i,n,s))return!0;Je(l,r,Ni);return!!(s.intersectsBox(Ni)&&Gi(l,t,i,n,s))}{const s=t.geometry,c=s.index,h=s.attributes.position,d=i.index,u=i.attributes.position,p=ot(e,a),f=at(l,o);if(Ui.copy(n).invert(),i.boundsTree){Je(e,r,$i),$i.matrix.copy(Ui),$i.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:e=>$i.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(Mi(Ri,t,c,h),Ri.needsUpdate=!0,e.intersectsTriangle(Ri))return!0;return!1}})}{const e=Xt(i);for(let t=3*p,i=3*(f+p);t<i;t+=3){Mi(Fi,t,c,h),Fi.a.applyMatrix4(Ui),Fi.b.applyMatrix4(Ui),Fi.c.applyMatrix4(Ui),Fi.needsUpdate=!0;for(let t=0,i=3*e;t<i;t+=3)if(Mi(Ri,t,d,u),Ri.needsUpdate=!0,Fi.intersectsTriangle(Ri))return!0}}}}const Hi=new n.Matrix4,qi=new li,Zi=new li,Yi=new n.Vector3,Xi=new n.Vector3,Ki=new n.Vector3,Qi=new n.Vector3;function Ji(e,t,i,n={},s={},r=0,o=1/0){t.boundingBox||t.computeBoundingBox(),qi.set(t.boundingBox.min,t.boundingBox.max,i),qi.needsUpdate=!0;const a=e.geometry,l=a.attributes.position,c=a.index,h=t.attributes.position,d=t.index,u=hi.getPrimitive(),p=hi.getPrimitive();let f=Yi,m=Xi,g=null,w=null;s&&(g=Ki,w=Qi);let y=1/0,_=null,b=null;return Hi.copy(i).invert(),Zi.matrix.copy(Hi),e.shapecast({boundsTraverseOrder:e=>qi.distanceToBox(e),intersectsBounds:(e,t,i)=>i<y&&i<o&&(t&&(Zi.min.copy(e.min),Zi.max.copy(e.max),Zi.needsUpdate=!0),!0),intersectsRange:(e,n)=>{if(t.boundsTree){return t.boundsTree.shapecast({boundsTraverseOrder:e=>Zi.distanceToBox(e),intersectsBounds:(e,t,i)=>i<y&&i<o,intersectsRange:(t,s)=>{for(let o=t,a=t+s;o<a;o++){Mi(p,3*o,d,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++){Mi(u,3*t,c,l),u.needsUpdate=!0;const e=u.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=Xt(t);s<o;s++){Mi(p,3*s,d,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++){Mi(u,3*t,c,l),u.needsUpdate=!0;const e=u.distanceToTriangle(p,f,g);if(e<y&&(m.copy(f),w&&w.copy(g),y=e,_=t,b=s),e<r)return!0}}}}),hi.releasePrimitive(u),hi.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(Hi),m.applyMatrix4(Hi),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function en(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),d(0,c),c+=r.byteLength;function d(i,r,c=!1){const h=2*i;if(rt(h,a)){const t=ot(i,o);let r=1/0,c=1/0,d=1/0,u=-1/0,p=-1/0,f=-1/0;for(let i=t,o=t+at(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>u&&(u=o),a<c&&(c=a),a>p&&(p=a),l<d&&(d=l),l>f&&(f=l)}}return(l[i+0]!==r||l[i+1]!==c||l[i+2]!==d||l[i+3]!==u||l[i+4]!==p||l[i+5]!==f)&&(l[i+0]=r,l[i+1]=c,l[i+2]=d,l[i+3]=u,l[i+4]=p,l[i+5]=f,!0)}{const e=lt(i),n=ct(i,o);let s=c,a=!1,h=!1;if(t){if(!s){const i=e/8+r/Ye,o=n/8+r/Ye;a=t.has(i),h=t.has(o),s=!a&&!h}}else a=!0,h=!0;const u=s||h;let p=!1;(s||a)&&(p=d(e,r,s));let f=!1;u&&(f=d(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 tn(e,t,i,n,s,r,o){It.setBuffer(e._roots[t]),nn(0,e,i,n,s,r,o),It.clearBuffer()}function nn(e,t,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=It,h=2*e;if(rt(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++)Ei(l,t,i,c?c[e]:e,r,o,a)}(t,i,n,ot(e,c),at(h,l),s,r,o)}else{const l=lt(e);zi(l,a,n,r,o)&&nn(l,t,i,n,s,r,o);const h=ct(e,c);zi(h,a,n,r,o)&&nn(h,t,i,n,s,r,o)}}const sn=["x","y","z"];function rn(e,t,i,n,s,r){It.setBuffer(e._roots[t]);const o=on(0,e,i,n,s,r);return It.clearBuffer(),o}function on(e,t,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=It;let c=2*e;if(rt(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,d=n+s;e<d;e++){let n;n=Ei(a,t,i,l?l[e]:e,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(t,i,n,ot(e,l),at(c,a),s,r)}{const a=ht(e,l),c=sn[a],h=n.direction[c]>=0;let d,u;h?(d=lt(e),u=ct(e,l)):(d=ct(e,l),u=lt(e));const p=zi(d,o,n,s,r)?on(d,t,i,n,s,r):null;if(p){const e=p.point[c];if(h?e<=o[u+a]:e>=o[u+a+3])return p}const f=zi(u,o,n,s,r)?on(u,t,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const an=new n.Box3,ln=new ai,cn=new ai,hn=new n.Matrix4,dn=new li,un=new li;function pn(e,t,i,n){It.setBuffer(e._roots[t]);const s=fn(0,e,i,n);return It.clearBuffer(),s}function fn(e,t,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=It;let l=2*e;null===s&&(i.boundingBox||i.computeBoundingBox(),dn.set(i.boundingBox.min,i.boundingBox.max,n),s=dn);if(!rt(l,o)){const o=lt(e),l=ct(e,a);Je(o,r,an);if(s.intersectsBox(an)&&fn(o,t,i,n,s))return!0;Je(l,r,an);return!!(s.intersectsBox(an)&&fn(l,t,i,n,s))}{const s=t.geometry,c=s.index,h=s.attributes.position,d=i.index,u=i.attributes.position,p=ot(e,a),f=at(l,o);if(hn.copy(n).invert(),i.boundsTree){Je(e,r,un),un.matrix.copy(hn),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 i=p,n=f+p;i<n;i++)if(Mi(cn,3*t.resolveTriangleIndex(i),c,h),cn.needsUpdate=!0,e.intersectsTriangle(cn))return!0;return!1}})}{const e=Xt(i);for(let i=p,n=f+p;i<n;i++){const n=t.resolveTriangleIndex(i);Mi(ln,3*n,c,h),ln.a.applyMatrix4(hn),ln.b.applyMatrix4(hn),ln.c.applyMatrix4(hn),ln.needsUpdate=!0;for(let t=0,i=3*e;t<i;t+=3)if(Mi(cn,t,d,u),cn.needsUpdate=!0,ln.intersectsTriangle(cn))return!0}}}}const mn=new n.Matrix4,gn=new li,wn=new li,yn=new n.Vector3,_n=new n.Vector3,bn=new n.Vector3,vn=new n.Vector3;function xn(e,t,i,n={},s={},r=0,o=1/0){t.boundingBox||t.computeBoundingBox(),gn.set(t.boundingBox.min,t.boundingBox.max,i),gn.needsUpdate=!0;const a=e.geometry,l=a.attributes.position,c=a.index,h=t.attributes.position,d=t.index,u=hi.getPrimitive(),p=hi.getPrimitive();let f=yn,m=_n,g=null,w=null;s&&(g=bn,w=vn);let y=1/0,_=null,b=null;return mn.copy(i).invert(),wn.matrix.copy(mn),e.shapecast({boundsTraverseOrder:e=>gn.distanceToBox(e),intersectsBounds:(e,t,i)=>i<y&&i<o&&(t&&(wn.min.copy(e.min),wn.max.copy(e.max),wn.needsUpdate=!0),!0),intersectsRange:(n,s)=>{if(t.boundsTree){const a=t.boundsTree;return a.shapecast({boundsTraverseOrder:e=>wn.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);Mi(p,3*t,d,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);Mi(u,3*i,c,l),u.needsUpdate=!0;const n=u.distanceToTriangle(p,f,g);if(n<y&&(m.copy(f),w&&w.copy(g),y=n,_=t,b=v),n<r)return!0}}}})}for(let o=0,a=Xt(t);o<a;o++){Mi(p,3*o,d,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);Mi(u,3*i,c,l),u.needsUpdate=!0;const n=u.distanceToTriangle(p,f,g);if(n<y&&(m.copy(f),w&&w.copy(g),y=n,_=t,b=o),n<r)return!0}}}}),hi.releasePrimitive(u),hi.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(mn),m.applyMatrix4(mn),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function Sn(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 Cn=new li,Tn=new n.Ray,An=new n.Vector3,En=new n.Matrix4,Mn=new n.Vector3,Pn=["getX","getY","getZ"];class In extends Jt{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,t,i={}){i={setIndex:!0,indirect:Boolean(e.indirectBuffer),...i};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/Ye;e<t;e++){const t=8*e;rt(2*t,s)||(n[t+6]=n[t+6]/8-e)}}}(r));const a=new In(t,{...i,[Ke]:!0});if(a._roots=r,a._indirectBuffer=o||null,i.setIndex){const i=t.getIndex();if(null===i){const i=new n.BufferAttribute(e.index,1,!1);t.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(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[Pn[e]](l),s=r[Pn[e]](c),o=r[Pn[e]](h);let a=n;s<a&&(a=s),o<a&&(a=o);let d=n;s>d&&(d=s),o>d&&(d=o),t[i+e]=a,t[i+e+3]=d}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 d=["getX","getY","getZ"],u=i.offset;for(let n=e,p=e+t;n<p;n++){const e=3*(s?s[n]:n),t=6*(n-u);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[d[e]](p),s=r[d[e]](f),o=r[d[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 u=(h-c)/2,g=2*e;i[t+g+0]=c+u,i[t+g+1]=u+(Math.abs(c)+u)*Xe}}return i}raycastObject3D(e,t,i=[]){const{material:n}=e;if(void 0===n)return;En.copy(e.matrixWorld).invert(),Tn.copy(t.ray).applyMatrix4(En),Mn.setFromMatrixScale(e.matrixWorld),An.copy(Tn.direction).multiply(Mn);const s=An.length(),r=t.near/s,o=t.far/s;if(!0===t.firstHitOnly){let s=this.raycastFirst(Tn,n,r,o);s=Sn(s,e,t),s&&i.push(s)}else{const s=this.raycast(Tn,n,r,o);for(let n=0,r=s.length;n<r;n++){const r=Sn(s[n],e,t);r&&i.push(r)}}return i}refit(e=null){return(this.indirect?en:Ii)(this,e)}raycast(e,t=n.FrontSide,i=0,s=1/0){const r=this._roots,o=[],a=this.indirect?tn:ki;for(let n=0,l=r.length;n<l;n++)a(this,n,t,e,o,i,s);return o}raycastFirst(e,t=n.FrontSide,i=0,s=1/0){const r=this._roots;let o=null;const a=this.indirect?rn:Vi;for(let n=0,l=r.length;n<l;n++){const r=a(this,n,t,e,i,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?pn:Wi;for(let r=0,o=n.length;r<o&&(i=s(this,r,e,t),!i);r++);return i}shapecast(e){const t=hi.getPrimitive(),i=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?Di:Pi});return hi.releasePrimitive(t),i}bvhcast(e,t,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=hi.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?e=>{const t=this.resolveTriangleIndex(e);Mi(r,3*t,o,a)}:e=>{Mi(r,3*e,o,a)},c=hi.getPrimitive(),h=e.geometry.index,d=e.geometry.attributes.position,u=e.indirect?t=>{const i=e.resolveTriangleIndex(t);Mi(c,3*i,h,d)}:e=>{Mi(c,3*e,h,d)};if(s){if(!(e instanceof In))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const i=(e,i,n,o,a,h,d,p)=>{for(let f=n,m=n+o;f<m;f++){u(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,d,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 Cn.set(e.min,e.max,t),Cn.needsUpdate=!0,this.shapecast({intersectsBounds:e=>Cn.intersectsBox(e),intersectsTriangle:e=>Cn.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?xn:Ji)(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=>(di.copy(t).clamp(e.min,e.max),di.distanceToSquared(t)),intersectsBounds:(e,t,i)=>i<a&&i<o,intersectsTriangle:(e,i)=>{e.closestPointToPoint(t,di);const n=t.distanceToSquared(di);return n<a&&(ui.copy(di),a=n,l=i),n<r}}),a===1/0)return null;const c=Math.sqrt(a);return i.point?i.point.copy(ui):i.point=ui.clone(),i.distance=c,i.faceIndex=l,i}(this,e,t,i,n)}}const zn=new n.Matrix4,Dn=new n.Ray,kn=new Mt(()=>new n.Line3),Bn=new n.Vector3,On=new n.Vector3,Vn=new n.Box3,Ln=["getX","getY","getZ"];class Nn extends Jt{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[Ln[e]](c),s=o[Ln[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=kn.getPrimitive(),i=super.shapecast({...e,intersectsPrimitive:e.intersectsLine,scratchPrimitive:t,iterate:Fn});return kn.releasePrimitive(t),i}raycastObject3D(e,t,i=[]){const{matrixWorld:n}=e,{firstHitOnly:s}=t;zn.copy(n).invert(),Dn.copy(t.ray).applyMatrix4(zn);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(Dn.origin),intersectsBounds:e=>(Vn.copy(e).expandByScalar(Math.abs(r)),Dn.intersectsBox(Vn)?1:0),intersectsLine:(r,c)=>{if(Dn.distanceSqToSegment(r.start,r.end,Bn,On)>o)return;Bn.applyMatrix4(e.matrixWorld);const h=t.ray.origin.distanceTo(Bn);h<t.near||h>t.far||s&&h>=l||(l=h,c=this.resolvePrimitiveIndex(c),a={distance:h,point:On.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 Fn(e,t,i,n,s,r,o){const{geometry:a,primitiveStride:l}=i,{index:c}=a,h=a.attributes.position,d=c?c.count:h.count;for(let a=e,u=t+e;a<u;a++){let e=i.resolvePrimitiveIndex(a)*l,t=(e+1)%d;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 Rn={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},Un=new n.Mesh,jn=[];function $n(e,t){if(this.isBatchedMesh)Wn.call(this,e,t);else{const{geometry:i}=this;if(i.boundsTree)i.boundsTree.raycastObject3D(this,e,t);else{let i;if(this instanceof n.Mesh)i=Rn.Mesh;else if(this instanceof n.LineSegments)i=Rn.LineSegments;else if(this instanceof n.LineLoop)i=Rn.LineLoop;else if(this instanceof n.Line)i=Rn.Line;else{if(!(this instanceof n.Points))throw new Error("BVH: Fallback raycast function not found.");i=Rn.Points}i.call(this,e,t)}}}function Wn(e,t){if(this.boundsTrees){const i=this.boundsTrees,s=this._drawInfo||this._instanceInfo,r=this._drawRanges||this._geometryInfo,o=this.matrixWorld;Un.material=this.material,Un.geometry=this.geometry;const a=Un.geometry.boundsTree,l=Un.geometry.drawRange;null===Un.geometry.boundingSphere&&(Un.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(Un.geometry.boundsTree=i[a],this.getMatrixAt(n,Un.matrixWorld).premultiply(o),!Un.geometry.boundsTree){this.getBoundingBoxAt(a,Un.geometry.boundingBox),this.getBoundingSphereAt(a,Un.geometry.boundingSphere);const e=r[a];Un.geometry.setDrawRange(e.start,e.count)}Un.raycast(e,jn);for(let e=0,i=jn.length;e<i;e++){const i=jn[e];i.object=this,i.batchId=n,t.push(i)}jn.length=0}Un.geometry.boundsTree=a,Un.geometry.drawRange=l,Un.material=null,Un.geometry=null}else Rn.BatchedMesh.call(this,e,t)}function Gn(e={}){const{type:t=In}=e;return this.boundsTree=new t(this,e),this.boundsTree}function Hn(){this.boundsTree=null}const qn=class e extends g{constructor(i){super(i),t(this,"onDisposed",new f),t(this,"onBeforeDispose",new f),t(this,"onFragmentsLoaded",new f),t(this,"baseCoordinationModel",""),t(this,"baseCoordinationMatrix",new d.Matrix4),t(this,"enabled",!0),t(this,"_core"),this.components.add(e.uuid,this)}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(e,t){this._core=new i.FragmentsModels(e,t),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 d.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 d.Matrix4;return t&&i.copy(t.clone()).invert(),i.multiply(this.baseCoordinationMatrix),e.applyMatrix4(i),i}};t(qn,"uuid","fef46874-46a3-461b-8c44-2922ab77c806");let Zn=qn;function Yn(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16}class Xn{constructor(e,t={}){const{pixelsPerMeter:i=.1}=t;this.pixelsPerMeter=i,this.renderer=e}async cull(e){e=function(e){const t=new Set;return e.traverse(e=>{e.isMesh&&t.add(e)}),Array.from(t)}(e);const{renderer:t,pixelsPerMeter:i}=this,s=new n.Vector3,r=new n.OrthographicCamera,o=new n.Box3,a=new n.WebGLRenderTarget(1,1);o.makeEmpty(),e.forEach(e=>{o.expandByObject(e)}),o.getSize(s);const l=Math.min(t.capabilities.maxTextureSize,8192),c=Math.ceil(s.x/i),h=Math.ceil(s.z/i),d=Math.ceil(c/l),u=Math.ceil(h/l);a.setSize(Math.ceil(c/d),Math.ceil(h/u)),r.rotation.x=-Math.PI/2,r.far=o.max.y-o.min.y+r.near,r.position.y=o.max.y+r.near;const p=new n.Scene,f=new Map,m=new Map,g=[];for(let t=0;t<e.length;t++){const i=e[t];f.set(i,i.material),m.set(i,i.parent);const n=new Kn;n.objectId=t,g.push(n),i.material=n,p.add(i)}const w=t.getClearColor(new n.Color),y=t.getClearAlpha(),_=t.getRenderTarget(),b=t.autoClear;t.autoClear=!0,t.setClearColor(0,0),t.setRenderTarget(a);const v=new Uint8Array(a.width*a.height*4),x=new Set,S=s.x/d,C=s.z/u;for(let i=0;i<d;i++)for(let n=0;n<u;n++){const s=o.min.x+S*i,l=s+S,c=o.min.z+C*n,h=(s+l)/2,d=(c+(c+C))/2;r.position.set(h,o.max.y,d);const u=S/2,f=C/2;r.left=-u,r.right=u,r.top=f,r.bottom=-f,r.updateProjectionMatrix(),t.render(p,r);const m=await t.readRenderTargetPixelsAsync(a,0,0,a.width,a.height,v);for(let t=0,i=m.length;t<i;t+=4){if(0===m[t+3])continue;const i=Yn(m,t);x.add(e[i])}}for(const t of e){t.material=f.get(t);const e=m.get(t);e?e.add(t):p.remove(t)}t.setClearColor(w,y),t.setRenderTarget(_),t.autoClear=b;for(const e of g)e.dispose();return a.dispose(),Array.from(x)}}class Kn extends n.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:n.GLSL3,blending:n.NoBlending,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(e)}}const Qn=1e-16,Jn=new n.Vector3(0,1,0),es=new n.Vector3;function ts(e){return e.delta(es).normalize(),Math.abs(es.dot(Jn))>=1-Qn}function is(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)<=Qn&&(r=!0),!o&&n.distanceToSquared(t)<=Qn&&(o=!0),r&&o)return!0}return r&&o}const ns=new n.Line3;function ss(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;ns.start.lerpVectors(i,r,s[t][0]),ns.end.lerpVectors(i,r,s[t][1]),n.push(new Float32Array([ns.start.x,ns.start.y,ns.start.z,ns.end.x,ns.end.y,ns.end.z]))}return n}const rs=new n.Vector3(0,1,0),os=new n.Vector3,as=new n.Vector3,ls=new n.Vector3,cs=new n.Triangle;function*hs(e,t=[],i={}){const{projectionDirection:s=rs,thresholdAngle:r=1,iterationTime:o=30}=i,a=Math.pow(10,4),l=Math.cos(n.MathUtils.DEG2RAD*r),c=e.getIndex(),h=e.getAttribute("position"),d=c?c.count:h.count,u=[0,0,0],p=["a","b","c"],f=new Array(3),m={};let g=performance.now();for(let e=0;e<d;e+=3){performance.now()-g>o&&(yield,g=performance.now()),c?(u[0]=c.getX(e),u[1]=c.getX(e+1),u[2]=c.getX(e+2)):(u[0]=e,u[1]=e+1,u[2]=e+2);const{a:i,b:r,c:d}=cs;if(i.fromBufferAttribute(h,u[0]),r.fromBufferAttribute(h,u[1]),d.fromBufferAttribute(h,u[2]),cs.getNormal(ls),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(d.x*a)},${Math.round(d.y*a)},${Math.round(d.z*a)}`,f[0]!==f[1]&&f[1]!==f[2]&&f[2]!==f[0])for(let e=0;e<3;e++){const i=(e+1)%3,r=f[e],o=f[i],a=cs[p[e]],c=cs[p[i]],h=`${r}_${o}`,d=`${o}_${r}`;if(d in m&&m[d]){const e=m[d].normal,i=ls.dot(e)<=l;let r=!1;if(null!==s){let t=s.dot(ls);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(i||r){const e=new n.Line3;e.start.copy(a),e.end.copy(c),t.push(e)}m[d]=null}else h in m||(m[h]={index0:u[e],index1:u[i],normal:ls.clone()})}}for(const e in m)if(m[e]){const{index0:i,index1:s}=m[e];os.fromBufferAttribute(h,i),as.fromBufferAttribute(h,s);const r=new n.Line3;r.start.copy(os),r.end.copy(as),t.push(r)}return t}const ds=new n.Line3;function us(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++){ps(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,ds,!0)||is(e,ds)||is(t,ds)||n.push(ds.clone())))}),n}function ps(e,t){return e.distanceTo(t)<1e-10}function fs(e){ms(e);let t=[];return e.traverse(e=>{e.geometry&&e.visible&&t.push(e)}),t}const ms=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):ms(i)},gs=new n.Matrix4,ws=new n.Matrix4;class ys{constructor(){this.projectionDirection=new n.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,t=[],i=null){const{projectionDirection:s,thresholdAngle:r,iterationTime:o}=this;if(e.isObject3D){const a=fs(e);let l=null;s&&(l=new n.Vector3);let c=performance.now();for(let e=0;e<a.length;e++){c-performance.now()>o&&(yield);const n=a[e];l&&(ws.copy(n.matrixWorld).invert(),l.copy(s).transformDirection(ws).normalize());const h=yield*hs(n.geometry,[],{projectionDirection:l,thresholdAngle:r,iterationTime:o});_s(h,n.matrixWorld);for(let e=0;e<h.length;e++)t.push(h[e]);if(null!==i)for(let e=0;e<h.length;e++)i.push(n)}return t}return yield*hs(e,t,{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=fs(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 In(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),d=r.get(c.geometry);gs.copy(l.matrixWorld).invert().multiply(c.matrixWorld);const u=us(h,d,gs,[]);_s(u,l.matrixWorld);for(let e=0;e<u.length;e++)t.push(u[e]);if(null!==i)for(let e=0;e<u.length;e++)i.push(l)}return t}{let i;return e.isBufferGeometry?i=e.boundsTree||new In(e,{maxLeafSize:1}):(i=e,e=i.geometry),gs.identity(),us(i,i,gs,t)}}}function _s(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 bs extends Zt{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 vs=new n.Vector3(0,1,0),xs=new n.Plane,Ss=new n.Vector3,Cs=new n.Vector3;function Ts(e,t,i){e.needsUpdate&&e.update(),xs.copy(e.plane),xs.normal.dot(vs)<0&&(xs.normal.multiplyScalar(-1),xs.constant*=-1);const s=xs.distanceToPoint(t.start),r=xs.distanceToPoint(t.end),o=Math.abs(s)<1e-16,a=s<0,l=r<0;if(t.delta(Cs).normalize(),Math.abs(xs.normal.dot(Cs))<1e-16)return!(o||!a)&&(i.copy(t),!0);if(a&&l)return i.copy(t),!0;if(!a&&!l)return!1;{const e=n.MathUtils.mapLinear(0,s,r,0,1);if(t.at(e,Ss),a)return i.start.copy(t.start),i.end.copy(Ss),!0;if(l)return i.end.copy(t.end),i.start.copy(Ss),!0}return!1}const As=new n.Plane,Es=new n.Vector3,Ms=new n.Vector3,Ps=new ai,Is=new n.Line3,zs=new n.Line3,Ds=new n.Vector3,ks=new n.Vector3,Bs=new n.Vector3;function Os(e,t,i=new n.Line3){if(Ps.copy(t),Ps.a.y=0,Ps.b.y=0,Ps.c.y=0,Ps.update(),Is.copy(e),Is.start.y=0,Is.end.y=0,Ps.getArea()<=1e-16)return null;const s=Is.distance();Is.delta(Ds).divideScalar(s),ks.copy(Ds).cross(Ps.plane.normal).normalize(),As.setFromNormalAndCoplanarPoint(ks,Is.start);let r=0;const{points:o}=Ps;for(let e=0;e<3;e++){const t=o[e],i=o[(e+1)%3],n=As.distanceToPoint(t),s=As.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);Es.lerpVectors(t,i,e),c=!0}if((c&&!l||a)&&(a&&!c&&Es.copy(t),0===r?zs.start.copy(Es):zs.end.copy(Es),r++,2===r))break}if(2===r){if(zs.delta(Bs).normalize(),Ds.dot(Bs)<0){const e=zs.start;zs.start=zs.end,zs.end=e}const t=0,n=Ms.subVectors(Is.end,Is.start).dot(Ds),r=Ms.subVectors(zs.start,Is.start).dot(Ds),o=Ms.subVectors(zs.end,Is.start).dot(Ds);return n<=r||o<=t?null:(e.at(Math.max(t,r)/s,i.start),e.at(Math.min(n,o)/s,i.end),i)}return null}const Vs=new n.Vector3,Ls=new n.Vector3,Ns=new n.Vector3;function Fs(e,t,i){const n=function(e,t){e.delta(Vs),Ls.subVectors(t.start,e.start),Ns.subVectors(t.end,e.start);const i=Vs.length();let n=Ls.length()/i,s=Ns.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&&(Rs(n,i),!0)}function Rs(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 Us=new n.Vector3(0,1,0),js=new n.Line3,$s=new n.Line3,Ws=new ai;function Gs(e,t,i,s,r=null){const{geometry:o,matrixWorld:a,material:l}=i,c=l.side,h=a.determinant()<0,d=e.lines;e.bvhcast(t,a,{intersectsRanges:(e,t,i,l)=>{r&&(r.candidates+=t*l);for(let u=i,p=l+i;u<p;u++){let i=3*u+0,l=3*u+1,p=3*u+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}=Ws;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),Ws.needsUpdate=!0,Ws.update(),c!==n.DoubleSide){if(Ws.plane.normal.dot(Us)!==h===(c===n.BackSide)){r&&(r.backFaceCulled+=t);continue}}const w=Math.max(f.y,m.y,g.y),y=Math.min(f.y,m.y,g.y),_=Ws.plane.normal;let b=_.x,v=_.y,x=_.z,S=Ws.plane.constant;v<0&&(b=-b,v=-v,x=-x,S=-S);for(let i=e,n=t+e;i<n;i++){const e=d[i],t=Math.min(e.start.y,e.end.y),n=Math.max(e.start.y,e.end.y);if(w<=t){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,d=f.z-e.start.z,u=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+d*n,b=u*i+p*n,v=w*i+y*n,x=1/t,S=Math.min(_,b,v);if(Math.max(_,b,v)<0||S>x){r&&r.xzBoundsCulled++;continue}const C=h*s+d*c,T=u*s+p*c,A=w*s+y*c,E=Math.min(C,T,A),M=Math.max(C,T,A);if(E>0||M<0){r&&r.xzBoundsCulled++;continue}}const c=b*e.start.x+v*e.start.y+x*e.start.z+S,h=b*e.end.x+v*e.end.y+x*e.end.z+S;if(c>=0&&h>=0)r&&r.planeTrimCulled++;else if(is(Ws,e))r&&r.triangleEdgeCulled++;else{if(n<y)js.copy(e);else if(!Ts(Ws,e,js)){r&&r.planeTrimCulled++;continue}js.distance()<1e-10?r&&r.distThresholdCulled++:Os(js,Ws,$s)?(r&&r.used++,Fs(e,$s,s[i])):r&&r.noOverlapCulled++}}}}})}Ws.update=()=>{Ws.plane.setFromCoplanarPoints(...Ws.points)};let Hs=!1;const qs={},Zs={};let Ys=null,Xs=0,Ks=0;const Qs={get enabled(){return Hs},set enabled(e){Hs=e},reset(){for(const e in qs)delete qs[e];for(const e in Zs)delete Zs[e];Ys=null,Xs=0,Ks=0},setStat(e,t){Zs[e]=t},startTotal(){Hs&&(Ks=performance.now())},startStep(e){Hs&&(null!==Ys&&this.endStep(),Ys=e,Xs=performance.now())},endStep(){if(!Hs||null===Ys)return;const e=performance.now()-Xs;qs[Ys]=e,Ys=null},printSummary(){if(!Hs)return;null!==Ys&&this.endStep();const e=performance.now()-Ks;console.log("\n=== Projection Summary ==="),console.log(`Total time: ${e.toFixed(1)}ms\n`);for(const[t,i]of Object.entries(qs)){const n=(i/e*100).toFixed(1);console.log(` ${t}: ${i.toFixed(1)}ms (${n}%)`)}if(Object.keys(Zs).length>0){console.log("\n--- Stats ---");for(const[e,t]of Object.entries(Zs))console.log(` ${e}: ${t}`)}console.log("")}},Js=1e-5,er=1e-16,tr=1e-16;function ir(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 nr=null;async function sr(e,t,i,n,s=null){const o=await async function(){return null===nr&&(nr=new u.WebGPURenderer,await nr.init()),nr}();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=r.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");Qs.enabled&&console.log("Number of meshes:",t.length),Qs.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}}Qs.enabled&&console.log(`Split ${t.length} meshes into ${l.length} batches`);let c=0,h=0,d=0,p=0,f=0;for(let i=0;i<l.length;i++){const{start:u,end:m}=l[i],g=m-u;Qs.enabled&&console.log(`Processing batch ${i+1}/${l.length} (meshes ${u}-${m-1})`);let w=0,y=0;const _=[];for(let e=u;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,S=0,C=0;for(let e=u;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[S+e]=s[e]+C;S+=s.length,C+=i.attributes.position.count}const T=new Float32Array(16*g);for(let e=u;e<m;e++){const i=e-u;T.set(t[e].matrixWorld.elements,16*i)}const A=[];for(let t=0;t<e.groupCount;t++){const i=e.meshIndex[t];if(i>=u&&i<m){const n=i-u,s=_[n]+e.meshOffsets[t];A.push({edgeOffset:e.edgeOffsets[t],edgeCount:e.edgeCounts[t],triOffset:s,triCount:e.meshCounts[t],meshIdx:n})}}if(0===A.length){Qs.enabled&&console.log(` Batch ${i+1}: no groups, skipping`);continue}const E=new Uint32Array(5*A.length);for(let e=0;e<A.length;e++){const t=A[e],i=5*e;E[i+0]=t.edgeOffset,E[i+1]=t.edgeCount,E[i+2]=t.triOffset,E[i+3]=t.triCount,E[i+4]=t.meshIdx}let M=0;for(let e=0;e<A.length;e++)M+=A[e].edgeCount*A[e].triCount;s&&(s.candidates+=M);let P=Math.min(Math.ceil(.1*M),2e6),I=Math.max(P,1e4);Qs.enabled&&console.log(` Batch ${i+1}: ${A.length} groups, ${w/3} vertices, ${y/3} triangles, ${M} pairs, buffer for ${I} overlaps`);const z=performance.now(),D=r.instancedArray(b,"float"),k=r.instancedArray(v,"uint"),B=r.instancedArray(T,"float"),O=r.instancedArray(E,"uint");let V=r.instancedArray(new Uint32Array([0]),"uint").toAtomic(),L=r.instancedArray(new Float32Array(3*I),"float");p+=performance.now()-z;const N=performance.now(),F=r.Fn(()=>{const e=r.instanceIndex.mul(5),t=O.element(e),i=O.element(e.add(1)),n=O.element(e.add(2)),s=O.element(e.add(3)),o=O.element(e.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:e})=>{const s=n.add(e.toUint()).mul(3),o=k.element(s),c=k.element(s.add(1)),h=k.element(s.add(2)),d=r.vec3(D.element(o.mul(3)),D.element(o.mul(3).add(1)),D.element(o.mul(3).add(2))),u=r.vec3(D.element(c.mul(3)),D.element(c.mul(3).add(1)),D.element(c.mul(3).add(2))),p=r.vec3(D.element(h.mul(3)),D.element(h.mul(3).add(1)),D.element(h.mul(3).add(2))),f=l.mul(r.vec4(d,r.float(1))).xyz,m=l.mul(r.vec4(u,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*er)),()=>{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:e})=>{const i=t.add(e.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(),d=c.y.lessThan(0),u=r.select(d,c.negate(),c),p=r.select(d,h.negate(),h),w=u.dot(s).add(p),y=u.dot(o).add(p),b=w.lessThan(0),x=y.lessThan(0),S=r.abs(w).lessThan(r.float(Js)),C=b.not().and(x.not()),T=y.sub(w),A=r.abs(T).lessThan(r.float(Js)),E=A.and(S.or(b.not()));r.If(E,()=>{r.Continue()}),r.If(C.and(A.not()),()=>{r.Continue()});const M=w.negate().div(T),P=r.mix(s,o,M),z=r.vec3(r.select(A.or(b),s.x,P.x),r.select(A.or(b),s.y,P.y),r.select(A.or(b),s.z,P.z)),D=r.vec3(r.select(A.or(x),o.x,P.x),r.select(A.or(x),o.y,P.y),r.select(A.or(x),o.z,P.z)),k=D.sub(z),B=k.dot(k);r.If(B.lessThan(r.float(Js)),()=>{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(Js)),W=N.dot(N).lessThanEqual(r.float(Js)),G=F.dot(F).lessThanEqual(r.float(Js)),H=R.dot(R).lessThanEqual(r.float(Js)),q=U.dot(U).lessThanEqual(r.float(Js)),Z=j.dot(j).lessThanEqual(r.float(Js)),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),ee=r.vec3(g.x,r.float(0),g.z),te=r.vec3(z.x,r.float(0),z.z),ie=r.vec3(D.x,r.float(0),D.z),ne=r.vec3(s.x,r.float(0),s.z),se=r.vec3(o.x,r.float(0),o.z).sub(ne),re=se.dot(se);r.If(re.lessThan(r.float(Js)),()=>{r.Continue()});const oe=re.sqrt(),ae=J.sub(Q),le=ee.sub(Q),ce=r.cross(ae,le),he=ce.dot(ce);r.If(he.lessThanEqual(r.float(4e-16*er)),()=>{r.Continue()});const de=ie.sub(te),ue=de.dot(de);r.If(ue.lessThan(r.float(Js)),()=>{r.Continue()});const pe=ue.sqrt(),fe=de.div(pe),me=se.div(oe),ge=r.normalize(ce),we=r.cross(fe,ge),ye=r.float(0).toVar(),_e=r.float(0).toVar(),be=r.float(0).toVar(),ve=r.float(0).toVar(),xe=r.uint(0).toVar(),Se=we.dot(Q.sub(te)),Ce=we.dot(J.sub(te)),Te=r.abs(Se).lessThan(r.float(tr)),Ae=r.abs(Ce).lessThan(r.float(tr)),Ee=Te.not().and(Ae.not()).and(Se.mul(Ce).lessThan(0));r.If(Ee,()=>{const e=Se.div(Se.sub(Ce)),t=r.mix(Q.x,J.x,e),i=r.mix(Q.z,J.z,e);r.If(xe.equal(0),()=>{ye.assign(t),_e.assign(i)}).Else(()=>{be.assign(t),ve.assign(i)}),xe.addAssign(1)}).ElseIf(Te,()=>{r.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=Ce,Pe=we.dot(ee.sub(te)),Ie=Ae,ze=r.abs(Pe).lessThan(r.float(tr)),De=Ie.not().and(ze.not()).and(Me.mul(Pe).lessThan(0));r.If(xe.lessThan(2),()=>{r.If(De,()=>{const e=Me.div(Me.sub(Pe)),t=r.mix(J.x,ee.x,e),i=r.mix(J.z,ee.z,e);r.If(xe.equal(0),()=>{ye.assign(t),_e.assign(i)}).Else(()=>{be.assign(t),ve.assign(i)}),xe.addAssign(1)}).ElseIf(Ie.and(Ee.not()).and(Te.not()),()=>{r.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=Pe,Be=Se,Oe=ze,Ve=Te,Le=Oe.not().and(Ve.not()).and(ke.mul(Be).lessThan(0));r.If(xe.lessThan(2),()=>{r.If(Le,()=>{const e=ke.div(ke.sub(Be)),t=r.mix(ee.x,Q.x,e),i=r.mix(ee.z,Q.z,e);r.If(xe.equal(0),()=>{ye.assign(t),_e.assign(i)}).Else(()=>{be.assign(t),ve.assign(i)}),xe.addAssign(1)}).ElseIf(Oe.and(De.not()).and(Ie.not()),()=>{r.If(xe.equal(0),()=>{ye.assign(ee.x),_e.assign(ee.z)}).Else(()=>{be.assign(ee.x),ve.assign(ee.z)}),xe.addAssign(1)})}),r.If(xe.notEqual(2),()=>{r.Continue()});const Ne=r.vec3(ye,r.float(0),_e),Fe=r.vec3(be,r.float(0),ve).sub(Ne).dot(fe),Re=r.vec3(ye,r.float(0),_e).toVar(),Ue=r.vec3(be,r.float(0),ve).toVar();r.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=r.float(0),$e=pe,We=Re.sub(te).dot(fe),Ge=Ue.sub(te).dot(fe),He=$e.lessThanEqual(We).or(Ge.lessThanEqual(je));r.If(He,()=>{r.Continue()});const qe=r.max(je,We),Ze=r.min($e,Ge),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=r.max(r.float(0),r.min(r.float(1),Ke)),et=r.max(r.float(0),r.min(r.float(1),Qe)),tt=r.abs(et.sub(Je));r.If(tt.lessThanEqual(r.float(tr)),()=>{r.Continue()});const it=r.atomicAdd(V.element(0),1);r.If(it.lessThan(r.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(A.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)),Qs.enabled&&console.log(` Batch ${i+1}: ${$} overlaps found (capacity: ${I})`),$>I&&Qs.enabled&&console.warn(` WARNING: Overlap buffer overflow! ${$} > ${I}. Some occlusion data lost.`),$>0){const e=await o.getArrayBufferAsync(L.value),t=new Float32Array(e);h+=performance.now()-U;const i=performance.now(),s=Math.min($,I);for(let e=0;e<s;e++){const i=3*e,s=Math.round(t[i]);Rs([t[i+1],t[i+2]],n[s])}d+=performance.now()-i,Qs.enabled&&console.log(` Processed ${s} overlaps into hiddenOverlapMap`)}else h+=performance.now()-U}o.dispose(),nr=null;const m=p+f+c+h+d;Qs.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: ${d.toFixed(1)}ms`))}const rr=new n.Vector3(0,1,0);function or(e,t=null){const i=new Float32Array(6*e.length);let s=0;for(let t=0,n=e.length;t<n;t++){const n=e[t];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),t){const i=new Float32Array(2*e.length);for(let e=0,n=t.length;e<n;e++)i[2*e]=t[e],i[2*e+1]=t[e];r.setAttribute("group",new n.BufferAttribute(i,1))}return r}class ar{constructor(e,t=!0){this.meshes=fs(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 or(this.visibleEdges,this.groupKeyToIndex?this.visibleGroupIndices:null)}getHiddenLineGeometry(){return or(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();Qs.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 In(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]=[];Qs.startStep("Building line BVH");const h=new bs(e,{maxLeafSize:2,strategy:2});Qs.startStep("BVHcast overlaps"),a=performance.now();const d={candidates:0,backFaceCulled:0,yBoundsCulled:0,xzBoundsCulled:0,triangleEdgeCulled:0,planeTrimCulled:0,distThresholdCulled:0,noOverlapCulled:0,used:0,totalEdges:e.length,totalTriangles:l},u=this.useWebGPU,p={};u&&(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];u?ir(h,n.get(s.geometry),s,p,e):Gs(h,n.get(s.geometry),s,c,d)}if(u){let e=!1;for(sr(p,i,h,c,d).then(()=>{e=!0});!e;)yield}const f=d.totalEdges*d.totalTriangles;if(Qs.setStat("Total edges",d.totalEdges.toLocaleString()),Qs.setStat("Total triangles",d.totalTriangles.toLocaleString()),Qs.setStat("Brute-force pairs (edges × triangles)",f.toLocaleString()),Qs.setStat("BVH candidate pairs",d.candidates.toLocaleString()),f>0&&Qs.setStat("BVH reduction",(d.candidates/f*100).toFixed(3)+"% of brute-force"),d.candidates>0){const e=d.candidates,t=t=>(t/e*100).toFixed(2)+"%";u||(Qs.setStat("Rejected: back-face culling",d.backFaceCulled.toLocaleString()+" ("+t(d.backFaceCulled)+")"),Qs.setStat("Rejected: Y-bounds (tri below edge)",d.yBoundsCulled.toLocaleString()+" ("+t(d.yBoundsCulled)+")"),Qs.setStat("Rejected: XZ-bounds (no 2D overlap)",d.xzBoundsCulled.toLocaleString()+" ("+t(d.xzBoundsCulled)+")"),Qs.setStat("Rejected: edge lies on triangle",d.triangleEdgeCulled.toLocaleString()+" ("+t(d.triangleEdgeCulled)+")"),Qs.setStat("Rejected: line above tri plane",d.planeTrimCulled.toLocaleString()+" ("+t(d.planeTrimCulled)+")"),Qs.setStat("Rejected: trimmed edge too small",d.distThresholdCulled.toLocaleString()+" ("+t(d.distThresholdCulled)+")"),Qs.setStat("Rejected: no projected overlap",d.noOverlapCulled.toLocaleString()+" ("+t(d.noOverlapCulled)+")")),Qs.setStat("Producing overlaps",d.used.toLocaleString()+" ("+t(d.used)+")")}Qs.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(ss(i,n,!1,s),ss(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 lr{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."));const t=r.next();t.done?i(t.value):requestAnimationFrame(e)}()})}*generate(e,t){const{iterationTime:i,angleThreshold:s,includeIntersectionEdges:r}=this,{onProgress:o=()=>{},visibilityCuller:a=null,groupFn:l=null}=t;if(Qs.reset(),Qs.startTotal(),e.isBufferGeometry&&(e=new n.Mesh(e)),a){Qs.startStep("Visibility culling");let t=!1;for(a.cull(e).then(i=>{(e=new n.Scene).children=i,t=!0});!t;)yield}const c=new ys;c.iterationTime=i,c.thresholdAngle=s,c.projectionDirection.copy(rr),Qs.startStep("Generating candidate edges"),o("Generating candidate edges");let h=[],d=l?[]:null;if(yield*c.getEdgesGenerator(e,h,d),r&&(Qs.startStep("Generating intersection edges"),o("Generating intersection edges"),yield*c.getIntersectionEdgesGenerator(e,h,d)),Qs.startStep("Pre-filtering edges"),o("Pre-filtering edges"),d){const e=[],t=[];for(let i=0;i<h.length;i++)ts(h[i])||(e.push(h[i]),t.push(d[i]));h=e,d=t}else h=h.filter(e=>!ts(e));yield;const u=new ar(e,this.useWebGPU);if(u.iterationTime=i,l&&d){const e=new Map;for(let t=0;t<h.length;t++){const i=l(d[t]);e.has(i)||e.set(i,e.size),h[t].groupIndex=e.get(i)}u.groupKeyToIndex=e,u.hasGroups=!0}return o("Building BVH & computing overlaps"),yield*u.addEdgesGenerator(h,{onProgress:o?(e,t)=>{o("Building BVH & computing overlaps",e/t,u)}:null}),Qs.printSummary(),u}}new n.Line3,new n.Line3,new n.Vector3;const cr=class e extends g{constructor(i){super(i),t(this,"enabled",!0),t(this,"onDisposed",new f),t(this,"generator",new lr),t(this,"cullerPixelsPerMeter",.05),t(this,"projectionDirection",new d.Vector3(0,-1,0)),t(this,"nearPlane",-1/0),t(this,"farPlane",1/0),this.components.add(e.uuid,this),this.generator.includeIntersectionEdges=!1}async get(e,t,i){const n=this.components.get(Zn),s=new d.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 d.BufferGeometry;e.setAttribute("position",new d.Float32BufferAttribute(i.positions,3)),i.normals&&e.setAttribute("normal",new d.Float32BufferAttribute(i.normals,3)),e.setIndex(Array.from(i.indices)),r.set(n,e)}const o=r.get(n),a=new d.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 d.Vector3(0,-1,0),l=(new d.Quaternion).setFromUnitVectors(o,a),c=(new d.Matrix4).makeRotationFromQuaternion(l),h=c.clone().invert();for(const e of s.children)e.applyMatrix4(c),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 In(t.geometry,{maxLeafSize:1,strategy:2})}}),this.nearPlane!==-1/0||this.farPlane!==1/0){const e=new d.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 u=t.renderer.three,p=new Xn(u,{pixelsPerMeter:this.cullerPixelsPerMeter}),f=await this.generator.generateAsync(s,{visibilityCuller:p,groupFn:e=>`${e.userData._edgeProjectorModelId??"unknown"}:${e.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[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(e.uuid),this.onDisposed.reset()}};t(cr,"uuid","f2e76c3a-8b1d-4d5e-9a3f-7c6b2d4e8f1a");let hr=cr;class dr{constructor(){t(this,"wasm",{path:"",absolute:!1,logLevel:p.LogLevel.LOG_LEVEL_OFF}),t(this,"webIfc",{COORDINATE_TO_ORIGIN:!0}),t(this,"autoSetWasm",!0),t(this,"customLocateFileHandler",null)}}const ur=class e extends g{constructor(i){super(i),t(this,"onDisposed",new f),t(this,"onIfcStartedLoading",new f),t(this,"onIfcImporterInitialized",new f),t(this,"onSetup",new f),t(this,"settings",new dr),t(this,"webIfc",new p.IfcAPI),t(this,"enabled",!0),this.components.add(e.uuid,this)}dispose(){this.webIfc=null,this.onDisposed.trigger(e.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(Zn);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 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:e});return await s.core.load(o,{modelId:i,userData:null==n?void 0: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 p.IfcAPI}async autoSetWasm(){const e=await fetch(`https://unpkg.com/@thatopen/components@${$r.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.")}};t(ur,"uuid","a659add7-1418-4771-a0d6-7d4d438e4624");let pr=ur;const fr=class e extends g{constructor(i){super(i),t(this,"enabled",!0),this.components.add(e.uuid,this)}async set(e,t){const i=this.components.get(Zn),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(Zn);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(Zn);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}};t(fr,"uuid","dd9ccf2d-8a21-4821-b7f6-2949add16a29");let mr=fr;const gr=class e extends g{constructor(i){super(i),t(this,"enabled",!0),t(this,"onDisposed",new f),t(this,"list",new h.DataSet),this.components.add(e.uuid,this)}dispose(t=!0){this.list.clear(),this.onDisposed.trigger(e.uuid),t&&(this.onDisposed.reset(),this.list.eventsEnabled=!1,this.list.dispose())}get(){const e=new d.Box3;for(const t of this.list)e.union(t);return e}async addFromModelIdMap(e){const t=this.components.get(Zn),i=new d.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(Zn);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 d.Vector3;return t.getCenter(i),i}async getCameraOrientation(e,t=1){const i=this.components.get(Zn);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 d.Vector3;n.getCenter(s);const r=new d.Vector3;n.getSize(r);const o=Math.max(r.x,r.y,r.z)*t,a=new d.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}}};t(gr,"uuid","d1444724-dba6-4cdd-a0c7-68ee1450d166");let wr=gr;class yr{constructor(e,i){t(this,"name","Query"),t(this,"customData",{}),t(this,"_components"),t(this,"_queries",[]),t(this,"_aggregation","exclusive"),t(this,"result",null),t(this,"cache",!0),t(this,"serializeQueryParameters",e=>{var t;return{categories:null==(t=e.categories)?void 0:t.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}}),t(this,"deserializeQueryParameters",e=>{var t;return{categories:null==(t=e.categories)?void 0:t.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}}),this._components=e,this.queries=i}set queries(e){this._queries=e,this.clearCache()}get queries(){return this._queries}set aggregation(e){e!==this._aggregation&&this.clearCache(),this._aggregation=e}get aggregation(){return this._aggregation}async test(e){const{modelIds:t,force:i}={force:!1,...e};if(this.result&&!i)return this.result;const n=this._components.get(br),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}}toJSON(){return{guid:this._components.get(br).list.getKey(this)??T.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}}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}}const _r=class e extends g{constructor(i){super(i),t(this,"enabled",!0),t(this,"list",new h.DataMap),i.add(e.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=(null==t?void 0:t.aggregation)??"exclusive",s=this.components.get(Zn),r=await Promise.all(e.map(async e=>{const n={};return await Promise.all(Array.from(s.list).map(async([s,r])=>{var o;if(i&&!i.some(e=>e.test(s)))return;const a=null==(o=null==t?void 0:t.items)?void 0:o[s],l=await r.getItemsByQuery(e,{localIds:a?[...a]:void 0});n[s]=new Set(l)})),n}));return"inclusive"===n?Ue.join(r):Ue.intersect(r)}create(e,t){const i=new yr(this.components,t);return this.list.set(e,i),i}async addFromCategories(e){const t=new Set,i=this.components.get(Zn);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}}};t(_r,"uuid","0da7ad77-f734-42ca-942f-a074adfd1e3a");let br=_r;const vr=class e extends g{constructor(i){super(i),t(this,"enabled",!0),t(this,"onDisposed",new f),t(this,"list",new h.DataMap),t(this,"defaultSaveFunction",e=>"value"in e.Name?e.Name.value:null),t(this,"onBeforeFragmentsDispose",async e=>{const{key:t,value:i}=e,n=await i.getLocalIds(),s={[t]:new Set(n)};this.removeItems(s)}),i.add(e.uuid,this),this.setupEvents();i.get(Zn).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 h.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(br),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=Ue.join([t,s.map]);e(i)})}else e(s.map);else e({})})},n.set(t,s)),s}async aggregateItems(e,t,i){const n=(null==i?void 0:i.data)??void 0,s=(null==i?void 0:i.aggregationCallback)??this.defaultSaveFunction,r=this.components.get(Zn),o=this.components.get(br),a=await o.getItems([t],{modelIds:null==i?void 0: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);Ue.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=Ue.join(e);t.push(r)}return Ue.intersect(t)}async aggregateItemRelations(e,t,i,n){const s=(null==n?void 0:n.attribute)??"Name",r={relations:{[i]:{attributes:!0,relations:!1}}};await this.aggregateItems(e,t,{modelIds:null==n?void 0:n.modelIds,data:r,aggregationCallback:(e,t)=>{if(!(null==e?void 0: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((null==e?void 0:e.classificationName)??"Storeys",{categories:[/BUILDINGSTOREY/]},"ContainsElements",{modelIds:null==e?void 0:e.modelIds})}async byCategory(e){const t=this.components.get(br),i=await t.addFromCategories(null==e?void 0:e.modelIds);for(const t of i)this.setGroupQuery((null==e?void 0:e.classificationName)??"Categories",t,{name:t})}dispose(){this.list.clear();this.components.get(Zn).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)Ue.remove(t.map,e);return}for(const[,t]of this.list.entries())for(const[,i]of t)Ue.remove(i.map,e)}async byModel(e){const t=this.components.get(Zn),i=(null==e?void 0: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)}}};t(vr,"uuid","e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7");let xr=vr;class Sr{constructor(e,i){t(this,"enabled",!0),t(this,"components"),t(this,"onDisposed",new f),t(this,"mouse"),t(this,"world"),t(this,"debugMode",!1),t(this,"colorToModelId",new Map),t(this,"modelIdToColor",new Map),t(this,"renderTarget"),t(this,"renderTargetSize",new d.Vector2),t(this,"debugCanvas"),t(this,"debugContainer"),t(this,"colorMaterials",new Map),t(this,"originalMaterials",new Map),t(this,"originalLodColors",new Map),t(this,"colorsNeedUpdate",!0);const n=i.renderer;if(!n)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=i,this.mouse=new qe(n.three.domElement),this.components=e,this.setupRenderTarget(),this.setupFragmentListeners()}setupFragmentListeners(){const e=this.components.get(Zn);e.list.onItemSet.add(()=>{this.colorsNeedUpdate=!0}),e.list.onItemDeleted.add(()=>{this.colorsNeedUpdate=!0})}setupRenderTarget(){const e=this.world.renderer.three.getSize(new d.Vector2);this.renderTargetSize.copy(e),this.renderTarget=new d.WebGLRenderTarget(e.x,e.y),this.renderTarget.texture.format=d.RGBAFormat,this.renderTarget.texture.type=d.UnsignedByteType,this.debugMode&&this.setupDebugCanvas(),this.world.renderer.onResize.add(e=>{this.renderTargetSize.copy(e),this.renderTarget.setSize(e.x,e.y),this.debugCanvas&&(this.debugCanvas.width=e.x,this.debugCanvas.height=e.y)})}setupDebugCanvas(){if(this.debugCanvas)return;const e=this.world.renderer.three.getSize(new d.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)}generateColorForModel(e){let t=0;for(let i=0;i<e.length;i++)t=(t<<5)-t+e.charCodeAt(i),t&=t;let i=Math.abs(t)%16777215;0===i&&(i=1);const n=i>>16&255||1,s=i>>8&255||1,r=255&i||1;return new d.Color(n/255,s/255,r/255)}colorToId(e){return Math.round(255*e.r)<<16|Math.round(255*e.g)<<8|Math.round(255*e.b)}assignColors(){const e=this.components.get(Zn);if(e.initialized){if(!this.colorsNeedUpdate){const t=new Set(e.list.keys()),i=new Set(this.modelIdToColor.keys());(t.size!==i.size||[...t].some(e=>!i.has(e)))&&(this.colorsNeedUpdate=!0)}if(this.colorsNeedUpdate){this.colorToModelId.clear(),this.modelIdToColor.clear();for(const e of this.colorMaterials.values())e.dispose();this.colorMaterials.clear();for(const[t]of e.list){const e=this.generateColorForModel(t),i=this.colorToId(e);this.colorToModelId.set(i,t),this.modelIdToColor.set(t,e);const n=new d.MeshBasicMaterial({color:e,depthTest:!0,depthWrite:!0});this.colorMaterials.set(t,n)}this.colorsNeedUpdate=!1}}}applyColorMaterials(){const e=this.components.get(Zn);if(e.initialized)for(const[t,i]of e.list){const e=this.colorMaterials.get(t);e&&i.object.traverse(t=>{if(t instanceof d.Mesh){if("isLODGeometry"in t.geometry){const i=t.material[0].uniforms.lodColor;return this.originalLodColors.has(i)||this.originalLodColors.set(i,i.value),void(i.value=e.color)}this.originalMaterials.has(t)||this.originalMaterials.set(t,t.material),t.material=e}})}}restoreOriginalMaterials(){for(const[e,t]of this.originalMaterials)e.material=t;for(const[e,t]of this.originalLodColors)e.value=t;this.originalMaterials.clear()}renderColorCoded(){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const e=this.world.renderer.three,t=this.world.scene.three,i=this.world.camera.three,n=e.getRenderTarget(),s=e.autoClear,r=new d.Color,o=e.getClearAlpha();e.getClearColor(r),this.applyColorMaterials(),e.setRenderTarget(this.renderTarget),e.autoClear=!0,e.setClearColor(0,1),e.clear(!0,!0,!1),e.render(t,i),e.setRenderTarget(n),e.autoClear=s,e.setClearColor(r,o),this.restoreOriginalMaterials(),this.debugMode&&this.debugCanvas&&this.updateDebugCanvas()}updateDebugCanvas(){if(!this.debugCanvas||!this.renderTarget||!this.world.renderer)return;const e=this.world.renderer.three,t=this.renderTargetSize,i=new Uint8Array(t.x*t.y*4);e.readRenderTargetPixels(this.renderTarget,0,0,t.x,t.y,i);const n=this.debugCanvas.getContext("2d");if(!n)return;const s=n.createImageData(t.x,t.y),r=4*t.x;for(let e=0;e<t.y;e++){const n=e*r,o=(t.y-1-e)*r;s.data.set(i.subarray(n,n+r),o)}n.putImageData(s,0,0)}async getModelAt(e){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const t=this.components.get(Zn);if(!t.initialized||0===t.list.size)return null;this.assignColors(),this.renderColorCoded();const i=e||this.mouse.position,n=this.renderTargetSize,s=Math.floor(.5*(i.x+1)*n.x),r=Math.floor(.5*(i.y+1)*(n.y-1)),o=Math.max(0,Math.min(n.x-1,s)),a=Math.max(0,Math.min(n.y-1,r)),l=this.world.renderer.three,c=new Uint8Array(4);l.readRenderTargetPixels(this.renderTarget,o,a,1,1,c);const h=c[0]<<16|c[1]<<8|c[2];return this.colorToModelId.get(h)||null}setDebugMode(e){this.debugMode=e,e?this.setupDebugCanvas():this.removeDebugCanvas()}removeDebugCanvas(){this.debugContainer&&(this.debugContainer.remove(),this.debugContainer=void 0,this.debugCanvas=void 0)}dispose(){this.mouse.dispose(),this.removeDebugCanvas();for(const e of this.colorMaterials.values())e.dispose();this.colorMaterials.clear(),this.renderTarget&&this.renderTarget.dispose(),this.colorToModelId.clear(),this.modelIdToColor.clear(),this.originalMaterials.clear(),this.originalLodColors.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}}const Cr=class e extends g{constructor(i){super(i),t(this,"enabled",!0),t(this,"list",new Map),t(this,"onDisposed",new f),i.add(e.uuid,this)}get(e){if(this.list.has(e.uuid))return this.list.get(e.uuid);const t=new Sr(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()}};t(Cr,"uuid","4a82430c-7ff2-49ea-9401-60807502dad6");let Tr=Cr;class Ar{constructor(e,i){t(this,"enabled",!0),t(this,"components"),t(this,"onDisposed",new f),t(this,"mouse"),t(this,"three",new d.Raycaster),t(this,"world"),t(this,"useFastModelPicking",!1);const n=i.renderer;if(!n)throw new Error("A renderer is needed for the raycaster to work!");this.world=i,this.mouse=new qe(n.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=null==e?void 0:e.snappingClasses,i=(null==e?void 0:e.items)??Array.from(this.world.meshes),n=(null==e?void 0: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(Zn),o=this.world.renderer.three.domElement,a=this.mouse.rawPosition;let l=null;if(r.initialized){if(this.useFastModelPicking){const e=this.components.get(Tr).get(this.world),i=await e.getModelAt(n);if(i){const e=r.list.get(i);if(e)if(t&&t.length>0){const i=await e.raycastWithSnapping({camera:s,dom:o,mouse:a,snappingClasses:t});l=i&&i.length>0?i[0]:await e.raycast({camera:s,dom:o,mouse:a})}else l=await e.raycast({camera:s,dom:o,mouse:a})}}else l=await r.raycast({camera:s,dom:o,mouse:a,snappingClasses:t});if(0===i.length)return l}this.three.setFromCamera(n,s);const c=this.intersect(i);return l?c&&c.distance<l.distance?c:l:c}castRayFromVector(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||(null==i?void 0:i.length)<=0?e:e.filter(e=>i.every(t=>t.distanceToPoint(e.point)>0))}}const Er=class e extends g{constructor(i){super(i),t(this,"enabled",!0),t(this,"list",new Map),t(this,"onDisposed",new f),i.add(e.uuid,this)}get(e){if(this.list.has(e.uuid))return this.list.get(e.uuid);const t=new Ar(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()}};t(Er,"uuid","d5d8bdf0-db25-4952-b951-b643af207ace");let Mr=Er;class Pr extends m{constructor(){super(...arguments),t(this,"onCameraChanged",new f),t(this,"meshes",new Set),t(this,"onAfterUpdate",new f),t(this,"onBeforeUpdate",new f),t(this,"onDisposed",new f),t(this,"isDisposing",!1),t(this,"enabled",!0),t(this,"_dynamicAnchor",!1),t(this,"uuid",T.create()),t(this,"name"),t(this,"_scene"),t(this,"_camera"),t(this,"_renderer",null),t(this,"onPointerDown",async e=>{if(!this.camera.hasCameraControls())throw new Error("World: can't set dynamic anchor if the camera doesn't have controls.");const t=this.components.get(Mr).get(this),i=await t.castRay();i&&i.point&&0===e.button&&this.camera.controls.setOrbitPoint(i.point.x,i.point.y,i.point.z)}),t(this,"_defaultCamera")}set dynamicAnchor(e){var t;const i=null==(t=this.renderer)?void 0:t.three.domElement.parentElement;if(!i)throw new Error("World: the renderer must have a parentElement to set dynamic anchoring.");e?(this.camera.controls&&(this.camera.controls.minDistance=.01),i.addEventListener("pointerdown",this.onPointerDown)):i.removeEventListener("pointerdown",this.onPointerDown)}get dynamicAnchor(){return this._dynamicAnchor}get defaultCamera(){if(!this._defaultCamera)throw new Error("World: there is no default camera defined.");return this._defaultCamera}set defaultCamera(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.enabled=!1,this.isDisposing=!0,this.scene.onWorldChanged.trigger({world:this,action:"removed"}),this.camera.onWorldChanged.trigger({world:this,action:"removed"}),this.renderer&&this.renderer.onWorldChanged.trigger({world:this,action:"removed"}),e){const e=this.components.get(v);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(Lr).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class Ir{constructor(e,i){t(this,"_list"),t(this,"_scene"),this._list=e,this._scene=i}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 zr{constructor(e,i){t(this,"_list"),t(this,"_scene"),this._list=e,this._scene=i}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 Dr extends We{constructor(){super(...arguments),t(this,"_config",{backgroundColor:{value:new d.Color,type:"Color"},ambientLight:{color:{type:"Color",value:new d.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2}},directionalLight:{color:{type:"Color",value:new d.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2},position:{type:"Vector3",value:new d.Vector3}}}),t(this,"ambientLight",new zr(this._config,this._component)),t(this,"directionalLight",new Ir(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 kr extends x{constructor(e){super(e),t(this,"onSetup",new f),t(this,"isSetup",!1),t(this,"three"),t(this,"config",new Dr(this,this.components,"Scene")),t(this,"_defaultConfig",{backgroundColor:new d.Color(2107698),directionalLight:{color:new d.Color("white"),intensity:1.5,position:new d.Vector3(5,10,3)},ambientLight:{color:new d.Color("white"),intensity:1}}),this.three=new d.Scene,this.three.background=new d.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 d.DirectionalLight(s,r);o.position.copy(n.position);const{color:a,intensity:l}=this.config.directionalLight,c=new d.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(He).list.delete(this.config.uuid)}}var Br=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTO=1]="AUTO",e))(Br||{});class Or extends y{constructor(e){super(e),t(this,"onBeforeUpdate",new f),t(this,"onAfterUpdate",new f),t(this,"onAspectUpdated",new f),t(this,"onDisposed",new f),t(this,"three"),t(this,"_resizeObserver",null),t(this,"_allControls",new Map),t(this,"updateAspect",()=>{var e;if(this.currentWorld&&this.currentWorld.renderer)if(this.three instanceof d.OrthographicCamera)this.onAspectUpdated.trigger();else if(null==(e=this.currentWorld.renderer)?void 0:e.isResizeable()){const e=this.currentWorld.renderer.getSize();this.three.aspect=e.width/e.height,this.three.updateProjectionMatrix(),this.onAspectUpdated.trigger()}}),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})=>{var t;const i=this._allControls.get(e.uuid);i&&(i.dispose(),this._allControls.delete(e.uuid)),null==(t=this._resizeObserver)||t.disconnect()})}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}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);this.controls.setOrbitPoint(t.center.x,t.center.y,t.center.z)}update(e){this.enabled&&(this.onBeforeUpdate.trigger(this),this.controls.update(e),this.onAfterUpdate.trigger(this))}async getItemsBounding(e){const t=this.components.get(Zn),i=this.components.get(wr);i.list.clear();const n=new d.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 d.PerspectiveCamera(60,e,1,1e3);return t.position.set(50,50,50),t.lookAt(new d.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!");a.install({THREE:Or.getSubsetOfThree()});const{domElement:e}=this.currentWorld.renderer.three,t=new a(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:d.MOUSE,Vector2:d.Vector2,Vector3:d.Vector3,Vector4:d.Vector4,Quaternion:d.Quaternion,Matrix4:d.Matrix4,Spherical:d.Spherical,Box3:d.Box3,Sphere:d.Sphere,Raycaster:d.Raycaster,MathUtils:d.MathUtils}}}const Vr=class e extends g{constructor(n){super(n),t(this,"onAfterUpdate",new f),t(this,"onBeforeUpdate",new f),t(this,"onDisposed",new f),t(this,"list",new i.DataMap),t(this,"enabled",!0),n.add(e.uuid,this)}create(){const e=new Pr(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)}};t(Vr,"uuid","fdb61dc4-2ec1-4966-b83d-54ea795fad4a");let Lr=Vr;class Nr extends We{constructor(){super(...arguments),t(this,"_config",{visible:{value:!0,type:"Boolean"},color:{value:new d.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 Fr{constructor(e,i){t(this,"onDisposed",new f),t(this,"onSetup",new f),t(this,"isSetup",!1),t(this,"world"),t(this,"components"),t(this,"config"),t(this,"_defaultConfig",{visible:!0,color:new d.Color(12303291),primarySize:1,secondarySize:10,distance:500}),t(this,"three"),t(this,"_fade",3),t(this,"updateZoom",()=>{this.world.camera instanceof Or&&(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=e,this.config=new Nr(this,this.components,"Grid");const a=new d.PlaneGeometry(2,2,1,1),l=new d.ShaderMaterial({side:d.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 d.Mesh(a,l),this.three.frustumCulled=!1,i.scene.three.add(this.three),this.setupEvents(!0)}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}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(He).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(e){if(this.world.isDisposing)return;if(!(this.world.camera instanceof Or))return;const t=this.world.camera.controls;e?t.addEventListener("update",this.updateZoom):t.removeEventListener("update",this.updateZoom)}}const Rr=class e extends g{constructor(i){super(i),t(this,"list",new Map),t(this,"onDisposed",new f),t(this,"enabled",!0),i.add(e.uuid,this)}create(e){if(this.list.has(e.uuid))throw new Error("This world already has a grid!");const t=new Fr(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()}};t(Rr,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");let Ur=Rr;const jr=class e{constructor(){t(this,"onDisposed",new f),t(this,"list",new i.DataMap),t(this,"enabled",!1),t(this,"_clock"),t(this,"onInit",new f),t(this,"update",()=>{if(!this.enabled)return;const e=this._clock.getDelta();for(const[t,i]of this.list)i.enabled&&i.isUpdateable()&&i.update(e);requestAnimationFrame(this.update)}),this._clock=new d.Clock,e.setupBVH()}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.");T.validate(e),this.list.set(e,t)}get(e){var t;const i=e.uuid;if(!this.list.has(i)){const n=new e(this);return(null==(t=n.isDisposeable)?void 0:t.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[e,t]of this.list.entries())t.enabled=!0;this._clock.start(),this.update(),this.onInit.trigger()}dispose(){let e;this.enabled=!1;for(const[t,i]of this.list)i.enabled=!1,t!==Zn.uuid?i.isDisposeable()&&i.dispose():e=i;null==e||e.dispose(),this._clock.stop(),this.onDisposed.trigger()}static setupBVH(){d.BufferGeometry.prototype.computeBoundsTree=Gn,d.BufferGeometry.prototype.disposeBoundsTree=Hn,d.Mesh.prototype.raycast=$n,d.LineSegments.prototype.raycast=$n}};t(jr,"release","2.4.3");let $r=jr;class Wr{constructor(e){t(this,"enabled",!1),t(this,"id","FirstPerson"),this.camera=e}set(e){if(this.enabled=e,e){if("Perspective"!==this.camera.projection.current)return void this.camera.set("Orbit");this.setupFirstPersonCamera()}}setupFirstPersonCamera(){const e=this.camera.controls,t=new d.Vector3;e.distance--,e.getPosition(t),e.minDistance=1,e.maxDistance=1,e.distance=1,e.moveTo(t.x,t.y,t.z),e.truckSpeed=50,e.mouseButtons.wheel=a.ACTION.DOLLY,e.touches.two=a.ACTION.TOUCH_ZOOM_TRUCK}}class Gr{constructor(e){t(this,"enabled",!0),t(this,"id","Orbit"),this.camera=e,this.activateOrbitControls()}set(e){this.enabled=e,e&&this.activateOrbitControls()}activateOrbitControls(){const e=this.camera.controls;e.minDistance=1,e.maxDistance=300;const t=new d.Vector3;e.getPosition(t);const i=t.length();e.distance=i,e.truckSpeed=2;const{rotation:n}=this.camera.three,s=new d.Vector3(0,0,-1).applyEuler(n),r=t.addScaledVector(s,i);e.moveTo(r.x,r.y,r.z)}}class Hr{constructor(e){t(this,"enabled",!1),t(this,"id","Plan"),t(this,"mouseAction1"),t(this,"mouseAction2"),t(this,"mouseInitialized",!1),t(this,"defaultAzimuthSpeed"),t(this,"defaultPolarSpeed"),this.camera=e,this.defaultAzimuthSpeed=e.controls.azimuthRotateSpeed,this.defaultPolarSpeed=e.controls.polarRotateSpeed}set(e){this.enabled=e;const t=this.camera.controls;t.azimuthRotateSpeed=e?0:this.defaultAzimuthSpeed,t.polarRotateSpeed=e?0:this.defaultPolarSpeed,this.mouseInitialized||(this.mouseAction1=t.touches.one,this.mouseAction2=t.touches.two,this.mouseInitialized=!0),e?(t.mouseButtons.left=a.ACTION.TRUCK,t.touches.one=a.ACTION.TOUCH_TRUCK,t.touches.two=a.ACTION.TOUCH_ZOOM):(t.mouseButtons.left=a.ACTION.ROTATE,t.touches.one=this.mouseAction1,t.touches.two=this.mouseAction2)}}class qr{constructor(e){t(this,"onChanged",new f),t(this,"current","Perspective"),t(this,"camera"),t(this,"matchOrthoDistanceEnabled",!1),t(this,"_component"),t(this,"_previousDistance",-1),this._component=e,this.camera=e.three}async set(e){this.current!==e&&("Orthographic"===e?this.setOrthoCamera():await this.setPerspectiveCamera(),this.onChanged.trigger(this.camera))}async toggle(){const e="Perspective"===this.current?"Orthographic":"Perspective";await this.set(e)}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 e=this.getPerspectiveDims();if(!e)return;const{width:t,height:i}=e;this.setupOrthoCamera(i,t),this.camera=this._component.threeOrtho,this.current="Orthographic"}getPerspectiveDims(){const e=this._component.currentWorld;if(!e||!e.renderer)return null;const t=new d.Vector3;this._component.threePersp.getWorldDirection(t);const i=new d.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.atan(o.fov*(Math.PI/180)/2);return{width:a*r,height:a}}setupOrthoCamera(e,t){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=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.atan(e.fov*(Math.PI/180)/2))}async setPerspectiveCamera(){this._component.controls.mouseButtons.wheel=a.ACTION.DOLLY,this._component.controls.mouseButtons.middle=a.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=a.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 Zr extends Or{constructor(e){super(e),t(this,"projection"),t(this,"threeOrtho"),t(this,"threePersp"),t(this,"_userInputButtons",{}),t(this,"_frustumSize",50),t(this,"_navigationModes",new Map),t(this,"_mode",null),t(this,"previousSize",null),this.threePersp=this.three,this.threeOrtho=this.newOrthoCamera(),this.projection=new qr(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 Gr(this)),this._navigationModes.set("FirstPerson",new Wr(this)),this._navigationModes.set("Plan",new Hr(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(e){if(null!==this.mode&&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 d.Vector3(i,i,i),r=new d.Vector3(n,n,n);for(const t of e){const e=(new d.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 d.Box3(s,r),a=this.components.get(Zn);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 d.Vector3;o.getSize(l);const c=new d.Vector3;o.getCenter(c);const h=Math.max(l.x,l.y,l.z)*t,u=new d.Sphere(c,h);await this.controls.fitToSphere(u,!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 d.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(),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 Yr="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Xr(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Kr(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 Qr={exports:{}};
|
|
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",[])}updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(t,e,i){e.isLocal=i;const n=this.clippingPlanes.indexOf(e);t&&-1===n?this.clippingPlanes.push(e):!t&&n>-1&&this.clippingPlanes.splice(n,1),this.three.clippingPlanes=this.clippingPlanes.filter((t=>!t.isLocal))}}const 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]);else{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.",W(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}}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.",G(i[t]));if(void 0!==i[t][3]&&void 0===i[t][4])return j("InvalidAttr","Attribute '"+i[t][2]+"' is without value.",G(i[t]));if(void 0===i[t][3]&&!e.allowBooleanAttributes)return j("InvalidAttr","boolean attribute '"+i[t][2]+"' is not allowed.",G(i[t]));const s=i[t][2];if(!$(s))return j("InvalidAttr","Attribute '"+s+"' is an invalid name.",G(i[t]));if(Object.prototype.hasOwnProperty.call(n,s))return j("InvalidAttr","Attribute '"+s+"' is repeated.",G(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,e){const i=t.substring(0,e).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function G(t){return t.startIndex+t[1].length}const H={cent:"¢",pound:"£",curren:"¤",yen:"¥",euro:"€",dollar:"$",euro:"€",fnof:"ƒ",inr:"₹",af:"؋",birr:"ብር",peso:"₱",rub:"₽",won:"₩",yuan:"¥",cedil:"¸"},q={amp:"&",apos:"'",gt:">",lt:"<",quot:'"'},Z={nbsp:" ",copy:"©",reg:"®",trade:"™",mdash:"—",ndash:"–",hellip:"…",laquo:"«",raquo:"»",lsquo:"‘",rsquo:"’",ldquo:"“",rdquo:"”",bull:"•",para:"¶",sect:"§",deg:"°",frac12:"½",frac14:"¼",frac34:"¾"},Y=new Set("!?\\\\/[]$%{}^&*()<>|+");function X(t){if("#"===t[0])throw new Error(`[EntityReplacer] Invalid character '#' in entity name: "${t}"`);for(const e of t)if(Y.has(e))throw new Error(`[EntityReplacer] Invalid character '${e}' in entity name: "${t}"`);return t}function K(...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 Q="external",J="base",tt="all";const et=Object.freeze({allow:0,leave:1,remove:2,throw:3}),it=new Set([9,10,13]);class nt{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??Q)&&e!==Q?e===tt?new Set([tt]):e===J?new Set([J]):Array.isArray(e)?new Set(e):new Set([Q]):new Set([Q]),this._numericAllowed=t.numericAllowed??!0,this._baseMap=K(q,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:et.allow,nullLevel:et.remove};const e=1.1===t.xmlVersion?1.1:1,i=et[t.onNCR]??et.allow,n=et[t.nullNCR]??et.remove;return{xmlVersion:e,onLevel:i,nullLevel:Math.max(n,et.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))X(e);this._externalMap=K(t)}addExternalEntity(t,e){X(t),"string"==typeof e&&-1===e.indexOf("&")&&(this._externalMap[t]=e)}addInputEntities(t){this._totalExpansions=0,this._expandedLength=0,this._inputMap=K(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=Q);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=J}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(tt)||this._limitTiers.has(t)}_resolveName(t){return t in this._inputMap?{value:this._inputMap[t],tier:Q}:t in this._externalMap?{value:this._externalMap[t],tier:Q}:t in this._baseMap?{value:this._baseMap[t],tier:J}:void 0}_classifyNCR(t){return 0===t?this._ncrNullLevel:t>=55296&&t<=57343||1===this._ncrXmlVersion&&t>=1&&t<=31&&!it.has(t)?et.remove:-1}_applyNCRAction(t,e,i){switch(t){case et.allow:return String.fromCodePoint(i);case et.remove:return"";case et.leave:return;case et.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<et.remove)return;const s=-1===n?this._ncrOnLevel:Math.max(this._ncrOnLevel,n);return this._applyNCRAction(s,t,i)}}const st=t=>I.includes(t)?"__"+t:t,rt={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:st};function ot(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 at(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"}:at(!0)}const lt=function(t){const e=Object.assign({},rt,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&&ot(t,e);return null===e.onDangerousProperty&&(e.onDangerousProperty=st),e.processEntities=at(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 ct;ct="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class ht{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][ct]={startIndex:e})}static getMetaDataSymbol(){return ct}}class ut{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&&pt(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&&pt(t,"!ELEMENT",e)){e+=8;const{index:i}=this.readElementExp(t,e+1);e=i}else if(r&&pt(t,"!ATTLIST",e))e+=8;else if(r&&pt(t,"!NOTATION",e)){e+=9;const{index:i}=this.readNotationExp(t,e+1,this.suppressValidationErr);e=i}else{if(!pt(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=dt(t,e);for(;e<t.length&&!/\s/.test(t[e])&&'"'!==t[e]&&"'"!==t[e];)e++;let n=t.substring(i,e);if(ft(n),e=dt(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=dt(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let n=t.substring(i,e);!this.suppressValidationErr&&ft(n),e=dt(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=dt(t,e);let r=null,o=null;if("PUBLIC"===s)[e,r]=this.readIdentifierVal(t,e,"publicIdentifier"),'"'!==t[e=dt(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=dt(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=dt(t,e)]&&pt(t,"MPTY",e))e+=4;else if("A"===t[e]&&pt(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=dt(t,e);for(;e<t.length&&!/\s/.test(t[e]);)e++;let n=t.substring(i,e);for(ft(n),i=e=dt(t,e);e<t.length&&!/\s/.test(t[e]);)e++;let s=t.substring(i,e);if(!ft(s))throw new Error(`Invalid attribute name: "${s}"`);e=dt(t,e);let r="";if("NOTATION"===t.substring(e,e+8).toUpperCase()){if(r="NOTATION","("!==t[e=dt(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(),!ft(s))throw new Error(`Invalid notation name: "${s}"`);i.push(s),"|"===t[e]&&(e++,e=dt(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=dt(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 dt=(t,e)=>{for(;e<t.length&&/\s/.test(t[e]);)e++;return e};function pt(t,e,i){for(let n=0;n<e.length;n++)if(e[n]!==t[i+n+1])return!1;return!0}function ft(t){if(E(t))return t;throw new Error(`Invalid entity name ${t}`)}const mt=/^[-+]?0x[a-fA-F0-9]+$/,gt=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,wt={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0,infinity:"original"};function yt(t,e={}){if(e=Object.assign({},wt,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&&mt.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(_t);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=gt.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 _t=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;class bt{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 vt{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 xt{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 Ct{constructor(t={}){this.separator=t.separator||".",this.path=[],this.siblingStacks=[],this._pathStringCache=null,this._view=new xt(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 St(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 At(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 Pt{constructor(t,e){var i;this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.parseXml=Dt,this.parseTextData=Tt,this.resolveNameSpace=Mt,this.buildAttributesMap=It,this.isItStopNode=Ot,this.replaceEntitiesValue=kt,this.readStopNodeData=Ft,this.saveTextToParentTag=Bt,this.addChild=zt,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={...q};this.options.entityDecoder?this.entityDecoder=this.options.entityDecoder:("object"==typeof this.options.htmlEntities?n=this.options.htmlEntities:!0===this.options.htmlEntities&&(n={...Z,...H}),this.entityDecoder=new nt({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 Ct,this.readonlyMatcher=this.matcher.readOnly(),this.isCurrentNodeStopNode=!1,this.stopNodeExpressionsSet=new vt;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 bt(e)):e instanceof bt&&this.stopNodeExpressionsSet.add(e)}this.stopNodeExpressionsSet.seal()}}}function Tt(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 Rt(t,a.parseTagValue,a.numberParseOptions);return t.trim()===t?Rt(t,a.parseTagValue,a.numberParseOptions):t}}function Mt(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 Et=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function It(t,e,i,n=!1){const s=this.options;if(!0===n||!0!==s.ignoreAttributes&&"string"==typeof t){const n=M(t,Et),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=jt(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:Rt(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 Dt=function(t){t=t.replace(/\r\n?/g,"\n");const e=new ht("!xml");let i=e,n="";this.matcher.reset(),this.entityDecoder.reset(),this.entityExpansionCount=0,this.currentExpandedLength=0;const s=this.options,r=new ut(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=Vt(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=Ut(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=Nt(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 ht(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=Vt(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=Vt(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=Nt(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}=Ut(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=At(c),l!==e.tagname&&this.matcher.push(l,{},m),l!==h&&u&&(g=this.buildAttributesMap(h,this.matcher,l),g&&St(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 ht(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}=Ut(s.transformTagName,l,h,s));const t=new ht(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 ht(l);g&&(t[":@"]=g),this.addChild(i,t,this.readonlyMatcher,w),this.matcher.pop(),this.isCurrentNodeStopNode=!1,a=r.closeIndex;continue}{const t=new ht(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 zt(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 kt(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 Bt(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 Ot(){return 0!==this.stopNodeExpressionsSet.size&&this.matcher.matchesAny(this.stopNodeExpressionsSet)}function Vt(t,e,i,n){const s=t.indexOf(e,i);if(-1===s)throw new Error(n);return s+e.length-1}function Lt(t,e,i,n){const s=t.indexOf(e,i);if(-1===s)throw new Error(n);return s}function Nt(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 Ft(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=Lt(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=Vt(t,"?>",i+1,"StopNode is not closed.")}else if(33===r&&45===t.charCodeAt(i+2)&&45===t.charCodeAt(i+3)){i=Vt(t,"--\x3e",i+3,"StopNode is not closed.")}else if(33===r&&91===t.charCodeAt(i+2)){i=Vt(t,"]]>",i,"StopNode is not closed.")-2}else{const n=Nt(t,i,">");if(n){(n&&n.tagName)===e&&"/"!==n.tagExp[n.tagExp.length-1]&&s++,i=n.closeIndex}}}}function Rt(t,e,i){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&yt(t,i)}return void 0!==t?t:""}function Ut(t,e,i,n){if(t){const n=t(e);i===e&&(i=n),e=n}return{tagName:e=jt(e,n),tagExp:i}}function jt(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 $t=ht.getMetaDataSymbol();function Wt(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 Gt(t,e,i,n){return Ht(t,e,i,n)}function Ht(t,e,i,n){let s;const r={};for(let o=0;o<t.length;o++){const a=t[o],l=qt(a);if(void 0!==l&&l!==e.textNodeName){const t=Wt(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=Ht(a[l],e,i,n);const s=Yt(t,e);if(a[":@"]?Zt(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[$t]&&"object"==typeof t&&null!==t&&(t[$t]=a[$t]),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 qt(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const i=e[t];if(":@"!==i)return i}}function Zt(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 Yt(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 Xt{constructor(t){this.externalEntities={},this.options=lt(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.",W(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--),!E(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",j("InvalidTag",e,W(t,r))}const c=N(t,r);if(!1===c)return j("InvalidAttr","Attributes for '"+l+"' have open quote.",W(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,W(t,i+s.err.line));n=!0}else if(a){if(!c.tagClosed)return j("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",W(t,r));if(h.trim().length>0)return j("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",W(t,o));if(0===i.length)return j("InvalidTag","Closing tag '"+l+"' has not been opened.",W(t,o));{const e=i.pop();if(l!==e.tagName){let i=W(t,e.tagStartPos);return j("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",W(t,o))}0==i.length&&(s=!0)}}else{const a=R(h,e);if(!0!==a)return j(a.err.code,a.err.msg,W(t,r-h.length+a.err.line));if(!0===s)return j("InvalidXml","Multiple possible root nodes found.",W(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.",W(t,r));r=e}else if(!0===s&&!k(t[r]))return j("InvalidXml","Extra text at the end",W(t,r));"<"===t[r]&&r--}}}return n?1==i.length?j("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",W(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 Pt(this.options,this.externalEntities),n=i.parseXml(t);return this.options.preserveOrder||void 0===n?n:Gt(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 '
'");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}static getMetaDataSymbol(){return ht.getMetaDataSymbol()}}function Kt(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 bt(i)):i instanceof bt&&n.push(i)}return Qt(t,e,i,new Ct,n)}function Qt(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=re(i,e),i}return""}for(let a=0;a<t.length;a++){const l=t[a],c=ie(l);if(void 0===c)continue;const h=Jt(l[":@"],e);n.push(c,h);const u=se(n,s);if(c===e.textNodeName){let t=l[c];u||(t=e.tagValueProcessor(c,t),t=re(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=ne(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}${ne(l[":@"],e,u)}`;let f;f=u?te(l[c],e):Qt(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 Jt(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 te(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=ie(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=ee(s[":@"],e),n=te(s[r],e);n&&0!==n.length?i+=`<${r}${t}>${n}</${r}>`:i+=`<${r}${t}/>`}}}return i}function ee(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 ie(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 ne(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=re(r,e)),!0===r&&e.suppressBooleanAttributes?n+=` ${s.substr(e.attributeNamePrefix.length)}`:n+=` ${s.substr(e.attributeNamePrefix.length)}="${r}"`}return n}function se(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 re(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 oe={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:"&"},{regex:new RegExp(">","g"),val:">"},{regex:new RegExp("<","g"),val:"<"},{regex:new RegExp("'","g"),val:"'"},{regex:new RegExp('"',"g"),val:"""}],processEntities:!0,stopNodes:[],oneListGroup:!1,maxNestedTags:100,jPath:!0};function ae(t){if(this.options=Object.assign({},oe,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 bt(e)):e instanceof bt&&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=he),this.processTextOrObjNode=le,this.options.format?(this.indentate=ce,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function le(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 ce(t){return this.options.indentBy.repeat(t)}function he(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}ae.prototype.build=function(t){if(this.options.preserveOrder)return Kt(t,this.options);{Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t});const e=new Ct;return this.j2x(t,0,e).val}},ae.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}},ae.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+'"'},ae.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},ae.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},ae.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},ae.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}},ae.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`></${t}`,e},ae.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},ae.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}},ae.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 ue{}e(ue,"parser",new Xt({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(ue,"builder",new ae({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1}));class de{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=de.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=de.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=de.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 pe 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 fe{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 me{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(we).list.set(this.uuid,this)}get controls(){return fe.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(fe.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(fe.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 ge=class t extends g{constructor(n){super(n),e(this,"list",new i.DataMap),e(this,"enabled",!0),n.add(t.uuid,this)}};e(ge,"uuid","b8c764e0-6b24-4e77-9a32-35fa728ee5b4");let we=ge;class ye{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 _e=1.25,be=32,ve=Math.pow(2,-24),xe=Symbol("SKIP_GENERATION"),Ce={strategy:0,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[xe]:!1};function Se(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 Ae(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 Pe(t,e){e.set(t)}function Te(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 Me(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 Ee(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 Ie(t,e){return 65535===e[t+15]}function De(t,e){return e[t+6]}function ze(t,e){return e[t+14]}function ke(t){return t+8}function Be(t,e){return t+8*e[t+6]}function Oe(t,e){return e[t+7]}function Ve(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 Le=32,Ne=(t,e)=>t.candidate-e.candidate,Fe=new Array(Le).fill().map((()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0}))),Re=new Float32Array(6);class Ue{constructor(){this.boundingData=new Float32Array(6)}}let je,$e,We,Ge;const He=Math.pow(2,32);function qe(t){return"count"in t?1:1+qe(t.left)+qe(t.right)}function Ze(t,e,i){return je=new Float32Array(i),$e=new Uint32Array(i),We=new Uint16Array(i),Ge=new Uint8Array(i),Ye(t,e)}function Ye(t,e){const i=t/4,n=t/2,s="count"in e,r=e.boundingData;for(let t=0;t<6;t++)je[i+t]=r[t];if(s)return e.buffer?(Ge.set(new Uint8Array(e.buffer),t),t+e.buffer.byteLength):($e[i+6]=e.offset,We[n+14]=e.count,We[n+15]=65535,t+be);{const{left:n,right:s,splitAxis:r}=e;let o=Ye(t+be,n);const a=o/be-t/be;if(a>He)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return $e[i+6]=a,$e[i+7]=r,Ye(o,s)}}function Xe(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 Ue;return Ve(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=Ae(e),-1!==o&&(a=(e[o]+e[o+3])/2);else if(1===r)o=Ae(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=Ee(t);let l=_e*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)/Le;if(s<8){const e=[...Fe];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;Me(s,i,o)}e.sort(Ne);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?Me(n,i,r.rightCacheBounds):(Me(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=Ee(u)/r);let f=0;0!==h&&(f=Ee(d)/r);const m=1+_e*(p*c+f*h);m<l&&(o=t,l=m,a=n.candidate)}}else{for(let t=0;t<Le;t++){const e=Fe[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>=Le&&(s=31);const r=Fe[s];r.count++,Me(e,i,r.bounds)}const e=Fe[31];Pe(e.bounds,e.rightCacheBounds);for(let t=30;t>=0;t--){const e=Fe[t],i=Fe[t+1];Te(e.bounds,i.rightCacheBounds,e.rightCacheBounds)}let d=0;for(let e=0;e<31;e++){const i=Fe[e],n=i.count,c=i.bounds,h=Fe[e+1].rightCacheBounds;0!==n&&(0===d?Pe(c,Re):Te(c,Re,Re)),d+=n;let u=0,p=0;0!==d&&(u=Ee(Re)/r);const f=s-d;0!==f&&(p=Ee(h)/r);const m=1+_e*(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 Ue,o=n,a=w-n;i.left=r,Ve(e,o,a,r.boundingData,p),t(r,o,a,p,h+1);const l=new Ue,c=w,u=s-a;i.right=l,Ve(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 Ke(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=Xe(t,a,n.offset,n.count,e,o),r=qe(s),l=new i(be*r);return Ze(0,s,l),l}))}class Qe{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 Je{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 ti=new Je;let ei,ii;const ni=[],si=new Qe((()=>new n.Box3));function ri(t,e,i,n,s,r){ei=si.getPrimitive(),ii=si.getPrimitive(),ni.push(ei,ii),ti.setBuffer(t._roots[e]);const o=oi(0,t.geometry,i,n,s,r);ti.clearBuffer(),si.releasePrimitive(ei),si.releasePrimitive(ii),ni.pop(),ni.pop();const a=ni.length;return a>0&&(ii=ni[a-1],ei=ni[a-2]),o}function oi(t,e,i,n,s=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:c}=ti;let h=2*t;if(Ie(h,l)){const e=De(t,c),i=ze(h,l);return Se(t,a,ei),n(e,i,!1,o,r+t/8,ei)}{let h=function(t){const{uint16Array:e,uint32Array:i}=ti;let n=2*t;for(;!Ie(n,e);)n=2*(t=ke(t));return De(t,i)},u=function(t){const{uint16Array:e,uint32Array:i}=ti;let n=2*t;for(;!Ie(n,e);)n=2*(t=Be(t,i));return De(t,i)+ze(n,e)};const d=ke(t),p=Be(t,c);let f,m,g,w,y=d,_=p;if(s&&(g=ei,w=ii,Se(y,a,g),Se(_,a,w),f=s(g),m=s(w),m<f)){y=p,_=d;const t=f;f=m,m=t,g=w}g||(g=ei,Se(y,a,g));const b=i(g,Ie(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&&oi(y,e,i,n,s,r,o+1);if(v)return!0;w=ii,Se(_,a,w);const x=i(w,Ie(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&&oi(_,e,i,n,s,r,o+1);return!!C}}const ai=new ti.constructor,li=new ti.constructor,ci=new Qe((()=>new n.Box3)),hi=new n.Box3,ui=new n.Box3,di=new n.Box3,pi=new n.Box3;let fi=!1;function mi(t,e,i,n,s,r=0,o=0,a=0,l=0,c=null,h=!1){let u,d;h?(u=li,d=ai):(u=ai,d=li);const p=u.float32Array,f=u.uint32Array,m=u.uint16Array,g=d.float32Array,w=d.uint32Array,y=d.uint16Array,_=2*e,b=Ie(2*t,m),v=Ie(_,y);let x=!1;if(v&&b)x=h?s(De(e,w),ze(2*e,y),De(t,f),ze(2*t,m),l,o+e/8,a,r+t/8):s(De(t,f),ze(2*t,m),De(e,w),ze(2*e,y),a,r+t/8,l,o+e/8);else if(v){const c=ci.getPrimitive();Se(e,g,c),c.applyMatrix4(i);const u=ke(t),d=Be(t,f);Se(u,p,hi),Se(d,p,ui);const m=c.intersectsBox(hi),w=c.intersectsBox(ui);x=m&&mi(e,u,n,i,s,o,r,l,a+1,c,!h)||w&&mi(e,d,n,i,s,o,r,l,a+1,c,!h),ci.releasePrimitive(c)}else{const u=ke(e),d=Be(e,w);Se(u,g,di),Se(d,g,pi);const m=c.intersectsBox(di),y=c.intersectsBox(pi);if(m&&y)x=mi(t,u,i,n,s,r,o,a,l+1,c,h)||mi(t,d,i,n,s,r,o,a,l+1,c,h);else if(m)if(b)x=mi(t,u,i,n,s,r,o,a,l+1,c,h);else{const e=ci.getPrimitive();e.copy(di).applyMatrix4(i);const c=ke(t),d=Be(t,f);Se(c,p,hi),Se(d,p,ui);const m=e.intersectsBox(hi),g=e.intersectsBox(ui);x=m&&mi(u,c,n,i,s,o,r,l,a+1,e,!h)||g&&mi(u,d,n,i,s,o,r,l,a+1,e,!h),ci.releasePrimitive(e)}else if(y)if(b)x=mi(t,d,i,n,s,r,o,a,l+1,c,h);else{const e=ci.getPrimitive();e.copy(pi).applyMatrix4(i);const c=ke(t),u=Be(t,f);Se(c,p,hi),Se(u,p,ui);const m=e.intersectsBox(hi),g=e.intersectsBox(ui);x=m&&mi(d,c,n,i,s,o,r,l,a+1,e,!h)||g&&mi(d,u,n,i,s,o,r,l,a+1,e,!h),ci.releasePrimitive(e)}}return x}const gi=new n.Box3,wi=new Float32Array(6);class yi{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(t){Ke(this,t={...Ce,...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,wi,0);const[t,e,n,h,u,d]=wi;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,wi,0);const[t,e,r,o,a,l]=wi,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)*ve,i[m+2]=h,i[m+3]=p+(Math.abs(h)+p)*ve,i[m+4]=u,i[m+5]=f+(Math.abs(u)+f)*ve}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/be;for(let e=0;e<o;e++){const i=8*e;Ie(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=Ie(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=ke(r),a=Be(r,n),c=Oe(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/be-1;t>=0;t--){const e=8*t,i=2*e;if(Ie(i,s)){const t=De(e,n),o=ze(i,s);this.writePrimitiveRangeBounds(t,o,wi,0),r.set(wi,e)}else{const t=ke(e),i=Be(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=>{Se(0,new Float32Array(e),gi),t.union(gi)})),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=ri(this,t,i,n,e,l),a)break;l+=s.byteLength/be}return a}bvhcast(t,e,i){let{intersectsRanges:s}=i;return function(t,e,i,s){if(fi)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");fi=!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++){ai.setBuffer(r[t]),c=0;const e=ci.getPrimitive();Se(0,ai.float32Array,e),e.applyMatrix4(h);for(let t=0,n=o.length;t<n&&(li.setBuffer(o[t]),a=mi(0,0,i,h,s,l,c,0,0,e),li.clearBuffer(),c+=o[t].byteLength/be,!a);t++);if(ci.releasePrimitive(e),ai.clearBuffer(),l+=r[t].byteLength/be,a)break}return fi=!1,a}(this,t,e,s)}}function _i(t){return t.index?t.index.count:t.attributes.position.count}function bi(t){return _i(t)/3}function vi(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 xi(t,e,i){const n=function(t,e,i){const n=_i(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=_i(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 Ci extends yi{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={...Ce,...e})[xe]||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}(xi(e,t.range,i),t.useSharedArrayBuffer);this._indirectBuffer=n}else vi(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}]:xi(this.geometry,t,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Si{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}}Si.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 Ai=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}}(),Pi=function(){const t=new n.Vector2,e=new n.Vector3,i=new n.Vector3;return function(n,s,r,o){Ai(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))}}}(),Ti=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}}(),Mi=["x","y","z"],Ei=1e-15;function Ii(t){return Math.abs(t)<Ei}class Di 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 Si)),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 Ti(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<Ei?m<Ei||g<Ei?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(i)):m<Ei?g<Ei?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(t)):g<Ei&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(i),this.degenerateSegment.end.copy(e)),this.plane.setFromNormalAndCoplanarPoint(o,t),this.needsUpdate=!1}}Di.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]),Pi(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)}}(),Di.prototype.intersectsTriangle=function(){const t=new Di,e=new Si,i=new Si,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 Ii(o)?Ii(a)?p(t,e,i,n):(i&&(i.start.copy(r.start),i.end.copy(r.start)),t.containsPoint(r.start)):Ii(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!(!Ii(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(Ii(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)&&(!!Ii(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);Ii(b)&&(b=0),Ii(v)&&(v=0),Ii(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);Ii(A)&&(A=0),Ii(P)&&(P=0),Ii(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=Mi[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)}}(),Di.prototype.distanceToPoint=function(){const t=new n.Vector3;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),Di.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]),Pi(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 zi{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 Si)),this.alignedSatBounds=new Array(3).fill().map((()=>new Si)),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}}zi.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}}(),zi.prototype.intersectsBox=function(){const t=new Si;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}}(),zi.prototype.intersectsTriangle=function(){const t=new Di,e=new Array(3),i=new Si,s=new Si,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}}(),zi.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}}(),zi.prototype.distanceToPoint=function(){const t=new n.Vector3;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),zi.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];Pi(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 ki extends Qe{constructor(){super((()=>new Di))}}const Bi=new ki,Oi=new n.Vector3,Vi=new n.Vector3;const Li=parseInt(n.REVISION)>=169,Ni=parseInt(n.REVISION)<=161,Fi=new n.Vector3,Ri=new n.Vector3,Ui=new n.Vector3,ji=new n.Vector2,$i=new n.Vector2,Wi=new n.Vector2,Gi=new n.Vector3,Hi=new n.Vector3,qi=new n.Vector3,Zi=new n.Vector3;function Yi(t,e,i,s,r,o,a,l,c,h,u){Fi.fromBufferAttribute(e,o),Ri.fromBufferAttribute(e,a),Ui.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,Fi,Ri,Ui,Zi,c,h,u);if(d){if(s){ji.fromBufferAttribute(s,o),$i.fromBufferAttribute(s,a),Wi.fromBufferAttribute(s,l),d.uv=new n.Vector2;const t=n.Triangle.getInterpolation(Zi,Fi,Ri,Ui,ji,$i,Wi,d.uv);Li||(d.uv=t)}if(r){ji.fromBufferAttribute(r,o),$i.fromBufferAttribute(r,a),Wi.fromBufferAttribute(r,l),d.uv1=new n.Vector2;const t=n.Triangle.getInterpolation(Zi,Fi,Ri,Ui,ji,$i,Wi,d.uv1);Li||(d.uv1=t),Ni&&(d.uv2=d.uv1)}if(i){Gi.fromBufferAttribute(i,o),Hi.fromBufferAttribute(i,a),qi.fromBufferAttribute(i,l),d.normal=new n.Vector3;const e=n.Triangle.getInterpolation(Zi,Fi,Ri,Ui,Gi,Hi,qi,d.normal);d.normal.dot(t.direction)>0&&d.normal.multiplyScalar(-1),Li||(d.normal=e)}const e={a:o,b:a,c:l,normal:new n.Vector3,materialIndex:0};if(n.Triangle.getNormal(Fi,Ri,Ui,e.normal),d.face=e,d.faceIndex=o,Li){const t=new n.Vector3;n.Triangle.getBarycoord(Zi,Fi,Ri,Ui,t),d.barycoord=t}}return d}function Xi(t){return t&&t.isMaterial?t.side:t}function Ki(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=Yi(i,p,f,m,g,l,c,h,Xi(e[y]),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=y,!s)return t;s.push(t)}}}}else{const t=Yi(i,p,f,m,g,l,c,h,Xi(e),r,o);if(t){if(t.faceIndex=n,t.face.materialIndex=0,!s)return t;s.push(t)}}return null}function Qi(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 Ji(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,Qi(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}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(t,i,r=!1){const c=2*t;if(Ie(c,a)){const e=De(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+ze(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=ke(t),s=Be(t,o);let a=r,c=!1,h=!1;if(e){if(!a){const t=n/8+i/be,r=s/8+i/be;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 en(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 nn(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),Qi(o,3*t,l,c),o.needsUpdate=!0,n(o,t,s,r))return!0}return!1}function sn(t,e,i,n,s,r,o){ti.setBuffer(t._roots[e]),rn(0,t,i,n,s,r,o),ti.clearBuffer()}function rn(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=ti,h=2*t;if(Ie(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++)Ki(l,e,i,t,r,o,a)}(e,i,n,De(t,c),ze(h,l),s,r,o)}else{const l=ke(t);en(l,a,n,r,o)&&rn(l,e,i,n,s,r,o);const h=Be(t,c);en(h,a,n,r,o)&&rn(h,e,i,n,s,r,o)}}const on=["x","y","z"];function an(t,e,i,n,s,r){ti.setBuffer(t._roots[e]);const o=ln(0,t,i,n,s,r);return ti.clearBuffer(),o}function ln(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=ti;let c=2*t;if(Ie(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=Ki(a,e,i,t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,De(t,l),ze(c,a),s,r)}{const a=Oe(t,l),c=on[a],h=n.direction[c]>=0;let u,d;h?(u=ke(t),d=Be(t,l)):(u=Be(t,l),d=ke(t));const p=en(u,o,n,s,r)?ln(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=en(d,o,n,s,r)?ln(d,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const cn=new n.Box3,hn=new Di,un=new Di,dn=new n.Matrix4,pn=new zi,fn=new zi;function mn(t,e,i,n){ti.setBuffer(t._roots[e]);const s=gn(0,t,i,n);return ti.clearBuffer(),s}function gn(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=ti;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),pn.set(i.boundingBox.min,i.boundingBox.max,n),s=pn);if(!Ie(l,o)){const o=ke(t),l=Be(t,a);Se(o,r,cn);if(s.intersectsBox(cn)&&gn(o,e,i,n,s))return!0;Se(l,r,cn);return!!(s.intersectsBox(cn)&&gn(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,u=i.index,d=i.attributes.position,p=De(t,a),f=ze(l,o);if(dn.copy(n).invert(),i.boundsTree){Se(t,r,fn),fn.matrix.copy(dn),fn.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>fn.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(Qi(un,e,c,h),un.needsUpdate=!0,t.intersectsTriangle(un))return!0;return!1}})}{const t=bi(i);for(let e=3*p,i=3*(f+p);e<i;e+=3){Qi(hn,e,c,h),hn.a.applyMatrix4(dn),hn.b.applyMatrix4(dn),hn.c.applyMatrix4(dn),hn.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(Qi(un,e,u,d),un.needsUpdate=!0,hn.intersectsTriangle(un))return!0}}}}const wn=new n.Matrix4,yn=new zi,_n=new zi,bn=new n.Vector3,vn=new n.Vector3,xn=new n.Vector3,Cn=new n.Vector3;function Sn(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),yn.set(e.boundingBox.min,e.boundingBox.max,i),yn.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,u=e.index,d=Bi.getPrimitive(),p=Bi.getPrimitive();let f=bn,m=vn,g=null,w=null;s&&(g=xn,w=Cn);let y=1/0,_=null,b=null;return wn.copy(i).invert(),_n.matrix.copy(wn),t.shapecast({boundsTraverseOrder:t=>yn.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:(t,n)=>{if(e.boundsTree){return e.boundsTree.shapecast({boundsTraverseOrder:t=>_n.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,s)=>{for(let o=e,a=e+s;o<a;o++){Qi(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++){Qi(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=bi(e);s<o;s++){Qi(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++){Qi(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}}}}),Bi.releasePrimitive(d),Bi.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(wn),m.applyMatrix4(wn),s.distance=m.sub(s.point).length(),s.faceIndex=b),n)}function An(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(Ie(h,a)){const e=De(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+ze(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=ke(i),n=Be(i,o);let s=c,a=!1,h=!1;if(e){if(!s){const i=t/8+r/be,o=n/8+r/be;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 Pn(t,e,i,n,s,r,o){ti.setBuffer(t._roots[e]),Tn(0,t,i,n,s,r,o),ti.clearBuffer()}function Tn(t,e,i,n,s,r,o){const{float32Array:a,uint16Array:l,uint32Array:c}=ti,h=2*t;if(Ie(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++)Ki(l,e,i,c?c[t]:t,r,o,a)}(e,i,n,De(t,c),ze(h,l),s,r,o)}else{const l=ke(t);en(l,a,n,r,o)&&Tn(l,e,i,n,s,r,o);const h=Be(t,c);en(h,a,n,r,o)&&Tn(h,e,i,n,s,r,o)}}const Mn=["x","y","z"];function En(t,e,i,n,s,r){ti.setBuffer(t._roots[e]);const o=In(0,t,i,n,s,r);return ti.clearBuffer(),o}function In(t,e,i,n,s,r){const{float32Array:o,uint16Array:a,uint32Array:l}=ti;let c=2*t;if(Ie(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=Ki(a,e,i,l?l[t]:t,null,r,o),n&&n.distance<c&&(h=n,c=n.distance)}return h}(e,i,n,De(t,l),ze(c,a),s,r)}{const a=Oe(t,l),c=Mn[a],h=n.direction[c]>=0;let u,d;h?(u=ke(t),d=Be(t,l)):(u=Be(t,l),d=ke(t));const p=en(u,o,n,s,r)?In(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=en(d,o,n,s,r)?In(d,e,i,n,s,r):null;return p&&f?p.distance<=f.distance?p:f:p||f||null}}const Dn=new n.Box3,zn=new Di,kn=new Di,Bn=new n.Matrix4,On=new zi,Vn=new zi;function Ln(t,e,i,n){ti.setBuffer(t._roots[e]);const s=Nn(0,t,i,n);return ti.clearBuffer(),s}function Nn(t,e,i,n,s=null){const{float32Array:r,uint16Array:o,uint32Array:a}=ti;let l=2*t;null===s&&(i.boundingBox||i.computeBoundingBox(),On.set(i.boundingBox.min,i.boundingBox.max,n),s=On);if(!Ie(l,o)){const o=ke(t),l=Be(t,a);Se(o,r,Dn);if(s.intersectsBox(Dn)&&Nn(o,e,i,n,s))return!0;Se(l,r,Dn);return!!(s.intersectsBox(Dn)&&Nn(l,e,i,n,s))}{const s=e.geometry,c=s.index,h=s.attributes.position,u=i.index,d=i.attributes.position,p=De(t,a),f=ze(l,o);if(Bn.copy(n).invert(),i.boundsTree){Se(t,r,Vn),Vn.matrix.copy(Bn),Vn.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>Vn.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(Qi(kn,3*e.resolveTriangleIndex(i),c,h),kn.needsUpdate=!0,t.intersectsTriangle(kn))return!0;return!1}})}{const t=bi(i);for(let i=p,n=f+p;i<n;i++){const n=e.resolveTriangleIndex(i);Qi(zn,3*n,c,h),zn.a.applyMatrix4(Bn),zn.b.applyMatrix4(Bn),zn.c.applyMatrix4(Bn),zn.needsUpdate=!0;for(let e=0,i=3*t;e<i;e+=3)if(Qi(kn,e,u,d),kn.needsUpdate=!0,zn.intersectsTriangle(kn))return!0}}}}const Fn=new n.Matrix4,Rn=new zi,Un=new zi,jn=new n.Vector3,$n=new n.Vector3,Wn=new n.Vector3,Gn=new n.Vector3;function Hn(t,e,i,n={},s={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Rn.set(e.boundingBox.min,e.boundingBox.max,i),Rn.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,c=a.index,h=e.attributes.position,u=e.index,d=Bi.getPrimitive(),p=Bi.getPrimitive();let f=jn,m=$n,g=null,w=null;s&&(g=Wn,w=Gn);let y=1/0,_=null,b=null;return Fn.copy(i).invert(),Un.matrix.copy(Fn),t.shapecast({boundsTraverseOrder:t=>Rn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(Un.min.copy(t.min),Un.max.copy(t.max),Un.needsUpdate=!0),!0),intersectsRange:(n,s)=>{if(e.boundsTree){const a=e.boundsTree;return a.shapecast({boundsTraverseOrder:t=>Un.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);Qi(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);Qi(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=bi(e);o<a;o++){Qi(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);Qi(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}}}}),Bi.releasePrimitive(d),Bi.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 qn(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 Zn=new zi,Yn=new n.Ray,Xn=new n.Vector3,Kn=new n.Matrix4,Qn=new n.Vector3,Jn=["getX","getY","getZ"];class ts extends Ci{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/be;t<e;t++){const e=8*t;Ie(2*e,s)||(n[e+6]=n[e+6]/8-t)}}}(r));const a=new ts(e,{...i,[xe]:!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[Jn[t]](l),s=r[Jn[t]](c),o=r[Jn[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)*ve}}return i}raycastObject3D(t,e,i=[]){const{material:n}=t;if(void 0===n)return;Kn.copy(t.matrixWorld).invert(),Yn.copy(e.ray).applyMatrix4(Kn),Qn.setFromMatrixScale(t.matrixWorld),Xn.copy(Yn.direction).multiply(Qn);const s=Xn.length(),r=e.near/s,o=e.far/s;if(!0===e.firstHitOnly){let s=this.raycastFirst(Yn,n,r,o);s=qn(s,t,e),s&&i.push(s)}else{const s=this.raycast(Yn,n,r,o);for(let n=0,r=s.length;n<r;n++){const r=qn(s[n],t,e);r&&i.push(r)}}return i}refit(t=null){return(this.indirect?An:tn)(this,t)}raycast(t,e=n.FrontSide,i=0,s=1/0){const r=this._roots,o=[],a=this.indirect?Pn:sn;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?En:an;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?Ln:mn;for(let r=0,o=n.length;r<o&&(i=s(this,r,t,e),!i);r++);return i}shapecast(t){const e=Bi.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsTriangle,scratchPrimitive:e,iterate:this.indirect?nn:Ji});return Bi.releasePrimitive(e),i}bvhcast(t,e,i){let{intersectsRanges:n,intersectsTriangles:s}=i;const r=Bi.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?t=>{const e=this.resolveTriangleIndex(t);Qi(r,3*e,o,a)}:t=>{Qi(r,3*t,o,a)},c=Bi.getPrimitive(),h=t.geometry.index,u=t.geometry.attributes.position,d=t.indirect?e=>{const i=t.resolveTriangleIndex(e);Qi(c,3*i,h,u)}:t=>{Qi(c,3*t,h,u)};if(s){if(!(t instanceof ts))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 Zn.set(t.min,t.max,e),Zn.needsUpdate=!0,this.shapecast({intersectsBounds:t=>Zn.intersectsBox(t),intersectsTriangle:t=>Zn.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?Hn:Sn)(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=>(Oi.copy(e).clamp(t.min,t.max),Oi.distanceToSquared(e)),intersectsBounds:(t,e,i)=>i<a&&i<o,intersectsTriangle:(t,i)=>{t.closestPointToPoint(e,Oi);const n=e.distanceToSquared(Oi);return n<a&&(Vi.copy(Oi),a=n,l=i),n<r}}),a===1/0)return null;const c=Math.sqrt(a);return i.point?i.point.copy(Vi):i.point=Vi.clone(),i.distance=c,i.faceIndex=l,i}(this,t,e,i,n)}}const es=new n.Matrix4,is=new n.Ray,ns=new Qe((()=>new n.Line3)),ss=new n.Vector3,rs=new n.Vector3,os=new n.Box3,as=["getX","getY","getZ"];class ls extends Ci{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[as[t]](c),s=o[as[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=ns.getPrimitive(),i=super.shapecast({...t,intersectsPrimitive:t.intersectsLine,scratchPrimitive:e,iterate:cs});return ns.releasePrimitive(e),i}raycastObject3D(t,e,i=[]){const{matrixWorld:n}=t,{firstHitOnly:s}=e;es.copy(n).invert(),is.copy(e.ray).applyMatrix4(es);const r=e.params.Line.threshold/((t.scale.x+t.scale.y+t.scale.z)/3),o=r*r;let a=null,l=1/0;return this.shapecast({boundsTraverseOrder:t=>t.distanceToPoint(is.origin),intersectsBounds:t=>(os.copy(t).expandByScalar(Math.abs(r)),is.intersectsBox(os)?1:0),intersectsLine:(r,c)=>{if(is.distanceSqToSegment(r.start,r.end,ss,rs)>o)return;ss.applyMatrix4(t.matrixWorld);const h=e.ray.origin.distanceTo(ss);h<e.near||h>e.far||s&&h>=l||(l=h,c=this.resolvePrimitiveIndex(c),a={distance:h,point:rs.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 cs(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 hs={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},us=new n.Mesh,ds=[];function ps(t,e){if(this.isBatchedMesh)fs.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=hs.Mesh;else if(this instanceof n.LineSegments)i=hs.LineSegments;else if(this instanceof n.LineLoop)i=hs.LineLoop;else if(this instanceof n.Line)i=hs.Line;else{if(!(this instanceof n.Points))throw new Error("BVH: Fallback raycast function not found.");i=hs.Points}i.call(this,t,e)}}}function fs(t,e){if(this.boundsTrees){const i=this.boundsTrees,s=this._drawInfo||this._instanceInfo,r=this._drawRanges||this._geometryInfo,o=this.matrixWorld;us.material=this.material,us.geometry=this.geometry;const a=us.geometry.boundsTree,l=us.geometry.drawRange;null===us.geometry.boundingSphere&&(us.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(us.geometry.boundsTree=i[a],this.getMatrixAt(n,us.matrixWorld).premultiply(o),!us.geometry.boundsTree){this.getBoundingBoxAt(a,us.geometry.boundingBox),this.getBoundingSphereAt(a,us.geometry.boundingSphere);const t=r[a];us.geometry.setDrawRange(t.start,t.count)}us.raycast(t,ds);for(let t=0,i=ds.length;t<i;t++){const i=ds[t];i.object=this,i.batchId=n,e.push(i)}ds.length=0}us.geometry.boundsTree=a,us.geometry.drawRange=l,us.material=null,us.geometry=null}else hs.BatchedMesh.call(this,t,e)}function ms(t={}){const{type:e=ts}=t;return this.boundsTree=new e(this,t),this.boundsTree}function gs(){this.boundsTree=null}const ws=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(ws,"uuid","fef46874-46a3-461b-8c44-2922ab77c806");let ys=ws;function _s(t,e){return t[e]|t[e+1]<<8|t[e+2]<<16}class bs{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)),r.rotation.x=-Math.PI/2,r.far=o.max.y-o.min.y+r.near,r.position.y=o.max.y+r.near;const p=new n.Scene,f=new Map,m=new Map,g=[];for(let e=0;e<t.length;e++){const i=t[e];f.set(i,i.material),m.set(i,i.parent);const n=new vs;n.objectId=e,g.push(n),i.material=n,p.add(i)}const w=e.getClearColor(new n.Color),y=e.getClearAlpha(),_=e.getRenderTarget(),b=e.autoClear;e.autoClear=!0,e.setClearColor(0,0),e.setRenderTarget(a);const v=new Uint8Array(a.width*a.height*4),x=new Set,C=s.x/u,S=s.z/d;for(let i=0;i<u;i++)for(let n=0;n<d;n++){const s=o.min.x+C*i,l=s+C,c=o.min.z+S*n,h=(s+l)/2,u=(c+(c+S))/2;r.position.set(h,o.max.y,u);const d=C/2,f=S/2;r.left=-d,r.right=d,r.top=f,r.bottom=-f,r.updateProjectionMatrix(),e.render(p,r);const m=await e.readRenderTargetPixelsAsync(a,0,0,a.width,a.height,v);for(let e=0,i=m.length;e<i;e+=4){if(0===m[e+3])continue;const i=_s(m,e);x.add(t[i])}}for(const e of t){e.material=f.get(e);const t=m.get(e);t?t.add(e):p.remove(e)}e.setClearColor(w,y),e.setRenderTarget(_),e.autoClear=b;for(const t of g)t.dispose();return a.dispose(),Array.from(x)}}class vs 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,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 xs=1e-16,Cs=new n.Vector3(0,1,0),Ss=new n.Vector3;function As(t){return t.delta(Ss).normalize(),Math.abs(Ss.dot(Cs))>=1-xs}function Ps(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)<=xs&&(r=!0),!o&&n.distanceToSquared(e)<=xs&&(o=!0),r&&o)return!0}return r&&o}const Ts=new n.Line3;function Ms(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;Ts.start.lerpVectors(i,r,s[e][0]),Ts.end.lerpVectors(i,r,s[e][1]),n.push(new Float32Array([Ts.start.x,Ts.start.y,Ts.start.z,Ts.end.x,Ts.end.y,Ts.end.z]))}return n}const Es=new n.Vector3(0,1,0),Is=new n.Vector3,Ds=new n.Vector3,zs=new n.Vector3,ks=new n.Triangle;function*Bs(t,e=[],i={}){const{projectionDirection:s=Es,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}=ks;if(i.fromBufferAttribute(h,d[0]),r.fromBufferAttribute(h,d[1]),u.fromBufferAttribute(h,d[2]),ks.getNormal(zs),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=ks[p[t]],c=ks[p[i]],h=`${r}_${o}`,u=`${o}_${r}`;if(u in m&&m[u]){const t=m[u].normal,i=zs.dot(t)<=l;let r=!1;if(null!==s){let e=s.dot(zs);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:zs.clone()})}}for(const t in m)if(m[t]){const{index0:i,index1:s}=m[t];Is.fromBufferAttribute(h,i),Ds.fromBufferAttribute(h,s);const r=new n.Line3;r.start.copy(Is),r.end.copy(Ds),e.push(r)}return e}const Os=new n.Line3;function Vs(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++){Ls(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,Os,!0)||Ps(t,Os)||Ps(e,Os)||n.push(Os.clone())))}),n}function Ls(t,e){return t.distanceTo(e)<1e-10}function Ns(t){Fs(t);let e=[];return t.traverse((t=>{t.geometry&&t.visible&&e.push(t)})),e}const Fs=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):Fs(i)},Rs=new n.Matrix4,Us=new n.Matrix4;class js{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=Ns(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&&(Us.copy(n.matrixWorld).invert(),l.copy(s).transformDirection(Us).normalize());const h=yield*Bs(n.geometry,[],{projectionDirection:l,thresholdAngle:r,iterationTime:o});$s(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*Bs(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=Ns(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 ts(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);Rs.copy(l.matrixWorld).invert().multiply(c.matrixWorld);const d=Vs(h,u,Rs,[]);$s(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 ts(t,{maxLeafSize:1}):(i=t,t=i.geometry),Rs.identity(),Vs(i,i,Rs,e)}}}function $s(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 Ws extends yi{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 Gs=new n.Vector3(0,1,0),Hs=new n.Plane,qs=new n.Vector3,Zs=new n.Vector3;function Ys(t,e,i){t.needsUpdate&&t.update(),Hs.copy(t.plane),Hs.normal.dot(Gs)<0&&(Hs.normal.multiplyScalar(-1),Hs.constant*=-1);const s=Hs.distanceToPoint(e.start),r=Hs.distanceToPoint(e.end),o=Math.abs(s)<1e-16,a=s<0,l=r<0;if(e.delta(Zs).normalize(),Math.abs(Hs.normal.dot(Zs))<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,qs),a)return i.start.copy(e.start),i.end.copy(qs),!0;if(l)return i.end.copy(e.end),i.start.copy(qs),!0}return!1}const Xs=new n.Plane,Ks=new n.Vector3,Qs=new n.Vector3,Js=new Di,tr=new n.Line3,er=new n.Line3,ir=new n.Vector3,nr=new n.Vector3,sr=new n.Vector3;function rr(t,e,i=new n.Line3){if(Js.copy(e),Js.a.y=0,Js.b.y=0,Js.c.y=0,Js.update(),tr.copy(t),tr.start.y=0,tr.end.y=0,Js.getArea()<=1e-16)return null;const s=tr.distance();tr.delta(ir).divideScalar(s),nr.copy(ir).cross(Js.plane.normal).normalize(),Xs.setFromNormalAndCoplanarPoint(nr,tr.start);let r=0;const{points:o}=Js;for(let t=0;t<3;t++){const e=o[t],i=o[(t+1)%3],n=Xs.distanceToPoint(e),s=Xs.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);Ks.lerpVectors(e,i,t),c=!0}if((c&&!l||a)&&(a&&!c&&Ks.copy(e),0===r?er.start.copy(Ks):er.end.copy(Ks),r++,2===r))break}if(2===r){if(er.delta(sr).normalize(),ir.dot(sr)<0){const t=er.start;er.start=er.end,er.end=t}const e=0,n=Qs.subVectors(tr.end,tr.start).dot(ir),r=Qs.subVectors(er.start,tr.start).dot(ir),o=Qs.subVectors(er.end,tr.start).dot(ir);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 or=new n.Vector3,ar=new n.Vector3,lr=new n.Vector3;function cr(t,e,i){const n=function(t,e){t.delta(or),ar.subVectors(e.start,t.start),lr.subVectors(e.end,t.start);const i=or.length();let n=ar.length()/i,s=lr.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&&(hr(n,i),!0)}function hr(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 ur=new n.Vector3(0,1,0),dr=new n.Line3,pr=new n.Line3,fr=new Di;function mr(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}=fr;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),fr.needsUpdate=!0,fr.update(),c!==n.DoubleSide){if(fr.plane.normal.dot(ur)!==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),_=fr.plane.normal;let b=_.x,v=_.y,x=_.z,C=fr.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(Ps(fr,t))r&&r.triangleEdgeCulled++;else{if(n<y)dr.copy(t);else if(!Ys(fr,t,dr)){r&&r.planeTrimCulled++;continue}dr.distance()<1e-10?r&&r.distThresholdCulled++:rr(dr,fr,pr)?(r&&r.used++,cr(t,pr,s[i])):r&&r.noOverlapCulled++}}}}})}fr.update=()=>{fr.plane.setFromCoplanarPoints(...fr.points)};let gr=!1;const wr={},yr={};let _r=null,br=0,vr=0;const xr={get enabled(){return gr},set enabled(t){gr=t},reset(){for(const t in wr)delete wr[t];for(const t in yr)delete yr[t];_r=null,br=0,vr=0},setStat(t,e){yr[t]=e},startTotal(){gr&&(vr=performance.now())},startStep(t){gr&&(null!==_r&&this.endStep(),_r=t,br=performance.now())},endStep(){if(!gr||null===_r)return;const t=performance.now()-br;wr[_r]=t,_r=null},printSummary(){if(!gr)return;null!==_r&&this.endStep();const t=performance.now()-vr;console.log("\n=== Projection Summary ==="),console.log(`Total time: ${t.toFixed(1)}ms\n`);for(const[e,i]of Object.entries(wr)){const n=(i/t*100).toFixed(1);console.log(` ${e}: ${i.toFixed(1)}ms (${n}%)`)}if(Object.keys(yr).length>0){console.log("\n--- Stats ---");for(const[t,e]of Object.entries(yr))console.log(` ${t}: ${e}`)}console.log("")}},Cr=1e-5,Sr=1e-16,Ar=1e-16;function Pr(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 Tr=null;async function Mr(t,e,i,n,s=null){const o=await async function(){return null===Tr&&(Tr=new d.WebGPURenderer,await Tr.init()),Tr}();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");xr.enabled&&console.log("Number of meshes:",e.length),xr.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}}xr.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;xr.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){xr.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);xr.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*Sr)),(()=>{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(Cr)),S=b.not().and(x.not()),A=y.sub(w),P=r.abs(A).lessThan(r.float(Cr)),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(Cr)),(()=>{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(Cr)),W=N.dot(N).lessThanEqual(r.float(Cr)),G=F.dot(F).lessThanEqual(r.float(Cr)),H=R.dot(R).lessThanEqual(r.float(Cr)),q=U.dot(U).lessThanEqual(r.float(Cr)),Z=j.dot(j).lessThanEqual(r.float(Cr)),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(Cr)),(()=>{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*Sr)),(()=>{r.Continue()}));const ut=it.sub(et),dt=ut.dot(ut);r.If(dt.lessThan(r.float(Cr)),(()=>{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(Ar)),Pt=r.abs(St).lessThan(r.float(Ar)),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(Ar)),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(Ar)),(()=>{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)),xr.enabled&&console.log(` Batch ${i+1}: ${$} overlaps found (capacity: ${I})`),$>I&&xr.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]);hr([e[i+1],e[i+2]],n[s])}u+=performance.now()-i,xr.enabled&&console.log(` Processed ${s} overlaps into hiddenOverlapMap`)}else h+=performance.now()-U}o.dispose(),Tr=null;const m=p+f+c+h+u;xr.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 Er=new n.Vector3(0,1,0);function Ir(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 Dr{constructor(t,e=!0){this.meshes=Ns(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 Ir(this.visibleEdges,this.groupKeyToIndex?this.visibleGroupIndices:null)}getHiddenLineGeometry(){return Ir(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();xr.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 ts(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]=[];xr.startStep("Building line BVH");const h=new Ws(t,{maxLeafSize:2,strategy:2});xr.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?Pr(h,n.get(s.geometry),s,p,t):mr(h,n.get(s.geometry),s,c,u)}if(d){let t=!1;for(Mr(p,i,h,c,u).then((()=>{t=!0}));!t;)yield}const f=u.totalEdges*u.totalTriangles;if(xr.setStat("Total edges",u.totalEdges.toLocaleString()),xr.setStat("Total triangles",u.totalTriangles.toLocaleString()),xr.setStat("Brute-force pairs (edges × triangles)",f.toLocaleString()),xr.setStat("BVH candidate pairs",u.candidates.toLocaleString()),f>0&&xr.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||(xr.setStat("Rejected: back-face culling",u.backFaceCulled.toLocaleString()+" ("+e(u.backFaceCulled)+")"),xr.setStat("Rejected: Y-bounds (tri below edge)",u.yBoundsCulled.toLocaleString()+" ("+e(u.yBoundsCulled)+")"),xr.setStat("Rejected: XZ-bounds (no 2D overlap)",u.xzBoundsCulled.toLocaleString()+" ("+e(u.xzBoundsCulled)+")"),xr.setStat("Rejected: edge lies on triangle",u.triangleEdgeCulled.toLocaleString()+" ("+e(u.triangleEdgeCulled)+")"),xr.setStat("Rejected: line above tri plane",u.planeTrimCulled.toLocaleString()+" ("+e(u.planeTrimCulled)+")"),xr.setStat("Rejected: trimmed edge too small",u.distThresholdCulled.toLocaleString()+" ("+e(u.distThresholdCulled)+")"),xr.setStat("Rejected: no projected overlap",u.noOverlapCulled.toLocaleString()+" ("+e(u.noOverlapCulled)+")")),xr.setStat("Producing overlaps",u.used.toLocaleString()+" ("+e(u.used)+")")}xr.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(Ms(i,n,!1,s),Ms(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 zr{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(xr.reset(),xr.startTotal(),t.isBufferGeometry&&(t=new n.Mesh(t)),a){xr.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 js;c.iterationTime=i,c.thresholdAngle=s,c.projectionDirection.copy(Er),xr.startStep("Generating candidate edges"),o("Generating candidate edges");let h=[],u=l?[]:null;if(yield*c.getEdgesGenerator(t,h,u),r&&(xr.startStep("Generating intersection edges"),o("Generating intersection edges"),yield*c.getIntersectionEdgesGenerator(t,h,u)),xr.startStep("Pre-filtering edges"),o("Pre-filtering edges"),u){const t=[],e=[];for(let i=0;i<h.length;i++)As(h[i])||(t.push(h[i]),e.push(u[i]));h=t,u=e}else h=h.filter((t=>!As(t)));yield;const d=new Dr(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}),xr.printSummary(),d}}new n.Line3,new n.Line3,new n.Vector3;const kr=class t extends g{constructor(i){super(i),e(this,"enabled",!0),e(this,"onDisposed",new f),e(this,"generator",new zr),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(ys),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 ts(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 bs(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(kr,"uuid","f2e76c3a-8b1d-4d5e-9a3f-7c6b2d4e8f1a");let Br=kr;class Or{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 Vr=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 Or),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(ys);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@${ko.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(Vr,"uuid","a659add7-1418-4771-a0d6-7d4d438e4624");let Lr=Vr;const Nr=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(ys),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(ys);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(ys);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(Nr,"uuid","dd9ccf2d-8a21-4821-b7f6-2949add16a29");let Fr=Nr;const Rr=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(ys),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(ys);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(ys);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(Rr,"uuid","d1444724-dba6-4cdd-a0c7-68ee1450d166");let Ur=Rr;class jr{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(Wr),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(Wr).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 $r=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(ys),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?de.join(r):de.intersect(r)}create(t,e){const i=new jr(this.components,e);return this.list.set(t,i),i}async addFromCategories(t){const e=new Set,i=this.components.get(ys);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($r,"uuid","0da7ad77-f734-42ca-942f-a074adfd1e3a");let Wr=$r;const Gr=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(ys).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(Wr),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=de.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(ys),o=this.components.get(Wr),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);de.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=de.join(t);e.push(r)}return de.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(Wr),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(ys).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)de.remove(e.map,t)}else for(const[,e]of this.list.entries())for(const[,i]of e)de.remove(i.map,t)}async byModel(t){const e=this.components.get(ys),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(Gr,"uuid","e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7");let Hr=Gr;const qr=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",[]),!i.renderer)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=i,this.mouse=new ye(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(ys).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(ys);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(ys);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(ys);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(ys),i=new Map;let n=1;for(const[s,r]of e.list){if(n>t.MAX_MODELS)break;const e=n;n+=1;let o=!1;r.object.traverse((t=>{if(!(t instanceof u.Mesh))return;const e=t.geometry;e&&(e.attributes&&e.attributes.id?(this._originalMaterials.set(t,t.material),t.material=this._idMaterial,o=!0):t.visible&&(this._hiddenLods.push(t),t.visible=!1))})),o&&i.set(e,s)}return i}renderIdPass(t,e){this.renderPickPass(t,this._renderTarget,this._idMaterial,e)}renderPickPass(t,e,i,n){const s=this.world.renderer.three,r=this.world.scene.three,o=this.world.camera.three,a=this.components.get(ys),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);s.setRenderTarget(e),s.setClearColor(0,0),s.autoClear=!1,s.setScissorTest(!1),s.clear(!0,!0,!1);const g=e.width,w=e.height,y=Math.floor(.5*(n.x+1)*g),_=Math.floor(.5*(n.y+1)*(w-1)),b=Math.max(0,Math.min(g-4,y-2)),v=Math.max(0,Math.min(w-4,_-2));s.setScissor(b,v,4,4),s.setScissorTest(!0);const x=new Map;for(const[t,e]of a.list)x.set(t,e.object);const C=new Set(x.values()),S=new Map;r.traverse((t=>{t!==r&&t.isMesh&&((t=>{let e=t;for(;e;){if(C.has(e))return!0;e=e.parent}return!1})(t)||(S.set(t,t.visible),t.visible=!1))}));const A=new Map;for(const t of x.values())A.set(t,t.visible),t.visible=!1;for(const[e,n]of t){const t=x.get(n);t&&(t.visible=!0,i.uniforms.modelByte.value=e,s.render(r,o),t.visible=!1)}for(const[t,e]of A)t.visible=e;for(const[t,e]of S)t.visible=e;s.setScissorTest(f),s.setScissor(m),s.setRenderTarget(c),s.autoClear=h,s.setClearColor(d,p)}renderWithTileMaterial(t){const e=this.world.renderer.three,i=this.world.scene.three,n=this.world.camera.three,s=this.components.get(ys),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=new Map,d=[];for(const[,e]of s.list)e.object.traverse((e=>{if(!(e instanceof u.Mesh))return;const i=e.geometry;i&&(i.attributes&&i.attributes.id?e.visible&&(h.set(e,e.material),e.material=t):e.visible&&(d.push(e),e.visible=!1))}));const p=new Set;for(const[,t]of s.list)p.add(t.object);const f=new Map;i.traverse((t=>{t!==i&&t.isMesh&&((t=>{let e=t;for(;e;){if(p.has(e))return!0;e=e.parent}return!1})(t)||(f.set(t,t.visible),t.visible=!1))})),e.setRenderTarget(this._renderTarget),e.setClearColor(0,0),e.autoClear=!1,e.clear(!0,!0,!1),e.render(i,n);for(const[t,e]of h)t.material=e;for(const t of d)t.visible=!0;for(const[t,e]of f)t.visible=e;e.setRenderTarget(o),e.autoClear=a,e.setClearColor(l,c)}renderDepthPass(){this.renderWithTileMaterial(this._depthMaterial)}renderNormalPass(){this.renderWithTileMaterial(this._normalMaterial)}restoreOriginalMaterials(){for(const[t,e]of this._originalMaterials)t.material=e;this._originalMaterials.clear();for(const t of this._hiddenLods)t.visible=!0;this._hiddenLods.length=0}readPixelAt(t,e){let i,n;t instanceof 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(qr,"MAX_MODELS",254);let Zr=qr;const Yr=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 Zr(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(Yr,"uuid","4a82430c-7ff2-49ea-9401-60807502dad6");let Xr=Yr;var Kr=(t=>(t[t.POINT=0]="POINT",t[t.LINE=1]="LINE",t[t.FACE=2]="FACE",t))(Kr||{});const Qr=1e3;class Jr{constructor(t){e(this,"onDisposed",new f),e(this,"maxDistance",1),e(this,"maxCacheSize",1e3),e(this,"components"),e(this,"cache",new Map),this.components=t}dispose(){this.cache.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}async resolve(t,e,i,n){const s=Jr.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=Jr.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=Jr.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(ys).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=ao(s,n.globalTransforms[e.item],a);this.collectPolygonsFromShell(o,l,r)}if(0===r.length)return null;return{faces:r,edges:function(t){const e=new Set,i=[];for(const n of t){const t=n.points,s=t.length/3;for(let n=0;n<s;n++){const r=(n+1)%s,o=t[3*n],a=t[3*n+1],l=t[3*n+2],c=t[3*r],h=t[3*r+1],u=t[3*r+2],d=ho(o,a,l,c,h,u);e.has(d)||(e.add(d),i.push(o,a,l,c,h,u))}}return new Float32Array(i)}(r),vertices:function(t){const e=new Set,i=[];for(const n of t){const t=n.points,s=t.length/3;for(let n=0;n<s;n++){const s=t[3*n],r=t[3*n+1],o=t[3*n+2],a=co(s,r,o);e.has(a)||(e.add(a),i.push(s,r,o))}}return new Float32Array(i)}(r)}}collectPolygonsFromShell(t,e,i){const n=t.points,s=t.profiles??new Map,r=t.bigProfiles??new Map,o=new u.Vector3,a=t=>{if(t.length<3)return;const s=new Float32Array(3*t.length);for(let i=0;i<t.length;i++){const r=n[t[i]];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=uo(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;for(const e of i){const i=e.normal.x*t.x+e.normal.y*t.y+e.normal.z*t.z-e.d,r=Math.abs(i);r<=this.maxDistance&&r<s&&(s=r,n=e)}if(!n)return null;return{result:{point:t.clone().sub(n.normal.clone().multiplyScalar(n.normal.x*t.x+n.normal.y*t.y+n.normal.z*t.z-n.d)),normal:n.normal.clone(),snappingClass:2,facePoints:n.points,faceIndices:lo(n.points.length/3)}}}}const to=new u.Matrix4,eo=new u.Vector3,io=new u.Vector3,no=new u.Vector3;function so(t,e){if(!t)return e.identity();const i=t.position[0],n=t.position[1],s=t.position[2];return eo.set(t.xDirection[0],t.xDirection[1],t.xDirection[2]),io.set(t.yDirection[0],t.yDirection[1],t.yDirection[2]),no.crossVectors(eo,io),e.set(eo.x,io.x,no.x,i,eo.y,io.y,no.y,n,eo.z,io.z,no.z,s,0,0,0,1),e}const ro=new u.Matrix4,oo=new u.Matrix4;function ao(t,e,i){return so(e,ro),so(i,oo),to.copy(t).multiply(ro).multiply(oo).clone()}function lo(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 co(t,e,i){return`${Math.round(t*Qr)},${Math.round(e*Qr)},${Math.round(i*Qr)}`}function ho(t,e,i,n,s,r){const o=co(t,e,i),a=co(n,s,r);return o<a?`${o}|${a}`:`${a}|${o}`}function uo(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 po=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 Jr(i)}get(){return this._resolver}dispose(){this._resolver.dispose(),this.onDisposed.trigger()}};e(po,"uuid","be9b8e6c-7f5b-4a36-8e7e-3a1f5e2a6c9d");let fo=po;class mo{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 ye(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(ys);let o=null;if(r.initialized){const t=this.components.get(Xr).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(fo).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 go=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 mo(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(go,"uuid","d5d8bdf0-db25-4952-b951-b643af207ace");let wo=go;class yo 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,"uuid",A.create()),e(this,"name"),e(this,"_scene"),e(this,"_camera"),e(this,"_renderer",null),e(this,"onPointerDown",(async t=>{if(!this.camera.hasCameraControls())throw new Error("World: can't set dynamic anchor if the camera doesn't have controls.");const e=this.components.get(wo).get(this),i=await e.castRay();i&&i.point&&0===t.button&&this.camera.controls.setOrbitPoint(i.point.x,i.point.y,i.point.z)})),e(this,"_defaultCamera")}set dynamicAnchor(t){var e;const i=null==(e=this.renderer)?void 0:e.three.domElement.parentElement;if(!i)throw new Error("World: the renderer must have a parentElement to set dynamic anchoring.");t?(this.camera.controls&&(this.camera.controls.minDistance=.01),i.addEventListener("pointerdown",this.onPointerDown)):i.removeEventListener("pointerdown",this.onPointerDown)}get dynamicAnchor(){return this._dynamicAnchor}get defaultCamera(){if(!this._defaultCamera)throw new Error("World: there is no default camera defined.");return this._defaultCamera}set defaultCamera(t){this._defaultCamera=t}get scene(){if(!this._scene)throw new Error("No scene initialized!");return this._scene}set scene(t){this._scene=t,t.worlds.set(this.uuid,this),t.currentWorld=this,t.onWorldChanged.trigger({world:this,action:"added"})}get camera(){if(!this._camera)throw new Error("No camera initialized!");return this._camera}set camera(t){this._camera||(this.defaultCamera=t),this._camera=t,t.currentWorld=this,this.onCameraChanged.trigger(t)}get renderer(){return this._renderer}set renderer(t){this._renderer=t,t&&(t.worlds.set(this.uuid,this),t.currentWorld=this,t.onWorldChanged.trigger({world:this,action:"added"}))}useDefaultCamera(){this.camera=this.defaultCamera}update(t){this.enabled&&this._scene&&this._camera&&(this.scene.currentWorld=this,this.camera.currentWorld=this,this.renderer&&(this.renderer.currentWorld=this),this.onBeforeUpdate.trigger(),this.scene.isUpdateable()&&this.scene.update(t),this.camera.isUpdateable()&&this.camera.update(t),this.renderer&&this.renderer.update(t),this.onAfterUpdate.trigger())}dispose(t=!0){if(this.enabled=!1,this.isDisposing=!0,this.scene.onWorldChanged.trigger({world:this,action:"removed"}),this.camera.onWorldChanged.trigger({world:this,action:"removed"}),this.renderer&&this.renderer.onWorldChanged.trigger({world:this,action:"removed"}),t){const t=this.components.get(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(To).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class _o{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 bo{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 vo extends me{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 bo(this._config,this._component)),e(this,"directionalLight",new _o(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 xo extends x{constructor(t){super(t),e(this,"onSetup",new f),e(this,"isSetup",!1),e(this,"three"),e(this,"config",new vo(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(we).list.delete(this.config.uuid)}}const Co='\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 So=(t=>(t[t.MANUAL=0]="MANUAL",t[t.AUTO=1]="AUTO",t))(So||{});class Ao 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(ys),i=this.components.get(Ur);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:Ao.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 Po=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 yo(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(Po,"uuid","fdb61dc4-2ec1-4966-b83d-54ea795fad4a");let To=Po;class Mo extends me{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 Eo{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 Ao&&(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 Mo(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(we).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 Ao))return;const e=this.world.camera.controls;t?e.addEventListener("update",this.updateZoom):e.removeEventListener("update",this.updateZoom)}}const Io=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 Eo(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(Io,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");let Do=Io;const zo=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;this.enabled=!1;for(const[e,i]of this.list)i.enabled=!1,e!==ys.uuid?i.isDisposeable()&&i.dispose():t=i;null==t||t.dispose(),this._timer.dispose(),this.onDisposed.trigger()}static setupBVH(){u.BufferGeometry.prototype.computeBoundsTree=ms,u.BufferGeometry.prototype.disposeBoundsTree=gs,u.Mesh.prototype.raycast=ps,u.LineSegments.prototype.raycast=ps}};e(zo,"release","2.4.3");let ko=zo;class Bo{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 Oo{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 Vo{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 Lo{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 No extends Ao{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 Lo(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 Oo(this)),this._navigationModes.set("FirstPerson",new Bo(this)),this._navigationModes.set("Plan",new Vo(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(ys);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 Fo="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Ro(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}function Uo(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 jo={exports:{}};
|
|
2
2
|
/*!
|
|
3
3
|
|
|
4
4
|
JSZip v3.10.1 - A JavaScript class for generating and reading zip files
|
|
@@ -9,4 +9,4 @@ Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/js
|
|
|
9
9
|
|
|
10
10
|
JSZip uses the library pako released under the MIT license :
|
|
11
11
|
https://github.com/nodeca/pako/blob/main/LICENSE
|
|
12
|
-
*/const Jr=Xr(Qr.exports=function e(t,i,n){function s(o,a){if(!i[o]){if(!t[o]){if(!a&&Kr)return Kr(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=Kr,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=[],d=0,u=e.length,p=u,f="string"!==n.getTypeOf(e);d<e.length;)p=u-d,s=f?(t=e[d++],i=d<u?e[d++]:0,d<u?e[d++]:0):(t=e.charCodeAt(d++),i=d<u?e.charCodeAt(d++):0,d<u?e.charCodeAt(d++):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,d="data:";if(e.substr(0,d.length)===d)throw new Error("Invalid base64 input, it looks like a data url.");var u,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(u=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++))),u[h++]=t,64!==a&&(u[h++]=i),64!==l&&(u[h++]=n);return u}},{"./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 d,u,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,S="",C="",T="",A=p.dir,E=p.date,M={crc32:0,compressedSize:0,uncompressedSize:0};t&&!i||(M.crc32=e.crc32,M.compressedSize=e.compressedSize,M.uncompressedSize=e.uncompressedSize);var P=0;t&&(P|=8),m||!v&&!x||(P|=2048);var I,z,D,k=0,B=0;A&&(k|=16),"UNIX"===o?(B=798,k|=(I=p.unixPermissions,z=A,D=I,I||(D=z?16893:33204),(65535&D)<<16)):(B=20,k|=function(e){return 63&(e||0)}(p.dosPermissions)),d=E.getUTCHours(),d<<=6,d|=E.getUTCMinutes(),d<<=5,d|=E.getUTCSeconds()/2,u=E.getUTCFullYear()-1980,u<<=4,u|=E.getUTCMonth()+1,u<<=5,u|=E.getUTCDate(),v&&(C=n(1,1)+n(l(g),4)+w,S+="up"+n(C.length,2)+C),x&&(T=n(1,1)+n(l(_),4)+b,S+="uc"+n(T.length,2)+T);var O="";return O+="\n\0",O+=n(P,2),O+=f.magic,O+=n(d,2),O+=n(u,2),O+=n(M.crc32,4),O+=n(M.compressedSize,4),O+=n(M.uncompressedSize,4),O+=n(g.length,2),O+=n(S.length,2),{fileRecord:c.LOCAL_FILE_HEADER+O+g+S,dirRecord:c.CENTRAL_FILE_HEADER+n(B,2)+O+n(_.length,2)+"\0\0\0\0"+n(k,4)+n(s,4)+g+S+_}}var r=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,d=this.bytesWritten-e,u=(i=this.dirRecords.length,s=d,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:u,meta:{percent:100}})},h.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},h.prototype.registerPrevious=function(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 d="string"===s&&!1===a.binary&&!1===a.base64;i&&void 0!==i.binary||(a.binary=!d),(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:u.isNode&&u.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"),d=e("./generate"),u=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=d.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 d(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)}}d.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=d},{"../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 d(e,t){for(var i=0;i<e.length;i++)t[i]=e[i];return t}i.applyFromCharCode=h;var u={};u.string={string:a,array:function(e){return l(e,new Array(e.length))},arraybuffer:function(e){return u.string.uint8array(e).buffer},uint8array:function(e){return l(e,new Uint8Array(e.length))},nodebuffer:function(e){return l(e,r.allocBuffer(e.length))}},u.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)}},u.arraybuffer={string:function(e){return h(new Uint8Array(e))},array:function(e){return d(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))}},u.uint8array={string:h,array:function(e){return d(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:a,nodebuffer:function(e){return r.newBufferFrom(e)}},u.nodebuffer={string:h,array:function(e){return d(e,new Array(e.length))},arraybuffer:function(e){return u.nodebuffer.uint8array(e).buffer},uint8array:function(e){return d(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 u[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,d=i.getTypeOf(t);return d?("arraybuffer"===d?t=i.transformTo("uint8array",t):"string"===d&&(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.")},d=0;d<c.length;d++)n.prototype[c[d]]=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!==Yr?Yr:"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 d(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 u(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?d(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){d(this.promise,this.onFulfilled,e)},h.prototype.callRejected=function(e){r.reject(this.promise,e)},h.prototype.otherCallRejected=function(e){d(this.promise,this.onRejected,e)},r.resolve=function(e,t){var i=f(u,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,d=0,u=8;function p(e){if(!(this instanceof p))return new p(e);this.options=s.assign({level:h,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:d,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 d(e){if(!(this instanceof d))return new d(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 u(e,t){var i=new d(t);if(i.push(e,!0),i.err)throw i.msg||a[i.err];return i.result}d.prototype.push=function(e,t){var i,a,l,c,d,u,p=this.strm,f=this.options.chunkSize,m=this.options.dictionary,g=!1;if(this.ended)return!1;a=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&&(u="string"==typeof m?r.string2buf(m):"[object ArrayBuffer]"===h.call(m)?new Uint8Array(m):m,i=n.inflateSetDictionary(this.strm,u)),i===o.Z_BUF_ERROR&&!0===g&&(i=o.Z_OK,g=!1),i!==o.Z_STREAM_END&&i!==o.Z_OK)return this.onEnd(i),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&i!==o.Z_STREAM_END&&(0!==p.avail_in||a!==o.Z_FINISH&&a!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(l=r.utf8border(p.output,p.next_out),c=p.next_out-l,d=r.buf2string(p.output,l),p.next_out=c,p.avail_out=f-c,c&&s.arraySet(p.output,p.output,l,c,0),this.onData(d)):this.onData(s.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((0<p.avail_in||0===p.avail_out)&&i!==o.Z_STREAM_END);return i===o.Z_STREAM_END&&(a=o.Z_FINISH),a===o.Z_FINISH?(i=n.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===o.Z_OK):a!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),!(p.avail_out=0))},d.prototype.onData=function(e){this.chunks.push(e)},d.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=d,i.inflate=u,i.inflateRaw=function(e,t){return(t=t||{}).raw=!0,u(e,t)},i.ungzip=u},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(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,d=0,u=-2,p=-1,f=4,m=2,g=8,w=9,y=286,_=30,b=19,v=2*y+1,x=15,S=3,C=258,T=C+S+1,A=42,E=113,M=1,P=2,I=3,z=4;function D(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-T?e.strstart-(e.w_size-T):0,c=e.window,h=e.w_mask,d=e.prev,u=e.strstart+C,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<u);if(n=C-(u-r),r=u-C,o<n){if(e.match_start=t,a<=(o=n))break;p=c[r+o-1],f=c[r+o]}}}while((t=d[t&h])>l&&0!=--s);return o<=e.lookahead?o:e.lookahead}function R(e){var t,i,n,r,l,c,h,d,u,p,f=e.w_size;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=f+(f-T)){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,d=e.strstart+e.lookahead,p=void 0,(u=r)<(p=c.avail_in)&&(p=u),i=0===p?0:(c.avail_in-=p,s.arraySet(h,c.input,c.next_in,p,d),1===c.state.wrap?c.adler=o(c.adler,h,p,d):2===c.state.wrap&&(c.adler=a(c.adler,h,p,d)),c.next_in+=p,c.total_in+=p,p),e.lookahead+=i,e.lookahead+e.insert>=S)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+S-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<S)););}while(e.lookahead<T&&0!==e.strm.avail_in)}function U(e,t){for(var i,n;;){if(e.lookahead<T){if(R(e),e.lookahead<T&&t===c)return M;if(0===e.lookahead)break}if(i=0,e.lookahead>=S&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+S-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-T&&(e.match_length=F(e,i)),e.match_length>=S)if(n=r._tr_tally(e,e.strstart-e.match_start,e.match_length-S),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=S){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+S-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<S-1?e.strstart:S-1,t===h?(V(e,!0),0===e.strm.avail_out?I:z):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?M:P}function j(e,t){for(var i,n,s;;){if(e.lookahead<T){if(R(e),e.lookahead<T&&t===c)return M;if(0===e.lookahead)break}if(i=0,e.lookahead>=S&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+S-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=S-1,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-T&&(e.match_length=F(e,i),e.match_length<=5&&(1===e.strategy||e.match_length===S&&4096<e.strstart-e.match_start)&&(e.match_length=S-1)),e.prev_length>=S&&e.match_length<=e.prev_length){for(s=e.strstart+e.lookahead-S,n=r._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-S),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+S-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=S-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<S-1?e.strstart:S-1,t===h?(V(e,!0),0===e.strm.avail_out?I:z):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?M:P}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 G(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?A:E,e.adler=2===t.wrap?0:1,t.last_flush=c,r._tr_init(t),d):D(e,u)}function H(e){var t,i=G(e);return i===d&&((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=S-1,t.match_available=0,t.ins_h=0),i}function q(e,t,i,n,r,o){if(!e)return u;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 D(e,u);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+S-1)/S),l.window=new s.Buf8(2*l.w_size),l.head=new s.Buf16(l.hash_size),l.prev=new s.Buf16(l.w_size),l.lit_bufsize=1<<r+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new s.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=t,l.strategy=o,l.method=i,H(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-T&&(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:z):(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=H,i.deflateResetKeep=G,i.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?u:(e.state.gzhead=t,d):u},i.deflate=function(e,t){var i,s,o,l;if(!e||!e.state||5<t||t<0)return e?D(e,u):u;if(s=e.state,!e.output||!e.input&&0!==e.avail_in||666===s.status&&t!==h)return D(e,0===e.avail_out?-5:u);if(s.strm=e,i=s.last_flush,s.last_flush=t,s.status===A)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=E);else{var p=g+(s.w_bits-8<<4)<<8;p|=(2<=s.strategy||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(p|=32),p+=31-p%31,s.status=E,N(s,p),0!==s.strstart&&(N(s,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=E)):s.status=E),0!==s.pending){if(O(e),0===e.avail_out)return s.last_flush=-1,d}else if(0===e.avail_in&&k(t)<=k(i)&&t!==h)return D(e,-5);if(666===s.status&&0!==e.avail_in)return D(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:z):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?M:P}(s,t):3===s.strategy?function(e,t){for(var i,n,s,o,a=e.window;;){if(e.lookahead<=C){if(R(e),e.lookahead<=C&&t===c)return M;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=S&&0<e.strstart&&(n=a[s=e.strstart-1])===a[++s]&&n===a[++s]&&n===a[++s]){o=e.strstart+C;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=C-(o-s),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=S?(i=r._tr_tally(e,1,e.match_length-S),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:z):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?M:P}(s,t):n[s.level].func(s,t);if(f!==I&&f!==z||(s.status=666),f===M||f===I)return 0===e.avail_out&&(s.last_flush=-1),d;if(f===P&&(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,d}return t!==h?d: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?d:1)},i.deflateEnd=function(e){var t;return e&&e.state?(t=e.state.status)!==A&&69!==t&&73!==t&&91!==t&&103!==t&&t!==E&&666!==t?D(e,u):(e.state=null,t===E?D(e,-3):d):u},i.deflateSetDictionary=function(e,t){var i,n,r,a,l,c,h,p,f=t.length;if(!e||!e.state)return u;if(2===(a=(i=e.state).wrap)||1===a&&i.status!==A||i.lookahead)return u;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>=S;){for(n=i.strstart,r=i.lookahead-(S-1);i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+S-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++,--r;);i.strstart=n,i.lookahead=S-1,R(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=S-1,i.match_available=0,e.next_in=c,e.input=h,e.avail_in=l,i.wrap=a,d},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(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,d,u,p,f,m,g,w,y,_,b,v,x,S,C,T,A;i=e.state,n=e.next_in,T=e.input,s=n+(e.avail_in-5),r=e.next_out,A=e.output,o=r-(t-e.avail_out),a=r+(e.avail_out-257),l=i.dmax,c=i.wsize,h=i.whave,d=i.wnext,u=i.window,p=i.hold,f=i.bits,m=i.lencode,g=i.distcode,w=(1<<i.lenbits)-1,y=(1<<i.distbits)-1;e:do{f<15&&(p+=T[n++]<<f,f+=8,p+=T[n++]<<f,f+=8),_=m[p&w];t:for(;;){if(p>>>=b=_>>>24,f-=b,0==(b=_>>>16&255))A[r++]=65535&_;else{if(!(16&b)){if(!(64&b)){_=m[(65535&_)+(p&(1<<b)-1)];continue 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+=T[n++]<<f,f+=8),v+=p&(1<<b)-1,p>>>=b,f-=b),f<15&&(p+=T[n++]<<f,f+=8,p+=T[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+=T[n++]<<f,(f+=8)<b&&(p+=T[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(C=u,(S=0)===d){if(S+=c-b,b<v){for(v-=b;A[r++]=u[S++],--b;);S=r-x,C=A}}else if(d<b){if(S+=c+d-b,(b-=d)<v){for(v-=b;A[r++]=u[S++],--b;);if(S=0,d<v){for(v-=b=d;A[r++]=u[S++],--b;);S=r-x,C=A}}}else if(S+=d-b,b<v){for(v-=b;A[r++]=u[S++],--b;);S=r-x,C=A}for(;2<v;)A[r++]=C[S++],A[r++]=C[S++],A[r++]=C[S++],v-=3;v&&(A[r++]=C[S++],1<v&&(A[r++]=C[S++]))}else{for(S=r-x;A[r++]=A[S++],A[r++]=A[S++],A[r++]=A[S++],2<(v-=3););v&&(A[r++]=A[S++],1<v&&(A[r++]=A[S++]))}break}}break}}while(n<s&&r<a);n-=v=f>>3,p&=(1<<(f-=v<<3))-1,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,d=-2,u=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=u,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):d}function y(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,w(e)):d}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)?d:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,y(e))):d}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):d}var v,x,S=!0;function C(e){if(S){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}),S=!1}e.lencode=v,e.lenbits=9,e.distcode=x,e.distbits=5}function T(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,S,A,E,M,P,I,z,D,k,B,O,V,L,N,F=0,R=new n.Buf8(4),U=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return d;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,S=_,V=h;e:for(;;)switch(i.mode){case u: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<(A=i.length)&&(A=y),A&&(i.head&&(O=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),n.arraySet(i.head.extra,p,g,A,O)),512&i.flags&&(i.check=r(i.check,p,A,g)),y-=A,g+=A,i.length-=A),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===y)break e;for(A=0;O=p[g+A++],i.head&&O&&i.length<65536&&(i.head.name+=String.fromCharCode(O)),O&&A<y;);if(512&i.flags&&(i.check=r(i.check,p,A,g)),y-=A,g+=A,O)break 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(A=0;O=p[g+A++],i.head&&O&&i.length<65536&&(i.head.comment+=String.fromCharCode(O)),O&&A<y;);if(512&i.flags&&(i.check=r(i.check,p,A,g)),y-=A,g+=A,O)break 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(C(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(A=i.length){if(y<A&&(A=y),_<A&&(A=_),0===A)break e;n.arraySet(f,p,g,A,w),y-=A,g+=A,_-=A,w+=A,i.length-=A;break}i.mode=12;break;case 17:for(;v<14;){if(0===y)break 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,z=65535&F,!((P=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(z<16)b>>>=P,v-=P,i.lens[i.have++]=z;else{if(16===z){for(N=P+2;v<N;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(b>>>=P,v-=P,0===i.have){e.msg="invalid bit length repeat",i.mode=30;break}O=i.lens[i.have-1],A=3+(3&b),b>>>=2,v-=2}else if(17===z){for(N=P+3;v<N;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}v-=P,O=0,A=3+(7&(b>>>=P)),b>>>=3,v-=3}else{for(N=P+7;v<N;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}v-=P,O=0,A=11+(127&(b>>>=P)),b>>>=7,v-=7}if(i.have+A>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=30;break}for(;A--;)i.lens[i.have++]=O}}if(30===i.mode)break;if(0===i.lens[256]){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,S),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,z=65535&F,!((P=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(I&&!(240&I)){for(D=P,k=I,B=z;I=(F=i.lencode[B+((b&(1<<D+k)-1)>>D)])>>>16&255,z=65535&F,!(D+(P=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}b>>>=D,v-=D,i.back+=D}if(b>>>=P,v-=P,i.back+=P,i.length=z,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,z=65535&F,!((P=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(!(240&I)){for(D=P,k=I,B=z;I=(F=i.distcode[B+((b&(1<<D+k)-1)>>D)])>>>16&255,z=65535&F,!(D+(P=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}b>>>=D,v-=D,i.back+=D}if(b>>>=P,v-=P,i.back+=P,64&I){e.msg="invalid distance code",i.mode=30;break}i.offset=z,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(A=S-_,i.offset>A){if((A=i.offset-A)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=30;break}E=A>i.wnext?(A-=i.wnext,i.wsize-A):i.wnext-A,A>i.length&&(A=i.length),M=i.window}else M=f,E=w-i.offset,A=i.length;for(_<A&&(A=_),_-=A,i.length-=A;f[w++]=M[E++],--A;);0===i.length&&(i.mode=21);break;case 26:if(0===_)break 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(S-=_,e.total_out+=S,i.total+=S,S&&(e.adler=i.check=i.flags?r(i.check,f,S,w-S):s(i.check,f,S,w-S)),S=_,(i.flags?b:m(b))!==i.check){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 d}return e.next_out=w,e.avail_out=_,e.next_in=g,e.avail_in=y,i.hold=b,i.bits=v,(i.wsize||S!==e.avail_out&&i.mode<30&&(i.mode<27||4!==t))&&T(e,e.output,e.next_out,S-e.avail_out)?(i.mode=31,-4):(x-=e.avail_in,S-=e.avail_out,e.total_in+=x,e.total_out+=S,i.total+=S,i.wrap&&S&&(e.adler=i.check=i.flags?r(i.check,f,S,e.next_out-S):s(i.check,f,S,e.next_out-S)),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===S||4===t)&&V===h&&(V=-5),V)},i.inflateEnd=function(e){if(!e||!e.state)return d;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):d},i.inflateSetDictionary=function(e,t){var i,n=t.length;return e&&e.state?0!==(i=e.state).wrap&&11!==i.mode?d:11===i.mode&&s(1,t,n,0)!==i.check?-3:T(e,t,n,n)?(i.mode=31,-4):(i.havedict=1,h):d},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(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,d,u){var p,f,m,g,w,y,_,b,v,x=u.bits,S=0,C=0,T=0,A=0,E=0,M=0,P=0,I=0,z=0,D=0,k=null,B=0,O=new n.Buf16(16),V=new n.Buf16(16),L=null,N=0;for(S=0;S<=15;S++)O[S]=0;for(C=0;C<l;C++)O[t[i+C]]++;for(E=x,A=15;1<=A&&0===O[A];A--);if(A<E&&(E=A),0===A)return c[h++]=20971520,c[h++]=20971520,u.bits=1,0;for(T=1;T<A&&0===O[T];T++);for(E<T&&(E=T),S=I=1;S<=15;S++)if(I<<=1,(I-=O[S])<0)return-1;if(0<I&&(0===e||1!==A))return-1;for(V[1]=0,S=1;S<15;S++)V[S+1]=V[S]+O[S];for(C=0;C<l;C++)0!==t[i+C]&&(d[V[t[i+C]]++]=C);if(y=0===e?(k=L=d,19):1===e?(k=s,B-=257,L=r,N-=257,256):(k=o,L=a,-1),S=T,w=h,P=C=D=0,m=-1,g=(z=1<<(M=E))-1,1===e&&852<z||2===e&&592<z)return 1;for(;;){for(_=S-P,v=d[C]<y?(b=0,d[C]):d[C]>y?(b=L[N+d[C]],k[B+d[C]]):(b=96,0),p=1<<S-P,T=f=1<<M;c[w+(D>>P)+(f-=p)]=_<<24|b<<16|v,0!==f;);for(p=1<<S-1;D&p;)p>>=1;if(0!==p?(D&=p-1,D+=p):D=0,C++,0==--O[S]){if(S===A)break;S=t[i+d[C]]}if(E<S&&(D&g)!==m){for(0===P&&(P=E),w+=T,I=1<<(M=S-P);M+P<A&&!((I-=O[M+P])<=0);)M++,I<<=1;if(z+=1<<M,1===e&&852<z||2===e&&592<z)return 1;c[m=D&g]=E<<24|M<<16|w-h}}return 0!==D&&(c[w+D]=S-P<<24|64<<16),u.bits=E,0}},{"../utils/common":41}],51:[function(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,d=30,u=19,p=2*h+1,f=15,m=16,g=7,w=256,y=16,_=17,b=18,v=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],x=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],S=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],C=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],T=new Array(2*(h+2));o(T);var A=new Array(2*d);o(A);var E=new Array(512);o(E);var M=new Array(256);o(M);var P=new Array(l);o(P);var I,z,D,k=new Array(d);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?E[e]:E[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<d;t++)e.dyn_dtree[2*t]=0;for(t=0;t<u;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 G(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 H(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-=P[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--)G(e,r,i);for(s=l;i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],G(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++,G(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,d=t.stat_desc.has_stree,u=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=u[n-m]),a=l[2*n],e.opt_len+=a*(r+o),d&&(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(P[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++)E[s++]=n;for(s>>=7;n<d;n++)for(k[n]=s<<7,e=0;e<1<<x[n]-7;e++)E[256+s++]=n;for(t=0;t<=f;t++)r[t]=0;for(e=0;e<=143;)T[2*e+1]=8,e++,r[8]++;for(;e<=255;)T[2*e+1]=9,e++,r[9]++;for(;e<=279;)T[2*e+1]=7,e++,r[7]++;for(;e<=287;)T[2*e+1]=8,e++,r[8]++;for(U(T,h+1,r),e=0;e<d;e++)A[2*e+1]=5,A[2*e]=R(e,5);I=new B(T,v,c+1,h,f),z=new B(A,x,0,d,f),D=new B(new Array(0),S,0,u,g)}(),X=!0),e.l_desc=new O(e.dyn_ltree,I),e.d_desc=new O(e.dyn_dtree,z),e.bl_desc=new O(e.bl_tree,D),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=u-1;3<=t&&0===e.bl_tree[2*C[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),H(e,T,A)):(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*C[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),H(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,T),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(){u(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){u(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(){u(e),t.onreadystatechange=null,n.removeChild(t),t=null},n.appendChild(t)}):function(e){setTimeout(u,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=d}function d(e){delete a[e]}function u(e){if(l)setTimeout(u,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{d(e),l=!1}}}}function p(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(r)&&u(+t.data.slice(r.length))}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,void 0!==Yr?Yr:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10));class eo{constructor(e,i){t(this,"date",new Date),t(this,"author"),t(this,"guid",T.create()),t(this,"viewpoint"),t(this,"modifiedAuthor"),t(this,"modifiedDate"),t(this,"topic"),t(this,"_components"),t(this,"_comment",""),this._components=e,this._comment=i;const n=this._components.get(oo);this.author=n.config.author}set comment(e){var t;const i=this._components.get(oo);this._comment=e,this.modifiedDate=new Date,this.modifiedAuthor=i.config.author,null==(t=this.topic)||t.comments.set(this.guid,this)}get comment(){return this._comment}toJSON(){var e,t;const i={guid:this.guid,date:this.date.toISOString(),author:this.author,comment:this.comment,topic_guid:null==(e=this.topic)?void 0:e.guid,viewpoint_guid:this.viewpoint,modified_date:null==(t=this.modifiedDate)?void 0:t.toISOString(),modified_author:this.modifiedAuthor};for(const[e,t]of Object.entries(i))void 0===t&&delete i[e];return i}}const to=class e{constructor(n){t(this,"guid",T.create()),t(this,"title",e.default.title),t(this,"creationDate",new Date),t(this,"creationAuthor",""),t(this,"viewpoints",new i.DataSet),t(this,"relatedTopics",new i.DataSet),t(this,"comments",new i.DataMap),t(this,"documentReferences",new i.DataSet),t(this,"customData",{}),t(this,"description"),t(this,"serverAssignedId"),t(this,"dueDate"),t(this,"modifiedAuthor"),t(this,"modifiedDate"),t(this,"index"),t(this,"_type",e.default.type),t(this,"_status",e.default.status),t(this,"_priority",e.default.priority),t(this,"_stage",e.default.stage),t(this,"_assignedTo",e.default.assignedTo),t(this,"_labels",e.default.labels??new Set),t(this,"_components"),this._components=n;const s=n.get(oo);this.creationAuthor=s.config.author,this.relatedTopics.guard=e=>e!==this.guid}set type(e){const t=this._components.get(oo),{strict:i,types:n}=t.config;(!i||n.has(e))&&(this._type=e)}get type(){return this._type}set status(e){const t=this._components.get(oo),{strict:i,statuses:n}=t.config;(!i||n.has(e))&&(this._status=e)}get status(){return this._status}set priority(e){const t=this._components.get(oo);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}set stage(e){const t=this._components.get(oo);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}set assignedTo(e){const t=this._components.get(oo);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}set labels(e){const t=this._components.get(oo),{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}get _managerVersion(){return this._components.get(oo).config.version}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(oo).list.set(this.guid,this),this}createComment(e,t){const i=new eo(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(oo).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=>{var t;return{$Guid:e.guid,Date:e.date.toISOString(),Author:e.author,Comment:e.comment,ModifiedAuthor:e.modifiedAuthor,ModifiedDate:null==(t=e.modifiedDate)?void 0:t.toISOString(),Viewpoint:e.viewpoint?{$Guid:e.viewpoint}:void 0}})}createViewpointTags(){const e=this._components.get(mo);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(oo);for(const n of this.documentReferences){const s=i.documents.get(n);if(!s)continue;let r={$Guid:T.create(),Description:s.description};"2.1"===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(){var e,t;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==(e=this.modifiedDate)?void 0:e.toISOString(),modified_author:this.modifiedAuthor,assigned_to:this.assignedTo,stage:this.stage,description:this.description,due_date:null==(t=this.dueDate)?void 0:t.toISOString(),comments:[...this.comments].map(([e,t])=>t.toJSON()),relatedTopics:[...this.relatedTopics].map(e=>({related_topic_guid:e}))},n=this._components.get(mo);for(const e of this.viewpoints){const t=n.list.get(e);t&&(i.viewpoints||(i.viewpoints=[]),i.viewpoints.push(t.toJSON()))}const s=this._components.get(oo);for(const e of this.documentReferences){const t=s.documents.get(e);t&&(i.document_references||(i.document_references=[]),"external"===t.type?i.document_references.push({guid:T.create(),description:t.description,url:t.url}):i.document_references.push({guid:T.create(),description:t.description,document_guid:e}))}for(const[e,t]of Object.entries(i))(void 0===t||Array.isArray(t)&&0===t.length)&&delete i[e];return i}serialize(){var e,t;const i=this._managerVersion,n={$Guid:this.guid,$TopicType:this.type,$TopicStatus:this.status,$ServerAssignedId:this.serverAssignedId,Title:this.title,CreationAuthor:this.creationAuthor,CreationDate:this.creationDate.toISOString(),Priority:this.priority,Index:"2.1"===i?this.index:void 0,ModifiedDate:null==(e=this.modifiedDate)?void 0:e.toISOString(),ModifiedAuthor:this.modifiedAuthor,DueDate:null==(t=this.dueDate)?void 0:t.toISOString(),AssignedTo:this.assignedTo,Description:this.description,Stage:this.stage,DocumentReferences:"3"===i?{DocumentReference:this.createDocumentReferencesTag(i)}:void 0,RelatedTopics:"3"===i?{RelatedTopic:this.createRelatedTopicTags()}:void 0,RelatedTopic:"2.1"===i?this.createRelatedTopicTags():void 0,Labels:"3"===i?{Label:this.createLabelTags()}:void 0,Viewpoints:"3"===i?{ViewPoint:this.createViewpointTags()}:void 0,Comments:"3"===i?{Comment:this.createCommentTags()}:void 0};"2.1"===i&&(n.Labels=this.createLabelTags(),n.DocumentReference=this.createDocumentReferencesTag(i));const s={Markup:{Topic:n}};return"2.1"===i&&(s.Markup.Viewpoints=this.createViewpointTags(),s.Markup.Comment=this.createCommentTags()),`<?xml version="1.0" encoding="UTF-8"?>\n ${Re.builder.build(s)}`}};t(to,"default",{title:"BCF Topic",type:"Issue",status:"Active"});let io=to;const no=(e,t)=>{if(""===t.trim())return;const i=oo.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 so extends We{constructor(){super(...arguments),t(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(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}}const ro=class e extends g{constructor(){super(...arguments),t(this,"enabled",!1),t(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}),t(this,"config",new so(this,this.components,"BCF Topics",e.uuid)),t(this,"list",new i.DataMap),t(this,"documents",new i.DataMap),t(this,"onSetup",new f),t(this,"isSetup",!1),t(this,"onBCFImported",new f),t(this,"onDisposed",new f)}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()}create(e){const t=new io(this.components);return e?(t.guid=e.guid??t.guid,t.set(e)):this.list.set(t.guid,t),t}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(mo);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 Jr;t.file("bcf.version",`<?xml version="1.0" encoding="UTF-8"?>\n <Version VersionId="${this.config.version}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/release_3_0/Schemas/version.xsd"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n </Version>`);for(const[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("bcf.extensions",this.serializeExtensions());const i=this.components.get(mo);for(const n of e){const e=t.folder(n.guid);e.file("markup.bcf",n.serialize());for(const t of n.viewpoints){const n=i.list.get(t);if(!n)continue;const s=n.title??n.guid;e.file(`${s}.bcfv`,await n.serialize());const r=i.snapshots.get(n.snapshot);if(!r)continue;const o=r?n.snapshot:n.guid,a=i.getSnapshotExtension(n.snapshot);e.file(`${o}.${a}`,r,{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&&(eo||r)))return null;const o=new eo(this.components,s??"");return o.guid=t,o.date=new Date(i),o.author=n,o.viewpoint=null==r?void 0:r.Guid,o.modifiedAuthor=e.ModifiedAuthor,o.modifiedDate=e.ModifiedDate?new Date(e.ModifiedDate):void 0,o}getMarkupComments(e,t){var i;let n;if("2.1"===t&&(n=e.Comment),"3"===t&&(n=null==(i=e.Topic.Comments)?void 0:i.Comment),!n)return[];n=Array.isArray(n)?n:[n];const s=n.map(e=>this.processMarkupComment(e)).filter(e=>e);return Array.isArray(s)?s:[s]}getMarkupLabels(e,t){var i;let n;if("2.1"===t&&(n=e.Topic.Labels),"3"===t&&(n=null==(i=e.Topic.Labels)?void 0:i.Label),!n)return[];return Array.isArray(n)?n:[n]}getMarkupViewpoints(e,t){var i;let n;return"2.1"===t&&(n=e.Viewpoints),"3"===t&&(n=null==(i=e.Topic.Viewpoints)?void 0:i.ViewPoint),n?(n=Array.isArray(n)?n:[n],n):[]}getMarkupRelatedTopics(e,t){var i;let n;if("2.1"===t&&(n=e.Topic.RelatedTopic),"3"===t&&(n=null==(i=e.Topic.RelatedTopics)?void 0:i.RelatedTopic),!n)return[];return(Array.isArray(n)?n:[n]).map(e=>e.Guid)}getMarkupDocumentReferences(e,t){var i;let n;if("2.1"===t&&(n=e.Topic.DocumentReference),"3"===t&&(n=null==(i=e.Topic.DocumentReferences)?void 0:i.DocumentReference),!n)return[];return Array.isArray(n)?n:[n]}async load(t){var i,n,s;const{fallbackVersionOnImport:r,ignoreIncompleteTopicsOnImport:o,updateExtensionsOnImport:a}=this.config,l=new Jr;await l.loadAsync(t);const c=Object.values(l.files);let h=r;const u=c.find(e=>e.name.endsWith(".version"));if(u){const t=await u.async("string"),i=e.xmlParser.parse(t).Version.VersionId;h=String(i)}if(!h||"2.1"!==h&&"3"!==h)throw new Error(`BCFTopics: ${h} is not supported.`);const p=c.find(e=>e.name.endsWith(".extensions"));if(a&&p){const e=await p.async("string");no(this,e)}const f=[],m=this.components.get(mo),g=c.filter(e=>e.name.endsWith(".bcfv"));for(const t of g){const n=await t.async("string"),s=e.xmlParser.parse(n).VisualizationInfo;if(!s){console.warn("Missing VisualizationInfo in Viewpoint");continue}const r={},{Guid:o,ClippingPlanes:a,Components:l,OrthogonalCamera:c,PerspectiveCamera:u}=s;if(o&&(r.guid=o),l){const e={selection:[],coloring:[],visibility:{default_visibility:!1,exceptions:[],view_setup_hints:{spaces_visible:!1,space_boundaries_visible:!1,openings_visible:!1}}};r.components=e;const{Selection:t,Visibility:n}=l;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(n&&"DefaultVisibility"in n&&(e.visibility.default_visibility=n.DefaultVisibility),n&&n.Exceptions&&"Component"in n.Exceptions){const{Component:t}=n.Exceptions,i=Array.isArray(t)?t:[t];e.visibility.exceptions=i.map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e)}let s;"2.1"===h&&(s=l.ViewSetupHints),"3"===h&&(s=null==(i=l.Visibility)?void 0:i.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:o}=l;if(o&&o.Color){const t=Array.isArray(o.Color)?o.Color:[o.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(c||u){const e=s.PerspectiveCamera??s.OrthogonalCamera,{CameraViewPoint:t,CameraDirection:i}=e,n=new d.Vector3(Number(t.X),Number(t.Z),Number(-t.Y)),o=new d.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 e?e.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in e&&(r.orthogonal_camera={...a,view_to_world_scale:e.ViewToWorldScale}),"FieldOfView"in e&&(r.perspective_camera={...a,field_of_view:e.FieldOfView})}if(a){const e=(Array.isArray(a.ClippingPlane)?a.ClippingPlane:[a.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}}));r.clipping_planes=e}const p=new uo(this.components,r);f.push(p)}const w={},y=[],_=c.filter(e=>e.name.endsWith(".bcf"));for(const t of _){const i=await t.async("string"),r=e.xmlParser.parse(i).Markup,a=r.Topic,{Guid:l,TopicType:d,TopicStatus:u,Title:p,CreationDate:f,CreationAuthor:g}=a;if(o&&!(l&&d&&u&&p&&f&&g))continue;const _=new io(this.components);_.guid=l??_.guid;const b=this.getMarkupRelatedTopics(r,h);w[_.guid]=new Set(b),_.type=d??_.type,_.status=u??_.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 e of v)_.labels.add(e);const x=this.getMarkupComments(r,h);for(const e of x)_.comments.set(e.guid,e);const S=this.getMarkupViewpoints(r,h);for(const e of S){if(!e||!e.Guid)continue;const t=m.list.get(e.Guid);if(!t)continue;_.viewpoints.add(t.guid);const i=`${_.guid}/${e.Snapshot}`,n=c.find(({name:e})=>e===i);if(n){const e=await n.async("arraybuffer"),i=new Uint8Array(e);m.snapshots.set(t.guid,i),t.snapshot=t.guid??null}}const C=this.getMarkupDocumentReferences(r,h),T=c.find(e=>"documents.xml"===e.name);let A=[];const E=await(null==T?void 0:T.async("string"));if(E){const e=null==(s=null==(n=Re.parser.parse(E).DocumentInfo)?void 0:n.Documents)?void 0:s.Document;A=Array.isArray(e)?e:[e]}for(const e of C){const{Description:t,DocumentGuid:i,Url:n,isExternal:s,ReferencedDocument:r}=e;if(i&&A.length>0){const e=A.find(({Guid:e})=>e===i),t=c.find(e=>e.name.endsWith(i)),n=await(null==t?void 0:t.async("uint8array"));if(!e||!n)continue;const{Description:s,Filename:r}=e;this.documents.set(i,{type:"internal",fileName:r,description:s,data:n}),_.documentReferences.add(i)}if(n){const e=this.documents.add({type:"external",url:n,description:t});_.documentReferences.add(e)}if(r){let e=null;if(s)e=this.documents.add({type:"external",url:r,description:t});else{const i=r.split("/"),n=i[i.length-1],s=c.find(e=>e.name.endsWith(n)),o=await(null==s?void 0:s.async("uint8array"));if(!o)continue;e=this.documents.add({type:"internal",fileName:n,data:o,description:t})}_.documentReferences.add(e)}}this.list.set(_.guid,_),y.push(_)}for(const e in w){const t=this.list.get(e);if(!t)continue;const i=w[e];for(const e of i)t.relatedTopics.add(e)}return this.onBCFImported.trigger(y),{viewpoints:f,topics:y}}};t(ro,"uuid","de977976-e4f6-4e4f-a01a-204727839802"),t(ro,"xmlParser",new Me({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 oo=ro;class ao{constructor(e,i,n,s,r,o=5,a=!0){var l;if(t(this,"onDraggingStarted",new f),t(this,"onDraggingEnded",new f),t(this,"onDisposed",new f),t(this,"normal"),t(this,"origin"),t(this,"three",new d.Plane),t(this,"components"),t(this,"world"),t(this,"type","default"),t(this,"_title","Clipping Plane"),t(this,"_helper"),t(this,"_visible",!0),t(this,"_enabled",!0),t(this,"_controlsActive",!1),t(this,"_arrowBoundBox",new d.Mesh),t(this,"_planeMesh"),t(this,"_controls"),t(this,"_hiddenMaterial",new d.MeshBasicMaterial({visible:!1})),t(this,"_sizeMultiplier",5),t(this,"_autoScale",!0),t(this,"_visibilityBeforeDisabled",!0),t(this,"notifyManager",()=>{const e=this.components.get(ho),t=e.list.getKey(this);t&&e.list.set(t,this)}),t(this,"update",()=>{this._enabled&&(this.three.setFromNormalAndCoplanarPoint(this.normal,this._helper.position),this.updateScale())}),t(this,"updateScale",()=>{var e;if(!this.autoScale)return;const t=null==(e=this.world.camera)?void 0:e.three;if(!t)return;if(!(t instanceof d.PerspectiveCamera))return;const i=new d.Vector3;t.getWorldPosition(i);const n=i.distanceTo(this._helper.position)/7*this._sizeMultiplier;this._planeMesh.scale.set(n,n,n)}),t(this,"changeDrag",e=>{this._visible=!e.value,this.preventCameraMovement(),this.notifyDraggingChanged(e)}),this.components=e,this.world=i,!i.renderer)throw new Error("The given world must have a renderer!");this.normal=s,this.origin=n,this._sizeMultiplier=o,i.renderer.setPlane(!0,this.three),this._planeMesh=ao.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(e){this._title=e,this.notifyManager()}get title(){return this._title}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){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),this.world.renderer.setPlane(e,this.three),this.notifyManager()}}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}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()}dispose(){var e;this._enabled=!1,(null==(e=this.world.camera)?void 0:e.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 d.Vector3(1,0,0),t=new d.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 l.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 d.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(e){e.value?this.onDraggingStarted.trigger():this.onDraggingEnded.trigger()}preventCameraMovement(){this.world.camera.enabled=this._visible}newHelper(){const e=new d.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 d.PlaneGeometry(1),n=new d.Mesh(i,t);return n.scale.set(e,e,e),n}}class lo extends We{constructor(){super(...arguments),t(this,"_config",{enabled:{value:!0,type:"Boolean"},visible:{value:!0,type:"Boolean"},color:{value:new d.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}}const co=class e extends g{constructor(i){super(i),t(this,"onSetup",new f),t(this,"onBeforeDrag",new f),t(this,"onAfterDrag",new f),t(this,"onBeforeCreate",new f),t(this,"onBeforeCancel",new f),t(this,"onAfterCancel",new f),t(this,"onBeforeDelete",new f),t(this,"onAfterCreate",new f),t(this,"onAfterDelete",new f),t(this,"onDisposed",new f),t(this,"isSetup",!1),t(this,"orthogonalY",!1),t(this,"toleranceOrthogonalY",.7),t(this,"autoScalePlanes",!0),t(this,"Type",ao),t(this,"list",new h.DataMap),t(this,"config",new lo(this,this.components,"Clipper",e.uuid)),t(this,"_defaultConfig",{color:new d.Color(12255487),opacity:.2,size:2}),t(this,"_material",new d.MeshBasicMaterial({color:12255487,side:d.DoubleSide,transparent:!0,opacity:.2})),t(this,"_size",5),t(this,"_enabled",!1),t(this,"_visible",!0),t(this,"onStateChanged",new f),this.components.add(e.uuid,this),this.setEvents()}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"])}setEvents(){this.list.onBeforeDelete.add(({value:e})=>{if(!e.world.renderer)throw new Error("Renderer not found for this plane's world!");e.world.renderer.setPlane(!1,e.three),e.dispose(),this.updateMaterialsAndPlanes(),this.onAfterDelete.trigger(e)})}dispose(){this._enabled=!1;this.components.get(He).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(e.uuid),this.onDisposed.reset()}async create(e){const t=this.components.get(Mr).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(Mr).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){var i;if(!e.renderer)throw new Error("The given world must have a renderer!");const n=t.point.distanceTo(new d.Vector3(0,0,0)),s=t.normal||(null==(i=t.face)?void 0:i.normal);if(!n||!s)return null;const r=this.getWorldNormal(t,s),o=this.newPlane(e,t.point,r.negate()),a=this.list.get(o);return a.visible=this._visible,a.size=this._size,e.renderer.setPlane(!0,a.three),this.updateMaterialsAndPlanes(),a}getWorldNormal(e,t){const i=e.object;let n=e.object.matrixWorld.clone();if(i instanceof d.InstancedMesh&&void 0!==e.instanceId){const t=new d.Matrix4;i.getMatrixAt(e.instanceId,t),n=t.multiply(n)}const s=(new d.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=T.create();return this.list.set(s,n),this.onAfterCreate.trigger(n),s}updateMaterialsAndPlanes(){const e=this.components.get(Lr);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}}};t(co,"uuid","66290bc5-18c4-4cd1-9379-2e17a0617611");let ho=co;class uo{constructor(e,i){t(this,"title"),t(this,"guid",T.create()),t(this,"clippingPlanes",new h.DataSet),t(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}}),t(this,"customData",{}),t(this,"exceptionComponents",new h.DataSet),t(this,"selectionComponents",new h.DataSet),t(this,"componentColors",new h.DataMap),t(this,"spacesVisible",!1),t(this,"spaceBoundariesVisible",!1),t(this,"openingsVisible",!1),t(this,"defaultVisibility",!0),t(this,"snapshot",this.guid),t(this,"_components"),t(this,"_world",null),t(this,"notifyUpdate",()=>{this._components.get(mo).list.set(this.guid,this)}),this._components=e,i&&(this.guid=i.guid??this.guid,this.set(i)),this.setEvents()}async getSelectionMap(){const e=this._components.get(Zn);return await e.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const e=this._components.get(Zn);return await e.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const e=this._components.get(Zn),{camera_view_point:t}=this.camera,{x:i,y:n,z:s}=t,r=new d.Vector3(i,n,s);return e.applyBaseCoordinateSystem(r,new d.Matrix4),r}set position(e){const t=e.clone(),i=this._components.get(Zn);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 d.Vector3(t,i,n)}set world(e){this._world=e}get world(){return this._world}get _managerVersion(){return this._components.get(oo).config.version}get topics(){return[...this._components.get(oo).list.values()].filter(e=>e.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(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(ho);for(const t of s){const{location:i,direction:n}=t,s=new d.Vector3(i.x,i.z,-i.y),r=new d.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 Zr))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 d.Vector3(this.camera.camera_view_point.x,this.camera.camera_view_point.y,this.camera.camera_view_point.z),a=new d.Vector3(this.camera.camera_direction.x,this.camera.camera_direction.y,this.camera.camera_direction.z);if(o.equals(new d.Vector3)&&a.equals(new d.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},u=[];n&&this.setClippingState(!0),s&&u.push(this.applyVisibility()),this.setClippingVisibility(r),u.push(t.controls.setLookAt(l.x,l.y,l.z,h.x,h.y,h.z,i)),await Promise.all(u)}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=new d.Vector3;i.controls.getPosition(s);const r=i.three,o=new d.Vector3(0,0,-1).applyEuler(r.rotation),{width:a,height:l}=n.getSize();let c=a/l;Number.isNaN(c)&&(c=1);const h=this._components.get(Zn);s.applyMatrix4(h.baseCoordinationMatrix.clone().invert());const u={aspect_ratio:c,camera_view_point:{x:s.x,y:s.y,z:s.z},camera_direction:{x:o.x,y:o.y,z:o.z},camera_up_vector:{x:0,y:1,z:0}};if(r instanceof d.PerspectiveCamera?this.camera={...u,field_of_view:r.fov}:r instanceof d.OrthographicCamera&&(this.camera={...u,view_to_world_scale:r.top-r.bottom}),e){const e=this._components.get(mo),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(mo),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(ho);for(const[t,i]of e.list)i.enabled&&this.clippingPlanes.add(t)}async applyVisibility(){const e=this._components.get(mr);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(Zn),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 d.Color(s),renderedFaces:h.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(ho);for(const[i,n]of t.list)n.enabled=e&&this.clippingPlanes.has(i)}setClippingVisibility(e){const t=this._components.get(ho);for(const i of this.clippingPlanes){const n=t.list.get(i);n&&(n.visible=e)}}async createComponentTags(e){var t;const i=this._components.get(Zn);let n="";if(this._components.get(oo).config.includeSelectionTag){const s="selection"===e?await this.getSelectionMap():await this.getExceptionMap();for(const e in s){const r=i.list.get(e);if(!r)continue;const o=s[e];for(const e of o){const i=r.getItem(e),s=await i.getGuid();if(!s)continue;const o=null==(t=await i.getAttributes())?void 0:t.getValue("Tag");let a=null;o&&(a=`AuthoringToolId="${o}"`),n+=`\n<Component IfcGuid="${s}" ${a??""} />`}}}else n=[...this.selectionComponents].map(e=>`<Component IfcGuid="${e}" />`).join("\n");return n}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(ho),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(mo),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(Zn),i=this.position;i.applyMatrix4(t.baseCoordinationMatrix.clone().invert());const n=this.direction;n.normalize();const s=(new d.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 u=`<ViewSetupHints SpacesVisible="${this.spacesVisible??!1}" SpaceBoundariesVisible="${this.spaceBoundariesVisible??!1}" OpeningsVisible="${this.openingsVisible??!1}" />`,p=(await this.createComponentTags("selection")).trim(),f=(await this.createComponentTags("exception")).trim(),m=this.createColorTags();return`<?xml version="1.0" encoding="UTF-8"?>\n <VisualizationInfo Guid="${this.guid}">\n <Components>\n ${"2.1"===e?u:""}\n ${0!==p.length?`<Selection>${p}</Selection>`:""}\n <Visibility DefaultVisibility="${this.defaultVisibility}">\n ${"3"===e?u:""}\n ${0!==f.length?`<Exceptions>${f}</Exceptions>`:""}\n </Visibility>\n ${m}\n </Components>\n ${h}\n </VisualizationInfo>`}}class po extends We{constructor(){super(...arguments),t(this,"_config",{overwriteColors:{value:!1,type:"Boolean"}})}get overwriteColors(){return this._config.overwriteColors.value}set overwriteColors(e){this._config.overwriteColors.value=e}}const fo=class e extends g{constructor(n){super(n),t(this,"enabled",!0),t(this,"world",null),t(this,"list",new i.DataMap),t(this,"snapshots",new i.DataMap),t(this,"isSetup",!1),t(this,"onSetup",new f),t(this,"config",new po(this,this.components,"Viewpoints",e.uuid)),t(this,"onDisposed",new f),n.add(e.uuid,this)}create(e){const t=new uo(this.components,e);return t.world=this.world,e||this.list.set(t.guid,t),t}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}setup(){}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}};t(fo,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");let mo=fo;class go{constructor(e,i){t(this,"_components"),t(this,"_cameraOffset",10),t(this,"_planeHelper"),t(this,"_farPlaneHelper"),t(this,"_cameraHelper"),t(this,"onStateChanged",new f),t(this,"onUpdated",new f),t(this,"onDisposed",new f),t(this,"camera"),t(this,"plane",new d.Plane),t(this,"farPlane",new d.Plane),t(this,"id",T.create()),t(this,"_open",!1),t(this,"_range",yo.defaultRange),t(this,"_world",null),t(this,"_helpersVisible",!1),t(this,"_planesEnabled",!1),this._components=e,this.camera=new Zr(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:e,point:t}=i;this.plane.setFromNormalAndCoplanarPoint(e,t)}this._cameraHelper=new d.CameraHelper(n),this._planeHelper=new d.PlaneHelper(this.plane,50),this._farPlaneHelper=new d.PlaneHelper(this.farPlane,50),this.farPlaneHelperColor=new d.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(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 d.Color&&(this._planeHelper.material.color=e)}set farPlaneHelperColor(e){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof d.Color&&(this._farPlaneHelper.material.color=e)}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}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}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}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}dispose(){this.helpersVisible=!1;const e=this._components.get(v);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()}}const wo=class e extends g{constructor(n){super(n),t(this,"list",new i.DataMap),t(this,"enabled",!0),t(this,"world",null),t(this,"_fragmentsUpdateEvent",()=>{this.components.get(Zn).core.update(!0)}),n.add(e.uuid,this),this.setupEvents()}get hasOpenViews(){return[...this.list.values()].some(e=>e.open)}setupEvents(){this.list.onBeforeDelete.add(({key:e,value:t})=>{t.open&&this.close(e),t.dispose()})}create(e,t,i){const n=new go(this.components,{id:null==i?void 0:i.id,normal:e,point:t});return n.world=(null==i?void 0:i.world)??this.world,this.list.set(n.id,n),n}createFromPlane(e,t){const i=new go(this.components,{id:null==t?void 0:t.id});return i.plane.copy(e),i.update(),i.world=(null==t?void 0:t.world)??this.world,this.list.set(i.id,i),i}async createFromIfcStoreys(e){const t=[],i=this.components.get(Zn),n=void 0===(null==e?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 d.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==e?void 0:e.storeyNames)&&!e.storeyNames.some(e=>e.test(s)))continue;const r=i.Elevation.value+a+n,o=new d.Plane(l,r),c=this.createFromPlane(o,{id:s,world:null==e?void 0:e.world});t.push(c)}}return t}createElevations(e){const t=[],i=this.components.get(Zn),n=void 0!==(null==e?void 0:e.combine)&&e.combine,s=(null==e?void 0: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(wr);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),c=new d.Vector3;n.getCenter(c);const h=new d.Plane(new d.Vector3(0,0,-1),o.z),u=new d.Plane(new d.Vector3(0,0,1),-r.z),p=new d.Plane(new d.Vector3(-1,0,0),o.x),f=new d.Plane(new d.Vector3(1,0,0),-r.x),{front:m,back:g,left:w,right:y}=s(i),_=this.createFromPlane(h,{id:m,world:null==e?void 0:e.world});_.range=l;const b=this.createFromPlane(u,{id:g,world:null==e?void 0:e.world});b.range=l;const v=this.createFromPlane(p,{id:w,world:null==e?void 0:e.world});v.range=a;const x=this.createFromPlane(f,{id:y,world:null==e?void 0: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);n.setPlane(!0,t.plane),n.setPlane(!0,t.farPlane),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}.`);n.setPlane(!1,t.plane),n.setPlane(!1,t.farPlane),t.camera.controls.removeEventListener("rest",this._fragmentsUpdateEvent),i.useDefaultCamera(),t.open=!1}};t(wo,"uuid","fb22f1f5-6598-4664-a11d-de8963ae420f"),t(wo,"defaultRange",15);let yo=wo;async function _o(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 bo{constructor(e,i){if(t(this,"onDisposed",new f),t(this,"onDistanceComputed",new f),t(this,"excludedObjects",new Set),t(this,"enabled",!0),t(this,"renderDebugFrame",!1),t(this,"components"),t(this,"scene",new d.Scene),t(this,"camera",new d.OrthographicCamera(-1,1,1,-1,0,1)),t(this,"depthMaterial"),t(this,"world"),t(this,"worker"),t(this,"_width",512),t(this,"_height",512),t(this,"_postQuad"),t(this,"tempRT"),t(this,"resultRT"),t(this,"bufferSize"),t(this,"_buffer"),t(this,"_isWorkerBusy",!1),t(this,"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 _o(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})}),t(this,"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||d.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=e,this.world=i;const n=i.camera.three;this.tempRT=new d.WebGLRenderTarget(this._width,this._height),this.bufferSize=this._width*this._height*4,this._buffer=new Uint8Array(this.bufferSize),this.tempRT.texture.minFilter=d.NearestFilter,this.tempRT.texture.magFilter=d.NearestFilter,this.tempRT.stencilBuffer=!1,this.tempRT.samples=0,this.tempRT.depthTexture=new d.DepthTexture(this._width,this._height),this.tempRT.depthTexture.format=d.DepthFormat,this.tempRT.depthTexture.type=d.UnsignedShortType,this.resultRT=new d.WebGLRenderTarget(this._width,this._height),this.depthMaterial=new d.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 d.PlaneGeometry(2,2);this._postQuad=new d.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 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()}}class vo{constructor(e){t(this,"cardinality","required"),t(this,"instructions"),t(this,"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}),this._components=e}addCheckResult(e,t){const i=t.findIndex(({parameter:t})=>t===e.parameter);-1!==i?t[i]=e:t.push(e)}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 h.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 xo=(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 So extends vo{constructor(e,i){super(e),t(this,"facetType","Attribute"),t(this,"name"),t(this,"value"),this.name=i}serialize(e){const t=xo("Name",this.name),i=xo("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(Zn);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 Co extends vo{constructor(e,i){super(e),t(this,"facetType","Classification"),t(this,"system"),t(this,"value"),t(this,"uri"),this.system=i}serialize(e){const t=xo("System",this.system),i=xo("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 To extends vo{constructor(e,i){super(e),t(this,"facetType","Entity"),t(this,"name"),t(this,"predefinedType"),this.name=i}serialize(e){const t=xo("Name",this.name),i=xo("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(Zn),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)&&Ue.append(t,e,i._localId.value)}}else Ue.add(t,s)}async test(e,t,i){const n=this._components.get(Zn);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(Zn).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 Ao extends vo{constructor(e,i,n){super(e),t(this,"facetType","Property"),t(this,"propertySet"),t(this,"baseName"),t(this,"value"),t(this,"dataType"),t(this,"uri"),t(this,"_unsupportedTypes",["IFCCOMPLEXPROPERTY","IFCPHYSICALCOMPLEXQUANTITY"]),this.propertySet=i,this.baseName=n}serialize(e){const t=xo("PropertySet",this.propertySet),i=xo("BaseName",this.baseName),n=xo("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(Zn);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},DefinesOcurrence:{attributes:!0,relations:!1}}});for(const e of o){if(!("value"in e._localId&&"value"in e._category&&"value"in e.Name&&Array.isArray(e.DefinesOcurrence)))continue;if(!this.evalRequirement(e.Name.value,this.propertySet,"PropertySet"))continue;let i;if("IFCPROPERTYSET"===e._category.value&&(i="HasProperties"),"IFCELEMENTQUANTITY"===e._category.value&&(i="Quantities"),!i)continue;const s=e[i];if(Array.isArray(s))for(const i of s){const s=Object.keys(i),r=s.find(e=>/Name/.test(e));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 e=s.find(e=>/Value/.test(e));if(!e)continue;const t=i[e];if(!("value"in t))continue;if(!this.evalRequirement(t.value,this.value,"Value"))continue}const a=e.DefinesOcurrence.map(e=>"value"in e._localId&&"number"==typeof e._localId.value?e._localId.value:null).filter(e=>null!==e);Ue.append(t,n,...a)}}}}async test(e,t,i={skipIfFails:!0}){const n=this._components.get(Zn);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},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){if(!Array.isArray(e.IsTypedBy))return[];const[t]=e.IsTypedBy;return t&&Array.isArray(t.HasPropertySets)?t.HasPropertySets:[]}async getPsets(e){const t=this.getTypePsets(e);if(!Array.isArray(e.IsDefinedBy))return t;const i=[];for(const n of e.IsDefinedBy){if(!("value"in n.Name))continue;const e=n.Name.value,s=this.getPropertyListName(n);if(!e||!s)continue;const r=t.find(t=>"value"in t.Name&&t.Name.value===e);if(r&&Array.isArray(r.HasProperties)&&Array.isArray(n.HasProperties))for(const e of r.HasProperties){if(!("value"in e.Name))continue;const t=e.Name.value;n.HasProperties.find(e=>"value"in e.Name&&e.Name.value===t)||n.HasProperties.push(e)}i.push(n)}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 null==t||t.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;const e=structuredClone(this.value);"IFCLABEL"===n.type&&"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()||(null==t||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 null==t||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 Eo extends vo{constructor(){super(...arguments),t(this,"_ifcMaterialEntities",[/^IFCMATERIALLAYERSETUSAGE$/,/^IFCMATERIALCONSTITUENTSET$/,/^IFCMATERIAL$/,/^IFCMATERIALLIST$/]),t(this,"facetType","Material"),t(this,"value"),t(this,"uri")}serialize(e){if(!this.value||!this.uri)return"<material />";const t=xo("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(Zn);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},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});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);Ue.append(t,n,...i)}}}async test(e,t,i={skipIfFails:!0}){const n=this._components.get(Zn);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},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});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(["ForLayerSet","MaterialLayers","Material","MaterialConstituents","Materials"].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 null==t||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 Mo extends vo{constructor(e,i){super(e),t(this,"facetType","PartOf"),t(this,"_entityFacet"),t(this,"_entity"),t(this,"relation"),t(this,"cardinality","required"),this._entity=i,this._entityFacet=new To(e,i.name),this._entityFacet.predefinedType=i.predefinedType}set entity(e){this._entity=e;const{name:t,predefinedType:i}=e;this._entityFacet=new To(this._components,t),this._entityFacet.predefinedType=i}get entity(){return this._entity}serialize(){return""}async getEntities(e,t){}async test(e){}}class Po{constructor(e,i,n){t(this,"name"),t(this,"ifcVersion",new Set),t(this,"identifier",T.create()),t(this,"description"),t(this,"instructions"),t(this,"requirementsDescription"),t(this,"applicability",new h.DataSet),t(this,"requirements",new h.DataSet),t(this,"components"),this.components=e,this.name=i;for(const e of n)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(No).list.set(this.identifier,this),this}async test(e,t={skipIfFails:!0}){const i=new h.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 Io=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},zo=(e,t)=>{const i=[];for(const n of t){const t=n.name,s=Io(t);if(!s)continue;const r=new To(e,s);n.cardinality&&(r.cardinality=n.cardinality),r.predefinedType=Io(n.predefinedType),r.instructions=n.instructions,i.push(r)}return i},Do=(e,t)=>{const i=[];for(const n of t){const t=n.name,s=Io(t);if(!s)continue;const r=new So(e,s);n.cardinality&&(r.cardinality=n.cardinality),r.value=Io(n.value),r.instructions=n.instructions,i.push(r)}return i},ko=(e,t)=>{const i=[];for(const n of t){const t=new Eo(e);n.cardinality&&(t.cardinality=n.cardinality);const s=Io(n.value);"enumeration"===(null==s?void 0: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},Bo=(e,t)=>{const i=[];for(const n of t){const t=n.propertySet,s=n.baseName,r=Io(t),o=Io(s);if(!o||!r)continue;const a=new Ao(e,r,o);n.cardinality&&(a.cardinality=n.cardinality);const l=Io(n.value);a.value=l,a.dataType=n.dataType,a.uri=n.uri,a.instructions=n.instructions,i.push(a)}return i},Oo=(e,t)=>{const i=[];for(const n of t){const t=n.system,s=Io(t);if(!s)continue;const r=new Co(e,s);n.cardinality&&(r.cardinality=n.cardinality);const o=Io(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},Vo=(e,t)=>{const i=[];for(const n of t){const t=Io(n.entity.name);if(!t)continue;const s=Io(n.entity.predefinedType),r=new Mo(e,{name:t,predefinedType:s});r.relation=n.relation,n.cardinality&&(r.cardinality=n.cardinality),r.instructions=n.instructions,i.push(r)}return i},Lo=class e extends g{constructor(n){super(n),t(this,"enabled",!0),t(this,"IDSInfo"),t(this,"list",new i.DataMap),n.add(e.uuid,this)}getModelIdMap(e){const t={},i={};for(const[n,s]of e){const e=[...s].filter(([,e])=>e.pass).map(([e])=>e);Ue.append(t,n,...e);const r=[...s].filter(([,e])=>!e.pass).map(([e])=>e);Ue.append(i,n,...r)}return{pass:t,fail:i}}create(e,t,i){const n=new Po(this.components,e,t);return i&&(n.identifier=i),this.list.set(n.identifier,n),n}load(t){const i=[],n=e.xmlParser.parse(t).ids,{specifications:s,info:r}=n;if(this.IDSInfo={...r},s&&s.specification){const e=Array.isArray(s.specification)?s.specification:[s.specification];for(const t of e){const{name:e,ifcVersion:n,description:s,instructions:r,identifier:o}=t;if(!e||!n)continue;const a=[],l=[],{applicability:c,requirements:h}=t;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=zo(this.components,i);a.push(...e)}if("attribute"===t){const e=Do(this.components,i);a.push(...e)}if("material"===t){const e=ko(this.components,i);a.push(...e)}if("classification"===t){const e=Oo(this.components,i);a.push(...e)}if("property"===t){const e=Bo(this.components,i);a.push(...e)}if("partOf"===t){const e=Vo(this.components,i);a.push(...e)}}}let d;if(h){const{maxOccurs:e,...t}=h;d=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=zo(this.components,i);l.push(...e)}if("attribute"===t){const e=Do(this.components,i);l.push(...e)}if("material"===t){const e=ko(this.components,i);l.push(...e)}if("classification"===t){const e=Oo(this.components,i);l.push(...e)}if("property"===t){const e=Bo(this.components,i);l.push(...e)}if("partOf"===t){const e=Vo(this.components,i);l.push(...e)}}}const u=this.create(e,n.split(/\s+/),o);u.description=s,u.instructions=r,u.requirementsDescription=d,u.applicability.add(...a),u.requirements.add(...l),i.push(u)}}return i}export(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 ${$r.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>`}};t(Lo,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c"),t(Lo,"xmlParser",new Me({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 No=Lo;const Fo=class e extends g{constructor(i){super(i),t(this,"enabled",!0),i.add(e.uuid,this)}static distanceFromPointToLine(e,t,i,n=!1){const s=new d.Line3,r=new d.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(Zn);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}};t(Fo,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");let Ro=Fo;const Uo=(e,t,i)=>{const n=new d.Vector3(-t.z,0,t.x),s=new d.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]},jo=(e,t,i)=>{const n=new d.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]},$o=()=>[],Wo=(e,t,i)=>{const n=new d.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 Go extends h.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 Ho extends h.DataMap{constructor(e){super(),t(this,"_container"),this._container=e,this.deleteGuard=e=>"0"!==e,this.set("0",{name:"0",visible:!0,material:new d.LineBasicMaterial({color:0})})}create(e,t){if(!this.has(e)){const i={name:e,visible:(null==t?void 0:t.visible)??!0,material:(null==t?void 0:t.material)??new d.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()}}const qo=class e extends d.Group{constructor(i){super(),t(this,"_viewport"),t(this,"_border"),t(this,"_handles",[]),t(this,"_raycaster",new d.Raycaster),t(this,"_resizable",!1),t(this,"_movable",!1),t(this,"_dragHandle",null),t(this,"_dragConstraints",[]),t(this,"_hoveredHandle",null),t(this,"_moveDrag",null),t(this,"_hoveringBorder",!1),t(this,"_normalMat"),t(this,"_hoverMat"),t(this,"_borderMat"),this._viewport=i,this._borderMat=new d.LineBasicMaterial({color:e._BORDER_COLOR,depthTest:!1});const n=new d.BufferGeometry;n.setAttribute("position",new d.BufferAttribute(new Float32Array(24),3)),this._border=new d.LineSegments(n,this._borderMat),this._border.renderOrder=999,this._border.frustumCulled=!1,this._border.userData.isDimension=!0,this.add(this._border),this._normalMat=new d.MeshBasicMaterial({color:e._BORDER_COLOR}),this._hoverMat=new d.MeshBasicMaterial({color:e._BORDER_HOVER_COLOR});const s=new d.SphereGeometry(.05,8,6);for(const t of e._HANDLE_DEFS){const e=new d.Mesh(s,this._normalMat);e.renderOrder=1e3,e.visible=!1,e.userData.constraints=t.constraints,e.userData.isDimension=!0,this.add(e),this._handles.push(e)}this.update()}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}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(t){if(this._dragHandle){const e=this._projectToLocal(t);if(!e)return;for(const t of this._dragConstraints)switch(t){case"left":this._viewport.left=e.x;break;case"right":this._viewport.right=e.x;break;case"top":this._viewport.top=-e.z;break;case"bottom":this._viewport.bottom=-e.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 e=this._projectToLocal(t);if(!e)return;const i=e.x-this._moveDrag.origin.x,n=e.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(t.origin,t.direction);let i=null;if(this._resizable){const e=this._handles.filter(e=>e.visible),t=this._raycaster.intersectObjects(e,!1);i=t.length>0?t[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:e._LINE_THRESHOLD};const t=this._raycaster.intersectObject(this._border,!1).length>0;this._setBorderHover(t)}else this._setBorderHover(!1)}onPointerDown(t){if(this._resizable||this._movable){if(this._raycaster.set(t.origin,t.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:e._LINE_THRESHOLD};if(this._raycaster.intersectObject(this._border,!1).length>0){const e=this._projectToLocal(t);if(!e)return;this._moveDrag={origin:e,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 d.Vector3(0,1,0).transformDirection(this.matrixWorld),i=(new d.Vector3).setFromMatrixPosition(this.matrixWorld),n=(new d.Plane).setFromNormalAndCoplanarPoint(t,i),s=new d.Vector3;return e.intersectPlane(n,s)?this.worldToLocal(s):null}_setBorderHover(t){t!==this._hoveringBorder&&(this._hoveringBorder=t,this._borderMat.color.setHex(t?e._BORDER_HOVER_COLOR:e._BORDER_COLOR))}};t(qo,"_BORDER_COLOR",22015),t(qo,"_BORDER_HOVER_COLOR",16746496),t(qo,"_LINE_THRESHOLD",.06),t(qo,"_HANDLE_DEFS",[{constraints:["left","top"]},{constraints:["right","top"]},{constraints:["right","bottom"]},{constraints:["left","bottom"]},{constraints:["top"]},{constraints:["right"]},{constraints:["bottom"]},{constraints:["left"]}]);let Zo=qo;class Yo{constructor(e){t(this,"uuid",d.MathUtils.generateUUID()),t(this,"name"),t(this,"camera"),t(this,"onDisposed",new f),t(this,"_left"),t(this,"_right"),t(this,"_top"),t(this,"_bottom"),t(this,"_drawingScale"),t(this,"_container",null),t(this,"_helper",null),t(this,"_helperVisible",!1),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 d.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(e){var t;this._left=e,this.camera.left=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get right(){return this._right}set right(e){var t;this._right=e,this.camera.right=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get top(){return this._top}set top(e){var t;this._top=e,this.camera.top=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get bottom(){return this._bottom}set bottom(e){var t;this._bottom=e,this.camera.bottom=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get drawingScale(){return this._drawingScale}set drawingScale(e){this._drawingScale=e}get helper(){return this._helper||(this._helper=new Zo(this)),this._helper}get helperVisible(){return this._helperVisible}set helperVisible(e){var t,i;this._helperVisible=e,e?null==(t=this._container)||t.add(this.helper):null==(i=this._helper)||i.removeFromParent()}get bbox(){const e=new d.Vector3(this._left,0,-this._top),t=new d.Vector3(this._right,0,-this._bottom);return new d.Box3(e,t)}get size(){const e=new d.Vector3;return this.bbox.getSize(e),new d.Vector2(1e3*e.x,1e3*e.z)}get localXAxis(){return new d.Vector3(1,0,0)}get localYAxis(){return new d.Vector3(0,0,-1)}get normal(){return new d.Vector3(0,1,0)}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 d.Line3(t[0],t[1])}const o=this.getPlaneIntersections(e);return 0===o.length?null:s?new d.Line3(i,o[0]):new d.Line3(o[0],n)}dispose(){var e;null==(e=this._helper)||e.dispose(),this._helper=null,this.onDisposed.trigger(),this.onDisposed.reset()}get bboxPlanes(){const e=this.bbox;return[new d.Plane(new d.Vector3(1,0,0),-e.min.x),new d.Plane(new d.Vector3(-1,0,0),e.max.x),new d.Plane(new d.Vector3(0,0,1),-e.min.z),new d.Plane(new d.Vector3(0,0,-1),e.max.z)]}getPlaneIntersections(e){const t=[];for(const i of this.bboxPlanes){const n=new d.Vector3;i.intersectLine(e,n)&&this.bbox.containsPoint(n)&&t.push(n)}return t}}class Xo extends h.DataMap{constructor(e){super(),t(this,"_container"),this._container=e,this.onBeforeDelete.add(({value:e})=>{this._container.remove(e.camera),e.dispose()})}create(e){const t=new Yo(e);return this._container.add(t.camera),t.setContainer(this._container),this.set(t.uuid,t),t}}const Ko=class e extends d.Group{constructor(i){super(),t(this,"_drawing"),t(this,"_topFrame"),t(this,"_pillars"),t(this,"_bottomFrame"),t(this,"_topPlane"),t(this,"_bottomPlane"),t(this,"_frameMat"),t(this,"_depthMat"),t(this,"_planeMat"),t(this,"width",10),t(this,"height",10),t(this,"farHandle",new d.Object3D),t(this,"widthHandle",new d.Object3D),t(this,"heightHandle",new d.Object3D),this._drawing=i,this._frameMat=new d.LineBasicMaterial({color:e._FRAME_COLOR,depthTest:!1}),this._depthMat=new d.LineBasicMaterial({color:e._DEPTH_COLOR,depthTest:!1,transparent:!0,opacity:.4}),this._planeMat=new d.MeshBasicMaterial({color:e._FRAME_COLOR,transparent:!0,opacity:.07,side:d.DoubleSide,depthTest:!1});const n=()=>{const e=new d.BufferGeometry;return e.setAttribute("position",new d.BufferAttribute(new Float32Array(12),3)),e.setIndex([0,1,2,0,2,3]),e};this._topPlane=new d.Mesh(n(),this._planeMat),this._topPlane.renderOrder=998,this._topPlane.frustumCulled=!1,this._topPlane.userData.isDimension=!0,this._bottomPlane=new d.Mesh(n(),this._planeMat),this._bottomPlane.renderOrder=998,this._bottomPlane.frustumCulled=!1,this._bottomPlane.userData.isDimension=!0;const s=new d.BufferGeometry;s.setAttribute("position",new d.BufferAttribute(new Float32Array(24),3)),this._topFrame=new d.LineSegments(s,this._frameMat),this._topFrame.renderOrder=999,this._topFrame.frustumCulled=!1,this._topFrame.userData.isDimension=!0;const r=new d.BufferGeometry;r.setAttribute("position",new d.BufferAttribute(new Float32Array(24),3)),this._pillars=new d.LineSegments(r,this._depthMat),this._pillars.renderOrder=999,this._pillars.frustumCulled=!1,this._pillars.userData.isDimension=!0;const o=new d.BufferGeometry;o.setAttribute("position",new d.BufferAttribute(new Float32Array(24),3)),this._bottomFrame=new d.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 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 d=(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()};d(this._topPlane,n),d(this._bottomPlane,i),this.farHandle.position.set(0,i,0),this.widthHandle.position.set(r,n,0),this.heightHandle.position.set(0,n,a)}attachFarGizmo(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()}};t(Ko,"_FRAME_COLOR",22015),t(Ko,"_DEPTH_COLOR",22015);let Qo=Ko;function Jo(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 d.Vector3).subVectors(e[1],e[0]),n=(new d.Vector3).subVectors(e[2],e[0]);if((new d.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 d.Vector3).subVectors(t,e),s=(new d.Vector3).subVectors(i,e),r=n.clone().normalize(),o=(new d.Vector3).crossVectors(n,s).normalize(),a=(new d.Vector3).crossVectors(r,o).normalize();return(new d.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),c=(new d.Vector3).subVectors(t[0],l),h=(new d.Quaternion).setFromRotationMatrix(r),u=new d.Matrix4;return u.compose(c,h,new d.Vector3(a,a,a)),u}class ea{constructor(e){t(this,"uuid",d.MathUtils.generateUUID()),t(this,"_raycaster",new d.Raycaster),t(this,"_components"),t(this,"world",null),t(this,"three",new d.Group),t(this,"annotations",new Go),t(this,"layers",new Ho(this.three)),t(this,"activeLayer","0"),t(this,"far",10),t(this,"viewports",new Xo(this.three)),t(this,"onDisposed",new f),this._components=e}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 d.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 d.LineSegments&&void 0!==s.index){const e=s.object.geometry.attributes.position,t=s.index,i=new d.Vector3(e.getX(t),e.getY(t),e.getZ(t)),n=new d.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 d.Line3(i,n)}return{point:r,object:s.object,viewport:t,line:o}}alignTo(e,t){Jo(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 d.Matrix4).copy(t.three.matrixWorld).invert().multiply(e.matrixWorld),n=e.geometry.attributes.position,s=n.count,r=new Float32Array(3*s),o=new d.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 d.BufferGeometry;return a.setAttribute("position",new d.BufferAttribute(r,3)),new d.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 d.LineDashedMaterial&&e.computeLineDistances(),e.geometry.computeBoundsTree({strategy:0,indirect:!0,type:Nn}),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(hr),n=i.projectionDirection.clone(),s=i.nearPlane,r=i.farPlane;try{this.three.updateWorldMatrix(!0,!1);const n=new d.Vector3(0,-1,0).transformDirection(this.three.matrixWorld).normalize();i.projectionDirection.copy(n);const s=(new d.Matrix4).makeRotationFromQuaternion((new d.Quaternion).setFromUnitVectors(n,new d.Vector3(0,-1,0))),r=(new d.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=>ea.toDrawingSpace(new d.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(v).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset()}}class ta{constructor(e){t(this,"styles",new h.DataMap),t(this,"activeStyle","default"),t(this,"onCommit",new f),t(this,"onUpdate",new f),t(this,"onDelete",new f),t(this,"onDisposed",new f),t(this,"_knownDrawings",new Set),t(this,"_previewMaterial",new d.LineBasicMaterial({color:16737894,depthTest:!1})),t(this,"_previewObject",null),t(this,"_previewDrawing",null),t(this,"_materialCache",new h.DataMap),t(this,"_meshMaterialCache",new h.DataMap),t(this,"_ownsChildGeometry",!0),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(Ra),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,{})}})}_onAfterPersist(e,t){}_onDispose(){}_updatePreview(){}get(e){const t=new h.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:d.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 d.Raycaster;i.ray.copy(e),i.params.Line={threshold:t},i.params.LineSegments={threshold:t};const n=d.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 d.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 d.Mesh){const e=(new d.Box3).setFromObject(o),n=new d.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 d.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 d.MeshBasicMaterial({color:this._resolveStyle(e).color,side:d.DoubleSide});return this._meshMaterialCache.set(e,i),i}_disposeGroup(e){if(e.removeFromParent(),this._ownsChildGeometry)e.traverse(e=>{e.geometry instanceof d.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 d.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 ia(e,t){const i=e[0],n=e[e.length-1],s=(new d.Vector3).subVectors(n,i);if(s.lengthSq()<1e-10)return 0;s.normalize();const r=new d.Vector3(-s.z,0,s.x);return t.clone().sub(i).dot(r)}function na(e,t){const i=[];for(let n=0;n<e.length-1;n++)i.push({uuid:d.MathUtils.generateUUID(),pointA:e[n].clone(),pointB:e[n+1].clone(),offset:t,style:""});return i}function sa(e,t){switch(e.kind){case"awaitingFirstPoint":if("CLICK"===t.type){if(!t.line)return e;const i=(new d.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 d.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 d.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=ia(e.points,t.point);return{kind:"committed",dimensions:na(e.points,i)}}return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e}var i,n}function ra(e){const{pointA:t,pointB:i,offset:n}=e,s=(new d.Vector3).subVectors(i,t),r=new d.Vector3(-s.z,0,s.x).normalize(),o=t.clone().addScaledVector(r,n),a=i.clone().addScaledVector(r,n),l=(new d.Vector3).subVectors(a,o).normalize();return[{tip:o,dir:l},{tip:a,dir:l.clone().negate()}]}function oa(e,t){const{pointA:i,pointB:n,offset:s}=e,r=(new d.Vector3).subVectors(n,i),o=new d.Vector3(-r.z,0,r.x).normalize(),a=s>=0?1:-1,l=Math.abs(s),c=i.clone().addScaledVector(o,t.extensionGap*a),h=i.clone().addScaledVector(o,(l+t.extensionOvershoot)*a),u=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 d.Vector3).subVectors(m,f).normalize(),w=t.lineTick(f,g,t.tickSize),y=t.lineTick(m,g.clone().negate(),t.tickSize);return[c.x,c.y,c.z,h.x,h.y,h.z,u.x,u.y,u.z,p.x,p.y,p.z,f.x,f.y,f.z,m.x,m.y,m.z,...w,...y]}function aa(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=ia(t,i),r=[];for(let e=0;e<t.length-1;e++)r.push(...oa({pointA:t[e],pointB:t[e+1],offset:s},n));return r}class la extends ta{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingFirstPoint"}),t(this,"onMachineStateChanged",new f),this.styles.set("default",{lineTick:Uo,tickSize:.4,extensionGap:.05,extensionOvershoot:.2,color:0,textOffset:.4,fontSize:.45})}pickHandle(e,t,i=.1){const n=(new d.Matrix4).copy(e.three.matrixWorld).invert(),s=t.origin.clone().applyMatrix4(n),r=t.direction.clone().transformDirection(n).normalize(),o=new d.Ray(s,r),a=new d.Plane(new d.Vector3(0,1,0),0),l=o.intersectPlane(a,new d.Vector3);if(!l)return null;let c=null,h=i;for(const[t,i]of e.annotations.getBySystem(this)){const e=(new d.Vector3).subVectors(i.pointB,i.pointA),n=new d.Vector3(-e.z,0,e.x).normalize(),s=(new d.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<h&&(h=i,c={uuid:t,handle:e})}}return c}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const i=sa(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 d.Group,n=oa(e,t),s=new d.BufferGeometry;s.setAttribute("position",new d.BufferAttribute(new Float32Array(n),3));const r=new d.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 ra(e)){const r=t.meshTick(n,s,t.tickSize),o=new d.BufferGeometry;o.setAttribute("position",new d.BufferAttribute(new Float32Array(r),3));const a=new d.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=aa(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 d.BufferGeometry;e.setAttribute("position",new d.BufferAttribute(new Float32Array(i),3)),this._previewObject=new d.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 ca=Math.PI/180;function ha(e,t,i,n){const s=function(e,t,i){const n=(new d.Vector3).subVectors(e,t).normalize(),s=(new d.Vector3).subVectors(i,t).normalize();return(new d.Vector3).addVectors(n,s).normalize()}(e,t,i);return(new d.Vector3).subVectors(n,t).setY(0).dot(s)}function da(e,t,i,n){return ha(e,t,i,n)<0}function ua(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 d.Vector3).subVectors(e.line1.end,e.line1.start).normalize(),n=(new d.Vector3).subVectors(t.line.end,t.line.start).normalize();if(Math.abs(i.dot(n))>Math.cos(ca))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 d.Vector3).subVectors(i,e),o=(r.x*n.z-r.z*n.x)/s;return new d.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=da(e.pointA,e.vertex,e.pointB,t.point);return{...e,cursor:t.point.clone(),flipped:i}}if("CLICK"===t.type){const i=da(e.pointA,e.vertex,e.pointB,t.point),n=Math.max(.05,Math.abs(ha(e.pointA,e.vertex,e.pointB,t.point)));return{kind:"committed",dimension:{uuid:d.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 pa(e){const t=(new d.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new d.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 d.Vector3(e.vertex.x+Math.cos(n)*e.arcRadius,0,e.vertex.z+Math.sin(n)*e.arcRadius),o=n+s,a=new d.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 d.Vector3(-Math.sin(n)*l,0,Math.cos(n)*l)},{tip:a,dir:new d.Vector3(Math.sin(o)*l,0,-Math.cos(o)*l)}]}function fa(e){const t=(new d.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new d.Vector3).subVectors(e.pointB,e.vertex).normalize(),n=Math.acos(d.MathUtils.clamp(t.dot(i),-1,1));return e.flipped?2*Math.PI-n:n}function ma(e){const t=(new d.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new d.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 ga(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 c=new d.Vector3(e.x+Math.cos(o)*n,0,e.z+Math.sin(o)*n),h=new d.Vector3(e.x+Math.cos(o+a)*n,0,e.z+Math.sin(o+a)*n),u=e.clone().addScaledVector(t,s.extensionGap),p=e.clone().addScaledVector(i,s.extensionGap);l.push(u.x,u.y,u.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 d.Vector3(-Math.sin(o)*f,0,Math.cos(o)*f),g=o+a,w=new d.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 wa(e,t){const i=(new d.Vector3).subVectors(e.pointA,e.vertex).normalize(),n=(new d.Vector3).subVectors(e.pointB,e.vertex).normalize();return ga(e.vertex,i,n,e.arcRadius,t,e.flipped??!1)}function ya(e,t,i,n,s,r=!1){if(!n)return[];const o=Math.max(.05,(new d.Vector3).subVectors(n,t).setY(0).length());return ga(t,(new d.Vector3).subVectors(e,t).normalize(),(new d.Vector3).subVectors(i,t).normalize(),o,s,r)}class _a extends ta{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingFirstLine"}),t(this,"onMachineStateChanged",new f),t(this,"_secondLinePreviewObject",null),this.styles.set("default",{lineTick:Uo,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=ua(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 d.Group,n=wa(e,t),s=new d.BufferGeometry;s.setAttribute("position",new d.BufferAttribute(new Float32Array(n),3));const r=new d.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 pa(e)){const r=t.meshTick(n,s,t.tickSize),o=new d.BufferGeometry;o.setAttribute("position",new d.BufferAttribute(new Float32Array(r),3));const a=new d.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=ya(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 d.BufferGeometry;e.setAttribute("position",new d.BufferAttribute(new Float32Array(i),3)),this._previewObject=new d.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 d.Vector3).subVectors(i.line1.end,i.line1.start).normalize();if(!t)return void this._clearSecondLinePreview();const s=(new d.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 d.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 d.Vector3).subVectors(o,r).setY(0);if(a.length()<.01)return void this._clearSecondLinePreview();const l=(new d.Vector3).subVectors(i.pointA,r).normalize(),c=a.normalize(),h=Math.atan2(l.z,l.x);let u=Math.atan2(c.z,c.x)-h;for(;u>Math.PI;)u-=2*Math.PI;for(;u<-Math.PI;)u+=2*Math.PI;const p=h+u/2,f=Math.max(.1,.4*Math.min(i.pointA.distanceTo(r),o.distanceTo(r))),m=new d.Vector3(r.x+Math.cos(p)*f,0,r.z+Math.sin(p)*f),g=this._resolveStyle(this.activeStyle),w=ya(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 d.BufferGeometry;e.setAttribute("position",new d.BufferAttribute(new Float32Array(w),3)),this._secondLinePreviewObject=new d.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 ba(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 d.Vector3(e.x+Math.cos(o)*s,0,e.z+Math.sin(o)*s)}function va(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:ba(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",arrowTip:e.arrowTip,elbow:e.elbow,extensionEnd:ba(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:d.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 xa(e,t,i,n){return"curved"===n.leaderShape?function(e,t,i,n){const s=new d.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 d.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 d.Vector3).subVectors(e,t);i.lengthSq()>1e-10&&s.push(...n.lineTick(e,i.normalize(),n.tickSize))}return s}(e,t,i,n)}function Sa(e,t){return xa(e.arrowTip,e.elbow,e.extensionEnd,t)}function Ca(e,t,i,n,s){return n?xa(t,"placingElbow"===e?n:i,n,s):[]}class Ta extends ta{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingArrowTip"}),t(this,"onMachineStateChanged",new f),t(this,"_previewMeshMaterial",new d.MeshBasicMaterial({color:16737894,side:d.DoubleSide,depthTest:!1})),t(this,"_previewMeshObject",null),this.styles.set("default",{tickSize:.4,color:0,textOffset:.1,fontSize:.45,lineTick:jo})}pickHandle(e,t,i=.1){const n=(new d.Matrix4).copy(e.three.matrixWorld).invert(),s=t.origin.clone().applyMatrix4(n),r=t.direction.clone().transformDirection(n).normalize(),o=new d.Ray(s,r),a=new d.Plane(new d.Vector3(0,1,0),0),l=o.intersectPlane(a,new d.Vector3);if(!l)return null;let c=null,h=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<h&&(h=i,c={uuid:t,handle:e})}return c}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const i=va(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 d.Group,n=Sa(e,t),s=new d.BufferGeometry;s.setAttribute("position",new d.BufferAttribute(new Float32Array(n),3));const r=new d.LineSegments(s,this._getMaterial(e.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),t.meshTick){const n=(new d.Vector3).subVectors(e.arrowTip,e.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=t.meshTick(e.arrowTip,n,t.tickSize),r=new d.BufferGeometry;r.setAttribute("position",new d.BufferAttribute(new Float32Array(s),3));const o=new d.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?Ca("placingElbow",e.arrowTip,null,e.cursor,t):Ca("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 d.BufferGeometry;e.setAttribute("position",new d.BufferAttribute(new Float32Array(i),3)),this._previewObject=new d.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 d.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 d.BufferGeometry;e.setAttribute("position",new d.BufferAttribute(new Float32Array(i),3)),this._previewMeshObject=new d.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 Aa extends ta{constructor(e){super(e),t(this,"enabled",!0),t(this,"_ownsChildGeometry",!1),t(this,"definitions",new h.DataMap),this.styles.set("default",{color:0,textOffset:0,fontSize:0})}pickHandle(e,t,i){return null}pick(e,t=.05){const i=new d.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 d.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 d.Group;if(i.lines){const t=new d.LineSegments(i.lines,this._getMaterial(e.style));t.layers.set(1),t.userData.isDimension=!0,n.add(t)}if(i.mesh){const t=new d.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(){var e,t;for(const i of this.definitions.values())null==(e=i.lines)||e.dispose(),null==(t=i.mesh)||t.dispose();this.definitions.clear()}}function Ea(e,t){const{position:i,direction:n}=e,{length:s}=t,r=new d.Vector3(i.x+n.x*s,0,i.z+n.z*s),o=new d.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 Ma(e,t){return new d.Vector3(e.position.x+e.direction.x*t,0,e.position.z+e.direction.z*t)}function Pa(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 Ia extends ta{constructor(e){super(e),t(this,"enabled",!0),this.styles.set("default",{lineTick:$o,meshTick:Wo,tickSize:.4,length:3,color:0,textOffset:.1,fontSize:.45,format:"percentage"})}pickHandle(e,t,i){return null}_buildGroup(e,t){const i=new d.Group,n=Ea(e,t),s=new d.BufferGeometry;s.setAttribute("position",new d.BufferAttribute(n,3));const r=new d.LineSegments(s,this._getMaterial(e.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),t.meshTick){const n=Ma(e,t.length),s=t.meshTick(n,e.direction,t.tickSize),r=new d.BufferGeometry;r.setAttribute("position",new d.BufferAttribute(new Float32Array(s),3));const o=new d.Mesh(r,this._getMeshMaterial(e.style));o.layers.set(1),o.userData.isDimension=!0,i.add(o)}return i}}function za(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 d.Vector3(e.x+Math.cos(o)*s,0,e.z+Math.sin(o)*s)}function Da(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:za(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",center:e.center,halfW:e.halfW,halfH:e.halfH,elbow:e.elbow,extensionEnd:za(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:d.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 ka(e,t){const i=[];i.push(...t.enclosure.buildGeometry(e.center,e.halfW,e.halfH));const n=(new d.Vector3).subVectors(e.elbow,e.center),s=n.lengthSq()>1e-10?n.clone().normalize():new d.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 d.Vector3).subVectors(e.extensionEnd,e.elbow);n.lengthSq()>1e-10&&i.push(...t.lineTick(e.extensionEnd,n.normalize(),t.tickSize))}return i}function Ba(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 c=[];if(c.push(...o.enclosure.buildGeometry(t,a,l)),"awaitingRadius"===e)return c;const h="awaitingElbow"===e?r:s;if(!h)return c;const u=(new d.Vector3).subVectors(h,t),p=u.lengthSq()>1e-10?u.clone().normalize():new d.Vector3(1,0,0),f=o.enclosure.getAttachmentPoint(t,a,l,p);return"awaitingElbow"===e?(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 Oa={buildGeometry(e,t,i){const n=.25*Math.min(t,i),s=new d.Vector3(e.x-t,0,e.z-i),r=new d.Vector3(e.x+t,0,e.z-i),o=new d.Vector3(e.x+t,0,e.z+i),a=new d.Vector3(e.x-t,0,e.z+i),l=[[s,r,new d.Vector3(0,0,-1)],[r,o,new d.Vector3(1,0,0)],[o,a,new d.Vector3(0,0,1)],[a,s,new d.Vector3(-1,0,0)]],c=[];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 d.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 d.Vector3).subVectors(s,n);let h=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 d.Vector3(s,0,o);c.push(h.x,0,h.z,l.x,0,l.z),h=l}}}return c},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 d.Vector3(e.x+n.x*o,0,e.z+n.z*o)}},Va={buildGeometry(e,t,i){const n=new d.Vector3(e.x-t,0,e.z-i),s=new d.Vector3(e.x+t,0,e.z-i),r=new d.Vector3(e.x+t,0,e.z+i),o=new d.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 d.Vector3(e.x+n.x*o,0,e.z+n.z*o)}},La={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 d.Vector3(e.x+n.x*a,0,e.z+n.z*a)}};class Na extends ta{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingCenter"}),t(this,"onMachineStateChanged",new f),this.styles.set("default",{enclosure:Oa,lineTick:jo,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=Da(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 d.Group,n=ka(e,t),s=new d.BufferGeometry;s.setAttribute("position",new d.BufferAttribute(new Float32Array(n),3));const r=new d.LineSegments(s,this._getMaterial(e.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),t.meshTick){const n=(new d.Vector3).subVectors(e.extensionEnd,e.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=t.meshTick(e.extensionEnd,n,t.tickSize),r=new d.BufferGeometry;r.setAttribute("position",new d.BufferAttribute(new Float32Array(s),3));const o=new d.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 Ba("awaitingRadius",e.center,0,0,null,e.cursor,t);case"awaitingElbow":return Ba("awaitingElbow",e.center,e.halfW,e.halfH,null,e.cursor,t);case"awaitingExtension":return Ba("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 d.BufferGeometry;e.setAttribute("position",new d.BufferAttribute(new Float32Array(i),3)),this._previewObject=new d.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)}}const Fa=class e extends g{constructor(i){super(i),t(this,"enabled",!0),t(this,"list",new h.DataMap),t(this,"systems",new h.DataMap),t(this,"onDisposed",new f),i.add(e.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 ea(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 Zr&&(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()}};t(Fa,"uuid","5c7d3b9a-4e8f-4a2b-9c1d-0e3f2a5b7c8d");let Ra=Fa;const Ua=[[16711680,1],[16776960,2],[65280,3],[65535,4],[255,5],[16711935,6],[16777215,7],[0,7]];function ja(e){const t=e>>16&255,i=e>>8&255,n=255&e;let s=7,r=1/0;for(const[e,o]of Ua){const a=(t-(e>>16&255))**2+(i-(e>>8&255))**2+(n-(255&e))**2;a<r&&(r=a,s=o)}return s}class $a{constructor(){t(this,"_lines",[]),t(this,"_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()}build(){return this._lines.join("\n")+"\n"}}class Wa{constructor(e){t(this,"precision",2),t(this,"config",{trueColor:!1}),t(this,"_viewport",null),t(this,"_paperSlot",null),t(this,"_annotationLayers",new Map),t(this,"_systemExporters",new Map),this._components=e}registerSystemExporter(e,t){this._systemExporters.set(e,t)}export(e,t){const i=!!t,n=new $a,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(Ra).systems.get(Aa),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,"$INSUNITS").p(70,t?4:6),e.p(0,"ENDSEC")}_writeTables(e,t,i){e.p(0,"SECTION").p(2,"TABLES"),e.p(0,"TABLE").p(2,"VPORT").p(70,0).p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"LTYPE").p(70,1),e.p(0,"LTYPE").p(2,"CONTINUOUS").p(70,0).p(3,"Solid line").p(72,65).p(73,0).n(40,0),e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"LAYER").p(70,t.length);for(const i of t){const t=ja(i.material.color.getHex());e.p(0,"LAYER").p(2,i.name).p(70,0).p(62,t).p(6,"CONTINUOUS")}e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"STYLE").p(70,1),e.p(0,"STYLE").p(2,"STANDARD").p(70,0).n(40,0).n(41,1).n(50,0).p(71,0).n(42,.2).p(3,"txt").p(4,""),e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"VIEW").p(70,0).p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"UCS").p(70,0).p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"APPID").p(70,1),e.p(0,"APPID").p(2,"ACAD").p(70,0),e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"DIMSTYLE").p(70,0).p(0,"ENDTAB");const n=["*Model_Space","*Paper_Space",...i];e.p(0,"TABLE").p(2,"BLOCK_RECORD").p(70,n.length);for(const t of n)e.p(0,"BLOCK_RECORD").p(5,e.handle()).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(8,"0").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(8,"0")}_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,"AcDbRootDictionary"),e.p(0,"ENDSEC")}_writeRawLines(e,t){t.three.traverse(t=>{var i;if(!(t instanceof d.LineSegments))return;if(t.userData.isDimension)return;if(null==(i=t.parent)?void 0:i.userData.blockUuid)return;if(!t.visible)return;const n=t.userData.layer??"0",s=t.material.color.getHex();this._writeGeoAsLines(e,t.geometry,n,ja(s),s)})}_writeLinearAnnotations(e,t){var i;const n=this._components.get(Ra).systems.get(la);if(n)for(const[,s]of t.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=ja(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=t.layers.get(a))?void 0:i.visible))continue;const l=oa(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick)for(const{tip:t,dir:i}of ra(s))this._writeMeshTriangles(e,r.meshTick(t,i,r.tickSize),a,o,r.color);const c=(new d.Vector3).subVectors(s.pointB,s.pointA),h=new d.Vector3(-c.z,0,c.x).normalize(),u=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)*u),g=r.unit??{factor:1,suffix:"m"},w=`${(s.pointA.distanceTo(s.pointB)*g.factor).toFixed(this.precision)} ${g.suffix}`;this._writeText(e,w,m.x,m.z,r.fontSize,a,o,this._textAngle(c.x,c.z),1,2,r.color)}}_writeAngleAnnotations(e,t){var i;const n=this._components.get(Ra).systems.get(_a);if(n)for(const[,s]of t.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=ja(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=t.layers.get(a))?void 0:i.visible))continue;const l=wa(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick)for(const{tip:t,dir:i}of pa(s))this._writeMeshTriangles(e,r.meshTick(t,i,r.tickSize),a,o,r.color);const c=ma(s),h=s.arcRadius+r.textOffset,u=s.vertex.x+Math.cos(c)*h,p=s.vertex.z+Math.sin(c)*h,f=d.MathUtils.radToDeg(fa(s));this._writeText(e,`${f.toFixed(this.precision)}°`,u,p,r.fontSize,a,o,0,1,0,r.color)}}_writeLeaderAnnotations(e,t){var i;const n=this._components.get(Ra).systems.get(Ta);if(n)for(const[,s]of t.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=ja(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=t.layers.get(a))?void 0:i.visible))continue;const l=Sa(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick){const t=(new d.Vector3).subVectors(s.arrowTip,s.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,r.meshTick(s.arrowTip,t.normalize(),r.tickSize),a,o,r.color)}const c=(new d.Vector3).subVectors(s.extensionEnd,s.elbow).setY(0).normalize(),h=c.x<-.1?2:c.x>.1?0:1,u=1===h?.5*r.fontSize:0,p=s.extensionEnd.clone().addScaledVector(c,r.textOffset+u);this._writeText(e,s.text,p.x,p.z,r.fontSize,a,o,0,h,2,r.color)}}_writeSlopeAnnotations(e,t){var i;const n=this._components.get(Ra).systems.get(Ia);if(n)for(const[,s]of t.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=ja(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=t.layers.get(a))?void 0:i.visible))continue;const l=Ea(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick){const t=Ma(s,r.length);this._writeMeshTriangles(e,r.meshTick(t,s.direction,r.tickSize),a,o,r.color)}const c=new d.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 d.Vector3(-s.direction.z,0,s.direction.x),r.textOffset+r.fontSize);this._writeText(e,Pa(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(e,t){var i;const n=this._components.get(Ra).systems.get(Na);if(n)for(const[,s]of t.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=ja(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=t.layers.get(a))?void 0:i.visible))continue;const l=ka(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick){const t=(new d.Vector3).subVectors(s.extensionEnd,s.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,r.meshTick(s.extensionEnd,t.normalize(),r.tickSize),a,o,r.color)}const c=(new d.Vector3).subVectors(s.extensionEnd,s.elbow).setY(0).normalize(),h=c.x<-.1?2:c.x>.1?0:1,u=1===h?.5*r.fontSize:0,p=s.extensionEnd.clone().addScaledVector(c,r.textOffset+u);this._writeText(e,s.text,p.x,p.z,r.fontSize,a,o,0,h,2,r.color)}}_writeBlockInsertions(e,t){const i=this._components.get(Ra).systems.get(Aa);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=ja(t.color),r=-d.MathUtils.radToDeg(n.rotation),o=n.scale*this._scale();e.p(0,"INSERT").p(5,e.handle()).p(8,"0").p(62,s),this._emitTrueColor(e,t.color),e.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 d.Vector3(r.getX(t),0,r.getZ(t)),new d.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 d.Vector3(t[r],0,t[r+2]),new d.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.p(0,"LINE").p(5,e.handle()).p(8,r).p(62,o),this._emitTrueColor(e,a),e.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.p(0,"LINE").p(5,e.handle()).p(8,r).p(62,o).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.p(0,"SOLID").p(5,e.handle()).p(8,a).p(62,l),this._emitTrueColor(e,c),e.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 d=this._tx(i),u=this._ty(n);e.p(0,"TEXT").p(5,e.handle()).p(8,r).p(62,o),this._emitTrueColor(e,h),e.n(10,d).n(20,u).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,d).n(21,u).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 d.Line3(e,t)):new d.Line3(e,t)}_inViewport(e,t){return!this._viewport||this._viewport.bbox.containsPoint(new d.Vector3(e,0,t))}_bboxFromPositions(e){const t=new d.Box3;for(let i=0;i+2<e.length;i+=3)t.expandByPoint(new d.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),d.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(Ra).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:ja,textAngle:(e,t)=>this._textAngle(e,t)}}}const Ga=class e extends g{constructor(i){super(i),t(this,"enabled",!0),t(this,"exporter",new Wa(this.components)),i.add(e.uuid,this)}};t(Ga,"uuid","e9a2c3d4-5f67-4b89-a012-1c3d5e7f9b2a");let Ha=Ga;exports.AngleAnnotations=_a,exports.AnnotationSystem=ta,exports.ArrowTick=(e,t,i)=>{const n=new d.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{constructor(){t(this,"enabled",!0),t(this,"trigger",async e=>{if(!this.enabled)return;const t=this.handlers.slice(0);for(const i of t)await i(e)}),t(this,"handlers",[])}add(e){this.handlers.push(e)}remove(e){this.handlers=this.handlers.filter(t=>t!==e)}reset(){this.handlers.length=0}},exports.BCFTopics=oo,exports.BCFTopicsConfigManager=so,exports.Base=m,exports.BaseCamera=y,exports.BaseRenderer=_,exports.BaseScene=x,exports.BaseWorldItem=w,exports.BlockAnnotations=Aa,exports.BoundingBoxer=wr,exports.CalloutAnnotations=Na,exports.CircleEnclosure=La,exports.Classifier=xr,exports.Clipper=ho,exports.CloudEnclosure=Oa,exports.Comment=eo,exports.Component=g,exports.Components=$r,exports.ConfigManager=He,exports.Configurator=We,exports.ControlsUtils=$e,exports.DataMap=je,exports.DataSet=S,exports.DiagonalTick=Uo,exports.Disposer=v,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=Go,exports.DrawingLayers=Ho,exports.DrawingSystem=ta,exports.DrawingViewport=Yo,exports.DrawingViewportHelper=Zo,exports.DrawingViewports=Xo,exports.DxfExporter=Wa,exports.DxfManager=Ha,exports.EdgeProjector=hr,exports.Event=f,exports.EventManager=class{constructor(){t(this,"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=Sr,exports.FastModelPickers=Tr,exports.FilledArrowTick=Wo,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 d.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=yr,exports.FirstPersonMode=Wr,exports.FragmentsManager=Zn,exports.Grids=Ur,exports.Hider=mr,exports.IDSAttribute=So,exports.IDSClassification=Co,exports.IDSEntity=To,exports.IDSFacet=vo,exports.IDSMaterial=Eo,exports.IDSPartOf=Mo,exports.IDSProperty=Ao,exports.IDSSpecification=Po,exports.IDSSpecifications=No,exports.IfcFragmentSettings=dr,exports.IfcLoader=pr,exports.ItemsFinder=br,exports.LeaderAnnotations=Ta,exports.LinearAnnotations=la,exports.MeasurementUtils=Ro,exports.ModelIdMapUtils=Ue,exports.Mouse=qe,exports.NoTick=$o,exports.OpenArrowTick=jo,exports.OrbitMode=Gr,exports.OrthoPerspectiveCamera=Zr,exports.PlanMode=Hr,exports.ProjectionManager=qr,exports.Raycasters=Mr,exports.RectEnclosure=Va,exports.RendererMode=Br,exports.ShadowedScene=class extends kr{constructor(){super(...arguments),t(this,"_distanceRenderer"),t(this,"autoBias",!0),t(this,"_defaultShadowConfig",{cascade:1,resolution:512}),t(this,"_lightsWithShadow",new Map),t(this,"_isComputingShadows",!1),t(this,"_shadowsEnabled",!0),t(this,"_bias",0),t(this,"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 d.PerspectiveCamera||t instanceof d.OrthographicCamera))throw new Error("Invalid camera type!");const i=new d.Vector3;t.getWorldDirection(i);let n=e;const s=new d.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 d.Vector3;a.copy(i);const l=e===this._lightsWithShadow.size-1,c=l?n/2:2*n/3;a.multiplyScalar(c),a.add(t.position);const h=n-c,u=new d.Vector3;u.copy(s),u.multiplyScalar(h),o.target.position.copy(a),o.position.copy(a),o.position.add(u),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(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 bo(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let e=0;e<t.cascade;e++){const i=new d.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())}},exports.SimpleCamera=Or,exports.SimpleGrid=Fr,exports.SimpleGridConfigManager=Nr,exports.SimplePlane=ao,exports.SimpleRaycaster=Ar,exports.SimpleRenderer=class extends _{constructor(e,i,n){super(e),t(this,"enabled",!0),t(this,"container"),t(this,"three"),t(this,"mode",1),t(this,"needsUpdate",!1),t(this,"_canvas"),t(this,"_parameters"),t(this,"_resizeObserver",null),t(this,"onContainerUpdated",new f),t(this,"_resizing",!1),t(this,"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 d.Vector2(t,i)),this._resizing=!1}),t(this,"resizeEvent",()=>{this.resize()}),t(this,"onContextLost",e=>{e.preventDefault(),this.enabled=!1}),t(this,"onContextBack",()=>{this.three.setRenderTarget(null),this.three.dispose(),this.three=new d.WebGLRenderer({canvas:this._canvas,antialias:!0,alpha:!0,...this._parameters}),this.enabled=!0}),this.container=i,this._parameters=n,this.three=new d.WebGLRenderer({antialias:!0,alpha:!0,...n}),this.three.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.setupRenderer(),this.setupEvents(!0),this.resize(),this._canvas=this.three.domElement;const s=this.three.getContext(),{canvas:r}=s;r.addEventListener("webglcontextlost",this.onContextLost,!1),r.addEventListener("webglcontextrestored",this.onContextBack,!1)}update(){if(!this.enabled||!this.currentWorld)return;if(0===this.mode&&!this.needsUpdate)return;this.needsUpdate=!1,this.onBeforeUpdate.trigger(this);const 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.three.forceContextLoss(),this.three.dispose(),this.onResize.reset(),this.onAfterUpdate.reset(),this.onBeforeUpdate.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}getSize(){return new d.Vector2(this.three.domElement.clientWidth,this.three.domElement.clientHeight)}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))}setupRenderer(){this.three.localClippingEnabled=!0,this.container&&this.container.appendChild(this.three.domElement),this.onContainerUpdated.trigger()}},exports.SimpleScene=kr,exports.SimpleSceneConfigManager=Dr,exports.SimpleWorld=Pr,exports.SlopeAnnotations=Ia,exports.TechnicalDrawing=ea,exports.TechnicalDrawingHelper=Qo,exports.TechnicalDrawings=Ra,exports.Topic=io,exports.UUID=T,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(e,i){super(e),t(this,"onDisposed",new f),t(this,"onVertexFound",new f),t(this,"onVertexLost",new f),t(this,"onEnabled",new f),t(this,"components"),t(this,"workingPlane",null),t(this,"_pickedPoint",null),t(this,"_config"),t(this,"_enabled",!1),this.components=e,this.config={snapDistance:.25,showOnlyVertex:!1,...i},this.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}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(Mr).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=go,exports.Viewpoint=uo,exports.Viewpoints=mo,exports.Views=yo,exports.Worlds=Lr,exports.XML=Re,exports.angleDimensionMachine=ua,exports.buildAnglePositions=wa,exports.buildAnglePreviewPositions=ya,exports.buildCalloutPositions=ka,exports.buildCalloutPreviewPositions=Ba,exports.buildDimensionPositions=oa,exports.buildDimensions=na,exports.buildLeaderPositions=Sa,exports.buildLeaderPreviewPositions=Ca,exports.buildPreviewPositions=aa,exports.buildSlopePositions=Ea,exports.calloutAnnotationMachine=Da,exports.computeAlignmentMatrix=Jo,exports.computeAngle=fa,exports.computeBisectorAngle=ma,exports.computeOffset=ia,exports.extensionsImporter=no,exports.formatSlope=Pa,exports.getAngleTickEndpoints=pa,exports.getDimensionTickEndpoints=ra,exports.getSlopeTip=Ma,exports.leaderAnnotationMachine=va,exports.linearDimensionMachine=sa;
|
|
12
|
+
*/const $o=Ro(jo.exports=function t(e,i,n){function s(o,a){if(!i[o]){if(!e[o]){if(!a&&Uo)return Uo(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=Uo,o=0;o<n.length;o++)s(n[o]);return s}({1:[function(t,e,i){var n=t("./utils"),s=t("./support"),r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(t){for(var e,i,s,o,a,l,c,h=[],u=0,d=t.length,p=d,f="string"!==n.getTypeOf(t);u<t.length;)p=d-u,s=f?(e=t[u++],i=u<d?t[u++]:0,u<d?t[u++]:0):(e=t.charCodeAt(u++),i=u<d?t.charCodeAt(u++):0,u<d?t.charCodeAt(u++):0),o=e>>2,a=(3&e)<<4|i>>4,l=1<p?(15&i)<<2|s>>6:64,c=2<p?63&s:64,h.push(r.charAt(o)+r.charAt(a)+r.charAt(l)+r.charAt(c));return h.join("")},i.decode=function(t){var e,i,n,o,a,l,c=0,h=0,u="data:";if(t.substr(0,u.length)===u)throw new Error("Invalid base64 input, it looks like a data url.");var d,p=3*(t=t.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(t.charAt(t.length-1)===r.charAt(64)&&p--,t.charAt(t.length-2)===r.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(d=s.uint8array?new Uint8Array(0|p):new Array(0|p);c<t.length;)e=r.indexOf(t.charAt(c++))<<2|(o=r.indexOf(t.charAt(c++)))>>4,i=(15&o)<<4|(a=r.indexOf(t.charAt(c++)))>>2,n=(3&a)<<6|(l=r.indexOf(t.charAt(c++))),d[h++]=e,64!==a&&(d[h++]=i),64!==l&&(d[h++]=n);return d}},{"./support":30,"./utils":32}],2:[function(t,e,i){var n=t("./external"),s=t("./stream/DataWorker"),r=t("./stream/Crc32Probe"),o=t("./stream/DataLengthProbe");function a(t,e,i,n,s){this.compressedSize=t,this.uncompressedSize=e,this.crc32=i,this.compression=n,this.compressedContent=s}a.prototype={getContentWorker:function(){var t=new s(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o("data_length")),e=this;return t.on("end",(function(){if(this.streamInfo.data_length!==e.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")})),t},getCompressedWorker:function(){return new s(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(t,e,i){return t.pipe(new r).pipe(new o("uncompressedSize")).pipe(e.compressWorker(i)).pipe(new o("compressedSize")).withStreamInfo("compression",e)},e.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,e,i){var n=t("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new n("STORE compression")},uncompressWorker:function(){return new n("STORE decompression")}},i.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,e,i){var n=t("./utils"),s=function(){for(var t,e=[],i=0;i<256;i++){t=i;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e}();e.exports=function(t,e){return void 0!==t&&t.length?"string"!==n.getTypeOf(t)?function(t,e,i,n){var r=s,o=n+i;t^=-1;for(var a=n;a<o;a++)t=t>>>8^r[255&(t^e[a])];return~t}(0|e,t,t.length,0):function(t,e,i,n){var r=s,o=n+i;t^=-1;for(var a=n;a<o;a++)t=t>>>8^r[255&(t^e.charCodeAt(a))];return~t}(0|e,t,t.length,0):0}},{"./utils":32}],5:[function(t,e,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(t,e,i){var n=null;n="undefined"!=typeof Promise?Promise:t("lie"),e.exports={Promise:n}},{lie:37}],7:[function(t,e,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,s=t("pako"),r=t("./utils"),o=t("./stream/GenericWorker"),a=n?"uint8array":"array";function l(t,e){o.call(this,"FlateWorker/"+t),this._pako=null,this._pakoAction=t,this._pakoOptions=e,this.meta={}}i.magic="\b\0",r.inherits(l,o),l.prototype.processChunk=function(t){this.meta=t.meta,null===this._pako&&this._createPako(),this._pako.push(r.transformTo(a,t.data),!1)},l.prototype.flush=function(){o.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},l.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this._pako=null},l.prototype._createPako=function(){this._pako=new s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var t=this;this._pako.onData=function(e){t.push({data:e,meta:t.meta})}},i.compressWorker=function(t){return new l("Deflate",t)},i.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(t,e,i){function n(t,e){var i,n="";for(i=0;i<e;i++)n+=String.fromCharCode(255&t),t>>>=8;return n}function s(t,e,i,s,o,h){var u,d,p=t.file,f=t.compression,m=h!==a.utf8encode,g=r.transformTo("string",h(p.name)),w=r.transformTo("string",a.utf8encode(p.name)),y=p.comment,_=r.transformTo("string",h(y)),b=r.transformTo("string",a.utf8encode(y)),v=w.length!==p.name.length,x=b.length!==y.length,C="",S="",A="",P=p.dir,T=p.date,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!==Fo?Fo:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(t,e,i){var n=t("immediate");function s(){}var r={},o=["REJECTED"],a=["FULFILLED"],l=["PENDING"];function c(t){if("function"!=typeof t)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,t!==s&&p(this,t)}function h(t,e,i){this.promise=t,"function"==typeof e&&(this.onFulfilled=e,this.callFulfilled=this.otherCallFulfilled),"function"==typeof i&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}function u(t,e,i){n((function(){var n;try{n=e(i)}catch(e){return r.reject(t,e)}n===t?r.reject(t,new TypeError("Cannot resolve promise with itself")):r.resolve(t,n)}))}function d(t){var e=t&&t.then;if(t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof e)return function(){e.apply(t,arguments)}}function p(t,e){var i=!1;function n(e){i||(i=!0,r.reject(t,e))}function s(e){i||(i=!0,r.resolve(t,e))}var o=f((function(){e(s,n)}));"error"===o.status&&n(o.value)}function f(t,e){var i={};try{i.value=t(e),i.status="success"}catch(t){i.status="error",i.value=t}return i}(e.exports=c).prototype.finally=function(t){if("function"!=typeof t)return this;var e=this.constructor;return this.then((function(i){return e.resolve(t()).then((function(){return i}))}),(function(i){return e.resolve(t()).then((function(){throw i}))}))},c.prototype.catch=function(t){return this.then(null,t)},c.prototype.then=function(t,e){if("function"!=typeof t&&this.state===a||"function"!=typeof e&&this.state===o)return this;var i=new this.constructor(s);return this.state!==l?u(i,this.state===a?t:e,this.outcome):this.queue.push(new h(i,t,e)),i},h.prototype.callFulfilled=function(t){r.resolve(this.promise,t)},h.prototype.otherCallFulfilled=function(t){u(this.promise,this.onFulfilled,t)},h.prototype.callRejected=function(t){r.reject(this.promise,t)},h.prototype.otherCallRejected=function(t){u(this.promise,this.onRejected,t)},r.resolve=function(t,e){var i=f(d,e);if("error"===i.status)return r.reject(t,i.value);var n=i.value;if(n)p(t,n);else{t.state=a,t.outcome=e;for(var s=-1,o=t.queue.length;++s<o;)t.queue[s].callFulfilled(e)}return t},r.reject=function(t,e){t.state=o,t.outcome=e;for(var i=-1,n=t.queue.length;++i<n;)t.queue[i].callRejected(e);return t},c.resolve=function(t){return t instanceof this?t:r.resolve(new this(s),t)},c.reject=function(t){var e=new this(s);return r.reject(e,t)},c.all=function(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,n=!1;if(!i)return this.resolve([]);for(var o=new Array(i),a=0,l=-1,c=new this(s);++l<i;)h(t[l],l);return c;function h(t,s){e.resolve(t).then((function(t){o[s]=t,++a!==i||n||(n=!0,r.resolve(c,o))}),(function(t){n||(n=!0,r.reject(c,t))}))}},c.race=function(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,n=!1;if(!i)return this.resolve([]);for(var o,a=-1,l=new this(s);++a<i;)o=t[a],e.resolve(o).then((function(t){n||(n=!0,r.resolve(l,t))}),(function(t){n||(n=!0,r.reject(l,t))}));return l}},{immediate:36}],38:[function(t,e,i){var n={};(0,t("./lib/utils/common").assign)(n,t("./lib/deflate"),t("./lib/inflate"),t("./lib/zlib/constants")),e.exports=n},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(t,e,i){var n=t("./zlib/deflate"),s=t("./utils/common"),r=t("./utils/strings"),o=t("./zlib/messages"),a=t("./zlib/zstream"),l=Object.prototype.toString,c=0,h=-1,u=0,d=8;function p(t){if(!(this instanceof p))return new p(t);this.options=s.assign({level:h,method:d,chunkSize:16384,windowBits:15,memLevel:8,strategy:u,to:""},t||{});var e=this.options;e.raw&&0<e.windowBits?e.windowBits=-e.windowBits:e.gzip&&0<e.windowBits&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var i=n.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==c)throw new Error(o[i]);if(e.header&&n.deflateSetHeader(this.strm,e.header),e.dictionary){var f;if(f="string"==typeof e.dictionary?r.string2buf(e.dictionary):"[object ArrayBuffer]"===l.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,(i=n.deflateSetDictionary(this.strm,f))!==c)throw new Error(o[i]);this._dict_set=!0}}function f(t,e){var i=new p(e);if(i.push(t,!0),i.err)throw i.msg||o[i.err];return i.result}p.prototype.push=function(t,e){var i,o,a=this.strm,h=this.options.chunkSize;if(this.ended)return!1;o=e===~~e?e:!0===e?4:0,"string"==typeof t?a.input=r.string2buf(t):"[object ArrayBuffer]"===l.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new s.Buf8(h),a.next_out=0,a.avail_out=h),1!==(i=n.deflate(a,o))&&i!==c)return this.onEnd(i),!(this.ended=!0);0!==a.avail_out&&(0!==a.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(r.buf2binstring(s.shrinkBuf(a.output,a.next_out))):this.onData(s.shrinkBuf(a.output,a.next_out)))}while((0<a.avail_in||0===a.avail_out)&&1!==i);return 4===o?(i=n.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===c):2!==o||(this.onEnd(c),!(a.avail_out=0))},p.prototype.onData=function(t){this.chunks.push(t)},p.prototype.onEnd=function(t){t===c&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},i.Deflate=p,i.deflate=f,i.deflateRaw=function(t,e){return(e=e||{}).raw=!0,f(t,e)},i.gzip=function(t,e){return(e=e||{}).gzip=!0,f(t,e)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(t,e,i){var n=t("./zlib/inflate"),s=t("./utils/common"),r=t("./utils/strings"),o=t("./zlib/constants"),a=t("./zlib/messages"),l=t("./zlib/zstream"),c=t("./zlib/gzheader"),h=Object.prototype.toString;function u(t){if(!(this instanceof u))return new u(t);this.options=s.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&0<=e.windowBits&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(0<=e.windowBits&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),15<e.windowBits&&e.windowBits<48&&!(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var i=n.inflateInit2(this.strm,e.windowBits);if(i!==o.Z_OK)throw new Error(a[i]);this.header=new c,n.inflateGetHeader(this.strm,this.header)}function d(t,e){var i=new u(e);if(i.push(t,!0),i.err)throw i.msg||a[i.err];return i.result}u.prototype.push=function(t,e){var i,a,l,c,u,d,p=this.strm,f=this.options.chunkSize,m=this.options.dictionary,g=!1;if(this.ended)return!1;a=e===~~e?e:!0===e?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof t?p.input=r.binstring2buf(t):"[object ArrayBuffer]"===h.call(t)?p.input=new Uint8Array(t):p.input=t,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new s.Buf8(f),p.next_out=0,p.avail_out=f),(i=n.inflate(p,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&m&&(d="string"==typeof m?r.string2buf(m):"[object ArrayBuffer]"===h.call(m)?new Uint8Array(m):m,i=n.inflateSetDictionary(this.strm,d)),i===o.Z_BUF_ERROR&&!0===g&&(i=o.Z_OK,g=!1),i!==o.Z_STREAM_END&&i!==o.Z_OK)return this.onEnd(i),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&i!==o.Z_STREAM_END&&(0!==p.avail_in||a!==o.Z_FINISH&&a!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(l=r.utf8border(p.output,p.next_out),c=p.next_out-l,u=r.buf2string(p.output,l),p.next_out=c,p.avail_out=f-c,c&&s.arraySet(p.output,p.output,l,c,0),this.onData(u)):this.onData(s.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((0<p.avail_in||0===p.avail_out)&&i!==o.Z_STREAM_END);return i===o.Z_STREAM_END&&(a=o.Z_FINISH),a===o.Z_FINISH?(i=n.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===o.Z_OK):a!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),!(p.avail_out=0))},u.prototype.onData=function(t){this.chunks.push(t)},u.prototype.onEnd=function(t){t===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},i.Inflate=u,i.inflate=d,i.inflateRaw=function(t,e){return(e=e||{}).raw=!0,d(t,e)},i.ungzip=d},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(t,e,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;i.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var n in i)i.hasOwnProperty(n)&&(t[n]=i[n])}}return t},i.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var s={arraySet:function(t,e,i,n,s){if(e.subarray&&t.subarray)t.set(e.subarray(i,i+n),s);else for(var r=0;r<n;r++)t[s+r]=e[i+r]},flattenChunks:function(t){var e,i,n,s,r,o;for(e=n=0,i=t.length;e<i;e++)n+=t[e].length;for(o=new Uint8Array(n),e=s=0,i=t.length;e<i;e++)r=t[e],o.set(r,s),s+=r.length;return o}},r={arraySet:function(t,e,i,n,s){for(var r=0;r<n;r++)t[s+r]=e[i+r]},flattenChunks:function(t){return[].concat.apply([],t)}};i.setTyped=function(t){t?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,s)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,r))},i.setTyped(n)},{}],42:[function(t,e,i){var n=t("./common"),s=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch(t){s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){r=!1}for(var o=new n.Buf8(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function l(t,e){if(e<65537&&(t.subarray&&r||!t.subarray&&s))return String.fromCharCode.apply(null,n.shrinkBuf(t,e));for(var i="",o=0;o<e;o++)i+=String.fromCharCode(t[o]);return i}o[254]=o[254]=1,i.string2buf=function(t){var e,i,s,r,o,a=t.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(e=new n.Buf8(l),r=o=0;o<l;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),i<128?e[o++]=i:(i<2048?e[o++]=192|i>>>6:(i<65536?e[o++]=224|i>>>12:(e[o++]=240|i>>>18,e[o++]=128|i>>>12&63),e[o++]=128|i>>>6&63),e[o++]=128|63&i);return e},i.buf2binstring=function(t){return l(t,t.length)},i.binstring2buf=function(t){for(var e=new n.Buf8(t.length),i=0,s=e.length;i<s;i++)e[i]=t.charCodeAt(i);return e},i.buf2string=function(t,e){var i,n,s,r,a=e||t.length,c=new Array(2*a);for(i=n=0;i<a;)if((s=t[i++])<128)c[n++]=s;else if(4<(r=o[s]))c[n++]=65533,i+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&i<a;)s=s<<6|63&t[i++],r--;1<r?c[n++]=65533:s<65536?c[n++]=s:(s-=65536,c[n++]=55296|s>>10&1023,c[n++]=56320|1023&s)}return l(c,n)},i.utf8border=function(t,e){var i;for((e=e||t.length)>t.length&&(e=t.length),i=e-1;0<=i&&128==(192&t[i]);)i--;return i<0||0===i?e:i+o[t[i]]>e?i:e}},{"./common":41}],43:[function(t,e,i){e.exports=function(t,e,i,n){for(var s=65535&t,r=t>>>16&65535,o=0;0!==i;){for(i-=o=2e3<i?2e3:i;r=r+(s=s+e[n++]|0)|0,--o;);s%=65521,r%=65521}return s|r<<16}},{}],44:[function(t,e,i){e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(t,e,i){var n=function(){for(var t,e=[],i=0;i<256;i++){t=i;for(var n=0;n<8;n++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e}();e.exports=function(t,e,i,s){var r=n,o=s+i;t^=-1;for(var a=s;a<o;a++)t=t>>>8^r[255&(t^e[a])];return~t}},{}],46:[function(t,e,i){var n,s=t("../utils/common"),r=t("./trees"),o=t("./adler32"),a=t("./crc32"),l=t("./messages"),c=0,h=4,u=0,d=-2,p=-1,f=4,m=2,g=8,w=9,y=286,_=30,b=19,v=2*y+1,x=15,C=3,S=258,A=S+C+1,P=42,T=113,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!==Fo?Fo:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10));class Wo{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(Xo);this.author=n.config.author}set comment(t){var e;const i=this._components.get(Xo);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 Go=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(Xo);this.creationAuthor=s.config.author,this.relatedTopics.guard=t=>t!==this.guid}set type(t){const e=this._components.get(Xo),{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(Xo),{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(Xo);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(Xo);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(Xo);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(Xo),{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(Xo).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(Xo).list.set(this.guid,this),this}createComment(t,e){const i=new Wo(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(Xo).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(sa);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(Xo);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(sa);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(Xo);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={$Guid:this.guid,$TopicType:this.type,$TopicStatus:this.status,$ServerAssignedId:this.serverAssignedId,Title:this.title,CreationAuthor:this.creationAuthor,CreationDate:this.creationDate.toISOString(),Priority:this.priority,Index:"2.1"===i?this.index:void 0,ModifiedDate:null==(t=this.modifiedDate)?void 0:t.toISOString(),ModifiedAuthor:this.modifiedAuthor,DueDate:null==(e=this.dueDate)?void 0:e.toISOString(),AssignedTo:this.assignedTo,Description:this.description,Stage:this.stage,DocumentReferences:"3"===i?{DocumentReference:this.createDocumentReferencesTag(i)}:void 0,RelatedTopics:"3"===i?{RelatedTopic:this.createRelatedTopicTags()}:void 0,RelatedTopic:"2.1"===i?this.createRelatedTopicTags():void 0,Labels:"3"===i?{Label:this.createLabelTags()}:void 0,Viewpoints:"3"===i?{ViewPoint:this.createViewpointTags()}:void 0,Comments:"3"===i?{Comment:this.createCommentTags()}:void 0};"2.1"===i&&(n.Labels=this.createLabelTags(),n.DocumentReference=this.createDocumentReferencesTag(i));const s={Markup:{Topic:n}};return"2.1"===i&&(s.Markup.Viewpoints=this.createViewpointTags(),s.Markup.Comment=this.createCommentTags()),`<?xml version="1.0" encoding="UTF-8"?>\n ${ue.builder.build(s)}`}};e(Go,"default",{title:"BCF Topic",type:"Issue",status:"Active"});let Ho=Go;const qo=(t,e)=>{if(""===e.trim())return;const i=Xo.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 Zo extends me{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 Yo=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 Zo(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 Ho(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(sa);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 $o;e.file("bcf.version",`<?xml version="1.0" encoding="UTF-8"?>\n <Version VersionId="${this.config.version}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/release_3_0/Schemas/version.xsd"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n </Version>`);for(const[t,i]of this.documents.entries())"external"!==i.type&&e.file("2.1"===this.config.version?i.fileName:`documents/${t}`,i.data);if("3"===this.config.version){const t=[];for(const[e,i]of this.documents.entries()){const{type:n,description:s}=i;"external"!==n&&t.push(`<Document Guid="${e}">\n <Filename>${i.fileName}</Filename>\n ${s?`<Description>${s}</Description>`:""}\n </Document>`)}t.length>0&&e.file("documents.xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n <DocumentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="documents.xsd">\n <Documents>\n ${t.join("\n")}\n </Documents>\n </DocumentInfo>`)}e.file("bcf.extensions",this.serializeExtensions());const i=this.components.get(sa);for(const n of t){const t=e.folder(n.guid);t.file("markup.bcf",n.serialize());for(const e of n.viewpoints){const n=i.list.get(e);if(!n)continue;const s=n.title??n.guid;t.file(`${s}.bcfv`,await n.serialize());const r=i.snapshots.get(n.snapshot);if(!r)continue;const o=r?n.snapshot:n.guid,a=i.getSnapshotExtension(n.snapshot);t.file(`${o}.${a}`,r,{binary:!0})}}return await e.generateAsync({type:"blob"})}serializeExtensions(){const t=[...this.config.types].map((t=>`<TopicType>${t}</TopicType>`)).join("\n"),e=[...this.config.statuses].map((t=>`<TopicStatus>${t}</TopicStatus>`)).join("\n"),i=[...this.config.priorities].map((t=>`<Priority>${t}</Priority>`)).join("\n"),n=[...this.config.labels].map((t=>`<TopicLabel>${t}</TopicLabel>`)).join("\n"),s=[...this.config.stages].map((t=>`<Stage>${t}</Stage>`)).join("\n"),r=[...this.config.users].map((t=>`<User>${t}</User>`)).join("\n");return`\n <?xml version="1.0" encoding="UTF-8"?>\n <Extensions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-schema-location.xsd">\n ${0!==t.length?`<TopicTypes>\n${t}\n</TopicTypes>`:""}\n ${0!==e.length?`<TopicStatuses>\n${e}\n</TopicStatuses>`:""}\n ${0!==i.length?`<Priorities>\n${i}\n</Priorities>`:""}\n ${0!==n.length?`<TopicLabels>\n${n}\n</TopicLabels>`:""}\n ${0!==s.length?`<Stages>\n${s}\n</Stages>`:""}\n ${0!==r.length?`<Users>\n${r}\n</Users>`:""}\n </Extensions>\n `}processMarkupComment(t){const{Guid:e,Date:i,Author:n,Comment:s,Viewpoint:r}=t;if(!(e&&i&&n&&Wo))return null;const o=new Wo(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 $o;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=t.xmlParser.parse(e).Version.VersionId;h=String(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")));if(a&&p){const t=await p.async("string");qo(this,t)}const f=[],m=this.components.get(sa),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 ea(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 Ho(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=ue.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(Yo,"uuid","de977976-e4f6-4e4f-a01a-204727839802"),e(Yo,"xmlParser",new Xt({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 Xo=Yo;class Ko{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(ta),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(ta);i.renderer.setPlane(!0,this.three,c.localClippingPlanes),this._planeMesh=Ko.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(ta);this.world.renderer.setPlane(t,this.three,e.localClippingPlanes),this.notifyManager()}get visible(){return this._visible}set visible(t){this._visible=t,this._controls.getHelper().visible=t,this._helper.visible=t,this.toggleControls(t),this.notifyManager()}get meshes(){return[this._planeMesh,this._arrowBoundBox]}get planeMaterial(){return this._planeMesh.material}set planeMaterial(t){this._planeMesh.material=t}get size(){return this._sizeMultiplier}set size(t){this._sizeMultiplier=t,this.autoScale?this.updateScale():this._planeMesh.scale.set(t,t,t)}get helper(){return this._helper}get controls(){return this._controls}setFromNormalAndCoplanarPoint(t,e){this.reset(),this.normal.equals(t)||(this.normal.copy(t),this._helper.lookAt(t)),this.origin.copy(e),this._helper.position.copy(e),this._helper.updateMatrix(),this.update()}dispose(){var t;this._enabled=!1,(null==(t=this.world.camera)?void 0:t.controls)&&this.world.camera.controls.removeEventListener("update",this.updateScale),this.onDraggingStarted.reset(),this.onDraggingEnded.reset(),this._helper.removeFromParent(),this.world.renderer&&this.world.renderer.setPlane(!1,this.three),this._arrowBoundBox.removeFromParent(),this._arrowBoundBox.geometry.dispose(),this._planeMesh.geometry.dispose(),this._controls.getHelper().removeFromParent(),this._controls.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}reset(){const t=new 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 Qo extends me{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 Jo=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",Ko),e(this,"list",new h.DataMap),e(this,"config",new Qo(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 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(ys);if(t.initialized)this.subscribeToFragmentMaterials();else{const e=()=>{t.onFragmentsLoaded.remove(e),this.subscribeToFragmentMaterials()};t.onFragmentsLoaded.add(e)}}subscribeToFragmentMaterials(){const t=this.components.get(ys);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(To);for(const[,i]of e.list)if(i.renderer)return void(t.clippingPlanes=i.renderer.clippingPlanes)}dispose(){this._enabled=!1;this.components.get(we).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(wo).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(wo).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(To);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(Jo,"uuid","66290bc5-18c4-4cd1-9379-2e17a0617611");let ta=Jo;class ea{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(sa).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(ys);return await t.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const t=this._components.get(ys);return await t.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const t=this._components.get(ys),{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(ys);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(Xo).config.version}get topics(){return[...this._components.get(Xo).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(ta);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 No))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(ys);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(sa),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(sa),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(ta);for(const[e,i]of t.list)i.enabled&&this.clippingPlanes.add(e)}async applyVisibility(){const t=this._components.get(Fr);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(ys),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(ta);for(const[i,n]of e.list)n.enabled=t&&this.clippingPlanes.has(i)}setClippingVisibility(t){const e=this._components.get(ta);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(ys);let n="";if(this._components.get(Xo).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(ta),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(sa),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(ys),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 ia extends me{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 na=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 ia(this,this.components,"Viewpoints",t.uuid)),e(this,"onDisposed",new f),n.add(t.uuid,this)}create(t){const e=new ea(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(na,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");let sa=na;class ra{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",aa.defaultRange),e(this,"_world",null),e(this,"_helpersVisible",!1),e(this,"_planesEnabled",!1),this._components=t,this.camera=new No(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 oa=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(ys).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 ra(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 ra(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(ys),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(ys),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(Ur);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(oa,"uuid","fb22f1f5-6598-4664-a11d-de8963ae420f"),e(oa,"defaultRange",15);let aa=oa;async function la(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 ca{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 la(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 ha{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 ua=(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 da extends ha{constructor(t,i){super(t),e(this,"facetType","Attribute"),e(this,"name"),e(this,"value"),this.name=i}serialize(t){const e=ua("Name",this.name),i=ua("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(ys);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 pa extends ha{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=ua("System",this.system),i=ua("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 fa extends ha{constructor(t,i){super(t),e(this,"facetType","Entity"),e(this,"name"),e(this,"predefinedType"),this.name=i}serialize(t){const e=ua("Name",this.name),i=ua("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(ys),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)&&de.append(e,t,i._localId.value)}}else de.add(e,s)}async test(t,e,i){const n=this._components.get(ys);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(ys).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 ma extends ha{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=ua("PropertySet",this.propertySet),i=ua("BaseName",this.baseName),n=ua("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(ys);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));de.append(e,n,...a)}}}}async test(t,e,i={skipIfFails:!0}){const n=this._components.get(ys);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([...r],{relations:{IsDefinedBy:{attributes:!0,relations:!0},IsTypedBy:{attributes:!0,relations:!1},HasPropertySets:{attributes:!0,relations:!0},DefinesOcurrence:{attributes:!1,relations:!1}}});for(const t of o){const n=this.getItemChecks(e,s,t,i.skipIfFails);if(!n)continue;const r=(await this.getPsets(t)).filter((t=>{if(!("value"in t.Name))return!1;return!!this.evalRequirement(t.Name.value,this.propertySet,"PropertySet")&&(n.push({currentValue:t.Name.value,parameter:"PropertySet",pass:!0,requiredValue:this.propertySet}),!0)}));if(0!==r.length)for(const t of r){const e=this.getPropertyListName(t);if(!e)continue;const i=t[e];if(!Array.isArray(i)){n.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}const s=i.filter((t=>{if(!("value"in t._category)||!("value"in t.Name))return!1;if(this._unsupportedTypes.includes(t._category.value))return!1;return!!this.evalRequirement(t.Name.value,this.baseName,"BaseName")&&(n.push({currentValue:t.Name.value,parameter:"BaseName",pass:!0,requiredValue:this.baseName}),!0)}));if(0!==s.length)for(const t of s)this.evalValue(t,n),this.evalDataType(t,n),this.evalURI();else n.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName})}else n.push({currentValue:null,parameter:"PropertySet",pass:!1,requiredValue:this.propertySet})}}}getPropertyListName(t){let e;return"value"in t._category?("IFCPROPERTYSET"===t._category.value&&(e="HasProperties"),"IFCELEMENTQUANTITY"===t._category.value&&(e="Quantities"),e):e}getValueKey(t){return Object.keys(t).find((t=>/Value/.test(t)||/Values/.test(t)))}getTypePsets(t){if(!Array.isArray(t.IsTypedBy))return[];const[e]=t.IsTypedBy;return e&&Array.isArray(e.HasPropertySets)?e.HasPropertySets:[]}async getPsets(t){const e=this.getTypePsets(t);if(!Array.isArray(t.IsDefinedBy))return e;const i=[];for(const n of t.IsDefinedBy){if(!("value"in n.Name))continue;const t=n.Name.value,s=this.getPropertyListName(n);if(!t||!s)continue;const r=e.find((e=>"value"in e.Name&&e.Name.value===t));if(r&&Array.isArray(r.HasProperties)&&Array.isArray(n.HasProperties))for(const t of r.HasProperties){if(!("value"in t.Name))continue;const e=t.Name.value;n.HasProperties.find((t=>"value"in t.Name&&t.Name.value===e))||n.HasProperties.push(t)}i.push(n)}return i}evalValue(t,e){const i=this.getValueKey(t),n=t[i];if(!("value"in n))return!1;if(this.value){if(!i)return null==e||e.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;const t=structuredClone(this.value);"IFCLABEL"===n.type&&"simple"===t.type&&(t.parameter=String(t.parameter));return this.evalRequirement(n.value,t,"Value",e)}return!i||("string"!=typeof n.value||""!==n.value.trim()||(null==e||e.push({parameter:"Value",currentValue:"",pass:!1,requiredValue:this.value}),!1))}evalDataType(t,e){if(!this.dataType)return!0;const i=this.getValueKey(t);if(!i||!("value"in t[i]))return null==e||e.push({parameter:"DataType",currentValue:null,pass:!1,requiredValue:this.dataType}),!1;const n=t[i];return this.evalRequirement(n.type??null,{type:"simple",parameter:this.dataType},"DataType",e)}evalURI(){return!0}}class ga extends ha{constructor(){super(...arguments),e(this,"_ifcMaterialEntities",[/^IFCMATERIALLAYERSETUSAGE$/,/^IFCMATERIALCONSTITUENTSET$/,/^IFCMATERIAL$/,/^IFCMATERIALLIST$/]),e(this,"facetType","Material"),e(this,"value"),e(this,"uri")}serialize(t){if(!this.value||!this.uri)return"<material />";const e=ua("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(ys);for(const[n,s]of i.list){if(!t.find((t=>t.test(n))))continue;const i=await s.getItemsOfCategories(this._ifcMaterialEntities),r=Object.values(i).flat();if(0===r.length)continue;const o=await s.getItemsData(r,{relations:{AssociatedTo:{attributes:!0,relations:!1},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const t of o){if(!("value"in t._localId&&"value"in t._category&&Array.isArray(t.AssociatedTo)))continue;if(!this.hasValidMaterial(t))continue;const i=t.AssociatedTo.map((t=>"value"in t._localId&&t._localId.value?t._localId.value:null)).filter((t=>null!==t));de.append(e,n,...i)}}}async test(t,e,i={skipIfFails:!0}){const n=this._components.get(ys);for(const[s,r]of Object.entries(t)){const t=n.list.get(s);if(!t)continue;const o=await t.getItemsData([[...r][0]],{relations:{AssociatedTo:{attributes:!1,relations:!1},HasAssociations:{attributes:!0,relations:!0},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const t of o){const n=this.getItemChecks(e,s,t,i.skipIfFails);if(n)if(Array.isArray(t.HasAssociations))for(const e of t.HasAssociations){if(!this._ifcMaterialEntities.some((t=>"value"in e._category&&t.test(e._category.value))))continue;if(this.hasValidMaterial(e,n))break}else n.push({parameter:null,currentValue:null,requiredValue:this.value,pass:!1})}}}hasValidMaterial(t,e){let i=!1;if("value"in t._category&&"IFCMATERIAL"===t._category.value){this.evalValue(t,e)&&(i=!0)}else for(const[n,s]of Object.entries(t))if(["ForLayerSet","MaterialLayers","Material","MaterialConstituents","Materials"].includes(n)&&Array.isArray(s))for(const t of s){if("value"in t._category&&"IFCMATERIAL"===t._category.value){if(this.evalValue(t,e)){i=!0;break}}else{if(this.hasValidMaterial(t)){i=!0;break}}}return i}evalValue(t,e){if(!this.value)return null==e||e.push({parameter:null,currentValue:t.Name&&"value"in t.Name?t.Name.value:null,pass:!0}),!0;if(!("value"in t._category)||"IFCMATERIAL"!==t._category.value)return null;let i=!1;return t.Name&&"value"in t.Name&&(i=this.evalRequirement(t.Name.value,this.value,"Value",e)),i||(t.Category&&"value"in t.Category&&(i=this.evalRequirement(t.Category.value,this.value,"Value",e)),i)}}class wa extends ha{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 fa(t,i.name),this._entityFacet.predefinedType=i.predefinedType}set entity(t){this._entity=t;const{name:e,predefinedType:i}=t;this._entityFacet=new fa(this._components,e),this._entityFacet.predefinedType=i}get entity(){return this._entity}serialize(){return""}async getEntities(t,e){}async test(t){}}class ya{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(Ta).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 _a=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},ba=(t,e)=>{const i=[];for(const n of e){const e=n.name,s=_a(e);if(!s)continue;const r=new fa(t,s);n.cardinality&&(r.cardinality=n.cardinality),r.predefinedType=_a(n.predefinedType),r.instructions=n.instructions,i.push(r)}return i},va=(t,e)=>{const i=[];for(const n of e){const e=n.name,s=_a(e);if(!s)continue;const r=new da(t,s);n.cardinality&&(r.cardinality=n.cardinality),r.value=_a(n.value),r.instructions=n.instructions,i.push(r)}return i},xa=(t,e)=>{const i=[];for(const n of e){const e=new ga(t);n.cardinality&&(e.cardinality=n.cardinality);const s=_a(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},Ca=(t,e)=>{const i=[];for(const n of e){const e=n.propertySet,s=n.baseName,r=_a(e),o=_a(s);if(!o||!r)continue;const a=new ma(t,r,o);n.cardinality&&(a.cardinality=n.cardinality);const l=_a(n.value);a.value=l,a.dataType=n.dataType,a.uri=n.uri,a.instructions=n.instructions,i.push(a)}return i},Sa=(t,e)=>{const i=[];for(const n of e){const e=n.system,s=_a(e);if(!s)continue;const r=new pa(t,s);n.cardinality&&(r.cardinality=n.cardinality);const o=_a(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},Aa=(t,e)=>{const i=[];for(const n of e){const e=_a(n.entity.name);if(!e)continue;const s=_a(n.entity.predefinedType),r=new wa(t,{name:e,predefinedType:s});r.relation=n.relation,n.cardinality&&(r.cardinality=n.cardinality),r.instructions=n.instructions,i.push(r)}return i},Pa=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));de.append(e,n,...t);const r=[...s].filter((([,t])=>!t.pass)).map((([t])=>t));de.append(i,n,...r)}return{pass:e,fail:i}}create(t,e,i){const n=new ya(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=ba(this.components,i);a.push(...t)}if("attribute"===e){const t=va(this.components,i);a.push(...t)}if("material"===e){const t=xa(this.components,i);a.push(...t)}if("classification"===e){const t=Sa(this.components,i);a.push(...t)}if("property"===e){const t=Ca(this.components,i);a.push(...t)}if("partOf"===e){const t=Aa(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=ba(this.components,i);l.push(...t)}if("attribute"===e){const t=va(this.components,i);l.push(...t)}if("material"===e){const t=xa(this.components,i);l.push(...t)}if("classification"===e){const t=Sa(this.components,i);l.push(...t)}if("property"===e){const t=Ca(this.components,i);l.push(...t)}if("partOf"===e){const t=Aa(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 ${ko.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(Pa,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c"),e(Pa,"xmlParser",new Xt({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 Ta=Pa;const Ma=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(ys);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(Ma,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");let Ea=Ma;const Ia=(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]},Da=(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]},za=()=>[],ka=(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 Ba 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 Oa 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 Va=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(Va,"_BORDER_COLOR",22015),e(Va,"_BORDER_HOVER_COLOR",16746496),e(Va,"_LINE_THRESHOLD",.06),e(Va,"_HANDLE_DEFS",[{constraints:["left","top"]},{constraints:["right","top"]},{constraints:["right","bottom"]},{constraints:["left","bottom"]},{constraints:["top"]},{constraints:["right"]},{constraints:["bottom"]},{constraints:["left"]}]);let La=Va;class Na{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 La(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 Fa 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 Na(t);return this._container.add(e.camera),e.setContainer(this._container),this.set(e.uuid,e),e}}const Ra=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(Ra,"_FRAME_COLOR",22015),e(Ra,"_DEPTH_COLOR",22015);let Ua=Ra;function ja(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 $a{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 Ba),e(this,"layers",new Oa(this.three)),e(this,"activeLayer","0"),e(this,"far",10),e(this,"viewports",new Fa(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){ja(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:ls}),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(Br),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=>$a.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 Wa{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(El),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 Ga(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 Ha(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 qa(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=Ga(t.points,e.point);return{kind:"committed",dimensions:Ha(t.points,i)}}return"ESCAPE"===e.type?{kind:"awaitingFirstPoint"}:t;case"committed":return"ESCAPE"===e.type?{kind:"awaitingFirstPoint"}:t}var i,n}function Za(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 Ya(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 Xa(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=Ga(e,i),r=[];for(let t=0;t<e.length-1;t++)r.push(...Ya({uuid:"",pointA:e[t],pointB:e[t+1],offset:s,style:""},n));return r}class Ka extends Wa{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingFirstPoint"}),e(this,"onMachineStateChanged",new f),this.styles.set("default",{lineTick:Ia,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=qa(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=Ya(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 Za(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=Xa(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 Qa=Math.PI/180;function Ja(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 tl(t,e,i,n){return Ja(t,e,i,n)<0}function el(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(Qa))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=tl(t.pointA,t.vertex,t.pointB,e.point);return{...t,cursor:e.point.clone(),flipped:i}}if("CLICK"===e.type){const i=tl(t.pointA,t.vertex,t.pointB,e.point),n=Math.max(.05,Math.abs(Ja(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 il(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 nl(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 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;const r=n+s/2;return t.flipped?r+Math.PI:r}function rl(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 ol(t,e){const i=(new u.Vector3).subVectors(t.pointA,t.vertex).normalize(),n=(new u.Vector3).subVectors(t.pointB,t.vertex).normalize();return rl(t.vertex,i,n,t.arcRadius,e,t.flipped??!1)}function al(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 rl(e,(new u.Vector3).subVectors(t,e).normalize(),(new u.Vector3).subVectors(i,e).normalize(),o,s,r)}class ll extends Wa{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:Ia,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=el(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=ol(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 il(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=al(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=al(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 cl(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 hl(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:cl(t.elbow,e.point)}:"CLICK"===e.type?{kind:"enteringText",arrowTip:t.arrowTip,elbow:t.elbow,extensionEnd:cl(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 ul(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 dl(t,e){return ul(t.arrowTip,t.elbow,t.extensionEnd,e)}function pl(t,e,i,n,s){return n?ul(e,"placingElbow"===t?n:i,n,s):[]}class fl extends Wa{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:Da})}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=hl(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=dl(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?pl("placingElbow",t.arrowTip,null,t.cursor,e):pl("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 ml extends Wa{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 gl(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 wl(t,e){return new u.Vector3(t.position.x+t.direction.x*e,0,t.position.z+t.direction.z*e)}function yl(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 _l extends Wa{constructor(t){super(t),e(this,"enabled",!0),this.styles.set("default",{lineTick:za,meshTick:ka,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=gl(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=wl(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 bl(t,e){const i=e.x-t.x,n=e.z-t.z,s=Math.sqrt(i*i+n*n);if(0===s)return t.clone();const r=Math.atan2(n,i),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 vl(t,e){switch(t.kind){case"awaitingCenter":return"CLICK"===e.type?{kind:"awaitingRadius",center:e.point.clone(),cursor:null}:t;case"awaitingRadius":if("MOUSE_MOVE"===e.type)return{...t,cursor:e.point.clone()};if("CLICK"===e.type){const i=Math.max(.1,Math.abs(e.point.x-t.center.x)),n=Math.max(.1,Math.abs(e.point.z-t.center.z));return{kind:"awaitingElbow",center:t.center,halfW:i,halfH:n,cursor:null}}return"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"awaitingElbow":return"MOUSE_MOVE"===e.type?{...t,cursor:e.point.clone()}:"CLICK"===e.type?{kind:"awaitingExtension",center:t.center,halfW:t.halfW,halfH:t.halfH,elbow:e.point.clone(),cursor:null}:"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"awaitingExtension":return"MOUSE_MOVE"===e.type?{...t,cursor:bl(t.elbow,e.point)}:"CLICK"===e.type?{kind:"enteringText",center:t.center,halfW:t.halfW,halfH:t.halfH,elbow:t.elbow,extensionEnd:bl(t.elbow,e.point)}:"ESCAPE"===e.type?{kind:"awaitingCenter"}:t;case"enteringText":if("SUBMIT_TEXT"===e.type&&e.text.trim().length>0){return{kind:"committed",annotation:{uuid: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 xl(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 Cl(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 Sl={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)}},Al={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)}},Pl={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 Tl extends Wa{constructor(t){super(t),e(this,"enabled",!0),e(this,"machineState",{kind:"awaitingCenter"}),e(this,"onMachineStateChanged",new f),this.styles.set("default",{enclosure:Sl,lineTick:Da,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=vl(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=xl(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 Cl("awaitingRadius",t.center,0,0,null,t.cursor,e);case"awaitingElbow":return Cl("awaitingElbow",t.center,t.halfW,t.halfH,null,t.cursor,e);case"awaitingExtension":return Cl("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 Ml=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 $a(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 No&&(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(Ml,"uuid","5c7d3b9a-4e8f-4a2b-9c1d-0e3f2a5b7c8d");let El=Ml;const Il=[[16711680,1],[16776960,2],[65280,3],[65535,4],[255,5],[16711935,6],[16777215,7],[0,7]];function Dl(t){const e=t>>16&255,i=t>>8&255,n=255&t;let s=7,r=1/0;for(const[t,o]of Il){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 zl="\0HANDSEED\0";class kl{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",zl),this}build(){return(this._lines.join("\n")+"\n").replace(zl,this._handleCounter.toString(16).toUpperCase())}}class Bl{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 kl,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(El).systems.get(ml),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=Dl(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,Dl(s),s)}))}_writeLinearAnnotations(t,e){var i;const n=this._components.get(El).systems.get(Ka);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=Dl(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(a))?void 0:i.visible))continue;const l=Ya(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 Za(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(El).systems.get(ll);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=Dl(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(a))?void 0:i.visible))continue;const l=ol(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 il(s))this._writeMeshTriangles(t,r.meshTick(e,i,r.tickSize),a,o,r.color);const c=sl(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(nl(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(El).systems.get(fl);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=Dl(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(a))?void 0:i.visible))continue;const l=dl(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(El).systems.get(_l);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=Dl(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(a))?void 0:i.visible))continue;const l=gl(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(t,l,a,o,r.color),r.meshTick){const e=wl(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,yl(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(El).systems.get(Tl);if(n)for(const[,s]of e.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=Dl(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=e.layers.get(a))?void 0:i.visible))continue;const l=xl(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(El).systems.get(ml);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=Dl(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(El).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:Dl,textAngle:(t,e)=>this._textAngle(t,e)}}}const Ol=class t extends g{constructor(i){super(i),e(this,"enabled",!0),e(this,"exporter",new Bl(this.components)),i.add(t.uuid,this)}};e(Ol,"uuid","e9a2c3d4-5f67-4b89-a012-1c3d5e7f9b2a");let Vl=Ol;exports.AngleAnnotations=ll,exports.AnnotationSystem=Wa,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=Xo,exports.BCFTopicsConfigManager=Zo,exports.Base=m,exports.BaseCamera=y,exports.BaseRenderer=_,exports.BaseScene=x,exports.BaseWorldItem=w,exports.BlockAnnotations=ml,exports.BoundingBoxer=Ur,exports.CalloutAnnotations=Tl,exports.CircleEnclosure=Pl,exports.Classifier=Hr,exports.Clipper=ta,exports.CloudEnclosure=Sl,exports.Comment=Wo,exports.Component=g,exports.Components=ko,exports.ConfigManager=we,exports.Configurator=me,exports.ControlsUtils=fe,exports.DataMap=pe,exports.DataSet=C,exports.DiagonalTick=Ia,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=Ba,exports.DrawingLayers=Oa,exports.DrawingSystem=Wa,exports.DrawingViewport=Na,exports.DrawingViewportHelper=La,exports.DrawingViewports=Fa,exports.DxfExporter=Bl,exports.DxfManager=Vl,exports.EdgeProjector=Br,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=Zr,exports.FastModelPickers=Xr,exports.FilledArrowTick=ka,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=jr,exports.FirstPersonMode=Bo,exports.FragmentsManager=ys,exports.Grids=Do,exports.Hider=Fr,exports.IDSAttribute=da,exports.IDSClassification=pa,exports.IDSEntity=fa,exports.IDSFacet=ha,exports.IDSMaterial=ga,exports.IDSPartOf=wa,exports.IDSProperty=ma,exports.IDSSpecification=ya,exports.IDSSpecifications=Ta,exports.IfcFragmentSettings=Or,exports.IfcLoader=Lr,exports.ItemsFinder=Wr,exports.LeaderAnnotations=fl,exports.LinearAnnotations=Ka,exports.MeasurementUtils=Ea,exports.ModelIdMapUtils=de,exports.Mouse=ye,exports.NoTick=za,exports.OpenArrowTick=Da,exports.OrbitMode=Oo,exports.OrthoPerspectiveCamera=No,exports.PlanMode=Vo,exports.ProjectionManager=Lo,exports.Raycasters=wo,exports.RectEnclosure=Al,exports.RendererMode=So,exports.ShadowedScene=class extends xo{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 ca(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=Ao,exports.SimpleGrid=Eo,exports.SimpleGridConfigManager=Mo,exports.SimplePlane=Ko,exports.SimpleRaycaster=mo,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=Co,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=xo,exports.SimpleSceneConfigManager=vo,exports.SimpleWorld=yo,exports.SlopeAnnotations=_l,exports.SnapClass=Kr,exports.SnapResolver=Jr,exports.SnapResolvers=fo,exports.TechnicalDrawing=$a,exports.TechnicalDrawingHelper=Ua,exports.TechnicalDrawings=El,exports.Topic=Ho,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(wo).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=ra,exports.Viewpoint=ea,exports.Viewpoints=sa,exports.Views=aa,exports.Worlds=To,exports.XML=ue,exports.angleDimensionMachine=el,exports.buildAnglePositions=ol,exports.buildAnglePreviewPositions=al,exports.buildCalloutPositions=xl,exports.buildCalloutPreviewPositions=Cl,exports.buildDimensionPositions=Ya,exports.buildDimensions=Ha,exports.buildLeaderPositions=dl,exports.buildLeaderPreviewPositions=pl,exports.buildPreviewPositions=Xa,exports.buildSlopePositions=gl,exports.calloutAnnotationMachine=vl,exports.computeAlignmentMatrix=ja,exports.computeAngle=nl,exports.computeBisectorAngle=sl,exports.computeOffset=Ga,exports.extensionsImporter=qo,exports.formatSlope=yl,exports.getAngleTickEndpoints=il,exports.getDimensionTickEndpoints=Za,exports.getSlopeTip=wl,exports.leaderAnnotationMachine=hl,exports.linearDimensionMachine=qa;
|