@thatopen/components 3.4.1 → 3.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +21 -0
- package/dist/index.d.ts +20 -1
- package/dist/index.min.cjs +1 -1
- package/dist/index.min.mjs +1 -1
- package/dist/index.mjs +21 -0
- package/package.json +2 -2
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 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)}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(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:{}};
|
|
2
2
|
/*!
|
|
3
3
|
|
|
4
4
|
JSZip v3.10.1 - A JavaScript class for generating and reading zip files
|