@thatopen/components 3.4.0 → 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.
@@ -1,19 +1,4 @@
1
- "use strict";var e=Object.defineProperty,t=(t,s,i)=>(((t,s,i)=>{s in t?e(t,s,{enumerable:!0,configurable:!0,writable:!0,value:i}):t[s]=i})(t,"symbol"!=typeof s?s+"":s,i),i);Object.defineProperty(exports,Symbol.toStringTag,{value:"Module"});const s=require("@thatopen/fragments"),i=require("three"),r=require("web-ifc"),n=require("camera-controls");function o(e){const t=Object.create(null,{[Symbol.toStringTag]:{value:"Module"}});if(e)for(const s in e)if("default"!==s){const i=Object.getOwnPropertyDescriptor(e,s);Object.defineProperty(t,s,i.get?i:{enumerable:!0,get:()=>e[s]})}return t.default=e,Object.freeze(t)}const a=o(s),l=o(i),h=o(r);class u{constructor(){t(this,"enabled",!0),t(this,"trigger",e=>{if(!this.enabled)return;const t=this.handlers.slice(0);for(const s of t)s(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 c{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 d extends c{}class p extends c{constructor(e){super(e),t(this,"worlds",new s.DataMap),t(this,"onWorldChanged",new u),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 m extends p{constructor(){super(...arguments),t(this,"hasCameraControls",()=>"controls"in this)}}class f extends p{constructor(){super(...arguments),t(this,"onAfterUpdate",new u),t(this,"onBeforeUpdate",new u),t(this,"onDisposed",new u),t(this,"onResize",new u),t(this,"onClippingPlanesUpdated",new u),t(this,"clippingPlanes",[])}updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(e,t,s){t.isLocal=s;const i=this.clippingPlanes.indexOf(t);e&&-1===i?this.clippingPlanes.push(t):!e&&i>-1&&this.clippingPlanes.splice(i,1),this.three.clippingPlanes=this.clippingPlanes.filter(e=>!e.isLocal)}}const g=class e extends d{constructor(s){super(s),t(this,"_disposedComponents",new Set),t(this,"enabled",!0),s.add(e.uuid,this)}get(){return this._disposedComponents}destroy(e,t=!0,s=!0){e.removeFromParent();const i=e;i.dispose&&i.dispose(),this.disposeGeometryAndMaterials(e,t),s&&i.children&&i.children.length&&this.disposeChildren(i),e.children.length=0}disposeGeometry(e){e.boundsTree&&e.disposeBoundsTree&&e.disposeBoundsTree(),e.dispose()}disposeGeometryAndMaterials(t,s){const i=t;i.geometry&&this.disposeGeometry(i.geometry),s&&i.material&&e.disposeMaterial(i),i.material=[],i.geometry=null}disposeChildren(e){for(const t of e.children)this.destroy(t)}static disposeMaterial(e){if(e.material)if(Array.isArray(e.material))for(const t of e.material)t.dispose();else e.material.dispose()}};t(g,"uuid","76e9cd8e-ad8f-4753-9ef6-cbc60f7247fe");let y=g;class x extends p{constructor(e){super(e),t(this,"onDisposed",new u),t(this,"directionalLights",new Map),t(this,"ambientLights",new Map)}dispose(){const e=this.components.get(y);for(const t of this.three.children){const s=t;s.geometry&&e.destroy(s)}this.deleteAllLights(),this.three.children=[],this.onDisposed.trigger(),this.onDisposed.reset()}deleteAllLights(){for(const[,e]of this.directionalLights)e.removeFromParent(),e.target.removeFromParent(),e.dispose();this.directionalLights.clear();for(const[,e]of this.ambientLights)e.removeFromParent(),e.dispose();this.ambientLights.clear()}}class b extends Set{constructor(e){super(e),t(this,"onItemAdded",new u),t(this,"onItemDeleted",new u),t(this,"onCleared",new u),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 u),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 _=class e{static create(){const t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0,r=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&s]}${e._lut[s>>8&255]}-${e._lut[s>>16&15|64]}${e._lut[s>>24&255]}-${e._lut[63&i|128]}${e._lut[i>>8&255]}-${e._lut[i>>16&255]}${e._lut[i>>24&255]}${e._lut[255&r]}${e._lut[r>>8&255]}${e._lut[r>>16&255]}${e._lut[r>>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(_,"_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(_,"_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 w=_;const v=":A-Za-z_\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD",T=new RegExp("^"+("["+v+"]["+(v+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*")+"$");function S(e,t){const s=[];let i=t.exec(e);for(;i;){const r=[];r.startIndex=t.lastIndex-i[0].length;const n=i.length;for(let e=0;e<n;e++)r.push(i[e]);s.push(r),i=t.exec(e)}return s}const M=function(e){const t=T.exec(e);return!(null==t)};const A={allowBooleanAttributes:!1,unpairedTags:[]};function N(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function E(e,t){const s=t;for(;t<e.length;t++)if("?"==e[t]||" "==e[t]){const i=e.substr(s,t-s);if(t>5&&"xml"===i)return F("InvalidXml","XML declaration allowed only at the start of the document.",z(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}continue}return t}function C(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 s=1;for(t+=8;t<e.length;t++)if("<"===e[t])s++;else if(">"===e[t]&&(s--,0===s))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 R='"',P="'";function B(e,t){let s="",i="",r=!1;for(;t<e.length;t++){if(e[t]===R||e[t]===P)""===i?i=e[t]:i!==e[t]||(i="");else if(">"===e[t]&&""===i){r=!0;break}s+=e[t]}return""===i&&{value:s,index:t,tagClosed:r}}const I=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function D(e,t){const s=S(e,I),i={};for(let e=0;e<s.length;e++){if(0===s[e][1].length)return F("InvalidAttr","Attribute '"+s[e][2]+"' has no space in starting.",k(s[e]));if(void 0!==s[e][3]&&void 0===s[e][4])return F("InvalidAttr","Attribute '"+s[e][2]+"' is without value.",k(s[e]));if(void 0===s[e][3]&&!t.allowBooleanAttributes)return F("InvalidAttr","boolean attribute '"+s[e][2]+"' is not allowed.",k(s[e]));const r=s[e][2];if(!O(r))return F("InvalidAttr","Attribute '"+r+"' is an invalid name.",k(s[e]));if(i.hasOwnProperty(r))return F("InvalidAttr","Attribute '"+r+"' is repeated.",k(s[e]));i[r]=1}return!0}function L(e,t){if(";"===e[++t])return-1;if("#"===e[t])return function(e,t){let s=/\d/;for("x"===e[t]&&(t++,s=/[\da-fA-F]/);t<e.length;t++){if(";"===e[t])return t;if(!e[t].match(s))break}return-1}(e,++t);let s=0;for(;t<e.length;t++,s++)if(!(e[t].match(/\w/)&&s<20)){if(";"===e[t])break;return-1}return t}function F(e,t,s){return{err:{code:e,msg:t,line:s.line||s,col:s.col}}}function O(e){return M(e)}function V(e){return M(e)}function z(e,t){const s=e.substring(0,t).split(/\r?\n/);return{line:s.length,col:s[s.length-1].length+1}}function k(e){return e.startIndex+e[1].length}const U={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,s){return e},captureMetaData:!1};function G(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}:G(!0)}const j=function(e){const t=Object.assign({},U,e);return t.processEntities=G(t.processEntities),t};let $;$="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class W{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][$]={startIndex:t})}static getMetaDataSymbol(){return $}}class H{constructor(e){this.suppressValidationErr=!e,this.options=e}readDocType(e,t){const s={};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 i=1,r=!1,n=!1,o="";for(;t<e.length;t++)if("<"!==e[t]||n)if(">"===e[t]){if(n?"-"===e[t-1]&&"-"===e[t-2]&&(n=!1,i--):i--,0===i)break}else"["===e[t]?r=!0:o+=e[t];else{if(r&&X(e,"!ENTITY",t)){let i,r;if(t+=7,[i,r,t]=this.readEntityExp(e,t+1,this.suppressValidationErr),-1===r.indexOf("&")){const e=i.replace(/[.\-+*:]/g,"\\.");s[i]={regx:RegExp(`&${e};`,"g"),val:r}}}else if(r&&X(e,"!ELEMENT",t)){t+=8;const{index:s}=this.readElementExp(e,t+1);t=s}else if(r&&X(e,"!ATTLIST",t))t+=8;else if(r&&X(e,"!NOTATION",t)){t+=9;const{index:s}=this.readNotationExp(e,t+1,this.suppressValidationErr);t=s}else{if(!X(e,"!--",t))throw new Error("Invalid DOCTYPE");n=!0}i++,o=""}if(0!==i)throw new Error("Unclosed DOCTYPE")}return{entities:s,i:t}}readEntityExp(e,t){t=q(e,t);let s="";for(;t<e.length&&!/\s/.test(e[t])&&'"'!==e[t]&&"'"!==e[t];)s+=e[t],t++;if(Y(s),t=q(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 i="";if([t,i]=this.readIdentifierVal(e,t,"entity"),!1!==this.options.enabled&&this.options.maxEntitySize&&i.length>this.options.maxEntitySize)throw new Error(`Entity "${s}" size (${i.length}) exceeds maximum allowed size (${this.options.maxEntitySize})`);return[s,i,--t]}readNotationExp(e,t){t=q(e,t);let s="";for(;t<e.length&&!/\s/.test(e[t]);)s+=e[t],t++;!this.suppressValidationErr&&Y(s),t=q(e,t);const i=e.substring(t,t+6).toUpperCase();if(!this.suppressValidationErr&&"SYSTEM"!==i&&"PUBLIC"!==i)throw new Error(`Expected SYSTEM or PUBLIC, found "${i}"`);t+=i.length,t=q(e,t);let r=null,n=null;if("PUBLIC"===i)[t,r]=this.readIdentifierVal(e,t,"publicIdentifier"),'"'!==e[t=q(e,t)]&&"'"!==e[t]||([t,n]=this.readIdentifierVal(e,t,"systemIdentifier"));else if("SYSTEM"===i&&([t,n]=this.readIdentifierVal(e,t,"systemIdentifier"),!this.suppressValidationErr&&!n))throw new Error("Missing mandatory system identifier for SYSTEM notation");return{notationName:s,publicIdentifier:r,systemIdentifier:n,index:--t}}readIdentifierVal(e,t,s){let i="";const r=e[t];if('"'!==r&&"'"!==r)throw new Error(`Expected quoted string, found "${r}"`);for(t++;t<e.length&&e[t]!==r;)i+=e[t],t++;if(e[t]!==r)throw new Error(`Unterminated ${s} value`);return[++t,i]}readElementExp(e,t){t=q(e,t);let s="";for(;t<e.length&&!/\s/.test(e[t]);)s+=e[t],t++;if(!this.suppressValidationErr&&!M(s))throw new Error(`Invalid element name: "${s}"`);let i="";if("E"===e[t=q(e,t)]&&X(e,"MPTY",t))t+=4;else if("A"===e[t]&&X(e,"NY",t))t+=2;else if("("===e[t]){for(t++;t<e.length&&")"!==e[t];)i+=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:s,contentModel:i.trim(),index:t}}readAttlistExp(e,t){t=q(e,t);let s="";for(;t<e.length&&!/\s/.test(e[t]);)s+=e[t],t++;Y(s),t=q(e,t);let i="";for(;t<e.length&&!/\s/.test(e[t]);)i+=e[t],t++;if(!Y(i))throw new Error(`Invalid attribute name: "${i}"`);t=q(e,t);let r="";if("NOTATION"===e.substring(t,t+8).toUpperCase()){if(r="NOTATION","("!==e[t=q(e,t+=8)])throw new Error(`Expected '(', found "${e[t]}"`);t++;let s=[];for(;t<e.length&&")"!==e[t];){let i="";for(;t<e.length&&"|"!==e[t]&&")"!==e[t];)i+=e[t],t++;if(i=i.trim(),!Y(i))throw new Error(`Invalid notation name: "${i}"`);s.push(i),"|"===e[t]&&(t++,t=q(e,t))}if(")"!==e[t])throw new Error("Unterminated list of notations");t++,r+=" ("+s.join("|")+")"}else{for(;t<e.length&&!/\s/.test(e[t]);)r+=e[t],t++;const s=["CDATA","ID","IDREF","IDREFS","ENTITY","ENTITIES","NMTOKEN","NMTOKENS"];if(!this.suppressValidationErr&&!s.includes(r.toUpperCase()))throw new Error(`Invalid attribute type: "${r}"`)}t=q(e,t);let n="";return"#REQUIRED"===e.substring(t,t+8).toUpperCase()?(n="#REQUIRED",t+=8):"#IMPLIED"===e.substring(t,t+7).toUpperCase()?(n="#IMPLIED",t+=7):[t,n]=this.readIdentifierVal(e,t,"ATTLIST"),{elementName:s,attributeName:i,attributeType:r,defaultValue:n,index:t}}}const q=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function X(e,t,s){for(let i=0;i<t.length;i++)if(t[i]!==e[s+i+1])return!1;return!0}function Y(e){if(M(e))return e;throw new Error(`Invalid entity name ${e}`)}const Z=/^[-+]?0x[a-fA-F0-9]+$/,Q=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,K={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function J(e,t={}){if(t=Object.assign({},K,t),!e||"string"!=typeof e)return e;let s=e.trim();if(void 0!==t.skipLike&&t.skipLike.test(s))return e;if("0"===e)return 0;if(t.hex&&Z.test(s))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")}(s,16);if(s.includes("e")||s.includes("E"))return function(e,t,s){if(!s.eNotation)return e;const i=t.match(ee);if(i){let r=i[1]||"";const n=-1===i[3].indexOf("e")?"E":"e",o=i[2],a=r?e[o.length+1]===n:e[o.length]===n;return o.length>1&&a?e:1!==o.length||!i[3].startsWith(`.${n}`)&&i[3][0]!==n?s.leadingZeros&&!a?(t=(i[1]||"")+i[3],Number(t)):e:Number(t)}return e}(e,s,t);{const i=Q.exec(s);if(i){const r=i[1]||"",n=i[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}(i[3]);const a=r?"."===e[n.length+1]:"."===e[n.length];if(!t.leadingZeros&&(n.length>1||1===n.length&&!a))return e;{const i=Number(s),a=String(i);if(0===i)return i;if(-1!==a.search(/[eE]/))return t.eNotation?i:e;if(-1!==s.indexOf("."))return"0"===a||a===o||a===`${r}${o}`?i:e;let l=n?o:s;return n?l===a||r+l===a?i:e:l===a||l===r+a?i:e}}return e}}const ee=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function te(e){return"function"==typeof e?e:Array.isArray(e)?t=>{for(const s of e){if("string"==typeof s&&t===s)return!0;if(s instanceof RegExp&&s.test(t))return!0}}:()=>!1}class se{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)=>ye(t,10,"&#")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,t)=>ye(t,16,"&#x")}},this.addExternalEntities=ie,this.parseXml=le,this.parseTextData=re,this.resolveNameSpace=ne,this.buildAttributesMap=ae,this.isItStopNode=de,this.replaceEntitiesValue=ue,this.readStopNodeData=fe,this.saveTextToParentTag=ce,this.addChild=he,this.ignoreAttributesFn=te(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 ie(e){const t=Object.keys(e);for(let s=0;s<t.length;s++){const i=t[s],r=i.replace(/[.\-+*:]/g,"\\.");this.lastEntities[i]={regex:new RegExp("&"+r+";","g"),val:e[i]}}}function re(e,t,s,i,r,n,o){if(void 0!==e&&(this.options.trimValues&&!i&&(e=e.trim()),e.length>0)){o||(e=this.replaceEntitiesValue(e,t,s));const i=this.options.tagValueProcessor(t,e,s,r,n);if(null==i)return e;if(typeof i!=typeof e||i!==e)return i;if(this.options.trimValues)return ge(e,this.options.parseTagValue,this.options.numberParseOptions);return e.trim()===e?ge(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function ne(e){if(this.options.removeNSPrefix){const t=e.split(":"),s="/"===e.charAt(0)?"/":"";if("xmlns"===t[0])return"";2===t.length&&(e=s+t[1])}return e}const oe=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function ae(e,t,s){if(!0!==this.options.ignoreAttributes&&"string"==typeof e){const i=S(e,oe),r=i.length,n={};for(let e=0;e<r;e++){const r=this.resolveNameSpace(i[e][1]);if(this.ignoreAttributesFn(r,t))continue;let o=i[e][4],a=this.options.attributeNamePrefix+r;if(r.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,s,t);const e=this.options.attributeValueProcessor(r,o,t);n[a]=null==e?o:typeof e!=typeof o||e!==o?e:ge(o,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(n[a]=!0)}if(!Object.keys(n).length)return;if(this.options.attributesGroupName){const e={};return e[this.options.attributesGroupName]=n,e}return n}}const le=function(e){e=e.replace(/\r\n?/g,"\n");const t=new W("!xml");let s=t,i="",r="";this.entityExpansionCount=0,this.currentExpandedLength=0;const n=new H(this.options.processEntities);for(let o=0;o<e.length;o++){if("<"===e[o])if("/"===e[o+1]){const t=pe(e,">",o,"Closing Tag is not closed.");let n=e.substring(o+2,t).trim();if(this.options.removeNSPrefix){const e=n.indexOf(":");-1!==e&&(n=n.substr(e+1))}this.options.transformTagName&&(n=this.options.transformTagName(n)),s&&(i=this.saveTextToParentTag(i,s,r));const a=r.substring(r.lastIndexOf(".")+1);if(n&&-1!==this.options.unpairedTags.indexOf(n))throw new Error(`Unpaired tag can not be used as closing tag: </${n}>`);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=r.lastIndexOf(".",r.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=r.lastIndexOf("."),r=r.substring(0,l),s=this.tagsNodeStack.pop(),i="",o=t}else if("?"===e[o+1]){let t=me(e,o,!1,"?>");if(!t)throw new Error("Pi Tag is not closed.");if(i=this.saveTextToParentTag(i,s,r),this.options.ignoreDeclaration&&"?xml"===t.tagName||this.options.ignorePiTags);else{const e=new W(t.tagName);e.add(this.options.textNodeName,""),t.tagName!==t.tagExp&&t.attrExpPresent&&(e[":@"]=this.buildAttributesMap(t.tagExp,r,t.tagName)),this.addChild(s,e,r,o)}o=t.closeIndex+1}else if("!--"===e.substr(o+1,3)){const t=pe(e,"--\x3e",o+4,"Comment is not closed.");if(this.options.commentPropName){const n=e.substring(o+4,t-2);i=this.saveTextToParentTag(i,s,r),s.add(this.options.commentPropName,[{[this.options.textNodeName]:n}])}o=t}else if("!D"===e.substr(o+1,2)){const t=n.readDocType(e,o);this.docTypeEntities=t.entities,o=t.i}else if("!["===e.substr(o+1,2)){const t=pe(e,"]]>",o,"CDATA is not closed.")-2,n=e.substring(o+9,t);i=this.saveTextToParentTag(i,s,r);let a=this.parseTextData(n,s.tagname,r,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?s.add(this.options.cdataPropName,[{[this.options.textNodeName]:n}]):s.add(this.options.textNodeName,a),o=t+2}else{let n=me(e,o,this.options.removeNSPrefix),a=n.tagName;const l=n.rawTagName;let h=n.tagExp,u=n.attrExpPresent,c=n.closeIndex;if(this.options.transformTagName){const e=this.options.transformTagName(a);h===a&&(h=e),a=e}s&&i&&"!xml"!==s.tagname&&(i=this.saveTextToParentTag(i,s,r,!1));const d=s;d&&-1!==this.options.unpairedTags.indexOf(d.tagname)&&(s=this.tagsNodeStack.pop(),r=r.substring(0,r.lastIndexOf("."))),a!==t.tagname&&(r+=r?"."+a:a);const p=o;if(this.isItStopNode(this.stopNodesExact,this.stopNodesWildcard,r,a)){let t="";if(h.length>0&&h.lastIndexOf("/")===h.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),r=r.substr(0,r.length-1),h=a):h=h.substr(0,h.length-1),o=n.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))o=n.closeIndex;else{const s=this.readStopNodeData(e,l,c+1);if(!s)throw new Error(`Unexpected end of ${l}`);o=s.i,t=s.tagContent}const i=new W(a);a!==h&&u&&(i[":@"]=this.buildAttributesMap(h,r,a)),t&&(t=this.parseTextData(t,a,r,!0,u,!0,!0)),r=r.substr(0,r.lastIndexOf(".")),i.add(this.options.textNodeName,t),this.addChild(s,i,r,p)}else{if(h.length>0&&h.lastIndexOf("/")===h.length-1){if("/"===a[a.length-1]?(a=a.substr(0,a.length-1),r=r.substr(0,r.length-1),h=a):h=h.substr(0,h.length-1),this.options.transformTagName){const e=this.options.transformTagName(a);h===a&&(h=e),a=e}const e=new W(a);a!==h&&u&&(e[":@"]=this.buildAttributesMap(h,r,a)),this.addChild(s,e,r,p),r=r.substr(0,r.lastIndexOf("."))}else{const e=new W(a);this.tagsNodeStack.push(s),a!==h&&u&&(e[":@"]=this.buildAttributesMap(h,r,a)),this.addChild(s,e,r,p),s=e}i="",o=c}}else i+=e[o]}return t.child};function he(e,t,s,i){this.options.captureMetaData||(i=void 0);const r=this.options.updateTag(t.tagname,s,t[":@"]);!1===r||("string"==typeof r?(t.tagname=r,e.addChild(t,i)):e.addChild(t,i))}const ue=function(e,t,s){if(-1===e.indexOf("&"))return e;const i=this.options.processEntities;if(!i.enabled)return e;if(i.allowedTags&&!i.allowedTags.includes(t))return e;if(i.tagFilter&&!i.tagFilter(t,s))return e;for(let t in this.docTypeEntities){const s=this.docTypeEntities[t],r=e.match(s.regx);if(r){if(this.entityExpansionCount+=r.length,i.maxTotalExpansions&&this.entityExpansionCount>i.maxTotalExpansions)throw new Error(`Entity expansion limit exceeded: ${this.entityExpansionCount} > ${i.maxTotalExpansions}`);const t=e.length;if(e=e.replace(s.regx,s.val),i.maxExpandedLength&&(this.currentExpandedLength+=e.length-t,this.currentExpandedLength>i.maxExpandedLength))throw new Error(`Total expanded content size exceeded: ${this.currentExpandedLength} > ${i.maxExpandedLength}`)}}if(-1===e.indexOf("&"))return e;for(let t in this.lastEntities){const s=this.lastEntities[t];e=e.replace(s.regex,s.val)}if(-1===e.indexOf("&"))return e;if(this.options.htmlEntities)for(let t in this.htmlEntities){const s=this.htmlEntities[t];e=e.replace(s.regex,s.val)}return e=e.replace(this.ampEntity.regex,this.ampEntity.val)};function ce(e,t,s,i){return e&&(void 0===i&&(i=0===t.child.length),void 0!==(e=this.parseTextData(e,t.tagname,s,!1,!!t[":@"]&&0!==Object.keys(t[":@"]).length,i))&&""!==e&&t.add(this.options.textNodeName,e),e=""),e}function de(e,t,s,i){return!(!t||!t.has(i))||!(!e||!e.has(s))}function pe(e,t,s,i){const r=e.indexOf(t,s);if(-1===r)throw new Error(i);return r+t.length-1}function me(e,t,s,i=">"){const r=function(e,t,s=">"){let i,r="";for(let n=t;n<e.length;n++){let t=e[n];if(i)t===i&&(i="");else if('"'===t||"'"===t)i=t;else if(t===s[0]){if(!s[1])return{data:r,index:n};if(e[n+1]===s[1])return{data:r,index:n}}else"\t"===t&&(t=" ");r+=t}}(e,t+1,i);if(!r)return;let n=r.data;const o=r.index,a=n.search(/\s/);let l=n,h=!0;-1!==a&&(l=n.substring(0,a),n=n.substring(a+1).trimStart());const u=l;if(s){const e=l.indexOf(":");-1!==e&&(l=l.substr(e+1),h=l!==r.data.substr(e+1))}return{tagName:l,tagExp:n,closeIndex:o,attrExpPresent:h,rawTagName:u}}function fe(e,t,s){const i=s;let r=1;for(;s<e.length;s++)if("<"===e[s])if("/"===e[s+1]){const n=pe(e,">",s,`${t} is not closed`);if(e.substring(s+2,n).trim()===t&&(r--,0===r))return{tagContent:e.substring(i,s),i:n};s=n}else if("?"===e[s+1]){s=pe(e,"?>",s+1,"StopNode is not closed.")}else if("!--"===e.substr(s+1,3)){s=pe(e,"--\x3e",s+3,"StopNode is not closed.")}else if("!["===e.substr(s+1,2)){s=pe(e,"]]>",s,"StopNode is not closed.")-2}else{const i=me(e,s,">");if(i){(i&&i.tagName)===t&&"/"!==i.tagExp[i.tagExp.length-1]&&r++,s=i.closeIndex}}}function ge(e,t,s){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&J(e,s)}return void 0!==e?e:""}function ye(e,t,s){const i=Number.parseInt(e,t);return i>=0&&i<=1114111?String.fromCodePoint(i):s+e+";"}const xe=W.getMetaDataSymbol();function be(e,t){return _e(e,t)}function _e(e,t,s){let i;const r={};for(let n=0;n<e.length;n++){const o=e[n],a=we(o);let l="";if(l=void 0===s?a:s+"."+a,a===t.textNodeName)void 0===i?i=o[a]:i+=""+o[a];else{if(void 0===a)continue;if(o[a]){let e=_e(o[a],t,l);const s=Te(e,t);void 0!==o[xe]&&(e[xe]=o[xe]),o[":@"]?ve(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!==r[a]&&r.hasOwnProperty(a)?(Array.isArray(r[a])||(r[a]=[r[a]]),r[a].push(e)):t.isArray(a,l,s)?r[a]=[e]:r[a]=e}}}return"string"==typeof i?i.length>0&&(r[t.textNodeName]=i):void 0!==i&&(r[t.textNodeName]=i),r}function we(e){const t=Object.keys(e);for(let e=0;e<t.length;e++){const s=t[e];if(":@"!==s)return s}}function ve(e,t,s,i){if(t){const r=Object.keys(t),n=r.length;for(let o=0;o<n;o++){const n=r[o];i.isArray(n,s+"."+n,!0,!0)?e[n]=[t[n]]:e[n]=t[n]}}}function Te(e,t){const{textNodeName:s}=t,i=Object.keys(e).length;return 0===i||!(1!==i||!e[s]&&"boolean"!=typeof e[s]&&0!==e[s])}class Se{constructor(e){this.externalEntities={},this.options=j(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 s=function(e,t){t=Object.assign({},A,t);const s=[];let i=!1,r=!1;"\ufeff"===e[0]&&(e=e.substr(1));for(let n=0;n<e.length;n++)if("<"===e[n]&&"?"===e[n+1]){if(n+=2,n=E(e,n),n.err)return n}else{if("<"!==e[n]){if(N(e[n]))continue;return F("InvalidChar","char '"+e[n]+"' is not expected.",z(e,n))}{let o=n;if(n++,"!"===e[n]){n=C(e,n);continue}{let a=!1;"/"===e[n]&&(a=!0,n++);let l="";for(;n<e.length&&">"!==e[n]&&" "!==e[n]&&"\t"!==e[n]&&"\n"!==e[n]&&"\r"!==e[n];n++)l+=e[n];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),n--),!V(l)){let t;return t=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",F("InvalidTag",t,z(e,n))}const h=B(e,n);if(!1===h)return F("InvalidAttr","Attributes for '"+l+"' have open quote.",z(e,n));let u=h.value;if(n=h.index,"/"===u[u.length-1]){const s=n-u.length;u=u.substring(0,u.length-1);const r=D(u,t);if(!0!==r)return F(r.err.code,r.err.msg,z(e,s+r.err.line));i=!0}else if(a){if(!h.tagClosed)return F("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",z(e,n));if(u.trim().length>0)return F("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",z(e,o));if(0===s.length)return F("InvalidTag","Closing tag '"+l+"' has not been opened.",z(e,o));{const t=s.pop();if(l!==t.tagName){let s=z(e,t.tagStartPos);return F("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+s.line+", col "+s.col+") instead of closing tag '"+l+"'.",z(e,o))}0==s.length&&(r=!0)}}else{const a=D(u,t);if(!0!==a)return F(a.err.code,a.err.msg,z(e,n-u.length+a.err.line));if(!0===r)return F("InvalidXml","Multiple possible root nodes found.",z(e,n));-1!==t.unpairedTags.indexOf(l)||s.push({tagName:l,tagStartPos:o}),i=!0}for(n++;n<e.length;n++)if("<"===e[n]){if("!"===e[n+1]){n++,n=C(e,n);continue}if("?"!==e[n+1])break;if(n=E(e,++n),n.err)return n}else if("&"===e[n]){const t=L(e,n);if(-1==t)return F("InvalidChar","char '&' is not expected.",z(e,n));n=t}else if(!0===r&&!N(e[n]))return F("InvalidXml","Extra text at the end",z(e,n));"<"===e[n]&&n--}}}return i?1==s.length?F("InvalidTag","Unclosed tag '"+s[0].tagName+"'.",z(e,s[0].tagStartPos)):!(s.length>0)||F("InvalidXml","Invalid '"+JSON.stringify(s.map(e=>e.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):F("InvalidXml","Start tag expected.",1)}(e,t);if(!0!==s)throw Error(`${s.err.msg}:${s.err.line}:${s.err.col}`)}const s=new se(this.options);s.addExternalEntities(this.externalEntities);const i=s.parseXml(e);return this.options.preserveOrder||void 0===i?i:be(i,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 '&#xD;'");if("&"===t)throw new Error("An entity with value '&' is not permitted");this.externalEntities[e]=t}static getMetaDataSymbol(){return W.getMetaDataSymbol()}}function Me(e,t){let s="";return t.format&&t.indentBy.length>0&&(s="\n"),Ae(e,t,"",s)}function Ae(e,t,s,i){let r="",n=!1;for(let o=0;o<e.length;o++){const a=e[o],l=Ne(a);if(void 0===l)continue;let h="";if(h=0===s.length?l:`${s}.${l}`,l===t.textNodeName){let e=a[l];Ce(h,t)||(e=t.tagValueProcessor(l,e),e=Re(e,t)),n&&(r+=i),r+=e,n=!1;continue}if(l===t.cdataPropName){n&&(r+=i),r+=`<![CDATA[${a[l][0][t.textNodeName]}]]>`,n=!1;continue}if(l===t.commentPropName){r+=i+`\x3c!--${a[l][0][t.textNodeName]}--\x3e`,n=!0;continue}if("?"===l[0]){const e=Ee(a[":@"],t),s="?xml"===l?"":i;let o=a[l][0][t.textNodeName];o=0!==o.length?" "+o:"",r+=s+`<${l}${o}${e}?>`,n=!0;continue}let u=i;""!==u&&(u+=t.indentBy);const c=i+`<${l}${Ee(a[":@"],t)}`,d=Ae(a[l],t,h,u);-1!==t.unpairedTags.indexOf(l)?t.suppressUnpairedNode?r+=c+">":r+=c+"/>":d&&0!==d.length||!t.suppressEmptyNode?d&&d.endsWith(">")?r+=c+`>${d}${i}</${l}>`:(r+=c+">",d&&""!==i&&(d.includes("/>")||d.includes("</"))?r+=i+t.indentBy+d+i:r+=d,r+=`</${l}>`):r+=c+"/>",n=!0}return r}function Ne(e){const t=Object.keys(e);for(let s=0;s<t.length;s++){const i=t[s];if(e.hasOwnProperty(i)&&":@"!==i)return i}}function Ee(e,t){let s="";if(e&&!t.ignoreAttributes)for(let i in e){if(!e.hasOwnProperty(i))continue;let r=t.attributeValueProcessor(i,e[i]);r=Re(r,t),!0===r&&t.suppressBooleanAttributes?s+=` ${i.substr(t.attributeNamePrefix.length)}`:s+=` ${i.substr(t.attributeNamePrefix.length)}="${r}"`}return s}function Ce(e,t){let s=(e=e.substr(0,e.length-t.textNodeName.length-1)).substr(e.lastIndexOf(".")+1);for(let i in t.stopNodes)if(t.stopNodes[i]===e||t.stopNodes[i]==="*."+s)return!0;return!1}function Re(e,t){if(e&&e.length>0&&t.processEntities)for(let s=0;s<t.entities.length;s++){const i=t.entities[s];e=e.replace(i.regex,i.val)}return e}const Pe={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(e,t){return t},attributeValueProcessor:function(e,t){return t},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function Be(e){this.options=Object.assign({},Pe,e),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=te(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Le),this.processTextOrObjNode=Ie,this.options.format?(this.indentate=De,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function Ie(e,t,s,i){const r=this.j2x(e,s+1,i.concat(t));return void 0!==e[this.options.textNodeName]&&1===Object.keys(e).length?this.buildTextValNode(e[this.options.textNodeName],t,r.attrStr,s):this.buildObjectNode(r.val,t,r.attrStr,s)}function De(e){return this.options.indentBy.repeat(e)}function Le(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}Be.prototype.build=function(e){return this.options.preserveOrder?Me(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},Be.prototype.j2x=function(e,t,s){let i="",r="";const n=s.join(".");for(let o in e)if(Object.prototype.hasOwnProperty.call(e,o))if(void 0===e[o])this.isAttribute(o)&&(r+="");else if(null===e[o])this.isAttribute(o)||o===this.options.cdataPropName?r+="":"?"===o[0]?r+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:r+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if(e[o]instanceof Date)r+=this.buildTextValNode(e[o],o,"",t);else if("object"!=typeof e[o]){const s=this.isAttribute(o);if(s&&!this.ignoreAttributesFn(s,n))i+=this.buildAttrPairStr(s,""+e[o]);else if(!s)if(o===this.options.textNodeName){let t=this.options.tagValueProcessor(o,""+e[o]);r+=this.replaceEntitiesValue(t)}else r+=this.buildTextValNode(e[o],o,"",t)}else if(Array.isArray(e[o])){const i=e[o].length;let n="",a="";for(let l=0;l<i;l++){const i=e[o][l];if(void 0===i);else if(null===i)"?"===o[0]?r+=this.indentate(t)+"<"+o+"?"+this.tagEndChar:r+=this.indentate(t)+"<"+o+"/"+this.tagEndChar;else if("object"==typeof i)if(this.options.oneListGroup){const e=this.j2x(i,t+1,s.concat(o));n+=e.val,this.options.attributesGroupName&&i.hasOwnProperty(this.options.attributesGroupName)&&(a+=e.attrStr)}else n+=this.processTextOrObjNode(i,o,t,s);else if(this.options.oneListGroup){let e=this.options.tagValueProcessor(o,i);e=this.replaceEntitiesValue(e),n+=e}else n+=this.buildTextValNode(i,o,"",t)}this.options.oneListGroup&&(n=this.buildObjectNode(n,o,a,t)),r+=n}else if(this.options.attributesGroupName&&o===this.options.attributesGroupName){const t=Object.keys(e[o]),s=t.length;for(let r=0;r<s;r++)i+=this.buildAttrPairStr(t[r],""+e[o][t[r]])}else r+=this.processTextOrObjNode(e[o],o,t,s);return{attrStr:i,val:r}},Be.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&"true"===t?" "+e:" "+e+'="'+t+'"'},Be.prototype.buildObjectNode=function(e,t,s,i){if(""===e)return"?"===t[0]?this.indentate(i)+"<"+t+s+"?"+this.tagEndChar:this.indentate(i)+"<"+t+s+this.closeTag(t)+this.tagEndChar;{let r="</"+t+this.tagEndChar,n="";return"?"===t[0]&&(n="?",r=""),!s&&""!==s||-1!==e.indexOf("<")?!1!==this.options.commentPropName&&t===this.options.commentPropName&&0===n.length?this.indentate(i)+`\x3c!--${e}--\x3e`+this.newLine:this.indentate(i)+"<"+t+s+n+this.tagEndChar+e+this.indentate(i)+r:this.indentate(i)+"<"+t+s+n+">"+e+r}},Be.prototype.closeTag=function(e){let t="";return-1!==this.options.unpairedTags.indexOf(e)?this.options.suppressUnpairedNode||(t="/"):t=this.options.suppressEmptyNode?"/":`></${e}`,t},Be.prototype.buildTextValNode=function(e,t,s,i){if(!1!==this.options.cdataPropName&&t===this.options.cdataPropName)return this.indentate(i)+`<![CDATA[${e}]]>`+this.newLine;if(!1!==this.options.commentPropName&&t===this.options.commentPropName)return this.indentate(i)+`\x3c!--${e}--\x3e`+this.newLine;if("?"===t[0])return this.indentate(i)+"<"+t+s+"?"+this.tagEndChar;{let r=this.options.tagValueProcessor(t,e);return r=this.replaceEntitiesValue(r),""===r?this.indentate(i)+"<"+t+s+this.closeTag(t)+this.tagEndChar:this.indentate(i)+"<"+t+s+">"+r+"</"+t+this.tagEndChar}},Be.prototype.replaceEntitiesValue=function(e){if(e&&e.length>0&&this.options.processEntities)for(let t=0;t<this.options.entities.length;t++){const s=this.options.entities[t];e=e.replace(s.regex,s.val)}return e};class Fe{}t(Fe,"parser",new Se({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(Fe,"builder",new Be({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1}));class Oe{static join(e){const t={};for(const s of e)for(const e in s)if(t[e])for(const i of s[e])t[e].add(i);else t[e]=new Set(s[e]);return t}static intersect(e){if(0===e.length)return{};let t=Oe.clone(e[0]);for(let s=1;s<e.length;s++){const i=e[s],r={};for(const e in t)if(i[e]){const s=new Set;for(const r of t[e])i[e].has(r)&&s.add(r);s.size>0&&(r[e]=s)}t=r}return t}static clone(e){const t={};for(const s in e)t[s]=new Set(e[s]);return t}static remove(e,t,s=!1){s&&(e=Oe.clone(e));for(const s in t)if(e[s]){for(const i of t[s])e[s].delete(i);0===e[s].size&&delete e[s]}}static add(e,t,s=!1){s&&(e=Oe.clone(e));for(const s in t)if(e[s])for(const i of t[s])e[s].add(i);else e[s]=new Set(t[s])}static append(e,t,...s){let i=e[t];i||(i=new Set,e[t]=i);for(const e of s)i.add(e)}static isEqual(e,t){const s=Object.keys(e),i=Object.keys(t);if(s.length!==i.length)return!1;for(const i of s){if(!t[i])return!1;if(e[i].size!==t[i].size)return!1;for(const s of e[i])if(!t[i].has(s))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 s in e)t[s]=Array.from(e[s]);return t}static fromRaw(e){const t={};for(const s in e)t[s]=new Set(e[s]);return t}}let Ve=class extends Map{constructor(e){super(e),t(this,"onItemSet",new u),t(this,"onItemUpdated",new u),t(this,"onItemDeleted",new u),t(this,"onCleared",new u),t(this,"guard",()=>!0)}clear(){super.clear(),this.onCleared.trigger()}set(e,t){const s=this.has(e);if(!(this.guard??(()=>!0))(e,t))return this;const i=super.set(e,t);return s?(this.onItemUpdated||(this.onItemUpdated=new u),this.onItemUpdated.trigger({key:e,value:t})):(this.onItemSet||(this.onItemSet=new u),this.onItemSet.trigger({key:e,value:t})),i}add(e){const t=w.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 ze{static isEntry(e){return new Set(["Boolean","Color","Text","Number","Select","Vector3","TextSet","None"]).has(e.type)}static copySchema(e,t={}){for(const s in e){const i=e[s];this.isEntry(i)?t[s]=this.copyEntry(i):(t[s]={},this.copySchema(i,t[s]))}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 ke{constructor(e,s,i,r){t(this,"_component"),t(this,"name"),t(this,"uuid"),this._component=e,this.name=i,this.uuid=r??w.create();s.get(Ge).list.set(this.uuid,this)}get controls(){return ze.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 s in e){const i=e[s];if(ze.isEntry(i))if("Color"===i.type){const{r:e,g:r,b:n}=i.value;t[s]={...i,value:{r:e,g:r,b:n}}}else if("Vector3"===i.type){const{x:e,y:r,z:n}=i.value;t[s]={...i,value:{x:e,y:r,z:n}}}else if("TextSet"===i.type){const e=Array.from(i.value);t[s]={...i,value:e}}else if("Select"===i.type){const e=Array.from(i.options);t[s]={...i,options:e}}else t[s]={...i};else t[s]={},this.export(i,t[s])}return t}import(e,t={},s=!0){for(const s in e){const i=e[s];if(ze.isEntry(i))if("Color"===i.type){const{r:e,g:r,b:n}=i.value;t[s]={...i,value:new l.Color(e,r,n)}}else if("Vector3"===i.type){const{x:e,y:r,z:n}=i.value;t[s]={...i,value:new l.Vector3(e,r,n)}}else"TextSet"===i.type?t[s]={...i,value:new Set(i.value)}:"Select"===i.type?t[s]={...i,options:new Set(i.options)}:t[s]={...i};else t[s]={},this.import(i,t[s],!1)}s&&this.set(t)}}const Ue=class e extends d{constructor(i){super(i),t(this,"list",new s.DataMap),t(this,"enabled",!0),i.add(e.uuid,this)}};t(Ue,"uuid","b8c764e0-6b24-4e77-9a32-35fa728ee5b4");let Ge=Ue;class je{constructor(e){t(this,"_event"),t(this,"_position",new l.Vector2),t(this,"onDisposed",new u),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,s){const i=this.getDataObject(t);return s?i.clientY:-(i.clientY-e.top)/(e.bottom-e.top)*2+1}getPositionX(e,t,s){const i=this.getDataObject(t);return s?i.clientX:(i.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 $e=1.25,We=32,He=Math.pow(2,-24),qe=Symbol("SKIP_GENERATION"),Xe={strategy:0,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[qe]:!1};function Ye(e,t,s){return s.min.x=t[e],s.min.y=t[e+1],s.min.z=t[e+2],s.max.x=t[e+3],s.max.y=t[e+4],s.max.z=t[e+5],s}function Ze(e){let t=-1,s=-1/0;for(let i=0;i<3;i++){const r=e[i+3]-e[i];r>s&&(s=r,t=i)}return t}function Qe(e,t){t.set(e)}function Ke(e,t,s){let i,r;for(let n=0;n<3;n++){const o=n+3;i=e[n],r=t[n],s[n]=i<r?i:r,i=e[o],r=t[o],s[o]=i>r?i:r}}function Je(e,t,s){for(let i=0;i<3;i++){const r=t[e+2*i],n=t[e+2*i+1],o=r-n,a=r+n;o<s[i]&&(s[i]=o),a>s[i+3]&&(s[i+3]=a)}}function et(e){const t=e[3]-e[0],s=e[4]-e[1],i=e[5]-e[2];return 2*(t*s+s*i+i*t)}function tt(e,t){return 65535===t[e+15]}function st(e,t){return t[e+6]}function it(e,t){return t[e+14]}function rt(e){return e+8}function nt(e,t){return e+8*t[e+6]}function ot(e,t){return t[e+7]}function at(e){return e}function lt(e,t,s,i,r){let n=1/0,o=1/0,a=1/0,l=-1/0,h=-1/0,u=-1/0,c=1/0,d=1/0,p=1/0,m=-1/0,f=-1/0,g=-1/0;const y=e.offset||0;for(let i=6*(t-y),r=6*(t+s-y);i<r;i+=6){const t=e[i+0],s=e[i+1],r=t-s,y=t+s;r<n&&(n=r),y>l&&(l=y),t<c&&(c=t),t>m&&(m=t);const x=e[i+2],b=e[i+3],_=x-b,w=x+b;_<o&&(o=_),w>h&&(h=w),x<d&&(d=x),x>f&&(f=x);const v=e[i+4],T=e[i+5],S=v-T,M=v+T;S<a&&(a=S),M>u&&(u=M),v<p&&(p=v),v>g&&(g=v)}i[0]=n,i[1]=o,i[2]=a,i[3]=l,i[4]=h,i[5]=u,r[0]=c,r[1]=d,r[2]=p,r[3]=m,r[4]=f,r[5]=g}const ht=32,ut=(e,t)=>e.candidate-t.candidate,ct=new Array(ht).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),dt=new Float32Array(6);class pt{constructor(){this.boundingData=new Float32Array(6)}}let mt,ft,gt,yt;const xt=Math.pow(2,32);function bt(e){return"count"in e?1:1+bt(e.left)+bt(e.right)}function _t(e,t,s){return mt=new Float32Array(s),ft=new Uint32Array(s),gt=new Uint16Array(s),yt=new Uint8Array(s),wt(e,t)}function wt(e,t){const s=e/4,i=e/2,r="count"in t,n=t.boundingData;for(let e=0;e<6;e++)mt[s+e]=n[e];if(r)return t.buffer?(yt.set(new Uint8Array(t.buffer),e),e+t.buffer.byteLength):(ft[s+6]=t.offset,gt[i+14]=t.count,gt[i+15]=65535,e+We);{const{left:i,right:r,splitAxis:n}=t;let o=wt(e+We,i);const a=o/We-e/We;if(a>xt)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return ft[s+6]=a,ft[s+7]=n,wt(o,r)}}function vt(e,t,s,i,r,n){const{maxDepth:o,verbose:a,maxLeafSize:l,strategy:h,onProgress:u}=r,c=e.primitiveBuffer,d=e.primitiveBufferStride,p=new Float32Array(6);let m=!1;const f=new pt;return lt(t,s,i,f.boundingData,p),function e(s,i,r,n=null,u=0){!m&&u>=o&&(m=!0,a&&console.warn(`BVH: Max depth of ${o} reached when generating BVH. Consider increasing maxDepth.`));if(r<=l||u>=o)return g(i+r),s.offset=i,s.count=r,s;const f=function(e,t,s,i,r,n){let o=-1,a=0;if(0===n)o=Ze(t),-1!==o&&(a=(t[o]+t[o+3])/2);else if(1===n)o=Ze(e),-1!==o&&(a=function(e,t,s,i){let r=0;const n=e.offset;for(let o=t,a=t+s;o<a;o++)r+=e[6*(o-n)+2*i];return r/s}(s,i,r,o));else if(2===n){const n=et(e);let l=$e*r;const h=s.offset||0,u=6*(i-h),c=6*(i+r-h);for(let e=0;e<3;e++){const i=t[e],h=(t[e+3]-i)/ht;if(r<8){const t=[...ct];t.length=r;let i=0;for(let r=u;r<c;r+=6,i++){const n=t[i];n.candidate=s[r+2*e],n.count=0;const{bounds:o,leftCacheBounds:a,rightCacheBounds:l}=n;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;Je(r,s,o)}t.sort(ut);let h=r;for(let e=0;e<h;e++){const s=t[e];for(;e+1<h&&t[e+1].candidate===s.candidate;)t.splice(e+1,1),h--}for(let i=u;i<c;i+=6){const r=s[i+2*e];for(let e=0;e<h;e++){const n=t[e];r>=n.candidate?Je(i,s,n.rightCacheBounds):(Je(i,s,n.leftCacheBounds),n.count++)}}for(let s=0;s<h;s++){const i=t[s],h=i.count,u=r-i.count,c=i.leftCacheBounds,d=i.rightCacheBounds;let p=0;0!==h&&(p=et(c)/n);let m=0;0!==u&&(m=et(d)/n);const f=1+$e*(p*h+m*u);f<l&&(o=e,l=f,a=i.candidate)}}else{for(let e=0;e<ht;e++){const t=ct[e];t.count=0,t.candidate=i+h+e*h;const s=t.bounds;for(let e=0;e<3;e++)s[e]=1/0,s[e+3]=-1/0}for(let t=u;t<c;t+=6){let r=~~((s[t+2*e]-i)/h);r>=ht&&(r=31);const n=ct[r];n.count++,Je(t,s,n.bounds)}const t=ct[31];Qe(t.bounds,t.rightCacheBounds);for(let e=30;e>=0;e--){const t=ct[e],s=ct[e+1];Ke(t.bounds,s.rightCacheBounds,t.rightCacheBounds)}let d=0;for(let t=0;t<31;t++){const s=ct[t],i=s.count,h=s.bounds,u=ct[t+1].rightCacheBounds;0!==i&&(0===d?Qe(h,dt):Ke(h,dt,dt)),d+=i;let c=0,p=0;0!==d&&(c=et(dt)/n);const m=r-d;0!==m&&(p=et(u)/n);const f=1+$e*(c*d+p*m);f<l&&(o=e,l=f,a=s.candidate)}}}}else console.warn(`BVH: Invalid build strategy value ${n} used.`);return{axis:o,pos:a}}(s.boundingData,n,t,i,r,h);if(-1===f.axis)return g(i+r),s.offset=i,s.count=r,s;const y=function(e,t,s,i,r,n){let o=i,a=i+r-1;const l=n.pos,h=2*n.axis,u=s.offset||0;for(;;){for(;o<=a&&s[6*(o-u)+h]<l;)o++;for(;o<=a&&s[6*(a-u)+h]>=l;)a--;if(!(o<a))return o;for(let s=0;s<t;s++){let i=e[o*t+s];e[o*t+s]=e[a*t+s],e[a*t+s]=i}for(let e=0;e<6;e++){const t=o-u,i=a-u,r=s[6*t+e];s[6*t+e]=s[6*i+e],s[6*i+e]=r}o++,a--}}(c,d,t,i,r,f);if(y===i||y===i+r)g(i+r),s.offset=i,s.count=r;else{s.splitAxis=f.axis;const n=new pt,o=i,a=y-i;s.left=n,lt(t,o,a,n.boundingData,p),e(n,o,a,p,u+1);const l=new pt,h=y,c=r-a;s.right=l,lt(t,h,c,l.boundingData,p),e(l,h,c,p,u+1)}return s}(f,s,i,p),f;function g(e){u&&u((e-n.offset)/n.count)}}function Tt(e,t){const s=t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer,i=e.getRootRanges(t.range),r=i[0],n=i[i.length-1],o={offset:r.offset,count:n.offset+n.count-r.offset},a=new Float32Array(6*o.count);a.offset=o.offset,e.computePrimitiveBounds(o.offset,o.count,a),e._roots=i.map(i=>{const r=vt(e,a,i.offset,i.count,t,o),n=bt(r),l=new s(We*n);return _t(0,r,l),l})}class St{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 Mt{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const e=[];let t=null;this.setBuffer=s=>{t&&e.push(t),t=s,this.float32Array=new Float32Array(s),this.uint16Array=new Uint16Array(s),this.uint32Array=new Uint32Array(s)},this.clearBuffer=()=>{t=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,0!==e.length&&this.setBuffer(e.pop())}}}const At=new Mt;let Nt,Et;const Ct=[],Rt=new St(()=>new i.Box3);function Pt(e,t,s,i,r,n){Nt=Rt.getPrimitive(),Et=Rt.getPrimitive(),Ct.push(Nt,Et),At.setBuffer(e._roots[t]);const o=Bt(0,e.geometry,s,i,r,n);At.clearBuffer(),Rt.releasePrimitive(Nt),Rt.releasePrimitive(Et),Ct.pop(),Ct.pop();const a=Ct.length;return a>0&&(Et=Ct[a-1],Nt=Ct[a-2]),o}function Bt(e,t,s,i,r=null,n=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:h}=At;let u=2*e;if(tt(u,l)){const t=st(e,h),s=it(u,l);return Ye(e,a,Nt),i(t,s,!1,o,n+e/8,Nt)}{let u=function(e){const{uint16Array:t,uint32Array:s}=At;let i=2*e;for(;!tt(i,t);)i=2*(e=rt(e));return st(e,s)},c=function(e){const{uint16Array:t,uint32Array:s}=At;let i=2*e;for(;!tt(i,t);)i=2*(e=nt(e,s));return st(e,s)+it(i,t)};const d=rt(e),p=nt(e,h);let m,f,g,y,x=d,b=p;if(r&&(g=Nt,y=Et,Ye(x,a,g),Ye(b,a,y),m=r(g),f=r(y),f<m)){x=p,b=d;const e=m;m=f,f=e,g=y}g||(g=Nt,Ye(x,a,g));const _=s(g,tt(2*x,l),m,o+1,n+x/8);let w;if(2===_){const e=u(x);w=i(e,c(x)-e,!0,o+1,n+x/8,g)}else w=_&&Bt(x,t,s,i,r,n,o+1);if(w)return!0;y=Et,Ye(b,a,y);const v=s(y,tt(2*b,l),f,o+1,n+b/8);let T;if(2===v){const e=u(b);T=i(e,c(b)-e,!0,o+1,n+b/8,y)}else T=v&&Bt(b,t,s,i,r,n,o+1);return!!T}}const It=new At.constructor,Dt=new At.constructor,Lt=new St(()=>new i.Box3),Ft=new i.Box3,Ot=new i.Box3,Vt=new i.Box3,zt=new i.Box3;let kt=!1;function Ut(e,t,s,i,r,n=0,o=0,a=0,l=0,h=null,u=!1){let c,d;u?(c=Dt,d=It):(c=It,d=Dt);const p=c.float32Array,m=c.uint32Array,f=c.uint16Array,g=d.float32Array,y=d.uint32Array,x=d.uint16Array,b=2*t,_=tt(2*e,f),w=tt(b,x);let v=!1;if(w&&_)v=u?r(st(t,y),it(2*t,x),st(e,m),it(2*e,f),l,o+t/8,a,n+e/8):r(st(e,m),it(2*e,f),st(t,y),it(2*t,x),a,n+e/8,l,o+t/8);else if(w){const h=Lt.getPrimitive();Ye(t,g,h),h.applyMatrix4(s);const c=rt(e),d=nt(e,m);Ye(c,p,Ft),Ye(d,p,Ot);const f=h.intersectsBox(Ft),y=h.intersectsBox(Ot);v=f&&Ut(t,c,i,s,r,o,n,l,a+1,h,!u)||y&&Ut(t,d,i,s,r,o,n,l,a+1,h,!u),Lt.releasePrimitive(h)}else{const c=rt(t),d=nt(t,y);Ye(c,g,Vt),Ye(d,g,zt);const f=h.intersectsBox(Vt),x=h.intersectsBox(zt);if(f&&x)v=Ut(e,c,s,i,r,n,o,a,l+1,h,u)||Ut(e,d,s,i,r,n,o,a,l+1,h,u);else if(f)if(_)v=Ut(e,c,s,i,r,n,o,a,l+1,h,u);else{const t=Lt.getPrimitive();t.copy(Vt).applyMatrix4(s);const h=rt(e),d=nt(e,m);Ye(h,p,Ft),Ye(d,p,Ot);const f=t.intersectsBox(Ft),g=t.intersectsBox(Ot);v=f&&Ut(c,h,i,s,r,o,n,l,a+1,t,!u)||g&&Ut(c,d,i,s,r,o,n,l,a+1,t,!u),Lt.releasePrimitive(t)}else if(x)if(_)v=Ut(e,d,s,i,r,n,o,a,l+1,h,u);else{const t=Lt.getPrimitive();t.copy(zt).applyMatrix4(s);const h=rt(e),c=nt(e,m);Ye(h,p,Ft),Ye(c,p,Ot);const f=t.intersectsBox(Ft),g=t.intersectsBox(Ot);v=f&&Ut(d,h,i,s,r,o,n,l,a+1,t,!u)||g&&Ut(d,c,i,s,r,o,n,l,a+1,t,!u),Lt.releasePrimitive(t)}}return v}const Gt=new i.Box3,jt=new Float32Array(6);class $t{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){Tt(this,e={...Xe,...e})}getRootRanges(){throw new Error("BVH: getRootRanges() not implemented")}writePrimitiveBounds(){throw new Error("BVH: writePrimitiveBounds() not implemented")}writePrimitiveRangeBounds(e,t,s,i){let r=1/0,n=1/0,o=1/0,a=-1/0,l=-1/0,h=-1/0;for(let s=e,i=e+t;s<i;s++){this.writePrimitiveBounds(s,jt,0);const[e,t,i,u,c,d]=jt;e<r&&(r=e),u>a&&(a=u),t<n&&(n=t),c>l&&(l=c),i<o&&(o=i),d>h&&(h=d)}return s[i+0]=r,s[i+1]=n,s[i+2]=o,s[i+3]=a,s[i+4]=l,s[i+5]=h,s}computePrimitiveBounds(e,t,s){const i=s.offset||0;for(let r=e,n=e+t;r<n;r++){this.writePrimitiveBounds(r,jt,0);const[e,t,n,o,a,l]=jt,h=(e+o)/2,u=(t+a)/2,c=(n+l)/2,d=(o-e)/2,p=(a-t)/2,m=(l-n)/2,f=6*(r-i);s[f+0]=h,s[f+1]=d+(Math.abs(h)+d)*He,s[f+2]=u,s[f+3]=p+(Math.abs(u)+p)*He,s[f+4]=c,s[f+5]=m+(Math.abs(c)+m)*He}return s}shiftPrimitiveOffsets(e){const t=this._indirectBuffer;if(t)for(let s=0,i=t.length;s<i;s++)t[s]+=e;else{const t=this._roots;for(let s=0;s<t.length;s++){const i=t[s],r=new Uint32Array(i),n=new Uint16Array(i),o=i.byteLength/We;for(let t=0;t<o;t++){const s=8*t;tt(2*s,n)&&(r[s+6]+=e)}}}}traverse(e,t=0){const s=this._roots[t],i=new Uint32Array(s),r=new Uint16Array(s);!function t(n,o=0){const a=2*n,l=tt(a,r);if(l){const t=i[n+6],h=r[a+14];e(o,l,new Float32Array(s,4*n,6),t,h)}else{const r=rt(n),a=nt(n,i),h=ot(n,i);e(o,l,new Float32Array(s,4*n,6),h)||(t(r,o+1),t(a,o+1))}}(0)}refit(){const e=this._roots;for(let t=0,s=e.length;t<s;t++){const s=e[t],i=new Uint32Array(s),r=new Uint16Array(s),n=new Float32Array(s);for(let e=s.byteLength/We-1;e>=0;e--){const t=8*e,s=2*t;if(tt(s,r)){const e=st(t,i),o=it(s,r);this.writePrimitiveRangeBounds(e,o,jt,0),n.set(jt,t)}else{const e=rt(t),s=nt(t,i);for(let i=0;i<3;i++){const r=n[e+i],o=n[e+i+3],a=n[s+i],l=n[s+i+3];n[t+i]=r<a?r:a,n[t+i+3]=o>l?o:l}}}}}getBoundingBox(e){e.makeEmpty();return this._roots.forEach(t=>{Ye(0,new Float32Array(t),Gt),e.union(Gt)}),e}shapecast(e){let{boundsTraverseOrder:t,intersectsBounds:s,intersectsRange:i,intersectsPrimitive:r,scratchPrimitive:n,iterate:o}=e;if(i&&r){const e=i;i=(t,s,i,a,l)=>!!e(t,s,i,a,l)||o(t,s,this,r,i,a,n)}else i||(i=r?(e,t,s,i)=>o(e,t,this,r,s,i,n):(e,t,s)=>s);let a=!1,l=0;const h=this._roots;for(let e=0,r=h.length;e<r;e++){const r=h[e];if(a=Pt(this,e,s,i,t,l),a)break;l+=r.byteLength/We}return a}bvhcast(e,t,s){let{intersectsRanges:r}=s;return function(e,t,s,r){if(kt)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");kt=!0;const n=e._roots,o=t._roots;let a,l=0,h=0;const u=(new i.Matrix4).copy(s).invert();for(let e=0,t=n.length;e<t;e++){It.setBuffer(n[e]),h=0;const t=Lt.getPrimitive();Ye(at(0),It.float32Array,t),t.applyMatrix4(u);for(let e=0,i=o.length;e<i&&(Dt.setBuffer(o[e]),a=Ut(0,0,s,u,r,l,h,0,0,t),Dt.clearBuffer(),h+=o[e].byteLength/We,!a);e++);if(Lt.releasePrimitive(t),It.clearBuffer(),l+=n[e].byteLength/We,a)break}return kt=!1,a}(this,e,t,r)}}function Wt(e){return e.index?e.index.count:e.attributes.position.count}function Ht(e){return Wt(e)/3}function qt(e,t){if(!e.index){const s=e.attributes.position.count,r=function(e,t=ArrayBuffer){return e>65535?new Uint32Array(new t(4*e)):new Uint16Array(new t(2*e))}(s,t.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer);e.setIndex(new i.BufferAttribute(r,1));for(let e=0;e<s;e++)r[e]=e}}function Xt(e,t,s){const i=function(e,t,s){const i=Wt(e)/s,r=t||e.drawRange,n=r.start/s,o=(r.start+r.count)/s,a=Math.max(0,n),l=Math.min(i,o)-a;return{offset:Math.floor(a),count:Math.floor(l)}}(e,t,s),r=function(e,t){return e.groups.map(e=>({offset:e.start/t,count:e.count/t}))}(e,s);if(!r.length)return[i];const n=[],o=i.offset,a=i.offset+i.count,l=Wt(e)/s,h=[];for(const e of r){const{offset:t,count:s}=e,i=t,r=t+(isFinite(s)?s:l-t);i<a&&r>o&&(h.push({pos:Math.max(o,i),isStart:!0}),h.push({pos:Math.min(a,r),isStart:!1}))}h.sort((e,t)=>e.pos!==t.pos?e.pos-t.pos:"end"===e.type?-1:1);let u=0,c=null;for(const e of h){const t=e.pos;0!==u&&t!==c&&n.push({offset:c,count:t-c}),u+=e.isStart?1:-1,c=t}return n}class Yt extends $t{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={...Xe,...t})[qe]||this.init(t)}init(e){const{geometry:t,primitiveStride:s}=this;if(e.indirect){const i=function(e,t){const s=e[e.length-1],i=s.offset+s.count>65536,r=e.reduce((e,t)=>e+t.count,0),n=i?4:2,o=t?new SharedArrayBuffer(r*n):new ArrayBuffer(r*n),a=i?new Uint32Array(o):new Uint16Array(o);let l=0;for(let t=0;t<e.length;t++){const{offset:s,count:i}=e[t];for(let e=0;e<i;e++)a[l+e]=s+e;l+=i}return a}(Xt(t,e.range,s),e.useSharedArrayBuffer);this._indirectBuffer=i}else qt(t,e);super.init(e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new i.Box3))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:Xt(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Zt{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(e,t){let s=1/0,i=-1/0;for(let r=0,n=e.length;r<n;r++){const n=e[r][t];s=n<s?n:s,i=n>i?n:i}this.min=s,this.max=i}setFromPoints(e,t){let s=1/0,i=-1/0;for(let r=0,n=t.length;r<n;r++){const n=t[r],o=e.dot(n);s=o<s?o:s,i=o>i?o:i}this.min=s,this.max=i}isSeparated(e){return this.min>e.max||e.min>this.max}}Zt.prototype.setFromBox=function(){const e=new i.Vector3;return function(t,s){const i=s.min,r=s.max;let n=1/0,o=-1/0;for(let s=0;s<=1;s++)for(let a=0;a<=1;a++)for(let l=0;l<=1;l++){e.x=i.x*s+r.x*(1-s),e.y=i.y*a+r.y*(1-a),e.z=i.z*l+r.z*(1-l);const h=t.dot(e);n=Math.min(h,n),o=Math.max(h,o)}this.min=n,this.max=o}}();const Qt=function(){const e=new i.Vector3,t=new i.Vector3,s=new i.Vector3;return function(i,r,n){const o=i.start,a=e,l=r.start,h=t;s.subVectors(o,l),e.subVectors(i.end,i.start),t.subVectors(r.end,r.start);const u=s.dot(h),c=h.dot(a),d=h.dot(h),p=s.dot(a),m=a.dot(a)*d-c*c;let f,g;f=0!==m?(u*c-p*d)/m:0,g=(u+f*c)/d,n.x=f,n.y=g}}(),Kt=function(){const e=new i.Vector2,t=new i.Vector3,s=new i.Vector3;return function(i,r,n,o){Qt(i,r,e);let a=e.x,l=e.y;if(a>=0&&a<=1&&l>=0&&l<=1)return i.at(a,n),void r.at(l,o);if(a>=0&&a<=1)return l<0?r.at(0,o):r.at(1,o),void i.closestPointToPoint(o,!0,n);if(l>=0&&l<=1)return a<0?i.at(0,n):i.at(1,n),void r.closestPointToPoint(n,!0,o);{let e,h;e=a<0?i.start:i.end,h=l<0?r.start:r.end;const u=t,c=s;return i.closestPointToPoint(h,!0,t),r.closestPointToPoint(e,!0,s),u.distanceToSquared(h)<=c.distanceToSquared(e)?(n.copy(u),void o.copy(h)):(n.copy(e),void o.copy(c))}}}(),Jt=function(){const e=new i.Vector3,t=new i.Vector3,s=new i.Plane,r=new i.Line3;return function(i,n){const{radius:o,center:a}=i,{a:l,b:h,c:u}=n;r.start=l,r.end=h;if(r.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;r.start=l,r.end=u;if(r.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;r.start=h,r.end=u;if(r.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;const c=n.getPlane(s);if(Math.abs(c.distanceToPoint(a))<=o){const e=c.projectPoint(a,t);if(n.containsPoint(e))return!0}return!1}}(),es=["x","y","z"],ts=1e-15;function ss(e){return Math.abs(e)<ts}class is extends i.Triangle{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new i.Vector3),this.satBounds=new Array(4).fill().map(()=>new Zt),this.points=[this.a,this.b,this.c],this.plane=new i.Plane,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new i.Line3,this.needsUpdate=!0}intersectsSphere(e){return Jt(e,this)}update(){const e=this.a,t=this.b,s=this.c,i=this.points,r=this.satAxes,n=this.satBounds,o=r[0],a=n[0];this.getNormal(o),a.setFromPoints(o,i);const l=r[1],h=n[1];l.subVectors(e,t),h.setFromPoints(l,i);const u=r[2],c=n[2];u.subVectors(t,s),c.setFromPoints(u,i);const d=r[3],p=n[3];d.subVectors(s,e),p.setFromPoints(d,i);const m=l.length(),f=u.length(),g=d.length();this.isDegenerateIntoPoint=!1,this.isDegenerateIntoSegment=!1,m<ts?f<ts||g<ts?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(s)):f<ts?g<ts?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):g<ts&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(s),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(o,e),this.needsUpdate=!1}}is.prototype.closestPointToSegment=function(){const e=new i.Vector3,t=new i.Vector3,s=new i.Line3;return function(i,r=null,n=null){const{start:o,end:a}=i,l=this.points;let h,u=1/0;for(let o=0;o<3;o++){const a=(o+1)%3;s.start.copy(l[o]),s.end.copy(l[a]),Kt(s,i,e,t),h=e.distanceToSquared(t),h<u&&(u=h,r&&r.copy(e),n&&n.copy(t))}return this.closestPointToPoint(o,e),h=o.distanceToSquared(e),h<u&&(u=h,r&&r.copy(e),n&&n.copy(o)),this.closestPointToPoint(a,e),h=a.distanceToSquared(e),h<u&&(u=h,r&&r.copy(e),n&&n.copy(a)),Math.sqrt(u)}}(),is.prototype.intersectsTriangle=function(){const e=new is,t=new Zt,s=new Zt,r=new i.Vector3,n=new i.Vector3,o=new i.Vector3,a=new i.Vector3,l=new i.Line3,h=new i.Line3,u=new i.Vector3,c=new i.Vector2,d=new i.Vector2;function p(e,i,n,o){const l=r;e.isDegenerateIntoPoint||e.isDegenerateIntoSegment?l.copy(i.plane.normal):l.copy(e.plane.normal);const h=e.satBounds,u=e.satAxes;for(let r=1;r<4;r++){const n=h[r],o=u[r];if(t.setFromPoints(o,i.points),n.isSeparated(t))return!1;if(a.copy(l).cross(o),t.setFromPoints(a,e.points),s.setFromPoints(a,i.points),t.isSeparated(s))return!1}const c=i.satBounds,d=i.satAxes;for(let r=1;r<4;r++){const n=c[r],o=d[r];if(t.setFromPoints(o,e.points),n.isSeparated(t))return!1;if(a.crossVectors(l,o),t.setFromPoints(a,e.points),s.setFromPoints(a,i.points),t.isSeparated(s))return!1}return n&&(o||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),n.start.set(0,0,0),n.end.set(0,0,0)),!0}function m(e,t,s,i,r,n,o,a,l,h,u){let c=o/(o-a);h.x=i+(r-i)*c,u.start.subVectors(t,e).multiplyScalar(c).add(e),c=o/(o-l),h.y=i+(n-i)*c,u.end.subVectors(s,e).multiplyScalar(c).add(e)}function f(e,t,s,i,r,n,o,a,l,h,u){if(r>0)m(e.c,e.a,e.b,i,t,s,l,o,a,h,u);else if(n>0)m(e.b,e.a,e.c,s,t,i,a,o,l,h,u);else if(a*l>0||0!=o)m(e.a,e.b,e.c,t,s,i,o,a,l,h,u);else if(0!=a)m(e.b,e.a,e.c,s,t,i,a,o,l,h,u);else{if(0==l)return!0;m(e.c,e.a,e.b,i,t,s,l,o,a,h,u)}return!1}function g(e,t,s,i){const n=t.degenerateSegment,o=e.plane.distanceToPoint(n.start),a=e.plane.distanceToPoint(n.end);return ss(o)?ss(a)?p(e,t,s,i):(s&&(s.start.copy(n.start),s.end.copy(n.start)),e.containsPoint(n.start)):ss(a)?(s&&(s.start.copy(n.end),s.end.copy(n.end)),e.containsPoint(n.end)):null!=e.plane.intersectLine(n,r)&&(s&&(s.start.copy(r),s.end.copy(r)),e.containsPoint(r))}function y(e,t,s){const i=t.a;return!(!ss(e.plane.distanceToPoint(i))||!e.containsPoint(i))&&(s&&(s.start.copy(i),s.end.copy(i)),!0)}function x(e,t,s){const i=e.degenerateSegment,n=t.a;return i.closestPointToPoint(n,!0,r),n.distanceToSquared(r)<1e-30&&(s&&(s.start.copy(n),s.end.copy(n)),!0)}return function(t,s=null,i=!1){this.needsUpdate&&this.update(),t.isExtendedTriangle?t.needsUpdate&&t.update():(e.copy(t),e.update(),t=e);const a=function(e,t,s,i){if(e.isDegenerateIntoSegment){if(t.isDegenerateIntoSegment){const i=e.degenerateSegment,a=t.degenerateSegment,l=n,h=o;i.delta(l),a.delta(h);const u=r.subVectors(a.start,i.start),c=l.x*h.y-l.y*h.x;if(ss(c))return!1;const d=(u.x*h.y-u.y*h.x)/c,p=-(l.x*u.y-l.y*u.x)/c;return!(d<0||d>1||p<0||p>1)&&(!!ss(i.start.z+l.z*d-(a.start.z+h.z*p))&&(s&&(s.start.copy(i.start).addScaledVector(l,d),s.end.copy(i.start).addScaledVector(l,d)),!0))}return t.isDegenerateIntoPoint?x(e,t,s):g(t,e,s,i)}return e.isDegenerateIntoPoint?t.isDegenerateIntoPoint?t.a.distanceToSquared(e.a)<1e-30&&(s&&(s.start.copy(e.a),s.end.copy(e.a)),!0):t.isDegenerateIntoSegment?x(t,e,s):y(t,e,s):t.isDegenerateIntoPoint?y(e,t,s):t.isDegenerateIntoSegment?g(e,t,s,i):void 0}(this,t,s,i);if(void 0!==a)return a;const m=this.plane,b=t.plane;let _=b.distanceToPoint(this.a),w=b.distanceToPoint(this.b),v=b.distanceToPoint(this.c);ss(_)&&(_=0),ss(w)&&(w=0),ss(v)&&(v=0);const T=_*w,S=_*v;if(T>0&&S>0)return!1;let M=m.distanceToPoint(t.a),A=m.distanceToPoint(t.b),N=m.distanceToPoint(t.c);ss(M)&&(M=0),ss(A)&&(A=0),ss(N)&&(N=0);const E=M*A,C=M*N;if(E>0&&C>0)return!1;n.copy(m.normal),o.copy(b.normal);const R=n.cross(o);let P=0,B=Math.abs(R.x);const I=Math.abs(R.y);I>B&&(B=I,P=1);Math.abs(R.z)>B&&(P=2);const D=es[P],L=this.a[D],F=this.b[D],O=this.c[D],V=t.a[D],z=t.b[D],k=t.c[D];if(f(this,L,F,O,T,S,_,w,v,c,l))return p(this,t,s,i);if(f(t,V,z,k,E,C,M,A,N,d,h))return p(this,t,s,i);if(c.y<c.x){const e=c.y;c.y=c.x,c.x=e,u.copy(l.start),l.start.copy(l.end),l.end.copy(u)}if(d.y<d.x){const e=d.y;d.y=d.x,d.x=e,u.copy(h.start),h.start.copy(h.end),h.end.copy(u)}return!(c.y<d.x||d.y<c.x)&&(s&&(d.x>c.x?s.start.copy(h.start):s.start.copy(l.start),d.y<c.y?s.end.copy(h.end):s.end.copy(l.end)),!0)}}(),is.prototype.distanceToPoint=function(){const e=new i.Vector3;return function(t){return this.closestPointToPoint(t,e),t.distanceTo(e)}}(),is.prototype.distanceToTriangle=function(){const e=new i.Vector3,t=new i.Vector3,s=["a","b","c"],r=new i.Line3,n=new i.Line3;return function(i,o=null,a=null){const l=o||a?r:null;if(this.intersectsTriangle(i,l))return(o||a)&&(o&&l.getCenter(o),a&&l.getCenter(a)),0;let h=1/0;for(let t=0;t<3;t++){let r;const n=s[t],l=i[n];this.closestPointToPoint(l,e),r=l.distanceToSquared(e),r<h&&(h=r,o&&o.copy(e),a&&a.copy(l));const u=this[n];i.closestPointToPoint(u,e),r=u.distanceToSquared(e),r<h&&(h=r,o&&o.copy(u),a&&a.copy(e))}for(let l=0;l<3;l++){const u=s[l],c=s[(l+1)%3];r.set(this[u],this[c]);for(let l=0;l<3;l++){const u=s[l],c=s[(l+1)%3];n.set(i[u],i[c]),Kt(r,n,e,t);const d=e.distanceToSquared(t);d<h&&(h=d,o&&o.copy(e),a&&a.copy(t))}}return Math.sqrt(h)}}();class rs{constructor(e,t,s){this.isOrientedBox=!0,this.min=new i.Vector3,this.max=new i.Vector3,this.matrix=new i.Matrix4,this.invMatrix=new i.Matrix4,this.points=new Array(8).fill().map(()=>new i.Vector3),this.satAxes=new Array(3).fill().map(()=>new i.Vector3),this.satBounds=new Array(3).fill().map(()=>new Zt),this.alignedSatBounds=new Array(3).fill().map(()=>new Zt),this.needsUpdate=!1,e&&this.min.copy(e),t&&this.max.copy(t),s&&this.matrix.copy(s)}set(e,t,s){this.min.copy(e),this.max.copy(t),this.matrix.copy(s),this.needsUpdate=!0}copy(e){this.min.copy(e.min),this.max.copy(e.max),this.matrix.copy(e.matrix),this.needsUpdate=!0}}rs.prototype.update=function(){return function(){const e=this.matrix,t=this.min,s=this.max,i=this.points;for(let r=0;r<=1;r++)for(let n=0;n<=1;n++)for(let o=0;o<=1;o++){const a=i[1*r|2*n|4*o];a.x=r?s.x:t.x,a.y=n?s.y:t.y,a.z=o?s.z:t.z,a.applyMatrix4(e)}const r=this.satBounds,n=this.satAxes,o=i[0];for(let e=0;e<3;e++){const t=n[e],s=r[e],a=i[1<<e];t.subVectors(o,a),s.setFromPoints(t,i)}const a=this.alignedSatBounds;a[0].setFromPointsField(i,"x"),a[1].setFromPointsField(i,"y"),a[2].setFromPointsField(i,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}(),rs.prototype.intersectsBox=function(){const e=new Zt;return function(t){this.needsUpdate&&this.update();const s=t.min,i=t.max,r=this.satBounds,n=this.satAxes,o=this.alignedSatBounds;if(e.min=s.x,e.max=i.x,o[0].isSeparated(e))return!1;if(e.min=s.y,e.max=i.y,o[1].isSeparated(e))return!1;if(e.min=s.z,e.max=i.z,o[2].isSeparated(e))return!1;for(let s=0;s<3;s++){const i=n[s],o=r[s];if(e.setFromBox(i,t),o.isSeparated(e))return!1}return!0}}(),rs.prototype.intersectsTriangle=function(){const e=new is,t=new Array(3),s=new Zt,r=new Zt,n=new i.Vector3;return function(i){this.needsUpdate&&this.update(),i.isExtendedTriangle?i.needsUpdate&&i.update():(e.copy(i),e.update(),i=e);const o=this.satBounds,a=this.satAxes;t[0]=i.a,t[1]=i.b,t[2]=i.c;for(let e=0;e<3;e++){const i=o[e],r=a[e];if(s.setFromPoints(r,t),i.isSeparated(s))return!1}const l=i.satBounds,h=i.satAxes,u=this.points;for(let e=0;e<3;e++){const t=l[e],i=h[e];if(s.setFromPoints(i,u),t.isSeparated(s))return!1}for(let e=0;e<3;e++){const i=a[e];for(let e=0;e<4;e++){const o=h[e];if(n.crossVectors(i,o),s.setFromPoints(n,t),r.setFromPoints(n,u),s.isSeparated(r))return!1}}return!0}}(),rs.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}}(),rs.prototype.distanceToPoint=function(){const e=new i.Vector3;return function(t){return this.closestPointToPoint(t,e),t.distanceTo(e)}}(),rs.prototype.distanceToBox=function(){const e=["x","y","z"],t=new Array(12).fill().map(()=>new i.Line3),s=new Array(12).fill().map(()=>new i.Line3),r=new i.Vector3,n=new i.Vector3;return function(i,o=0,a=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(i))return(a||l)&&(i.getCenter(n),this.closestPointToPoint(n,r),i.closestPointToPoint(r,n),a&&a.copy(r),l&&l.copy(n)),0;const h=o*o,u=i.min,c=i.max,d=this.points;let p=1/0;for(let e=0;e<8;e++){const t=d[e];n.copy(t).clamp(u,c);const s=t.distanceToSquared(n);if(s<p&&(p=s,a&&a.copy(t),l&&l.copy(n),s<h))return Math.sqrt(s)}let m=0;for(let i=0;i<3;i++)for(let r=0;r<=1;r++)for(let n=0;n<=1;n++){const o=(i+1)%3,a=(i+2)%3,l=1<<i|r<<o|n<<a,h=d[r<<o|n<<a],p=d[l];t[m].set(h,p);const f=e[i],g=e[o],y=e[a],x=s[m],b=x.start,_=x.end;b[f]=u[f],b[g]=r?u[g]:c[g],b[y]=n?u[y]:c[g],_[f]=c[f],_[g]=r?u[g]:c[g],_[y]=n?u[y]:c[g],m++}for(let e=0;e<=1;e++)for(let t=0;t<=1;t++)for(let s=0;s<=1;s++){n.x=e?c.x:u.x,n.y=t?c.y:u.y,n.z=s?c.z:u.z,this.closestPointToPoint(n,r);const i=n.distanceToSquared(r);if(i<p&&(p=i,a&&a.copy(r),l&&l.copy(n),i<h))return Math.sqrt(i)}for(let e=0;e<12;e++){const i=t[e];for(let e=0;e<12;e++){const t=s[e];Kt(i,t,r,n);const o=r.distanceToSquared(n);if(o<p&&(p=o,a&&a.copy(r),l&&l.copy(n),o<h))return Math.sqrt(o)}}return Math.sqrt(p)}}();class ns extends St{constructor(){super(()=>new is)}}const os=new ns,as=new i.Vector3,ls=new i.Vector3;const hs=parseInt(i.REVISION)>=169,us=parseInt(i.REVISION)<=161,cs=new i.Vector3,ds=new i.Vector3,ps=new i.Vector3,ms=new i.Vector2,fs=new i.Vector2,gs=new i.Vector2,ys=new i.Vector3,xs=new i.Vector3,bs=new i.Vector3,_s=new i.Vector3;function ws(e,t,s,r,n,o,a,l,h,u,c){cs.fromBufferAttribute(t,o),ds.fromBufferAttribute(t,a),ps.fromBufferAttribute(t,l);const d=function(e,t,s,r,n,o,a,l){let h;if(h=o===i.BackSide?e.intersectTriangle(r,s,t,!0,n):e.intersectTriangle(t,s,r,o!==i.DoubleSide,n),null===h)return null;const u=e.origin.distanceTo(n);return u<a||u>l?null:{distance:u,point:n.clone()}}(e,cs,ds,ps,_s,h,u,c);if(d){if(r){ms.fromBufferAttribute(r,o),fs.fromBufferAttribute(r,a),gs.fromBufferAttribute(r,l),d.uv=new i.Vector2;const e=i.Triangle.getInterpolation(_s,cs,ds,ps,ms,fs,gs,d.uv);hs||(d.uv=e)}if(n){ms.fromBufferAttribute(n,o),fs.fromBufferAttribute(n,a),gs.fromBufferAttribute(n,l),d.uv1=new i.Vector2;const e=i.Triangle.getInterpolation(_s,cs,ds,ps,ms,fs,gs,d.uv1);hs||(d.uv1=e),us&&(d.uv2=d.uv1)}if(s){ys.fromBufferAttribute(s,o),xs.fromBufferAttribute(s,a),bs.fromBufferAttribute(s,l),d.normal=new i.Vector3;const t=i.Triangle.getInterpolation(_s,cs,ds,ps,ys,xs,bs,d.normal);d.normal.dot(e.direction)>0&&d.normal.multiplyScalar(-1),hs||(d.normal=t)}const t={a:o,b:a,c:l,normal:new i.Vector3,materialIndex:0};if(i.Triangle.getNormal(cs,ds,ps,t.normal),d.face=t,d.faceIndex=o,hs){const e=new i.Vector3;i.Triangle.getBarycoord(_s,cs,ds,ps,e),d.barycoord=e}}return d}function vs(e){return e&&e.isMaterial?e.side:e}function Ts(e,t,s,i,r,n,o){const a=3*i;let l=a+0,h=a+1,u=a+2;const{index:c,groups:d}=e;e.index&&(l=c.getX(l),h=c.getX(h),u=c.getX(u));const{position:p,normal:m,uv:f,uv1:g}=e.attributes;if(Array.isArray(t)){const e=3*i;for(let a=0,c=d.length;a<c;a++){const{start:c,count:y,materialIndex:x}=d[a];if(e>=c&&e<c+y){const e=ws(s,p,m,f,g,l,h,u,vs(t[x]),n,o);if(e){if(e.faceIndex=i,e.face.materialIndex=x,!r)return e;r.push(e)}}}}else{const e=ws(s,p,m,f,g,l,h,u,vs(t),n,o);if(e){if(e.faceIndex=i,e.face.materialIndex=0,!r)return e;r.push(e)}}return null}function Ss(e,t,s,i){const r=e.a,n=e.b,o=e.c;let a=t,l=t+1,h=t+2;s&&(a=s.getX(a),l=s.getX(l),h=s.getX(h)),r.x=i.getX(a),r.y=i.getY(a),r.z=i.getZ(a),n.x=i.getX(l),n.y=i.getY(l),n.z=i.getZ(l),o.x=i.getX(h),o.y=i.getY(h),o.z=i.getZ(h)}function Ms(e,t,s,i,r,n,o){const{geometry:a}=s,{index:l}=a,h=a.attributes.position;for(let s=e,a=t+e;s<a;s++){let e;if(e=s,Ss(o,3*e,l,h),o.needsUpdate=!0,i(o,e,r,n))return!0}return!1}function As(e,t=null){t&&Array.isArray(t)&&(t=new Set(t));const s=e.geometry,i=s.index?s.index.array:null,r=s.attributes.position;let n,o,a,l,h=0;const u=e._roots;for(let e=0,t=u.length;e<t;e++)n=u[e],o=new Uint32Array(n),a=new Uint16Array(n),l=new Float32Array(n),c(0,h),h+=n.byteLength;function c(e,s,n=!1){const h=2*e;if(tt(h,a)){const t=st(e,o);let s=1/0,n=1/0,u=1/0,c=-1/0,d=-1/0,p=-1/0;for(let e=3*t,o=3*(t+it(h,a));e<o;e++){let t=i[e];const o=r.getX(t),a=r.getY(t),l=r.getZ(t);o<s&&(s=o),o>c&&(c=o),a<n&&(n=a),a>d&&(d=a),l<u&&(u=l),l>p&&(p=l)}return(l[e+0]!==s||l[e+1]!==n||l[e+2]!==u||l[e+3]!==c||l[e+4]!==d||l[e+5]!==p)&&(l[e+0]=s,l[e+1]=n,l[e+2]=u,l[e+3]=c,l[e+4]=d,l[e+5]=p,!0)}{const i=rt(e),r=nt(e,o);let a=n,h=!1,u=!1;if(t){if(!a){const e=i/8+s/We,n=r/8+s/We;h=t.has(e),u=t.has(n),a=!h&&!u}}else h=!0,u=!0;const d=a||u;let p=!1;(a||h)&&(p=c(i,s,a));let m=!1;d&&(m=c(r,s,a));const f=p||m;if(f)for(let t=0;t<3;t++){const s=i+t,n=r+t,o=l[s],a=l[s+3],h=l[n],u=l[n+3];l[e+t]=o<h?o:h,l[e+t+3]=a>u?a:u}return f}}}function Ns(e,t,s,i,r){let n,o,a,l,h,u;const c=1/s.direction.x,d=1/s.direction.y,p=1/s.direction.z,m=s.origin.x,f=s.origin.y,g=s.origin.z;let y=t[e],x=t[e+3],b=t[e+1],_=t[e+3+1],w=t[e+2],v=t[e+3+2];return c>=0?(n=(y-m)*c,o=(x-m)*c):(n=(x-m)*c,o=(y-m)*c),d>=0?(a=(b-f)*d,l=(_-f)*d):(a=(_-f)*d,l=(b-f)*d),!(n>l||a>o)&&((a>n||isNaN(n))&&(n=a),(l<o||isNaN(o))&&(o=l),p>=0?(h=(w-g)*p,u=(v-g)*p):(h=(v-g)*p,u=(w-g)*p),!(n>u||h>o)&&((h>n||n!=n)&&(n=h),(u<o||o!=o)&&(o=u),n<=r&&o>=i))}function Es(e,t,s,i,r,n,o){const{geometry:a}=s,{index:l}=a,h=a.attributes.position;for(let a=e,u=t+e;a<u;a++){let e;if(e=s.resolveTriangleIndex(a),Ss(o,3*e,l,h),o.needsUpdate=!0,i(o,e,r,n))return!0}return!1}function Cs(e,t,s,i,r,n,o){At.setBuffer(e._roots[t]),Rs(0,e,s,i,r,n,o),At.clearBuffer()}function Rs(e,t,s,i,r,n,o){const{float32Array:a,uint16Array:l,uint32Array:h}=At,u=2*e;if(tt(u,l)){!function(e,t,s,i,r,n,o,a){const{geometry:l,_indirectBuffer:h}=e;for(let e=i,h=i+r;e<h;e++)Ts(l,t,s,e,n,o,a)}(t,s,i,st(e,h),it(u,l),r,n,o)}else{const l=rt(e);Ns(l,a,i,n,o)&&Rs(l,t,s,i,r,n,o);const u=nt(e,h);Ns(u,a,i,n,o)&&Rs(u,t,s,i,r,n,o)}}const Ps=["x","y","z"];function Bs(e,t,s,i,r,n){At.setBuffer(e._roots[t]);const o=Is(0,e,s,i,r,n);return At.clearBuffer(),o}function Is(e,t,s,i,r,n){const{float32Array:o,uint16Array:a,uint32Array:l}=At;let h=2*e;if(tt(h,a)){return function(e,t,s,i,r,n,o){const{geometry:a,_indirectBuffer:l}=e;let h=1/0,u=null;for(let e=i,l=i+r;e<l;e++){let i;i=Ts(a,t,s,e,null,n,o),i&&i.distance<h&&(u=i,h=i.distance)}return u}(t,s,i,st(e,l),it(h,a),r,n)}{const a=ot(e,l),h=Ps[a],u=i.direction[h]>=0;let c,d;u?(c=rt(e),d=nt(e,l)):(c=nt(e,l),d=rt(e));const p=Ns(c,o,i,r,n)?Is(c,t,s,i,r,n):null;if(p){const e=p.point[h];if(u?e<=o[d+a]:e>=o[d+a+3])return p}const m=Ns(d,o,i,r,n)?Is(d,t,s,i,r,n):null;return p&&m?p.distance<=m.distance?p:m:p||m||null}}const Ds=new i.Box3,Ls=new is,Fs=new is,Os=new i.Matrix4,Vs=new rs,zs=new rs;function ks(e,t,s,i){At.setBuffer(e._roots[t]);const r=Us(0,e,s,i);return At.clearBuffer(),r}function Us(e,t,s,i,r=null){const{float32Array:n,uint16Array:o,uint32Array:a}=At;let l=2*e;null===r&&(s.boundingBox||s.computeBoundingBox(),Vs.set(s.boundingBox.min,s.boundingBox.max,i),r=Vs);if(!tt(l,o)){const o=rt(e),l=nt(e,a);Ye(o,n,Ds);if(r.intersectsBox(Ds)&&Us(o,t,s,i,r))return!0;Ye(l,n,Ds);return!!(r.intersectsBox(Ds)&&Us(l,t,s,i,r))}{const r=t.geometry,h=r.index,u=r.attributes.position,c=s.index,d=s.attributes.position,p=st(e,a),m=it(l,o);if(Os.copy(i).invert(),s.boundsTree){Ye(e,n,zs),zs.matrix.copy(Os),zs.needsUpdate=!0;return s.boundsTree.shapecast({intersectsBounds:e=>zs.intersectsBox(e),intersectsTriangle:e=>{e.a.applyMatrix4(i),e.b.applyMatrix4(i),e.c.applyMatrix4(i),e.needsUpdate=!0;for(let t=3*p,s=3*(m+p);t<s;t+=3)if(Ss(Fs,t,h,u),Fs.needsUpdate=!0,e.intersectsTriangle(Fs))return!0;return!1}})}{const e=Ht(s);for(let t=3*p,s=3*(m+p);t<s;t+=3){Ss(Ls,t,h,u),Ls.a.applyMatrix4(Os),Ls.b.applyMatrix4(Os),Ls.c.applyMatrix4(Os),Ls.needsUpdate=!0;for(let t=0,s=3*e;t<s;t+=3)if(Ss(Fs,t,c,d),Fs.needsUpdate=!0,Ls.intersectsTriangle(Fs))return!0}}}}const Gs=new i.Matrix4,js=new rs,$s=new rs,Ws=new i.Vector3,Hs=new i.Vector3,qs=new i.Vector3,Xs=new i.Vector3;function Ys(e,t,s,i={},r={},n=0,o=1/0){t.boundingBox||t.computeBoundingBox(),js.set(t.boundingBox.min,t.boundingBox.max,s),js.needsUpdate=!0;const a=e.geometry,l=a.attributes.position,h=a.index,u=t.attributes.position,c=t.index,d=os.getPrimitive(),p=os.getPrimitive();let m=Ws,f=Hs,g=null,y=null;r&&(g=qs,y=Xs);let x=1/0,b=null,_=null;return Gs.copy(s).invert(),$s.matrix.copy(Gs),e.shapecast({boundsTraverseOrder:e=>js.distanceToBox(e),intersectsBounds:(e,t,s)=>s<x&&s<o&&(t&&($s.min.copy(e.min),$s.max.copy(e.max),$s.needsUpdate=!0),!0),intersectsRange:(e,i)=>{if(t.boundsTree){return t.boundsTree.shapecast({boundsTraverseOrder:e=>$s.distanceToBox(e),intersectsBounds:(e,t,s)=>s<x&&s<o,intersectsRange:(t,r)=>{for(let o=t,a=t+r;o<a;o++){Ss(p,3*o,c,u),p.a.applyMatrix4(s),p.b.applyMatrix4(s),p.c.applyMatrix4(s),p.needsUpdate=!0;for(let t=e,s=e+i;t<s;t++){Ss(d,3*t,h,l),d.needsUpdate=!0;const e=d.distanceToTriangle(p,m,g);if(e<x&&(f.copy(m),y&&y.copy(g),x=e,b=t,_=o),e<n)return!0}}}})}for(let r=0,o=Ht(t);r<o;r++){Ss(p,3*r,c,u),p.a.applyMatrix4(s),p.b.applyMatrix4(s),p.c.applyMatrix4(s),p.needsUpdate=!0;for(let t=e,s=e+i;t<s;t++){Ss(d,3*t,h,l),d.needsUpdate=!0;const e=d.distanceToTriangle(p,m,g);if(e<x&&(f.copy(m),y&&y.copy(g),x=e,b=t,_=r),e<n)return!0}}}}),os.releasePrimitive(d),os.releasePrimitive(p),x===1/0?null:(i.point?i.point.copy(f):i.point=f.clone(),i.distance=x,i.faceIndex=b,r&&(r.point?r.point.copy(y):r.point=y.clone(),r.point.applyMatrix4(Gs),f.applyMatrix4(Gs),r.distance=f.sub(r.point).length(),r.faceIndex=_),i)}function Zs(e,t=null){t&&Array.isArray(t)&&(t=new Set(t));const s=e.geometry,i=s.index?s.index.array:null,r=s.attributes.position;let n,o,a,l,h=0;const u=e._roots;for(let e=0,t=u.length;e<t;e++)n=u[e],o=new Uint32Array(n),a=new Uint16Array(n),l=new Float32Array(n),c(0,h),h+=n.byteLength;function c(s,n,h=!1){const u=2*s;if(tt(u,a)){const t=st(s,o);let n=1/0,h=1/0,c=1/0,d=-1/0,p=-1/0,m=-1/0;for(let s=t,o=t+it(u,a);s<o;s++){const t=3*e.resolveTriangleIndex(s);for(let e=0;e<3;e++){let s=t+e;s=i?i[s]:s;const o=r.getX(s),a=r.getY(s),l=r.getZ(s);o<n&&(n=o),o>d&&(d=o),a<h&&(h=a),a>p&&(p=a),l<c&&(c=l),l>m&&(m=l)}}return(l[s+0]!==n||l[s+1]!==h||l[s+2]!==c||l[s+3]!==d||l[s+4]!==p||l[s+5]!==m)&&(l[s+0]=n,l[s+1]=h,l[s+2]=c,l[s+3]=d,l[s+4]=p,l[s+5]=m,!0)}{const e=rt(s),i=nt(s,o);let r=h,a=!1,u=!1;if(t){if(!r){const s=e/8+n/We,o=i/8+n/We;a=t.has(s),u=t.has(o),r=!a&&!u}}else a=!0,u=!0;const d=r||u;let p=!1;(r||a)&&(p=c(e,n,r));let m=!1;d&&(m=c(i,n,r));const f=p||m;if(f)for(let t=0;t<3;t++){const r=e+t,n=i+t,o=l[r],a=l[r+3],h=l[n],u=l[n+3];l[s+t]=o<h?o:h,l[s+t+3]=a>u?a:u}return f}}}function Qs(e,t,s,i,r,n,o){At.setBuffer(e._roots[t]),Ks(0,e,s,i,r,n,o),At.clearBuffer()}function Ks(e,t,s,i,r,n,o){const{float32Array:a,uint16Array:l,uint32Array:h}=At,u=2*e;if(tt(u,l)){!function(e,t,s,i,r,n,o,a){const{geometry:l,_indirectBuffer:h}=e;for(let e=i,u=i+r;e<u;e++)Ts(l,t,s,h?h[e]:e,n,o,a)}(t,s,i,st(e,h),it(u,l),r,n,o)}else{const l=rt(e);Ns(l,a,i,n,o)&&Ks(l,t,s,i,r,n,o);const u=nt(e,h);Ns(u,a,i,n,o)&&Ks(u,t,s,i,r,n,o)}}const Js=["x","y","z"];function ei(e,t,s,i,r,n){At.setBuffer(e._roots[t]);const o=ti(0,e,s,i,r,n);return At.clearBuffer(),o}function ti(e,t,s,i,r,n){const{float32Array:o,uint16Array:a,uint32Array:l}=At;let h=2*e;if(tt(h,a)){return function(e,t,s,i,r,n,o){const{geometry:a,_indirectBuffer:l}=e;let h=1/0,u=null;for(let e=i,c=i+r;e<c;e++){let i;i=Ts(a,t,s,l?l[e]:e,null,n,o),i&&i.distance<h&&(u=i,h=i.distance)}return u}(t,s,i,st(e,l),it(h,a),r,n)}{const a=ot(e,l),h=Js[a],u=i.direction[h]>=0;let c,d;u?(c=rt(e),d=nt(e,l)):(c=nt(e,l),d=rt(e));const p=Ns(c,o,i,r,n)?ti(c,t,s,i,r,n):null;if(p){const e=p.point[h];if(u?e<=o[d+a]:e>=o[d+a+3])return p}const m=Ns(d,o,i,r,n)?ti(d,t,s,i,r,n):null;return p&&m?p.distance<=m.distance?p:m:p||m||null}}const si=new i.Box3,ii=new is,ri=new is,ni=new i.Matrix4,oi=new rs,ai=new rs;function li(e,t,s,i){At.setBuffer(e._roots[t]);const r=hi(0,e,s,i);return At.clearBuffer(),r}function hi(e,t,s,i,r=null){const{float32Array:n,uint16Array:o,uint32Array:a}=At;let l=2*e;null===r&&(s.boundingBox||s.computeBoundingBox(),oi.set(s.boundingBox.min,s.boundingBox.max,i),r=oi);if(!tt(l,o)){const o=rt(e),l=nt(e,a);Ye(o,n,si);if(r.intersectsBox(si)&&hi(o,t,s,i,r))return!0;Ye(l,n,si);return!!(r.intersectsBox(si)&&hi(l,t,s,i,r))}{const r=t.geometry,h=r.index,u=r.attributes.position,c=s.index,d=s.attributes.position,p=st(e,a),m=it(l,o);if(ni.copy(i).invert(),s.boundsTree){Ye(e,n,ai),ai.matrix.copy(ni),ai.needsUpdate=!0;return s.boundsTree.shapecast({intersectsBounds:e=>ai.intersectsBox(e),intersectsTriangle:e=>{e.a.applyMatrix4(i),e.b.applyMatrix4(i),e.c.applyMatrix4(i),e.needsUpdate=!0;for(let s=p,i=m+p;s<i;s++)if(Ss(ri,3*t.resolveTriangleIndex(s),h,u),ri.needsUpdate=!0,e.intersectsTriangle(ri))return!0;return!1}})}{const e=Ht(s);for(let s=p,i=m+p;s<i;s++){const i=t.resolveTriangleIndex(s);Ss(ii,3*i,h,u),ii.a.applyMatrix4(ni),ii.b.applyMatrix4(ni),ii.c.applyMatrix4(ni),ii.needsUpdate=!0;for(let t=0,s=3*e;t<s;t+=3)if(Ss(ri,t,c,d),ri.needsUpdate=!0,ii.intersectsTriangle(ri))return!0}}}}const ui=new i.Matrix4,ci=new rs,di=new rs,pi=new i.Vector3,mi=new i.Vector3,fi=new i.Vector3,gi=new i.Vector3;function yi(e,t,s,i={},r={},n=0,o=1/0){t.boundingBox||t.computeBoundingBox(),ci.set(t.boundingBox.min,t.boundingBox.max,s),ci.needsUpdate=!0;const a=e.geometry,l=a.attributes.position,h=a.index,u=t.attributes.position,c=t.index,d=os.getPrimitive(),p=os.getPrimitive();let m=pi,f=mi,g=null,y=null;r&&(g=fi,y=gi);let x=1/0,b=null,_=null;return ui.copy(s).invert(),di.matrix.copy(ui),e.shapecast({boundsTraverseOrder:e=>ci.distanceToBox(e),intersectsBounds:(e,t,s)=>s<x&&s<o&&(t&&(di.min.copy(e.min),di.max.copy(e.max),di.needsUpdate=!0),!0),intersectsRange:(i,r)=>{if(t.boundsTree){const a=t.boundsTree;return a.shapecast({boundsTraverseOrder:e=>di.distanceToBox(e),intersectsBounds:(e,t,s)=>s<x&&s<o,intersectsRange:(t,o)=>{for(let w=t,v=t+o;w<v;w++){const t=a.resolveTriangleIndex(w);Ss(p,3*t,c,u),p.a.applyMatrix4(s),p.b.applyMatrix4(s),p.c.applyMatrix4(s),p.needsUpdate=!0;for(let t=i,s=i+r;t<s;t++){const s=e.resolveTriangleIndex(t);Ss(d,3*s,h,l),d.needsUpdate=!0;const i=d.distanceToTriangle(p,m,g);if(i<x&&(f.copy(m),y&&y.copy(g),x=i,b=t,_=w),i<n)return!0}}}})}for(let o=0,a=Ht(t);o<a;o++){Ss(p,3*o,c,u),p.a.applyMatrix4(s),p.b.applyMatrix4(s),p.c.applyMatrix4(s),p.needsUpdate=!0;for(let t=i,s=i+r;t<s;t++){const s=e.resolveTriangleIndex(t);Ss(d,3*s,h,l),d.needsUpdate=!0;const i=d.distanceToTriangle(p,m,g);if(i<x&&(f.copy(m),y&&y.copy(g),x=i,b=t,_=o),i<n)return!0}}}}),os.releasePrimitive(d),os.releasePrimitive(p),x===1/0?null:(i.point?i.point.copy(f):i.point=f.clone(),i.distance=x,i.faceIndex=b,r&&(r.point?r.point.copy(y):r.point=y.clone(),r.point.applyMatrix4(ui),f.applyMatrix4(ui),r.distance=f.sub(r.point).length(),r.faceIndex=_),i)}function xi(e,t,s){return null===e?null:(e.point.applyMatrix4(t.matrixWorld),e.distance=e.point.distanceTo(s.ray.origin),e.object=t,e)}const bi=new rs,_i=new i.Ray,wi=new i.Vector3,vi=new i.Matrix4,Ti=new i.Vector3,Si=["getX","getY","getZ"];class Mi extends Yt{static serialize(e,t={}){t={cloneBuffers:!0,...t};const s=e.geometry,i=e._roots,r=e._indirectBuffer,n=s.getIndex(),o={version:1,roots:null,index:null,indirectBuffer:null};return t.cloneBuffers?(o.roots=i.map(e=>e.slice()),o.index=n?n.array.slice():null,o.indirectBuffer=r?r.slice():null):(o.roots=i,o.index=n?n.array:null,o.indirectBuffer=r),o}static deserialize(e,t,s={}){s={setIndex:!0,indirect:Boolean(e.indirectBuffer),...s};const{index:r,roots:n,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 s=e[t],i=new Uint32Array(s),r=new Uint16Array(s);for(let e=0,t=s.byteLength/We;e<t;e++){const t=8*e;tt(2*t,r)||(i[t+6]=i[t+6]/8-e)}}}(n));const a=new Mi(t,{...s,[qe]:!0});if(a._roots=n,a._indirectBuffer=o||null,s.setIndex){const s=t.getIndex();if(null===s){const s=new i.BufferAttribute(e.index,1,!1);t.setIndex(s)}else s.array!==r&&(s.array.set(r),s.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,s){const i=this.geometry,r=this._indirectBuffer,n=i.attributes.position,o=i.index?i.index.array:null,a=3*(r?r[e]:e);let l=a+0,h=a+1,u=a+2;o&&(l=o[l],h=o[h],u=o[u]);for(let e=0;e<3;e++){const i=n[Si[e]](l),r=n[Si[e]](h),o=n[Si[e]](u);let a=i;r<a&&(a=r),o<a&&(a=o);let c=i;r>c&&(c=r),o>c&&(c=o),t[s+e]=a,t[s+e+3]=c}return t}computePrimitiveBounds(e,t,s){const i=this.geometry,r=this._indirectBuffer,n=i.attributes.position,o=i.index?i.index.array:null,a=n.normalized;if(e<0||t+e-s.offset>s.length/6)throw new Error("MeshBVH: compute triangle bounds range is invalid.");const l=n.array,h=n.offset||0;let u=3;n.isInterleavedBufferAttribute&&(u=n.data.stride);const c=["getX","getY","getZ"],d=s.offset;for(let i=e,p=e+t;i<p;i++){const e=3*(r?r[i]:i),t=6*(i-d);let p=e+0,m=e+1,f=e+2;o&&(p=o[p],m=o[m],f=o[f]),a||(p=p*u+h,m=m*u+h,f=f*u+h);for(let e=0;e<3;e++){let i,r,o;a?(i=n[c[e]](p),r=n[c[e]](m),o=n[c[e]](f)):(i=l[p+e],r=l[m+e],o=l[f+e]);let h=i;r<h&&(h=r),o<h&&(h=o);let u=i;r>u&&(u=r),o>u&&(u=o);const d=(u-h)/2,g=2*e;s[t+g+0]=h+d,s[t+g+1]=d+(Math.abs(h)+d)*He}}return s}raycastObject3D(e,t,s=[]){const{material:i}=e;if(void 0===i)return;vi.copy(e.matrixWorld).invert(),_i.copy(t.ray).applyMatrix4(vi),Ti.setFromMatrixScale(e.matrixWorld),wi.copy(_i.direction).multiply(Ti);const r=wi.length(),n=t.near/r,o=t.far/r;if(!0===t.firstHitOnly){let r=this.raycastFirst(_i,i,n,o);r=xi(r,e,t),r&&s.push(r)}else{const r=this.raycast(_i,i,n,o);for(let i=0,n=r.length;i<n;i++){const n=xi(r[i],e,t);n&&s.push(n)}}return s}refit(e=null){return(this.indirect?Zs:As)(this,e)}raycast(e,t=i.FrontSide,s=0,r=1/0){const n=this._roots,o=[],a=this.indirect?Qs:Cs;for(let i=0,l=n.length;i<l;i++)a(this,i,t,e,o,s,r);return o}raycastFirst(e,t=i.FrontSide,s=0,r=1/0){const n=this._roots;let o=null;const a=this.indirect?ei:Bs;for(let i=0,l=n.length;i<l;i++){const n=a(this,i,t,e,s,r);null!=n&&(null==o||n.distance<o.distance)&&(o=n)}return o}intersectsGeometry(e,t){let s=!1;const i=this._roots,r=this.indirect?li:ks;for(let n=0,o=i.length;n<o&&(s=r(this,n,e,t),!s);n++);return s}shapecast(e){const t=os.getPrimitive(),s=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?Es:Ms});return os.releasePrimitive(t),s}bvhcast(e,t,s){let{intersectsRanges:i,intersectsTriangles:r}=s;const n=os.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?e=>{const t=this.resolveTriangleIndex(e);Ss(n,3*t,o,a)}:e=>{Ss(n,3*e,o,a)},h=os.getPrimitive(),u=e.geometry.index,c=e.geometry.attributes.position,d=e.indirect?t=>{const s=e.resolveTriangleIndex(t);Ss(h,3*s,u,c)}:e=>{Ss(h,3*e,u,c)};if(r){if(!(e instanceof Mi))throw new Error('MeshBVH: "intersectsTriangles" callback can only be used with another MeshBVH.');const s=(e,s,i,o,a,u,c,p)=>{for(let m=i,f=i+o;m<f;m++){d(m),h.a.applyMatrix4(t),h.b.applyMatrix4(t),h.c.applyMatrix4(t),h.needsUpdate=!0;for(let t=e,i=e+s;t<i;t++)if(l(t),n.needsUpdate=!0,r(n,h,t,m,a,u,c,p))return!0}return!1};if(i){const e=i;i=function(t,i,r,n,o,a,l,h){return!!e(t,i,r,n,o,a,l,h)||s(t,i,r,n,o,a,l,h)}}else i=s}return super.bvhcast(e,t,{intersectsRanges:i})}intersectsBox(e,t){return bi.set(e.min,e.max,t),bi.needsUpdate=!0,this.shapecast({intersectsBounds:e=>bi.intersectsBox(e),intersectsTriangle:e=>bi.intersectsTriangle(e)})}intersectsSphere(e){return this.shapecast({intersectsBounds:t=>e.intersectsBox(t),intersectsTriangle:t=>t.intersectsSphere(e)})}closestPointToGeometry(e,t,s={},i={},r=0,n=1/0){return(this.indirect?yi:Ys)(this,e,t,s,i,r,n)}closestPointToPoint(e,t={},s=0,i=1/0){return function(e,t,s={},i=0,r=1/0){const n=i*i,o=r*r;let a=1/0,l=null;if(e.shapecast({boundsTraverseOrder:e=>(as.copy(t).clamp(e.min,e.max),as.distanceToSquared(t)),intersectsBounds:(e,t,s)=>s<a&&s<o,intersectsTriangle:(e,s)=>{e.closestPointToPoint(t,as);const i=t.distanceToSquared(as);return i<a&&(ls.copy(as),a=i,l=s),i<n}}),a===1/0)return null;const h=Math.sqrt(a);return s.point?s.point.copy(ls):s.point=ls.clone(),s.distance=h,s.faceIndex=l,s}(this,e,t,s,i)}}const Ai=new i.Matrix4,Ni=new i.Ray,Ei=new St(()=>new i.Line3),Ci=new i.Vector3,Ri=new i.Vector3,Pi=new i.Box3,Bi=["getX","getY","getZ"];class Ii extends Yt{get primitiveStride(){return 2}writePrimitiveBounds(e,t,s){const i=this._indirectBuffer,{geometry:r,primitiveStride:n}=this,o=r.attributes.position,a=r.index,l=a?a.count:o.count;let h=(i?i[e]:e)*n,u=(h+1)%l;a&&(h=a.getX(h),u=a.getX(u));for(let e=0;e<3;e++){const i=o[Bi[e]](h),r=o[Bi[e]](u),n=i<r?i:r,a=i>r?i:r;t[s+e]=n,t[s+e+3]=a}return t}shapecast(e){const t=Ei.getPrimitive(),s=super.shapecast({...e,intersectsPrimitive:e.intersectsLine,scratchPrimitive:t,iterate:Di});return Ei.releasePrimitive(t),s}raycastObject3D(e,t,s=[]){const{matrixWorld:i}=e,{firstHitOnly:r}=t;Ai.copy(i).invert(),Ni.copy(t.ray).applyMatrix4(Ai);const n=t.params.Line.threshold/((e.scale.x+e.scale.y+e.scale.z)/3),o=n*n;let a=null,l=1/0;return this.shapecast({boundsTraverseOrder:e=>e.distanceToPoint(Ni.origin),intersectsBounds:e=>(Pi.copy(e).expandByScalar(Math.abs(n)),Ni.intersectsBox(Pi)?1:0),intersectsLine:(n,h)=>{if(Ni.distanceSqToSegment(n.start,n.end,Ci,Ri)>o)return;Ci.applyMatrix4(e.matrixWorld);const u=t.ray.origin.distanceTo(Ci);u<t.near||u>t.far||r&&u>=l||(l=u,h=this.resolvePrimitiveIndex(h),a={distance:u,point:Ri.clone().applyMatrix4(i),index:h*this.primitiveStride,face:null,faceIndex:null,barycoord:null,object:e},r||s.push(a))}}),r&&a&&s.push(a),s}}function Di(e,t,s,i,r,n,o){const{geometry:a,primitiveStride:l}=s,{index:h}=a,u=a.attributes.position,c=h?h.count:u.count;for(let a=e,d=t+e;a<d;a++){let e=s.resolvePrimitiveIndex(a)*l,t=(e+1)%c;if(h&&(e=h.getX(e),t=h.getX(t)),o.start.fromBufferAttribute(u,e),o.end.fromBufferAttribute(u,t),i(o,a,r,n))return!0}return!1}const Li={Mesh:i.Mesh.prototype.raycast,Line:i.Line.prototype.raycast,LineSegments:i.LineSegments.prototype.raycast,LineLoop:i.LineLoop.prototype.raycast,Points:i.Points.prototype.raycast,BatchedMesh:i.BatchedMesh.prototype.raycast},Fi=new i.Mesh,Oi=[];function Vi(e,t){if(this.isBatchedMesh)zi.call(this,e,t);else{const{geometry:s}=this;if(s.boundsTree)s.boundsTree.raycastObject3D(this,e,t);else{let s;if(this instanceof i.Mesh)s=Li.Mesh;else if(this instanceof i.LineSegments)s=Li.LineSegments;else if(this instanceof i.LineLoop)s=Li.LineLoop;else if(this instanceof i.Line)s=Li.Line;else{if(!(this instanceof i.Points))throw new Error("BVH: Fallback raycast function not found.");s=Li.Points}s.call(this,e,t)}}}function zi(e,t){if(this.boundsTrees){const s=this.boundsTrees,r=this._drawInfo||this._instanceInfo,n=this._drawRanges||this._geometryInfo,o=this.matrixWorld;Fi.material=this.material,Fi.geometry=this.geometry;const a=Fi.geometry.boundsTree,l=Fi.geometry.drawRange;null===Fi.geometry.boundingSphere&&(Fi.geometry.boundingSphere=new i.Sphere);for(let i=0,a=r.length;i<a;i++){if(!this.getVisibleAt(i))continue;const a=r[i].geometryIndex;if(Fi.geometry.boundsTree=s[a],this.getMatrixAt(i,Fi.matrixWorld).premultiply(o),!Fi.geometry.boundsTree){this.getBoundingBoxAt(a,Fi.geometry.boundingBox),this.getBoundingSphereAt(a,Fi.geometry.boundingSphere);const e=n[a];Fi.geometry.setDrawRange(e.start,e.count)}Fi.raycast(e,Oi);for(let e=0,s=Oi.length;e<s;e++){const s=Oi[e];s.object=this,s.batchId=i,t.push(s)}Oi.length=0}Fi.geometry.boundsTree=a,Fi.geometry.drawRange=l,Fi.material=null,Fi.geometry=null}else Li.BatchedMesh.call(this,e,t)}function ki(e={}){const{type:t=Mi}=e;return this.boundsTree=new t(this,e),this.boundsTree}function Ui(){this.boundsTree=null}const Gi=class e extends d{constructor(s){super(s),t(this,"onDisposed",new u),t(this,"onBeforeDispose",new u),t(this,"onFragmentsLoaded",new u),t(this,"baseCoordinationModel",""),t(this,"baseCoordinationMatrix",new l.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 s.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 l.Matrix4)})}async raycast(e){const t=[];for(const s of this.core.models.list.values())if(e.snappingClasses&&e.snappingClasses.length>0){const i=await s.raycastWithSnapping(e);if(i&&i.length>0)t.push(i[0]);else{const i=await s.raycast(e);i&&t.push(i)}}else{const i=await s.raycast(e);i&&t.push(i)}if(await Promise.all(t),0===t.length)return;let s=t[0],i=s.distance;for(let e=1;e<t.length;e++)t[e].distance<i&&(i=t[e].distance,s=t[e]);return s}async getPositions(e){const t=[],s=async(e,s)=>{const i=await e.getPositions(s);for(const e of i)t.push(e)},i=[];for(const t in e){const r=this.core.models.list.get(t);r&&i.push(s(r,Array.from(e[t])))}return await Promise.all(i),t}async getBBoxes(e){const t=[],s=async(e,s)=>{const i=await e.getBoxes(s);if(i)for(const e of i)t.push(e)},i=[];for(const t in e){const r=this.core.models.list.get(t);r&&i.push(s(r,Array.from(e[t])))}return await Promise.all(i),t}async highlight(e,t){await this.forEachModel(t,"highlight",e)}async getData(e,t){const s={};for(const[i,r]of Object.entries(e)){const e=this.list.get(i);if(!e)continue;if(0===r.size){s[i]=[];continue}const n=await e.getItemsData([...r],t);s[i]=n}return s}async resetHighlight(e){await this.forEachModel(e,"resetHighlight")}async forEachModel(e,t,...s){const i={};if(e)for(const t in e){const s=e[t];i[t]=Array.from(s)}else for(const e of this.core.models.list.keys())i[e]=void 0;const r=[];for(const e in i){const n=this.core.models.list.get(e);if(n){const o=i[e],a=n[t](o,...s);r.push(a)}}await Promise.all(r)}async guidsToModelIdMap(e){const t={};for(const[s,i]of this.list){const r=(await i.getLocalIdsByGuids([...e])).filter(e=>null!==e);t[s]=new Set(r)}return t}async modelIdMapToGuids(e){const t=[];for(const[s,i]of Object.entries(e)){const e=this.list.get(s);if(!e)continue;const r=(await e.getGuidsByLocalIds([...i])).filter(e=>null!==e);t.push(...r)}return t}applyBaseCoordinateSystem(e,t){const s=new l.Matrix4;return t&&s.copy(t.clone()).invert(),s.multiply(this.baseCoordinationMatrix),e.applyMatrix4(s),s}};t(Gi,"uuid","fef46874-46a3-461b-8c44-2922ab77c806");let ji=Gi;function $i(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16}class Wi{constructor(e,t={}){const{pixelsPerMeter:s=.1}=t;this.pixelsPerMeter=s,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:s}=this,r=new i.Vector3,n=new i.OrthographicCamera,o=new i.Box3,a=new i.WebGLRenderTarget(1,1);o.makeEmpty(),e.forEach(e=>{o.expandByObject(e)}),o.getSize(r);const l=Math.min(t.capabilities.maxTextureSize,8192),h=Math.ceil(r.x/s),u=Math.ceil(r.z/s),c=Math.ceil(h/l),d=Math.ceil(u/l);a.setSize(Math.ceil(h/c),Math.ceil(u/d)),n.rotation.x=-Math.PI/2,n.far=o.max.y-o.min.y+n.near,n.position.y=o.max.y+n.near;const p=new i.Scene,m=new Map,f=new Map,g=[];for(let t=0;t<e.length;t++){const s=e[t];m.set(s,s.material),f.set(s,s.parent);const i=new Hi;i.objectId=t,g.push(i),s.material=i,p.add(s)}const y=t.getClearColor(new i.Color),x=t.getClearAlpha(),b=t.getRenderTarget(),_=t.autoClear;t.autoClear=!0,t.setClearColor(0,0),t.setRenderTarget(a);const w=new Uint8Array(a.width*a.height*4),v=new Set,T=r.x/c,S=r.z/d;for(let s=0;s<c;s++)for(let i=0;i<d;i++){const r=o.min.x+T*s,l=r+T,h=o.min.z+S*i,u=(r+l)/2,c=(h+(h+S))/2;n.position.set(u,o.max.y,c);const d=T/2,m=S/2;n.left=-d,n.right=d,n.top=m,n.bottom=-m,n.updateProjectionMatrix(),t.render(p,n);const f=await t.readRenderTargetPixelsAsync(a,0,0,a.width,a.height,w);for(let t=0,s=f.length;t<s;t+=4){if(0===f[t+3])continue;const s=$i(f,t);v.add(e[s])}}for(const t of e){t.material=m.get(t);const e=f.get(t);e?e.add(t):p.remove(t)}t.setClearColor(y,x),t.setRenderTarget(b),t.autoClear=_;for(const e of g)e.dispose();return a.dispose(),Array.from(v)}}class Hi extends i.ShaderMaterial{get objectId(){return this._objectId}set objectId(e){var t,s;this._objectId=e,t=e,(s=this.uniforms.objectId.value).x=(255&t)/255,s.y=(t>>8&255)/255,s.z=(t>>16&255)/255,s.w=1}constructor(e){super({glslVersion:i.GLSL3,blending:i.NoBlending,uniforms:{objectId:{value:new i.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 qi=1e-16,Xi=new i.Vector3(0,1,0),Yi=new i.Vector3;function Zi(e){return e.delta(Yi).normalize(),Math.abs(Yi.dot(Xi))>=1-qi}function Qi(e,t){const{start:s,end:i}=t,r=e.points;let n=!1,o=!1;for(let e=0;e<3;e++){const t=r[e];if(!n&&s.distanceToSquared(t)<=qi&&(n=!0),!o&&i.distanceToSquared(t)<=qi&&(o=!0),n&&o)return!0}return n&&o}const Ki=new i.Line3;function Ji(e,t,s=!1,i=[]){let r=[[0,1]];for(let e=0,s=t.length;e<s;e++){const s=r[e],i=t[e];s[1]=i[0],r.push([i[1],1])}s&&([t,r]=[r,t]);for(let t=0,s=r.length;t<s;t++){const{start:s,end:n}=e;Ki.start.lerpVectors(s,n,r[t][0]),Ki.end.lerpVectors(s,n,r[t][1]),i.push(new Float32Array([Ki.start.x,Ki.start.y,Ki.start.z,Ki.end.x,Ki.end.y,Ki.end.z]))}return i}const er=new i.Vector3(0,1,0),tr=new i.Vector3,sr=new i.Vector3,ir=new i.Vector3,rr=new i.Triangle;function*nr(e,t=[],s={}){const{projectionDirection:r=er,thresholdAngle:n=1,iterationTime:o=30}=s,a=Math.pow(10,4),l=Math.cos(i.MathUtils.DEG2RAD*n),h=e.getIndex(),u=e.getAttribute("position"),c=h?h.count:u.count,d=[0,0,0],p=["a","b","c"],m=new Array(3),f={};let g=performance.now();for(let e=0;e<c;e+=3){performance.now()-g>o&&(yield,g=performance.now()),h?(d[0]=h.getX(e),d[1]=h.getX(e+1),d[2]=h.getX(e+2)):(d[0]=e,d[1]=e+1,d[2]=e+2);const{a:s,b:n,c:c}=rr;if(s.fromBufferAttribute(u,d[0]),n.fromBufferAttribute(u,d[1]),c.fromBufferAttribute(u,d[2]),rr.getNormal(ir),m[0]=`${Math.round(s.x*a)},${Math.round(s.y*a)},${Math.round(s.z*a)}`,m[1]=`${Math.round(n.x*a)},${Math.round(n.y*a)},${Math.round(n.z*a)}`,m[2]=`${Math.round(c.x*a)},${Math.round(c.y*a)},${Math.round(c.z*a)}`,m[0]!==m[1]&&m[1]!==m[2]&&m[2]!==m[0])for(let e=0;e<3;e++){const s=(e+1)%3,n=m[e],o=m[s],a=rr[p[e]],h=rr[p[s]],u=`${n}_${o}`,c=`${o}_${n}`;if(c in f&&f[c]){const e=f[c].normal,s=ir.dot(e)<=l;let n=!1;if(null!==r){let t=r.dot(ir);t=Math.abs(t)<1e-10?0:t;let s=r.dot(e);s=Math.abs(s)<1e-10?0:s,n=Math.sign(t)!==Math.sign(s)}if(s||n){const e=new i.Line3;e.start.copy(a),e.end.copy(h),t.push(e)}f[c]=null}else u in f||(f[u]={index0:d[e],index1:d[s],normal:ir.clone()})}}for(const e in f)if(f[e]){const{index0:s,index1:r}=f[e];tr.fromBufferAttribute(u,s),sr.fromBufferAttribute(u,r);const n=new i.Line3;n.start.copy(tr),n.end.copy(sr),t.push(n)}return t}const or=new i.Line3;function ar(e,t,s,i=[]){return e.bvhcast(t,s,{intersectsTriangles:(e,t)=>!function(e,t){const s=["a","b","c"];let i=0;for(let r=0;r<3;r++)for(let n=0;n<3;n++){lr(e[s[r]],t[s[n]])&&i++}return i>=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,or,!0)||Qi(e,or)||Qi(t,or)||i.push(or.clone())))}),i}function lr(e,t){return e.distanceTo(t)<1e-10}function hr(e){ur(e);let t=[];return e.traverse(e=>{e.geometry&&e.visible&&t.push(e)}),t}const ur=e=>{if(void 0===e)return;const t=[...e.children];for(const s of t)void 0===s?e.children.splice(e.children.indexOf(s),1):ur(s)},cr=new i.Matrix4,dr=new i.Matrix4;class pr{constructor(){this.projectionDirection=new i.Vector3(0,1,0),this.thresholdAngle=50,this.iterationTime=30}getEdges(...e){const t=this.iterationTime;this.iterationTime=1/0;const s=this.getEdgesGenerator(...e).next().value;return this.iterationTime=t,s}*getEdgesGenerator(e,t=[],s=null){const{projectionDirection:r,thresholdAngle:n,iterationTime:o}=this;if(e.isObject3D){const a=hr(e);let l=null;r&&(l=new i.Vector3);let h=performance.now();for(let e=0;e<a.length;e++){h-performance.now()>o&&(yield);const i=a[e];l&&(dr.copy(i.matrixWorld).invert(),l.copy(r).transformDirection(dr).normalize());const u=yield*nr(i.geometry,[],{projectionDirection:l,thresholdAngle:n,iterationTime:o});mr(u,i.matrixWorld);for(let e=0;e<u.length;e++)t.push(u[e]);if(null!==s)for(let e=0;e<u.length;e++)s.push(i)}return t}return yield*nr(e,t,{projectionDirection:r,thresholdAngle:n,iterationTime:o})}getIntersectionEdges(...e){const t=this.iterationTime;this.iterationTime=1/0;const s=this.getIntersectionEdgesGenerator(...e).next().value;return this.iterationTime=t,s}*getIntersectionEdgesGenerator(e,t=[],s=null){const{iterationTime:i}=this;if(e.isObject3D){const r=hr(e),n=new Map;let o=performance.now();for(let e=0;e<r.length;e++){performance.now()-o>i&&(yield,o=performance.now());const t=r[e].geometry;if(!n.has(t)){const e=t.boundsTree||new Mi(t,{maxLeafSize:1});n.set(t,e)}}o=performance.now();for(let e=0;e<r.length;e++)for(let a=e;a<r.length;a++){performance.now()-o>i&&(yield,o=performance.now());const l=r[e],h=r[a],u=n.get(l.geometry),c=n.get(h.geometry);cr.copy(l.matrixWorld).invert().multiply(h.matrixWorld);const d=ar(u,c,cr,[]);mr(d,l.matrixWorld);for(let e=0;e<d.length;e++)t.push(d[e]);if(null!==s)for(let e=0;e<d.length;e++)s.push(l)}return t}{let s;return e.isBufferGeometry?s=e.boundsTree||new Mi(e,{maxLeafSize:1}):(s=e,e=s.geometry),cr.identity(),ar(s,s,cr,t)}}}function mr(e,t,s=1e-6){for(let i=0;i<e.length;i++){const r=e[i];r.applyMatrix4(t),r.start.y+=s,r.end.y+=s}}class fr extends $t{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,s){const{primitiveBuffer:i,heightOffset:r}=this,{start:n,end:o}=i[e];t[s+0]=Math.min(n.x,o.x),t[s+1]=Math.min(n.y,o.y),t[s+2]=Math.min(n.z,o.z),t[s+3]=Math.max(n.x,o.x),t[s+4]=Math.max(n.y,o.y)+r,t[s+5]=Math.max(n.z,o.z)}getRootRanges(){return[{offset:0,count:this.primitiveBuffer.length}]}}const gr=new i.Vector3(0,1,0),yr=new i.Plane,xr=new i.Vector3,br=new i.Vector3;function _r(e,t,s){e.needsUpdate&&e.update(),yr.copy(e.plane),yr.normal.dot(gr)<0&&(yr.normal.multiplyScalar(-1),yr.constant*=-1);const r=yr.distanceToPoint(t.start),n=yr.distanceToPoint(t.end),o=Math.abs(r)<1e-16,a=r<0,l=n<0;if(t.delta(br).normalize(),Math.abs(yr.normal.dot(br))<1e-16)return!(o||!a)&&(s.copy(t),!0);if(a&&l)return s.copy(t),!0;if(!a&&!l)return!1;{const e=i.MathUtils.mapLinear(0,r,n,0,1);if(t.at(e,xr),a)return s.start.copy(t.start),s.end.copy(xr),!0;if(l)return s.end.copy(t.end),s.start.copy(xr),!0}return!1}const wr=new i.Plane,vr=new i.Vector3,Tr=new i.Vector3,Sr=new is,Mr=new i.Line3,Ar=new i.Line3,Nr=new i.Vector3,Er=new i.Vector3,Cr=new i.Vector3;function Rr(e,t,s=new i.Line3){if(Sr.copy(t),Sr.a.y=0,Sr.b.y=0,Sr.c.y=0,Sr.update(),Mr.copy(e),Mr.start.y=0,Mr.end.y=0,Sr.getArea()<=1e-16)return null;const r=Mr.distance();Mr.delta(Nr).divideScalar(r),Er.copy(Nr).cross(Sr.plane.normal).normalize(),wr.setFromNormalAndCoplanarPoint(Er,Mr.start);let n=0;const{points:o}=Sr;for(let e=0;e<3;e++){const t=o[e],s=o[(e+1)%3],i=wr.distanceToPoint(t),r=wr.distanceToPoint(s),a=Math.abs(i)<1e-16,l=Math.abs(r)<1e-16;let h=!1;if(!a&&!l&&i*r<0){const e=i/(i-r);vr.lerpVectors(t,s,e),h=!0}if((h&&!l||a)&&(a&&!h&&vr.copy(t),0===n?Ar.start.copy(vr):Ar.end.copy(vr),n++,2===n))break}if(2===n){if(Ar.delta(Cr).normalize(),Nr.dot(Cr)<0){const e=Ar.start;Ar.start=Ar.end,Ar.end=e}const t=0,i=Tr.subVectors(Mr.end,Mr.start).dot(Nr),n=Tr.subVectors(Ar.start,Mr.start).dot(Nr),o=Tr.subVectors(Ar.end,Mr.start).dot(Nr);return i<=n||o<=t?null:(e.at(Math.max(t,n)/r,s.start),e.at(Math.min(i,o)/r,s.end),s)}return null}const Pr=new i.Vector3,Br=new i.Vector3,Ir=new i.Vector3;function Dr(e,t,s){const i=function(e,t){e.delta(Pr),Br.subVectors(t.start,e.start),Ir.subVectors(t.end,e.start);const s=Pr.length();let i=Br.length()/s,r=Ir.length()/s;if(i=Math.min(Math.max(i,0),1),r=Math.min(Math.max(r,0),1),Math.abs(i-r)<=1e-16)return null;return[i,r]}(e,t);return!!i&&(Lr(i,s),!0)}function Lr(e,t){let[s,i]=e,r=0,n=t.length;for(;r<n;){const e=r+n>>>1;t[e][0]<=s?r=e+1:n=e}let o=Math.max(0,r-1),a=0;for(let e=o,r=t.length;e<r;e++){const[r,n]=t[e];if(s<=n&&i>=r)s=Math.min(r,s),i=Math.max(n,i),a++;else{if(!(s>=r))break;o=e+1}}t.splice(o,a,[s,i])}const Fr=new i.Vector3(0,1,0),Or=new i.Line3,Vr=new i.Line3,zr=new is;function kr(e,t,s,r,n=null){const{geometry:o,matrixWorld:a,material:l}=s,h=l.side,u=a.determinant()<0,c=e.lines;e.bvhcast(t,a,{intersectsRanges:(e,t,s,l)=>{n&&(n.candidates+=t*l);for(let d=s,p=l+s;d<p;d++){let s=3*d+0,l=3*d+1,p=3*d+2;o.index&&(s=o.index.getX(s),l=o.index.getX(l),p=o.index.getX(p));const{a:m,b:f,c:g}=zr;if(m.fromBufferAttribute(o.attributes.position,s).applyMatrix4(a),f.fromBufferAttribute(o.attributes.position,l).applyMatrix4(a),g.fromBufferAttribute(o.attributes.position,p).applyMatrix4(a),zr.needsUpdate=!0,zr.update(),h!==i.DoubleSide){if(zr.plane.normal.dot(Fr)!==u===(h===i.BackSide)){n&&(n.backFaceCulled+=t);continue}}const y=Math.max(m.y,f.y,g.y),x=Math.min(m.y,f.y,g.y),b=zr.plane.normal;let _=b.x,w=b.y,v=b.z,T=zr.plane.constant;w<0&&(_=-_,w=-w,v=-v,T=-T);for(let s=e,i=t+e;s<i;s++){const e=c[s],t=Math.min(e.start.y,e.end.y),i=Math.max(e.start.y,e.end.y);if(y<=t){n&&n.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),s=o*t,i=a*t,r=-i,h=s,u=m.x-e.start.x,c=m.z-e.start.z,d=f.x-e.start.x,p=f.z-e.start.z,y=g.x-e.start.x,x=g.z-e.start.z,b=u*s+c*i,_=d*s+p*i,w=y*s+x*i,v=1/t,T=Math.min(b,_,w);if(Math.max(b,_,w)<0||T>v){n&&n.xzBoundsCulled++;continue}const S=u*r+c*h,M=d*r+p*h,A=y*r+x*h,N=Math.min(S,M,A),E=Math.max(S,M,A);if(N>0||E<0){n&&n.xzBoundsCulled++;continue}}const h=_*e.start.x+w*e.start.y+v*e.start.z+T,u=_*e.end.x+w*e.end.y+v*e.end.z+T;if(h>=0&&u>=0)n&&n.planeTrimCulled++;else if(Qi(zr,e))n&&n.triangleEdgeCulled++;else{if(i<x)Or.copy(e);else if(!_r(zr,e,Or)){n&&n.planeTrimCulled++;continue}Or.distance()<1e-10?n&&n.distThresholdCulled++:Rr(Or,zr,Vr)?(n&&n.used++,Dr(e,Vr,r[s])):n&&n.noOverlapCulled++}}}}})}zr.update=()=>{zr.plane.setFromCoplanarPoints(...zr.points)};let Ur=!1;const Gr={},jr={};let $r=null,Wr=0,Hr=0;const qr={get enabled(){return Ur},set enabled(e){Ur=e},reset(){for(const e in Gr)delete Gr[e];for(const e in jr)delete jr[e];$r=null,Wr=0,Hr=0},setStat(e,t){jr[e]=t},startTotal(){Ur&&(Hr=performance.now())},startStep(e){Ur&&(null!==$r&&this.endStep(),$r=e,Wr=performance.now())},endStep(){if(!Ur||null===$r)return;const e=performance.now()-Wr;Gr[$r]=e,$r=null},printSummary(){if(!Ur)return;null!==$r&&this.endStep();const e=performance.now()-Hr;console.log("\n=== Projection Summary ==="),console.log(`Total time: ${e.toFixed(1)}ms\n`);for(const[t,s]of Object.entries(Gr)){const i=(s/e*100).toFixed(1);console.log(` ${t}: ${s.toFixed(1)}ms (${i}%)`)}if(Object.keys(jr).length>0){console.log("\n--- Stats ---");for(const[e,t]of Object.entries(jr))console.log(` ${e}: ${t}`)}console.log("")}},Xr="182",Yr=100,Zr=101,Qr=102,Kr=200,Jr=201,en=202,tn=203,sn=204,rn=205,nn=206,on=207,an=208,ln=209,hn=210,un=301,cn=302,dn=1e3,pn=1001,mn=1002,fn=1003,gn=1004,yn=1005,xn=1006,bn=1007,_n=1008,wn=1009,vn=1010,Tn=1011,Sn=1012,Mn=1013,An=1014,Nn=1015,En=1016,Cn=1017,Rn=1018,Pn=1020,Bn=35902,In=35899,Dn=1022,Ln=1023,Fn=1026,On=1027,Vn=1028,zn=1029,kn=1030,Un=1031,Gn=1033,jn=33776,$n=33777,Wn=33778,Hn=33779,qn=35840,Xn=35841,Yn=35842,Zn=35843,Qn=36196,Kn=37492,Jn=37496,eo=37488,to=37489,so=37490,io=37491,ro=37808,no=37809,oo=37810,ao=37811,lo=37812,ho=37813,uo=37814,co=37815,po=37816,mo=37817,fo=37818,go=37819,yo=37820,xo=37821,bo=36492,_o=36283,wo=36284,vo=36285,To=36286,So="",Mo="srgb",Ao="srgb-linear",No="linear",Eo="srgb",Co=7680,Ro=512,Po=513,Bo=514,Io=515,Do=516,Lo=517,Fo=518,Oo=519,Vo=35044,zo=35048,ko=2e3,Uo=2001,Go="compute",jo="render";
2
- /**
3
- * @license
4
- * Copyright 2010-2025 Three.js Authors
5
- * SPDX-License-Identifier: MIT
6
- */function $o(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function Wo(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function Ho(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}const qo={};function Xo(...e){const t="THREE."+e.shift();console.log(t,...e)}function Yo(...e){const t="THREE."+e.shift();console.warn(t,...e)}function Zo(...e){const t="THREE."+e.shift();console.error(t,...e)}function Qo(...e){const t=e.join(" ");t in qo||(qo[t]=!0,Yo(...e))}class Ko{addEventListener(e,t){void 0===this._listeners&&(this._listeners={});const s=this._listeners;void 0===s[e]&&(s[e]=[]),-1===s[e].indexOf(t)&&s[e].push(t)}hasEventListener(e,t){const s=this._listeners;return void 0!==s&&(void 0!==s[e]&&-1!==s[e].indexOf(t))}removeEventListener(e,t){const s=this._listeners;if(void 0===s)return;const i=s[e];if(void 0!==i){const e=i.indexOf(t);-1!==e&&i.splice(e,1)}}dispatchEvent(e){const t=this._listeners;if(void 0===t)return;const s=t[e.type];if(void 0!==s){e.target=this;const t=s.slice(0);for(let s=0,i=t.length;s<i;s++)t[s].call(this,e);e.target=null}}}const Jo=["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 ea=1234567;const ta=Math.PI/180,sa=180/Math.PI;function ia(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(Jo[255&e]+Jo[e>>8&255]+Jo[e>>16&255]+Jo[e>>24&255]+"-"+Jo[255&t]+Jo[t>>8&255]+"-"+Jo[t>>16&15|64]+Jo[t>>24&255]+"-"+Jo[63&s|128]+Jo[s>>8&255]+"-"+Jo[s>>16&255]+Jo[s>>24&255]+Jo[255&i]+Jo[i>>8&255]+Jo[i>>16&255]+Jo[i>>24&255]).toLowerCase()}function ra(e,t,s){return Math.max(t,Math.min(s,e))}function na(e,t){return(e%t+t)%t}function oa(e,t,s){return(1-s)*e+s*t}function aa(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return e/4294967295;case Uint16Array:return e/65535;case Uint8Array:return e/255;case Int32Array:return Math.max(e/2147483647,-1);case Int16Array:return Math.max(e/32767,-1);case Int8Array:return Math.max(e/127,-1);default:throw new Error("Invalid component type.")}}function la(e,t){switch(t.constructor){case Float32Array:return e;case Uint32Array:return Math.round(4294967295*e);case Uint16Array:return Math.round(65535*e);case Uint8Array:return Math.round(255*e);case Int32Array:return Math.round(2147483647*e);case Int16Array:return Math.round(32767*e);case Int8Array:return Math.round(127*e);default:throw new Error("Invalid component type.")}}const ha={DEG2RAD:ta,RAD2DEG:sa,generateUUID:ia,clamp:ra,euclideanModulo:na,mapLinear:function(e,t,s,i,r){return i+(e-t)*(r-i)/(s-t)},inverseLerp:function(e,t,s){return e!==t?(s-e)/(t-e):0},lerp:oa,damp:function(e,t,s,i){return oa(e,t,1-Math.exp(-s*i))},pingpong:function(e,t=1){return t-Math.abs(na(e,2*t)-t)},smoothstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*(3-2*e)},smootherstep:function(e,t,s){return e<=t?0:e>=s?1:(e=(e-t)/(s-t))*e*e*(e*(6*e-15)+10)},randInt:function(e,t){return e+Math.floor(Math.random()*(t-e+1))},randFloat:function(e,t){return e+Math.random()*(t-e)},randFloatSpread:function(e){return e*(.5-Math.random())},seededRandom:function(e){void 0!==e&&(ea=e);let t=ea+=1831565813;return t=Math.imul(t^t>>>15,1|t),t^=t+Math.imul(t^t>>>7,61|t),((t^t>>>14)>>>0)/4294967296},degToRad:function(e){return e*ta},radToDeg:function(e){return e*sa},isPowerOfTwo:function(e){return!(e&e-1)&&0!==e},ceilPowerOfTwo:function(e){return Math.pow(2,Math.ceil(Math.log(e)/Math.LN2))},floorPowerOfTwo:function(e){return Math.pow(2,Math.floor(Math.log(e)/Math.LN2))},setQuaternionFromProperEuler:function(e,t,s,i,r){const n=Math.cos,o=Math.sin,a=n(s/2),l=o(s/2),h=n((t+i)/2),u=o((t+i)/2),c=n((t-i)/2),d=o((t-i)/2),p=n((i-t)/2),m=o((i-t)/2);switch(r){case"XYX":e.set(a*u,l*c,l*d,a*h);break;case"YZY":e.set(l*d,a*u,l*c,a*h);break;case"ZXZ":e.set(l*c,l*d,a*u,a*h);break;case"XZX":e.set(a*u,l*m,l*p,a*h);break;case"YXY":e.set(l*p,a*u,l*m,a*h);break;case"ZYZ":e.set(l*m,l*p,a*u,a*h);break;default:Yo("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:la,denormalize:aa};class ua{constructor(e=0,t=0){ua.prototype.isVector2=!0,this.x=e,this.y=t}get width(){return this.x}set width(e){this.x=e}get height(){return this.y}set height(e){this.y=e}set(e,t){return this.x=e,this.y=t,this}setScalar(e){return this.x=e,this.y=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y)}copy(e){return this.x=e.x,this.y=e.y,this}add(e){return this.x+=e.x,this.y+=e.y,this}addScalar(e){return this.x+=e,this.y+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this}subScalar(e){return this.x-=e,this.y-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this}multiply(e){return this.x*=e.x,this.y*=e.y,this}multiplyScalar(e){return this.x*=e,this.y*=e,this}divide(e){return this.x/=e.x,this.y/=e.y,this}divideScalar(e){return this.multiplyScalar(1/e)}applyMatrix3(e){const t=this.x,s=this.y,i=e.elements;return this.x=i[0]*t+i[3]*s+i[6],this.y=i[1]*t+i[4]*s+i[7],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this}clamp(e,t){return this.x=ra(this.x,e.x,t.x),this.y=ra(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=ra(this.x,e,t),this.y=ra(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(ra(s,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this}negate(){return this.x=-this.x,this.y=-this.y,this}dot(e){return this.x*e.x+this.y*e.y}cross(e){return this.x*e.y-this.y*e.x}lengthSq(){return this.x*this.x+this.y*this.y}length(){return Math.sqrt(this.x*this.x+this.y*this.y)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)}normalize(){return this.divideScalar(this.length()||1)}angle(){return Math.atan2(-this.y,-this.x)+Math.PI}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(ra(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y;return t*t+s*s}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this}equals(e){return e.x===this.x&&e.y===this.y}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this}rotateAround(e,t){const s=Math.cos(t),i=Math.sin(t),r=this.x-e.x,n=this.y-e.y;return this.x=r*s-n*i+e.x,this.y=r*i+n*s+e.y,this}random(){return this.x=Math.random(),this.y=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y}}class ca{constructor(e=0,t=0,s=0,i=1){this.isQuaternion=!0,this._x=e,this._y=t,this._z=s,this._w=i}static slerpFlat(e,t,s,i,r,n,o){let a=s[i+0],l=s[i+1],h=s[i+2],u=s[i+3],c=r[n+0],d=r[n+1],p=r[n+2],m=r[n+3];if(o<=0)return e[t+0]=a,e[t+1]=l,e[t+2]=h,void(e[t+3]=u);if(o>=1)return e[t+0]=c,e[t+1]=d,e[t+2]=p,void(e[t+3]=m);if(u!==m||a!==c||l!==d||h!==p){let e=a*c+l*d+h*p+u*m;e<0&&(c=-c,d=-d,p=-p,m=-m,e=-e);let t=1-o;if(e<.9995){const s=Math.acos(e),i=Math.sin(s);t=Math.sin(t*s)/i,a=a*t+c*(o=Math.sin(o*s)/i),l=l*t+d*o,h=h*t+p*o,u=u*t+m*o}else{a=a*t+c*o,l=l*t+d*o,h=h*t+p*o,u=u*t+m*o;const e=1/Math.sqrt(a*a+l*l+h*h+u*u);a*=e,l*=e,h*=e,u*=e}}e[t]=a,e[t+1]=l,e[t+2]=h,e[t+3]=u}static multiplyQuaternionsFlat(e,t,s,i,r,n){const o=s[i],a=s[i+1],l=s[i+2],h=s[i+3],u=r[n],c=r[n+1],d=r[n+2],p=r[n+3];return e[t]=o*p+h*u+a*d-l*c,e[t+1]=a*p+h*c+l*u-o*d,e[t+2]=l*p+h*d+o*c-a*u,e[t+3]=h*p-o*u-a*c-l*d,e}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get w(){return this._w}set w(e){this._w=e,this._onChangeCallback()}set(e,t,s,i){return this._x=e,this._y=t,this._z=s,this._w=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._w)}copy(e){return this._x=e.x,this._y=e.y,this._z=e.z,this._w=e.w,this._onChangeCallback(),this}setFromEuler(e,t=!0){const s=e._x,i=e._y,r=e._z,n=e._order,o=Math.cos,a=Math.sin,l=o(s/2),h=o(i/2),u=o(r/2),c=a(s/2),d=a(i/2),p=a(r/2);switch(n){case"XYZ":this._x=c*h*u+l*d*p,this._y=l*d*u-c*h*p,this._z=l*h*p+c*d*u,this._w=l*h*u-c*d*p;break;case"YXZ":this._x=c*h*u+l*d*p,this._y=l*d*u-c*h*p,this._z=l*h*p-c*d*u,this._w=l*h*u+c*d*p;break;case"ZXY":this._x=c*h*u-l*d*p,this._y=l*d*u+c*h*p,this._z=l*h*p+c*d*u,this._w=l*h*u-c*d*p;break;case"ZYX":this._x=c*h*u-l*d*p,this._y=l*d*u+c*h*p,this._z=l*h*p-c*d*u,this._w=l*h*u+c*d*p;break;case"YZX":this._x=c*h*u+l*d*p,this._y=l*d*u+c*h*p,this._z=l*h*p-c*d*u,this._w=l*h*u-c*d*p;break;case"XZY":this._x=c*h*u-l*d*p,this._y=l*d*u-c*h*p,this._z=l*h*p+c*d*u,this._w=l*h*u+c*d*p;break;default:Yo("Quaternion: .setFromEuler() encountered an unknown order: "+n)}return!0===t&&this._onChangeCallback(),this}setFromAxisAngle(e,t){const s=t/2,i=Math.sin(s);return this._x=e.x*i,this._y=e.y*i,this._z=e.z*i,this._w=Math.cos(s),this._onChangeCallback(),this}setFromRotationMatrix(e){const t=e.elements,s=t[0],i=t[4],r=t[8],n=t[1],o=t[5],a=t[9],l=t[2],h=t[6],u=t[10],c=s+o+u;if(c>0){const e=.5/Math.sqrt(c+1);this._w=.25/e,this._x=(h-a)*e,this._y=(r-l)*e,this._z=(n-i)*e}else if(s>o&&s>u){const e=2*Math.sqrt(1+s-o-u);this._w=(h-a)/e,this._x=.25*e,this._y=(i+n)/e,this._z=(r+l)/e}else if(o>u){const e=2*Math.sqrt(1+o-s-u);this._w=(r-l)/e,this._x=(i+n)/e,this._y=.25*e,this._z=(a+h)/e}else{const e=2*Math.sqrt(1+u-s-o);this._w=(n-i)/e,this._x=(r+l)/e,this._y=(a+h)/e,this._z=.25*e}return this._onChangeCallback(),this}setFromUnitVectors(e,t){let s=e.dot(t)+1;return s<1e-8?(s=0,Math.abs(e.x)>Math.abs(e.z)?(this._x=-e.y,this._y=e.x,this._z=0,this._w=s):(this._x=0,this._y=-e.z,this._z=e.y,this._w=s)):(this._x=e.y*t.z-e.z*t.y,this._y=e.z*t.x-e.x*t.z,this._z=e.x*t.y-e.y*t.x,this._w=s),this.normalize()}angleTo(e){return 2*Math.acos(Math.abs(ra(this.dot(e),-1,1)))}rotateTowards(e,t){const s=this.angleTo(e);if(0===s)return this;const i=Math.min(1,t/s);return this.slerp(e,i),this}identity(){return this.set(0,0,0,1)}invert(){return this.conjugate()}conjugate(){return this._x*=-1,this._y*=-1,this._z*=-1,this._onChangeCallback(),this}dot(e){return this._x*e._x+this._y*e._y+this._z*e._z+this._w*e._w}lengthSq(){return this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w}length(){return Math.sqrt(this._x*this._x+this._y*this._y+this._z*this._z+this._w*this._w)}normalize(){let e=this.length();return 0===e?(this._x=0,this._y=0,this._z=0,this._w=1):(e=1/e,this._x=this._x*e,this._y=this._y*e,this._z=this._z*e,this._w=this._w*e),this._onChangeCallback(),this}multiply(e){return this.multiplyQuaternions(this,e)}premultiply(e){return this.multiplyQuaternions(e,this)}multiplyQuaternions(e,t){const s=e._x,i=e._y,r=e._z,n=e._w,o=t._x,a=t._y,l=t._z,h=t._w;return this._x=s*h+n*o+i*l-r*a,this._y=i*h+n*a+r*o-s*l,this._z=r*h+n*l+s*a-i*o,this._w=n*h-s*o-i*a-r*l,this._onChangeCallback(),this}slerp(e,t){if(t<=0)return this;if(t>=1)return this.copy(e);let s=e._x,i=e._y,r=e._z,n=e._w,o=this.dot(e);o<0&&(s=-s,i=-i,r=-r,n=-n,o=-o);let a=1-t;if(o<.9995){const e=Math.acos(o),l=Math.sin(e);a=Math.sin(a*e)/l,t=Math.sin(t*e)/l,this._x=this._x*a+s*t,this._y=this._y*a+i*t,this._z=this._z*a+r*t,this._w=this._w*a+n*t,this._onChangeCallback()}else this._x=this._x*a+s*t,this._y=this._y*a+i*t,this._z=this._z*a+r*t,this._w=this._w*a+n*t,this.normalize();return this}slerpQuaternions(e,t,s){return this.copy(e).slerp(t,s)}random(){const e=2*Math.PI*Math.random(),t=2*Math.PI*Math.random(),s=Math.random(),i=Math.sqrt(1-s),r=Math.sqrt(s);return this.set(i*Math.sin(e),i*Math.cos(e),r*Math.sin(t),r*Math.cos(t))}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._w===this._w}fromArray(e,t=0){return this._x=e[t],this._y=e[t+1],this._z=e[t+2],this._w=e[t+3],this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._w,e}fromBufferAttribute(e,t){return this._x=e.getX(t),this._y=e.getY(t),this._z=e.getZ(t),this._w=e.getW(t),this._onChangeCallback(),this}toJSON(){return this.toArray()}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._w}}class da{constructor(e=0,t=0,s=0){da.prototype.isVector3=!0,this.x=e,this.y=t,this.z=s}set(e,t,s){return void 0===s&&(s=this.z),this.x=e,this.y=t,this.z=s,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this}multiplyVectors(e,t){return this.x=e.x*t.x,this.y=e.y*t.y,this.z=e.z*t.z,this}applyEuler(e){return this.applyQuaternion(ma.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(ma.setFromAxisAngle(e,t))}applyMatrix3(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[3]*s+r[6]*i,this.y=r[1]*t+r[4]*s+r[7]*i,this.z=r[2]*t+r[5]*s+r[8]*i,this}applyNormalMatrix(e){return this.applyMatrix3(e).normalize()}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=e.elements,n=1/(r[3]*t+r[7]*s+r[11]*i+r[15]);return this.x=(r[0]*t+r[4]*s+r[8]*i+r[12])*n,this.y=(r[1]*t+r[5]*s+r[9]*i+r[13])*n,this.z=(r[2]*t+r[6]*s+r[10]*i+r[14])*n,this}applyQuaternion(e){const t=this.x,s=this.y,i=this.z,r=e.x,n=e.y,o=e.z,a=e.w,l=2*(n*i-o*s),h=2*(o*t-r*i),u=2*(r*s-n*t);return this.x=t+a*l+n*u-o*h,this.y=s+a*h+o*l-r*u,this.z=i+a*u+r*h-n*l,this}project(e){return this.applyMatrix4(e.matrixWorldInverse).applyMatrix4(e.projectionMatrix)}unproject(e){return this.applyMatrix4(e.projectionMatrixInverse).applyMatrix4(e.matrixWorld)}transformDirection(e){const t=this.x,s=this.y,i=this.z,r=e.elements;return this.x=r[0]*t+r[4]*s+r[8]*i,this.y=r[1]*t+r[5]*s+r[9]*i,this.z=r[2]*t+r[6]*s+r[10]*i,this.normalize()}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this}divideScalar(e){return this.multiplyScalar(1/e)}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this}clamp(e,t){return this.x=ra(this.x,e.x,t.x),this.y=ra(this.y,e.y,t.y),this.z=ra(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=ra(this.x,e,t),this.y=ra(this.y,e,t),this.z=ra(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(ra(s,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this}cross(e){return this.crossVectors(this,e)}crossVectors(e,t){const s=e.x,i=e.y,r=e.z,n=t.x,o=t.y,a=t.z;return this.x=i*a-r*o,this.y=r*n-s*a,this.z=s*o-i*n,this}projectOnVector(e){const t=e.lengthSq();if(0===t)return this.set(0,0,0);const s=e.dot(this)/t;return this.copy(e).multiplyScalar(s)}projectOnPlane(e){return pa.copy(this).projectOnVector(e),this.sub(pa)}reflect(e){return this.sub(pa.copy(e).multiplyScalar(2*this.dot(e)))}angleTo(e){const t=Math.sqrt(this.lengthSq()*e.lengthSq());if(0===t)return Math.PI/2;const s=this.dot(e)/t;return Math.acos(ra(s,-1,1))}distanceTo(e){return Math.sqrt(this.distanceToSquared(e))}distanceToSquared(e){const t=this.x-e.x,s=this.y-e.y,i=this.z-e.z;return t*t+s*s+i*i}manhattanDistanceTo(e){return Math.abs(this.x-e.x)+Math.abs(this.y-e.y)+Math.abs(this.z-e.z)}setFromSpherical(e){return this.setFromSphericalCoords(e.radius,e.phi,e.theta)}setFromSphericalCoords(e,t,s){const i=Math.sin(t)*e;return this.x=i*Math.sin(s),this.y=Math.cos(t)*e,this.z=i*Math.cos(s),this}setFromCylindrical(e){return this.setFromCylindricalCoords(e.radius,e.theta,e.y)}setFromCylindricalCoords(e,t,s){return this.x=e*Math.sin(t),this.y=s,this.z=e*Math.cos(t),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this}setFromMatrixScale(e){const t=this.setFromMatrixColumn(e,0).length(),s=this.setFromMatrixColumn(e,1).length(),i=this.setFromMatrixColumn(e,2).length();return this.x=t,this.y=s,this.z=i,this}setFromMatrixColumn(e,t){return this.fromArray(e.elements,4*t)}setFromMatrix3Column(e,t){return this.fromArray(e.elements,3*t)}setFromEuler(e){return this.x=e._x,this.y=e._y,this.z=e._z,this}setFromColor(e){return this.x=e.r,this.y=e.g,this.z=e.b,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this}randomDirection(){const e=Math.random()*Math.PI*2,t=2*Math.random()-1,s=Math.sqrt(1-t*t);return this.x=s*Math.cos(e),this.y=t,this.z=s*Math.sin(e),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z}}const pa=new da,ma=new ca;class fa{constructor(e,t,s,i,r,n,o,a,l){fa.prototype.isMatrix3=!0,this.elements=[1,0,0,0,1,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,o,a,l)}set(e,t,s,i,r,n,o,a,l){const h=this.elements;return h[0]=e,h[1]=i,h[2]=o,h[3]=t,h[4]=r,h[5]=a,h[6]=s,h[7]=n,h[8]=l,this}identity(){return this.set(1,0,0,0,1,0,0,0,1),this}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],this}extractBasis(e,t,s){return e.setFromMatrix3Column(this,0),t.setFromMatrix3Column(this,1),s.setFromMatrix3Column(this,2),this}setFromMatrix4(e){const t=e.elements;return this.set(t[0],t[4],t[8],t[1],t[5],t[9],t[2],t[6],t[10]),this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],o=s[3],a=s[6],l=s[1],h=s[4],u=s[7],c=s[2],d=s[5],p=s[8],m=i[0],f=i[3],g=i[6],y=i[1],x=i[4],b=i[7],_=i[2],w=i[5],v=i[8];return r[0]=n*m+o*y+a*_,r[3]=n*f+o*x+a*w,r[6]=n*g+o*b+a*v,r[1]=l*m+h*y+u*_,r[4]=l*f+h*x+u*w,r[7]=l*g+h*b+u*v,r[2]=c*m+d*y+p*_,r[5]=c*f+d*x+p*w,r[8]=c*g+d*b+p*v,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[3]*=e,t[6]*=e,t[1]*=e,t[4]*=e,t[7]*=e,t[2]*=e,t[5]*=e,t[8]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8];return t*n*h-t*o*l-s*r*h+s*o*a+i*r*l-i*n*a}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8],u=h*n-o*l,c=o*a-h*r,d=l*r-n*a,p=t*u+s*c+i*d;if(0===p)return this.set(0,0,0,0,0,0,0,0,0);const m=1/p;return e[0]=u*m,e[1]=(i*l-h*s)*m,e[2]=(o*s-i*n)*m,e[3]=c*m,e[4]=(h*t-i*a)*m,e[5]=(i*r-o*t)*m,e[6]=d*m,e[7]=(s*a-l*t)*m,e[8]=(n*t-s*r)*m,this}transpose(){let e;const t=this.elements;return e=t[1],t[1]=t[3],t[3]=e,e=t[2],t[2]=t[6],t[6]=e,e=t[5],t[5]=t[7],t[7]=e,this}getNormalMatrix(e){return this.setFromMatrix4(e).invert().transpose()}transposeIntoArray(e){const t=this.elements;return e[0]=t[0],e[1]=t[3],e[2]=t[6],e[3]=t[1],e[4]=t[4],e[5]=t[7],e[6]=t[2],e[7]=t[5],e[8]=t[8],this}setUvTransform(e,t,s,i,r,n,o){const a=Math.cos(r),l=Math.sin(r);return this.set(s*a,s*l,-s*(a*n+l*o)+n+e,-i*l,i*a,-i*(-l*n+a*o)+o+t,0,0,1),this}scale(e,t){return this.premultiply(ga.makeScale(e,t)),this}rotate(e){return this.premultiply(ga.makeRotation(-e)),this}translate(e,t){return this.premultiply(ga.makeTranslation(e,t)),this}makeTranslation(e,t){return e.isVector2?this.set(1,0,e.x,0,1,e.y,0,0,1):this.set(1,0,e,0,1,t,0,0,1),this}makeRotation(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,s,t,0,0,0,1),this}makeScale(e,t){return this.set(e,0,0,0,t,0,0,0,1),this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<9;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<9;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e}clone(){return(new this.constructor).fromArray(this.elements)}}const ga=new fa,ya=(new fa).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),xa=(new fa).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function ba(){const e={enabled:!0,workingColorSpace:Ao,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===Eo&&(e.r=wa(e.r),e.g=wa(e.g),e.b=wa(e.b)),this.spaces[t].primaries!==this.spaces[s].primaries&&(e.applyMatrix3(this.spaces[t].toXYZ),e.applyMatrix3(this.spaces[s].fromXYZ)),this.spaces[s].transfer===Eo&&(e.r=va(e.r),e.g=va(e.g),e.b=va(e.b)),e):e},workingToColorSpace:function(e,t){return this.convert(e,this.workingColorSpace,t)},colorSpaceToWorking:function(e,t){return this.convert(e,t,this.workingColorSpace)},getPrimaries:function(e){return this.spaces[e].primaries},getTransfer:function(e){return e===So?No:this.spaces[e].transfer},getToneMappingMode:function(e){return this.spaces[e].outputColorSpaceConfig.toneMappingMode||"standard"},getLuminanceCoefficients:function(e,t=this.workingColorSpace){return e.fromArray(this.spaces[t].luminanceCoefficients)},define:function(e){Object.assign(this.spaces,e)},_getMatrix:function(e,t,s){return e.copy(this.spaces[t].toXYZ).multiply(this.spaces[s].fromXYZ)},_getDrawingBufferColorSpace:function(e){return this.spaces[e].outputColorSpaceConfig.drawingBufferColorSpace},_getUnpackColorSpace:function(e=this.workingColorSpace){return this.spaces[e].workingColorSpaceConfig.unpackColorSpace},fromWorkingColorSpace:function(t,s){return Qo("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(t,s)},toWorkingColorSpace:function(t,s){return Qo("ColorManagement: .toWorkingColorSpace() has been renamed to .colorSpaceToWorking()."),e.colorSpaceToWorking(t,s)}},t=[.64,.33,.3,.6,.15,.06],s=[.2126,.7152,.0722],i=[.3127,.329];return e.define({[Ao]:{primaries:t,whitePoint:i,transfer:No,toXYZ:ya,fromXYZ:xa,luminanceCoefficients:s,workingColorSpaceConfig:{unpackColorSpace:Mo},outputColorSpaceConfig:{drawingBufferColorSpace:Mo}},[Mo]:{primaries:t,whitePoint:i,transfer:Eo,toXYZ:ya,fromXYZ:xa,luminanceCoefficients:s,outputColorSpaceConfig:{drawingBufferColorSpace:Mo}}}),e}const _a=ba();function wa(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function va(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let Ta;class Sa{static getDataURL(e,t="image/png"){if(/^data:/i.test(e.src))return e.src;if("undefined"==typeof HTMLCanvasElement)return e.src;let s;if(e instanceof HTMLCanvasElement)s=e;else{void 0===Ta&&(Ta=Ho("canvas")),Ta.width=e.width,Ta.height=e.height;const t=Ta.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),s=Ta}return s.toDataURL(t)}static sRGBToLinear(e){if("undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap){const t=Ho("canvas");t.width=e.width,t.height=e.height;const s=t.getContext("2d");s.drawImage(e,0,0,e.width,e.height);const i=s.getImageData(0,0,e.width,e.height),r=i.data;for(let e=0;e<r.length;e++)r[e]=255*wa(r[e]/255);return s.putImageData(i,0,0),t}if(e.data){const t=e.data.slice(0);for(let e=0;e<t.length;e++)t instanceof Uint8Array||t instanceof Uint8ClampedArray?t[e]=Math.floor(255*wa(t[e]/255)):t[e]=wa(t[e]);return{data:t,width:e.width,height:e.height}}return Yo("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let Ma=0;class Aa{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:Ma++}),this.uuid=ia(),this.data=e,this.dataReady=!0,this.version=0}getSize(e){const t=this.data;return"undefined"!=typeof HTMLVideoElement&&t instanceof HTMLVideoElement?e.set(t.videoWidth,t.videoHeight,0):"undefined"!=typeof VideoFrame&&t instanceof VideoFrame?e.set(t.displayHeight,t.displayWidth,0):null!==t?e.set(t.width,t.height,t.depth||0):e.set(0,0,0),e}set needsUpdate(e){!0===e&&this.version++}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.images[this.uuid])return e.images[this.uuid];const s={uuid:this.uuid,url:""},i=this.data;if(null!==i){let e;if(Array.isArray(i)){e=[];for(let t=0,s=i.length;t<s;t++)i[t].isDataTexture?e.push(Na(i[t].image)):e.push(Na(i[t]))}else e=Na(i);s.url=e}return t||(e.images[this.uuid]=s),s}}function Na(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?Sa.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(Yo("Texture: Unable to serialize Texture."),{})}let Ea=0;const Ca=new da;class Ra extends Ko{constructor(e=Ra.DEFAULT_IMAGE,t=Ra.DEFAULT_MAPPING,s=1001,i=1001,r=1006,n=1008,o=1023,a=1009,l=Ra.DEFAULT_ANISOTROPY,h=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:Ea++}),this.uuid=ia(),this.name="",this.source=new Aa(e),this.mipmaps=[],this.mapping=t,this.channel=0,this.wrapS=s,this.wrapT=i,this.magFilter=r,this.minFilter=n,this.anisotropy=l,this.format=o,this.internalFormat=null,this.type=a,this.offset=new ua(0,0),this.repeat=new ua(1,1),this.center=new ua(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new fa,this.generateMipmaps=!0,this.premultiplyAlpha=!1,this.flipY=!0,this.unpackAlignment=4,this.colorSpace=h,this.userData={},this.updateRanges=[],this.version=0,this.onUpdate=null,this.renderTarget=null,this.isRenderTargetTexture=!1,this.isArrayTexture=!!(e&&e.depth&&e.depth>1),this.pmremVersion=0}get width(){return this.source.getSize(Ca).x}get height(){return this.source.getSize(Ca).y}get depth(){return this.source.getSize(Ca).z}get image(){return this.source.data}set image(e=null){this.source.data=e}updateMatrix(){this.matrix.setUvTransform(this.offset.x,this.offset.y,this.repeat.x,this.repeat.y,this.rotation,this.center.x,this.center.y)}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}clone(){return(new this.constructor).copy(this)}copy(e){return this.name=e.name,this.source=e.source,this.mipmaps=e.mipmaps.slice(0),this.mapping=e.mapping,this.channel=e.channel,this.wrapS=e.wrapS,this.wrapT=e.wrapT,this.magFilter=e.magFilter,this.minFilter=e.minFilter,this.anisotropy=e.anisotropy,this.format=e.format,this.internalFormat=e.internalFormat,this.type=e.type,this.offset.copy(e.offset),this.repeat.copy(e.repeat),this.center.copy(e.center),this.rotation=e.rotation,this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrix.copy(e.matrix),this.generateMipmaps=e.generateMipmaps,this.premultiplyAlpha=e.premultiplyAlpha,this.flipY=e.flipY,this.unpackAlignment=e.unpackAlignment,this.colorSpace=e.colorSpace,this.renderTarget=e.renderTarget,this.isRenderTargetTexture=e.isRenderTargetTexture,this.isArrayTexture=e.isArrayTexture,this.userData=JSON.parse(JSON.stringify(e.userData)),this.needsUpdate=!0,this}setValues(e){for(const t in e){const s=e[t];if(void 0===s){Yo(`Texture.setValues(): parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&s&&i.isVector2&&s.isVector2||i&&s&&i.isVector3&&s.isVector3||i&&s&&i.isMatrix3&&s.isMatrix3?i.copy(s):this[t]=s:Yo(`Texture.setValues(): property '${t}' does not exist.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;if(!t&&void 0!==e.textures[this.uuid])return e.textures[this.uuid];const s={metadata:{version:4.7,type:"Texture",generator:"Texture.toJSON"},uuid:this.uuid,name:this.name,image:this.source.toJSON(e).uuid,mapping:this.mapping,channel:this.channel,repeat:[this.repeat.x,this.repeat.y],offset:[this.offset.x,this.offset.y],center:[this.center.x,this.center.y],rotation:this.rotation,wrap:[this.wrapS,this.wrapT],format:this.format,internalFormat:this.internalFormat,type:this.type,colorSpace:this.colorSpace,minFilter:this.minFilter,magFilter:this.magFilter,anisotropy:this.anisotropy,flipY:this.flipY,generateMipmaps:this.generateMipmaps,premultiplyAlpha:this.premultiplyAlpha,unpackAlignment:this.unpackAlignment};return Object.keys(this.userData).length>0&&(s.userData=this.userData),t||(e.textures[this.uuid]=s),s}dispose(){this.dispatchEvent({type:"dispose"})}transformUv(e){if(300!==this.mapping)return e;if(e.applyMatrix3(this.matrix),e.x<0||e.x>1)switch(this.wrapS){case dn:e.x=e.x-Math.floor(e.x);break;case pn:e.x=e.x<0?0:1;break;case mn:1===Math.abs(Math.floor(e.x)%2)?e.x=Math.ceil(e.x)-e.x:e.x=e.x-Math.floor(e.x)}if(e.y<0||e.y>1)switch(this.wrapT){case dn:e.y=e.y-Math.floor(e.y);break;case pn:e.y=e.y<0?0:1;break;case mn:1===Math.abs(Math.floor(e.y)%2)?e.y=Math.ceil(e.y)-e.y:e.y=e.y-Math.floor(e.y)}return this.flipY&&(e.y=1-e.y),e}set needsUpdate(e){!0===e&&(this.version++,this.source.needsUpdate=!0)}set needsPMREMUpdate(e){!0===e&&this.pmremVersion++}}Ra.DEFAULT_IMAGE=null,Ra.DEFAULT_MAPPING=300,Ra.DEFAULT_ANISOTROPY=1;class Pa{constructor(e=0,t=0,s=0,i=1){Pa.prototype.isVector4=!0,this.x=e,this.y=t,this.z=s,this.w=i}get width(){return this.z}set width(e){this.z=e}get height(){return this.w}set height(e){this.w=e}set(e,t,s,i){return this.x=e,this.y=t,this.z=s,this.w=i,this}setScalar(e){return this.x=e,this.y=e,this.z=e,this.w=e,this}setX(e){return this.x=e,this}setY(e){return this.y=e,this}setZ(e){return this.z=e,this}setW(e){return this.w=e,this}setComponent(e,t){switch(e){case 0:this.x=t;break;case 1:this.y=t;break;case 2:this.z=t;break;case 3:this.w=t;break;default:throw new Error("index is out of range: "+e)}return this}getComponent(e){switch(e){case 0:return this.x;case 1:return this.y;case 2:return this.z;case 3:return this.w;default:throw new Error("index is out of range: "+e)}}clone(){return new this.constructor(this.x,this.y,this.z,this.w)}copy(e){return this.x=e.x,this.y=e.y,this.z=e.z,this.w=void 0!==e.w?e.w:1,this}add(e){return this.x+=e.x,this.y+=e.y,this.z+=e.z,this.w+=e.w,this}addScalar(e){return this.x+=e,this.y+=e,this.z+=e,this.w+=e,this}addVectors(e,t){return this.x=e.x+t.x,this.y=e.y+t.y,this.z=e.z+t.z,this.w=e.w+t.w,this}addScaledVector(e,t){return this.x+=e.x*t,this.y+=e.y*t,this.z+=e.z*t,this.w+=e.w*t,this}sub(e){return this.x-=e.x,this.y-=e.y,this.z-=e.z,this.w-=e.w,this}subScalar(e){return this.x-=e,this.y-=e,this.z-=e,this.w-=e,this}subVectors(e,t){return this.x=e.x-t.x,this.y=e.y-t.y,this.z=e.z-t.z,this.w=e.w-t.w,this}multiply(e){return this.x*=e.x,this.y*=e.y,this.z*=e.z,this.w*=e.w,this}multiplyScalar(e){return this.x*=e,this.y*=e,this.z*=e,this.w*=e,this}applyMatrix4(e){const t=this.x,s=this.y,i=this.z,r=this.w,n=e.elements;return this.x=n[0]*t+n[4]*s+n[8]*i+n[12]*r,this.y=n[1]*t+n[5]*s+n[9]*i+n[13]*r,this.z=n[2]*t+n[6]*s+n[10]*i+n[14]*r,this.w=n[3]*t+n[7]*s+n[11]*i+n[15]*r,this}divide(e){return this.x/=e.x,this.y/=e.y,this.z/=e.z,this.w/=e.w,this}divideScalar(e){return this.multiplyScalar(1/e)}setAxisAngleFromQuaternion(e){this.w=2*Math.acos(e.w);const t=Math.sqrt(1-e.w*e.w);return t<1e-4?(this.x=1,this.y=0,this.z=0):(this.x=e.x/t,this.y=e.y/t,this.z=e.z/t),this}setAxisAngleFromRotationMatrix(e){let t,s,i,r;const n=.01,o=.1,a=e.elements,l=a[0],h=a[4],u=a[8],c=a[1],d=a[5],p=a[9],m=a[2],f=a[6],g=a[10];if(Math.abs(h-c)<n&&Math.abs(u-m)<n&&Math.abs(p-f)<n){if(Math.abs(h+c)<o&&Math.abs(u+m)<o&&Math.abs(p+f)<o&&Math.abs(l+d+g-3)<o)return this.set(1,0,0,0),this;t=Math.PI;const e=(l+1)/2,a=(d+1)/2,y=(g+1)/2,x=(h+c)/4,b=(u+m)/4,_=(p+f)/4;return e>a&&e>y?e<n?(s=0,i=.707106781,r=.707106781):(s=Math.sqrt(e),i=x/s,r=b/s):a>y?a<n?(s=.707106781,i=0,r=.707106781):(i=Math.sqrt(a),s=x/i,r=_/i):y<n?(s=.707106781,i=.707106781,r=0):(r=Math.sqrt(y),s=b/r,i=_/r),this.set(s,i,r,t),this}let y=Math.sqrt((f-p)*(f-p)+(u-m)*(u-m)+(c-h)*(c-h));return Math.abs(y)<.001&&(y=1),this.x=(f-p)/y,this.y=(u-m)/y,this.z=(c-h)/y,this.w=Math.acos((l+d+g-1)/2),this}setFromMatrixPosition(e){const t=e.elements;return this.x=t[12],this.y=t[13],this.z=t[14],this.w=t[15],this}min(e){return this.x=Math.min(this.x,e.x),this.y=Math.min(this.y,e.y),this.z=Math.min(this.z,e.z),this.w=Math.min(this.w,e.w),this}max(e){return this.x=Math.max(this.x,e.x),this.y=Math.max(this.y,e.y),this.z=Math.max(this.z,e.z),this.w=Math.max(this.w,e.w),this}clamp(e,t){return this.x=ra(this.x,e.x,t.x),this.y=ra(this.y,e.y,t.y),this.z=ra(this.z,e.z,t.z),this.w=ra(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=ra(this.x,e,t),this.y=ra(this.y,e,t),this.z=ra(this.z,e,t),this.w=ra(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(ra(s,e,t))}floor(){return this.x=Math.floor(this.x),this.y=Math.floor(this.y),this.z=Math.floor(this.z),this.w=Math.floor(this.w),this}ceil(){return this.x=Math.ceil(this.x),this.y=Math.ceil(this.y),this.z=Math.ceil(this.z),this.w=Math.ceil(this.w),this}round(){return this.x=Math.round(this.x),this.y=Math.round(this.y),this.z=Math.round(this.z),this.w=Math.round(this.w),this}roundToZero(){return this.x=Math.trunc(this.x),this.y=Math.trunc(this.y),this.z=Math.trunc(this.z),this.w=Math.trunc(this.w),this}negate(){return this.x=-this.x,this.y=-this.y,this.z=-this.z,this.w=-this.w,this}dot(e){return this.x*e.x+this.y*e.y+this.z*e.z+this.w*e.w}lengthSq(){return this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w}length(){return Math.sqrt(this.x*this.x+this.y*this.y+this.z*this.z+this.w*this.w)}manhattanLength(){return Math.abs(this.x)+Math.abs(this.y)+Math.abs(this.z)+Math.abs(this.w)}normalize(){return this.divideScalar(this.length()||1)}setLength(e){return this.normalize().multiplyScalar(e)}lerp(e,t){return this.x+=(e.x-this.x)*t,this.y+=(e.y-this.y)*t,this.z+=(e.z-this.z)*t,this.w+=(e.w-this.w)*t,this}lerpVectors(e,t,s){return this.x=e.x+(t.x-e.x)*s,this.y=e.y+(t.y-e.y)*s,this.z=e.z+(t.z-e.z)*s,this.w=e.w+(t.w-e.w)*s,this}equals(e){return e.x===this.x&&e.y===this.y&&e.z===this.z&&e.w===this.w}fromArray(e,t=0){return this.x=e[t],this.y=e[t+1],this.z=e[t+2],this.w=e[t+3],this}toArray(e=[],t=0){return e[t]=this.x,e[t+1]=this.y,e[t+2]=this.z,e[t+3]=this.w,e}fromBufferAttribute(e,t){return this.x=e.getX(t),this.y=e.getY(t),this.z=e.getZ(t),this.w=e.getW(t),this}random(){return this.x=Math.random(),this.y=Math.random(),this.z=Math.random(),this.w=Math.random(),this}*[Symbol.iterator](){yield this.x,yield this.y,yield this.z,yield this.w}}class Ba extends Ko{constructor(e=1,t=1,s={}){super(),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:xn,depthBuffer:!0,stencilBuffer:!1,resolveDepthBuffer:!0,resolveStencilBuffer:!0,depthTexture:null,samples:0,count:1,depth:1,multiview:!1},s),this.isRenderTarget=!0,this.width=e,this.height=t,this.depth=s.depth,this.scissor=new Pa(0,0,e,t),this.scissorTest=!1,this.viewport=new Pa(0,0,e,t);const i={width:e,height:t,depth:s.depth},r=new Ra(i);this.textures=[];const n=s.count;for(let e=0;e<n;e++)this.textures[e]=r.clone(),this.textures[e].isRenderTargetTexture=!0,this.textures[e].renderTarget=this;this._setTextureOptions(s),this.depthBuffer=s.depthBuffer,this.stencilBuffer=s.stencilBuffer,this.resolveDepthBuffer=s.resolveDepthBuffer,this.resolveStencilBuffer=s.resolveStencilBuffer,this._depthTexture=null,this.depthTexture=s.depthTexture,this.samples=s.samples,this.multiview=s.multiview}_setTextureOptions(e={}){const t={minFilter:xn,generateMipmaps:!1,flipY:!1,internalFormat:null};void 0!==e.mapping&&(t.mapping=e.mapping),void 0!==e.wrapS&&(t.wrapS=e.wrapS),void 0!==e.wrapT&&(t.wrapT=e.wrapT),void 0!==e.wrapR&&(t.wrapR=e.wrapR),void 0!==e.magFilter&&(t.magFilter=e.magFilter),void 0!==e.minFilter&&(t.minFilter=e.minFilter),void 0!==e.format&&(t.format=e.format),void 0!==e.type&&(t.type=e.type),void 0!==e.anisotropy&&(t.anisotropy=e.anisotropy),void 0!==e.colorSpace&&(t.colorSpace=e.colorSpace),void 0!==e.flipY&&(t.flipY=e.flipY),void 0!==e.generateMipmaps&&(t.generateMipmaps=e.generateMipmaps),void 0!==e.internalFormat&&(t.internalFormat=e.internalFormat);for(let e=0;e<this.textures.length;e++){this.textures[e].setValues(t)}}get texture(){return this.textures[0]}set texture(e){this.textures[0]=e}set depthTexture(e){null!==this._depthTexture&&(this._depthTexture.renderTarget=null),null!==e&&(e.renderTarget=this),this._depthTexture=e}get depthTexture(){return this._depthTexture}setSize(e,t,s=1){if(this.width!==e||this.height!==t||this.depth!==s){this.width=e,this.height=t,this.depth=s;for(let i=0,r=this.textures.length;i<r;i++)this.textures[i].image.width=e,this.textures[i].image.height=t,this.textures[i].image.depth=s,!0!==this.textures[i].isData3DTexture&&(this.textures[i].isArrayTexture=this.textures[i].image.depth>1);this.dispose()}this.viewport.set(0,0,e,t),this.scissor.set(0,0,e,t)}clone(){return(new this.constructor).copy(this)}copy(e){this.width=e.width,this.height=e.height,this.depth=e.depth,this.scissor.copy(e.scissor),this.scissorTest=e.scissorTest,this.viewport.copy(e.viewport),this.textures.length=0;for(let t=0,s=e.textures.length;t<s;t++){this.textures[t]=e.textures[t].clone(),this.textures[t].isRenderTargetTexture=!0,this.textures[t].renderTarget=this;const s=Object.assign({},e.textures[t].image);this.textures[t].source=new Aa(s)}return this.depthBuffer=e.depthBuffer,this.stencilBuffer=e.stencilBuffer,this.resolveDepthBuffer=e.resolveDepthBuffer,this.resolveStencilBuffer=e.resolveStencilBuffer,null!==e.depthTexture&&(this.depthTexture=e.depthTexture.clone()),this.samples=e.samples,this}dispose(){this.dispatchEvent({type:"dispose"})}}class Ia extends Ba{constructor(e=1,t=1,s={}){super(e,t,s),this.isWebGLRenderTarget=!0}}class Da extends Ra{constructor(e=null,t=1,s=1,i=1){super(null),this.isDataArrayTexture=!0,this.image={data:e,width:t,height:s,depth:i},this.magFilter=fn,this.minFilter=fn,this.wrapR=pn,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class La{constructor(e=new da(1/0,1/0,1/0),t=new da(-1/0,-1/0,-1/0)){this.isBox3=!0,this.min=e,this.max=t}set(e,t){return this.min.copy(e),this.max.copy(t),this}setFromArray(e){this.makeEmpty();for(let t=0,s=e.length;t<s;t+=3)this.expandByPoint(Oa.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(Oa.fromBufferAttribute(e,t));return this}setFromPoints(e){this.makeEmpty();for(let t=0,s=e.length;t<s;t++)this.expandByPoint(e[t]);return this}setFromCenterAndSize(e,t){const s=Oa.copy(t).multiplyScalar(.5);return this.min.copy(e).sub(s),this.max.copy(e).add(s),this}setFromObject(e,t=!1){return this.makeEmpty(),this.expandByObject(e,t)}clone(){return(new this.constructor).copy(this)}copy(e){return this.min.copy(e.min),this.max.copy(e.max),this}makeEmpty(){return this.min.x=this.min.y=this.min.z=1/0,this.max.x=this.max.y=this.max.z=-1/0,this}isEmpty(){return this.max.x<this.min.x||this.max.y<this.min.y||this.max.z<this.min.z}getCenter(e){return this.isEmpty()?e.set(0,0,0):e.addVectors(this.min,this.max).multiplyScalar(.5)}getSize(e){return this.isEmpty()?e.set(0,0,0):e.subVectors(this.max,this.min)}expandByPoint(e){return this.min.min(e),this.max.max(e),this}expandByVector(e){return this.min.sub(e),this.max.add(e),this}expandByScalar(e){return this.min.addScalar(-e),this.max.addScalar(e),this}expandByObject(e,t=!1){e.updateWorldMatrix(!1,!1);const s=e.geometry;if(void 0!==s){const i=s.getAttribute("position");if(!0===t&&void 0!==i&&!0!==e.isInstancedMesh)for(let t=0,s=i.count;t<s;t++)!0===e.isMesh?e.getVertexPosition(t,Oa):Oa.fromBufferAttribute(i,t),Oa.applyMatrix4(e.matrixWorld),this.expandByPoint(Oa);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),Va.copy(e.boundingBox)):(null===s.boundingBox&&s.computeBoundingBox(),Va.copy(s.boundingBox)),Va.applyMatrix4(e.matrixWorld),this.union(Va)}const i=e.children;for(let e=0,s=i.length;e<s;e++)this.expandByObject(i[e],t);return this}containsPoint(e){return e.x>=this.min.x&&e.x<=this.max.x&&e.y>=this.min.y&&e.y<=this.max.y&&e.z>=this.min.z&&e.z<=this.max.z}containsBox(e){return this.min.x<=e.min.x&&e.max.x<=this.max.x&&this.min.y<=e.min.y&&e.max.y<=this.max.y&&this.min.z<=e.min.z&&e.max.z<=this.max.z}getParameter(e,t){return t.set((e.x-this.min.x)/(this.max.x-this.min.x),(e.y-this.min.y)/(this.max.y-this.min.y),(e.z-this.min.z)/(this.max.z-this.min.z))}intersectsBox(e){return e.max.x>=this.min.x&&e.min.x<=this.max.x&&e.max.y>=this.min.y&&e.min.y<=this.max.y&&e.max.z>=this.min.z&&e.min.z<=this.max.z}intersectsSphere(e){return this.clampPoint(e.center,Oa),Oa.distanceToSquared(e.center)<=e.radius*e.radius}intersectsPlane(e){let t,s;return e.normal.x>0?(t=e.normal.x*this.min.x,s=e.normal.x*this.max.x):(t=e.normal.x*this.max.x,s=e.normal.x*this.min.x),e.normal.y>0?(t+=e.normal.y*this.min.y,s+=e.normal.y*this.max.y):(t+=e.normal.y*this.max.y,s+=e.normal.y*this.min.y),e.normal.z>0?(t+=e.normal.z*this.min.z,s+=e.normal.z*this.max.z):(t+=e.normal.z*this.max.z,s+=e.normal.z*this.min.z),t<=-e.constant&&s>=-e.constant}intersectsTriangle(e){if(this.isEmpty())return!1;this.getCenter(Wa),Ha.subVectors(this.max,Wa),za.subVectors(e.a,Wa),ka.subVectors(e.b,Wa),Ua.subVectors(e.c,Wa),Ga.subVectors(ka,za),ja.subVectors(Ua,ka),$a.subVectors(za,Ua);let t=[0,-Ga.z,Ga.y,0,-ja.z,ja.y,0,-$a.z,$a.y,Ga.z,0,-Ga.x,ja.z,0,-ja.x,$a.z,0,-$a.x,-Ga.y,Ga.x,0,-ja.y,ja.x,0,-$a.y,$a.x,0];return!!Ya(t,za,ka,Ua,Ha)&&(t=[1,0,0,0,1,0,0,0,1],!!Ya(t,za,ka,Ua,Ha)&&(qa.crossVectors(Ga,ja),t=[qa.x,qa.y,qa.z],Ya(t,za,ka,Ua,Ha)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Oa).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Oa).length()),e}intersect(e){return this.min.max(e.min),this.max.min(e.max),this.isEmpty()&&this.makeEmpty(),this}union(e){return this.min.min(e.min),this.max.max(e.max),this}applyMatrix4(e){return this.isEmpty()||(Fa[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),Fa[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),Fa[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),Fa[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),Fa[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),Fa[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),Fa[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),Fa[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(Fa)),this}translate(e){return this.min.add(e),this.max.add(e),this}equals(e){return e.min.equals(this.min)&&e.max.equals(this.max)}toJSON(){return{min:this.min.toArray(),max:this.max.toArray()}}fromJSON(e){return this.min.fromArray(e.min),this.max.fromArray(e.max),this}}const Fa=[new da,new da,new da,new da,new da,new da,new da,new da],Oa=new da,Va=new La,za=new da,ka=new da,Ua=new da,Ga=new da,ja=new da,$a=new da,Wa=new da,Ha=new da,qa=new da,Xa=new da;function Ya(e,t,s,i,r){for(let n=0,o=e.length-3;n<=o;n+=3){Xa.fromArray(e,n);const o=r.x*Math.abs(Xa.x)+r.y*Math.abs(Xa.y)+r.z*Math.abs(Xa.z),a=t.dot(Xa),l=s.dot(Xa),h=i.dot(Xa);if(Math.max(-Math.max(a,l,h),Math.min(a,l,h))>o)return!1}return!0}const Za=new La,Qa=new da,Ka=new da;class Ja{constructor(e=new da,t=-1){this.isSphere=!0,this.center=e,this.radius=t}set(e,t){return this.center.copy(e),this.radius=t,this}setFromPoints(e,t){const s=this.center;void 0!==t?s.copy(t):Za.setFromPoints(e).getCenter(s);let i=0;for(let t=0,r=e.length;t<r;t++)i=Math.max(i,s.distanceToSquared(e[t]));return this.radius=Math.sqrt(i),this}copy(e){return this.center.copy(e.center),this.radius=e.radius,this}isEmpty(){return this.radius<0}makeEmpty(){return this.center.set(0,0,0),this.radius=-1,this}containsPoint(e){return e.distanceToSquared(this.center)<=this.radius*this.radius}distanceToPoint(e){return e.distanceTo(this.center)-this.radius}intersectsSphere(e){const t=this.radius+e.radius;return e.center.distanceToSquared(this.center)<=t*t}intersectsBox(e){return e.intersectsSphere(this)}intersectsPlane(e){return Math.abs(e.distanceToPoint(this.center))<=this.radius}clampPoint(e,t){const s=this.center.distanceToSquared(e);return t.copy(e),s>this.radius*this.radius&&(t.sub(this.center).normalize(),t.multiplyScalar(this.radius).add(this.center)),t}getBoundingBox(e){return this.isEmpty()?(e.makeEmpty(),e):(e.set(this.center,this.center),e.expandByScalar(this.radius),e)}applyMatrix4(e){return this.center.applyMatrix4(e),this.radius=this.radius*e.getMaxScaleOnAxis(),this}translate(e){return this.center.add(e),this}expandByPoint(e){if(this.isEmpty())return this.center.copy(e),this.radius=0,this;Qa.subVectors(e,this.center);const t=Qa.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(Qa,s/e),this.radius+=s}return this}union(e){return e.isEmpty()?this:this.isEmpty()?(this.copy(e),this):(!0===this.center.equals(e.center)?this.radius=Math.max(this.radius,e.radius):(Ka.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(Qa.copy(e.center).add(Ka)),this.expandByPoint(Qa.copy(e.center).sub(Ka))),this)}equals(e){return e.center.equals(this.center)&&e.radius===this.radius}clone(){return(new this.constructor).copy(this)}toJSON(){return{radius:this.radius,center:this.center.toArray()}}fromJSON(e){return this.radius=e.radius,this.center.fromArray(e.center),this}}const el=new da,tl=new da,sl=new da,il=new da,rl=new da,nl=new da,ol=new da;class al{constructor(e=new da,t=new da(0,0,-1)){this.origin=e,this.direction=t}set(e,t){return this.origin.copy(e),this.direction.copy(t),this}copy(e){return this.origin.copy(e.origin),this.direction.copy(e.direction),this}at(e,t){return t.copy(this.origin).addScaledVector(this.direction,e)}lookAt(e){return this.direction.copy(e).sub(this.origin).normalize(),this}recast(e){return this.origin.copy(this.at(e,el)),this}closestPointToPoint(e,t){t.subVectors(e,this.origin);const s=t.dot(this.direction);return s<0?t.copy(this.origin):t.copy(this.origin).addScaledVector(this.direction,s)}distanceToPoint(e){return Math.sqrt(this.distanceSqToPoint(e))}distanceSqToPoint(e){const t=el.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(el.copy(this.origin).addScaledVector(this.direction,t),el.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){tl.copy(e).add(t).multiplyScalar(.5),sl.copy(t).sub(e).normalize(),il.copy(this.origin).sub(tl);const r=.5*e.distanceTo(t),n=-this.direction.dot(sl),o=il.dot(this.direction),a=-il.dot(sl),l=il.lengthSq(),h=Math.abs(1-n*n);let u,c,d,p;if(h>0)if(u=n*a-o,c=n*o-a,p=r*h,u>=0)if(c>=-p)if(c<=p){const e=1/h;u*=e,c*=e,d=u*(u+n*c+2*o)+c*(n*u+c+2*a)+l}else c=r,u=Math.max(0,-(n*c+o)),d=-u*u+c*(c+2*a)+l;else c=-r,u=Math.max(0,-(n*c+o)),d=-u*u+c*(c+2*a)+l;else c<=-p?(u=Math.max(0,-(-n*r+o)),c=u>0?-r:Math.min(Math.max(-r,-a),r),d=-u*u+c*(c+2*a)+l):c<=p?(u=0,c=Math.min(Math.max(-r,-a),r),d=c*(c+2*a)+l):(u=Math.max(0,-(n*r+o)),c=u>0?r:Math.min(Math.max(-r,-a),r),d=-u*u+c*(c+2*a)+l);else c=n>0?-r:r,u=Math.max(0,-(n*c+o)),d=-u*u+c*(c+2*a)+l;return s&&s.copy(this.origin).addScaledVector(this.direction,u),i&&i.copy(tl).addScaledVector(sl,c),d}intersectSphere(e,t){el.subVectors(e.center,this.origin);const s=el.dot(this.direction),i=el.dot(el)-s*s,r=e.radius*e.radius;if(i>r)return null;const n=Math.sqrt(r-i),o=s-n,a=s+n;return a<0?null:o<0?this.at(a,t):this.at(o,t)}intersectsSphere(e){return!(e.radius<0)&&this.distanceSqToPoint(e.center)<=e.radius*e.radius}distanceToPlane(e){const t=e.normal.dot(this.direction);if(0===t)return 0===e.distanceToPoint(this.origin)?0:null;const s=-(this.origin.dot(e.normal)+e.constant)/t;return s>=0?s:null}intersectPlane(e,t){const s=this.distanceToPlane(e);return null===s?null:this.at(s,t)}intersectsPlane(e){const t=e.distanceToPoint(this.origin);if(0===t)return!0;return e.normal.dot(this.direction)*t<0}intersectBox(e,t){let s,i,r,n,o,a;const l=1/this.direction.x,h=1/this.direction.y,u=1/this.direction.z,c=this.origin;return l>=0?(s=(e.min.x-c.x)*l,i=(e.max.x-c.x)*l):(s=(e.max.x-c.x)*l,i=(e.min.x-c.x)*l),h>=0?(r=(e.min.y-c.y)*h,n=(e.max.y-c.y)*h):(r=(e.max.y-c.y)*h,n=(e.min.y-c.y)*h),s>n||r>i?null:((r>s||isNaN(s))&&(s=r),(n<i||isNaN(i))&&(i=n),u>=0?(o=(e.min.z-c.z)*u,a=(e.max.z-c.z)*u):(o=(e.max.z-c.z)*u,a=(e.min.z-c.z)*u),s>a||o>i?null:((o>s||s!=s)&&(s=o),(a<i||i!=i)&&(i=a),i<0?null:this.at(s>=0?s:i,t)))}intersectsBox(e){return null!==this.intersectBox(e,el)}intersectTriangle(e,t,s,i,r){rl.subVectors(t,e),nl.subVectors(s,e),ol.crossVectors(rl,nl);let n,o=this.direction.dot(ol);if(o>0){if(i)return null;n=1}else{if(!(o<0))return null;n=-1,o=-o}il.subVectors(this.origin,e);const a=n*this.direction.dot(nl.crossVectors(il,nl));if(a<0)return null;const l=n*this.direction.dot(rl.cross(il));if(l<0)return null;if(a+l>o)return null;const h=-n*il.dot(ol);return h<0?null:this.at(h/o,r)}applyMatrix4(e){return this.origin.applyMatrix4(e),this.direction.transformDirection(e),this}equals(e){return e.origin.equals(this.origin)&&e.direction.equals(this.direction)}clone(){return(new this.constructor).copy(this)}}class ll{constructor(e,t,s,i,r,n,o,a,l,h,u,c,d,p,m,f){ll.prototype.isMatrix4=!0,this.elements=[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1],void 0!==e&&this.set(e,t,s,i,r,n,o,a,l,h,u,c,d,p,m,f)}set(e,t,s,i,r,n,o,a,l,h,u,c,d,p,m,f){const g=this.elements;return g[0]=e,g[4]=t,g[8]=s,g[12]=i,g[1]=r,g[5]=n,g[9]=o,g[13]=a,g[2]=l,g[6]=h,g[10]=u,g[14]=c,g[3]=d,g[7]=p,g[11]=m,g[15]=f,this}identity(){return this.set(1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1),this}clone(){return(new ll).fromArray(this.elements)}copy(e){const t=this.elements,s=e.elements;return t[0]=s[0],t[1]=s[1],t[2]=s[2],t[3]=s[3],t[4]=s[4],t[5]=s[5],t[6]=s[6],t[7]=s[7],t[8]=s[8],t[9]=s[9],t[10]=s[10],t[11]=s[11],t[12]=s[12],t[13]=s[13],t[14]=s[14],t[15]=s[15],this}copyPosition(e){const t=this.elements,s=e.elements;return t[12]=s[12],t[13]=s[13],t[14]=s[14],this}setFromMatrix3(e){const t=e.elements;return this.set(t[0],t[3],t[6],0,t[1],t[4],t[7],0,t[2],t[5],t[8],0,0,0,0,1),this}extractBasis(e,t,s){return 0===this.determinant()?(e.set(1,0,0),t.set(0,1,0),s.set(0,0,1),this):(e.setFromMatrixColumn(this,0),t.setFromMatrixColumn(this,1),s.setFromMatrixColumn(this,2),this)}makeBasis(e,t,s){return this.set(e.x,t.x,s.x,0,e.y,t.y,s.y,0,e.z,t.z,s.z,0,0,0,0,1),this}extractRotation(e){if(0===e.determinant())return this.identity();const t=this.elements,s=e.elements,i=1/hl.setFromMatrixColumn(e,0).length(),r=1/hl.setFromMatrixColumn(e,1).length(),n=1/hl.setFromMatrixColumn(e,2).length();return t[0]=s[0]*i,t[1]=s[1]*i,t[2]=s[2]*i,t[3]=0,t[4]=s[4]*r,t[5]=s[5]*r,t[6]=s[6]*r,t[7]=0,t[8]=s[8]*n,t[9]=s[9]*n,t[10]=s[10]*n,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromEuler(e){const t=this.elements,s=e.x,i=e.y,r=e.z,n=Math.cos(s),o=Math.sin(s),a=Math.cos(i),l=Math.sin(i),h=Math.cos(r),u=Math.sin(r);if("XYZ"===e.order){const e=n*h,s=n*u,i=o*h,r=o*u;t[0]=a*h,t[4]=-a*u,t[8]=l,t[1]=s+i*l,t[5]=e-r*l,t[9]=-o*a,t[2]=r-e*l,t[6]=i+s*l,t[10]=n*a}else if("YXZ"===e.order){const e=a*h,s=a*u,i=l*h,r=l*u;t[0]=e+r*o,t[4]=i*o-s,t[8]=n*l,t[1]=n*u,t[5]=n*h,t[9]=-o,t[2]=s*o-i,t[6]=r+e*o,t[10]=n*a}else if("ZXY"===e.order){const e=a*h,s=a*u,i=l*h,r=l*u;t[0]=e-r*o,t[4]=-n*u,t[8]=i+s*o,t[1]=s+i*o,t[5]=n*h,t[9]=r-e*o,t[2]=-n*l,t[6]=o,t[10]=n*a}else if("ZYX"===e.order){const e=n*h,s=n*u,i=o*h,r=o*u;t[0]=a*h,t[4]=i*l-s,t[8]=e*l+r,t[1]=a*u,t[5]=r*l+e,t[9]=s*l-i,t[2]=-l,t[6]=o*a,t[10]=n*a}else if("YZX"===e.order){const e=n*a,s=n*l,i=o*a,r=o*l;t[0]=a*h,t[4]=r-e*u,t[8]=i*u+s,t[1]=u,t[5]=n*h,t[9]=-o*h,t[2]=-l*h,t[6]=s*u+i,t[10]=e-r*u}else if("XZY"===e.order){const e=n*a,s=n*l,i=o*a,r=o*l;t[0]=a*h,t[4]=-u,t[8]=l*h,t[1]=e*u+r,t[5]=n*h,t[9]=s*u-i,t[2]=i*u-s,t[6]=o*h,t[10]=r*u+e}return t[3]=0,t[7]=0,t[11]=0,t[12]=0,t[13]=0,t[14]=0,t[15]=1,this}makeRotationFromQuaternion(e){return this.compose(cl,e,dl)}lookAt(e,t,s){const i=this.elements;return fl.subVectors(e,t),0===fl.lengthSq()&&(fl.z=1),fl.normalize(),pl.crossVectors(s,fl),0===pl.lengthSq()&&(1===Math.abs(s.z)?fl.x+=1e-4:fl.z+=1e-4,fl.normalize(),pl.crossVectors(s,fl)),pl.normalize(),ml.crossVectors(fl,pl),i[0]=pl.x,i[4]=ml.x,i[8]=fl.x,i[1]=pl.y,i[5]=ml.y,i[9]=fl.y,i[2]=pl.z,i[6]=ml.z,i[10]=fl.z,this}multiply(e){return this.multiplyMatrices(this,e)}premultiply(e){return this.multiplyMatrices(e,this)}multiplyMatrices(e,t){const s=e.elements,i=t.elements,r=this.elements,n=s[0],o=s[4],a=s[8],l=s[12],h=s[1],u=s[5],c=s[9],d=s[13],p=s[2],m=s[6],f=s[10],g=s[14],y=s[3],x=s[7],b=s[11],_=s[15],w=i[0],v=i[4],T=i[8],S=i[12],M=i[1],A=i[5],N=i[9],E=i[13],C=i[2],R=i[6],P=i[10],B=i[14],I=i[3],D=i[7],L=i[11],F=i[15];return r[0]=n*w+o*M+a*C+l*I,r[4]=n*v+o*A+a*R+l*D,r[8]=n*T+o*N+a*P+l*L,r[12]=n*S+o*E+a*B+l*F,r[1]=h*w+u*M+c*C+d*I,r[5]=h*v+u*A+c*R+d*D,r[9]=h*T+u*N+c*P+d*L,r[13]=h*S+u*E+c*B+d*F,r[2]=p*w+m*M+f*C+g*I,r[6]=p*v+m*A+f*R+g*D,r[10]=p*T+m*N+f*P+g*L,r[14]=p*S+m*E+f*B+g*F,r[3]=y*w+x*M+b*C+_*I,r[7]=y*v+x*A+b*R+_*D,r[11]=y*T+x*N+b*P+_*L,r[15]=y*S+x*E+b*B+_*F,this}multiplyScalar(e){const t=this.elements;return t[0]*=e,t[4]*=e,t[8]*=e,t[12]*=e,t[1]*=e,t[5]*=e,t[9]*=e,t[13]*=e,t[2]*=e,t[6]*=e,t[10]*=e,t[14]*=e,t[3]*=e,t[7]*=e,t[11]*=e,t[15]*=e,this}determinant(){const e=this.elements,t=e[0],s=e[4],i=e[8],r=e[12],n=e[1],o=e[5],a=e[9],l=e[13],h=e[2],u=e[6],c=e[10],d=e[14],p=e[3],m=e[7],f=e[11],g=e[15],y=a*d-l*c,x=o*d-l*u,b=o*c-a*u,_=n*d-l*h,w=n*c-a*h,v=n*u-o*h;return t*(m*y-f*x+g*b)-s*(p*y-f*_+g*w)+i*(p*x-m*_+g*v)-r*(p*b-m*w+f*v)}transpose(){const e=this.elements;let t;return t=e[1],e[1]=e[4],e[4]=t,t=e[2],e[2]=e[8],e[8]=t,t=e[6],e[6]=e[9],e[9]=t,t=e[3],e[3]=e[12],e[12]=t,t=e[7],e[7]=e[13],e[13]=t,t=e[11],e[11]=e[14],e[14]=t,this}setPosition(e,t,s){const i=this.elements;return e.isVector3?(i[12]=e.x,i[13]=e.y,i[14]=e.z):(i[12]=e,i[13]=t,i[14]=s),this}invert(){const e=this.elements,t=e[0],s=e[1],i=e[2],r=e[3],n=e[4],o=e[5],a=e[6],l=e[7],h=e[8],u=e[9],c=e[10],d=e[11],p=e[12],m=e[13],f=e[14],g=e[15],y=u*f*l-m*c*l+m*a*d-o*f*d-u*a*g+o*c*g,x=p*c*l-h*f*l-p*a*d+n*f*d+h*a*g-n*c*g,b=h*m*l-p*u*l+p*o*d-n*m*d-h*o*g+n*u*g,_=p*u*a-h*m*a-p*o*c+n*m*c+h*o*f-n*u*f,w=t*y+s*x+i*b+r*_;if(0===w)return this.set(0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0);const v=1/w;return e[0]=y*v,e[1]=(m*c*r-u*f*r-m*i*d+s*f*d+u*i*g-s*c*g)*v,e[2]=(o*f*r-m*a*r+m*i*l-s*f*l-o*i*g+s*a*g)*v,e[3]=(u*a*r-o*c*r-u*i*l+s*c*l+o*i*d-s*a*d)*v,e[4]=x*v,e[5]=(h*f*r-p*c*r+p*i*d-t*f*d-h*i*g+t*c*g)*v,e[6]=(p*a*r-n*f*r-p*i*l+t*f*l+n*i*g-t*a*g)*v,e[7]=(n*c*r-h*a*r+h*i*l-t*c*l-n*i*d+t*a*d)*v,e[8]=b*v,e[9]=(p*u*r-h*m*r-p*s*d+t*m*d+h*s*g-t*u*g)*v,e[10]=(n*m*r-p*o*r+p*s*l-t*m*l-n*s*g+t*o*g)*v,e[11]=(h*o*r-n*u*r-h*s*l+t*u*l+n*s*d-t*o*d)*v,e[12]=_*v,e[13]=(h*m*i-p*u*i+p*s*c-t*m*c-h*s*f+t*u*f)*v,e[14]=(p*o*i-n*m*i-p*s*a+t*m*a+n*s*f-t*o*f)*v,e[15]=(n*u*i-h*o*i+h*s*a-t*u*a-n*s*c+t*o*c)*v,this}scale(e){const t=this.elements,s=e.x,i=e.y,r=e.z;return t[0]*=s,t[4]*=i,t[8]*=r,t[1]*=s,t[5]*=i,t[9]*=r,t[2]*=s,t[6]*=i,t[10]*=r,t[3]*=s,t[7]*=i,t[11]*=r,this}getMaxScaleOnAxis(){const e=this.elements,t=e[0]*e[0]+e[1]*e[1]+e[2]*e[2],s=e[4]*e[4]+e[5]*e[5]+e[6]*e[6],i=e[8]*e[8]+e[9]*e[9]+e[10]*e[10];return Math.sqrt(Math.max(t,s,i))}makeTranslation(e,t,s){return e.isVector3?this.set(1,0,0,e.x,0,1,0,e.y,0,0,1,e.z,0,0,0,1):this.set(1,0,0,e,0,1,0,t,0,0,1,s,0,0,0,1),this}makeRotationX(e){const t=Math.cos(e),s=Math.sin(e);return this.set(1,0,0,0,0,t,-s,0,0,s,t,0,0,0,0,1),this}makeRotationY(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,0,s,0,0,1,0,0,-s,0,t,0,0,0,0,1),this}makeRotationZ(e){const t=Math.cos(e),s=Math.sin(e);return this.set(t,-s,0,0,s,t,0,0,0,0,1,0,0,0,0,1),this}makeRotationAxis(e,t){const s=Math.cos(t),i=Math.sin(t),r=1-s,n=e.x,o=e.y,a=e.z,l=r*n,h=r*o;return this.set(l*n+s,l*o-i*a,l*a+i*o,0,l*o+i*a,h*o+s,h*a-i*n,0,l*a-i*o,h*a+i*n,r*a*a+s,0,0,0,0,1),this}makeScale(e,t,s){return this.set(e,0,0,0,0,t,0,0,0,0,s,0,0,0,0,1),this}makeShear(e,t,s,i,r,n){return this.set(1,s,r,0,e,1,n,0,t,i,1,0,0,0,0,1),this}compose(e,t,s){const i=this.elements,r=t._x,n=t._y,o=t._z,a=t._w,l=r+r,h=n+n,u=o+o,c=r*l,d=r*h,p=r*u,m=n*h,f=n*u,g=o*u,y=a*l,x=a*h,b=a*u,_=s.x,w=s.y,v=s.z;return i[0]=(1-(m+g))*_,i[1]=(d+b)*_,i[2]=(p-x)*_,i[3]=0,i[4]=(d-b)*w,i[5]=(1-(c+g))*w,i[6]=(f+y)*w,i[7]=0,i[8]=(p+x)*v,i[9]=(f-y)*v,i[10]=(1-(c+m))*v,i[11]=0,i[12]=e.x,i[13]=e.y,i[14]=e.z,i[15]=1,this}decompose(e,t,s){const i=this.elements;if(e.x=i[12],e.y=i[13],e.z=i[14],0===this.determinant())return s.set(1,1,1),t.identity(),this;let r=hl.set(i[0],i[1],i[2]).length();const n=hl.set(i[4],i[5],i[6]).length(),o=hl.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),ul.copy(this);const a=1/r,l=1/n,h=1/o;return ul.elements[0]*=a,ul.elements[1]*=a,ul.elements[2]*=a,ul.elements[4]*=l,ul.elements[5]*=l,ul.elements[6]*=l,ul.elements[8]*=h,ul.elements[9]*=h,ul.elements[10]*=h,t.setFromRotationMatrix(ul),s.x=r,s.y=n,s.z=o,this}makePerspective(e,t,s,i,r,n,o=2e3,a=!1){const l=this.elements,h=2*r/(t-e),u=2*r/(s-i),c=(t+e)/(t-e),d=(s+i)/(s-i);let p,m;if(a)p=r/(n-r),m=n*r/(n-r);else if(o===ko)p=-(n+r)/(n-r),m=-2*n*r/(n-r);else{if(o!==Uo)throw new Error("THREE.Matrix4.makePerspective(): Invalid coordinate system: "+o);p=-n/(n-r),m=-n*r/(n-r)}return l[0]=h,l[4]=0,l[8]=c,l[12]=0,l[1]=0,l[5]=u,l[9]=d,l[13]=0,l[2]=0,l[6]=0,l[10]=p,l[14]=m,l[3]=0,l[7]=0,l[11]=-1,l[15]=0,this}makeOrthographic(e,t,s,i,r,n,o=2e3,a=!1){const l=this.elements,h=2/(t-e),u=2/(s-i),c=-(t+e)/(t-e),d=-(s+i)/(s-i);let p,m;if(a)p=1/(n-r),m=n/(n-r);else if(o===ko)p=-2/(n-r),m=-(n+r)/(n-r);else{if(o!==Uo)throw new Error("THREE.Matrix4.makeOrthographic(): Invalid coordinate system: "+o);p=-1/(n-r),m=-r/(n-r)}return l[0]=h,l[4]=0,l[8]=0,l[12]=c,l[1]=0,l[5]=u,l[9]=0,l[13]=d,l[2]=0,l[6]=0,l[10]=p,l[14]=m,l[3]=0,l[7]=0,l[11]=0,l[15]=1,this}equals(e){const t=this.elements,s=e.elements;for(let e=0;e<16;e++)if(t[e]!==s[e])return!1;return!0}fromArray(e,t=0){for(let s=0;s<16;s++)this.elements[s]=e[s+t];return this}toArray(e=[],t=0){const s=this.elements;return e[t]=s[0],e[t+1]=s[1],e[t+2]=s[2],e[t+3]=s[3],e[t+4]=s[4],e[t+5]=s[5],e[t+6]=s[6],e[t+7]=s[7],e[t+8]=s[8],e[t+9]=s[9],e[t+10]=s[10],e[t+11]=s[11],e[t+12]=s[12],e[t+13]=s[13],e[t+14]=s[14],e[t+15]=s[15],e}}const hl=new da,ul=new ll,cl=new da(0,0,0),dl=new da(1,1,1),pl=new da,ml=new da,fl=new da,gl=new ll,yl=new ca;class xl{constructor(e=0,t=0,s=0,i=xl.DEFAULT_ORDER){this.isEuler=!0,this._x=e,this._y=t,this._z=s,this._order=i}get x(){return this._x}set x(e){this._x=e,this._onChangeCallback()}get y(){return this._y}set y(e){this._y=e,this._onChangeCallback()}get z(){return this._z}set z(e){this._z=e,this._onChangeCallback()}get order(){return this._order}set order(e){this._order=e,this._onChangeCallback()}set(e,t,s,i=this._order){return this._x=e,this._y=t,this._z=s,this._order=i,this._onChangeCallback(),this}clone(){return new this.constructor(this._x,this._y,this._z,this._order)}copy(e){return this._x=e._x,this._y=e._y,this._z=e._z,this._order=e._order,this._onChangeCallback(),this}setFromRotationMatrix(e,t=this._order,s=!0){const i=e.elements,r=i[0],n=i[4],o=i[8],a=i[1],l=i[5],h=i[9],u=i[2],c=i[6],d=i[10];switch(t){case"XYZ":this._y=Math.asin(ra(o,-1,1)),Math.abs(o)<.9999999?(this._x=Math.atan2(-h,d),this._z=Math.atan2(-n,r)):(this._x=Math.atan2(c,l),this._z=0);break;case"YXZ":this._x=Math.asin(-ra(h,-1,1)),Math.abs(h)<.9999999?(this._y=Math.atan2(o,d),this._z=Math.atan2(a,l)):(this._y=Math.atan2(-u,r),this._z=0);break;case"ZXY":this._x=Math.asin(ra(c,-1,1)),Math.abs(c)<.9999999?(this._y=Math.atan2(-u,d),this._z=Math.atan2(-n,l)):(this._y=0,this._z=Math.atan2(a,r));break;case"ZYX":this._y=Math.asin(-ra(u,-1,1)),Math.abs(u)<.9999999?(this._x=Math.atan2(c,d),this._z=Math.atan2(a,r)):(this._x=0,this._z=Math.atan2(-n,l));break;case"YZX":this._z=Math.asin(ra(a,-1,1)),Math.abs(a)<.9999999?(this._x=Math.atan2(-h,l),this._y=Math.atan2(-u,r)):(this._x=0,this._y=Math.atan2(o,d));break;case"XZY":this._z=Math.asin(-ra(n,-1,1)),Math.abs(n)<.9999999?(this._x=Math.atan2(c,l),this._y=Math.atan2(o,r)):(this._x=Math.atan2(-h,d),this._y=0);break;default:Yo("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===s&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return gl.makeRotationFromQuaternion(e),this.setFromRotationMatrix(gl,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return yl.setFromEuler(this),this.setFromQuaternion(yl,e)}equals(e){return e._x===this._x&&e._y===this._y&&e._z===this._z&&e._order===this._order}fromArray(e){return this._x=e[0],this._y=e[1],this._z=e[2],void 0!==e[3]&&(this._order=e[3]),this._onChangeCallback(),this}toArray(e=[],t=0){return e[t]=this._x,e[t+1]=this._y,e[t+2]=this._z,e[t+3]=this._order,e}_onChange(e){return this._onChangeCallback=e,this}_onChangeCallback(){}*[Symbol.iterator](){yield this._x,yield this._y,yield this._z,yield this._order}}xl.DEFAULT_ORDER="XYZ";class bl{constructor(){this.mask=1}set(e){this.mask=1<<e>>>0}enable(e){this.mask|=1<<e}enableAll(){this.mask=-1}toggle(e){this.mask^=1<<e}disable(e){this.mask&=~(1<<e)}disableAll(){this.mask=0}test(e){return 0!==(this.mask&e.mask)}isEnabled(e){return!!(this.mask&1<<e)}}let _l=0;const wl=new da,vl=new ca,Tl=new ll,Sl=new da,Ml=new da,Al=new da,Nl=new ca,El=new da(1,0,0),Cl=new da(0,1,0),Rl=new da(0,0,1),Pl={type:"added"},Bl={type:"removed"},Il={type:"childadded",child:null},Dl={type:"childremoved",child:null};class Ll extends Ko{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:_l++}),this.uuid=ia(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Ll.DEFAULT_UP.clone();const e=new da,t=new xl,s=new ca,i=new da(1,1,1);t._onChange(function(){s.setFromEuler(t,!1)}),s._onChange(function(){t.setFromQuaternion(s,void 0,!1)}),Object.defineProperties(this,{position:{configurable:!0,enumerable:!0,value:e},rotation:{configurable:!0,enumerable:!0,value:t},quaternion:{configurable:!0,enumerable:!0,value:s},scale:{configurable:!0,enumerable:!0,value:i},modelViewMatrix:{value:new ll},normalMatrix:{value:new fa}}),this.matrix=new ll,this.matrixWorld=new ll,this.matrixAutoUpdate=Ll.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Ll.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new bl,this.visible=!0,this.castShadow=!1,this.receiveShadow=!1,this.frustumCulled=!0,this.renderOrder=0,this.animations=[],this.customDepthMaterial=void 0,this.customDistanceMaterial=void 0,this.userData={}}onBeforeShadow(){}onAfterShadow(){}onBeforeRender(){}onAfterRender(){}applyMatrix4(e){this.matrixAutoUpdate&&this.updateMatrix(),this.matrix.premultiply(e),this.matrix.decompose(this.position,this.quaternion,this.scale)}applyQuaternion(e){return this.quaternion.premultiply(e),this}setRotationFromAxisAngle(e,t){this.quaternion.setFromAxisAngle(e,t)}setRotationFromEuler(e){this.quaternion.setFromEuler(e,!0)}setRotationFromMatrix(e){this.quaternion.setFromRotationMatrix(e)}setRotationFromQuaternion(e){this.quaternion.copy(e)}rotateOnAxis(e,t){return vl.setFromAxisAngle(e,t),this.quaternion.multiply(vl),this}rotateOnWorldAxis(e,t){return vl.setFromAxisAngle(e,t),this.quaternion.premultiply(vl),this}rotateX(e){return this.rotateOnAxis(El,e)}rotateY(e){return this.rotateOnAxis(Cl,e)}rotateZ(e){return this.rotateOnAxis(Rl,e)}translateOnAxis(e,t){return wl.copy(e).applyQuaternion(this.quaternion),this.position.add(wl.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(El,e)}translateY(e){return this.translateOnAxis(Cl,e)}translateZ(e){return this.translateOnAxis(Rl,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(Tl.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?Sl.copy(e):Sl.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),Ml.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?Tl.lookAt(Ml,Sl,this.up):Tl.lookAt(Sl,Ml,this.up),this.quaternion.setFromRotationMatrix(Tl),i&&(Tl.extractRotation(i.matrixWorld),vl.setFromRotationMatrix(Tl),this.quaternion.premultiply(vl.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(Zo("Object3D.add: object can't be added as a child of itself.",e),this):(e&&e.isObject3D?(e.removeFromParent(),e.parent=this,this.children.push(e),e.dispatchEvent(Pl),Il.child=e,this.dispatchEvent(Il),Il.child=null):Zo("Object3D.add: object not an instance of THREE.Object3D.",e),this)}remove(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.remove(arguments[e]);return this}const t=this.children.indexOf(e);return-1!==t&&(e.parent=null,this.children.splice(t,1),e.dispatchEvent(Bl),Dl.child=e,this.dispatchEvent(Dl),Dl.child=null),this}removeFromParent(){const e=this.parent;return null!==e&&e.remove(this),this}clear(){return this.remove(...this.children)}attach(e){return this.updateWorldMatrix(!0,!1),Tl.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),Tl.multiply(e.parent.matrixWorld)),e.applyMatrix4(Tl),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Pl),Il.child=e,this.dispatchEvent(Il),Il.child=null,this}getObjectById(e){return this.getObjectByProperty("id",e)}getObjectByName(e){return this.getObjectByProperty("name",e)}getObjectByProperty(e,t){if(this[e]===t)return this;for(let s=0,i=this.children.length;s<i;s++){const i=this.children[s].getObjectByProperty(e,t);if(void 0!==i)return i}}getObjectsByProperty(e,t,s=[]){this[e]===t&&s.push(this);const i=this.children;for(let r=0,n=i.length;r<n;r++)i[r].getObjectsByProperty(e,t,s);return s}getWorldPosition(e){return this.updateWorldMatrix(!0,!1),e.setFromMatrixPosition(this.matrixWorld)}getWorldQuaternion(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ml,e,Al),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(Ml,Nl,e),e}getWorldDirection(e){this.updateWorldMatrix(!0,!1);const t=this.matrixWorld.elements;return e.set(t[8],t[9],t[10]).normalize()}raycast(){}traverse(e){e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverse(e)}traverseVisible(e){if(!1===this.visible)return;e(this);const t=this.children;for(let s=0,i=t.length;s<i;s++)t[s].traverseVisible(e)}traverseAncestors(e){const t=this.parent;null!==t&&(e(t),t.traverseAncestors(e))}updateMatrix(){this.matrix.compose(this.position,this.quaternion,this.scale),this.matrixWorldNeedsUpdate=!0}updateMatrixWorld(e){this.matrixAutoUpdate&&this.updateMatrix(),(this.matrixWorldNeedsUpdate||e)&&(!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),this.matrixWorldNeedsUpdate=!1,e=!0);const t=this.children;for(let s=0,i=t.length;s<i;s++){t[s].updateMatrixWorld(e)}}updateWorldMatrix(e,t){const s=this.parent;if(!0===e&&null!==s&&s.updateWorldMatrix(!0,!1),this.matrixAutoUpdate&&this.updateMatrix(),!0===this.matrixWorldAutoUpdate&&(null===this.parent?this.matrixWorld.copy(this.matrix):this.matrixWorld.multiplyMatrices(this.parent.matrixWorld,this.matrix)),!0===t){const e=this.children;for(let t=0,s=e.length;t<s;t++){e[t].updateWorldMatrix(!1,!0)}}}toJSON(e){const t=void 0===e||"string"==typeof e,s={};t&&(e={geometries:{},materials:{},textures:{},images:{},shapes:{},skeletons:{},animations:{},nodes:{}},s.metadata={version:4.7,type:"Object",generator:"Object3D.toJSON"});const i={};function r(t,s){return void 0===t[s.uuid]&&(t[s.uuid]=s.toJSON(e)),s.uuid}if(i.uuid=this.uuid,i.type=this.type,""!==this.name&&(i.name=this.name),!0===this.castShadow&&(i.castShadow=!0),!0===this.receiveShadow&&(i.receiveShadow=!0),!1===this.visible&&(i.visible=!1),!1===this.frustumCulled&&(i.frustumCulled=!1),0!==this.renderOrder&&(i.renderOrder=this.renderOrder),Object.keys(this.userData).length>0&&(i.userData=this.userData),i.layers=this.layers.mask,i.matrix=this.matrix.toArray(),i.up=this.up.toArray(),!1===this.matrixAutoUpdate&&(i.matrixAutoUpdate=!1),this.isInstancedMesh&&(i.type="InstancedMesh",i.count=this.count,i.instanceMatrix=this.instanceMatrix.toJSON(),null!==this.instanceColor&&(i.instanceColor=this.instanceColor.toJSON())),this.isBatchedMesh&&(i.type="BatchedMesh",i.perObjectFrustumCulled=this.perObjectFrustumCulled,i.sortObjects=this.sortObjects,i.drawRanges=this._drawRanges,i.reservedRanges=this._reservedRanges,i.geometryInfo=this._geometryInfo.map(e=>({...e,boundingBox:e.boundingBox?e.boundingBox.toJSON():void 0,boundingSphere:e.boundingSphere?e.boundingSphere.toJSON():void 0})),i.instanceInfo=this._instanceInfo.map(e=>({...e})),i.availableInstanceIds=this._availableInstanceIds.slice(),i.availableGeometryIds=this._availableGeometryIds.slice(),i.nextIndexStart=this._nextIndexStart,i.nextVertexStart=this._nextVertexStart,i.geometryCount=this._geometryCount,i.maxInstanceCount=this._maxInstanceCount,i.maxVertexCount=this._maxVertexCount,i.maxIndexCount=this._maxIndexCount,i.geometryInitialized=this._geometryInitialized,i.matricesTexture=this._matricesTexture.toJSON(e),i.indirectTexture=this._indirectTexture.toJSON(e),null!==this._colorsTexture&&(i.colorsTexture=this._colorsTexture.toJSON(e)),null!==this.boundingSphere&&(i.boundingSphere=this.boundingSphere.toJSON()),null!==this.boundingBox&&(i.boundingBox=this.boundingBox.toJSON())),this.isScene)this.background&&(this.background.isColor?i.background=this.background.toJSON():this.background.isTexture&&(i.background=this.background.toJSON(e).uuid)),this.environment&&this.environment.isTexture&&!0!==this.environment.isRenderTargetTexture&&(i.environment=this.environment.toJSON(e).uuid);else if(this.isMesh||this.isLine||this.isPoints){i.geometry=r(e.geometries,this.geometry);const t=this.geometry.parameters;if(void 0!==t&&void 0!==t.shapes){const s=t.shapes;if(Array.isArray(s))for(let t=0,i=s.length;t<i;t++){const i=s[t];r(e.shapes,i)}else r(e.shapes,s)}}if(this.isSkinnedMesh&&(i.bindMode=this.bindMode,i.bindMatrix=this.bindMatrix.toArray(),void 0!==this.skeleton&&(r(e.skeletons,this.skeleton),i.skeleton=this.skeleton.uuid)),void 0!==this.material)if(Array.isArray(this.material)){const t=[];for(let s=0,i=this.material.length;s<i;s++)t.push(r(e.materials,this.material[s]));i.material=t}else i.material=r(e.materials,this.material);if(this.children.length>0){i.children=[];for(let t=0;t<this.children.length;t++)i.children.push(this.children[t].toJSON(e).object)}if(this.animations.length>0){i.animations=[];for(let t=0;t<this.animations.length;t++){const s=this.animations[t];i.animations.push(r(e.animations,s))}}if(t){const t=n(e.geometries),i=n(e.materials),r=n(e.textures),o=n(e.images),a=n(e.shapes),l=n(e.skeletons),h=n(e.animations),u=n(e.nodes);t.length>0&&(s.geometries=t),i.length>0&&(s.materials=i),r.length>0&&(s.textures=r),o.length>0&&(s.images=o),a.length>0&&(s.shapes=a),l.length>0&&(s.skeletons=l),h.length>0&&(s.animations=h),u.length>0&&(s.nodes=u)}return s.object=i,s;function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}}clone(e){return(new this.constructor).copy(this,e)}copy(e,t=!0){if(this.name=e.name,this.up.copy(e.up),this.position.copy(e.position),this.rotation.order=e.rotation.order,this.quaternion.copy(e.quaternion),this.scale.copy(e.scale),this.matrix.copy(e.matrix),this.matrixWorld.copy(e.matrixWorld),this.matrixAutoUpdate=e.matrixAutoUpdate,this.matrixWorldAutoUpdate=e.matrixWorldAutoUpdate,this.matrixWorldNeedsUpdate=e.matrixWorldNeedsUpdate,this.layers.mask=e.layers.mask,this.visible=e.visible,this.castShadow=e.castShadow,this.receiveShadow=e.receiveShadow,this.frustumCulled=e.frustumCulled,this.renderOrder=e.renderOrder,this.animations=e.animations.slice(),this.userData=JSON.parse(JSON.stringify(e.userData)),!0===t)for(let t=0;t<e.children.length;t++){const s=e.children[t];this.add(s.clone())}return this}}Ll.DEFAULT_UP=new da(0,1,0),Ll.DEFAULT_MATRIX_AUTO_UPDATE=!0,Ll.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Fl=new da,Ol=new da,Vl=new da,zl=new da,kl=new da,Ul=new da,Gl=new da,jl=new da,$l=new da,Wl=new da,Hl=new Pa,ql=new Pa,Xl=new Pa;class Yl{constructor(e=new da,t=new da,s=new da){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),Fl.subVectors(e,t),i.cross(Fl);const r=i.lengthSq();return r>0?i.multiplyScalar(1/Math.sqrt(r)):i.set(0,0,0)}static getBarycoord(e,t,s,i,r){Fl.subVectors(i,t),Ol.subVectors(s,t),Vl.subVectors(e,t);const n=Fl.dot(Fl),o=Fl.dot(Ol),a=Fl.dot(Vl),l=Ol.dot(Ol),h=Ol.dot(Vl),u=n*l-o*o;if(0===u)return r.set(0,0,0),null;const c=1/u,d=(l*a-o*h)*c,p=(n*h-o*a)*c;return r.set(1-d-p,p,d)}static containsPoint(e,t,s,i){return null!==this.getBarycoord(e,t,s,i,zl)&&(zl.x>=0&&zl.y>=0&&zl.x+zl.y<=1)}static getInterpolation(e,t,s,i,r,n,o,a){return null===this.getBarycoord(e,t,s,i,zl)?(a.x=0,a.y=0,"z"in a&&(a.z=0),"w"in a&&(a.w=0),null):(a.setScalar(0),a.addScaledVector(r,zl.x),a.addScaledVector(n,zl.y),a.addScaledVector(o,zl.z),a)}static getInterpolatedAttribute(e,t,s,i,r,n){return Hl.setScalar(0),ql.setScalar(0),Xl.setScalar(0),Hl.fromBufferAttribute(e,t),ql.fromBufferAttribute(e,s),Xl.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(Hl,r.x),n.addScaledVector(ql,r.y),n.addScaledVector(Xl,r.z),n}static isFrontFacing(e,t,s,i){return Fl.subVectors(s,t),Ol.subVectors(e,t),Fl.cross(Ol).dot(i)<0}set(e,t,s){return this.a.copy(e),this.b.copy(t),this.c.copy(s),this}setFromPointsAndIndices(e,t,s,i){return this.a.copy(e[t]),this.b.copy(e[s]),this.c.copy(e[i]),this}setFromAttributeAndIndices(e,t,s,i){return this.a.fromBufferAttribute(e,t),this.b.fromBufferAttribute(e,s),this.c.fromBufferAttribute(e,i),this}clone(){return(new this.constructor).copy(this)}copy(e){return this.a.copy(e.a),this.b.copy(e.b),this.c.copy(e.c),this}getArea(){return Fl.subVectors(this.c,this.b),Ol.subVectors(this.a,this.b),.5*Fl.cross(Ol).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Yl.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Yl.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return Yl.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return Yl.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Yl.isFrontFacing(this.a,this.b,this.c,e)}intersectsBox(e){return e.intersectsTriangle(this)}closestPointToPoint(e,t){const s=this.a,i=this.b,r=this.c;let n,o;kl.subVectors(i,s),Ul.subVectors(r,s),jl.subVectors(e,s);const a=kl.dot(jl),l=Ul.dot(jl);if(a<=0&&l<=0)return t.copy(s);$l.subVectors(e,i);const h=kl.dot($l),u=Ul.dot($l);if(h>=0&&u<=h)return t.copy(i);const c=a*u-h*l;if(c<=0&&a>=0&&h<=0)return n=a/(a-h),t.copy(s).addScaledVector(kl,n);Wl.subVectors(e,r);const d=kl.dot(Wl),p=Ul.dot(Wl);if(p>=0&&d<=p)return t.copy(r);const m=d*l-a*p;if(m<=0&&l>=0&&p<=0)return o=l/(l-p),t.copy(s).addScaledVector(Ul,o);const f=h*p-d*u;if(f<=0&&u-h>=0&&d-p>=0)return Gl.subVectors(r,i),o=(u-h)/(u-h+(d-p)),t.copy(i).addScaledVector(Gl,o);const g=1/(f+m+c);return n=m*g,o=c*g,t.copy(s).addScaledVector(kl,n).addScaledVector(Ul,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Zl={aliceblue:15792383,antiquewhite:16444375,aqua:65535,aquamarine:8388564,azure:15794175,beige:16119260,bisque:16770244,black:0,blanchedalmond:16772045,blue:255,blueviolet:9055202,brown:10824234,burlywood:14596231,cadetblue:6266528,chartreuse:8388352,chocolate:13789470,coral:16744272,cornflowerblue:6591981,cornsilk:16775388,crimson:14423100,cyan:65535,darkblue:139,darkcyan:35723,darkgoldenrod:12092939,darkgray:11119017,darkgreen:25600,darkgrey:11119017,darkkhaki:12433259,darkmagenta:9109643,darkolivegreen:5597999,darkorange:16747520,darkorchid:10040012,darkred:9109504,darksalmon:15308410,darkseagreen:9419919,darkslateblue:4734347,darkslategray:3100495,darkslategrey:3100495,darkturquoise:52945,darkviolet:9699539,deeppink:16716947,deepskyblue:49151,dimgray:6908265,dimgrey:6908265,dodgerblue:2003199,firebrick:11674146,floralwhite:16775920,forestgreen:2263842,fuchsia:16711935,gainsboro:14474460,ghostwhite:16316671,gold:16766720,goldenrod:14329120,gray:8421504,green:32768,greenyellow:11403055,grey:8421504,honeydew:15794160,hotpink:16738740,indianred:13458524,indigo:4915330,ivory:16777200,khaki:15787660,lavender:15132410,lavenderblush:16773365,lawngreen:8190976,lemonchiffon:16775885,lightblue:11393254,lightcoral:15761536,lightcyan:14745599,lightgoldenrodyellow:16448210,lightgray:13882323,lightgreen:9498256,lightgrey:13882323,lightpink:16758465,lightsalmon:16752762,lightseagreen:2142890,lightskyblue:8900346,lightslategray:7833753,lightslategrey:7833753,lightsteelblue:11584734,lightyellow:16777184,lime:65280,limegreen:3329330,linen:16445670,magenta:16711935,maroon:8388608,mediumaquamarine:6737322,mediumblue:205,mediumorchid:12211667,mediumpurple:9662683,mediumseagreen:3978097,mediumslateblue:8087790,mediumspringgreen:64154,mediumturquoise:4772300,mediumvioletred:13047173,midnightblue:1644912,mintcream:16121850,mistyrose:16770273,moccasin:16770229,navajowhite:16768685,navy:128,oldlace:16643558,olive:8421376,olivedrab:7048739,orange:16753920,orangered:16729344,orchid:14315734,palegoldenrod:15657130,palegreen:10025880,paleturquoise:11529966,palevioletred:14381203,papayawhip:16773077,peachpuff:16767673,peru:13468991,pink:16761035,plum:14524637,powderblue:11591910,purple:8388736,rebeccapurple:6697881,red:16711680,rosybrown:12357519,royalblue:4286945,saddlebrown:9127187,salmon:16416882,sandybrown:16032864,seagreen:3050327,seashell:16774638,sienna:10506797,silver:12632256,skyblue:8900331,slateblue:6970061,slategray:7372944,slategrey:7372944,snow:16775930,springgreen:65407,steelblue:4620980,tan:13808780,teal:32896,thistle:14204888,tomato:16737095,turquoise:4251856,violet:15631086,wheat:16113331,white:16777215,whitesmoke:16119285,yellow:16776960,yellowgreen:10145074},Ql={h:0,s:0,l:0},Kl={h:0,s:0,l:0};function Jl(e,t,s){return s<0&&(s+=1),s>1&&(s-=1),s<1/6?e+6*(t-e)*s:s<.5?t:s<2/3?e+6*(t-e)*(2/3-s):e}class eh{constructor(e,t,s){return this.isColor=!0,this.r=1,this.g=1,this.b=1,this.set(e,t,s)}set(e,t,s){if(void 0===t&&void 0===s){const t=e;t&&t.isColor?this.copy(t):"number"==typeof t?this.setHex(t):"string"==typeof t&&this.setStyle(t)}else this.setRGB(e,t,s);return this}setScalar(e){return this.r=e,this.g=e,this.b=e,this}setHex(e,t=Mo){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,_a.colorSpaceToWorking(this,t),this}setRGB(e,t,s,i=_a.workingColorSpace){return this.r=e,this.g=t,this.b=s,_a.colorSpaceToWorking(this,i),this}setHSL(e,t,s,i=_a.workingColorSpace){if(e=na(e,1),t=ra(t,0,1),s=ra(s,0,1),0===t)this.r=this.g=this.b=s;else{const i=s<=.5?s*(1+t):s+t-s*t,r=2*s-i;this.r=Jl(r,i,e+1/3),this.g=Jl(r,i,e),this.b=Jl(r,i,e-1/3)}return _a.colorSpaceToWorking(this,i),this}setStyle(e,t=Mo){function s(t){void 0!==t&&parseFloat(t)<1&&Yo("Color: Alpha component of "+e+" will be ignored.")}let i;if(i=/^(\w+)\(([^\)]*)\)/.exec(e)){let r;const n=i[1],o=i[2];switch(n){case"rgb":case"rgba":if(r=/^\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(255,parseInt(r[1],10))/255,Math.min(255,parseInt(r[2],10))/255,Math.min(255,parseInt(r[3],10))/255,t);if(r=/^\s*(\d+)\%\s*,\s*(\d+)\%\s*,\s*(\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setRGB(Math.min(100,parseInt(r[1],10))/100,Math.min(100,parseInt(r[2],10))/100,Math.min(100,parseInt(r[3],10))/100,t);break;case"hsl":case"hsla":if(r=/^\s*(\d*\.?\d+)\s*,\s*(\d*\.?\d+)\%\s*,\s*(\d*\.?\d+)\%\s*(?:,\s*(\d*\.?\d+)\s*)?$/.exec(o))return s(r[4]),this.setHSL(parseFloat(r[1])/360,parseFloat(r[2])/100,parseFloat(r[3])/100,t);break;default:Yo("Color: Unknown color model "+e)}}else if(i=/^\#([A-Fa-f\d]+)$/.exec(e)){const s=i[1],r=s.length;if(3===r)return this.setRGB(parseInt(s.charAt(0),16)/15,parseInt(s.charAt(1),16)/15,parseInt(s.charAt(2),16)/15,t);if(6===r)return this.setHex(parseInt(s,16),t);Yo("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=Mo){const s=Zl[e.toLowerCase()];return void 0!==s?this.setHex(s,t):Yo("Color: Unknown color "+e),this}clone(){return new this.constructor(this.r,this.g,this.b)}copy(e){return this.r=e.r,this.g=e.g,this.b=e.b,this}copySRGBToLinear(e){return this.r=wa(e.r),this.g=wa(e.g),this.b=wa(e.b),this}copyLinearToSRGB(e){return this.r=va(e.r),this.g=va(e.g),this.b=va(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=Mo){return _a.workingToColorSpace(th.copy(this),e),65536*Math.round(ra(255*th.r,0,255))+256*Math.round(ra(255*th.g,0,255))+Math.round(ra(255*th.b,0,255))}getHexString(e=Mo){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=_a.workingColorSpace){_a.workingToColorSpace(th.copy(this),t);const s=th.r,i=th.g,r=th.b,n=Math.max(s,i,r),o=Math.min(s,i,r);let a,l;const h=(o+n)/2;if(o===n)a=0,l=0;else{const e=n-o;switch(l=h<=.5?e/(n+o):e/(2-n-o),n){case s:a=(i-r)/e+(i<r?6:0);break;case i:a=(r-s)/e+2;break;case r:a=(s-i)/e+4}a/=6}return e.h=a,e.s=l,e.l=h,e}getRGB(e,t=_a.workingColorSpace){return _a.workingToColorSpace(th.copy(this),t),e.r=th.r,e.g=th.g,e.b=th.b,e}getStyle(e=Mo){_a.workingToColorSpace(th.copy(this),e);const t=th.r,s=th.g,i=th.b;return e!==Mo?`color(${e} ${t.toFixed(3)} ${s.toFixed(3)} ${i.toFixed(3)})`:`rgb(${Math.round(255*t)},${Math.round(255*s)},${Math.round(255*i)})`}offsetHSL(e,t,s){return this.getHSL(Ql),this.setHSL(Ql.h+e,Ql.s+t,Ql.l+s)}add(e){return this.r+=e.r,this.g+=e.g,this.b+=e.b,this}addColors(e,t){return this.r=e.r+t.r,this.g=e.g+t.g,this.b=e.b+t.b,this}addScalar(e){return this.r+=e,this.g+=e,this.b+=e,this}sub(e){return this.r=Math.max(0,this.r-e.r),this.g=Math.max(0,this.g-e.g),this.b=Math.max(0,this.b-e.b),this}multiply(e){return this.r*=e.r,this.g*=e.g,this.b*=e.b,this}multiplyScalar(e){return this.r*=e,this.g*=e,this.b*=e,this}lerp(e,t){return this.r+=(e.r-this.r)*t,this.g+=(e.g-this.g)*t,this.b+=(e.b-this.b)*t,this}lerpColors(e,t,s){return this.r=e.r+(t.r-e.r)*s,this.g=e.g+(t.g-e.g)*s,this.b=e.b+(t.b-e.b)*s,this}lerpHSL(e,t){this.getHSL(Ql),e.getHSL(Kl);const s=oa(Ql.h,Kl.h,t),i=oa(Ql.s,Kl.s,t),r=oa(Ql.l,Kl.l,t);return this.setHSL(s,i,r),this}setFromVector3(e){return this.r=e.x,this.g=e.y,this.b=e.z,this}applyMatrix3(e){const t=this.r,s=this.g,i=this.b,r=e.elements;return this.r=r[0]*t+r[3]*s+r[6]*i,this.g=r[1]*t+r[4]*s+r[7]*i,this.b=r[2]*t+r[5]*s+r[8]*i,this}equals(e){return e.r===this.r&&e.g===this.g&&e.b===this.b}fromArray(e,t=0){return this.r=e[t],this.g=e[t+1],this.b=e[t+2],this}toArray(e=[],t=0){return e[t]=this.r,e[t+1]=this.g,e[t+2]=this.b,e}fromBufferAttribute(e,t){return this.r=e.getX(t),this.g=e.getY(t),this.b=e.getZ(t),this}toJSON(){return this.getHex()}*[Symbol.iterator](){yield this.r,yield this.g,yield this.b}}const th=new eh;eh.NAMES=Zl;let sh=0;class ih extends Ko{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:sh++}),this.uuid=ia(),this.name="",this.type="Material",this.blending=1,this.side=0,this.vertexColors=!1,this.opacity=1,this.transparent=!1,this.alphaHash=!1,this.blendSrc=sn,this.blendDst=rn,this.blendEquation=Yr,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new eh(0,0,0),this.blendAlpha=0,this.depthFunc=3,this.depthTest=!0,this.depthWrite=!0,this.stencilWriteMask=255,this.stencilFunc=519,this.stencilRef=0,this.stencilFuncMask=255,this.stencilFail=Co,this.stencilZFail=Co,this.stencilZPass=Co,this.stencilWrite=!1,this.clippingPlanes=null,this.clipIntersection=!1,this.clipShadows=!1,this.shadowSide=null,this.colorWrite=!0,this.precision=null,this.polygonOffset=!1,this.polygonOffsetFactor=0,this.polygonOffsetUnits=0,this.dithering=!1,this.alphaToCoverage=!1,this.premultipliedAlpha=!1,this.forceSinglePass=!1,this.allowOverride=!0,this.visible=!0,this.toneMapped=!0,this.userData={},this.version=0,this._alphaTest=0}get alphaTest(){return this._alphaTest}set alphaTest(e){this._alphaTest>0!=e>0&&this.version++,this._alphaTest=e}onBeforeRender(){}onBeforeCompile(){}customProgramCacheKey(){return this.onBeforeCompile.toString()}setValues(e){if(void 0!==e)for(const t in e){const s=e[t];if(void 0===s){Yo(`Material: parameter '${t}' has value of undefined.`);continue}const i=this[t];void 0!==i?i&&i.isColor?i.set(s):i&&i.isVector3&&s&&s.isVector3?i.copy(s):this[t]=s:Yo(`Material: '${t}' is not a property of THREE.${this.type}.`)}}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{}});const s={metadata:{version:4.7,type:"Material",generator:"Material.toJSON"}};function i(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(s.uuid=this.uuid,s.type=this.type,""!==this.name&&(s.name=this.name),this.color&&this.color.isColor&&(s.color=this.color.getHex()),void 0!==this.roughness&&(s.roughness=this.roughness),void 0!==this.metalness&&(s.metalness=this.metalness),void 0!==this.sheen&&(s.sheen=this.sheen),this.sheenColor&&this.sheenColor.isColor&&(s.sheenColor=this.sheenColor.getHex()),void 0!==this.sheenRoughness&&(s.sheenRoughness=this.sheenRoughness),this.emissive&&this.emissive.isColor&&(s.emissive=this.emissive.getHex()),void 0!==this.emissiveIntensity&&1!==this.emissiveIntensity&&(s.emissiveIntensity=this.emissiveIntensity),this.specular&&this.specular.isColor&&(s.specular=this.specular.getHex()),void 0!==this.specularIntensity&&(s.specularIntensity=this.specularIntensity),this.specularColor&&this.specularColor.isColor&&(s.specularColor=this.specularColor.getHex()),void 0!==this.shininess&&(s.shininess=this.shininess),void 0!==this.clearcoat&&(s.clearcoat=this.clearcoat),void 0!==this.clearcoatRoughness&&(s.clearcoatRoughness=this.clearcoatRoughness),this.clearcoatMap&&this.clearcoatMap.isTexture&&(s.clearcoatMap=this.clearcoatMap.toJSON(e).uuid),this.clearcoatRoughnessMap&&this.clearcoatRoughnessMap.isTexture&&(s.clearcoatRoughnessMap=this.clearcoatRoughnessMap.toJSON(e).uuid),this.clearcoatNormalMap&&this.clearcoatNormalMap.isTexture&&(s.clearcoatNormalMap=this.clearcoatNormalMap.toJSON(e).uuid,s.clearcoatNormalScale=this.clearcoatNormalScale.toArray()),this.sheenColorMap&&this.sheenColorMap.isTexture&&(s.sheenColorMap=this.sheenColorMap.toJSON(e).uuid),this.sheenRoughnessMap&&this.sheenRoughnessMap.isTexture&&(s.sheenRoughnessMap=this.sheenRoughnessMap.toJSON(e).uuid),void 0!==this.dispersion&&(s.dispersion=this.dispersion),void 0!==this.iridescence&&(s.iridescence=this.iridescence),void 0!==this.iridescenceIOR&&(s.iridescenceIOR=this.iridescenceIOR),void 0!==this.iridescenceThicknessRange&&(s.iridescenceThicknessRange=this.iridescenceThicknessRange),this.iridescenceMap&&this.iridescenceMap.isTexture&&(s.iridescenceMap=this.iridescenceMap.toJSON(e).uuid),this.iridescenceThicknessMap&&this.iridescenceThicknessMap.isTexture&&(s.iridescenceThicknessMap=this.iridescenceThicknessMap.toJSON(e).uuid),void 0!==this.anisotropy&&(s.anisotropy=this.anisotropy),void 0!==this.anisotropyRotation&&(s.anisotropyRotation=this.anisotropyRotation),this.anisotropyMap&&this.anisotropyMap.isTexture&&(s.anisotropyMap=this.anisotropyMap.toJSON(e).uuid),this.map&&this.map.isTexture&&(s.map=this.map.toJSON(e).uuid),this.matcap&&this.matcap.isTexture&&(s.matcap=this.matcap.toJSON(e).uuid),this.alphaMap&&this.alphaMap.isTexture&&(s.alphaMap=this.alphaMap.toJSON(e).uuid),this.lightMap&&this.lightMap.isTexture&&(s.lightMap=this.lightMap.toJSON(e).uuid,s.lightMapIntensity=this.lightMapIntensity),this.aoMap&&this.aoMap.isTexture&&(s.aoMap=this.aoMap.toJSON(e).uuid,s.aoMapIntensity=this.aoMapIntensity),this.bumpMap&&this.bumpMap.isTexture&&(s.bumpMap=this.bumpMap.toJSON(e).uuid,s.bumpScale=this.bumpScale),this.normalMap&&this.normalMap.isTexture&&(s.normalMap=this.normalMap.toJSON(e).uuid,s.normalMapType=this.normalMapType,s.normalScale=this.normalScale.toArray()),this.displacementMap&&this.displacementMap.isTexture&&(s.displacementMap=this.displacementMap.toJSON(e).uuid,s.displacementScale=this.displacementScale,s.displacementBias=this.displacementBias),this.roughnessMap&&this.roughnessMap.isTexture&&(s.roughnessMap=this.roughnessMap.toJSON(e).uuid),this.metalnessMap&&this.metalnessMap.isTexture&&(s.metalnessMap=this.metalnessMap.toJSON(e).uuid),this.emissiveMap&&this.emissiveMap.isTexture&&(s.emissiveMap=this.emissiveMap.toJSON(e).uuid),this.specularMap&&this.specularMap.isTexture&&(s.specularMap=this.specularMap.toJSON(e).uuid),this.specularIntensityMap&&this.specularIntensityMap.isTexture&&(s.specularIntensityMap=this.specularIntensityMap.toJSON(e).uuid),this.specularColorMap&&this.specularColorMap.isTexture&&(s.specularColorMap=this.specularColorMap.toJSON(e).uuid),this.envMap&&this.envMap.isTexture&&(s.envMap=this.envMap.toJSON(e).uuid,void 0!==this.combine&&(s.combine=this.combine)),void 0!==this.envMapRotation&&(s.envMapRotation=this.envMapRotation.toArray()),void 0!==this.envMapIntensity&&(s.envMapIntensity=this.envMapIntensity),void 0!==this.reflectivity&&(s.reflectivity=this.reflectivity),void 0!==this.refractionRatio&&(s.refractionRatio=this.refractionRatio),this.gradientMap&&this.gradientMap.isTexture&&(s.gradientMap=this.gradientMap.toJSON(e).uuid),void 0!==this.transmission&&(s.transmission=this.transmission),this.transmissionMap&&this.transmissionMap.isTexture&&(s.transmissionMap=this.transmissionMap.toJSON(e).uuid),void 0!==this.thickness&&(s.thickness=this.thickness),this.thicknessMap&&this.thicknessMap.isTexture&&(s.thicknessMap=this.thicknessMap.toJSON(e).uuid),void 0!==this.attenuationDistance&&this.attenuationDistance!==1/0&&(s.attenuationDistance=this.attenuationDistance),void 0!==this.attenuationColor&&(s.attenuationColor=this.attenuationColor.getHex()),void 0!==this.size&&(s.size=this.size),null!==this.shadowSide&&(s.shadowSide=this.shadowSide),void 0!==this.sizeAttenuation&&(s.sizeAttenuation=this.sizeAttenuation),1!==this.blending&&(s.blending=this.blending),0!==this.side&&(s.side=this.side),!0===this.vertexColors&&(s.vertexColors=!0),this.opacity<1&&(s.opacity=this.opacity),!0===this.transparent&&(s.transparent=!0),this.blendSrc!==sn&&(s.blendSrc=this.blendSrc),this.blendDst!==rn&&(s.blendDst=this.blendDst),this.blendEquation!==Yr&&(s.blendEquation=this.blendEquation),null!==this.blendSrcAlpha&&(s.blendSrcAlpha=this.blendSrcAlpha),null!==this.blendDstAlpha&&(s.blendDstAlpha=this.blendDstAlpha),null!==this.blendEquationAlpha&&(s.blendEquationAlpha=this.blendEquationAlpha),this.blendColor&&this.blendColor.isColor&&(s.blendColor=this.blendColor.getHex()),0!==this.blendAlpha&&(s.blendAlpha=this.blendAlpha),3!==this.depthFunc&&(s.depthFunc=this.depthFunc),!1===this.depthTest&&(s.depthTest=this.depthTest),!1===this.depthWrite&&(s.depthWrite=this.depthWrite),!1===this.colorWrite&&(s.colorWrite=this.colorWrite),255!==this.stencilWriteMask&&(s.stencilWriteMask=this.stencilWriteMask),519!==this.stencilFunc&&(s.stencilFunc=this.stencilFunc),0!==this.stencilRef&&(s.stencilRef=this.stencilRef),255!==this.stencilFuncMask&&(s.stencilFuncMask=this.stencilFuncMask),this.stencilFail!==Co&&(s.stencilFail=this.stencilFail),this.stencilZFail!==Co&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==Co&&(s.stencilZPass=this.stencilZPass),!0===this.stencilWrite&&(s.stencilWrite=this.stencilWrite),void 0!==this.rotation&&0!==this.rotation&&(s.rotation=this.rotation),!0===this.polygonOffset&&(s.polygonOffset=!0),0!==this.polygonOffsetFactor&&(s.polygonOffsetFactor=this.polygonOffsetFactor),0!==this.polygonOffsetUnits&&(s.polygonOffsetUnits=this.polygonOffsetUnits),void 0!==this.linewidth&&1!==this.linewidth&&(s.linewidth=this.linewidth),void 0!==this.dashSize&&(s.dashSize=this.dashSize),void 0!==this.gapSize&&(s.gapSize=this.gapSize),void 0!==this.scale&&(s.scale=this.scale),!0===this.dithering&&(s.dithering=!0),this.alphaTest>0&&(s.alphaTest=this.alphaTest),!0===this.alphaHash&&(s.alphaHash=!0),!0===this.alphaToCoverage&&(s.alphaToCoverage=!0),!0===this.premultipliedAlpha&&(s.premultipliedAlpha=!0),!0===this.forceSinglePass&&(s.forceSinglePass=!0),!1===this.allowOverride&&(s.allowOverride=!1),!0===this.wireframe&&(s.wireframe=!0),this.wireframeLinewidth>1&&(s.wireframeLinewidth=this.wireframeLinewidth),"round"!==this.wireframeLinecap&&(s.wireframeLinecap=this.wireframeLinecap),"round"!==this.wireframeLinejoin&&(s.wireframeLinejoin=this.wireframeLinejoin),!0===this.flatShading&&(s.flatShading=!0),!1===this.visible&&(s.visible=!1),!1===this.toneMapped&&(s.toneMapped=!1),!1===this.fog&&(s.fog=!1),Object.keys(this.userData).length>0&&(s.userData=this.userData),t){const t=i(e.textures),r=i(e.images);t.length>0&&(s.textures=t),r.length>0&&(s.images=r)}return s}clone(){return(new this.constructor).copy(this)}copy(e){this.name=e.name,this.blending=e.blending,this.side=e.side,this.vertexColors=e.vertexColors,this.opacity=e.opacity,this.transparent=e.transparent,this.blendSrc=e.blendSrc,this.blendDst=e.blendDst,this.blendEquation=e.blendEquation,this.blendSrcAlpha=e.blendSrcAlpha,this.blendDstAlpha=e.blendDstAlpha,this.blendEquationAlpha=e.blendEquationAlpha,this.blendColor.copy(e.blendColor),this.blendAlpha=e.blendAlpha,this.depthFunc=e.depthFunc,this.depthTest=e.depthTest,this.depthWrite=e.depthWrite,this.stencilWriteMask=e.stencilWriteMask,this.stencilFunc=e.stencilFunc,this.stencilRef=e.stencilRef,this.stencilFuncMask=e.stencilFuncMask,this.stencilFail=e.stencilFail,this.stencilZFail=e.stencilZFail,this.stencilZPass=e.stencilZPass,this.stencilWrite=e.stencilWrite;const t=e.clippingPlanes;let s=null;if(null!==t){const e=t.length;s=new Array(e);for(let i=0;i!==e;++i)s[i]=t[i].clone()}return this.clippingPlanes=s,this.clipIntersection=e.clipIntersection,this.clipShadows=e.clipShadows,this.shadowSide=e.shadowSide,this.colorWrite=e.colorWrite,this.precision=e.precision,this.polygonOffset=e.polygonOffset,this.polygonOffsetFactor=e.polygonOffsetFactor,this.polygonOffsetUnits=e.polygonOffsetUnits,this.dithering=e.dithering,this.alphaTest=e.alphaTest,this.alphaHash=e.alphaHash,this.alphaToCoverage=e.alphaToCoverage,this.premultipliedAlpha=e.premultipliedAlpha,this.forceSinglePass=e.forceSinglePass,this.allowOverride=e.allowOverride,this.visible=e.visible,this.toneMapped=e.toneMapped,this.userData=JSON.parse(JSON.stringify(e.userData)),this}dispose(){this.dispatchEvent({type:"dispose"})}set needsUpdate(e){!0===e&&this.version++}}class rh extends ih{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new eh(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new xl,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}const nh=oh();function oh(){const e=new ArrayBuffer(4),t=new Float32Array(e),s=new Uint32Array(e),i=new Uint32Array(512),r=new Uint32Array(512);for(let e=0;e<256;++e){const t=e-127;t<-27?(i[e]=0,i[256|e]=32768,r[e]=24,r[256|e]=24):t<-14?(i[e]=1024>>-t-14,i[256|e]=1024>>-t-14|32768,r[e]=-t-1,r[256|e]=-t-1):t<=15?(i[e]=t+15<<10,i[256|e]=t+15<<10|32768,r[e]=13,r[256|e]=13):t<128?(i[e]=31744,i[256|e]=64512,r[e]=24,r[256|e]=24):(i[e]=31744,i[256|e]=64512,r[e]=13,r[256|e]=13)}const n=new Uint32Array(2048),o=new Uint32Array(64),a=new Uint32Array(64);for(let e=1;e<1024;++e){let t=e<<13,s=0;for(;!(8388608&t);)t<<=1,s-=8388608;t&=-8388609,s+=947912704,n[e]=t|s}for(let e=1024;e<2048;++e)n[e]=939524096+(e-1024<<13);for(let e=1;e<31;++e)o[e]=e<<23;o[31]=1199570944,o[32]=2147483648;for(let e=33;e<63;++e)o[e]=2147483648+(e-32<<23);o[63]=3347054592;for(let e=1;e<64;++e)32!==e&&(a[e]=1024);return{floatView:t,uint32View:s,baseTable:i,shiftTable:r,mantissaTable:n,exponentTable:o,offsetTable:a}}function ah(e){Math.abs(e)>65504&&Yo("DataUtils.toHalfFloat(): Value out of range."),e=ra(e,-65504,65504),nh.floatView[0]=e;const t=nh.uint32View[0],s=t>>23&511;return nh.baseTable[s]+((8388607&t)>>nh.shiftTable[s])}function lh(e){const t=e>>10;return nh.uint32View[0]=nh.mantissaTable[nh.offsetTable[t]+(1023&e)]+nh.exponentTable[t],nh.floatView[0]}const hh=new da,uh=new ua;let ch=0;class dh{constructor(e,t,s=!1){if(Array.isArray(e))throw new TypeError("THREE.BufferAttribute: array should be a Typed Array.");this.isBufferAttribute=!0,Object.defineProperty(this,"id",{value:ch++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=Vo,this.updateRanges=[],this.gpuType=Nn,this.version=0}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.name=e.name,this.array=new e.array.constructor(e.array),this.itemSize=e.itemSize,this.count=e.count,this.normalized=e.normalized,this.usage=e.usage,this.gpuType=e.gpuType,this}copyAt(e,t,s){e*=this.itemSize,s*=t.itemSize;for(let i=0,r=this.itemSize;i<r;i++)this.array[e+i]=t.array[s+i];return this}copyArray(e){return this.array.set(e),this}applyMatrix3(e){if(2===this.itemSize)for(let t=0,s=this.count;t<s;t++)uh.fromBufferAttribute(this,t),uh.applyMatrix3(e),this.setXY(t,uh.x,uh.y);else if(3===this.itemSize)for(let t=0,s=this.count;t<s;t++)hh.fromBufferAttribute(this,t),hh.applyMatrix3(e),this.setXYZ(t,hh.x,hh.y,hh.z);return this}applyMatrix4(e){for(let t=0,s=this.count;t<s;t++)hh.fromBufferAttribute(this,t),hh.applyMatrix4(e),this.setXYZ(t,hh.x,hh.y,hh.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)hh.fromBufferAttribute(this,t),hh.applyNormalMatrix(e),this.setXYZ(t,hh.x,hh.y,hh.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)hh.fromBufferAttribute(this,t),hh.transformDirection(e),this.setXYZ(t,hh.x,hh.y,hh.z);return this}set(e,t=0){return this.array.set(e,t),this}getComponent(e,t){let s=this.array[e*this.itemSize+t];return this.normalized&&(s=aa(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=la(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=aa(t,this.array)),t}setX(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=aa(t,this.array)),t}setY(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize+1]=t,this}getZ(e){let t=this.array[e*this.itemSize+2];return this.normalized&&(t=aa(t,this.array)),t}setZ(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize+2]=t,this}getW(e){let t=this.array[e*this.itemSize+3];return this.normalized&&(t=aa(t,this.array)),t}setW(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=la(t,this.array),s=la(s,this.array)),this.array[e+0]=t,this.array[e+1]=s,this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=la(t,this.array),s=la(s,this.array),i=la(i,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=la(t,this.array),s=la(s,this.array),i=la(i,this.array),r=la(r,this.array)),this.array[e+0]=t,this.array[e+1]=s,this.array[e+2]=i,this.array[e+3]=r,this}onUpload(e){return this.onUploadCallback=e,this}clone(){return new this.constructor(this.array,this.itemSize).copy(this)}toJSON(){const e={itemSize:this.itemSize,type:this.array.constructor.name,array:Array.from(this.array),normalized:this.normalized};return""!==this.name&&(e.name=this.name),this.usage!==Vo&&(e.usage=this.usage),e}}class ph extends dh{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class mh extends dh{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class fh extends dh{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=lh(this.array[e*this.itemSize]);return this.normalized&&(t=aa(t,this.array)),t}setX(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize]=ah(t),this}getY(e){let t=lh(this.array[e*this.itemSize+1]);return this.normalized&&(t=aa(t,this.array)),t}setY(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize+1]=ah(t),this}getZ(e){let t=lh(this.array[e*this.itemSize+2]);return this.normalized&&(t=aa(t,this.array)),t}setZ(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize+2]=ah(t),this}getW(e){let t=lh(this.array[e*this.itemSize+3]);return this.normalized&&(t=aa(t,this.array)),t}setW(e,t){return this.normalized&&(t=la(t,this.array)),this.array[e*this.itemSize+3]=ah(t),this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=la(t,this.array),s=la(s,this.array)),this.array[e+0]=ah(t),this.array[e+1]=ah(s),this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=la(t,this.array),s=la(s,this.array),i=la(i,this.array)),this.array[e+0]=ah(t),this.array[e+1]=ah(s),this.array[e+2]=ah(i),this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=la(t,this.array),s=la(s,this.array),i=la(i,this.array),r=la(r,this.array)),this.array[e+0]=ah(t),this.array[e+1]=ah(s),this.array[e+2]=ah(i),this.array[e+3]=ah(r),this}}class gh extends dh{constructor(e,t,s){super(new Float32Array(e),t,s)}}let yh=0;const xh=new ll,bh=new Ll,_h=new da,wh=new La,vh=new La,Th=new da;class Sh extends Ko{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:yh++}),this.uuid=ia(),this.name="",this.type="BufferGeometry",this.index=null,this.indirect=null,this.indirectOffset=0,this.attributes={},this.morphAttributes={},this.morphTargetsRelative=!1,this.groups=[],this.boundingBox=null,this.boundingSphere=null,this.drawRange={start:0,count:1/0},this.userData={}}getIndex(){return this.index}setIndex(e){return Array.isArray(e)?this.index=new($o(e)?mh:ph)(e,1):this.index=e,this}setIndirect(e,t=0){return this.indirect=e,this.indirectOffset=t,this}getIndirect(){return this.indirect}getAttribute(e){return this.attributes[e]}setAttribute(e,t){return this.attributes[e]=t,this}deleteAttribute(e){return delete this.attributes[e],this}hasAttribute(e){return void 0!==this.attributes[e]}addGroup(e,t,s=0){this.groups.push({start:e,count:t,materialIndex:s})}clearGroups(){this.groups=[]}setDrawRange(e,t){this.drawRange.start=e,this.drawRange.count=t}applyMatrix4(e){const t=this.attributes.position;void 0!==t&&(t.applyMatrix4(e),t.needsUpdate=!0);const s=this.attributes.normal;if(void 0!==s){const t=(new fa).getNormalMatrix(e);s.applyNormalMatrix(t),s.needsUpdate=!0}const i=this.attributes.tangent;return void 0!==i&&(i.transformDirection(e),i.needsUpdate=!0),null!==this.boundingBox&&this.computeBoundingBox(),null!==this.boundingSphere&&this.computeBoundingSphere(),this}applyQuaternion(e){return xh.makeRotationFromQuaternion(e),this.applyMatrix4(xh),this}rotateX(e){return xh.makeRotationX(e),this.applyMatrix4(xh),this}rotateY(e){return xh.makeRotationY(e),this.applyMatrix4(xh),this}rotateZ(e){return xh.makeRotationZ(e),this.applyMatrix4(xh),this}translate(e,t,s){return xh.makeTranslation(e,t,s),this.applyMatrix4(xh),this}scale(e,t,s){return xh.makeScale(e,t,s),this.applyMatrix4(xh),this}lookAt(e){return bh.lookAt(e),bh.updateMatrix(),this.applyMatrix4(bh.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(_h).negate(),this.translate(_h.x,_h.y,_h.z),this}setFromPoints(e){const t=this.getAttribute("position");if(void 0===t){const t=[];for(let s=0,i=e.length;s<i;s++){const i=e[s];t.push(i.x,i.y,i.z||0)}this.setAttribute("position",new gh(t,3))}else{const s=Math.min(e.length,t.count);for(let i=0;i<s;i++){const s=e[i];t.setXYZ(i,s.x,s.y,s.z||0)}e.length>t.count&&Yo("BufferGeometry: Buffer size too small for points data. Use .dispose() and create a new geometry."),t.needsUpdate=!0}return this}computeBoundingBox(){null===this.boundingBox&&(this.boundingBox=new La);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return Zo("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new da(-1/0,-1/0,-1/0),new da(1/0,1/0,1/0));if(void 0!==e){if(this.boundingBox.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const s=t[e];wh.setFromBufferAttribute(s),this.morphTargetsRelative?(Th.addVectors(this.boundingBox.min,wh.min),this.boundingBox.expandByPoint(Th),Th.addVectors(this.boundingBox.max,wh.max),this.boundingBox.expandByPoint(Th)):(this.boundingBox.expandByPoint(wh.min),this.boundingBox.expandByPoint(wh.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Zo('BufferGeometry.computeBoundingBox(): Computed min/max have NaN values. The "position" attribute is likely to have NaN values.',this)}computeBoundingSphere(){null===this.boundingSphere&&(this.boundingSphere=new Ja);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return Zo("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new da,1/0);if(e){const s=this.boundingSphere.center;if(wh.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const s=t[e];vh.setFromBufferAttribute(s),this.morphTargetsRelative?(Th.addVectors(wh.min,vh.min),wh.expandByPoint(Th),Th.addVectors(wh.max,vh.max),wh.expandByPoint(Th)):(wh.expandByPoint(vh.min),wh.expandByPoint(vh.max))}wh.getCenter(s);let i=0;for(let t=0,r=e.count;t<r;t++)Th.fromBufferAttribute(e,t),i=Math.max(i,s.distanceToSquared(Th));if(t)for(let r=0,n=t.length;r<n;r++){const n=t[r],o=this.morphTargetsRelative;for(let t=0,r=n.count;t<r;t++)Th.fromBufferAttribute(n,t),o&&(_h.fromBufferAttribute(e,t),Th.add(_h)),i=Math.max(i,s.distanceToSquared(Th))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&Zo('BufferGeometry.computeBoundingSphere(): Computed radius is NaN. The "position" attribute is likely to have NaN values.',this)}}computeTangents(){const e=this.index,t=this.attributes;if(null===e||void 0===t.position||void 0===t.normal||void 0===t.uv)return void Zo("BufferGeometry: .computeTangents() failed. Missing required attributes (index, position, normal or uv)");const s=t.position,i=t.normal,r=t.uv;!1===this.hasAttribute("tangent")&&this.setAttribute("tangent",new dh(new Float32Array(4*s.count),4));const n=this.getAttribute("tangent"),o=[],a=[];for(let e=0;e<s.count;e++)o[e]=new da,a[e]=new da;const l=new da,h=new da,u=new da,c=new ua,d=new ua,p=new ua,m=new da,f=new da;function g(e,t,i){l.fromBufferAttribute(s,e),h.fromBufferAttribute(s,t),u.fromBufferAttribute(s,i),c.fromBufferAttribute(r,e),d.fromBufferAttribute(r,t),p.fromBufferAttribute(r,i),h.sub(l),u.sub(l),d.sub(c),p.sub(c);const n=1/(d.x*p.y-p.x*d.y);isFinite(n)&&(m.copy(h).multiplyScalar(p.y).addScaledVector(u,-d.y).multiplyScalar(n),f.copy(u).multiplyScalar(d.x).addScaledVector(h,-p.x).multiplyScalar(n),o[e].add(m),o[t].add(m),o[i].add(m),a[e].add(f),a[t].add(f),a[i].add(f))}let y=this.groups;0===y.length&&(y=[{start:0,count:e.count}]);for(let t=0,s=y.length;t<s;++t){const s=y[t],i=s.start;for(let t=i,r=i+s.count;t<r;t+=3)g(e.getX(t+0),e.getX(t+1),e.getX(t+2))}const x=new da,b=new da,_=new da,w=new da;function v(e){_.fromBufferAttribute(i,e),w.copy(_);const t=o[e];x.copy(t),x.sub(_.multiplyScalar(_.dot(t))).normalize(),b.crossVectors(w,t);const s=b.dot(a[e])<0?-1:1;n.setXYZW(e,x.x,x.y,x.z,s)}for(let t=0,s=y.length;t<s;++t){const s=y[t],i=s.start;for(let t=i,r=i+s.count;t<r;t+=3)v(e.getX(t+0)),v(e.getX(t+1)),v(e.getX(t+2))}}computeVertexNormals(){const e=this.index,t=this.getAttribute("position");if(void 0!==t){let s=this.getAttribute("normal");if(void 0===s)s=new dh(new Float32Array(3*t.count),3),this.setAttribute("normal",s);else for(let e=0,t=s.count;e<t;e++)s.setXYZ(e,0,0,0);const i=new da,r=new da,n=new da,o=new da,a=new da,l=new da,h=new da,u=new da;if(e)for(let c=0,d=e.count;c<d;c+=3){const d=e.getX(c+0),p=e.getX(c+1),m=e.getX(c+2);i.fromBufferAttribute(t,d),r.fromBufferAttribute(t,p),n.fromBufferAttribute(t,m),h.subVectors(n,r),u.subVectors(i,r),h.cross(u),o.fromBufferAttribute(s,d),a.fromBufferAttribute(s,p),l.fromBufferAttribute(s,m),o.add(h),a.add(h),l.add(h),s.setXYZ(d,o.x,o.y,o.z),s.setXYZ(p,a.x,a.y,a.z),s.setXYZ(m,l.x,l.y,l.z)}else for(let e=0,o=t.count;e<o;e+=3)i.fromBufferAttribute(t,e+0),r.fromBufferAttribute(t,e+1),n.fromBufferAttribute(t,e+2),h.subVectors(n,r),u.subVectors(i,r),h.cross(u),s.setXYZ(e+0,h.x,h.y,h.z),s.setXYZ(e+1,h.x,h.y,h.z),s.setXYZ(e+2,h.x,h.y,h.z);this.normalizeNormals(),s.needsUpdate=!0}}normalizeNormals(){const e=this.attributes.normal;for(let t=0,s=e.count;t<s;t++)Th.fromBufferAttribute(e,t),Th.normalize(),e.setXYZ(t,Th.x,Th.y,Th.z)}toNonIndexed(){function e(e,t){const s=e.array,i=e.itemSize,r=e.normalized,n=new s.constructor(t.length*i);let o=0,a=0;for(let r=0,l=t.length;r<l;r++){o=e.isInterleavedBufferAttribute?t[r]*e.data.stride+e.offset:t[r]*i;for(let e=0;e<i;e++)n[a++]=s[o++]}return new dh(n,i,r)}if(null===this.index)return Yo("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new Sh,s=this.index.array,i=this.attributes;for(const r in i){const n=e(i[r],s);t.setAttribute(r,n)}const r=this.morphAttributes;for(const i in r){const n=[],o=r[i];for(let t=0,i=o.length;t<i;t++){const i=e(o[t],s);n.push(i)}t.morphAttributes[i]=n}t.morphTargetsRelative=this.morphTargetsRelative;const n=this.groups;for(let e=0,s=n.length;e<s;e++){const s=n[e];t.addGroup(s.start,s.count,s.materialIndex)}return t}toJSON(){const e={metadata:{version:4.7,type:"BufferGeometry",generator:"BufferGeometry.toJSON"}};if(e.uuid=this.uuid,e.type=this.type,""!==this.name&&(e.name=this.name),Object.keys(this.userData).length>0&&(e.userData=this.userData),void 0!==this.parameters){const t=this.parameters;for(const s in t)void 0!==t[s]&&(e[s]=t[s]);return e}e.data={attributes:{}};const t=this.index;null!==t&&(e.data.index={type:t.array.constructor.name,array:Array.prototype.slice.call(t.array)});const s=this.attributes;for(const t in s){const i=s[t];e.data.attributes[t]=i.toJSON(e.data)}const i={};let r=!1;for(const t in this.morphAttributes){const s=this.morphAttributes[t],n=[];for(let t=0,i=s.length;t<i;t++){const i=s[t];n.push(i.toJSON(e.data))}n.length>0&&(i[t]=n,r=!0)}r&&(e.data.morphAttributes=i,e.data.morphTargetsRelative=this.morphTargetsRelative);const n=this.groups;n.length>0&&(e.data.groups=JSON.parse(JSON.stringify(n)));const o=this.boundingSphere;return null!==o&&(e.data.boundingSphere=o.toJSON()),e}clone(){return(new this.constructor).copy(this)}copy(e){this.index=null,this.attributes={},this.morphAttributes={},this.groups=[],this.boundingBox=null,this.boundingSphere=null;const t={};this.name=e.name;const s=e.index;null!==s&&this.setIndex(s.clone());const i=e.attributes;for(const e in i){const s=i[e];this.setAttribute(e,s.clone(t))}const r=e.morphAttributes;for(const e in r){const s=[],i=r[e];for(let e=0,r=i.length;e<r;e++)s.push(i[e].clone(t));this.morphAttributes[e]=s}this.morphTargetsRelative=e.morphTargetsRelative;const n=e.groups;for(let e=0,t=n.length;e<t;e++){const t=n[e];this.addGroup(t.start,t.count,t.materialIndex)}const o=e.boundingBox;null!==o&&(this.boundingBox=o.clone());const a=e.boundingSphere;return null!==a&&(this.boundingSphere=a.clone()),this.drawRange.start=e.drawRange.start,this.drawRange.count=e.drawRange.count,this.userData=e.userData,this}dispose(){this.dispatchEvent({type:"dispose"})}}const Mh=new ll,Ah=new al,Nh=new Ja,Eh=new da,Ch=new da,Rh=new da,Ph=new da,Bh=new da,Ih=new da,Dh=new da,Lh=new da;class Fh extends Ll{constructor(e=new Sh,t=new rh){super(),this.isMesh=!0,this.type="Mesh",this.geometry=e,this.material=t,this.morphTargetDictionary=void 0,this.morphTargetInfluences=void 0,this.count=1,this.updateMorphTargets()}copy(e,t){return super.copy(e,t),void 0!==e.morphTargetInfluences&&(this.morphTargetInfluences=e.morphTargetInfluences.slice()),void 0!==e.morphTargetDictionary&&(this.morphTargetDictionary=Object.assign({},e.morphTargetDictionary)),this.material=Array.isArray(e.material)?e.material.slice():e.material,this.geometry=e.geometry,this}updateMorphTargets(){const e=this.geometry.morphAttributes,t=Object.keys(e);if(t.length>0){const s=e[t[0]];if(void 0!==s){this.morphTargetInfluences=[],this.morphTargetDictionary={};for(let e=0,t=s.length;e<t;e++){const t=s[e].name||String(e);this.morphTargetInfluences.push(0),this.morphTargetDictionary[t]=e}}}}getVertexPosition(e,t){const s=this.geometry,i=s.attributes.position,r=s.morphAttributes.position,n=s.morphTargetsRelative;t.fromBufferAttribute(i,e);const o=this.morphTargetInfluences;if(r&&o){Ih.set(0,0,0);for(let s=0,i=r.length;s<i;s++){const i=o[s],a=r[s];0!==i&&(Bh.fromBufferAttribute(a,e),n?Ih.addScaledVector(Bh,i):Ih.addScaledVector(Bh.sub(t),i))}t.add(Ih)}return t}raycast(e,t){const s=this.geometry,i=this.material,r=this.matrixWorld;if(void 0!==i){if(null===s.boundingSphere&&s.computeBoundingSphere(),Nh.copy(s.boundingSphere),Nh.applyMatrix4(r),Ah.copy(e.ray).recast(e.near),!1===Nh.containsPoint(Ah.origin)){if(null===Ah.intersectSphere(Nh,Eh))return;if(Ah.origin.distanceToSquared(Eh)>(e.far-e.near)**2)return}Mh.copy(r).invert(),Ah.copy(e.ray).applyMatrix4(Mh),null!==s.boundingBox&&!1===Ah.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,Ah)}}_computeIntersections(e,t,s){let i;const r=this.geometry,n=this.material,o=r.index,a=r.attributes.position,l=r.attributes.uv,h=r.attributes.uv1,u=r.attributes.normal,c=r.groups,d=r.drawRange;if(null!==o)if(Array.isArray(n))for(let r=0,a=c.length;r<a;r++){const a=c[r],p=n[a.materialIndex];for(let r=Math.max(a.start,d.start),n=Math.min(o.count,Math.min(a.start+a.count,d.start+d.count));r<n;r+=3){i=Oh(this,p,e,s,l,h,u,o.getX(r),o.getX(r+1),o.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=a.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),a=Math.min(o.count,d.start+d.count);r<a;r+=3){i=Oh(this,n,e,s,l,h,u,o.getX(r),o.getX(r+1),o.getX(r+2)),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}else if(void 0!==a)if(Array.isArray(n))for(let r=0,o=c.length;r<o;r++){const o=c[r],p=n[o.materialIndex];for(let r=Math.max(o.start,d.start),n=Math.min(a.count,Math.min(o.start+o.count,d.start+d.count));r<n;r+=3){i=Oh(this,p,e,s,l,h,u,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),i.face.materialIndex=o.materialIndex,t.push(i))}}else{for(let r=Math.max(0,d.start),o=Math.min(a.count,d.start+d.count);r<o;r+=3){i=Oh(this,n,e,s,l,h,u,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function Oh(e,t,s,i,r,n,o,a,l,h){e.getVertexPosition(a,Ch),e.getVertexPosition(l,Rh),e.getVertexPosition(h,Ph);const u=function(e,t,s,i,r,n,o,a){let l;if(l=1===t.side?i.intersectTriangle(o,n,r,!0,a):i.intersectTriangle(r,n,o,0===t.side,a),null===l)return null;Lh.copy(a),Lh.applyMatrix4(e.matrixWorld);const h=s.ray.origin.distanceTo(Lh);return h<s.near||h>s.far?null:{distance:h,point:Lh.clone(),object:e}}(e,t,s,i,Ch,Rh,Ph,Dh);if(u){const e=new da;Yl.getBarycoord(Dh,Ch,Rh,Ph,e),r&&(u.uv=Yl.getInterpolatedAttribute(r,a,l,h,e,new ua)),n&&(u.uv1=Yl.getInterpolatedAttribute(n,a,l,h,e,new ua)),o&&(u.normal=Yl.getInterpolatedAttribute(o,a,l,h,e,new da),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const t={a:a,b:l,c:h,normal:new da,materialIndex:0};Yl.getNormal(Ch,Rh,Ph,t.normal),u.face=t,u.barycoord=e}return u}class Vh extends Sh{constructor(e=1,t=1,s=1,i=1,r=1,n=1){super(),this.type="BoxGeometry",this.parameters={width:e,height:t,depth:s,widthSegments:i,heightSegments:r,depthSegments:n};const o=this;i=Math.floor(i),r=Math.floor(r),n=Math.floor(n);const a=[],l=[],h=[],u=[];let c=0,d=0;function p(e,t,s,i,r,n,p,m,f,g,y){const x=n/f,b=p/g,_=n/2,w=p/2,v=m/2,T=f+1,S=g+1;let M=0,A=0;const N=new da;for(let n=0;n<S;n++){const o=n*b-w;for(let a=0;a<T;a++){const c=a*x-_;N[e]=c*i,N[t]=o*r,N[s]=v,l.push(N.x,N.y,N.z),N[e]=0,N[t]=0,N[s]=m>0?1:-1,h.push(N.x,N.y,N.z),u.push(a/f),u.push(1-n/g),M+=1}}for(let e=0;e<g;e++)for(let t=0;t<f;t++){const s=c+t+T*e,i=c+t+T*(e+1),r=c+(t+1)+T*(e+1),n=c+(t+1)+T*e;a.push(s,i,n),a.push(i,r,n),A+=6}o.addGroup(d,A,y),d+=A,c+=M}p("z","y","x",-1,-1,s,t,e,n,r,0),p("z","y","x",1,-1,s,t,-e,n,r,1),p("x","z","y",1,1,e,s,t,i,n,2),p("x","z","y",1,-1,e,s,-t,i,n,3),p("x","y","z",1,-1,e,t,s,i,r,4),p("x","y","z",-1,-1,e,t,-s,i,r,5),this.setIndex(a),this.setAttribute("position",new gh(l,3)),this.setAttribute("normal",new gh(h,3)),this.setAttribute("uv",new gh(u,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Vh(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function zh(e){const t={};for(const s in e){t[s]={};for(const i in e[s]){const r=e[s][i];r&&(r.isColor||r.isMatrix3||r.isMatrix4||r.isVector2||r.isVector3||r.isVector4||r.isTexture||r.isQuaternion)?r.isRenderTargetTexture?(Yo("UniformsUtils: Textures of render targets cannot be cloned via cloneUniforms() or mergeUniforms()."),t[s][i]=null):t[s][i]=r.clone():Array.isArray(r)?t[s][i]=r.slice():t[s][i]=r}}return t}class kh extends ih{constructor(e){super(),this.isShaderMaterial=!0,this.type="ShaderMaterial",this.defines={},this.uniforms={},this.uniformsGroups=[],this.vertexShader="void main() {\n\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n}",this.fragmentShader="void main() {\n\tgl_FragColor = vec4( 1.0, 0.0, 0.0, 1.0 );\n}",this.linewidth=1,this.wireframe=!1,this.wireframeLinewidth=1,this.fog=!1,this.lights=!1,this.clipping=!1,this.forceSinglePass=!0,this.extensions={clipCullDistance:!1,multiDraw:!1},this.defaultAttributeValues={color:[1,1,1],uv:[0,0],uv1:[0,0]},this.index0AttributeName=void 0,this.uniformsNeedUpdate=!1,this.glslVersion=null,void 0!==e&&this.setValues(e)}copy(e){return super.copy(e),this.fragmentShader=e.fragmentShader,this.vertexShader=e.vertexShader,this.uniforms=zh(e.uniforms),this.uniformsGroups=function(e){const t=[];for(let s=0;s<e.length;s++)t.push(e[s].clone());return t}(e.uniformsGroups),this.defines=Object.assign({},e.defines),this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.fog=e.fog,this.lights=e.lights,this.clipping=e.clipping,this.extensions=Object.assign({},e.extensions),this.glslVersion=e.glslVersion,this.defaultAttributeValues=Object.assign({},e.defaultAttributeValues),this.index0AttributeName=e.index0AttributeName,this.uniformsNeedUpdate=e.uniformsNeedUpdate,this}toJSON(e){const t=super.toJSON(e);t.glslVersion=this.glslVersion,t.uniforms={};for(const s in this.uniforms){const i=this.uniforms[s].value;i&&i.isTexture?t.uniforms[s]={type:"t",value:i.toJSON(e).uuid}:i&&i.isColor?t.uniforms[s]={type:"c",value:i.getHex()}:i&&i.isVector2?t.uniforms[s]={type:"v2",value:i.toArray()}:i&&i.isVector3?t.uniforms[s]={type:"v3",value:i.toArray()}:i&&i.isVector4?t.uniforms[s]={type:"v4",value:i.toArray()}:i&&i.isMatrix3?t.uniforms[s]={type:"m3",value:i.toArray()}:i&&i.isMatrix4?t.uniforms[s]={type:"m4",value:i.toArray()}:t.uniforms[s]={value:i}}Object.keys(this.defines).length>0&&(t.defines=this.defines),t.vertexShader=this.vertexShader,t.fragmentShader=this.fragmentShader,t.lights=this.lights,t.clipping=this.clipping;const s={};for(const e in this.extensions)!0===this.extensions[e]&&(s[e]=!0);return Object.keys(s).length>0&&(t.extensions=s),t}}class Uh extends Ll{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new ll,this.projectionMatrix=new ll,this.projectionMatrixInverse=new ll,this.coordinateSystem=ko,this._reversedDepth=!1}get reversedDepth(){return this._reversedDepth}copy(e,t){return super.copy(e,t),this.matrixWorldInverse.copy(e.matrixWorldInverse),this.projectionMatrix.copy(e.projectionMatrix),this.projectionMatrixInverse.copy(e.projectionMatrixInverse),this.coordinateSystem=e.coordinateSystem,this}getWorldDirection(e){return super.getWorldDirection(e).negate()}updateMatrixWorld(e){super.updateMatrixWorld(e),this.matrixWorldInverse.copy(this.matrixWorld).invert()}updateWorldMatrix(e,t){super.updateWorldMatrix(e,t),this.matrixWorldInverse.copy(this.matrixWorld).invert()}clone(){return(new this.constructor).copy(this)}}const Gh=new da,jh=new ua,$h=new ua;class Wh extends Uh{constructor(e=50,t=1,s=.1,i=2e3){super(),this.isPerspectiveCamera=!0,this.type="PerspectiveCamera",this.fov=e,this.zoom=1,this.near=s,this.far=i,this.focus=10,this.aspect=t,this.view=null,this.filmGauge=35,this.filmOffset=0,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.fov=e.fov,this.zoom=e.zoom,this.near=e.near,this.far=e.far,this.focus=e.focus,this.aspect=e.aspect,this.view=null===e.view?null:Object.assign({},e.view),this.filmGauge=e.filmGauge,this.filmOffset=e.filmOffset,this}setFocalLength(e){const t=.5*this.getFilmHeight()/e;this.fov=2*sa*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*ta*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*sa*Math.atan(Math.tan(.5*ta*this.fov)/this.zoom)}getFilmWidth(){return this.filmGauge*Math.min(this.aspect,1)}getFilmHeight(){return this.filmGauge/Math.max(this.aspect,1)}getViewBounds(e,t,s){Gh.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Gh.x,Gh.y).multiplyScalar(-e/Gh.z),Gh.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(Gh.x,Gh.y).multiplyScalar(-e/Gh.z)}getViewSize(e,t){return this.getViewBounds(e,jh,$h),t.subVectors($h,jh)}setViewOffset(e,t,s,i,r,n){this.aspect=e/t,null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=i,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=this.near;let t=e*Math.tan(.5*ta*this.fov)/this.zoom,s=2*t,i=this.aspect*s,r=-.5*i;const n=this.view;if(null!==this.view&&this.view.enabled){const e=n.fullWidth,o=n.fullHeight;r+=n.offsetX*i/e,t-=n.offsetY*s/o,i*=n.width/e,s*=n.height/o}const o=this.filmOffset;0!==o&&(r+=e*o/this.getFilmWidth()),this.projectionMatrix.makePerspective(r,r+i,t,t-s,e,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.fov=this.fov,t.object.zoom=this.zoom,t.object.near=this.near,t.object.far=this.far,t.object.focus=this.focus,t.object.aspect=this.aspect,null!==this.view&&(t.object.view=Object.assign({},this.view)),t.object.filmGauge=this.filmGauge,t.object.filmOffset=this.filmOffset,t}}const Hh=-90;class qh extends Ll{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Wh(Hh,1,e,t);i.layers=this.layers,this.add(i);const r=new Wh(Hh,1,e,t);r.layers=this.layers,this.add(r);const n=new Wh(Hh,1,e,t);n.layers=this.layers,this.add(n);const o=new Wh(Hh,1,e,t);o.layers=this.layers,this.add(o);const a=new Wh(Hh,1,e,t);a.layers=this.layers,this.add(a);const l=new Wh(Hh,1,e,t);l.layers=this.layers,this.add(l)}updateCoordinateSystem(){const e=this.coordinateSystem,t=this.children.concat(),[s,i,r,n,o,a]=t;for(const e of t)this.remove(e);if(e===ko)s.up.set(0,1,0),s.lookAt(1,0,0),i.up.set(0,1,0),i.lookAt(-1,0,0),r.up.set(0,0,-1),r.lookAt(0,1,0),n.up.set(0,0,1),n.lookAt(0,-1,0),o.up.set(0,1,0),o.lookAt(0,0,1),a.up.set(0,1,0),a.lookAt(0,0,-1);else{if(e!==Uo)throw new Error("THREE.CubeCamera.updateCoordinateSystem(): Invalid coordinate system: "+e);s.up.set(0,-1,0),s.lookAt(-1,0,0),i.up.set(0,-1,0),i.lookAt(1,0,0),r.up.set(0,0,1),r.lookAt(0,1,0),n.up.set(0,0,-1),n.lookAt(0,-1,0),o.up.set(0,-1,0),o.lookAt(0,0,1),a.up.set(0,-1,0),a.lookAt(0,0,-1)}for(const e of t)this.add(e),e.updateMatrixWorld()}update(e,t){null===this.parent&&this.updateMatrixWorld();const{renderTarget:s,activeMipmapLevel:i}=this;this.coordinateSystem!==e.coordinateSystem&&(this.coordinateSystem=e.coordinateSystem,this.updateCoordinateSystem());const[r,n,o,a,l,h]=this.children,u=e.getRenderTarget(),c=e.getActiveCubeFace(),d=e.getActiveMipmapLevel(),p=e.xr.enabled;e.xr.enabled=!1;const m=s.texture.generateMipmaps;s.texture.generateMipmaps=!1,e.setRenderTarget(s,0,i),e.render(t,r),e.setRenderTarget(s,1,i),e.render(t,n),e.setRenderTarget(s,2,i),e.render(t,o),e.setRenderTarget(s,3,i),e.render(t,a),e.setRenderTarget(s,4,i),e.render(t,l),s.texture.generateMipmaps=m,e.setRenderTarget(s,5,i),e.render(t,h),e.setRenderTarget(u,c,d),e.xr.enabled=p,s.texture.needsPMREMUpdate=!0}}class Xh extends Ra{constructor(e=[],t=301,s,i,r,n,o,a,l,h){super(e,t,s,i,r,n,o,a,l,h),this.isCubeTexture=!0,this.flipY=!1}get images(){return this.image}set images(e){this.image=e}}class Yh extends Ia{constructor(e=1,t={}){super(e,e,t),this.isWebGLCubeRenderTarget=!0;const s={width:e,height:e,depth:1},i=[s,s,s,s,s,s];this.texture=new Xh(i),this._setTextureOptions(t),this.texture.isRenderTargetTexture=!0}fromEquirectangularTexture(e,t){this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const s={uniforms:{tEquirect:{value:null}},vertexShader:"\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\tvec3 transformDirection( in vec3 dir, in mat4 matrix ) {\n\n\t\t\t\t\treturn normalize( ( matrix * vec4( dir, 0.0 ) ).xyz );\n\n\t\t\t\t}\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvWorldDirection = transformDirection( position, modelMatrix );\n\n\t\t\t\t\t#include <begin_vertex>\n\t\t\t\t\t#include <project_vertex>\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\n\t\t\t\tuniform sampler2D tEquirect;\n\n\t\t\t\tvarying vec3 vWorldDirection;\n\n\t\t\t\t#include <common>\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tvec3 direction = normalize( vWorldDirection );\n\n\t\t\t\t\tvec2 sampleUV = equirectUv( direction );\n\n\t\t\t\t\tgl_FragColor = texture2D( tEquirect, sampleUV );\n\n\t\t\t\t}\n\t\t\t"},i=new Vh(5,5,5),r=new kh({name:"CubemapFromEquirect",uniforms:zh(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const n=new Fh(i,r),o=t.minFilter;t.minFilter===_n&&(t.minFilter=xn);return new qh(1,10,this).update(e,n),t.minFilter=o,n.geometry.dispose(),n.material.dispose(),this}clear(e,t=!0,s=!0,i=!0){const r=e.getRenderTarget();for(let r=0;r<6;r++)e.setRenderTarget(this,r),e.clear(t,s,i);e.setRenderTarget(r)}}class Zh extends Ll{constructor(){super(),this.isGroup=!0,this.type="Group"}}const Qh={type:"move"};class Kh{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Zh,this._hand.matrixAutoUpdate=!1,this._hand.visible=!1,this._hand.joints={},this._hand.inputState={pinching:!1}),this._hand}getTargetRaySpace(){return null===this._targetRay&&(this._targetRay=new Zh,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new da,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new da),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Zh,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new da,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new da),this._grip}dispatchEvent(e){return null!==this._targetRay&&this._targetRay.dispatchEvent(e),null!==this._grip&&this._grip.dispatchEvent(e),null!==this._hand&&this._hand.dispatchEvent(e),this}connect(e){if(e&&e.hand){const t=this._hand;if(t)for(const s of e.hand.values())this._getHandJoint(t,s)}return this.dispatchEvent({type:"connected",data:e}),this}disconnect(e){return this.dispatchEvent({type:"disconnected",data:e}),null!==this._targetRay&&(this._targetRay.visible=!1),null!==this._grip&&(this._grip.visible=!1),null!==this._hand&&(this._hand.visible=!1),this}update(e,t,s){let i=null,r=null,n=null;const o=this._targetRay,a=this._grip,l=this._hand;if(e&&"visible-blurred"!==t.session.visibilityState){if(l&&e.hand){n=!0;for(const i of e.hand.values()){const e=t.getJointPose(i,s),r=this._getHandJoint(l,i);null!==e&&(r.matrix.fromArray(e.transform.matrix),r.matrix.decompose(r.position,r.rotation,r.scale),r.matrixWorldNeedsUpdate=!0,r.jointRadius=e.radius),r.visible=null!==e}const i=l.joints["index-finger-tip"],r=l.joints["thumb-tip"],o=i.position.distanceTo(r.position),a=.02,h=.005;l.inputState.pinching&&o>a+h?(l.inputState.pinching=!1,this.dispatchEvent({type:"pinchend",handedness:e.handedness,target:this})):!l.inputState.pinching&&o<=a-h&&(l.inputState.pinching=!0,this.dispatchEvent({type:"pinchstart",handedness:e.handedness,target:this}))}else null!==a&&e.gripSpace&&(r=t.getPose(e.gripSpace,s),null!==r&&(a.matrix.fromArray(r.transform.matrix),a.matrix.decompose(a.position,a.rotation,a.scale),a.matrixWorldNeedsUpdate=!0,r.linearVelocity?(a.hasLinearVelocity=!0,a.linearVelocity.copy(r.linearVelocity)):a.hasLinearVelocity=!1,r.angularVelocity?(a.hasAngularVelocity=!0,a.angularVelocity.copy(r.angularVelocity)):a.hasAngularVelocity=!1));null!==o&&(i=t.getPose(e.targetRaySpace,s),null===i&&null!==r&&(i=r),null!==i&&(o.matrix.fromArray(i.transform.matrix),o.matrix.decompose(o.position,o.rotation,o.scale),o.matrixWorldNeedsUpdate=!0,i.linearVelocity?(o.hasLinearVelocity=!0,o.linearVelocity.copy(i.linearVelocity)):o.hasLinearVelocity=!1,i.angularVelocity?(o.hasAngularVelocity=!0,o.angularVelocity.copy(i.angularVelocity)):o.hasAngularVelocity=!1,this.dispatchEvent(Qh)))}return null!==o&&(o.visible=null!==i),null!==a&&(a.visible=null!==r),null!==l&&(l.visible=null!==n),this}_getHandJoint(e,t){if(void 0===e.joints[t.jointName]){const s=new Zh;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}class Jh extends Ll{constructor(){super(),this.isScene=!0,this.type="Scene",this.background=null,this.environment=null,this.fog=null,this.backgroundBlurriness=0,this.backgroundIntensity=1,this.backgroundRotation=new xl,this.environmentIntensity=1,this.environmentRotation=new xl,this.overrideMaterial=null,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}copy(e,t){return super.copy(e,t),null!==e.background&&(this.background=e.background.clone()),null!==e.environment&&(this.environment=e.environment.clone()),null!==e.fog&&(this.fog=e.fog.clone()),this.backgroundBlurriness=e.backgroundBlurriness,this.backgroundIntensity=e.backgroundIntensity,this.backgroundRotation.copy(e.backgroundRotation),this.environmentIntensity=e.environmentIntensity,this.environmentRotation.copy(e.environmentRotation),null!==e.overrideMaterial&&(this.overrideMaterial=e.overrideMaterial.clone()),this.matrixAutoUpdate=e.matrixAutoUpdate,this}toJSON(e){const t=super.toJSON(e);return null!==this.fog&&(t.object.fog=this.fog.toJSON()),this.backgroundBlurriness>0&&(t.object.backgroundBlurriness=this.backgroundBlurriness),1!==this.backgroundIntensity&&(t.object.backgroundIntensity=this.backgroundIntensity),t.object.backgroundRotation=this.backgroundRotation.toArray(),1!==this.environmentIntensity&&(t.object.environmentIntensity=this.environmentIntensity),t.object.environmentRotation=this.environmentRotation.toArray(),t}}class eu{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=Vo,this.updateRanges=[],this.version=0,this.uuid=ia()}onUploadCallback(){}set needsUpdate(e){!0===e&&this.version++}setUsage(e){return this.usage=e,this}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}copy(e){return this.array=new e.array.constructor(e.array),this.count=e.count,this.stride=e.stride,this.usage=e.usage,this}copyAt(e,t,s){e*=this.stride,s*=t.stride;for(let i=0,r=this.stride;i<r;i++)this.array[e+i]=t.array[s+i];return this}set(e,t=0){return this.array.set(e,t),this}clone(e){void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=ia()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(e.arrayBuffers[this.array.buffer._uuid]=this.array.slice(0).buffer);const t=new this.array.constructor(e.arrayBuffers[this.array.buffer._uuid]),s=new this.constructor(t,this.stride);return s.setUsage(this.usage),s}onUpload(e){return this.onUploadCallback=e,this}toJSON(e){return void 0===e.arrayBuffers&&(e.arrayBuffers={}),void 0===this.array.buffer._uuid&&(this.array.buffer._uuid=ia()),void 0===e.arrayBuffers[this.array.buffer._uuid]&&(e.arrayBuffers[this.array.buffer._uuid]=Array.from(new Uint32Array(this.array.buffer))),{uuid:this.uuid,buffer:this.array.buffer._uuid,type:this.array.constructor.name,stride:this.stride}}}const tu=new da;class su{constructor(e,t,s,i=!1){this.isInterleavedBufferAttribute=!0,this.name="",this.data=e,this.itemSize=t,this.offset=s,this.normalized=i}get count(){return this.data.count}get array(){return this.data.array}set needsUpdate(e){this.data.needsUpdate=e}applyMatrix4(e){for(let t=0,s=this.data.count;t<s;t++)tu.fromBufferAttribute(this,t),tu.applyMatrix4(e),this.setXYZ(t,tu.x,tu.y,tu.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)tu.fromBufferAttribute(this,t),tu.applyNormalMatrix(e),this.setXYZ(t,tu.x,tu.y,tu.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)tu.fromBufferAttribute(this,t),tu.transformDirection(e),this.setXYZ(t,tu.x,tu.y,tu.z);return this}getComponent(e,t){let s=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(s=aa(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=la(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=la(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=la(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=la(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=la(t,this.array)),this.data.array[e*this.data.stride+this.offset+3]=t,this}getX(e){let t=this.data.array[e*this.data.stride+this.offset];return this.normalized&&(t=aa(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=aa(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=aa(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=aa(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=la(t,this.array),s=la(s,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this}setXYZ(e,t,s,i){return e=e*this.data.stride+this.offset,this.normalized&&(t=la(t,this.array),s=la(s,this.array),i=la(i,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this}setXYZW(e,t,s,i,r){return e=e*this.data.stride+this.offset,this.normalized&&(t=la(t,this.array),s=la(s,this.array),i=la(i,this.array),r=la(r,this.array)),this.data.array[e+0]=t,this.data.array[e+1]=s,this.data.array[e+2]=i,this.data.array[e+3]=r,this}clone(e){if(void 0===e){Xo("InterleavedBufferAttribute.clone(): Cloning an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const s=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[s+t])}return new dh(new this.array.constructor(e),this.itemSize,this.normalized)}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.clone(e)),new su(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){Xo("InterleavedBufferAttribute.toJSON(): Serializing an interleaved buffer attribute will de-interleave buffer data.");const e=[];for(let t=0;t<this.count;t++){const s=t*this.data.stride+this.offset;for(let t=0;t<this.itemSize;t++)e.push(this.data.array[s+t])}return{itemSize:this.itemSize,type:this.array.constructor.name,array:e,normalized:this.normalized}}return void 0===e.interleavedBuffers&&(e.interleavedBuffers={}),void 0===e.interleavedBuffers[this.data.uuid]&&(e.interleavedBuffers[this.data.uuid]=this.data.toJSON(e)),{isInterleavedBufferAttribute:!0,itemSize:this.itemSize,data:this.data.uuid,offset:this.offset,normalized:this.normalized}}}class iu extends ih{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new eh(16777215),this.map=null,this.alphaMap=null,this.rotation=0,this.sizeAttenuation=!0,this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.rotation=e.rotation,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}class ru extends Ra{constructor(e=null,t=1,s=1,i,r,n,o,a,l=1003,h=1003,u,c){super(null,n,o,a,l,h,i,r,u,c),this.isDataTexture=!0,this.image={data:e,width:t,height:s},this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1}}class nu extends dh{constructor(e,t,s,i=1){super(e,t,s),this.isInstancedBufferAttribute=!0,this.meshPerAttribute=i}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}toJSON(){const e=super.toJSON();return e.meshPerAttribute=this.meshPerAttribute,e.isInstancedBufferAttribute=!0,e}}const ou=new da,au=new da,lu=new fa;class hu{constructor(e=new da(1,0,0),t=0){this.isPlane=!0,this.normal=e,this.constant=t}set(e,t){return this.normal.copy(e),this.constant=t,this}setComponents(e,t,s,i){return this.normal.set(e,t,s),this.constant=i,this}setFromNormalAndCoplanarPoint(e,t){return this.normal.copy(e),this.constant=-t.dot(this.normal),this}setFromCoplanarPoints(e,t,s){const i=ou.subVectors(s,t).cross(au.subVectors(e,t)).normalize();return this.setFromNormalAndCoplanarPoint(i,e),this}copy(e){return this.normal.copy(e.normal),this.constant=e.constant,this}normalize(){const e=1/this.normal.length();return this.normal.multiplyScalar(e),this.constant*=e,this}negate(){return this.constant*=-1,this.normal.negate(),this}distanceToPoint(e){return this.normal.dot(e)+this.constant}distanceToSphere(e){return this.distanceToPoint(e.center)-e.radius}projectPoint(e,t){return t.copy(e).addScaledVector(this.normal,-this.distanceToPoint(e))}intersectLine(e,t){const s=e.delta(ou),i=this.normal.dot(s);if(0===i)return 0===this.distanceToPoint(e.start)?t.copy(e.start):null;const r=-(e.start.dot(this.normal)+this.constant)/i;return r<0||r>1?null:t.copy(e.start).addScaledVector(s,r)}intersectsLine(e){const t=this.distanceToPoint(e.start),s=this.distanceToPoint(e.end);return t<0&&s>0||s<0&&t>0}intersectsBox(e){return e.intersectsPlane(this)}intersectsSphere(e){return e.intersectsPlane(this)}coplanarPoint(e){return e.copy(this.normal).multiplyScalar(-this.constant)}applyMatrix4(e,t){const s=t||lu.getNormalMatrix(e),i=this.coplanarPoint(ou).applyMatrix4(e),r=this.normal.applyMatrix3(s).normalize();return this.constant=-i.dot(r),this}translate(e){return this.constant-=e.dot(this.normal),this}equals(e){return e.normal.equals(this.normal)&&e.constant===this.constant}clone(){return(new this.constructor).copy(this)}}const uu=new Ja,cu=new ua(.5,.5),du=new da;class pu{constructor(e=new hu,t=new hu,s=new hu,i=new hu,r=new hu,n=new hu){this.planes=[e,t,s,i,r,n]}set(e,t,s,i,r,n){const o=this.planes;return o[0].copy(e),o[1].copy(t),o[2].copy(s),o[3].copy(i),o[4].copy(r),o[5].copy(n),this}copy(e){const t=this.planes;for(let s=0;s<6;s++)t[s].copy(e.planes[s]);return this}setFromProjectionMatrix(e,t=2e3,s=!1){const i=this.planes,r=e.elements,n=r[0],o=r[1],a=r[2],l=r[3],h=r[4],u=r[5],c=r[6],d=r[7],p=r[8],m=r[9],f=r[10],g=r[11],y=r[12],x=r[13],b=r[14],_=r[15];if(i[0].setComponents(l-n,d-h,g-p,_-y).normalize(),i[1].setComponents(l+n,d+h,g+p,_+y).normalize(),i[2].setComponents(l+o,d+u,g+m,_+x).normalize(),i[3].setComponents(l-o,d-u,g-m,_-x).normalize(),s)i[4].setComponents(a,c,f,b).normalize(),i[5].setComponents(l-a,d-c,g-f,_-b).normalize();else if(i[4].setComponents(l-a,d-c,g-f,_-b).normalize(),t===ko)i[5].setComponents(l+a,d+c,g+f,_+b).normalize();else{if(t!==Uo)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);i[5].setComponents(a,c,f,b).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),uu.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),uu.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(uu)}intersectsSprite(e){uu.center.set(0,0,0);const t=cu.distanceTo(e.center);return uu.radius=.7071067811865476+t,uu.applyMatrix4(e.matrixWorld),this.intersectsSphere(uu)}intersectsSphere(e){const t=this.planes,s=e.center,i=-e.radius;for(let e=0;e<6;e++){if(t[e].distanceToPoint(s)<i)return!1}return!0}intersectsBox(e){const t=this.planes;for(let s=0;s<6;s++){const i=t[s];if(du.x=i.normal.x>0?e.max.x:e.min.x,du.y=i.normal.y>0?e.max.y:e.min.y,du.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(du)<0)return!1}return!0}containsPoint(e){const t=this.planes;for(let s=0;s<6;s++)if(t[s].distanceToPoint(e)<0)return!1;return!0}clone(){return(new this.constructor).copy(this)}}const mu=new ll,fu=new pu;class gu{constructor(){this.coordinateSystem=ko}intersectsObject(e,t){if(!t.isArrayCamera||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(mu.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),fu.setFromProjectionMatrix(mu,i.coordinateSystem,i.reversedDepth),fu.intersectsObject(e))return!0}return!1}intersectsSprite(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(mu.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),fu.setFromProjectionMatrix(mu,i.coordinateSystem,i.reversedDepth),fu.intersectsSprite(e))return!0}return!1}intersectsSphere(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(mu.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),fu.setFromProjectionMatrix(mu,i.coordinateSystem,i.reversedDepth),fu.intersectsSphere(e))return!0}return!1}intersectsBox(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(mu.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),fu.setFromProjectionMatrix(mu,i.coordinateSystem,i.reversedDepth),fu.intersectsBox(e))return!0}return!1}containsPoint(e,t){if(!t||!t.cameras||0===t.cameras.length)return!1;for(let s=0;s<t.cameras.length;s++){const i=t.cameras[s];if(mu.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),fu.setFromProjectionMatrix(mu,i.coordinateSystem,i.reversedDepth),fu.containsPoint(e))return!0}return!1}clone(){return new gu}}class yu extends ih{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new eh(16777215),this.map=null,this.linewidth=1,this.linecap="round",this.linejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.linewidth=e.linewidth,this.linecap=e.linecap,this.linejoin=e.linejoin,this.fog=e.fog,this}}class xu extends ih{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new eh(16777215),this.map=null,this.alphaMap=null,this.size=1,this.sizeAttenuation=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.alphaMap=e.alphaMap,this.size=e.size,this.sizeAttenuation=e.sizeAttenuation,this.fog=e.fog,this}}class bu extends Ra{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=fn,this.minFilter=fn,this.generateMipmaps=!1,this.needsUpdate=!0}}class _u extends Ra{constructor(e,t,s=1014,i,r,n,o=1003,a=1003,l,h=1026,u=1){if(h!==Fn&&h!==On)throw new Error("DepthTexture format must be either THREE.DepthFormat or THREE.DepthStencilFormat");super({width:e,height:t,depth:u},i,r,n,o,a,h,s,l),this.isDepthTexture=!0,this.flipY=!1,this.generateMipmaps=!1,this.compareFunction=null}copy(e){return super.copy(e),this.source=new Aa(Object.assign({},e.image)),this.compareFunction=e.compareFunction,this}toJSON(e){const t=super.toJSON(e);return null!==this.compareFunction&&(t.compareFunction=this.compareFunction),t}}class wu extends _u{constructor(e,t=1014,s=301,i,r,n=1003,o=1003,a,l=1026){const h={width:e,height:e,depth:1},u=[h,h,h,h,h,h];super(e,e,t,s,i,r,n,o,a,l),this.image=u,this.isCubeDepthTexture=!0,this.isCubeTexture=!0}get images(){return this.image}set images(e){this.image=e}}class vu extends Sh{constructor(e=1,t=1,s=1,i=32,r=1,n=!1,o=0,a=2*Math.PI){super(),this.type="CylinderGeometry",this.parameters={radiusTop:e,radiusBottom:t,height:s,radialSegments:i,heightSegments:r,openEnded:n,thetaStart:o,thetaLength:a};const l=this;i=Math.floor(i),r=Math.floor(r);const h=[],u=[],c=[],d=[];let p=0;const m=[],f=s/2;let g=0;function y(s){const r=p,n=new ua,m=new da;let y=0;const x=!0===s?e:t,b=!0===s?1:-1;for(let e=1;e<=i;e++)u.push(0,f*b,0),c.push(0,b,0),d.push(.5,.5),p++;const _=p;for(let e=0;e<=i;e++){const t=e/i*a+o,s=Math.cos(t),r=Math.sin(t);m.x=x*r,m.y=f*b,m.z=x*s,u.push(m.x,m.y,m.z),c.push(0,b,0),n.x=.5*s+.5,n.y=.5*r*b+.5,d.push(n.x,n.y),p++}for(let e=0;e<i;e++){const t=r+e,i=_+e;!0===s?h.push(i,i+1,t):h.push(i+1,i,t),y+=3}l.addGroup(g,y,!0===s?1:2),g+=y}!function(){const n=new da,y=new da;let x=0;const b=(t-e)/s;for(let l=0;l<=r;l++){const h=[],g=l/r,x=g*(t-e)+e;for(let e=0;e<=i;e++){const t=e/i,r=t*a+o,l=Math.sin(r),m=Math.cos(r);y.x=x*l,y.y=-g*s+f,y.z=x*m,u.push(y.x,y.y,y.z),n.set(l,b,m).normalize(),c.push(n.x,n.y,n.z),d.push(t,1-g),h.push(p++)}m.push(h)}for(let s=0;s<i;s++)for(let i=0;i<r;i++){const n=m[i][s],o=m[i+1][s],a=m[i+1][s+1],l=m[i][s+1];(e>0||0!==i)&&(h.push(n,o,l),x+=3),(t>0||i!==r-1)&&(h.push(o,a,l),x+=3)}l.addGroup(g,x,0),g+=x}(),!1===n&&(e>0&&y(!0),t>0&&y(!1)),this.setIndex(h),this.setAttribute("position",new gh(u,3)),this.setAttribute("normal",new gh(c,3)),this.setAttribute("uv",new gh(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new vu(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class Tu extends Sh{constructor(e=1,t=1,s=1,i=1){super(),this.type="PlaneGeometry",this.parameters={width:e,height:t,widthSegments:s,heightSegments:i};const r=e/2,n=t/2,o=Math.floor(s),a=Math.floor(i),l=o+1,h=a+1,u=e/o,c=t/a,d=[],p=[],m=[],f=[];for(let e=0;e<h;e++){const t=e*c-n;for(let s=0;s<l;s++){const i=s*u-r;p.push(i,-t,0),m.push(0,0,1),f.push(s/o),f.push(1-e/a)}}for(let e=0;e<a;e++)for(let t=0;t<o;t++){const s=t+l*e,i=t+l*(e+1),r=t+1+l*(e+1),n=t+1+l*e;d.push(s,i,n),d.push(i,r,n)}this.setIndex(d),this.setAttribute("position",new gh(p,3)),this.setAttribute("normal",new gh(m,3)),this.setAttribute("uv",new gh(f,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Tu(e.width,e.height,e.widthSegments,e.heightSegments)}}class Su extends Sh{constructor(e=1,t=32,s=16,i=0,r=2*Math.PI,n=0,o=Math.PI){super(),this.type="SphereGeometry",this.parameters={radius:e,widthSegments:t,heightSegments:s,phiStart:i,phiLength:r,thetaStart:n,thetaLength:o},t=Math.max(3,Math.floor(t)),s=Math.max(2,Math.floor(s));const a=Math.min(n+o,Math.PI);let l=0;const h=[],u=new da,c=new da,d=[],p=[],m=[],f=[];for(let d=0;d<=s;d++){const g=[],y=d/s;let x=0;0===d&&0===n?x=.5/t:d===s&&a===Math.PI&&(x=-.5/t);for(let s=0;s<=t;s++){const a=s/t;u.x=-e*Math.cos(i+a*r)*Math.sin(n+y*o),u.y=e*Math.cos(n+y*o),u.z=e*Math.sin(i+a*r)*Math.sin(n+y*o),p.push(u.x,u.y,u.z),c.copy(u).normalize(),m.push(c.x,c.y,c.z),f.push(a+x,1-y),g.push(l++)}h.push(g)}for(let e=0;e<s;e++)for(let i=0;i<t;i++){const t=h[e][i+1],r=h[e][i],o=h[e+1][i],l=h[e+1][i+1];(0!==e||n>0)&&d.push(t,r,l),(e!==s-1||a<Math.PI)&&d.push(r,o,l)}this.setIndex(d),this.setAttribute("position",new gh(p,3)),this.setAttribute("normal",new gh(m,3)),this.setAttribute("uv",new gh(f,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Su(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class Mu extends ih{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new eh(0),this.transparent=!0,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.fog=e.fog,this}}class Au extends ih{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new eh(16777215),this.roughness=1,this.metalness=0,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new eh(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ua(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.roughnessMap=null,this.metalnessMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new xl,this.envMapIntensity=1,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={STANDARD:""},this.color.copy(e.color),this.roughness=e.roughness,this.metalness=e.metalness,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.roughnessMap=e.roughnessMap,this.metalnessMap=e.metalnessMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.envMapIntensity=e.envMapIntensity,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Nu extends Au{constructor(e){super(),this.isMeshPhysicalMaterial=!0,this.defines={STANDARD:"",PHYSICAL:""},this.type="MeshPhysicalMaterial",this.anisotropyRotation=0,this.anisotropyMap=null,this.clearcoatMap=null,this.clearcoatRoughness=0,this.clearcoatRoughnessMap=null,this.clearcoatNormalScale=new ua(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return ra(2.5*(this.ior-1)/(this.ior+1),0,1)},set:function(e){this.ior=(1+.4*e)/(1-.4*e)}}),this.iridescenceMap=null,this.iridescenceIOR=1.3,this.iridescenceThicknessRange=[100,400],this.iridescenceThicknessMap=null,this.sheenColor=new eh(0),this.sheenColorMap=null,this.sheenRoughness=1,this.sheenRoughnessMap=null,this.transmissionMap=null,this.thickness=0,this.thicknessMap=null,this.attenuationDistance=1/0,this.attenuationColor=new eh(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new eh(1,1,1),this.specularColorMap=null,this._anisotropy=0,this._clearcoat=0,this._dispersion=0,this._iridescence=0,this._sheen=0,this._transmission=0,this.setValues(e)}get anisotropy(){return this._anisotropy}set anisotropy(e){this._anisotropy>0!=e>0&&this.version++,this._anisotropy=e}get clearcoat(){return this._clearcoat}set clearcoat(e){this._clearcoat>0!=e>0&&this.version++,this._clearcoat=e}get iridescence(){return this._iridescence}set iridescence(e){this._iridescence>0!=e>0&&this.version++,this._iridescence=e}get dispersion(){return this._dispersion}set dispersion(e){this._dispersion>0!=e>0&&this.version++,this._dispersion=e}get sheen(){return this._sheen}set sheen(e){this._sheen>0!=e>0&&this.version++,this._sheen=e}get transmission(){return this._transmission}set transmission(e){this._transmission>0!=e>0&&this.version++,this._transmission=e}copy(e){return super.copy(e),this.defines={STANDARD:"",PHYSICAL:""},this.anisotropy=e.anisotropy,this.anisotropyRotation=e.anisotropyRotation,this.anisotropyMap=e.anisotropyMap,this.clearcoat=e.clearcoat,this.clearcoatMap=e.clearcoatMap,this.clearcoatRoughness=e.clearcoatRoughness,this.clearcoatRoughnessMap=e.clearcoatRoughnessMap,this.clearcoatNormalMap=e.clearcoatNormalMap,this.clearcoatNormalScale.copy(e.clearcoatNormalScale),this.dispersion=e.dispersion,this.ior=e.ior,this.iridescence=e.iridescence,this.iridescenceMap=e.iridescenceMap,this.iridescenceIOR=e.iridescenceIOR,this.iridescenceThicknessRange=[...e.iridescenceThicknessRange],this.iridescenceThicknessMap=e.iridescenceThicknessMap,this.sheen=e.sheen,this.sheenColor.copy(e.sheenColor),this.sheenColorMap=e.sheenColorMap,this.sheenRoughness=e.sheenRoughness,this.sheenRoughnessMap=e.sheenRoughnessMap,this.transmission=e.transmission,this.transmissionMap=e.transmissionMap,this.thickness=e.thickness,this.thicknessMap=e.thicknessMap,this.attenuationDistance=e.attenuationDistance,this.attenuationColor.copy(e.attenuationColor),this.specularIntensity=e.specularIntensity,this.specularIntensityMap=e.specularIntensityMap,this.specularColor.copy(e.specularColor),this.specularColorMap=e.specularColorMap,this}}class Eu extends ih{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new eh(16777215),this.specular=new eh(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new eh(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ua(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new xl,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.specular.copy(e.specular),this.shininess=e.shininess,this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Cu extends ih{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new eh(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new eh(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ua(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.gradientMap=e.gradientMap,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.fog=e.fog,this}}class Ru extends ih{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ua(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.setValues(e)}copy(e){return super.copy(e),this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this}}class Pu extends ih{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new eh(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new eh(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ua(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new xl,this.combine=0,this.reflectivity=1,this.refractionRatio=.98,this.wireframe=!1,this.wireframeLinewidth=1,this.wireframeLinecap="round",this.wireframeLinejoin="round",this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.color.copy(e.color),this.map=e.map,this.lightMap=e.lightMap,this.lightMapIntensity=e.lightMapIntensity,this.aoMap=e.aoMap,this.aoMapIntensity=e.aoMapIntensity,this.emissive.copy(e.emissive),this.emissiveMap=e.emissiveMap,this.emissiveIntensity=e.emissiveIntensity,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.specularMap=e.specularMap,this.alphaMap=e.alphaMap,this.envMap=e.envMap,this.envMapRotation.copy(e.envMapRotation),this.combine=e.combine,this.reflectivity=e.reflectivity,this.refractionRatio=e.refractionRatio,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.wireframeLinecap=e.wireframeLinecap,this.wireframeLinejoin=e.wireframeLinejoin,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Bu extends ih{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new eh(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new ua(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.alphaMap=null,this.wireframe=!1,this.wireframeLinewidth=1,this.flatShading=!1,this.fog=!0,this.setValues(e)}copy(e){return super.copy(e),this.defines={MATCAP:""},this.color.copy(e.color),this.matcap=e.matcap,this.map=e.map,this.bumpMap=e.bumpMap,this.bumpScale=e.bumpScale,this.normalMap=e.normalMap,this.normalMapType=e.normalMapType,this.normalScale.copy(e.normalScale),this.displacementMap=e.displacementMap,this.displacementScale=e.displacementScale,this.displacementBias=e.displacementBias,this.alphaMap=e.alphaMap,this.wireframe=e.wireframe,this.wireframeLinewidth=e.wireframeLinewidth,this.flatShading=e.flatShading,this.fog=e.fog,this}}class Iu extends yu{constructor(e){super(),this.isLineDashedMaterial=!0,this.type="LineDashedMaterial",this.scale=1,this.dashSize=3,this.gapSize=1,this.setValues(e)}copy(e){return super.copy(e),this.scale=e.scale,this.dashSize=e.dashSize,this.gapSize=e.gapSize,this}}class Du extends Ll{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new eh(e),this.intensity=t}dispose(){this.dispatchEvent({type:"dispose"})}copy(e,t){return super.copy(e,t),this.color.copy(e.color),this.intensity=e.intensity,this}toJSON(e){const t=super.toJSON(e);return t.object.color=this.color.getHex(),t.object.intensity=this.intensity,t}}class Lu extends Du{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Ll.DEFAULT_UP),this.updateMatrix(),this.groundColor=new eh(t)}copy(e,t){return super.copy(e,t),this.groundColor.copy(e.groundColor),this}toJSON(e){const t=super.toJSON(e);return t.object.groundColor=this.groundColor.getHex(),t}}const Fu=new ll,Ou=new da,Vu=new da;class zu{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new ua(512,512),this.mapType=wn,this.map=null,this.mapPass=null,this.matrix=new ll,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new pu,this._frameExtents=new ua(1,1),this._viewportCount=1,this._viewports=[new Pa(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;Ou.setFromMatrixPosition(e.matrixWorld),t.position.copy(Ou),Vu.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Vu),t.updateMatrixWorld(),Fu.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Fu,t.coordinateSystem,t.reversedDepth),t.reversedDepth?s.set(.5,0,0,.5,0,.5,0,.5,0,0,1,0,0,0,0,1):s.set(.5,0,0,.5,0,.5,0,.5,0,0,.5,.5,0,0,0,1),s.multiply(Fu)}getViewport(e){return this._viewports[e]}getFrameExtents(){return this._frameExtents}dispose(){this.map&&this.map.dispose(),this.mapPass&&this.mapPass.dispose()}copy(e){return this.camera=e.camera.clone(),this.intensity=e.intensity,this.bias=e.bias,this.radius=e.radius,this.autoUpdate=e.autoUpdate,this.needsUpdate=e.needsUpdate,this.normalBias=e.normalBias,this.blurSamples=e.blurSamples,this.mapSize.copy(e.mapSize),this}clone(){return(new this.constructor).copy(this)}toJSON(){const e={};return 1!==this.intensity&&(e.intensity=this.intensity),0!==this.bias&&(e.bias=this.bias),0!==this.normalBias&&(e.normalBias=this.normalBias),1!==this.radius&&(e.radius=this.radius),512===this.mapSize.x&&512===this.mapSize.y||(e.mapSize=this.mapSize.toArray()),e.camera=this.camera.toJSON(!1).object,delete e.camera.matrix,e}}class ku extends zu{constructor(){super(new Wh(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,s=2*sa*e.angle*this.focus,i=this.mapSize.width/this.mapSize.height*this.aspect,r=e.distance||t.far;s===t.fov&&i===t.aspect&&r===t.far||(t.fov=s,t.aspect=i,t.far=r,t.updateProjectionMatrix()),super.updateMatrices(e)}copy(e){return super.copy(e),this.focus=e.focus,this}}class Uu extends Du{constructor(e,t,s=0,i=Math.PI/3,r=0,n=2){super(e,t),this.isSpotLight=!0,this.type="SpotLight",this.position.copy(Ll.DEFAULT_UP),this.updateMatrix(),this.target=new Ll,this.distance=s,this.angle=i,this.penumbra=r,this.decay=n,this.map=null,this.shadow=new ku}get power(){return this.intensity*Math.PI}set power(e){this.intensity=e/Math.PI}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.angle=e.angle,this.penumbra=e.penumbra,this.decay=e.decay,this.target=e.target.clone(),this.map=e.map,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.angle=this.angle,t.object.decay=this.decay,t.object.penumbra=this.penumbra,t.object.target=this.target.uuid,this.map&&this.map.isTexture&&(t.object.map=this.map.toJSON(e).uuid),t.object.shadow=this.shadow.toJSON(),t}}class Gu extends zu{constructor(){super(new Wh(90,1,.5,500)),this.isPointLightShadow=!0}}class ju extends Du{constructor(e,t,s=0,i=2){super(e,t),this.isPointLight=!0,this.type="PointLight",this.distance=s,this.decay=i,this.shadow=new Gu}get power(){return 4*this.intensity*Math.PI}set power(e){this.intensity=e/(4*Math.PI)}dispose(){super.dispose(),this.shadow.dispose()}copy(e,t){return super.copy(e,t),this.distance=e.distance,this.decay=e.decay,this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.distance=this.distance,t.object.decay=this.decay,t.object.shadow=this.shadow.toJSON(),t}}class $u extends Uh{constructor(e=-1,t=1,s=1,i=-1,r=.1,n=2e3){super(),this.isOrthographicCamera=!0,this.type="OrthographicCamera",this.zoom=1,this.view=null,this.left=e,this.right=t,this.top=s,this.bottom=i,this.near=r,this.far=n,this.updateProjectionMatrix()}copy(e,t){return super.copy(e,t),this.left=e.left,this.right=e.right,this.top=e.top,this.bottom=e.bottom,this.near=e.near,this.far=e.far,this.zoom=e.zoom,this.view=null===e.view?null:Object.assign({},e.view),this}setViewOffset(e,t,s,i,r,n){null===this.view&&(this.view={enabled:!0,fullWidth:1,fullHeight:1,offsetX:0,offsetY:0,width:1,height:1}),this.view.enabled=!0,this.view.fullWidth=e,this.view.fullHeight=t,this.view.offsetX=s,this.view.offsetY=i,this.view.width=r,this.view.height=n,this.updateProjectionMatrix()}clearViewOffset(){null!==this.view&&(this.view.enabled=!1),this.updateProjectionMatrix()}updateProjectionMatrix(){const e=(this.right-this.left)/(2*this.zoom),t=(this.top-this.bottom)/(2*this.zoom),s=(this.right+this.left)/2,i=(this.top+this.bottom)/2;let r=s-e,n=s+e,o=i+t,a=i-t;if(null!==this.view&&this.view.enabled){const e=(this.right-this.left)/this.view.fullWidth/this.zoom,t=(this.top-this.bottom)/this.view.fullHeight/this.zoom;r+=e*this.view.offsetX,n=r+e*this.view.width,o-=t*this.view.offsetY,a=o-t*this.view.height}this.projectionMatrix.makeOrthographic(r,n,o,a,this.near,this.far,this.coordinateSystem,this.reversedDepth),this.projectionMatrixInverse.copy(this.projectionMatrix).invert()}toJSON(e){const t=super.toJSON(e);return t.object.zoom=this.zoom,t.object.left=this.left,t.object.right=this.right,t.object.top=this.top,t.object.bottom=this.bottom,t.object.near=this.near,t.object.far=this.far,null!==this.view&&(t.object.view=Object.assign({},this.view)),t}}class Wu extends zu{constructor(){super(new $u(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class Hu extends Du{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Ll.DEFAULT_UP),this.updateMatrix(),this.target=new Ll,this.shadow=new Wu}dispose(){super.dispose(),this.shadow.dispose()}copy(e){return super.copy(e),this.target=e.target.clone(),this.shadow=e.shadow.clone(),this}toJSON(e){const t=super.toJSON(e);return t.object.shadow=this.shadow.toJSON(),t.object.target=this.target.uuid,t}}class qu extends Du{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class Xu extends Du{constructor(e,t,s=10,i=10){super(e,t),this.isRectAreaLight=!0,this.type="RectAreaLight",this.width=s,this.height=i}get power(){return this.intensity*this.width*this.height*Math.PI}set power(e){this.intensity=e/(this.width*this.height*Math.PI)}copy(e){return super.copy(e),this.width=e.width,this.height=e.height,this}toJSON(e){const t=super.toJSON(e);return t.object.width=this.width,t.object.height=this.height,t}}class Yu{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new da)}set(e){for(let t=0;t<9;t++)this.coefficients[t].copy(e[t]);return this}zero(){for(let e=0;e<9;e++)this.coefficients[e].set(0,0,0);return this}getAt(e,t){const s=e.x,i=e.y,r=e.z,n=this.coefficients;return t.copy(n[0]).multiplyScalar(.282095),t.addScaledVector(n[1],.488603*i),t.addScaledVector(n[2],.488603*r),t.addScaledVector(n[3],.488603*s),t.addScaledVector(n[4],s*i*1.092548),t.addScaledVector(n[5],i*r*1.092548),t.addScaledVector(n[6],.315392*(3*r*r-1)),t.addScaledVector(n[7],s*r*1.092548),t.addScaledVector(n[8],.546274*(s*s-i*i)),t}getIrradianceAt(e,t){const s=e.x,i=e.y,r=e.z,n=this.coefficients;return t.copy(n[0]).multiplyScalar(.886227),t.addScaledVector(n[1],1.023328*i),t.addScaledVector(n[2],1.023328*r),t.addScaledVector(n[3],1.023328*s),t.addScaledVector(n[4],.858086*s*i),t.addScaledVector(n[5],.858086*i*r),t.addScaledVector(n[6],.743125*r*r-.247708),t.addScaledVector(n[7],.858086*s*r),t.addScaledVector(n[8],.429043*(s*s-i*i)),t}add(e){for(let t=0;t<9;t++)this.coefficients[t].add(e.coefficients[t]);return this}addScaledSH(e,t){for(let s=0;s<9;s++)this.coefficients[s].addScaledVector(e.coefficients[s],t);return this}scale(e){for(let t=0;t<9;t++)this.coefficients[t].multiplyScalar(e);return this}lerp(e,t){for(let s=0;s<9;s++)this.coefficients[s].lerp(e.coefficients[s],t);return this}equals(e){for(let t=0;t<9;t++)if(!this.coefficients[t].equals(e.coefficients[t]))return!1;return!0}copy(e){return this.set(e.coefficients)}clone(){return(new this.constructor).copy(this)}fromArray(e,t=0){const s=this.coefficients;for(let i=0;i<9;i++)s[i].fromArray(e,t+3*i);return this}toArray(e=[],t=0){const s=this.coefficients;for(let i=0;i<9;i++)s[i].toArray(e,t+3*i);return e}static getBasisAt(e,t){const s=e.x,i=e.y,r=e.z;t[0]=.282095,t[1]=.488603*i,t[2]=.488603*r,t[3]=.488603*s,t[4]=1.092548*s*i,t[5]=1.092548*i*r,t[6]=.315392*(3*r*r-1),t[7]=1.092548*s*r,t[8]=.546274*(s*s-i*i)}}class Zu extends Du{constructor(e=new Yu,t=1){super(void 0,t),this.isLightProbe=!0,this.sh=e}copy(e){return super.copy(e),this.sh.copy(e.sh),this}toJSON(e){const t=super.toJSON(e);return t.object.sh=this.sh.toArray(),t}}class Qu extends Wh{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class Ku extends eu{constructor(e,t,s=1){super(e,t),this.isInstancedInterleavedBuffer=!0,this.meshPerAttribute=s}copy(e){return super.copy(e),this.meshPerAttribute=e.meshPerAttribute,this}clone(e){const t=super.clone(e);return t.meshPerAttribute=this.meshPerAttribute,t}toJSON(e){const t=super.toJSON(e);return t.isInstancedInterleavedBuffer=!0,t.meshPerAttribute=this.meshPerAttribute,t}}class Ju{constructor(e,t,s,i){Ju.prototype.isMatrix2=!0,this.elements=[1,0,0,1],void 0!==e&&this.set(e,t,s,i)}identity(){return this.set(1,0,0,1),this}fromArray(e,t=0){for(let s=0;s<4;s++)this.elements[s]=e[s+t];return this}set(e,t,s,i){const r=this.elements;return r[0]=e,r[2]=t,r[1]=s,r[3]=i,this}}function ec(e,t,s,i){const r=function(e){switch(e){case wn:case vn:return{byteLength:1,components:1};case Sn:case Tn:case En:return{byteLength:2,components:1};case Cn:case Rn:return{byteLength:2,components:4};case An:case Mn:case Nn:return{byteLength:4,components:1};case Bn:case In:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}(i);switch(s){case 1021:return e*t;case Vn:case zn:return e*t/r.components*r.byteLength;case kn:case Un:return e*t*2/r.components*r.byteLength;case Dn:return e*t*3/r.components*r.byteLength;case Ln:case Gn:return e*t*4/r.components*r.byteLength;case jn:case $n:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Wn:case Hn:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Xn:case Zn:return Math.max(e,16)*Math.max(t,8)/4;case qn:case Yn:return Math.max(e,8)*Math.max(t,8)/2;case Qn:case Kn:case eo:case to:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Jn:case so:case io:case ro:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case no:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case oo:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case ao:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case lo:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case ho:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case uo:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case co:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case po:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case mo:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case fo:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case go:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case yo:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case xo:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case bo:case 36494:case 36495:return Math.ceil(e/4)*Math.ceil(t/4)*16;case _o:case wo:return Math.ceil(e/4)*Math.ceil(t/4)*8;case vo:case To:return Math.ceil(e/4)*Math.ceil(t/4)*16}throw new Error(`Unable to determine texture byte length for ${s} format.`)}"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("register",{detail:{revision:Xr}})),"undefined"!=typeof window&&(window.__THREE__?Yo("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Xr)
7
- /**
8
- * @license
9
- * Copyright 2010-2025 Three.js Authors
10
- * SPDX-License-Identifier: MIT
11
- */;const tc=["alphaMap","alphaTest","anisotropy","anisotropyMap","anisotropyRotation","aoMap","aoMapIntensity","attenuationColor","attenuationDistance","bumpMap","clearcoat","clearcoatMap","clearcoatNormalMap","clearcoatNormalScale","clearcoatRoughness","color","dispersion","displacementMap","emissive","emissiveIntensity","emissiveMap","envMap","envMapIntensity","gradientMap","ior","iridescence","iridescenceIOR","iridescenceMap","iridescenceThicknessMap","lightMap","lightMapIntensity","map","matcap","metalness","metalnessMap","normalMap","normalScale","opacity","roughness","roughnessMap","sheen","sheenColor","sheenColorMap","sheenRoughnessMap","shininess","specular","specularColor","specularColorMap","specularIntensity","specularIntensityMap","specularMap","thickness","transmission","transmissionMap"],sc=new WeakMap;class ic{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=tc,this.renderId=0}firstInitialization(e){return!1===this.renderObjects.has(e)&&(this.getRenderObjectData(e),!0)}needsVelocity(e){const t=e.getMRT();return null!==t&&t.has("velocity")}getRenderObjectData(e){let t=this.renderObjects.get(e);if(void 0===t){const{geometry:s,material:i,object:r}=e;if(t={material:this.getMaterialData(i),geometry:{id:s.id,attributes:this.getAttributesData(s.attributes),indexVersion:s.index?s.index.version:null,drawRange:{start:s.drawRange.start,count:s.drawRange.count}},worldMatrix:r.matrixWorld.clone()},r.center&&(t.center=r.center.clone()),r.morphTargetInfluences&&(t.morphTargetInfluences=r.morphTargetInfluences.slice()),null!==e.bundle&&(t.version=e.bundle.version),t.material.transmission>0){const{width:s,height:i}=e.context;t.bufferWidth=s,t.bufferHeight=i}t.lights=this.getLightsData(e.lightsNode.getLights()),this.renderObjects.set(e,t)}return t}getAttributesData(e){const t={};for(const s in e){const i=e[s];t[s]={version:i.version}}return t}containsNode(e){const t=e.material;for(const e in t)if(t[e]&&t[e].isNode)return!0;return!!(e.context.modelViewMatrix||e.context.modelNormalViewMatrix||e.context.getAO||e.context.getShadow)}getMaterialData(e){const t={};for(const s of this.refreshUniforms){const i=e[s];null!=i&&("object"==typeof i&&void 0!==i.clone?!0===i.isTexture?t[s]={id:i.id,version:i.version}:t[s]=i.clone():t[s]=i)}return t}equals(e,t){const{object:s,material:i,geometry:r}=e,n=this.getRenderObjectData(e);if(!0!==n.worldMatrix.equals(s.matrixWorld))return n.worldMatrix.copy(s.matrixWorld),!1;const o=n.material;for(const e in o){const t=o[e],s=i[e];if(void 0!==t.equals){if(!1===t.equals(s))return t.copy(s),!1}else if(!0===s.isTexture){if(t.id!==s.id||t.version!==s.version)return t.id=s.id,t.version=s.version,!1}else if(t!==s)return o[e]=s,!1}if(o.transmission>0){const{width:t,height:s}=e.context;if(n.bufferWidth!==t||n.bufferHeight!==s)return n.bufferWidth=t,n.bufferHeight=s,!1}const a=n.geometry,l=r.attributes,h=a.attributes,u=Object.keys(h),c=Object.keys(l);if(a.id!==r.id)return a.id=r.id,!1;if(u.length!==c.length)return n.geometry.attributes=this.getAttributesData(l),!1;for(const e of u){const t=h[e],s=l[e];if(void 0===s)return delete h[e],!1;if(t.version!==s.version)return t.version=s.version,!1}const d=r.index,p=a.indexVersion,m=d?d.version:null;if(p!==m)return a.indexVersion=m,!1;if(a.drawRange.start!==r.drawRange.start||a.drawRange.count!==r.drawRange.count)return a.drawRange.start=r.drawRange.start,a.drawRange.count=r.drawRange.count,!1;if(n.morphTargetInfluences){let e=!1;for(let t=0;t<n.morphTargetInfluences.length;t++)n.morphTargetInfluences[t]!==s.morphTargetInfluences[t]&&(n.morphTargetInfluences[t]=s.morphTargetInfluences[t],e=!0);if(e)return!1}if(n.lights)for(let e=0;e<t.length;e++)if(n.lights[e].map!==t[e].map)return!1;return n.center&&!1===n.center.equals(s.center)?(n.center.copy(s.center),!0):(null!==e.bundle&&(n.version=e.bundle.version),!0)}getLightsData(e){const t=[];for(const s of e)!0===s.isSpotLight&&null!==s.map&&t.push({map:s.map.version});return t}getLights(e,t){if(sc.has(e)){const s=sc.get(e);if(s.renderId===t)return s.lightsData}const s=this.getLightsData(e.getLights());return sc.set(e,{renderId:t,lightsData:s}),s}needsRefresh(e,t){if(this.hasNode||this.hasAnimation||this.firstInitialization(e)||this.needsVelocity(t.renderer))return!0;const{renderId:s}=t;if(this.renderId!==s)return this.renderId=s,!0;const i=!0===e.object.static,r=null!==e.bundle&&!0===e.bundle.static&&this.getRenderObjectData(e).version===e.bundle.version;if(i||r)return!1;const n=this.getLights(e.lightsNode,s);return!0!==this.equals(e,n)}}function rc(e,t=0){let s=3735928559^t,i=1103547991^t;if(e instanceof Array)for(let t,r=0;r<e.length;r++)t=e[r],s=Math.imul(s^t,2654435761),i=Math.imul(i^t,1597334677);else for(let t,r=0;r<e.length;r++)t=e.charCodeAt(r),s=Math.imul(s^t,2654435761),i=Math.imul(i^t,1597334677);return s=Math.imul(s^s>>>16,2246822507),s^=Math.imul(i^i>>>13,3266489909),i=Math.imul(i^i>>>16,2246822507),i^=Math.imul(s^s>>>13,3266489909),4294967296*(2097151&i)+(s>>>0)}const nc=e=>rc(e),oc=e=>rc(e),ac=(...e)=>rc(e),lc=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),hc=new WeakMap;function uc(e){return lc.get(e)}function cc(e){if(/[iu]?vec\d/.test(e))return e.startsWith("ivec")?Int32Array:e.startsWith("uvec")?Uint32Array:Float32Array;if(/mat\d/.test(e))return Float32Array;if(/float/.test(e))return Float32Array;if(/uint/.test(e))return Uint32Array;if(/int/.test(e))return Int32Array;throw new Error(`THREE.NodeUtils: Unsupported type: ${e}`)}function dc(e){return/float|int|uint/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?9:/mat4/.test(e)?16:void Zo("TSL: Unsupported type:",e)}function pc(e){return/float|int|uint/.test(e)?1:/vec2/.test(e)?2:/vec3/.test(e)?3:/vec4/.test(e)||/mat2/.test(e)?4:/mat3/.test(e)?12:/mat4/.test(e)?16:void Zo("TSL: Unsupported type:",e)}function mc(e){return/float|int|uint/.test(e)?4:/vec2/.test(e)?8:/vec3/.test(e)||/vec4/.test(e)?16:/mat2/.test(e)?8:/mat3/.test(e)||/mat4/.test(e)?16:void Zo("TSL: Unsupported type:",e)}function fc(e){if(null==e)return null;const t=typeof e;return!0===e.isNode?"node":"number"===t?"float":"boolean"===t?"bool":"string"===t?"string":"function"===t?"shader":!0===e.isVector2?"vec2":!0===e.isVector3?"vec3":!0===e.isVector4?"vec4":!0===e.isMatrix2?"mat2":!0===e.isMatrix3?"mat3":!0===e.isMatrix4?"mat4":!0===e.isColor?"color":e instanceof ArrayBuffer?"ArrayBuffer":null}function gc(e,...t){const s=e?e.slice(-4):void 0;return 1===t.length&&("vec2"===s?t=[t[0],t[0]]:"vec3"===s?t=[t[0],t[0],t[0]]:"vec4"===s&&(t=[t[0],t[0],t[0],t[0]])),"color"===e?new eh(...t):"vec2"===s?new ua(...t):"vec3"===s?new da(...t):"vec4"===s?new Pa(...t):"mat2"===s?new Ju(...t):"mat3"===s?new fa(...t):"mat4"===s?new ll(...t):"bool"===e?t[0]||!1:"float"===e||"int"===e||"uint"===e?t[0]||0:"string"===e?t[0]||"":"ArrayBuffer"===e?bc(t[0]):null}function yc(e){let t=hc.get(e);return void 0===t&&(t={},hc.set(e,t)),t}function xc(e){let t="";const s=new Uint8Array(e);for(let e=0;e<s.length;e++)t+=String.fromCharCode(s[e]);return btoa(t)}function bc(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0)).buffer}const _c={VERTEX:"vertex",FRAGMENT:"fragment"},wc={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},vc={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},Tc=["fragment","vertex"],Sc=["setup","analyze","generate"],Mc=[...Tc,"compute"],Ac=["x","y","z","w"],Nc={analyze:"setup",generate:"analyze"};let Ec=0;class Cc extends Ko{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=wc.NONE,this.updateBeforeType=wc.NONE,this.updateAfterType=wc.NONE,this.uuid=ha.generateUUID(),this.version=0,this.name="",this.global=!1,this.parents=!1,this.isNode=!0,this._beforeNodes=null,this._cacheKey=null,this._cacheKeyVersion=0,Object.defineProperty(this,"id",{value:Ec++})}set needsUpdate(e){!0===e&&this.version++}get type(){return this.constructor.type}onUpdate(e,t){return this.updateType=t,this.update=e.bind(this),this}onFrameUpdate(e){return this.onUpdate(e,wc.FRAME)}onRenderUpdate(e){return this.onUpdate(e,wc.RENDER)}onObjectUpdate(e){return this.onUpdate(e,wc.OBJECT)}onReference(e){return this.updateReference=e.bind(this),this}updateReference(){return this}isGlobal(){return this.global}*getChildren(){for(const{childNode:e}of this._getChildren())yield e}dispose(){this.dispatchEvent({type:"dispose"})}traverse(e){e(this);for(const t of this.getChildren())t.traverse(e)}_getChildren(e=new Set){const t=[];e.add(this);for(const s of Object.getOwnPropertyNames(this)){const i=this[s];if(!0!==s.startsWith("_")&&!e.has(i))if(!0===Array.isArray(i))for(let e=0;e<i.length;e++){const r=i[e];r&&!0===r.isNode&&t.push({property:s,index:e,childNode:r})}else if(i&&!0===i.isNode)t.push({property:s,childNode:i});else if(i&&Object.getPrototypeOf(i)===Object.prototype)for(const e in i){if(!0===e.startsWith("_"))continue;const r=i[e];r&&!0===r.isNode&&t.push({property:s,index:e,childNode:r})}}return t}getCacheKey(e=!1,t=null){if(!0===(e=e||this.version!==this._cacheKeyVersion)||null===this._cacheKey){null===t&&(t=new Set);const s=[];for(const{property:i,childNode:r}of this._getChildren(t))s.push(nc(i.slice(0,-4)),r.getCacheKey(e,t));this._cacheKey=ac(oc(s),this.customCacheKey()),this._cacheKeyVersion=this.version}return this._cacheKey}customCacheKey(){return this.id}getScope(){return this}getHash(){return this.uuid}getUpdateType(){return this.updateType}getUpdateBeforeType(){return this.updateBeforeType}getUpdateAfterType(){return this.updateAfterType}getElementType(e){const t=this.getNodeType(e);return e.getElementType(t)}getMemberType(){return"void"}getNodeType(e){const t=e.getNodeProperties(this);return t.outputNode?t.outputNode.getNodeType(e):this.nodeType}getShared(e){const t=this.getHash(e);return e.getNodeFromHash(t)||this}getArrayCount(){return null}setup(e){const t=e.getNodeProperties(this);let s=0;for(const e of this.getChildren())t["node"+s++]=e;return t.outputNode||null}analyze(e,t=null){const s=e.increaseUsage(this);if(!0===this.parents){const s=e.getDataFromNode(this,"any");s.stages=s.stages||{},s.stages[e.shaderStage]=s.stages[e.shaderStage]||[],s.stages[e.shaderStage].push(t)}if(1===s){const t=e.getNodeProperties(this);for(const s of Object.values(t))s&&!0===s.isNode&&s.build(e,this)}}generate(e,t){const{outputNode:s}=e.getNodeProperties(this);if(s&&!0===s.isNode)return s.build(e,t)}updateBefore(){Yo("Abstract function.")}updateAfter(){Yo("Abstract function.")}update(){Yo("Abstract function.")}before(e){return null===this._beforeNodes&&(this._beforeNodes=[]),this._beforeNodes.push(e),this}build(e,t=null){const s=this.getShared(e);if(this!==s)return s.build(e,t);if(null!==this._beforeNodes){const s=this._beforeNodes;this._beforeNodes=null;for(const i of s)i.build(e,t);this._beforeNodes=s}const i=e.getDataFromNode(this);i.buildStages=i.buildStages||{},i.buildStages[e.buildStage]=!0;const r=Nc[e.buildStage];if(r&&!0!==i.buildStages[r]){const t=e.getBuildStage();e.setBuildStage(r),this.build(e),e.setBuildStage(t)}e.addNode(this),e.addChain(this);let n=null;const o=e.getBuildStage();if("setup"===o){this.updateReference(e);const t=e.getNodeProperties(this);if(!0!==t.initialized){t.initialized=!0,t.outputNode=this.setup(e)||t.outputNode||null;for(const s of Object.values(t))if(s&&!0===s.isNode){if(!0===s.parents){const t=e.getNodeProperties(s);t.parents=t.parents||[],t.parents.push(this)}s.build(e)}}n=t.outputNode}else if("analyze"===o)this.analyze(e,t);else if("generate"===o){if(this.generate.length<2){const s=this.getNodeType(e),i=e.getDataFromNode(this);n=i.snippet,void 0===n?void 0===i.generated?(i.generated=!0,n=this.generate(e)||"",i.snippet=n):(Yo("Node: Recursion detected.",this),n="/* Recursion detected. */"):void 0!==i.flowCodes&&void 0!==e.context.nodeBlock&&e.addFlowCodeHierarchy(this,e.context.nodeBlock),n=e.format(n,s,t)}else n=this.generate(e,t)||"";""===n&&null!==t&&"void"!==t&&"OutputType"!==t&&(Zo(`TSL: Invalid generated code, expected a "${t}".`),n=e.generateConst(t))}return e.removeChain(this),e.addSequentialNode(this),n}getSerializeChildren(){return this._getChildren()}serialize(e){const t=this.getSerializeChildren(),s={};for(const{property:i,index:r,childNode:n}of t)void 0!==r?(void 0===s[i]&&(s[i]=Number.isInteger(r)?[]:{}),s[i][r]=n.toJSON(e.meta).uuid):s[i]=n.toJSON(e.meta).uuid;Object.keys(s).length>0&&(e.inputNodes=s)}deserialize(e){if(void 0!==e.inputNodes){const t=e.meta.nodes;for(const s in e.inputNodes)if(Array.isArray(e.inputNodes[s])){const i=[];for(const r of e.inputNodes[s])i.push(t[r]);this[s]=i}else if("object"==typeof e.inputNodes[s]){const i={};for(const r in e.inputNodes[s]){const n=e.inputNodes[s][r];i[r]=t[n]}this[s]=i}else{const i=e.inputNodes[s];this[s]=t[i]}}}toJSON(e){const{uuid:t,type:s}=this,i=void 0===e||"string"==typeof e;i&&(e={textures:{},images:{},nodes:{}});let r=e.nodes[t];function n(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(void 0===r&&(r={uuid:t,type:s,meta:e,metadata:{version:4.7,type:"Node",generator:"Node.toJSON"}},!0!==i&&(e.nodes[r.uuid]=r),this.serialize(r),delete r.meta),i){const t=n(e.textures),s=n(e.images),i=n(e.nodes);t.length>0&&(r.textures=t),s.length>0&&(r.images=s),i.length>0&&(r.nodes=i)}return r}}class Rc extends Cc{static get type(){return"ArrayElementNode"}constructor(e,t){super(),this.node=e,this.indexNode=t,this.isArrayElementNode=!0}getNodeType(e){return this.node.getElementType(e)}getMemberType(e,t){return this.node.getMemberType(e,t)}generate(e){const t=this.indexNode.getNodeType(e);return`${this.node.build(e)}[ ${this.indexNode.build(e,!e.isVector(t)&&e.isInteger(t)?t:"uint")} ]`}}class Pc extends Cc{static get type(){return"ConvertNode"}constructor(e,t){super(),this.node=e,this.convertTo=t}getNodeType(e){const t=this.node.getNodeType(e);let s=null;for(const i of this.convertTo.split("|"))null!==s&&e.getTypeLength(t)!==e.getTypeLength(i)||(s=i);return s}serialize(e){super.serialize(e),e.convertTo=this.convertTo}deserialize(e){super.deserialize(e),this.convertTo=e.convertTo}generate(e,t){const s=this.node,i=this.getNodeType(e),r=s.build(e,i);return e.format(r,i,t)}}class Bc extends Cc{static get type(){return"TempNode"}constructor(e=null){super(e),this.isTempNode=!0}hasDependencies(e){return e.getDataFromNode(this).usageCount>1}build(e,t){if("generate"===e.getBuildStage()){const s=e.getVectorType(this.getNodeType(e,t)),i=e.getDataFromNode(this);if(void 0!==i.propertyName)return e.format(i.propertyName,s,t);if("void"!==s&&"void"!==t&&this.hasDependencies(e)){const r=super.build(e,s),n=e.getVarFromNode(this,null,s),o=e.getPropertyName(n);return e.addLineFlowCode(`${o} = ${r}`,this),i.snippet=r,i.propertyName=o,e.format(i.propertyName,s,t)}}return super.build(e,t)}}class Ic extends Bc{static get type(){return"JoinNode"}constructor(e=[],t=null){super(t),this.nodes=e}getNodeType(e){return null!==this.nodeType?e.getVectorType(this.nodeType):e.getTypeFromLength(this.nodes.reduce((t,s)=>t+e.getTypeLength(s.getNodeType(e)),0))}generate(e,t){const s=this.getNodeType(e),i=e.getTypeLength(s),r=this.nodes,n=e.getComponentType(s),o=[];let a=0;for(const t of r){if(a>=i){Zo(`TSL: Length of parameters exceeds maximum length of function '${s}()' type.`);break}let r,l=t.getNodeType(e),h=e.getTypeLength(l);a+h>i&&(Zo(`TSL: Length of '${s}()' data exceeds maximum length of output type.`),h=i-a,l=e.getTypeFromLength(h)),a+=h,r=t.build(e,l);if(e.getComponentType(l)!==n){const t=e.getTypeFromLength(h,n);r=e.format(r,l,t)}o.push(r)}const l=`${e.getType(s)}( ${o.join(", ")} )`;return e.format(l,s,t)}}const Dc=Ac.join("");class Lc extends Cc{static get type(){return"SplitNode"}constructor(e,t="x"){super(),this.node=e,this.components=t,this.isSplitNode=!0}getVectorLength(){let e=this.components.length;for(const t of this.components)e=Math.max(Ac.indexOf(t)+1,e);return e}getComponentType(e){return e.getComponentType(this.node.getNodeType(e))}getNodeType(e){return e.getTypeFromLength(this.components.length,this.getComponentType(e))}getScope(){return this.node.getScope()}generate(e,t){const s=this.node,i=e.getTypeLength(s.getNodeType(e));let r=null;if(i>1){let n=null;this.getVectorLength()>=i&&(n=e.getTypeFromLength(this.getVectorLength(),this.getComponentType(e)));const o=s.build(e,n);r=this.components.length===i&&this.components===Dc.slice(0,this.components.length)?e.format(o,n,t):e.format(`${o}.${this.components}`,this.getNodeType(e),t)}else r=s.build(e,t);return r}serialize(e){super.serialize(e),e.components=this.components}deserialize(e){super.deserialize(e),this.components=e.components}}class Fc extends Bc{static get type(){return"SetNode"}constructor(e,t,s){super(),this.sourceNode=e,this.components=t,this.targetNode=s}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{sourceNode:t,components:s,targetNode:i}=this,r=this.getNodeType(e),n=e.getComponentType(i.getNodeType(e)),o=e.getTypeFromLength(s.length,n),a=i.build(e,o),l=t.build(e,r),h=e.getTypeLength(r),u=[];for(let e=0;e<h;e++){const t=Ac[e];t===s[0]?(u.push(a),e+=s.length-1):u.push(l+"."+t)}return`${e.getType(r)}( ${u.join(", ")} )`}}class Oc extends Bc{static get type(){return"FlipNode"}constructor(e,t){super(),this.sourceNode=e,this.components=t}getNodeType(e){return this.sourceNode.getNodeType(e)}generate(e){const{components:t,sourceNode:s}=this,i=this.getNodeType(e),r=s.build(e),n=e.getVarFromNode(this),o=e.getPropertyName(n);e.addLineFlowCode(o+" = "+r,this);const a=e.getTypeLength(i),l=[];let h=0;for(let e=0;e<a;e++){const s=Ac[e];s===t[h]?(l.push("1.0 - "+o+"."+s),h++):l.push(o+"."+s)}return`${e.getType(i)}( ${l.join(", ")} )`}}class Vc extends Cc{static get type(){return"InputNode"}constructor(e,t=null){super(t),this.isInputNode=!0,this.value=e,this.precision=null}getNodeType(){return null===this.nodeType?fc(this.value):this.nodeType}getInputType(e){return this.getNodeType(e)}setPrecision(e){return this.precision=e,this}serialize(e){super.serialize(e),e.value=this.value,this.value&&this.value.toArray&&(e.value=this.value.toArray()),e.valueType=fc(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=xc(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?gc(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){Yo("Abstract function.")}}const zc=/float|u?int/;class kc extends Vc{static get type(){return"ConstNode"}constructor(e,t=null){super(e,t),this.isConstNode=!0}generateConst(e){return e.generateConst(this.getNodeType(e),this.value)}generate(e,t){const s=this.getNodeType(e);return zc.test(s)&&zc.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),s,t)}}class Uc extends Cc{static get type(){return"MemberNode"}constructor(e,t){super(),this.structNode=e,this.property=t,this.isMemberNode=!0}hasMember(e){return(!this.structNode.isMemberNode||!1!==this.structNode.hasMember(e))&&"void"!==this.structNode.getMemberType(e,this.property)}getNodeType(e){return!1===this.hasMember(e)?"float":this.structNode.getMemberType(e,this.property)}getMemberType(e,t){if(!1===this.hasMember(e))return"float";const s=this.getNodeType(e);return e.getStructTypeNode(s).getMemberType(e,t)}generate(e){if(!1===this.hasMember(e)){Yo(`TSL: Member "${this.property}" does not exist in struct.`);const t=this.getNodeType(e);return e.generateConst(t)}return this.structNode.build(e)+"."+this.property}}let Gc=null;const jc=new Map;function $c(e,t){if(jc.has(e))Yo(`TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);jc.set(e,t),"assign"!==e&&(Cc.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},Cc.prototype[e+"Assign"]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}}const Wc=e=>(e=>e.replace(/r|s/g,"x").replace(/g|t/g,"y").replace(/b|p/g,"z").replace(/a|q/g,"w"))(e).split("").sort().join("");Cc.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==Gc?Gc.assign(this,...e):Zo("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn()."),this;{const t=jc.get("assign");return this.addToStack(t(...e))}},Cc.prototype.toVarIntent=function(){return this},Cc.prototype.get=function(e){return new Uc(this,e)};const Hc={};function qc(e,t,s){Hc[e]=Hc[t]=Hc[s]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new Lc(this,e),this._cache[e]=t),t},set(t){this[e].assign(bd(t))}};const i=e.toUpperCase(),r=t.toUpperCase(),n=s.toUpperCase();Cc.prototype["set"+i]=Cc.prototype["set"+r]=Cc.prototype["set"+n]=function(t){const s=Wc(e);return new Fc(this,s,bd(t))},Cc.prototype["flip"+i]=Cc.prototype["flip"+r]=Cc.prototype["flip"+n]=function(){const t=Wc(e);return new Oc(this,t)}}const Xc=["x","y","z","w"],Yc=["r","g","b","a"],Zc=["s","t","p","q"];for(let e=0;e<4;e++){let t=Xc[e],s=Yc[e],i=Zc[e];qc(t,s,i);for(let r=0;r<4;r++){t=Xc[e]+Xc[r],s=Yc[e]+Yc[r],i=Zc[e]+Zc[r],qc(t,s,i);for(let n=0;n<4;n++){t=Xc[e]+Xc[r]+Xc[n],s=Yc[e]+Yc[r]+Yc[n],i=Zc[e]+Zc[r]+Zc[n],qc(t,s,i);for(let o=0;o<4;o++)t=Xc[e]+Xc[r]+Xc[n]+Xc[o],s=Yc[e]+Yc[r]+Yc[n]+Yc[o],i=Zc[e]+Zc[r]+Zc[n]+Zc[o],qc(t,s,i)}}}for(let e=0;e<32;e++)Hc[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new Rc(this,new kc(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(bd(t))}};Object.defineProperties(Cc.prototype,Hc);const Qc=new WeakMap,Kc=function(e,t=null){for(const s in e)e[s]=bd(e[s],t);return e},Jc=function(e,t=null){const s=e.length;for(let i=0;i<s;i++)e[i]=bd(e[i],t);return e},ed=function(e,t=null,s=null,i=null){function r(e){return null!==i?(e=bd(Object.assign(e,i)),!0===i.intent&&(e=e.toVarIntent())):e=bd(e),e}let n,o,a,l=t;function h(t){let s;return s=l?/[a-z]/i.test(l)?l+"()":l:e.type,void 0!==o&&t.length<o?(Zo(`TSL: "${s}" parameter length is less than minimum required.`),t.concat(new Array(o-t.length).fill(0))):void 0!==a&&t.length>a?(Zo(`TSL: "${s}" parameter length exceeds limit.`),t.slice(0,a)):t}return null===t?n=(...t)=>r(new e(...vd(h(t)))):null!==s?(s=bd(s),n=(...i)=>r(new e(t,...vd(h(i)),s))):n=(...s)=>r(new e(t,...vd(h(s)))),n.setParameterLength=(...e)=>(1===e.length?o=a=e[0]:2===e.length&&([o,a]=e),n),n.setName=e=>(l=e,n),n},td=function(e,...t){return new e(...vd(t))};class sd extends Cc{constructor(e,t){super(),this.shaderNode=e,this.rawInputs=t,this.isShaderCallNodeInternal=!0}getNodeType(e){return this.shaderNode.nodeType||this.getOutputNode(e).getNodeType(e)}getElementType(e){return this.getOutputNode(e).getElementType(e)}getMemberType(e,t){return this.getOutputNode(e).getMemberType(e,t)}call(e){const{shaderNode:t,rawInputs:s}=this,i=e.getNodeProperties(t),r=e.getClosestSubBuild(t.subBuilds)||"",n=r||"default";if(i[n])return i[n];const o=e.subBuildFn,a=e.fnCall;e.subBuildFn=r,e.fnCall=this;let l=null;if(t.layout){let i=Qc.get(e.constructor);void 0===i&&(i=new WeakMap,Qc.set(e.constructor,i));let r=i.get(t);void 0===r&&(r=bd(e.buildFunctionNode(t)),i.set(t,r)),e.addInclude(r);const n=s?function(e){let t;wd(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(s):null;l=bd(r.call(n))}else{const i=new Proxy(e,{get:(e,t,s)=>{let i;return i=Symbol.iterator===t?function*(){yield}:Reflect.get(e,t,s),i}}),r=s?function(e){let t=0;return wd(e),new Proxy(e,{get:(s,i,r)=>{let n;if("length"===i)return n=e.length,n;if(Symbol.iterator===i)n=function*(){for(const t of e)yield bd(t)};else{if(e.length>0)if(Object.getPrototypeOf(e[0])===Object.prototype){const s=e[0];n=void 0===s[i]?s[t++]:Reflect.get(s,i,r)}else e[0]instanceof Cc&&(n=void 0===e[i]?e[t++]:Reflect.get(e,i,r));else n=Reflect.get(s,i,r);n=bd(n)}return n}})}(s):null,n=Array.isArray(s)?s.length>0:null!==s,o=t.jsFunc,a=n||o.length>1?o(r,i):o(i);l=bd(a)}return e.subBuildFn=o,e.fnCall=a,t.once&&(i[n]=l),l}setupOutput(e){return e.addStack(),e.stack.outputNode=this.call(e),e.removeStack()}getOutputNode(e){const t=e.getNodeProperties(this),s=e.getSubBuildOutput(this);return t[s]=t[s]||this.setupOutput(e),t[s].subBuild=e.getClosestSubBuild(this),t[s]}build(e,t=null){let s=null;const i=e.getBuildStage(),r=e.getNodeProperties(this),n=e.getSubBuildOutput(this),o=this.getOutputNode(e),a=e.fnCall;if(e.fnCall=this,"setup"===i){const t=e.getSubBuildProperty("initialized",this);if(!0!==r[t]&&(r[t]=!0,r[n]=this.getOutputNode(e),r[n].build(e),this.shaderNode.subBuilds))for(const t of e.chaining){const s=e.getDataFromNode(t,"any");s.subBuilds=s.subBuilds||new Set;for(const e of this.shaderNode.subBuilds)s.subBuilds.add(e)}s=r[n]}else"analyze"===i?o.build(e,t):"generate"===i&&(s=o.build(e,t)||"");return e.fnCall=a,s}}class id extends Cc{constructor(e,t){super(t),this.jsFunc=e,this.layout=null,this.global=!0,this.once=!1}setLayout(e){return this.layout=e,this}getLayout(){return this.layout}call(e=null){return new sd(this,e)}setup(){return this.call()}}const rd=[!1,!0],nd=[0,1,2,3],od=[-1,-2],ad=[.5,1.5,1/3,1e-6,1e6,Math.PI,2*Math.PI,1/Math.PI,2/Math.PI,1/(2*Math.PI),Math.PI/2],ld=new Map;for(const e of rd)ld.set(e,new kc(e));const hd=new Map;for(const e of nd)hd.set(e,new kc(e,"uint"));const ud=new Map([...hd].map(e=>new kc(e.value,"int")));for(const e of od)ud.set(e,new kc(e,"int"));const cd=new Map([...ud].map(e=>new kc(e.value)));for(const e of ad)cd.set(e,new kc(e));for(const e of ad)cd.set(-e,new kc(-e));const dd={bool:ld,uint:hd,ints:ud,float:cd},pd=new Map([...ld,...cd]),md=(e,t)=>pd.has(e)?pd.get(e):!0===e.isNode?e:new kc(e,t),fd=function(e,t=null){return(...s)=>{for(const t of s)if(void 0===t)return Zo(`TSL: Invalid parameter for the type "${e}".`),new kc(0,e);if((0===s.length||!["bool","float","int","uint"].includes(e)&&s.every(e=>{const t=typeof e;return"object"!==t&&"function"!==t}))&&(s=[gc(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return _d(t.get(s[0]));if(1===s.length){const t=md(s[0],e);return t.nodeType===e?_d(t):_d(new Pc(t,e))}const i=s.map(e=>md(e));return _d(new Ic(i,e))}},gd=e=>"object"==typeof e&&null!==e?e.value:e,yd=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function xd(e,t){return new id(e,t)}const bd=(e,t=null)=>function(e,t=null){const s=fc(e);return"node"===s?e:null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?bd(md(e,t)):"shader"===s?e.isFn?e:Ed(e):e}(e,t),_d=(e,t=null)=>bd(e,t).toVarIntent(),wd=(e,t=null)=>new Kc(e,t),vd=(e,t=null)=>new Jc(e,t),Td=(e,t=null,s=null,i=null)=>new ed(e,t,s,i),Sd=(e,...t)=>new td(e,...t),Md=(e,t=null,s=null,i={})=>new ed(e,t,s,{...i,intent:!0});let Ad=0;class Nd extends Cc{constructor(e,t=null){super();let s=null;null!==t&&("object"==typeof t?s=t.return:("string"==typeof t?s=t:Zo("TSL: Invalid layout type."),t=null)),this.shaderNode=new xd(e,s),null!==t&&this.setLayout(t),this.isFn=!0}setLayout(e){const t=this.shaderNode.nodeType;if("object"!=typeof e.inputs){const s={name:"fn"+Ad++,type:t,inputs:[]};for(const t in e)"return"!==t&&s.inputs.push({name:t,type:e[t]});e=s}return this.shaderNode.setLayout(e),this}getNodeType(e){return this.shaderNode.getNodeType(e)||"float"}call(...e){const t=this.shaderNode.call(e);return"void"===this.shaderNode.nodeType&&t.toStack(),t.toVarIntent()}once(e=null){return this.shaderNode.once=!0,this.shaderNode.subBuilds=e,this}generate(e){const t=this.getNodeType(e);return Zo('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".'),e.generateConst(t)}}function Ed(e,t=null){const s=new Nd(e,t);return new Proxy(()=>{},{apply:(e,t,i)=>s.call(...i),get:(e,t,i)=>Reflect.get(s,t,i),set:(e,t,i,r)=>Reflect.set(s,t,i,r)})}const Cd=e=>{Gc=e},Rd=()=>Gc,Pd=(...e)=>Gc.If(...e);function Bd(e){return Gc&&Gc.addToStack(e),e}$c("toStack",Bd);const Id=new fd("color"),Dd=new fd("float",dd.float),Ld=new fd("int",dd.ints),Fd=new fd("uint",dd.uint),Od=new fd("bool",dd.bool),Vd=new fd("vec2"),zd=new fd("ivec2"),kd=new fd("uvec2"),Ud=new fd("bvec2"),Gd=new fd("vec3"),jd=new fd("ivec3"),$d=new fd("uvec3"),Wd=new fd("bvec3"),Hd=new fd("vec4"),qd=new fd("ivec4"),Xd=new fd("uvec4"),Yd=new fd("bvec4"),Zd=new fd("mat2"),Qd=new fd("mat3"),Kd=new fd("mat4");$c("toColor",Id),$c("toFloat",Dd),$c("toInt",Ld),$c("toUint",Fd),$c("toBool",Od),$c("toVec2",Vd),$c("toIVec2",zd),$c("toUVec2",kd),$c("toBVec2",Ud),$c("toVec3",Gd),$c("toIVec3",jd),$c("toUVec3",$d),$c("toBVec3",Wd),$c("toVec4",Hd),$c("toIVec4",qd),$c("toUVec4",Xd),$c("toBVec4",Yd),$c("toMat2",Zd),$c("toMat3",Qd),$c("toMat4",Kd);const Jd=Td(Rc).setParameterLength(2),ep=(e,t)=>bd(new Pc(bd(e),t));$c("element",Jd),$c("convert",ep);$c("append",e=>(Yo("TSL: .append() has been renamed to .toStack()."),Bd(e)));class tp extends Cc{static get type(){return"PropertyNode"}constructor(e,t=null,s=!1){super(e),this.name=t,this.varying=s,this.isPropertyNode=!0,this.global=!0}customCacheKey(){return nc(this.type+":"+(this.name||"")+":"+(this.varying?"1":"0"))}getHash(e){return this.name||super.getHash(e)}generate(e){let t;return!0===this.varying?(t=e.getVaryingFromNode(this,this.name),t.needsInterpolation=!0):t=e.getVarFromNode(this,this.name),e.getPropertyName(t)}}const sp=(e,t)=>new tp(e,t),ip=(e,t)=>new tp(e,t,!0),rp=Sd(tp,"vec4","DiffuseColor"),np=Sd(tp,"vec3","DiffuseContribution"),op=Sd(tp,"vec3","EmissiveColor"),ap=Sd(tp,"float","Roughness"),lp=Sd(tp,"float","Metalness"),hp=Sd(tp,"float","Clearcoat"),up=Sd(tp,"float","ClearcoatRoughness"),cp=Sd(tp,"vec3","Sheen"),dp=Sd(tp,"float","SheenRoughness"),pp=Sd(tp,"float","Iridescence"),mp=Sd(tp,"float","IridescenceIOR"),fp=Sd(tp,"float","IridescenceThickness"),gp=Sd(tp,"float","AlphaT"),yp=Sd(tp,"float","Anisotropy"),xp=Sd(tp,"vec3","AnisotropyT"),bp=Sd(tp,"vec3","AnisotropyB"),_p=Sd(tp,"color","SpecularColor"),wp=Sd(tp,"color","SpecularColorBlended"),vp=Sd(tp,"float","SpecularF90"),Tp=Sd(tp,"float","Shininess"),Sp=Sd(tp,"vec4","Output"),Mp=Sd(tp,"float","dashSize"),Ap=Sd(tp,"float","gapSize"),Np=Sd(tp,"float","pointWidth"),Ep=Sd(tp,"float","IOR"),Cp=Sd(tp,"float","Transmission"),Rp=Sd(tp,"float","Thickness"),Pp=Sd(tp,"float","AttenuationDistance"),Bp=Sd(tp,"color","AttenuationColor"),Ip=Sd(tp,"float","Dispersion");class Dp extends Cc{static get type(){return"UniformGroupNode"}constructor(e,t=!1,s=1){super("string"),this.name=e,this.shared=t,this.order=s,this.isUniformGroup=!0}serialize(e){super.serialize(e),e.name=this.name,e.version=this.version,e.shared=this.shared}deserialize(e){super.deserialize(e),this.name=e.name,this.version=e.version,this.shared=e.shared}}const Lp=e=>new Dp(e),Fp=(e,t=0)=>new Dp(e,!0,t),Op=Fp("frame"),Vp=Fp("render"),zp=Lp("object");class kp extends Vc{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=zp}setName(e){return this.name=e,this}label(e){return Yo('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setGroup(e){return this.groupNode=e,this}getGroup(){return this.groupNode}getUniformHash(e){return this.getHash(e)}onUpdate(e,t){return e=e.bind(this),super.onUpdate(t=>{const s=e(t,this);void 0!==s&&(this.value=s)},t)}getInputType(e){let t=super.getInputType(e);return"bool"===t&&(t="uint"),t}generate(e,t){const s=this.getNodeType(e),i=this.getUniformHash(e);let r=e.getNodeFromHash(i);void 0===r&&(e.setHashNode(this,i),r=this);const n=r.getInputType(e),o=e.getUniformFromNode(r,n,e.shaderStage,this.name||e.context.nodeName),a=e.getPropertyName(o);void 0!==e.context.nodeName&&delete e.context.nodeName;let l=a;if("bool"===s){const t=e.getDataFromNode(this);let i=t.propertyName;if(void 0===i){const r=e.getVarFromNode(this,null,"bool");i=e.getPropertyName(r),t.propertyName=i,l=e.format(a,n,s),e.addLineFlowCode(`${i} = ${l}`,this)}l=i}return e.format(l,s,t)}}const Up=(e,t)=>{const s=yd(t||e);if(s===e&&(e=gc(s)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new kp(e,s)};class Gp extends Bc{static get type(){return"ArrayNode"}constructor(e,t,s=null){super(e),this.count=t,this.values=s,this.isArrayNode=!0}getArrayCount(){return this.count}getNodeType(e){return null===this.nodeType?this.values[0].getNodeType(e):this.nodeType}getElementType(e){return this.getNodeType(e)}getMemberType(e,t){return null===this.nodeType?this.values[0].getMemberType(e,t):super.getMemberType(e,t)}generate(e){const t=this.getNodeType(e);return e.generateArray(t,this.count,this.values)}}const jp=(...e)=>{let t;if(1===e.length){const s=e[0];t=new Gp(null,s.length,s)}else{const s=e[0],i=e[1];t=new Gp(s,i)}return bd(t)};$c("toArray",(e,t)=>jp(Array(t).fill(e)));class $p extends Bc{static get type(){return"AssignNode"}constructor(e,t){super(),this.targetNode=e,this.sourceNode=t,this.isAssignNode=!0}hasDependencies(){return!1}getNodeType(e,t){return"void"!==t?this.targetNode.getNodeType(e):"void"}needsSplitAssign(e){const{targetNode:t}=this;if(!1===e.isAvailable("swizzleAssign")&&t.isSplitNode&&t.components.length>1){const s=e.getTypeLength(t.node.getNodeType(e));return Ac.join("").slice(0,s)!==t.components}return!1}setup(e){const{targetNode:t,sourceNode:s}=this,i=t.getScope();e.getDataFromNode(i).assign=!0;const r=e.getNodeProperties(this);r.sourceNode=s,r.targetNode=t.context({assign:!0})}generate(e,t){const{targetNode:s,sourceNode:i}=e.getNodeProperties(this),r=this.needsSplitAssign(e),n=s.build(e),o=s.getNodeType(e),a=i.build(e,o),l=i.getNodeType(e),h=e.getDataFromNode(this);let u;if(!0===h.initialized)"void"!==t&&(u=n);else if(r){const i=e.getVarFromNode(this,null,o),r=e.getPropertyName(i);e.addLineFlowCode(`${r} = ${a}`,this);const l=s.node,h=l.node.context({assign:!0}).build(e);for(let t=0;t<l.components.length;t++){const s=l.components[t];e.addLineFlowCode(`${h}.${s} = ${r}[ ${t} ]`,this)}"void"!==t&&(u=n)}else u=`${n} = ${a}`,"void"!==t&&"void"!==l||(e.addLineFlowCode(u,this),"void"!==t&&(u=n));return h.initialized=!0,e.format(u,o,t)}}const Wp=Td($p).setParameterLength(2);$c("assign",Wp);class Hp extends Bc{static get type(){return"FunctionCallNode"}constructor(e=null,t={}){super(),this.functionNode=e,this.parameters=t}setParameters(e){return this.parameters=e,this}getParameters(){return this.parameters}getNodeType(e){return this.functionNode.getNodeType(e)}getMemberType(e,t){return this.functionNode.getMemberType(e,t)}generate(e){const t=[],s=this.functionNode,i=s.getInputs(e),r=this.parameters,n=(t,s)=>{const i=s.type;let r;return r="pointer"===i?"&"+t.build(e):t.build(e,i),r};if(Array.isArray(r)){if(r.length>i.length)Zo("TSL: The number of provided parameters exceeds the expected number of inputs in 'Fn()'."),r.length=i.length;else if(r.length<i.length)for(Zo("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");r.length<i.length;)r.push(Dd(0));for(let e=0;e<r.length;e++)t.push(n(r[e],i[e]))}else for(const e of i){const s=r[e.name];void 0!==s?t.push(n(s,e)):(Zo(`TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(n(Dd(0),e)))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}const qp=(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?vd(t):wd(t[0]),new Hp(bd(e),t));$c("call",qp);const Xp={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class Yp extends Bc{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new Yp(e,t,s);for(let t=0;t<i.length-1;t++)r=new Yp(e,r,i[t]);t=r,s=i[i.length-1]}this.op=e,this.aNode=t,this.bNode=s,this.isOperatorNode=!0}getOperatorMethod(e,t){return e.getMethod(Xp[this.op],t)}getNodeType(e,t=null){const s=this.op,i=this.aNode,r=this.bNode,n=i.getNodeType(e),o=r?r.getNodeType(e):null;if("void"===n||"void"===o)return t||"void";if("%"===s)return n;if("~"===s||"&"===s||"|"===s||"^"===s||">>"===s||"<<"===s)return e.getIntegerType(n);if("!"===s||"&&"===s||"||"===s||"^^"===s)return"bool";if("=="===s||"!="===s||"<"===s||">"===s||"<="===s||">="===s){const t=Math.max(e.getTypeLength(n),e.getTypeLength(o));return t>1?`bvec${t}`:"bool"}if(e.isMatrix(n)){if("float"===o)return n;if(e.isVector(o))return e.getVectorFromMatrix(n);if(e.isMatrix(o))return n}else if(e.isMatrix(o)){if("float"===n)return o;if(e.isVector(n))return e.getVectorFromMatrix(o)}return e.getTypeLength(o)>e.getTypeLength(n)?o:n}generate(e,t){const s=this.op,{aNode:i,bNode:r}=this,n=this.getNodeType(e,t);let o=null,a=null;"void"!==n?(o=i.getNodeType(e),a=r?r.getNodeType(e):null,"<"===s||">"===s||"<="===s||">="===s||"=="===s||"!="===s?e.isVector(o)?a=o:e.isVector(a)?o=a:o!==a&&(o=a="float"):">>"===s||"<<"===s?(o=n,a=e.changeComponentType(a,"uint")):"%"===s?(o=n,a=e.isInteger(o)&&e.isInteger(a)?a:o):e.isMatrix(o)?"float"===a?a="float":e.isVector(a)?a=e.getVectorFromMatrix(o):e.isMatrix(a)||(o=a=n):o=e.isMatrix(a)?"float"===o?"float":e.isVector(o)?e.getVectorFromMatrix(a):a=n:a=n):o=a=n;const l=i.build(e,o),h=r?r.build(e,a):null,u=e.getFunctionOperator(s);if("void"!==t){const i=e.renderer.coordinateSystem===ko;if("=="===s||"!="===s||"<"===s||">"===s||"<="===s||">="===s)return i&&e.isVector(o)?e.format(`${this.getOperatorMethod(e,t)}( ${l}, ${h} )`,n,t):e.format(`( ${l} ${s} ${h} )`,n,t);if("%"===s)return e.isInteger(a)?e.format(`( ${l} % ${h} )`,n,t):e.format(`${this.getOperatorMethod(e,n)}( ${l}, ${h} )`,n,t);if("!"===s||"~"===s)return e.format(`(${s}${l})`,o,t);if(u)return e.format(`${u}( ${l}, ${h} )`,n,t);if(e.isMatrix(o)&&"float"===a)return e.format(`( ${h} ${s} ${l} )`,n,t);if("float"===o&&e.isMatrix(a))return e.format(`${l} ${s} ${h}`,n,t);{let r=`( ${l} ${s} ${h} )`;return!i&&"bool"===n&&e.isVector(o)&&e.isVector(a)&&(r=`all${r}`),e.format(r,n,t)}}if("void"!==o)return u?e.format(`${u}( ${l}, ${h} )`,n,t):e.isMatrix(o)&&"float"===a?e.format(`${h} ${s} ${l}`,n,t):e.format(`${l} ${s} ${h}`,n,t)}serialize(e){super.serialize(e),e.op=this.op}deserialize(e){super.deserialize(e),this.op=e.op}}const Zp=Md(Yp,"+").setParameterLength(2,1/0).setName("add"),Qp=Md(Yp,"-").setParameterLength(2,1/0).setName("sub"),Kp=Md(Yp,"*").setParameterLength(2,1/0).setName("mul"),Jp=Md(Yp,"/").setParameterLength(2,1/0).setName("div"),em=Md(Yp,"%").setParameterLength(2).setName("mod"),tm=Md(Yp,"==").setParameterLength(2).setName("equal"),sm=Md(Yp,"!=").setParameterLength(2).setName("notEqual"),im=Md(Yp,"<").setParameterLength(2).setName("lessThan"),rm=Md(Yp,">").setParameterLength(2).setName("greaterThan"),nm=Md(Yp,"<=").setParameterLength(2).setName("lessThanEqual"),om=Md(Yp,">=").setParameterLength(2).setName("greaterThanEqual"),am=Md(Yp,"&&").setParameterLength(2,1/0).setName("and"),lm=Md(Yp,"||").setParameterLength(2,1/0).setName("or"),hm=Md(Yp,"!").setParameterLength(1).setName("not"),um=Md(Yp,"^^").setParameterLength(2).setName("xor"),cm=Md(Yp,"&").setParameterLength(2).setName("bitAnd"),dm=Md(Yp,"~").setParameterLength(1).setName("bitNot"),pm=Md(Yp,"|").setParameterLength(2).setName("bitOr"),mm=Md(Yp,"^").setParameterLength(2).setName("bitXor"),fm=Md(Yp,"<<").setParameterLength(2).setName("shiftLeft"),gm=Md(Yp,">>").setParameterLength(2).setName("shiftRight"),ym=Ed(([e])=>(e.addAssign(1),e)),xm=Ed(([e])=>(e.subAssign(1),e)),bm=Ed(([e])=>{const t=Ld(e).toConst();return e.addAssign(1),t}),_m=Ed(([e])=>{const t=Ld(e).toConst();return e.subAssign(1),t});$c("add",Zp),$c("sub",Qp),$c("mul",Kp),$c("div",Jp),$c("mod",em),$c("equal",tm),$c("notEqual",sm),$c("lessThan",im),$c("greaterThan",rm),$c("lessThanEqual",nm),$c("greaterThanEqual",om),$c("and",am),$c("or",lm),$c("not",hm),$c("xor",um),$c("bitAnd",cm),$c("bitNot",dm),$c("bitOr",pm),$c("bitXor",mm),$c("shiftLeft",fm),$c("shiftRight",gm),$c("incrementBefore",ym),$c("decrementBefore",xm),$c("increment",bm),$c("decrement",_m);const wm=(e,t)=>(Yo('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),em(Ld(e),Ld(t)));$c("modInt",wm);class vm extends Bc{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){if(super(),(e===vm.MAX||e===vm.MIN)&&arguments.length>3){let r=new vm(e,t,s);for(let t=2;t<arguments.length-1;t++)r=new vm(e,r,arguments[t]);t=r,s=arguments[arguments.length-1],i=null}this.method=e,this.aNode=t,this.bNode=s,this.cNode=i,this.isMathNode=!0}getInputType(e){const t=this.aNode.getNodeType(e),s=this.bNode?this.bNode.getNodeType(e):null,i=this.cNode?this.cNode.getNodeType(e):null,r=e.isMatrix(t)?0:e.getTypeLength(t),n=e.isMatrix(s)?0:e.getTypeLength(s),o=e.isMatrix(i)?0:e.getTypeLength(i);return r>n&&r>o?t:n>o?s:o>r?i:t}getNodeType(e){const t=this.method;return t===vm.LENGTH||t===vm.DISTANCE||t===vm.DOT?"float":t===vm.CROSS?"vec3":t===vm.ALL||t===vm.ANY?"bool":t===vm.EQUALS?e.changeComponentType(this.aNode.getNodeType(e),"bool"):this.getInputType(e)}setup(e){const{aNode:t,bNode:s,method:i}=this;let r=null;if(i===vm.ONE_MINUS)r=Qp(1,t);else if(i===vm.RECIPROCAL)r=Jp(1,t);else if(i===vm.DIFFERENCE)r=Ym(Qp(t,s));else if(i===vm.TRANSFORM_DIRECTION){let i=t,n=s;e.isMatrix(i.getNodeType(e))?n=Hd(Gd(n),0):i=Hd(Gd(i),0);const o=Kp(i,n).xyz;r=Um(o)}return null!==r?r:super.setup(e)}generate(e,t){if(e.getNodeProperties(this).outputNode)return super.generate(e,t);let s=this.method;const i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,o=this.bNode,a=this.cNode,l=e.renderer.coordinateSystem;if(s===vm.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);{const h=[];return s===vm.CROSS?h.push(n.build(e,i),o.build(e,i)):l===ko&&s===vm.STEP?h.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),o.build(e,r)):l!==ko||s!==vm.MIN&&s!==vm.MAX?s===vm.REFRACT?h.push(n.build(e,r),o.build(e,r),a.build(e,"float")):s===vm.MIX?h.push(n.build(e,r),o.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)):(l===Uo&&s===vm.ATAN&&null!==o&&(s="atan2"),"fragment"===e.shaderStage||s!==vm.DFDX&&s!==vm.DFDY||(Yo(`TSL: '${s}' is not supported in the ${e.shaderStage} stage.`),s="/*"+s+"*/"),h.push(n.build(e,r)),null!==o&&h.push(o.build(e,r)),null!==a&&h.push(a.build(e,r))):h.push(n.build(e,r),o.build(e,1===e.getTypeLength(o.getNodeType(e))?"float":r)),e.format(`${e.getMethod(s,i)}( ${h.join(", ")} )`,i,t)}}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}vm.ALL="all",vm.ANY="any",vm.RADIANS="radians",vm.DEGREES="degrees",vm.EXP="exp",vm.EXP2="exp2",vm.LOG="log",vm.LOG2="log2",vm.SQRT="sqrt",vm.INVERSE_SQRT="inversesqrt",vm.FLOOR="floor",vm.CEIL="ceil",vm.NORMALIZE="normalize",vm.FRACT="fract",vm.SIN="sin",vm.COS="cos",vm.TAN="tan",vm.ASIN="asin",vm.ACOS="acos",vm.ATAN="atan",vm.ABS="abs",vm.SIGN="sign",vm.LENGTH="length",vm.NEGATE="negate",vm.ONE_MINUS="oneMinus",vm.DFDX="dFdx",vm.DFDY="dFdy",vm.ROUND="round",vm.RECIPROCAL="reciprocal",vm.TRUNC="trunc",vm.FWIDTH="fwidth",vm.TRANSPOSE="transpose",vm.DETERMINANT="determinant",vm.INVERSE="inverse",vm.EQUALS="equals",vm.MIN="min",vm.MAX="max",vm.STEP="step",vm.REFLECT="reflect",vm.DISTANCE="distance",vm.DIFFERENCE="difference",vm.DOT="dot",vm.CROSS="cross",vm.POW="pow",vm.TRANSFORM_DIRECTION="transformDirection",vm.MIX="mix",vm.CLAMP="clamp",vm.REFRACT="refract",vm.SMOOTHSTEP="smoothstep",vm.FACEFORWARD="faceforward";const Tm=Dd(1e-6),Sm=Dd(1e6),Mm=Dd(Math.PI),Am=Dd(2*Math.PI),Nm=Dd(2*Math.PI),Em=Dd(.5*Math.PI),Cm=Md(vm,vm.ALL).setParameterLength(1),Rm=Md(vm,vm.ANY).setParameterLength(1),Pm=Md(vm,vm.RADIANS).setParameterLength(1),Bm=Md(vm,vm.DEGREES).setParameterLength(1),Im=Md(vm,vm.EXP).setParameterLength(1),Dm=Md(vm,vm.EXP2).setParameterLength(1),Lm=Md(vm,vm.LOG).setParameterLength(1),Fm=Md(vm,vm.LOG2).setParameterLength(1),Om=Md(vm,vm.SQRT).setParameterLength(1),Vm=Md(vm,vm.INVERSE_SQRT).setParameterLength(1),zm=Md(vm,vm.FLOOR).setParameterLength(1),km=Md(vm,vm.CEIL).setParameterLength(1),Um=Md(vm,vm.NORMALIZE).setParameterLength(1),Gm=Md(vm,vm.FRACT).setParameterLength(1),jm=Md(vm,vm.SIN).setParameterLength(1),$m=Md(vm,vm.COS).setParameterLength(1),Wm=Md(vm,vm.TAN).setParameterLength(1),Hm=Md(vm,vm.ASIN).setParameterLength(1),qm=Md(vm,vm.ACOS).setParameterLength(1),Xm=Md(vm,vm.ATAN).setParameterLength(1,2),Ym=Md(vm,vm.ABS).setParameterLength(1),Zm=Md(vm,vm.SIGN).setParameterLength(1),Qm=Md(vm,vm.LENGTH).setParameterLength(1),Km=Md(vm,vm.NEGATE).setParameterLength(1),Jm=Md(vm,vm.ONE_MINUS).setParameterLength(1),ef=Md(vm,vm.DFDX).setParameterLength(1),tf=Md(vm,vm.DFDY).setParameterLength(1),sf=Md(vm,vm.ROUND).setParameterLength(1),rf=Md(vm,vm.RECIPROCAL).setParameterLength(1),nf=Md(vm,vm.TRUNC).setParameterLength(1),of=Md(vm,vm.FWIDTH).setParameterLength(1),af=Md(vm,vm.TRANSPOSE).setParameterLength(1),lf=Md(vm,vm.DETERMINANT).setParameterLength(1),hf=Md(vm,vm.INVERSE).setParameterLength(1),uf=(e,t)=>(Yo('TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),tm(e,t)),cf=Md(vm,vm.MIN).setParameterLength(2,1/0),df=Md(vm,vm.MAX).setParameterLength(2,1/0),pf=Md(vm,vm.STEP).setParameterLength(2),mf=Md(vm,vm.REFLECT).setParameterLength(2),ff=Md(vm,vm.DISTANCE).setParameterLength(2),gf=Md(vm,vm.DIFFERENCE).setParameterLength(2),yf=Md(vm,vm.DOT).setParameterLength(2),xf=Md(vm,vm.CROSS).setParameterLength(2),bf=Md(vm,vm.POW).setParameterLength(2),_f=e=>Kp(e,e),wf=e=>Kp(e,e,e),vf=e=>Kp(e,e,e,e),Tf=Md(vm,vm.TRANSFORM_DIRECTION).setParameterLength(2),Sf=e=>Kp(Zm(e),bf(Ym(e),1/3)),Mf=e=>yf(e,e),Af=Md(vm,vm.MIX).setParameterLength(3),Nf=(e,t=0,s=1)=>bd(new vm(vm.CLAMP,bd(e),bd(t),bd(s))),Ef=e=>Nf(e),Cf=Md(vm,vm.REFRACT).setParameterLength(3),Rf=Md(vm,vm.SMOOTHSTEP).setParameterLength(3),Pf=Md(vm,vm.FACEFORWARD).setParameterLength(3),Bf=Ed(([e])=>{const t=yf(e.xy,Vd(12.9898,78.233)),s=em(t,Mm);return Gm(jm(s).mul(43758.5453))}),If=(e,t,s)=>Af(t,s,e),Df=(e,t,s)=>Rf(t,s,e),Lf=(e,t)=>pf(t,e),Ff=(e,t)=>(Yo('TSL: "atan2" is overloaded. Use "atan" instead.'),Xm(e,t)),Of=Pf,Vf=Vm;$c("all",Cm),$c("any",Rm),$c("equals",uf),$c("radians",Pm),$c("degrees",Bm),$c("exp",Im),$c("exp2",Dm),$c("log",Lm),$c("log2",Fm),$c("sqrt",Om),$c("inverseSqrt",Vm),$c("floor",zm),$c("ceil",km),$c("normalize",Um),$c("fract",Gm),$c("sin",jm),$c("cos",$m),$c("tan",Wm),$c("asin",Hm),$c("acos",qm),$c("atan",Xm),$c("abs",Ym),$c("sign",Zm),$c("length",Qm),$c("lengthSq",Mf),$c("negate",Km),$c("oneMinus",Jm),$c("dFdx",ef),$c("dFdy",tf),$c("round",sf),$c("reciprocal",rf),$c("trunc",nf),$c("fwidth",of),$c("atan2",Ff),$c("min",cf),$c("max",df),$c("step",Lf),$c("reflect",mf),$c("distance",ff),$c("dot",yf),$c("cross",xf),$c("pow",bf),$c("pow2",_f),$c("pow3",wf),$c("pow4",vf),$c("transformDirection",Tf),$c("mix",If),$c("clamp",Nf),$c("refract",Cf),$c("smoothstep",Df),$c("faceForward",Pf),$c("difference",gf),$c("saturate",Ef),$c("cbrt",Sf),$c("transpose",af),$c("determinant",lf),$c("inverse",hf),$c("rand",Bf);class zf extends Cc{static get type(){return"ConditionalNode"}constructor(e,t,s=null){super(),this.condNode=e,this.ifNode=t,this.elseNode=s}getNodeType(e){const{ifNode:t,elseNode:s}=e.getNodeProperties(this);if(void 0===t)return e.flowBuildStage(this,"setup"),this.getNodeType(e);const i=t.getNodeType(e);if(null!==s){const t=s.getNodeType(e);if(e.getTypeLength(t)>e.getTypeLength(i))return t}return i}setup(e){const t=this.condNode,s=this.ifNode.isolate(),i=this.elseNode?this.elseNode.isolate():null,r=e.context.nodeBlock;e.getDataFromNode(s).parentNodeBlock=r,null!==i&&(e.getDataFromNode(i).parentNodeBlock=r);const n=e.context.uniformFlow,o=e.getNodeProperties(this);o.condNode=t,o.ifNode=n?s:s.context({nodeBlock:s}),o.elseNode=i?n?i:i.context({nodeBlock:i}):null}generate(e,t){const s=this.getNodeType(e),i=e.getDataFromNode(this);if(void 0!==i.nodeProperty)return i.nodeProperty;const{condNode:r,ifNode:n,elseNode:o}=e.getNodeProperties(this),a=e.currentFunctionNode,l="void"!==t,h=l?sp(s).build(e):"";i.nodeProperty=h;const u=r.build(e,"bool");if(e.context.uniformFlow&&null!==o){const i=n.build(e,s),r=o.build(e,s),a=e.getTernary(u,i,r);return e.format(a,s,t)}e.addFlowCode(`\n${e.tab}if ( ${u} ) {\n\n`).addFlowTab();let c=n.build(e,s);if(c&&(l?c=h+" = "+c+";":(c="return "+c+";",null===a&&(Yo("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),c="// "+c))),e.removeFlowTab().addFlowCode(e.tab+"\t"+c+"\n\n"+e.tab+"}"),null!==o){e.addFlowCode(" else {\n\n").addFlowTab();let t=o.build(e,s);t&&(l?t=h+" = "+t+";":(t="return "+t+";",null===a&&(Yo("TSL: Return statement used in an inline 'Fn()'. Define a layout struct to allow return values."),t="// "+t))),e.removeFlowTab().addFlowCode(e.tab+"\t"+t+"\n\n"+e.tab+"}\n\n")}else e.addFlowCode("\n\n");return e.format(h,s,t)}}const kf=Td(zf).setParameterLength(2,3);$c("select",kf);class Uf extends Cc{static get type(){return"ContextNode"}constructor(e=null,t={}){super(),this.isContextNode=!0,this.node=e,this.value=t}getScope(){return this.node.getScope()}getNodeType(e){return this.node.getNodeType(e)}getFlowContextData(){const e=[];return this.traverse(t=>{!0===t.isContextNode&&e.push(t.value)}),Object.assign({},...e)}getMemberType(e,t){return this.node.getMemberType(e,t)}analyze(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}setup(e){const t=e.addContext(this.value);this.node.build(e),e.setContext(t)}generate(e,t){const s=e.addContext(this.value),i=this.node.build(e,t);return e.setContext(s),i}}const Gf=(e=null,t={})=>{let s=e;return null!==s&&!0===s.isNode||(t=s||t,s=null),new Uf(s,t)},jf=e=>Gf(e,{uniformFlow:!0}),$f=(e,t)=>Gf(e,{nodeName:t});function Wf(e,t,s=null){return Gf(s,{getShadow:({light:s,shadowColorNode:i})=>t===s?i.mul(e):i})}function Hf(e,t=null){return Gf(t,{getAO:(t,{material:s})=>!0===s.transparent?t:null!==t?t.mul(e):e})}function qf(e,t){return Yo('TSL: "label()" has been deprecated. Use "setName()" instead.'),$f(e,t)}$c("context",Gf),$c("label",qf),$c("uniformFlow",jf),$c("setName",$f),$c("builtinShadowContext",(e,t,s)=>Wf(t,s,e)),$c("builtinAOContext",(e,t)=>Hf(t,e));class Xf extends Cc{static get type(){return"VarNode"}constructor(e,t=null,s=!1){super(),this.node=e,this.name=t,this.global=!0,this.isVarNode=!0,this.readOnly=s,this.parents=!0,this.intent=!1}setIntent(e){return this.intent=e,this}isIntent(e){return!0!==e.getDataFromNode(this).forceDeclaration&&this.intent}getIntent(){return this.intent}getMemberType(e,t){return this.node.getMemberType(e,t)}getElementType(e){return this.node.getElementType(e)}getNodeType(e){return this.node.getNodeType(e)}getArrayCount(e){return this.node.getArrayCount(e)}isAssign(e){return e.getDataFromNode(this).assign}build(...e){const t=e[0];if(!1===this._hasStack(t)&&"setup"===t.buildStage&&(t.context.nodeLoop||t.context.nodeBlock)){let e=!1;if(this.node.isShaderCallNodeInternal&&null===this.node.shaderNode.getLayout()&&t.fnCall&&t.fnCall.shaderNode){if(t.getDataFromNode(this.node.shaderNode).hasLoop){t.getDataFromNode(this).forceDeclaration=!0,e=!0}}const s=t.getBaseStack();e?s.addToStackBefore(this):s.addToStack(this)}return this.isIntent(t)&&!0!==this.isAssign(t)?this.node.build(...e):super.build(...e)}generate(e){const{node:t,name:s,readOnly:i}=this,{renderer:r}=e,n=!0===r.backend.isWebGPUBackend;let o=!1,a=!1;i&&(o=e.isDeterministic(t),a=n?i:o);const l=this.getNodeType(e);if("void"==l){!0!==this.isIntent(e)&&Zo('TSL: ".toVar()" can not be used with void type.');return t.build(e)}const h=e.getVectorType(l),u=t.build(e,h),c=e.getVarFromNode(this,s,h,void 0,a),d=e.getPropertyName(c);let p=d;if(a)if(n)p=o?`const ${d}`:`let ${d}`;else{const s=t.getArrayCount(e);p=`const ${e.getVar(c.type,d,s)}`}return e.addLineFlowCode(`${p} = ${u}`,this),d}_hasStack(e){return void 0!==e.getDataFromNode(this).stack}}const Yf=Td(Xf),Zf=(e,t=null)=>Yf(e,t).toStack(),Qf=(e,t=null)=>Yf(e,t,!0).toStack(),Kf=e=>Yf(e).setIntent(!0).toStack();$c("toVar",Zf),$c("toConst",Qf),$c("toVarIntent",Kf);class Jf extends Cc{static get type(){return"SubBuild"}constructor(e,t,s=null){super(s),this.node=e,this.name=t,this.isSubBuildNode=!0}getNodeType(e){if(null!==this.nodeType)return this.nodeType;e.addSubBuild(this.name);const t=this.node.getNodeType(e);return e.removeSubBuild(),t}build(e,...t){e.addSubBuild(this.name);const s=this.node.build(e,...t);return e.removeSubBuild(),s}}const eg=(e,t,s=null)=>bd(new Jf(bd(e),t,s));class tg extends Cc{static get type(){return"VaryingNode"}constructor(e,t=null){super(),this.node=e,this.name=t,this.isVaryingNode=!0,this.interpolationType=null,this.interpolationSampling=null,this.global=!0}setInterpolation(e,t=null){return this.interpolationType=e,this.interpolationSampling=t,this}getHash(e){return this.name||super.getHash(e)}getNodeType(e){return this.node.getNodeType(e)}setupVarying(e){const t=e.getNodeProperties(this);let s=t.varying;if(void 0===s){const i=this.name,r=this.getNodeType(e),n=this.interpolationType,o=this.interpolationSampling;t.varying=s=e.getVaryingFromNode(this,i,r,n,o),t.node=eg(this.node,"VERTEX")}return s.needsInterpolation||(s.needsInterpolation="fragment"===e.shaderStage),s}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(_c.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(_c.VERTEX,this.node)}generate(e){const t=e.getSubBuildProperty("property",e.currentStack),s=e.getNodeProperties(this),i=this.setupVarying(e);if(void 0===s[t]){const r=this.getNodeType(e),n=e.getPropertyName(i,_c.VERTEX);e.flowNodeFromShaderStage(_c.VERTEX,s.node,r,n),s[t]=n}return e.getPropertyName(i)}}const sg=Td(tg).setParameterLength(1,2),ig=e=>sg(e);$c("toVarying",sg),$c("toVertexStage",ig),$c("varying",(...e)=>(Yo("TSL: .varying() has been renamed to .toVarying()."),sg(...e))),$c("vertexStage",(...e)=>(Yo("TSL: .vertexStage() has been renamed to .toVertexStage()."),sg(...e)));const rg=Ed(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return Af(t,s,i)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),ng=Ed(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return Af(t,s,i)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),og="WorkingColorSpace";class ag extends Bc{static get type(){return"ColorSpaceNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this.source=t,this.target=s}resolveColorSpace(e,t){return t===og?_a.workingColorSpace:"OutputColorSpace"===t?e.context.outputColorSpace||e.renderer.outputColorSpace:t}setup(e){const{colorNode:t}=this,s=this.resolveColorSpace(e,this.source),i=this.resolveColorSpace(e,this.target);let r=t;return!1!==_a.enabled&&s!==i&&s&&i?(_a.getTransfer(s)===Eo&&(r=Hd(rg(r.rgb),r.a)),_a.getPrimaries(s)!==_a.getPrimaries(i)&&(r=Hd(Qd(_a._getMatrix(new fa,s,i)).mul(r.rgb),r.a)),_a.getTransfer(i)===Eo&&(r=Hd(ng(r.rgb),r.a)),r):r}}const lg=(e,t)=>bd(new ag(bd(e),og,t)),hg=(e,t)=>bd(new ag(bd(e),t,og));$c("workingToColorSpace",lg),$c("colorSpaceToWorking",hg);let ug=class extends Rc{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}};class cg extends Cc{static get type(){return"ReferenceBaseNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.updateType=wc.OBJECT}setGroup(e){return this.group=e,this}element(e){return new ug(this,bd(e))}setNodeType(e){const t=Up(null,e);null!==this.group&&t.setGroup(this.group),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let e=1;e<t.length;e++)s=s[t[e]];return s}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}class dg extends cg{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(Vp)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const pg=(e,t,s=null)=>new dg(e,t,s);class mg extends Bc{static get type(){return"ToneMappingNode"}constructor(e,t=gg,s=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return ac(this._toneMapping)}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup(e){const t=this.colorNode||e.context.color,s=this._toneMapping;if(0===s)return t;let i=null;const r=e.renderer.library.getToneMappingFunction(s);return null!==r?i=Hd(r(t.rgb,this.exposureNode),t.a):(Zo("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const fg=(e,t,s)=>bd(new mg(e,bd(t),bd(s))),gg=pg("toneMappingExposure","float");$c("toneMapping",(e,t,s)=>fg(t,s,e));const yg=new WeakMap;function xg(e,t){let s=yg.get(e);return void 0===s&&(s=new eu(e,t),yg.set(e,s)),s}class bg extends Vc{static get type(){return"BufferAttributeNode"}constructor(e,t=null,s=0,i=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferStride=s,this.bufferOffset=i,this.usage=Vo,this.instanced=!1,this.attribute=null,this.global=!0,e&&!0===e.isBufferAttribute&&e.itemSize<=4&&(this.attribute=e,this.usage=e.usage,this.instanced=e.isInstancedBufferAttribute)}getHash(e){if(0===this.bufferStride&&0===this.bufferOffset){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getNodeType(e){return null===this.bufferType&&(this.bufferType=e.getTypeFromAttribute(this.attribute)),this.bufferType}setup(e){if(null!==this.attribute)return;const t=this.getNodeType(e),s=e.getTypeLength(t),i=this.value,r=this.bufferStride||s,n=this.bufferOffset;let o;o=!0===i.isInterleavedBuffer?i:!0===i.isBufferAttribute?xg(i.array,r):xg(i,r);const a=new su(o,s,n);o.setUsage(this.usage),this.attribute=a,this.attribute.isInstancedBufferAttribute=this.instanced}generate(e){const t=this.getNodeType(e),s=e.getBufferAttributeFromNode(this,t),i=e.getPropertyName(s);let r=null;if("vertex"===e.shaderStage||"compute"===e.shaderStage)this.name=i,r=i;else{r=sg(this).build(e,t)}return r}getInputType(){return"bufferAttribute"}setUsage(e){return this.usage=e,this.attribute&&!0===this.attribute.isBufferAttribute&&(this.attribute.usage=e),this}setInstanced(e){return this.instanced=e,this}}function _g(e,t=null,s=0,i=0,r=35044,n=!1){return"mat3"===t||null===t&&9===e.itemSize?Qd(new bg(e,"vec3",9,0).setUsage(r).setInstanced(n),new bg(e,"vec3",9,3).setUsage(r).setInstanced(n),new bg(e,"vec3",9,6).setUsage(r).setInstanced(n)):"mat4"===t||null===t&&16===e.itemSize?Kd(new bg(e,"vec4",16,0).setUsage(r).setInstanced(n),new bg(e,"vec4",16,4).setUsage(r).setInstanced(n),new bg(e,"vec4",16,8).setUsage(r).setInstanced(n),new bg(e,"vec4",16,12).setUsage(r).setInstanced(n)):new bg(e,t,s,i)}const wg=(e,t=null,s=0,i=0)=>_g(e,t,s,i),vg=(e,t=null,s=0,i=0)=>_g(e,t,s,i,Vo,!0),Tg=(e,t=null,s=0,i=0)=>_g(e,t,s,i,zo,!0);$c("toAttribute",e=>wg(e.value));class Sg extends Cc{static get type(){return"ComputeNode"}constructor(e,t){super("void"),this.isComputeNode=!0,this.computeNode=e,this.workgroupSize=t,this.count=null,this.version=1,this.name="",this.updateBeforeType=wc.OBJECT,this.onInitFunction=null}setCount(e){return this.count=e,this}getCount(){return this.count}dispose(){this.dispatchEvent({type:"dispose"})}setName(e){return this.name=e,this}label(e){return Yo('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}onInit(e){return this.onInitFunction=e,this}updateBefore({renderer:e}){e.compute(this)}setup(e){const t=this.computeNode.build(e);if(t){e.getNodeProperties(this).outputComputeNode=t.outputNode,t.outputNode=null}return t}generate(e,t){const{shaderStage:s}=e;if("compute"===s){const t=this.computeNode.build(e,"void");""!==t&&e.addLineFlowCode(t,this)}else{const s=e.getNodeProperties(this).outputComputeNode;if(s)return s.build(e,t)}}}const Mg=(e,t=[64])=>{(0===t.length||t.length>3)&&Zo("TSL: compute() workgroupSize must have 1, 2, or 3 elements");for(let e=0;e<t.length;e++){const s=t[e];("number"!=typeof s||s<=0||!Number.isInteger(s))&&Zo(`TSL: compute() workgroupSize element at index [ ${e} ] must be a positive integer`)}for(;t.length<3;)t.push(1);return bd(new Sg(bd(e),t))},Ag=(e,t,s)=>Mg(e,s).setCount(t);$c("compute",Ag),$c("computeKernel",Mg);class Ng extends Cc{static get type(){return"IsolateNode"}constructor(e,t=!0){super(),this.node=e,this.parent=t,this.isIsolateNode=!0}getNodeType(e){const t=e.getCache(),s=e.getCacheFromNode(this,this.parent);e.setCache(s);const i=this.node.getNodeType(e);return e.setCache(t),i}build(e,...t){const s=e.getCache(),i=e.getCacheFromNode(this,this.parent);e.setCache(i);const r=this.node.build(e,...t);return e.setCache(s),r}setParent(e){return this.parent=e,this}getParent(){return this.parent}}const Eg=e=>new Ng(bd(e));function Cg(e,t=!0){return Yo('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),Eg(e).setParent(t)}$c("cache",Cg),$c("isolate",Eg);class Rg extends Cc{static get type(){return"BypassNode"}constructor(e,t){super(),this.isBypassNode=!0,this.outputNode=e,this.callNode=t}getNodeType(e){return this.outputNode.getNodeType(e)}generate(e){const t=this.callNode.build(e,"void");return""!==t&&e.addLineFlowCode(t,this),this.outputNode.build(e)}}const Pg=Td(Rg).setParameterLength(2);$c("bypass",Pg);class Bg extends Cc{static get type(){return"RemapNode"}constructor(e,t,s,i=Dd(0),r=Dd(1)){super(),this.node=e,this.inLowNode=t,this.inHighNode=s,this.outLowNode=i,this.outHighNode=r,this.doClamp=!0}setup(){const{node:e,inLowNode:t,inHighNode:s,outLowNode:i,outHighNode:r,doClamp:n}=this;let o=e.sub(t).div(s.sub(t));return!0===n&&(o=o.clamp()),o.mul(r.sub(i)).add(i)}}const Ig=Td(Bg,null,null,{doClamp:!1}).setParameterLength(3,5),Dg=Td(Bg).setParameterLength(3,5);$c("remap",Ig),$c("remapClamp",Dg);class Lg extends Cc{static get type(){return"ExpressionNode"}constructor(e="",t="void"){super(t),this.snippet=e}generate(e,t){const s=this.getNodeType(e),i=this.snippet;if("void"!==s)return e.format(i,s,t);e.addLineFlowCode(i,this)}}const Fg=Td(Lg).setParameterLength(1,2),Og=e=>(e?kf(e,Fg("discard")):Fg("discard")).toStack();$c("discard",Og);class Vg extends Bc{static get type(){return"RenderOutputNode"}constructor(e,t,s){super("vec4"),this.colorNode=e,this._toneMapping=t,this.outputColorSpace=s,this.isRenderOutputNode=!0}setToneMapping(e){return this._toneMapping=e,this}getToneMapping(){return this._toneMapping}setup({context:e}){let t=this.colorNode||e.color;const s=(null!==this._toneMapping?this._toneMapping:e.toneMapping)||0,i=(null!==this.outputColorSpace?this.outputColorSpace:e.outputColorSpace)||So;return 0!==s&&(t=t.toneMapping(s)),i!==So&&i!==_a.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const zg=(e,t=null,s=null)=>bd(new Vg(bd(e),t,s));$c("renderOutput",zg);class kg extends Bc{static get type(){return"DebugNode"}constructor(e,t=null){super(),this.node=e,this.callback=t}getNodeType(e){return this.node.getNodeType(e)}setup(e){return this.node.build(e)}analyze(e){return this.node.build(e)}generate(e){const t=this.callback,s=this.node.build(e),i="--- TSL debug - "+e.shaderStage+" shader ---",r="-".repeat(i.length);let n="";return n+="// #"+i+"#\n",n+=e.flow.code.replace(/^\t/gm,"")+"\n",n+="/* ... */ "+s+" /* ... */\n",n+="// #"+r+"#\n",null!==t?t(e,n):Xo(n),s}}const Ug=(e,t=null)=>bd(new kg(bd(e),t)).toStack();$c("debug",Ug);class Gg{constructor(){this._renderer=null,this.currentFrame=null}get nodeFrame(){return this._renderer._nodes.nodeFrame}setRenderer(e){return this._renderer=e,this}getRenderer(){return this._renderer}init(){}begin(){}finish(){}inspect(){}computeAsync(){}beginCompute(){}finishCompute(){}beginRender(){}finishRender(){}copyTextureToTexture(){}copyFramebufferToTexture(){}}class jg extends Cc{static get type(){return"InspectorNode"}constructor(e,t="",s=null){super(),this.node=e,this.name=t,this.callback=s,this.updateType=wc.FRAME,this.isInspectorNode=!0}getName(){return this.name||this.node.name}update(e){e.renderer.inspector.inspect(this)}getNodeType(e){return this.node.getNodeType(e)}setup(e){let t=this.node;return!0===e.context.inspector&&null!==this.callback&&(t=this.callback(t)),!0!==e.renderer.backend.isWebGPUBackend&&e.renderer.inspector.constructor!==Gg&&Qo('TSL: ".toInspector()" is only available with WebGPU.'),t}}function $g(e,t="",s=null){return(e=bd(e)).before(new jg(e,t,s))}$c("toInspector",$g);class Wg extends Cc{static get type(){return"AttributeNode"}constructor(e,t=null){super(t),this.global=!0,this._attributeName=e}getHash(e){return this.getAttributeName(e)}getNodeType(e){let t=this.nodeType;if(null===t){const s=this.getAttributeName(e);if(e.hasGeometryAttribute(s)){const i=e.geometry.getAttribute(s);t=e.getTypeFromAttribute(i)}else t="float"}return t}setAttributeName(e){return this._attributeName=e,this}getAttributeName(){return this._attributeName}generate(e){const t=this.getAttributeName(e),s=this.getNodeType(e);if(!0===e.hasGeometryAttribute(t)){const i=e.geometry.getAttribute(t),r=e.getTypeFromAttribute(i),n=e.getAttribute(t,r);if("vertex"===e.shaderStage)return e.format(n.name,r,s);return sg(this).build(e,s)}return Yo(`AttributeNode: Vertex attribute "${t}" not found on geometry.`),e.generateConst(s)}serialize(e){super.serialize(e),e.global=this.global,e._attributeName=this._attributeName}deserialize(e){super.deserialize(e),this.global=e.global,this._attributeName=e._attributeName}}const Hg=(e,t=null)=>new Wg(e,t),qg=(e=0)=>Hg("uv"+(e>0?e:""),"vec2");class Xg extends Cc{static get type(){return"TextureSizeNode"}constructor(e,t=null){super("uvec2"),this.isTextureSizeNode=!0,this.textureNode=e,this.levelNode=t}generate(e,t){const s=this.textureNode.build(e,"property"),i=null===this.levelNode?"0":this.levelNode.build(e,"int");return e.format(`${e.getMethod("textureDimensions")}( ${s}, ${i} )`,this.getNodeType(e),t)}}const Yg=Td(Xg).setParameterLength(1,2);class Zg extends kp{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=wc.FRAME}get textureNode(){return this._textureNode}get texture(){return this._textureNode.value}update(){const e=this.texture,t=e.images,s=t&&t.length>0?t[0]&&t[0].image||t[0]:e.image;if(s&&void 0!==s.width){const{width:e,height:t}=s;this.value=Math.log2(Math.max(e,t))}}}const Qg=Td(Zg).setParameterLength(1),Kg=new Ra;class Jg extends kp{static get type(){return"TextureNode"}constructor(e=Kg,t=null,s=null,i=null){super(e),this.isTextureNode=!0,this.uvNode=t,this.levelNode=s,this.biasNode=i,this.compareNode=null,this.depthNode=null,this.gradNode=null,this.offsetNode=null,this.sampler=!0,this.updateMatrix=!1,this.updateType=wc.NONE,this.referenceNode=null,this._value=e,this._matrixUniform=null,this._flipYUniform=null,this.setUpdateMatrix(null===t)}set value(e){this.referenceNode?this.referenceNode.value=e:this._value=e}get value(){return this.referenceNode?this.referenceNode.value:this._value}getUniformHash(){return this.value.uuid}getNodeType(){return!0===this.value.isDepthTexture?"float":this.value.type===An?"uvec4":this.value.type===Mn?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return qg(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Up(this.value.matrix)),this._matrixUniform.mul(Gd(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=Up(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(Ld(Yg(this,this.levelNode).y).sub(t.y).sub(1)),t)),t}setup(e){const t=e.getNodeProperties(this);t.referenceNode=this.referenceNode;const s=this.value;if(!s||!0!==s.isTexture)throw new Error("THREE.TSL: `texture( value )` function expects a valid instance of THREE.Texture().");const i=Ed(()=>{let t=this.uvNode;return null!==t&&!0!==e.context.forceUVContext||!e.context.getUV||(t=e.context.getUV(this,e)),t||(t=this.getDefaultUV()),!0===this.updateMatrix&&(t=this.getTransformedUV(t)),t=this.setupUV(e,t),this.updateType=null!==this._matrixUniform||null!==this._flipYUniform?wc.OBJECT:wc.NONE,t})();let r=this.levelNode;null===r&&e.context.getTextureLevel&&(r=e.context.getTextureLevel(this)),t.uvNode=i,t.levelNode=r,t.biasNode=this.biasNode,t.compareNode=this.compareNode,t.gradNode=this.gradNode,t.depthNode=this.depthNode,t.offsetNode=this.offsetNode}generateUV(e,t){return t.build(e,!0===this.sampler?"vec2":"ivec2")}generateOffset(e,t){return t.build(e,"ivec2")}generateSnippet(e,t,s,i,r,n,o,a,l){const h=this.value;let u;return u=r?e.generateTextureBias(h,t,s,r,n,l):a?e.generateTextureGrad(h,t,s,a,n,l):o?e.generateTextureCompare(h,t,s,o,n,l):!1===this.sampler?e.generateTextureLoad(h,t,s,i,n,l):i?e.generateTextureLevel(h,t,s,i,n,l):e.generateTexture(h,t,s,n,l),u}generate(e,t){const s=this.value,i=e.getNodeProperties(this),r=super.generate(e,"property");if(/^sampler/.test(t))return r+"_sampler";if(e.isReference(t))return r;{const n=e.getDataFromNode(this);let o=n.propertyName;if(void 0===o){const{uvNode:t,levelNode:s,biasNode:a,compareNode:l,depthNode:h,gradNode:u,offsetNode:c}=i,d=this.generateUV(e,t),p=s?s.build(e,"float"):null,m=a?a.build(e,"float"):null,f=h?h.build(e,"int"):null,g=l?l.build(e,"float"):null,y=u?[u[0].build(e,"vec2"),u[1].build(e,"vec2")]:null,x=c?this.generateOffset(e,c):null,b=e.getVarFromNode(this);o=e.getPropertyName(b);const _=this.generateSnippet(e,r,d,p,m,f,g,y,x);e.addLineFlowCode(`${o} = ${_}`,this),n.snippet=_,n.propertyName=o}let a=o;const l=this.getNodeType(e);return e.needsToWorkingColorSpace(s)&&(a=hg(Fg(a,l),s.colorSpace).setup(e).build(e,l)),e.format(a,l,t)}}setSampler(e){return this.sampler=e,this}getSampler(){return this.sampler}uv(e){return Yo("TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=bd(e),t.referenceNode=this.getBase(),bd(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=bd(e).mul(Qg(t)),t.referenceNode=this.getBase();const s=t.value;return!1===t.generateMipmaps&&(s&&!1===s.generateMipmaps||s.minFilter===fn||s.magFilter===fn)&&(Yo("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),bd(t)}level(e){const t=this.clone();return t.levelNode=bd(e),t.referenceNode=this.getBase(),bd(t)}size(e){return Yg(this,e)}bias(e){const t=this.clone();return t.biasNode=bd(e),t.referenceNode=this.getBase(),bd(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=bd(e),t.referenceNode=this.getBase(),bd(t)}grad(e,t){const s=this.clone();return s.gradNode=[bd(e),bd(t)],s.referenceNode=this.getBase(),bd(s)}depth(e){const t=this.clone();return t.depthNode=bd(e),t.referenceNode=this.getBase(),bd(t)}offset(e){const t=this.clone();return t.offsetNode=bd(e),t.referenceNode=this.getBase(),bd(t)}serialize(e){super.serialize(e),e.value=this.value.toJSON(e.meta).uuid,e.sampler=this.sampler,e.updateMatrix=this.updateMatrix,e.updateType=this.updateType}deserialize(e){super.deserialize(e),this.value=e.meta.textures[e.value],this.sampler=e.sampler,this.updateMatrix=e.updateMatrix,this.updateType=e.updateType}update(){const e=this.value,t=this._matrixUniform;null!==t&&(t.value=e.matrix),!0===e.matrixAutoUpdate&&e.updateMatrix();const s=this._flipYUniform;null!==s&&(s.value=e.image instanceof ImageBitmap&&!0===e.flipY||!0===e.isRenderTargetTexture||!0===e.isFramebufferTexture||!0===e.isDepthTexture)}clone(){const e=new this.constructor(this.value,this.uvNode,this.levelNode,this.biasNode);return e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}const ey=Td(Jg).setParameterLength(1,4).setName("texture"),ty=(e=Kg,t=null,s=null,i=null)=>{let r;return e&&!0===e.isTextureNode?(r=bd(e.clone()),r.referenceNode=e.getBase(),null!==t&&(r.uvNode=bd(t)),null!==s&&(r.levelNode=bd(s)),null!==i&&(r.biasNode=bd(i))):r=ey(e,t,s,i),r},sy=(...e)=>ty(...e).setSampler(!1);class iy extends kp{static get type(){return"BufferNode"}constructor(e,t,s=0){super(e,t),this.isBufferNode=!0,this.bufferType=t,this.bufferCount=s,this.updateRanges=[]}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}getElementType(e){return this.getNodeType(e)}getInputType(){return"buffer"}}const ry=(e,t,s)=>new iy(e,t,s);class ny extends Rc{static get type(){return"UniformArrayElementNode"}constructor(e,t){super(e,t),this.isArrayBufferElementNode=!0}generate(e){const t=super.generate(e),s=this.getNodeType(),i=this.node.getPaddedType();return e.format(t,i,s)}}class oy extends iy{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?fc(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=wc.RENDER,this.isArrayBufferNode=!0}getNodeType(){return this.paddedType}getElementType(){return this.elementType}getPaddedType(){const e=this.elementType;let t="vec4";return"mat2"===e?t="mat2":!0===/mat/.test(e)?t="mat4":"i"===e.charAt(0)?t="ivec4":"u"===e.charAt(0)&&(t="uvec4"),t}update(){const{array:e,value:t}=this,s=this.elementType;if("float"===s||"int"===s||"uint"===s)for(let s=0;s<e.length;s++){t[4*s]=e[s]}else if("color"===s)for(let s=0;s<e.length;s++){const i=4*s,r=e[s];t[i]=r.r,t[i+1]=r.g,t[i+2]=r.b||0}else if("mat2"===s)for(let s=0;s<e.length;s++){const i=4*s,r=e[s];t[i]=r.elements[0],t[i+1]=r.elements[1],t[i+2]=r.elements[2],t[i+3]=r.elements[3]}else if("mat3"===s)for(let s=0;s<e.length;s++){const i=16*s,r=e[s];t[i]=r.elements[0],t[i+1]=r.elements[1],t[i+2]=r.elements[2],t[i+4]=r.elements[3],t[i+5]=r.elements[4],t[i+6]=r.elements[5],t[i+8]=r.elements[6],t[i+9]=r.elements[7],t[i+10]=r.elements[8],t[i+15]=1}else if("mat4"===s)for(let s=0;s<e.length;s++){const i=16*s,r=e[s];for(let e=0;e<r.elements.length;e++)t[i+e]=r.elements[e]}else for(let s=0;s<e.length;s++){const i=4*s,r=e[s];t[i]=r.x,t[i+1]=r.y,t[i+2]=r.z||0,t[i+3]=r.w||0}}setup(e){const t=this.array.length,s=this.elementType;let i=Float32Array;const r=this.paddedType,n=e.getTypeLength(r);return"i"===s.charAt(0)&&(i=Int32Array),"u"===s.charAt(0)&&(i=Uint32Array),this.value=new i(t*n),this.bufferCount=t,this.bufferType=r,super.setup(e)}element(e){return new ny(this,bd(e))}}const ay=(e,t)=>new oy(e,t);const ly=Td(class extends Cc{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1);let hy,uy;class cy extends Cc{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}getNodeType(){return this.scope===cy.DPR?"float":this.scope===cy.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=wc.NONE;return this.scope!==cy.SIZE&&this.scope!==cy.VIEWPORT&&this.scope!==cy.DPR||(e=wc.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===cy.VIEWPORT?null!==t?uy.copy(t.viewport):(e.getViewport(uy),uy.multiplyScalar(e.getPixelRatio())):this.scope===cy.DPR?this._output.value=e.getPixelRatio():null!==t?(hy.width=t.width,hy.height=t.height):e.getDrawingBufferSize(hy)}setup(){const e=this.scope;let t=null;return t=e===cy.SIZE?Up(hy||(hy=new ua)):e===cy.VIEWPORT?Up(uy||(uy=new Pa)):e===cy.DPR?Up(1):Vd(fy.div(my)),this._output=t,t}generate(e){if(this.scope===cy.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(my).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}cy.COORDINATE="coordinate",cy.VIEWPORT="viewport",cy.SIZE="size",cy.UV="uv",cy.DPR="dpr";const dy=Sd(cy,cy.DPR),py=Sd(cy,cy.UV),my=Sd(cy,cy.SIZE),fy=Sd(cy,cy.COORDINATE),gy=Sd(cy,cy.VIEWPORT),yy=gy.zw,xy=fy.sub(gy.xy),by=xy.div(yy),_y=Ed(()=>(Yo('TSL: "viewportResolution" is deprecated. Use "screenSize" instead.'),my),"vec2").once()(),wy=Up(0,"uint").setName("u_cameraIndex").setGroup(Fp("cameraIndex")).toVarying("v_cameraIndex"),vy=Up("float").setName("cameraNear").setGroup(Vp).onRenderUpdate(({camera:e})=>e.near),Ty=Up("float").setName("cameraFar").setGroup(Vp).onRenderUpdate(({camera:e})=>e.far),Sy=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrix);t=ay(s).setGroup(Vp).setName("cameraProjectionMatrices").element(e.isMultiViewCamera?ly("gl_ViewID_OVR"):wy).toConst("cameraProjectionMatrix")}else t=Up("mat4").setName("cameraProjectionMatrix").setGroup(Vp).onRenderUpdate(({camera:e})=>e.projectionMatrix);return t}).once()(),My=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrixInverse);t=ay(s).setGroup(Vp).setName("cameraProjectionMatricesInverse").element(e.isMultiViewCamera?ly("gl_ViewID_OVR"):wy).toConst("cameraProjectionMatrixInverse")}else t=Up("mat4").setName("cameraProjectionMatrixInverse").setGroup(Vp).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse);return t}).once()(),Ay=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.matrixWorldInverse);t=ay(s).setGroup(Vp).setName("cameraViewMatrices").element(e.isMultiViewCamera?ly("gl_ViewID_OVR"):wy).toConst("cameraViewMatrix")}else t=Up("mat4").setName("cameraViewMatrix").setGroup(Vp).onRenderUpdate(({camera:e})=>e.matrixWorldInverse);return t}).once()(),Ny=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.matrixWorld);t=ay(s).setGroup(Vp).setName("cameraWorldMatrices").element(e.isMultiViewCamera?ly("gl_ViewID_OVR"):wy).toConst("cameraWorldMatrix")}else t=Up("mat4").setName("cameraWorldMatrix").setGroup(Vp).onRenderUpdate(({camera:e})=>e.matrixWorld);return t}).once()(),Ey=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.normalMatrix);t=ay(s).setGroup(Vp).setName("cameraNormalMatrices").element(e.isMultiViewCamera?ly("gl_ViewID_OVR"):wy).toConst("cameraNormalMatrix")}else t=Up("mat3").setName("cameraNormalMatrix").setGroup(Vp).onRenderUpdate(({camera:e})=>e.normalMatrix);return t}).once()(),Cy=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(let t=0,i=e.cameras.length;t<i;t++)s.push(new da);t=ay(s).setGroup(Vp).setName("cameraPositions").onRenderUpdate(({camera:e},t)=>{const s=e.cameras,i=t.array;for(let e=0,t=s.length;e<t;e++)i[e].setFromMatrixPosition(s[e].matrixWorld)}).element(e.isMultiViewCamera?ly("gl_ViewID_OVR"):wy).toConst("cameraPosition")}else t=Up(new da).setName("cameraPosition").setGroup(Vp).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld));return t}).once()(),Ry=Ed(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.viewport);t=ay(s,"vec4").setGroup(Vp).setName("cameraViewports").element(wy).toConst("cameraViewport")}else t=Hd(0,0,my.x,my.y).toConst("cameraViewport");return t}).once()(),Py=new Ja;class By extends Cc{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=wc.OBJECT,this.uniformNode=new kp(null)}getNodeType(){const e=this.scope;return e===By.WORLD_MATRIX?"mat4":e===By.POSITION||e===By.VIEW_POSITION||e===By.DIRECTION||e===By.SCALE?"vec3":e===By.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===By.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===By.POSITION)s.value=s.value||new da,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===By.SCALE)s.value=s.value||new da,s.value.setFromMatrixScale(t.matrixWorld);else if(i===By.DIRECTION)s.value=s.value||new da,t.getWorldDirection(s.value);else if(i===By.VIEW_POSITION){const i=e.camera;s.value=s.value||new da,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===By.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),Py.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),s.value=Py.radius}}generate(e){const t=this.scope;return t===By.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===By.POSITION||t===By.VIEW_POSITION||t===By.DIRECTION||t===By.SCALE?this.uniformNode.nodeType="vec3":t===By.RADIUS&&(this.uniformNode.nodeType="float"),this.uniformNode.build(e)}serialize(e){super.serialize(e),e.scope=this.scope}deserialize(e){super.deserialize(e),this.scope=e.scope}}By.WORLD_MATRIX="worldMatrix",By.POSITION="position",By.SCALE="scale",By.VIEW_POSITION="viewPosition",By.DIRECTION="direction",By.RADIUS="radius";const Iy=Td(By,By.DIRECTION).setParameterLength(1),Dy=Td(By,By.WORLD_MATRIX).setParameterLength(1),Ly=Td(By,By.POSITION).setParameterLength(1),Fy=Td(By,By.SCALE).setParameterLength(1),Oy=Td(By,By.VIEW_POSITION).setParameterLength(1),Vy=Td(By,By.RADIUS).setParameterLength(1);class zy extends By{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const ky=Sd(zy,zy.DIRECTION),Uy=Sd(zy,zy.WORLD_MATRIX),Gy=Sd(zy,zy.POSITION),jy=Sd(zy,zy.SCALE),$y=Sd(zy,zy.VIEW_POSITION),Wy=Sd(zy,zy.RADIUS),Hy=Up(new fa).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),qy=Up(new ll).onObjectUpdate(({object:e},t)=>t.value.copy(e.matrixWorld).invert()),Xy=Ed(e=>e.context.modelViewMatrix||Yy).once()().toVar("modelViewMatrix"),Yy=Ay.mul(Uy),Zy=Ed(e=>(e.context.isHighPrecisionModelViewMatrix=!0,Up("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),Qy=Ed(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return Up("mat3").onObjectUpdate(({object:e,camera:s})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),Ky=Hg("position","vec3"),Jy=Ky.toVarying("positionLocal"),ex=Ky.toVarying("positionPrevious"),tx=Ed(e=>Uy.mul(Jy).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),sx=Ed(()=>Jy.transformDirection(Uy).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),ix=Ed(e=>e.context.setupPositionView().toVarying("v_positionView"),"vec3").once(["POSITION"])(),rx=Ed(e=>{let t;return t=e.camera.isOrthographicCamera?Gd(0,0,1):ix.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class nx extends Cc{static get type(){return"FrontFacingNode"}constructor(){super("bool"),this.isFrontFacingNode=!0}generate(e){if("fragment"!==e.shaderStage)return"true";const{material:t}=e;return 1===t.side?"false":e.getFrontFacing()}}const ox=Sd(nx),ax=Dd(ox).mul(2).sub(1),lx=Ed(([e],{material:t})=>{const s=t.side;return 1===s?e=e.mul(-1):2===s&&(e=e.mul(ax)),e}),hx=Hg("normal","vec3"),ux=Ed(e=>!1===e.geometry.hasAttribute("normal")?(Yo('TSL: Vertex attribute "normal" not found on geometry.'),Gd(0,1,0)):hx,"vec3").once()().toVar("normalLocal"),cx=ix.dFdx().cross(ix.dFdy()).normalize().toVar("normalFlat"),dx=Ed(e=>{let t;return t=!0===e.material.flatShading?cx:xx(ux).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),px=Ed(e=>{let t=dx.transformDirection(Ay);return!0!==e.material.flatShading&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),mx=Ed(({subBuildFn:e,material:t,context:s})=>{let i;return"NORMAL"===e||"VERTEX"===e?(i=dx,!0!==t.flatShading&&(i=lx(i))):i=s.setupNormal().context({getUV:null}),i},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),fx=mx.transformDirection(Ay).toVar("normalWorld"),gx=Ed(({subBuildFn:e,context:t})=>{let s;return s="NORMAL"===e||"VERTEX"===e?mx:t.setupClearcoatNormal().context({getUV:null}),s},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),yx=Ed(([e,t=Uy])=>{const s=Qd(t),i=e.div(Gd(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz}),xx=Ed(([e],t)=>{const s=t.context.modelNormalViewMatrix;if(s)return s.transformDirection(e);const i=Hy.mul(e);return Ay.transformDirection(i)}),bx=Ed(()=>(Yo('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),mx)).once(["NORMAL","VERTEX"])(),_x=Ed(()=>(Yo('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),fx)).once(["NORMAL","VERTEX"])(),wx=Ed(()=>(Yo('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),gx)).once(["NORMAL","VERTEX"])(),vx=new xl,Tx=new ll,Sx=Up(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),Mx=Up(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),Ax=Up(new ll).onReference(function(e){return e.material}).onObjectUpdate(function({material:e,scene:t}){const s=null!==t.environment&&null===e.envMap?t.environmentRotation:e.envMapRotation;return s?(vx.copy(s),Tx.makeRotationFromEuler(vx)):Tx.identity(),Tx}),Nx=rx.negate().reflect(mx),Ex=rx.negate().refract(mx,Sx),Cx=Nx.transformDirection(Ay).toVar("reflectVector"),Rx=Ex.transformDirection(Ay).toVar("reflectVector"),Px=new Xh;class Bx extends Jg{static get type(){return"CubeTextureNode"}constructor(e,t=null,s=null,i=null){super(e,t,s,i),this.isCubeTextureNode=!0}getInputType(){return!0===this.value.isDepthTexture?"cubeDepthTexture":"cubeTexture"}getDefaultUV(){const e=this.value;return e.mapping===un?Cx:e.mapping===cn?Rx:(Zo('CubeTextureNode: Mapping "%s" not supported.',e.mapping),Gd(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return!0===s.isDepthTexture?e.renderer.coordinateSystem===Uo?Gd(t.x,t.y.negate(),t.z):t:(e.renderer.coordinateSystem!==Uo&&s.isRenderTargetTexture||(t=Gd(t.x.negate(),t.yz)),Ax.mul(t))}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const Ix=Td(Bx).setParameterLength(1,4).setName("cubeTexture"),Dx=(e=Px,t=null,s=null,i=null)=>{let r;return e&&!0===e.isCubeTextureNode?(r=bd(e.clone()),r.referenceNode=e,null!==t&&(r.uvNode=bd(t)),null!==s&&(r.levelNode=bd(s)),null!==i&&(r.biasNode=bd(i))):r=Ix(e,t,s,i),r};class Lx extends Rc{static get type(){return"ReferenceElementNode"}constructor(e,t){super(e,t),this.referenceNode=e,this.isReferenceElementNode=!0}getNodeType(){return this.referenceNode.uniformType}generate(e){const t=super.generate(e),s=this.referenceNode.getNodeType(),i=this.getNodeType();return e.format(t,s,i)}}class Fx extends Cc{static get type(){return"ReferenceNode"}constructor(e,t,s=null,i=null){super(),this.property=e,this.uniformType=t,this.object=s,this.count=i,this.properties=e.split("."),this.reference=s,this.node=null,this.group=null,this.name=null,this.updateType=wc.OBJECT}element(e){return new Lx(this,bd(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return Yo('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?ry(null,e,this.count):Array.isArray(this.getValueFromReference())?ay(null,e):"texture"===e?ty(null):"cubeTexture"===e?Dx(null):Up(null,e),null!==this.group&&t.setGroup(this.group),null!==this.name&&t.setName(this.name),this.node=t}getNodeType(e){return null===this.node&&(this.updateReference(e),this.updateValue()),this.node.getNodeType(e)}getValueFromReference(e=this.reference){const{properties:t}=this;let s=e[t[0]];for(let e=1;e<t.length;e++)s=s[t[e]];return s}updateReference(e){return this.reference=null!==this.object?this.object:e.object,this.reference}setup(){return this.updateValue(),this.node}update(){this.updateValue()}updateValue(){null===this.node&&this.setNodeType(this.uniformType);const e=this.getValueFromReference();Array.isArray(e)?this.node.array=e:this.node.value=e}}const Ox=(e,t,s)=>new Fx(e,t,s),Vx=(e,t,s,i)=>new Fx(e,t,i,s);class zx extends Fx{static get type(){return"MaterialReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.material=s,this.isMaterialReferenceNode=!0}updateReference(e){return this.reference=null!==this.material?this.material:e.material,this.reference}}const kx=(e,t,s=null)=>new zx(e,t,s),Ux=qg(),Gx=ix.dFdx(),jx=ix.dFdy(),$x=Ux.dFdx(),Wx=Ux.dFdy(),Hx=mx,qx=jx.cross(Hx),Xx=Hx.cross(Gx),Yx=qx.mul($x.x).add(Xx.mul(Wx.x)),Zx=qx.mul($x.y).add(Xx.mul(Wx.y)),Qx=Yx.dot(Yx).max(Zx.dot(Zx)),Kx=Qx.equal(0).select(0,Qx.inverseSqrt()),Jx=Yx.mul(Kx).toVar("tangentViewFrame"),eb=Zx.mul(Kx).toVar("bitangentViewFrame"),tb=Hg("tangent","vec4"),sb=tb.xyz.toVar("tangentLocal"),ib=Ed(({subBuildFn:e,geometry:t,material:s})=>{let i;return i="VERTEX"===e||t.hasAttribute("tangent")?Xy.mul(Hd(sb,0)).xyz.toVarying("v_tangentView").normalize():Jx,!0!==s.flatShading&&(i=lx(i)),i},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),rb=ib.transformDirection(Ay).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),nb=Ed(([e,t],{subBuildFn:s,material:i})=>{let r=e.mul(tb.w).xyz;return"NORMAL"===s&&!0!==i.flatShading&&(r=r.toVarying(t)),r}).once(["NORMAL"]),ob=nb(hx.cross(tb),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),ab=nb(ux.cross(sb),"v_bitangentLocal").normalize().toVar("bitangentLocal"),lb=Ed(({subBuildFn:e,geometry:t,material:s})=>{let i;return i="VERTEX"===e||t.hasAttribute("tangent")?nb(mx.cross(ib),"v_bitangentView").normalize():eb,!0!==s.flatShading&&(i=lx(i)),i},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),hb=nb(fx.cross(rb),"v_bitangentWorld").normalize().toVar("bitangentWorld"),ub=Qd(ib,lb,mx).toVar("TBNViewMatrix"),cb=rx.mul(ub),db=Ed(()=>{let e=bp.cross(rx);return e=e.cross(bp).normalize(),e=Af(e,mx,yp.mul(ap.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),pb=e=>bd(e).mul(.5).add(.5),mb=e=>Gd(e,Om(Ef(Dd(1).sub(yf(e,e)))));class fb extends Bc{static get type(){return"NormalMapNode"}constructor(e,t=null){super("vec3"),this.node=e,this.scaleNode=t,this.normalMapType=0,this.unpackNormalMode=""}setup({material:e}){const{normalMapType:t,scaleNode:s,unpackNormalMode:i}=this;let r=this.node.mul(2).sub(1);if(0===t?"rg"===i?r=mb(r.xy):"ga"===i?r=mb(r.yw):""!==i&&console.error(`THREE.NodeMaterial: Unexpected unpack normal mode: ${i}`):""!==i&&console.error(`THREE.NodeMaterial: Normal map type '${t}' is not compatible with unpack normal mode '${i}'`),null!==s){let t=s;!0===e.flatShading&&(t=lx(t)),r=Gd(r.xy.mul(t),r.z)}let n=null;return 1===t?n=xx(r):0===t?n=ub.mul(r).normalize():(Zo(`NodeMaterial: Unsupported normal map type: ${t}`),n=mx),n}}const gb=Td(fb).setParameterLength(1,2),yb=Ed(({textureNode:e,bumpScale:t})=>{const s=t=>e.isolate().context({getUV:e=>t(e.uvNode||qg()),forceUVContext:!0}),i=Dd(s(e=>e));return Vd(Dd(s(e=>e.add(e.dFdx()))).sub(i),Dd(s(e=>e.add(e.dFdy()))).sub(i)).mul(t)}),xb=Ed(e=>{const{surf_pos:t,surf_norm:s,dHdxy:i}=e,r=t.dFdx().normalize(),n=s,o=t.dFdy().normalize().cross(n),a=n.cross(r),l=r.dot(o).mul(ax),h=l.sign().mul(i.x.mul(o).add(i.y.mul(a)));return l.abs().mul(s).sub(h).normalize()});class bb extends Bc{static get type(){return"BumpMapNode"}constructor(e,t=null){super("vec3"),this.textureNode=e,this.scaleNode=t}setup(){const e=null!==this.scaleNode?this.scaleNode:1,t=yb({textureNode:this.textureNode,bumpScale:e});return xb({surf_pos:ix,surf_norm:mx,dHdxy:t})}}const _b=Td(bb).setParameterLength(1,2),wb=new Map;class vb extends Cc{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=wb.get(e);return void 0===s&&(s=kx(e,t),wb.set(e,s)),s}getFloat(e){return this.getCache(e,"float")}getColor(e){return this.getCache(e,"color")}getTexture(e){return this.getCache("map"===e?"map":e+"Map","texture")}setup(e){const t=e.context.material,s=this.scope;let i=null;if(s===vb.COLOR){const e=void 0!==t.color?this.getColor(s):Gd();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===vb.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===vb.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:Dd(1);else if(s===vb.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(s).a):e}else if(s===vb.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===vb.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===vb.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===vb.EMISSIVE){const e=this.getFloat("emissiveIntensity"),r=this.getColor(s).mul(e);i=t.emissiveMap&&!0===t.emissiveMap.isTexture?r.mul(this.getTexture(s)):r}else if(s===vb.NORMAL)t.normalMap?(i=gb(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,t.normalMap.format!=kn&&t.normalMap.format!=vo&&t.normalMap.format!=so||(i.unpackNormalMode="rg")):i=t.bumpMap?_b(this.getTexture("bump").r,this.getFloat("bumpScale")):mx;else if(s===vb.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===vb.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===vb.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?gb(this.getTexture(s),this.getCache(s+"Scale","vec2")):mx;else if(s===vb.SHEEN){const e=this.getColor("sheenColor").mul(this.getFloat("sheen"));i=t.sheenColorMap&&!0===t.sheenColorMap.isTexture?e.mul(this.getTexture("sheenColor").rgb):e}else if(s===vb.SHEEN_ROUGHNESS){const e=this.getFloat(s);i=t.sheenRoughnessMap&&!0===t.sheenRoughnessMap.isTexture?e.mul(this.getTexture(s).a):e,i=i.clamp(1e-4,1)}else if(s===vb.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=Zd(o_.x,o_.y,o_.y.negate(),o_.x).mul(e.rg.mul(2).sub(Vd(1)).normalize().mul(e.b))}else i=o_;else if(s===vb.IRIDESCENCE_THICKNESS){const e=Ox("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Ox("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===vb.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===vb.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===vb.IOR)i=this.getFloat(s);else if(s===vb.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===vb.AO)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(s===vb.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(s):Dd(0);else{const t=this.getNodeType(e);i=this.getCache(s,t)}return i}}vb.ALPHA_TEST="alphaTest",vb.COLOR="color",vb.OPACITY="opacity",vb.SHININESS="shininess",vb.SPECULAR="specular",vb.SPECULAR_STRENGTH="specularStrength",vb.SPECULAR_INTENSITY="specularIntensity",vb.SPECULAR_COLOR="specularColor",vb.REFLECTIVITY="reflectivity",vb.ROUGHNESS="roughness",vb.METALNESS="metalness",vb.NORMAL="normal",vb.CLEARCOAT="clearcoat",vb.CLEARCOAT_ROUGHNESS="clearcoatRoughness",vb.CLEARCOAT_NORMAL="clearcoatNormal",vb.EMISSIVE="emissive",vb.ROTATION="rotation",vb.SHEEN="sheen",vb.SHEEN_ROUGHNESS="sheenRoughness",vb.ANISOTROPY="anisotropy",vb.IRIDESCENCE="iridescence",vb.IRIDESCENCE_IOR="iridescenceIOR",vb.IRIDESCENCE_THICKNESS="iridescenceThickness",vb.IOR="ior",vb.TRANSMISSION="transmission",vb.THICKNESS="thickness",vb.ATTENUATION_DISTANCE="attenuationDistance",vb.ATTENUATION_COLOR="attenuationColor",vb.LINE_SCALE="scale",vb.LINE_DASH_SIZE="dashSize",vb.LINE_GAP_SIZE="gapSize",vb.LINE_WIDTH="linewidth",vb.LINE_DASH_OFFSET="dashOffset",vb.POINT_SIZE="size",vb.DISPERSION="dispersion",vb.LIGHT_MAP="light",vb.AO="ao";const Tb=Sd(vb,vb.ALPHA_TEST),Sb=Sd(vb,vb.COLOR),Mb=Sd(vb,vb.SHININESS),Ab=Sd(vb,vb.EMISSIVE),Nb=Sd(vb,vb.OPACITY),Eb=Sd(vb,vb.SPECULAR),Cb=Sd(vb,vb.SPECULAR_INTENSITY),Rb=Sd(vb,vb.SPECULAR_COLOR),Pb=Sd(vb,vb.SPECULAR_STRENGTH),Bb=Sd(vb,vb.REFLECTIVITY),Ib=Sd(vb,vb.ROUGHNESS),Db=Sd(vb,vb.METALNESS),Lb=Sd(vb,vb.NORMAL),Fb=Sd(vb,vb.CLEARCOAT),Ob=Sd(vb,vb.CLEARCOAT_ROUGHNESS),Vb=Sd(vb,vb.CLEARCOAT_NORMAL),zb=Sd(vb,vb.ROTATION),kb=Sd(vb,vb.SHEEN),Ub=Sd(vb,vb.SHEEN_ROUGHNESS),Gb=Sd(vb,vb.ANISOTROPY),jb=Sd(vb,vb.IRIDESCENCE),$b=Sd(vb,vb.IRIDESCENCE_IOR),Wb=Sd(vb,vb.IRIDESCENCE_THICKNESS),Hb=Sd(vb,vb.TRANSMISSION),qb=Sd(vb,vb.THICKNESS),Xb=Sd(vb,vb.IOR),Yb=Sd(vb,vb.ATTENUATION_DISTANCE),Zb=Sd(vb,vb.ATTENUATION_COLOR),Qb=Sd(vb,vb.LINE_SCALE),Kb=Sd(vb,vb.LINE_DASH_SIZE),Jb=Sd(vb,vb.LINE_GAP_SIZE),e_=Sd(vb,vb.LINE_WIDTH),t_=Sd(vb,vb.LINE_DASH_OFFSET),s_=Sd(vb,vb.POINT_SIZE),i_=Sd(vb,vb.DISPERSION),r_=Sd(vb,vb.LIGHT_MAP),n_=Sd(vb,vb.AO),o_=Up(new ua).onReference(function(e){return e.material}).onRenderUpdate(function({material:e}){this.value.set(e.anisotropy*Math.cos(e.anisotropyRotation),e.anisotropy*Math.sin(e.anisotropyRotation))}),a_=Ed(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class l_ extends Rc{static get type(){return"StorageArrayElementNode"}constructor(e,t){super(e,t),this.isStorageArrayElementNode=!0}set storageBufferNode(e){this.node=e}get storageBufferNode(){return this.node}getMemberType(e,t){const s=this.storageBufferNode.structTypeNode;return s?s.getMemberType(e,t):"void"}setup(e){return!1===e.isAvailable("storageBuffer")&&!0===this.node.isPBO&&e.setupPBO(this.node),super.setup(e)}generate(e,t){let s;const i=e.context.assign;if(s=!1===e.isAvailable("storageBuffer")?!0!==this.node.isPBO||!0===i||!this.node.value.isInstancedBufferAttribute&&"compute"===e.shaderStage?this.node.build(e):e.generatePBO(this):super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}const h_=Td(l_).setParameterLength(2);class u_ extends iy{static get type(){return"StorageBufferNode"}constructor(e,t=null,s=0){let i,r=null;t&&t.isStruct?(i="struct",r=t.layout,(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(s=e.count)):null===t&&(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)?(i=uc(e.itemSize),s=e.count):i=t,super(e,i,s),this.isStorageBufferNode=!0,this.structTypeNode=r,this.access=vc.READ_WRITE,this.isAtomic=!1,this.isPBO=!1,this._attribute=null,this._varying=null,this.global=!0,!0!==e.isStorageBufferAttribute&&!0!==e.isStorageInstancedBufferAttribute&&(e.isInstancedBufferAttribute?e.isStorageInstancedBufferAttribute=!0:e.isStorageBufferAttribute=!0)}getHash(e){if(0===this.bufferCount){let t=e.globalCache.getData(this.value);return void 0===t&&(t={node:this},e.globalCache.setData(this.value,t)),t.node.uuid}return this.uuid}getInputType(){return this.value.isIndirectStorageBufferAttribute?"indirectStorageBuffer":"storageBuffer"}element(e){return h_(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(vc.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=wg(this.value),this._varying=sg(this._attribute)),{attribute:this._attribute,varying:this._varying}}getNodeType(e){if(null!==this.structTypeNode)return this.structTypeNode.getNodeType(e);if(e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.getNodeType(e);const{attribute:t}=this.getAttributeData();return t.getNodeType(e)}getMemberType(e,t){return null!==this.structTypeNode?this.structTypeNode.getMemberType(e,t):"void"}generate(e){if(null!==this.structTypeNode&&this.structTypeNode.build(e),e.isAvailable("storageBuffer")||e.isAvailable("indirectStorageBuffer"))return super.generate(e);const{attribute:t,varying:s}=this.getAttributeData(),i=s.build(e);return e.registerTransform(i,t),i}}const c_=(e,t=null,s=0)=>new u_(e,t,s);class d_ extends Cc{static get type(){return"IndexNode"}constructor(e){super("uint"),this.scope=e,this.isIndexNode=!0}generate(e){const t=this.getNodeType(e),s=this.scope;let i,r;if(s===d_.VERTEX)i=e.getVertexIndex();else if(s===d_.INSTANCE)i=e.getInstanceIndex();else if(s===d_.DRAW)i=e.getDrawIndex();else if(s===d_.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===d_.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==d_.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=sg(this).build(e,t)}return r}}d_.VERTEX="vertex",d_.INSTANCE="instance",d_.SUBGROUP="subgroup",d_.INVOCATION_LOCAL="invocationLocal",d_.INVOCATION_SUBGROUP="invocationSubgroup",d_.DRAW="draw";const p_=Sd(d_,d_.VERTEX),m_=Sd(d_,d_.INSTANCE),f_=Sd(d_,d_.SUBGROUP),g_=Sd(d_,d_.INVOCATION_SUBGROUP),y_=Sd(d_,d_.INVOCATION_LOCAL),x_=Sd(d_,d_.DRAW);class b_ extends Cc{static get type(){return"InstanceNode"}constructor(e,t,s=null){super("void"),this.count=e,this.instanceMatrix=t,this.instanceColor=s,this.instanceMatrixNode=null,this.instanceColorNode=null,this.updateType=wc.FRAME,this.buffer=null,this.bufferColor=null}get isStorageMatrix(){const{instanceMatrix:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}get isStorageColor(){const{instanceColor:e}=this;return e&&!0===e.isStorageInstancedBufferAttribute}setup(e){const{instanceMatrix:t,instanceColor:s,isStorageMatrix:i,isStorageColor:r}=this,{count:n}=t;let{instanceMatrixNode:o,instanceColorNode:a}=this;if(null===o){if(i)o=c_(t,"mat4",Math.max(n,1)).element(m_);else if(n<=1e3)o=ry(t.array,"mat4",Math.max(n,1)).element(m_);else{const e=new Ku(t.array,16,1);this.buffer=e;const s=t.usage===zo?Tg:vg,i=[s(e,"vec4",16,0),s(e,"vec4",16,4),s(e,"vec4",16,8),s(e,"vec4",16,12)];o=Kd(...i)}this.instanceMatrixNode=o}if(s&&null===a){if(r)a=c_(s,"vec3",Math.max(s.count,1)).element(m_);else{const e=new nu(s.array,3),t=s.usage===zo?Tg:vg;this.bufferColor=e,a=Gd(t(e,"vec3",3,0))}this.instanceColorNode=a}const l=o.mul(Jy).xyz;if(Jy.assign(l),e.hasGeometryAttribute("normal")){const e=yx(ux,o);ux.assign(e)}null!==this.instanceColorNode&&ip("vec3","vInstanceColor").assign(this.instanceColorNode)}update(){null!==this.buffer&&!0!==this.isStorageMatrix&&(this.buffer.clearUpdateRanges(),this.buffer.updateRanges.push(...this.instanceMatrix.updateRanges),this.instanceMatrix.usage!==zo&&this.instanceMatrix.version!==this.buffer.version&&(this.buffer.version=this.instanceMatrix.version)),this.instanceColor&&null!==this.bufferColor&&!0!==this.isStorageColor&&(this.bufferColor.clearUpdateRanges(),this.bufferColor.updateRanges.push(...this.instanceColor.updateRanges),this.instanceColor.usage!==zo&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version))}}const __=Td(b_).setParameterLength(2,3);class w_ extends b_{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instancedMesh=e}}const v_=Td(w_).setParameterLength(1);class T_ extends Cc{static get type(){return"BatchNode"}constructor(e){super("void"),this.batchMesh=e,this.batchingIdNode=null}setup(e){null===this.batchingIdNode&&(null===e.getDrawIndex()?this.batchingIdNode=m_:this.batchingIdNode=x_);const t=Ed(([e])=>{const t=Ld(Yg(sy(this.batchMesh._indirectTexture),0).x).toConst(),s=Ld(e).mod(t).toConst(),i=Ld(e).div(t).toConst();return sy(this.batchMesh._indirectTexture,zd(s,i)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]})(Ld(this.batchingIdNode)),s=this.batchMesh._matricesTexture,i=Ld(Yg(sy(s),0).x).toConst(),r=Dd(t).mul(4).toInt().toConst(),n=r.mod(i).toConst(),o=r.div(i).toConst(),a=Kd(sy(s,zd(n,o)),sy(s,zd(n.add(1),o)),sy(s,zd(n.add(2),o)),sy(s,zd(n.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=Ed(([e])=>{const t=Ld(Yg(sy(l),0).x).toConst(),s=e,i=s.mod(t).toConst(),r=s.div(t).toConst();return sy(l,zd(i,r)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]})(t);ip("vec3","vBatchColor").assign(e)}const h=Qd(a);Jy.assign(a.mul(Jy));const u=ux.div(Gd(h[0].dot(h[0]),h[1].dot(h[1]),h[2].dot(h[2]))),c=h.mul(u).xyz;ux.assign(c),e.hasGeometryAttribute("tangent")&&sb.mulAssign(h)}}const S_=Td(T_).setParameterLength(1),M_=new WeakMap;class A_ extends Cc{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=wc.OBJECT,this.skinIndexNode=Hg("skinIndex","uvec4"),this.skinWeightNode=Hg("skinWeight","vec4"),this.bindMatrixNode=Ox("bindMatrix","mat4"),this.bindMatrixInverseNode=Ox("bindMatrixInverse","mat4"),this.boneMatricesNode=Vx("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Jy,this.toPositionNode=Jy,this.previousBoneMatricesNode=null}getSkinnedPosition(e=this.boneMatricesNode,t=this.positionNode){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),l=e.element(s.z),h=e.element(s.w),u=r.mul(t),c=Zp(o.mul(i.x).mul(u),a.mul(i.y).mul(u),l.mul(i.z).mul(u),h.mul(i.w).mul(u));return n.mul(c).xyz}getSkinnedNormal(e=this.boneMatricesNode,t=ux){const{skinIndexNode:s,skinWeightNode:i,bindMatrixNode:r,bindMatrixInverseNode:n}=this,o=e.element(s.x),a=e.element(s.y),l=e.element(s.z),h=e.element(s.w);let u=Zp(i.x.mul(o),i.y.mul(a),i.z.mul(l),i.w.mul(h));return u=n.mul(u).mul(r),u.transformDirection(t).xyz}getPreviousSkinnedPosition(e){const t=e.object;return null===this.previousBoneMatricesNode&&(t.skeleton.previousBoneMatrices=new Float32Array(t.skeleton.boneMatrices),this.previousBoneMatricesNode=Vx("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,ex)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===yc(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&ex.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();ux.assign(t),e.hasGeometryAttribute("tangent")&&sb.assign(t)}return t}generate(e,t){if("void"!==t)return super.generate(e,t)}update(e){const t=e.object&&e.object.skeleton?e.object.skeleton:this.skinnedMesh.skeleton;M_.get(t)!==e.frameId&&(M_.set(t,e.frameId),null!==this.previousBoneMatricesNode&&(null===t.previousBoneMatrices&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}const N_=e=>new A_(e);class E_ extends Cc{static get type(){return"LoopNode"}constructor(e=[]){super("void"),this.params=e}getVarName(e){return String.fromCharCode("i".charCodeAt(0)+e)}getProperties(e){const t=e.getNodeProperties(this);if(void 0!==t.stackNode)return t;const s={};for(let e=0,t=this.params.length-1;e<t;e++){const t=this.params[e],i=!0!==t.isNode&&t.name||this.getVarName(e),r=!0!==t.isNode&&t.type||"int";s[i]=Fg(i,r)}const i=e.addStack(),r=this.params[this.params.length-1](s);t.returnsNode=r.context({nodeLoop:r}),t.stackNode=i;const n=this.params[0];if(!0!==n.isNode&&"function"==typeof n.update){const e=Ed(this.params[0].update)(s);t.updateNode=e.context({nodeLoop:e})}return e.removeStack(),t}setup(e){if(this.getProperties(e),e.fnCall){e.getDataFromNode(e.fnCall.shaderNode).hasLoop=!0}}generate(e){const t=this.getProperties(e),s=this.params,i=t.stackNode;for(let i=0,r=s.length-1;i<r;i++){const r=s[i];let n,o=!1,a=null,l=null,h=null,u=null,c=null,d=null;if(r.isNode?"bool"===r.getNodeType(e)?(o=!0,u="bool",l=r.build(e,u)):(u="int",h=this.getVarName(i),a="0",l=r.build(e,u),c="<"):(u=r.type||"int",h=r.name||this.getVarName(i),a=r.start,l=r.end,c=r.condition,d=r.update,"number"==typeof a?a=e.generateConst(u,a):a&&a.isNode&&(a=a.build(e,u)),"number"==typeof l?l=e.generateConst(u,l):l&&l.isNode&&(l=l.build(e,u)),void 0!==a&&void 0===l?(a+=" - 1",l="0",c=">="):void 0!==l&&void 0===a&&(a="0",c="<"),void 0===c&&(c=Number(a)>Number(l)?">=":"<")),o)n=`while ( ${l} )`;else{const s={start:a,end:l},i=s.start,r=s.end;let o;const p=()=>c.includes("<")?"+=":"-=";if(null!=d)switch(typeof d){case"function":o=e.flowStagesNode(t.updateNode,"void").code.replace(/\t|;/g,"");break;case"number":o=h+" "+p()+" "+e.generateConst(u,d);break;case"string":o=h+" "+d;break;default:d.isNode?o=h+" "+p()+" "+d.build(e):(Zo("TSL: 'Loop( { update: ... } )' is not a function, string or number."),o="break /* invalid update */")}else d="int"===u||"uint"===u?c.includes("<")?"++":"--":p()+" 1.",o=h+" "+d;n=`for ( ${e.getVar(u,h)+" = "+i}; ${h+" "+c+" "+r}; ${o} )`}e.addFlowCode((0===i?"\n":"")+e.tab+n+" {\n\n").addFlowTab()}const r=i.build(e,"void");t.returnsNode.build(e,"void"),e.removeFlowTab().addFlowCode("\n"+e.tab+r);for(let t=0,s=this.params.length-1;t<s;t++)e.addFlowCode((0===t?"":e.tab)+"}\n\n").removeFlowTab();e.addFlowTab()}}const C_=(...e)=>new E_(vd(e,"int")).toStack(),R_=()=>Fg("break").toStack(),P_=new WeakMap,B_=new Pa,I_=Ed(({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const o=Ld(p_).mul(s).add(n),a=o.div(i),l=o.sub(a.mul(i));return sy(e,zd(l,a)).depth(r).xyz.mul(t)});class D_ extends Cc{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Up(1),this.updateType=wc.OBJECT}setup(e){const{geometry:t}=e,s=void 0!==t.morphAttributes.position,i=t.hasAttribute("normal")&&void 0!==t.morphAttributes.normal,r=t.morphAttributes.position||t.morphAttributes.normal||t.morphAttributes.color,n=void 0!==r?r.length:0,{texture:o,stride:a,size:l}=function(e){const t=void 0!==e.morphAttributes.position,s=void 0!==e.morphAttributes.normal,i=void 0!==e.morphAttributes.color,r=e.morphAttributes.position||e.morphAttributes.normal||e.morphAttributes.color,n=void 0!==r?r.length:0;let o=P_.get(e);if(void 0===o||o.count!==n){let r=function(){f.dispose(),P_.delete(e),e.removeEventListener("dispose",r)};void 0!==o&&o.texture.dispose();const a=e.morphAttributes.position||[],l=e.morphAttributes.normal||[],h=e.morphAttributes.color||[];let u=0;!0===t&&(u=1),!0===s&&(u=2),!0===i&&(u=3);let c=e.attributes.position.count*u,d=1;const p=4096;c>p&&(d=Math.ceil(c/p),c=p);const m=new Float32Array(c*d*4*n),f=new Da(m,c,d,n);f.type=Nn,f.needsUpdate=!0;const g=4*u;for(let e=0;e<n;e++){const r=a[e],n=l[e],o=h[e],u=c*d*4*e;for(let e=0;e<r.count;e++){const a=e*g;!0===t&&(B_.fromBufferAttribute(r,e),m[u+a+0]=B_.x,m[u+a+1]=B_.y,m[u+a+2]=B_.z,m[u+a+3]=0),!0===s&&(B_.fromBufferAttribute(n,e),m[u+a+4]=B_.x,m[u+a+5]=B_.y,m[u+a+6]=B_.z,m[u+a+7]=0),!0===i&&(B_.fromBufferAttribute(o,e),m[u+a+8]=B_.x,m[u+a+9]=B_.y,m[u+a+10]=B_.z,m[u+a+11]=4===o.itemSize?B_.w:1)}}o={count:n,texture:f,stride:u,size:new ua(c,d)},P_.set(e,o),e.addEventListener("dispose",r)}return o}(t);!0===s&&Jy.mulAssign(this.morphBaseInfluence),!0===i&&ux.mulAssign(this.morphBaseInfluence);const h=Ld(l.width);C_(n,({i:e})=>{const t=Dd(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(sy(this.mesh.morphTexture,zd(Ld(e).add(1),Ld(m_))).r):t.assign(Ox("morphTargetInfluences","float").element(e).toVar()),Pd(t.notEqual(0),()=>{!0===s&&Jy.addAssign(I_({bufferMap:o,influence:t,stride:a,width:h,depth:e,offset:Ld(0)})),!0===i&&ux.addAssign(I_({bufferMap:o,influence:t,stride:a,width:h,depth:e,offset:Ld(1)}))})})}update(){const e=this.morphBaseInfluence;this.mesh.geometry.morphTargetsRelative?e.value=1:e.value=1-this.mesh.morphTargetInfluences.reduce((e,t)=>e+t,0)}}const L_=Td(D_).setParameterLength(1);class F_ extends Cc{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class O_ extends F_{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class V_ extends Uf{static get type(){return"LightingContextNode"}constructor(e,t=null,s=null,i=null){super(e),this.lightingModel=t,this.backdropNode=s,this.backdropAlphaNode=i,this._value=null}getContext(){const{backdropNode:e,backdropAlphaNode:t}=this,s={directDiffuse:Gd().toVar("directDiffuse"),directSpecular:Gd().toVar("directSpecular"),indirectDiffuse:Gd().toVar("indirectDiffuse"),indirectSpecular:Gd().toVar("indirectSpecular")};return{radiance:Gd().toVar("radiance"),irradiance:Gd().toVar("irradiance"),iblIrradiance:Gd().toVar("iblIrradiance"),ambientOcclusion:Dd(1).toVar("ambientOcclusion"),reflectedLight:s,backdrop:e,backdropAlpha:t}}setup(e){return this.value=this._value||(this._value=this.getContext()),this.value.lightingModel=this.lightingModel||e.context.lightingModel,super.setup(e)}}const z_=Td(V_);class k_ extends F_{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const U_=new ua;class G_ extends Jg{static get type(){return"ViewportTextureNode"}constructor(e=py,t=null,s=null){let i=null;null===s?(i=new bu,i.minFilter=_n,s=i):i=s,super(s,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=wc.FRAME,this._cacheTextures=new WeakMap}getTextureForReference(e=null){let t,s;if(this.referenceNode?(t=this.referenceNode.defaultFramebuffer,s=this.referenceNode._cacheTextures):(t=this.defaultFramebuffer,s=this._cacheTextures),null===e)return t;if(!1===s.has(e)){const i=t.clone();s.set(e,i)}return s.get(e)}updateReference(e){const t=e.renderer.getRenderTarget();return this.value=this.getTextureForReference(t),this.value}updateBefore(e){const t=e.renderer,s=t.getRenderTarget();null===s?t.getDrawingBufferSize(U_):U_.set(s.width,s.height);const i=this.getTextureForReference(s);i.image.width===U_.width&&i.image.height===U_.height||(i.image.width=U_.width,i.image.height=U_.height,i.needsUpdate=!0);const r=i.generateMipmaps;i.generateMipmaps=this.generateMipmaps,t.copyFramebufferToTexture(i),i.generateMipmaps=r}clone(){const e=new this.constructor(this.uvNode,this.levelNode,this.value);return e.generateMipmaps=this.generateMipmaps,e}}const j_=Td(G_).setParameterLength(0,3),$_=Td(G_,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let W_=null;class H_ extends G_{static get type(){return"ViewportDepthTextureNode"}constructor(e=py,t=null){null===W_&&(W_=new _u),super(e,t,W_)}getTextureForReference(){return W_}}const q_=Td(H_).setParameterLength(0,2);class X_ extends Cc{static get type(){return"ViewportDepthNode"}constructor(e,t=null){super("float"),this.scope=e,this.valueNode=t,this.isViewportDepthNode=!0}generate(e){const{scope:t}=this;return t===X_.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===X_.DEPTH_BASE)null!==s&&(i=J_().assign(s));else if(t===X_.DEPTH)i=e.isPerspectiveCamera?Z_(ix.z,vy,Ty):Y_(ix.z,vy,Ty);else if(t===X_.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=Q_(s,vy,Ty);i=Y_(e,vy,Ty)}else i=s;else i=Y_(ix.z,vy,Ty);return i}}X_.DEPTH_BASE="depthBase",X_.DEPTH="depth",X_.LINEAR_DEPTH="linearDepth";const Y_=(e,t,s)=>e.add(t).div(t.sub(s)),Z_=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),Q_=(e,t,s)=>t.mul(s).div(s.sub(t).mul(e).sub(s)),K_=(e,t,s)=>{t=t.max(1e-6).toVar();const i=Fm(e.negate().div(t)),r=Fm(s.div(t));return i.div(r)},J_=Td(X_,X_.DEPTH_BASE),ew=Sd(X_,X_.DEPTH),tw=Td(X_,X_.LINEAR_DEPTH).setParameterLength(0,1),sw=tw(q_());ew.assign=e=>J_(e);class iw extends Cc{static get type(){return"ClippingNode"}constructor(e=iw.DEFAULT){super(),this.scope=e}setup(e){super.setup(e);const t=e.clippingContext,{intersectionPlanes:s,unionPlanes:i}=t;return this.hardwareClipping=e.material.hardwareClipping,this.scope===iw.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===iw.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return Ed(()=>{const s=Dd().toVar("distanceToPlane"),i=Dd().toVar("distanceToGradient"),r=Dd(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=ay(t).setGroup(Vp);C_(n,({i:t})=>{const n=e.element(t);s.assign(ix.dot(n.xyz).negate().add(n.w)),i.assign(s.fwidth().div(2)),r.mulAssign(Rf(i.negate(),i,s))})}const o=e.length;if(o>0){const t=ay(e).setGroup(Vp),n=Dd(1).toVar("intersectionClipOpacity");C_(o,({i:e})=>{const r=t.element(e);s.assign(ix.dot(r.xyz).negate().add(r.w)),i.assign(s.fwidth().div(2)),n.mulAssign(Rf(i.negate(),i,s).oneMinus())}),r.mulAssign(n.oneMinus())}rp.a.mulAssign(r),rp.a.equal(0).discard()})()}setupDefault(e,t){return Ed(()=>{const s=t.length;if(!1===this.hardwareClipping&&s>0){const e=ay(t).setGroup(Vp);C_(s,({i:t})=>{const s=e.element(t);ix.dot(s.xyz).greaterThan(s.w).discard()})}const i=e.length;if(i>0){const t=ay(e).setGroup(Vp),s=Od(!0).toVar("clipped");C_(i,({i:e})=>{const i=t.element(e);s.assign(ix.dot(i.xyz).greaterThan(i.w).and(s))}),s.discard()}})()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),Ed(()=>{const i=ay(e).setGroup(Vp),r=ly(t.getClipDistance());C_(s,({i:e})=>{const t=i.element(e),s=ix.dot(t.xyz).sub(t.w).negate();r.element(e).assign(s)})})()}}iw.ALPHA_TO_COVERAGE="alphaToCoverage",iw.DEFAULT="default",iw.HARDWARE="hardware";const rw=Ed(([e])=>Gm(Kp(1e4,jm(Kp(17,e.x).add(Kp(.1,e.y)))).mul(Zp(.1,Ym(jm(Kp(13,e.y).add(e.x))))))),nw=Ed(([e])=>rw(Vd(rw(e.xy),e.z))),ow=Ed(([e])=>{const t=df(Qm(ef(e.xyz)),Qm(tf(e.xyz))),s=Dd(1).div(Dd(.05).mul(t)).toVar("pixScale"),i=Vd(Dm(zm(Fm(s))),Dm(km(Fm(s)))),r=Vd(nw(zm(i.x.mul(e.xyz))),nw(zm(i.y.mul(e.xyz)))),n=Gm(Fm(s)),o=Zp(Kp(n.oneMinus(),r.x),Kp(n,r.y)),a=cf(n,n.oneMinus()),l=Gd(o.mul(o).div(Kp(2,a).mul(Qp(1,a))),o.sub(Kp(.5,a)).div(Qp(1,a)),Qp(1,Qp(1,o).mul(Qp(1,o)).div(Kp(2,a).mul(Qp(1,a))))),h=o.lessThan(a.oneMinus()).select(o.lessThan(a).select(l.x,l.y),l.z);return Nf(h,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class aw extends Wg{static get type(){return"VertexColorNode"}constructor(e){super(null,"vec4"),this.isVertexColorNode=!0,this.index=e}getAttributeName(){const e=this.index;return"color"+(e>0?e:"")}generate(e){const t=this.getAttributeName(e);let s;return s=!0===e.hasGeometryAttribute(t)?super.generate(e):e.generateConst(this.nodeType,new Pa(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const lw=(e=0)=>new aw(e),hw=Ed(([e,t])=>cf(1,e.oneMinus().div(t)).oneMinus()).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),uw=Ed(([e,t])=>cf(e.div(t.oneMinus()),1)).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),cw=Ed(([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus()).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),dw=Ed(([e,t])=>Af(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),pf(.5,e))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),pw=Ed(([e,t])=>{const s=t.a.add(e.a.mul(t.a.oneMinus()));return Hd(t.rgb.mul(t.a).add(e.rgb.mul(e.a).mul(t.a.oneMinus())).div(s),s)}).setLayout({name:"blendColor",type:"vec4",inputs:[{name:"base",type:"vec4"},{name:"blend",type:"vec4"}]}),mw=Ed(([e])=>Hd(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"}),fw=Ed(([e])=>(Pd(e.a.equal(0),()=>Hd(0)),Hd(e.rgb.div(e.a),e.a)),{color:"vec4",return:"vec4"});class gw extends ih{static get type(){return"NodeMaterial"}get type(){return this.constructor.type}set type(e){}constructor(){super(),this.isNodeMaterial=!0,this.fog=!0,this.lights=!1,this.hardwareClipping=!1,this.lightsNode=null,this.envNode=null,this.aoNode=null,this.colorNode=null,this.normalNode=null,this.opacityNode=null,this.backdropNode=null,this.backdropAlphaNode=null,this.alphaTestNode=null,this.maskNode=null,this.positionNode=null,this.geometryNode=null,this.depthNode=null,this.receivedShadowPositionNode=null,this.castShadowPositionNode=null,this.receivedShadowNode=null,this.castShadowNode=null,this.outputNode=null,this.mrtNode=null,this.fragmentNode=null,this.vertexNode=null,this.contextNode=null,Object.defineProperty(this,"shadowPositionNode",{get:()=>this.receivedShadowPositionNode,set:e=>{Yo('NodeMaterial: ".shadowPositionNode" was renamed to ".receivedShadowPositionNode".'),this.receivedShadowPositionNode=e}})}_getNodeChildren(){const e=[];for(const t of Object.getOwnPropertyNames(this)){if(!0===t.startsWith("_"))continue;const s=this[t];s&&!0===s.isNode&&e.push({property:t,childNode:s})}return e}customProgramCacheKey(){const e=[];for(const{property:t,childNode:s}of this._getNodeChildren())e.push(nc(t.slice(0,-4)),s.getCacheKey());return this.type+oc(e)}build(e){this.setup(e)}setupObserver(e){return new ic(e)}setup(e){e.context.setupNormal=()=>eg(this.setupNormal(e),"NORMAL","vec3"),e.context.setupPositionView=()=>this.setupPositionView(e),e.context.setupModelViewProjection=()=>this.setupModelViewProjection(e);const t=e.renderer,s=t.getRenderTarget();!0===t.contextNode.isContextNode?e.context={...e.context,...t.contextNode.getFlowContextData()}:Zo('NodeMaterial: "renderer.contextNode" must be an instance of `context()`.'),null!==this.contextNode&&(!0===this.contextNode.isContextNode?e.context={...e.context,...this.contextNode.getFlowContextData()}:Zo('NodeMaterial: "material.contextNode" must be an instance of `context()`.')),e.addStack();const i=eg(this.setupVertex(e),"VERTEX"),r=this.vertexNode||i;let n;e.stack.outputNode=r,this.setupHardwareClipping(e),null!==this.geometryNode&&(e.stack.outputNode=e.stack.outputNode.bypass(this.geometryNode)),e.addFlow("vertex",e.removeStack()),e.addStack();const o=this.setupClipping(e);if(!0!==this.depthWrite&&!0!==this.depthTest||(null!==s?!0===s.depthBuffer&&this.setupDepth(e):!0===t.depth&&this.setupDepth(e)),null===this.fragmentNode){this.setupDiffuseColor(e),this.setupVariants(e);const i=this.setupLighting(e);null!==o&&e.stack.addToStack(o);const r=Hd(i,rp.a).max(0);n=this.setupOutput(e,r),Sp.assign(n);const a=null!==this.outputNode;if(a&&(n=this.outputNode),e.context.getOutput&&(n=e.context.getOutput(n,e)),null!==s){const e=t.getMRT(),s=this.mrtNode;null!==e?(a&&Sp.assign(n),n=e,null!==s&&(n=e.merge(s))):null!==s&&(n=s)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=Hd(t)),n=this.setupOutput(e,t)}e.stack.outputNode=n,e.addFlow("fragment",e.removeStack()),e.observer=this.setupObserver(e)}setupClipping(e){if(null===e.clippingContext)return null;const{unionPlanes:t,intersectionPlanes:s}=e.clippingContext;let i=null;if(t.length>0||s.length>0){const t=e.renderer.currentSamples;this.alphaToCoverage&&t>1?i=new iw(iw.ALPHA_TO_COVERAGE):e.stack.addToStack(new iw)}return i}setupHardwareClipping(e){if(this.hardwareClipping=!1,null===e.clippingContext)return;const t=e.clippingContext.unionPlanes.length;t>0&&t<=8&&e.isAvailable("clipDistance")&&(e.stack.addToStack(new iw(iw.HARDWARE)),this.hardwareClipping=!0)}setupDepth(e){const{renderer:t,camera:s}=e;let i=this.depthNode;if(null===i){const e=t.getMRT();e&&e.has("depth")?i=e.get("depth"):!0===t.logarithmicDepthBuffer&&(i=s.isPerspectiveCamera?K_(ix.z,vy,Ty):Y_(ix.z,vy,Ty))}null!==i&&ew.assign(i).toStack()}setupPositionView(){return Xy.mul(Jy).xyz}setupModelViewProjection(){return Sy.mul(ix)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),a_}setupPosition(e){const{object:t,geometry:s}=e;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&L_(t).toStack(),!0===t.isSkinnedMesh&&N_(t).toStack(),this.displacementMap){const e=kx("displacementMap","texture"),t=kx("displacementScale","float"),s=kx("displacementBias","float");Jy.addAssign(ux.normalize().mul(e.x.mul(t).add(s)))}return t.isBatchedMesh&&S_(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&v_(t).toStack(),null!==this.positionNode&&Jy.assign(eg(this.positionNode,"POSITION","vec3")),Jy}setupDiffuseColor(e){const{object:t,geometry:s}=e;null!==this.maskNode&&Od(this.maskNode).not().discard();let i=this.colorNode?Hd(this.colorNode):Sb;if(!0===this.vertexColors&&s.hasAttribute("color")&&(i=i.mul(lw())),t.instanceColor){i=ip("vec3","vInstanceColor").mul(i)}if(t.isBatchedMesh&&t._colorsTexture){i=ip("vec3","vBatchColor").mul(i)}rp.assign(i);const r=this.opacityNode?Dd(this.opacityNode):Nb;rp.a.assign(rp.a.mul(r));let n=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(n=null!==this.alphaTestNode?Dd(this.alphaTestNode):Tb,!0===this.alphaToCoverage?(rp.a=Rf(n,n.add(of(rp.a)),rp.a),rp.a.lessThanEqual(0).discard()):rp.a.lessThanEqual(n).discard()),!0===this.alphaHash&&rp.a.lessThan(ow(Jy)).discard(),e.isOpaque()&&rp.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Gd(0):rp.rgb}setupNormal(){return this.normalNode?Gd(this.normalNode):Lb}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?kx("envMap","cubeTexture"):kx("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new k_(r_)),t}setupLights(e){const t=[],s=this.setupEnvironment(e);s&&s.isLightingNode&&t.push(s);const i=this.setupLightMap(e);i&&i.isLightingNode&&t.push(i);let r=this.aoNode;null===r&&e.material.aoMap&&(r=n_),e.context.getAO&&(r=e.context.getAO(r,e)),r&&t.push(new O_(r));let n=this.lightsNode||e.lightsNode;return t.length>0&&(n=e.renderer.lighting.createNode([...n.getLights(),...t])),n}setupLightingModel(){}setupLighting(e){const{material:t}=e,{backdropNode:s,backdropAlphaNode:i,emissiveNode:r}=this,n=!0===this.lights||null!==this.lightsNode?this.setupLights(e):null;let o=this.setupOutgoingLight(e);if(n&&n.getScope().hasLights){const t=this.setupLightingModel(e)||null;o=z_(n,t,s,i)}else null!==s&&(o=Gd(null!==i?Af(o,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(op.assign(Gd(r||Ab)),o=o.add(op)),o}setupFog(e,t){const s=e.fogNode;return s&&(Sp.assign(t),t=Hd(s.toVar())),t}setupPremultipliedAlpha(e,t){return mw(t)}setupOutput(e,t){return!0===this.fog&&(t=this.setupFog(e,t)),!0===this.premultipliedAlpha&&(t=this.setupPremultipliedAlpha(e,t)),t}setDefaultValues(e){for(const t in e){const s=e[t];void 0===this[t]&&(this[t]=s,s&&s.clone&&(this[t]=s.clone()))}const t=Object.getOwnPropertyDescriptors(e.constructor.prototype);for(const e in t)void 0===Object.getOwnPropertyDescriptor(this.constructor.prototype,e)&&void 0!==t[e].get&&Object.defineProperty(this.constructor.prototype,e,t[e])}toJSON(e){const t=void 0===e||"string"==typeof e;t&&(e={textures:{},images:{},nodes:{}});const s=ih.prototype.toJSON.call(this,e);s.inputNodes={};for(const{property:t,childNode:i}of this._getNodeChildren())s.inputNodes[t]=i.toJSON(e).uuid;function i(e){const t=[];for(const s in e){const i=e[s];delete i.metadata,t.push(i)}return t}if(t){const t=i(e.textures),r=i(e.images),n=i(e.nodes);t.length>0&&(s.textures=t),r.length>0&&(s.images=r),n.length>0&&(s.nodes=n)}return s}copy(e){return this.lightsNode=e.lightsNode,this.envNode=e.envNode,this.aoNode=e.aoNode,this.colorNode=e.colorNode,this.normalNode=e.normalNode,this.opacityNode=e.opacityNode,this.backdropNode=e.backdropNode,this.backdropAlphaNode=e.backdropAlphaNode,this.alphaTestNode=e.alphaTestNode,this.maskNode=e.maskNode,this.positionNode=e.positionNode,this.geometryNode=e.geometryNode,this.depthNode=e.depthNode,this.receivedShadowPositionNode=e.receivedShadowPositionNode,this.castShadowPositionNode=e.castShadowPositionNode,this.receivedShadowNode=e.receivedShadowNode,this.castShadowNode=e.castShadowNode,this.outputNode=e.outputNode,this.mrtNode=e.mrtNode,this.fragmentNode=e.fragmentNode,this.vertexNode=e.vertexNode,this.contextNode=e.contextNode,super.copy(e)}}const yw=new yu;class xw extends gw{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(yw),this.setValues(e)}}const bw=new Iu;class _w extends gw{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(bw),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?Dd(this.offsetNode):t_,t=this.dashScaleNode?Dd(this.dashScaleNode):Qb,s=this.dashSizeNode?Dd(this.dashSizeNode):Kb,i=this.gapSizeNode?Dd(this.gapSizeNode):Jb;Mp.assign(s),Ap.assign(i);const r=sg(Hg("lineDistance").mul(t));(e?r.add(e):r).mod(Mp.add(Ap)).greaterThan(Mp).discard()}}let ww=null;class vw extends G_{static get type(){return"ViewportSharedTextureNode"}constructor(e=py,t=null){null===ww&&(ww=new bu),super(e,t,ww)}getTextureForReference(){return ww}updateReference(){return this}}const Tw=Td(vw).setParameterLength(0,2),Sw=new Ru;class Mw extends gw{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(Sw),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Dd(this.opacityNode):Nb;rp.assign(hg(Hd(pb(mx),e),Mo))}}const Aw=Ed(([e=sx])=>{const t=e.z.atan(e.x).mul(1/(2*Math.PI)).add(.5),s=e.y.clamp(-1,1).asin().mul(1/Math.PI).add(.5);return Vd(t,s)});class Nw extends Yh{constructor(e=1,t={}){super(e,t),this.isCubeRenderTarget=!0}fromEquirectangularTexture(e,t){const s=t.minFilter,i=t.generateMipmaps;t.generateMipmaps=!0,this.texture.type=t.type,this.texture.colorSpace=t.colorSpace,this.texture.generateMipmaps=t.generateMipmaps,this.texture.minFilter=t.minFilter,this.texture.magFilter=t.magFilter;const r=new Vh(5,5,5),n=Aw(sx),o=new gw;o.colorNode=ty(t,n,0),o.side=1,o.blending=0;const a=new Fh(r,o),l=new Jh;l.add(a),t.minFilter===_n&&(t.minFilter=xn);const h=new qh(1,10,this),u=e.getMRT();return e.setMRT(null),h.update(e,l),e.setMRT(u),t.minFilter=s,t.currentGenerateMipmaps=i,a.geometry.dispose(),a.material.dispose(),this}}const Ew=new WeakMap;class Cw extends Bc{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Dx(null);const t=new Xh;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=wc.RENDER}updateBefore(e){const{renderer:t,material:s}=e,i=this.envNode;if(i.isTextureNode||i.isMaterialReferenceNode){const e=i.isTextureNode?i.value:s[i.property];if(e&&e.isTexture){const s=e.mapping;if(303===s||304===s){if(Ew.has(e)){const t=Ew.get(e);Pw(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new Nw(s.height);i.fromEquirectangularTexture(t,e),Pw(i.texture,e.mapping),this._cubeTexture=i.texture,Ew.set(e,i.texture),e.addEventListener("dispose",Rw)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function Rw(e){const t=e.target;t.removeEventListener("dispose",Rw);const s=Ew.get(t);void 0!==s&&(Ew.delete(t),s.dispose())}function Pw(e,t){303===t?e.mapping=un:304===t&&(e.mapping=cn)}const Bw=Td(Cw).setParameterLength(1);class Iw extends F_{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Bw(this.envNode)}}class Dw extends F_{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=Dd(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Lw{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Fw extends Lw{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,s=e.reflectedLight,i=e.irradianceLightMap;s.indirectDiffuse.assign(Hd(0)),i?s.indirectDiffuse.addAssign(i):s.indirectDiffuse.addAssign(Hd(1,1,1,0)),s.indirectDiffuse.mulAssign(t),s.indirectDiffuse.mulAssign(rp.rgb)}finish(e){const{material:t,context:s}=e,i=s.outgoingLight,r=e.context.environment;if(r)switch(t.combine){case 0:i.rgb.assign(Af(i.rgb,i.rgb.mul(r.rgb),Pb.mul(Bb)));break;case 1:i.rgb.assign(Af(i.rgb,r.rgb,Pb.mul(Bb)));break;case 2:i.rgb.addAssign(r.rgb.mul(Pb.mul(Bb)));break;default:Yo("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const Ow=new rh;class Vw extends gw{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Ow),this.setValues(e)}setupNormal(){return lx(dx)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Iw(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Dw(r_)),t}setupOutgoingLight(){return rp.rgb}setupLightingModel(){return new Fw}}const zw=Ed(({f0:e,f90:t,dotVH:s})=>{const i=s.mul(-5.55473).sub(6.98316).mul(s).exp2();return e.mul(i.oneMinus()).add(t.mul(i))}),kw=Ed(e=>e.diffuseColor.mul(1/Math.PI)),Uw=Ed(({dotNH:e})=>Tp.mul(Dd(.5)).add(1).mul(Dd(1/Math.PI)).mul(e.pow(Tp))),Gw=Ed(({lightDirection:e})=>{const t=e.add(rx).normalize(),s=mx.dot(t).clamp(),i=rx.dot(t).clamp(),r=zw({f0:_p,f90:1,dotVH:i}),n=Dd(.25),o=Uw({dotNH:s});return r.mul(n).mul(o)});class jw extends Fw{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=mx.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(kw({diffuseColor:rp.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(Gw({lightDirection:e})).mul(Pb))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(kw({diffuseColor:rp}))),i.indirectDiffuse.mulAssign(t)}}const $w=new Pu;class Ww extends gw{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues($w),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Iw(t):null}setupLightingModel(){return new jw(!1)}}const Hw=new Eu;class qw extends gw{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(Hw),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Iw(t):null}setupLightingModel(){return new jw}setupVariants(){const e=(this.shininessNode?Dd(this.shininessNode):Mb).max(1e-4);Tp.assign(e);const t=this.specularNode||Eb;_p.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const Xw=Ed(e=>{if(!1===e.geometry.hasAttribute("normal"))return Dd(0);const t=dx.dFdx().abs().max(dx.dFdy().abs());return t.x.max(t.y).max(t.z)}),Yw=Ed(e=>{const{roughness:t}=e,s=Xw();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i}),Zw=Ed(({alpha:e,dotNL:t,dotNV:s})=>{const i=e.pow2(),r=t.mul(i.add(i.oneMinus().mul(s.pow2())).sqrt()),n=s.mul(i.add(i.oneMinus().mul(t.pow2())).sqrt());return Jp(.5,r.add(n).max(Tm))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),Qw=Ed(({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:o,dotNL:a})=>{const l=a.mul(Gd(e.mul(s),t.mul(i),o).length()),h=o.mul(Gd(e.mul(r),t.mul(n),a).length());return Jp(.5,l.add(h))}).setLayout({name:"V_GGX_SmithCorrelated_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotTV",type:"float",qualifier:"in"},{name:"dotBV",type:"float",qualifier:"in"},{name:"dotTL",type:"float",qualifier:"in"},{name:"dotBL",type:"float",qualifier:"in"},{name:"dotNV",type:"float",qualifier:"in"},{name:"dotNL",type:"float",qualifier:"in"}]}),Kw=Ed(({alpha:e,dotNH:t})=>{const s=e.pow2(),i=t.pow2().mul(s.oneMinus()).oneMinus();return s.div(i.pow2()).mul(1/Math.PI)}).setLayout({name:"D_GGX",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNH",type:"float"}]}),Jw=Dd(1/Math.PI),ev=Ed(({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),o=Gd(t.mul(i),e.mul(r),n.mul(s)),a=o.dot(o),l=n.div(a);return Jw.mul(n.mul(l.pow2()))}).setLayout({name:"D_GGX_Anisotropic",type:"float",inputs:[{name:"alphaT",type:"float",qualifier:"in"},{name:"alphaB",type:"float",qualifier:"in"},{name:"dotNH",type:"float",qualifier:"in"},{name:"dotTH",type:"float",qualifier:"in"},{name:"dotBH",type:"float",qualifier:"in"}]}),tv=Ed(({lightDirection:e,f0:t,f90:s,roughness:i,f:r,normalView:n=mx,USE_IRIDESCENCE:o,USE_ANISOTROPY:a})=>{const l=i.pow2(),h=e.add(rx).normalize(),u=n.dot(e).clamp(),c=n.dot(rx).clamp(),d=n.dot(h).clamp(),p=rx.dot(h).clamp();let m,f,g=zw({f0:t,f90:s,dotVH:p});if(gd(o)&&(g=pp.mix(g,r)),gd(a)){const t=xp.dot(e),s=xp.dot(rx),i=xp.dot(h),r=bp.dot(e),n=bp.dot(rx),o=bp.dot(h);m=Qw({alphaT:gp,alphaB:l,dotTV:s,dotBV:n,dotTL:t,dotBL:r,dotNV:c,dotNL:u}),f=ev({alphaT:gp,alphaB:l,dotNH:d,dotTH:i,dotBH:o})}else m=Zw({alpha:l,dotNL:u,dotNV:c}),f=Kw({alpha:l,dotNH:d});return g.mul(m).mul(f)}),sv=new Uint16Array([12469,15057,12620,14925,13266,14620,13807,14376,14323,13990,14545,13625,14713,13328,14840,12882,14931,12528,14996,12233,15039,11829,15066,11525,15080,11295,15085,10976,15082,10705,15073,10495,13880,14564,13898,14542,13977,14430,14158,14124,14393,13732,14556,13410,14702,12996,14814,12596,14891,12291,14937,11834,14957,11489,14958,11194,14943,10803,14921,10506,14893,10278,14858,9960,14484,14039,14487,14025,14499,13941,14524,13740,14574,13468,14654,13106,14743,12678,14818,12344,14867,11893,14889,11509,14893,11180,14881,10751,14852,10428,14812,10128,14765,9754,14712,9466,14764,13480,14764,13475,14766,13440,14766,13347,14769,13070,14786,12713,14816,12387,14844,11957,14860,11549,14868,11215,14855,10751,14825,10403,14782,10044,14729,9651,14666,9352,14599,9029,14967,12835,14966,12831,14963,12804,14954,12723,14936,12564,14917,12347,14900,11958,14886,11569,14878,11247,14859,10765,14828,10401,14784,10011,14727,9600,14660,9289,14586,8893,14508,8533,15111,12234,15110,12234,15104,12216,15092,12156,15067,12010,15028,11776,14981,11500,14942,11205,14902,10752,14861,10393,14812,9991,14752,9570,14682,9252,14603,8808,14519,8445,14431,8145,15209,11449,15208,11451,15202,11451,15190,11438,15163,11384,15117,11274,15055,10979,14994,10648,14932,10343,14871,9936,14803,9532,14729,9218,14645,8742,14556,8381,14461,8020,14365,7603,15273,10603,15272,10607,15267,10619,15256,10631,15231,10614,15182,10535,15118,10389,15042,10167,14963,9787,14883,9447,14800,9115,14710,8665,14615,8318,14514,7911,14411,7507,14279,7198,15314,9675,15313,9683,15309,9712,15298,9759,15277,9797,15229,9773,15166,9668,15084,9487,14995,9274,14898,8910,14800,8539,14697,8234,14590,7790,14479,7409,14367,7067,14178,6621,15337,8619,15337,8631,15333,8677,15325,8769,15305,8871,15264,8940,15202,8909,15119,8775,15022,8565,14916,8328,14804,8009,14688,7614,14569,7287,14448,6888,14321,6483,14088,6171,15350,7402,15350,7419,15347,7480,15340,7613,15322,7804,15287,7973,15229,8057,15148,8012,15046,7846,14933,7611,14810,7357,14682,7069,14552,6656,14421,6316,14251,5948,14007,5528,15356,5942,15356,5977,15353,6119,15348,6294,15332,6551,15302,6824,15249,7044,15171,7122,15070,7050,14949,6861,14818,6611,14679,6349,14538,6067,14398,5651,14189,5311,13935,4958,15359,4123,15359,4153,15356,4296,15353,4646,15338,5160,15311,5508,15263,5829,15188,6042,15088,6094,14966,6001,14826,5796,14678,5543,14527,5287,14377,4985,14133,4586,13869,4257,15360,1563,15360,1642,15358,2076,15354,2636,15341,3350,15317,4019,15273,4429,15203,4732,15105,4911,14981,4932,14836,4818,14679,4621,14517,4386,14359,4156,14083,3795,13808,3437,15360,122,15360,137,15358,285,15355,636,15344,1274,15322,2177,15281,2765,15215,3223,15120,3451,14995,3569,14846,3567,14681,3466,14511,3305,14344,3121,14037,2800,13753,2467,15360,0,15360,1,15359,21,15355,89,15346,253,15325,479,15287,796,15225,1148,15133,1492,15008,1749,14856,1882,14685,1886,14506,1783,14324,1608,13996,1398,13702,1183]);let iv=null;const rv=Ed(({roughness:e,dotNV:t})=>{null===iv&&(iv=new ru(sv,16,16,kn,En),iv.name="DFG_LUT",iv.minFilter=xn,iv.magFilter=xn,iv.wrapS=pn,iv.wrapT=pn,iv.generateMipmaps=!1,iv.needsUpdate=!0);const s=Vd(e,t);return ty(iv,s).rg}),nv=Ed(({lightDirection:e,f0:t,f90:s,roughness:i,f:r,USE_IRIDESCENCE:n,USE_ANISOTROPY:o})=>{const a=tv({lightDirection:e,f0:t,f90:s,roughness:i,f:r,USE_IRIDESCENCE:n,USE_ANISOTROPY:o}),l=mx.dot(e).clamp(),h=mx.dot(rx).clamp(),u=rv({roughness:i,dotNV:h}),c=rv({roughness:i,dotNV:l}),d=t.mul(u.x).add(s.mul(u.y)),p=t.mul(c.x).add(s.mul(c.y)),m=u.x.add(u.y),f=c.x.add(c.y),g=Dd(1).sub(m),y=Dd(1).sub(f),x=t.add(t.oneMinus().mul(.047619)),b=d.mul(p).mul(x).div(Dd(1).sub(g.mul(y).mul(x).mul(x)).add(Tm)),_=g.mul(y),w=b.mul(_);return a.add(w)}),ov=Ed(e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=rv({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))}),av=Ed(({f:e,f90:t,dotVH:s})=>{const i=s.oneMinus().saturate(),r=i.mul(i),n=i.mul(r,r).clamp(0,.9999);return e.sub(Gd(t).mul(n)).div(n.oneMinus())}).setLayout({name:"Schlick_to_F0",type:"vec3",inputs:[{name:"f",type:"vec3"},{name:"f90",type:"float"},{name:"dotVH",type:"float"}]}),lv=Ed(({roughness:e,dotNH:t})=>{const s=e.pow2(),i=Dd(1).div(s),r=t.pow2().oneMinus().max(.0078125);return Dd(2).add(i).mul(r.pow(i.mul(.5))).div(2*Math.PI)}).setLayout({name:"D_Charlie",type:"float",inputs:[{name:"roughness",type:"float"},{name:"dotNH",type:"float"}]}),hv=Ed(({dotNV:e,dotNL:t})=>Dd(1).div(Dd(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),uv=Ed(({lightDirection:e})=>{const t=e.add(rx).normalize(),s=mx.dot(e).clamp(),i=mx.dot(rx).clamp(),r=mx.dot(t).clamp(),n=lv({roughness:dp,dotNH:r}),o=hv({dotNV:i,dotNL:s});return cp.mul(n).mul(o)}),cv=Ed(({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=Vd(s,i.oneMinus().sqrt());return r.assign(r.mul(.984375).add(.0078125)),r}).setLayout({name:"LTC_Uv",type:"vec2",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"roughness",type:"float"}]}),dv=Ed(({f:e})=>{const t=e.length();return df(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),pv=Ed(({v1:e,v2:t})=>{const s=e.dot(t),i=s.abs().toVar(),r=i.mul(.0145206).add(.4965155).mul(i).add(.8543985).toVar(),n=i.add(4.1616724).mul(i).add(3.417594).toVar(),o=r.div(n),a=s.greaterThan(0).select(o,df(s.mul(s).oneMinus(),1e-7).inverseSqrt().mul(.5).sub(o));return e.cross(t).mul(a)}).setLayout({name:"LTC_EdgeVectorFormFactor",type:"vec3",inputs:[{name:"v1",type:"vec3"},{name:"v2",type:"vec3"}]}),mv=Ed(({N:e,V:t,P:s,mInv:i,p0:r,p1:n,p2:o,p3:a})=>{const l=n.sub(r).toVar(),h=a.sub(r).toVar(),u=l.cross(h),c=Gd().toVar();return Pd(u.dot(s.sub(r)).greaterThanEqual(0),()=>{const l=t.sub(e.mul(t.dot(e))).normalize(),h=e.cross(l).negate(),u=i.mul(Qd(l,h,e).transpose()).toVar(),d=u.mul(r.sub(s)).normalize().toVar(),p=u.mul(n.sub(s)).normalize().toVar(),m=u.mul(o.sub(s)).normalize().toVar(),f=u.mul(a.sub(s)).normalize().toVar(),g=Gd(0).toVar();g.addAssign(pv({v1:d,v2:p})),g.addAssign(pv({v1:p,v2:m})),g.addAssign(pv({v1:m,v2:f})),g.addAssign(pv({v1:f,v2:d})),c.assign(Gd(dv({f:g})))}),c}).setLayout({name:"LTC_Evaluate",type:"vec3",inputs:[{name:"N",type:"vec3"},{name:"V",type:"vec3"},{name:"P",type:"vec3"},{name:"mInv",type:"mat3"},{name:"p0",type:"vec3"},{name:"p1",type:"vec3"},{name:"p2",type:"vec3"},{name:"p3",type:"vec3"}]}),fv=1/6,gv=e=>Kp(fv,Kp(e,Kp(e,e.negate().add(3)).sub(3)).add(1)),yv=e=>Kp(fv,Kp(e,Kp(e,Kp(3,e).sub(6))).add(4)),xv=e=>Kp(fv,Kp(e,Kp(e,Kp(-3,e).add(3)).add(3)).add(1)),bv=e=>Kp(fv,bf(e,3)),_v=e=>gv(e).add(yv(e)),wv=e=>xv(e).add(bv(e)),vv=e=>Zp(-1,yv(e).div(gv(e).add(yv(e)))),Tv=e=>Zp(1,bv(e).div(xv(e).add(bv(e)))),Sv=(e,t,s)=>{const i=e.uvNode,r=Kp(i,t.zw).add(.5),n=zm(r),o=Gm(r),a=_v(o.x),l=wv(o.x),h=vv(o.x),u=Tv(o.x),c=vv(o.y),d=Tv(o.y),p=Vd(n.x.add(h),n.y.add(c)).sub(.5).mul(t.xy),m=Vd(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),f=Vd(n.x.add(h),n.y.add(d)).sub(.5).mul(t.xy),g=Vd(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),y=_v(o.y).mul(Zp(a.mul(e.sample(p).level(s)),l.mul(e.sample(m).level(s)))),x=wv(o.y).mul(Zp(a.mul(e.sample(f).level(s)),l.mul(e.sample(g).level(s))));return y.add(x)},Mv=Ed(([e,t])=>{const s=Vd(e.size(Ld(t))),i=Vd(e.size(Ld(t.add(1)))),r=Jp(1,s),n=Jp(1,i),o=Sv(e,Hd(r,s),zm(t)),a=Sv(e,Hd(n,i),km(t));return Gm(t).mix(o,a)}),Av=Ed(([e,t])=>{const s=t.mul(Qg(e));return Mv(e,s)}),Nv=Ed(([e,t,s,i,r])=>{const n=Gd(Cf(t.negate(),Um(e),Jp(1,i))),o=Gd(Qm(r[0].xyz),Qm(r[1].xyz),Qm(r[2].xyz));return Um(n).mul(s.mul(o))}).setLayout({name:"getVolumeTransmissionRay",type:"vec3",inputs:[{name:"n",type:"vec3"},{name:"v",type:"vec3"},{name:"thickness",type:"float"},{name:"ior",type:"float"},{name:"modelMatrix",type:"mat4"}]}),Ev=Ed(([e,t])=>e.mul(Nf(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),Cv=$_(),Rv=$_(),Pv=Ed(([e,t,s],{material:i})=>{const r=(1===i.side?Cv:Rv).sample(e),n=Fm(my.x).mul(Ev(t,s));return Mv(r,n)}),Bv=Ed(([e,t,s])=>(Pd(s.notEqual(0),()=>{const i=Lm(t).negate().div(s);return Im(i.negate().mul(e))}),Gd(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),Iv=Ed(([e,t,s,i,r,n,o,a,l,h,u,c,d,p,m])=>{let f,g;if(m){f=Hd().toVar(),g=Gd().toVar();const r=u.sub(1).mul(m.mul(.025)),n=Gd(u.sub(r),u,u.add(r));C_({start:0,end:3},({i:r})=>{const u=n.element(r),m=Nv(e,t,c,u,a),y=o.add(m),x=h.mul(l.mul(Hd(y,1))),b=Vd(x.xy.div(x.w)).toVar();b.addAssign(1),b.divAssign(2),b.assign(Vd(b.x,b.y.oneMinus()));const _=Pv(b,s,u);f.element(r).assign(_.element(r)),f.a.addAssign(_.a),g.element(r).assign(i.element(r).mul(Bv(Qm(m),d,p).element(r)))}),f.a.divAssign(3)}else{const r=Nv(e,t,c,u,a),n=o.add(r),m=h.mul(l.mul(Hd(n,1))),y=Vd(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Vd(y.x,y.y.oneMinus())),f=Pv(y,s,u),g=i.mul(Bv(Qm(r),d,p))}const y=g.rgb.mul(f.rgb),x=e.dot(t).clamp(),b=Gd(ov({dotNV:x,specularColor:r,specularF90:n,roughness:s})),_=g.r.add(g.g,g.b).div(3);return Hd(b.oneMinus().mul(y),f.a.oneMinus().mul(_).oneMinus())}),Dv=Qd(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),Lv=(e,t)=>e.sub(t).div(e.add(t)).pow2(),Fv=Ed(({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=Af(e,t,Rf(0,.03,i)),o=e.div(n).pow2().mul(s.pow2().oneMinus()).oneMinus();Pd(o.lessThan(0),()=>Gd(1));const a=o.sqrt(),l=Lv(n,e),h=zw({f0:l,f90:1,dotVH:s}),u=h.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=Dd(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return Gd(1).add(t).div(Gd(1).sub(t))})(r.clamp(0,.9999)),m=Lv(p,n.toVec3()),f=zw({f0:m,f90:1,dotVH:a}),g=Gd(p.x.lessThan(n).select(Math.PI,0),p.y.lessThan(n).select(Math.PI,0),p.z.lessThan(n).select(Math.PI,0)),y=n.mul(i,a,2),x=Gd(d).add(g),b=h.mul(f).clamp(1e-5,.9999),_=b.sqrt(),w=u.pow2().mul(f).div(Gd(1).sub(b)),v=h.add(w).toVar(),T=w.sub(u).toVar();return C_({start:1,end:2,condition:"<=",name:"m"},({m:e})=>{T.mulAssign(_);const t=((e,t)=>{const s=e.mul(2*Math.PI*1e-9),i=Gd(54856e-17,44201e-17,52481e-17),r=Gd(1681e3,1795300,2208400),n=Gd(43278e5,93046e5,66121e5),o=Dd(9747e-17*Math.sqrt(2*Math.PI*45282e5)).mul(s.mul(2239900).add(t.x).cos()).mul(s.pow2().mul(-45282e5).exp());let a=i.mul(n.mul(2*Math.PI).sqrt()).mul(r.mul(s).add(t).cos()).mul(s.pow2().negate().mul(n).exp());return a=Gd(a.x.add(o),a.y,a.z).div(1.0685e-7),Dv.mul(a)})(Dd(e).mul(y),Dd(e).mul(x)).mul(2);v.addAssign(T.mul(t))}),v.max(Gd(0))}).setLayout({name:"evalIridescence",type:"vec3",inputs:[{name:"outsideIOR",type:"float"},{name:"eta2",type:"float"},{name:"cosTheta1",type:"float"},{name:"thinFilmThickness",type:"float"},{name:"baseF0",type:"vec3"}]}),Ov=Ed(({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.mul(s),n=s.add(.1).reciprocal(),o=Dd(-1.9362).add(s.mul(1.0678)).add(r.mul(.4573)).sub(n.mul(.8469)),a=Dd(-.6014).add(s.mul(.5538)).sub(r.mul(.467)).sub(n.mul(.1255));return o.mul(i).add(a).exp().saturate()}),Vv=Gd(.04),zv=Dd(1);class kv extends Lw{constructor(e=!1,t=!1,s=!1,i=!1,r=!1,n=!1){super(),this.clearcoat=e,this.sheen=t,this.iridescence=s,this.anisotropy=i,this.transmission=r,this.dispersion=n,this.clearcoatRadiance=null,this.clearcoatSpecularDirect=null,this.clearcoatSpecularIndirect=null,this.sheenSpecularDirect=null,this.sheenSpecularIndirect=null,this.iridescenceFresnel=null,this.iridescenceF0=null,this.iridescenceF0Dielectric=null,this.iridescenceF0Metallic=null}start(e){if(!0===this.clearcoat&&(this.clearcoatRadiance=Gd().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Gd().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Gd().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Gd().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Gd().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=mx.dot(rx).clamp(),t=Fv({outsideIOR:Dd(1),eta2:mp,cosTheta1:e,thinFilmThickness:fp,baseF0:_p}),s=Fv({outsideIOR:Dd(1),eta2:mp,cosTheta1:e,thinFilmThickness:fp,baseF0:rp.rgb});this.iridescenceFresnel=Af(t,s,lp),this.iridescenceF0Dielectric=av({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=av({f:s,f90:1,dotVH:e}),this.iridescenceF0=Af(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,lp)}if(!0===this.transmission){const t=tx,s=Cy.sub(tx).normalize(),i=fx,r=e.context;r.backdrop=Iv(i,s,ap,np,wp,vp,t,Uy,Ay,Sy,Ep,Rp,Bp,Pp,this.dispersion?Ip:null),r.backdropAlpha=Cp,rp.a.mulAssign(Af(1,r.backdrop.a,Cp))}super.start(e)}computeMultiscattering(e,t,s,i,r=null){const n=mx.dot(rx).clamp(),o=rv({roughness:ap,dotNV:n}),a=r?pp.mix(i,r):i,l=a.mul(o.x).add(s.mul(o.y)),h=o.x.add(o.y).oneMinus(),u=a.add(a.oneMinus().mul(.047619)),c=l.mul(u).div(h.mul(u).oneMinus());e.addAssign(l),t.addAssign(c.mul(h))}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=mx.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(i.mul(uv({lightDirection:e})));const t=Ov({normal:mx,viewDir:rx,roughness:dp}),s=Ov({normal:mx,viewDir:e,roughness:dp}),r=cp.r.max(cp.g).max(cp.b).mul(t.max(s)).oneMinus();i.mulAssign(r)}if(!0===this.clearcoat){const s=gx.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(tv({lightDirection:e,f0:Vv,f90:zv,roughness:up,normalView:gx})))}s.directDiffuse.addAssign(i.mul(kw({diffuseColor:np}))),s.directSpecular.addAssign(i.mul(nv({lightDirection:e,f0:wp,f90:1,roughness:ap,f:this.iridescenceFresnel,USE_IRIDESCENCE:this.iridescence,USE_ANISOTROPY:this.anisotropy})))}directRectArea({lightColor:e,lightPosition:t,halfWidth:s,halfHeight:i,reflectedLight:r,ltc_1:n,ltc_2:o}){const a=t.add(s).sub(i),l=t.sub(s).sub(i),h=t.sub(s).add(i),u=t.add(s).add(i),c=mx,d=rx,p=ix.toVar(),m=cv({N:c,V:d,roughness:ap}),f=n.sample(m).toVar(),g=o.sample(m).toVar(),y=Qd(Gd(f.x,0,f.y),Gd(0,1,0),Gd(f.z,0,f.w)).toVar(),x=wp.mul(g.x).add(wp.oneMinus().mul(g.y)).toVar();r.directSpecular.addAssign(e.mul(x).mul(mv({N:c,V:d,P:p,mInv:y,p0:a,p1:l,p2:h,p3:u}))),r.directDiffuse.addAssign(e.mul(np).mul(mv({N:c,V:d,P:p,mInv:Qd(1,0,0,0,1,0,0,0,1),p0:a,p1:l,p2:h,p3:u})))}indirect(e){this.indirectDiffuse(e),this.indirectSpecular(e),this.ambientOcclusion(e)}indirectDiffuse(e){const{irradiance:t,reflectedLight:s}=e.context,i=t.mul(kw({diffuseColor:np})).toVar();if(!0===this.sheen){const e=Ov({normal:mx,viewDir:rx,roughness:dp}),t=cp.r.max(cp.g).max(cp.b).mul(e).oneMinus();i.mulAssign(t)}s.indirectDiffuse.addAssign(i)}indirectSpecular(e){const{radiance:t,iblIrradiance:s,reflectedLight:i}=e.context;if(!0===this.sheen&&this.sheenSpecularIndirect.addAssign(s.mul(cp,Ov({normal:mx,viewDir:rx,roughness:dp}))),!0===this.clearcoat){const e=gx.dot(rx).clamp(),t=ov({dotNV:e,specularColor:Vv,specularF90:zv,roughness:up});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=Gd().toVar("singleScatteringDielectric"),n=Gd().toVar("multiScatteringDielectric"),o=Gd().toVar("singleScatteringMetallic"),a=Gd().toVar("multiScatteringMetallic");this.computeMultiscattering(r,n,vp,_p,this.iridescenceF0Dielectric),this.computeMultiscattering(o,a,vp,rp.rgb,this.iridescenceF0Metallic);const l=Af(r,o,lp),h=Af(n,a,lp),u=r.add(n),c=np.mul(u.oneMinus()),d=s.mul(1/Math.PI),p=t.mul(l).add(h.mul(d)).toVar(),m=c.mul(d).toVar();if(!0===this.sheen){const e=Ov({normal:mx,viewDir:rx,roughness:dp}),t=cp.r.max(cp.g).max(cp.b).mul(e).oneMinus();p.mulAssign(t),m.mulAssign(t)}i.indirectSpecular.addAssign(p),i.indirectDiffuse.addAssign(m)}ambientOcclusion(e){const{ambientOcclusion:t,reflectedLight:s}=e.context,i=mx.dot(rx).clamp().add(t),r=ap.mul(-16).oneMinus().negate().exp2(),n=t.sub(i.pow(r).oneMinus()).clamp();!0===this.clearcoat&&this.clearcoatSpecularIndirect.mulAssign(t),!0===this.sheen&&this.sheenSpecularIndirect.mulAssign(t),s.indirectDiffuse.mulAssign(t),s.indirectSpecular.mulAssign(n)}finish({context:e}){const{outgoingLight:t}=e;if(!0===this.clearcoat){const e=gx.dot(rx).clamp(),s=zw({dotVH:e,f0:Vv,f90:zv}),i=t.mul(hp.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(hp));t.assign(i)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const Uv=Dd(1),Gv=Dd(-2),jv=Dd(.8),$v=Dd(-1),Wv=Dd(.4),Hv=Dd(2),qv=Dd(.305),Xv=Dd(3),Yv=Dd(.21),Zv=Dd(4),Qv=Dd(4),Kv=Dd(16),Jv=Ed(([e])=>{const t=Gd(Ym(e)).toVar(),s=Dd(-1).toVar();return Pd(t.x.greaterThan(t.z),()=>{Pd(t.x.greaterThan(t.y),()=>{s.assign(kf(e.x.greaterThan(0),0,3))}).Else(()=>{s.assign(kf(e.y.greaterThan(0),1,4))})}).Else(()=>{Pd(t.z.greaterThan(t.y),()=>{s.assign(kf(e.z.greaterThan(0),2,5))}).Else(()=>{s.assign(kf(e.y.greaterThan(0),1,4))})}),s}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),eT=Ed(([e,t])=>{const s=Vd().toVar();return Pd(t.equal(0),()=>{s.assign(Vd(e.z,e.y).div(Ym(e.x)))}).ElseIf(t.equal(1),()=>{s.assign(Vd(e.x.negate(),e.z.negate()).div(Ym(e.y)))}).ElseIf(t.equal(2),()=>{s.assign(Vd(e.x.negate(),e.y).div(Ym(e.z)))}).ElseIf(t.equal(3),()=>{s.assign(Vd(e.z.negate(),e.y).div(Ym(e.x)))}).ElseIf(t.equal(4),()=>{s.assign(Vd(e.x.negate(),e.z).div(Ym(e.y)))}).Else(()=>{s.assign(Vd(e.x,e.y).div(Ym(e.z)))}),Kp(.5,s.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),tT=Ed(([e])=>{const t=Dd(0).toVar();return Pd(e.greaterThanEqual(jv),()=>{t.assign(Uv.sub(e).mul($v.sub(Gv)).div(Uv.sub(jv)).add(Gv))}).ElseIf(e.greaterThanEqual(Wv),()=>{t.assign(jv.sub(e).mul(Hv.sub($v)).div(jv.sub(Wv)).add($v))}).ElseIf(e.greaterThanEqual(qv),()=>{t.assign(Wv.sub(e).mul(Xv.sub(Hv)).div(Wv.sub(qv)).add(Hv))}).ElseIf(e.greaterThanEqual(Yv),()=>{t.assign(qv.sub(e).mul(Zv.sub(Xv)).div(qv.sub(Yv)).add(Xv))}).Else(()=>{t.assign(Dd(-2).mul(Fm(Kp(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),sT=Ed(([e,t])=>{const s=e.toVar();s.assign(Kp(2,s).sub(1));const i=Gd(s,1).toVar();return Pd(t.equal(0),()=>{i.assign(i.zyx)}).ElseIf(t.equal(1),()=>{i.assign(i.xzy),i.xz.mulAssign(-1)}).ElseIf(t.equal(2),()=>{i.x.mulAssign(-1)}).ElseIf(t.equal(3),()=>{i.assign(i.zyx),i.xz.mulAssign(-1)}).ElseIf(t.equal(4),()=>{i.assign(i.xzy),i.xy.mulAssign(-1)}).ElseIf(t.equal(5),()=>{i.z.mulAssign(-1)}),i}).setLayout({name:"getDirection",type:"vec3",inputs:[{name:"uv",type:"vec2"},{name:"face",type:"float"}]}),iT=Ed(([e,t,s,i,r,n])=>{const o=Dd(s),a=Gd(t),l=Nf(tT(o),Gv,n),h=Gm(l),u=zm(l),c=Gd(rT(e,a,u,i,r,n)).toVar();return Pd(h.notEqual(0),()=>{const t=Gd(rT(e,a,u.add(1),i,r,n)).toVar();c.assign(Af(c,t,h))}),c}),rT=Ed(([e,t,s,i,r,n])=>{const o=Dd(s).toVar(),a=Gd(t),l=Dd(Jv(a)).toVar(),h=Dd(df(Qv.sub(o),0)).toVar();o.assign(df(o,Qv));const u=Dd(Dm(o)).toVar(),c=Vd(eT(a,l).mul(u.sub(2)).add(1)).toVar();return Pd(l.greaterThan(2),()=>{c.y.addAssign(u),l.subAssign(3)}),c.x.addAssign(l.mul(u)),c.x.addAssign(h.mul(Kp(3,Kv))),c.y.addAssign(Kp(4,Dm(n).sub(u))),c.x.mulAssign(i),c.y.mulAssign(r),e.sample(c).grad(Vd(),Vd())}),nT=Ed(({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const l=$m(i),h=s.mul(l).add(r.cross(s).mul(jm(i))).add(r.mul(r.dot(s).mul(l.oneMinus())));return rT(e,h,t,n,o,a)}),oT=Ed(({n:e,latitudinal:t,poleAxis:s,outputDirection:i,weights:r,samples:n,dTheta:o,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})=>{const d=Gd(kf(t,s,xf(s,i))).toVar();Pd(d.equal(Gd(0)),()=>{d.assign(Gd(i.z,0,i.x.negate()))}),d.assign(Um(d));const p=Gd().toVar();return p.addAssign(r.element(0).mul(nT({theta:0,axis:d,outputDirection:i,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),C_({start:Ld(1),end:e},({i:e})=>{Pd(e.greaterThanEqual(n),()=>{R_()});const t=Dd(o.mul(Dd(e))).toVar();p.addAssign(r.element(e).mul(nT({theta:t.mul(-1),axis:d,outputDirection:i,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),p.addAssign(r.element(e).mul(nT({theta:t,axis:d,outputDirection:i,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})))}),Hd(p,1)}),aT=Ed(([e])=>{const t=Fd(e).toVar();return t.assign(t.shiftLeft(Fd(16)).bitOr(t.shiftRight(Fd(16)))),t.assign(t.bitAnd(Fd(1431655765)).shiftLeft(Fd(1)).bitOr(t.bitAnd(Fd(2863311530)).shiftRight(Fd(1)))),t.assign(t.bitAnd(Fd(858993459)).shiftLeft(Fd(2)).bitOr(t.bitAnd(Fd(3435973836)).shiftRight(Fd(2)))),t.assign(t.bitAnd(Fd(252645135)).shiftLeft(Fd(4)).bitOr(t.bitAnd(Fd(4042322160)).shiftRight(Fd(4)))),t.assign(t.bitAnd(Fd(16711935)).shiftLeft(Fd(8)).bitOr(t.bitAnd(Fd(4278255360)).shiftRight(Fd(8)))),Dd(t).mul(2.3283064365386963e-10)}),lT=Ed(([e,t])=>Vd(Dd(e).div(Dd(t)),aT(e))),hT=Ed(([e,t,s])=>{const i=Gd(t).toVar(),r=Dd(s),n=r.mul(r).toVar(),o=Um(Gd(n.mul(i.x),n.mul(i.y),i.z)).toVar(),a=o.x.mul(o.x).add(o.y.mul(o.y)),l=kf(a.greaterThan(0),Gd(o.y.negate(),o.x,0).div(Om(a)),Gd(1,0,0)).toVar(),h=xf(o,l).toVar(),u=Om(e.x),c=Kp(2,3.14159265359).mul(e.y),d=u.mul($m(c)).toVar(),p=u.mul(jm(c)).toVar(),m=Kp(.5,o.z.add(1));p.assign(m.oneMinus().mul(Om(d.mul(d).oneMinus())).add(m.mul(p)));const f=l.mul(d).add(h.mul(p)).add(o.mul(Om(df(0,d.mul(d).add(p.mul(p)).oneMinus()))));return Um(Gd(n.mul(f.x),n.mul(f.y),df(0,f.z)))}),uT=Ed(({roughness:e,mipInt:t,envMap:s,N_immutable:i,GGX_SAMPLES:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const l=Gd(i).toVar(),h=Gd(0).toVar(),u=Dd(0).toVar();return Pd(e.lessThan(.001),()=>{h.assign(rT(s,l,t,n,o,a))}).Else(()=>{const i=kf(Ym(l.z).lessThan(.999),Gd(0,0,1),Gd(1,0,0)),c=Um(xf(i,l)).toVar(),d=xf(l,c).toVar();C_({start:Fd(0),end:r},({i:i})=>{const p=lT(i,r),m=hT(p,Gd(0,0,1),e),f=Um(c.mul(m.x).add(d.mul(m.y)).add(l.mul(m.z))),g=Um(f.mul(yf(l,f).mul(2)).sub(l)),y=df(yf(l,g),0);Pd(y.greaterThan(0),()=>{const e=rT(s,g,t,n,o,a);h.addAssign(e.mul(y)),u.addAssign(y)})}),Pd(u.greaterThan(0),()=>{h.assign(h.div(u))})}),Hd(h,1)}),cT=[.125,.215,.35,.446,.526,.582],dT=20,pT=new $u(-1,1,1,-1,0,1),mT=new Wh(90,1),fT=new eh;let gT=null,yT=0,xT=0;const bT=new da,_T=new WeakMap,wT=[3,1,5,0,4,2],vT=sT(qg(),Hg("faceIndex")).normalize(),TT=Gd(vT.x,vT.y,vT.z);class ST{constructor(e){this._renderer=e,this._pingPongRenderTarget=null,this._lodMax=0,this._cubeSize=0,this._sizeLods=[],this._sigmas=[],this._lodMeshes=[],this._blurMaterial=null,this._ggxMaterial=null,this._cubemapMaterial=null,this._equirectMaterial=null,this._backgroundBox=null}get _hasInitialized(){return this._renderer.hasInitialized()}fromScene(e,t=0,s=.1,i=100,r={}){const{size:n=256,position:o=bT,renderTarget:a=null}=r;if(this._setSize(n),!1===this._hasInitialized){Yo('PMREMGenerator: ".fromScene()" called before the backend is initialized. Try using "await renderer.init()" instead.');const n=a||this._allocateTarget();return r.renderTarget=n,this.fromSceneAsync(e,t,s,i,r),n}gT=this._renderer.getRenderTarget(),yT=this._renderer.getActiveCubeFace(),xT=this._renderer.getActiveMipmapLevel();const l=a||this._allocateTarget();return l.depthBuffer=!0,this._init(l),this._sceneToCubeUV(e,s,i,l,o),t>0&&this._blur(l,0,0,t),this._applyPMREM(l),this._cleanup(l),l}async fromSceneAsync(e,t=0,s=.1,i=100,r={}){return Qo('PMREMGenerator: ".fromSceneAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this.fromScene(e,t,s,i,r)}fromEquirectangular(e,t=null){if(!1===this._hasInitialized){Yo('PMREMGenerator: .fromEquirectangular() called before the backend is initialized. Try using "await renderer.init()" instead.'),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromEquirectangularAsync(e,s),s}return this._fromTexture(e,t)}async fromEquirectangularAsync(e,t=null){return Qo('PMREMGenerator: ".fromEquirectangularAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}fromCubemap(e,t=null){if(!1===this._hasInitialized){Yo("PMREMGenerator: .fromCubemap() called before the backend is initialized. Try using .fromCubemapAsync() instead."),this._setSizeFromTexture(e);const s=t||this._allocateTarget();return this.fromCubemapAsync(e,t),s}return this._fromTexture(e,t)}async fromCubemapAsync(e,t=null){return Qo('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=ET(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=CT(),await this._compileMaterial(this._equirectMaterial))}dispose(){this._dispose(),null!==this._cubemapMaterial&&this._cubemapMaterial.dispose(),null!==this._equirectMaterial&&this._equirectMaterial.dispose(),null!==this._backgroundBox&&(this._backgroundBox.geometry.dispose(),this._backgroundBox.material.dispose())}_setSizeFromTexture(e){e.mapping===un||e.mapping===cn?this._setSize(0===e.image.length?16:e.image[0].width||e.image[0].image.width):this._setSize(e.image.width/4)}_setSize(e){this._lodMax=Math.floor(Math.log2(e)),this._cubeSize=Math.pow(2,this._lodMax)}_dispose(){null!==this._blurMaterial&&this._blurMaterial.dispose(),null!==this._ggxMaterial&&this._ggxMaterial.dispose(),null!==this._pingPongRenderTarget&&this._pingPongRenderTarget.dispose();for(let e=0;e<this._lodMeshes.length;e++)this._lodMeshes[e].geometry.dispose()}_cleanup(e){this._renderer.setRenderTarget(gT,yT,xT),e.scissorTest=!1,AT(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),gT=this._renderer.getRenderTarget(),yT=this._renderer.getActiveCubeFace(),xT=this._renderer.getActiveMipmapLevel();const s=t||this._allocateTarget();return this._init(s),this._textureToCubeUV(e,s),this._applyPMREM(s),this._cleanup(s),s}_allocateTarget(){return MT(3*Math.max(this._cubeSize,112),4*this._cubeSize)}_init(e){if(null===this._pingPongRenderTarget||this._pingPongRenderTarget.width!==e.width||this._pingPongRenderTarget.height!==e.height){null!==this._pingPongRenderTarget&&this._dispose(),this._pingPongRenderTarget=MT(e.width,e.height);const{_lodMax:t}=this;({lodMeshes:this._lodMeshes,sizeLods:this._sizeLods,sigmas:this._sigmas}=function(e){const t=[],s=[],i=[];let r=e;const n=e-4+1+cT.length;for(let o=0;o<n;o++){const n=Math.pow(2,r);t.push(n);let a=1/n;o>e-4?a=cT[o-e+4-1]:0===o&&(a=0),s.push(a);const l=1/(n-2),h=-l,u=1+l,c=[h,h,u,h,u,u,h,h,u,u,h,u],d=6,p=6,m=3,f=2,g=1,y=new Float32Array(m*p*d),x=new Float32Array(f*p*d),b=new Float32Array(g*p*d);for(let e=0;e<d;e++){const t=e%3*2/3-1,s=e>2?0:-1,i=[t,s,0,t+2/3,s,0,t+2/3,s+1,0,t,s,0,t+2/3,s+1,0,t,s+1,0],r=wT[e];y.set(i,m*p*r),x.set(c,f*p*r);const n=[r,r,r,r,r,r];b.set(n,g*p*r)}const _=new Sh;_.setAttribute("position",new dh(y,m)),_.setAttribute("uv",new dh(x,f)),_.setAttribute("faceIndex",new dh(b,g)),i.push(new Fh(_,null)),r>4&&r--}return{lodMeshes:i,sizeLods:t,sigmas:s}}(t)),this._blurMaterial=function(e,t,s){const i=ay(new Array(dT).fill(0)),r=Up(new da(0,1,0)),n=Up(0),o=Dd(dT),a=Up(0),l=Up(1),h=ty(),u=Up(0),c=Dd(1/t),d=Dd(1/s),p=Dd(e),m={n:o,latitudinal:a,weights:i,poleAxis:r,outputDirection:TT,dTheta:n,samples:l,envMap:h,mipInt:u,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},f=NT("blur");return f.fragmentNode=oT({...m,latitudinal:a.equal(1)}),_T.set(f,m),f}(t,e.width,e.height),this._ggxMaterial=function(e,t,s){const i=ty(),r=Up(0),n=Up(0),o=Dd(1/t),a=Dd(1/s),l=Dd(e),h={envMap:i,roughness:r,mipInt:n,CUBEUV_TEXEL_WIDTH:o,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:l},u=NT("ggx");return u.fragmentNode=uT({...h,N_immutable:TT,GGX_SAMPLES:Fd(512)}),_T.set(u,h),u}(t,e.width,e.height)}}async _compileMaterial(e){const t=new Fh(new Sh,e);await this._renderer.compile(t,pT)}_sceneToCubeUV(e,t,s,i,r){const n=mT;n.near=t,n.far=s;const o=[1,1,1,1,-1,1],a=[1,-1,1,-1,1,-1],l=this._renderer,h=l.autoClear;l.getClearColor(fT),l.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new Fh(new Vh,new rh({name:"PMREM.Background",side:1,depthWrite:!1,depthTest:!1})));const u=this._backgroundBox,c=u.material;let d=!1;const p=e.background;p?p.isColor&&(c.color.copy(p),e.background=null,d=!0):(c.color.copy(fT),d=!0),l.setRenderTarget(i),l.clear(),d&&l.render(u,n);for(let t=0;t<6;t++){const s=t%3;0===s?(n.up.set(0,o[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x+a[t],r.y,r.z)):1===s?(n.up.set(0,0,o[t]),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y+a[t],r.z)):(n.up.set(0,o[t],0),n.position.set(r.x,r.y,r.z),n.lookAt(r.x,r.y,r.z+a[t]));const h=this._cubeSize;AT(i,s*h,t>2?h:0,h,h),l.render(e,n)}l.autoClear=h,e.background=p}_textureToCubeUV(e,t){const s=this._renderer,i=e.mapping===un||e.mapping===cn;i?null===this._cubemapMaterial&&(this._cubemapMaterial=ET(e)):null===this._equirectMaterial&&(this._equirectMaterial=CT(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const o=this._cubeSize;AT(t,0,0,3*o,2*o),s.setRenderTarget(t),s.render(n,pT)}_applyPMREM(e){const t=this._renderer,s=t.autoClear;t.autoClear=!1;const i=this._lodMeshes.length;for(let t=1;t<i;t++)this._applyGGXFilter(e,t-1,t);t.autoClear=s}_applyGGXFilter(e,t,s){const i=this._renderer,r=this._pingPongRenderTarget,n=this._ggxMaterial,o=this._lodMeshes[s];o.material=n;const a=_T.get(n),l=s/(this._lodMeshes.length-1),h=t/(this._lodMeshes.length-1),u=Math.sqrt(l*l-h*h)*(0+1.25*l),{_lodMax:c}=this,d=this._sizeLods[s],p=3*d*(s>c-4?s-c+4:0),m=4*(this._cubeSize-d);e.texture.frame=(e.texture.frame||0)+1,a.envMap.value=e.texture,a.roughness.value=u,a.mipInt.value=c-t,AT(r,p,m,3*d,2*d),i.setRenderTarget(r),i.render(o,pT),r.texture.frame=(r.texture.frame||0)+1,a.envMap.value=r.texture,a.roughness.value=0,a.mipInt.value=c-s,AT(e,p,m,3*d,2*d),i.setRenderTarget(e),i.render(o,pT)}_blur(e,t,s,i,r){const n=this._pingPongRenderTarget;this._halfBlur(e,n,t,s,i,"latitudinal",r),this._halfBlur(n,e,s,s,i,"longitudinal",r)}_halfBlur(e,t,s,i,r,n,o){const a=this._renderer,l=this._blurMaterial;"latitudinal"!==n&&"longitudinal"!==n&&Zo("blur direction must be either latitudinal or longitudinal!");const h=this._lodMeshes[i];h.material=l;const u=_T.get(l),c=this._sizeLods[s]-1,d=isFinite(r)?Math.PI/(2*c):2*Math.PI/39,p=r/d,m=isFinite(r)?1+Math.floor(3*p):dT;m>dT&&Yo(`sigmaRadians, ${r}, is too large and will clip, as it requested ${m} samples when the maximum is set to 20`);const f=[];let g=0;for(let e=0;e<dT;++e){const t=e/p,s=Math.exp(-t*t/2);f.push(s),0===e?g+=s:e<m&&(g+=2*s)}for(let e=0;e<f.length;e++)f[e]=f[e]/g;e.texture.frame=(e.texture.frame||0)+1,u.envMap.value=e.texture,u.samples.value=m,u.weights.array=f,u.latitudinal.value="latitudinal"===n?1:0,o&&(u.poleAxis.value=o);const{_lodMax:y}=this;u.dTheta.value=d,u.mipInt.value=y-s;const x=this._sizeLods[i];AT(t,3*x*(i>y-4?i-y+4:0),4*(this._cubeSize-x),3*x,2*x),a.setRenderTarget(t),a.render(h,pT)}}function MT(e,t){const s=new Ba(e,t,{magFilter:xn,minFilter:xn,generateMipmaps:!1,type:En,format:Ln,colorSpace:Ao});return s.texture.mapping=306,s.texture.name="PMREM.cubeUv",s.texture.isPMREMTexture=!0,s.scissorTest=!0,s}function AT(e,t,s,i,r){e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r)}function NT(e){const t=new gw;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function ET(e){const t=NT("cubemap");return t.fragmentNode=Dx(e,TT),t}function CT(e){const t=NT("equirect");return t.fragmentNode=ty(e,Aw(TT),0),t}const RT=new WeakMap;function PT(e,t,s){const i=function(e){let t=RT.get(e);void 0===t&&(t=new WeakMap,RT.set(e,t));return t}(t);let r=i.get(e);if((void 0!==r?r.pmremVersion:-1)!==e.pmremVersion){const t=e.image;if(e.isCubeTexture){if(!function(e){if(null==e)return!1;let t=0;const s=6;for(let i=0;i<s;i++)void 0!==e[i]&&t++;return t===s}(t))return null;r=s.fromCubemap(e,r)}else{if(!function(e){return null!=e&&e.height>0}(t))return null;r=s.fromEquirectangular(e,r)}r.pmremVersion=e.pmremVersion,i.set(e,r)}return r.texture}class BT extends Bc{static get type(){return"PMREMNode"}constructor(e,t=null,s=null){super("vec3"),this._value=e,this._pmrem=null,this.uvNode=t,this.levelNode=s,this._generator=null;const i=new Ra;i.isRenderTargetTexture=!0,this._texture=ty(i),this._width=Up(0),this._height=Up(0),this._maxMip=Up(0),this.updateBeforeType=wc.RENDER}set value(e){this._value=e,this._pmrem=null}get value(){return this._value}updateFromTexture(e){const t=function(e){const t=Math.log2(e)-2,s=1/e;return{texelWidth:1/(3*Math.max(Math.pow(2,t),112)),texelHeight:s,maxMip:t}}(e.image.height);this._texture.value=e,this._width.value=t.texelWidth,this._height.value=t.texelHeight,this._maxMip.value=t.maxMip}updateBefore(e){let t=this._pmrem;const s=t?t.pmremVersion:-1,i=this._value;s!==i.pmremVersion&&(t=!0===i.isPMREMTexture?i:PT(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new ST(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=Ax.mul(Gd(t.x,t.y.negate(),t.z));let s=this.levelNode;return null===s&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),iT(this._texture,t,s,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const IT=Td(BT).setParameterLength(1,3),DT=new WeakMap;class LT extends F_{static get type(){return"EnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){const{material:t}=e;let s=this.envNode;if(s.isTextureNode||s.isMaterialReferenceNode){const e=s.isTextureNode?s.value:t[s.property];let i=DT.get(e);void 0===i&&(i=IT(e),DT.set(e,i)),s=i}const i=!0===t.useAnisotropy||t.anisotropy>0?db:mx,r=s.context(FT(ap,i)).mul(Mx),n=s.context(OT(fx)).mul(Math.PI).mul(Mx),o=Eg(r),a=Eg(n);e.context.radiance.addAssign(o),e.context.iblIrradiance.addAssign(a);const l=e.context.lightingModel.clearcoatRadiance;if(l){const e=s.context(FT(up,gx)).mul(Mx),t=Eg(e);l.addAssign(t)}}}const FT=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=rx.negate().reflect(t),s=vf(e).mix(s,t).normalize(),s=s.transformDirection(Ay)),s),getTextureLevel:()=>e}},OT=e=>({getUV:()=>e,getTextureLevel:()=>Dd(1)}),VT=new Au;class zT extends gw{static get type(){return"MeshStandardNodeMaterial"}constructor(e){super(),this.isMeshStandardNodeMaterial=!0,this.lights=!0,this.emissiveNode=null,this.metalnessNode=null,this.roughnessNode=null,this.setDefaultValues(VT),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new LT(t):null}setupLightingModel(){return new kv}setupSpecular(){const e=Af(Gd(.04),rp.rgb,lp);_p.assign(Gd(.04)),wp.assign(e),vp.assign(1)}setupVariants(){const e=this.metalnessNode?Dd(this.metalnessNode):Db;lp.assign(e);let t=this.roughnessNode?Dd(this.roughnessNode):Ib;t=Yw({roughness:t}),ap.assign(t),this.setupSpecular(),np.assign(rp.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const kT=new Nu;class UT extends zT{static get type(){return"MeshPhysicalNodeMaterial"}constructor(e){super(),this.isMeshPhysicalNodeMaterial=!0,this.clearcoatNode=null,this.clearcoatRoughnessNode=null,this.clearcoatNormalNode=null,this.sheenNode=null,this.sheenRoughnessNode=null,this.iridescenceNode=null,this.iridescenceIORNode=null,this.iridescenceThicknessNode=null,this.specularIntensityNode=null,this.specularColorNode=null,this.iorNode=null,this.transmissionNode=null,this.thicknessNode=null,this.attenuationDistanceNode=null,this.attenuationColorNode=null,this.dispersionNode=null,this.anisotropyNode=null,this.setDefaultValues(kT),this.setValues(e)}get useClearcoat(){return this.clearcoat>0||null!==this.clearcoatNode}get useIridescence(){return this.iridescence>0||null!==this.iridescenceNode}get useSheen(){return this.sheen>0||null!==this.sheenNode}get useAnisotropy(){return this.anisotropy>0||null!==this.anisotropyNode}get useTransmission(){return this.transmission>0||null!==this.transmissionNode}get useDispersion(){return this.dispersion>0||null!==this.dispersionNode}setupSpecular(){const e=this.iorNode?Dd(this.iorNode):Xb;Ep.assign(e),_p.assign(cf(_f(Ep.sub(1).div(Ep.add(1))).mul(Rb),Gd(1)).mul(Cb)),wp.assign(Af(_p,rp.rgb,lp)),vp.assign(Af(Cb,1,lp))}setupLightingModel(){return new kv(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Dd(this.clearcoatNode):Fb,t=this.clearcoatRoughnessNode?Dd(this.clearcoatRoughnessNode):Ob;hp.assign(e),up.assign(Yw({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Gd(this.sheenNode):kb,t=this.sheenRoughnessNode?Dd(this.sheenRoughnessNode):Ub;cp.assign(e),dp.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?Dd(this.iridescenceNode):jb,t=this.iridescenceIORNode?Dd(this.iridescenceIORNode):$b,s=this.iridescenceThicknessNode?Dd(this.iridescenceThicknessNode):Wb;pp.assign(e),mp.assign(t),fp.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?Vd(this.anisotropyNode):Gb).toVar();yp.assign(e.length()),Pd(yp.equal(0),()=>{e.assign(Vd(1,0))}).Else(()=>{e.divAssign(Vd(yp)),yp.assign(yp.saturate())}),gp.assign(yp.pow2().mix(ap.pow2(),1)),xp.assign(ub[0].mul(e.x).add(ub[1].mul(e.y))),bp.assign(ub[1].mul(e.x).sub(ub[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?Dd(this.transmissionNode):Hb,t=this.thicknessNode?Dd(this.thicknessNode):qb,s=this.attenuationDistanceNode?Dd(this.attenuationDistanceNode):Yb,i=this.attenuationColorNode?Gd(this.attenuationColorNode):Zb;if(Cp.assign(e),Rp.assign(t),Pp.assign(s),Bp.assign(i),this.useDispersion){const e=this.dispersionNode?Dd(this.dispersionNode):i_;Ip.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Gd(this.clearcoatNormalNode):Vb}setup(e){e.context.setupClearcoatNormal=()=>eg(this.setupClearcoatNormal(e),"NORMAL","vec3"),super.setup(e)}copy(e){return this.clearcoatNode=e.clearcoatNode,this.clearcoatRoughnessNode=e.clearcoatRoughnessNode,this.clearcoatNormalNode=e.clearcoatNormalNode,this.sheenNode=e.sheenNode,this.sheenRoughnessNode=e.sheenRoughnessNode,this.iridescenceNode=e.iridescenceNode,this.iridescenceIORNode=e.iridescenceIORNode,this.iridescenceThicknessNode=e.iridescenceThicknessNode,this.specularIntensityNode=e.specularIntensityNode,this.specularColorNode=e.specularColorNode,this.transmissionNode=e.transmissionNode,this.thicknessNode=e.thicknessNode,this.attenuationDistanceNode=e.attenuationDistanceNode,this.attenuationColorNode=e.attenuationColorNode,this.dispersionNode=e.dispersionNode,this.anisotropyNode=e.anisotropyNode,super.copy(e)}}const GT=Ed(({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=Vd(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=kx("gradientMap","texture").context({getUV:()=>r});return Gd(e.r)}{const e=r.fwidth().mul(.5);return Af(Gd(.7),Gd(1),Rf(Dd(.7).sub(e.x),Dd(.7).add(e.x),r.x))}});class jT extends Lw{direct({lightDirection:e,lightColor:t,reflectedLight:s},i){const r=GT({normal:hx,lightDirection:e,builder:i}).mul(t);s.directDiffuse.addAssign(r.mul(kw({diffuseColor:rp.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(kw({diffuseColor:rp}))),i.indirectDiffuse.mulAssign(t)}}const $T=new Cu;class WT extends gw{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues($T),this.setValues(e)}setupLightingModel(){return new jT}}const HT=Ed(()=>{const e=Gd(rx.z,0,rx.x.negate()).normalize(),t=rx.cross(e);return Vd(e.dot(mx),t.dot(mx)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),qT=new Bu;class XT extends gw{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(qT),this.setValues(e)}setupVariants(e){const t=HT;let s;s=e.material.matcap?kx("matcap","texture").context({getUV:()=>t}):Gd(Af(.2,.8,t.y)),rp.rgb.mulAssign(s.rgb)}}class YT extends Bc{static get type(){return"RotateNode"}constructor(e,t){super(),this.positionNode=e,this.rotationNode=t}getNodeType(e){return this.positionNode.getNodeType(e)}setup(e){const{rotationNode:t,positionNode:s}=this;if("vec2"===this.getNodeType(e)){const e=t.cos(),i=t.sin();return Zd(e,i,i.negate(),e).mul(s)}{const e=t,i=Kd(Hd(1,0,0,0),Hd(0,$m(e.x),jm(e.x).negate(),0),Hd(0,jm(e.x),$m(e.x),0),Hd(0,0,0,1)),r=Kd(Hd($m(e.y),0,jm(e.y),0),Hd(0,1,0,0),Hd(jm(e.y).negate(),0,$m(e.y),0),Hd(0,0,0,1)),n=Kd(Hd($m(e.z),jm(e.z).negate(),0,0),Hd(jm(e.z),$m(e.z),0,0),Hd(0,0,1,0),Hd(0,0,0,1));return i.mul(r).mul(n).mul(Hd(s,1)).xyz}}}const ZT=Td(YT).setParameterLength(2),QT=new iu;class KT extends gw{static get type(){return"SpriteNodeMaterial"}constructor(e){super(),this.isSpriteNodeMaterial=!0,this._useSizeAttenuation=!0,this.positionNode=null,this.rotationNode=null,this.scaleNode=null,this.transparent=!0,this.setDefaultValues(QT),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,{positionNode:i,rotationNode:r,scaleNode:n,sizeAttenuation:o}=this,a=Xy.mul(Gd(i||0));let l=Vd(Uy[0].xyz.length(),Uy[1].xyz.length());null!==n&&(l=l.mul(Vd(n))),s.isPerspectiveCamera&&!1===o&&(l=l.mul(a.z.negate()));let h=Ky.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,s)=>new cg(e,t,s))("center","vec2",t);h=h.sub(e.sub(.5))}h=h.mul(l);const u=Dd(r||zb),c=ZT(h,u);return Hd(a.xy.add(c),a.zw)}copy(e){return this.positionNode=e.positionNode,this.rotationNode=e.rotationNode,this.scaleNode=e.scaleNode,super.copy(e)}get sizeAttenuation(){return this._useSizeAttenuation}set sizeAttenuation(e){this._useSizeAttenuation!==e&&(this._useSizeAttenuation=e,this.needsUpdate=!0)}}const JT=new xu,eS=new ua;class tS extends KT{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(JT),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return Xy.mul(Gd(e||Jy)).xyz}setupVertexSprite(e){const{material:t,camera:s}=e,{rotationNode:i,scaleNode:r,sizeNode:n,sizeAttenuation:o}=this;let a=super.setupVertex(e);if(!0!==t.isNodeMaterial)return a;let l=null!==n?Vd(n):s_;l=l.mul(dy),s.isPerspectiveCamera&&!0===o&&(l=l.mul(sS.div(ix.z.negate()))),r&&r.isNode&&(l=l.mul(Vd(r)));let h=Ky.xy;if(i&&i.isNode){const e=Dd(i);h=ZT(h,e)}return h=h.mul(l),h=h.div(yy.div(2)),h=h.mul(a.w),a=a.add(Hd(h,0,0)),a}setupVertex(e){return e.object.isPoints?super.setupVertex(e):this.setupVertexSprite(e)}get alphaToCoverage(){return this._useAlphaToCoverage}set alphaToCoverage(e){this._useAlphaToCoverage!==e&&(this._useAlphaToCoverage=e,this.needsUpdate=!0)}}const sS=Up(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(eS);this.value=.5*t.y});class iS extends Lw{constructor(){super(),this.shadowNode=Dd(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){rp.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(rp.rgb)}}const rS=new Mu;class nS extends gw{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(rS),this.setValues(e)}setupLightingModel(){return new iS}}sp("vec3"),sp("vec3"),sp("vec3");class oS{constructor(e,t,s){this.renderer=e,this.nodes=t,this.info=s,this._context="undefined"!=typeof self?self:null,this._animationLoop=null,this._requestId=null}start(){const e=(t,s)=>{this._requestId=this._context.requestAnimationFrame(e),!0===this.info.autoReset&&this.info.reset(),this.nodes.nodeFrame.update(),this.info.frame=this.nodes.nodeFrame.frameId,this.renderer._inspector.begin(),null!==this._animationLoop&&this._animationLoop(t,s),this.renderer._inspector.finish()};e()}stop(){this._context.cancelAnimationFrame(this._requestId),this._requestId=null}getAnimationLoop(){return this._animationLoop}setAnimationLoop(e){this._animationLoop=e}getContext(){return this._context}setContext(e){this._context=e}dispose(){this.stop()}}class aS{constructor(){this.weakMaps={}}_getWeakMap(e){const t=e.length;let s=this.weakMaps[t];return void 0===s&&(s=new WeakMap,this.weakMaps[t]=s),s}get(e){let t=this._getWeakMap(e);for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),void 0===t)return;return t.get(e[e.length-1])}set(e,t){let s=this._getWeakMap(e);for(let t=0;t<e.length-1;t++){const i=e[t];!1===s.has(i)&&s.set(i,new WeakMap),s=s.get(i)}return s.set(e[e.length-1],t),this}delete(e){let t=this._getWeakMap(e);for(let s=0;s<e.length-1;s++)if(t=t.get(e[s]),void 0===t)return!1;return t.delete(e[e.length-1])}}let lS=0;class hS{constructor(e,t,s,i,r,n,o,a,l,h){this.id=lS++,this._nodes=e,this._geometries=t,this.renderer=s,this.object=i,this.material=r,this.scene=n,this.camera=o,this.lightsNode=a,this.context=l,this.geometry=i.geometry,this.version=r.version,this.drawRange=null,this.attributes=null,this.attributesId=null,this.pipeline=null,this.group=null,this.vertexBuffers=null,this.drawParams=null,this.bundle=null,this.clippingContext=h,this.clippingContextCacheKey=null!==h?h.cacheKey:"",this.initialNodesCacheKey=this.getDynamicCacheKey(),this.initialCacheKey=this.getCacheKey(),this._nodeBuilderState=null,this._bindings=null,this._monitor=null,this.onDispose=null,this.isRenderObject=!0,this.onMaterialDispose=()=>{this.dispose()},this.onGeometryDispose=()=>{this.attributes=null,this.attributesId=null},this.material.addEventListener("dispose",this.onMaterialDispose),this.geometry.addEventListener("dispose",this.onGeometryDispose)}updateClipping(e){this.clippingContext=e}get clippingNeedsUpdate(){return null!==this.clippingContext&&this.clippingContext.cacheKey!==this.clippingContextCacheKey&&(this.clippingContextCacheKey=this.clippingContext.cacheKey,!0)}get hardwareClippingPlanes(){return!0===this.material.hardwareClipping?this.clippingContext.unionClippingCount:0}getNodeBuilderState(){return this._nodeBuilderState||(this._nodeBuilderState=this._nodes.getForRender(this))}getMonitor(){return this._monitor||(this._monitor=this.getNodeBuilderState().observer)}getBindings(){return this._bindings||(this._bindings=this.getNodeBuilderState().createBindings())}getBindingGroup(e){for(const t of this.getBindings())if(t.name===e)return t}getIndex(){return this._geometries.getIndex(this)}getIndirect(){return this._geometries.getIndirect(this)}getIndirectOffset(){return this._geometries.getIndirectOffset(this)}getChainArray(){return[this.object,this.material,this.context,this.lightsNode]}setGeometry(e){this.geometry=e,this.attributes=null,this.attributesId=null}getAttributes(){if(null!==this.attributes)return this.attributes;const e=this.getNodeBuilderState().nodeAttributes,t=this.geometry,s=[],i=new Set,r={};for(const n of e){let e;if(n.node&&n.node.attribute?e=n.node.attribute:(e=t.getAttribute(n.name),r[n.name]=e.version),void 0===e)continue;s.push(e);const o=e.isInterleavedBufferAttribute?e.data:e;i.add(o)}return this.attributes=s,this.attributesId=r,this.vertexBuffers=Array.from(i.values()),s}getVertexBuffers(){return null===this.vertexBuffers&&this.getAttributes(),this.vertexBuffers}getDrawParameters(){const{object:e,material:t,geometry:s,group:i,drawRange:r}=this,n=this.drawParams||(this.drawParams={vertexCount:0,firstVertex:0,instanceCount:0,firstInstance:0}),o=this.getIndex(),a=null!==o;let l=1;if(!0===s.isInstancedBufferGeometry?l=s.instanceCount:void 0!==e.count&&(l=Math.max(0,e.count)),0===l)return null;if(n.instanceCount=l,!0===e.isBatchedMesh)return n;let h=1;!0!==t.wireframe||e.isPoints||e.isLineSegments||e.isLine||e.isLineLoop||(h=2);let u=r.start*h,c=(r.start+r.count)*h;null!==i&&(u=Math.max(u,i.start*h),c=Math.min(c,(i.start+i.count)*h));const d=s.attributes.position;let p=1/0;a?p=o.count:null!=d&&(p=d.count),u=Math.max(u,0),c=Math.min(c,p);const m=c-u;return m<0||m===1/0?null:(n.vertexCount=m,n.firstVertex=u,n)}getGeometryCacheKey(){const{geometry:e}=this;let t="";for(const s of Object.keys(e.attributes).sort()){const i=e.attributes[s];t+=s+",",i.data&&(t+=i.data.stride+","),i.offset&&(t+=i.offset+","),i.itemSize&&(t+=i.itemSize+","),i.normalized&&(t+="n,")}for(const s of Object.keys(e.morphAttributes).sort()){const i=e.morphAttributes[s];t+="morph-"+s+",";for(let e=0,s=i.length;e<s;e++){t+=i[e].id+","}}return e.index&&(t+="index,"),t}getMaterialCacheKey(){const{object:e,material:t,renderer:s}=this;let i=t.customProgramCacheKey();for(const e of function(e){const t=Object.keys(e);let s=Object.getPrototypeOf(e);for(;s;){const e=Object.getOwnPropertyDescriptors(s);for(const s in e)if(void 0!==e[s]){const i=e[s];i&&"function"==typeof i.get&&t.push(s)}s=Object.getPrototypeOf(s)}return t}(t)){if(/^(is[A-Z]|_)|^(visible|version|uuid|name|opacity|userData)$/.test(e))continue;const r=t[e];let n;if(null!==r){const e=typeof r;"number"===e?n=0!==r?"1":"0":"object"===e?(n="{",r.isTexture&&(n+=r.mapping,!0===s.backend.isWebGPUBackend&&(n+=r.magFilter,n+=r.minFilter,n+=r.wrapS,n+=r.wrapT,n+=r.wrapR)),n+="}"):n=String(r)}else n=String(r);i+=n+","}return i+=this.clippingContextCacheKey+",",e.geometry&&(i+=this.getGeometryCacheKey()),e.skeleton&&(i+=e.skeleton.bones.length+","),e.isBatchedMesh&&(i+=e._matricesTexture.uuid+",",null!==e._colorsTexture&&(i+=e._colorsTexture.uuid+",")),(e.isInstancedMesh||e.count>1||Array.isArray(e.morphTargetInfluences))&&(i+=e.uuid+","),i+=this.context.id+",",i+=e.receiveShadow+",",nc(i)}get needsGeometryUpdate(){if(this.geometry.id!==this.object.geometry.id)return!0;if(null!==this.attributes){const e=this.attributesId;for(const t in e){const s=this.geometry.getAttribute(t);if(void 0===s||e[t]!==s.id)return!0}}return!1}get needsUpdate(){return this.initialNodesCacheKey!==this.getDynamicCacheKey()||this.clippingNeedsUpdate}getDynamicCacheKey(){let e=0;return!0!==this.material.isShadowPassMaterial&&(e=this._nodes.getCacheKey(this.scene,this.lightsNode)),this.camera.isArrayCamera&&(e=ac(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=ac(e,1)),e=ac(e,this.camera.id,this.renderer.contextNode.id,this.renderer.contextNode.version),e}getCacheKey(){return this.getMaterialCacheKey()+this.getDynamicCacheKey()}dispose(){this.material.removeEventListener("dispose",this.onMaterialDispose),this.geometry.removeEventListener("dispose",this.onGeometryDispose),this.onDispose()}}const uS=[];class cS{constructor(e,t,s,i,r,n){this.renderer=e,this.nodes=t,this.geometries=s,this.pipelines=i,this.bindings=r,this.info=n,this.chainMaps={}}get(e,t,s,i,r,n,o,a){const l=this.getChainMap(a);uS[0]=e,uS[1]=t,uS[2]=n,uS[3]=r;let h=l.get(uS);return void 0===h?(h=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,o,a),l.set(uS,h)):(h.updateClipping(o),h.needsGeometryUpdate&&h.setGeometry(e.geometry),(h.version!==t.version||h.needsUpdate)&&(h.initialCacheKey!==h.getCacheKey()?(h.dispose(),h=this.get(e,t,s,i,r,n,o,a)):h.version=t.version)),uS.length=0,h}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new aS)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,o,a,l,h,u){const c=this.getChainMap(u),d=new hS(e,t,s,i,r,n,o,a,l,h);return d.onDispose=()=>{this.pipelines.delete(d),this.bindings.deleteForRender(d),this.nodes.delete(d),c.delete(d.getChainArray())},d}}class dS{constructor(){this.data=new WeakMap}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}delete(e){let t=null;return this.data.has(e)&&(t=this.data.get(e),this.data.delete(e)),t}has(e){return this.data.has(e)}dispose(){this.data=new WeakMap}}const pS=1,mS=2,fS=3,gS=4,yS=16;class xS extends dS{constructor(e){super(),this.backend=e}delete(e){const t=super.delete(e);return null!==t&&this.backend.destroyAttribute(e),t}update(e,t){const s=this.get(e);if(void 0===s.version)t===pS?this.backend.createAttribute(e):t===mS?this.backend.createIndexAttribute(e):t===fS?this.backend.createStorageAttribute(e):t===gS&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version<t.version||t.usage===zo)&&(this.backend.updateAttribute(e),s.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function bS(e){return null!==e.index?e.index.version:e.attributes.position.version}function _S(e){const t=[],s=e.index,i=e.attributes.position;if(null!==s){const e=s.array;for(let s=0,i=e.length;s<i;s+=3){const i=e[s+0],r=e[s+1],n=e[s+2];t.push(i,r,r,n,n,i)}}else{for(let e=0,s=i.array.length/3-1;e<s;e+=3){const s=e+0,i=e+1,r=e+2;t.push(s,i,i,r,r,s)}}const r=new($o(t)?mh:ph)(t,1);return r.version=bS(e),r}class wS extends dS{constructor(e,t){super(),this.attributes=e,this.info=t,this.wireframes=new WeakMap,this.attributeCall=new WeakMap,this._geometryDisposeListeners=new Map}has(e){const t=e.geometry;return super.has(t)&&!0===this.get(t).initialized}updateForRender(e){!1===this.has(e)&&this.initGeometry(e),this.updateAttributes(e)}initGeometry(e){const t=e.geometry;this.get(t).initialized=!0,this.info.memory.geometries++;const s=()=>{this.info.memory.geometries--;const i=t.index,r=e.getAttributes();null!==i&&this.attributes.delete(i);for(const e of r)this.attributes.delete(e);const n=this.wireframes.get(t);void 0!==n&&this.attributes.delete(n),t.removeEventListener("dispose",s),this._geometryDisposeListeners.delete(t)};t.addEventListener("dispose",s),this._geometryDisposeListeners.set(t,s)}updateAttributes(e){const t=e.getAttributes();for(const e of t)e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute?this.updateAttribute(e,fS):this.updateAttribute(e,pS);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,mS);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,gS)}updateAttribute(e,t){const s=this.info.render.calls;e.isInterleavedBufferAttribute?void 0===this.attributeCall.get(e)?(this.attributes.update(e,t),this.attributeCall.set(e,s)):this.attributeCall.get(e.data)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e.data,s),this.attributeCall.set(e,s)):this.attributeCall.get(e)!==s&&(this.attributes.update(e,t),this.attributeCall.set(e,s))}getIndirect(e){return e.geometry.indirect}getIndirectOffset(e){return e.geometry.indirectOffset}getIndex(e){const{geometry:t,material:s}=e;let i=t.index;if(!0===s.wireframe){const e=this.wireframes;let s=e.get(t);void 0===s?(s=_S(t),e.set(t,s)):s.version!==bS(t)&&(this.attributes.delete(s),s=_S(t),e.set(t,s)),i=s}return i}dispose(){for(const[e,t]of this._geometryDisposeListeners.entries())e.removeEventListener("dispose",t);this._geometryDisposeListeners.clear()}}class vS{constructor(){this.autoReset=!0,this.frame=0,this.calls=0,this.render={calls:0,frameCalls:0,drawCalls:0,triangles:0,points:0,lines:0,timestamp:0},this.compute={calls:0,frameCalls:0,timestamp:0},this.memory={geometries:0,textures:0}}update(e,t,s){this.render.drawCalls++,e.isMesh||e.isSprite?this.render.triangles+=s*(t/3):e.isPoints?this.render.points+=s*t:e.isLineSegments?this.render.lines+=s*(t/2):e.isLine?this.render.lines+=s*(t-1):Zo("WebGPUInfo: Unknown object type.")}reset(){this.render.drawCalls=0,this.render.frameCalls=0,this.compute.frameCalls=0,this.render.triangles=0,this.render.points=0,this.render.lines=0}dispose(){this.reset(),this.calls=0,this.render.calls=0,this.compute.calls=0,this.render.timestamp=0,this.compute.timestamp=0,this.memory.geometries=0,this.memory.textures=0}}class TS{constructor(e){this.cacheKey=e,this.usedTimes=0}}class SS extends TS{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class MS extends TS{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let AS=0;class NS{constructor(e,t,s,i=null,r=null){this.id=AS++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=r,this.usedTimes=0}}class ES extends dS{constructor(e,t){super(),this.backend=e,this.nodes=t,this.bindings=null,this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}getForCompute(e,t){const{backend:s}=this,i=this.get(e);if(this._needsComputeUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.computeProgram.usedTimes--);const n=this.nodes.getForCompute(e);let o=this.programs.compute.get(n.computeShader);void 0===o&&(r&&0===r.computeProgram.usedTimes&&this._releaseProgram(r.computeProgram),o=new NS(n.computeShader,"compute",e.name,n.transforms,n.nodeAttributes),this.programs.compute.set(n.computeShader,o),s.createProgram(o));const a=this._getComputeCacheKey(e,o);let l=this.caches.get(a);void 0===l&&(r&&0===r.usedTimes&&this._releasePipeline(r),l=this._getComputePipeline(e,o,a,t)),l.usedTimes++,o.usedTimes++,i.version=e.version,i.pipeline=l}return i.pipeline}getForRender(e,t=null){const{backend:s}=this,i=this.get(e);if(this._needsRenderUpdate(e)){const r=i.pipeline;r&&(r.usedTimes--,r.vertexProgram.usedTimes--,r.fragmentProgram.usedTimes--);const n=e.getNodeBuilderState(),o=e.material?e.material.name:"";let a=this.programs.vertex.get(n.vertexShader);void 0===a&&(r&&0===r.vertexProgram.usedTimes&&this._releaseProgram(r.vertexProgram),a=new NS(n.vertexShader,"vertex",o),this.programs.vertex.set(n.vertexShader,a),s.createProgram(a));let l=this.programs.fragment.get(n.fragmentShader);void 0===l&&(r&&0===r.fragmentProgram.usedTimes&&this._releaseProgram(r.fragmentProgram),l=new NS(n.fragmentShader,"fragment",o),this.programs.fragment.set(n.fragmentShader,l),s.createProgram(l));const h=this._getRenderCacheKey(e,a,l);let u=this.caches.get(h);void 0===u?(r&&0===r.usedTimes&&this._releasePipeline(r),u=this._getRenderPipeline(e,a,l,h,t)):e.pipeline=u,u.usedTimes++,a.usedTimes++,l.usedTimes++,i.pipeline=u}return i.pipeline}delete(e){const t=this.get(e).pipeline;return t&&(t.usedTimes--,0===t.usedTimes&&this._releasePipeline(t),t.isComputePipeline?(t.computeProgram.usedTimes--,0===t.computeProgram.usedTimes&&this._releaseProgram(t.computeProgram)):(t.fragmentProgram.usedTimes--,t.vertexProgram.usedTimes--,0===t.vertexProgram.usedTimes&&this._releaseProgram(t.vertexProgram),0===t.fragmentProgram.usedTimes&&this._releaseProgram(t.fragmentProgram))),super.delete(e)}dispose(){super.dispose(),this.caches=new Map,this.programs={vertex:new Map,fragment:new Map,compute:new Map}}updateForRender(e){this.getForRender(e)}_getComputePipeline(e,t,s,i){s=s||this._getComputeCacheKey(e,t);let r=this.caches.get(s);return void 0===r&&(r=new MS(s,t),this.caches.set(s,r),this.backend.createComputePipeline(r,i)),r}_getRenderPipeline(e,t,s,i,r){i=i||this._getRenderCacheKey(e,t,s);let n=this.caches.get(i);return void 0===n&&(n=new SS(i,t,s),this.caches.set(i,n),e.pipeline=n,this.backend.createRenderPipeline(e,r)),n}_getComputeCacheKey(e,t){return e.id+","+t.id}_getRenderCacheKey(e,t,s){return t.id+","+s.id+","+this.backend.getRenderCacheKey(e)}_releasePipeline(e){this.caches.delete(e.cacheKey)}_releaseProgram(e){const t=e.code,s=e.stage;this.programs[s].delete(t)}_needsComputeUpdate(e){const t=this.get(e);return void 0===t.pipeline||t.version!==e.version}_needsRenderUpdate(e){return void 0===this.get(e).pipeline||this.backend.needsRenderUpdate(e)}}class CS extends dS{constructor(e,t,s,i,r,n){super(),this.backend=e,this.textures=s,this.pipelines=r,this.attributes=i,this.nodes=t,this.info=n,this.pipelines.bindings=this}getForRender(e){const t=e.getBindings();for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),s.bindGroup=e)}return t}getForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t){const s=this.get(e);void 0===s.bindGroup&&(this._init(e),this.backend.createBindings(e,t,0),s.bindGroup=e)}return t}updateForCompute(e){this._updateBindings(this.getForCompute(e))}updateForRender(e){this._updateBindings(this.getForRender(e))}deleteForCompute(e){const t=this.nodes.getForCompute(e).bindings;for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}deleteForRender(e){const t=e.getBindings();for(const e of t)this.backend.deleteBindGroupData(e),this.delete(e)}_updateBindings(e){for(const t of e)this._update(t,e)}_init(e){for(const t of e.bindings)if(t.isSampledTexture)this.textures.updateTexture(t.texture);else if(t.isSampler)this.textures.updateSampler(t.texture);else if(t.isStorageBuffer){const e=t.attribute,s=e.isIndirectStorageBufferAttribute?gS:fS;this.attributes.update(e,s)}}_update(e,t){const{backend:s}=this;let i=!1,r=!0,n=0,o=0;for(const t of e.bindings){if(!1!==this.nodes.updateGroup(t)){if(t.isStorageBuffer){const e=t.attribute,s=e.isIndirectStorageBufferAttribute?gS:fS;this.attributes.update(e,s)}if(t.isUniformBuffer){t.update()&&s.updateBinding(t)}else if(t.isSampledTexture){const e=t.update(),a=t.texture,l=this.textures.get(a);e&&(this.textures.updateTexture(a),t.generation!==l.generation&&(t.generation=l.generation,i=!0,r=!1));if(void 0!==s.get(a).externalTexture||l.isDefaultTexture?r=!1:(n=10*n+a.id,o+=a.version),!0===a.isStorageTexture&&!0===a.mipmapsAutoUpdate){const e=this.get(a);!0===t.store?e.needsMipmap=!0:this.textures.needsMipmaps(a)&&!0===e.needsMipmap&&(this.backend.generateMipmaps(a),e.needsMipmap=!1)}}else if(t.isSampler){if(t.update()){const e=this.textures.updateSampler(t.texture);t.samplerKey!==e&&(t.samplerKey=e,i=!0,r=!1)}}}}!0===i&&this.backend.updateBindings(e,t,r?n:0,o)}}function RS(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?e.z-t.z:e.id-t.id}function PS(e,t){return e.groupOrder!==t.groupOrder?e.groupOrder-t.groupOrder:e.renderOrder!==t.renderOrder?e.renderOrder-t.renderOrder:e.z!==t.z?t.z-e.z:e.id-t.id}function BS(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&2===e.side&&!1===e.forceSinglePass}class IS{constructor(e,t,s){this.renderItems=[],this.renderItemsIndex=0,this.opaque=[],this.transparentDoublePass=[],this.transparent=[],this.bundles=[],this.lightsNode=e.getNode(t,s),this.lightsArray=[],this.scene=t,this.camera=s,this.occlusionQueryCount=0}begin(){return this.renderItemsIndex=0,this.opaque.length=0,this.transparentDoublePass.length=0,this.transparent.length=0,this.bundles.length=0,this.lightsArray.length=0,this.occlusionQueryCount=0,this}getNextRenderItem(e,t,s,i,r,n,o){let a=this.renderItems[this.renderItemsIndex];return void 0===a?(a={id:e.id,object:e,geometry:t,material:s,groupOrder:i,renderOrder:e.renderOrder,z:r,group:n,clippingContext:o},this.renderItems[this.renderItemsIndex]=a):(a.id=e.id,a.object=e,a.geometry=t,a.material=s,a.groupOrder=i,a.renderOrder=e.renderOrder,a.z=r,a.group=n,a.clippingContext=o),this.renderItemsIndex++,a}push(e,t,s,i,r,n,o){const a=this.getNextRenderItem(e,t,s,i,r,n,o);!0===e.occlusionTest&&this.occlusionQueryCount++,!0===s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(BS(s)&&this.transparentDoublePass.push(a),this.transparent.push(a)):this.opaque.push(a)}unshift(e,t,s,i,r,n,o){const a=this.getNextRenderItem(e,t,s,i,r,n,o);!0===s.transparent||s.transmission>0||s.transmissionNode&&s.transmissionNode.isNode||s.backdropNode&&s.backdropNode.isNode?(BS(s)&&this.transparentDoublePass.unshift(a),this.transparent.unshift(a)):this.opaque.unshift(a)}pushBundle(e){this.bundles.push(e)}pushLight(e){this.lightsArray.push(e)}sort(e,t){this.opaque.length>1&&this.opaque.sort(e||RS),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||PS),this.transparent.length>1&&this.transparent.sort(t||PS)}finish(){this.lightsNode.setLights(this.lightsArray);for(let e=this.renderItemsIndex,t=this.renderItems.length;e<t;e++){const t=this.renderItems[e];if(null===t.id)break;t.id=null,t.object=null,t.geometry=null,t.material=null,t.groupOrder=null,t.renderOrder=null,t.z=null,t.group=null,t.clippingContext=null}}}const DS=[];class LS{constructor(e){this.lighting=e,this.lists=new aS}get(e,t){const s=this.lists;DS[0]=e,DS[1]=t;let i=s.get(DS);return void 0===i&&(i=new IS(this.lighting,e,t),s.set(DS,i)),DS.length=0,i}dispose(){this.lists=new aS}}let FS=0;class OS{constructor(){this.id=FS++,this.color=!0,this.clearColor=!0,this.clearColorValue={r:0,g:0,b:0,a:1},this.depth=!0,this.clearDepth=!0,this.clearDepthValue=1,this.stencil=!1,this.clearStencil=!0,this.clearStencilValue=1,this.viewport=!1,this.viewportValue=new Pa,this.scissor=!1,this.scissorValue=new Pa,this.renderTarget=null,this.textures=null,this.depthTexture=null,this.activeCubeFace=0,this.activeMipmapLevel=0,this.sampleCount=1,this.width=0,this.height=0,this.occlusionQueryCount=0,this.clippingContext=null,this.isRenderContext=!0}getCacheKey(){return VS(this)}}function VS(e){const{textures:t,activeCubeFace:s,activeMipmapLevel:i}=e,r=[s,i];for(const e of t)r.push(e.id);return oc(r)}const zS=[],kS=new Jh,US=new Uh;class GS{constructor(){this.chainMaps={}}get(e,t,s=null,i=null){let r;if(zS[0]=e,zS[1]=t,null!==i&&(zS[2]=i),null===s)r="default";else{const e=s.texture.format;r=`${s.textures.length}:${e}:${s.samples}:${s.depthBuffer}:${s.stencilBuffer}`}const n=this._getChainMap(r);let o=n.get(zS);return void 0===o&&(o=new OS,n.set(zS,o)),zS.length=0,null!==s&&(o.sampleCount=0===s.samples?1:s.samples),o}getForClear(e=null){return this.get(kS,US,e)}_getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new aS)}dispose(){this.chainMaps={}}}const jS=new da;class $S extends dS{constructor(e,t,s){super(),this.renderer=e,this.backend=t,this.info=s}updateRenderTarget(e,t=0){const s=this.get(e),i=0===e.samples?1:e.samples,r=s.depthTextureMips||(s.depthTextureMips={}),n=e.textures,o=this.getSize(n[0]),a=o.width>>t,l=o.height>>t;let h=e.depthTexture||r[t];const u=!0===e.depthBuffer||!0===e.stencilBuffer;let c=!1;void 0===h&&u&&(h=new _u,h.format=e.stencilBuffer?On:Fn,h.type=e.stencilBuffer?Pn:An,h.image.width=a,h.image.height=l,h.image.depth=o.depth,h.renderTarget=e,h.isArrayTexture=!0===e.multiview&&o.depth>1,r[t]=h),s.width===o.width&&o.height===s.height||(c=!0,h&&(h.needsUpdate=!0,h.image.width=a,h.image.height=l,h.image.depth=h.isArrayTexture?h.image.depth:1)),s.width=o.width,s.height=o.height,s.textures=n,s.depthTexture=h||null,s.depth=e.depthBuffer,s.stencil=e.stencilBuffer,s.renderTarget=e,s.sampleCount!==i&&(c=!0,h&&(h.needsUpdate=!0),s.sampleCount=i);const d={sampleCount:i};if(!0!==e.isXRRenderTarget){for(let e=0;e<n.length;e++){const t=n[e];c&&(t.needsUpdate=!0),this.updateTexture(t,d)}h&&this.updateTexture(h,d)}!0!==s.initialized&&(s.initialized=!0,s.onDispose=()=>{this._destroyRenderTarget(e)},e.addEventListener("dispose",s.onDispose))}updateTexture(e,t={}){const s=this.get(e);if(!0===s.initialized&&s.version===e.version)return;const i=e.isRenderTargetTexture||e.isDepthTexture||e.isFramebufferTexture,r=this.backend;if(i&&!0===s.initialized&&r.destroyTexture(e),e.isFramebufferTexture){const t=this.renderer.getRenderTarget();e.type=t?t.texture.type:wn}const{width:n,height:o,depth:a}=this.getSize(e);if(t.width=n,t.height=o,t.depth=a,t.needsMipmaps=this.needsMipmaps(e),t.levels=t.needsMipmaps?this.getMipLevels(e,n,o):1,e.isCubeTexture&&e.mipmaps.length>0&&t.levels++,i||!0===e.isStorageTexture||!0===e.isExternalTexture)r.createTexture(e,t),s.generation=e.version;else if(e.version>0){const i=e.image;if(void 0===i)Yo("Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)Yo("Renderer: Texture marked for update but image is incomplete.");else{if(e.images){const s=[];for(const t of e.images)s.push(t);t.images=s}else t.image=i;void 0!==s.isDefaultTexture&&!0!==s.isDefaultTexture||(r.createTexture(e,t),s.isDefaultTexture=!1,s.generation=e.version),!0===e.source.dataReady&&r.updateTexture(e,t);const n=!0===e.isStorageTexture&&!1===e.mipmapsAutoUpdate;t.needsMipmaps&&0===e.mipmaps.length&&!n&&r.generateMipmaps(e),e.onUpdate&&e.onUpdate(e)}}else r.createDefaultTexture(e),s.isDefaultTexture=!0,s.generation=e.version;!0!==s.initialized&&(s.initialized=!0,s.generation=e.version,this.info.memory.textures++,e.isVideoTexture&&!0===_a.enabled&&_a.getTransfer(e.colorSpace)!==Eo&&Yo("WebGPURenderer: Video textures must use a color space with a sRGB transfer function, e.g. SRGBColorSpace."),s.onDispose=()=>{this._destroyTexture(e)},e.addEventListener("dispose",s.onDispose)),s.version=e.version}updateSampler(e){return this.backend.updateSampler(e)}getSize(e,t=jS){let s=e.images?e.images[0]:e.image;return s?(void 0!==s.image&&(s=s.image),"undefined"!=typeof HTMLVideoElement&&s instanceof HTMLVideoElement?(t.width=s.videoWidth||1,t.height=s.videoHeight||1,t.depth=1):"undefined"!=typeof VideoFrame&&s instanceof VideoFrame?(t.width=s.displayWidth||1,t.height=s.displayHeight||1,t.depth=1):(t.width=s.width||1,t.height=s.height||1,t.depth=e.isCubeTexture?6:s.depth||1)):t.width=t.height=t.depth=1,t}getMipLevels(e,t,s){let i;return i=e.mipmaps.length>0?e.mipmaps.length:!0===e.isCompressedTexture?1:Math.floor(Math.log2(Math.max(t,s)))+1,i}needsMipmaps(e){return!0===e.generateMipmaps||e.mipmaps.length>0}_destroyRenderTarget(e){if(!0===this.has(e)){const t=this.get(e),s=t.textures,i=t.depthTexture;e.removeEventListener("dispose",t.onDispose);for(let e=0;e<s.length;e++)this._destroyTexture(s[e]);i&&this._destroyTexture(i),this.delete(e),this.backend.delete(e)}}_destroyTexture(e){if(!0===this.has(e)){const t=this.get(e);e.removeEventListener("dispose",t.onDispose);const s=t.isDefaultTexture;this.backend.destroyTexture(e,s),this.delete(e),this.info.memory.textures--}}}class WS extends eh{constructor(e,t,s,i=1){super(e,t,s),this.a=i}set(e,t,s,i=1){return this.a=i,super.set(e,t,s)}copy(e){return void 0!==e.a&&(this.a=e.a),super.copy(e)}clone(){return new this.constructor(this.r,this.g,this.b,this.a)}}class HS extends tp{static get type(){return"ParameterNode"}constructor(e,t=null){super(e,t),this.isParameterNode=!0}getMemberType(e,t){const s=this.getNodeType(e),i=e.getStructTypeNode(s);let r;return null!==i?r=i.getMemberType(e,t):(Zo(`TSL: Member "${t}" not found in struct "${s}".`),r="float"),r}getHash(){return this.uuid}generate(){return this.name}}class qS extends Cc{static get type(){return"StackNode"}constructor(e=null){super(),this.nodes=[],this.outputNode=null,this.parent=e,this._currentCond=null,this._expressionNode=null,this._currentNode=null,this.isStackNode=!0}getElementType(e){return this.hasOutput?this.outputNode.getElementType(e):"void"}getNodeType(e){return this.hasOutput?this.outputNode.getNodeType(e):"void"}getMemberType(e,t){return this.hasOutput?this.outputNode.getMemberType(e,t):"void"}addToStack(e,t=this.nodes.length){return!0!==e.isNode?(Zo("TSL: Invalid node added to stack."),this):(this.nodes.splice(t,0,e),this)}addToStackBefore(e){const t=this._currentNode?this.nodes.indexOf(this._currentNode):0;return this.addToStack(e,t)}If(e,t){const s=new xd(t);return this._currentCond=kf(e,s),this.addToStack(this._currentCond)}ElseIf(e,t){const s=new xd(t),i=kf(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new xd(e),this}Switch(e){return this._expressionNode=bd(e),this}Case(...e){const t=[];if(e.length>=2)for(let s=0;s<e.length-1;s++)t.push(this._expressionNode.equal(bd(e[s])));else Zo("TSL: Invalid parameter length. Case() requires at least two parameters.");const s=new xd(e[e.length-1]);let i=t[0];for(let e=1;e<t.length;e++)i=i.or(t[e]);const r=kf(i,s);return null===this._currentCond?(this._currentCond=r,this.addToStack(this._currentCond)):(this._currentCond.elseNode=r,this._currentCond=r,this)}Default(e){return this.Else(e),this}setup(e){const t=e.getNodeProperties(this);let s=0;for(const i of this.getChildren())i.isVarNode&&i.isIntent(e)&&!0!==i.isAssign(e)||(t["node"+s++]=i);return t.outputNode||null}get hasOutput(){return this.outputNode&&this.outputNode.isNode}build(e,...t){const s=Rd(),i=e.buildStage;Cd(this),e.setActiveStack(this);const r=t=>{if(this._currentNode=t,!t.isVarNode||!t.isIntent(e)||!0===t.isAssign(e))if("setup"===i)t.build(e);else if("analyze"===i)t.build(e,this);else if("generate"===i){const s=e.getDataFromNode(t,"any").stages,i=s&&s[e.shaderStage];if(t.isVarNode&&i&&1===i.length&&i[0]&&i[0].isStackNode)return;t.build(e,"void")}},n=[...this.nodes];for(const e of n)r(e);this._currentNode=null;const o=this.nodes.filter(e=>-1===n.indexOf(e));for(const e of o)r(e);let a;return a=this.hasOutput?this.outputNode.build(e,...t):super.build(e,...t),Cd(s),e.removeActiveStack(this),a}}const XS=Td(qS).setParameterLength(0,1);class YS extends Cc{static get type(){return"StructTypeNode"}constructor(e,t=null){var s;super("struct"),this.membersLayout=(s=e,Object.entries(s).map(([e,t])=>"string"==typeof t?{name:e,type:t,atomic:!1}:{name:e,type:t.type,atomic:t.atomic||!1})),this.name=t,this.isStructLayoutNode=!0}getLength(){const e=Float32Array.BYTES_PER_ELEMENT;let t=1,s=0;for(const i of this.membersLayout){const r=i.type,n=pc(r),o=mc(r)/e;t=Math.max(t,o);const a=s%t%o;0!==a&&(s+=o-a),s+=n}return Math.ceil(s/t)*t}getMemberType(e,t){const s=this.membersLayout.find(e=>e.name===t);return s?s.type:"void"}getNodeType(e){return e.getStructTypeFromNode(this,this.membersLayout,this.name).name}setup(e){e.getStructTypeFromNode(this,this.membersLayout,this.name),e.addInclude(this)}generate(e){return this.getNodeType(e)}}class ZS extends Cc{static get type(){return"StructNode"}constructor(e,t){super("vec3"),this.structTypeNode=e,this.values=t,this.isStructNode=!0}getNodeType(e){return this.structTypeNode.getNodeType(e)}getMemberType(e,t){return this.structTypeNode.getMemberType(e,t)}generate(e){const t=e.getVarFromNode(this),s=t.type,i=e.getPropertyName(t);return e.addLineFlowCode(`${i} = ${e.generateStruct(s,this.structTypeNode.membersLayout,this.values)}`,this),t.name}}class QS extends Cc{static get type(){return"OutputStructNode"}constructor(...e){super(),this.members=e,this.isOutputStructNode=!0}getNodeType(e){const t=e.getNodeProperties(this);if(void 0===t.membersLayout){const s=this.members,i=[];for(let t=0;t<s.length;t++){const r="m"+t,n=s[t].getNodeType(e);i.push({name:r,type:n,index:t})}t.membersLayout=i,t.structType=e.getOutputStructTypeFromNode(this,t.membersLayout)}return t.structType.name}generate(e){const t=e.getOutputStructName(),s=this.members,i=""!==t?t+".":"";for(let t=0;t<s.length;t++){const r=s[t].build(e);e.addLineFlowCode(`${i}m${t} = ${r}`,this)}return t}}const KS=Td(QS);function JS(e,t){for(let s=0;s<e.length;s++)if(e[s].name===t)return s;return-1}class eM extends QS{static get type(){return"MRTNode"}constructor(e){super(),this.outputNodes=e,this.isMRTNode=!0}has(e){return void 0!==this.outputNodes[e]}get(e){return this.outputNodes[e]}merge(e){const t={...this.outputNodes,...e.outputNodes};return tM(t)}setup(e){const t=this.outputNodes,s=[],i=e.renderer.getRenderTarget().textures;for(const e in t){s[JS(i,e)]=Hd(t[e])}return this.members=s,super.setup(e)}}const tM=Td(eM);class sM extends Bc{static get type(){return"BitcastNode"}constructor(e,t,s=null){super(),this.valueNode=e,this.conversionType=t,this.inputType=s,this.isBitcastNode=!0}getNodeType(e){if(null!==this.inputType){const t=this.valueNode.getNodeType(e),s=e.getTypeLength(t);return e.getTypeFromLength(s,this.conversionType)}return this.conversionType}generate(e){const t=this.getNodeType(e);let s="";if(null!==this.inputType){const t=this.valueNode.getNodeType(e);s=1===e.getTypeLength(t)?this.inputType:e.changeComponentType(t,this.inputType)}else s=this.valueNode.getNodeType(e);return`${e.getBitcastMethod(t,s)}( ${this.valueNode.build(e,s)} )`}}const iM=Md(sM).setParameterLength(2),rM=e=>new sM(e,"uint","float"),nM={};class oM extends vm{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,s){"int"===s?t.assign(iM(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return Fd;case"int":return Ld;case"uvec2":return kd;case"uvec3":return $d;case"uvec4":return Xd;case"ivec2":return zd;case"ivec3":return jd;case"ivec4":return qd}}_createTrailingZerosBaseLayout(e,t){const s=this._returnDataNode(t);return Ed(([e])=>{const i=Fd(0);this._resolveElementType(e,i,t);const r=Dd(i.bitAnd(Km(i))),n=rM(r).shiftRight(23).sub(127);return s(n)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createLeadingZerosBaseLayout(e,t){const s=this._returnDataNode(t);return Ed(([e])=>{Pd(e.equal(Fd(0)),()=>Fd(32));const i=Fd(0),r=Fd(0);return this._resolveElementType(e,i,t),Pd(i.shiftRight(16).equal(0),()=>{r.addAssign(16),i.shiftLeftAssign(16)}),Pd(i.shiftRight(24).equal(0),()=>{r.addAssign(8),i.shiftLeftAssign(8)}),Pd(i.shiftRight(28).equal(0),()=>{r.addAssign(4),i.shiftLeftAssign(4)}),Pd(i.shiftRight(30).equal(0),()=>{r.addAssign(2),i.shiftLeftAssign(2)}),Pd(i.shiftRight(31).equal(0),()=>{r.addAssign(1)}),s(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createOneBitsBaseLayout(e,t){const s=this._returnDataNode(t);return Ed(([e])=>{const i=Fd(0);this._resolveElementType(e,i,t),i.assign(i.sub(i.shiftRight(Fd(1)).bitAnd(Fd(1431655765)))),i.assign(i.bitAnd(Fd(858993459)).add(i.shiftRight(Fd(2)).bitAnd(Fd(858993459))));const r=i.add(i.shiftRight(Fd(4))).bitAnd(Fd(252645135)).mul(Fd(16843009)).shiftRight(Fd(24));return s(r)}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}_createMainLayout(e,t,s,i){const r=this._returnDataNode(t);return Ed(([e])=>{if(1===s)return r(i(e));{const t=r(0),n=["x","y","z","w"];for(let r=0;r<s;r++){const s=n[r];t[s].assign(i(e[s]))}return t}}).setLayout({name:e,type:t,inputs:[{name:"value",type:t}]})}setup(e){const{method:t,aNode:s}=this,{renderer:i}=e;if(i.backend.isWebGPUBackend)return super.setup(e);const r=this.getInputType(e),n=e.getElementType(r),o=e.getTypeLength(r),a=`${t}_base_${n}`,l=`${t}_${r}`;let h=nM[a];if(void 0===h){switch(t){case oM.COUNT_LEADING_ZEROS:h=this._createLeadingZerosBaseLayout(a,n);break;case oM.COUNT_TRAILING_ZEROS:h=this._createTrailingZerosBaseLayout(a,n);break;case oM.COUNT_ONE_BITS:h=this._createOneBitsBaseLayout(a,n)}nM[a]=h}let u=nM[l];void 0===u&&(u=this._createMainLayout(l,r,o,h),nM[l]=u);return Ed(()=>u(s))()}}oM.COUNT_TRAILING_ZEROS="countTrailingZeros",oM.COUNT_LEADING_ZEROS="countLeadingZeros",oM.COUNT_ONE_BITS="countOneBits";const aM=Md(oM,oM.COUNT_TRAILING_ZEROS).setParameterLength(1),lM=Md(oM,oM.COUNT_LEADING_ZEROS).setParameterLength(1),hM=Md(oM,oM.COUNT_ONE_BITS).setParameterLength(1),uM=Ed(([e])=>{const t=e.toUint().mul(747796405).add(2891336453),s=t.shiftRight(t.shiftRight(28).add(4)).bitXor(t).mul(277803737);return s.shiftRight(22).bitXor(s).toFloat().mul(1/2**32)}),cM=(e,t)=>bf(Kp(4,e.mul(Qp(1,e))),t);class dM extends Bc{static get type(){return"PackFloatNode"}constructor(e,t){super(),this.vectorNode=t,this.encoding=e,this.isPackFloatNode=!0}getNodeType(){return"uint"}generate(e){const t=this.vectorNode.getNodeType(e);return`${e.getFloatPackingMethod(this.encoding)}(${this.vectorNode.build(e,t)})`}}const pM=Md(dM,"snorm").setParameterLength(1),mM=Md(dM,"unorm").setParameterLength(1),fM=Md(dM,"float16").setParameterLength(1);class gM extends Bc{static get type(){return"UnpackFloatNode"}constructor(e,t){super(),this.uintNode=t,this.encoding=e,this.isUnpackFloatNode=!0}getNodeType(){return"vec2"}generate(e){const t=this.uintNode.getNodeType(e);return`${e.getFloatUnpackingMethod(this.encoding)}(${this.uintNode.build(e,t)})`}}const yM=Md(gM,"snorm").setParameterLength(1),xM=Md(gM,"unorm").setParameterLength(1),bM=Md(gM,"float16").setParameterLength(1),_M=Ed(([e])=>e.fract().sub(.5).abs()).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),wM=Ed(([e])=>Gd(_M(e.z.add(_M(e.y.mul(1)))),_M(e.z.add(_M(e.x.mul(1)))),_M(e.y.add(_M(e.x.mul(1)))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),vM=Ed(([e,t,s])=>{const i=Gd(e).toVar(),r=Dd(1.4).toVar(),n=Dd(0).toVar(),o=Gd(i).toVar();return C_({start:Dd(0),end:Dd(3),type:"float",condition:"<="},()=>{const e=Gd(wM(o.mul(2))).toVar();i.addAssign(e.add(s.mul(Dd(.1).mul(t)))),o.mulAssign(1.8),r.mulAssign(1.5),i.mulAssign(1.2);const a=Dd(_M(i.z.add(_M(i.x.add(_M(i.y)))))).toVar();n.addAssign(a.div(r)),o.addAssign(.14)}),n}).setLayout({name:"triNoise3D",type:"float",inputs:[{name:"position",type:"vec3"},{name:"speed",type:"float"},{name:"time",type:"float"}]});class TM extends Cc{static get type(){return"FunctionOverloadingNode"}constructor(e=[],...t){super(),this.functionNodes=e,this.parametersNodes=t,this._candidateFn=null,this.global=!0}getNodeType(e){return this.getCandidateFn(e).shaderNode.layout.type}getCandidateFn(e){const t=this.parametersNodes;let s=this._candidateFn;if(null===s){let i=null,r=-1;for(const s of this.functionNodes){const n=s.shaderNode.layout;if(null===n)throw new Error("FunctionOverloadingNode: FunctionNode must be a layout.");const o=n.inputs;if(t.length===o.length){let n=0;for(let s=0;s<t.length;s++){const i=t[s],r=o[s];i.getNodeType(e)===r.type&&n++}n>r&&(i=s,r=n)}}this._candidateFn=s=i}return s}setup(e){return this.getCandidateFn(e)(...this.parametersNodes)}}const SM=Td(TM),MM=e=>(...t)=>SM(e,...t),AM=Up(0).setGroup(Vp).onRenderUpdate(e=>e.time),NM=Up(0).setGroup(Vp).onRenderUpdate(e=>e.deltaTime),EM=Up(0,"uint").setGroup(Vp).onRenderUpdate(e=>e.frameId);const CM=Ed(([e,t,s=Vd(.5)])=>ZT(e.sub(s),t).add(s)),RM=Ed(([e,t,s=Vd(.5)])=>{const i=e.sub(s),r=i.dot(i),n=r.mul(r).mul(t);return e.add(i.mul(n))}),PM=Ed(({position:e=null,horizontal:t=!0,vertical:s=!1})=>{let i;null!==e?(i=Uy.toVar(),i[3][0]=e.x,i[3][1]=e.y,i[3][2]=e.z):i=Uy;const r=Ay.mul(i);return gd(t)&&(r[0][0]=Uy[0].length(),r[0][1]=0,r[0][2]=0),gd(s)&&(r[1][0]=0,r[1][1]=Uy[1].length(),r[1][2]=0),r[2][0]=0,r[2][1]=0,r[2][2]=1,Sy.mul(r).mul(Jy)}),BM=Ed(([e=null])=>{const t=tw();return tw(q_(e)).sub(t).lessThan(0).select(py,e)});class IM extends Cc{static get type(){return"SpriteSheetUVNode"}constructor(e,t=qg(),s=Dd(0)){super("vec2"),this.countNode=e,this.uvNode=t,this.frameNode=s}setup(){const{frameNode:e,uvNode:t,countNode:s}=this,{width:i,height:r}=s,n=e.mod(i.mul(r)).floor(),o=n.mod(i),a=r.sub(n.add(1).div(i).ceil()),l=s.reciprocal(),h=Vd(o,a);return t.add(h).mul(l)}}const DM=Td(IM).setParameterLength(3),LM=Ed(([e,t=null,s=null,i=Dd(1),r=Jy,n=ux])=>{let o=n.abs().normalize();o=o.div(o.dot(Gd(1)));const a=r.yz.mul(i),l=r.zx.mul(i),h=r.xy.mul(i),u=e.value,c=null!==t?t.value:u,d=null!==s?s.value:u,p=ty(u,a).mul(o.x),m=ty(c,l).mul(o.y),f=ty(d,h).mul(o.z);return Zp(p,m,f)}),FM=new hu,OM=new da,VM=new da,zM=new da,kM=new ll,UM=new da(0,0,-1),GM=new Pa,jM=new da,$M=new da,WM=new Pa,HM=new ua,qM=new Ba,XM=py.flipX();qM.depthTexture=new _u(1,1);let YM=!1;class ZM extends Jg{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||qM.texture,XM),this._reflectorBaseNode=e.reflector||new QM(this,e),this._depthNode=null,this.setUpdateMatrix(!1)}get reflector(){return this._reflectorBaseNode}get target(){return this._reflectorBaseNode.target}getDepthNode(){if(null===this._depthNode){if(!0!==this._reflectorBaseNode.depth)throw new Error("THREE.ReflectorNode: Depth node can only be requested when the reflector is created with { depth: true }. ");this._depthNode=bd(new ZM({defaultTexture:qM.depthTexture,reflector:this._reflectorBaseNode}))}return this._depthNode}setup(e){return e.object.isQuadMesh||this._reflectorBaseNode.build(e),super.setup(e)}clone(){const e=new this.constructor(this.reflectorNode);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e._reflectorBaseNode=this._reflectorBaseNode,e}dispose(){super.dispose(),this._reflectorBaseNode.dispose()}}class QM extends Cc{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:s=new Ll,resolutionScale:i=1,generateMipmaps:r=!1,bounces:n=!0,depth:o=!1,samples:a=0}=t;this.textureNode=e,this.target=s,this.resolutionScale=i,void 0!==t.resolution&&(Qo('ReflectorNode: The "resolution" parameter has been renamed to "resolutionScale".'),this.resolutionScale=t.resolution),this.generateMipmaps=r,this.bounces=n,this.depth=o,this.samples=a,this.updateBeforeType=n?wc.RENDER:wc.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const s=this.resolutionScale;t.getDrawingBufferSize(HM),e.setSize(Math.round(HM.width*s),Math.round(HM.height*s))}setup(e){return this._updateResolution(qM,e.renderer),super.setup(e)}dispose(){super.dispose();for(const e of this.renderTargets.values())e.dispose()}getVirtualCamera(e){let t=this.virtualCameras.get(e);return void 0===t&&(t=e.clone(),this.virtualCameras.set(e,t)),t}getRenderTarget(e){let t=this.renderTargets.get(e);return void 0===t&&(t=new Ba(0,0,{type:En,samples:this.samples}),!0===this.generateMipmaps&&(t.texture.minFilter=1008,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new _u),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&YM)return!1;YM=!0;const{scene:t,camera:s,renderer:i,material:r}=e,{target:n}=this,o=this.getVirtualCamera(s),a=this.getRenderTarget(o);i.getDrawingBufferSize(HM),this._updateResolution(a,i),VM.setFromMatrixPosition(n.matrixWorld),zM.setFromMatrixPosition(s.matrixWorld),kM.extractRotation(n.matrixWorld),OM.set(0,0,1),OM.applyMatrix4(kM),jM.subVectors(VM,zM);let l=!1;if(!0===jM.dot(OM)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(YM=!1);l=!0}jM.reflect(OM).negate(),jM.add(VM),kM.extractRotation(s.matrixWorld),UM.set(0,0,-1),UM.applyMatrix4(kM),UM.add(zM),$M.subVectors(VM,UM),$M.reflect(OM).negate(),$M.add(VM),o.coordinateSystem=s.coordinateSystem,o.position.copy(jM),o.up.set(0,1,0),o.up.applyMatrix4(kM),o.up.reflect(OM),o.lookAt($M),o.near=s.near,o.far=s.far,o.updateMatrixWorld(),o.projectionMatrix.copy(s.projectionMatrix),FM.setFromNormalAndCoplanarPoint(OM,VM),FM.applyMatrix4(o.matrixWorldInverse),GM.set(FM.normal.x,FM.normal.y,FM.normal.z,FM.constant);const h=o.projectionMatrix;WM.x=(Math.sign(GM.x)+h.elements[8])/h.elements[0],WM.y=(Math.sign(GM.y)+h.elements[9])/h.elements[5],WM.z=-1,WM.w=(1+h.elements[10])/h.elements[14],GM.multiplyScalar(1/GM.dot(WM));h.elements[2]=GM.x,h.elements[6]=GM.y,h.elements[10]=i.coordinateSystem===Uo?GM.z-0:GM.z+1-0,h.elements[14]=GM.w,this.textureNode.value=a.texture,!0===this.depth&&(this.textureNode.getDepthNode().value=a.depthTexture),r.visible=!1;const u=i.getRenderTarget(),c=i.getMRT(),d=i.autoClear;i.setMRT(null),i.setRenderTarget(a),i.autoClear=!0;const p=t.name;t.name=(t.name||"Scene")+" [ Reflector ]",l?(i.clear(),this.hasOutput=!1):(i.render(t,o),this.hasOutput=!0),t.name=p,i.setMRT(c),i.setRenderTarget(u),i.autoClear=d,r.visible=!0,YM=!1,this.forceUpdate=!1}get resolution(){return Qo('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale}set resolution(e){Qo('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale=e}}const KM=new $u(-1,1,1,-1,0,1);class JM extends Sh{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new gh([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new gh(t,2))}}const eA=new JM;class tA extends Fh{constructor(e=null){super(eA,e),this.camera=KM,this.isQuadMesh=!0}async renderAsync(e){Qo('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,KM)}render(e){e.render(this,KM)}}const sA=new ua;class iA extends Jg{static get type(){return"RTTNode"}constructor(e,t=null,s=null,i={type:En}){const r=new Ba(t,s,i);super(r.texture,qg()),this.isRTTNode=!0,this.node=e,this.width=t,this.height=s,this.pixelRatio=1,this.renderTarget=r,this.textureNeedsUpdate=!0,this.autoUpdate=!0,this._rttNode=null,this._quadMesh=new tA(new gw),this.updateBeforeType=wc.RENDER}get autoResize(){return null===this.width}setup(e){return this._rttNode=this.node.context(e.getSharedContext()),this._quadMesh.material.name="RTT",this._quadMesh.material.needsUpdate=!0,super.setup(e)}setSize(e,t){this.width=e,this.height=t;const s=e*this.pixelRatio,i=t*this.pixelRatio;this.renderTarget.setSize(s,i),this.textureNeedsUpdate=!0}setPixelRatio(e){this.pixelRatio=e,this.setSize(this.width,this.height)}updateBefore({renderer:e}){if(!1===this.textureNeedsUpdate&&!1===this.autoUpdate)return;if(this.textureNeedsUpdate=!1,!0===this.autoResize){const t=e.getPixelRatio(),s=e.getSize(sA),i=Math.floor(s.width*t),r=Math.floor(s.height*t);i===this.renderTarget.width&&r===this.renderTarget.height||(this.renderTarget.setSize(i,r),this.textureNeedsUpdate=!0)}let t="RTT";this.node.name&&(t=this.node.name+" [ "+t+" ]"),this._quadMesh.material.fragmentNode=this._rttNode,this._quadMesh.name=t;const s=e.getRenderTarget();e.setRenderTarget(this.renderTarget),this._quadMesh.render(e),e.setRenderTarget(s)}clone(){const e=new Jg(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const rA=(e,...t)=>bd(new iA(bd(e),...t)),nA=Ed(([e,t,s],i)=>{let r;i.renderer.coordinateSystem===Uo?(e=Vd(e.x,e.y.oneMinus()).mul(2).sub(1),r=Hd(Gd(e,t),1)):r=Hd(Gd(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=Hd(s.mul(r));return n.xyz.div(n.w)}),oA=Ed(([e,t])=>{const s=t.mul(Hd(e,1)),i=s.xy.div(s.w).mul(.5).add(.5).toVar();return Vd(i.x,i.y.oneMinus())}),aA=Ed(([e,t,s])=>{const i=Yg(sy(t)),r=zd(e.mul(i)).toVar(),n=sy(t,r).toVar(),o=sy(t,r.sub(zd(2,0))).toVar(),a=sy(t,r.sub(zd(1,0))).toVar(),l=sy(t,r.add(zd(1,0))).toVar(),h=sy(t,r.add(zd(2,0))).toVar(),u=sy(t,r.add(zd(0,2))).toVar(),c=sy(t,r.add(zd(0,1))).toVar(),d=sy(t,r.sub(zd(0,1))).toVar(),p=sy(t,r.sub(zd(0,2))).toVar(),m=Ym(Qp(Dd(2).mul(a).sub(o),n)).toVar(),f=Ym(Qp(Dd(2).mul(l).sub(h),n)).toVar(),g=Ym(Qp(Dd(2).mul(c).sub(u),n)).toVar(),y=Ym(Qp(Dd(2).mul(d).sub(p),n)).toVar(),x=nA(e,n,s).toVar(),b=m.lessThan(f).select(x.sub(nA(e.sub(Vd(Dd(1).div(i.x),0)),a,s)),x.negate().add(nA(e.add(Vd(Dd(1).div(i.x),0)),l,s))),_=g.lessThan(y).select(x.sub(nA(e.add(Vd(0,Dd(1).div(i.y))),c,s)),x.negate().add(nA(e.sub(Vd(0,Dd(1).div(i.y))),d,s)));return Um(xf(b,_))}),lA=Ed(([e])=>Gm(Dd(52.9829189).mul(Gm(yf(e,Vd(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),hA=Ed(([e,t,s])=>{const i=Dd(2.399963229728653),r=Om(Dd(e).add(.5).div(Dd(t))),n=Dd(e).mul(i).add(s);return Vd($m(n),jm(n)).mul(r)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class uA extends Cc{static get type(){return"SampleNode"}constructor(e,t=null){super(),this.callback=e,this.uvNode=t,this.isSampleNode=!0}setup(){return this.sample(qg())}sample(e){return this.callback(e)}}class cA extends Cc{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===cA.OBJECT?this.updateType=wc.OBJECT:e===cA.MATERIAL?this.updateType=wc.RENDER:e===cA.BEFORE_OBJECT?this.updateBeforeType=wc.OBJECT:e===cA.BEFORE_MATERIAL&&(this.updateBeforeType=wc.RENDER)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}cA.OBJECT="object",cA.MATERIAL="material",cA.BEFORE_OBJECT="beforeObject",cA.BEFORE_MATERIAL="beforeMaterial";const dA=(e,t)=>new cA(e,t).toStack();class pA extends nu{constructor(e,t,s=Float32Array){super(ArrayBuffer.isView(e)?e:new s(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class mA extends dh{constructor(e,t,s=Float32Array){super(ArrayBuffer.isView(e)?e:new s(e*t),t),this.isStorageBufferAttribute=!0}}class fA extends Cc{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const gA=Sd(fA),yA=new xl,xA=new ll;class bA extends Cc{static get type(){return"SceneNode"}constructor(e=bA.BACKGROUND_BLURRINESS,t=null){super(),this.scope=e,this.scene=t}setup(e){const t=this.scope,s=null!==this.scene?this.scene:e.scene;let i;return t===bA.BACKGROUND_BLURRINESS?i=Ox("backgroundBlurriness","float",s):t===bA.BACKGROUND_INTENSITY?i=Ox("backgroundIntensity","float",s):t===bA.BACKGROUND_ROTATION?i=Up("mat4").setName("backgroundRotation").setGroup(Vp).onRenderUpdate(()=>{const e=s.background;return null!==e&&e.isTexture&&300!==e.mapping?(yA.copy(s.backgroundRotation),yA.x*=-1,yA.y*=-1,yA.z*=-1,xA.makeRotationFromEuler(yA)):xA.identity(),xA}):Zo("SceneNode: Unknown scope:",t),i}}bA.BACKGROUND_BLURRINESS="backgroundBlurriness",bA.BACKGROUND_INTENSITY="backgroundIntensity",bA.BACKGROUND_ROTATION="backgroundRotation";const _A=Sd(bA,bA.BACKGROUND_BLURRINESS),wA=Sd(bA,bA.BACKGROUND_INTENSITY),vA=Sd(bA,bA.BACKGROUND_ROTATION);class TA extends Jg{static get type(){return"StorageTextureNode"}constructor(e,t,s=null){super(e,t),this.storeNode=s,this.mipLevel=0,this.isStorageTextureNode=!0,this.access=vc.WRITE_ONLY}getInputType(){return"storageTexture"}setup(e){super.setup(e);const t=e.getNodeProperties(this);return t.storeNode=this.storeNode,t}setAccess(e){return this.access=e,this}setMipLevel(e){return this.mipLevel=e,this}generate(e,t){let s;return s=null!==this.storeNode?this.generateStore(e):super.generate(e,t),s}toReadWrite(){return this.setAccess(vc.READ_WRITE)}toReadOnly(){return this.setAccess(vc.READ_ONLY)}toWriteOnly(){return this.setAccess(vc.WRITE_ONLY)}generateStore(e){const t=e.getNodeProperties(this),{uvNode:s,storeNode:i,depthNode:r}=t,n=super.generate(e,"property"),o=s.build(e,!0===this.value.is3DTexture?"uvec3":"uvec2"),a=i.build(e,"vec4"),l=r?r.build(e,"int"):null,h=e.generateTextureStore(e,n,o,l,a);e.addLineFlowCode(h,this)}clone(){const e=super.clone();return e.storeNode=this.storeNode,e.mipLevel=this.mipLevel,e}}const SA=Td(TA).setParameterLength(1,3),MA=Ed(({texture:e,uv:t})=>{const s=1e-4,i=Gd().toVar();return Pd(t.x.lessThan(s),()=>{i.assign(Gd(1,0,0))}).ElseIf(t.y.lessThan(s),()=>{i.assign(Gd(0,1,0))}).ElseIf(t.z.lessThan(s),()=>{i.assign(Gd(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{i.assign(Gd(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{i.assign(Gd(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{i.assign(Gd(0,0,-1))}).Else(()=>{const s=.01,r=e.sample(t.add(Gd(-.01,0,0))).r.sub(e.sample(t.add(Gd(s,0,0))).r),n=e.sample(t.add(Gd(0,-.01,0))).r.sub(e.sample(t.add(Gd(0,s,0))).r),o=e.sample(t.add(Gd(0,0,-.01))).r.sub(e.sample(t.add(Gd(0,0,s))).r);i.assign(Gd(r,n,o))}),i.normalize()});class AA extends Jg{static get type(){return"Texture3DNode"}constructor(e,t=null,s=null){super(e,t,s),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return Gd(.5,.5,.5)}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return!e.isFlipY()||!0!==s.isRenderTargetTexture&&!0!==s.isFramebufferTexture||(t=this.sampler?t.flipY():t.setY(Ld(Yg(this,this.levelNode).y).sub(t.y).sub(1))),t}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}generateOffset(e,t){return t.build(e,"ivec3")}normal(e){return MA({texture:this,uv:e})}}const NA=Td(AA).setParameterLength(1,3);class EA extends Fx{static get type(){return"UserDataNode"}constructor(e,t,s=null){super(e,t,s),this.userData=s}updateReference(e){return this.reference=null!==this.userData?this.userData:e.object.userData,this.reference}}const CA=new WeakMap;class RA extends Bc{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=wc.OBJECT,this.updateAfterType=wc.OBJECT,this.previousModelWorldMatrix=Up(new ll),this.previousProjectionMatrix=Up(new ll).setGroup(Vp),this.previousCameraViewMatrix=Up(new ll)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:s}){const i=BA(s);this.previousModelWorldMatrix.value.copy(i);const r=PA(t);r.frameId!==e&&(r.frameId=e,void 0===r.previousProjectionMatrix?(r.previousProjectionMatrix=new ll,r.previousCameraViewMatrix=new ll,r.currentProjectionMatrix=new ll,r.currentCameraViewMatrix=new ll,r.previousProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),r.previousCameraViewMatrix.copy(t.matrixWorldInverse)):(r.previousProjectionMatrix.copy(r.currentProjectionMatrix),r.previousCameraViewMatrix.copy(r.currentCameraViewMatrix)),r.currentProjectionMatrix.copy(this.projectionMatrix||t.projectionMatrix),r.currentCameraViewMatrix.copy(t.matrixWorldInverse),this.previousProjectionMatrix.value.copy(r.previousProjectionMatrix),this.previousCameraViewMatrix.value.copy(r.previousCameraViewMatrix))}updateAfter({object:e}){BA(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?Sy:Up(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),s=e.mul(Xy).mul(Jy),i=this.previousProjectionMatrix.mul(t).mul(ex),r=s.xy.div(s.w),n=i.xy.div(i.w);return Qp(r,n)}}function PA(e){let t=CA.get(e);return void 0===t&&(t={},CA.set(e,t)),t}function BA(e,t=0){const s=PA(e);let i=s[t];return void 0===i&&(s[t]=i=new ll,s[t].copy(e.matrixWorld)),i}const IA=Sd(RA),DA=Ed(([e])=>VA(e.rgb)),LA=Ed(([e,t=Dd(1)])=>t.mix(VA(e.rgb),e.rgb)),FA=Ed(([e,t=Dd(1)])=>{const s=Zp(e.r,e.g,e.b).div(3),i=e.r.max(e.g.max(e.b)),r=i.sub(s).mul(t).mul(-3);return Af(e.rgb,i,r)}),OA=Ed(([e,t=Dd(1)])=>{const s=Gd(.57735,.57735,.57735),i=t.cos();return Gd(e.rgb.mul(i).add(s.cross(e.rgb).mul(t.sin()).add(s.mul(yf(s,e.rgb).mul(i.oneMinus())))))}),VA=(e,t=Gd(_a.getLuminanceCoefficients(new da)))=>yf(e,t),zA=Ed(([e,t=Gd(1),s=Gd(0),i=Gd(1),r=Dd(1),n=Gd(_a.getLuminanceCoefficients(new da,Ao))])=>{const o=e.rgb.dot(Gd(n)),a=df(e.rgb.mul(t).add(s),0).toVar(),l=a.pow(i).toVar();return Pd(a.r.greaterThan(0),()=>{a.r.assign(l.r)}),Pd(a.g.greaterThan(0),()=>{a.g.assign(l.g)}),Pd(a.b.greaterThan(0),()=>{a.b.assign(l.b)}),a.assign(o.add(a.sub(o).mul(r))),Hd(a.rgb,e.a)});class kA extends Bc{static get type(){return"PosterizeNode"}constructor(e,t){super(),this.sourceNode=e,this.stepsNode=t}setup(){const{sourceNode:e,stepsNode:t}=this;return e.mul(t).floor().div(t)}}const UA=Td(kA).setParameterLength(2),GA=new ua;class jA extends Jg{static get type(){return"PassTextureNode"}constructor(e,t){super(t),this.passNode=e,this.setUpdateMatrix(!1)}setup(e){return this.passNode.build(e),super.setup(e)}clone(){return new this.constructor(this.passNode,this.value)}}class $A extends jA{static get type(){return"PassMultipleTextureNode"}constructor(e,t,s=!1){super(e,null),this.textureName=t,this.previousTexture=s}updateTexture(){this.value=this.previousTexture?this.passNode.getPreviousTexture(this.textureName):this.passNode.getTexture(this.textureName)}setup(e){return this.updateTexture(),super.setup(e)}clone(){const e=new this.constructor(this.passNode,this.textureName,this.previousTexture);return e.uvNode=this.uvNode,e.levelNode=this.levelNode,e.biasNode=this.biasNode,e.sampler=this.sampler,e.depthNode=this.depthNode,e.compareNode=this.compareNode,e.gradNode=this.gradNode,e.offsetNode=this.offsetNode,e}}class WA extends Bc{static get type(){return"PassNode"}constructor(e,t,s,i={}){super("vec4"),this.scope=e,this.scene=t,this.camera=s,this.options=i,this._pixelRatio=1,this._width=1,this._height=1;const r=new _u;r.isRenderTargetTexture=!0,r.name="depth";const n=new Ba(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:En,...i});n.texture.name="output",n.depthTexture=r,this.renderTarget=n,this.overrideMaterial=null,this.transparent=!0,this.opaque=!0,this.contextNode=null,this._contextNodeCache=null,this._textures={output:n.texture,depth:r},this._textureNodes={},this._linearDepthNodes={},this._viewZNodes={},this._previousTextures={},this._previousTextureNodes={},this._cameraNear=Up(0),this._cameraFar=Up(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=wc.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return Yo("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return Yo("PassNode: .getResolution() is deprecated. Use .getResolutionScale() instead."),this.getResolutionScale()}setLayers(e){return this._layers=e,this}getLayers(){return this._layers}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getTexture(e){let t=this._textures[e];if(void 0===t){t=this.renderTarget.texture.clone(),t.name=e,this._textures[e]=t,this.renderTarget.textures.push(t)}return t}getPreviousTexture(e){let t=this._previousTextures[e];return void 0===t&&(t=this.getTexture(e).clone(),this._previousTextures[e]=t),t}toggleTexture(e){const t=this._previousTextures[e];if(void 0!==t){const s=this._textures[e],i=this.renderTarget.textures.indexOf(s);this.renderTarget.textures[i]=t,this._textures[e]=t,this._previousTextures[e]=s,this._textureNodes[e].updateTexture(),this._previousTextureNodes[e].updateTexture()}}getTextureNode(e="output"){let t=this._textureNodes[e];return void 0===t&&(t=new $A(this,e),t.updateTexture(),this._textureNodes[e]=t),t}getPreviousTextureNode(e="output"){let t=this._previousTextureNodes[e];return void 0===t&&(void 0===this._textureNodes[e]&&this.getTextureNode(e),t=new $A(this,e,!0),t.updateTexture(),this._previousTextureNodes[e]=t),t}getViewZNode(e="depth"){let t=this._viewZNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar;this._viewZNodes[e]=t=Q_(this.getTextureNode(e),s,i)}return t}getLinearDepthNode(e="depth"){let t=this._linearDepthNodes[e];if(void 0===t){const s=this._cameraNear,i=this._cameraFar,r=this.getViewZNode(e);this._linearDepthNodes[e]=t=Y_(r,s,i)}return t}async compileAsync(e){const t=e.getRenderTarget(),s=e.getMRT();e.setRenderTarget(this.renderTarget),e.setMRT(this._mrt),await e.compileAsync(this.scene,this.camera),e.setRenderTarget(t),e.setMRT(s)}setup({renderer:e}){return this.renderTarget.samples=void 0===this.options.samples?e.samples:this.options.samples,this.renderTarget.texture.type=e.getOutputBufferType(),this.scope===WA.COLOR?this.getTextureNode():this.getLinearDepthNode()}updateBefore(e){const{renderer:t}=e,{scene:s}=this;let i,r;const n=t.getOutputRenderTarget();n&&!0===n.isXRRenderTarget?(r=1,i=t.xr.getCamera(),t.xr.updateCamera(i),GA.set(n.width,n.height)):(i=this.camera,r=t.getPixelRatio(),t.getSize(GA)),this._pixelRatio=r,this.setSize(GA.width,GA.height);const o=t.getRenderTarget(),a=t.getMRT(),l=t.autoClear,h=t.transparent,u=t.opaque,c=i.layers.mask,d=t.contextNode,p=s.overrideMaterial;this._cameraNear.value=i.near,this._cameraFar.value=i.far,null!==this._layers&&(i.layers.mask=this._layers.mask);for(const e in this._previousTextures)this.toggleTexture(e);null!==this.overrideMaterial&&(s.overrideMaterial=this.overrideMaterial),t.setRenderTarget(this.renderTarget),t.setMRT(this._mrt),t.autoClear=!0,t.transparent=this.transparent,t.opaque=this.opaque,null!==this.contextNode&&(null!==this._contextNodeCache&&this._contextNodeCache.version===this.version||(this._contextNodeCache={version:this.version,context:Gf({...t.contextNode.getFlowContextData(),...this.contextNode.getFlowContextData()})}),t.contextNode=this._contextNodeCache.context);const m=s.name;s.name=this.name?this.name:s.name,t.render(s,i),s.name=m,s.overrideMaterial=p,t.setRenderTarget(o),t.setMRT(a),t.autoClear=l,t.transparent=h,t.opaque=u,t.contextNode=d,i.layers.mask=c}setSize(e,t){this._width=e,this._height=t;const s=Math.floor(this._width*this._pixelRatio*this._resolutionScale),i=Math.floor(this._height*this._pixelRatio*this._resolutionScale);this.renderTarget.setSize(s,i),null!==this._scissor&&this.renderTarget.scissor.copy(this._scissor),null!==this._viewport&&this.renderTarget.viewport.copy(this._viewport)}setScissor(e,t,s,i){null===e?this._scissor=null:(null===this._scissor&&(this._scissor=new Pa),e.isVector4?this._scissor.copy(e):this._scissor.set(e,t,s,i),this._scissor.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setViewport(e,t,s,i){null===e?this._viewport=null:(null===this._viewport&&(this._viewport=new Pa),e.isVector4?this._viewport.copy(e):this._viewport.set(e,t,s,i),this._viewport.multiplyScalar(this._pixelRatio*this._resolutionScale).floor())}setPixelRatio(e){this._pixelRatio=e,this.setSize(this._width,this._height)}dispose(){this.renderTarget.dispose()}}WA.COLOR="color",WA.DEPTH="depth";class HA extends WA{static get type(){return"ToonOutlinePassNode"}constructor(e,t,s,i,r){super(WA.COLOR,e,t),this.colorNode=s,this.thicknessNode=i,this.alphaNode=r,this._materialCache=new WeakMap,this.name="Outline Pass"}updateBefore(e){const{renderer:t}=e,s=t.getRenderObjectFunction();t.setRenderObjectFunction((e,s,i,r,n,o,a,l)=>{if((n.isMeshToonMaterial||n.isMeshToonNodeMaterial)&&!1===n.wireframe){const h=this._getOutlineMaterial(n);t.renderObject(e,s,i,r,h,o,a,l)}t.renderObject(e,s,i,r,n,o,a,l)}),super.updateBefore(e),t.setRenderObjectFunction(s)}_createMaterial(){const e=new gw;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=1;const t=ux.negate(),s=Sy.mul(Xy),i=Dd(1),r=s.mul(Hd(Jy,1)),n=s.mul(Hd(Jy.add(t),1)),o=Um(r.sub(n));return e.vertexNode=r.add(o.mul(this.thicknessNode).mul(r.w).mul(i)),e.colorNode=Hd(this.colorNode,this.alphaNode),e}_getOutlineMaterial(e){let t=this._materialCache.get(e);return void 0===t&&(t=this._createMaterial(),this._materialCache.set(e,t)),t}}const qA=Ed(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),XA=Ed(([e,t])=>(e=e.mul(t)).div(e.add(1)).clamp()).setLayout({name:"reinhardToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),YA=Ed(([e,t])=>{const s=(e=(e=e.mul(t)).sub(.004).max(0)).mul(e.mul(6.2).add(.5)),i=e.mul(e.mul(6.2).add(1.7)).add(.06);return s.div(i).pow(2.2)}).setLayout({name:"cineonToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),ZA=Ed(([e])=>{const t=e.mul(e.add(.0245786)).sub(90537e-9),s=e.mul(e.add(.432951).mul(.983729)).add(.238081);return t.div(s)}),QA=Ed(([e,t])=>{const s=Qd(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=Qd(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=ZA(e),(e=i.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),KA=Qd(Gd(1.6605,-.1246,-.0182),Gd(-.5876,1.1329,-.1006),Gd(-.0728,-.0083,1.1187)),JA=Qd(Gd(.6274,.0691,.0164),Gd(.3293,.9195,.088),Gd(.0433,.0113,.8956)),eN=Ed(([e])=>{const t=Gd(e).toVar(),s=Gd(t.mul(t)).toVar(),i=Gd(s.mul(s)).toVar();return Dd(15.5).mul(i.mul(s)).sub(Kp(40.14,i.mul(t))).add(Kp(31.96,i).sub(Kp(6.868,s.mul(t))).add(Kp(.4298,s).add(Kp(.1191,t).sub(.00232))))}),tN=Ed(([e,t])=>{const s=Gd(e).toVar(),i=Qd(Gd(.856627153315983,.137318972929847,.11189821299995),Gd(.0951212405381588,.761241990602591,.0767994186031903),Gd(.0482516061458583,.101439036467562,.811302368396859)),r=Qd(Gd(1.1271005818144368,-.1413297634984383,-.14132976349843826),Gd(-.11060664309660323,1.157823702216272,-.11060664309660294),Gd(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=Dd(-12.47393),o=Dd(4.026069);return s.mulAssign(t),s.assign(JA.mul(s)),s.assign(i.mul(s)),s.assign(df(s,1e-10)),s.assign(Fm(s)),s.assign(s.sub(n).div(o.sub(n))),s.assign(Nf(s,0,1)),s.assign(eN(s)),s.assign(r.mul(s)),s.assign(bf(df(Gd(0),s),Gd(2.2))),s.assign(KA.mul(s)),s.assign(Nf(s,0,1)),s}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),sN=Ed(([e,t])=>{const s=Dd(.76),i=Dd(.15);e=e.mul(t);const r=cf(e.r,cf(e.g,e.b)),n=kf(r.lessThan(.08),r.sub(Kp(6.25,r.mul(r))),.04);e.subAssign(n);const o=df(e.r,df(e.g,e.b));Pd(o.lessThan(s),()=>e);const a=Qp(1,s),l=Qp(1,a.mul(a).div(o.add(a.sub(s))));e.mulAssign(l.div(o));const h=Qp(1,Jp(1,i.mul(o.sub(l)).add(1)));return Af(e,Gd(l),h)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class iN extends Cc{static get type(){return"CodeNode"}constructor(e="",t=[],s=""){super("code"),this.isCodeNode=!0,this.global=!0,this.code=e,this.includes=t,this.language=s}setIncludes(e){return this.includes=e,this}getIncludes(){return this.includes}generate(e){const t=this.getIncludes(e);for(const s of t)s.build(e);const s=e.getCodeFromNode(this,this.getNodeType(e));return s.code=this.code,s.code}serialize(e){super.serialize(e),e.code=this.code,e.language=this.language}deserialize(e){super.deserialize(e),this.code=e.code,this.language=e.language}}const rN=Td(iN).setParameterLength(1,3);class nN extends iN{static get type(){return"FunctionNode"}constructor(e="",t=[],s=""){super(e,t,s)}getNodeType(e){return this.getNodeFunction(e).type}getMemberType(e,t){const s=this.getNodeType(e);return e.getStructTypeNode(s).getMemberType(e,t)}getInputs(e){return this.getNodeFunction(e).inputs}getNodeFunction(e){const t=e.getDataFromNode(this);let s=t.nodeFunction;return void 0===s&&(s=e.parser.parseFunction(this.code),t.nodeFunction=s),s}generate(e,t){super.generate(e);const s=this.getNodeFunction(e),i=s.name,r=s.type,n=e.getCodeFromNode(this,r);""!==i&&(n.name=i);const o=e.getPropertyName(n),a=this.getNodeFunction(e).getCode(o);return n.code=a+"\n","property"===t?o:e.format(`${o}()`,r,t)}}const oN=(e,t=[],s="")=>{for(let e=0;e<t.length;e++){const s=t[e];"function"==typeof s&&(t[e]=s.functionNode)}const i=new nN(e,t,s),r=(...e)=>i.call(...e);return r.functionNode=i,r};class aN extends Cc{static get type(){return"ScriptableValueNode"}constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outputType=null,this.events=new Ko,this.isScriptableValueNode=!0}get isScriptableOutputNode(){return null!==this.outputType}set value(e){this._value!==e&&(this._cache&&"URL"===this.inputType&&this.value.value instanceof ArrayBuffer&&(URL.revokeObjectURL(this._cache),this._cache=null),this._value=e,this.events.dispatchEvent({type:"change"}),this.refresh())}get value(){return this._value}refresh(){this.events.dispatchEvent({type:"refresh"})}getValue(){const e=this.value;if(e&&null===this._cache&&"URL"===this.inputType&&e.value instanceof ArrayBuffer)this._cache=URL.createObjectURL(new Blob([e.value]));else if(e&&null!==e.value&&void 0!==e.value&&(("URL"===this.inputType||"String"===this.inputType)&&"string"==typeof e.value||"Number"===this.inputType&&"number"==typeof e.value||"Vector2"===this.inputType&&e.value.isVector2||"Vector3"===this.inputType&&e.value.isVector3||"Vector4"===this.inputType&&e.value.isVector4||"Color"===this.inputType&&e.value.isColor||"Matrix3"===this.inputType&&e.value.isMatrix3||"Matrix4"===this.inputType&&e.value.isMatrix4))return e.value;return this._cache||e}getNodeType(e){return this.value&&this.value.isNode?this.value.getNodeType(e):"float"}setup(){return this.value&&this.value.isNode?this.value:Dd()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=xc(this.value):e.value=this.value?this.value.toJSON(e.meta).uuid:null:e.value=null,e.inputType=this.inputType,e.outputType=this.outputType}deserialize(e){super.deserialize(e);let t=null;null!==e.value&&(t="ArrayBuffer"===e.inputType?bc(e.value):"Texture"===e.inputType?e.meta.textures[e.value]:e.meta.nodes[e.value]||null),this.value=t,this.inputType=e.inputType,this.outputType=e.outputType}}const lN=Td(aN).setParameterLength(1);class hN extends Map{get(e,t=null,...s){if(this.has(e))return super.get(e);if(null!==t){const i=t(...s);return this.set(e,i),i}}}class uN{constructor(e){this.scriptableNode=e}get parameters(){return this.scriptableNode.parameters}get layout(){return this.scriptableNode.getLayout()}getInputLayout(e){return this.scriptableNode.getInputLayout(e)}get(e){const t=this.parameters[e];return t?t.getValue():null}}const cN=new hN;class dN extends Cc{static get type(){return"ScriptableNode"}constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new hN,this._output=lN(null),this._outputs={},this._source=this.source,this._method=null,this._object=null,this._value=null,this._needsOutputUpdate=!0,this.onRefresh=this.onRefresh.bind(this),this.isScriptableNode=!0}get source(){return this.codeNode?this.codeNode.code:""}setLocal(e,t){return this._local.set(e,t)}getLocal(e){return this._local.get(e)}onRefresh(){this._refresh()}getInputLayout(e){for(const t of this.getLayout())if(t.inputType&&(t.id===e||t.name===e))return t}getOutputLayout(e){for(const t of this.getLayout())if(t.outputType&&(t.id===e||t.name===e))return t}setOutput(e,t){const s=this._outputs;return void 0===s[e]?s[e]=lN(t):s[e].value=t,this}getOutput(e){return this._outputs[e]}getParameter(e){return this.parameters[e]}setParameter(e,t){const s=this.parameters;return t&&t.isScriptableNode?(this.deleteParameter(e),s[e]=t,s[e].getDefaultOutput().events.addEventListener("refresh",this.onRefresh)):t&&t.isScriptableValueNode?(this.deleteParameter(e),s[e]=t,s[e].events.addEventListener("refresh",this.onRefresh)):void 0===s[e]?(s[e]=lN(t),s[e].events.addEventListener("refresh",this.onRefresh)):s[e].value=t,this}getValue(){return this.getDefaultOutput().getValue()}deleteParameter(e){let t=this.parameters[e];return t&&(t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.removeEventListener("refresh",this.onRefresh)),this}clearParameters(){for(const e of Object.keys(this.parameters))this.deleteParameter(e);return this.needsUpdate=!0,this}call(e,...t){const s=this.getObject()[e];if("function"==typeof s)return s(...t)}async callAsync(e,...t){const s=this.getObject()[e];if("function"==typeof s)return"AsyncFunction"===s.constructor.name?await s(...t):s(...t)}getNodeType(e){return this.getDefaultOutputNode().getNodeType(e)}refresh(e=null){null!==e?this.getOutput(e).refresh():this._refresh()}getObject(){if(this.needsUpdate&&this.dispose(),null!==this._object)return this._object;const e=new uN(this),t=cN.get("THREE"),s=cN.get("TSL"),i=this.getMethod(),r=[e,this._local,cN,()=>this.refresh(),(e,t)=>this.setOutput(e,t),t,s];this._object=i(...r);const n=this._object.layout;if(n&&(!1===n.cache&&this._local.clear(),this._output.outputType=n.outputType||null,Array.isArray(n.elements)))for(const e of n.elements){const t=e.id||e.name;e.inputType&&(void 0===this.getParameter(t)&&this.setParameter(t,null),this.getParameter(t).inputType=e.inputType),e.outputType&&(void 0===this.getOutput(t)&&this.setOutput(t,null),this.getOutput(t).outputType=e.outputType)}return this._object}deserialize(e){super.deserialize(e);for(const e in this.parameters){let t=this.parameters[e];t.isScriptableNode&&(t=t.getDefaultOutput()),t.events.addEventListener("refresh",this.onRefresh)}}getLayout(){return this.getObject().layout}getDefaultOutputNode(){const e=this.getDefaultOutput().value;return e&&e.isNode?e:Dd()}getDefaultOutput(){return this._exec()._output}getMethod(){if(this.needsUpdate&&this.dispose(),null!==this._method)return this._method;const e=["layout","init","main","dispose"].join(", "),t="\nreturn { ...output, "+e+" };",s="var "+e+"; var output = {};\n"+this.codeNode.code+t;return this._method=new Function(...["parameters","local","global","refresh","setOutput","THREE","TSL"],s),this._method}dispose(){null!==this._method&&(this._object&&"function"==typeof this._object.dispose&&this._object.dispose(),this._method=null,this._object=null,this._source=null,this._value=null,this._needsOutputUpdate=!0,this._output.value=null,this._outputs={})}setup(){return this.getDefaultOutputNode()}getCacheKey(e){const t=[nc(this.source),this.getDefaultOutputNode().getCacheKey(e)];for(const s in this.parameters)t.push(this.parameters[s].getCacheKey(e));return oc(t)}set needsUpdate(e){!0===e&&this.dispose()}get needsUpdate(){return this.source!==this._source}_exec(){return null===this.codeNode||(!0===this._needsOutputUpdate&&(this._value=this.call("main"),this._needsOutputUpdate=!1),this._output.value=this._value),this}_refresh(){this.needsUpdate=!0,this._exec(),this._output.refresh()}}const pN=Td(dN).setParameterLength(1,2);function mN(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||ix.z).negate()}const fN=Ed(([e,t],s)=>{const i=mN(s);return Rf(e,t,i)}),gN=Ed(([e],t)=>{const s=mN(t);return e.mul(e,s,s).negate().exp().oneMinus()}),yN=Ed(([e,t])=>Hd(t.toFloat().mix(Sp.rgb,e.toVec3()),Sp.a));let xN=null,bN=null;class _N extends Cc{static get type(){return"RangeNode"}constructor(e=Dd(),t=Dd()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=this.getConstNode(this.minNode),s=this.getConstNode(this.maxNode),i=e.getTypeLength(fc(t.value)),r=e.getTypeLength(fc(s.value));return i>r?i:r}getNodeType(e){return e.object.count>1?e.getTypeFromLength(this.getVectorLength(e)):"float"}getConstNode(e){let t=null;if(e.traverse(e=>{!0===e.isConstNode&&(t=e)}),null===t)throw new Error('THREE.TSL: No "ConstNode" found in node graph.');return t}setup(e){const t=e.object;let s=null;if(t.count>1){const i=this.getConstNode(this.minNode),r=this.getConstNode(this.maxNode),n=i.value,o=r.value,a=e.getTypeLength(fc(n)),l=e.getTypeLength(fc(o));xN=xN||new Pa,bN=bN||new Pa,xN.setScalar(0),bN.setScalar(0),1===a?xN.setScalar(n):n.isColor?xN.set(n.r,n.g,n.b,1):xN.set(n.x,n.y,n.z||0,n.w||0),1===l?bN.setScalar(o):o.isColor?bN.set(o.r,o.g,o.b,1):bN.set(o.x,o.y,o.z||0,o.w||0);const h=4,u=h*t.count,c=new Float32Array(u);for(let e=0;e<u;e++){const t=e%h,s=xN.getComponent(t),i=bN.getComponent(t);c[e]=ha.lerp(s,i,Math.random())}const d=this.getNodeType(e);if(t.count<=4096)s=ry(c,"vec4",t.count).element(m_).convert(d);else{const t=new nu(c,4);e.geometry.setAttribute("__range"+this.id,t),s=vg(t).convert(d)}}else s=Dd(0);return s}}const wN=Td(_N).setParameterLength(2);class vN extends Cc{static get type(){return"ComputeBuiltinNode"}constructor(e,t){super(t),this._builtinName=e}getHash(e){return this.getBuiltinName(e)}getNodeType(){return this.nodeType}setBuiltinName(e){return this._builtinName=e,this}getBuiltinName(){return this._builtinName}hasBuiltin(e){return e.hasBuiltin(this._builtinName)}generate(e,t){const s=this.getBuiltinName(e),i=this.getNodeType(e);return"compute"===e.shaderStage?e.format(s,i,t):(Yo(`ComputeBuiltinNode: Compute built-in value ${s} can not be accessed in the ${e.shaderStage} stage`),e.generateConst(i))}serialize(e){super.serialize(e),e.global=this.global,e._builtinName=this._builtinName}deserialize(e){super.deserialize(e),this.global=e.global,this._builtinName=e._builtinName}}const TN=(e,t)=>new vN(e,t),SN=TN("numWorkgroups","uvec3"),MN=TN("workgroupId","uvec3"),AN=TN("globalId","uvec3"),NN=TN("localId","uvec3"),EN=TN("subgroupSize","uint");const CN=Td(class extends Cc{constructor(e){super(),this.scope=e}generate(e){const{scope:t}=this,{renderer:s}=e;!0===s.backend.isWebGLBackend?e.addFlowCode(`\t// ${t}Barrier \n`):e.addLineFlowCode(`${t}Barrier()`,this)}});class RN extends Rc{constructor(e,t){super(e,t),this.isWorkgroupInfoElementNode=!0}generate(e,t){let s;const i=e.context.assign;if(s=super.generate(e),!0!==i){const i=this.getNodeType(e);s=e.format(s,i,t)}return s}}class PN extends Cc{constructor(e,t,s=0){super(t),this.bufferType=t,this.bufferCount=s,this.isWorkgroupInfoNode=!0,this.elementType=t,this.scope=e,this.name=""}setName(e){return this.name=e,this}label(e){return Yo('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setScope(e){return this.scope=e,this}getElementType(){return this.elementType}getInputType(){return`${this.scope}Array`}element(e){return new RN(this,e)}generate(e){const t=""!==this.name?this.name:`${this.scope}Array_${this.id}`;return e.getScopedArray(t,this.scope.toLowerCase(),this.bufferType,this.bufferCount)}}class BN extends Cc{static get type(){return"AtomicFunctionNode"}constructor(e,t,s){super("uint"),this.method=e,this.pointerNode=t,this.valueNode=s,this.parents=!0}getInputType(e){return this.pointerNode.getNodeType(e)}getNodeType(e){return this.getInputType(e)}generate(e){const t=e.getNodeProperties(this),s=t.parents,i=this.method,r=this.getNodeType(e),n=this.getInputType(e),o=this.pointerNode,a=this.valueNode,l=[];l.push(`&${o.build(e,n)}`),null!==a&&l.push(a.build(e,n));const h=`${e.getMethod(i,r)}( ${l.join(", ")} )`;if(!(!!s&&(1===s.length&&!0===s[0].isStackNode)))return void 0===t.constNode&&(t.constNode=Fg(h,r).toConst()),t.constNode.build(e);e.addLineFlowCode(h,this)}}BN.ATOMIC_LOAD="atomicLoad",BN.ATOMIC_STORE="atomicStore",BN.ATOMIC_ADD="atomicAdd",BN.ATOMIC_SUB="atomicSub",BN.ATOMIC_MAX="atomicMax",BN.ATOMIC_MIN="atomicMin",BN.ATOMIC_AND="atomicAnd",BN.ATOMIC_OR="atomicOr",BN.ATOMIC_XOR="atomicXor";const IN=Td(BN),DN=(e,t,s)=>IN(e,t,s).toStack();class LN extends Bc{static get type(){return"SubgroupFunctionNode"}constructor(e,t=null,s=null){super(),this.method=e,this.aNode=t,this.bNode=s}getInputType(e){const t=this.aNode?this.aNode.getNodeType(e):null,s=this.bNode?this.bNode.getNodeType(e):null;return(e.isMatrix(t)?0:e.getTypeLength(t))>(e.isMatrix(s)?0:e.getTypeLength(s))?t:s}getNodeType(e){const t=this.method;return t===LN.SUBGROUP_ELECT?"bool":t===LN.SUBGROUP_BALLOT?"uvec4":this.getInputType(e)}generate(e,t){const s=this.method,i=this.getNodeType(e),r=this.getInputType(e),n=this.aNode,o=this.bNode,a=[];if(s===LN.SUBGROUP_BROADCAST||s===LN.SUBGROUP_SHUFFLE||s===LN.QUAD_BROADCAST){const t=o.getNodeType(e);a.push(n.build(e,i),o.build(e,"float"===t?"int":i))}else s===LN.SUBGROUP_SHUFFLE_XOR||s===LN.SUBGROUP_SHUFFLE_DOWN||s===LN.SUBGROUP_SHUFFLE_UP?a.push(n.build(e,i),o.build(e,"uint")):(null!==n&&a.push(n.build(e,r)),null!==o&&a.push(o.build(e,r)));const l=0===a.length?"()":`( ${a.join(", ")} )`;return e.format(`${e.getMethod(s,i)}${l}`,i,t)}serialize(e){super.serialize(e),e.method=this.method}deserialize(e){super.deserialize(e),this.method=e.method}}LN.SUBGROUP_ELECT="subgroupElect",LN.SUBGROUP_BALLOT="subgroupBallot",LN.SUBGROUP_ADD="subgroupAdd",LN.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",LN.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",LN.SUBGROUP_MUL="subgroupMul",LN.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",LN.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",LN.SUBGROUP_AND="subgroupAnd",LN.SUBGROUP_OR="subgroupOr",LN.SUBGROUP_XOR="subgroupXor",LN.SUBGROUP_MIN="subgroupMin",LN.SUBGROUP_MAX="subgroupMax",LN.SUBGROUP_ALL="subgroupAll",LN.SUBGROUP_ANY="subgroupAny",LN.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",LN.QUAD_SWAP_X="quadSwapX",LN.QUAD_SWAP_Y="quadSwapY",LN.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",LN.SUBGROUP_BROADCAST="subgroupBroadcast",LN.SUBGROUP_SHUFFLE="subgroupShuffle",LN.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",LN.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",LN.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",LN.QUAD_BROADCAST="quadBroadcast";const FN=Md(LN,LN.SUBGROUP_ELECT).setParameterLength(0),ON=Md(LN,LN.SUBGROUP_BALLOT).setParameterLength(1),VN=Md(LN,LN.SUBGROUP_ADD).setParameterLength(1),zN=Md(LN,LN.SUBGROUP_INCLUSIVE_ADD).setParameterLength(1),kN=Md(LN,LN.SUBGROUP_EXCLUSIVE_AND).setParameterLength(1),UN=Md(LN,LN.SUBGROUP_MUL).setParameterLength(1),GN=Md(LN,LN.SUBGROUP_INCLUSIVE_MUL).setParameterLength(1),jN=Md(LN,LN.SUBGROUP_EXCLUSIVE_MUL).setParameterLength(1),$N=Md(LN,LN.SUBGROUP_AND).setParameterLength(1),WN=Md(LN,LN.SUBGROUP_OR).setParameterLength(1),HN=Md(LN,LN.SUBGROUP_XOR).setParameterLength(1),qN=Md(LN,LN.SUBGROUP_MIN).setParameterLength(1),XN=Md(LN,LN.SUBGROUP_MAX).setParameterLength(1),YN=Md(LN,LN.SUBGROUP_ALL).setParameterLength(0),ZN=Md(LN,LN.SUBGROUP_ANY).setParameterLength(0),QN=Md(LN,LN.SUBGROUP_BROADCAST_FIRST).setParameterLength(2),KN=Md(LN,LN.QUAD_SWAP_X).setParameterLength(1),JN=Md(LN,LN.QUAD_SWAP_Y).setParameterLength(1),eE=Md(LN,LN.QUAD_SWAP_DIAGONAL).setParameterLength(1),tE=Md(LN,LN.SUBGROUP_BROADCAST).setParameterLength(2),sE=Md(LN,LN.SUBGROUP_SHUFFLE).setParameterLength(2),iE=Md(LN,LN.SUBGROUP_SHUFFLE_XOR).setParameterLength(2),rE=Md(LN,LN.SUBGROUP_SHUFFLE_UP).setParameterLength(2),nE=Md(LN,LN.SUBGROUP_SHUFFLE_DOWN).setParameterLength(2),oE=Md(LN,LN.QUAD_BROADCAST).setParameterLength(1);let aE;function lE(e){aE=aE||new WeakMap;let t=aE.get(e);return void 0===t&&aE.set(e,t={}),t}function hE(e){const t=lE(e);return t.shadowMatrix||(t.shadowMatrix=Up("mat4").setGroup(Vp).onRenderUpdate(t=>(!0===e.castShadow&&!1!==t.renderer.shadowMap.enabled||(e.shadow.camera.coordinateSystem!==t.camera.coordinateSystem&&(e.shadow.camera.coordinateSystem=t.camera.coordinateSystem,e.shadow.camera.updateProjectionMatrix()),e.shadow.updateMatrices(e)),e.shadow.matrix)))}function uE(e,t=tx){const s=hE(e).mul(t);return s.xyz.div(s.w)}function cE(e){const t=lE(e);return t.position||(t.position=Up(new da).setGroup(Vp).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld)))}function dE(e){const t=lE(e);return t.targetPosition||(t.targetPosition=Up(new da).setGroup(Vp).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld)))}function pE(e){const t=lE(e);return t.viewPosition||(t.viewPosition=Up(new da).setGroup(Vp).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new da,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const mE=e=>Ay.transformDirection(cE(e).sub(dE(e))),fE=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},gE=new WeakMap,yE=[];class xE extends Cc{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=sp("vec3","totalDiffuse"),this.totalSpecularNode=sp("vec3","totalSpecular"),this.outgoingLightNode=sp("vec3","outgoingLight"),this._lights=[],this._lightNodes=null,this._lightNodesHash=null,this.global=!0}customCacheKey(){const e=this._lights;for(let t=0;t<e.length;t++){const s=e[t];if(yE.push(s.id),yE.push(s.castShadow?1:0),!0===s.isSpotLight){const e=null!==s.map?s.map.id:-1,t=s.colorNode?s.colorNode.getCacheKey():-1;yE.push(e,t)}}const t=oc(yE);return yE.length=0,t}getHash(e){if(null===this._lightNodesHash){null===this._lightNodes&&this.setupLightsNode(e);const t=[];for(const e of this._lightNodes)t.push(e.getHash());this._lightNodesHash="lights-"+t.join(",")}return this._lightNodesHash}analyze(e){const t=e.getNodeProperties(this);for(const s of t.nodes)s.build(e);t.outputNode.build(e)}setupLightsNode(e){const t=[],s=this._lightNodes,i=(e=>e.sort((e,t)=>e.id-t.id))(this._lights),r=e.renderer.library;for(const e of i)if(e.isNode)t.push(bd(e));else{let i=null;if(null!==s&&(i=fE(e.id,s)),null===i){const s=r.getLightNodeClass(e.constructor);if(null===s){Yo(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;gE.has(e)?i=gE.get(e):(i=new s(e),gE.set(e,i)),t.push(i)}}this._lightNodes=t}setupDirectLight(e,t,s){const{lightingModel:i,reflectedLight:r}=e.context;i.direct({...s,lightNode:t,reflectedLight:r},e)}setupDirectRectAreaLight(e,t,s){const{lightingModel:i,reflectedLight:r}=e.context;i.directRectArea({...s,lightNode:t,reflectedLight:r},e)}setupLights(e,t){for(const s of t)s.build(e)}getLightNodes(e){return null===this._lightNodes&&this.setupLightsNode(e),this._lightNodes}setup(e){const t=e.lightsNode;e.lightsNode=this;let s=this.outgoingLightNode;const i=e.context,r=i.lightingModel,n=e.getNodeProperties(this);if(r){const{totalDiffuseNode:t,totalSpecularNode:o}=this;i.outgoingLight=s;const a=e.addStack();n.nodes=a.nodes,r.start(e);const{backdrop:l,backdropAlpha:h}=i,{directDiffuse:u,directSpecular:c,indirectDiffuse:d,indirectSpecular:p}=i.reflectedLight;let m=u.add(d);null!==l&&(m=Gd(null!==h?h.mix(m,l):l)),t.assign(m),o.assign(c.add(p)),s.assign(t.add(o)),r.finish(e),s=s.bypass(e.removeStack())}else n.nodes=[];return e.lightsNode=t,s}setLights(e){return this._lights=e,this._lightNodes=null,this._lightNodesHash=null,this}getLights(){return this._lights}get hasLights(){return this._lights.length>0}}class bE extends Cc{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=wc.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){_E.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||tx)}}const _E=sp("vec3","shadowPositionWorld");function wE(e,t){return t=function(e,t={}){return t.toneMapping=e.toneMapping,t.toneMappingExposure=e.toneMappingExposure,t.outputColorSpace=e.outputColorSpace,t.renderTarget=e.getRenderTarget(),t.activeCubeFace=e.getActiveCubeFace(),t.activeMipmapLevel=e.getActiveMipmapLevel(),t.renderObjectFunction=e.getRenderObjectFunction(),t.pixelRatio=e.getPixelRatio(),t.mrt=e.getMRT(),t.clearColor=e.getClearColor(t.clearColor||new eh),t.clearAlpha=e.getClearAlpha(),t.autoClear=e.autoClear,t.scissorTest=e.getScissorTest(),t}(e,t),e.setMRT(null),e.setRenderObjectFunction(null),e.setClearColor(0,1),e.autoClear=!0,t}const vE=new WeakMap,TE=Ed(({depthTexture:e,shadowCoord:t,depthLayer:s})=>{let i=ty(e,t.xy).setName("t_basic");return e.isArrayTexture&&(i=i.depth(s)),i.compare(t.z)}),SE=Ed(({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=ty(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(s)},n=Ox("mapSize","vec2",s).setGroup(Vp),o=Ox("radius","float",s).setGroup(Vp),a=Vd(1).div(n),l=o.mul(a.x),h=lA(fy.xy).mul(6.28318530718);return Zp(r(t.xy.add(hA(0,5,h).mul(l)),t.z),r(t.xy.add(hA(1,5,h).mul(l)),t.z),r(t.xy.add(hA(2,5,h).mul(l)),t.z),r(t.xy.add(hA(3,5,h).mul(l)),t.z),r(t.xy.add(hA(4,5,h).mul(l)),t.z)).mul(.2)}),ME=Ed(({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=ty(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(s)},n=Ox("mapSize","vec2",s).setGroup(Vp),o=Vd(1).div(n),a=o.x,l=o.y,h=t.xy,u=Gm(h.mul(n).add(.5));return h.subAssign(u.mul(o)),Zp(r(h,t.z),r(h.add(Vd(a,0)),t.z),r(h.add(Vd(0,l)),t.z),r(h.add(o),t.z),Af(r(h.add(Vd(a.negate(),0)),t.z),r(h.add(Vd(a.mul(2),0)),t.z),u.x),Af(r(h.add(Vd(a.negate(),l)),t.z),r(h.add(Vd(a.mul(2),l)),t.z),u.x),Af(r(h.add(Vd(0,l.negate())),t.z),r(h.add(Vd(0,l.mul(2))),t.z),u.y),Af(r(h.add(Vd(a,l.negate())),t.z),r(h.add(Vd(a,l.mul(2))),t.z),u.y),Af(Af(r(h.add(Vd(a.negate(),l.negate())),t.z),r(h.add(Vd(a.mul(2),l.negate())),t.z),u.x),Af(r(h.add(Vd(a.negate(),l.mul(2))),t.z),r(h.add(Vd(a.mul(2),l.mul(2))),t.z),u.x),u.y)).mul(1/9)}),AE=Ed(({depthTexture:e,shadowCoord:t,depthLayer:s})=>{let i=ty(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(s)),i=i.rg;const r=i.x,n=df(1e-7,i.y.mul(i.y)),o=pf(t.z,r);Pd(o.equal(1),()=>Dd(1));const a=t.z.sub(r);let l=n.div(n.add(a.mul(a)));return l=Nf(Qp(l,.3).div(.65)),df(o,l)}),NE=Ed(([e,t,s])=>{let i=tx.sub(e).length();return i=i.sub(t).div(s.sub(t)),i=i.saturate(),i}),EE=e=>{let t=vE.get(e);if(void 0===t){const s=e.isPointLight?(e=>{const t=e.shadow.camera,s=Ox("near","float",t).setGroup(Vp),i=Ox("far","float",t).setGroup(Vp),r=Ly(e);return NE(r,s,i)})(e):null;t=new gw,t.colorNode=Hd(0,0,0,1),t.depthNode=s,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,vE.set(e,t)}return t},CE=e=>{const t=vE.get(e);void 0!==t&&(t.dispose(),vE.delete(e))},RE=new aS,PE=[],BE=(e,t,s,i)=>{PE[0]=e,PE[1]=t;let r=RE.get(PE);return void 0!==r&&r.shadowType===s&&r.useVelocity===i||(r=(r,n,o,a,l,h,...u)=>{(!0===r.castShadow||r.receiveShadow&&3===s)&&(i&&(yc(r).useVelocity=!0),r.onBeforeShadow(e,r,o,t.camera,a,n.overrideMaterial,h),e.renderObject(r,n,o,a,l,h,...u),r.onAfterShadow(e,r,o,t.camera,a,n.overrideMaterial,h))},r.shadowType=s,r.useVelocity=i,RE.set(PE,r)),PE[0]=null,PE[1]=null,r},IE=Ed(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=Dd(0).toVar("meanVertical"),o=Dd(0).toVar("squareMeanVertical"),a=e.lessThanEqual(Dd(1)).select(Dd(0),Dd(2).div(e.sub(1))),l=e.lessThanEqual(Dd(1)).select(Dd(0),Dd(-1));C_({start:Ld(0),end:Ld(e),type:"int",condition:"<"},({i:e})=>{const h=l.add(Dd(e).mul(a));let u=i.sample(Zp(fy.xy,Vd(0,h).mul(t)).div(s));i.value.isArrayTexture&&(u=u.depth(r)),u=u.x,n.addAssign(u),o.addAssign(u.mul(u))}),n.divAssign(e),o.divAssign(e);const h=Om(o.sub(n.mul(n)).max(0));return Vd(n,h)}),DE=Ed(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=Dd(0).toVar("meanHorizontal"),o=Dd(0).toVar("squareMeanHorizontal"),a=e.lessThanEqual(Dd(1)).select(Dd(0),Dd(2).div(e.sub(1))),l=e.lessThanEqual(Dd(1)).select(Dd(0),Dd(-1));C_({start:Ld(0),end:Ld(e),type:"int",condition:"<"},({i:e})=>{const h=l.add(Dd(e).mul(a));let u=i.sample(Zp(fy.xy,Vd(h,0).mul(t)).div(s));i.value.isArrayTexture&&(u=u.depth(r)),n.addAssign(u.x),o.addAssign(Zp(u.y.mul(u.y),u.x.mul(u.x)))}),n.divAssign(e),o.divAssign(e);const h=Om(o.sub(n.mul(n)).max(0));return Vd(n,h)}),LE=[TE,SE,ME,AE];let FE;const OE=new tA;class VE extends bE{static get type(){return"ShadowNode"}constructor(e,t=null){super(e),this.shadow=t||e.shadow,this.shadowMap=null,this.vsmShadowMapVertical=null,this.vsmShadowMapHorizontal=null,this.vsmMaterialVertical=null,this.vsmMaterialHorizontal=null,this._node=null,this._currentShadowType=null,this._cameraFrameId=new WeakMap,this.isShadowNode=!0,this.depthLayer=0}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:r,depthLayer:n}){const o=i.x.greaterThanEqual(0).and(i.x.lessThanEqual(1)).and(i.y.greaterThanEqual(0)).and(i.y.lessThanEqual(1)).and(i.z.lessThanEqual(1)),a=t({depthTexture:s,shadowCoord:i,shadow:r,depthLayer:n});return o.select(a,Dd(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,r=Ox("bias","float",s).setGroup(Vp);let n,o=t;if(s.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)o=o.xyz.div(o.w),n=o.z,i.coordinateSystem===Uo&&(n=n.mul(2).sub(1));else{const e=o.w;o=o.xy.div(e);const t=Ox("near","float",s.camera).setGroup(Vp),i=Ox("far","float",s.camera).setGroup(Vp);n=K_(e.negate(),t,i)}return o=Gd(o.x,o.y.oneMinus(),n.add(r)),o}getShadowFilterFn(e){return LE[e]}setupRenderTarget(e,t){const s=new _u(e.mapSize.width,e.mapSize.height);s.name="ShadowDepthTexture",s.compareFunction=Po;const i=t.createRenderTarget(e.mapSize.width,e.mapSize.height);return i.texture.name="ShadowMap",i.texture.type=e.mapType,i.depthTexture=s,{shadowMap:i,depthTexture:s}}setupShadow(e){const{renderer:t,camera:s}=e,{light:i,shadow:r}=this,n=t.shadowMap.type,{depthTexture:o,shadowMap:a}=this.setupRenderTarget(r,e);if(r.camera.coordinateSystem=s.coordinateSystem,r.camera.updateProjectionMatrix(),3===n&&!0!==r.isPointLightShadow){o.compareFunction=null,a.depth>1?(a._vsmShadowMapVertical||(a._vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:kn,type:En,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapVertical.texture.name="VSMVertical"),this.vsmShadowMapVertical=a._vsmShadowMapVertical,a._vsmShadowMapHorizontal||(a._vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:kn,type:En,depth:a.depth,depthBuffer:!1}),a._vsmShadowMapHorizontal.texture.name="VSMHorizontal"),this.vsmShadowMapHorizontal=a._vsmShadowMapHorizontal):(this.vsmShadowMapVertical=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:kn,type:En,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:kn,type:En,depthBuffer:!1}));let t=ty(o);o.isArrayTexture&&(t=t.depth(this.depthLayer));let s=ty(this.vsmShadowMapVertical.texture);o.isArrayTexture&&(s=s.depth(this.depthLayer));const i=Ox("blurSamples","float",r).setGroup(Vp),n=Ox("radius","float",r).setGroup(Vp),l=Ox("mapSize","vec2",r).setGroup(Vp);let h=this.vsmMaterialVertical||(this.vsmMaterialVertical=new gw);h.fragmentNode=IE({samples:i,radius:n,size:l,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),h.name="VSMVertical",h=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new gw),h.fragmentNode=DE({samples:i,radius:n,size:l,shadowPass:s,depthLayer:this.depthLayer}).context(e.getSharedContext()),h.name="VSMHorizontal"}const l=Ox("intensity","float",r).setGroup(Vp),h=Ox("normalBias","float",r).setGroup(Vp),u=hE(i).mul(_E.add(fx.mul(h))),c=this.setupShadowCoord(e,u),d=r.filterNode||this.getShadowFilterFn(t.shadowMap.type)||null;if(null===d)throw new Error("THREE.WebGPURenderer: Shadow map type not supported yet.");const p=3===n&&!0!==r.isPointLightShadow?this.vsmShadowMapHorizontal.texture:o,m=this.setupShadowFilter(e,{filterFn:d,shadowTexture:a.texture,depthTexture:p,shadowCoord:c,shadow:r,depthLayer:this.depthLayer});let f;a.texture.isCubeTexture?f=Dx(a.texture,c.xyz):(f=ty(a.texture,c),o.isArrayTexture&&(f=f.depth(this.depthLayer)));const g=Af(1,m.rgb.mix(f,1),l.mul(f.a)).toVar();this.shadowMap=a,this.shadow.map=a;const y=`${this.light.type} Shadow [ ${this.light.name||"ID: "+this.light.id} ]`;return g.toInspector(`${y} / Color`,()=>this.shadowMap.texture.isCubeTexture?Dx(this.shadowMap.texture):ty(this.shadowMap.texture)).toInspector(`${y} / Depth`,()=>this.shadowMap.texture.isCubeTexture?Dx(this.shadowMap.texture).r.oneMinus():sy(this.shadowMap.depthTexture,qg().mul(Yg(ty(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(!1!==e.renderer.shadowMap.enabled)return Ed(()=>{const t=e.renderer.shadowMap.type;this._currentShadowType!==t&&(this._reset(),this._node=null);let s=this._node;return this.setupShadowPosition(e),null===s&&(this._node=s=this.setupShadow(e),this._currentShadowType=t),e.material.shadowNode&&Yo('NodeMaterial: ".shadowNode" is deprecated. Use ".castShadowNode" instead.'),e.material.receivedShadowNode&&(s=e.material.receivedShadowNode(s)),s})()}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:r,scene:n}=e;t.updateMatrices(i),s.setSize(t.mapSize.width,t.mapSize.height,s.depth);const o=n.name;n.name=`Shadow Map [ ${i.name||"ID: "+i.id} ]`,r.render(n,t.camera),n.name=o}updateShadow(e){const{shadowMap:t,light:s,shadow:i}=this,{renderer:r,scene:n,camera:o}=e,a=r.shadowMap.type,l=t.depthTexture.version;this._depthVersionCached=l;const h=i.camera.layers.mask;4294967294&i.camera.layers.mask||(i.camera.layers.mask=o.layers.mask);const u=r.getRenderObjectFunction(),c=r.getMRT(),d=!!c&&c.has("velocity");FE=function(e,t,s){return s=function(e,t){return t=function(e,t={}){return t.background=e.background,t.backgroundNode=e.backgroundNode,t.overrideMaterial=e.overrideMaterial,t}(e,t),e.background=null,e.backgroundNode=null,e.overrideMaterial=null,t}(t,s=wE(e,s)),s}(r,n,FE),n.overrideMaterial=EE(s),r.setRenderObjectFunction(BE(r,i,a,d)),r.setClearColor(0,0),r.setRenderTarget(t),this.renderShadow(e),r.setRenderObjectFunction(u),3===a&&!0!==i.isPointLightShadow&&this.vsmPass(r),i.camera.layers.mask=h,function(e,t,s){!function(e,t){e.toneMapping=t.toneMapping,e.toneMappingExposure=t.toneMappingExposure,e.outputColorSpace=t.outputColorSpace,e.setRenderTarget(t.renderTarget,t.activeCubeFace,t.activeMipmapLevel),e.setRenderObjectFunction(t.renderObjectFunction),e.setPixelRatio(t.pixelRatio),e.setMRT(t.mrt),e.setClearColor(t.clearColor,t.clearAlpha),e.autoClear=t.autoClear,e.setScissorTest(t.scissorTest)}(e,s),function(e,t){e.background=t.background,e.backgroundNode=t.backgroundNode,e.overrideMaterial=t.overrideMaterial}(t,s)}(r,n,FE)}vsmPass(e){const{shadow:t}=this,s=this.shadowMap.depth;this.vsmShadowMapVertical.setSize(t.mapSize.width,t.mapSize.height,s),this.vsmShadowMapHorizontal.setSize(t.mapSize.width,t.mapSize.height,s),e.setRenderTarget(this.vsmShadowMapVertical),OE.material=this.vsmMaterialVertical,OE.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),OE.material=this.vsmMaterialHorizontal,OE.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,CE(this.light),this.shadowMap&&(this.shadowMap.dispose(),this.shadowMap=null),null!==this.vsmShadowMapVertical&&(this.vsmShadowMapVertical.dispose(),this.vsmShadowMapVertical=null,this.vsmMaterialVertical.dispose(),this.vsmMaterialVertical=null),null!==this.vsmShadowMapHorizontal&&(this.vsmShadowMapHorizontal.dispose(),this.vsmShadowMapHorizontal=null,this.vsmMaterialHorizontal.dispose(),this.vsmMaterialHorizontal=null)}updateBefore(e){const{shadow:t}=this;let s=t.needsUpdate||t.autoUpdate;s&&(this._cameraFrameId[e.camera]===e.frameId&&(s=!1),this._cameraFrameId[e.camera]=e.frameId),s&&(this.updateShadow(e),this.shadowMap.depthTexture.version===this._depthVersionCached&&(t.needsUpdate=!1))}}const zE=(e,t)=>new VE(e,t),kE=new eh,UE=new ll,GE=new da,jE=new da,$E=[new da(1,0,0),new da(-1,0,0),new da(0,-1,0),new da(0,1,0),new da(0,0,1),new da(0,0,-1)],WE=[new da(0,-1,0),new da(0,-1,0),new da(0,0,-1),new da(0,0,1),new da(0,-1,0),new da(0,-1,0)],HE=[new da(1,0,0),new da(-1,0,0),new da(0,1,0),new da(0,-1,0),new da(0,0,1),new da(0,0,-1)],qE=[new da(0,-1,0),new da(0,-1,0),new da(0,0,1),new da(0,0,-1),new da(0,-1,0),new da(0,-1,0)],XE=Ed(({depthTexture:e,bd3D:t,dp:s})=>Dx(e,t).compare(s)),YE=Ed(({depthTexture:e,bd3D:t,dp:s,shadow:i})=>{const r=Ox("radius","float",i).setGroup(Vp),n=Ox("mapSize","vec2",i).setGroup(Vp),o=r.div(n.x),a=Ym(t),l=Um(xf(t,a.x.greaterThan(a.z).select(Gd(0,1,0),Gd(1,0,0)))),h=xf(t,l),u=lA(fy.xy).mul(6.28318530718),c=hA(0,5,u),d=hA(1,5,u),p=hA(2,5,u),m=hA(3,5,u),f=hA(4,5,u);return Dx(e,t.add(l.mul(c.x).add(h.mul(c.y)).mul(o))).compare(s).add(Dx(e,t.add(l.mul(d.x).add(h.mul(d.y)).mul(o))).compare(s)).add(Dx(e,t.add(l.mul(p.x).add(h.mul(p.y)).mul(o))).compare(s)).add(Dx(e,t.add(l.mul(m.x).add(h.mul(m.y)).mul(o))).compare(s)).add(Dx(e,t.add(l.mul(f.x).add(h.mul(f.y)).mul(o))).compare(s)).mul(.2)}),ZE=Ed(({filterFn:e,depthTexture:t,shadowCoord:s,shadow:i})=>{const r=s.xyz.toVar(),n=r.length(),o=Up("float").setGroup(Vp).onRenderUpdate(()=>i.camera.near),a=Up("float").setGroup(Vp).onRenderUpdate(()=>i.camera.far),l=Ox("bias","float",i).setGroup(Vp),h=Dd(1).toVar();return Pd(n.sub(a).lessThanEqual(0).and(n.sub(o).greaterThanEqual(0)),()=>{const s=n.sub(o).div(a.sub(o)).toVar();s.addAssign(l);const u=r.normalize();h.assign(e({depthTexture:t,bd3D:u,dp:s,shadow:i}))}),h});class QE extends VE{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?XE:YE}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:r}){return ZE({filterFn:t,depthTexture:s,shadowCoord:i,shadow:r})}setupRenderTarget(e,t){const s=new wu(e.mapSize.width);s.name="PointShadowDepthTexture",s.compareFunction=Po;const i=t.createCubeRenderTarget(e.mapSize.width);return i.texture.name="PointShadowMap",i.depthTexture=s,{shadowMap:i,depthTexture:s}}renderShadow(e){const{shadow:t,shadowMap:s,light:i}=this,{renderer:r,scene:n}=e,o=t.camera,a=t.matrix,l=r.coordinateSystem===Uo,h=l?$E:HE,u=l?WE:qE;s.setSize(t.mapSize.width,t.mapSize.width);const c=r.autoClear,d=r.getClearColor(kE),p=r.getClearAlpha();r.autoClear=!1,r.setClearColor(t.clearColor,t.clearAlpha);for(let e=0;e<6;e++){r.setRenderTarget(s,e),r.clear();const l=i.distance||o.far;l!==o.far&&(o.far=l,o.updateProjectionMatrix()),GE.setFromMatrixPosition(i.matrixWorld),o.position.copy(GE),jE.copy(o.position),jE.add(h[e]),o.up.copy(u[e]),o.lookAt(jE),o.updateMatrixWorld(),a.makeTranslation(-GE.x,-GE.y,-GE.z),UE.multiplyMatrices(o.projectionMatrix,o.matrixWorldInverse),t._frustum.setFromProjectionMatrix(UE,o.coordinateSystem,o.reversedDepth);const c=n.name;n.name=`Point Light Shadow [ ${i.name||"ID: "+i.id} ] - Face ${e+1}`,r.render(n,o),n.name=c}r.autoClear=c,r.setClearColor(d,p)}}const KE=(e,t)=>new QE(e,t);class JE extends F_{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new eh,this.colorNode=e&&e.colorNode||Up(this.color).setGroup(Vp),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=wc.FRAME,e&&e.shadow&&(this._shadowDisposeListener=()=>{this.disposeShadow()},e.addEventListener("dispose",this._shadowDisposeListener))}dispose(){this._shadowDisposeListener&&this.light.removeEventListener("dispose",this._shadowDisposeListener),super.dispose()}disposeShadow(){null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null),this.shadowColorNode=null,null!==this.baseColorNode&&(this.colorNode=this.baseColorNode,this.baseColorNode=null)}getHash(){return this.light.uuid}getLightVector(e){return pE(this.light).sub(e.context.positionView||ix)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return zE(this.light)}setupShadow(e){const{renderer:t}=e;if(!1===t.shadowMap.enabled)return;let s=this.shadowColorNode;if(null===s){const e=this.light.shadow.shadowNode;let t;t=void 0!==e?bd(e):this.setupShadowNode(),this.shadowNode=t,this.shadowColorNode=s=this.colorNode.mul(t),this.baseColorNode=this.colorNode}e.context.getShadow&&(s=e.context.getShadow(this,e)),this.colorNode=s}setup(e){this.colorNode=this.baseColorNode||this.colorNode,this.light.castShadow?e.object.receiveShadow&&this.setupShadow(e):null!==this.shadowNode&&(this.shadowNode.dispose(),this.shadowNode=null,this.shadowColorNode=null);const t=this.setupDirect(e),s=this.setupDirectRectArea(e);t&&e.lightsNode.setupDirectLight(e,this,t),s&&e.lightsNode.setupDirectRectAreaLight(e,this,s)}update(){const{light:e}=this;this.color.copy(e.color).multiplyScalar(e.intensity)}}const eC=Ed(({lightDistance:e,cutoffDistance:t,decayExponent:s})=>{const i=e.pow(s).max(.01).reciprocal();return t.greaterThan(0).select(i.mul(e.div(t).pow4().oneMinus().clamp().pow2()),i)}),tC=({color:e,lightVector:t,cutoffDistance:s,decayExponent:i})=>{const r=t.normalize(),n=t.length(),o=eC({lightDistance:n,cutoffDistance:s,decayExponent:i});return{lightDirection:r,lightColor:e.mul(o)}};class sC extends JE{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Up(0).setGroup(Vp),this.decayExponentNode=Up(2).setGroup(Vp)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return KE(this.light)}setupDirect(e){return tC({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const iC=Ed(([e=qg()])=>{const t=e.mul(2),s=t.x.floor(),i=t.y.floor();return s.add(i).mod(2).sign()}),rC=Ed(([e=qg()],{renderer:t,material:s})=>{const i=Mf(e.mul(2).sub(1));let r;if(s.alphaToCoverage&&t.currentSamples>0){const e=Dd(i.fwidth()).toVar();r=Rf(e.oneMinus(),e.add(1),i).oneMinus()}else r=kf(i.greaterThan(1),0,1);return r}),nC=Ed(([e,t,s])=>{const i=Dd(s).toVar(),r=Dd(t).toVar(),n=Od(e).toVar();return kf(n,r,i)}).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),oC=Ed(([e,t])=>{const s=Od(t).toVar(),i=Dd(e).toVar();return kf(s,i.negate(),i)}).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),aC=Ed(([e])=>{const t=Dd(e).toVar();return Ld(zm(t))}).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),lC=Ed(([e,t])=>{const s=Dd(e).toVar();return t.assign(aC(s)),s.sub(Dd(t))}),hC=MM([Ed(([e,t,s,i,r,n])=>{const o=Dd(n).toVar(),a=Dd(r).toVar(),l=Dd(i).toVar(),h=Dd(s).toVar(),u=Dd(t).toVar(),c=Dd(e).toVar(),d=Dd(Qp(1,a)).toVar();return Qp(1,o).mul(c.mul(d).add(u.mul(a))).add(o.mul(h.mul(d).add(l.mul(a))))}).setLayout({name:"mx_bilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"}]}),Ed(([e,t,s,i,r,n])=>{const o=Dd(n).toVar(),a=Dd(r).toVar(),l=Gd(i).toVar(),h=Gd(s).toVar(),u=Gd(t).toVar(),c=Gd(e).toVar(),d=Dd(Qp(1,a)).toVar();return Qp(1,o).mul(c.mul(d).add(u.mul(a))).add(o.mul(h.mul(d).add(l.mul(a))))}).setLayout({name:"mx_bilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"}]})]),uC=MM([Ed(([e,t,s,i,r,n,o,a,l,h,u])=>{const c=Dd(u).toVar(),d=Dd(h).toVar(),p=Dd(l).toVar(),m=Dd(a).toVar(),f=Dd(o).toVar(),g=Dd(n).toVar(),y=Dd(r).toVar(),x=Dd(i).toVar(),b=Dd(s).toVar(),_=Dd(t).toVar(),w=Dd(e).toVar(),v=Dd(Qp(1,p)).toVar(),T=Dd(Qp(1,d)).toVar();return Dd(Qp(1,c)).toVar().mul(T.mul(w.mul(v).add(_.mul(p))).add(d.mul(b.mul(v).add(x.mul(p))))).add(c.mul(T.mul(y.mul(v).add(g.mul(p))).add(d.mul(f.mul(v).add(m.mul(p))))))}).setLayout({name:"mx_trilerp_0",type:"float",inputs:[{name:"v0",type:"float"},{name:"v1",type:"float"},{name:"v2",type:"float"},{name:"v3",type:"float"},{name:"v4",type:"float"},{name:"v5",type:"float"},{name:"v6",type:"float"},{name:"v7",type:"float"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]}),Ed(([e,t,s,i,r,n,o,a,l,h,u])=>{const c=Dd(u).toVar(),d=Dd(h).toVar(),p=Dd(l).toVar(),m=Gd(a).toVar(),f=Gd(o).toVar(),g=Gd(n).toVar(),y=Gd(r).toVar(),x=Gd(i).toVar(),b=Gd(s).toVar(),_=Gd(t).toVar(),w=Gd(e).toVar(),v=Dd(Qp(1,p)).toVar(),T=Dd(Qp(1,d)).toVar();return Dd(Qp(1,c)).toVar().mul(T.mul(w.mul(v).add(_.mul(p))).add(d.mul(b.mul(v).add(x.mul(p))))).add(c.mul(T.mul(y.mul(v).add(g.mul(p))).add(d.mul(f.mul(v).add(m.mul(p))))))}).setLayout({name:"mx_trilerp_1",type:"vec3",inputs:[{name:"v0",type:"vec3"},{name:"v1",type:"vec3"},{name:"v2",type:"vec3"},{name:"v3",type:"vec3"},{name:"v4",type:"vec3"},{name:"v5",type:"vec3"},{name:"v6",type:"vec3"},{name:"v7",type:"vec3"},{name:"s",type:"float"},{name:"t",type:"float"},{name:"r",type:"float"}]})]),cC=MM([Ed(([e,t,s])=>{const i=Dd(s).toVar(),r=Dd(t).toVar(),n=Fd(e).toVar(),o=Fd(n.bitAnd(Fd(7))).toVar(),a=Dd(nC(o.lessThan(Fd(4)),r,i)).toVar(),l=Dd(Kp(2,nC(o.lessThan(Fd(4)),i,r))).toVar();return oC(a,Od(o.bitAnd(Fd(1)))).add(oC(l,Od(o.bitAnd(Fd(2)))))}).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Ed(([e,t,s,i])=>{const r=Dd(i).toVar(),n=Dd(s).toVar(),o=Dd(t).toVar(),a=Fd(e).toVar(),l=Fd(a.bitAnd(Fd(15))).toVar(),h=Dd(nC(l.lessThan(Fd(8)),o,n)).toVar(),u=Dd(nC(l.lessThan(Fd(4)),n,nC(l.equal(Fd(12)).or(l.equal(Fd(14))),o,r))).toVar();return oC(h,Od(l.bitAnd(Fd(1)))).add(oC(u,Od(l.bitAnd(Fd(2)))))}).setLayout({name:"mx_gradient_float_1",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]})]),dC=MM([Ed(([e,t,s])=>{const i=Dd(s).toVar(),r=Dd(t).toVar(),n=$d(e).toVar();return Gd(cC(n.x,r,i),cC(n.y,r,i),cC(n.z,r,i))}).setLayout({name:"mx_gradient_vec3_0",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"}]}),Ed(([e,t,s,i])=>{const r=Dd(i).toVar(),n=Dd(s).toVar(),o=Dd(t).toVar(),a=$d(e).toVar();return Gd(cC(a.x,o,n,r),cC(a.y,o,n,r),cC(a.z,o,n,r))}).setLayout({name:"mx_gradient_vec3_1",type:"vec3",inputs:[{name:"hash",type:"uvec3"},{name:"x",type:"float"},{name:"y",type:"float"},{name:"z",type:"float"}]})]),pC=Ed(([e])=>{const t=Dd(e).toVar();return Kp(.6616,t)}).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),mC=Ed(([e])=>{const t=Dd(e).toVar();return Kp(.982,t)}).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),fC=MM([pC,Ed(([e])=>{const t=Gd(e).toVar();return Kp(.6616,t)}).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),gC=MM([mC,Ed(([e])=>{const t=Gd(e).toVar();return Kp(.982,t)}).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),yC=Ed(([e,t])=>{const s=Ld(t).toVar(),i=Fd(e).toVar();return i.shiftLeft(s).bitOr(i.shiftRight(Ld(32).sub(s)))}).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),xC=Ed(([e,t,s])=>{e.subAssign(s),e.bitXorAssign(yC(s,Ld(4))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(yC(e,Ld(6))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(yC(t,Ld(8))),t.addAssign(e),e.subAssign(s),e.bitXorAssign(yC(s,Ld(16))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(yC(e,Ld(19))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(yC(t,Ld(4))),t.addAssign(e)}),bC=Ed(([e,t,s])=>{const i=Fd(s).toVar(),r=Fd(t).toVar(),n=Fd(e).toVar();return i.bitXorAssign(r),i.subAssign(yC(r,Ld(14))),n.bitXorAssign(i),n.subAssign(yC(i,Ld(11))),r.bitXorAssign(n),r.subAssign(yC(n,Ld(25))),i.bitXorAssign(r),i.subAssign(yC(r,Ld(16))),n.bitXorAssign(i),n.subAssign(yC(i,Ld(4))),r.bitXorAssign(n),r.subAssign(yC(n,Ld(14))),i.bitXorAssign(r),i.subAssign(yC(r,Ld(24))),i}).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),_C=Ed(([e])=>{const t=Fd(e).toVar();return Dd(t).div(Dd(Fd(Ld(4294967295))))}).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),wC=Ed(([e])=>{const t=Dd(e).toVar();return t.mul(t).mul(t).mul(t.mul(t.mul(6).sub(15)).add(10))}).setLayout({name:"mx_fade",type:"float",inputs:[{name:"t",type:"float"}]}),vC=MM([Ed(([e])=>{const t=Ld(e).toVar(),s=Fd(Fd(1)).toVar(),i=Fd(Fd(Ld(3735928559)).add(s.shiftLeft(Fd(2))).add(Fd(13))).toVar();return bC(i.add(Fd(t)),i,i)}).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),Ed(([e,t])=>{const s=Ld(t).toVar(),i=Ld(e).toVar(),r=Fd(Fd(2)).toVar(),n=Fd().toVar(),o=Fd().toVar(),a=Fd().toVar();return n.assign(o.assign(a.assign(Fd(Ld(3735928559)).add(r.shiftLeft(Fd(2))).add(Fd(13))))),n.addAssign(Fd(i)),o.addAssign(Fd(s)),bC(n,o,a)}).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Ld(t).toVar(),n=Ld(e).toVar(),o=Fd(Fd(3)).toVar(),a=Fd().toVar(),l=Fd().toVar(),h=Fd().toVar();return a.assign(l.assign(h.assign(Fd(Ld(3735928559)).add(o.shiftLeft(Fd(2))).add(Fd(13))))),a.addAssign(Fd(n)),l.addAssign(Fd(r)),h.addAssign(Fd(i)),bC(a,l,h)}).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),Ed(([e,t,s,i])=>{const r=Ld(i).toVar(),n=Ld(s).toVar(),o=Ld(t).toVar(),a=Ld(e).toVar(),l=Fd(Fd(4)).toVar(),h=Fd().toVar(),u=Fd().toVar(),c=Fd().toVar();return h.assign(u.assign(c.assign(Fd(Ld(3735928559)).add(l.shiftLeft(Fd(2))).add(Fd(13))))),h.addAssign(Fd(a)),u.addAssign(Fd(o)),c.addAssign(Fd(n)),xC(h,u,c),h.addAssign(Fd(r)),bC(h,u,c)}).setLayout({name:"mx_hash_int_3",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"}]}),Ed(([e,t,s,i,r])=>{const n=Ld(r).toVar(),o=Ld(i).toVar(),a=Ld(s).toVar(),l=Ld(t).toVar(),h=Ld(e).toVar(),u=Fd(Fd(5)).toVar(),c=Fd().toVar(),d=Fd().toVar(),p=Fd().toVar();return c.assign(d.assign(p.assign(Fd(Ld(3735928559)).add(u.shiftLeft(Fd(2))).add(Fd(13))))),c.addAssign(Fd(h)),d.addAssign(Fd(l)),p.addAssign(Fd(a)),xC(c,d,p),c.addAssign(Fd(o)),d.addAssign(Fd(n)),bC(c,d,p)}).setLayout({name:"mx_hash_int_4",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xx",type:"int"},{name:"yy",type:"int"}]})]),TC=MM([Ed(([e,t])=>{const s=Ld(t).toVar(),i=Ld(e).toVar(),r=Fd(vC(i,s)).toVar(),n=$d().toVar();return n.x.assign(r.bitAnd(Ld(255))),n.y.assign(r.shiftRight(Ld(8)).bitAnd(Ld(255))),n.z.assign(r.shiftRight(Ld(16)).bitAnd(Ld(255))),n}).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Ld(t).toVar(),n=Ld(e).toVar(),o=Fd(vC(n,r,i)).toVar(),a=$d().toVar();return a.x.assign(o.bitAnd(Ld(255))),a.y.assign(o.shiftRight(Ld(8)).bitAnd(Ld(255))),a.z.assign(o.shiftRight(Ld(16)).bitAnd(Ld(255))),a}).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),SC=MM([Ed(([e])=>{const t=Vd(e).toVar(),s=Ld().toVar(),i=Ld().toVar(),r=Dd(lC(t.x,s)).toVar(),n=Dd(lC(t.y,i)).toVar(),o=Dd(wC(r)).toVar(),a=Dd(wC(n)).toVar(),l=Dd(hC(cC(vC(s,i),r,n),cC(vC(s.add(Ld(1)),i),r.sub(1),n),cC(vC(s,i.add(Ld(1))),r,n.sub(1)),cC(vC(s.add(Ld(1)),i.add(Ld(1))),r.sub(1),n.sub(1)),o,a)).toVar();return fC(l)}).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),Ed(([e])=>{const t=Gd(e).toVar(),s=Ld().toVar(),i=Ld().toVar(),r=Ld().toVar(),n=Dd(lC(t.x,s)).toVar(),o=Dd(lC(t.y,i)).toVar(),a=Dd(lC(t.z,r)).toVar(),l=Dd(wC(n)).toVar(),h=Dd(wC(o)).toVar(),u=Dd(wC(a)).toVar(),c=Dd(uC(cC(vC(s,i,r),n,o,a),cC(vC(s.add(Ld(1)),i,r),n.sub(1),o,a),cC(vC(s,i.add(Ld(1)),r),n,o.sub(1),a),cC(vC(s.add(Ld(1)),i.add(Ld(1)),r),n.sub(1),o.sub(1),a),cC(vC(s,i,r.add(Ld(1))),n,o,a.sub(1)),cC(vC(s.add(Ld(1)),i,r.add(Ld(1))),n.sub(1),o,a.sub(1)),cC(vC(s,i.add(Ld(1)),r.add(Ld(1))),n,o.sub(1),a.sub(1)),cC(vC(s.add(Ld(1)),i.add(Ld(1)),r.add(Ld(1))),n.sub(1),o.sub(1),a.sub(1)),l,h,u)).toVar();return gC(c)}).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),MC=MM([Ed(([e])=>{const t=Vd(e).toVar(),s=Ld().toVar(),i=Ld().toVar(),r=Dd(lC(t.x,s)).toVar(),n=Dd(lC(t.y,i)).toVar(),o=Dd(wC(r)).toVar(),a=Dd(wC(n)).toVar(),l=Gd(hC(dC(TC(s,i),r,n),dC(TC(s.add(Ld(1)),i),r.sub(1),n),dC(TC(s,i.add(Ld(1))),r,n.sub(1)),dC(TC(s.add(Ld(1)),i.add(Ld(1))),r.sub(1),n.sub(1)),o,a)).toVar();return fC(l)}).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Ed(([e])=>{const t=Gd(e).toVar(),s=Ld().toVar(),i=Ld().toVar(),r=Ld().toVar(),n=Dd(lC(t.x,s)).toVar(),o=Dd(lC(t.y,i)).toVar(),a=Dd(lC(t.z,r)).toVar(),l=Dd(wC(n)).toVar(),h=Dd(wC(o)).toVar(),u=Dd(wC(a)).toVar(),c=Gd(uC(dC(TC(s,i,r),n,o,a),dC(TC(s.add(Ld(1)),i,r),n.sub(1),o,a),dC(TC(s,i.add(Ld(1)),r),n,o.sub(1),a),dC(TC(s.add(Ld(1)),i.add(Ld(1)),r),n.sub(1),o.sub(1),a),dC(TC(s,i,r.add(Ld(1))),n,o,a.sub(1)),dC(TC(s.add(Ld(1)),i,r.add(Ld(1))),n.sub(1),o,a.sub(1)),dC(TC(s,i.add(Ld(1)),r.add(Ld(1))),n,o.sub(1),a.sub(1)),dC(TC(s.add(Ld(1)),i.add(Ld(1)),r.add(Ld(1))),n.sub(1),o.sub(1),a.sub(1)),l,h,u)).toVar();return gC(c)}).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),AC=MM([Ed(([e])=>{const t=Dd(e).toVar(),s=Ld(aC(t)).toVar();return _C(vC(s))}).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),Ed(([e])=>{const t=Vd(e).toVar(),s=Ld(aC(t.x)).toVar(),i=Ld(aC(t.y)).toVar();return _C(vC(s,i))}).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),Ed(([e])=>{const t=Gd(e).toVar(),s=Ld(aC(t.x)).toVar(),i=Ld(aC(t.y)).toVar(),r=Ld(aC(t.z)).toVar();return _C(vC(s,i,r))}).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),Ed(([e])=>{const t=Hd(e).toVar(),s=Ld(aC(t.x)).toVar(),i=Ld(aC(t.y)).toVar(),r=Ld(aC(t.z)).toVar(),n=Ld(aC(t.w)).toVar();return _C(vC(s,i,r,n))}).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),NC=MM([Ed(([e])=>{const t=Dd(e).toVar(),s=Ld(aC(t)).toVar();return Gd(_C(vC(s,Ld(0))),_C(vC(s,Ld(1))),_C(vC(s,Ld(2))))}).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),Ed(([e])=>{const t=Vd(e).toVar(),s=Ld(aC(t.x)).toVar(),i=Ld(aC(t.y)).toVar();return Gd(_C(vC(s,i,Ld(0))),_C(vC(s,i,Ld(1))),_C(vC(s,i,Ld(2))))}).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),Ed(([e])=>{const t=Gd(e).toVar(),s=Ld(aC(t.x)).toVar(),i=Ld(aC(t.y)).toVar(),r=Ld(aC(t.z)).toVar();return Gd(_C(vC(s,i,r,Ld(0))),_C(vC(s,i,r,Ld(1))),_C(vC(s,i,r,Ld(2))))}).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),Ed(([e])=>{const t=Hd(e).toVar(),s=Ld(aC(t.x)).toVar(),i=Ld(aC(t.y)).toVar(),r=Ld(aC(t.z)).toVar(),n=Ld(aC(t.w)).toVar();return Gd(_C(vC(s,i,r,n,Ld(0))),_C(vC(s,i,r,n,Ld(1))),_C(vC(s,i,r,n,Ld(2))))}).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),EC=Ed(([e,t,s,i])=>{const r=Dd(i).toVar(),n=Dd(s).toVar(),o=Ld(t).toVar(),a=Gd(e).toVar(),l=Dd(0).toVar(),h=Dd(1).toVar();return C_(o,()=>{l.addAssign(h.mul(SC(a))),h.mulAssign(r),a.mulAssign(n)}),l}).setLayout({name:"mx_fractal_noise_float",type:"float",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),CC=Ed(([e,t,s,i])=>{const r=Dd(i).toVar(),n=Dd(s).toVar(),o=Ld(t).toVar(),a=Gd(e).toVar(),l=Gd(0).toVar(),h=Dd(1).toVar();return C_(o,()=>{l.addAssign(h.mul(MC(a))),h.mulAssign(r),a.mulAssign(n)}),l}).setLayout({name:"mx_fractal_noise_vec3",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),RC=Ed(([e,t,s,i])=>{const r=Dd(i).toVar(),n=Dd(s).toVar(),o=Ld(t).toVar(),a=Gd(e).toVar();return Vd(EC(a,o,n,r),EC(a.add(Gd(Ld(19),Ld(193),Ld(17))),o,n,r))}).setLayout({name:"mx_fractal_noise_vec2",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),PC=Ed(([e,t,s,i])=>{const r=Dd(i).toVar(),n=Dd(s).toVar(),o=Ld(t).toVar(),a=Gd(e).toVar(),l=Gd(CC(a,o,n,r)).toVar(),h=Dd(EC(a.add(Gd(Ld(19),Ld(193),Ld(17))),o,n,r)).toVar();return Hd(l,h)}).setLayout({name:"mx_fractal_noise_vec4",type:"vec4",inputs:[{name:"p",type:"vec3"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),BC=MM([Ed(([e,t,s,i,r,n,o])=>{const a=Ld(o).toVar(),l=Dd(n).toVar(),h=Ld(r).toVar(),u=Ld(i).toVar(),c=Ld(s).toVar(),d=Ld(t).toVar(),p=Vd(e).toVar(),m=Gd(NC(Vd(d.add(u),c.add(h)))).toVar(),f=Vd(m.x,m.y).toVar();f.subAssign(.5),f.mulAssign(l),f.addAssign(.5);const g=Vd(Vd(Dd(d),Dd(c)).add(f)).toVar(),y=Vd(g.sub(p)).toVar();return Pd(a.equal(Ld(2)),()=>Ym(y.x).add(Ym(y.y))),Pd(a.equal(Ld(3)),()=>df(Ym(y.x),Ym(y.y))),yf(y,y)}).setLayout({name:"mx_worley_distance_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),Ed(([e,t,s,i,r,n,o,a,l])=>{const h=Ld(l).toVar(),u=Dd(a).toVar(),c=Ld(o).toVar(),d=Ld(n).toVar(),p=Ld(r).toVar(),m=Ld(i).toVar(),f=Ld(s).toVar(),g=Ld(t).toVar(),y=Gd(e).toVar(),x=Gd(NC(Gd(g.add(p),f.add(d),m.add(c)))).toVar();x.subAssign(.5),x.mulAssign(u),x.addAssign(.5);const b=Gd(Gd(Dd(g),Dd(f),Dd(m)).add(x)).toVar(),_=Gd(b.sub(y)).toVar();return Pd(h.equal(Ld(2)),()=>Ym(_.x).add(Ym(_.y)).add(Ym(_.z))),Pd(h.equal(Ld(3)),()=>df(Ym(_.x),Ym(_.y),Ym(_.z))),yf(_,_)}).setLayout({name:"mx_worley_distance_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"},{name:"xoff",type:"int"},{name:"yoff",type:"int"},{name:"zoff",type:"int"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),IC=Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Dd(t).toVar(),n=Vd(e).toVar(),o=Ld().toVar(),a=Ld().toVar(),l=Vd(lC(n.x,o),lC(n.y,a)).toVar(),h=Dd(1e6).toVar();return C_({start:-1,end:Ld(1),name:"x",condition:"<="},({x:e})=>{C_({start:-1,end:Ld(1),name:"y",condition:"<="},({y:t})=>{const s=Dd(BC(l,e,t,o,a,r,i)).toVar();h.assign(cf(h,s))})}),Pd(i.equal(Ld(0)),()=>{h.assign(Om(h))}),h}).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),DC=Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Dd(t).toVar(),n=Vd(e).toVar(),o=Ld().toVar(),a=Ld().toVar(),l=Vd(lC(n.x,o),lC(n.y,a)).toVar(),h=Vd(1e6,1e6).toVar();return C_({start:-1,end:Ld(1),name:"x",condition:"<="},({x:e})=>{C_({start:-1,end:Ld(1),name:"y",condition:"<="},({y:t})=>{const s=Dd(BC(l,e,t,o,a,r,i)).toVar();Pd(s.lessThan(h.x),()=>{h.y.assign(h.x),h.x.assign(s)}).ElseIf(s.lessThan(h.y),()=>{h.y.assign(s)})})}),Pd(i.equal(Ld(0)),()=>{h.assign(Om(h))}),h}).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),LC=Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Dd(t).toVar(),n=Vd(e).toVar(),o=Ld().toVar(),a=Ld().toVar(),l=Vd(lC(n.x,o),lC(n.y,a)).toVar(),h=Gd(1e6,1e6,1e6).toVar();return C_({start:-1,end:Ld(1),name:"x",condition:"<="},({x:e})=>{C_({start:-1,end:Ld(1),name:"y",condition:"<="},({y:t})=>{const s=Dd(BC(l,e,t,o,a,r,i)).toVar();Pd(s.lessThan(h.x),()=>{h.z.assign(h.y),h.y.assign(h.x),h.x.assign(s)}).ElseIf(s.lessThan(h.y),()=>{h.z.assign(h.y),h.y.assign(s)}).ElseIf(s.lessThan(h.z),()=>{h.z.assign(s)})})}),Pd(i.equal(Ld(0)),()=>{h.assign(Om(h))}),h}).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),FC=MM([IC,Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Dd(t).toVar(),n=Gd(e).toVar(),o=Ld().toVar(),a=Ld().toVar(),l=Ld().toVar(),h=Gd(lC(n.x,o),lC(n.y,a),lC(n.z,l)).toVar(),u=Dd(1e6).toVar();return C_({start:-1,end:Ld(1),name:"x",condition:"<="},({x:e})=>{C_({start:-1,end:Ld(1),name:"y",condition:"<="},({y:t})=>{C_({start:-1,end:Ld(1),name:"z",condition:"<="},({z:s})=>{const n=Dd(BC(h,e,t,s,o,a,l,r,i)).toVar();u.assign(cf(u,n))})})}),Pd(i.equal(Ld(0)),()=>{u.assign(Om(u))}),u}).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),OC=MM([DC,Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Dd(t).toVar(),n=Gd(e).toVar(),o=Ld().toVar(),a=Ld().toVar(),l=Ld().toVar(),h=Gd(lC(n.x,o),lC(n.y,a),lC(n.z,l)).toVar(),u=Vd(1e6,1e6).toVar();return C_({start:-1,end:Ld(1),name:"x",condition:"<="},({x:e})=>{C_({start:-1,end:Ld(1),name:"y",condition:"<="},({y:t})=>{C_({start:-1,end:Ld(1),name:"z",condition:"<="},({z:s})=>{const n=Dd(BC(h,e,t,s,o,a,l,r,i)).toVar();Pd(n.lessThan(u.x),()=>{u.y.assign(u.x),u.x.assign(n)}).ElseIf(n.lessThan(u.y),()=>{u.y.assign(n)})})})}),Pd(i.equal(Ld(0)),()=>{u.assign(Om(u))}),u}).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),VC=MM([LC,Ed(([e,t,s])=>{const i=Ld(s).toVar(),r=Dd(t).toVar(),n=Gd(e).toVar(),o=Ld().toVar(),a=Ld().toVar(),l=Ld().toVar(),h=Gd(lC(n.x,o),lC(n.y,a),lC(n.z,l)).toVar(),u=Gd(1e6,1e6,1e6).toVar();return C_({start:-1,end:Ld(1),name:"x",condition:"<="},({x:e})=>{C_({start:-1,end:Ld(1),name:"y",condition:"<="},({y:t})=>{C_({start:-1,end:Ld(1),name:"z",condition:"<="},({z:s})=>{const n=Dd(BC(h,e,t,s,o,a,l,r,i)).toVar();Pd(n.lessThan(u.x),()=>{u.z.assign(u.y),u.y.assign(u.x),u.x.assign(n)}).ElseIf(n.lessThan(u.y),()=>{u.z.assign(u.y),u.y.assign(n)}).ElseIf(n.lessThan(u.z),()=>{u.z.assign(n)})})})}),Pd(i.equal(Ld(0)),()=>{u.assign(Om(u))}),u}).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),zC=Ed(([e,t,s,i,r,n,o,a,l,h,u])=>{const c=Ld(e).toVar(),d=Vd(t).toVar(),p=Vd(s).toVar(),m=Vd(i).toVar(),f=Dd(r).toVar(),g=Dd(n).toVar(),y=Dd(o).toVar(),x=Od(a).toVar(),b=Ld(l).toVar(),_=Dd(h).toVar(),w=Dd(u).toVar(),v=d.mul(p).add(m),T=Dd(0).toVar();return Pd(c.equal(Ld(0)),()=>{T.assign(MC(v))}),Pd(c.equal(Ld(1)),()=>{T.assign(NC(v))}),Pd(c.equal(Ld(2)),()=>{T.assign(VC(v,f,Ld(0)))}),Pd(c.equal(Ld(3)),()=>{T.assign(CC(Gd(v,0),b,_,w))}),T.assign(T.mul(y.sub(g)).add(g)),Pd(x,()=>{T.assign(Nf(T,g,y))}),T}).setLayout({name:"mx_unifiednoise2d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"texcoord",type:"vec2"},{name:"freq",type:"vec2"},{name:"offset",type:"vec2"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),kC=Ed(([e,t,s,i,r,n,o,a,l,h,u])=>{const c=Ld(e).toVar(),d=Gd(t).toVar(),p=Gd(s).toVar(),m=Gd(i).toVar(),f=Dd(r).toVar(),g=Dd(n).toVar(),y=Dd(o).toVar(),x=Od(a).toVar(),b=Ld(l).toVar(),_=Dd(h).toVar(),w=Dd(u).toVar(),v=d.mul(p).add(m),T=Dd(0).toVar();return Pd(c.equal(Ld(0)),()=>{T.assign(MC(v))}),Pd(c.equal(Ld(1)),()=>{T.assign(NC(v))}),Pd(c.equal(Ld(2)),()=>{T.assign(VC(v,f,Ld(0)))}),Pd(c.equal(Ld(3)),()=>{T.assign(CC(v,b,_,w))}),T.assign(T.mul(y.sub(g)).add(g)),Pd(x,()=>{T.assign(Nf(T,g,y))}),T}).setLayout({name:"mx_unifiednoise3d",type:"float",inputs:[{name:"noiseType",type:"int"},{name:"position",type:"vec3"},{name:"freq",type:"vec3"},{name:"offset",type:"vec3"},{name:"jitter",type:"float"},{name:"outmin",type:"float"},{name:"outmax",type:"float"},{name:"clampoutput",type:"bool"},{name:"octaves",type:"int"},{name:"lacunarity",type:"float"},{name:"diminish",type:"float"}]}),UC=Ed(([e])=>{const t=e.y,s=e.z,i=Gd().toVar();return Pd(t.lessThan(1e-4),()=>{i.assign(Gd(s,s,s))}).Else(()=>{let r=e.x;r=r.sub(zm(r)).mul(6).toVar();const n=Ld(nf(r)),o=r.sub(Dd(n)),a=s.mul(t.oneMinus()),l=s.mul(t.mul(o).oneMinus()),h=s.mul(t.mul(o.oneMinus()).oneMinus());Pd(n.equal(Ld(0)),()=>{i.assign(Gd(s,h,a))}).ElseIf(n.equal(Ld(1)),()=>{i.assign(Gd(l,s,a))}).ElseIf(n.equal(Ld(2)),()=>{i.assign(Gd(a,s,h))}).ElseIf(n.equal(Ld(3)),()=>{i.assign(Gd(a,l,s))}).ElseIf(n.equal(Ld(4)),()=>{i.assign(Gd(h,a,s))}).Else(()=>{i.assign(Gd(s,a,l))})}),i}).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),GC=Ed(([e])=>{const t=Gd(e).toVar(),s=Dd(t.x).toVar(),i=Dd(t.y).toVar(),r=Dd(t.z).toVar(),n=Dd(cf(s,cf(i,r))).toVar(),o=Dd(df(s,df(i,r))).toVar(),a=Dd(o.sub(n)).toVar(),l=Dd().toVar(),h=Dd().toVar(),u=Dd().toVar();return u.assign(o),Pd(o.greaterThan(0),()=>{h.assign(a.div(o))}).Else(()=>{h.assign(0)}),Pd(h.lessThanEqual(0),()=>{l.assign(0)}).Else(()=>{Pd(s.greaterThanEqual(o),()=>{l.assign(i.sub(r).div(a))}).ElseIf(i.greaterThanEqual(o),()=>{l.assign(Zp(2,r.sub(s).div(a)))}).Else(()=>{l.assign(Zp(4,s.sub(i).div(a)))}),l.mulAssign(1/6),Pd(l.lessThan(0),()=>{l.addAssign(1)})}),Gd(l,h,u)}).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),jC=Ed(([e])=>{const t=Gd(e).toVar(),s=Wd(rm(t,Gd(.04045))).toVar(),i=Gd(t.div(12.92)).toVar(),r=Gd(bf(df(t.add(Gd(.055)),Gd(0)).div(1.055),Gd(2.4))).toVar();return Af(i,r,s)}).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),$C=(e,t)=>{e=Dd(e),t=Dd(t);const s=Vd(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return Rf(e.sub(s),e.add(s),t)},WC=(e,t,s,i)=>Af(e,t,s[i].clamp()),HC=(e,t,s,i,r)=>Af(e,t,$C(s,i[r])),qC=Ed(([e,t,s])=>{const i=Um(e).toVar(),r=Qp(Dd(.5).mul(t.sub(s)),tx).div(i).toVar(),n=Qp(Dd(-.5).mul(t.sub(s)),tx).div(i).toVar(),o=Gd().toVar();o.x=i.x.greaterThan(Dd(0)).select(r.x,n.x),o.y=i.y.greaterThan(Dd(0)).select(r.y,n.y),o.z=i.z.greaterThan(Dd(0)).select(r.z,n.z);const a=cf(o.x,o.y,o.z).toVar();return tx.add(i.mul(a)).toVar().sub(s)}),XC=Ed(([e,t])=>{const s=e.x,i=e.y,r=e.z;let n=t.element(0).mul(.886227);return n=n.add(t.element(1).mul(1.023328).mul(i)),n=n.add(t.element(2).mul(1.023328).mul(r)),n=n.add(t.element(3).mul(1.023328).mul(s)),n=n.add(t.element(4).mul(.858086).mul(s).mul(i)),n=n.add(t.element(5).mul(.858086).mul(i).mul(r)),n=n.add(t.element(6).mul(r.mul(r).mul(.743125).sub(.247708))),n=n.add(t.element(7).mul(.858086).mul(s).mul(r)),n=n.add(t.element(8).mul(.429043).mul(Kp(s,s).sub(Kp(i,i)))),n});var YC=Object.freeze({__proto__:null,BRDF_GGX:tv,BRDF_Lambert:kw,BasicPointShadowFilter:XE,BasicShadowFilter:TE,Break:R_,Const:Qf,Continue:()=>Fg("continue").toStack(),DFGLUT:rv,D_GGX:Kw,Discard:Og,EPSILON:Tm,F_Schlick:zw,Fn:Ed,HALF_PI:Em,INFINITY:Sm,If:Pd,Loop:C_,NodeAccess:vc,NodeShaderStage:_c,NodeType:{BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},NodeUpdateType:wc,OnBeforeMaterialUpdate:e=>dA(cA.BEFORE_MATERIAL,e),OnBeforeObjectUpdate:e=>dA(cA.BEFORE_OBJECT,e),OnMaterialUpdate:e=>dA(cA.MATERIAL,e),OnObjectUpdate:e=>dA(cA.OBJECT,e),PCFShadowFilter:SE,PCFSoftShadowFilter:ME,PI:Mm,PI2:Am,PointShadowFilter:YE,Return:()=>Fg("return").toStack(),Schlick_to_F0:av,ScriptableNodeResources:cN,ShaderNode:xd,Stack:Bd,Switch:(...e)=>Gc.Switch(...e),TBNViewMatrix:ub,TWO_PI:Nm,VSMShadowFilter:AE,V_GGX_SmithCorrelated:Zw,Var:Zf,VarIntent:Kf,abs:Ym,acesFilmicToneMapping:QA,acos:qm,add:Zp,addMethodChaining:$c,addNodeElement:function(e){Yo("TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:tN,all:Cm,alphaT:gp,and:am,anisotropy:yp,anisotropyB:bp,anisotropyT:xp,any:Rm,append:e=>(Yo("TSL: append() has been renamed to Stack()."),Bd(e)),array:jp,arrayBuffer:e=>new kc(e,"ArrayBuffer"),asin:Hm,assign:Wp,atan:Xm,atan2:Ff,atomicAdd:(e,t)=>DN(BN.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>DN(BN.ATOMIC_AND,e,t),atomicFunc:DN,atomicLoad:e=>DN(BN.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>DN(BN.ATOMIC_MAX,e,t),atomicMin:(e,t)=>DN(BN.ATOMIC_MIN,e,t),atomicOr:(e,t)=>DN(BN.ATOMIC_OR,e,t),atomicStore:(e,t)=>DN(BN.ATOMIC_STORE,e,t),atomicSub:(e,t)=>DN(BN.ATOMIC_SUB,e,t),atomicXor:(e,t)=>DN(BN.ATOMIC_XOR,e,t),attenuationColor:Bp,attenuationDistance:Pp,attribute:Hg,attributeArray:(e,t="float")=>{let s,i;!0===t.isStruct?(s=t.layout.getLength(),i=cc("float")):(s=dc(t),i=cc(t));const r=new mA(e,s,i);return c_(r,t,e)},backgroundBlurriness:_A,backgroundIntensity:wA,backgroundRotation:vA,batch:S_,bentNormalView:db,billboarding:PM,bitAnd:cm,bitNot:dm,bitOr:pm,bitXor:mm,bitangentGeometry:ob,bitangentLocal:ab,bitangentView:lb,bitangentWorld:hb,bitcast:iM,blendBurn:hw,blendColor:pw,blendDodge:uw,blendOverlay:dw,blendScreen:cw,blur:oT,bool:Od,buffer:ry,bufferAttribute:wg,builtin:ly,builtinAOContext:Hf,builtinShadowContext:Wf,bumpMap:_b,burn:(...e)=>(Yo('TSL: "burn" has been renamed. Use "blendBurn" instead.'),hw(e)),bvec2:Ud,bvec3:Wd,bvec4:Yd,bypass:Pg,cache:Cg,call:qp,cameraFar:Ty,cameraIndex:wy,cameraNear:vy,cameraNormalMatrix:Ey,cameraPosition:Cy,cameraProjectionMatrix:Sy,cameraProjectionMatrixInverse:My,cameraViewMatrix:Ay,cameraViewport:Ry,cameraWorldMatrix:Ny,cbrt:Sf,cdl:zA,ceil:km,checker:iC,cineonToneMapping:YA,clamp:Nf,clearcoat:hp,clearcoatNormalView:gx,clearcoatRoughness:up,code:rN,color:Id,colorSpaceToWorking:hg,colorToDirection:e=>bd(e).mul(2).sub(1),compute:Ag,computeKernel:Mg,computeSkinning:(e,t=null)=>{const s=new A_(e);return s.positionNode=c_(new nu(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(m_).toVar(),s.skinIndexNode=c_(new nu(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(m_).toVar(),s.skinWeightNode=c_(new nu(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(m_).toVar(),s.bindMatrixNode=Up(e.bindMatrix,"mat4"),s.bindMatrixInverseNode=Up(e.bindMatrixInverse,"mat4"),s.boneMatricesNode=ry(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),s.toPositionNode=t,bd(s)},context:Gf,convert:ep,convertColorSpace:(e,t,s)=>bd(new ag(bd(e),t,s)),convertToTexture:(e,...t)=>e.isSampleNode||e.isTextureNode?e:e.isPassNode?e.getTextureNode():rA(e,...t),cos:$m,countLeadingZeros:lM,countOneBits:hM,countTrailingZeros:aM,cross:xf,cubeTexture:Dx,cubeTextureBase:Ix,dFdx:ef,dFdy:tf,dashSize:Mp,debug:Ug,decrement:_m,decrementBefore:xm,defaultBuildStages:Sc,defaultShaderStages:Tc,defined:gd,degrees:Bm,deltaTime:NM,densityFog:function(e,t){return Yo('TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.'),yN(e,gN(t))},densityFogFactor:gN,depth:ew,depthPass:(e,t,s)=>new WA(WA.DEPTH,e,t,s),determinant:lf,difference:gf,diffuseColor:rp,diffuseContribution:np,directPointLight:tC,directionToColor:pb,directionToFaceDirection:lx,dispersion:Ip,disposeShadowMaterial:CE,distance:ff,div:Jp,dodge:(...e)=>(Yo('TSL: "dodge" has been renamed. Use "blendDodge" instead.'),uw(e)),dot:yf,drawIndex:x_,dynamicBufferAttribute:(e,t=null,s=0,i=0)=>_g(e,t,s,i,zo),element:Jd,emissive:op,equal:tm,equals:uf,equirectUV:Aw,exp:Im,exp2:Dm,expression:Fg,faceDirection:ax,faceForward:Pf,faceforward:Of,float:Dd,floatBitsToInt:e=>new sM(e,"int","float"),floatBitsToUint:rM,floor:zm,fog:yN,fract:Gm,frameGroup:Op,frameId:EM,frontFacing:ox,fwidth:of,gain:(e,t)=>e.lessThan(.5)?cM(e.mul(2),t).div(2):Qp(1,cM(Kp(Qp(1,e),2),t).div(2)),gapSize:Ap,getConstNodeType:yd,getCurrentStack:Rd,getDirection:sT,getDistanceAttenuation:eC,getGeometryRoughness:Xw,getNormalFromDepth:aA,getParallaxCorrectNormal:qC,getRoughness:Yw,getScreenPosition:oA,getShIrradianceAt:XC,getShadowMaterial:EE,getShadowRenderObjectFunction:BE,getTextureIndex:JS,getViewPosition:nA,ggxConvolution:uT,globalId:AN,glsl:(e,t)=>rN(e,t,"glsl"),glslFn:(e,t)=>oN(e,t,"glsl"),grayscale:DA,greaterThan:rm,greaterThanEqual:om,hash:uM,highpModelNormalViewMatrix:Qy,highpModelViewMatrix:Zy,hue:OA,increment:bm,incrementBefore:ym,inspector:$g,instance:__,instanceIndex:m_,instancedArray:(e,t="float")=>{let s,i;!0===t.isStruct?(s=t.layout.getLength(),i=cc("float")):(s=dc(t),i=cc(t));const r=new pA(e,s,i);return c_(r,t,e)},instancedBufferAttribute:vg,instancedDynamicBufferAttribute:Tg,instancedMesh:v_,int:Ld,intBitsToFloat:e=>new sM(e,"float","int"),interleavedGradientNoise:lA,inverse:hf,inverseSqrt:Vm,inversesqrt:Vf,invocationLocalIndex:y_,invocationSubgroupIndex:g_,ior:Ep,iridescence:pp,iridescenceIOR:mp,iridescenceThickness:fp,isolate:Eg,ivec2:zd,ivec3:jd,ivec4:qd,js:(e,t)=>rN(e,t,"js"),label:qf,length:Qm,lengthSq:Mf,lessThan:im,lessThanEqual:nm,lightPosition:cE,lightProjectionUV:uE,lightShadowMatrix:hE,lightTargetDirection:mE,lightTargetPosition:dE,lightViewPosition:pE,lightingContext:z_,lights:(e=[])=>(new xE).setLights(e),linearDepth:tw,linearToneMapping:qA,localId:NN,log:Lm,log2:Fm,logarithmicDepthToViewZ:(e,t,s)=>{const i=e.mul(Lm(s.div(t)));return Dd(Math.E).pow(i).mul(t).negate()},luminance:VA,mat2:Zd,mat3:Qd,mat4:Kd,matcapUV:HT,materialAO:n_,materialAlphaTest:Tb,materialAnisotropy:Gb,materialAnisotropyVector:o_,materialAttenuationColor:Zb,materialAttenuationDistance:Yb,materialClearcoat:Fb,materialClearcoatNormal:Vb,materialClearcoatRoughness:Ob,materialColor:Sb,materialDispersion:i_,materialEmissive:Ab,materialEnvIntensity:Mx,materialEnvRotation:Ax,materialIOR:Xb,materialIridescence:jb,materialIridescenceIOR:$b,materialIridescenceThickness:Wb,materialLightMap:r_,materialLineDashOffset:t_,materialLineDashSize:Kb,materialLineGapSize:Jb,materialLineScale:Qb,materialLineWidth:e_,materialMetalness:Db,materialNormal:Lb,materialOpacity:Nb,materialPointSize:s_,materialReference:kx,materialReflectivity:Bb,materialRefractionRatio:Sx,materialRotation:zb,materialRoughness:Ib,materialSheen:kb,materialSheenRoughness:Ub,materialShininess:Mb,materialSpecular:Eb,materialSpecularColor:Rb,materialSpecularIntensity:Cb,materialSpecularStrength:Pb,materialThickness:qb,materialTransmission:Hb,max:df,maxMipLevel:Qg,mediumpModelViewMatrix:Yy,metalness:lp,min:cf,mix:Af,mixElement:If,mod:em,modInt:wm,modelDirection:ky,modelNormalMatrix:Hy,modelPosition:Gy,modelRadius:Wy,modelScale:jy,modelViewMatrix:Xy,modelViewPosition:$y,modelViewProjection:a_,modelWorldMatrix:Uy,modelWorldMatrixInverse:qy,morphReference:L_,mrt:tM,mul:Kp,mx_aastep:$C,mx_add:(e,t=Dd(0))=>Zp(e,t),mx_atan2:(e=Dd(0),t=Dd(1))=>Xm(e,t),mx_cell_noise_float:(e=qg())=>AC(e.convert("vec2|vec3")),mx_contrast:(e,t=1,s=.5)=>Dd(e).sub(s).mul(t).add(s),mx_divide:(e,t=Dd(1))=>Jp(e,t),mx_fractal_noise_float:(e=qg(),t=3,s=2,i=.5,r=1)=>EC(e,Ld(t),s,i).mul(r),mx_fractal_noise_vec2:(e=qg(),t=3,s=2,i=.5,r=1)=>RC(e,Ld(t),s,i).mul(r),mx_fractal_noise_vec3:(e=qg(),t=3,s=2,i=.5,r=1)=>CC(e,Ld(t),s,i).mul(r),mx_fractal_noise_vec4:(e=qg(),t=3,s=2,i=.5,r=1)=>PC(e,Ld(t),s,i).mul(r),mx_frame:()=>EM,mx_heighttonormal:(e,t)=>(e=Gd(e),t=Dd(t),_b(e,t)),mx_hsvtorgb:UC,mx_ifequal:(e,t,s,i)=>e.equal(t).mix(s,i),mx_ifgreater:(e,t,s,i)=>e.greaterThan(t).mix(s,i),mx_ifgreatereq:(e,t,s,i)=>e.greaterThanEqual(t).mix(s,i),mx_invert:(e,t=Dd(1))=>Qp(t,e),mx_modulo:(e,t=Dd(1))=>em(e,t),mx_multiply:(e,t=Dd(1))=>Kp(e,t),mx_noise_float:(e=qg(),t=1,s=0)=>SC(e.convert("vec2|vec3")).mul(t).add(s),mx_noise_vec3:(e=qg(),t=1,s=0)=>MC(e.convert("vec2|vec3")).mul(t).add(s),mx_noise_vec4:(e=qg(),t=1,s=0)=>{e=e.convert("vec2|vec3");return Hd(MC(e),SC(e.add(Vd(19,73)))).mul(t).add(s)},mx_place2d:(e,t=Vd(.5,.5),s=Vd(1,1),i=Dd(0),r=Vd(0,0))=>{let n=e;if(t&&(n=n.sub(t)),s&&(n=n.mul(s)),i){const e=i.mul(Math.PI/180),t=e.cos(),s=e.sin();n=Vd(n.x.mul(t).sub(n.y.mul(s)),n.x.mul(s).add(n.y.mul(t)))}return t&&(n=n.add(t)),r&&(n=n.add(r)),n},mx_power:(e,t=Dd(1))=>bf(e,t),mx_ramp4:(e,t,s,i,r=qg())=>{const n=r.x.clamp(),o=r.y.clamp(),a=Af(e,t,n),l=Af(s,i,n);return Af(a,l,o)},mx_ramplr:(e,t,s=qg())=>WC(e,t,s,"x"),mx_ramptb:(e,t,s=qg())=>WC(e,t,s,"y"),mx_rgbtohsv:GC,mx_rotate2d:(e,t)=>{e=Vd(e);const s=(t=Dd(t)).mul(Math.PI/180);return ZT(e,s)},mx_rotate3d:(e,t,s)=>{e=Gd(e),t=Dd(t),s=Gd(s);const i=t.mul(Math.PI/180),r=s.normalize(),n=i.cos(),o=i.sin(),a=Dd(1).sub(n);return e.mul(n).add(r.cross(e).mul(o)).add(r.mul(r.dot(e)).mul(a))},mx_safepower:(e,t=1)=>(e=Dd(e)).abs().pow(t).mul(e.sign()),mx_separate:(e,t=null)=>{if("string"==typeof t){const s={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3},i=t.replace(/^out/,"").toLowerCase();if(void 0!==s[i])return e.element(s[i])}if("number"==typeof t)return e.element(t);if("string"==typeof t&&1===t.length){const s={x:0,r:0,y:1,g:1,z:2,b:2,w:3,a:3};if(void 0!==s[t])return e.element(s[t])}return e},mx_splitlr:(e,t,s,i=qg())=>HC(e,t,s,i,"x"),mx_splittb:(e,t,s,i=qg())=>HC(e,t,s,i,"y"),mx_srgb_texture_to_lin_rec709:jC,mx_subtract:(e,t=Dd(0))=>Qp(e,t),mx_timer:()=>AM,mx_transform_uv:(e=1,t=0,s=qg())=>s.mul(e).add(t),mx_unifiednoise2d:(e,t=qg(),s=Vd(1,1),i=Vd(0,0),r=1,n=0,o=1,a=!1,l=1,h=2,u=.5)=>zC(e,t.convert("vec2|vec3"),s,i,r,n,o,a,l,h,u),mx_unifiednoise3d:(e,t=qg(),s=Vd(1,1),i=Vd(0,0),r=1,n=0,o=1,a=!1,l=1,h=2,u=.5)=>kC(e,t.convert("vec2|vec3"),s,i,r,n,o,a,l,h,u),mx_worley_noise_float:(e=qg(),t=1)=>FC(e.convert("vec2|vec3"),t,Ld(1)),mx_worley_noise_vec2:(e=qg(),t=1)=>OC(e.convert("vec2|vec3"),t,Ld(1)),mx_worley_noise_vec3:(e=qg(),t=1)=>VC(e.convert("vec2|vec3"),t,Ld(1)),negate:Km,neutralToneMapping:sN,nodeArray:vd,nodeImmutable:Sd,nodeObject:bd,nodeObjectIntent:_d,nodeObjects:wd,nodeProxy:Td,nodeProxyIntent:Md,normalFlat:cx,normalGeometry:hx,normalLocal:ux,normalMap:gb,normalView:mx,normalViewGeometry:dx,normalWorld:fx,normalWorldGeometry:px,normalize:Um,not:hm,notEqual:sm,numWorkgroups:SN,objectDirection:Iy,objectGroup:zp,objectPosition:Ly,objectRadius:Vy,objectScale:Fy,objectViewPosition:Oy,objectWorldMatrix:Dy,oneMinus:Jm,or:lm,orthographicDepthToViewZ:(e,t,s)=>t.sub(s).mul(e).sub(t),oscSawtooth:(e=AM)=>e.fract(),oscSine:(e=AM)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=AM)=>e.fract().round(),oscTriangle:(e=AM)=>e.add(.5).fract().mul(2).sub(1).abs(),output:Sp,outputStruct:KS,overlay:(...e)=>(Yo('TSL: "overlay" has been renamed. Use "blendOverlay" instead.'),dw(e)),overloadingFn:MM,packHalf2x16:fM,packSnorm2x16:pM,packUnorm2x16:mM,parabola:cM,parallaxDirection:cb,parallaxUV:(e,t)=>e.sub(cb.mul(t)),parameter:(e,t)=>new HS(e,t),pass:(e,t,s)=>new WA(WA.COLOR,e,t,s),passTexture:(e,t)=>new jA(e,t),pcurve:(e,t,s)=>bf(Jp(bf(e,t),Zp(bf(e,t),bf(Qp(1,e),s))),1/t),perspectiveDepthToViewZ:Q_,pmremTexture:IT,pointShadow:KE,pointUV:gA,pointWidth:Np,positionGeometry:Ky,positionLocal:Jy,positionPrevious:ex,positionView:ix,positionViewDirection:rx,positionWorld:tx,positionWorldDirection:sx,posterize:UA,pow:bf,pow2:_f,pow3:wf,pow4:vf,premultiplyAlpha:mw,property:sp,quadBroadcast:oE,quadSwapDiagonal:eE,quadSwapX:KN,quadSwapY:JN,radians:Pm,rand:Bf,range:wN,rangeFog:function(e,t,s){return Yo('TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.'),yN(e,fN(t,s))},rangeFogFactor:fN,reciprocal:rf,reference:Ox,referenceBuffer:Vx,reflect:mf,reflectVector:Cx,reflectView:Nx,reflector:e=>new ZM(e),refract:Cf,refractVector:Rx,refractView:Ex,reinhardToneMapping:XA,remap:Ig,remapClamp:Dg,renderGroup:Vp,renderOutput:zg,rendererReference:pg,replaceDefaultUV:function(e,t=null){return Gf(t,{getUV:e})},rotate:ZT,rotateUV:CM,roughness:ap,round:sf,rtt:rA,sRGBTransferEOTF:rg,sRGBTransferOETF:ng,sample:(e,t=null)=>new uA(e,bd(t)),sampler:e=>(!0===e.isNode?e:ty(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:ty(e)).convert("samplerComparison"),saturate:Ef,saturation:LA,screen:(...e)=>(Yo('TSL: "screen" has been renamed. Use "blendScreen" instead.'),cw(e)),screenCoordinate:fy,screenDPR:dy,screenSize:my,screenUV:py,scriptable:pN,scriptableValue:lN,select:kf,setCurrentStack:Cd,setName:$f,shaderStages:Mc,shadow:zE,shadowPositionWorld:_E,shapeCircle:rC,sharedUniformGroup:Fp,sheen:cp,sheenRoughness:dp,shiftLeft:fm,shiftRight:gm,shininess:Tp,sign:Zm,sin:jm,sinc:(e,t)=>jm(Mm.mul(t.mul(e).sub(1))).div(Mm.mul(t.mul(e).sub(1))),skinning:N_,smoothstep:Rf,smoothstepElement:Df,specularColor:_p,specularColorBlended:wp,specularF90:vp,spherizeUV:RM,split:(e,t)=>bd(new Lc(bd(e),t)),spritesheetUV:DM,sqrt:Om,stack:XS,step:pf,stepElement:Lf,storage:c_,storageBarrier:()=>CN("storage").toStack(),storageObject:(e,t,s)=>(Yo('TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.'),c_(e,t,s).setPBO(!0)),storageTexture:SA,string:(e="")=>new kc(e,"string"),struct:(e,t=null)=>{const s=new YS(e,t),i=(...t)=>{let i=null;if(t.length>0)if(t[0].isNode){i={};const s=Object.keys(e);for(let e=0;e<t.length;e++)i[s[e]]=t[e]}else i=t[0];return new ZS(s,i)};return i.layout=s,i.isStruct=!0,i},sub:Qp,subBuild:eg,subgroupAdd:VN,subgroupAll:YN,subgroupAnd:$N,subgroupAny:ZN,subgroupBallot:ON,subgroupBroadcast:tE,subgroupBroadcastFirst:QN,subgroupElect:FN,subgroupExclusiveAdd:kN,subgroupExclusiveMul:jN,subgroupInclusiveAdd:zN,subgroupInclusiveMul:GN,subgroupIndex:f_,subgroupMax:XN,subgroupMin:qN,subgroupMul:UN,subgroupOr:WN,subgroupShuffle:sE,subgroupShuffleDown:nE,subgroupShuffleUp:rE,subgroupShuffleXor:iE,subgroupSize:EN,subgroupXor:HN,tan:Wm,tangentGeometry:tb,tangentLocal:sb,tangentView:ib,tangentWorld:rb,texture:ty,texture3D:NA,texture3DLevel:(e,t,s)=>NA(e,t).level(s),texture3DLoad:(...e)=>NA(...e).setSampler(!1),textureBarrier:()=>CN("texture").toStack(),textureBicubic:Av,textureBicubicLevel:Mv,textureCubeUV:iT,textureLevel:(e,t,s)=>ty(e,t).level(s),textureLoad:sy,textureSize:Yg,textureStore:(e,t,s)=>{const i=SA(e,t,s);return null!==s&&i.toStack(),i},thickness:Rp,time:AM,toneMapping:fg,toneMappingExposure:gg,toonOutlinePass:(e,t,s=new eh(0,0,0),i=.003,r=1)=>bd(new HA(e,t,bd(s),bd(i),bd(r))),transformDirection:Tf,transformNormal:yx,transformNormalToView:xx,transformedClearcoatNormalView:wx,transformedNormalView:bx,transformedNormalWorld:_x,transmission:Cp,transpose:af,triNoise3D:vM,triplanarTexture:(...e)=>LM(...e),triplanarTextures:LM,trunc:nf,uint:Fd,uintBitsToFloat:e=>new sM(e,"float","uint"),uniform:Up,uniformArray:ay,uniformCubeTexture:(e=Px)=>Ix(e),uniformFlow:jf,uniformGroup:Lp,uniformTexture:(e=Kg)=>ty(e),unpackHalf2x16:bM,unpackNormal:mb,unpackSnorm2x16:yM,unpackUnorm2x16:xM,unpremultiplyAlpha:fw,userData:(e,t,s)=>new EA(e,t,s),uv:qg,uvec2:kd,uvec3:$d,uvec4:Xd,varying:sg,varyingProperty:ip,vec2:Vd,vec3:Gd,vec4:Hd,vectorComponents:Ac,velocity:IA,vertexColor:lw,vertexIndex:p_,vertexStage:ig,vibrance:FA,viewZToLogarithmicDepth:K_,viewZToOrthographicDepth:Y_,viewZToPerspectiveDepth:Z_,viewport:gy,viewportCoordinate:xy,viewportDepthTexture:q_,viewportLinearDepth:sw,viewportMipTexture:$_,viewportResolution:_y,viewportSafeUV:BM,viewportSharedTexture:Tw,viewportSize:yy,viewportTexture:j_,viewportUV:by,vogelDiskSample:hA,wgsl:(e,t)=>rN(e,t,"wgsl"),wgslFn:(e,t)=>oN(e,t,"wgsl"),workgroupArray:(e,t)=>new PN("Workgroup",e,t),workgroupBarrier:()=>CN("workgroup").toStack(),workgroupId:MN,workingToColorSpace:lg,xor:um});const ZC=new WS;class QC extends dS{constructor(e,t){super(),this.renderer=e,this.nodes=t}update(e,t,s){const i=this.renderer,r=this.nodes.getBackgroundNode(e)||e.background;let n=!1;if(null===r)i._clearColor.getRGB(ZC),ZC.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(ZC),ZC.a=1,n=!0;else if(!0===r.isNode){const s=this.get(e),n=r;ZC.copy(i._clearColor);let o=s.backgroundMesh;if(void 0===o){let e=function(){r.removeEventListener("dispose",e),o.material.dispose(),o.geometry.dispose()};const t=Hd(n).mul(wA).context({getUV:()=>vA.mul(px),getTextureLevel:()=>_A}),i=Sy.element(3).element(3).equal(1),a=Jp(1,Sy.element(1).element(1)).mul(3),l=i.select(Jy.mul(a),Jy);let h=Sy.mul(Xy.mul(Hd(l,0)));h=h.setZ(h.w);const u=new gw;u.name="Background.material",u.side=1,u.depthTest=!1,u.depthWrite=!1,u.allowOverride=!1,u.fog=!1,u.lights=!1,u.vertexNode=h,u.colorNode=t,s.backgroundMeshNode=t,s.backgroundMesh=o=new Fh(new Su(1,32,32),u),o.frustumCulled=!1,o.name="Background.mesh",r.addEventListener("dispose",e)}const a=n.getCacheKey();s.backgroundCacheKey!==a&&(s.backgroundMeshNode.node=Hd(n).mul(wA),s.backgroundMeshNode.needsUpdate=!0,o.material.needsUpdate=!0,s.backgroundCacheKey=a),t.unshift(o,o.geometry,o.material,0,0,null,null)}else Zo("Renderer: Unsupported background configuration.",r);const o=i.xr.getEnvironmentBlendMode();if("additive"===o?ZC.set(0,0,0,1):"alpha-blend"===o&&ZC.set(0,0,0,0),!0===i.autoClear||!0===n){const e=s.clearColorValue;e.r=ZC.r,e.g=ZC.g,e.b=ZC.b,e.a=ZC.a,!0!==i.backend.isWebGLBackend&&!0!==i.alpha||(e.r*=e.a,e.g*=e.a,e.b*=e.a),s.depthClearValue=i._clearDepth,s.stencilClearValue=i._clearStencil,s.clearColor=!0===i.autoClearColor,s.clearDepth=!0===i.autoClearDepth,s.clearStencil=!0===i.autoClearStencil}else s.clearColor=!1,s.clearDepth=!1,s.clearStencil=!1}}let KC=0;class JC{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=KC++}}class eR{constructor(e,t,s,i,r,n,o,a,l,h=[]){this.vertexShader=e,this.fragmentShader=t,this.computeShader=s,this.transforms=h,this.nodeAttributes=i,this.bindings=r,this.updateNodes=n,this.updateBeforeNodes=o,this.updateAfterNodes=a,this.observer=l,this.usedTimes=0}createBindings(){const e=[];for(const t of this.bindings){if(!0!==t.bindings[0].groupNode.shared){const s=new JC(t.name,[],t.index,t.bindingsReference);e.push(s);for(const e of t.bindings)s.bindings.push(e.clone())}else e.push(t)}return e}}class tR{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class sR{constructor(e,t,s){this.isNodeUniform=!0,this.name=e,this.type=t,this.node=s}get value(){return this.node.value}set value(e){this.node.value=e}get id(){return this.node.id}get groupNode(){return this.node.groupNode}}class iR{constructor(e,t,s=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=s,this.count=i}}class rR extends iR{constructor(e,t,s=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=s,this.interpolationSampling=i}}class nR{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let oR=0;class aR{constructor(e=null){this.id=oR++,this.nodesData=new WeakMap,this.parent=e}getData(e){let t=this.nodesData.get(e);return void 0===t&&null!==this.parent&&(t=this.parent.getData(e)),t}setData(e,t){this.nodesData.set(e,t)}}class lR{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class hR{constructor(e,t){this.name=e,this.value=t,this.boundary=0,this.itemSize=0,this.offset=0}setValue(e){this.value=e}getValue(){return this.value}}class uR extends hR{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class cR extends hR{constructor(e,t=new ua){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class dR extends hR{constructor(e,t=new da){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class pR extends hR{constructor(e,t=new Pa){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class mR extends hR{constructor(e,t=new eh){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class fR extends hR{constructor(e,t=new Ju){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class gR extends hR{constructor(e,t=new fa){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class yR extends hR{constructor(e,t=new ll){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class xR extends uR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class bR extends cR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class _R extends dR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class wR extends pR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class vR extends mR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class TR extends fR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class SR extends gR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class MR extends yR{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let AR=0;const NR=new WeakMap,ER=new WeakMap,CR=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),RR=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class PR{constructor(e,t,s){this.object=e,this.material=e&&e.material||null,this.geometry=e&&e.geometry||null,this.renderer=t,this.parser=s,this.scene=null,this.camera=null,this.nodes=[],this.sequentialNodes=[],this.updateNodes=[],this.updateBeforeNodes=[],this.updateAfterNodes=[],this.hashNodes={},this.observer=null,this.lightsNode=null,this.environmentNode=null,this.fogNode=null,this.clippingContext=null,this.vertexShader=null,this.fragmentShader=null,this.computeShader=null,this.flowNodes={vertex:[],fragment:[],compute:[]},this.flowCode={vertex:"",fragment:"",compute:""},this.uniforms={vertex:[],fragment:[],compute:[],index:0},this.structs={vertex:[],fragment:[],compute:[],index:0},this.types={vertex:[],fragment:[],compute:[],index:0},this.bindings={vertex:{},fragment:{},compute:{}},this.bindingsIndexes={},this.bindGroups=null,this.attributes=[],this.bufferAttributes=[],this.varyings=[],this.codes={},this.vars={},this.declarations={},this.flow={code:""},this.chaining=[],this.stack=XS(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new aR,this.globalCache=this.cache,this.flowsData=new WeakMap,this.shaderStage=null,this.buildStage=null,this.subBuildLayers=[],this.activeStacks=[],this.subBuildFn=null,this.fnCall=null,Object.defineProperty(this,"id",{value:AR++})}isOpaque(){const e=this.material;return!1===e.transparent&&1===e.blending&&!1===e.alphaToCoverage}getBindGroupsCache(){let e=ER.get(this.renderer);return void 0===e&&(e=new aS,ER.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new Ba(e,t,s)}createCubeRenderTarget(e,t){return new Nw(e,t)}includes(e){return this.nodes.includes(e)}getOutputStructName(){}_getBindGroup(e,t){const s=this.getBindGroupsCache(),i=[];let r,n=!0;for(const e of t)i.push(e),n=n&&!0!==e.groupNode.shared;return n?(r=s.get(i),void 0===r&&(r=new JC(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new JC(e,i,this.bindingsIndexes[e].group,i),r}getBindGroupArray(e,t){const s=this.bindings[t];let i=s[e];return void 0===i&&(void 0===this.bindingsIndexes[e]&&(this.bindingsIndexes[e]={binding:0,group:Object.keys(this.bindingsIndexes).length}),s[e]=i=[]),i}getBindings(){let e=this.bindGroups;if(null===e){const t={},s=this.bindings;for(const e of Mc)for(const i in s[e]){const r=s[e][i];(t[i]||(t[i]=[])).push(...r)}e=[];for(const s in t){const i=t[s],r=this._getBindGroup(s,i);e.push(r)}this.bindGroups=e}return e}sortBindingGroups(){const e=this.getBindings();e.sort((e,t)=>e.bindings[0].groupNode.order-t.bindings[0].groupNode.order);for(let t=0;t<e.length;t++){const s=e[t];this.bindingsIndexes[s.name].group=t,s.index=t}}setHashNode(e,t){this.hashNodes[t]=e}addNode(e){!1===this.nodes.includes(e)&&(this.nodes.push(e),this.setHashNode(e,e.getHash(this)))}addSequentialNode(e){!1===this.sequentialNodes.includes(e)&&this.sequentialNodes.push(e)}buildUpdateNodes(){for(const e of this.nodes){e.getUpdateType()!==wc.NONE&&this.updateNodes.push(e)}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t!==wc.NONE&&this.updateBeforeNodes.push(e),s!==wc.NONE&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===xn||e.magFilter===bn||e.magFilter===yn||e.magFilter===_n||e.minFilter===xn||e.minFilter===bn||e.minFilter===yn||e.minFilter===_n}addChain(e){this.chaining.push(e)}removeChain(e){if(this.chaining.pop()!==e)throw new Error("NodeBuilder: Invalid node chaining!")}getMethod(e){return e}getTernary(){return null}getNodeFromHash(e){return this.hashNodes[e]}addFlow(e,t){return this.flowNodes[e].push(t),t}setContext(e){this.context=e}getContext(){return this.context}addContext(e){const t=this.getContext();return this.setContext({...this.context,...e}),t}getSharedContext(){const e={...this.context};return delete e.material,delete e.getUV,delete e.getOutput,delete e.getTextureLevel,delete e.getAO,delete e.getShadow,e}setCache(e){this.cache=e}getCache(){return this.cache}getCacheFromNode(e,t=!0){const s=this.getDataFromNode(e);return void 0===s.cache&&(s.cache=new aR(t?this.getCache():null)),s.cache}isAvailable(){return!1}getVertexIndex(){Yo("Abstract function.")}getInstanceIndex(){Yo("Abstract function.")}getDrawIndex(){Yo("Abstract function.")}getFrontFacing(){Yo("Abstract function.")}getFragCoord(){Yo("Abstract function.")}isFlipY(){return!1}increaseUsage(e){const t=this.getDataFromNode(e);return t.usageCount=void 0===t.usageCount?1:t.usageCount+1,t.usageCount}generateTexture(){Yo("Abstract function.")}generateTextureLod(){Yo("Abstract function.")}generateArrayDeclaration(e,t){return this.getType(e)+"[ "+t+" ]"}generateArray(e,t,s=null){let i=this.generateArrayDeclaration(e,t)+"( ";for(let r=0;r<t;r++){const n=s?s[r]:null;i+=null!==n?n.build(this,e):this.generateConst(e),r<t-1&&(i+=", ")}return i+=" )",i}generateStruct(e,t,s=null){const i=[];for(const e of t){const{name:t,type:r}=e;s&&s[t]&&s[t].isNode?i.push(s[t].build(this,r)):i.push(this.generateConst(r))}return e+"( "+i.join(", ")+" )"}generateConst(e,t=null){if(null===t&&("float"===e||"int"===e||"uint"===e?t=0:"bool"===e?t=!1:"color"===e?t=new eh:"vec2"===e||"uvec2"===e||"ivec2"===e?t=new ua:"vec3"===e||"uvec3"===e||"ivec3"===e?t=new da:"vec4"!==e&&"uvec4"!==e&&"ivec4"!==e||(t=new Pa)),"float"===e)return RR(t);if("int"===e)return`${Math.round(t)}`;if("uint"===e)return t>=0?`${Math.round(t)}u`:"0u";if("bool"===e)return t?"true":"false";if("color"===e)return`${this.getType("vec3")}( ${RR(t.r)}, ${RR(t.g)}, ${RR(t.b)} )`;const s=this.getTypeLength(e),i=this.getComponentType(e),r=e=>this.generateConst(i,e);if(2===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)} )`;if(3===s)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)} )`;if(4===s&&"mat2"!==e)return`${this.getType(e)}( ${r(t.x)}, ${r(t.y)}, ${r(t.z)}, ${r(t.w)} )`;if(s>=4&&t&&(t.isMatrix2||t.isMatrix3||t.isMatrix4))return`${this.getType(e)}( ${t.elements.map(r).join(", ")} )`;if(s>4)return`${this.getType(e)}()`;throw new Error(`NodeBuilder: Type '${e}' not found in generate constant attempt.`)}getType(e){return"color"===e?"vec3":e}hasGeometryAttribute(e){return this.geometry&&void 0!==this.geometry.getAttribute(e)}getAttribute(e,t){const s=this.attributes;for(const t of s)if(t.name===e)return t;const i=new tR(e,t);return this.registerDeclaration(i),s.push(i),i}getPropertyName(e){return e.name}isVector(e){return/vec\d/.test(e)}isMatrix(e){return/mat\d/.test(e)}isReference(e){return"void"===e||"property"===e||"sampler"===e||"samplerComparison"===e||"texture"===e||"cubeTexture"===e||"storageTexture"===e||"depthTexture"===e||"texture3D"===e}needsToWorkingColorSpace(){return!1}getComponentTypeFromTexture(e){const t=e.type;if(e.isDataTexture){if(t===Mn)return"int";if(t===An)return"uint"}return"float"}getElementType(e){return"mat2"===e?"vec2":"mat3"===e?"vec3":"mat4"===e?"vec4":this.getComponentType(e)}getComponentType(e){if("float"===(e=this.getVectorType(e))||"bool"===e||"int"===e||"uint"===e)return e;const t=/(b|i|u|)(vec|mat)([2-4])/.exec(e);return null===t?null:"b"===t[1]?"bool":"i"===t[1]?"int":"u"===t[1]?"uint":"float"}getVectorType(e){return"color"===e?"vec3":"texture"===e||"cubeTexture"===e||"storageTexture"===e||"texture3D"===e?"vec4":e}getTypeFromLength(e,t="float"){if(1===e)return t;let s=uc(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(s=s.replace("vec","mat")),i+s}getTypeFromArray(e){return CR.get(e.constructor)}isInteger(e){return/int|uint|(i|u)vec/.test(e)}getTypeFromAttribute(e){let t=e;e.isInterleavedBufferAttribute&&(t=e.data);const s=t.array,i=e.itemSize,r=e.normalized;let n;return e instanceof fh||!0===r||(n=this.getTypeFromArray(s)),this.getTypeFromLength(i,n)}getTypeLength(e){const t=this.getVectorType(e),s=/vec([2-4])/.exec(t);return null!==s?Number(s[1]):"float"===t||"bool"===t||"int"===t||"uint"===t?1:!0===/mat2/.test(e)?4:!0===/mat3/.test(e)?9:!0===/mat4/.test(e)?16:0}getVectorFromMatrix(e){return e.replace("mat","vec")}changeComponentType(e,t){return this.getTypeFromLength(this.getTypeLength(e),t)}getIntegerType(e){const t=this.getComponentType(e);return"int"===t||"uint"===t?e:this.changeComponentType(e,"int")}setActiveStack(e){this.activeStacks.push(e)}removeActiveStack(e){if(this.activeStacks[this.activeStacks.length-1]!==e)throw new Error("NodeBuilder: Invalid active stack removal.");this.activeStacks.pop()}getActiveStack(){return this.activeStacks[this.activeStacks.length-1]}getBaseStack(){return this.activeStacks[0]}addStack(){this.stack=XS(this.stack);const e=Rd();return this.stacks.push(e),Cd(this.stack),this.stack}removeStack(){const e=this.stack;for(const t of e.nodes){this.getDataFromNode(t).stack=e}return this.stack=e.parent,Cd(this.stacks.pop()),e}getDataFromNode(e,t=this.shaderStage,s=null){let i=(s=null===s?e.isGlobal(this)?this.globalCache:this.cache:s).getData(e);void 0===i&&(i={},s.setData(e,i)),void 0===i[t]&&(i[t]={});let r=i[t];const n=i.any?i.any.subBuilds:null,o=this.getClosestSubBuild(n);return o&&(void 0===r.subBuildsCache&&(r.subBuildsCache={}),r=r.subBuildsCache[o]||(r.subBuildsCache[o]={}),r.subBuilds=n),r}getNodeProperties(e,t="any"){const s=this.getDataFromNode(e,t);return s.properties||(s.properties={outputNode:null})}getBufferAttributeFromNode(e,t){const s=this.getDataFromNode(e,"vertex");let i=s.bufferAttribute;if(void 0===i){const r=this.uniforms.index++;i=new tR("nodeAttribute"+r,t,e),this.bufferAttributes.push(i),s.bufferAttribute=i}return i}getStructTypeNode(e,t=this.shaderStage){return this.types[t][e]||null}getStructTypeFromNode(e,t,s=null,i=this.shaderStage){const r=this.getDataFromNode(e,i,this.globalCache);let n=r.structType;if(void 0===n){const o=this.structs.index++;null===s&&(s="StructType"+o),n=new lR(s,t),this.structs[i].push(n),this.types[i][s]=e,r.structType=n}return n}getOutputStructTypeFromNode(e,t){const s=this.getStructTypeFromNode(e,t,"OutputType","fragment");return s.output=!0,s}getUniformFromNode(e,t,s=this.shaderStage,i=null){const r=this.getDataFromNode(e,s,this.globalCache);let n=r.uniform;if(void 0===n){const o=this.uniforms.index++;n=new sR(i||"nodeUniform"+o,t,e),this.uniforms[s].push(n),this.registerDeclaration(n),r.uniform=n}return n}getVarFromNode(e,t=null,s=e.getNodeType(this),i=this.shaderStage,r=!1){const n=this.getDataFromNode(e,i),o=this.getSubBuildProperty("variable",n.subBuilds);let a=n[o];if(void 0===a){const l=r?"_const":"_var",h=this.vars[i]||(this.vars[i]=[]),u=this.vars[l]||(this.vars[l]=0);null===t&&(t=(r?"nodeConst":"nodeVar")+u,this.vars[l]++),"variable"!==o&&(t=this.getSubBuildProperty(t,n.subBuilds));const c=e.getArrayCount(this);a=new iR(t,s,r,c),r||h.push(a),this.registerDeclaration(a),n[o]=a}return a}isDeterministic(e){if(e.isMathNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode))&&(!e.cNode||this.isDeterministic(e.cNode));if(e.isOperatorNode)return this.isDeterministic(e.aNode)&&(!e.bNode||this.isDeterministic(e.bNode));if(e.isArrayNode){if(null!==e.values)for(const t of e.values)if(!this.isDeterministic(t))return!1;return!0}return!!e.isConstNode}getVaryingFromNode(e,t=null,s=e.getNodeType(this),i=null,r=null){const n=this.getDataFromNode(e,"any"),o=this.getSubBuildProperty("varying",n.subBuilds);let a=n[o];if(void 0===a){const e=this.varyings,l=e.length;null===t&&(t="nodeVarying"+l),"varying"!==o&&(t=this.getSubBuildProperty(t,n.subBuilds)),a=new rR(t,s,i,r),e.push(a),this.registerDeclaration(a),n[o]=a}return a}registerDeclaration(e){const t=this.shaderStage,s=this.declarations[t]||(this.declarations[t]={}),i=this.getPropertyName(e);let r=1,n=i;for(;void 0!==s[n];)n=i+"_"+r++;r>1&&(e.name=n,Yo(`TSL: Declaration name '${i}' of '${e.type}' already in use. Renamed to '${n}'.`)),s[n]=e}getCodeFromNode(e,t,s=this.shaderStage){const i=this.getDataFromNode(e);let r=i.code;if(void 0===r){const e=this.codes[s]||(this.codes[s]=[]),n=e.length;r=new nR("nodeCode"+n,t),e.push(r),i.code=r}return r}addFlowCodeHierarchy(e,t){const{flowCodes:s,flowCodeBlock:i}=this.getDataFromNode(e);let r=!0,n=t;for(;n;){if(!0===i.get(n)){r=!1;break}n=this.getDataFromNode(n).parentNodeBlock}if(r)for(const e of s)this.addLineFlowCode(e)}addLineFlowCodeBlock(e,t,s){const i=this.getDataFromNode(e),r=i.flowCodes||(i.flowCodes=[]),n=i.flowCodeBlock||(i.flowCodeBlock=new WeakMap);r.push(t),n.set(s,!0)}addLineFlowCode(e,t=null){return""===e||(null!==t&&this.context.nodeBlock&&this.addLineFlowCodeBlock(t,e,this.context.nodeBlock),e=this.tab+e,/;\s*$/.test(e)||(e+=";\n"),this.flow.code+=e),this}addFlowCode(e){return this.flow.code+=e,this}addFlowTab(){return this.tab+="\t",this}removeFlowTab(){return this.tab=this.tab.slice(0,-1),this}getFlowData(e){return this.flowsData.get(e)}flowNode(e){const t=e.getNodeType(this),s=this.flowChildNode(e,t);return this.flowsData.set(e,s),s}addInclude(e){null!==this.currentFunctionNode&&this.currentFunctionNode.includes.push(e)}buildFunctionNode(e){const t=new nN,s=this.currentFunctionNode;return this.currentFunctionNode=t,t.code=this.buildFunctionCode(e),this.currentFunctionNode=s,t}flowShaderNode(e){const t=e.layout,s={[Symbol.iterator](){let e=0;const t=Object.values(this);return{next:()=>({value:t[e],done:e++>=t.length})}}};for(const e of t.inputs)s[e.name]=new HS(e.type,e.name);e.layout=null;const i=e.call(s),r=this.flowStagesNode(i,t.type);return e.layout=t,r}flowBuildStage(e,t,s=null){const i=this.getBuildStage();this.setBuildStage(t);const r=e.build(this,s);return this.setBuildStage(i),r}flowStagesNode(e,t=null){const s=this.flow,i=this.vars,r=this.declarations,n=this.cache,o=this.buildStage,a=this.stack,l={code:""};this.flow=l,this.vars={},this.declarations={},this.cache=new aR,this.stack=XS();for(const s of Sc)this.setBuildStage(s),l.result=e.build(this,t);return l.vars=this.getVars(this.shaderStage),this.flow=s,this.vars=i,this.declarations=r,this.cache=n,this.stack=a,this.setBuildStage(o),l}getFunctionOperator(){return null}buildFunctionCode(){Yo("Abstract function.")}flowChildNode(e,t=null){const s=this.flow,i={code:""};return this.flow=i,i.result=e.build(this,t),this.flow=s,i}flowNodeFromShaderStage(e,t,s=null,i=null){const r=this.tab,n=this.cache,o=this.shaderStage,a=this.context;this.setShaderStage(e);const l={...this.context};delete l.nodeBlock,this.cache=this.globalCache,this.tab="\t",this.context=l;let h=null;if("generate"===this.buildStage){const r=this.flowChildNode(t,s);null!==i&&(r.code+=`${this.tab+i} = ${r.result};\n`),this.flowCode[e]=this.flowCode[e]+r.code,h=r}else h=t.build(this);return this.setShaderStage(o),this.cache=n,this.tab=r,this.context=a,h}getAttributesArray(){return this.attributes.concat(this.bufferAttributes)}getAttributes(){Yo("Abstract function.")}getVaryings(){Yo("Abstract function.")}getVar(e,t,s=null){return`${null!==s?this.generateArrayDeclaration(e,s):this.getType(e)} ${t}`}getVars(e){let t="";const s=this.vars[e];if(void 0!==s)for(const e of s)t+=`${this.getVar(e.type,e.name)}; `;return t}getUniforms(){Yo("Abstract function.")}getCodes(e){const t=this.codes[e];let s="";if(void 0!==t)for(const e of t)s+=e.code+"\n";return s}getHash(){return this.vertexShader+this.fragmentShader+this.computeShader}setShaderStage(e){this.shaderStage=e}getShaderStage(){return this.shaderStage}setBuildStage(e){this.buildStage=e}getBuildStage(){return this.buildStage}buildCode(){Yo("Abstract function.")}get subBuild(){return this.subBuildLayers[this.subBuildLayers.length-1]||null}addSubBuild(e){this.subBuildLayers.push(e)}removeSubBuild(){return this.subBuildLayers.pop()}getClosestSubBuild(e){let t;if(t=e&&e.isNode?e.isShaderCallNodeInternal?e.shaderNode.subBuilds:e.isStackNode?[e.subBuild]:this.getDataFromNode(e,"any").subBuilds:e instanceof Set?[...e]:e,!t)return null;const s=this.subBuildLayers;for(let e=t.length-1;e>=0;e--){const i=t[e];if(s.includes(i))return i}return null}getSubBuildOutput(e){return this.getSubBuildProperty("outputNode",e)}getSubBuildProperty(e="",t=null){let s,i;return s=null!==t?this.getClosestSubBuild(t):this.subBuildFn,i=s?e?s+"_"+e:s:e,i}build(){const{object:e,material:t,renderer:s}=this;if(null!==t){let e=s.library.fromMaterial(t);null===e&&(Zo(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new gw),e.build(this)}else this.addFlow("compute",e);for(const e of Sc){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of Mc){this.setShaderStage(t);const s=this.flowNodes[t];for(const t of s)"generate"===e?this.flowNode(t):t.build(this)}}return this.setBuildStage(null),this.setShaderStage(null),this.buildCode(),this.buildUpdateNodes(),this}getSharedDataFromNode(e){let t=NR.get(e);return void 0===t&&(t={}),t}getNodeUniform(e,t){const s=this.getSharedDataFromNode(e);let i=s.cache;if(void 0===i){if("float"===t||"int"===t||"uint"===t)i=new xR(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)i=new bR(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)i=new _R(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)i=new wR(e);else if("color"===t)i=new vR(e);else if("mat2"===t)i=new TR(e);else if("mat3"===t)i=new SR(e);else{if("mat4"!==t)throw new Error(`Uniform "${t}" not implemented.`);i=new MR(e)}s.cache=i}return i}format(e,t,s){if((t=this.getVectorType(t))===(s=this.getVectorType(s))||null===s||this.isReference(s))return e;const i=this.getTypeLength(t),r=this.getTypeLength(s);return 16===i&&9===r?`${this.getType(s)}( ${e}[ 0 ].xyz, ${e}[ 1 ].xyz, ${e}[ 2 ].xyz )`:9===i&&4===r?`${this.getType(s)}( ${e}[ 0 ].xy, ${e}[ 1 ].xy )`:i>4||r>4||0===r?e:i===r?`${this.getType(s)}( ${e} )`:i>r?(e="bool"===s?`all( ${e} )`:`${e}.${"xyz".slice(0,r)}`,this.format(e,this.getTypeFromLength(r,this.getComponentType(t)),s)):4===r&&i>1?`${this.getType(s)}( ${this.format(e,t,"vec3")}, 1.0 )`:2===i?`${this.getType(s)}( ${this.format(e,t,"vec2")}, 0.0 )`:(1===i&&r>1&&t!==this.getComponentType(s)&&(e=`${this.getType(this.getComponentType(s))}( ${e} )`),`${this.getType(s)}( ${e} )`)}getSignature(){return`// Three.js r${Xr} - Node System\n`}}class BR{constructor(){this.time=0,this.deltaTime=0,this.frameId=0,this.renderId=0,this.updateMap=new WeakMap,this.updateBeforeMap=new WeakMap,this.updateAfterMap=new WeakMap,this.renderer=null,this.material=null,this.camera=null,this.object=null,this.scene=null}_getMaps(e,t){let s=e.get(t);return void 0===s&&(s={renderId:0,frameId:0},e.set(t,s)),s}updateBeforeNode(e){const t=e.getUpdateBeforeType(),s=e.updateReference(this);if(t===wc.FRAME){const t=this._getMaps(this.updateBeforeMap,s);if(t.frameId!==this.frameId){const s=t.frameId;t.frameId=this.frameId,!1===e.updateBefore(this)&&(t.frameId=s)}}else if(t===wc.RENDER){const t=this._getMaps(this.updateBeforeMap,s);if(t.renderId!==this.renderId){const s=t.renderId;t.renderId=this.renderId,!1===e.updateBefore(this)&&(t.renderId=s)}}else t===wc.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===wc.FRAME){const t=this._getMaps(this.updateAfterMap,s);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===wc.RENDER){const t=this._getMaps(this.updateAfterMap,s);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===wc.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===wc.FRAME){const t=this._getMaps(this.updateMap,s);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===wc.RENDER){const t=this._getMaps(this.updateMap,s);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===wc.OBJECT&&e.update(this)}update(){this.frameId++,void 0===this.lastTime&&(this.lastTime=performance.now()),this.deltaTime=(performance.now()-this.lastTime)/1e3,this.lastTime=performance.now(),this.time+=this.deltaTime}}class IR{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}IR.isNodeFunctionInput=!0;class DR extends JE{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:mE(this.light),lightColor:e}}}const LR=new ll,FR=new ll;let OR=null;class VR extends JE{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Up(new da).setGroup(Vp),this.halfWidth=Up(new da).setGroup(Vp),this.updateType=wc.RENDER}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;FR.identity(),LR.copy(t.matrixWorld),LR.premultiply(s),FR.extractRotation(LR),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(FR),this.halfHeight.value.applyMatrix4(FR)}setupDirectRectArea(e){let t,s;e.isAvailable("float32Filterable")?(t=ty(OR.LTC_FLOAT_1),s=ty(OR.LTC_FLOAT_2)):(t=ty(OR.LTC_HALF_1),s=ty(OR.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:pE(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:s}}static setLTC(e){OR=e}}class zR extends JE{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Up(0).setGroup(Vp),this.penumbraCosNode=Up(0).setGroup(Vp),this.cutoffDistanceNode=Up(0).setGroup(Vp),this.decayExponentNode=Up(0).setGroup(Vp),this.colorNode=Up(this.color).setGroup(Vp)}update(e){super.update(e);const{light:t}=this;this.coneCosNode.value=Math.cos(t.angle),this.penumbraCosNode.value=Math.cos(t.angle*(1-t.penumbra)),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}getSpotAttenuation(e,t){const{coneCosNode:s,penumbraCosNode:i}=this;return Rf(s,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let s=t.projectionUV;return void 0===s&&(s=uE(this.light,e.context.positionWorld),t.projectionUV=s),s}setupDirect(e){const{colorNode:t,cutoffDistanceNode:s,decayExponentNode:i,light:r}=this,n=this.getLightVector(e),o=n.normalize(),a=o.dot(mE(r)),l=this.getSpotAttenuation(e,a),h=n.length(),u=eC({lightDistance:h,cutoffDistance:s,decayExponent:i});let c,d,p=t.mul(l).mul(u);if(r.colorNode?(d=this.getLightCoord(e),c=r.colorNode(d)):r.map&&(d=this.getLightCoord(e),c=ty(r.map,d.xy).onRenderUpdate(()=>r.map)),c){p=d.mul(2).sub(1).abs().lessThan(1).all().select(p.mul(c),p)}return{lightColor:p,lightDirection:o}}}class kR extends zR{static get type(){return"IESSpotLightNode"}getSpotAttenuation(e,t){const s=this.light.iesMap;let i=null;if(s&&!0===s.isTexture){const e=t.acos().mul(1/Math.PI);i=ty(s,Vd(e,0),0).r}else i=super.getSpotAttenuation(t);return i}}const UR=Ed(([e,t])=>{const s=e.abs().sub(t);return Qm(df(s,0)).add(cf(df(s.x,s.y),0))});class GR extends zR{static get type(){return"ProjectorLightNode"}update(e){super.update(e);const t=this.light;if(this.penumbraCosNode.value=Math.min(Math.cos(t.angle*(1-t.penumbra)),.99999),null===t.aspect){let e=1;null!==t.map&&(e=t.map.width/t.map.height),t.shadow.aspect=e}else t.shadow.aspect=t.aspect}getSpotAttenuation(e){const t=Dd(0),s=this.penumbraCosNode,i=hE(this.light).mul(e.context.positionWorld||tx);return Pd(i.w.greaterThan(0),()=>{const e=i.xyz.div(i.w),r=UR(e.xy.sub(Vd(.5)),Vd(.5)),n=Jp(-1,Qp(1,qm(s)).sub(1));t.assign(Ef(r.mul(-2).mul(n)))}),t}}class jR extends JE{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class $R extends JE{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=cE(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Up(new eh).setGroup(Vp)}update(e){const{light:t}=this;super.update(e),this.lightPositionNode.object3d=t,this.groundColorNode.value.copy(t.groundColor).multiplyScalar(t.intensity)}setup(e){const{colorNode:t,groundColorNode:s,lightDirectionNode:i}=this,r=fx.dot(i).mul(.5).add(.5),n=Af(s,t,r);e.context.irradiance.addAssign(n)}}class WR extends JE{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new da);this.lightProbe=ay(t)}update(e){const{light:t}=this;super.update(e);for(let e=0;e<9;e++)this.lightProbe.array[e].copy(t.sh.coefficients[e]).multiplyScalar(t.intensity)}setup(e){const t=XC(fx,this.lightProbe);e.context.irradiance.addAssign(t)}}class HR{parseFunction(){Yo("Abstract function.")}}class qR{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){Yo("Abstract function.")}}qR.isNodeFunction=!0;const XR=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,YR=/[a-z_0-9]+/gi,ZR="#pragma main";class QR extends qR{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:o,headerCode:a}=(e=>{const t=(e=e.trim()).indexOf(ZR),s=-1!==t?e.slice(t+12):e,i=s.match(XR);if(null!==i&&5===i.length){const r=i[4],n=[];let o=null;for(;null!==(o=YR.exec(r));)n.push(o);const a=[];let l=0;for(;l<n.length;){const e="const"===n[l][0];!0===e&&l++;let t=n[l][0];"in"===t||"out"===t||"inout"===t?l++:t="";const s=n[l++][0];let i=Number.parseInt(n[l][0]);!1===Number.isNaN(i)?l++:i=null;const r=n[l++][0];a.push(new IR(s,r,i,t,e))}const h=s.substring(i[0].length),u=void 0!==i[3]?i[3]:"";return{type:i[2],inputs:a,name:u,precision:void 0!==i[1]?i[1]:"",inputsCode:r,blockCode:h,headerCode:-1!==t?e.slice(0,t):""}}throw new Error("FunctionNode: Function is not a GLSL code.")})(e);super(t,s,i,r),this.inputsCode=n,this.blockCode=o,this.headerCode=a}getCode(e=this.name){let t;const s=this.blockCode;if(""!==s){const{type:i,inputsCode:r,headerCode:n,precision:o}=this;let a=`${i} ${e} ( ${r.trim()} )`;""!==o&&(a=`${o} ${a}`),t=n+a+s}else t="";return t}}class KR extends HR{parseFunction(e){return new QR(e)}}const JR=new WeakMap,eP=[],tP=[];class sP extends dS{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new BR,this.nodeBuilderCache=new Map,this.callHashCache=new aS,this.groupsData=new aS,this.cacheLib={}}updateGroup(e){const t=e.groupNode,s=t.name;if(s===zp.name)return!0;if(s===Vp.name){const t=this.get(e),s=this.nodeFrame.renderId;return t.renderId!==s&&(t.renderId=s,!0)}if(s===Op.name){const t=this.get(e),s=this.nodeFrame.frameId;return t.frameId!==s&&(t.frameId=s,!0)}eP[0]=t,eP[1]=e;let i=this.groupsData.get(eP);return void 0===i&&this.groupsData.set(eP,i={}),eP.length=0,i.version!==t.version&&(i.version=t.version,!0)}getForRenderCacheKey(e){return e.initialCacheKey}getForRender(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const{nodeBuilderCache:i}=this,r=this.getForRenderCacheKey(e);if(s=i.get(r),void 0===s){const t=t=>{const s=this.backend.createNodeBuilder(e.object,this.renderer);return s.scene=e.scene,s.material=t,s.camera=e.camera,s.context.material=t,s.lightsNode=e.lightsNode,s.environmentNode=this.getEnvironmentNode(e.scene),s.fogNode=this.getFogNode(e.scene),s.clippingContext=e.clippingContext,this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview&&s.enableMultiview(),s};let n=t(e.material);try{n.build()}catch(e){n=t(new gw),n.build(),Zo("TSL: "+e)}s=this._createNodeBuilderState(n),i.set(r,s)}s.usedTimes++,t.nodeBuilderState=s}return s}delete(e){if(e.isRenderObject){const t=this.get(e).nodeBuilderState;t.usedTimes--,0===t.usedTimes&&this.nodeBuilderCache.delete(this.getForRenderCacheKey(e))}return super.delete(e)}getForCompute(e){const t=this.get(e);let s=t.nodeBuilderState;if(void 0===s){const i=this.backend.createNodeBuilder(e,this.renderer);i.build(),s=this._createNodeBuilderState(i),t.nodeBuilderState=s}return s}_createNodeBuilderState(e){return new eR(e.vertexShader,e.fragmentShader,e.computeShader,e.getAttributesArray(),e.getBindings(),e.updateNodes,e.updateBeforeNodes,e.updateAfterNodes,e.observer,e.transforms)}getEnvironmentNode(e){this.updateEnvironment(e);let t=null;if(e.environmentNode&&e.environmentNode.isNode)t=e.environmentNode;else{const s=this.get(e);s.environmentNode&&(t=s.environmentNode)}return t}getBackgroundNode(e){this.updateBackground(e);let t=null;if(e.backgroundNode&&e.backgroundNode.isNode)t=e.backgroundNode;else{const s=this.get(e);s.backgroundNode&&(t=s.backgroundNode)}return t}getFogNode(e){return this.updateFog(e),e.fogNode||this.get(e).fogNode||null}getCacheKey(e,t){eP[0]=e,eP[1]=t;const s=this.renderer.info.calls,i=this.callHashCache.get(eP)||{};if(i.callId!==s){const r=this.getEnvironmentNode(e),n=this.getFogNode(e);t&&tP.push(t.getCacheKey(!0)),r&&tP.push(r.getCacheKey()),n&&tP.push(n.getCacheKey()),tP.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),tP.push(this.renderer.shadowMap.enabled?1:0),tP.push(this.renderer.shadowMap.type),i.callId=s,i.cacheKey=oc(tP),this.callHashCache.set(eP,i),tP.length=0}return eP.length=0,i.cacheKey}get isToneMappingState(){return!this.renderer.getRenderTarget()}updateBackground(e){const t=this.get(e),s=e.background;if(s){const i=0===e.backgroundBlurriness&&t.backgroundBlurriness>0||e.backgroundBlurriness>0&&0===t.backgroundBlurriness;if(t.background!==s||i){const r=this.getCacheNode("background",s,()=>{if(!0===s.isCubeTexture||303===s.mapping||304===s.mapping||306===s.mapping){if(e.backgroundBlurriness>0||306===s.mapping)return IT(s);{let e;return e=!0===s.isCubeTexture?Dx(s):ty(s),Bw(e)}}if(!0===s.isTexture)return ty(s,py.flipY()).setUpdateMatrix(!0);!0!==s.isColor&&Zo("WebGPUNodes: Unsupported background configuration.",s)},i);t.backgroundNode=r,t.background=s,t.backgroundBlurriness=e.backgroundBlurriness}}else t.backgroundNode&&(delete t.backgroundNode,delete t.background)}getCacheNode(e,t,s,i=!1){const r=this.cacheLib[e]||(this.cacheLib[e]=new WeakMap);let n=r.get(t);return(void 0===n||i)&&(n=s(),r.set(t,n)),n}updateFog(e){const t=this.get(e),s=e.fog;if(s){if(t.fog!==s){const e=this.getCacheNode("fog",s,()=>{if(s.isFogExp2){const e=Ox("color","color",s).setGroup(Vp),t=Ox("density","float",s).setGroup(Vp);return yN(e,gN(t))}if(s.isFog){const e=Ox("color","color",s).setGroup(Vp),t=Ox("near","float",s).setGroup(Vp),i=Ox("far","float",s).setGroup(Vp);return yN(e,fN(t,i))}Zo("Renderer: Unsupported fog configuration.",s)});t.fogNode=e,t.fog=s}}else delete t.fogNode,delete t.fog}updateEnvironment(e){const t=this.get(e),s=e.environment;if(s){if(t.environment!==s){const e=this.getCacheNode("environment",s,()=>!0===s.isCubeTexture?Dx(s):!0===s.isTexture?ty(s):void Zo("Nodes: Unsupported environment configuration.",s));t.environmentNode=e,t.environment=s}}else t.environmentNode&&(delete t.environmentNode,delete t.environment)}getNodeFrame(e=this.renderer,t=null,s=null,i=null,r=null){const n=this.nodeFrame;return n.renderer=e,n.scene=t,n.object=s,n.camera=i,n.material=r,n}getNodeFrameForRender(e){return this.getNodeFrame(e.renderer,e.scene,e.object,e.camera,e.material)}getOutputCacheKey(){const e=this.renderer;return e.toneMapping+","+e.currentColorSpace+","+e.xr.isPresenting}hasOutputChange(e){return JR.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=e.isArrayTexture?NA(e,Gd(py,ly("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):ty(e,py).renderOutput(t.toneMapping,t.currentColorSpace);return JR.set(e,s),i}updateBefore(e){const t=e.getNodeBuilderState();for(const s of t.updateBeforeNodes)this.getNodeFrameForRender(e).updateBeforeNode(s)}updateAfter(e){const t=e.getNodeBuilderState();for(const s of t.updateAfterNodes)this.getNodeFrameForRender(e).updateAfterNode(s)}updateForCompute(e){const t=this.getNodeFrame(),s=this.getForCompute(e);for(const e of s.updateNodes)t.updateNode(e)}updateForRender(e){const t=this.getNodeFrameForRender(e),s=e.getNodeBuilderState();for(const e of s.updateNodes)t.updateNode(e)}needsRefresh(e){const t=this.getNodeFrameForRender(e);return e.getMonitor().needsRefresh(e,t)}dispose(){super.dispose(),this.nodeFrame=new BR,this.nodeBuilderCache=new Map,this.cacheLib={}}}const iP=new hu;class rP{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new fa,this.clippingGroupContexts=new WeakMap,this.intersectionPlanes=[],this.unionPlanes=[],this.parentVersion=null,null!==e&&(this.viewNormalMatrix=e.viewNormalMatrix,this.clippingGroupContexts=e.clippingGroupContexts,this.shadowPass=e.shadowPass,this.viewMatrix=e.viewMatrix)}projectPlanes(e,t,s){const i=e.length;for(let r=0;r<i;r++){iP.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const i=t[s+r],n=iP.normal;i.x=-n.x,i.y=-n.y,i.z=-n.z,i.w=iP.constant}}updateGlobal(e,t){this.shadowPass=null!==e.overrideMaterial&&e.overrideMaterial.isShadowPassMaterial,this.viewMatrix=t.matrixWorldInverse,this.viewNormalMatrix.getNormalMatrix(this.viewMatrix)}update(e,t){let s=!1;e.version!==this.parentVersion&&(this.intersectionPlanes=Array.from(e.intersectionPlanes),this.unionPlanes=Array.from(e.unionPlanes),this.parentVersion=e.version),this.clipIntersection!==t.clipIntersection&&(this.clipIntersection=t.clipIntersection,this.clipIntersection?this.unionPlanes.length=e.unionPlanes.length:this.intersectionPlanes.length=e.intersectionPlanes.length);const i=t.clippingPlanes,r=i.length;let n,o;if(this.clipIntersection?(n=this.intersectionPlanes,o=e.intersectionPlanes.length):(n=this.unionPlanes,o=e.unionPlanes.length),n.length!==o+r){n.length=o+r;for(let e=0;e<r;e++)n[o+e]=new Pa;s=!0}this.projectPlanes(i,n,o),s&&(this.version++,this.cacheKey=`${this.intersectionPlanes.length}:${this.unionPlanes.length}`)}getGroupContext(e){if(this.shadowPass&&!e.clipShadows)return this;let t=this.clippingGroupContexts.get(e);return void 0===t&&(t=new rP(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class nP{constructor(e,t){this.bundleGroup=e,this.camera=t}}const oP=[];class aP{constructor(){this.bundles=new aS}get(e,t){const s=this.bundles;oP[0]=e,oP[1]=t;let i=s.get(oP);return void 0===i&&(i=new nP(e,t),s.set(oP,i)),oP.length=0,i}dispose(){this.bundles=new aS}}class lP{constructor(){this.lightNodes=new WeakMap,this.materialNodes=new Map,this.toneMappingNodes=new Map}fromMaterial(e){if(e.isNodeMaterial)return e;let t=null;const s=this.getMaterialNodeClass(e.type);if(null!==s){t=new s;for(const s in e)t[s]=e[s]}return t}addToneMapping(e,t){this.addType(e,t,this.toneMappingNodes)}getToneMappingFunction(e){return this.toneMappingNodes.get(e)||null}getMaterialNodeClass(e){return this.materialNodes.get(e)||null}addMaterial(e,t){this.addType(e,t,this.materialNodes)}getLightNodeClass(e){return this.lightNodes.get(e)||null}addLight(e,t){this.addClass(e,t,this.lightNodes)}addType(e,t,s){if(s.has(t))Yo(`Redefinition of node ${t}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"==typeof t||"object"==typeof t)throw new Error(`Base class ${t} is not a class.`);s.set(t,e)}}addClass(e,t,s){if(s.has(t))Yo(`Redefinition of node ${t.name}`);else{if("function"!=typeof e)throw new Error(`Node class ${e.name} is not a class.`);if("function"!=typeof t)throw new Error(`Base class ${t.name} is not a class.`);s.set(t,e)}}}const hP=new xE,uP=[];class cP extends aS{constructor(){super()}createNode(e=[]){return(new xE).setLights(e)}getNode(e,t){if(e.isQuadMesh)return hP;uP[0]=e,uP[1]=t;let s=this.get(uP);return void 0===s&&(s=this.createNode(),this.set(uP,s)),uP.length=0,s}}class dP extends Ba{constructor(e=1,t=1,s={}){super(e,t,s),this.isXRRenderTarget=!0,this._hasExternalTextures=!1,this._autoAllocateDepthBuffer=!0,this._isOpaqueFramebuffer=!1}copy(e){return super.copy(e),this._hasExternalTextures=e._hasExternalTextures,this._autoAllocateDepthBuffer=e._autoAllocateDepthBuffer,this._isOpaqueFramebuffer=e._isOpaqueFramebuffer,this}}const pP=new da,mP=new da;class fP extends Ko{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Wh,this._cameraL.viewport=new Pa,this._cameraR=new Wh,this._cameraR.viewport=new Pa,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new Qu,this._currentDepthNear=null,this._currentDepthFar=null,this._controllers=[],this._controllerInputSources=[],this._xrRenderTarget=null,this._layers=[],this._sessionUsesLayers=!1,this._supportsGlBinding="undefined"!=typeof XRWebGLBinding,this._frameBufferTargets=null,this._createXRLayer=_P.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new ua,this._onSessionEvent=yP.bind(this),this._onSessionEnd=xP.bind(this),this._onInputSourcesChange=bP.bind(this),this._onAnimationFrame=wP.bind(this),this._referenceSpace=null,this._referenceSpaceType="local-floor",this._customReferenceSpace=null,this._framebufferScaleFactor=1,this._foveation=1,this._session=null,this._glBaseLayer=null,this._glBinding=null,this._glProjLayer=null,this._xrFrame=null,this._supportsLayers=this._supportsGlBinding&&"createProjectionLayer"in XRWebGLBinding.prototype,this._useMultiviewIfPossible=t,this._useMultiview=!1}getController(e){return this._getController(e).getTargetRaySpace()}getControllerGrip(e){return this._getController(e).getGripSpace()}getHand(e){return this._getController(e).getHandSpace()}getFoveation(){if(null!==this._glProjLayer||null!==this._glBaseLayer)return this._foveation}setFoveation(e){this._foveation=e,null!==this._glProjLayer&&(this._glProjLayer.fixedFoveation=e),null!==this._glBaseLayer&&void 0!==this._glBaseLayer.fixedFoveation&&(this._glBaseLayer.fixedFoveation=e)}getFramebufferScaleFactor(){return this._framebufferScaleFactor}setFramebufferScaleFactor(e){this._framebufferScaleFactor=e,!0===this.isPresenting&&Yo("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&Yo("XRManager: Cannot change reference space type while presenting.")}getReferenceSpace(){return this._customReferenceSpace||this._referenceSpace}setReferenceSpace(e){this._customReferenceSpace=e}getCamera(){return this._cameraXR}getEnvironmentBlendMode(){if(null!==this._session)return this._session.environmentBlendMode}getBinding(){return null===this._glBinding&&this._supportsGlBinding&&(this._glBinding=new XRWebGLBinding(this._session,this._gl)),this._glBinding}getFrame(){return this._xrFrame}useMultiview(){return this._useMultiview}createQuadLayer(e,t,s,i,r,n,o,a={}){const l=new Tu(e,t),h=new dP(r,n,{format:Ln,type:wn,depthTexture:new _u(r,n,a.stencil?Pn:An,void 0,void 0,void 0,void 0,void 0,void 0,a.stencil?On:Fn),stencilBuffer:a.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});h._autoAllocateDepthBuffer=!0;const u=new rh({color:16777215,side:0});u.map=h.texture,u.map.offset.y=1,u.map.repeat.y=-1;const c=new Fh(l,u);c.position.copy(s),c.quaternion.copy(i);const d={type:"quad",width:e,height:t,translation:s,quaternion:i,pixelwidth:r,pixelheight:n,plane:c,material:u,rendercall:o,renderTarget:h};if(this._layers.push(d),null!==this._session){d.plane.material=new rh({color:16777215,side:0}),d.plane.material.blending=5,d.plane.material.blendEquation=Yr,d.plane.material.blendSrc=Kr,d.plane.material.blendDst=Kr,d.xrlayer=this._createXRLayer(d);const e=this._session.renderState.layers;e.unshift(d.xrlayer),this._session.updateRenderState({layers:e})}else h.isXRRenderTarget=!1;return c}createCylinderLayer(e,t,s,i,r,n,o,a,l={}){const h=new vu(e,e,e*t/s,64,64,!0,Math.PI-t/2,t),u=new dP(n,o,{format:Ln,type:wn,depthTexture:new _u(n,o,l.stencil?Pn:An,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?On:Fn),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});u._autoAllocateDepthBuffer=!0;const c=new rh({color:16777215,side:1});c.map=u.texture,c.map.offset.y=1,c.map.repeat.y=-1;const d=new Fh(h,c);d.position.copy(i),d.quaternion.copy(r);const p={type:"cylinder",radius:e,centralAngle:t,aspectratio:s,translation:i,quaternion:r,pixelwidth:n,pixelheight:o,plane:d,material:c,rendercall:a,renderTarget:u};if(this._layers.push(p),null!==this._session){p.plane.material=new rh({color:16777215,side:1}),p.plane.material.blending=5,p.plane.material.blendEquation=Yr,p.plane.material.blendSrc=Kr,p.plane.material.blendDst=Kr,p.xrlayer=this._createXRLayer(p);const e=this._session.renderState.layers;e.unshift(p.xrlayer),this._session.updateRenderState({layers:e})}else u.isXRRenderTarget=!1;return d}renderLayers(){const e=new da,t=new ca,s=this._renderer,i=this.isPresenting,r=s.getOutputRenderTarget(),n=s._frameBufferTarget;this.isPresenting=!1;const o=new ua;s.getSize(o);const a=s._quad;for(const i of this._layers)if(i.renderTarget.isXRRenderTarget=null!==this._session,i.renderTarget._hasExternalTextures=i.renderTarget.isXRRenderTarget,i.renderTarget.isXRRenderTarget&&this._sessionUsesLayers){i.xrlayer.transform=new XRRigidTransform(i.plane.getWorldPosition(e),i.plane.getWorldQuaternion(t));const r=this._glBinding.getSubImage(i.xrlayer,this._xrFrame);s.backend.setXRRenderTargetTextures(i.renderTarget,r.colorTexture,void 0),s._setXRLayerSize(i.renderTarget.width,i.renderTarget.height),s.setOutputRenderTarget(i.renderTarget),s.setRenderTarget(null),s._frameBufferTarget=null,this._frameBufferTargets||(this._frameBufferTargets=new WeakMap);const{frameBufferTarget:n,quad:o}=this._frameBufferTargets.get(i.renderTarget)||{frameBufferTarget:null,quad:null};n?(s._frameBufferTarget=n,s._quad=o):(s._quad=new tA(new gw),this._frameBufferTargets.set(i.renderTarget,{frameBufferTarget:s._getFrameBufferTarget(),quad:s._quad})),i.rendercall(),s._frameBufferTarget=null}else s.setRenderTarget(i.renderTarget),i.rendercall();s.setRenderTarget(null),s.setOutputRenderTarget(r),s._frameBufferTarget=n,s._setXRLayerSize(o.x,o.y),s._quad=a,this.isPresenting=i}getSession(){return this._session}async setSession(e){const t=this._renderer,s=t.backend;this._gl=t.getContext();const i=this._gl,r=i.getContextAttributes();if(this._session=e,null!==e){if(!0===s.isWebGPUBackend)throw new Error('THREE.XRManager: XR is currently not supported with a WebGPU backend. Use WebGL by passing "{ forceWebGL: true }" to the constructor of the renderer.');if(e.addEventListener("select",this._onSessionEvent),e.addEventListener("selectstart",this._onSessionEvent),e.addEventListener("selectend",this._onSessionEvent),e.addEventListener("squeeze",this._onSessionEvent),e.addEventListener("squeezestart",this._onSessionEvent),e.addEventListener("squeezeend",this._onSessionEvent),e.addEventListener("end",this._onSessionEnd),e.addEventListener("inputsourceschange",this._onInputSourcesChange),await s.makeXRCompatible(),this._currentPixelRatio=t.getPixelRatio(),t.getSize(this._currentSize),this._currentAnimationContext=t._animation.getContext(),this._currentAnimationLoop=t._animation.getAnimationLoop(),t._animation.stop(),!0===this._supportsLayers){let s=null,n=null,o=null;t.depth&&(o=t.stencil?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24,s=t.stencil?On:Fn,n=t.stencil?Pn:An);const a={colorFormat:i.RGBA8,depthFormat:o,scaleFactor:this._framebufferScaleFactor,clearOnAccess:!1};this._useMultiviewIfPossible&&t.hasFeature("OVR_multiview2")&&(a.textureType="texture-array",this._useMultiview=!0),this._glBinding=this.getBinding();const l=this._glBinding.createProjectionLayer(a),h=[l];this._glProjLayer=l,t.setPixelRatio(1),t._setXRLayerSize(l.textureWidth,l.textureHeight);const u=this._useMultiview?2:1,c=new _u(l.textureWidth,l.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,s,u);if(this._xrRenderTarget=new dP(l.textureWidth,l.textureHeight,{format:Ln,type:wn,colorSpace:t.outputColorSpace,depthTexture:c,stencilBuffer:t.stencil,samples:r.antialias?4:0,resolveDepthBuffer:!1===l.ignoreDepthValues,resolveStencilBuffer:!1===l.ignoreDepthValues,depth:this._useMultiview?2:1,multiview:this._useMultiview}),this._xrRenderTarget._hasExternalTextures=!0,this._xrRenderTarget.depth=this._useMultiview?2:1,this._sessionUsesLayers=e.enabledFeatures.includes("layers"),this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType()),this._sessionUsesLayers)for(const e of this._layers)e.plane.material=new rh({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=Yr,e.plane.material.blendSrc=Kr,e.plane.material.blendDst=Kr,e.xrlayer=this._createXRLayer(e),h.unshift(e.xrlayer);e.updateRenderState({layers:h})}else{const s={antialias:t.currentSamples>0,alpha:!0,depth:t.depth,stencil:t.stencil,framebufferScaleFactor:this.getFramebufferScaleFactor()},r=new XRWebGLLayer(e,i,s);this._glBaseLayer=r,e.updateRenderState({baseLayer:r}),t.setPixelRatio(1),t._setXRLayerSize(r.framebufferWidth,r.framebufferHeight),this._xrRenderTarget=new dP(r.framebufferWidth,r.framebufferHeight,{format:Ln,type:wn,colorSpace:t.outputColorSpace,stencilBuffer:t.stencil,resolveDepthBuffer:!1===r.ignoreDepthValues,resolveStencilBuffer:!1===r.ignoreDepthValues}),this._xrRenderTarget._isOpaqueFramebuffer=!0,this._referenceSpace=await e.requestReferenceSpace(this.getReferenceSpaceType())}this.setFoveation(this.getFoveation()),t._animation.setAnimationLoop(this._onAnimationFrame),t._animation.setContext(e),t._animation.start(),this.isPresenting=!0,this.dispatchEvent({type:"sessionstart"})}}updateCamera(e){const t=this._session;if(null===t)return;const s=e.near,i=e.far,r=this._cameraXR,n=this._cameraL,o=this._cameraR;r.near=o.near=n.near=s,r.far=o.far=n.far=i,r.isMultiViewCamera=this._useMultiview,this._currentDepthNear===r.near&&this._currentDepthFar===r.far||(t.updateRenderState({depthNear:r.near,depthFar:r.far}),this._currentDepthNear=r.near,this._currentDepthFar=r.far),r.layers.mask=6|e.layers.mask,n.layers.mask=3&r.layers.mask,o.layers.mask=5&r.layers.mask;const a=e.parent,l=r.cameras;gP(r,a);for(let e=0;e<l.length;e++)gP(l[e],a);2===l.length?function(e,t,s){pP.setFromMatrixPosition(t.matrixWorld),mP.setFromMatrixPosition(s.matrixWorld);const i=pP.distanceTo(mP),r=t.projectionMatrix.elements,n=s.projectionMatrix.elements,o=r[14]/(r[10]-1),a=r[14]/(r[10]+1),l=(r[9]+1)/r[5],h=(r[9]-1)/r[5],u=(r[8]-1)/r[0],c=(n[8]+1)/n[0],d=o*u,p=o*c,m=i/(-u+c),f=m*-u;if(t.matrixWorld.decompose(e.position,e.quaternion,e.scale),e.translateX(f),e.translateZ(m),e.matrixWorld.compose(e.position,e.quaternion,e.scale),e.matrixWorldInverse.copy(e.matrixWorld).invert(),-1===r[10])e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse);else{const t=o+m,s=a+m,r=d-f,n=p+(i-f),u=l*a/s*t,c=h*a/s*t;e.projectionMatrix.makePerspective(r,n,u,c,t,s),e.projectionMatrixInverse.copy(e.projectionMatrix).invert()}}(r,n,o):r.projectionMatrix.copy(n.projectionMatrix),function(e,t,s){null===s?e.matrix.copy(t.matrixWorld):(e.matrix.copy(s.matrixWorld),e.matrix.invert(),e.matrix.multiply(t.matrixWorld));e.matrix.decompose(e.position,e.quaternion,e.scale),e.updateMatrixWorld(!0),e.projectionMatrix.copy(t.projectionMatrix),e.projectionMatrixInverse.copy(t.projectionMatrixInverse),e.isPerspectiveCamera&&(e.fov=2*sa*Math.atan(1/e.projectionMatrix.elements[5]),e.zoom=1)}(e,r,a)}_getController(e){let t=this._controllers[e];return void 0===t&&(t=new Kh,this._controllers[e]=t),t}}function gP(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function yP(e){const t=this._controllerInputSources.indexOf(e.inputSource);if(-1===t)return;const s=this._controllers[t];if(void 0!==s){const t=this.getReferenceSpace();s.update(e.inputSource,e.frame,t),s.dispatchEvent({type:e.type,data:e.inputSource})}}function xP(){const e=this._session,t=this._renderer;e.removeEventListener("select",this._onSessionEvent),e.removeEventListener("selectstart",this._onSessionEvent),e.removeEventListener("selectend",this._onSessionEvent),e.removeEventListener("squeeze",this._onSessionEvent),e.removeEventListener("squeezestart",this._onSessionEvent),e.removeEventListener("squeezeend",this._onSessionEvent),e.removeEventListener("end",this._onSessionEnd),e.removeEventListener("inputsourceschange",this._onInputSourcesChange);for(let e=0;e<this._controllers.length;e++){const t=this._controllerInputSources[e];null!==t&&(this._controllerInputSources[e]=null,this._controllers[e].disconnect(t))}if(this._currentDepthNear=null,this._currentDepthFar=null,t._resetXRState(),this._session=null,this._xrRenderTarget=null,this._glBinding=null,this._glBaseLayer=null,this._glProjLayer=null,!0===this._sessionUsesLayers)for(const e of this._layers)e.renderTarget=new dP(e.pixelwidth,e.pixelheight,{format:Ln,type:wn,depthTexture:new _u(e.pixelwidth,e.pixelheight,e.stencilBuffer?Pn:An,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?On:Fn),stencilBuffer:e.stencilBuffer,resolveDepthBuffer:!1,resolveStencilBuffer:!1}),e.renderTarget.isXRRenderTarget=!1,e.plane.material=e.material,e.material.map=e.renderTarget.texture,e.material.map.offset.y=1,e.material.map.repeat.y=-1,delete e.xrlayer;this.isPresenting=!1,this._useMultiview=!1,t._animation.stop(),t._animation.setAnimationLoop(this._currentAnimationLoop),t._animation.setContext(this._currentAnimationContext),t._animation.start(),t.setPixelRatio(this._currentPixelRatio),t.setSize(this._currentSize.width,this._currentSize.height,!1),this.dispatchEvent({type:"sessionend"})}function bP(e){const t=this._controllers,s=this._controllerInputSources;for(let i=0;i<e.removed.length;i++){const r=e.removed[i],n=s.indexOf(r);n>=0&&(s[n]=null,t[n].disconnect(r))}for(let i=0;i<e.added.length;i++){const r=e.added[i];let n=s.indexOf(r);if(-1===n){for(let e=0;e<t.length;e++){if(e>=s.length){s.push(r),n=e;break}if(null===s[e]){s[e]=r,n=e;break}}if(-1===n)break}const o=t[n];o&&o.connect(r)}}function _P(e){return"quad"===e.type?this._glBinding.createQuadLayer({transform:new XRRigidTransform(e.translation,e.quaternion),width:e.width/2,height:e.height/2,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1}):this._glBinding.createCylinderLayer({transform:new XRRigidTransform(e.translation,e.quaternion),radius:e.radius,centralAngle:e.centralAngle,aspectRatio:e.aspectRatio,space:this._referenceSpace,viewPixelWidth:e.pixelwidth,viewPixelHeight:e.pixelheight,clearOnAccess:!1})}function wP(e,t){if(void 0===t)return;const s=this._cameraXR,i=this._renderer,r=i.backend,n=this._glBaseLayer,o=this.getReferenceSpace(),a=t.getViewerPose(o);if(this._xrFrame=t,null!==a){const e=a.views;null!==this._glBaseLayer&&r.setXRTarget(n.framebuffer);let t=!1;e.length!==s.cameras.length&&(s.cameras.length=0,t=!0);for(let i=0;i<e.length;i++){const o=e[i];let a;if(!0===this._supportsLayers){const e=this._glBinding.getViewSubImage(this._glProjLayer,o);a=e.viewport,0===i&&r.setXRRenderTargetTextures(this._xrRenderTarget,e.colorTexture,this._glProjLayer.ignoreDepthValues&&!this._useMultiview?void 0:e.depthStencilTexture)}else a=n.getViewport(o);let l=this._cameras[i];void 0===l&&(l=new Wh,l.layers.enable(i),l.viewport=new Pa,this._cameras[i]=l),l.matrix.fromArray(o.transform.matrix),l.matrix.decompose(l.position,l.quaternion,l.scale),l.projectionMatrix.fromArray(o.projectionMatrix),l.projectionMatrixInverse.copy(l.projectionMatrix).invert(),l.viewport.set(a.x,a.y,a.width,a.height),0===i&&(s.matrix.copy(l.matrix),s.matrix.decompose(s.position,s.quaternion,s.scale)),!0===t&&s.cameras.push(l)}i.setOutputRenderTarget(this._xrRenderTarget)}for(let e=0;e<this._controllers.length;e++){const s=this._controllerInputSources[e],i=this._controllers[e];null!==s&&void 0!==i&&i.update(s,t,o)}this._currentAnimationLoop&&this._currentAnimationLoop(e,t),t.detectedPlanes&&this.dispatchEvent({type:"planesdetected",data:t}),this._xrFrame=null}class vP extends Ko{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new Pa(0,0,this._width,this._height),this._scissor=new Pa(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new bu,this.depthTexture=new _u}getPixelRatio(){return this._pixelRatio}getDrawingBufferSize(e){return e.set(this._width*this._pixelRatio,this._height*this._pixelRatio).floor()}getSize(e){return e.set(this._width,this._height)}setPixelRatio(e=1){this._pixelRatio!==e&&(this._pixelRatio=e,this.setSize(this._width,this._height,!1))}setDrawingBufferSize(e,t,s){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this._pixelRatio=s,this.domElement.width=Math.floor(e*s),this.domElement.height=Math.floor(t*s),this.setViewport(0,0,e,t),this._dispatchResize())}setSize(e,t,s=!0){this.xr&&this.xr.isPresenting||(this._width=e,this._height=t,this.domElement.width=Math.floor(e*this._pixelRatio),this.domElement.height=Math.floor(t*this._pixelRatio),!0===s&&(this.domElement.style.width=e+"px",this.domElement.style.height=t+"px"),this.setViewport(0,0,e,t),this._dispatchResize())}getScissor(e){const t=this._scissor;return e.x=t.x,e.y=t.y,e.width=t.width,e.height=t.height,e}setScissor(e,t,s,i){const r=this._scissor;e.isVector4?r.copy(e):r.set(e,t,s,i)}getScissorTest(){return this._scissorTest}setScissorTest(e){this._scissorTest=e}getViewport(e){return e.copy(this._viewport)}setViewport(e,t,s,i,r=0,n=1){const o=this._viewport;e.isVector4?o.copy(e):o.set(e,t,s,i),o.minDepth=r,o.maxDepth=n}_dispatchResize(){this.dispatchEvent({type:"resize"})}dispose(){this.dispatchEvent({type:"dispose"})}}const TP=new Jh,SP=new ua,MP=new Pa,AP=new pu,NP=new gu,EP=new ll,CP=new Pa;class RP{constructor(e,t={}){this.isRenderer=!0;const{logarithmicDepthBuffer:s=!1,alpha:i=!0,depth:r=!0,stencil:n=!1,antialias:o=!1,samples:a=0,getFallback:l=null,outputBufferType:h=En,multiview:u=!1}=t;this.backend=e,this.autoClear=!0,this.autoClearColor=!0,this.autoClearDepth=!0,this.autoClearStencil=!0,this.alpha=i,this.logarithmicDepthBuffer=s,this.outputColorSpace=Mo,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=r,this.stencil=n,this.info=new vS,this.contextNode=Gf(),this.library=new lP,this.lighting=new cP,this._samples=a||!0===o?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new vP(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new Gg,this._inspector.setRenderer(this),this._getFallback=l,this._attributes=null,this._geometries=null,this._nodes=null,this._animation=null,this._bindings=null,this._objects=null,this._pipelines=null,this._bundles=null,this._renderLists=null,this._renderContexts=null,this._textures=null,this._background=null,this._quad=new tA(new gw),this._quad.name="Output Color Transform",this._quad.material.name="outputColorTransform",this._currentRenderContext=null,this._opaqueSort=null,this._transparentSort=null,this._frameBufferTarget=null;const c=!0===this.alpha?0:1;this._clearColor=new WS(0,0,0,c),this._clearDepth=1,this._clearStencil=0,this._renderTarget=null,this._activeCubeFace=0,this._activeMipmapLevel=0,this._outputRenderTarget=null,this._mrt=null,this._renderObjectFunction=null,this._currentRenderObjectFunction=null,this._currentRenderBundle=null,this._handleObjectFunction=this._renderObjectDirect,this._isDeviceLost=!1,this.onDeviceLost=this._onDeviceLost,this._outputBufferType=h,this._cacheShadowNodes=new WeakMap,this._initialized=!1,this._initPromise=null,this._compilationPromises=null,this.transparent=!0,this.opaque=!0,this.shadowMap={enabled:!1,type:1},this.xr=new fP(this,u),this.debug={checkShaderErrors:!0,onShaderError:null,getShaderAsync:async(e,t,s)=>{await this.compileAsync(e,t);const i=this._renderLists.get(e,t),r=this._renderContexts.get(e,t,this._renderTarget,this._mrt),n=e.overrideMaterial||s.material,o=this._objects.get(s,n,e,t,i.lightsNode,r,r.clippingContext),{fragmentShader:a,vertexShader:l}=o.getNodeBuilderState();return{fragmentShader:a,vertexShader:l}}}}async init(){return null!==this._initPromise||(this._initPromise=new Promise(async(e,t)=>{let s=this.backend;try{await s.init(this)}catch(e){if(null===this._getFallback)return void t(e);try{this.backend=s=this._getFallback(e),await s.init(this)}catch(e){return void t(e)}}this._nodes=new sP(this,s),this._animation=new oS(this,this._nodes,this.info),this._attributes=new xS(s),this._background=new QC(this,this._nodes),this._geometries=new wS(this._attributes,this.info),this._textures=new $S(this,s,this.info),this._pipelines=new ES(s,this._nodes),this._bindings=new CS(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new cS(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new LS(this.lighting),this._bundles=new aP,this._renderContexts=new GS,this._animation.start(),this._initialized=!0,this._inspector.init(),e(this)})),this._initPromise}get domElement(){return this._canvasTarget.domElement}get coordinateSystem(){return this.backend.coordinateSystem}async compileAsync(e,t,s=null){if(!0===this._isDeviceLost)return;!1===this._initialized&&await this.init();const i=this._nodes.nodeFrame,r=i.renderId,n=this._currentRenderContext,o=this._currentRenderObjectFunction,a=this._compilationPromises,l=!0===e.isScene?e:TP;null===s&&(s=e);const h=this._renderTarget,u=this._renderContexts.get(s,t,h,this._mrt),c=this._activeMipmapLevel,d=[];this._currentRenderContext=u,this._currentRenderObjectFunction=this.renderObject,this._handleObjectFunction=this._createObjectPipeline,this._compilationPromises=d,i.renderId++,i.update(),u.depth=this.depth,u.stencil=this.stencil,u.clippingContext||(u.clippingContext=new rP),u.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,h);const p=this._renderLists.get(e,t);if(p.begin(),this._projectObject(e,t,0,p,u.clippingContext),s!==e&&s.traverseVisible(function(e){e.isLight&&e.layers.test(t.layers)&&p.pushLight(e)}),p.finish(),null!==h){this._textures.updateRenderTarget(h,c);const e=this._textures.get(h);u.textures=e.textures,u.depthTexture=e.depthTexture}else u.textures=null,u.depthTexture=null;this._background.update(l,p,u);const m=p.opaque,f=p.transparent,g=p.transparentDoublePass,y=p.lightsNode;!0===this.opaque&&m.length>0&&this._renderObjects(m,t,l,y),!0===this.transparent&&f.length>0&&this._renderTransparents(f,g,t,l,y),i.renderId=r,this._currentRenderContext=n,this._currentRenderObjectFunction=o,this._compilationPromises=a,this._handleObjectFunction=this._renderObjectDirect,await Promise.all(d)}async renderAsync(e,t){Qo('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){Zo("Renderer: waitForGPU() has been removed. Read https://github.com/mrdoob/three.js/issues/32012 for more information.")}set inspector(e){null!==this._inspector&&this._inspector.setRenderer(null),this._inspector=e,this._inspector.setRenderer(this)}get inspector(){return this._inspector}set highPrecision(e){const t=this.contextNode.value;!0===e?(t.modelViewMatrix=Zy,t.modelNormalViewMatrix=Qy):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===Zy&&e.modelNormalViewMatrix===Qy}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return Qo('Renderer: ".getColorBufferType()" has been renamed to ".getOutputBufferType()".'),this.getOutputBufferType()}_onDeviceLost(e){let t=`THREE.WebGPURenderer: ${e.api} Device Lost:\n\nMessage: ${e.message}`;e.reason&&(t+=`\nReason: ${e.reason}`),Zo(t),this._isDeviceLost=!0}_renderBundle(e,t,s){const{bundleGroup:i,camera:r,renderList:n}=e,o=this._currentRenderContext,a=this._bundles.get(i,r),l=this.backend.get(a);void 0===l.renderContexts&&(l.renderContexts=new Set);const h=i.version!==l.version,u=!1===l.renderContexts.has(o)||h;if(l.renderContexts.add(o),u){this.backend.beginBundle(o),(void 0===l.renderObjects||h)&&(l.renderObjects=[]),this._currentRenderBundle=a;const{transparentDoublePass:e,transparent:u,opaque:c}=n;!0===this.opaque&&c.length>0&&this._renderObjects(c,r,t,s),!0===this.transparent&&u.length>0&&this._renderTransparents(u,e,r,t,s),this._currentRenderBundle=null,this.backend.finishBundle(o,a),l.version=i.version}else{const{renderObjects:e}=l;for(let t=0,s=e.length;t<s;t++){const s=e[t];this._nodes.needsRefresh(s)&&(this._nodes.updateBefore(s),this._nodes.updateForRender(s),this._bindings.updateForRender(s),this._nodes.updateAfter(s))}}this.backend.addBundle(o,a)}render(e,t){if(!1===this._initialized)throw new Error('Renderer: .render() called before the backend is initialized. Use "await renderer.init();" before rendering.');this._renderScene(e,t)}get initialized(){return this._initialized}_getFrameBufferTarget(){const{currentToneMapping:e,currentColorSpace:t}=this,s=0!==e,i=t!==_a.workingColorSpace;if(!1===s&&!1===i)return null;const{width:r,height:n}=this.getDrawingBufferSize(SP),{depth:o,stencil:a}=this;let l=this._frameBufferTarget;null===l&&(l=new Ba(r,n,{depthBuffer:o,stencilBuffer:a,type:this._outputBufferType,format:Ln,colorSpace:_a.workingColorSpace,generateMipmaps:!1,minFilter:xn,magFilter:xn,samples:this.samples}),l.isPostProcessingRenderTarget=!0,this._frameBufferTarget=l);const h=this.getOutputRenderTarget();l.depthBuffer=o,l.stencilBuffer=a,null!==h?l.setSize(h.width,h.height,h.depth):l.setSize(r,n,1);const u=this._canvasTarget;return l.viewport.copy(u._viewport),l.scissor.copy(u._scissor),l.viewport.multiplyScalar(u._pixelRatio),l.scissor.multiplyScalar(u._pixelRatio),l.scissorTest=u._scissorTest,l.multiview=null!==h&&h.multiview,l.resolveDepthBuffer=null===h||h.resolveDepthBuffer,l._autoAllocateDepthBuffer=null!==h&&h._autoAllocateDepthBuffer,l}_renderScene(e,t,s=!0){if(!0===this._isDeviceLost)return;const i=s?this._getFrameBufferTarget():null,r=this._nodes.nodeFrame,n=r.renderId,o=this._currentRenderContext,a=this._currentRenderObjectFunction,l=!0===e.isScene?e:TP,h=this._renderTarget||this._outputRenderTarget,u=this._activeCubeFace,c=this._activeMipmapLevel;let d;null!==i?(d=i,this.setRenderTarget(d)):d=h;const p=this._renderContexts.get(e,t,d,this._mrt);this._currentRenderContext=p,this._currentRenderObjectFunction=this._renderObjectFunction||this.renderObject,this.info.calls++,this.info.render.calls++,this.info.render.frameCalls++,r.renderId=this.info.calls,this.backend.updateTimeStampUID(p),this.inspector.beginRender(this.backend.getTimestampUID(p),e,t,d);const m=this.coordinateSystem,f=this.xr;if(t.coordinateSystem!==m&&!1===f.isPresenting&&(t.coordinateSystem=m,t.updateProjectionMatrix(),t.isArrayCamera))for(const e of t.cameras)e.coordinateSystem=m,e.updateProjectionMatrix();!0===e.matrixWorldAutoUpdate&&e.updateMatrixWorld(),null===t.parent&&!0===t.matrixWorldAutoUpdate&&t.updateMatrixWorld(),!0===f.enabled&&!0===f.isPresenting&&(!0===f.cameraAutoUpdate&&f.updateCamera(t),t=f.getCamera());const g=this._canvasTarget;let y=g._viewport,x=g._scissor,b=g._pixelRatio;null!==d&&(y=d.viewport,x=d.scissor,b=1),this.getDrawingBufferSize(SP),MP.set(0,0,SP.width,SP.height);const _=void 0===y.minDepth?0:y.minDepth,w=void 0===y.maxDepth?1:y.maxDepth;p.viewportValue.copy(y).multiplyScalar(b).floor(),p.viewportValue.width>>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=_,p.viewportValue.maxDepth=w,p.viewport=!1===p.viewportValue.equals(MP),p.scissorValue.copy(x).multiplyScalar(b).floor(),p.scissor=g._scissorTest&&!1===p.scissorValue.equals(MP),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new rP),p.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,d);const v=t.isArrayCamera?NP:AP;t.isArrayCamera||(EP.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),v.setFromProjectionMatrix(EP,t.coordinateSystem,t.reversedDepth));const T=this._renderLists.get(e,t);if(T.begin(),this._projectObject(e,t,0,T,p.clippingContext),T.finish(),!0===this.sortObjects&&T.sort(this._opaqueSort,this._transparentSort),null!==d){this._textures.updateRenderTarget(d,c);const e=this._textures.get(d);p.textures=e.textures,p.depthTexture=e.depthTexture,p.width=e.width,p.height=e.height,p.renderTarget=d,p.depth=d.depthBuffer,p.stencil=d.stencilBuffer}else p.textures=null,p.depthTexture=null,p.width=SP.width,p.height=SP.height,p.depth=this.depth,p.stencil=this.stencil;p.width>>=c,p.height>>=c,p.activeCubeFace=u,p.activeMipmapLevel=c,p.occlusionQueryCount=T.occlusionQueryCount,p.scissorValue.max(CP.set(0,0,0,0)),p.scissorValue.x+p.scissorValue.width>p.width&&(p.scissorValue.width=Math.max(p.width-p.scissorValue.x,0)),p.scissorValue.y+p.scissorValue.height>p.height&&(p.scissorValue.height=Math.max(p.height-p.scissorValue.y,0)),this._background.update(l,T,p),p.camera=t,this.backend.beginRender(p);const{bundles:S,lightsNode:M,transparentDoublePass:A,transparent:N,opaque:E}=T;return S.length>0&&this._renderBundles(S,l,M),!0===this.opaque&&E.length>0&&this._renderObjects(E,t,l,M),!0===this.transparent&&N.length>0&&this._renderTransparents(N,A,t,l,M),this.backend.finishRender(p),r.renderId=n,this._currentRenderContext=o,this._currentRenderObjectFunction=a,null!==i&&(this.setRenderTarget(h,u,c),this._renderOutput(d)),l.onAfterRender(this,e,t,d),this.inspector.finishRender(this.backend.getTimestampUID(p)),p}_setXRLayerSize(e,t){this._canvasTarget._width=e,this._canvasTarget._height=t,this.setViewport(0,0,e,t)}_renderOutput(e){const t=this._quad;this._nodes.hasOutputChange(e.texture)&&(t.material.fragmentNode=this._nodes.getOutputNode(e.texture),t.material.needsUpdate=!0);const s=this.autoClear,i=this.xr.enabled;this.autoClear=!1,this.xr.enabled=!1,this._renderScene(t,t.camera,!1),this.autoClear=s,this.xr.enabled=i}getMaxAnisotropy(){return this.backend.getMaxAnisotropy()}getActiveCubeFace(){return this._activeCubeFace}getActiveMipmapLevel(){return this._activeMipmapLevel}async setAnimationLoop(e){!1===this._initialized&&await this.init(),this._animation.setAnimationLoop(e)}getAnimationLoop(){return this._animation.getAnimationLoop()}async getArrayBufferAsync(e){return await this.backend.getArrayBufferAsync(e)}getContext(){return this.backend.getContext()}getPixelRatio(){return this._canvasTarget.getPixelRatio()}getDrawingBufferSize(e){return this._canvasTarget.getDrawingBufferSize(e)}getSize(e){return this._canvasTarget.getSize(e)}setPixelRatio(e=1){this._canvasTarget.setPixelRatio(e)}setDrawingBufferSize(e,t,s){this.xr&&this.xr.isPresenting||this._canvasTarget.setDrawingBufferSize(e,t,s)}setSize(e,t,s=!0){this.xr&&this.xr.isPresenting||this._canvasTarget.setSize(e,t,s)}setOpaqueSort(e){this._opaqueSort=e}setTransparentSort(e){this._transparentSort=e}getScissor(e){return this._canvasTarget.getScissor(e)}setScissor(e,t,s,i){this._canvasTarget.setScissor(e,t,s,i)}getScissorTest(){return this._canvasTarget.getScissorTest()}setScissorTest(e){this._canvasTarget.setScissorTest(e),this.backend.setScissorTest(e)}getViewport(e){return this._canvasTarget.getViewport(e)}setViewport(e,t,s,i,r=0,n=1){this._canvasTarget.setViewport(e,t,s,i,r,n)}getClearColor(e){return e.copy(this._clearColor)}setClearColor(e,t=1){this._clearColor.set(e),this._clearColor.a=t}getClearAlpha(){return this._clearColor.a}setClearAlpha(e){this._clearColor.a=e}getClearDepth(){return this._clearDepth}setClearDepth(e){this._clearDepth=e}getClearStencil(){return this._clearStencil}setClearStencil(e){this._clearStencil=e}isOccluded(e){const t=this._currentRenderContext;return t&&this.backend.isOccluded(t,e)}clear(e=!0,t=!0,s=!0){if(!1===this._initialized)throw new Error('Renderer: .clear() called before the backend is initialized. Use "await renderer.init();" before before using this method.');const i=this._renderTarget||this._getFrameBufferTarget();let r=null;if(null!==i){this._textures.updateRenderTarget(i);const e=this._textures.get(i);r=this._renderContexts.getForClear(i),r.textures=e.textures,r.depthTexture=e.depthTexture,r.width=e.width,r.height=e.height,r.renderTarget=i,r.depth=i.depthBuffer,r.stencil=i.stencilBuffer,r.clearColorValue=this.backend.getClearColor(),r.activeCubeFace=this.getActiveCubeFace(),r.activeMipmapLevel=this.getActiveMipmapLevel()}this.backend.clear(e,t,s,r),null!==i&&null===this._renderTarget&&this._renderOutput(i)}clearColor(){this.clear(!0,!1,!1)}clearDepth(){this.clear(!1,!0,!1)}clearStencil(){this.clear(!1,!1,!0)}async clearAsync(e=!0,t=!0,s=!0){Qo('Renderer: "clearAsync()" has been deprecated. Use "clear()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.clear(e,t,s)}async clearColorAsync(){Qo('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){Qo('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){Qo('Renderer: "clearStencilAsync()" has been deprecated. Use "clearStencil()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!1,!0)}get needsFrameBufferTarget(){const e=0!==this.currentToneMapping,t=this.currentColorSpace!==_a.workingColorSpace;return e||t}get samples(){return this._samples}get currentSamples(){let e=this._samples;return null!==this._renderTarget?e=this._renderTarget.samples:this.needsFrameBufferTarget&&(e=0),e}get currentToneMapping(){return this.isOutputTarget?this.toneMapping:0}get currentColorSpace(){return this.isOutputTarget?this.outputColorSpace:_a.workingColorSpace}get isOutputTarget(){return this._renderTarget===this._outputRenderTarget||null===this._renderTarget}dispose(){!0===this._initialized&&(this.info.dispose(),this.backend.dispose(),this._animation.dispose(),this._objects.dispose(),this._geometries.dispose(),this._pipelines.dispose(),this._nodes.dispose(),this._bindings.dispose(),this._renderLists.dispose(),this._renderContexts.dispose(),this._textures.dispose(),null!==this._frameBufferTarget&&this._frameBufferTarget.dispose(),Object.values(this.backend.timestampQueryPool).forEach(e=>{null!==e&&e.dispose()})),this.setRenderTarget(null),this.setAnimationLoop(null)}setRenderTarget(e,t=0,s=0){this._renderTarget=e,this._activeCubeFace=t,this._activeMipmapLevel=s}getRenderTarget(){return this._renderTarget}setOutputRenderTarget(e){this._outputRenderTarget=e}getOutputRenderTarget(){return this._outputRenderTarget}setCanvasTarget(e){this._canvasTarget.removeEventListener("resize",this._onCanvasTargetResize),this._canvasTarget=e,this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize)}getCanvasTarget(){return this._canvasTarget}_resetXRState(){this.backend.setXRTarget(null),this.setOutputRenderTarget(null),this.setRenderTarget(null),this._frameBufferTarget.dispose(),this._frameBufferTarget=null}setRenderObjectFunction(e){this._renderObjectFunction=e}getRenderObjectFunction(){return this._renderObjectFunction}compute(e,t=null){if(!0===this._isDeviceLost)return;if(!1===this._initialized)return Yo("Renderer: .compute() called before the backend is initialized. Try using .computeAsync() instead."),this.computeAsync(e,t);const s=this._nodes.nodeFrame,i=s.renderId;this.info.calls++,this.info.compute.calls++,this.info.compute.frameCalls++,s.renderId=this.info.calls,this.backend.updateTimeStampUID(e),this.inspector.beginCompute(this.backend.getTimestampUID(e),e);const r=this.backend,n=this._pipelines,o=this._bindings,a=this._nodes,l=Array.isArray(e)?e:[e];if(void 0===l[0]||!0!==l[0].isComputeNode)throw new Error("THREE.Renderer: .compute() expects a ComputeNode.");r.beginCompute(e);for(const s of l){if(!1===n.has(s)){const e=()=>{s.removeEventListener("dispose",e),n.delete(s),o.deleteForCompute(s),a.delete(s)};s.addEventListener("dispose",e);const t=s.onInitFunction;null!==t&&t.call(s,{renderer:this})}a.updateForCompute(s),o.updateForCompute(s);const i=o.getForCompute(s),l=n.getForCompute(s,i);r.compute(e,s,i,l,t)}r.finishCompute(e),s.renderId=i,this.inspector.finishCompute(this.backend.getTimestampUID(e))}async computeAsync(e,t=null){!1===this._initialized&&await this.init(),this.compute(e,t)}async hasFeatureAsync(e){return Qo('Renderer: "hasFeatureAsync()" has been deprecated. Use "hasFeature()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.hasFeature(e)}async resolveTimestampsAsync(e="render"){return!1===this._initialized&&await this.init(),this.backend.resolveTimestampsAsync(e)}hasFeature(e){if(!1===this._initialized)throw new Error('Renderer: .hasFeature() called before the backend is initialized. Use "await renderer.init();" before before using this method.');return this.backend.hasFeature(e)}hasInitialized(){return this._initialized}async initTextureAsync(e){Qo('Renderer: "initTextureAsync()" has been deprecated. Use "initTexture()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.initTexture(e)}initTexture(e){if(!1===this._initialized)throw new Error('Renderer: .initTexture() called before the backend is initialized. Use "await renderer.init();" before before using this method.');this._textures.updateTexture(e)}copyFramebufferToTexture(e,t=null){if(null!==t)if(t.isVector2)t=CP.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void Zo("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=CP.copy(t).floor()}else t=CP.set(0,0,e.image.width,e.image.height);let s,i=this._currentRenderContext;null!==i?s=i.renderTarget:(s=this._renderTarget||this._getFrameBufferTarget(),null!==s&&(this._textures.updateRenderTarget(s),i=this._textures.get(s))),this._textures.updateTexture(e,{renderTarget:s}),this.backend.copyFramebufferToTexture(e,i,t),this._inspector.copyFramebufferToTexture(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){this._textures.updateTexture(e),this._textures.updateTexture(t),this.backend.copyTextureToTexture(e,t,s,i,r,n),this._inspector.copyTextureToTexture(e,t)}async readRenderTargetPixelsAsync(e,t,s,i,r,n=0,o=0){return this.backend.copyTextureToBuffer(e.textures[n],t,s,i,r,o)}_projectObject(e,t,s,i,r){if(!1===e.visible)return;if(e.layers.test(t.layers))if(e.isGroup)s=e.renderOrder,e.isClippingGroup&&e.enabled&&(r=r.getGroupContext(e));else if(e.isLOD)!0===e.autoUpdate&&e.update(t);else if(e.isLight)i.pushLight(e);else if(e.isSprite){const n=t.isArrayCamera?NP:AP;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&CP.setFromMatrixPosition(e.matrixWorld).applyMatrix4(EP);const{geometry:t,material:n}=e;n.visible&&i.push(e,t,n,s,CP.z,null,r)}}else if(e.isLineLoop)Zo("Renderer: Objects of type THREE.LineLoop are not supported. Please use THREE.Line or THREE.LineSegments.");else if(e.isMesh||e.isLine||e.isPoints){const n=t.isArrayCamera?NP:AP;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),CP.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(EP)),Array.isArray(n)){const o=t.groups;for(let a=0,l=o.length;a<l;a++){const l=o[a],h=n[l.materialIndex];h&&h.visible&&i.push(e,t,h,s,CP.z,l,r)}}else n.visible&&i.push(e,t,n,s,CP.z,null,r)}}if(!0===e.isBundleGroup&&void 0!==this.backend.beginBundle){const s=i;(i=this._renderLists.get(e,t)).begin(),s.pushBundle({bundleGroup:e,camera:t,renderList:i}),i.finish()}const n=e.children;for(let e=0,o=n.length;e<o;e++)this._projectObject(n[e],t,s,i,r)}_renderBundles(e,t,s){for(const i of e)this._renderBundle(i,t,s)}_renderTransparents(e,t,s,i,r){if(t.length>0){for(const{material:e}of t)e.side=1;this._renderObjects(t,s,i,r,"backSide");for(const{material:e}of t)e.side=0;this._renderObjects(e,s,i,r);for(const{material:e}of t)e.side=2}else this._renderObjects(e,s,i,r)}_renderObjects(e,t,s,i,r=null){for(let n=0,o=e.length;n<o;n++){const{object:o,geometry:a,material:l,group:h,clippingContext:u}=e[n];this._currentRenderObjectFunction(o,s,t,a,l,h,i,u,r)}}_getShadowNodes(e){const t=e.version;let s=this._cacheShadowNodes.get(e);if(void 0===s||s.version!==t){const i=null!==e.map,r=e.colorNode&&e.colorNode.isNode,n=e.castShadowNode&&e.castShadowNode.isNode;let o=null,a=null,l=null;if(i||r||n){let t,s;n?(t=e.castShadowNode.rgb,s=e.castShadowNode.a):(t=Gd(0),s=Dd(1)),i&&(s=s.mul(Ox("map","texture",e).a)),r&&(s=s.mul(e.colorNode.a)),a=Hd(t,s)}e.depthNode&&e.depthNode.isNode&&(l=e.depthNode),e.castShadowPositionNode&&e.castShadowPositionNode.isNode?o=e.castShadowPositionNode:e.positionNode&&e.positionNode.isNode&&(o=e.positionNode),s={version:t,colorNode:a,depthNode:l,positionNode:o},this._cacheShadowNodes.set(e,s)}return s}renderObject(e,t,s,i,r,n,o,a=null,l=null){let h,u,c,d,p=!1;if(e.onBeforeRender(this,t,s,i,r,n),!0===r.allowOverride&&null!==t.overrideMaterial){const e=t.overrideMaterial;if(p=!0,h=t.overrideMaterial.colorNode,u=t.overrideMaterial.depthNode,c=t.overrideMaterial.positionNode,d=t.overrideMaterial.side,r.positionNode&&r.positionNode.isNode&&(e.positionNode=r.positionNode),e.alphaTest=r.alphaTest,e.alphaMap=r.alphaMap,e.transparent=r.transparent||r.transmission>0||r.transmissionNode&&r.transmissionNode.isNode||r.backdropNode&&r.backdropNode.isNode,e.isShadowPassMaterial){const{colorNode:t,depthNode:s,positionNode:i}=this._getShadowNodes(r);e.side=null===r.shadowSide?r.side:r.shadowSide,null!==t&&(e.colorNode=t),null!==s&&(e.depthNode=s),null!==i&&(e.positionNode=i)}r=e}!0===r.transparent&&2===r.side&&!1===r.forceSinglePass?(r.side=1,this._handleObjectFunction(e,r,t,s,o,n,a,"backSide"),r.side=0,this._handleObjectFunction(e,r,t,s,o,n,a,l),r.side=2):this._handleObjectFunction(e,r,t,s,o,n,a,l),p&&(t.overrideMaterial.colorNode=h,t.overrideMaterial.depthNode=u,t.overrideMaterial.positionNode=c,t.overrideMaterial.side=d),e.onAfterRender(this,t,s,i,r,n)}_renderObjectDirect(e,t,s,i,r,n,o,a){const l=this._objects.get(e,t,s,i,r,this._currentRenderContext,o,a);l.drawRange=e.geometry.drawRange,l.group=n;const h=this._nodes.needsRefresh(l);if(h&&(this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l)),this._pipelines.updateForRender(l),null!==this._currentRenderBundle){this.backend.get(this._currentRenderBundle).renderObjects.push(l),l.bundle=this._currentRenderBundle.bundleGroup}this.backend.draw(l,this.info),h&&this._nodes.updateAfter(l)}_createObjectPipeline(e,t,s,i,r,n,o,a){const l=this._objects.get(e,t,s,i,r,this._currentRenderContext,o,a);l.drawRange=e.geometry.drawRange,l.group=n,this._nodes.updateBefore(l),this._geometries.updateForRender(l),this._nodes.updateForRender(l),this._bindings.updateForRender(l),this._pipelines.getForRender(l,this._compilationPromises),this._nodes.updateAfter(l)}_onCanvasTargetResize(){this._initialized&&this.backend.updateSize()}get compile(){return this.compileAsync}}class PP{constructor(e=""){this.name=e,this.visibility=0}setVisibility(e){this.visibility|=e}getVisibility(){return this.visibility}clone(){return Object.assign(new this.constructor,this)}}let BP=class extends PP{constructor(e,t=null){super(e),this.isBuffer=!0,this.bytesPerElement=Float32Array.BYTES_PER_ELEMENT,this._buffer=t,this._updateRanges=[]}get updateRanges(){return this._updateRanges}addUpdateRange(e,t){this.updateRanges.push({start:e,count:t})}clearUpdateRanges(){this.updateRanges.length=0}get byteLength(){return(e=this._buffer.byteLength)+(yS-e%yS)%yS;var e}get buffer(){return this._buffer}update(){return!0}};class IP extends BP{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let DP=0;class LP extends IP{constructor(e,t){super("UniformBuffer_"+DP++,e?e.value:null),this.nodeUniform=e,this.groupNode=t,this.isNodeUniformBuffer=!0}set updateRanges(e){this.nodeUniform.updateRanges=e}get updateRanges(){return this.nodeUniform.updateRanges}addUpdateRange(e,t){this.nodeUniform.addUpdateRange(e,t)}clearUpdateRanges(){this.nodeUniform.clearUpdateRanges()}get buffer(){return this.nodeUniform.value}}class FP extends IP{constructor(e){super(e),this.isUniformsGroup=!0,this._values=null,this.uniforms=[]}addUniform(e){return this.uniforms.push(e),this}removeUniform(e){const t=this.uniforms.indexOf(e);return-1!==t&&this.uniforms.splice(t,1),this}get values(){return null===this._values&&(this._values=Array.from(this.buffer)),this._values}get buffer(){let e=this._buffer;if(null===e){const t=this.byteLength;e=new Float32Array(new ArrayBuffer(t)),this._buffer=e}return e}get byteLength(){const e=this.bytesPerElement;let t=0;for(let s=0,i=this.uniforms.length;s<i;s++){const i=this.uniforms[s],r=i.boundary,n=i.itemSize*e,o=t%yS,a=o%r,l=o+a;t+=a,0!==l&&yS-l<n&&(t+=yS-l),i.offset=t/e,t+=n}return Math.ceil(t/yS)*yS}update(){let e=!1;for(const t of this.uniforms)!0===this.updateByType(t)&&(e=!0);return e}updateByType(e){return e.isNumberUniform?this.updateNumber(e):e.isVector2Uniform?this.updateVector2(e):e.isVector3Uniform?this.updateVector3(e):e.isVector4Uniform?this.updateVector4(e):e.isColorUniform?this.updateColor(e):e.isMatrix3Uniform?this.updateMatrix3(e):e.isMatrix4Uniform?this.updateMatrix4(e):void Zo("WebGPUUniformsGroup: Unsupported uniform type.",e)}updateNumber(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r]!==i){this._getBufferForType(n)[r]=s[r]=i,t=!0}return t}updateVector2(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r+0]!==i.x||s[r+1]!==i.y){const e=this._getBufferForType(n);e[r+0]=s[r+0]=i.x,e[r+1]=s[r+1]=i.y,t=!0}return t}updateVector3(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r+0]!==i.x||s[r+1]!==i.y||s[r+2]!==i.z){const e=this._getBufferForType(n);e[r+0]=s[r+0]=i.x,e[r+1]=s[r+1]=i.y,e[r+2]=s[r+2]=i.z,t=!0}return t}updateVector4(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset,n=e.getType();if(s[r+0]!==i.x||s[r+1]!==i.y||s[r+2]!==i.z||s[r+4]!==i.w){const e=this._getBufferForType(n);e[r+0]=s[r+0]=i.x,e[r+1]=s[r+1]=i.y,e[r+2]=s[r+2]=i.z,e[r+3]=s[r+3]=i.w,t=!0}return t}updateColor(e){let t=!1;const s=this.values,i=e.getValue(),r=e.offset;if(s[r+0]!==i.r||s[r+1]!==i.g||s[r+2]!==i.b){const e=this.buffer;e[r+0]=s[r+0]=i.r,e[r+1]=s[r+1]=i.g,e[r+2]=s[r+2]=i.b,t=!0}return t}updateMatrix3(e){let t=!1;const s=this.values,i=e.getValue().elements,r=e.offset;if(s[r+0]!==i[0]||s[r+1]!==i[1]||s[r+2]!==i[2]||s[r+4]!==i[3]||s[r+5]!==i[4]||s[r+6]!==i[5]||s[r+8]!==i[6]||s[r+9]!==i[7]||s[r+10]!==i[8]){const e=this.buffer;e[r+0]=s[r+0]=i[0],e[r+1]=s[r+1]=i[1],e[r+2]=s[r+2]=i[2],e[r+4]=s[r+4]=i[3],e[r+5]=s[r+5]=i[4],e[r+6]=s[r+6]=i[5],e[r+8]=s[r+8]=i[6],e[r+9]=s[r+9]=i[7],e[r+10]=s[r+10]=i[8],t=!0}return t}updateMatrix4(e){let t=!1;const s=this.values,i=e.getValue().elements,r=e.offset;if(!1===function(e,t,s){for(let i=0,r=t.length;i<r;i++)if(e[s+i]!==t[i])return!1;return!0}(s,i,r)){this.buffer.set(i,r),function(e,t,s){for(let i=0,r=t.length;i<r;i++)e[s+i]=t[i]}(s,i,r),t=!0}return t}_getBufferForType(e){return"int"===e||"ivec2"===e||"ivec3"===e||"ivec4"===e?new Int32Array(this.buffer.buffer):"uint"===e||"uvec2"===e||"uvec3"===e||"uvec4"===e?new Uint32Array(this.buffer.buffer):this.buffer}}let OP=0;class VP extends FP{constructor(e,t){super(e),this.id=OP++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class zP extends PP{constructor(e,t){super(e),this._texture=null,this._onTextureDispose=()=>{this.generation=null,this.version=0},this.texture=t,this.version=t?t.version:0,this.generation=null,this.samplerKey="",this.isSampler=!0}set texture(e){this._texture!==e&&(this._texture&&this._texture.removeEventListener("dispose",this._onTextureDispose),this._texture=e,this.generation=null,this.version=0,this._texture&&this._texture.addEventListener("dispose",this._onTextureDispose))}get texture(){return this._texture}update(){const{texture:e,version:t}=this;return t!==e.version&&(this.version=e.version,!0)}clone(){const e=super.clone();return e._texture=null,e._onTextureDispose=()=>{e.generation=null,e.version=0},e.texture=this.texture,e}}let kP=0;class UP extends zP{constructor(e,t){super(e,t),this.id=kP++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class GP extends UP{constructor(e,t,s,i=null){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s,this.access=i}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class jP extends GP{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class $P extends GP{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}const WP={bitcast_int_uint:new iN("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new iN("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},HP={textureDimensions:"textureSize",equals:"equal",bitcast_float_int:"floatBitsToInt",bitcast_int_float:"intBitsToFloat",bitcast_uint_float:"uintBitsToFloat",bitcast_float_uint:"floatBitsToUint",bitcast_uint_int:"tsl_bitcast_uint_to_int",bitcast_int_uint:"tsl_bitcast_int_to_uint",floatpack_snorm_2x16:"packSnorm2x16",floatpack_unorm_2x16:"packUnorm2x16",floatpack_float16_2x16:"packHalf2x16",floatunpack_snorm_2x16:"unpackSnorm2x16",floatunpack_unorm_2x16:"unpackUnorm2x16",floatunpack_float16_2x16:"unpackHalf2x16"},qP={low:"lowp",medium:"mediump",high:"highp"},XP={swizzleAssign:!0,storageBuffer:!1},YP={perspective:"smooth",linear:"noperspective"},ZP={centroid:"centroid"},QP="\nprecision highp float;\nprecision highp int;\nprecision highp sampler2D;\nprecision highp sampler3D;\nprecision highp samplerCube;\nprecision highp sampler2DArray;\n\nprecision highp usampler2D;\nprecision highp usampler3D;\nprecision highp usamplerCube;\nprecision highp usampler2DArray;\n\nprecision highp isampler2D;\nprecision highp isampler3D;\nprecision highp isamplerCube;\nprecision highp isampler2DArray;\n\nprecision lowp sampler2DShadow;\nprecision lowp sampler2DArrayShadow;\nprecision lowp samplerCubeShadow;\n";class KP extends PR{constructor(e,t){super(e,t,new KR),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==So}_include(e){const t=WP[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==WP[e]&&this._include(e),HP[e]||e}getBitcastMethod(e,t){return this.getMethod(`bitcast_${t}_${e}`)}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,s){return`${e} ? ${t} : ${s}`}getOutputStructName(){return""}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(this.getType(e.type)+" "+e.name);return`${this.getType(t.type)} ${t.name}( ${i.join(", ")} ) {\n\n\t${s.vars}\n\n${s.code}\n\treturn ${s.result};\n\n}`}setupPBO(e){const t=e.value;if(void 0===t.pbo){const e=t.array,s=t.count*t.itemSize,{itemSize:i}=t,r=t.array.constructor.name.toLowerCase().includes("int");let n=r?zn:Vn;2===i?n=r?Un:kn:3===i?n=r?1032:Dn:4===i&&(n=r?Gn:Ln);const o={Float32Array:Nn,Uint8Array:wn,Uint16Array:Sn,Uint32Array:An,Int8Array:vn,Int16Array:Tn,Int32Array:Mn,Uint8ClampedArray:wn},a=Math.pow(2,Math.ceil(Math.log2(Math.sqrt(s/i))));let l=Math.ceil(s/i/a);a*l*i<s&&l++;const h=a*l*i,u=new e.constructor(h);u.set(e,0),t.array=u;const c=new ru(t.array,a,l,n,o[t.array.constructor.name]||Nn);c.needsUpdate=!0,c.isPBOTexture=!0;const d=new Jg(c,null,null);d.setPrecision("high"),t.pboNode=d,t.pbo=d.value,this.getUniformFromNode(t.pboNode,"texture",this.shaderStage,this.context.nodeName)}}getPropertyName(e,t=this.shaderStage){return e.isNodeUniform&&!0!==e.node.isTextureNode&&!0!==e.node.isBufferNode?t.charAt(0)+"_"+e.name:super.getPropertyName(e,t)}generatePBO(e){const{node:t,indexNode:s}=e,i=t.value;if(this.renderer.backend.has(i)){this.renderer.backend.get(i).pbo=i.pbo}const r=this.getUniformFromNode(i.pboNode,"texture",this.shaderStage,this.context.nodeName),n=this.getPropertyName(r);this.increaseUsage(s);const o=s.build(this,"uint"),a=this.getDataFromNode(e);let l=a.propertyName;if(void 0===l){const s=this.getVarFromNode(e);l=this.getPropertyName(s);const r=this.getDataFromNode(t);let h=r.propertySizeName;void 0===h&&(h=l+"Size",this.getVarFromNode(t,h,"uint"),this.addLineFlowCode(`${h} = uint( textureSize( ${n}, 0 ).x )`,e),r.propertySizeName=h);const{itemSize:u}=i,c="."+Ac.join("").slice(0,u),d=`ivec2(${o} % ${h}, ${o} / ${h})`,p=this.generateTextureLoad(null,n,d,"0",null,null);let m="vec4";i.pbo.type===An?m="uvec4":i.pbo.type===Mn&&(m="ivec4"),this.addLineFlowCode(`${l} = ${m}(${p})${c}`,e),a.propertyName=l}return l}generateTextureLoad(e,t,s,i,r,n){let o;return null===i&&(i="0"),o=r?n?`texelFetchOffset( ${t}, ivec3( ${s}, ${r} ), ${i}, ${n} )`:`texelFetch( ${t}, ivec3( ${s}, ${r} ), ${i} )`:n?`texelFetchOffset( ${t}, ${s}, ${i}, ${n} )`:`texelFetch( ${t}, ${s}, ${i} )`,null!==e&&e.isDepthTexture&&(o+=".x"),o}generateTexture(e,t,s,i,r){return i&&(s=`vec3( ${s}, ${i} )`),e.isDepthTexture?r?`textureOffset( ${t}, ${s}, ${r} ).x`:`texture( ${t}, ${s} ).x`:r?`textureOffset( ${t}, ${s}, ${r} )`:`texture( ${t}, ${s} )`}generateTextureLevel(e,t,s,i,r){return r?`textureLodOffset( ${t}, ${s}, ${i}, ${r} )`:`textureLod( ${t}, ${s}, ${i} )`}generateTextureBias(e,t,s,i,r){return r?`textureOffset( ${t}, ${s}, ${r}, ${i} )`:`texture( ${t}, ${s}, ${i} )`}generateTextureGrad(e,t,s,i,r){return r?`textureGradOffset( ${t}, ${s}, ${i[0]}, ${i[1]}, ${r} )`:`textureGrad( ${t}, ${s}, ${i[0]}, ${i[1]} )`}generateTextureCompare(e,t,s,i,r,n,o=this.shaderStage){if("fragment"===o)return e.isCubeTexture?`texture( ${t}, vec4( ${s}, ${i} ) )`:r?n?`textureOffset( ${t}, vec4( ${s}, ${r}, ${i} ), ${n} )`:`texture( ${t}, vec4( ${s}, ${r}, ${i} ) )`:n?`textureOffset( ${t}, vec3( ${s}, ${i} ), ${n} )`:`texture( ${t}, vec3( ${s}, ${i} ) )`;Zo(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${o} shader.`)}getVars(e){const t=[],s=this.vars[e];if(void 0!==s)for(const e of s)t.push(`${this.getVar(e.type,e.name,e.count)};`);return t.join("\n\t")}getUniforms(e){const t=this.uniforms[e],s=[],i={};for(const r of t){let t=null,n=!1;if("texture"===r.type||"texture3D"===r.type){const e=r.node.value;let s="";!0!==e.isDataTexture&&!0!==e.isData3DTexture||(e.type===An?s="u":e.type===Mn&&(s="i")),t="texture3D"===r.type&&!1===e.isArrayTexture?`${s}sampler3D ${r.name};`:e.compareFunction?!0===e.isArrayTexture?`sampler2DArrayShadow ${r.name};`:`sampler2DShadow ${r.name};`:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?`${s}sampler2DArray ${r.name};`:`${s}sampler2D ${r.name};`}else if("cubeTexture"===r.type)t=`samplerCube ${r.name};`;else if("cubeDepthTexture"===r.type)t=`samplerCubeShadow ${r.name};`;else if("buffer"===r.type){const e=r.node,s=this.getType(e.bufferType),i=e.bufferCount,n=i>0?i:"";t=`${e.name} {\n\t${s} ${r.name}[${n}];\n};\n`}else{t=`${this.getVectorType(r.type)} ${this.getPropertyName(r,e)};`,n=!0}const o=r.node.precision;if(null!==o&&(t=qP[o]+" "+t),n){t="\t"+t;const e=r.groupNode.name;(i[e]||(i[e]=[])).push(t)}else t="uniform "+t,s.push(t)}let r="";for(const t in i){const s=i[t];r+=this._getGLSLUniformStruct(e+"_"+t,s.join("\n"))+"\n"}return r+=s.join("\n"),r}getTypeFromAttribute(e){let t=super.getTypeFromAttribute(e);if(/^[iu]/.test(t)&&e.gpuType!==Mn){let s=e;e.isInterleavedBufferAttribute&&(s=e.data);const i=s.array;!1==(i instanceof Uint32Array||i instanceof Int32Array)&&(t=t.slice(1))}return t}getAttributes(e){let t="";if("vertex"===e||"compute"===e){const e=this.getAttributesArray();let s=0;for(const i of e)t+=`layout( location = ${s++} ) in ${i.type} ${i.name};\n`}return t}getStructMembers(e){const t=[];for(const s of e.members)t.push(`\t${s.type} ${s.name};`);return t.join("\n")}getStructs(e){const t=[],s=this.structs[e],i=[];for(const e of s)if(e.output)for(const t of e.members)i.push(`layout( location = ${t.index} ) out ${t.type} ${t.name};`);else{let s="struct "+e.name+" {\n";s+=this.getStructMembers(e),s+="\n};\n",t.push(s)}return 0===i.length&&i.push("layout( location = 0 ) out vec4 fragColor;"),"\n"+i.join("\n")+"\n\n"+t.join("\n")}getVaryings(e){let t="";const s=this.varyings;if("vertex"===e||"compute"===e)for(const i of s){"compute"===e&&(i.needsInterpolation=!0);const s=this.getType(i.type);if(i.needsInterpolation)if(i.interpolationType){t+=`${YP[i.interpolationType]||i.interpolationType} ${ZP[i.interpolationSampling]||""} out ${s} ${i.name};\n`}else{t+=`${s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":""}out ${s} ${i.name};\n`}else t+=`${s} ${i.name};\n`}else if("fragment"===e)for(const e of s)if(e.needsInterpolation){const s=this.getType(e.type);if(e.interpolationType){t+=`${YP[e.interpolationType]||e.interpolationType} ${ZP[e.interpolationSampling]||""} in ${s} ${e.name};\n`}else{t+=`${s.includes("int")||s.includes("uv")||s.includes("iv")?"flat ":""}in ${s} ${e.name};\n`}}for(const s of this.builtins[e])t+=`${s};\n`;return t}getVertexIndex(){return"uint( gl_VertexID )"}getInstanceIndex(){return"uint( gl_InstanceID )"}getInvocationLocalIndex(){return`uint( gl_InstanceID ) % ${this.object.workgroupSize.reduce((e,t)=>e*t,1)}u`}getSubgroupSize(){Zo("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){Zo("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){Zo("GLSLNodeBuilder: WebGLBackend does not support the subgroupIndex node")}getDrawIndex(){return this.renderer.backend.extensions.has("WEBGL_multi_draw")?"uint( gl_DrawID )":null}getFrontFacing(){return"gl_FrontFacing"}getFragCoord(){return"gl_FragCoord.xy"}getFragDepth(){return"gl_FragDepth"}enableExtension(e,t,s=this.shaderStage){const i=this.extensions[s]||(this.extensions[s]=new Map);!1===i.has(e)&&i.set(e,{name:e,behavior:t})}getExtensions(e){const t=[];if("vertex"===e){const t=this.renderer.backend.extensions;this.object.isBatchedMesh&&t.has("WEBGL_multi_draw")&&this.enableExtension("GL_ANGLE_multi_draw","require",e)}const s=this.extensions[e];if(void 0!==s)for(const{name:e,behavior:i}of s.values())t.push(`#extension ${e} : ${i}`);return t.join("\n")}getClipDistance(){return"gl_ClipDistance"}isAvailable(e){let t=XP[e];if(void 0===t){let s;switch(t=!1,e){case"float32Filterable":s="OES_texture_float_linear";break;case"clipDistance":s="WEBGL_clip_cull_distance"}if(void 0!==s){const e=this.renderer.backend.extensions;e.has(s)&&(e.get(s),t=!0)}XP[e]=t}return t}isFlipY(){return!0}enableHardwareClipping(e){this.enableExtension("GL_ANGLE_clip_cull_distance","require"),this.builtins.vertex.push(`out float gl_ClipDistance[ ${e} ]`)}enableMultiview(){this.enableExtension("GL_OVR_multiview2","require","fragment"),this.enableExtension("GL_OVR_multiview2","require","vertex"),this.builtins.vertex.push("layout(num_views = 2) in")}registerTransform(e,t){this.transforms.push({varyingName:e,attributeNode:t})}getTransforms(){const e=this.transforms;let t="";for(let s=0;s<e.length;s++){const i=e[s],r=this.getPropertyName(i.attributeNode);r&&(t+=`${i.varyingName} = ${r};\n\t`)}return t}_getGLSLUniformStruct(e,t){return`\nlayout( std140 ) uniform ${e} {\n${t}\n};`}_getGLSLVertexCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${QP}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// attributes\n${e.attributes}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// transforms\n\t${e.transforms}\n\n\t// flow\n\t${e.flow}\n\n\tgl_PointSize = 1.0;\n\n}\n`}_getGLSLFragmentCode(e){return`#version 300 es\n\n${this.getSignature()}\n\n// extensions\n${e.extensions}\n\n// precision\n${QP}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\n\n// codes\n${e.codes}\n\nvoid main() {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){let s="// code\n\n";s+=this.flowCode[t];const i=this.flowNodes[t],r=i[i.length-1];for(const e of i){const i=this.getFlowData(e),n=e.name;n&&(s.length>0&&(s+="\n"),s+=`\t// flow -> ${n}\n\t`),s+=`${i.code}\n\t`,e===r&&"compute"!==t&&(s+="// result\n\t","vertex"===t?(s+="gl_Position = ",s+=`${i.result};`):"fragment"===t&&(e.outputNode.isOutputStructNode||(s+="fragColor = ",s+=`${i.result};`)))}const n=e[t];n.extensions=this.getExtensions(t),n.uniforms=this.getUniforms(t),n.attributes=this.getAttributes(t),n.varyings=this.getVaryings(t),n.vars=this.getVars(t),n.structs=this.getStructs(t),n.codes=this.getCodes(t),n.transforms=this.getTransforms(t),n.flow=s}null!==this.material?(this.vertexShader=this._getGLSLVertexCode(e.vertex),this.fragmentShader=this._getGLSLFragmentCode(e.fragment)):this.computeShader=this._getGLSLVertexCode(e.compute)}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);let o=n.uniformGPU;if(void 0===o){const i=e.groupNode,a=i.name,l=this.getBindGroupArray(a,s);if("texture"===t)o=new GP(r.name,r.node,i),l.push(o);else if("cubeTexture"===t||"cubeDepthTexture"===t)o=new jP(r.name,r.node,i),l.push(o);else if("texture3D"===t)o=new $P(r.name,r.node,i),l.push(o);else if("buffer"===t){r.name=`buffer${e.id}`;const t=this.getSharedDataFromNode(e);let s=t.buffer;void 0===s&&(e.name=`NodeBuffer_${e.id}`,s=new LP(e,i),s.name=e.name,t.buffer=s),l.push(s),o=s}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let n=e[a];void 0===n&&(n=new VP(s+"_"+a,i),e[a]=n,l.push(n)),o=this.getNodeUniform(r,t),n.addUniform(o)}n.uniformGPU=o}return r}}let JP=null,eB=null;class tB{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[jo]:null,[Go]:null},this.trackTimestamp=!0===e.trackTimestamp}async init(e){this.renderer=e}get coordinateSystem(){}beginRender(){}finishRender(){}beginCompute(){}finishCompute(){}draw(){}compute(){}createProgram(){}destroyProgram(){}createBindings(){}updateBindings(){}updateBinding(){}createRenderPipeline(){}createComputePipeline(){}needsRenderUpdate(){}getRenderCacheKey(){}createNodeBuilder(){}updateSampler(){}createDefaultTexture(){}createTexture(){}updateTexture(){}generateMipmaps(){}destroyTexture(){}async copyTextureToBuffer(){}copyTextureToTexture(){}copyFramebufferToTexture(){}createAttribute(){}createIndexAttribute(){}createStorageAttribute(){}updateAttribute(){}destroyAttribute(){}getContext(){}updateSize(){}updateViewport(){}updateTimeStampUID(e){const t=this.get(e),s=this.renderer.info.frame;let i;i=!0===e.isComputeNode?"c:"+this.renderer.info.compute.frameCalls:"r:"+this.renderer.info.render.frameCalls,t.timestampUID=i+":"+e.id+":f"+s}getTimestampUID(e){return this.get(e).timestampUID}getTimestampFrames(e){const t=this.timestampQueryPool[e];return t?t.getTimestampFrames():[]}_getQueryPool(e){const t=e.startsWith("c:")?Go:jo;return this.timestampQueryPool[t]}getTimestamp(e){return this._getQueryPool(e).getTimestamp(e)}hasTimestamp(e){return this._getQueryPool(e).hasTimestamp(e)}isOccluded(){}async resolveTimestampsAsync(e="render"){if(!this.trackTimestamp)return void Qo("WebGPURenderer: Timestamp tracking is disabled.");const t=this.timestampQueryPool[e];if(!t)return;const s=await t.resolveQueriesAsync();return this.renderer.info[e].timestamp=s,s}async getArrayBufferAsync(){}async hasFeatureAsync(){}hasFeature(){}getMaxAnisotropy(){}getDrawingBufferSize(){return JP=JP||new ua,this.renderer.getDrawingBufferSize(JP)}setScissorTest(){}getClearColor(){const e=this.renderer;return eB=eB||new WS,e.getClearColor(eB),eB.getRGB(eB),eB}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:function(){const e=Ho("canvas");return e.style.display="block",e}(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${Xr} webgpu`),this.domElement=e),e}set(e,t){this.data.set(e,t)}get(e){let t=this.data.get(e);return void 0===t&&(t={},this.data.set(e,t)),t}has(e){return this.data.has(e)}delete(e){this.data.delete(e)}deleteBindGroupData(){}dispose(){}}let sB,iB,rB=0;class nB{constructor(e,t){this.buffers=[e.bufferGPU,t],this.type=e.type,this.bufferType=e.bufferType,this.pbo=e.pbo,this.byteLength=e.byteLength,this.bytesPerElement=e.BYTES_PER_ELEMENT,this.version=e.version,this.isInteger=e.isInteger,this.activeBufferIndex=0,this.baseId=e.id}get id(){return`${this.baseId}|${this.activeBufferIndex}`}get bufferGPU(){return this.buffers[this.activeBufferIndex]}get transformBuffer(){return this.buffers[1^this.activeBufferIndex]}switchBuffers(){this.activeBufferIndex^=1}}class oB{constructor(e){this.backend=e}createAttribute(e,t){const s=this.backend,{gl:i}=s,r=e.array,n=e.usage||i.STATIC_DRAW,o=e.isInterleavedBufferAttribute?e.data:e,a=s.get(o);let l,h=a.bufferGPU;if(void 0===h&&(h=this._createBuffer(i,t,r,n),a.bufferGPU=h,a.bufferType=t,a.version=o.version),r instanceof Float32Array)l=i.FLOAT;else if("undefined"!=typeof Float16Array&&r instanceof Float16Array)l=i.HALF_FLOAT;else if(r instanceof Uint16Array)l=e.isFloat16BufferAttribute?i.HALF_FLOAT:i.UNSIGNED_SHORT;else if(r instanceof Int16Array)l=i.SHORT;else if(r instanceof Uint32Array)l=i.UNSIGNED_INT;else if(r instanceof Int32Array)l=i.INT;else if(r instanceof Int8Array)l=i.BYTE;else if(r instanceof Uint8Array)l=i.UNSIGNED_BYTE;else{if(!(r instanceof Uint8ClampedArray))throw new Error("THREE.WebGLBackend: Unsupported buffer data format: "+r);l=i.UNSIGNED_BYTE}let u={bufferGPU:h,bufferType:t,type:l,byteLength:r.byteLength,bytesPerElement:r.BYTES_PER_ELEMENT,version:e.version,pbo:e.pbo,isInteger:l===i.INT||l===i.UNSIGNED_INT||e.gpuType===Mn,id:rB++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);u=new nB(u,e)}s.set(e,u)}updateAttribute(e){const t=this.backend,{gl:s}=t,i=e.array,r=e.isInterleavedBufferAttribute?e.data:e,n=t.get(r),o=n.bufferType,a=e.isInterleavedBufferAttribute?e.data.updateRanges:e.updateRanges;if(s.bindBuffer(o,n.bufferGPU),0===a.length)s.bufferSubData(o,0,i);else{for(let e=0,t=a.length;e<t;e++){const t=a[e];s.bufferSubData(o,t.start*i.BYTES_PER_ELEMENT,i,t.start,t.count)}r.clearUpdateRanges()}s.bindBuffer(o,null),n.version=r.version}destroyAttribute(e){const t=this.backend,{gl:s}=t;e.isInterleavedBufferAttribute&&t.delete(e.data);const i=t.get(e);s.deleteBuffer(i.bufferGPU),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,{gl:s}=t,i=e.isInterleavedBufferAttribute?e.data:e,{bufferGPU:r}=t.get(i),n=e.array,o=n.byteLength;s.bindBuffer(s.COPY_READ_BUFFER,r);const a=s.createBuffer();s.bindBuffer(s.COPY_WRITE_BUFFER,a),s.bufferData(s.COPY_WRITE_BUFFER,o,s.STREAM_READ),s.copyBufferSubData(s.COPY_READ_BUFFER,s.COPY_WRITE_BUFFER,0,0,o),await t.utils._clientWaitAsync();const l=new e.array.constructor(n.length);return s.bindBuffer(s.COPY_WRITE_BUFFER,a),s.getBufferSubData(s.COPY_WRITE_BUFFER,0,l),s.deleteBuffer(a),s.bindBuffer(s.COPY_READ_BUFFER,null),s.bindBuffer(s.COPY_WRITE_BUFFER,null),l.buffer}_createBuffer(e,t,s,i){const r=e.createBuffer();return e.bindBuffer(t,r),e.bufferData(t,s,i),e.bindBuffer(t,null),r}}class aB{constructor(e){this.backend=e,this.gl=this.backend.gl,this.enabled={},this.currentFlipSided=null,this.currentCullFace=null,this.currentProgram=null,this.currentBlendingEnabled=!1,this.currentBlending=null,this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentPremultipledAlpha=null,this.currentPolygonOffsetFactor=null,this.currentPolygonOffsetUnits=null,this.currentColorMask=null,this.currentDepthFunc=null,this.currentDepthMask=null,this.currentStencilFunc=null,this.currentStencilRef=null,this.currentStencilFuncMask=null,this.currentStencilFail=null,this.currentStencilZFail=null,this.currentStencilZPass=null,this.currentStencilMask=null,this.currentLineWidth=null,this.currentClippingPlanes=0,this.currentVAO=null,this.currentIndex=null,this.currentBoundFramebuffers={},this.currentDrawbuffers=new WeakMap,this.maxTextures=this.gl.getParameter(this.gl.MAX_TEXTURE_IMAGE_UNITS),this.currentTextureSlot=null,this.currentBoundTextures={},this.currentBoundBufferBases={},this._init()}_init(){const e=this.gl;sB={[Yr]:e.FUNC_ADD,[Zr]:e.FUNC_SUBTRACT,[Qr]:e.FUNC_REVERSE_SUBTRACT},iB={[Kr]:e.ZERO,[Jr]:e.ONE,[en]:e.SRC_COLOR,[sn]:e.SRC_ALPHA,[hn]:e.SRC_ALPHA_SATURATE,[an]:e.DST_COLOR,[nn]:e.DST_ALPHA,[tn]:e.ONE_MINUS_SRC_COLOR,[rn]:e.ONE_MINUS_SRC_ALPHA,[ln]:e.ONE_MINUS_DST_COLOR,[on]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),s=e.getParameter(e.VIEWPORT);this.currentScissor=(new Pa).fromArray(t),this.currentViewport=(new Pa).fromArray(s),this._tempVec4=new Pa}enable(e){const{enabled:t}=this;!0!==t[e]&&(this.gl.enable(e),t[e]=!0)}disable(e){const{enabled:t}=this;!1!==t[e]&&(this.gl.disable(e),t[e]=!1)}setFlipSided(e){if(this.currentFlipSided!==e){const{gl:t}=this;e?t.frontFace(t.CW):t.frontFace(t.CCW),this.currentFlipSided=e}}setCullFace(e){const{gl:t}=this;0!==e?(this.enable(t.CULL_FACE),e!==this.currentCullFace&&(1===e?t.cullFace(t.BACK):2===e?t.cullFace(t.FRONT):t.cullFace(t.FRONT_AND_BACK))):this.disable(t.CULL_FACE),this.currentCullFace=e}setLineWidth(e){const{currentLineWidth:t,gl:s}=this;e!==t&&(s.lineWidth(e),this.currentLineWidth=e)}setMRTBlending(e){const t=this.gl,s=this.backend.drawBuffersIndexedExt;if(s)for(let i=1;i<e.length;i++)s.blendFuncSeparateiOES(i,t.ONE,t.ZERO,t.ONE,t.ZERO)}setBlending(e,t,s,i,r,n,o,a){const{gl:l}=this;if(0!==e){if(!1===this.currentBlendingEnabled&&(this.enable(l.BLEND),this.currentBlendingEnabled=!0),5===e)r=r||t,n=n||s,o=o||i,t===this.currentBlendEquation&&r===this.currentBlendEquationAlpha||(l.blendEquationSeparate(sB[t],sB[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),s===this.currentBlendSrc&&i===this.currentBlendDst&&n===this.currentBlendSrcAlpha&&o===this.currentBlendDstAlpha||(l.blendFuncSeparate(iB[s],iB[i],iB[n],iB[o]),this.currentBlendSrc=s,this.currentBlendDst=i,this.currentBlendSrcAlpha=n,this.currentBlendDstAlpha=o),this.currentBlending=e,this.currentPremultipledAlpha=!1;else if(e!==this.currentBlending||a!==this.currentPremultipledAlpha){if(this.currentBlendEquation===Yr&&this.currentBlendEquationAlpha===Yr||(l.blendEquation(l.FUNC_ADD),this.currentBlendEquation=Yr,this.currentBlendEquationAlpha=Yr),a)switch(e){case 1:l.blendFuncSeparate(l.ONE,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFunc(l.ONE,l.ONE);break;case 3:l.blendFuncSeparate(l.ZERO,l.ONE_MINUS_SRC_COLOR,l.ZERO,l.ONE);break;case 4:l.blendFuncSeparate(l.DST_COLOR,l.ONE_MINUS_SRC_ALPHA,l.ZERO,l.ONE);break;default:Zo("WebGLState: Invalid blending: ",e)}else switch(e){case 1:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE_MINUS_SRC_ALPHA,l.ONE,l.ONE_MINUS_SRC_ALPHA);break;case 2:l.blendFuncSeparate(l.SRC_ALPHA,l.ONE,l.ONE,l.ONE);break;case 3:Zo("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:Zo("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Zo("WebGLState: Invalid blending: ",e)}this.currentBlendSrc=null,this.currentBlendDst=null,this.currentBlendSrcAlpha=null,this.currentBlendDstAlpha=null,this.currentBlending=e,this.currentPremultipledAlpha=a}}else!0===this.currentBlendingEnabled&&(this.disable(l.BLEND),this.currentBlendingEnabled=!1)}setColorMask(e){this.currentColorMask!==e&&(this.gl.colorMask(e,e,e,e),this.currentColorMask=e)}setDepthTest(e){const{gl:t}=this;e?this.enable(t.DEPTH_TEST):this.disable(t.DEPTH_TEST)}setDepthMask(e){this.currentDepthMask!==e&&(this.gl.depthMask(e),this.currentDepthMask=e)}setDepthFunc(e){if(this.currentDepthFunc!==e){const{gl:t}=this;switch(e){case 0:t.depthFunc(t.NEVER);break;case 1:t.depthFunc(t.ALWAYS);break;case 2:t.depthFunc(t.LESS);break;case 3:default:t.depthFunc(t.LEQUAL);break;case 4:t.depthFunc(t.EQUAL);break;case 5:t.depthFunc(t.GEQUAL);break;case 6:t.depthFunc(t.GREATER);break;case 7:t.depthFunc(t.NOTEQUAL)}this.currentDepthFunc=e}}scissor(e,t,s,i){const r=this._tempVec4.set(e,t,s,i);if(!1===this.currentScissor.equals(r)){const{gl:e}=this;e.scissor(r.x,r.y,r.z,r.w),this.currentScissor.copy(r)}}viewport(e,t,s,i){const r=this._tempVec4.set(e,t,s,i);if(!1===this.currentViewport.equals(r)){const{gl:e}=this;e.viewport(r.x,r.y,r.z,r.w),this.currentViewport.copy(r)}}setScissorTest(e){const t=this.gl;e?this.enable(t.SCISSOR_TEST):this.disable(t.SCISSOR_TEST)}setStencilTest(e){const{gl:t}=this;e?this.enable(t.STENCIL_TEST):this.disable(t.STENCIL_TEST)}setStencilMask(e){this.currentStencilMask!==e&&(this.gl.stencilMask(e),this.currentStencilMask=e)}setStencilFunc(e,t,s){this.currentStencilFunc===e&&this.currentStencilRef===t&&this.currentStencilFuncMask===s||(this.gl.stencilFunc(e,t,s),this.currentStencilFunc=e,this.currentStencilRef=t,this.currentStencilFuncMask=s)}setStencilOp(e,t,s){this.currentStencilFail===e&&this.currentStencilZFail===t&&this.currentStencilZPass===s||(this.gl.stencilOp(e,t,s),this.currentStencilFail=e,this.currentStencilZFail=t,this.currentStencilZPass=s)}setMaterial(e,t,s){const{gl:i}=this;2===e.side?this.disable(i.CULL_FACE):this.enable(i.CULL_FACE);let r=1===e.side;t&&(r=!r),this.setFlipSided(r),1===e.blending&&!1===e.transparent?this.setBlending(0):this.setBlending(e.blending,e.blendEquation,e.blendSrc,e.blendDst,e.blendEquationAlpha,e.blendSrcAlpha,e.blendDstAlpha,e.premultipliedAlpha),this.setDepthFunc(e.depthFunc),this.setDepthTest(e.depthTest),this.setDepthMask(e.depthWrite),this.setColorMask(e.colorWrite);const n=e.stencilWrite;if(this.setStencilTest(n),n&&(this.setStencilMask(e.stencilWriteMask),this.setStencilFunc(e.stencilFunc,e.stencilRef,e.stencilFuncMask),this.setStencilOp(e.stencilFail,e.stencilZFail,e.stencilZPass)),this.setPolygonOffset(e.polygonOffset,e.polygonOffsetFactor,e.polygonOffsetUnits),!0===e.alphaToCoverage&&this.backend.renderer.currentSamples>0?this.enable(i.SAMPLE_ALPHA_TO_COVERAGE):this.disable(i.SAMPLE_ALPHA_TO_COVERAGE),s>0&&this.currentClippingPlanes!==s){const e=12288;for(let t=0;t<8;t++)t<s?this.enable(e+t):this.disable(e+t)}}setPolygonOffset(e,t,s){const{gl:i}=this;e?(this.enable(i.POLYGON_OFFSET_FILL),this.currentPolygonOffsetFactor===t&&this.currentPolygonOffsetUnits===s||(i.polygonOffset(t,s),this.currentPolygonOffsetFactor=t,this.currentPolygonOffsetUnits=s)):this.disable(i.POLYGON_OFFSET_FILL)}useProgram(e){return this.currentProgram!==e&&(this.gl.useProgram(e),this.currentProgram=e,!0)}setVertexState(e,t=null){const s=this.gl;return(this.currentVAO!==e||this.currentIndex!==t)&&(s.bindVertexArray(e),null!==t&&s.bindBuffer(s.ELEMENT_ARRAY_BUFFER,t),this.currentVAO=e,this.currentIndex=t,!0)}resetVertexState(){const e=this.gl;e.bindVertexArray(null),e.bindBuffer(e.ELEMENT_ARRAY_BUFFER,null),this.currentVAO=null,this.currentIndex=null}bindFramebuffer(e,t){const{gl:s,currentBoundFramebuffers:i}=this;return i[e]!==t&&(s.bindFramebuffer(e,t),i[e]=t,e===s.DRAW_FRAMEBUFFER&&(i[s.FRAMEBUFFER]=t),e===s.FRAMEBUFFER&&(i[s.DRAW_FRAMEBUFFER]=t),!0)}drawBuffers(e,t){const{gl:s}=this;let i=[],r=!1;if(null!==e.textures){i=this.currentDrawbuffers.get(t),void 0===i&&(i=[],this.currentDrawbuffers.set(t,i));const n=e.textures;if(i.length!==n.length||i[0]!==s.COLOR_ATTACHMENT0){for(let e=0,t=n.length;e<t;e++)i[e]=s.COLOR_ATTACHMENT0+e;i.length=n.length,r=!0}}else i[0]!==s.BACK&&(i[0]=s.BACK,r=!0);r&&s.drawBuffers(i)}activeTexture(e){const{gl:t,currentTextureSlot:s,maxTextures:i}=this;void 0===e&&(e=t.TEXTURE0+i-1),s!==e&&(t.activeTexture(e),this.currentTextureSlot=e)}bindTexture(e,t,s){const{gl:i,currentTextureSlot:r,currentBoundTextures:n,maxTextures:o}=this;void 0===s&&(s=null===r?i.TEXTURE0+o-1:r);let a=n[s];void 0===a&&(a={type:void 0,texture:void 0},n[s]=a),a.type===e&&a.texture===t||(r!==s&&(i.activeTexture(s),this.currentTextureSlot=s),i.bindTexture(e,t),a.type=e,a.texture=t)}bindBufferBase(e,t,s){const{gl:i}=this,r=`${e}-${t}`;return this.currentBoundBufferBases[r]!==s&&(i.bindBufferBase(e,t,s),this.currentBoundBufferBases[r]=s,!0)}unbindTexture(){const{gl:e,currentTextureSlot:t,currentBoundTextures:s}=this,i=s[t];void 0!==i&&void 0!==i.type&&(e.bindTexture(i.type,null),i.type=void 0,i.texture=void 0)}}class lB{constructor(e){this.backend=e,this.gl=this.backend.gl,this.extensions=e.extensions}convert(e,t=""){const{gl:s,extensions:i}=this;let r;const n=_a.getTransfer(t);if(e===wn)return s.UNSIGNED_BYTE;if(e===Cn)return s.UNSIGNED_SHORT_4_4_4_4;if(e===Rn)return s.UNSIGNED_SHORT_5_5_5_1;if(e===Bn)return s.UNSIGNED_INT_5_9_9_9_REV;if(e===In)return s.UNSIGNED_INT_10F_11F_11F_REV;if(e===vn)return s.BYTE;if(e===Tn)return s.SHORT;if(e===Sn)return s.UNSIGNED_SHORT;if(e===Mn)return s.INT;if(e===An)return s.UNSIGNED_INT;if(e===Nn)return s.FLOAT;if(e===En)return s.HALF_FLOAT;if(1021===e)return s.ALPHA;if(e===Dn)return s.RGB;if(e===Ln)return s.RGBA;if(e===Fn)return s.DEPTH_COMPONENT;if(e===On)return s.DEPTH_STENCIL;if(e===Vn)return s.RED;if(e===zn)return s.RED_INTEGER;if(e===kn)return s.RG;if(e===Un)return s.RG_INTEGER;if(e===Gn)return s.RGBA_INTEGER;if(e===jn||e===$n||e===Wn||e===Hn)if(n===Eo){if(r=i.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(e===jn)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===$n)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===Wn)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===Hn)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=i.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(e===jn)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===$n)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===Wn)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===Hn)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===qn||e===Xn||e===Yn||e===Zn){if(r=i.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(e===qn)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===Xn)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===Yn)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===Zn)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===Qn||e===Kn||e===Jn||e===eo||e===to||e===so||e===io){if(r=i.get("WEBGL_compressed_texture_etc"),null===r)return null;if(e===Qn||e===Kn)return n===Eo?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(e===Jn)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(e===eo)return r.COMPRESSED_R11_EAC;if(e===to)return r.COMPRESSED_SIGNED_R11_EAC;if(e===so)return r.COMPRESSED_RG11_EAC;if(e===io)return r.COMPRESSED_SIGNED_RG11_EAC}if(e===ro||e===no||e===oo||e===ao||e===lo||e===ho||e===uo||e===co||e===po||e===mo||e===fo||e===go||e===yo||e===xo){if(r=i.get("WEBGL_compressed_texture_astc"),null===r)return null;if(e===ro)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===no)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===oo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===ao)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===lo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===ho)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===uo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===co)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===po)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===mo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===fo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===go)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===yo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===xo)return n===Eo?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===bo){if(r=i.get("EXT_texture_compression_bptc"),null===r)return null;if(e===bo)return n===Eo?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT}if(e===_o||e===wo||e===vo||e===To){if(r=i.get("EXT_texture_compression_rgtc"),null===r)return null;if(e===_o)return r.COMPRESSED_RED_RGTC1_EXT;if(e===wo)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===vo)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===To)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===Pn?s.UNSIGNED_INT_24_8:void 0!==s[e]?s[e]:null}_clientWaitAsync(){const{gl:e}=this,t=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);return e.flush(),new Promise((s,i)=>{!function r(){const n=e.clientWaitSync(t,e.SYNC_FLUSH_COMMANDS_BIT,0);if(n===e.WAIT_FAILED)return e.deleteSync(t),void i();n!==e.TIMEOUT_EXPIRED?(e.deleteSync(t),s()):requestAnimationFrame(r)}()})}}let hB,uB,cB,dB=!1;class pB{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===dB&&(this._init(),dB=!0)}_init(){const e=this.gl;hB={[dn]:e.REPEAT,[pn]:e.CLAMP_TO_EDGE,[mn]:e.MIRRORED_REPEAT},uB={[fn]:e.NEAREST,[gn]:e.NEAREST_MIPMAP_NEAREST,[yn]:e.NEAREST_MIPMAP_LINEAR,[xn]:e.LINEAR,[bn]:e.LINEAR_MIPMAP_NEAREST,[_n]:e.LINEAR_MIPMAP_LINEAR},cB={[Ro]:e.NEVER,[Oo]:e.ALWAYS,[Po]:e.LESS,[Io]:e.LEQUAL,[Bo]:e.EQUAL,[Fo]:e.GEQUAL,[Do]:e.GREATER,[Lo]:e.NOTEQUAL}}getGLTextureType(e){const{gl:t}=this;let s;return s=!0===e.isCubeTexture?t.TEXTURE_CUBE_MAP:!0===e.isArrayTexture||!0===e.isDataArrayTexture||!0===e.isCompressedArrayTexture?t.TEXTURE_2D_ARRAY:!0===e.isData3DTexture?t.TEXTURE_3D:t.TEXTURE_2D,s}getInternalFormat(e,t,s,i,r=!1){const{gl:n,extensions:o}=this;if(null!==e){if(void 0!==n[e])return n[e];Yo("WebGLBackend: Attempt to use non-existing WebGL internal format '"+e+"'")}let a=t;if(t===n.RED&&(s===n.FLOAT&&(a=n.R32F),s===n.HALF_FLOAT&&(a=n.R16F),s===n.UNSIGNED_BYTE&&(a=n.R8),s===n.UNSIGNED_SHORT&&(a=n.R16),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RED_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.R8UI),s===n.UNSIGNED_SHORT&&(a=n.R16UI),s===n.UNSIGNED_INT&&(a=n.R32UI),s===n.BYTE&&(a=n.R8I),s===n.SHORT&&(a=n.R16I),s===n.INT&&(a=n.R32I)),t===n.RG&&(s===n.FLOAT&&(a=n.RG32F),s===n.HALF_FLOAT&&(a=n.RG16F),s===n.UNSIGNED_BYTE&&(a=n.RG8),s===n.UNSIGNED_SHORT&&(a=n.RG16),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RG_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RG8UI),s===n.UNSIGNED_SHORT&&(a=n.RG16UI),s===n.UNSIGNED_INT&&(a=n.RG32UI),s===n.BYTE&&(a=n.RG8I),s===n.SHORT&&(a=n.RG16I),s===n.INT&&(a=n.RG32I)),t===n.RGB){const e=r?No:_a.getTransfer(i);s===n.FLOAT&&(a=n.RGB32F),s===n.HALF_FLOAT&&(a=n.RGB16F),s===n.UNSIGNED_BYTE&&(a=n.RGB8),s===n.UNSIGNED_SHORT&&(a=n.RGB16),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I),s===n.UNSIGNED_BYTE&&(a=e===Eo?n.SRGB8:n.RGB8),s===n.UNSIGNED_SHORT_5_6_5&&(a=n.RGB565),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGB4),s===n.UNSIGNED_INT_5_9_9_9_REV&&(a=n.RGB9_E5),s===n.UNSIGNED_INT_10F_11F_11F_REV&&(a=n.R11F_G11F_B10F)}if(t===n.RGB_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGB8UI),s===n.UNSIGNED_SHORT&&(a=n.RGB16UI),s===n.UNSIGNED_INT&&(a=n.RGB32UI),s===n.BYTE&&(a=n.RGB8I),s===n.SHORT&&(a=n.RGB16I),s===n.INT&&(a=n.RGB32I)),t===n.RGBA){const e=r?No:_a.getTransfer(i);s===n.FLOAT&&(a=n.RGBA32F),s===n.HALF_FLOAT&&(a=n.RGBA16F),s===n.UNSIGNED_BYTE&&(a=n.RGBA8),s===n.UNSIGNED_SHORT&&(a=n.RGBA16),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I),s===n.UNSIGNED_BYTE&&(a=e===Eo?n.SRGB8_ALPHA8:n.RGBA8),s===n.UNSIGNED_SHORT_4_4_4_4&&(a=n.RGBA4),s===n.UNSIGNED_SHORT_5_5_5_1&&(a=n.RGB5_A1)}return t===n.RGBA_INTEGER&&(s===n.UNSIGNED_BYTE&&(a=n.RGBA8UI),s===n.UNSIGNED_SHORT&&(a=n.RGBA16UI),s===n.UNSIGNED_INT&&(a=n.RGBA32UI),s===n.BYTE&&(a=n.RGBA8I),s===n.SHORT&&(a=n.RGBA16I),s===n.INT&&(a=n.RGBA32I)),t===n.DEPTH_COMPONENT&&(s===n.UNSIGNED_SHORT&&(a=n.DEPTH_COMPONENT16),s===n.UNSIGNED_INT&&(a=n.DEPTH_COMPONENT24),s===n.FLOAT&&(a=n.DEPTH_COMPONENT32F)),t===n.DEPTH_STENCIL&&s===n.UNSIGNED_INT_24_8&&(a=n.DEPTH24_STENCIL8),a!==n.R16F&&a!==n.R32F&&a!==n.RG16F&&a!==n.RG32F&&a!==n.RGBA16F&&a!==n.RGBA32F||o.get("EXT_color_buffer_float"),a}setTextureParameters(e,t){const{gl:s,extensions:i,backend:r}=this,n=_a.getPrimaries(_a.workingColorSpace),o=t.colorSpace===So?null:_a.getPrimaries(t.colorSpace),a=t.colorSpace===So||n===o?s.NONE:s.BROWSER_DEFAULT_WEBGL;s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,t.flipY),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),s.pixelStorei(s.UNPACK_ALIGNMENT,t.unpackAlignment),s.pixelStorei(s.UNPACK_COLORSPACE_CONVERSION_WEBGL,a),s.texParameteri(e,s.TEXTURE_WRAP_S,hB[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,hB[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||t.isArrayTexture||s.texParameteri(e,s.TEXTURE_WRAP_R,hB[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,uB[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,h=t.minFilter===xn&&l?_n:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,uB[h]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,cB[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===fn)return;if(t.minFilter!==yn&&t.minFilter!==_n)return;if(t.type===Nn&&!1===i.has("OES_texture_float_linear"))return;if(t.anisotropy>1){const n=i.get("EXT_texture_filter_anisotropic");s.texParameterf(e,n.TEXTURE_MAX_ANISOTROPY_EXT,Math.min(t.anisotropy,r.getMaxAnisotropy()))}}}createDefaultTexture(e){const{gl:t,backend:s,defaultTextures:i}=this,r=this.getGLTextureType(e);let n=i[r];void 0===n&&(n=t.createTexture(),s.state.bindTexture(r,n),t.texParameteri(r,t.TEXTURE_MIN_FILTER,t.NEAREST),t.texParameteri(r,t.TEXTURE_MAG_FILTER,t.NEAREST),i[r]=n),s.set(e,{textureGPU:n,glTextureType:r})}createTexture(e,t){const{gl:s,backend:i}=this,{levels:r,width:n,height:o,depth:a}=t,l=i.utils.convert(e.format,e.colorSpace),h=i.utils.convert(e.type),u=this.getInternalFormat(e.internalFormat,l,h,e.colorSpace,e.isVideoTexture),c=s.createTexture(),d=this.getGLTextureType(e);i.state.bindTexture(d,c),this.setTextureParameters(d,e),e.isArrayTexture||e.isDataArrayTexture||e.isCompressedArrayTexture?s.texStorage3D(s.TEXTURE_2D_ARRAY,r,u,n,o,a):e.isData3DTexture?s.texStorage3D(s.TEXTURE_3D,r,u,n,o,a):e.isVideoTexture||s.texStorage2D(d,r,u,n,o),i.set(e,{textureGPU:c,glTextureType:d,glFormat:l,glType:h,glInternalFormat:u})}copyBufferToTexture(e,t){const{gl:s,backend:i}=this,{textureGPU:r,glTextureType:n,glFormat:o,glType:a}=i.get(t),{width:l,height:h}=t.source.data;s.bindBuffer(s.PIXEL_UNPACK_BUFFER,e),i.state.bindTexture(n,r),s.pixelStorei(s.UNPACK_FLIP_Y_WEBGL,!1),s.pixelStorei(s.UNPACK_PREMULTIPLY_ALPHA_WEBGL,!1),s.texSubImage2D(n,0,0,0,l,h,o,a,0),s.bindBuffer(s.PIXEL_UNPACK_BUFFER,null),i.state.unbindTexture()}updateTexture(e,t){const{gl:s}=this,{width:i,height:r}=t,{textureGPU:n,glTextureType:o,glFormat:a,glType:l,glInternalFormat:h}=this.backend.get(e);if(!e.isRenderTargetTexture&&void 0!==n)if(this.backend.state.bindTexture(o,n),this.setTextureParameters(o,e),e.isCompressedTexture){const i=e.mipmaps,r=t.image;for(let t=0;t<i.length;t++){const n=i[t];e.isCompressedArrayTexture?e.format!==s.RGBA?null!==a?s.compressedTexSubImage3D(s.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,r.depth,a,n.data):Yo("WebGLBackend: Attempt to load unsupported compressed texture format in .uploadTexture()"):s.texSubImage3D(s.TEXTURE_2D_ARRAY,t,0,0,0,n.width,n.height,r.depth,a,l,n.data):null!==a?s.compressedTexSubImage2D(s.TEXTURE_2D,t,0,0,n.width,n.height,a,n.data):Yo("WebGLBackend: Unsupported compressed texture format")}}else if(e.isCubeTexture){const n=t.images,o=e.mipmaps;for(let e=0;e<6;e++){const t=mB(n[e]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,0,0,0,i,r,a,l,t);for(let t=0;t<o.length;t++){const i=mB(o[t].images[e]);s.texSubImage2D(s.TEXTURE_CUBE_MAP_POSITIVE_X+e,t+1,0,0,i.width,i.height,a,l,i)}}}else if(e.isDataArrayTexture||e.isArrayTexture){const i=t.image;if(e.layerUpdates.size>0){const t=ec(i.width,i.height,e.format,e.type);for(const r of e.layerUpdates){const e=i.data.subarray(r*t/i.data.BYTES_PER_ELEMENT,(r+1)*t/i.data.BYTES_PER_ELEMENT);s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,r,i.width,i.height,1,a,l,e)}e.clearLayerUpdates()}else s.texSubImage3D(s.TEXTURE_2D_ARRAY,0,0,0,0,i.width,i.height,i.depth,a,l,i.data)}else if(e.isData3DTexture){const e=t.image;s.texSubImage3D(s.TEXTURE_3D,0,0,0,0,e.width,e.height,e.depth,a,l,e.data)}else if(e.isVideoTexture)e.update(),s.texImage2D(o,0,h,a,l,t.image);else{const n=e.mipmaps;if(n.length>0)for(let e=0,t=n.length;e<t;e++){const t=n[e],i=mB(t);s.texSubImage2D(o,e,0,0,t.width,t.height,a,l,i)}else{const e=mB(t.image);s.texSubImage2D(o,0,0,0,i,r,a,l,e)}}}generateMipmaps(e){const{gl:t,backend:s}=this,{textureGPU:i,glTextureType:r}=s.get(e);s.state.bindTexture(r,i),t.generateMipmap(r)}deallocateRenderBuffers(e){const{gl:t,backend:s}=this;if(e){const i=s.get(e);if(i.renderBufferStorageSetup=void 0,i.framebuffers){for(const e in i.framebuffers)t.deleteFramebuffer(i.framebuffers[e]);delete i.framebuffers}if(i.depthRenderbuffer&&(t.deleteRenderbuffer(i.depthRenderbuffer),delete i.depthRenderbuffer),i.stencilRenderbuffer&&(t.deleteRenderbuffer(i.stencilRenderbuffer),delete i.stencilRenderbuffer),i.msaaFrameBuffer&&(t.deleteFramebuffer(i.msaaFrameBuffer),delete i.msaaFrameBuffer),i.msaaRenderbuffers){for(let e=0;e<i.msaaRenderbuffers.length;e++)t.deleteRenderbuffer(i.msaaRenderbuffers[e]);delete i.msaaRenderbuffers}}}destroyTexture(e,t=!1){const{gl:s,backend:i}=this,{textureGPU:r,renderTarget:n}=i.get(e);this.deallocateRenderBuffers(n),!1===t&&s.deleteTexture(r),i.delete(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){const{gl:o,backend:a}=this,{state:l}=this.backend,{textureGPU:h,glTextureType:u,glType:c,glFormat:d}=a.get(t);let p,m,f,g,y,x,b,_,w;l.bindTexture(u,h);const v=e.isCompressedTexture?e.mipmaps[n]:e.image;if(null!==s)p=s.max.x-s.min.x,m=s.max.y-s.min.y,f=s.isBox3?s.max.z-s.min.z:1,g=s.min.x,y=s.min.y,x=s.isBox3?s.min.z:0;else{const t=Math.pow(2,-r);p=Math.floor(v.width*t),m=Math.floor(v.height*t),f=e.isDataArrayTexture||e.isArrayTexture?v.depth:e.isData3DTexture?Math.floor(v.depth*t):1,g=0,y=0,x=0}null!==i?(b=i.x,_=i.y,w=i.z):(b=0,_=0,w=0),o.pixelStorei(o.UNPACK_FLIP_Y_WEBGL,t.flipY),o.pixelStorei(o.UNPACK_PREMULTIPLY_ALPHA_WEBGL,t.premultiplyAlpha),o.pixelStorei(o.UNPACK_ALIGNMENT,t.unpackAlignment);const T=o.getParameter(o.UNPACK_ROW_LENGTH),S=o.getParameter(o.UNPACK_IMAGE_HEIGHT),M=o.getParameter(o.UNPACK_SKIP_PIXELS),A=o.getParameter(o.UNPACK_SKIP_ROWS),N=o.getParameter(o.UNPACK_SKIP_IMAGES);o.pixelStorei(o.UNPACK_ROW_LENGTH,v.width),o.pixelStorei(o.UNPACK_IMAGE_HEIGHT,v.height),o.pixelStorei(o.UNPACK_SKIP_PIXELS,g),o.pixelStorei(o.UNPACK_SKIP_ROWS,y),o.pixelStorei(o.UNPACK_SKIP_IMAGES,x);const E=e.isDataArrayTexture||e.isData3DTexture||t.isArrayTexture,C=t.isDataArrayTexture||t.isData3DTexture||t.isArrayTexture;if(e.isDepthTexture){const s=a.get(e),i=a.get(t),u=a.get(s.renderTarget),c=a.get(i.renderTarget),d=u.framebuffers[s.cacheKey],v=c.framebuffers[i.cacheKey];l.bindFramebuffer(o.READ_FRAMEBUFFER,d),l.bindFramebuffer(o.DRAW_FRAMEBUFFER,v);for(let e=0;e<f;e++)E&&(o.framebufferTextureLayer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,s.textureGPU,r,x+e),o.framebufferTextureLayer(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,h,n,w+e)),o.blitFramebuffer(g,y,p,m,b,_,p,m,o.DEPTH_BUFFER_BIT,o.NEAREST);l.bindFramebuffer(o.READ_FRAMEBUFFER,null),l.bindFramebuffer(o.DRAW_FRAMEBUFFER,null)}else if(0!==r||e.isRenderTargetTexture||a.has(e)){const t=a.get(e);null===this._srcFramebuffer&&(this._srcFramebuffer=o.createFramebuffer()),null===this._dstFramebuffer&&(this._dstFramebuffer=o.createFramebuffer()),l.bindFramebuffer(o.READ_FRAMEBUFFER,this._srcFramebuffer),l.bindFramebuffer(o.DRAW_FRAMEBUFFER,this._dstFramebuffer);for(let e=0;e<f;e++)E?o.framebufferTextureLayer(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,t.textureGPU,r,x+e):o.framebufferTexture2D(o.READ_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,t.textureGPU,r),C?o.framebufferTextureLayer(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,h,n,w+e):o.framebufferTexture2D(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,o.TEXTURE_2D,h,n),0!==r?o.blitFramebuffer(g,y,p,m,b,_,p,m,o.COLOR_BUFFER_BIT,o.NEAREST):C?o.copyTexSubImage3D(u,n,b,_,w+e,g,y,p,m):o.copyTexSubImage2D(u,n,b,_,g,y,p,m);l.bindFramebuffer(o.READ_FRAMEBUFFER,null),l.bindFramebuffer(o.DRAW_FRAMEBUFFER,null)}else C?e.isDataTexture||e.isData3DTexture?o.texSubImage3D(u,n,b,_,w,p,m,f,d,c,v.data):t.isCompressedArrayTexture?o.compressedTexSubImage3D(u,n,b,_,w,p,m,f,d,v.data):o.texSubImage3D(u,n,b,_,w,p,m,f,d,c,v):e.isDataTexture?o.texSubImage2D(o.TEXTURE_2D,n,b,_,p,m,d,c,v.data):e.isCompressedTexture?o.compressedTexSubImage2D(o.TEXTURE_2D,n,b,_,v.width,v.height,d,v.data):o.texSubImage2D(o.TEXTURE_2D,n,b,_,p,m,d,c,v);o.pixelStorei(o.UNPACK_ROW_LENGTH,T),o.pixelStorei(o.UNPACK_IMAGE_HEIGHT,S),o.pixelStorei(o.UNPACK_SKIP_PIXELS,M),o.pixelStorei(o.UNPACK_SKIP_ROWS,A),o.pixelStorei(o.UNPACK_SKIP_IMAGES,N),0===n&&t.generateMipmaps&&o.generateMipmap(u),l.unbindTexture()}copyFramebufferToTexture(e,t,s){const{gl:i}=this,{state:r}=this.backend,{textureGPU:n}=this.backend.get(e),{x:o,y:a,z:l,w:h}=s,u=!0===e.isDepthTexture||t.renderTarget&&t.renderTarget.samples>0,c=t.renderTarget?t.renderTarget.height:this.backend.getDrawingBufferSize().y;if(u){const s=0!==o||0!==a;let u,d;if(!0===e.isDepthTexture?(u=i.DEPTH_BUFFER_BIT,d=i.DEPTH_ATTACHMENT,t.stencil&&(u|=i.STENCIL_BUFFER_BIT)):(u=i.COLOR_BUFFER_BIT,d=i.COLOR_ATTACHMENT0),s){const e=this.backend.get(t.renderTarget),s=e.framebuffers[t.getCacheKey()],d=e.msaaFrameBuffer;r.bindFramebuffer(i.DRAW_FRAMEBUFFER,s),r.bindFramebuffer(i.READ_FRAMEBUFFER,d);const p=c-a-h;i.blitFramebuffer(o,p,o+l,p+h,o,p,o+l,p+h,u,i.NEAREST),r.bindFramebuffer(i.READ_FRAMEBUFFER,s),r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,p,l,h),r.unbindTexture()}else{const e=i.createFramebuffer();r.bindFramebuffer(i.DRAW_FRAMEBUFFER,e),i.framebufferTexture2D(i.DRAW_FRAMEBUFFER,d,i.TEXTURE_2D,n,0),i.blitFramebuffer(0,0,l,h,0,0,l,h,u,i.NEAREST),i.deleteFramebuffer(e)}}else r.bindTexture(i.TEXTURE_2D,n),i.copyTexSubImage2D(i.TEXTURE_2D,0,0,0,o,c-h-a,l,h),r.unbindTexture();e.generateMipmaps&&this.generateMipmaps(e),this.backend._setFramebuffer(t)}setupRenderBufferStorage(e,t,s,i=!1){const{gl:r}=this,n=t.renderTarget,{depthTexture:o,depthBuffer:a,stencilBuffer:l,width:h,height:u}=n;if(r.bindRenderbuffer(r.RENDERBUFFER,e),a&&!l){let t=r.DEPTH_COMPONENT24;if(!0===i){this.extensions.get("WEBGL_multisampled_render_to_texture").renderbufferStorageMultisampleEXT(r.RENDERBUFFER,n.samples,t,h,u)}else s>0?(o&&o.isDepthTexture&&o.type===r.FLOAT&&(t=r.DEPTH_COMPONENT32F),r.renderbufferStorageMultisample(r.RENDERBUFFER,s,t,h,u)):r.renderbufferStorage(r.RENDERBUFFER,t,h,u);r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_ATTACHMENT,r.RENDERBUFFER,e)}else a&&l&&(s>0?r.renderbufferStorageMultisample(r.RENDERBUFFER,s,r.DEPTH24_STENCIL8,h,u):r.renderbufferStorage(r.RENDERBUFFER,r.DEPTH_STENCIL,h,u),r.framebufferRenderbuffer(r.FRAMEBUFFER,r.DEPTH_STENCIL_ATTACHMENT,r.RENDERBUFFER,e));r.bindRenderbuffer(r.RENDERBUFFER,null)}async copyTextureToBuffer(e,t,s,i,r,n){const{backend:o,gl:a}=this,{textureGPU:l,glFormat:h,glType:u}=this.backend.get(e),c=a.createFramebuffer();o.state.bindFramebuffer(a.READ_FRAMEBUFFER,c);const d=e.isCubeTexture?a.TEXTURE_CUBE_MAP_POSITIVE_X+n:a.TEXTURE_2D;a.framebufferTexture2D(a.READ_FRAMEBUFFER,a.COLOR_ATTACHMENT0,d,l,0);const p=this._getTypedArrayType(u),m=i*r*this._getBytesPerTexel(u,h),f=a.createBuffer();a.bindBuffer(a.PIXEL_PACK_BUFFER,f),a.bufferData(a.PIXEL_PACK_BUFFER,m,a.STREAM_READ),a.readPixels(t,s,i,r,h,u,0),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),await o.utils._clientWaitAsync();const g=new p(m/p.BYTES_PER_ELEMENT);return a.bindBuffer(a.PIXEL_PACK_BUFFER,f),a.getBufferSubData(a.PIXEL_PACK_BUFFER,0,g),a.bindBuffer(a.PIXEL_PACK_BUFFER,null),o.state.bindFramebuffer(a.READ_FRAMEBUFFER,null),a.deleteFramebuffer(c),g}_getTypedArrayType(e){const{gl:t}=this;if(e===t.UNSIGNED_BYTE)return Uint8Array;if(e===t.UNSIGNED_SHORT_4_4_4_4)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_5_5_1)return Uint16Array;if(e===t.UNSIGNED_SHORT_5_6_5)return Uint16Array;if(e===t.UNSIGNED_SHORT)return Uint16Array;if(e===t.UNSIGNED_INT)return Uint32Array;if(e===t.HALF_FLOAT)return Uint16Array;if(e===t.FLOAT)return Float32Array;throw new Error(`Unsupported WebGL type: ${e}`)}_getBytesPerTexel(e,t){const{gl:s}=this;let i=0;return e===s.UNSIGNED_BYTE&&(i=1),e!==s.UNSIGNED_SHORT_4_4_4_4&&e!==s.UNSIGNED_SHORT_5_5_5_1&&e!==s.UNSIGNED_SHORT_5_6_5&&e!==s.UNSIGNED_SHORT&&e!==s.HALF_FLOAT||(i=2),e!==s.UNSIGNED_INT&&e!==s.FLOAT||(i=4),t===s.RGBA?4*i:t===s.RGB?3*i:t===s.ALPHA?i:void 0}dispose(){const{gl:e}=this;null!==this._srcFramebuffer&&e.deleteFramebuffer(this._srcFramebuffer),null!==this._dstFramebuffer&&e.deleteFramebuffer(this._dstFramebuffer)}}function mB(e){return e.isDataTexture?e.image.data:"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap||"undefined"!=typeof OffscreenCanvas&&e instanceof OffscreenCanvas?e:e.data}class fB{constructor(e){this.backend=e,this.gl=this.backend.gl,this.availableExtensions=this.gl.getSupportedExtensions(),this.extensions={}}get(e){let t=this.extensions[e];return void 0===t&&(t=this.gl.getExtension(e),this.extensions[e]=t),t}has(e){return this.availableExtensions.includes(e)}}class gB{constructor(e){this.backend=e,this.maxAnisotropy=null}getMaxAnisotropy(){if(null!==this.maxAnisotropy)return this.maxAnisotropy;const e=this.backend.gl,t=this.backend.extensions;if(!0===t.has("EXT_texture_filter_anisotropic")){const s=t.get("EXT_texture_filter_anisotropic");this.maxAnisotropy=e.getParameter(s.MAX_TEXTURE_MAX_ANISOTROPY_EXT)}else this.maxAnisotropy=0;return this.maxAnisotropy}}const yB={WEBGL_multi_draw:"WEBGL_multi_draw",WEBGL_compressed_texture_astc:"texture-compression-astc",WEBGL_compressed_texture_etc:"texture-compression-etc2",WEBGL_compressed_texture_etc1:"texture-compression-etc1",WEBGL_compressed_texture_pvrtc:"texture-compression-pvrtc",WEBGL_compressed_texture_s3tc:"texture-compression-s3tc",EXT_texture_compression_bptc:"texture-compression-bc",EXT_disjoint_timer_query_webgl2:"timestamp-query",OVR_multiview2:"OVR_multiview2"};class xB{constructor(e){this.gl=e.gl,this.extensions=e.extensions,this.info=e.renderer.info,this.mode=null,this.index=0,this.type=null,this.object=null}render(e,t){const{gl:s,mode:i,object:r,type:n,info:o,index:a}=this;0!==a?s.drawElements(i,t,n,e):s.drawArrays(i,e,t),o.update(r,t,1)}renderInstances(e,t,s){const{gl:i,mode:r,type:n,index:o,object:a,info:l}=this;0!==s&&(0!==o?i.drawElementsInstanced(r,t,n,e,s):i.drawArraysInstanced(r,e,t,s),l.update(a,t,s))}renderMultiDraw(e,t,s){const{extensions:i,mode:r,object:n,info:o}=this;if(0===s)return;const a=i.get("WEBGL_multi_draw");if(null===a)for(let i=0;i<s;i++)this.render(e[i],t[i]);else{0!==this.index?a.multiDrawElementsWEBGL(r,t,0,this.type,e,0,s):a.multiDrawArraysWEBGL(r,e,0,t,0,s);let i=0;for(let e=0;e<s;e++)i+=t[e];o.update(n,i,1)}}renderMultiDrawInstances(e,t,s,i){const{extensions:r,mode:n,object:o,info:a}=this;if(0===s)return;const l=r.get("WEBGL_multi_draw");if(null===l)for(let r=0;r<s;r++)this.renderInstances(e[r],t[r],i[r]);else{0!==this.index?l.multiDrawElementsInstancedWEBGL(n,t,0,this.type,e,0,i,0,s):l.multiDrawArraysInstancedWEBGL(n,e,0,t,0,i,0,s);let r=0;for(let e=0;e<s;e++)r+=t[e]*i[e];a.update(o,r,1)}}}class bB{constructor(e=256){this.trackTimestamp=!0,this.maxQueries=e,this.currentQueryIndex=0,this.queryOffsets=new Map,this.isDisposed=!1,this.lastValue=0,this.frames=[],this.pendingResolve=!1,this.timestamps=new Map}getTimestampFrames(){return this.frames}getTimestamp(e){let t=this.timestamps.get(e);return void 0===t&&(Yo(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestamp(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class _B extends bB{constructor(e,t,s=2048){if(super(s),this.gl=e,this.type=t,this.ext=e.getExtension("EXT_disjoint_timer_query_webgl2")||e.getExtension("EXT_disjoint_timer_query"),!this.ext)return Yo("EXT_disjoint_timer_query not supported; timestamps will be disabled."),void(this.trackTimestamp=!1);this.queries=[];for(let t=0;t<this.maxQueries;t++)this.queries.push(e.createQuery());this.activeQuery=null,this.queryStates=new Map}allocateQueriesForContext(e){if(!this.trackTimestamp)return null;if(this.currentQueryIndex+2>this.maxQueries)return Qo(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryStates.set(t,"inactive"),this.queryOffsets.set(e,t),t}beginQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null==t)return;if(null!==this.activeQuery)return;const s=this.queries[t];if(s)try{"inactive"===this.queryStates.get(t)&&(this.gl.beginQuery(this.ext.TIME_ELAPSED_EXT,s),this.activeQuery=t,this.queryStates.set(t,"started"))}catch(e){Zo("Error in beginQuery:",e),this.activeQuery=null,this.queryStates.set(t,"inactive")}}endQuery(e){if(!this.trackTimestamp||this.isDisposed)return;const t=this.queryOffsets.get(e);if(null!=t&&this.activeQuery===t)try{this.gl.endQuery(this.ext.TIME_ELAPSED_EXT),this.queryStates.set(t,"ended"),this.activeQuery=null}catch(e){Zo("Error in endQuery:",e),this.queryStates.set(t,"inactive"),this.activeQuery=null}}async resolveQueriesAsync(){if(!this.trackTimestamp||this.pendingResolve)return this.lastValue;this.pendingResolve=!0;try{const e=new Map;for(const[t,s]of this.queryOffsets){if("ended"===this.queryStates.get(s)){const i=this.queries[s];e.set(t,this.resolveQuery(i))}}if(0===e.size)return this.lastValue;const t={},s=[];for(const[i,r]of e){const e=i.match(/^(.*):f(\d+)$/),n=parseInt(e[2]);!1===s.includes(n)&&s.push(n),void 0===t[n]&&(t[n]=0);const o=await r;this.timestamps.set(i,o),t[n]+=o}const i=t[s[s.length-1]];return this.lastValue=i,this.frames=s,this.currentQueryIndex=0,this.queryOffsets.clear(),this.queryStates.clear(),this.activeQuery=null,i}catch(e){return Zo("Error resolving queries:",e),this.lastValue}finally{this.pendingResolve=!1}}async resolveQuery(e){return new Promise(t=>{if(this.isDisposed)return void t(this.lastValue);let s,i=!1;const r=e=>{i||(i=!0,s&&(clearTimeout(s),s=null),t(e))},n=()=>{if(this.isDisposed)r(this.lastValue);else try{if(this.gl.getParameter(this.ext.GPU_DISJOINT_EXT))return void r(this.lastValue);if(!this.gl.getQueryParameter(e,this.gl.QUERY_RESULT_AVAILABLE))return void(s=setTimeout(n,1));const i=this.gl.getQueryParameter(e,this.gl.QUERY_RESULT);t(Number(i)/1e6)}catch(e){Zo("Error checking query:",e),t(this.lastValue)}};n()})}dispose(){if(!this.isDisposed&&(this.isDisposed=!0,this.trackTimestamp)){for(const e of this.queries)this.gl.deleteQuery(e);this.queries=[],this.queryStates.clear(),this.queryOffsets.clear(),this.lastValue=0,this.activeQuery=null}}}class wB extends tB{constructor(e={}){super(e),this.isWebGLBackend=!0,this.attributeUtils=null,this.extensions=null,this.capabilities=null,this.textureUtils=null,this.bufferRenderer=null,this.gl=null,this.state=null,this.utils=null,this.vaoCache={},this.transformFeedbackCache={},this.discard=!1,this.disjoint=null,this.parallel=null,this._currentContext=null,this._knownBindings=new WeakSet,this._supportsInvalidateFramebuffer="undefined"!=typeof navigator&&/OculusBrowser/g.test(navigator.userAgent),this._xrFramebuffer=null}init(e){super.init(e);const t=this.parameters,s={antialias:e.currentSamples>0,alpha:!0,depth:e.depth,stencil:e.stencil},i=void 0!==t.context?t.context:e.domElement.getContext("webgl2",s);function r(t){t.preventDefault();const s={api:"WebGL",message:t.statusMessage||"Unknown reason",reason:null,originalEvent:t};e.onDeviceLost(s)}this._onContextLost=r,e.domElement.addEventListener("webglcontextlost",r,!1),this.gl=i,this.extensions=new fB(this),this.capabilities=new gB(this),this.attributeUtils=new oB(this),this.textureUtils=new pB(this),this.bufferRenderer=new xB(this),this.state=new aB(this),this.utils=new lB(this),this.extensions.get("EXT_color_buffer_float"),this.extensions.get("WEBGL_clip_cull_distance"),this.extensions.get("OES_texture_float_linear"),this.extensions.get("EXT_color_buffer_half_float"),this.extensions.get("WEBGL_multisampled_render_to_texture"),this.extensions.get("WEBGL_render_shared_exponent"),this.extensions.get("WEBGL_multi_draw"),this.extensions.get("OVR_multiview2"),this.disjoint=this.extensions.get("EXT_disjoint_timer_query_webgl2"),this.parallel=this.extensions.get("KHR_parallel_shader_compile"),this.drawBuffersIndexedExt=this.extensions.get("OES_draw_buffers_indexed")}get coordinateSystem(){return ko}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}async makeXRCompatible(){!0!==this.gl.getContextAttributes().xrCompatible&&await this.gl.makeXRCompatible()}setXRTarget(e){this._xrFramebuffer=e}setXRRenderTargetTextures(e,t,s=null){const i=this.gl;if(this.set(e.texture,{textureGPU:t,glInternalFormat:i.RGBA8}),null!==s){const t=e.stencilBuffer?i.DEPTH24_STENCIL8:i.DEPTH_COMPONENT24;this.set(e.depthTexture,{textureGPU:s,glInternalFormat:t}),!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!0===e._autoAllocateDepthBuffer&&!1===e.multiview&&Yo("WebGLBackend: Render-to-texture extension was disabled because an external texture was provided"),e._autoAllocateDepthBuffer=!1}}initTimestampQuery(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new _B(this.gl,e,2048));const s=this.timestampQueryPool[e];null!==s.allocateQueriesForContext(t)&&s.beginQuery(t)}prepareTimestampBuffer(e,t){if(!this.disjoint||!this.trackTimestamp)return;this.timestampQueryPool[e].endQuery(t)}getContext(){return this.gl}beginRender(e){const{state:t}=this,s=this.get(e);if(e.viewport)this.updateViewport(e);else{const{width:e,height:s}=this.getDrawingBufferSize();t.viewport(0,0,e,s)}if(e.scissor){const{x:s,y:i,width:r,height:n}=e.scissorValue;t.scissor(s,e.height-n-i,r,n)}this.initTimestampQuery(jo,this.getTimestampUID(e)),s.previousContext=this._currentContext,this._currentContext=e,this._setFramebuffer(e),this.clear(e.clearColor,e.clearDepth,e.clearStencil,e,!1);const i=e.occlusionQueryCount;i>0&&(s.currentOcclusionQueries=s.occlusionQueries,s.currentOcclusionQueryObjects=s.occlusionQueryObjects,s.lastOcclusionObject=null,s.occlusionQueries=new Array(i),s.occlusionQueryObjects=new Array(i),s.occlusionQueryIndex=0)}finishRender(e){const{gl:t,state:s}=this,i=this.get(e),r=i.previousContext;s.resetVertexState();const n=e.occlusionQueryCount;n>0&&(n>i.occlusionQueryIndex&&t.endQuery(t.ANY_SAMPLES_PASSED),this.resolveOccludedAsync(e));const o=e.textures;if(null!==o)for(let e=0;e<o.length;e++){const t=o[e];t.generateMipmaps&&this.generateMipmaps(t)}if(this._currentContext=r,this._resolveRenderTarget(e),null!==r)if(this._setFramebuffer(r),r.viewport)this.updateViewport(r);else{const{width:e,height:t}=this.getDrawingBufferSize();s.viewport(0,0,e,t)}this.prepareTimestampBuffer(jo,this.getTimestampUID(e))}resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueries:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const e=new WeakSet,{gl:r}=this;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueries=null;const n=()=>{let o=0;for(let t=0;t<s.length;t++){const n=s[t];null!==n&&(r.getQueryParameter(n,r.QUERY_RESULT_AVAILABLE)&&(0===r.getQueryParameter(n,r.QUERY_RESULT)&&e.add(i[t]),s[t]=null,r.deleteQuery(n),o++))}o<s.length?requestAnimationFrame(n):t.occluded=e};n()}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}updateViewport(e){const{state:t}=this,{x:s,y:i,width:r,height:n}=e.viewportValue;t.viewport(s,e.height-n-i,r,n)}setScissorTest(e){this.state.setScissorTest(e)}getClearColor(){const e=super.getClearColor();return e.r*=e.a,e.g*=e.a,e.b*=e.a,e}clear(e,t,s,i=null,r=!0,n=!0){const{gl:o,renderer:a}=this;if(null===i){i={textures:null,clearColorValue:this.getClearColor()}}let l=0;if(e&&(l|=o.COLOR_BUFFER_BIT),t&&(l|=o.DEPTH_BUFFER_BIT),s&&(l|=o.STENCIL_BUFFER_BIT),0!==l){let h;h=i.clearColorValue?i.clearColorValue:this.getClearColor();const u=a.getClearDepth(),c=a.getClearStencil();if(t&&this.state.setDepthMask(!0),null===i.textures)o.clearColor(h.r,h.g,h.b,h.a),o.clear(l);else{if(r&&this._setFramebuffer(i),e)for(let e=0;e<i.textures.length;e++)0===e?o.clearBufferfv(o.COLOR,e,[h.r,h.g,h.b,h.a]):o.clearBufferfv(o.COLOR,e,[0,0,0,1]);t&&s?o.clearBufferfi(o.DEPTH_STENCIL,0,u,c):t?o.clearBufferfv(o.DEPTH,0,[u]):s&&o.clearBufferiv(o.STENCIL,0,[c]),r&&n&&this._resolveRenderTarget(i)}}}beginCompute(e){const{state:t,gl:s}=this;t.bindFramebuffer(s.FRAMEBUFFER,null),this.initTimestampQuery(Go,this.getTimestampUID(e))}compute(e,t,s,i,r=null){const{state:n,gl:o}=this;!1===this.discard&&(n.enable(o.RASTERIZER_DISCARD),this.discard=!0);const{programGPU:a,transformBuffers:l,attributes:h}=this.get(i),u=this._getVaoKey(h),c=this.vaoCache[u];void 0===c?this.vaoCache[u]=this._createVao(h):n.setVertexState(c),n.useProgram(a),this._bindUniforms(s);const d=this._getTransformFeedback(l);o.bindTransformFeedback(o.TRANSFORM_FEEDBACK,d),o.beginTransformFeedback(o.POINTS),r=null!==r?r:t.count,Array.isArray(r)?(Qo("WebGLBackend.compute(): The count parameter must be a single number, not an array."),r=r[0]):r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute&&(Qo("WebGLBackend.compute(): The count parameter must be a single number, not IndirectStorageBufferAttribute"),r=t.count),h[0].isStorageInstancedBufferAttribute?o.drawArraysInstanced(o.POINTS,0,1,r):o.drawArrays(o.POINTS,0,r),o.endTransformFeedback(),o.bindTransformFeedback(o.TRANSFORM_FEEDBACK,null);for(let e=0;e<l.length;e++){const t=l[e];t.pbo&&this.has(t.pbo)&&this.textureUtils.copyBufferToTexture(t.transformBuffer,t.pbo),t.switchBuffers()}}finishCompute(e){const{state:t,gl:s}=this;this.discard=!1,t.disable(s.RASTERIZER_DISCARD),this.prepareTimestampBuffer(Go,this.getTimestampUID(e)),this._currentContext&&this._setFramebuffer(this._currentContext)}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.isArrayTexture&&e.camera.isArrayCamera}draw(e){const{object:t,pipeline:s,material:i,context:r,hardwareClippingPlanes:n}=e,{programGPU:o}=this.get(s),{gl:a,state:l}=this,h=this.get(r),u=e.getDrawParameters();if(null===u)return;this._bindUniforms(e.getBindings());const c=t.isMesh&&t.matrixWorld.determinant()<0;l.setMaterial(i,c,n),null!==r.textures&&r.textures.length>1&&l.setMRTBlending(r.textures),l.useProgram(o);const d=e.getAttributes(),p=this.get(d);let m=p.vaoGPU;if(void 0===m){const e=this._getVaoKey(d);m=this.vaoCache[e],void 0===m&&(m=this._createVao(d),this.vaoCache[e]=m,p.vaoGPU=m)}const f=e.getIndex(),g=null!==f?this.get(f).bufferGPU:null;l.setVertexState(m,g);const y=h.lastOcclusionObject;if(y!==t&&void 0!==y){if(null!==y&&!0===y.occlusionTest&&(a.endQuery(a.ANY_SAMPLES_PASSED),h.occlusionQueryIndex++),!0===t.occlusionTest){const e=a.createQuery();a.beginQuery(a.ANY_SAMPLES_PASSED,e),h.occlusionQueries[h.occlusionQueryIndex]=e,h.occlusionQueryObjects[h.occlusionQueryIndex]=t}h.lastOcclusionObject=t}const x=this.bufferRenderer;t.isPoints?x.mode=a.POINTS:t.isLineSegments?x.mode=a.LINES:t.isLine?x.mode=a.LINE_STRIP:t.isLineLoop?x.mode=a.LINE_LOOP:!0===i.wireframe?(l.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),x.mode=a.LINES):x.mode=a.TRIANGLES;const{vertexCount:b,instanceCount:_}=u;let{firstVertex:w}=u;if(x.object=t,null!==f){w*=f.array.BYTES_PER_ELEMENT;const e=this.get(f);x.index=f.count,x.type=e.type}else x.index=0;const v=()=>{t.isBatchedMesh?null!==t._multiDrawInstances?(Qo("WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),x.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?x.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):Qo("WebGLBackend: WEBGL_multi_draw not supported."):_>1?x.renderInstances(w,b,_):x.render(w,b)};if(!0===e.camera.isArrayCamera&&e.camera.cameras.length>0&&!1===e.camera.isMultiViewCamera){const s=this.get(e.camera),i=e.camera.cameras,r=e.getBindingGroup("cameraIndex").bindings[0];if(void 0===s.indexesGPU||s.indexesGPU.length!==i.length){const e=new Uint32Array([0,0,0,0]),t=[];for(let s=0,r=i.length;s<r;s++){const i=a.createBuffer();e[0]=s,a.bindBuffer(a.UNIFORM_BUFFER,i),a.bufferData(a.UNIFORM_BUFFER,e,a.STATIC_DRAW),t.push(i)}s.indexesGPU=t}const n=this.get(r),o=this.renderer.getPixelRatio(),h=this._currentContext.renderTarget,u=this._isRenderCameraDepthArray(this._currentContext),c=this._currentContext.activeCubeFace;if(u){const e=this.get(h.depthTexture);if(e.clearedRenderId!==this.renderer._nodes.nodeFrame.renderId){e.clearedRenderId=this.renderer._nodes.nodeFrame.renderId;const{stencilBuffer:t}=h;for(let e=0,s=i.length;e<s;e++)this.renderer._activeCubeFace=e,this._currentContext.activeCubeFace=e,this._setFramebuffer(this._currentContext),this.clear(!1,!0,t,this._currentContext,!1,!1);this.renderer._activeCubeFace=c,this._currentContext.activeCubeFace=c}}for(let r=0,h=i.length;r<h;r++){const h=i[r];if(t.layers.test(h.layers)){u&&(this.renderer._activeCubeFace=r,this._currentContext.activeCubeFace=r,this._setFramebuffer(this._currentContext));const t=h.viewport;if(void 0!==t){const s=t.x*o,i=t.y*o,r=t.width*o,n=t.height*o;l.viewport(Math.floor(s),Math.floor(e.context.height-n-i),Math.floor(r),Math.floor(n))}l.bindBufferBase(a.UNIFORM_BUFFER,n.index,s.indexesGPU[r]),v()}this._currentContext.activeCubeFace=c,this.renderer._activeCubeFace=c}}else v()}needsRenderUpdate(){return!1}getRenderCacheKey(){return""}createDefaultTexture(e){this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}updateSampler(){return""}createNodeBuilder(e,t){return new KP(e,t)}createProgram(e){const t=this.gl,{stage:s,code:i}=e,r="fragment"===s?t.createShader(t.FRAGMENT_SHADER):t.createShader(t.VERTEX_SHADER);t.shaderSource(r,i),t.compileShader(r),this.set(e,{shaderGPU:r})}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){const s=this.gl,i=e.pipeline,{fragmentProgram:r,vertexProgram:n}=i,o=s.createProgram(),a=this.get(r).shaderGPU,l=this.get(n).shaderGPU;if(s.attachShader(o,a),s.attachShader(o,l),s.linkProgram(o),this.set(i,{programGPU:o,fragmentShader:a,vertexShader:l}),null!==t&&this.parallel){const r=new Promise(t=>{const r=this.parallel,n=()=>{s.getProgramParameter(o,r.COMPLETION_STATUS_KHR)?(this._completeCompile(e,i),t()):requestAnimationFrame(n)};n()});return void t.push(r)}this._completeCompile(e,i)}_handleSource(e,t){const s=e.split("\n"),i=[],r=Math.max(t-6,0),n=Math.min(t+6,s.length);for(let e=r;e<n;e++){const r=e+1;i.push(`${r===t?">":" "} ${r}: ${s[e]}`)}return i.join("\n")}_getShaderErrors(e,t,s){const i=e.getShaderParameter(t,e.COMPILE_STATUS),r=(e.getShaderInfoLog(t)||"").trim();if(i&&""===r)return"";const n=/ERROR: 0:(\d+)/.exec(r);if(n){const i=parseInt(n[1]);return s.toUpperCase()+"\n\n"+r+"\n\n"+this._handleSource(e.getShaderSource(t),i)}return r}_logProgramError(e,t,s){if(this.renderer.debug.checkShaderErrors){const i=this.gl,r=(i.getProgramInfoLog(e)||"").trim();if(!1===i.getProgramParameter(e,i.LINK_STATUS))if("function"==typeof this.renderer.debug.onShaderError)this.renderer.debug.onShaderError(i,e,s,t);else{const n=this._getShaderErrors(i,s,"vertex"),o=this._getShaderErrors(i,t,"fragment");Zo("THREE.WebGLProgram: Shader Error "+i.getError()+" - VALIDATE_STATUS "+i.getProgramParameter(e,i.VALIDATE_STATUS)+"\n\nProgram Info Log: "+r+"\n"+n+"\n"+o)}else""!==r&&Yo("WebGLProgram: Program Info Log:",r)}}_completeCompile(e,t){const{state:s,gl:i}=this,r=this.get(t),{programGPU:n,fragmentShader:o,vertexShader:a}=r;!1===i.getProgramParameter(n,i.LINK_STATUS)&&this._logProgramError(n,o,a),s.useProgram(n);const l=e.getBindings();this._setupBindings(l,n),this.set(t,{programGPU:n})}createComputePipeline(e,t){const{state:s,gl:i}=this,r={stage:"fragment",code:"#version 300 es\nprecision highp float;\nvoid main() {}"};this.createProgram(r);const{computeProgram:n}=e,o=i.createProgram(),a=this.get(r).shaderGPU,l=this.get(n).shaderGPU,h=n.transforms,u=[],c=[];for(let e=0;e<h.length;e++){const t=h[e];u.push(t.varyingName),c.push(t.attributeNode)}i.attachShader(o,a),i.attachShader(o,l),i.transformFeedbackVaryings(o,u,i.SEPARATE_ATTRIBS),i.linkProgram(o),!1===i.getProgramParameter(o,i.LINK_STATUS)&&this._logProgramError(o,a,l),s.useProgram(o),this._setupBindings(t,o);const d=n.attributes,p=[],m=[];for(let e=0;e<d.length;e++){const t=d[e].node.attribute;p.push(t),this.has(t)||this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER)}for(let e=0;e<c.length;e++){const t=c[e].attribute;this.has(t)||this.attributeUtils.createAttribute(t,i.ARRAY_BUFFER);const s=this.get(t);m.push(s)}this.set(e,{programGPU:o,transformBuffers:m,attributes:p})}createBindings(e,t){if(!1===this._knownBindings.has(t)){this._knownBindings.add(t);let e=0,s=0;for(const i of t){this.set(i,{textures:s,uniformBuffers:e});for(const t of i.bindings)t.isUniformBuffer&&e++,t.isSampledTexture&&s++}}this.updateBindings(e,t)}updateBindings(e){const{gl:t}=this,s=this.get(e);let i=s.uniformBuffers,r=s.textures;for(const s of e.bindings){const e=this.get(s);if(s.isUniformsGroup||s.isUniformBuffer){const r=s.buffer;let{bufferGPU:n}=this.get(r);void 0===n?(n=t.createBuffer(),t.bindBuffer(t.UNIFORM_BUFFER,n),t.bufferData(t.UNIFORM_BUFFER,r.byteLength,t.DYNAMIC_DRAW),this.set(r,{bufferGPU:n})):t.bindBuffer(t.UNIFORM_BUFFER,n);const o=s.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,n),0===o.length)t.bufferData(t.UNIFORM_BUFFER,r,t.DYNAMIC_DRAW);else{const e=Wo(r),s=e?1:r.BYTES_PER_ELEMENT;for(let i=0,n=o.length;i<n;i++){const n=o[i],a=n.start*s,l=n.count*s,h=a*(e?r.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,h,r,a,l)}}e.index=i++,e.bufferGPU=n,this.set(s,e)}else if(s.isSampledTexture){const{textureGPU:t,glTextureType:i}=this.get(s.texture);e.index=r++,e.textureGPU=t,e.glTextureType=i,this.set(s,e)}}}updateBinding(e){const t=this.gl;if(e.isUniformsGroup||e.isUniformBuffer){const s=this.get(e).bufferGPU,i=e.buffer,r=e.updateRanges;if(t.bindBuffer(t.UNIFORM_BUFFER,s),0===r.length)t.bufferData(t.UNIFORM_BUFFER,i,t.DYNAMIC_DRAW);else{const e=Wo(i),s=e?1:i.BYTES_PER_ELEMENT;for(let n=0,o=r.length;n<o;n++){const o=r[n],a=o.start*s,l=o.count*s,h=a*(e?i.BYTES_PER_ELEMENT:1);t.bufferSubData(t.UNIFORM_BUFFER,h,i,a,l)}}}}createIndexAttribute(e){const t=this.gl;this.attributeUtils.createAttribute(e,t.ELEMENT_ARRAY_BUFFER)}createAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}createStorageAttribute(e){if(this.has(e))return;const t=this.gl;this.attributeUtils.createAttribute(e,t.ARRAY_BUFFER)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}hasFeature(e){const t=Object.keys(yB).filter(t=>yB[t]===e),s=this.extensions;for(let e=0;e<t.length;e++)if(s.has(t[e]))return!0;return!1}getMaxAnisotropy(){return this.capabilities.getMaxAnisotropy()}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){this.textureUtils.copyTextureToTexture(e,t,s,i,r,n)}copyFramebufferToTexture(e,t,s){this.textureUtils.copyFramebufferToTexture(e,t,s)}_setFramebuffer(e){const{gl:t,state:s}=this;let i=null;if(null!==e.textures){const r=e.renderTarget,n=this.get(r),{samples:o,depthBuffer:a,stencilBuffer:l}=r,h=!0===r.isWebGLCubeRenderTarget,u=!0===r.isRenderTarget3D,c=r.depth>1,d=!0===r.isXRRenderTarget,p=!0===d&&!0===r._hasExternalTextures;let m=n.msaaFrameBuffer,f=n.depthRenderbuffer;const g=this.extensions.get("WEBGL_multisampled_render_to_texture"),y=this.extensions.get("OVR_multiview2"),x=this._useMultisampledExtension(r),b=VS(e);let _;if(h?(n.cubeFramebuffers||(n.cubeFramebuffers={}),_=n.cubeFramebuffers[b]):d&&!1===p?_=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),_=n.framebuffers[b]),void 0===_){_=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,_);const i=e.textures,a=[];if(h){n.cubeFramebuffers[b]=_;const{textureGPU:e}=this.get(i[0]),s=this.renderer._activeCubeFace,r=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_CUBE_MAP_POSITIVE_X+s,e,r)}else{n.framebuffers[b]=_;for(let s=0;s<i.length;s++){const n=i[s],a=this.get(n);a.renderTarget=e.renderTarget,a.cacheKey=b;const l=t.COLOR_ATTACHMENT0+s;if(r.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,l,a.textureGPU,0,o,0,2);else if(u||c){const e=this.renderer._activeCubeFace,s=this.renderer._activeMipmapLevel;t.framebufferTextureLayer(t.FRAMEBUFFER,l,a.textureGPU,s,e)}else if(x)g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,l,t.TEXTURE_2D,a.textureGPU,0,o);else{const e=this.renderer._activeMipmapLevel;t.framebufferTexture2D(t.FRAMEBUFFER,l,t.TEXTURE_2D,a.textureGPU,e)}}}const d=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const s=t.createRenderbuffer();this.textureUtils.setupRenderBufferStorage(s,e,0,x),n.xrDepthRenderbuffer=s,a.push(l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT),t.bindRenderbuffer(t.RENDERBUFFER,s),t.framebufferRenderbuffer(t.FRAMEBUFFER,d,t.RENDERBUFFER,s)}else if(null!==e.depthTexture){a.push(l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT);const s=this.get(e.depthTexture);if(s.renderTarget=e.renderTarget,s.cacheKey=b,r.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,d,s.textureGPU,0,o,0,2);else if(p&&x)g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,d,t.TEXTURE_2D,s.textureGPU,0,o);else if(e.depthTexture.isArrayTexture){const e=this.renderer._activeCubeFace;t.framebufferTextureLayer(t.FRAMEBUFFER,d,s.textureGPU,0,e)}else if(e.depthTexture.isCubeTexture){const e=this.renderer._activeCubeFace;t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_CUBE_MAP_POSITIVE_X+e,s.textureGPU,0)}else t.framebufferTexture2D(t.FRAMEBUFFER,d,t.TEXTURE_2D,s.textureGPU,0)}n.depthInvalidationArray=a}else{if(this._isRenderCameraDepthArray(e)){s.bindFramebuffer(t.FRAMEBUFFER,_);const i=this.renderer._activeCubeFace,r=this.get(e.depthTexture),n=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;t.framebufferTextureLayer(t.FRAMEBUFFER,n,r.textureGPU,0,i)}if((d||x||r.multiview)&&!0!==r._isOpaqueFramebuffer){s.bindFramebuffer(t.FRAMEBUFFER,_);const i=this.get(e.textures[0]);r.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,i.textureGPU,0,o,0,2):x?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,i.textureGPU,0);const a=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;if(!0===r._autoAllocateDepthBuffer){const e=n.xrDepthRenderbuffer;t.bindRenderbuffer(t.RENDERBUFFER,e),t.framebufferRenderbuffer(t.FRAMEBUFFER,a,t.RENDERBUFFER,e)}else{const s=this.get(e.depthTexture);r.multiview?y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,a,s.textureGPU,0,o,0,2):x?g.framebufferTexture2DMultisampleEXT(t.FRAMEBUFFER,a,t.TEXTURE_2D,s.textureGPU,0,o):t.framebufferTexture2D(t.FRAMEBUFFER,a,t.TEXTURE_2D,s.textureGPU,0)}}}if(o>0&&!1===x&&!r.multiview){if(void 0===m){const i=[];m=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,m);const r=[],h=e.textures;for(let s=0;s<h.length;s++){r[s]=t.createRenderbuffer(),t.bindRenderbuffer(t.RENDERBUFFER,r[s]),i.push(t.COLOR_ATTACHMENT0+s);const n=e.textures[s],a=this.get(n);t.renderbufferStorageMultisample(t.RENDERBUFFER,o,a.glInternalFormat,e.width,e.height),t.framebufferRenderbuffer(t.FRAMEBUFFER,t.COLOR_ATTACHMENT0+s,t.RENDERBUFFER,r[s])}if(t.bindRenderbuffer(t.RENDERBUFFER,null),n.msaaFrameBuffer=m,n.msaaRenderbuffers=r,a&&void 0===f){f=t.createRenderbuffer(),this.textureUtils.setupRenderBufferStorage(f,e,o),n.depthRenderbuffer=f;const s=l?t.DEPTH_STENCIL_ATTACHMENT:t.DEPTH_ATTACHMENT;i.push(s)}n.invalidationArray=i}i=n.msaaFrameBuffer}else i=_;s.drawBuffers(e,_)}s.bindFramebuffer(t.FRAMEBUFFER,i)}_getVaoKey(e){let t="";for(let s=0;s<e.length;s++){t+=":"+this.get(e[s]).id}return t}_createVao(e){const{gl:t}=this,s=t.createVertexArray();t.bindVertexArray(s);for(let s=0;s<e.length;s++){const i=e[s],r=this.get(i);let n,o;t.bindBuffer(t.ARRAY_BUFFER,r.bufferGPU),t.enableVertexAttribArray(s),!0===i.isInterleavedBufferAttribute?(n=i.data.stride*r.bytesPerElement,o=i.offset*r.bytesPerElement):(n=0,o=0),r.isInteger?t.vertexAttribIPointer(s,i.itemSize,r.type,n,o):t.vertexAttribPointer(s,i.itemSize,r.type,i.normalized,n,o),i.isInstancedBufferAttribute&&!i.isInterleavedBufferAttribute?t.vertexAttribDivisor(s,i.meshPerAttribute):i.isInterleavedBufferAttribute&&i.data.isInstancedInterleavedBuffer&&t.vertexAttribDivisor(s,i.data.meshPerAttribute)}return t.bindBuffer(t.ARRAY_BUFFER,null),s}_getTransformFeedback(e){let t="";for(let s=0;s<e.length;s++)t+=":"+e[s].id;let s=this.transformFeedbackCache[t];if(void 0!==s)return s;const{gl:i}=this;s=i.createTransformFeedback(),i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,s);for(let t=0;t<e.length;t++){const s=e[t];i.bindBufferBase(i.TRANSFORM_FEEDBACK_BUFFER,t,s.transformBuffer)}return i.bindTransformFeedback(i.TRANSFORM_FEEDBACK,null),this.transformFeedbackCache[t]=s,s}_setupBindings(e,t){const s=this.gl;for(const i of e)for(const e of i.bindings){const i=this.get(e).index;if(e.isUniformsGroup||e.isUniformBuffer){const r=s.getUniformBlockIndex(t,e.name);s.uniformBlockBinding(t,r,i)}else if(e.isSampledTexture){const r=s.getUniformLocation(t,e.name);s.uniform1i(r,i)}}}_bindUniforms(e){const{gl:t,state:s}=this;for(const i of e)for(const e of i.bindings){const i=this.get(e),r=i.index;e.isUniformsGroup||e.isUniformBuffer?s.bindBufferBase(t.UNIFORM_BUFFER,r,i.bufferGPU):e.isSampledTexture&&s.bindTexture(i.glTextureType,i.textureGPU,t.TEXTURE0+r)}}_resolveRenderTarget(e){const{gl:t,state:s}=this,i=e.renderTarget;if(null!==e.textures&&i){const r=this.get(i);if(i.samples>0&&!1===this._useMultisampledExtension(i)){const n=r.framebuffers[e.getCacheKey()];let o=t.COLOR_BUFFER_BIT;i.resolveDepthBuffer&&(i.depthBuffer&&(o|=t.DEPTH_BUFFER_BIT),i.stencilBuffer&&i.resolveStencilBuffer&&(o|=t.STENCIL_BUFFER_BIT));const a=r.msaaFrameBuffer,l=r.msaaRenderbuffers,h=e.textures,u=h.length>1;if(s.bindFramebuffer(t.READ_FRAMEBUFFER,a),s.bindFramebuffer(t.DRAW_FRAMEBUFFER,n),u)for(let e=0;e<h.length;e++)t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,null),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,null,0);for(let s=0;s<h.length;s++){if(u){const{textureGPU:e}=this.get(h[s]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.RENDERBUFFER,l[s]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0,t.TEXTURE_2D,e,0)}if(e.scissor){const{x:s,y:i,width:r,height:n}=e.scissorValue,a=e.height-n-i;t.blitFramebuffer(s,a,s+r,a+n,s,a,s+r,a+n,o,t.NEAREST)}else t.blitFramebuffer(0,0,e.width,e.height,0,0,e.width,e.height,o,t.NEAREST)}if(u)for(let e=0;e<h.length;e++){const{textureGPU:s}=this.get(h[e]);t.framebufferRenderbuffer(t.READ_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.RENDERBUFFER,l[e]),t.framebufferTexture2D(t.DRAW_FRAMEBUFFER,t.COLOR_ATTACHMENT0+e,t.TEXTURE_2D,s,0)}!0===this._supportsInvalidateFramebuffer&&t.invalidateFramebuffer(t.READ_FRAMEBUFFER,r.invalidationArray)}else if(!1===i.resolveDepthBuffer&&r.framebuffers){const i=r.framebuffers[e.getCacheKey()];s.bindFramebuffer(t.DRAW_FRAMEBUFFER,i),t.invalidateFramebuffer(t.DRAW_FRAMEBUFFER,r.depthInvalidationArray)}}}_useMultisampledExtension(e){return!0===e.multiview||e.samples>0&&!0===this.extensions.has("WEBGL_multisampled_render_to_texture")&&!1!==e._autoAllocateDepthBuffer}dispose(){null!==this.textureUtils&&this.textureUtils.dispose();const e=this.extensions.get("WEBGL_lose_context");e&&e.loseContext(),this.renderer.domElement.removeEventListener("webglcontextlost",this._onContextLost)}}const vB="point-list",TB="line-list",SB="line-strip",MB="triangle-list",AB="triangle-strip",NB="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},EB="never",CB="less",RB="equal",PB="less-equal",BB="greater",IB="not-equal",DB="greater-equal",LB="always",FB="store",OB="load",VB="clear",zB="ccw",kB="cw",UB="none",GB="back",jB="uint16",$B="uint32",WB="r8unorm",HB="r8snorm",qB="r8uint",XB="r8sint",YB="r16uint",ZB="r16sint",QB="r16float",KB="rg8unorm",JB="rg8snorm",eI="rg8uint",tI="rg8sint",sI="r32uint",iI="r32sint",rI="r32float",nI="rg16uint",oI="rg16sint",aI="rg16float",lI="rgba8unorm",hI="rgba8unorm-srgb",uI="rgba8snorm",cI="rgba8uint",dI="rgba8sint",pI="bgra8unorm",mI="bgra8unorm-srgb",fI="rgb9e5ufloat",gI="rgb10a2unorm",yI="rg11b10ufloat",xI="rg32uint",bI="rg32sint",_I="rg32float",wI="rgba16uint",vI="rgba16sint",TI="rgba16float",SI="rgba32uint",MI="rgba32sint",AI="rgba32float",NI="depth16unorm",EI="depth24plus",CI="depth24plus-stencil8",RI="depth32float",PI="depth32float-stencil8",BI="bc1-rgba-unorm",II="bc1-rgba-unorm-srgb",DI="bc2-rgba-unorm",LI="bc2-rgba-unorm-srgb",FI="bc3-rgba-unorm",OI="bc3-rgba-unorm-srgb",VI="bc4-r-unorm",zI="bc4-r-snorm",kI="bc5-rg-unorm",UI="bc5-rg-snorm",GI="bc6h-rgb-ufloat",jI="bc6h-rgb-float",$I="bc7-rgba-unorm",WI="bc7-rgba-unorm-srgb",HI="etc2-rgb8unorm",qI="etc2-rgb8unorm-srgb",XI="etc2-rgb8a1unorm",YI="etc2-rgb8a1unorm-srgb",ZI="etc2-rgba8unorm",QI="etc2-rgba8unorm-srgb",KI="eac-r11unorm",JI="eac-r11snorm",eD="eac-rg11unorm",tD="eac-rg11snorm",sD="astc-4x4-unorm",iD="astc-4x4-unorm-srgb",rD="astc-5x4-unorm",nD="astc-5x4-unorm-srgb",oD="astc-5x5-unorm",aD="astc-5x5-unorm-srgb",lD="astc-6x5-unorm",hD="astc-6x5-unorm-srgb",uD="astc-6x6-unorm",cD="astc-6x6-unorm-srgb",dD="astc-8x5-unorm",pD="astc-8x5-unorm-srgb",mD="astc-8x6-unorm",fD="astc-8x6-unorm-srgb",gD="astc-8x8-unorm",yD="astc-8x8-unorm-srgb",xD="astc-10x5-unorm",bD="astc-10x5-unorm-srgb",_D="astc-10x6-unorm",wD="astc-10x6-unorm-srgb",vD="astc-10x8-unorm",TD="astc-10x8-unorm-srgb",SD="astc-10x10-unorm",MD="astc-10x10-unorm-srgb",AD="astc-12x10-unorm",ND="astc-12x10-unorm-srgb",ED="astc-12x12-unorm",CD="astc-12x12-unorm-srgb",RD="clamp-to-edge",PD="repeat",BD="mirror-repeat",ID="linear",DD="nearest",LD="zero",FD="one",OD="src",VD="one-minus-src",zD="src-alpha",kD="one-minus-src-alpha",UD="dst",GD="one-minus-dst",jD="dst-alpha",$D="one-minus-dst-alpha",WD="src-alpha-saturated",HD="constant",qD="one-minus-constant",XD="add",YD="subtract",ZD="reverse-subtract",QD="min",KD="max",JD=0,eL=15,tL="keep",sL="zero",iL="replace",rL="invert",nL="increment-clamp",oL="decrement-clamp",aL="increment-wrap",lL="decrement-wrap",hL="storage",uL="read-only-storage",cL="write-only",dL="read-only",pL="read-write",mL="non-filtering",fL="comparison",gL="float",yL="unfilterable-float",xL="depth",bL="sint",_L="uint",wL="2d",vL="3d",TL="2d",SL="2d-array",ML="cube",AL="3d",NL="all",EL="vertex",CL="instance",RL={CoreFeaturesAndLimits:"core-features-and-limits",DepthClipControl:"depth-clip-control",Depth32FloatStencil8:"depth32float-stencil8",TextureCompressionBC:"texture-compression-bc",TextureCompressionBCSliced3D:"texture-compression-bc-sliced-3d",TextureCompressionETC2:"texture-compression-etc2",TextureCompressionASTC:"texture-compression-astc",TextureCompressionASTCSliced3D:"texture-compression-astc-sliced-3d",TimestampQuery:"timestamp-query",IndirectFirstInstance:"indirect-first-instance",ShaderF16:"shader-f16",RG11B10UFloat:"rg11b10ufloat-renderable",BGRA8UNormStorage:"bgra8unorm-storage",Float32Filterable:"float32-filterable",Float32Blendable:"float32-blendable",ClipDistances:"clip-distances",DualSourceBlending:"dual-source-blending",Subgroups:"subgroups",TextureFormatsTier1:"texture-formats-tier1",TextureFormatsTier2:"texture-formats-tier2"},PL={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class BL extends zP{constructor(e,t,s){super(e,t?t.value:null),this.textureNode=t,this.groupNode=s}update(){const{textureNode:e}=this;return this.texture!==e.value?(this.texture=e.value,!0):super.update()}}class IL extends BP{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let DL=0;class LL extends IL{constructor(e,t){super("StorageBuffer_"+DL++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:vc.READ_WRITE,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class FL extends dS{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:ID}),this.flipYSampler=e.createSampler({minFilter:DD}),this.transferPipelines={},this.flipYPipelines={},this.mipmapVertexShaderModule=e.createShaderModule({label:"mipmapVertex",code:"\nstruct VarysStruct {\n\t@builtin( position ) Position: vec4<f32>,\n\t@location( 0 ) vTex : vec2<f32>\n};\n\n@vertex\nfn main( @builtin( vertex_index ) vertexIndex : u32 ) -> VarysStruct {\n\n\tvar Varys : VarysStruct;\n\n\tvar pos = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( -1.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 ),\n\t\tvec2<f32>( -1.0, -1.0 ),\n\t\tvec2<f32>( 1.0, -1.0 )\n\t);\n\n\tvar tex = array< vec2<f32>, 4 >(\n\t\tvec2<f32>( 0.0, 0.0 ),\n\t\tvec2<f32>( 1.0, 0.0 ),\n\t\tvec2<f32>( 0.0, 1.0 ),\n\t\tvec2<f32>( 1.0, 1.0 )\n\t);\n\n\tVarys.vTex = tex[ vertexIndex ];\n\tVarys.Position = vec4<f32>( pos[ vertexIndex ], 0.0, 1.0 );\n\n\treturn Varys;\n\n}\n"}),this.mipmapFragmentShaderModule=e.createShaderModule({label:"mipmapFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vTex );\n\n}\n"}),this.flipYFragmentShaderModule=e.createShaderModule({label:"flipYFragment",code:"\n@group( 0 ) @binding( 0 )\nvar imgSampler : sampler;\n\n@group( 0 ) @binding( 1 )\nvar img : texture_2d<f32>;\n\n@fragment\nfn main( @location( 0 ) vTex : vec2<f32> ) -> @location( 0 ) vec4<f32> {\n\n\treturn textureSample( img, imgSampler, vec2( vTex.x, 1.0 - vTex.y ) );\n\n}\n"})}getTransferPipeline(e){let t=this.transferPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`mipmap-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.mipmapFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:AB,stripIndexFormat:$B},layout:"auto"}),this.transferPipelines[e]=t),t}getFlipYPipeline(e){let t=this.flipYPipelines[e];return void 0===t&&(t=this.device.createRenderPipeline({label:`flipY-${e}`,vertex:{module:this.mipmapVertexShaderModule,entryPoint:"main"},fragment:{module:this.flipYFragmentShaderModule,entryPoint:"main",targets:[{format:e}]},primitive:{topology:AB,stripIndexFormat:$B},layout:"auto"}),this.flipYPipelines[e]=t),t}flipY(e,t,s=0){const i=t.format,{width:r,height:n}=t.size,o=this.getTransferPipeline(i),a=this.getFlipYPipeline(i),l=this.device.createTexture({size:{width:r,height:n,depthOrArrayLayers:1},format:i,usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.TEXTURE_BINDING}),h=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:TL,baseArrayLayer:s}),u=l.createView({baseMipLevel:0,mipLevelCount:1,dimension:TL,baseArrayLayer:0}),c=this.device.createCommandEncoder({}),d=(e,t,s)=>{const i=e.getBindGroupLayout(0),r=this.device.createBindGroup({layout:i,entries:[{binding:0,resource:this.flipYSampler},{binding:1,resource:t}]}),n=c.beginRenderPass({colorAttachments:[{view:s,loadOp:VB,storeOp:FB,clearValue:[0,0,0,0]}]});n.setPipeline(e),n.setBindGroup(0,r),n.draw(4,1,0,0),n.end()};d(o,h,u),d(a,u,h),this.device.queue.submit([c.finish()]),l.destroy()}generateMipmaps(e,t,s=0,i=null){const r=this.get(e);void 0===r.layers&&(r.layers=[]);const n=r.layers[s]||this._mipmapCreateBundles(e,t,s),o=i||this.device.createCommandEncoder({label:"mipmapEncoder"});this._mipmapRunBundles(o,n),null===i&&this.device.queue.submit([o.finish()]),r.layers[s]=n}_mipmapCreateBundles(e,t,s){const i=this.getTransferPipeline(t.format),r=i.getBindGroupLayout(0);let n=e.createView({baseMipLevel:0,mipLevelCount:1,dimension:TL,baseArrayLayer:s});const o=[];for(let a=1;a<t.mipLevelCount;a++){const l=this.device.createBindGroup({layout:r,entries:[{binding:0,resource:this.mipmapSampler},{binding:1,resource:n}]}),h=e.createView({baseMipLevel:a,mipLevelCount:1,dimension:TL,baseArrayLayer:s}),u={colorAttachments:[{view:h,loadOp:VB,storeOp:FB,clearValue:[0,0,0,0]}]},c=this.device.createRenderBundleEncoder({colorFormats:[t.format]});c.setPipeline(i),c.setBindGroup(0,l),c.draw(4,1,0,0),o.push({renderBundles:[c.finish()],passDescriptor:u}),n=h}return o}_mipmapRunBundles(e,t){const s=t.length;for(let i=0;i<s;i++){const s=t[i],r=e.beginRenderPass(s.passDescriptor);r.executeBundles(s.renderBundles),r.end()}}}const OL={[Ro]:"never",[Po]:"less",[Bo]:"equal",[Io]:"less-equal",[Do]:"greater",[Fo]:"greater-equal",[Oo]:"always",[Lo]:"not-equal"},VL=[0,1,3,2,4,5];class zL{constructor(e){this.backend=e,this._passUtils=null,this.defaultTexture={},this.defaultCubeTexture={},this.defaultVideoFrame=null,this._samplerCache=new Map}updateSampler(e){const t=this.backend,s=e.minFilter+"-"+e.magFilter+"-"+e.wrapS+"-"+e.wrapT+"-"+(e.wrapR||"0")+"-"+e.anisotropy+"-"+(e.compareFunction||0);let i=this._samplerCache.get(s);if(void 0===i){const r={addressModeU:this._convertAddressMode(e.wrapS),addressModeV:this._convertAddressMode(e.wrapT),addressModeW:this._convertAddressMode(e.wrapR),magFilter:this._convertFilterMode(e.magFilter),minFilter:this._convertFilterMode(e.minFilter),mipmapFilter:this._convertFilterMode(e.minFilter),maxAnisotropy:1};r.magFilter===ID&&r.minFilter===ID&&r.mipmapFilter===ID&&(r.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&(r.compare=OL[e.compareFunction]);i={sampler:t.device.createSampler(r),usedTimes:0},this._samplerCache.set(s,i)}const r=t.get(e);if(r.sampler!==i.sampler){if(void 0!==r.sampler){const e=this._samplerCache.get(r.samplerKey);e.usedTimes--,0===e.usedTimes&&this._samplerCache.delete(r.samplerKey)}r.samplerKey=s,r.sampler=i.sampler,i.usedTimes++}return s}createDefaultTexture(e){let t;const s=kL(e);t=e.isCubeTexture?this._getDefaultCubeTextureGPU(s):this._getDefaultTextureGPU(s),this.backend.get(e).texture=t}createTexture(e,t={}){const s=this.backend,i=s.get(e);if(i.initialized)throw new Error("WebGPUTextureUtils: Texture already initialized.");if(e.isExternalTexture)return i.texture=e.sourceTexture,void(i.initialized=!0);void 0===t.needsMipmaps&&(t.needsMipmaps=!1),void 0===t.levels&&(t.levels=1),void 0===t.depth&&(t.depth=1);const{width:r,height:n,depth:o,levels:a}=t;e.isFramebufferTexture&&(t.renderTarget?t.format=this.backend.utils.getCurrentColorFormat(t.renderTarget):t.format=this.backend.utils.getPreferredCanvasFormat());const l=this._getDimension(e),h=e.internalFormat||t.format||kL(e,s.device);i.format=h;const{samples:u,primarySamples:c,isMSAA:d}=s.utils.getTextureSampleData(e);let p=GPUTextureUsage.TEXTURE_BINDING|GPUTextureUsage.COPY_DST|GPUTextureUsage.COPY_SRC;!0===e.isStorageTexture&&(p|=GPUTextureUsage.STORAGE_BINDING),!0!==e.isCompressedTexture&&!0!==e.isCompressedArrayTexture&&h!==fI&&(p|=GPUTextureUsage.RENDER_ATTACHMENT);const m={label:e.name,size:{width:r,height:n,depthOrArrayLayers:o},mipLevelCount:a,sampleCount:c,dimension:l,format:h,usage:p};if(void 0===h)return Yo("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);if(e.isCubeTexture&&(m.textureBindingViewDimension=ML),i.texture=s.device.createTexture(m),d){const e=Object.assign({},m);e.label=e.label+"-msaa",e.sampleCount=u,e.mipLevelCount=1,i.msaaTexture=s.device.createTexture(e)}i.initialized=!0,i.textureDescriptorGPU=m}destroyTexture(e,t=!1){const s=this.backend,i=s.get(e);void 0!==i.texture&&!1===t&&i.texture.destroy(),void 0!==i.msaaTexture&&i.msaaTexture.destroy(),s.delete(e)}generateMipmaps(e,t=null){const s=this.backend.get(e);if(e.isCubeTexture)for(let e=0;e<6;e++)this._generateMipmaps(s.texture,s.textureDescriptorGPU,e,t);else{const i=e.image.depth||1;for(let e=0;e<i;e++)this._generateMipmaps(s.texture,s.textureDescriptorGPU,e,t)}}getColorBuffer(){const e=this.backend,t=e.renderer.getCanvasTarget(),{width:s,height:i}=e.getDrawingBufferSize(),r=e.renderer.currentSamples,n=t.colorTexture,o=e.get(n);if(n.width===s&&n.height===i&&n.samples===r)return o.texture;let a=o.texture;return a&&a.destroy(),a=e.device.createTexture({label:"colorBuffer",size:{width:s,height:i,depthOrArrayLayers:1},sampleCount:e.utils.getSampleCount(e.renderer.currentSamples),format:e.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC}),n.source.width=s,n.source.height=i,n.samples=r,o.texture=a,a}getDepthBuffer(e=!0,t=!1){const s=this.backend,i=s.renderer.getCanvasTarget(),{width:r,height:n}=s.getDrawingBufferSize(),o=s.renderer.currentSamples,a=i.depthTexture;if(a.width===r&&a.height===n&&a.samples===o&&a.depth===e&&a.stencil===t)return s.get(a).texture;const l=s.get(a).texture;let h,u;if(t?(h=On,u=Pn):e&&(h=Fn,u=An),void 0!==l){if(a.image.width===r&&a.image.height===n&&a.format===h&&a.type===u&&a.samples===o)return l;this.destroyTexture(a)}return a.name="depthBuffer",a.format=h,a.type=u,a.image.width=r,a.image.height=n,a.samples=o,this.createTexture(a,{width:r,height:n}),s.get(a).texture}updateTexture(e,t){const s=this.backend.get(e),i=e.mipmaps,{textureDescriptorGPU:r}=s;if(!e.isRenderTargetTexture&&void 0!==r){if(e.isDataTexture)if(i.length>0)for(let t=0,n=i.length;t<n;t++){const n=i[t];this._copyBufferToTexture(n,s.texture,r,0,e.flipY,0,t)}else this._copyBufferToTexture(t.image,s.texture,r,0,e.flipY);else if(e.isArrayTexture||e.isDataArrayTexture||e.isData3DTexture)for(let i=0;i<t.image.depth;i++)this._copyBufferToTexture(t.image,s.texture,r,i,e.flipY,i);else if(e.isCompressedTexture||e.isCompressedArrayTexture)this._copyCompressedBufferToTexture(e.mipmaps,s.texture,r);else if(e.isCubeTexture)this._copyCubeMapToTexture(e,s.texture,r);else if(i.length>0)for(let t=0,n=i.length;t<n;t++){const n=i[t];this._copyImageToTexture(n,s.texture,r,0,e.flipY,e.premultiplyAlpha,t)}else this._copyImageToTexture(t.image,s.texture,r,0,e.flipY,e.premultiplyAlpha);s.version=e.version}}async copyTextureToBuffer(e,t,s,i,r,n){const o=this.backend.device,a=this.backend.get(e),l=a.texture,h=a.textureDescriptorGPU.format,u=this._getBytesPerTexel(h);let c=i*u;c=256*Math.ceil(c/256);const d=o.createBuffer({size:(r-1)*c+i*u,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),p=o.createCommandEncoder();p.copyTextureToBuffer({texture:l,origin:{x:t,y:s,z:n}},{buffer:d,bytesPerRow:c},{width:i,height:r});const m=this._getTypedArrayType(h);o.queue.submit([p.finish()]),await d.mapAsync(GPUMapMode.READ);return new m(d.getMappedRange())}dispose(){this._samplerCache.clear()}_getDefaultTextureGPU(e){let t=this.defaultTexture[e];if(void 0===t){const s=new Ra;s.minFilter=fn,s.magFilter=fn,this.createTexture(s,{width:1,height:1,format:e}),this.defaultTexture[e]=t=s}return this.backend.get(t).texture}_getDefaultCubeTextureGPU(e){let t=this.defaultCubeTexture[e];if(void 0===t){const s=new Xh;s.minFilter=fn,s.magFilter=fn,this.createTexture(s,{width:1,height:1,depth:6}),this.defaultCubeTexture[e]=t=s}return this.backend.get(t).texture}_copyCubeMapToTexture(e,t,s){const i=e.images,r=e.mipmaps;for(let n=0;n<6;n++){const o=i[n],a=!0===e.flipY?VL[n]:n;o.isDataTexture?this._copyBufferToTexture(o.image,t,s,a,e.flipY):this._copyImageToTexture(o,t,s,a,e.flipY,e.premultiplyAlpha);for(let i=0;i<r.length;i++){const o=r[i].images[n];o.isDataTexture?this._copyBufferToTexture(o.image,t,s,a,e.flipY,0,i+1):this._copyImageToTexture(o,t,s,a,e.flipY,e.premultiplyAlpha,i+1)}}}_copyImageToTexture(e,t,s,i,r,n,o=0){const a=this.backend.device,l=o>0?e.width:s.size.width,h=o>0?e.height:s.size.height;try{a.queue.copyExternalImageToTexture({source:e,flipY:r},{texture:t,mipLevel:o,origin:{x:0,y:0,z:i},premultipliedAlpha:n},{width:l,height:h,depthOrArrayLayers:1})}catch(e){}}_getPassUtils(){let e=this._passUtils;return null===e&&(this._passUtils=e=new FL(this.backend.device)),e}_generateMipmaps(e,t,s=0,i=null){this._getPassUtils().generateMipmaps(e,t,s,i)}_flipY(e,t,s=0){this._getPassUtils().flipY(e,t,s)}_copyBufferToTexture(e,t,s,i,r,n=0,o=0){const a=this.backend.device,l=e.data,h=this._getBytesPerTexel(s.format),u=e.width*h;a.queue.writeTexture({texture:t,mipLevel:o,origin:{x:0,y:0,z:i}},l,{offset:e.width*e.height*h*n,bytesPerRow:u},{width:e.width,height:e.height,depthOrArrayLayers:1}),!0===r&&this._flipY(t,s,i)}_copyCompressedBufferToTexture(e,t,s){const i=this.backend.device,r=this._getBlockData(s.format),n=s.size.depthOrArrayLayers>1;for(let o=0;o<e.length;o++){const a=e[o],l=a.width,h=a.height,u=n?s.size.depthOrArrayLayers:1,c=Math.ceil(l/r.width)*r.byteLength,d=c*Math.ceil(h/r.height);for(let e=0;e<u;e++)i.queue.writeTexture({texture:t,mipLevel:o,origin:{x:0,y:0,z:e}},a.data,{offset:e*d,bytesPerRow:c,rowsPerImage:Math.ceil(h/r.height)},{width:Math.ceil(l/r.width)*r.width,height:Math.ceil(h/r.height)*r.height,depthOrArrayLayers:1})}}_getBlockData(e){return e===BI||e===II?{byteLength:8,width:4,height:4}:e===DI||e===LI||e===FI||e===OI?{byteLength:16,width:4,height:4}:e===VI||e===zI?{byteLength:8,width:4,height:4}:e===kI||e===UI||e===GI||e===jI||e===$I||e===WI?{byteLength:16,width:4,height:4}:e===HI||e===qI||e===XI||e===YI?{byteLength:8,width:4,height:4}:e===ZI||e===QI?{byteLength:16,width:4,height:4}:e===KI||e===JI?{byteLength:8,width:4,height:4}:e===eD||e===tD||e===sD||e===iD?{byteLength:16,width:4,height:4}:e===rD||e===nD?{byteLength:16,width:5,height:4}:e===oD||e===aD?{byteLength:16,width:5,height:5}:e===lD||e===hD?{byteLength:16,width:6,height:5}:e===uD||e===cD?{byteLength:16,width:6,height:6}:e===dD||e===pD?{byteLength:16,width:8,height:5}:e===mD||e===fD?{byteLength:16,width:8,height:6}:e===gD||e===yD?{byteLength:16,width:8,height:8}:e===xD||e===bD?{byteLength:16,width:10,height:5}:e===_D||e===wD?{byteLength:16,width:10,height:6}:e===vD||e===TD?{byteLength:16,width:10,height:8}:e===SD||e===MD?{byteLength:16,width:10,height:10}:e===AD||e===ND?{byteLength:16,width:12,height:10}:e===ED||e===CD?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=RD;return e===dn?t=PD:e===mn&&(t=BD),t}_convertFilterMode(e){let t=ID;return e!==fn&&1004!==e&&e!==yn||(t=DD),t}_getBytesPerTexel(e){return e===WB||e===HB||e===qB||e===XB?1:e===YB||e===ZB||e===QB||e===KB||e===JB||e===eI||e===tI?2:e===sI||e===iI||e===rI||e===nI||e===oI||e===aI||e===lI||e===hI||e===uI||e===cI||e===dI||e===pI||e===mI||e===fI||e===gI||e===yI||e===RI||e===EI||e===CI||e===PI?4:e===xI||e===bI||e===_I||e===wI||e===vI||e===TI?8:e===SI||e===MI||e===AI?16:void 0}_getTypedArrayType(e){return e===qB?Uint8Array:e===XB?Int8Array:e===WB?Uint8Array:e===HB?Int8Array:e===eI?Uint8Array:e===tI?Int8Array:e===KB?Uint8Array:e===JB?Int8Array:e===cI?Uint8Array:e===dI?Int8Array:e===lI||e===hI?Uint8Array:e===uI?Int8Array:e===YB?Uint16Array:e===ZB?Int16Array:e===nI?Uint16Array:e===oI?Int16Array:e===wI?Uint16Array:e===vI?Int16Array:e===QB||e===aI||e===TI?Uint16Array:e===sI?Uint32Array:e===iI?Int32Array:e===rI?Float32Array:e===xI?Uint32Array:e===bI?Int32Array:e===_I?Float32Array:e===SI?Uint32Array:e===MI?Int32Array:e===AI?Float32Array:e===pI||e===mI?Uint8Array:e===gI||e===fI||e===yI?Uint32Array:e===RI?Float32Array:e===EI||e===CI?Uint32Array:e===PI?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?vL:wL,t}}function kL(e,t=null){const s=e.format,i=e.type,r=e.colorSpace,n=_a.getTransfer(r);let o;if(!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(s){case jn:case $n:o=n===Eo?II:BI;break;case Wn:o=n===Eo?LI:DI;break;case Hn:o=n===Eo?OI:FI;break;case _o:o=VI;break;case wo:o=zI;break;case vo:o=kI;break;case To:o=UI;break;case bo:o=n===Eo?WI:$I;break;case Kn:case Qn:o=n===Eo?qI:HI;break;case Jn:o=n===Eo?QI:ZI;break;case eo:o=KI;break;case to:o=JI;break;case so:o=eD;break;case io:o=tD;break;case ro:o=n===Eo?iD:sD;break;case no:o=n===Eo?nD:rD;break;case oo:o=n===Eo?aD:oD;break;case ao:o=n===Eo?hD:lD;break;case lo:o=n===Eo?cD:uD;break;case ho:o=n===Eo?pD:dD;break;case uo:o=n===Eo?fD:mD;break;case co:o=n===Eo?yD:gD;break;case po:o=n===Eo?bD:xD;break;case mo:o=n===Eo?wD:_D;break;case fo:o=n===Eo?TD:vD;break;case go:o=n===Eo?MD:SD;break;case yo:o=n===Eo?ND:AD;break;case xo:o=n===Eo?CD:ED;break;case Ln:o=n===Eo?hI:lI;break;default:Zo("WebGPURenderer: Unsupported texture format.",s)}else switch(s){case Ln:switch(i){case vn:o=uI;break;case Tn:o=vI;break;case Sn:o=wI;break;case An:o=SI;break;case Mn:o=MI;break;case wn:o=n===Eo?hI:lI;break;case En:o=TI;break;case Nn:o=AI;break;default:Zo("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case Dn:switch(i){case Bn:o=fI;break;case In:o=yI;break;default:Zo("WebGPURenderer: Unsupported texture type with RGBFormat.",i)}break;case Vn:switch(i){case vn:o=HB;break;case Tn:o=ZB;break;case Sn:o=YB;break;case An:o=sI;break;case Mn:o=iI;break;case wn:o=WB;break;case En:o=QB;break;case Nn:o=rI;break;default:Zo("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case kn:switch(i){case vn:o=JB;break;case Tn:o=oI;break;case Sn:o=nI;break;case An:o=xI;break;case Mn:o=bI;break;case wn:o=KB;break;case En:o=aI;break;case Nn:o=_I;break;default:Zo("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case Fn:switch(i){case Sn:o=NI;break;case An:o=EI;break;case Nn:o=RI;break;default:Zo("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case On:switch(i){case Pn:o=CI;break;case Nn:t&&!1===t.features.has(RL.Depth32FloatStencil8)&&Zo('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),o=PI;break;default:Zo("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case zn:switch(i){case Mn:o=iI;break;case An:o=sI;break;default:Zo("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case Un:switch(i){case Mn:o=bI;break;case An:o=xI;break;default:Zo("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case Gn:switch(i){case Mn:o=MI;break;case An:o=SI;break;default:Zo("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:Zo("WebGPURenderer: Unsupported texture format.",s)}return o}const UL=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,GL=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,jL={f32:"float",i32:"int",u32:"uint",bool:"bool","vec2<f32>":"vec2","vec2<i32>":"ivec2","vec2<u32>":"uvec2","vec2<bool>":"bvec2",vec2f:"vec2",vec2i:"ivec2",vec2u:"uvec2",vec2b:"bvec2","vec3<f32>":"vec3","vec3<i32>":"ivec3","vec3<u32>":"uvec3","vec3<bool>":"bvec3",vec3f:"vec3",vec3i:"ivec3",vec3u:"uvec3",vec3b:"bvec3","vec4<f32>":"vec4","vec4<i32>":"ivec4","vec4<u32>":"uvec4","vec4<bool>":"bvec4",vec4f:"vec4",vec4i:"ivec4",vec4u:"uvec4",vec4b:"bvec4","mat2x2<f32>":"mat2",mat2x2f:"mat2","mat3x3<f32>":"mat3",mat3x3f:"mat3","mat4x4<f32>":"mat4",mat4x4f:"mat4",sampler:"sampler",texture_1d:"texture",texture_2d:"texture",texture_2d_array:"texture",texture_multisampled_2d:"cubeTexture",texture_depth_2d:"depthTexture",texture_depth_2d_array:"depthTexture",texture_depth_multisampled_2d:"depthTexture",texture_depth_cube:"depthTexture",texture_depth_cube_array:"depthTexture",texture_3d:"texture3D",texture_cube:"cubeTexture",texture_cube_array:"cubeTexture",texture_storage_1d:"storageTexture",texture_storage_2d:"storageTexture",texture_storage_2d_array:"storageTexture",texture_storage_3d:"storageTexture"};class $L extends qR{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:o}=(e=>{const t=(e=e.trim()).match(UL);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=GL.exec(s));)i.push({name:r[1],type:r[2]});const n=[];for(let e=0;e<i.length;e++){const{name:t,type:s}=i[e];let r=s;r.startsWith("ptr")?r="pointer":(r.startsWith("texture")&&(r=s.split("<")[0]),r=jL[r]),n.push(new IR(r,t))}const o=e.substring(t[0].length),a=t[3]||"void",l=void 0!==t[1]?t[1]:"";return{type:jL[a]||a,inputs:n,name:l,inputsCode:s,blockCode:o,outputType:a}}throw new Error("FunctionNode: Function is not a WGSL code.")})(e);super(t,s,i),this.inputsCode=r,this.blockCode=n,this.outputType=o}getCode(e=this.name){const t="void"!==this.outputType?"-> "+this.outputType:"";return`fn ${e} ( ${this.inputsCode.trim()} ) ${t}`+this.blockCode}}class WL extends HR{parseFunction(e){return new $L(e)}}const HL={[vc.READ_ONLY]:"read",[vc.WRITE_ONLY]:"write",[vc.READ_WRITE]:"read_write"},qL={[dn]:"repeat",[pn]:"clamp",[mn]:"mirror"},XL={vertex:NB.VERTEX,fragment:NB.FRAGMENT,compute:NB.COMPUTE},YL={instance:!0,swizzleAssign:!1,storageBuffer:!0},ZL={"^^":"tsl_xor"},QL={float:"f32",int:"i32",uint:"u32",bool:"bool",color:"vec3<f32>",vec2:"vec2<f32>",ivec2:"vec2<i32>",uvec2:"vec2<u32>",bvec2:"vec2<bool>",vec3:"vec3<f32>",ivec3:"vec3<i32>",uvec3:"vec3<u32>",bvec3:"vec3<bool>",vec4:"vec4<f32>",ivec4:"vec4<i32>",uvec4:"vec4<u32>",bvec4:"vec4<bool>",mat2:"mat2x2<f32>",mat3:"mat3x3<f32>",mat4:"mat4x4<f32>"},KL={},JL={tsl_xor:new iN("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new iN("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new iN("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new iN("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new iN("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new iN("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new iN("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new iN("fn tsl_equals_bvec3( a : vec3f, b : vec3f ) -> vec3<bool> { return vec3<bool>( a.x == b.x, a.y == b.y, a.z == b.z ); }"),equals_bvec4:new iN("fn tsl_equals_bvec4( a : vec4f, b : vec4f ) -> vec4<bool> { return vec4<bool>( a.x == b.x, a.y == b.y, a.z == b.z, a.w == b.w ); }"),repeatWrapping_float:new iN("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new iN("fn tsl_mirrorWrapping_float( coord: f32 ) -> f32 { let mirrored = fract( coord * 0.5 ) * 2.0; return 1.0 - abs( 1.0 - mirrored ); }"),clampWrapping_float:new iN("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new iN("\nfn tsl_biquadraticTexture( map : texture_2d<f32>, coord : vec2f, iRes : vec2u, level : u32 ) -> vec4f {\n\n\tlet res = vec2f( iRes );\n\n\tlet uvScaled = coord * res;\n\tlet uvWrapping = ( ( uvScaled % res ) + res ) % res;\n\n\t// https://www.shadertoy.com/view/WtyXRy\n\n\tlet uv = uvWrapping - 0.5;\n\tlet iuv = floor( uv );\n\tlet f = fract( uv );\n\n\tlet rg1 = textureLoad( map, vec2u( iuv + vec2( 0.5, 0.5 ) ) % iRes, level );\n\tlet rg2 = textureLoad( map, vec2u( iuv + vec2( 1.5, 0.5 ) ) % iRes, level );\n\tlet rg3 = textureLoad( map, vec2u( iuv + vec2( 0.5, 1.5 ) ) % iRes, level );\n\tlet rg4 = textureLoad( map, vec2u( iuv + vec2( 1.5, 1.5 ) ) % iRes, level );\n\n\treturn mix( mix( rg1, rg2, f.x ), mix( rg3, rg4, f.x ), f.y );\n\n}\n")},eF={dFdx:"dpdx",dFdy:"- dpdy",mod_float:"tsl_mod_float",mod_vec2:"tsl_mod_vec2",mod_vec3:"tsl_mod_vec3",mod_vec4:"tsl_mod_vec4",equals_bool:"tsl_equals_bool",equals_bvec2:"tsl_equals_bvec2",equals_bvec3:"tsl_equals_bvec3",equals_bvec4:"tsl_equals_bvec4",inversesqrt:"inverseSqrt",bitcast:"bitcast<f32>",floatpack_snorm_2x16:"pack2x16snorm",floatpack_unorm_2x16:"pack2x16unorm",floatpack_float16_2x16:"pack2x16float",floatunpack_snorm_2x16:"unpack2x16snorm",floatunpack_unorm_2x16:"unpack2x16unorm",floatunpack_float16_2x16:"unpack2x16float"};let tF="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(tF+="diagnostic( off, derivative_uniformity );\n");class sF extends PR{constructor(e,t){super(e,t,new WL),this.uniformGroups={},this.builtins={},this.directives={},this.scopedArrays=new Map}_generateTextureSample(e,t,s,i,r,n=this.shaderStage){return"fragment"===n?i?r?`textureSample( ${t}, ${t}_sampler, ${s}, ${i}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${s}, ${i} )`:r?`textureSample( ${t}, ${t}_sampler, ${s}, ${r} )`:`textureSample( ${t}, ${t}_sampler, ${s} )`:this.generateTextureSampleLevel(e,t,s,"0",i)}generateTextureSampleLevel(e,t,s,i,r,n){return!1===this.isUnfilterable(e)?n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,n,i):this.generateTextureLod(e,t,s,r,n,i)}generateWrapFunction(e){const t=`tsl_coord_${qL[e.wrapS]}S_${qL[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let s=KL[t];if(void 0===s){const i=[],r=e.is3DTexture||e.isData3DTexture?"vec3f":"vec2f";let n=`fn ${t}( coord : ${r} ) -> ${r} {\n\n\treturn ${r}(\n`;const o=(e,t)=>{e===dn?(i.push(JL.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===pn?(i.push(JL.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===mn?(i.push(JL.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,Yo(`WebGPURenderer: Unsupported texture wrap type "${e}" for vertex shader.`))};o(e.wrapS,"x"),n+=",\n",o(e.wrapT,"y"),(e.is3DTexture||e.isData3DTexture)&&(n+=",\n",o(e.wrapR,"z")),n+="\n\t);\n\n}\n",KL[t]=s=new iN(n,i)}return s.build(this),t}generateArrayDeclaration(e,t){return`array< ${this.getType(e)}, ${t} >`}generateTextureDimension(e,t,s){const i=this.getDataFromNode(e,this.shaderStage,this.globalCache);void 0===i.dimensionsSnippet&&(i.dimensionsSnippet={});let r=i.dimensionsSnippet[s];if(void 0===i.dimensionsSnippet[s]){let n,o;const{primarySamples:a}=this.renderer.backend.utils.getTextureSampleData(e),l=a>1;o=e.is3DTexture||e.isData3DTexture?"vec3<u32>":"vec2<u32>",n=l||e.isStorageTexture?t:`${t}${s?`, u32( ${s} )`:""}`,r=new Xf(new Lg(`textureDimensions( ${n} )`,o)),i.dimensionsSnippet[s]=r,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new Xf(new Lg(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new Xf(new Lg("6u","u32")))}return r.build(this)}generateFilteredTexture(e,t,s,i,r="0u"){this._include("biquadraticTexture");const n=this.generateWrapFunction(e),o=this.generateTextureDimension(e,t,r);return i&&(s=`${s} + vec2<f32>(${i}) / ${o}`),`tsl_biquadraticTexture( ${t}, ${n}( ${s} ), ${o}, u32( ${r} ) )`}generateTextureLod(e,t,s,i,r,n="0u"){const o=this.generateWrapFunction(e),a=this.generateTextureDimension(e,t,n),l=e.is3DTexture||e.isData3DTexture?"vec3":"vec2";r&&(s=`${s} + ${l}<f32>(${r}) / ${l}<f32>( ${a} )`);const h=`${l}<u32>( ${o}( ${s} ) * ${l}<f32>( ${a} ) )`;return this.generateTextureLoad(e,t,h,n,i,null)}generateTextureLoad(e,t,s,i,r,n){let o;return null===i&&(i="0u"),n&&(s=`${s} + ${n}`),r?o=`textureLoad( ${t}, ${s}, ${r}, u32( ${i} ) )`:(o=`textureLoad( ${t}, ${s}, u32( ${i} ) )`,this.renderer.backend.compatibilityMode&&e.isDepthTexture&&(o+=".x")),o}generateTextureStore(e,t,s,i,r){let n;return n=i?`textureStore( ${t}, ${s}, ${i}, ${r} )`:`textureStore( ${t}, ${s}, ${r} )`,n}isSampleCompare(e){return!0===e.isDepthTexture&&null!==e.compareFunction}isUnfilterable(e){return"float"!==this.getComponentTypeFromTexture(e)||!this.isAvailable("float32Filterable")&&!0===e.isDataTexture&&e.type===Nn||!1===this.isSampleCompare(e)&&e.minFilter===fn&&e.magFilter===fn||this.renderer.backend.utils.getTextureSampleData(e).primarySamples>1}generateTexture(e,t,s,i,r,n=this.shaderStage){let o=null;return o=this.isUnfilterable(e)?this.generateTextureLod(e,t,s,i,r,"0",n):this._generateTextureSample(e,t,s,i,r,n),o}generateTextureGrad(e,t,s,i,r,n,o=this.shaderStage){if("fragment"===o)return n?`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]}, ${n} )`:`textureSampleGrad( ${t}, ${t}_sampler, ${s}, ${i[0]}, ${i[1]} )`;Zo(`WebGPURenderer: THREE.TextureNode.gradient() does not support ${o} shader.`)}generateTextureCompare(e,t,s,i,r,n,o=this.shaderStage){if("fragment"===o)return!0===e.isDepthTexture&&!0===e.isArrayTexture?n?`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${r}, ${i}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${r}, ${i} )`:n?`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleCompare( ${t}, ${t}_sampler, ${s}, ${i} )`;Zo(`WebGPURenderer: THREE.DepthTexture.compareFunction() does not support ${o} shader.`)}generateTextureLevel(e,t,s,i,r,n){return!1===this.isUnfilterable(e)?n?`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleLevel( ${t}, ${t}_sampler, ${s}, ${i} )`:this.isFilteredTexture(e)?this.generateFilteredTexture(e,t,s,n,i):this.generateTextureLod(e,t,s,r,n,i)}generateTextureBias(e,t,s,i,r,n,o=this.shaderStage){if("fragment"===o)return n?`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i}, ${n} )`:`textureSampleBias( ${t}, ${t}_sampler, ${s}, ${i} )`;Zo(`WebGPURenderer: THREE.TextureNode.biasNode does not support ${o} shader.`)}getPropertyName(e,t=this.shaderStage){if(!0===e.isNodeVarying&&!0===e.needsInterpolation){if("vertex"===t)return`varyings.${e.name}`}else if(!0===e.isNodeUniform){const t=e.name,s=e.type;return"texture"===s||"cubeTexture"===s||"cubeDepthTexture"===s||"storageTexture"===s||"texture3D"===s?t:"buffer"===s||"storageBuffer"===s||"indirectStorageBuffer"===s?this.isCustomStruct(e)?t:t+".value":e.groupNode.name+"."+t}return super.getPropertyName(e)}getOutputStructName(){return"output"}getFunctionOperator(e){const t=ZL[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(Yo("WebGPURenderer: Atomic operations are only supported in compute shaders."),vc.READ_WRITE):vc.READ_ONLY:e.access}getStorageAccess(e,t){return HL[this.getNodeAccess(e,t)]}getUniformFromNode(e,t,s,i=null){const r=super.getUniformFromNode(e,t,s,i),n=this.getDataFromNode(e,s,this.globalCache);if(void 0===n.uniformGPU){let o;const a=e.groupNode,l=a.name,h=this.getBindGroupArray(l,s);if("texture"===t||"cubeTexture"===t||"cubeDepthTexture"===t||"storageTexture"===t||"texture3D"===t){let i=null;const n=this.getNodeAccess(e,s);if("texture"===t||"storageTexture"===t?i=!0===e.value.is3DTexture?new $P(r.name,r.node,a,n):new GP(r.name,r.node,a,n):"cubeTexture"===t||"cubeDepthTexture"===t?i=new jP(r.name,r.node,a,n):"texture3D"===t&&(i=new $P(r.name,r.node,a,n)),i.store=!0===e.isStorageTextureNode,i.mipLevel=i.store?e.mipLevel:0,i.setVisibility(XL[s]),!1===this.isUnfilterable(e.value)&&!1===i.store){const e=new BL(`${r.name}_sampler`,r.node,a);e.setVisibility(XL[s]),h.push(e,i),o=[e,i]}else h.push(i),o=[i]}else if("buffer"===t||"storageBuffer"===t||"indirectStorageBuffer"===t){const n=this.getSharedDataFromNode(e);let l=n.buffer;if(void 0===l){l=new("buffer"===t?LP:LL)(e,a),n.buffer=l}l.setVisibility(l.getVisibility()|XL[s]),h.push(l),o=l,r.name=i||"NodeBuffer_"+r.id}else{const e=this.uniformGroups[s]||(this.uniformGroups[s]={});let i=e[l];void 0===i&&(i=new VP(l,a),i.setVisibility(XL[s]),e[l]=i,h.push(i)),o=this.getNodeUniform(r,t),i.addUniform(o)}n.uniformGPU=o}return r}getBuiltin(e,t,s,i=this.shaderStage){const r=this.builtins[i]||(this.builtins[i]=new Map);return!1===r.has(e)&&r.set(e,{name:e,property:t,type:s}),t}hasBuiltin(e,t=this.shaderStage){return void 0!==this.builtins[t]&&this.builtins[t].has(e)}getVertexIndex(){return"vertex"===this.shaderStage?this.getBuiltin("vertex_index","vertexIndex","u32","attribute"):"vertexIndex"}buildFunctionCode(e){const t=e.layout,s=this.flowShaderNode(e),i=[];for(const e of t.inputs)i.push(e.name+" : "+this.getType(e.type));let r=`fn ${t.name}( ${i.join(", ")} ) -> ${this.getType(t.type)} {\n${s.vars}\n${s.code}\n`;return s.result&&(r+=`\treturn ${s.result};\n`),r+="\n}\n",r}getInstanceIndex(){return"vertex"===this.shaderStage?this.getBuiltin("instance_index","instanceIndex","u32","attribute"):"instanceIndex"}getInvocationLocalIndex(){return this.getBuiltin("local_invocation_index","invocationLocalIndex","u32","attribute")}getSubgroupSize(){return this.enableSubGroups(),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute")}getInvocationSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_invocation_id","invocationSubgroupIndex","u32","attribute")}getSubgroupIndex(){return this.enableSubGroups(),this.getBuiltin("subgroup_id","subgroupIndex","u32","attribute")}getDrawIndex(){return null}getFrontFacing(){return this.getBuiltin("front_facing","isFront","bool")}getFragCoord(){return this.getBuiltin("position","fragCoord","vec4<f32>")+".xy"}getFragDepth(){return"output."+this.getBuiltin("frag_depth","depth","f32","output")}getClipDistance(){return"varyings.hw_clip_distances"}isFlipY(){return!1}enableDirective(e,t=this.shaderStage){(this.directives[t]||(this.directives[t]=new Set)).add(e)}getDirectives(e){const t=[],s=this.directives[e];if(void 0!==s)for(const e of s)t.push(`enable ${e};`);return t.join("\n")}enableSubGroups(){this.enableDirective("subgroups")}enableSubgroupsF16(){this.enableDirective("subgroups-f16")}enableClipDistances(){this.enableDirective("clip_distances")}enableShaderF16(){this.enableDirective("f16")}enableDualSourceBlending(){this.enableDirective("dual_source_blending")}enableHardwareClipping(e){this.enableClipDistances(),this.getBuiltin("clip_distances","hw_clip_distances",`array<f32, ${e} >`,"vertex")}getBuiltins(e){const t=[],s=this.builtins[e];if(void 0!==s)for(const{name:e,property:i,type:r}of s.values())t.push(`@builtin( ${e} ) ${i} : ${r}`);return t.join(",\n\t")}getScopedArray(e,t,s,i){return!1===this.scopedArrays.has(e)&&this.scopedArrays.set(e,{name:e,scope:t,bufferType:s,bufferCount:i}),e}getScopedArrays(e){if("compute"!==e)return;const t=[];for(const{name:e,scope:s,bufferType:i,bufferCount:r}of this.scopedArrays.values()){const n=this.getType(i);t.push(`var<${s}> ${e}: array< ${n}, ${r} >;`)}return t.join("\n")}getAttributes(e){const t=[];if("compute"===e&&(this.getBuiltin("global_invocation_id","globalId","vec3<u32>","attribute"),this.getBuiltin("workgroup_id","workgroupId","vec3<u32>","attribute"),this.getBuiltin("local_invocation_id","localId","vec3<u32>","attribute"),this.getBuiltin("num_workgroups","numWorkgroups","vec3<u32>","attribute"),this.renderer.hasFeature("subgroups")&&(this.enableDirective("subgroups",e),this.getBuiltin("subgroup_size","subgroupSize","u32","attribute"))),"vertex"===e||"compute"===e){const e=this.getBuiltins("attribute");e&&t.push(e);const s=this.getAttributesArray();for(let e=0,i=s.length;e<i;e++){const i=s[e],r=i.name,n=this.getType(i.type);t.push(`@location( ${e} ) ${r} : ${n}`)}}return t.join(",\n\t")}getStructMembers(e){const t=[];for(const s of e.members){const i=e.output?"@location( "+s.index+" ) ":"";let r=this.getType(s.type);s.atomic&&(r="atomic< "+r+" >"),t.push(`\t${i+s.name} : ${r}`)}return e.output&&t.push(`\t${this.getBuiltins("output")}`),t.join(",\n")}getStructs(e){let t="";const s=this.structs[e];if(s.length>0){const e=[];for(const t of s){let s=`struct ${t.name} {\n`;s+=this.getStructMembers(t),s+="\n};",e.push(s)}t="\n"+e.join("\n\n")+"\n"}return t}getVar(e,t,s=null){let i=`var ${t} : `;return i+=null!==s?this.generateArrayDeclaration(e,s):this.getType(e),i}getVars(e){const t=[],s=this.vars[e];if(void 0!==s)for(const e of s)t.push(`\t${this.getVar(e.type,e.name,e.count)};`);return`\n${t.join("\n")}\n`}getVaryings(e){const t=[];if("vertex"===e&&this.getBuiltin("position","Vertex","vec4<f32>","vertex"),"vertex"===e||"fragment"===e){const s=this.varyings,i=this.vars[e];for(let r=0;r<s.length;r++){const n=s[r];if(n.needsInterpolation){let e=`@location( ${r} )`;if(n.interpolationType){const t=null!==n.interpolationSampling?`, ${n.interpolationSampling} )`:" )";e+=` @interpolate( ${n.interpolationType}${t}`}else/^(int|uint|ivec|uvec)/.test(n.type)&&(e+=` @interpolate( ${this.renderer.backend.compatibilityMode?"flat, either":"flat"} )`);t.push(`${e} ${n.name} : ${this.getType(n.type)}`)}else"vertex"===e&&!1===i.includes(n)&&i.push(n)}}const s=this.getBuiltins(e);s&&t.push(s);const i=t.join(",\n\t");return"vertex"===e?this._getWGSLStruct("VaryingsStruct","\t"+i):i}isCustomStruct(e){const t=e.value,s=e.node,i=(t.isBufferAttribute||t.isInstancedBufferAttribute)&&null!==s.structTypeNode,r=s.value&&s.value.array&&"number"==typeof s.value.itemSize&&s.value.array.length>s.value.itemSize;return i&&!r}getUniforms(e){const t=this.uniforms[e],s=[],i=[],r=[],n={};for(const r of t){const t=r.groupNode.name,o=this.bindingsIndexes[t];if("texture"===r.type||"cubeTexture"===r.type||"cubeDepthTexture"===r.type||"storageTexture"===r.type||"texture3D"===r.type){const t=r.node.value;let i;!1===this.isUnfilterable(t)&&!0!==r.node.isStorageTextureNode&&(this.isSampleCompare(t)?s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${r.name}_sampler : sampler_comparison;`):s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${r.name}_sampler : sampler;`));let n="";const{primarySamples:a}=this.renderer.backend.utils.getTextureSampleData(t);if(a>1&&(n="_multisampled"),!0===t.isCubeTexture&&!0===t.isDepthTexture)i="texture_depth_cube";else if(!0===t.isCubeTexture)i="texture_cube<f32>";else if(!0===t.isDepthTexture)i=this.renderer.backend.compatibilityMode&&null===t.compareFunction?`texture${n}_2d<f32>`:`texture_depth${n}_2d${!0===t.isArrayTexture?"_array":""}`;else if(!0===r.node.isStorageTextureNode){const s=kL(t),n=this.getStorageAccess(r.node,e),o=r.node.value.is3DTexture,a=r.node.value.isArrayTexture;i=`texture_storage_${o?"3d":"2d"+(a?"_array":"")}<${s}, ${n}>`}else if(!0===t.isArrayTexture||!0===t.isDataArrayTexture||!0===t.isCompressedArrayTexture)i="texture_2d_array<f32>";else if(!0===t.is3DTexture||!0===t.isData3DTexture)i="texture_3d<f32>";else{i=`texture${n}_2d<${this.getComponentTypeFromTexture(t).charAt(0)}32>`}s.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var ${r.name} : ${i};`)}else if("buffer"===r.type||"storageBuffer"===r.type||"indirectStorageBuffer"===r.type){const t=r.node,s=this.getType(t.getNodeType(this)),n=t.bufferCount,a=n>0&&"buffer"===r.type?", "+n:"",l=t.isStorageBufferNode?`storage, ${this.getStorageAccess(t,e)}`:"uniform";if(this.isCustomStruct(r))i.push(`@binding( ${o.binding++} ) @group( ${o.group} ) var<${l}> ${r.name} : ${s};`);else{const e=`\tvalue : array< ${t.isAtomic?`atomic<${s}>`:`${s}`}${a} >`;i.push(this._getWGSLStructBinding(r.name,e,l,o.binding++,o.group))}}else{const e=this.getType(this.getVectorType(r.type)),t=r.groupNode.name;(n[t]||(n[t]={index:o.binding++,id:o.group,snippets:[]})).snippets.push(`\t${r.name} : ${e}`)}}for(const e in n){const t=n[e];r.push(this._getWGSLStructBinding(e,t.snippets.join(",\n"),"uniform",t.index,t.id))}return[...s,...i,...r].join("\n")}buildCode(){const e=null!==this.material?{fragment:{},vertex:{}}:{compute:{}};this.sortBindingGroups();for(const t in e){this.shaderStage=t;const s=e[t];s.uniforms=this.getUniforms(t),s.attributes=this.getAttributes(t),s.varyings=this.getVaryings(t),s.structs=this.getStructs(t),s.vars=this.getVars(t),s.codes=this.getCodes(t),s.directives=this.getDirectives(t),s.scopedArrays=this.getScopedArrays(t);let i="// code\n\n";i+=this.flowCode[t];const r=this.flowNodes[t],n=r[r.length-1],o=n.outputNode,a=void 0!==o&&!0===o.isOutputStructNode;for(const e of r){const r=this.getFlowData(e),l=e.name;if(l&&(i.length>0&&(i+="\n"),i+=`\t// flow -> ${l}\n`),i+=`${r.code}\n\t`,e===n&&"compute"!==t)if(i+="// result\n\n\t","vertex"===t)i+=`varyings.Vertex = ${r.result};`;else if("fragment"===t)if(a)s.returnType=o.getNodeType(this),s.structs+="var<private> output : "+s.returnType+";",i+=`return ${r.result};`;else{let e="\t@location(0) color: vec4<f32>";const t=this.getBuiltins("output");t&&(e+=",\n\t"+t),s.returnType="OutputStruct",s.structs+=this._getWGSLStruct("OutputStruct",e),s.structs+="\nvar<private> output : OutputStruct;",i+=`output.color = ${r.result};\n\n\treturn output;`}}s.flow=i}if(this.shaderStage=null,null!==this.material)this.vertexShader=this._getWGSLVertexCode(e.vertex),this.fragmentShader=this._getWGSLFragmentCode(e.fragment);else{const t=this.object.workgroupSize;this.computeShader=this._getWGSLComputeCode(e.compute,t)}}getMethod(e,t=null){let s;return null!==t&&(s=this._getWGSLMethod(e+"_"+t)),void 0===s&&(s=this._getWGSLMethod(e)),s||e}getBitcastMethod(e){return`bitcast<${this.getType(e)}>`}getFloatPackingMethod(e){return this.getMethod(`floatpack_${e}_2x16`)}getFloatUnpackingMethod(e){return this.getMethod(`floatunpack_${e}_2x16`)}getTernary(e,t,s){return`select( ${s}, ${t}, ${e} )`}getType(e){return QL[e]||e}isAvailable(e){let t=YL[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),YL[e]=t),t}_getWGSLMethod(e){return void 0!==JL[e]&&this._include(e),eF[e]}_include(e){const t=JL[e];return t.build(this),this.addInclude(t),t}_getWGSLVertexCode(e){return`${this.getSignature()}\n// directives\n${e.directives}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// varyings\n${e.varyings}\nvar<private> varyings : VaryingsStruct;\n\n// codes\n${e.codes}\n\n@vertex\nfn main( ${e.attributes} ) -> VaryingsStruct {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n\treturn varyings;\n\n}\n`}_getWGSLFragmentCode(e){return`${this.getSignature()}\n// global\n${tF}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@fragment\nfn main( ${e.varyings} ) -> ${e.returnType} {\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLComputeCode(e,t){const[s,i,r]=t;return`${this.getSignature()}\n// directives\n${e.directives}\n\n// system\nvar<private> instanceIndex : u32;\n\n// locals\n${e.scopedArrays}\n\n// structs\n${e.structs}\n\n// uniforms\n${e.uniforms}\n\n// codes\n${e.codes}\n\n@compute @workgroup_size( ${s}, ${i}, ${r} )\nfn main( ${e.attributes} ) {\n\n\t// system\n\tinstanceIndex = globalId.x\n\t\t+ globalId.y * ( ${s} * numWorkgroups.x )\n\t\t+ globalId.z * ( ${s} * numWorkgroups.x ) * ( ${i} * numWorkgroups.y );\n\n\t// vars\n\t${e.vars}\n\n\t// flow\n\t${e.flow}\n\n}\n`}_getWGSLStruct(e,t){return`\nstruct ${e} {\n${t}\n};`}_getWGSLStructBinding(e,t,s,i=0,r=0){const n=e+"Struct";return`${this._getWGSLStruct(n,t)}\n@binding( ${i} ) @group( ${r} )\nvar<${s}> ${e} : ${n};`}}class iF{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=CI:e.depth&&(t=EI),t}getTextureFormatGPU(e){return this.backend.get(e).format}getTextureSampleData(e){let t;if(e.isFramebufferTexture)t=1;else if(e.isDepthTexture&&!e.renderTarget){const e=this.backend.renderer,s=e.getRenderTarget();t=s?s.samples:e.currentSamples}else e.renderTarget&&(t=e.renderTarget.samples);t=t||1;const s=t>1&&null!==e.renderTarget&&!0!==e.isDepthTexture&&!0!==e.isFramebufferTexture;return{samples:t,primarySamples:s?1:t,isMSAA:s}}getCurrentColorFormat(e){let t;return t=null!==e.textures?this.getTextureFormatGPU(e.textures[0]):this.getPreferredCanvasFormat(),t}getCurrentColorFormats(e){return null!==e.textures?e.textures.map(e=>this.getTextureFormatGPU(e)):[this.getPreferredCanvasFormat()]}getCurrentColorSpace(e){return null!==e.textures?e.textures[0].colorSpace:this.backend.renderer.outputColorSpace}getPrimitiveTopology(e,t){return e.isPoints?vB:e.isLineSegments||e.isMesh&&!0===t.wireframe?TB:e.isLine?SB:e.isMesh?MB:void 0}getSampleCount(e){return e>=4?4:1}getSampleCountRenderContext(e){return null!==e.textures?this.getSampleCount(e.sampleCount):this.getSampleCount(this.backend.renderer.currentSamples)}getPreferredCanvasFormat(){const e=this.backend.parameters.outputType;if(void 0===e)return navigator.gpu.getPreferredCanvasFormat();if(e===wn)return pI;if(e===En)return TI;throw new Error("Unsupported output buffer type.")}}const rF=new Map([[Int8Array,["sint8","snorm8"]],[Uint8Array,["uint8","unorm8"]],[Int16Array,["sint16","snorm16"]],[Uint16Array,["uint16","unorm16"]],[Int32Array,["sint32","snorm32"]],[Uint32Array,["uint32","unorm32"]],[Float32Array,["float32"]]]);"undefined"!=typeof Float16Array&&rF.set(Float16Array,["float16"]);const nF=new Map([[fh,["float16"]]]),oF=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class aF{constructor(e){this.backend=e}createAttribute(e,t){const s=this._getBufferAttribute(e),i=this.backend,r=i.get(s);let n=r.buffer;if(void 0===n){const o=i.device;let a=s.array;if(!1===e.normalized)if(a.constructor===Int16Array||a.constructor===Int8Array)a=new Int32Array(a);else if((a.constructor===Uint16Array||a.constructor===Uint8Array)&&(a=new Uint32Array(a),t&GPUBufferUsage.INDEX))for(let e=0;e<a.length;e++)65535===a[e]&&(a[e]=4294967295);if(s.array=a,(s.isStorageBufferAttribute||s.isStorageInstancedBufferAttribute)&&3===s.itemSize){a=new a.constructor(4*s.count);for(let e=0;e<s.count;e++)a.set(s.array.subarray(3*e,3*e+3),4*e);s.itemSize=4,s.array=a,r._force3to4BytesAlignment=!0}const l=a.byteLength,h=l+(4-l%4)%4;n=o.createBuffer({label:s.name,size:h,usage:t,mappedAtCreation:!0}),new a.constructor(n.getMappedRange()).set(a),n.unmap(),r.buffer=n}}updateAttribute(e){const t=this._getBufferAttribute(e),s=this.backend,i=s.device,r=s.get(t),n=s.get(t).buffer;let o=t.array;if(!0===r._force3to4BytesAlignment){o=new o.constructor(4*t.count);for(let e=0;e<t.count;e++)o.set(t.array.subarray(3*e,3*e+3),4*e);t.array=o}const a=t.updateRanges;if(0===a.length)i.queue.writeBuffer(n,0,o,0);else{const e=Wo(o),s=e?1:o.BYTES_PER_ELEMENT;for(let t=0,l=a.length;t<l;t++){const l=a[t];let h,u;if(!0===r._force3to4BytesAlignment){h=4*Math.floor(l.start/3)*s,u=4*Math.ceil(l.count/3)*s}else h=l.start*s,u=l.count*s;const c=h*(e?o.BYTES_PER_ELEMENT:1);i.queue.writeBuffer(n,c,o,h,u)}t.clearUpdateRanges()}}createShaderVertexBuffers(e){const t=e.getAttributes(),s=new Map;for(let e=0;e<t.length;e++){const i=t[e],r=i.array.BYTES_PER_ELEMENT,n=this._getBufferAttribute(i);let o=s.get(n);if(void 0===o){let e,t;!0===i.isInterleavedBufferAttribute?(e=i.data.stride*r,t=i.data.isInstancedInterleavedBuffer?CL:EL):(e=i.itemSize*r,t=i.isInstancedBufferAttribute?CL:EL),!1!==i.normalized||i.array.constructor!==Int16Array&&i.array.constructor!==Uint16Array||(e=4),o={arrayStride:e,attributes:[],stepMode:t},s.set(n,o)}const a=this._getVertexFormat(i),l=!0===i.isInterleavedBufferAttribute?i.offset*r:0;o.attributes.push({shaderLocation:e,offset:l,format:a})}return Array.from(s.values())}destroyAttribute(e){const t=this.backend;t.get(this._getBufferAttribute(e)).buffer.destroy(),t.delete(e)}async getArrayBufferAsync(e){const t=this.backend,s=t.device,i=t.get(this._getBufferAttribute(e)).buffer,r=i.size,n=s.createBuffer({label:`${e.name}_readback`,size:r,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ}),o=s.createCommandEncoder({label:`readback_encoder_${e.name}`});o.copyBufferToBuffer(i,0,n,0,r);const a=o.finish();s.queue.submit([a]),await n.mapAsync(GPUMapMode.READ);const l=n.getMappedRange(),h=new e.array.constructor(l.slice(0));return n.unmap(),h.buffer}_getVertexFormat(e){const{itemSize:t,normalized:s}=e,i=e.array.constructor,r=e.constructor;let n;if(1===t)n=oF.get(i);else{const e=(nF.get(r)||rF.get(i))[s?1:0];if(e){const s=i.BYTES_PER_ELEMENT*t,r=4*Math.floor((s+3)/4)/i.BYTES_PER_ELEMENT;if(r%1)throw new Error("THREE.WebGPUAttributeUtils: Bad vertex format item size.");n=`${e}x${r}`}}return n||Zo("WebGPUAttributeUtils: Vertex format not supported yet."),n}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class lF{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class hF{constructor(e){this.backend=e,this._bindGroupLayoutCache=new Map}createBindingsLayout(e){const t=this.backend,s=t.device,i=t.get(e);if(i.layout)return i.layout.layoutGPU;const r=this._createLayoutEntries(e),n=JSON.stringify(r);let o=this._bindGroupLayoutCache.get(n);return void 0===o&&(o=new lF(s.createBindGroupLayout({entries:r})),this._bindGroupLayoutCache.set(n,o)),o.usedTimes++,i.layout=o,i.layoutKey=n,o.layoutGPU}createBindings(e,t,s,i=0){const{backend:r}=this,n=r.get(e),o=this.createBindingsLayout(e);let a;s>0&&(void 0===n.groups&&(n.groups=[],n.versions=[]),n.versions[s]===i&&(a=n.groups[s])),void 0===a&&(a=this.createBindGroup(e,o),s>0&&(n.groups[s]=a,n.versions[s]=i)),n.group=a}updateBinding(e){const t=this.backend,s=t.device,i=e.buffer,r=t.get(e).buffer,n=e.updateRanges;if(0===n.length)s.queue.writeBuffer(r,0,i,0);else{const t=Wo(i),o=t?1:i.BYTES_PER_ELEMENT;for(let e=0,a=n.length;e<a;e++){const a=n[e],l=a.start*o,h=a.count*o,u=l*(t?i.BYTES_PER_ELEMENT:1);s.queue.writeBuffer(r,u,i,l,h)}e.clearUpdateRanges()}}createBindGroupIndex(e,t){const s=this.backend.device,i=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,r=e[0],n=s.createBuffer({label:"bindingCameraIndex_"+r,size:16,usage:i});s.queue.writeBuffer(n,0,e,0);const o=[{binding:0,resource:{buffer:n}}];return s.createBindGroup({label:"bindGroupCameraIndex_"+r,layout:t,entries:o})}createBindGroup(e,t){const s=this.backend,i=s.device;let r=0;const n=[];for(const t of e.bindings){if(t.isUniformBuffer){const e=s.get(t);if(void 0===e.buffer){const s=t.byteLength,r=GPUBufferUsage.UNIFORM|GPUBufferUsage.COPY_DST,n=[];t.visibility&NB.VERTEX&&n.push("vertex"),t.visibility&NB.FRAGMENT&&n.push("fragment"),t.visibility&NB.COMPUTE&&n.push("compute");const o=`(${n.join(",")})`,a=i.createBuffer({label:`bindingBuffer${t.id}_${t.name}_${o}`,size:s,usage:r});e.buffer=a}n.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isStorageBuffer){const e=s.get(t);if(void 0===e.buffer){const i=t.attribute;e.buffer=s.get(i).buffer}n.push({binding:r,resource:{buffer:e.buffer}})}else if(t.isSampledTexture){const e=s.get(t.texture);let o;if(void 0!==e.externalTexture)o=i.importExternalTexture({source:e.externalTexture});else{const s=t.store?1:e.texture.mipLevelCount,i=t.store?t.mipLevel:0;let r=`view-${e.texture.width}-${e.texture.height}`;if(e.texture.depthOrArrayLayers>1&&(r+=`-${e.texture.depthOrArrayLayers}`),r+=`-${s}-${i}`,o=e[r],void 0===o){const n=NL;let a;a=t.isSampledCubeTexture?ML:t.isSampledTexture3D?AL:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?SL:TL,o=e[r]=e.texture.createView({aspect:n,dimension:a,mipLevelCount:s,baseMipLevel:i})}}n.push({binding:r,resource:o})}else if(t.isSampler){const e=s.get(t.texture);n.push({binding:r,resource:e.sampler})}r++}return i.createBindGroup({label:"bindGroup_"+e.name,layout:t,entries:n})}_createLayoutEntries(e){const t=[];let s=0;for(const i of e.bindings){const e=this.backend,r={binding:s,visibility:i.visibility};if(i.isUniformBuffer||i.isStorageBuffer){const e={};i.isStorageBuffer&&(i.visibility&NB.COMPUTE&&(i.access===vc.READ_WRITE||i.access===vc.WRITE_ONLY)?e.type=hL:e.type=uL),r.buffer=e}else if(i.isSampledTexture&&i.store){const e={};e.format=this.backend.get(i.texture).texture.format;const t=i.access;e.access=t===vc.READ_WRITE?pL:t===vc.WRITE_ONLY?cL:dL,i.texture.isArrayTexture?e.viewDimension=SL:i.texture.is3DTexture&&(e.viewDimension=AL),r.storageTexture=e}else if(i.isSampledTexture){const t={},{primarySamples:s}=e.utils.getTextureSampleData(i.texture);if(s>1&&(t.multisampled=!0,i.texture.isDepthTexture||(t.sampleType=yL)),i.texture.isDepthTexture)e.compatibilityMode&&null===i.texture.compareFunction?t.sampleType=yL:t.sampleType=xL;else if(i.texture.isDataTexture||i.texture.isDataArrayTexture||i.texture.isData3DTexture){const e=i.texture.type;e===Mn?t.sampleType=bL:e===An?t.sampleType=_L:e===Nn&&(this.backend.hasFeature("float32-filterable")?t.sampleType=gL:t.sampleType=yL)}i.isSampledCubeTexture?t.viewDimension=ML:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?t.viewDimension=SL:i.isSampledTexture3D&&(t.viewDimension=AL),r.texture=t}else if(i.isSampler){const t={};i.texture.isDepthTexture&&(null!==i.texture.compareFunction?t.type=fL:e.compatibilityMode&&(t.type=mL)),r.sampler=t}else Zo(`WebGPUBindingUtils: Unsupported binding "${i}".`);t.push(r),s++}return t}deleteBindGroupData(e){const{backend:t}=this,s=t.get(e);s.layout&&(s.layout.usedTimes--,0===s.layout.usedTimes&&this._bindGroupLayoutCache.delete(s.layoutKey),s.layout=void 0,s.layoutKey=void 0)}dispose(){this._bindGroupLayoutCache.clear()}}class uF{constructor(e){this.backend=e,this._activePipelines=new WeakMap}setPipeline(e,t){this._activePipelines.get(e)!==t&&(e.setPipeline(t),this._activePipelines.set(e,t))}_getSampleCount(e){return this.backend.utils.getSampleCountRenderContext(e)}createRenderPipeline(e,t){const{object:s,material:i,geometry:r,pipeline:n}=e,{vertexProgram:o,fragmentProgram:a}=n,l=this.backend,h=l.device,u=l.utils,c=l.get(n),d=[];for(const t of e.getBindings()){const e=l.get(t),{layoutGPU:s}=e.layout;d.push(s)}const p=l.attributeUtils.createShaderVertexBuffers(e);let m;0===i.blending||1===i.blending&&!1===i.transparent||(m=this._getBlending(i));let f={};!0===i.stencilWrite&&(f={compare:this._getStencilCompare(i),failOp:this._getStencilOperation(i.stencilFail),depthFailOp:this._getStencilOperation(i.stencilZFail),passOp:this._getStencilOperation(i.stencilZPass)});const g=this._getColorWriteMask(i),y=[];if(null!==e.context.textures){const t=e.context.textures;for(let e=0;e<t.length;e++){const s=u.getTextureFormatGPU(t[e]);0===e?y.push({format:s,blend:m,writeMask:g}):y.push({format:s,writeMask:g})}}else{const t=u.getCurrentColorFormat(e.context);y.push({format:t,blend:m,writeMask:g})}const x=l.get(o).module,b=l.get(a).module,_=this._getPrimitiveState(s,r,i),w=this._getDepthCompare(i),v=u.getCurrentDepthStencilFormat(e.context),T=this._getSampleCount(e.context),S={label:`renderPipeline_${i.name||i.type}_${i.id}`,vertex:Object.assign({},x,{buffers:p}),fragment:Object.assign({},b,{targets:y}),primitive:_,multisample:{count:T,alphaToCoverageEnabled:i.alphaToCoverage&&T>1},layout:h.createPipelineLayout({bindGroupLayouts:d})},M={},A=e.context.depth,N=e.context.stencil;if(!0!==A&&!0!==N||(!0===A&&(M.format=v,M.depthWriteEnabled=i.depthWrite,M.depthCompare=w),!0===N&&(M.stencilFront=f,M.stencilBack={},M.stencilReadMask=i.stencilFuncMask,M.stencilWriteMask=i.stencilWriteMask),!0===i.polygonOffset&&(M.depthBias=i.polygonOffsetUnits,M.depthBiasSlopeScale=i.polygonOffsetFactor,M.depthBiasClamp=0),S.depthStencil=M),h.pushErrorScope("validation"),null===t)c.pipeline=h.createRenderPipeline(S),h.popErrorScope().then(e=>{null!==e&&(c.error=!0,Zo(e.message))});else{const e=new Promise(async e=>{try{c.pipeline=await h.createRenderPipelineAsync(S)}catch(e){}const t=await h.popErrorScope();null!==t&&(c.error=!0,Zo(t.message)),e()});t.push(e)}}createBundleEncoder(e,t="renderBundleEncoder"){const s=this.backend,{utils:i,device:r}=s,n=i.getCurrentDepthStencilFormat(e),o={label:t,colorFormats:i.getCurrentColorFormats(e),depthStencilFormat:n,sampleCount:this._getSampleCount(e)};return r.createRenderBundleEncoder(o)}createComputePipeline(e,t){const s=this.backend,i=s.device,r=s.get(e.computeProgram).module,n=s.get(e),o=[];for(const e of t){const t=s.get(e),{layoutGPU:i}=t.layout;o.push(i)}n.pipeline=i.createComputePipeline({compute:r,layout:i.createPipelineLayout({bindGroupLayouts:o})})}_getBlending(e){let t,s;const i=e.blending,r=e.blendSrc,n=e.blendDst,o=e.blendEquation;if(5===i){const i=null!==e.blendSrcAlpha?e.blendSrcAlpha:r,a=null!==e.blendDstAlpha?e.blendDstAlpha:n,l=null!==e.blendEquationAlpha?e.blendEquationAlpha:o;t={srcFactor:this._getBlendFactor(r),dstFactor:this._getBlendFactor(n),operation:this._getBlendOperation(o)},s={srcFactor:this._getBlendFactor(i),dstFactor:this._getBlendFactor(a),operation:this._getBlendOperation(l)}}else{const r=(e,i,r,n)=>{t={srcFactor:e,dstFactor:i,operation:XD},s={srcFactor:r,dstFactor:n,operation:XD}};if(e.premultipliedAlpha)switch(i){case 1:r(FD,kD,FD,kD);break;case 2:r(FD,FD,FD,FD);break;case 3:r(LD,VD,LD,FD);break;case 4:r(UD,kD,LD,FD)}else switch(i){case 1:r(zD,kD,FD,kD);break;case 2:r(zD,FD,FD,FD);break;case 3:Zo("WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:Zo("WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true")}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s};Zo("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case Kr:t=LD;break;case 201:t=FD;break;case 202:t=OD;break;case 203:t=VD;break;case sn:t=zD;break;case rn:t=kD;break;case 208:t=UD;break;case 209:t=GD;break;case 206:t=jD;break;case 207:t=$D;break;case 210:t=WD;break;case 211:t=HD;break;case 212:t=qD;break;default:Zo("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case 512:t=EB;break;case 519:t=LB;break;case 513:t=CB;break;case 515:t=PB;break;case 514:t=RB;break;case 518:t=DB;break;case 516:t=BB;break;case 517:t=IB;break;default:Zo("WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case Co:t=tL;break;case 0:t=sL;break;case 7681:t=iL;break;case 5386:t=rL;break;case 7682:t=nL;break;case 7683:t=oL;break;case 34055:t=aL;break;case 34056:t=lL;break;default:Zo("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case Yr:t=XD;break;case 101:t=YD;break;case 102:t=ZD;break;case 103:t=QD;break;case 104:t=KD;break;default:Zo("WebGPUPipelineUtils: Blend equation not supported.",e)}return t}_getPrimitiveState(e,t,s){const i={},r=this.backend.utils;i.topology=r.getPrimitiveTopology(e,s),null!==t.index&&!0===e.isLine&&!0!==e.isLineSegments&&(i.stripIndexFormat=t.index.array instanceof Uint16Array?jB:$B);let n=1===s.side;return e.isMesh&&e.matrixWorld.determinant()<0&&(n=!n),i.frontFace=!0===n?kB:zB,i.cullMode=2===s.side?UB:GB,i}_getColorWriteMask(e){return!0===e.colorWrite?eL:JD}_getDepthCompare(e){let t;if(!1===e.depthTest)t=LB;else{const s=e.depthFunc;switch(s){case 0:t=EB;break;case 1:t=LB;break;case 2:t=CB;break;case 3:t=PB;break;case 4:t=RB;break;case 5:t=DB;break;case 6:t=BB;break;case 7:t=IB;break;default:Zo("WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class cF extends bB{constructor(e,t,s=2048){super(s),this.device=e,this.type=t,this.querySet=this.device.createQuerySet({type:"timestamp",count:this.maxQueries,label:`queryset_global_timestamp_${t}`});const i=8*this.maxQueries;this.resolveBuffer=this.device.createBuffer({label:`buffer_timestamp_resolve_${t}`,size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.resultBuffer=this.device.createBuffer({label:`buffer_timestamp_result_${t}`,size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ})}allocateQueriesForContext(e){if(!this.trackTimestamp||this.isDisposed)return null;if(this.currentQueryIndex+2>this.maxQueries)return Qo(`WebGPUTimestampQueryPool [${this.type}]: Maximum number of queries exceeded, when using trackTimestamp it is necessary to resolves the queries via renderer.resolveTimestampsAsync( THREE.TimestampQuery.${this.type.toUpperCase()} ).`),null;const t=this.currentQueryIndex;return this.currentQueryIndex+=2,this.queryOffsets.set(e,t),t}async resolveQueriesAsync(){if(!this.trackTimestamp||0===this.currentQueryIndex||this.isDisposed)return this.lastValue;if(this.pendingResolve)return this.pendingResolve;this.pendingResolve=this._resolveQueries();try{return await this.pendingResolve}finally{this.pendingResolve=null}}async _resolveQueries(){if(this.isDisposed)return this.lastValue;try{if("unmapped"!==this.resultBuffer.mapState)return this.lastValue;const e=new Map(this.queryOffsets),t=this.currentQueryIndex,s=8*t;this.currentQueryIndex=0,this.queryOffsets.clear();const i=this.device.createCommandEncoder();i.resolveQuerySet(this.querySet,0,t,this.resolveBuffer,0),i.copyBufferToBuffer(this.resolveBuffer,0,this.resultBuffer,0,s);const r=i.finish();if(this.device.queue.submit([r]),"unmapped"!==this.resultBuffer.mapState)return this.lastValue;if(await this.resultBuffer.mapAsync(GPUMapMode.READ,0,s),this.isDisposed)return"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue;const n=new BigUint64Array(this.resultBuffer.getMappedRange(0,s)),o={},a=[];for(const[t,s]of e){const e=t.match(/^(.*):f(\d+)$/),i=parseInt(e[2]);!1===a.includes(i)&&a.push(i),void 0===o[i]&&(o[i]=0);const r=n[s],l=n[s+1],h=Number(l-r)/1e6;this.timestamps.set(t,h),o[i]+=h}const l=o[a[a.length-1]];return this.resultBuffer.unmap(),this.lastValue=l,this.frames=a,l}catch(e){return Zo("Error resolving queries:",e),"mapped"===this.resultBuffer.mapState&&this.resultBuffer.unmap(),this.lastValue}}async dispose(){if(!this.isDisposed){if(this.isDisposed=!0,this.pendingResolve)try{await this.pendingResolve}catch(e){Zo("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){Zo("Error unmapping buffer:",e)}this.querySet&&(this.querySet.destroy(),this.querySet=null),this.resolveBuffer&&(this.resolveBuffer.destroy(),this.resolveBuffer=null),this.resultBuffer&&(this.resultBuffer.destroy(),this.resultBuffer=null),this.queryOffsets.clear(),this.pendingResolve=null}}}class dF extends tB{constructor(e={}){super(e),this.isWebGPUBackend=!0,this.parameters.alpha=void 0===e.alpha||e.alpha,this.parameters.compatibilityMode=void 0!==e.compatibilityMode&&e.compatibilityMode,this.parameters.requiredLimits=void 0===e.requiredLimits?{}:e.requiredLimits,this.compatibilityMode=this.parameters.compatibilityMode,this.device=null,this.defaultRenderPassdescriptor=null,this.utils=new iF(this),this.attributeUtils=new aF(this),this.bindingUtils=new hF(this),this.pipelineUtils=new uF(this),this.textureUtils=new zL(this),this.occludedResolveCache=new Map}async init(e){await super.init(e);const t=this.parameters;let s;if(void 0===t.device){const e={powerPreference:t.powerPreference,featureLevel:t.compatibilityMode?"compatibility":void 0},i="undefined"!=typeof navigator?await navigator.gpu.requestAdapter(e):null;if(null===i)throw new Error("WebGPUBackend: Unable to create WebGPU adapter.");const r=Object.values(RL),n=[];for(const e of r)i.features.has(e)&&n.push(e);const o={requiredFeatures:n,requiredLimits:t.requiredLimits};s=await i.requestDevice(o)}else s=t.device;s.lost.then(t=>{if("destroyed"===t.reason)return;const s={api:"WebGPU",message:t.message||"Unknown reason",reason:t.reason||null,originalEvent:t};e.onDeviceLost(s)}),this.device=s,this.trackTimestamp=this.trackTimestamp&&this.hasFeature(RL.TimestampQuery),this.updateSize()}get context(){const e=this.renderer.getCanvasTarget(),t=this.get(e);let s=t.context;if(void 0===s){const i=this.parameters;s=!0===e.isDefaultCanvasTarget&&void 0!==i.context?i.context:e.domElement.getContext("webgpu"),"setAttribute"in e.domElement&&e.domElement.setAttribute("data-engine",`three.js r${Xr} webgpu`);const r=i.alpha?"premultiplied":"opaque",n=i.outputType===En?"extended":"standard";s.configure({device:this.device,format:this.utils.getPreferredCanvasFormat(),usage:GPUTextureUsage.RENDER_ATTACHMENT|GPUTextureUsage.COPY_SRC,alphaMode:r,toneMapping:{mode:n}}),t.context=s}return s}get coordinateSystem(){return Uo}async getArrayBufferAsync(e){return await this.attributeUtils.getArrayBufferAsync(e)}getContext(){return this.context}_getDefaultRenderPassDescriptor(){const e=this.renderer,t=e.getCanvasTarget(),s=this.get(t),i=e.currentSamples;let r=s.descriptor;if(void 0===r||s.samples!==i){r={colorAttachments:[{view:null}]},!0!==e.depth&&!0!==e.stencil||(r.depthStencilAttachment={view:this.textureUtils.getDepthBuffer(e.depth,e.stencil).createView()});const t=r.colorAttachments[0];i>0?t.view=this.textureUtils.getColorBuffer().createView():t.resolveTarget=void 0,s.descriptor=r,s.samples=i}const n=r.colorAttachments[0];return i>0?n.resolveTarget=this.context.getCurrentTexture().createView():n.view=this.context.getCurrentTexture().createView(),r}_isRenderCameraDepthArray(e){return e.depthTexture&&e.depthTexture.image.depth>1&&e.camera.isArrayCamera}_getRenderPassDescriptor(e,t={}){const s=e.renderTarget,i=this.get(s);let r=i.descriptors;void 0!==r&&i.width===s.width&&i.height===s.height&&i.samples===s.samples||(r={},i.descriptors=r);const n=e.getCacheKey();let o=r[n];if(void 0===o){const t=e.textures,a=[];let l;const h=this._isRenderCameraDepthArray(e);for(let i=0;i<t.length;i++){const r=this.get(t[i]),n={label:`colorAttachment_${i}`,baseMipLevel:e.activeMipmapLevel,mipLevelCount:1,baseArrayLayer:e.activeCubeFace,arrayLayerCount:1,dimension:TL};if(s.isRenderTarget3D)l=e.activeCubeFace,n.baseArrayLayer=0,n.dimension=AL,n.depthOrArrayLayers=t[i].image.depth;else if(s.isRenderTarget&&t[i].image.depth>1)if(!0===h){const t=e.camera.cameras;for(let e=0;e<t.length;e++){const t={...n,baseArrayLayer:e,arrayLayerCount:1,dimension:TL},s=r.texture.createView(t);a.push({view:s,resolveTarget:void 0,depthSlice:void 0})}}else n.dimension=SL,n.depthOrArrayLayers=t[i].image.depth;if(!0!==h){const e=r.texture.createView(n);let t,s;void 0!==r.msaaTexture?(t=r.msaaTexture.createView(),s=e):(t=e,s=void 0),a.push({view:t,resolveTarget:s,depthSlice:l})}}if(o={textureViews:a},e.depth){const t=this.get(e.depthTexture),s={};(e.depthTexture.isArrayTexture||e.depthTexture.isCubeTexture)&&(s.dimension=TL,s.arrayLayerCount=1,s.baseArrayLayer=e.activeCubeFace),o.depthStencilView=t.texture.createView(s)}r[n]=o,i.width=s.width,i.height=s.height,i.samples=s.samples,i.activeMipmapLevel=e.activeMipmapLevel,i.activeCubeFace=e.activeCubeFace}const a={colorAttachments:[]};for(let e=0;e<o.textureViews.length;e++){const s=o.textureViews[e];let i={r:0,g:0,b:0,a:1};0===e&&t.clearValue&&(i=t.clearValue),a.colorAttachments.push({view:s.view,depthSlice:s.depthSlice,resolveTarget:s.resolveTarget,loadOp:t.loadOp||OB,storeOp:t.storeOp||FB,clearValue:i})}return o.depthStencilView&&(a.depthStencilAttachment={view:o.depthStencilView}),a}beginRender(e){const t=this.get(e),s=this.device,i=e.occlusionQueryCount;let r,n;i>0&&(t.currentOcclusionQuerySet&&t.currentOcclusionQuerySet.destroy(),t.currentOcclusionQueryBuffer&&t.currentOcclusionQueryBuffer.destroy(),t.currentOcclusionQuerySet=t.occlusionQuerySet,t.currentOcclusionQueryBuffer=t.occlusionQueryBuffer,t.currentOcclusionQueryObjects=t.occlusionQueryObjects,r=s.createQuerySet({type:"occlusion",count:i,label:`occlusionQuerySet_${e.id}`}),t.occlusionQuerySet=r,t.occlusionQueryIndex=0,t.occlusionQueryObjects=new Array(i),t.lastOcclusionObject=null),n=null===e.textures?this._getDefaultRenderPassDescriptor():this._getRenderPassDescriptor(e,{loadOp:OB}),this.initTimestampQuery(jo,this.getTimestampUID(e),n),n.occlusionQuerySet=r;const o=n.depthStencilAttachment;if(null!==e.textures){const t=n.colorAttachments;for(let s=0;s<t.length;s++){const i=t[s];e.clearColor?(i.clearValue=0===s?e.clearColorValue:{r:0,g:0,b:0,a:1},i.loadOp=VB):i.loadOp=OB,i.storeOp=FB}}else{const t=n.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=VB):t.loadOp=OB,t.storeOp=FB}e.depth&&(e.clearDepth?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=VB):o.depthLoadOp=OB,o.depthStoreOp=FB),e.stencil&&(e.clearStencil?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=VB):o.stencilLoadOp=OB,o.stencilStoreOp=FB);const a=s.createCommandEncoder({label:"renderContext_"+e.id});if(!0===this._isRenderCameraDepthArray(e)){const s=e.camera.cameras;t.layerDescriptors&&t.layerDescriptors.length===s.length?this._updateDepthLayerDescriptors(e,t,s):this._createDepthLayerDescriptors(e,t,n,s),t.bundleEncoders=[],t.bundleSets=[];for(let i=0;i<s.length;i++){const s=this.pipelineUtils.createBundleEncoder(e,"renderBundleArrayCamera_"+i),r={attributes:{},bindingGroups:[],pipeline:null,index:null};t.bundleEncoders.push(s),t.bundleSets.push(r)}t.currentPass=null}else{const s=a.beginRenderPass(n);t.currentPass=s,e.viewport&&this.updateViewport(e),e.scissor&&this.updateScissor(e)}t.descriptor=n,t.encoder=a,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.renderBundles=[]}_createDepthLayerDescriptors(e,t,s,i){const r=s.depthStencilAttachment;t.layerDescriptors=[];const n=this.get(e.depthTexture);n.viewCache||(n.viewCache=[]);for(let o=0;o<i.length;o++){const i={...s,colorAttachments:[{...s.colorAttachments[0],view:s.colorAttachments[o].view}]};if(s.depthStencilAttachment){const t=o;n.viewCache[t]||(n.viewCache[t]=n.texture.createView({dimension:TL,baseArrayLayer:o,arrayLayerCount:1})),i.depthStencilAttachment={view:n.viewCache[t],depthLoadOp:r.depthLoadOp||VB,depthStoreOp:r.depthStoreOp||FB,depthClearValue:r.depthClearValue||1},e.stencil&&(i.depthStencilAttachment.stencilLoadOp=r.stencilLoadOp,i.depthStencilAttachment.stencilStoreOp=r.stencilStoreOp,i.depthStencilAttachment.stencilClearValue=r.stencilClearValue)}else i.depthStencilAttachment={...r};t.layerDescriptors.push(i)}}_updateDepthLayerDescriptors(e,t,s){for(let i=0;i<s.length;i++){const s=t.layerDescriptors[i];if(s.depthStencilAttachment){const t=s.depthStencilAttachment;e.depth&&(e.clearDepth?(t.depthClearValue=e.clearDepthValue,t.depthLoadOp=VB):t.depthLoadOp=OB),e.stencil&&(e.clearStencil?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=VB):t.stencilLoadOp=OB)}}}finishRender(e){const t=this.get(e),s=e.occlusionQueryCount;t.renderBundles.length>0&&t.currentPass.executeBundles(t.renderBundles),s>t.occlusionQueryIndex&&t.currentPass.endOcclusionQuery();const i=t.encoder;if(!0===this._isRenderCameraDepthArray(e)){const s=[];for(let e=0;e<t.bundleEncoders.length;e++){const i=t.bundleEncoders[e];s.push(i.finish())}for(let r=0;r<t.layerDescriptors.length;r++)if(r<s.length){const n=t.layerDescriptors[r],o=i.beginRenderPass(n);if(e.viewport){const{x:t,y:s,width:i,height:r,minDepth:n,maxDepth:a}=e.viewportValue;o.setViewport(t,s,i,r,n,a)}if(e.scissor){const{x:t,y:s,width:i,height:r}=e.scissorValue;o.setScissorRect(t,s,i,r)}o.executeBundles([s[r]]),o.end()}}else t.currentPass&&t.currentPass.end();if(s>0){const i=8*s;let r=this.occludedResolveCache.get(i);void 0===r&&(r=this.device.createBuffer({size:i,usage:GPUBufferUsage.QUERY_RESOLVE|GPUBufferUsage.COPY_SRC}),this.occludedResolveCache.set(i,r));const n=this.device.createBuffer({size:i,usage:GPUBufferUsage.COPY_DST|GPUBufferUsage.MAP_READ});t.encoder.resolveQuerySet(t.occlusionQuerySet,0,s,r,0),t.encoder.copyBufferToBuffer(r,0,n,0,i),t.occlusionQueryBuffer=n,this.resolveOccludedAsync(e)}if(this.device.queue.submit([t.encoder.finish()]),null!==e.textures){const t=e.textures;for(let e=0;e<t.length;e++){const s=t[e];!0===s.generateMipmaps&&this.textureUtils.generateMipmaps(s)}}}isOccluded(e,t){const s=this.get(e);return s.occluded&&s.occluded.has(t)}async resolveOccludedAsync(e){const t=this.get(e),{currentOcclusionQueryBuffer:s,currentOcclusionQueryObjects:i}=t;if(s&&i){const e=new WeakSet;t.currentOcclusionQueryObjects=null,t.currentOcclusionQueryBuffer=null,await s.mapAsync(GPUMapMode.READ);const r=s.getMappedRange(),n=new BigUint64Array(r);for(let t=0;t<i.length;t++)n[t]===BigInt(0)&&e.add(i[t]);s.destroy(),t.occluded=e}}updateViewport(e){const{currentPass:t}=this.get(e),{x:s,y:i,width:r,height:n,minDepth:o,maxDepth:a}=e.viewportValue;t.setViewport(s,i,r,n,o,a)}updateScissor(e){const{currentPass:t}=this.get(e),{x:s,y:i,width:r,height:n}=e.scissorValue;t.setScissorRect(s,i,r,n)}getClearColor(){const e=super.getClearColor();return!0===this.renderer.alpha&&(e.r*=e.a,e.g*=e.a,e.b*=e.a),e}clear(e,t,s,i=null){const r=this.device,n=this.renderer;let o,a,l,h,u=[];if(e){const e=this.getClearColor();a={r:e.r,g:e.g,b:e.b,a:e.a}}if(null===i){l=n.depth,h=n.stencil;const t=this._getDefaultRenderPassDescriptor();if(e){u=t.colorAttachments;const e=u[0];e.clearValue=a,e.loadOp=VB,e.storeOp=FB}(l||h)&&(o=t.depthStencilAttachment)}else{l=i.depth,h=i.stencil;const r={loadOp:e?VB:OB,clearValue:e?a:void 0};l&&(r.depthLoadOp=t?VB:OB,r.depthClearValue=t?n.getClearDepth():void 0,r.depthStoreOp=FB),h&&(r.stencilLoadOp=s?VB:OB,r.stencilClearValue=s?n.getClearStencil():void 0,r.stencilStoreOp=FB);const c=this._getRenderPassDescriptor(i,r);u=c.colorAttachments,o=c.depthStencilAttachment}l&&o&&(t?(o.depthLoadOp=VB,o.depthClearValue=n.getClearDepth(),o.depthStoreOp=FB):(o.depthLoadOp=OB,o.depthStoreOp=FB)),h&&o&&(s?(o.stencilLoadOp=VB,o.stencilClearValue=n.getClearStencil(),o.stencilStoreOp=FB):(o.stencilLoadOp=OB,o.stencilStoreOp=FB));const c=r.createCommandEncoder({label:"clear"});c.beginRenderPass({colorAttachments:u,depthStencilAttachment:o}).end(),r.queue.submit([c.finish()])}beginCompute(e){const t=this.get(e),s={label:"computeGroup_"+e.id};this.initTimestampQuery(Go,this.getTimestampUID(e),s),t.cmdEncoderGPU=this.device.createCommandEncoder({label:"computeGroup_"+e.id}),t.passEncoderGPU=t.cmdEncoderGPU.beginComputePass(s)}compute(e,t,s,i,r=null){const n=this.get(t),{passEncoderGPU:o}=this.get(e),a=this.get(i).pipeline;this.pipelineUtils.setPipeline(o,a);for(let e=0,t=s.length;e<t;e++){const t=s[e],i=this.get(t);o.setBindGroup(e,i.group)}if(null===r&&(r=t.count),r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute){const e=this.get(r).buffer;return void o.dispatchWorkgroupsIndirect(e,0)}if("number"==typeof r){const e=r;if(void 0===n.dispatchSize||n.count!==e){n.dispatchSize=[0,1,1],n.count=e;const s=t.workgroupSize;let i=s[0];for(let e=1;e<s.length;e++)i*=s[e];const o=Math.ceil(e/i),a=this.device.limits.maxComputeWorkgroupsPerDimension;r=[o,1,1],o>a&&(r[0]=Math.min(o,a),r[1]=Math.ceil(o/a)),n.dispatchSize=r}r=n.dispatchSize}o.dispatchWorkgroups(r[0],r[1]||1,r[2]||1)}finishCompute(e){const t=this.get(e);t.passEncoderGPU.end(),this.device.queue.submit([t.cmdEncoderGPU.finish()])}draw(e,t){const{object:s,material:i,context:r,pipeline:n}=e,o=e.getBindings(),a=this.get(r),l=this.get(n),h=l.pipeline;if(!0===l.error)return;const u=e.getIndex(),c=null!==u,d=e.getDrawParameters();if(null===d)return;const p=(t,s)=>{this.pipelineUtils.setPipeline(t,h),s.pipeline=h;const n=s.bindingGroups;for(let e=0,s=o.length;e<s;e++){const s=o[e],i=this.get(s);n[s.index]!==s.id&&(t.setBindGroup(s.index,i.group),n[s.index]=s.id)}if(!0===c&&s.index!==u){const e=this.get(u).buffer,i=u.array instanceof Uint16Array?jB:$B;t.setIndexBuffer(e,i),s.index=u}const l=e.getVertexBuffers();for(let e=0,i=l.length;e<i;e++){const i=l[e];if(s.attributes[e]!==i){const r=this.get(i).buffer;t.setVertexBuffer(e,r),s.attributes[e]=i}}!0===r.stencil&&!0===i.stencilWrite&&a.currentStencilRef!==i.stencilRef&&(t.setStencilReference(i.stencilRef),a.currentStencilRef=i.stencilRef)},m=(i,r)=>{if(p(i,r),!0===s.isBatchedMesh){const e=s._multiDrawStarts,r=s._multiDrawCounts,n=s._multiDrawCount,o=s._multiDrawInstances;null!==o&&Qo("WebGPUBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection.");for(let a=0;a<n;a++){const n=o?o[a]:1,l=n>1?0:a;!0===c?i.drawIndexed(r[a],n,e[a]/u.array.BYTES_PER_ELEMENT,0,l):i.draw(r[a],n,e[a],l),t.update(s,r[a],n)}}else if(!0===c){const{vertexCount:r,instanceCount:n,firstVertex:o}=d,a=e.getIndirect();if(null!==a){const t=this.get(a).buffer,s=e.getIndirectOffset(),r=Array.isArray(s)?s:[s];for(let e=0;e<r.length;e++)i.drawIndexedIndirect(t,r[e])}else i.drawIndexed(r,n,o,0,0);t.update(s,r,n)}else{const{vertexCount:r,instanceCount:n,firstVertex:o}=d,a=e.getIndirect();if(null!==a){const t=this.get(a).buffer,s=e.getIndirectOffset(),r=Array.isArray(s)?s:[s];for(let e=0;e<r.length;e++)i.drawIndirect(t,r[e])}else i.draw(r,n,o,0);t.update(s,r,n)}};if(e.camera.isArrayCamera&&e.camera.cameras.length>0){const t=this.get(e.camera),i=e.camera.cameras,n=e.getBindingGroup("cameraIndex");if(void 0===t.indexesGPU||t.indexesGPU.length!==i.length){const e=this.get(n),s=[],r=new Uint32Array([0,0,0,0]);for(let t=0,n=i.length;t<n;t++){r[0]=t;const{layoutGPU:i}=e.layout,n=this.bindingUtils.createBindGroupIndex(r,i);s.push(n)}t.indexesGPU=s}const o=this.renderer.getPixelRatio();for(let e=0,l=i.length;e<l;e++){const l=i[e];if(s.layers.test(l.layers)){const s=l.viewport;let i=a.currentPass,h=a.currentSets;if(a.bundleEncoders){i=a.bundleEncoders[e],h=a.bundleSets[e]}s&&i.setViewport(Math.floor(s.x*o),Math.floor(s.y*o),Math.floor(s.width*o),Math.floor(s.height*o),r.viewportValue.minDepth,r.viewportValue.maxDepth),n&&t.indexesGPU&&(i.setBindGroup(n.index,t.indexesGPU[e]),h.bindingGroups[n.index]=n.id),m(i,h)}}}else if(a.currentPass){if(void 0!==a.occlusionQuerySet){const e=a.lastOcclusionObject;e!==s&&(null!==e&&!0===e.occlusionTest&&(a.currentPass.endOcclusionQuery(),a.occlusionQueryIndex++),!0===s.occlusionTest&&(a.currentPass.beginOcclusionQuery(a.occlusionQueryIndex),a.occlusionQueryObjects[a.occlusionQueryIndex]=s),a.lastOcclusionObject=s)}m(a.currentPass,a.currentSets)}}needsRenderUpdate(e){const t=this.get(e),{object:s,material:i}=e,r=this.utils,n=r.getSampleCountRenderContext(e.context),o=r.getCurrentColorSpace(e.context),a=r.getCurrentColorFormat(e.context),l=r.getCurrentDepthStencilFormat(e.context),h=r.getPrimitiveTopology(s,i);let u=!1;return t.material===i&&t.materialVersion===i.version&&t.transparent===i.transparent&&t.blending===i.blending&&t.premultipliedAlpha===i.premultipliedAlpha&&t.blendSrc===i.blendSrc&&t.blendDst===i.blendDst&&t.blendEquation===i.blendEquation&&t.blendSrcAlpha===i.blendSrcAlpha&&t.blendDstAlpha===i.blendDstAlpha&&t.blendEquationAlpha===i.blendEquationAlpha&&t.colorWrite===i.colorWrite&&t.depthWrite===i.depthWrite&&t.depthTest===i.depthTest&&t.depthFunc===i.depthFunc&&t.stencilWrite===i.stencilWrite&&t.stencilFunc===i.stencilFunc&&t.stencilFail===i.stencilFail&&t.stencilZFail===i.stencilZFail&&t.stencilZPass===i.stencilZPass&&t.stencilFuncMask===i.stencilFuncMask&&t.stencilWriteMask===i.stencilWriteMask&&t.side===i.side&&t.alphaToCoverage===i.alphaToCoverage&&t.sampleCount===n&&t.colorSpace===o&&t.colorFormat===a&&t.depthStencilFormat===l&&t.primitiveTopology===h&&t.clippingContextCacheKey===e.clippingContextCacheKey||(t.material=i,t.materialVersion=i.version,t.transparent=i.transparent,t.blending=i.blending,t.premultipliedAlpha=i.premultipliedAlpha,t.blendSrc=i.blendSrc,t.blendDst=i.blendDst,t.blendEquation=i.blendEquation,t.blendSrcAlpha=i.blendSrcAlpha,t.blendDstAlpha=i.blendDstAlpha,t.blendEquationAlpha=i.blendEquationAlpha,t.colorWrite=i.colorWrite,t.depthWrite=i.depthWrite,t.depthTest=i.depthTest,t.depthFunc=i.depthFunc,t.stencilWrite=i.stencilWrite,t.stencilFunc=i.stencilFunc,t.stencilFail=i.stencilFail,t.stencilZFail=i.stencilZFail,t.stencilZPass=i.stencilZPass,t.stencilFuncMask=i.stencilFuncMask,t.stencilWriteMask=i.stencilWriteMask,t.side=i.side,t.alphaToCoverage=i.alphaToCoverage,t.sampleCount=n,t.colorSpace=o,t.colorFormat=a,t.depthStencilFormat=l,t.primitiveTopology=h,t.clippingContextCacheKey=e.clippingContextCacheKey,u=!0),u}getRenderCacheKey(e){const{object:t,material:s}=e,i=this.utils,r=e.context,n=t.isMesh&&t.matrixWorld.determinant()<0;return[s.transparent,s.blending,s.premultipliedAlpha,s.blendSrc,s.blendDst,s.blendEquation,s.blendSrcAlpha,s.blendDstAlpha,s.blendEquationAlpha,s.colorWrite,s.depthWrite,s.depthTest,s.depthFunc,s.stencilWrite,s.stencilFunc,s.stencilFail,s.stencilZFail,s.stencilZPass,s.stencilFuncMask,s.stencilWriteMask,s.side,n,i.getSampleCountRenderContext(r),i.getCurrentColorSpace(r),i.getCurrentColorFormat(r),i.getCurrentDepthStencilFormat(r),i.getPrimitiveTopology(t,s),e.getGeometryCacheKey(),e.clippingContextCacheKey].join()}updateSampler(e){return this.textureUtils.updateSampler(e)}createDefaultTexture(e){return this.textureUtils.createDefaultTexture(e)}createTexture(e,t){this.textureUtils.createTexture(e,t)}updateTexture(e,t){this.textureUtils.updateTexture(e,t)}generateMipmaps(e){this.textureUtils.generateMipmaps(e)}destroyTexture(e,t=!1){this.textureUtils.destroyTexture(e,t)}async copyTextureToBuffer(e,t,s,i,r,n){return this.textureUtils.copyTextureToBuffer(e,t,s,i,r,n)}initTimestampQuery(e,t,s){if(!this.trackTimestamp)return;this.timestampQueryPool[e]||(this.timestampQueryPool[e]=new cF(this.device,e,2048));const i=this.timestampQueryPool[e],r=i.allocateQueriesForContext(t);s.timestampWrites={querySet:i.querySet,beginningOfPassWriteIndex:r,endOfPassWriteIndex:r+1}}createNodeBuilder(e,t){return new sF(e,t)}createProgram(e){this.get(e).module={module:this.device.createShaderModule({code:e.code,label:e.stage+(""!==e.name?`_${e.name}`:"")}),entryPoint:"main"}}destroyProgram(e){this.delete(e)}createRenderPipeline(e,t){this.pipelineUtils.createRenderPipeline(e,t)}createComputePipeline(e,t){this.pipelineUtils.createComputePipeline(e,t)}beginBundle(e){const t=this.get(e);t._currentPass=t.currentPass,t._currentSets=t.currentSets,t.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.currentPass=this.pipelineUtils.createBundleEncoder(e)}finishBundle(e,t){const s=this.get(e),i=s.currentPass.finish();this.get(t).bundleGPU=i,s.currentSets=s._currentSets,s.currentPass=s._currentPass}addBundle(e,t){this.get(e).renderBundles.push(this.get(t).bundleGPU)}createBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBindings(e,t,s,i){this.bindingUtils.createBindings(e,t,s,i)}updateBinding(e){this.bindingUtils.updateBinding(e)}deleteBindGroupData(e){this.bindingUtils.deleteBindGroupData(e)}createIndexAttribute(e){let t=GPUBufferUsage.INDEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST;(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute)&&(t|=GPUBufferUsage.STORAGE),this.attributeUtils.createAttribute(e,t)}createAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.VERTEX|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}createIndirectStorageAttribute(e){this.attributeUtils.createAttribute(e,GPUBufferUsage.STORAGE|GPUBufferUsage.INDIRECT|GPUBufferUsage.COPY_SRC|GPUBufferUsage.COPY_DST)}updateAttribute(e){this.attributeUtils.updateAttribute(e)}destroyAttribute(e){this.attributeUtils.destroyAttribute(e)}updateSize(){this.delete(this.renderer.getCanvasTarget())}getMaxAnisotropy(){return 16}hasFeature(e){return void 0!==PL[e]&&(e=PL[e]),this.device.features.has(e)}copyTextureToTexture(e,t,s=null,i=null,r=0,n=0){let o=0,a=0,l=0,h=0,u=0,c=0,d=e.image.width,p=e.image.height,m=1;null!==s&&(!0===s.isBox3?(h=s.min.x,u=s.min.y,c=s.min.z,d=s.max.x-s.min.x,p=s.max.y-s.min.y,m=s.max.z-s.min.z):(h=s.min.x,u=s.min.y,d=s.max.x-s.min.x,p=s.max.y-s.min.y,m=1)),null!==i&&(o=i.x,a=i.y,l=i.z||0);const f=this.device.createCommandEncoder({label:"copyTextureToTexture_"+e.id+"_"+t.id}),g=this.get(e).texture,y=this.get(t).texture;f.copyTextureToTexture({texture:g,mipLevel:r,origin:{x:h,y:u,z:c}},{texture:y,mipLevel:n,origin:{x:o,y:a,z:l}},[d,p,m]),this.device.queue.submit([f.finish()]),0===n&&t.generateMipmaps&&this.textureUtils.generateMipmaps(t)}copyFramebufferToTexture(e,t,s){const i=this.get(t);let r=null;r=t.renderTarget?e.isDepthTexture?this.get(t.depthTexture).texture:this.get(t.textures[0]).texture:e.isDepthTexture?this.textureUtils.getDepthBuffer(t.depth,t.stencil):this.context.getCurrentTexture();const n=this.get(e).texture;if(r.format!==n.format)return void Zo("WebGPUBackend: copyFramebufferToTexture: Source and destination formats do not match.",r.format,n.format);let o;if(i.currentPass?(i.currentPass.end(),o=i.encoder):o=this.device.createCommandEncoder({label:"copyFramebufferToTexture_"+e.id}),o.copyTextureToTexture({texture:r,origin:[s.x,s.y,0]},{texture:n},[s.z,s.w]),e.generateMipmaps&&this.textureUtils.generateMipmaps(e,o),i.currentPass){const{descriptor:e}=i;for(let t=0;t<e.colorAttachments.length;t++)e.colorAttachments[t].loadOp=OB;t.depth&&(e.depthStencilAttachment.depthLoadOp=OB),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=OB),i.currentPass=o.beginRenderPass(e),i.currentSets={attributes:{},bindingGroups:[],pipeline:null,index:null},t.viewport&&this.updateViewport(t),t.scissor&&this.updateScissor(t)}else this.device.queue.submit([o.finish()])}dispose(){if(this.bindingUtils.dispose(),this.textureUtils.dispose(),this.occludedResolveCache){for(const e of this.occludedResolveCache.values())e.destroy();this.occludedResolveCache.clear()}if(this.timestampQueryPool)for(const e of Object.values(this.timestampQueryPool))null!==e&&e.dispose();void 0===this.parameters.device&&null!==this.device&&this.device.destroy()}}class pF extends Uu{constructor(e,t,s,i,r,n){super(e,t,s,i,r,n),this.iesMap=null}copy(e,t){return super.copy(e,t),this.iesMap=e.iesMap,this}}class mF extends Uu{constructor(e,t,s,i,r,n){super(e,t,s,i,r,n),this.aspect=null}copy(e,t){return super.copy(e,t),this.aspect=e.aspect,this}}class fF extends lP{constructor(){super(),this.addMaterial(qw,"MeshPhongMaterial"),this.addMaterial(zT,"MeshStandardMaterial"),this.addMaterial(UT,"MeshPhysicalMaterial"),this.addMaterial(WT,"MeshToonMaterial"),this.addMaterial(Vw,"MeshBasicMaterial"),this.addMaterial(Ww,"MeshLambertMaterial"),this.addMaterial(Mw,"MeshNormalMaterial"),this.addMaterial(XT,"MeshMatcapMaterial"),this.addMaterial(xw,"LineBasicMaterial"),this.addMaterial(_w,"LineDashedMaterial"),this.addMaterial(tS,"PointsMaterial"),this.addMaterial(KT,"SpriteMaterial"),this.addMaterial(nS,"ShadowMaterial"),this.addLight(sC,ju),this.addLight(DR,Hu),this.addLight(VR,Xu),this.addLight(zR,Uu),this.addLight(jR,qu),this.addLight($R,Lu),this.addLight(WR,Zu),this.addLight(kR,pF),this.addLight(GR,mF),this.addToneMapping(qA,1),this.addToneMapping(XA,2),this.addToneMapping(YA,3),this.addToneMapping(QA,4),this.addToneMapping(tN,6),this.addToneMapping(sN,7)}}class gF extends RP{constructor(e={}){let t;e.forceWebGL?t=wB:(t=dF,e.getFallback=()=>(Yo("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new wB(e)));super(new t(e),e),this.library=new fF,this.isWebGPURenderer=!0,"undefined"!=typeof __THREE_DEVTOOLS__&&__THREE_DEVTOOLS__.dispatchEvent(new CustomEvent("observe",{detail:this}))}}
12
- /**
13
- * @license
14
- * Copyright 2010-2025 Three.js Authors
15
- * SPDX-License-Identifier: MIT
16
- */YC.BRDF_GGX,YC.BRDF_Lambert,YC.BasicPointShadowFilter,YC.BasicShadowFilter,YC.Break,YC.Const;const yF=YC.Continue;YC.DFGLUT,YC.D_GGX,YC.Discard,YC.EPSILON,YC.F_Schlick;const xF=YC.Fn;YC.INFINITY;const bF=YC.If,_F=YC.Loop;YC.NodeAccess,YC.NodeShaderStage,YC.NodeType,YC.NodeUpdateType,YC.PCFShadowFilter,YC.PCFSoftShadowFilter,YC.PI,YC.PI2,YC.TWO_PI,YC.HALF_PI,YC.PointShadowFilter,YC.Return,YC.Schlick_to_F0,YC.ScriptableNodeResources,YC.ShaderNode,YC.Stack,YC.Switch,YC.TBNViewMatrix,YC.VSMShadowFilter,YC.V_GGX_SmithCorrelated,YC.Var,YC.VarIntent;const wF=YC.abs;YC.acesFilmicToneMapping,YC.acos,YC.add,YC.addMethodChaining,YC.addNodeElement,YC.agxToneMapping,YC.all,YC.alphaT,YC.and,YC.anisotropy,YC.anisotropyB,YC.anisotropyT,YC.any,YC.append,YC.array,YC.arrayBuffer,YC.asin,YC.assign,YC.atan,YC.atan2;const vF=YC.atomicAdd;YC.atomicAnd,YC.atomicFunc,YC.atomicLoad,YC.atomicMax,YC.atomicMin,YC.atomicOr,YC.atomicStore,YC.atomicSub,YC.atomicXor,YC.attenuationColor,YC.attenuationDistance,YC.attribute,YC.attributeArray,YC.backgroundBlurriness,YC.backgroundIntensity,YC.backgroundRotation,YC.batch,YC.bentNormalView,YC.billboarding,YC.bitAnd,YC.bitNot,YC.bitOr,YC.bitXor,YC.bitangentGeometry,YC.bitangentLocal,YC.bitangentView,YC.bitangentWorld,YC.bitcast,YC.blendBurn,YC.blendColor,YC.blendDodge,YC.blendOverlay,YC.blendScreen,YC.blur,YC.bool,YC.buffer,YC.bufferAttribute,YC.bumpMap,YC.burn,YC.builtin,YC.builtinAOContext,YC.builtinShadowContext,YC.bvec2,YC.bvec3,YC.bvec4,YC.bypass,YC.cache,YC.call,YC.cameraFar,YC.cameraIndex,YC.cameraNear,YC.cameraNormalMatrix,YC.cameraPosition,YC.cameraProjectionMatrix,YC.cameraProjectionMatrixInverse,YC.cameraViewMatrix,YC.cameraViewport,YC.cameraWorldMatrix,YC.cbrt,YC.cdl,YC.ceil,YC.checker,YC.cineonToneMapping,YC.clamp,YC.clearcoat,YC.clearcoatNormalView,YC.clearcoatRoughness,YC.code,YC.color,YC.colorSpaceToWorking,YC.colorToDirection,YC.compute,YC.computeKernel,YC.computeSkinning,YC.context,YC.convert,YC.convertColorSpace,YC.convertToTexture,YC.countLeadingZeros,YC.countOneBits,YC.countTrailingZeros,YC.cos;const TF=YC.cross;YC.cubeTexture,YC.cubeTextureBase,YC.dFdx,YC.dFdy,YC.dashSize,YC.debug,YC.decrement,YC.decrementBefore,YC.defaultBuildStages,YC.defaultShaderStages,YC.defined,YC.degrees,YC.deltaTime,YC.densityFog,YC.densityFogFactor,YC.depth,YC.depthPass,YC.determinant,YC.difference,YC.diffuseColor,YC.directPointLight,YC.directionToColor,YC.directionToFaceDirection,YC.dispersion,YC.distance,YC.div,YC.dodge,YC.dot,YC.drawIndex,YC.dynamicBufferAttribute,YC.element,YC.emissive,YC.equal,YC.equals,YC.equirectUV,YC.exp,YC.exp2,YC.expression,YC.faceDirection,YC.faceForward,YC.faceforward;const SF=YC.float;YC.floatBitsToInt,YC.floatBitsToUint,YC.floor,YC.fog,YC.fract,YC.frameGroup,YC.frameId,YC.frontFacing,YC.fwidth,YC.gain,YC.gapSize,YC.getConstNodeType,YC.getCurrentStack,YC.getDirection,YC.getDistanceAttenuation,YC.getGeometryRoughness,YC.getNormalFromDepth,YC.interleavedGradientNoise,YC.vogelDiskSample,YC.getParallaxCorrectNormal,YC.getRoughness,YC.getScreenPosition,YC.getShIrradianceAt,YC.getShadowMaterial,YC.getShadowRenderObjectFunction,YC.getTextureIndex,YC.getViewPosition,YC.globalId,YC.glsl,YC.glslFn,YC.grayscale,YC.greaterThan,YC.greaterThanEqual,YC.hash,YC.highpModelNormalViewMatrix,YC.highpModelViewMatrix,YC.hue,YC.increment,YC.incrementBefore,YC.instance;const MF=YC.instanceIndex,AF=YC.instancedArray;YC.instancedBufferAttribute,YC.instancedDynamicBufferAttribute,YC.instancedMesh;const NF=YC.int;YC.intBitsToFloat,YC.inverse,YC.inverseSqrt,YC.inversesqrt,YC.invocationLocalIndex,YC.invocationSubgroupIndex,YC.ior,YC.iridescence,YC.iridescenceIOR,YC.iridescenceThickness,YC.ivec2,YC.ivec3,YC.ivec4,YC.js,YC.label,YC.length,YC.lengthSq,YC.lessThan,YC.lessThanEqual,YC.lightPosition,YC.lightProjectionUV,YC.lightShadowMatrix,YC.lightTargetDirection,YC.lightTargetPosition,YC.lightViewPosition,YC.lightingContext,YC.lights,YC.linearDepth,YC.linearToneMapping,YC.localId,YC.log,YC.log2,YC.logarithmicDepthToViewZ,YC.luminance,YC.mat2,YC.mat3;const EF=YC.mat4;YC.matcapUV,YC.materialAO,YC.materialAlphaTest,YC.materialAnisotropy,YC.materialAnisotropyVector,YC.materialAttenuationColor,YC.materialAttenuationDistance,YC.materialClearcoat,YC.materialClearcoatNormal,YC.materialClearcoatRoughness,YC.materialColor,YC.materialDispersion,YC.materialEmissive,YC.materialEnvIntensity,YC.materialEnvRotation,YC.materialIOR,YC.materialIridescence,YC.materialIridescenceIOR,YC.materialIridescenceThickness,YC.materialLightMap,YC.materialLineDashOffset,YC.materialLineDashSize,YC.materialLineGapSize,YC.materialLineScale,YC.materialLineWidth,YC.materialMetalness,YC.materialNormal,YC.materialOpacity,YC.materialPointSize,YC.materialReference,YC.materialReflectivity,YC.materialRefractionRatio,YC.materialRotation,YC.materialRoughness,YC.materialSheen,YC.materialSheenRoughness,YC.materialShininess,YC.materialSpecular,YC.materialSpecularColor,YC.materialSpecularIntensity,YC.materialSpecularStrength,YC.materialThickness,YC.materialTransmission;const CF=YC.max;YC.maxMipLevel,YC.mediumpModelViewMatrix,YC.metalness;const RF=YC.min,PF=YC.mix;YC.mixElement,YC.mod,YC.modInt,YC.modelDirection,YC.modelNormalMatrix,YC.modelPosition,YC.modelRadius,YC.modelScale,YC.modelViewMatrix,YC.modelViewPosition,YC.modelViewProjection,YC.modelWorldMatrix,YC.modelWorldMatrixInverse,YC.morphReference,YC.mrt,YC.mul,YC.mx_aastep,YC.mx_add,YC.mx_atan2,YC.mx_cell_noise_float,YC.mx_contrast,YC.mx_divide,YC.mx_fractal_noise_float,YC.mx_fractal_noise_vec2,YC.mx_fractal_noise_vec3,YC.mx_fractal_noise_vec4,YC.mx_frame,YC.mx_heighttonormal,YC.mx_hsvtorgb,YC.mx_ifequal,YC.mx_ifgreater,YC.mx_ifgreatereq,YC.mx_invert,YC.mx_modulo,YC.mx_multiply,YC.mx_noise_float,YC.mx_noise_vec3,YC.mx_noise_vec4,YC.mx_place2d,YC.mx_power,YC.mx_ramp4,YC.mx_ramplr,YC.mx_ramptb,YC.mx_rgbtohsv,YC.mx_rotate2d,YC.mx_rotate3d,YC.mx_safepower,YC.mx_separate,YC.mx_splitlr,YC.mx_splittb,YC.mx_srgb_texture_to_lin_rec709,YC.mx_subtract,YC.mx_timer,YC.mx_transform_uv,YC.mx_unifiednoise2d,YC.mx_unifiednoise3d,YC.mx_worley_noise_float,YC.mx_worley_noise_vec2,YC.mx_worley_noise_vec3,YC.negate,YC.neutralToneMapping,YC.nodeArray,YC.nodeImmutable,YC.nodeObject,YC.nodeObjectIntent,YC.nodeObjects,YC.nodeProxy,YC.nodeProxyIntent,YC.normalFlat,YC.normalGeometry,YC.normalLocal,YC.normalMap,YC.normalView,YC.normalViewGeometry,YC.normalWorld,YC.normalWorldGeometry;const BF=YC.normalize;YC.not,YC.notEqual,YC.numWorkgroups,YC.objectDirection,YC.objectGroup,YC.objectPosition,YC.objectRadius,YC.objectScale,YC.objectViewPosition,YC.objectWorldMatrix,YC.OnBeforeObjectUpdate,YC.OnBeforeMaterialUpdate,YC.OnObjectUpdate,YC.OnMaterialUpdate,YC.oneMinus,YC.or,YC.orthographicDepthToViewZ,YC.oscSawtooth,YC.oscSine,YC.oscSquare,YC.oscTriangle,YC.output,YC.outputStruct,YC.overlay,YC.overloadingFn,YC.packHalf2x16,YC.packSnorm2x16,YC.packUnorm2x16,YC.parabola,YC.parallaxDirection,YC.parallaxUV,YC.parameter,YC.pass,YC.passTexture,YC.pcurve,YC.perspectiveDepthToViewZ,YC.pmremTexture,YC.pointShadow,YC.pointUV,YC.pointWidth,YC.positionGeometry,YC.positionLocal,YC.positionPrevious,YC.positionView,YC.positionViewDirection,YC.positionWorld,YC.positionWorldDirection,YC.posterize,YC.pow,YC.pow2,YC.pow3,YC.pow4,YC.premultiplyAlpha,YC.property,YC.radians,YC.rand,YC.range,YC.rangeFog,YC.rangeFogFactor,YC.reciprocal,YC.reference,YC.referenceBuffer,YC.reflect,YC.reflectVector,YC.reflectView,YC.reflector,YC.refract,YC.refractVector,YC.refractView,YC.reinhardToneMapping,YC.remap,YC.remapClamp,YC.renderGroup,YC.renderOutput,YC.rendererReference,YC.replaceDefaultUV,YC.rotate,YC.rotateUV,YC.roughness,YC.round,YC.rtt,YC.sRGBTransferEOTF,YC.sRGBTransferOETF,YC.sample,YC.sampler,YC.samplerComparison,YC.saturate,YC.saturation,YC.screen,YC.screenCoordinate,YC.screenDPR,YC.screenSize,YC.screenUV,YC.scriptable,YC.scriptableValue;const IF=YC.select;YC.setCurrentStack,YC.setName,YC.shaderStages,YC.shadow,YC.shadowPositionWorld,YC.shapeCircle,YC.sharedUniformGroup,YC.sheen,YC.sheenRoughness,YC.shiftLeft,YC.shiftRight,YC.shininess,YC.sign,YC.sin,YC.sinc,YC.skinning,YC.smoothstep,YC.smoothstepElement,YC.specularColor,YC.specularF90,YC.spherizeUV,YC.split,YC.spritesheetUV,YC.sqrt,YC.stack,YC.step,YC.stepElement,YC.storage,YC.storageBarrier,YC.storageObject,YC.storageTexture,YC.string,YC.struct,YC.sub,YC.subgroupAdd,YC.subgroupAll,YC.subgroupAnd,YC.subgroupAny,YC.subgroupBallot,YC.subgroupBroadcast,YC.subgroupBroadcastFirst,YC.subBuild,YC.subgroupElect,YC.subgroupExclusiveAdd,YC.subgroupExclusiveMul,YC.subgroupInclusiveAdd,YC.subgroupInclusiveMul,YC.subgroupIndex,YC.subgroupMax,YC.subgroupMin,YC.subgroupMul,YC.subgroupOr,YC.subgroupShuffle,YC.subgroupShuffleDown,YC.subgroupShuffleUp,YC.subgroupShuffleXor,YC.subgroupSize,YC.subgroupXor,YC.tan,YC.tangentGeometry,YC.tangentLocal,YC.tangentView,YC.tangentWorld,YC.texture,YC.texture3D,YC.textureBarrier,YC.textureBicubic,YC.textureBicubicLevel,YC.textureCubeUV,YC.textureLoad,YC.textureSize,YC.textureLevel,YC.textureStore,YC.thickness,YC.time,YC.toneMapping,YC.toneMappingExposure,YC.toonOutlinePass,YC.transformDirection,YC.transformNormal,YC.transformNormalToView,YC.transformedClearcoatNormalView,YC.transformedNormalView,YC.transformedNormalWorld,YC.transmission,YC.transpose,YC.triNoise3D,YC.triplanarTexture,YC.triplanarTextures,YC.trunc;const DF=YC.uint;YC.uintBitsToFloat,YC.uniform,YC.uniformArray,YC.uniformCubeTexture,YC.uniformGroup,YC.uniformFlow,YC.uniformTexture,YC.unpackHalf2x16,YC.unpackSnorm2x16,YC.unpackUnorm2x16,YC.unpremultiplyAlpha,YC.userData,YC.uv,YC.uvec2,YC.uvec3,YC.uvec4,YC.varying,YC.varyingProperty,YC.vec2;const LF=YC.vec3,FF=YC.vec4;YC.vectorComponents,YC.velocity,YC.vertexColor,YC.vertexIndex,YC.vertexStage,YC.vibrance,YC.viewZToLogarithmicDepth,YC.viewZToOrthographicDepth,YC.viewZToPerspectiveDepth,YC.viewport,YC.viewportCoordinate,YC.viewportDepthTexture,YC.viewportLinearDepth,YC.viewportMipTexture,YC.viewportResolution,YC.viewportSafeUV,YC.viewportSharedTexture,YC.viewportSize,YC.viewportTexture,YC.viewportUV,YC.wgsl,YC.wgslFn,YC.workgroupArray,YC.workgroupBarrier,YC.workgroupId,YC.workingToColorSpace,YC.xor;const OF=1e-5,VF=1e-16,zF=1e-16;function kF(e,t,s,i,r){e.bvhcast(t,s.matrixWorld,{intersectsRanges:(e,t,s,n)=>{i._edgeOffsets.push(e),i._edgeCounts.push(t),i._meshOffsets.push(s),i._meshCounts.push(n),i._meshIndex.push(r),i.groupCount++}})}let UF=null;async function GF(e,t,s,i,r=null){const n=await async function(){return null===UF&&(UF=new gF,await UF.init()),UF}();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 o=AF(function(e){const t=new Float32Array(6*e.length);for(let s=0;s<e.length;s++){const i=e[s];t[6*s+0]=i.start.x,t[6*s+1]=i.start.y,t[6*s+2]=i.start.z,t[6*s+3]=i.end.x,t[6*s+4]=i.end.y,t[6*s+5]=i.end.z}return t}(s.lines),"float");qr.enabled&&console.log("Number of meshes:",t.length),qr.enabled&&console.log("Group count:",e.groupCount);const a=[];{let e=0;for(;e<t.length;){let s=e,i=0;for(;s<t.length;){const r=t[s].geometry,n=r.index?r.index.count/3:r.attributes.position.count/3;if(s>e&&(s-e>=1e3||i+n>1e5))break;i+=n,s++}a.push({start:e,end:s}),e=s}}qr.enabled&&console.log(`Split ${t.length} meshes into ${a.length} batches`);let l=0,h=0,u=0,c=0,d=0;for(let s=0;s<a.length;s++){const{start:p,end:m}=a[s],f=m-p;qr.enabled&&console.log(`Processing batch ${s+1}/${a.length} (meshes ${p}-${m-1})`);let g=0,y=0;const x=[];for(let e=p;e<m;e++){const s=t[e].geometry;x.push(y/3),g+=s.attributes.position.array.length,y+=s.index.array.length}const b=new Float32Array(g),_=new Uint32Array(y);let w=0,v=0,T=0;for(let e=p;e<m;e++){const s=t[e].geometry,i=s.attributes.position.array,r=s.index.array;b.set(i,w),w+=i.length;for(let e=0;e<r.length;e++)_[v+e]=r[e]+T;v+=r.length,T+=s.attributes.position.count}const S=new Float32Array(16*f);for(let e=p;e<m;e++){const s=e-p;S.set(t[e].matrixWorld.elements,16*s)}const M=[];for(let t=0;t<e.groupCount;t++){const s=e.meshIndex[t];if(s>=p&&s<m){const i=s-p,r=x[i]+e.meshOffsets[t];M.push({edgeOffset:e.edgeOffsets[t],edgeCount:e.edgeCounts[t],triOffset:r,triCount:e.meshCounts[t],meshIdx:i})}}if(0===M.length){qr.enabled&&console.log(` Batch ${s+1}: no groups, skipping`);continue}const A=new Uint32Array(5*M.length);for(let e=0;e<M.length;e++){const t=M[e],s=5*e;A[s+0]=t.edgeOffset,A[s+1]=t.edgeCount,A[s+2]=t.triOffset,A[s+3]=t.triCount,A[s+4]=t.meshIdx}let N=0;for(let e=0;e<M.length;e++)N+=M[e].edgeCount*M[e].triCount;r&&(r.candidates+=N);let E=Math.min(Math.ceil(.1*N),2e6),C=Math.max(E,1e4);qr.enabled&&console.log(` Batch ${s+1}: ${M.length} groups, ${g/3} vertices, ${y/3} triangles, ${N} pairs, buffer for ${C} overlaps`);const R=performance.now(),P=AF(b,"float"),B=AF(_,"uint"),I=AF(S,"float"),D=AF(A,"uint");let L=AF(new Uint32Array([0]),"uint").toAtomic(),F=AF(new Float32Array(3*C),"float");c+=performance.now()-R;const O=performance.now(),V=xF(()=>{const e=MF.mul(5),t=D.element(e),s=D.element(e.add(1)),i=D.element(e.add(2)),r=D.element(e.add(3)),n=D.element(e.add(4)).mul(16),a=EF(I.element(n),I.element(n.add(1)),I.element(n.add(2)),I.element(n.add(3)),I.element(n.add(4)),I.element(n.add(5)),I.element(n.add(6)),I.element(n.add(7)),I.element(n.add(8)),I.element(n.add(9)),I.element(n.add(10)),I.element(n.add(11)),I.element(n.add(12)),I.element(n.add(13)),I.element(n.add(14)),I.element(n.add(15)));_F({start:NF(0),end:r.toInt(),type:"int",condition:"<",name:"triIdx"},({triIdx:e})=>{const r=i.add(e.toUint()).mul(3),n=B.element(r),l=B.element(r.add(1)),h=B.element(r.add(2)),u=LF(P.element(n.mul(3)),P.element(n.mul(3).add(1)),P.element(n.mul(3).add(2))),c=LF(P.element(l.mul(3)),P.element(l.mul(3).add(1)),P.element(l.mul(3).add(2))),d=LF(P.element(h.mul(3)),P.element(h.mul(3).add(1)),P.element(h.mul(3).add(2))),p=a.mul(FF(u,SF(1))).xyz,m=a.mul(FF(c,SF(1))).xyz,f=a.mul(FF(d,SF(1))).xyz,g=m.sub(p),y=f.sub(p),x=TF(g,y),b=x.dot(x);bF(b.lessThan(SF(4e-16*VF)),()=>{yF()}),bF(x.y.lessThan(0),()=>{yF()});const _=CF(p.y,CF(m.y,f.y));_F({start:NF(0),end:s.toInt(),type:"int",condition:"<",name:"edgeIdx"},({edgeIdx:e})=>{const s=t.add(e.toUint()),i=s.mul(6),r=LF(o.element(i),o.element(i.add(1)),o.element(i.add(2))),n=LF(o.element(i.add(3)),o.element(i.add(4)),o.element(i.add(5))),a=RF(r.y,n.y);bF(_.lessThanEqual(a),()=>{yF()});const l=BF(x),h=l.dot(p).negate(),u=l.y.lessThan(0),c=IF(u,l.negate(),l),d=IF(u,h.negate(),h),g=c.dot(r).add(d),y=c.dot(n).add(d),b=g.lessThan(0),w=y.lessThan(0),v=wF(g).lessThan(SF(OF)),T=b.not().and(w.not()),S=y.sub(g),M=wF(S).lessThan(SF(OF)),A=M.and(v.or(b.not()));bF(A,()=>{yF()}),bF(T.and(M.not()),()=>{yF()});const N=g.negate().div(S),E=PF(r,n,N),R=LF(IF(M.or(b),r.x,E.x),IF(M.or(b),r.y,E.y),IF(M.or(b),r.z,E.z)),P=LF(IF(M.or(w),n.x,E.x),IF(M.or(w),n.y,E.y),IF(M.or(w),n.z,E.z)),B=P.sub(R),I=B.dot(B);bF(I.lessThan(SF(OF)),()=>{yF()});const D=r.sub(p),O=r.sub(m),V=r.sub(f),z=n.sub(p),k=n.sub(m),U=n.sub(f),G=D.dot(D).lessThanEqual(SF(OF)),j=O.dot(O).lessThanEqual(SF(OF)),$=V.dot(V).lessThanEqual(SF(OF)),W=z.dot(z).lessThanEqual(SF(OF)),H=k.dot(k).lessThanEqual(SF(OF)),q=U.dot(U).lessThanEqual(SF(OF)),X=G.or(j).or($),Y=W.or(H).or(q),Z=X.and(Y);bF(Z,()=>{yF()});const Q=LF(p.x,SF(0),p.z),K=LF(m.x,SF(0),m.z),J=LF(f.x,SF(0),f.z),ee=LF(R.x,SF(0),R.z),te=LF(P.x,SF(0),P.z),se=LF(r.x,SF(0),r.z),ie=LF(n.x,SF(0),n.z).sub(se),re=ie.dot(ie);bF(re.lessThan(SF(OF)),()=>{yF()});const ne=re.sqrt(),oe=K.sub(Q),ae=J.sub(Q),le=TF(oe,ae),he=le.dot(le);bF(he.lessThanEqual(SF(4e-16*VF)),()=>{yF()});const ue=te.sub(ee),ce=ue.dot(ue);bF(ce.lessThan(SF(OF)),()=>{yF()});const de=ce.sqrt(),pe=ue.div(de),me=ie.div(ne),fe=BF(le),ge=TF(pe,fe),ye=SF(0).toVar(),xe=SF(0).toVar(),be=SF(0).toVar(),_e=SF(0).toVar(),we=DF(0).toVar(),ve=ge.dot(Q.sub(ee)),Te=ge.dot(K.sub(ee)),Se=wF(ve).lessThan(SF(zF)),Me=wF(Te).lessThan(SF(zF)),Ae=Se.not().and(Me.not()).and(ve.mul(Te).lessThan(0));bF(Ae,()=>{const e=ve.div(ve.sub(Te)),t=PF(Q.x,K.x,e),s=PF(Q.z,K.z,e);bF(we.equal(0),()=>{ye.assign(t),xe.assign(s)}).Else(()=>{be.assign(t),_e.assign(s)}),we.addAssign(1)}).ElseIf(Se,()=>{bF(we.equal(0),()=>{ye.assign(Q.x),xe.assign(Q.z)}).Else(()=>{be.assign(Q.x),_e.assign(Q.z)}),we.addAssign(1)});const Ne=Te,Ee=ge.dot(J.sub(ee)),Ce=Me,Re=wF(Ee).lessThan(SF(zF)),Pe=Ce.not().and(Re.not()).and(Ne.mul(Ee).lessThan(0));bF(we.lessThan(2),()=>{bF(Pe,()=>{const e=Ne.div(Ne.sub(Ee)),t=PF(K.x,J.x,e),s=PF(K.z,J.z,e);bF(we.equal(0),()=>{ye.assign(t),xe.assign(s)}).Else(()=>{be.assign(t),_e.assign(s)}),we.addAssign(1)}).ElseIf(Ce.and(Ae.not()).and(Se.not()),()=>{bF(we.equal(0),()=>{ye.assign(K.x),xe.assign(K.z)}).Else(()=>{be.assign(K.x),_e.assign(K.z)}),we.addAssign(1)})});const Be=Ee,Ie=ve,De=Re,Le=Se,Fe=De.not().and(Le.not()).and(Be.mul(Ie).lessThan(0));bF(we.lessThan(2),()=>{bF(Fe,()=>{const e=Be.div(Be.sub(Ie)),t=PF(J.x,Q.x,e),s=PF(J.z,Q.z,e);bF(we.equal(0),()=>{ye.assign(t),xe.assign(s)}).Else(()=>{be.assign(t),_e.assign(s)}),we.addAssign(1)}).ElseIf(De.and(Pe.not()).and(Ce.not()),()=>{bF(we.equal(0),()=>{ye.assign(J.x),xe.assign(J.z)}).Else(()=>{be.assign(J.x),_e.assign(J.z)}),we.addAssign(1)})}),bF(we.notEqual(2),()=>{yF()});const Oe=LF(ye,SF(0),xe),Ve=LF(be,SF(0),_e).sub(Oe).dot(pe),ze=LF(ye,SF(0),xe).toVar(),ke=LF(be,SF(0),_e).toVar();bF(Ve.lessThan(0),()=>{const e=ye,t=xe;ze.x.assign(be),ze.z.assign(_e),ke.x.assign(e),ke.z.assign(t)});const Ue=SF(0),Ge=de,je=ze.sub(ee).dot(pe),$e=ke.sub(ee).dot(pe),We=Ge.lessThanEqual(je).or($e.lessThanEqual(Ue));bF(We,()=>{yF()});const He=CF(Ue,je),qe=RF(Ge,$e),Xe=ee.add(pe.mul(He)),Ye=ee.add(pe.mul(qe)),Ze=Xe.sub(se).dot(me).div(ne),Qe=Ye.sub(se).dot(me).div(ne),Ke=CF(SF(0),RF(SF(1),Ze)),Je=CF(SF(0),RF(SF(1),Qe)),et=wF(Je.sub(Ke));bF(et.lessThanEqual(SF(zF)),()=>{yF()});const tt=vF(L.element(0),1);bF(tt.lessThan(DF(C)),()=>{const e=tt.mul(3);F.element(e).assign(s.toFloat()),F.element(e.add(1)).assign(Ke),F.element(e.add(2)).assign(Je)})})})})().compute(M.length);d+=performance.now()-O;const z=performance.now();await n.computeAsync(V),l+=performance.now()-z;const k=performance.now(),U=await n.getArrayBufferAsync(L.value),G=new Uint32Array(U)[0];if(r&&(r.used+=Math.min(G,C)),qr.enabled&&console.log(` Batch ${s+1}: ${G} overlaps found (capacity: ${C})`),G>C&&qr.enabled&&console.warn(` WARNING: Overlap buffer overflow! ${G} > ${C}. Some occlusion data lost.`),G>0){const e=await n.getArrayBufferAsync(F.value),t=new Float32Array(e);h+=performance.now()-k;const s=performance.now(),r=Math.min(G,C);for(let e=0;e<r;e++){const s=3*e,r=Math.round(t[s]);Lr([t[s+1],t[s+2]],i[r])}u+=performance.now()-s,qr.enabled&&console.log(` Processed ${r} overlaps into hiddenOverlapMap`)}else h+=performance.now()-k}n.dispose(),UF=null;const p=c+d+l+h+u;qr.enabled&&(console.log(`WebGPU timing breakdown (total: ${p.toFixed(1)}ms):`),console.log(` Buffer creation: ${c.toFixed(1)}ms`),console.log(` Shader build: ${d.toFixed(1)}ms`),console.log(` GPU compute: ${l.toFixed(1)}ms`),console.log(` Readback: ${h.toFixed(1)}ms`),console.log(` CPU merge: ${u.toFixed(1)}ms`))}const jF=new i.Vector3(0,1,0);function $F(e,t=null){const s=new Float32Array(6*e.length);let r=0;for(let t=0,i=e.length;t<i;t++){const i=e[t];s[r++]=i[0],s[r++]=0,s[r++]=i[2],s[r++]=i[3],s[r++]=0,s[r++]=i[5]}const n=new i.BufferGeometry,o=new i.BufferAttribute(s,3,!0);if(n.setAttribute("position",o),t){const s=new Float32Array(2*e.length);for(let e=0,i=t.length;e<i;e++)s[2*e]=t[e],s[2*e+1]=t[e];n.setAttribute("group",new i.BufferAttribute(s,1))}return n}class WF{constructor(e,t=!0){this.meshes=hr(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 $F(this.visibleEdges,this.groupKeyToIndex?this.visibleGroupIndices:null)}getHiddenLineGeometry(){return $F(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 s=this.addEdgesGenerator(...e).next().value;return this.iterationTime=t,s}*addEdgesGenerator(e,t={}){const{meshes:s,bvhs:i,visibleEdges:r,hiddenEdges:n,iterationTime:o}=this;let a=performance.now();qr.startStep("Building mesh BVH");for(let e=0;e<s.length;e++){performance.now()-a>o&&(yield,a=performance.now());const t=s[e].geometry;if(!i.has(t)){const e=t.boundsTree||new Mi(t);i.set(t,e)}}let l=0;for(let e=0;e<s.length;e++){const t=s[e].geometry;l+=t.index?t.index.count/3:t.attributes.position.count/3}const h={};for(let t=0;t<e.length;t++)h[t]=[];qr.startStep("Building line BVH");const u=new fr(e,{maxLeafSize:2,strategy:2});qr.startStep("BVHcast overlaps"),a=performance.now();const c={candidates:0,backFaceCulled:0,yBoundsCulled:0,xzBoundsCulled:0,triangleEdgeCulled:0,planeTrimCulled:0,distThresholdCulled:0,noOverlapCulled:0,used:0,totalEdges:e.length,totalTriangles:l},d=this.useWebGPU,p={};d&&(p._edgeOffsets=[],p._edgeCounts=[],p._meshOffsets=[],p._meshCounts=[],p._meshIndex=[],p.groupCount=0);for(let e=0;e<s.length;e++){performance.now()-a>o&&(t.onProgress&&t.onProgress(e,s.length),yield,a=performance.now());const r=s[e];d?kF(u,i.get(r.geometry),r,p,e):kr(u,i.get(r.geometry),r,h,c)}if(d){let e=!1;for(GF(p,s,u,h,c).then(()=>{e=!0});!e;)yield}const m=c.totalEdges*c.totalTriangles;if(qr.setStat("Total edges",c.totalEdges.toLocaleString()),qr.setStat("Total triangles",c.totalTriangles.toLocaleString()),qr.setStat("Brute-force pairs (edges × triangles)",m.toLocaleString()),qr.setStat("BVH candidate pairs",c.candidates.toLocaleString()),m>0&&qr.setStat("BVH reduction",(c.candidates/m*100).toFixed(3)+"% of brute-force"),c.candidates>0){const e=c.candidates,t=t=>(t/e*100).toFixed(2)+"%";d||(qr.setStat("Rejected: back-face culling",c.backFaceCulled.toLocaleString()+" ("+t(c.backFaceCulled)+")"),qr.setStat("Rejected: Y-bounds (tri below edge)",c.yBoundsCulled.toLocaleString()+" ("+t(c.yBoundsCulled)+")"),qr.setStat("Rejected: XZ-bounds (no 2D overlap)",c.xzBoundsCulled.toLocaleString()+" ("+t(c.xzBoundsCulled)+")"),qr.setStat("Rejected: edge lies on triangle",c.triangleEdgeCulled.toLocaleString()+" ("+t(c.triangleEdgeCulled)+")"),qr.setStat("Rejected: line above tri plane",c.planeTrimCulled.toLocaleString()+" ("+t(c.planeTrimCulled)+")"),qr.setStat("Rejected: trimmed edge too small",c.distThresholdCulled.toLocaleString()+" ("+t(c.distThresholdCulled)+")"),qr.setStat("Rejected: no projected overlap",c.noOverlapCulled.toLocaleString()+" ("+t(c.noOverlapCulled)+")")),qr.setStat("Producing overlaps",c.used.toLocaleString()+" ("+t(c.used)+")")}qr.startStep("Converting overlaps to lines");const f=this.hasGroups;for(let t=0;t<e.length;t++){performance.now()-a>o&&(yield,a=performance.now());const s=e[t],i=h[t],l=r.length,u=n.length;if(Ji(s,i,!1,r),Ji(s,i,!0,n),f){const e=s.groupIndex;for(let t=l;t<r.length;t++)this.visibleGroupIndices.push(e);for(let t=u;t<n.length;t++)this.hiddenGroupIndices.push(e)}}}}class HF{constructor(){this.iterationTime=30,this.angleThreshold=50,this.includeIntersectionEdges=!0,this.useWebGPU=!0}generateAsync(e,t={}){return new Promise((s,i)=>{const{signal:r}=t,n=this.generate(e,t);!function e(){if(r&&r.aborted)return void i(new Error("ProjectionGenerator: Process aborted via AbortSignal."));const t=n.next();t.done?s(t.value):requestAnimationFrame(e)}()})}*generate(e,t){const{iterationTime:s,angleThreshold:r,includeIntersectionEdges:n}=this,{onProgress:o=()=>{},visibilityCuller:a=null,groupFn:l=null}=t;if(qr.reset(),qr.startTotal(),e.isBufferGeometry&&(e=new i.Mesh(e)),a){qr.startStep("Visibility culling");let t=!1;for(a.cull(e).then(s=>{(e=new i.Scene).children=s,t=!0});!t;)yield}const h=new pr;h.iterationTime=s,h.thresholdAngle=r,h.projectionDirection.copy(jF),qr.startStep("Generating candidate edges"),o("Generating candidate edges");let u=[],c=l?[]:null;if(yield*h.getEdgesGenerator(e,u,c),n&&(qr.startStep("Generating intersection edges"),o("Generating intersection edges"),yield*h.getIntersectionEdgesGenerator(e,u,c)),qr.startStep("Pre-filtering edges"),o("Pre-filtering edges"),c){const e=[],t=[];for(let s=0;s<u.length;s++)Zi(u[s])||(e.push(u[s]),t.push(c[s]));u=e,c=t}else u=u.filter(e=>!Zi(e));yield;const d=new WF(e,this.useWebGPU);if(d.iterationTime=s,l&&c){const e=new Map;for(let t=0;t<u.length;t++){const s=l(c[t]);e.has(s)||e.set(s,e.size),u[t].groupIndex=e.get(s)}d.groupKeyToIndex=e,d.hasGroups=!0}return o("Building BVH & computing overlaps"),yield*d.addEdgesGenerator(u,{onProgress:o?(e,t)=>{o("Building BVH & computing overlaps",e/t,d)}:null}),qr.printSummary(),d}}new i.Line3,new i.Line3,new i.Vector3;const qF=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"onDisposed",new u),t(this,"generator",new HF),t(this,"cullerPixelsPerMeter",.05),t(this,"projectionDirection",new l.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,s){const i=this.components.get(ji),r=new l.Group,n=new Map;for(const[t,s]of Object.entries(e)){const e=i.list.get(t);if(!e)continue;const o=(await e.getItemsIdsWithGeometry()).filter(e=>s.has(e));if(0===o.length)continue;const a=await e.getItemsGeometry(o);for(const s in a){const i=a[s];for(const s of i){if(!(s.positions&&s.indices&&s.transform&&s.representationId))continue;const i=s.representationId;if(!n.has(i)){const e=new l.BufferGeometry;e.setAttribute("position",new l.Float32BufferAttribute(s.positions,3)),s.normals&&e.setAttribute("normal",new l.Float32BufferAttribute(s.normals,3)),e.setIndex(Array.from(s.indices)),n.set(i,e)}const o=n.get(i),a=new l.Mesh(o);a.applyMatrix4(s.transform),a.applyMatrix4(e.object.matrixWorld),a.updateWorldMatrix(!0,!0),a.userData._edgeProjectorModelId=t,a.userData._edgeProjectorLocalId=s.localId,r.add(a)}}}const o=this.projectionDirection.clone().normalize(),a=new l.Vector3(0,-1,0),h=(new l.Quaternion).setFromUnitVectors(o,a),u=(new l.Matrix4).makeRotationFromQuaternion(h),c=u.clone().invert();for(const e of r.children)e.applyMatrix4(u),e.updateWorldMatrix(!1,!1);if(r.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 Mi(t.geometry,{maxLeafSize:1,strategy:2})}}),this.nearPlane!==-1/0||this.farPlane!==1/0){const e=new l.Box3,t=[];for(const s of r.children){const i=s;i.geometry&&(e.setFromObject(i),(e.max.y<this.nearPlane||e.min.y>this.farPlane)&&t.push(i))}for(const e of t)r.remove(e)}const d=t.renderer.three,p=new Wi(d,{pixelsPerMeter:this.cullerPixelsPerMeter}),m=await this.generator.generateAsync(r,{visibilityCuller:p,groupFn:e=>`${e.userData._edgeProjectorModelId??"unknown"}:${e.userData._edgeProjectorLocalId??0}`,onProgress:null==s?void 0:s.onProgress}),f=m.getVisibleLineGeometry(),g=m.getHiddenLineGeometry();f.applyMatrix4(c),g.applyMatrix4(c);const y=m.getGroupKeys(),x={};for(const[e,t]of Object.entries(y)){const s=e.lastIndexOf(":"),i=e.substring(0,s),r=Number(e.substring(s+1));x[t]={modelId:i,localId:r}}for(const e of n.values())e.dispose();return{visible:f,hidden:g,groups:x}}dispose(){this.onDisposed.trigger(e.uuid),this.onDisposed.reset()}};t(qF,"uuid","f2e76c3a-8b1d-4d5e-9a3f-7c6b2d4e8f1a");let XF=qF;class YF{constructor(){t(this,"wasm",{path:"",absolute:!1,logLevel:h.LogLevel.LOG_LEVEL_OFF}),t(this,"webIfc",{COORDINATE_TO_ORIGIN:!0}),t(this,"autoSetWasm",!0),t(this,"customLocateFileHandler",null)}}const ZF=class e extends d{constructor(s){super(s),t(this,"onDisposed",new u),t(this,"onIfcStartedLoading",new u),t(this,"onIfcImporterInitialized",new u),t(this,"onSetup",new u),t(this,"settings",new YF),t(this,"webIfc",new h.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,s,i){const r=this.components.get(ji);if(!r.initialized)throw new Error("You need to initialize fragments first.");this.settings.autoSetWasm&&await this.autoSetWasm(),r.core.settings.autoCoordinate=t;const n=new a.IfcImporter;n.wasm.path=this.settings.wasm.path,n.wasm.absolute=this.settings.wasm.absolute,n.webIfcSettings=this.settings.webIfc,this.onIfcImporterInitialized.trigger(n),(null==i?void 0:i.instanceCallback)&&i.instanceCallback(n);const o=await n.process({...null==i?void 0:i.processData,bytes:e});return await r.core.load(o,{modelId:s,userData:null==i?void 0:i.userData})}async readIfcFile(e){const{path:t,absolute:s,logLevel:i}=this.settings.wasm;return this.webIfc.SetWasmPath(t,s),await this.webIfc.Init(this.settings.customLocateFileHandler||void 0),i&&this.webIfc.SetLogLevel(i),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 h.IfcAPI}async autoSetWasm(){const e=await fetch(`https://unpkg.com/@thatopen/components@${NO.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(ZF,"uuid","a659add7-1418-4771-a0d6-7d4d438e4624");let QF=ZF;const KF=class e extends d{constructor(s){super(s),t(this,"enabled",!0),this.components.add(e.uuid,this)}async set(e,t){const s=this.components.get(ji),i=[];if(t)for(const[r,n]of Object.entries(t)){const t=s.list.get(r);t&&i.push(t.setVisible([...n],e))}else for(const t of s.list.values())i.push(t.setVisible(void 0,e));await Promise.all(i),await s.core.update(!0)}async isolate(e){await Promise.all([this.set(!1),this.set(!0,e)])}async toggle(e){const t=[],s=this.components.get(ji);for(const[i,r]of Object.entries(e)){const e=s.list.get(i);e&&t.push(e.toggleVisible([...r]))}await Promise.all(t),await s.core.update(!0)}async getVisibilityMap(e,t){const s=[],i=[],r=this.components.get(ji);if(t)for(const n of t){const t=r.list.get(n);t&&(s.push(t.modelId),i.push(t.getItemsByVisibility(e)))}else for(const t of r.list.values())s.push(t.modelId),i.push(t.getItemsByVisibility(e));const n=await Promise.all(i),o={};for(const[e,t]of s.entries())o[t]=n[e];return o}};t(KF,"uuid","dd9ccf2d-8a21-4821-b7f6-2949add16a29");let JF=KF;const eO=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"onDisposed",new u),t(this,"list",new a.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 l.Box3;for(const t of this.list)e.union(t);return e}async addFromModelIdMap(e){const t=this.components.get(ji),s=new l.Box3;for(const[i,r]of Object.entries(e)){const e=t.list.get(i);if(!e)continue;const n=await e.getMergedBox([...r]);s.union(n)}this.list.add(s)}addFromModels(e){const t=this.components.get(ji);for(const[s,i]of t.list)e&&!e.some(e=>e.test(s))||this.list.add(i.box)}async getCenter(e){this.list.clear(),await this.addFromModelIdMap(e);const t=this.get();this.list.clear();const s=new l.Vector3;return t.getCenter(s),s}async getCameraOrientation(e,t=1){const s=this.components.get(ji);this.list.clear();for(const[e,t]of s.list)this.list.add(t.box);const i=this.get();this.list.clear();const r=new l.Vector3;i.getCenter(r);const n=new l.Vector3;i.getSize(n);const o=Math.max(n.x,n.y,n.z)*t,a=new l.Vector3;switch(e){case"front":default:a.set(r.x,r.y,r.z+o);break;case"back":a.set(r.x,r.y,r.z-o);break;case"left":a.set(r.x-o,r.y,r.z);break;case"right":a.set(r.x+o,r.y,r.z);break;case"top":a.set(r.x,r.y+o,r.z);break;case"bottom":a.set(r.x,r.y-o,r.z)}return{position:a,target:r}}};t(eO,"uuid","d1444724-dba6-4cdd-a0c7-68ee1450d166");let tO=eO;class sO{constructor(e,s){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=s}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:s}={force:!1,...e};if(this.result&&!s)return this.result;const i=this._components.get(rO),r=await i.getItems(this.queries,{modelIds:t,aggregation:this.aggregation});return this.cache&&(this.result=r),r}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(rO).list.getKey(this)??w.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 iO=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"list",new a.DataMap),s.add(e.uuid,this)}async getItems(e,t){let s;if(t){const{modelIds:e,items:i}=t;if(i){const e=Object.keys(i);e.length>0&&(s=e.map(e=>new RegExp(`^${e}$`)))}else e&&(s=e)}const i=(null==t?void 0:t.aggregation)??"exclusive",r=this.components.get(ji),n=await Promise.all(e.map(async e=>{const i={};return await Promise.all(Array.from(r.list).map(async([r,n])=>{var o;if(s&&!s.some(e=>e.test(r)))return;const a=null==(o=null==t?void 0:t.items)?void 0:o[r],l=await n.getItemsByQuery(e,{localIds:a?[...a]:void 0});i[r]=new Set(l)})),i}));return"inclusive"===i?Oe.join(n):Oe.intersect(n)}create(e,t){const s=new sO(this.components,t);return this.list.set(e,s),s}async addFromCategories(e){const t=new Set,s=this.components.get(ji);for(const[i,r]of s.list){if(e&&!e.some(e=>e.test(i)))continue;const s=(await r.getItemsWithGeometryCategories()).filter(e=>null!==e),n=new Set(s);for(const e of n)this.list.has(e)||(this.create(e,[{categories:[new RegExp(`^${e}$`)]}]),t.add(e))}return[...t]}import(e){const{data:t}=e,s=[];if(!t)return s;for(const e of t){const t=this.create(e.guid,[]);t.fromJSON(e),s.push(t)}return s}export(){const e=[];for(const[t,s]of this.list.entries()){const i={...s.toJSON(),name:t};e.push(i)}return{data:e}}};t(iO,"uuid","0da7ad77-f734-42ca-942f-a074adfd1e3a");let rO=iO;const nO=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"onDisposed",new u),t(this,"list",new a.DataMap),t(this,"defaultSaveFunction",e=>"value"in e.Name?e.Name.value:null),t(this,"onBeforeFragmentsDispose",async e=>{const{key:t,value:s}=e,i=await s.getLocalIds(),r={[t]:new Set(i)};this.removeItems(r)}),s.add(e.uuid,this),this.setupEvents();s.get(ji).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 a.DataMap,this.list.set(e,t)),t}getModelItems(e,t,s){const{map:i}=this.getGroupData(e,t);let r=i[s];return r||(r=new Set,i[s]=r),r}getGroupData(e,t){const s=this.components.get(rO),i=this.getClassificationGroups(e);let r=i.get(t);return r||(r={map:{},get:()=>new Promise(e=>{if(r)if(r.query){const{name:t,config:i}=r.query,n=s.list.get(t);if(!n)throw new Error("Classifier: the query name associated with the group doesn't exist in the ItemsFinder component");n.test(i).then(t=>{if(!r)return void e({});const s=Oe.join([t,r.map]);e(s)})}else e(r.map);else e({})})},i.set(t,r)),r}async aggregateItems(e,t,s){const i=(null==s?void 0:s.data)??void 0,r=(null==s?void 0:s.aggregationCallback)??this.defaultSaveFunction,n=this.components.get(ji),o=this.components.get(rO),a=await o.getItems([t],{modelIds:null==s?void 0:s.modelIds});for(const[t,s]of Object.entries(a)){const o=n.list.get(t);if(!o)continue;const a=(s,...i)=>{const r=this.getModelItems(e,s,t);for(const e of i)r.add(e)},l=await o.getItemsData([...s],i);for(const e of l)r(e,a)}}addGroupItems(e,t,s){const{map:i}=this.getGroupData(e,t);Oe.add(i,s)}setGroupQuery(e,t,s){this.getGroupData(e,t).query=s}async find(e){const t=[];for(const[s,i]of Object.entries(e)){const e=[],r=this.list.get(s);if(!r)continue;for(const t of i){const s=r.get(t);if(!s)continue;const i=await s.get();e.push(i)}const n=Oe.join(e);t.push(n)}return Oe.intersect(t)}async aggregateItemRelations(e,t,s,i){const r=(null==i?void 0:i.attribute)??"Name",n={relations:{[s]:{attributes:!0,relations:!1}}};await this.aggregateItems(e,t,{modelIds:null==i?void 0:i.modelIds,data:n,aggregationCallback:(e,t)=>{if(!(null==e?void 0:e[r]))return;const i=e[r];if(!("value"in i))return;const n=e[s];if(Array.isArray(n))for(const e of n)"value"in e._localId&&t(i.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(rO),s=await t.addFromCategories(null==e?void 0:e.modelIds);for(const t of s)this.setGroupQuery((null==e?void 0:e.classificationName)??"Categories",t,{name:t})}dispose(){this.list.clear();this.components.get(ji).list.onBeforeDelete.remove(this.onBeforeFragmentsDispose),this.onDisposed.trigger()}removeItems(e,t){if(t&&t.classificationName){const s=this.list.get(t.classificationName);if(!s)return;if(t.groupName){if(!s.get(t.groupName))return}for(const[,t]of s)Oe.remove(t.map,e);return}for(const[,t]of this.list.entries())for(const[,s]of t)Oe.remove(s.map,e)}async byModel(e){const t=this.components.get(ji),s=(null==e?void 0:e.classificationName)??"Models";for(const[i,r]of t.list){if(e&&e.modelIds&&!e.modelIds.some(e=>e.test(i)))continue;const t=await r.getItemsIdsWithGeometry(),n={[i]:new Set(t)};this.getGroupData(s,i),this.addGroupItems(s,i,n)}}};t(nO,"uuid","e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7");let oO=nO;class aO{constructor(e,s){t(this,"enabled",!0),t(this,"components"),t(this,"onDisposed",new u),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 l.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 i=s.renderer;if(!i)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=s,this.mouse=new je(i.three.domElement),this.components=e,this.setupRenderTarget(),this.setupFragmentListeners()}setupFragmentListeners(){const e=this.components.get(ji);e.list.onItemSet.add(()=>{this.colorsNeedUpdate=!0}),e.list.onItemDeleted.add(()=>{this.colorsNeedUpdate=!0})}setupRenderTarget(){const e=this.world.renderer.three.getSize(new l.Vector2);this.renderTargetSize.copy(e),this.renderTarget=new l.WebGLRenderTarget(e.x,e.y),this.renderTarget.texture.format=l.RGBAFormat,this.renderTarget.texture.type=l.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 l.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 s=0;s<e.length;s++)t=(t<<5)-t+e.charCodeAt(s),t&=t;let s=Math.abs(t)%16777215;0===s&&(s=1);const i=s>>16&255||1,r=s>>8&255||1,n=255&s||1;return new l.Color(i/255,r/255,n/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(ji);if(e.initialized){if(!this.colorsNeedUpdate){const t=new Set(e.list.keys()),s=new Set(this.modelIdToColor.keys());(t.size!==s.size||[...t].some(e=>!s.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),s=this.colorToId(e);this.colorToModelId.set(s,t),this.modelIdToColor.set(t,e);const i=new l.MeshBasicMaterial({color:e,depthTest:!0,depthWrite:!0});this.colorMaterials.set(t,i)}this.colorsNeedUpdate=!1}}}applyColorMaterials(){const e=this.components.get(ji);if(e.initialized)for(const[t,s]of e.list){const e=this.colorMaterials.get(t);e&&s.object.traverse(t=>{if(t instanceof l.Mesh){if("isLODGeometry"in t.geometry){const s=t.material[0].uniforms.lodColor;return this.originalLodColors.has(s)||this.originalLodColors.set(s,s.value),void(s.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,s=this.world.camera.three,i=e.getRenderTarget(),r=e.autoClear,n=new l.Color,o=e.getClearAlpha();e.getClearColor(n),this.applyColorMaterials(),e.setRenderTarget(this.renderTarget),e.autoClear=!0,e.setClearColor(0,1),e.clear(!0,!0,!1),e.render(t,s),e.setRenderTarget(i),e.autoClear=r,e.setClearColor(n,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,s=new Uint8Array(t.x*t.y*4);e.readRenderTargetPixels(this.renderTarget,0,0,t.x,t.y,s);const i=this.debugCanvas.getContext("2d");if(!i)return;const r=i.createImageData(t.x,t.y),n=4*t.x;for(let e=0;e<t.y;e++){const i=e*n,o=(t.y-1-e)*n;r.data.set(s.subarray(i,i+n),o)}i.putImageData(r,0,0)}async getModelAt(e){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const t=this.components.get(ji);if(!t.initialized||0===t.list.size)return null;this.assignColors(),this.renderColorCoded();const s=e||this.mouse.position,i=this.renderTargetSize,r=Math.floor(.5*(s.x+1)*i.x),n=Math.floor(.5*(s.y+1)*(i.y-1)),o=Math.max(0,Math.min(i.x-1,r)),a=Math.max(0,Math.min(i.y-1,n)),l=this.world.renderer.three,h=new Uint8Array(4);l.readRenderTargetPixels(this.renderTarget,o,a,1,1,h);const u=h[0]<<16|h[1]<<8|h[2];return this.colorToModelId.get(u)||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 lO=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"list",new Map),t(this,"onDisposed",new u),s.add(e.uuid,this)}get(e){if(this.list.has(e.uuid))return this.list.get(e.uuid);const t=new aO(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(lO,"uuid","4a82430c-7ff2-49ea-9401-60807502dad6");let hO=lO;class uO{constructor(e,s){t(this,"enabled",!0),t(this,"components"),t(this,"onDisposed",new u),t(this,"mouse"),t(this,"three",new l.Raycaster),t(this,"world"),t(this,"useFastModelPicking",!1);const i=s.renderer;if(!i)throw new Error("A renderer is needed for the raycaster to work!");this.world=s,this.mouse=new je(i.three.domElement),this.components=e}dispose(){this.mouse.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}castRayToObjects(e=Array.from(this.world.meshes),t=this.mouse.position){if(!this.world)throw new Error("A world is needed to cast rays!");const s=this.world.camera.three;return this.three.setFromCamera(t,s),this.intersect(e)}async castRay(e){const t=null==e?void 0:e.snappingClasses,s=(null==e?void 0:e.items)??Array.from(this.world.meshes),i=(null==e?void 0:e.position)??this.mouse.position;if(!this.world)throw new Error("A world is needed to cast rays!");const r=this.world.camera.three,n=this.components.get(ji),o=this.world.renderer.three.domElement,a=this.mouse.rawPosition;let l=null;if(n.initialized){if(this.useFastModelPicking){const e=this.components.get(hO).get(this.world),s=await e.getModelAt(i);if(s){const e=n.list.get(s);if(e)if(t&&t.length>0){const s=await e.raycastWithSnapping({camera:r,dom:o,mouse:a,snappingClasses:t});l=s&&s.length>0?s[0]:await e.raycast({camera:r,dom:o,mouse:a})}else l=await e.raycast({camera:r,dom:o,mouse:a})}}else l=await n.raycast({camera:r,dom:o,mouse:a,snappingClasses:t});if(0===s.length)return l}this.three.setFromCamera(i,r);const h=this.intersect(s);return l?h&&h.distance<l.distance?h:l:h}castRayFromVector(e,t,s=Array.from(this.world.meshes)){return this.three.set(e,t),this.intersect(s)}intersect(e=Array.from(this.world.meshes)){const t=this.three.intersectObjects(e),s=this.filterClippingPlanes(t);return s.length>0?s[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 s=t.clippingPlanes;return e.length<=0||!s||(null==s?void 0:s.length)<=0?e:e.filter(e=>s.every(t=>t.distanceToPoint(e.point)>0))}}const cO=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"list",new Map),t(this,"onDisposed",new u),s.add(e.uuid,this)}get(e){if(this.list.has(e.uuid))return this.list.get(e.uuid);const t=new uO(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(cO,"uuid","d5d8bdf0-db25-4952-b951-b643af207ace");let dO=cO;class pO extends c{constructor(){super(...arguments),t(this,"onCameraChanged",new u),t(this,"meshes",new Set),t(this,"onAfterUpdate",new u),t(this,"onBeforeUpdate",new u),t(this,"onDisposed",new u),t(this,"isDisposing",!1),t(this,"enabled",!0),t(this,"_dynamicAnchor",!1),t(this,"uuid",w.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(dO).get(this),s=await t.castRay();s&&s.point&&0===e.button&&this.camera.controls.setOrbitPoint(s.point.x,s.point.y,s.point.z)}),t(this,"_defaultCamera")}set dynamicAnchor(e){var t;const s=null==(t=this.renderer)?void 0:t.three.domElement.parentElement;if(!s)throw new Error("World: the renderer must have a parentElement to set dynamic anchoring.");e?(this.camera.controls&&(this.camera.controls.minDistance=.01),s.addEventListener("pointerdown",this.onPointerDown)):s.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(y);this.scene.dispose(),this.camera.isDisposeable()&&this.camera.dispose(),this.renderer&&this.renderer.dispose();for(const t of this.meshes)e.destroy(t);this.meshes.clear()}this._scene=null,this._camera=null,this._renderer=null;this.components.get(wO).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class mO{constructor(e,s){t(this,"_list"),t(this,"_scene"),this._list=e,this._scene=s}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 fO{constructor(e,s){t(this,"_list"),t(this,"_scene"),this._list=e,this._scene=s}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 gO extends ke{constructor(){super(...arguments),t(this,"_config",{backgroundColor:{value:new l.Color,type:"Color"},ambientLight:{color:{type:"Color",value:new l.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2}},directionalLight:{color:{type:"Color",value:new l.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2},position:{type:"Vector3",value:new l.Vector3}}}),t(this,"ambientLight",new fO(this._config,this._component)),t(this,"directionalLight",new mO(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 yO extends x{constructor(e){super(e),t(this,"onSetup",new u),t(this,"isSetup",!1),t(this,"three"),t(this,"config",new gO(this,this.components,"Scene")),t(this,"_defaultConfig",{backgroundColor:new l.Color(2107698),directionalLight:{color:new l.Color("white"),intensity:1.5,position:new l.Vector3(5,10,3)},ambientLight:{color:new l.Color("white"),intensity:1}}),this.three=new l.Scene,this.three.background=new l.Color(2107698)}setup(e){const t={...this._defaultConfig,...e};this.config.backgroundColor=t.backgroundColor;const s=t.ambientLight;this.config.ambientLight.color=s.color,this.config.ambientLight.intensity=s.intensity;const i=t.directionalLight;this.config.directionalLight.color=i.color,this.config.directionalLight.intensity=i.intensity,this.config.directionalLight.position=i.position,this.deleteAllLights();const{color:r,intensity:n}=this.config.directionalLight,o=new l.DirectionalLight(r,n);o.position.copy(i.position);const{color:a,intensity:h}=this.config.directionalLight,u=new l.AmbientLight(a,h);this.three.add(o,u),this.directionalLights.set(o.uuid,o),this.ambientLights.set(u.uuid,u),this.isSetup=!0,this.onSetup.trigger()}dispose(){super.dispose();this.components.get(Ge).list.delete(this.config.uuid)}}var xO=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTO=1]="AUTO",e))(xO||{});class bO extends m{constructor(e){super(e),t(this,"onBeforeUpdate",new u),t(this,"onAfterUpdate",new u),t(this,"onAspectUpdated",new u),t(this,"onDisposed",new u),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 l.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 s=this._allControls.get(e.uuid);s&&(s.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(ji),s=this.components.get(tO);s.list.clear();const i=new l.Sphere;if(e)await s.addFromModelIdMap(e);else for(const[,e]of t.list)s.list.add(e.box);return s.get().getBoundingSphere(i),s.list.clear(),i}setupCamera(){const e=window.innerWidth/window.innerHeight,t=new l.PerspectiveCamera(60,e,1,1e3);return t.position.set(50,50,50),t.lookAt(new l.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!");n.install({THREE:bO.getSubsetOfThree()});const{domElement:e}=this.currentWorld.renderer.three,t=new n(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:l.MOUSE,Vector2:l.Vector2,Vector3:l.Vector3,Vector4:l.Vector4,Quaternion:l.Quaternion,Matrix4:l.Matrix4,Spherical:l.Spherical,Box3:l.Box3,Sphere:l.Sphere,Raycaster:l.Raycaster,MathUtils:l.MathUtils}}}const _O=class e extends d{constructor(i){super(i),t(this,"onAfterUpdate",new u),t(this,"onBeforeUpdate",new u),t(this,"onDisposed",new u),t(this,"list",new s.DataMap),t(this,"enabled",!0),i.add(e.uuid,this)}create(){const e=new pO(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,s]of this.list)s.update(e)}};t(_O,"uuid","fdb61dc4-2ec1-4966-b83d-54ea795fad4a");let wO=_O;class vO extends ke{constructor(){super(...arguments),t(this,"_config",{visible:{value:!0,type:"Boolean"},color:{value:new l.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 TO{constructor(e,s){t(this,"onDisposed",new u),t(this,"onSetup",new u),t(this,"isSetup",!1),t(this,"world"),t(this,"components"),t(this,"config"),t(this,"_defaultConfig",{visible:!0,color:new l.Color(12303291),primarySize:1,secondarySize:10,distance:500}),t(this,"three"),t(this,"_fade",3),t(this,"updateZoom",()=>{this.world.camera instanceof bO&&(this.material.uniforms.uZoom.value=this.world.camera.three.zoom)}),this.world=s;const{color:i,primarySize:r,secondarySize:n,distance:o}=this._defaultConfig;this.components=e,this.config=new vO(this,this.components,"Grid");const a=new l.PlaneGeometry(2,2,1,1),h=new l.ShaderMaterial({side:l.DoubleSide,uniforms:{uSize1:{value:r},uSize2:{value:n},uColor:{value:i},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 l.Mesh(a,h),this.three.frustumCulled=!1,s.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(Ge).list.delete(this.config.uuid);this.components.get(y).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset(),this.world=null,this.components=null}setupEvents(e){if(this.world.isDisposing)return;if(!(this.world.camera instanceof bO))return;const t=this.world.camera.controls;e?t.addEventListener("update",this.updateZoom):t.removeEventListener("update",this.updateZoom)}}const SO=class e extends d{constructor(s){super(s),t(this,"list",new Map),t(this,"onDisposed",new u),t(this,"enabled",!0),s.add(e.uuid,this)}create(e){if(this.list.has(e.uuid))throw new Error("This world already has a grid!");const t=new TO(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(SO,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");let MO=SO;const AO=class e{constructor(){t(this,"onDisposed",new u),t(this,"list",new s.DataMap),t(this,"enabled",!1),t(this,"_clock"),t(this,"onInit",new u),t(this,"update",()=>{if(!this.enabled)return;const e=this._clock.getDelta();for(const[t,s]of this.list)s.enabled&&s.isUpdateable()&&s.update(e);requestAnimationFrame(this.update)}),this._clock=new l.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.");w.validate(e),this.list.set(e,t)}get(e){var t;const s=e.uuid;if(!this.list.has(s)){const i=new e(this);return(null==(t=i.isDisposeable)?void 0:t.call(i))&&i.onDisposed.add(()=>this.list.delete(s)),this.list.has(s)||this.add(s,i),i}return this.list.get(s)}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,s]of this.list)s.enabled=!1,t!==ji.uuid?s.isDisposeable()&&s.dispose():e=s;null==e||e.dispose(),this._clock.stop(),this.onDisposed.trigger()}static setupBVH(){l.BufferGeometry.prototype.computeBoundsTree=ki,l.BufferGeometry.prototype.disposeBoundsTree=Ui,l.Mesh.prototype.raycast=Vi,l.LineSegments.prototype.raycast=Vi}};t(AO,"release","2.4.3");let NO=AO;class EO{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 l.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=n.ACTION.DOLLY,e.touches.two=n.ACTION.TOUCH_ZOOM_TRUCK}}class CO{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 l.Vector3;e.getPosition(t);const s=t.length();e.distance=s,e.truckSpeed=2;const{rotation:i}=this.camera.three,r=new l.Vector3(0,0,-1).applyEuler(i),n=t.addScaledVector(r,s);e.moveTo(n.x,n.y,n.z)}}class RO{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=n.ACTION.TRUCK,t.touches.one=n.ACTION.TOUCH_TRUCK,t.touches.two=n.ACTION.TOUCH_ZOOM):(t.mouseButtons.left=n.ACTION.ROTATE,t.touches.one=this.mouseAction1,t.touches.two=this.mouseAction2)}}class PO{constructor(e){t(this,"onChanged",new u),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:s}=e;this.setupOrthoCamera(s,t),this.camera=this._component.threeOrtho,this.current="Orthographic"}getPerspectiveDims(){const e=this._component.currentWorld;if(!e||!e.renderer)return null;const t=new l.Vector3;this._component.threePersp.getWorldDirection(t);const s=new l.Vector3;this._component.controls.getTarget(s);const i=s.clone().sub(this._component.threePersp.position).dot(t),r=e.renderer.getSize(),n=r.x/r.y,o=this._component.threePersp,a=2*i*Math.atan(o.fov*(Math.PI/180)/2);return{width:a*n,height:a}}setupOrthoCamera(e,t){this._component.controls.mouseButtons.wheel=n.ACTION.ZOOM,this._component.controls.mouseButtons.middle=n.ACTION.ZOOM;const s=this._component.threePersp,i=this._component.threeOrtho;i.zoom=1,i.left=t/-2,i.right=t/2,i.top=e/2,i.bottom=e/-2,i.updateProjectionMatrix(),i.position.copy(s.position),i.quaternion.copy(s.quaternion),this._component.controls.camera=i}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=n.ACTION.DOLLY,this._component.controls.mouseButtons.middle=n.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=n.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 BO extends bO{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 PO(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 CO(this)),this._navigationModes.set("FirstPerson",new EO(this)),this._navigationModes.set("Plan",new RO(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 s=Number.MAX_VALUE,i=Number.MIN_VALUE,r=new l.Vector3(s,s,s),n=new l.Vector3(i,i,i);for(const t of e){const e=(new l.Box3).setFromObject(t);e.min.x<r.x&&(r.x=e.min.x),e.min.y<r.y&&(r.y=e.min.y),e.min.z<r.z&&(r.z=e.min.z),e.max.x>n.x&&(n.x=e.max.x),e.max.y>n.y&&(n.y=e.max.y),e.max.z>n.z&&(n.z=e.max.z)}const o=new l.Box3(r,n),a=this.components.get(ji);if(a.initialized)for(const[,e]of a.list){const t=e.box;t.min.x<r.x&&(r.x=t.min.x),t.min.y<r.y&&(r.y=t.min.y),t.min.z<r.z&&(r.z=t.min.z),t.max.x>n.x&&(n.x=t.max.x),t.max.y>n.y&&(n.y=t.max.y),t.max.z>n.z&&(n.z=t.max.z)}const h=new l.Vector3;o.getSize(h);const u=new l.Vector3;o.getCenter(u);const c=Math.max(h.x,h.y,h.z)*t,d=new l.Sphere(u,c);await this.controls.fitToSphere(d,!0)}setUserInput(e){e?this.enableUserInput():this.disableUserInput()}addCustomNavigationMode(e){this._navigationModes.set(e.id,e)}disableUserInput(){this._userInputButtons.left=this.controls.mouseButtons.left,this._userInputButtons.right=this.controls.mouseButtons.right,this._userInputButtons.middle=this.controls.mouseButtons.middle,this._userInputButtons.wheel=this.controls.mouseButtons.wheel,this.controls.mouseButtons.left=0,this.controls.mouseButtons.right=0,this.controls.mouseButtons.middle=0,this.controls.mouseButtons.wheel=0}enableUserInput(){0!==Object.keys(this._userInputButtons).length&&(this.controls.mouseButtons.left=this._userInputButtons.left,this.controls.mouseButtons.right=this._userInputButtons.right,this.controls.mouseButtons.middle=this._userInputButtons.middle,this.controls.mouseButtons.wheel=this._userInputButtons.wheel)}newOrthoCamera(){const e=window.innerWidth/window.innerHeight;return new l.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,s=this.threeOrtho.right,i=t*(e.y/this.previousSize.y),r=s*(e.x/this.previousSize.x);this.threeOrtho.left=-r,this.threeOrtho.right=r,this.threeOrtho.top=i,this.threeOrtho.bottom=-i,this.threeOrtho.updateProjectionMatrix(),this.previousSize.copy(e)}}var IO="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function DO(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function LO(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 FO={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 '&#xD;'");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:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function 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:{}};
17
2
  /*!
18
3
 
19
4
  JSZip v3.10.1 - A JavaScript class for generating and reading zip files
@@ -24,4 +9,4 @@ Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/js
24
9
 
25
10
  JSZip uses the library pako released under the MIT license :
26
11
  https://github.com/nodeca/pako/blob/main/LICENSE
27
- */const OO=DO(FO.exports=function e(t,s,i){function r(o,a){if(!s[o]){if(!t[o]){if(!a&&LO)return LO(o);if(n)return n(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var h=s[o]={exports:{}};t[o][0].call(h.exports,function(e){return r(t[o][1][e]||e)},h,h.exports,e,t,s,i)}return s[o].exports}for(var n=LO,o=0;o<i.length;o++)r(i[o]);return r}({1:[function(e,t,s){var i=e("./utils"),r=e("./support"),n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";s.encode=function(e){for(var t,s,r,o,a,l,h,u=[],c=0,d=e.length,p=d,m="string"!==i.getTypeOf(e);c<e.length;)p=d-c,r=m?(t=e[c++],s=c<d?e[c++]:0,c<d?e[c++]:0):(t=e.charCodeAt(c++),s=c<d?e.charCodeAt(c++):0,c<d?e.charCodeAt(c++):0),o=t>>2,a=(3&t)<<4|s>>4,l=1<p?(15&s)<<2|r>>6:64,h=2<p?63&r:64,u.push(n.charAt(o)+n.charAt(a)+n.charAt(l)+n.charAt(h));return u.join("")},s.decode=function(e){var t,s,i,o,a,l,h=0,u=0,c="data:";if(e.substr(0,c.length)===c)throw new Error("Invalid base64 input, it looks like a data url.");var d,p=3*(e=e.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(e.charAt(e.length-1)===n.charAt(64)&&p--,e.charAt(e.length-2)===n.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(d=r.uint8array?new Uint8Array(0|p):new Array(0|p);h<e.length;)t=n.indexOf(e.charAt(h++))<<2|(o=n.indexOf(e.charAt(h++)))>>4,s=(15&o)<<4|(a=n.indexOf(e.charAt(h++)))>>2,i=(3&a)<<6|(l=n.indexOf(e.charAt(h++))),d[u++]=t,64!==a&&(d[u++]=s),64!==l&&(d[u++]=i);return d}},{"./support":30,"./utils":32}],2:[function(e,t,s){var i=e("./external"),r=e("./stream/DataWorker"),n=e("./stream/Crc32Probe"),o=e("./stream/DataLengthProbe");function a(e,t,s,i,r){this.compressedSize=e,this.uncompressedSize=t,this.crc32=s,this.compression=i,this.compressedContent=r}a.prototype={getContentWorker:function(){var e=new r(i.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new r(i.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(e,t,s){return e.pipe(new n).pipe(new o("uncompressedSize")).pipe(t.compressWorker(s)).pipe(new o("compressedSize")).withStreamInfo("compression",t)},t.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,s){var i=e("./stream/GenericWorker");s.STORE={magic:"\0\0",compressWorker:function(){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},s.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,s){var i=e("./utils"),r=function(){for(var e,t=[],s=0;s<256;s++){e=s;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[s]=e}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==i.getTypeOf(e)?function(e,t,s,i){var n=r,o=i+s;e^=-1;for(var a=i;a<o;a++)e=e>>>8^n[255&(e^t[a])];return-1^e}(0|t,e,e.length,0):function(e,t,s,i){var n=r,o=i+s;e^=-1;for(var a=i;a<o;a++)e=e>>>8^n[255&(e^t.charCodeAt(a))];return-1^e}(0|t,e,e.length,0):0}},{"./utils":32}],5:[function(e,t,s){s.base64=!1,s.binary=!1,s.dir=!1,s.createFolders=!0,s.date=null,s.compression=null,s.compressionOptions=null,s.comment=null,s.unixPermissions=null,s.dosPermissions=null},{}],6:[function(e,t,s){var i=null;i="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:i}},{lie:37}],7:[function(e,t,s){var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,r=e("pako"),n=e("./utils"),o=e("./stream/GenericWorker"),a=i?"uint8array":"array";function l(e,t){o.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}s.magic="\b\0",n.inherits(l,o),l.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(n.transformTo(a,e.data),!1)},l.prototype.flush=function(){o.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},l.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this._pako=null},l.prototype._createPako=function(){this._pako=new r[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},s.compressWorker=function(e){return new l("Deflate",e)},s.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,s){function i(e,t){var s,i="";for(s=0;s<t;s++)i+=String.fromCharCode(255&e),e>>>=8;return i}function r(e,t,s,r,o,u){var c,d,p=e.file,m=e.compression,f=u!==a.utf8encode,g=n.transformTo("string",u(p.name)),y=n.transformTo("string",a.utf8encode(p.name)),x=p.comment,b=n.transformTo("string",u(x)),_=n.transformTo("string",a.utf8encode(x)),w=y.length!==p.name.length,v=_.length!==x.length,T="",S="",M="",A=p.dir,N=p.date,E={crc32:0,compressedSize:0,uncompressedSize:0};t&&!s||(E.crc32=e.crc32,E.compressedSize=e.compressedSize,E.uncompressedSize=e.uncompressedSize);var C=0;t&&(C|=8),f||!w&&!v||(C|=2048);var R,P,B,I=0,D=0;A&&(I|=16),"UNIX"===o?(D=798,I|=(R=p.unixPermissions,P=A,B=R,R||(B=P?16893:33204),(65535&B)<<16)):(D=20,I|=function(e){return 63&(e||0)}(p.dosPermissions)),c=N.getUTCHours(),c<<=6,c|=N.getUTCMinutes(),c<<=5,c|=N.getUTCSeconds()/2,d=N.getUTCFullYear()-1980,d<<=4,d|=N.getUTCMonth()+1,d<<=5,d|=N.getUTCDate(),w&&(S=i(1,1)+i(l(g),4)+y,T+="up"+i(S.length,2)+S),v&&(M=i(1,1)+i(l(b),4)+_,T+="uc"+i(M.length,2)+M);var L="";return L+="\n\0",L+=i(C,2),L+=m.magic,L+=i(c,2),L+=i(d,2),L+=i(E.crc32,4),L+=i(E.compressedSize,4),L+=i(E.uncompressedSize,4),L+=i(g.length,2),L+=i(T.length,2),{fileRecord:h.LOCAL_FILE_HEADER+L+g+T,dirRecord:h.CENTRAL_FILE_HEADER+i(D,2)+L+i(b.length,2)+"\0\0\0\0"+i(I,4)+i(r,4)+g+T+b}}var n=e("../utils"),o=e("../stream/GenericWorker"),a=e("../utf8"),l=e("../crc32"),h=e("../signature");function u(e,t,s,i){o.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=s,this.encodeFileName=i,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}n.inherits(u,o),u.prototype.push=function(e){var t=e.meta.percent||0,s=this.entriesCount,i=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,o.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:s?(t+100*(s-i-1))/s:100}}))},u.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var s=r(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:s.fileRecord,meta:{percent:0}})}else this.accumulate=!0},u.prototype.closedSource=function(e){this.accumulate=!1;var t,s=this.streamFiles&&!e.file.dir,n=r(e,s,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(n.dirRecord),s)this.push({data:(t=e,h.DATA_DESCRIPTOR+i(t.crc32,4)+i(t.compressedSize,4)+i(t.uncompressedSize,4)),meta:{percent:100}});else for(this.push({data:n.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},u.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var s,r,o,a,l,u,c=this.bytesWritten-e,d=(s=this.dirRecords.length,r=c,o=e,a=this.zipComment,l=this.encodeFileName,u=n.transformTo("string",l(a)),h.CENTRAL_DIRECTORY_END+"\0\0\0\0"+i(s,2)+i(s,2)+i(r,4)+i(o,4)+i(u.length,2)+u);this.push({data:d,meta:{percent:100}})},u.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},u.prototype.registerPrevious=function(e){this._sources.push(e);var t=this;return e.on("data",function(e){t.processChunk(e)}),e.on("end",function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end()}),e.on("error",function(e){t.error(e)}),this},u.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},u.prototype.error=function(e){var t=this._sources;if(!o.prototype.error.call(this,e))return!1;for(var s=0;s<t.length;s++)try{t[s].error(e)}catch(e){}return!0},u.prototype.lock=function(){o.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock()},t.exports=u},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(e,t,s){var i=e("../compressions"),r=e("./ZipFileWorker");s.generateWorker=function(e,t,s){var n=new r(t.streamFiles,s,t.platform,t.encodeFileName),o=0;try{e.forEach(function(e,s){o++;var r=function(e,t){var s=e||t,r=i[s];if(!r)throw new Error(s+" is not a valid compression method !");return r}(s.options.compression,t.compression),a=s.options.compressionOptions||t.compressionOptions||{},l=s.dir,h=s.date;s._compressWorker(r,a).withStreamInfo("file",{name:e,dir:l,date:h,comment:s.comment||"",unixPermissions:s.unixPermissions,dosPermissions:s.dosPermissions}).pipe(n)}),n.entriesCount=o}catch(e){n.error(e)}return n}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(e,t,s){function i(){if(!(this instanceof i))return new i;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var e=new i;for(var t in this)"function"!=typeof this[t]&&(e[t]=this[t]);return e}}(i.prototype=e("./object")).loadAsync=e("./load"),i.support=e("./support"),i.defaults=e("./defaults"),i.version="3.10.1",i.loadAsync=function(e,t){return(new i).loadAsync(e,t)},i.external=e("./external"),t.exports=i},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(e,t,s){var i=e("./utils"),r=e("./external"),n=e("./utf8"),o=e("./zipEntries"),a=e("./stream/Crc32Probe"),l=e("./nodejsUtils");function h(e){return new r.Promise(function(t,s){var i=e.decompressed.getContentWorker().pipe(new a);i.on("error",function(e){s(e)}).on("end",function(){i.streamInfo.crc32!==e.decompressed.crc32?s(new Error("Corrupted zip : CRC32 mismatch")):t()}).resume()})}t.exports=function(e,t){var s=this;return t=i.extend(t||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:n.utf8decode}),l.isNode&&l.isStream(e)?r.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):i.prepareContent("the loaded zip file",e,!0,t.optimizedBinaryString,t.base64).then(function(e){var s=new o(t);return s.load(e),s}).then(function(e){var s=[r.Promise.resolve(e)],i=e.files;if(t.checkCRC32)for(var n=0;n<i.length;n++)s.push(h(i[n]));return r.Promise.all(s)}).then(function(e){for(var r=e.shift(),n=r.files,o=0;o<n.length;o++){var a=n[o],l=a.fileNameStr,h=i.resolve(a.fileNameStr);s.file(h,a.decompressed,{binary:!0,optimizedBinaryString:!0,date:a.date,dir:a.dir,comment:a.fileCommentStr.length?a.fileCommentStr:null,unixPermissions:a.unixPermissions,dosPermissions:a.dosPermissions,createFolders:t.createFolders}),a.dir||(s.file(h).unsafeOriginalName=l)}return r.zipComment.length&&(s.comment=r.zipComment),s})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(e,t,s){var i=e("../utils"),r=e("../stream/GenericWorker");function n(e,t){r.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=!1,this._bindStream(t)}i.inherits(n,r),n.prototype._bindStream=function(e){var t=this;(this._stream=e).pause(),e.on("data",function(e){t.push({data:e,meta:{percent:0}})}).on("error",function(e){t.isPaused?this.generatedError=e:t.error(e)}).on("end",function(){t.isPaused?t._upstreamEnded=!0:t.end()})},n.prototype.pause=function(){return!!r.prototype.pause.call(this)&&(this._stream.pause(),!0)},n.prototype.resume=function(){return!!r.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},t.exports=n},{"../stream/GenericWorker":28,"../utils":32}],13:[function(e,t,s){var i=e("readable-stream").Readable;function r(e,t,s){i.call(this,t),this._helper=e;var r=this;e.on("data",function(e,t){r.push(e)||r._helper.pause(),s&&s(t)}).on("error",function(e){r.emit("error",e)}).on("end",function(){r.push(null)})}e("../utils").inherits(r,i),r.prototype._read=function(){this._helper.resume()},t.exports=r},{"../utils":32,"readable-stream":16}],14:[function(e,t,s){t.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if("number"==typeof e)throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&"function"==typeof e.on&&"function"==typeof e.pause&&"function"==typeof e.resume}}},{}],15:[function(e,t,s){function i(e,t,s){var i,r=n.getTypeOf(t),a=n.extend(s||{},l);a.date=a.date||new Date,null!==a.compression&&(a.compression=a.compression.toUpperCase()),"string"==typeof a.unixPermissions&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&16384&a.unixPermissions&&(a.dir=!0),a.dosPermissions&&16&a.dosPermissions&&(a.dir=!0),a.dir&&(e=f(e)),a.createFolders&&(i=m(e))&&g.call(this,i,!0);var c="string"===r&&!1===a.binary&&!1===a.base64;s&&void 0!==s.binary||(a.binary=!c),(t instanceof h&&0===t.uncompressedSize||a.dir||!t||0===t.length)&&(a.base64=!1,a.binary=!0,t="",a.compression="STORE",r="string");var y=null;y=t instanceof h||t instanceof o?t:d.isNode&&d.isStream(t)?new p(e,t):n.prepareContent(e,t,a.binary,a.optimizedBinaryString,a.base64);var x=new u(e,y,a);this.files[e]=x}var r=e("./utf8"),n=e("./utils"),o=e("./stream/GenericWorker"),a=e("./stream/StreamHelper"),l=e("./defaults"),h=e("./compressedObject"),u=e("./zipObject"),c=e("./generate"),d=e("./nodejsUtils"),p=e("./nodejs/NodejsStreamInputAdapter"),m=function(e){"/"===e.slice(-1)&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return 0<t?e.substring(0,t):""},f=function(e){return"/"!==e.slice(-1)&&(e+="/"),e},g=function(e,t){return t=void 0!==t?t:l.createFolders,e=f(e),this.files[e]||i.call(this,e,null,{dir:!0,createFolders:t}),this.files[e]};function y(e){return"[object RegExp]"===Object.prototype.toString.call(e)}var x={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,s,i;for(t in this.files)i=this.files[t],(s=t.slice(this.root.length,t.length))&&t.slice(0,this.root.length)===this.root&&e(s,i)},filter:function(e){var t=[];return this.forEach(function(s,i){e(s,i)&&t.push(i)}),t},file:function(e,t,s){if(1!==arguments.length)return e=this.root+e,i.call(this,e,t,s),this;if(y(e)){var r=e;return this.filter(function(e,t){return!t.dir&&r.test(e)})}var n=this.files[this.root+e];return n&&!n.dir?n:null},folder:function(e){if(!e)return this;if(y(e))return this.filter(function(t,s){return s.dir&&e.test(t)});var t=this.root+e,s=g.call(this,t),i=this.clone();return i.root=s.name,i},remove:function(e){e=this.root+e;var t=this.files[e];if(t||("/"!==e.slice(-1)&&(e+="/"),t=this.files[e]),t&&!t.dir)delete this.files[e];else for(var s=this.filter(function(t,s){return s.name.slice(0,e.length)===e}),i=0;i<s.length;i++)delete this.files[s[i].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(e){var t,s={};try{if((s=n.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:r.utf8encode})).type=s.type.toLowerCase(),s.compression=s.compression.toUpperCase(),"binarystring"===s.type&&(s.type="string"),!s.type)throw new Error("No output type specified.");n.checkSupport(s.type),"darwin"!==s.platform&&"freebsd"!==s.platform&&"linux"!==s.platform&&"sunos"!==s.platform||(s.platform="UNIX"),"win32"===s.platform&&(s.platform="DOS");var i=s.comment||this.comment||"";t=c.generateWorker(this,s,i)}catch(e){(t=new o("error")).error(e)}return new a(t,s.type||"string",s.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return(e=e||{}).type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};t.exports=x},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(e,t,s){t.exports=e("stream")},{stream:void 0}],17:[function(e,t,s){var i=e("./DataReader");function r(e){i.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=255&e[t]}e("../utils").inherits(r,i),r.prototype.byteAt=function(e){return this.data[this.zero+e]},r.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),s=e.charCodeAt(1),i=e.charCodeAt(2),r=e.charCodeAt(3),n=this.length-4;0<=n;--n)if(this.data[n]===t&&this.data[n+1]===s&&this.data[n+2]===i&&this.data[n+3]===r)return n-this.zero;return-1},r.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),s=e.charCodeAt(1),i=e.charCodeAt(2),r=e.charCodeAt(3),n=this.readData(4);return t===n[0]&&s===n[1]&&i===n[2]&&r===n[3]},r.prototype.readData=function(e){if(this.checkOffset(e),0===e)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=r},{"../utils":32,"./DataReader":18}],18:[function(e,t,s){var i=e("../utils");function r(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}r.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e},skip:function(e){this.setIndex(this.index+e)},byteAt:function(){},readInt:function(e){var t,s=0;for(this.checkOffset(e),t=this.index+e-1;t>=this.index;t--)s=(s<<8)+this.byteAt(t);return this.index+=e,s},readString:function(e){return i.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=r},{"../utils":32}],19:[function(e,t,s){var i=e("./Uint8ArrayReader");function r(e){i.call(this,e)}e("../utils").inherits(r,i),r.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=r},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,s){var i=e("./DataReader");function r(e){i.call(this,e)}e("../utils").inherits(r,i),r.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},r.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},r.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},r.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=r},{"../utils":32,"./DataReader":18}],21:[function(e,t,s){var i=e("./ArrayReader");function r(e){i.call(this,e)}e("../utils").inherits(r,i),r.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=r},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,s){var i=e("../utils"),r=e("../support"),n=e("./ArrayReader"),o=e("./StringReader"),a=e("./NodeBufferReader"),l=e("./Uint8ArrayReader");t.exports=function(e){var t=i.getTypeOf(e);return i.checkSupport(t),"string"!==t||r.uint8array?"nodebuffer"===t?new a(e):r.uint8array?new l(i.transformTo("uint8array",e)):new n(i.transformTo("array",e)):new o(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,s){s.LOCAL_FILE_HEADER="PK",s.CENTRAL_FILE_HEADER="PK",s.CENTRAL_DIRECTORY_END="PK",s.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",s.ZIP64_CENTRAL_DIRECTORY_END="PK",s.DATA_DESCRIPTOR="PK\b"},{}],24:[function(e,t,s){var i=e("./GenericWorker"),r=e("../utils");function n(e){i.call(this,"ConvertWorker to "+e),this.destType=e}r.inherits(n,i),n.prototype.processChunk=function(e){this.push({data:r.transformTo(this.destType,e.data),meta:e.meta})},t.exports=n},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,s){var i=e("./GenericWorker"),r=e("../crc32");function n(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(n,i),n.prototype.processChunk=function(e){this.streamInfo.crc32=r(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=n},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,s){var i=e("../utils"),r=e("./GenericWorker");function n(e){r.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}i.inherits(n,r),n.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}r.prototype.processChunk.call(this,e)},t.exports=n},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,s){var i=e("../utils"),r=e("./GenericWorker");function n(e){r.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=i.getTypeOf(e),t.isPaused||t._tickAndRepeat()},function(e){t.error(e)})}i.inherits(n,r),n.prototype.cleanUp=function(){r.prototype.cleanUp.call(this),this.data=null},n.prototype.resume=function(){return!!r.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},n.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},n.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=n},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,s){function i(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}i.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var s=0;s<this._listeners[e].length;s++)this._listeners[e][s].call(this,t)},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",function(e){t.processChunk(e)}),e.on("end",function(){t.end()}),e.on("error",function(e){t.error(e)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var e=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),e=!0),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e)},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}},t.exports=i},{}],29:[function(e,t,s){var i=e("../utils"),r=e("./ConvertWorker"),n=e("./GenericWorker"),o=e("../base64"),a=e("../support"),l=e("../external"),h=null;if(a.nodestream)try{h=e("../nodejs/NodejsStreamOutputAdapter")}catch(e){}function u(e,t){return new l.Promise(function(s,r){var n=[],a=e._internalType,l=e._outputType,h=e._mimeType;e.on("data",function(e,s){n.push(e),t&&t(s)}).on("error",function(e){n=[],r(e)}).on("end",function(){try{var e=function(e,t,s){switch(e){case"blob":return i.newBlob(i.transformTo("arraybuffer",t),s);case"base64":return o.encode(t);default:return i.transformTo(e,t)}}(l,function(e,t){var s,i=0,r=null,n=0;for(s=0;s<t.length;s++)n+=t[s].length;switch(e){case"string":return t.join("");case"array":return Array.prototype.concat.apply([],t);case"uint8array":for(r=new Uint8Array(n),s=0;s<t.length;s++)r.set(t[s],i),i+=t[s].length;return r;case"nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}(a,n),h);s(e)}catch(e){r(e)}n=[]}).resume()})}function c(e,t,s){var o=t;switch(t){case"blob":case"arraybuffer":o="uint8array";break;case"base64":o="string"}try{this._internalType=o,this._outputType=t,this._mimeType=s,i.checkSupport(o),this._worker=e.pipe(new r(o)),e.lock()}catch(e){this._worker=new n("error"),this._worker.error(e)}}c.prototype={accumulate:function(e){return u(this,e)},on:function(e,t){var s=this;return"data"===e?this._worker.on(e,function(e){t.call(s,e.data,e.meta)}):this._worker.on(e,function(){i.delay(t,arguments,s)}),this},resume:function(){return i.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){if(i.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new h(this,{objectMode:"nodebuffer"!==this._outputType},e)}},t.exports=c},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(e,t,s){if(s.base64=!0,s.array=!0,s.string=!0,s.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,s.nodebuffer="undefined"!=typeof Buffer,s.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)s.blob=!1;else{var i=new ArrayBuffer(0);try{s.blob=0===new Blob([i],{type:"application/zip"}).size}catch(e){try{var r=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);r.append(i),s.blob=0===r.getBlob("application/zip").size}catch(e){s.blob=!1}}}try{s.nodestream=!!e("readable-stream").Readable}catch(e){s.nodestream=!1}},{"readable-stream":16}],31:[function(e,t,s){for(var i=e("./utils"),r=e("./support"),n=e("./nodejsUtils"),o=e("./stream/GenericWorker"),a=new Array(256),l=0;l<256;l++)a[l]=252<=l?6:248<=l?5:240<=l?4:224<=l?3:192<=l?2:1;function h(){o.call(this,"utf-8 decode"),this.leftOver=null}function u(){o.call(this,"utf-8 encode")}a[254]=a[254]=1,s.utf8encode=function(e){return r.nodebuffer?n.newBufferFrom(e,"utf-8"):function(e){var t,s,i,n,o,a=e.length,l=0;for(n=0;n<a;n++)55296==(64512&(s=e.charCodeAt(n)))&&n+1<a&&56320==(64512&(i=e.charCodeAt(n+1)))&&(s=65536+(s-55296<<10)+(i-56320),n++),l+=s<128?1:s<2048?2:s<65536?3:4;for(t=r.uint8array?new Uint8Array(l):new Array(l),n=o=0;o<l;n++)55296==(64512&(s=e.charCodeAt(n)))&&n+1<a&&56320==(64512&(i=e.charCodeAt(n+1)))&&(s=65536+(s-55296<<10)+(i-56320),n++),s<128?t[o++]=s:(s<2048?t[o++]=192|s>>>6:(s<65536?t[o++]=224|s>>>12:(t[o++]=240|s>>>18,t[o++]=128|s>>>12&63),t[o++]=128|s>>>6&63),t[o++]=128|63&s);return t}(e)},s.utf8decode=function(e){return r.nodebuffer?i.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,s,r,n,o=e.length,l=new Array(2*o);for(t=s=0;t<o;)if((r=e[t++])<128)l[s++]=r;else if(4<(n=a[r]))l[s++]=65533,t+=n-1;else{for(r&=2===n?31:3===n?15:7;1<n&&t<o;)r=r<<6|63&e[t++],n--;1<n?l[s++]=65533:r<65536?l[s++]=r:(r-=65536,l[s++]=55296|r>>10&1023,l[s++]=56320|1023&r)}return l.length!==s&&(l.subarray?l=l.subarray(0,s):l.length=s),i.applyFromCharCode(l)}(e=i.transformTo(r.uint8array?"uint8array":"array",e))},i.inherits(h,o),h.prototype.processChunk=function(e){var t=i.transformTo(r.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(r.uint8array){var n=t;(t=new Uint8Array(n.length+this.leftOver.length)).set(this.leftOver,0),t.set(n,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var o=function(e,t){var s;for((t=t||e.length)>e.length&&(t=e.length),s=t-1;0<=s&&128==(192&e[s]);)s--;return s<0||0===s?t:s+a[e[s]]>t?s:t}(t),l=t;o!==t.length&&(r.uint8array?(l=t.subarray(0,o),this.leftOver=t.subarray(o,t.length)):(l=t.slice(0,o),this.leftOver=t.slice(o,t.length))),this.push({data:s.utf8decode(l),meta:e.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:s.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},s.Utf8DecodeWorker=h,i.inherits(u,o),u.prototype.processChunk=function(e){this.push({data:s.utf8encode(e.data),meta:e.meta})},s.Utf8EncodeWorker=u},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,s){var i=e("./support"),r=e("./base64"),n=e("./nodejsUtils"),o=e("./external");function a(e){return e}function l(e,t){for(var s=0;s<e.length;++s)t[s]=255&e.charCodeAt(s);return t}e("setimmediate"),s.newBlob=function(e,t){s.checkSupport("blob");try{return new Blob([e],{type:t})}catch(s){try{var i=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return i.append(e),i.getBlob(t)}catch(e){throw new Error("Bug : can't construct the Blob.")}}};var h={stringifyByChunk:function(e,t,s){var i=[],r=0,n=e.length;if(n<=s)return String.fromCharCode.apply(null,e);for(;r<n;)"array"===t||"nodebuffer"===t?i.push(String.fromCharCode.apply(null,e.slice(r,Math.min(r+s,n)))):i.push(String.fromCharCode.apply(null,e.subarray(r,Math.min(r+s,n)))),r+=s;return i.join("")},stringifyByChar:function(e){for(var t="",s=0;s<e.length;s++)t+=String.fromCharCode(e[s]);return t},applyCanBeUsed:{uint8array:function(){try{return i.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(e){return!1}}(),nodebuffer:function(){try{return i.nodebuffer&&1===String.fromCharCode.apply(null,n.allocBuffer(1)).length}catch(e){return!1}}()}};function u(e){var t=65536,i=s.getTypeOf(e),r=!0;if("uint8array"===i?r=h.applyCanBeUsed.uint8array:"nodebuffer"===i&&(r=h.applyCanBeUsed.nodebuffer),r)for(;1<t;)try{return h.stringifyByChunk(e,i,t)}catch(e){t=Math.floor(t/2)}return h.stringifyByChar(e)}function c(e,t){for(var s=0;s<e.length;s++)t[s]=e[s];return t}s.applyFromCharCode=u;var d={};d.string={string:a,array:function(e){return l(e,new Array(e.length))},arraybuffer:function(e){return d.string.uint8array(e).buffer},uint8array:function(e){return l(e,new Uint8Array(e.length))},nodebuffer:function(e){return l(e,n.allocBuffer(e.length))}},d.array={string:u,array:a,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return n.newBufferFrom(e)}},d.arraybuffer={string:function(e){return u(new Uint8Array(e))},array:function(e){return c(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:a,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return n.newBufferFrom(new Uint8Array(e))}},d.uint8array={string:u,array:function(e){return c(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:a,nodebuffer:function(e){return n.newBufferFrom(e)}},d.nodebuffer={string:u,array:function(e){return c(e,new Array(e.length))},arraybuffer:function(e){return d.nodebuffer.uint8array(e).buffer},uint8array:function(e){return c(e,new Uint8Array(e.length))},nodebuffer:a},s.transformTo=function(e,t){if(t=t||"",!e)return t;s.checkSupport(e);var i=s.getTypeOf(t);return d[i][e](t)},s.resolve=function(e){for(var t=e.split("/"),s=[],i=0;i<t.length;i++){var r=t[i];"."===r||""===r&&0!==i&&i!==t.length-1||(".."===r?s.pop():s.push(r))}return s.join("/")},s.getTypeOf=function(e){return"string"==typeof e?"string":"[object Array]"===Object.prototype.toString.call(e)?"array":i.nodebuffer&&n.isBuffer(e)?"nodebuffer":i.uint8array&&e instanceof Uint8Array?"uint8array":i.arraybuffer&&e instanceof ArrayBuffer?"arraybuffer":void 0},s.checkSupport=function(e){if(!i[e.toLowerCase()])throw new Error(e+" is not supported by this platform")},s.MAX_VALUE_16BITS=65535,s.MAX_VALUE_32BITS=-1,s.pretty=function(e){var t,s,i="";for(s=0;s<(e||"").length;s++)i+="\\x"+((t=e.charCodeAt(s))<16?"0":"")+t.toString(16).toUpperCase();return i},s.delay=function(e,t,s){setImmediate(function(){e.apply(s||null,t||[])})},s.inherits=function(e,t){function s(){}s.prototype=t.prototype,e.prototype=new s},s.extend=function(){var e,t,s={};for(e=0;e<arguments.length;e++)for(t in arguments[e])Object.prototype.hasOwnProperty.call(arguments[e],t)&&void 0===s[t]&&(s[t]=arguments[e][t]);return s},s.prepareContent=function(e,t,n,a,h){return o.Promise.resolve(t).then(function(e){return i.blob&&(e instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(e)))&&"undefined"!=typeof FileReader?new o.Promise(function(t,s){var i=new FileReader;i.onload=function(e){t(e.target.result)},i.onerror=function(e){s(e.target.error)},i.readAsArrayBuffer(e)}):e}).then(function(t){var u,c=s.getTypeOf(t);return c?("arraybuffer"===c?t=s.transformTo("uint8array",t):"string"===c&&(h?t=r.decode(t):n&&!0!==a&&(t=l(u=t,i.uint8array?new Uint8Array(u.length):new Array(u.length)))),t):o.Promise.reject(new Error("Can't read the data of '"+e+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(e,t,s){var i=e("./reader/readerFor"),r=e("./utils"),n=e("./signature"),o=e("./zipEntry"),a=e("./support");function l(e){this.files=[],this.loadOptions=e}l.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+r.pretty(t)+", expected "+r.pretty(e)+")")}},isSignature:function(e,t){var s=this.reader.index;this.reader.setIndex(e);var i=this.reader.readString(4)===t;return this.reader.setIndex(s),i},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var e=this.reader.readData(this.zipCommentLength),t=a.uint8array?"uint8array":"array",s=r.transformTo(t,e);this.zipComment=this.loadOptions.decodeFileName(s)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var e,t,s,i=this.zip64EndOfCentralSize-44;0<i;)e=this.reader.readInt(2),t=this.reader.readInt(4),s=this.reader.readData(t),this.zip64ExtensibleData[e]={id:e,length:t,value:s}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(n.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes()},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(n.CENTRAL_FILE_HEADER);)(e=new o({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(e);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var e=this.reader.lastIndexOfSignature(n.CENTRAL_DIRECTORY_END);if(e<0)throw this.isSignature(0,n.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(e);var t=e;if(this.checkSignature(n.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===r.MAX_VALUE_16BITS||this.diskWithCentralDirStart===r.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===r.MAX_VALUE_16BITS||this.centralDirRecords===r.MAX_VALUE_16BITS||this.centralDirSize===r.MAX_VALUE_32BITS||this.centralDirOffset===r.MAX_VALUE_32BITS){if(this.zip64=!0,(e=this.reader.lastIndexOfSignature(n.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(n.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,n.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(n.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(n.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var s=this.centralDirOffset+this.centralDirSize;this.zip64&&(s+=20,s+=12+this.zip64EndOfCentralSize);var i=t-s;if(0<i)this.isSignature(t,n.CENTRAL_FILE_HEADER)||(this.reader.zero=i);else if(i<0)throw new Error("Corrupted zip: missing "+Math.abs(i)+" bytes.")},prepareReader:function(e){this.reader=i(e)},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},t.exports=l},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(e,t,s){var i=e("./reader/readerFor"),r=e("./utils"),n=e("./compressedObject"),o=e("./crc32"),a=e("./utf8"),l=e("./compressions"),h=e("./support");function u(e,t){this.options=e,this.loadOptions=t}u.prototype={isEncrypted:function(){return!(1&~this.bitFlag)},useUTF8:function(){return!(2048&~this.bitFlag)},readLocalPart:function(e){var t,s;if(e.skip(22),this.fileNameLength=e.readInt(2),s=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.skip(s),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(t=function(e){for(var t in l)if(Object.prototype.hasOwnProperty.call(l,t)&&l[t].magic===e)return l[t];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+r.pretty(this.compressionMethod)+" unknown (inner file : "+r.transformTo("string",this.fileName)+")");this.decompressed=new n(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize))},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=i(this.extraFields[1].value);this.uncompressedSize===r.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===r.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===r.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===r.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t,s,i,r=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4<r;)t=e.readInt(2),s=e.readInt(2),i=e.readData(s),this.extraFields[t]={id:t,length:s,value:i};e.setIndex(r)},handleUTF8:function(){var e=h.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var t=this.findExtraFieldUnicodePath();if(null!==t)this.fileNameStr=t;else{var s=r.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(s)}var i=this.findExtraFieldUnicodeComment();if(null!==i)this.fileCommentStr=i;else{var n=r.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(n)}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=i(e.value);return 1!==t.readInt(1)||o(this.fileName)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=i(e.value);return 1!==t.readInt(1)||o(this.fileComment)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null}},t.exports=u},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(e,t,s){function i(e,t,s){this.name=e,this.dir=s.dir,this.date=s.date,this.comment=s.comment,this.unixPermissions=s.unixPermissions,this.dosPermissions=s.dosPermissions,this._data=t,this._dataBinary=s.binary,this.options={compression:s.compression,compressionOptions:s.compressionOptions}}var r=e("./stream/StreamHelper"),n=e("./stream/DataWorker"),o=e("./utf8"),a=e("./compressedObject"),l=e("./stream/GenericWorker");i.prototype={internalStream:function(e){var t=null,s="string";try{if(!e)throw new Error("No output type specified.");var i="string"===(s=e.toLowerCase())||"text"===s;"binarystring"!==s&&"text"!==s||(s="string"),t=this._decompressWorker();var n=!this._dataBinary;n&&!i&&(t=t.pipe(new o.Utf8EncodeWorker)),!n&&i&&(t=t.pipe(new o.Utf8DecodeWorker))}catch(e){(t=new l("error")).error(e)}return new r(t,s,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof a&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var s=this._decompressWorker();return this._dataBinary||(s=s.pipe(new o.Utf8EncodeWorker)),a.createWorkerFrom(s,e,t)},_decompressWorker:function(){return this._data instanceof a?this._data.getContentWorker():this._data instanceof l?this._data:new n(this._data)}};for(var h=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],u=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},c=0;c<h.length;c++)i.prototype[h[c]]=u;t.exports=i},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(e,t,s){(function(e){var s,i,r=e.MutationObserver||e.WebKitMutationObserver;if(r){var n=0,o=new r(u),a=e.document.createTextNode("");o.observe(a,{characterData:!0}),s=function(){a.data=n=++n%2}}else if(e.setImmediate||void 0===e.MessageChannel)s="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var t=e.document.createElement("script");t.onreadystatechange=function(){u(),t.onreadystatechange=null,t.parentNode.removeChild(t),t=null},e.document.documentElement.appendChild(t)}:function(){setTimeout(u,0)};else{var l=new e.MessageChannel;l.port1.onmessage=u,s=function(){l.port2.postMessage(0)}}var h=[];function u(){var e,t;i=!0;for(var s=h.length;s;){for(t=h,h=[],e=-1;++e<s;)t[e]();s=h.length}i=!1}t.exports=function(e){1!==h.push(e)||i||s()}}).call(this,void 0!==IO?IO:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(e,t,s){var i=e("immediate");function r(){}var n={},o=["REJECTED"],a=["FULFILLED"],l=["PENDING"];function h(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,e!==r&&p(this,e)}function u(e,t,s){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof s&&(this.onRejected=s,this.callRejected=this.otherCallRejected)}function c(e,t,s){i(function(){var i;try{i=t(s)}catch(t){return n.reject(e,t)}i===e?n.reject(e,new TypeError("Cannot resolve promise with itself")):n.resolve(e,i)})}function d(e){var t=e&&e.then;if(e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof t)return function(){t.apply(e,arguments)}}function p(e,t){var s=!1;function i(t){s||(s=!0,n.reject(e,t))}function r(t){s||(s=!0,n.resolve(e,t))}var o=m(function(){t(r,i)});"error"===o.status&&i(o.value)}function m(e,t){var s={};try{s.value=e(t),s.status="success"}catch(e){s.status="error",s.value=e}return s}(t.exports=h).prototype.finally=function(e){if("function"!=typeof e)return this;var t=this.constructor;return this.then(function(s){return t.resolve(e()).then(function(){return s})},function(s){return t.resolve(e()).then(function(){throw s})})},h.prototype.catch=function(e){return this.then(null,e)},h.prototype.then=function(e,t){if("function"!=typeof e&&this.state===a||"function"!=typeof t&&this.state===o)return this;var s=new this.constructor(r);return this.state!==l?c(s,this.state===a?e:t,this.outcome):this.queue.push(new u(s,e,t)),s},u.prototype.callFulfilled=function(e){n.resolve(this.promise,e)},u.prototype.otherCallFulfilled=function(e){c(this.promise,this.onFulfilled,e)},u.prototype.callRejected=function(e){n.reject(this.promise,e)},u.prototype.otherCallRejected=function(e){c(this.promise,this.onRejected,e)},n.resolve=function(e,t){var s=m(d,t);if("error"===s.status)return n.reject(e,s.value);var i=s.value;if(i)p(e,i);else{e.state=a,e.outcome=t;for(var r=-1,o=e.queue.length;++r<o;)e.queue[r].callFulfilled(t)}return e},n.reject=function(e,t){e.state=o,e.outcome=t;for(var s=-1,i=e.queue.length;++s<i;)e.queue[s].callRejected(t);return e},h.resolve=function(e){return e instanceof this?e:n.resolve(new this(r),e)},h.reject=function(e){var t=new this(r);return n.reject(t,e)},h.all=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var s=e.length,i=!1;if(!s)return this.resolve([]);for(var o=new Array(s),a=0,l=-1,h=new this(r);++l<s;)u(e[l],l);return h;function u(e,r){t.resolve(e).then(function(e){o[r]=e,++a!==s||i||(i=!0,n.resolve(h,o))},function(e){i||(i=!0,n.reject(h,e))})}},h.race=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var s=e.length,i=!1;if(!s)return this.resolve([]);for(var o,a=-1,l=new this(r);++a<s;)o=e[a],t.resolve(o).then(function(e){i||(i=!0,n.resolve(l,e))},function(e){i||(i=!0,n.reject(l,e))});return l}},{immediate:36}],38:[function(e,t,s){var i={};(0,e("./lib/utils/common").assign)(i,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=i},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(e,t,s){var i=e("./zlib/deflate"),r=e("./utils/common"),n=e("./utils/strings"),o=e("./zlib/messages"),a=e("./zlib/zstream"),l=Object.prototype.toString,h=0,u=-1,c=0,d=8;function p(e){if(!(this instanceof p))return new p(e);this.options=r.assign({level:u,method:d,chunkSize:16384,windowBits:15,memLevel:8,strategy:c,to:""},e||{});var t=this.options;t.raw&&0<t.windowBits?t.windowBits=-t.windowBits:t.gzip&&0<t.windowBits&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var s=i.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(s!==h)throw new Error(o[s]);if(t.header&&i.deflateSetHeader(this.strm,t.header),t.dictionary){var m;if(m="string"==typeof t.dictionary?n.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(s=i.deflateSetDictionary(this.strm,m))!==h)throw new Error(o[s]);this._dict_set=!0}}function m(e,t){var s=new p(t);if(s.push(e,!0),s.err)throw s.msg||o[s.err];return s.result}p.prototype.push=function(e,t){var s,o,a=this.strm,u=this.options.chunkSize;if(this.ended)return!1;o=t===~~t?t:!0===t?4:0,"string"==typeof e?a.input=n.string2buf(e):"[object ArrayBuffer]"===l.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new r.Buf8(u),a.next_out=0,a.avail_out=u),1!==(s=i.deflate(a,o))&&s!==h)return this.onEnd(s),!(this.ended=!0);0!==a.avail_out&&(0!==a.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(n.buf2binstring(r.shrinkBuf(a.output,a.next_out))):this.onData(r.shrinkBuf(a.output,a.next_out)))}while((0<a.avail_in||0===a.avail_out)&&1!==s);return 4===o?(s=i.deflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===h):2!==o||(this.onEnd(h),!(a.avail_out=0))},p.prototype.onData=function(e){this.chunks.push(e)},p.prototype.onEnd=function(e){e===h&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Deflate=p,s.deflate=m,s.deflateRaw=function(e,t){return(t=t||{}).raw=!0,m(e,t)},s.gzip=function(e,t){return(t=t||{}).gzip=!0,m(e,t)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(e,t,s){var i=e("./zlib/inflate"),r=e("./utils/common"),n=e("./utils/strings"),o=e("./zlib/constants"),a=e("./zlib/messages"),l=e("./zlib/zstream"),h=e("./zlib/gzheader"),u=Object.prototype.toString;function c(e){if(!(this instanceof c))return new c(e);this.options=r.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var s=i.inflateInit2(this.strm,t.windowBits);if(s!==o.Z_OK)throw new Error(a[s]);this.header=new h,i.inflateGetHeader(this.strm,this.header)}function d(e,t){var s=new c(t);if(s.push(e,!0),s.err)throw s.msg||a[s.err];return s.result}c.prototype.push=function(e,t){var s,a,l,h,c,d,p=this.strm,m=this.options.chunkSize,f=this.options.dictionary,g=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof e?p.input=n.binstring2buf(e):"[object ArrayBuffer]"===u.call(e)?p.input=new Uint8Array(e):p.input=e,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new r.Buf8(m),p.next_out=0,p.avail_out=m),(s=i.inflate(p,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&f&&(d="string"==typeof f?n.string2buf(f):"[object ArrayBuffer]"===u.call(f)?new Uint8Array(f):f,s=i.inflateSetDictionary(this.strm,d)),s===o.Z_BUF_ERROR&&!0===g&&(s=o.Z_OK,g=!1),s!==o.Z_STREAM_END&&s!==o.Z_OK)return this.onEnd(s),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&s!==o.Z_STREAM_END&&(0!==p.avail_in||a!==o.Z_FINISH&&a!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(l=n.utf8border(p.output,p.next_out),h=p.next_out-l,c=n.buf2string(p.output,l),p.next_out=h,p.avail_out=m-h,h&&r.arraySet(p.output,p.output,l,h,0),this.onData(c)):this.onData(r.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((0<p.avail_in||0===p.avail_out)&&s!==o.Z_STREAM_END);return s===o.Z_STREAM_END&&(a=o.Z_FINISH),a===o.Z_FINISH?(s=i.inflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===o.Z_OK):a!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),!(p.avail_out=0))},c.prototype.onData=function(e){this.chunks.push(e)},c.prototype.onEnd=function(e){e===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=r.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},s.Inflate=c,s.inflate=d,s.inflateRaw=function(e,t){return(t=t||{}).raw=!0,d(e,t)},s.ungzip=d},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(e,t,s){var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;s.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var s=t.shift();if(s){if("object"!=typeof s)throw new TypeError(s+"must be non-object");for(var i in s)s.hasOwnProperty(i)&&(e[i]=s[i])}}return e},s.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var r={arraySet:function(e,t,s,i,r){if(t.subarray&&e.subarray)e.set(t.subarray(s,s+i),r);else for(var n=0;n<i;n++)e[r+n]=t[s+n]},flattenChunks:function(e){var t,s,i,r,n,o;for(t=i=0,s=e.length;t<s;t++)i+=e[t].length;for(o=new Uint8Array(i),t=r=0,s=e.length;t<s;t++)n=e[t],o.set(n,r),r+=n.length;return o}},n={arraySet:function(e,t,s,i,r){for(var n=0;n<i;n++)e[r+n]=t[s+n]},flattenChunks:function(e){return[].concat.apply([],e)}};s.setTyped=function(e){e?(s.Buf8=Uint8Array,s.Buf16=Uint16Array,s.Buf32=Int32Array,s.assign(s,r)):(s.Buf8=Array,s.Buf16=Array,s.Buf32=Array,s.assign(s,n))},s.setTyped(i)},{}],42:[function(e,t,s){var i=e("./common"),r=!0,n=!0;try{String.fromCharCode.apply(null,[0])}catch(e){r=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){n=!1}for(var o=new i.Buf8(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function l(e,t){if(t<65537&&(e.subarray&&n||!e.subarray&&r))return String.fromCharCode.apply(null,i.shrinkBuf(e,t));for(var s="",o=0;o<t;o++)s+=String.fromCharCode(e[o]);return s}o[254]=o[254]=1,s.string2buf=function(e){var t,s,r,n,o,a=e.length,l=0;for(n=0;n<a;n++)55296==(64512&(s=e.charCodeAt(n)))&&n+1<a&&56320==(64512&(r=e.charCodeAt(n+1)))&&(s=65536+(s-55296<<10)+(r-56320),n++),l+=s<128?1:s<2048?2:s<65536?3:4;for(t=new i.Buf8(l),n=o=0;o<l;n++)55296==(64512&(s=e.charCodeAt(n)))&&n+1<a&&56320==(64512&(r=e.charCodeAt(n+1)))&&(s=65536+(s-55296<<10)+(r-56320),n++),s<128?t[o++]=s:(s<2048?t[o++]=192|s>>>6:(s<65536?t[o++]=224|s>>>12:(t[o++]=240|s>>>18,t[o++]=128|s>>>12&63),t[o++]=128|s>>>6&63),t[o++]=128|63&s);return t},s.buf2binstring=function(e){return l(e,e.length)},s.binstring2buf=function(e){for(var t=new i.Buf8(e.length),s=0,r=t.length;s<r;s++)t[s]=e.charCodeAt(s);return t},s.buf2string=function(e,t){var s,i,r,n,a=t||e.length,h=new Array(2*a);for(s=i=0;s<a;)if((r=e[s++])<128)h[i++]=r;else if(4<(n=o[r]))h[i++]=65533,s+=n-1;else{for(r&=2===n?31:3===n?15:7;1<n&&s<a;)r=r<<6|63&e[s++],n--;1<n?h[i++]=65533:r<65536?h[i++]=r:(r-=65536,h[i++]=55296|r>>10&1023,h[i++]=56320|1023&r)}return l(h,i)},s.utf8border=function(e,t){var s;for((t=t||e.length)>e.length&&(t=e.length),s=t-1;0<=s&&128==(192&e[s]);)s--;return s<0||0===s?t:s+o[e[s]]>t?s:t}},{"./common":41}],43:[function(e,t,s){t.exports=function(e,t,s,i){for(var r=65535&e,n=e>>>16&65535,o=0;0!==s;){for(s-=o=2e3<s?2e3:s;n=n+(r=r+t[i++]|0)|0,--o;);r%=65521,n%=65521}return r|n<<16}},{}],44:[function(e,t,s){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(e,t,s){var i=function(){for(var e,t=[],s=0;s<256;s++){e=s;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[s]=e}return t}();t.exports=function(e,t,s,r){var n=i,o=r+s;e^=-1;for(var a=r;a<o;a++)e=e>>>8^n[255&(e^t[a])];return-1^e}},{}],46:[function(e,t,s){var i,r=e("../utils/common"),n=e("./trees"),o=e("./adler32"),a=e("./crc32"),l=e("./messages"),h=0,u=4,c=0,d=-2,p=-1,m=4,f=2,g=8,y=9,x=286,b=30,_=19,w=2*x+1,v=15,T=3,S=258,M=S+T+1,A=42,N=113,E=1,C=2,R=3,P=4;function B(e,t){return e.msg=l[t],t}function I(e){return(e<<1)-(4<e?9:0)}function D(e){for(var t=e.length;0<=--t;)e[t]=0}function L(e){var t=e.state,s=t.pending;s>e.avail_out&&(s=e.avail_out),0!==s&&(r.arraySet(e.output,t.pending_buf,t.pending_out,s,e.next_out),e.next_out+=s,t.pending_out+=s,e.total_out+=s,e.avail_out-=s,t.pending-=s,0===t.pending&&(t.pending_out=0))}function F(e,t){n._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,L(e.strm)}function O(e,t){e.pending_buf[e.pending++]=t}function V(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function z(e,t){var s,i,r=e.max_chain_length,n=e.strstart,o=e.prev_length,a=e.nice_match,l=e.strstart>e.w_size-M?e.strstart-(e.w_size-M):0,h=e.window,u=e.w_mask,c=e.prev,d=e.strstart+S,p=h[n+o-1],m=h[n+o];e.prev_length>=e.good_match&&(r>>=2),a>e.lookahead&&(a=e.lookahead);do{if(h[(s=t)+o]===m&&h[s+o-1]===p&&h[s]===h[n]&&h[++s]===h[n+1]){n+=2,s++;do{}while(h[++n]===h[++s]&&h[++n]===h[++s]&&h[++n]===h[++s]&&h[++n]===h[++s]&&h[++n]===h[++s]&&h[++n]===h[++s]&&h[++n]===h[++s]&&h[++n]===h[++s]&&n<d);if(i=S-(d-n),n=d-S,o<i){if(e.match_start=t,a<=(o=i))break;p=h[n+o-1],m=h[n+o]}}}while((t=c[t&u])>l&&0!=--r);return o<=e.lookahead?o:e.lookahead}function k(e){var t,s,i,n,l,h,u,c,d,p,m=e.w_size;do{if(n=e.window_size-e.lookahead-e.strstart,e.strstart>=m+(m-M)){for(r.arraySet(e.window,e.window,m,m,0),e.match_start-=m,e.strstart-=m,e.block_start-=m,t=s=e.hash_size;i=e.head[--t],e.head[t]=m<=i?i-m:0,--s;);for(t=s=m;i=e.prev[--t],e.prev[t]=m<=i?i-m:0,--s;);n+=m}if(0===e.strm.avail_in)break;if(h=e.strm,u=e.window,c=e.strstart+e.lookahead,p=void 0,(d=n)<(p=h.avail_in)&&(p=d),s=0===p?0:(h.avail_in-=p,r.arraySet(u,h.input,h.next_in,p,c),1===h.state.wrap?h.adler=o(h.adler,u,p,c):2===h.state.wrap&&(h.adler=a(h.adler,u,p,c)),h.next_in+=p,h.total_in+=p,p),e.lookahead+=s,e.lookahead+e.insert>=T)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+T-1])&e.hash_mask,e.prev[l&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=l,l++,e.insert--,!(e.lookahead+e.insert<T)););}while(e.lookahead<M&&0!==e.strm.avail_in)}function U(e,t){for(var s,i;;){if(e.lookahead<M){if(k(e),e.lookahead<M&&t===h)return E;if(0===e.lookahead)break}if(s=0,e.lookahead>=T&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+T-1])&e.hash_mask,s=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==s&&e.strstart-s<=e.w_size-M&&(e.match_length=z(e,s)),e.match_length>=T)if(i=n._tr_tally(e,e.strstart-e.match_start,e.match_length-T),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=T){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+T-1])&e.hash_mask,s=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart,0!=--e.match_length;);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else i=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(i&&(F(e,!1),0===e.strm.avail_out))return E}return e.insert=e.strstart<T-1?e.strstart:T-1,t===u?(F(e,!0),0===e.strm.avail_out?R:P):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?E:C}function G(e,t){for(var s,i,r;;){if(e.lookahead<M){if(k(e),e.lookahead<M&&t===h)return E;if(0===e.lookahead)break}if(s=0,e.lookahead>=T&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+T-1])&e.hash_mask,s=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=T-1,0!==s&&e.prev_length<e.max_lazy_match&&e.strstart-s<=e.w_size-M&&(e.match_length=z(e,s),e.match_length<=5&&(1===e.strategy||e.match_length===T&&4096<e.strstart-e.match_start)&&(e.match_length=T-1)),e.prev_length>=T&&e.match_length<=e.prev_length){for(r=e.strstart+e.lookahead-T,i=n._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-T),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=r&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+T-1])&e.hash_mask,s=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!=--e.prev_length;);if(e.match_available=0,e.match_length=T-1,e.strstart++,i&&(F(e,!1),0===e.strm.avail_out))return E}else if(e.match_available){if((i=n._tr_tally(e,0,e.window[e.strstart-1]))&&F(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return E}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(i=n._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<T-1?e.strstart:T-1,t===u?(F(e,!0),0===e.strm.avail_out?R:P):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?E:C}function j(e,t,s,i,r){this.good_length=e,this.max_lazy=t,this.nice_length=s,this.max_chain=i,this.func=r}function $(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=g,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new r.Buf16(2*w),this.dyn_dtree=new r.Buf16(2*(2*b+1)),this.bl_tree=new r.Buf16(2*(2*_+1)),D(this.dyn_ltree),D(this.dyn_dtree),D(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new r.Buf16(v+1),this.heap=new r.Buf16(2*x+1),D(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new r.Buf16(2*x+1),D(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function W(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=f,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?A:N,e.adler=2===t.wrap?0:1,t.last_flush=h,n._tr_init(t),c):B(e,d)}function H(e){var t,s=W(e);return s===c&&((t=e.state).window_size=2*t.w_size,D(t.head),t.max_lazy_match=i[t.level].max_lazy,t.good_match=i[t.level].good_length,t.nice_match=i[t.level].nice_length,t.max_chain_length=i[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=T-1,t.match_available=0,t.ins_h=0),s}function q(e,t,s,i,n,o){if(!e)return d;var a=1;if(t===p&&(t=6),i<0?(a=0,i=-i):15<i&&(a=2,i-=16),n<1||y<n||s!==g||i<8||15<i||t<0||9<t||o<0||m<o)return B(e,d);8===i&&(i=9);var l=new $;return(e.state=l).strm=e,l.wrap=a,l.gzhead=null,l.w_bits=i,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=n+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+T-1)/T),l.window=new r.Buf8(2*l.w_size),l.head=new r.Buf16(l.hash_size),l.prev=new r.Buf16(l.w_size),l.lit_bufsize=1<<n+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new r.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=t,l.strategy=o,l.method=s,H(e)}i=[new j(0,0,0,0,function(e,t){var s=65535;for(s>e.pending_buf_size-5&&(s=e.pending_buf_size-5);;){if(e.lookahead<=1){if(k(e),0===e.lookahead&&t===h)return E;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var i=e.block_start+s;if((0===e.strstart||e.strstart>=i)&&(e.lookahead=e.strstart-i,e.strstart=i,F(e,!1),0===e.strm.avail_out))return E;if(e.strstart-e.block_start>=e.w_size-M&&(F(e,!1),0===e.strm.avail_out))return E}return e.insert=0,t===u?(F(e,!0),0===e.strm.avail_out?R:P):(e.strstart>e.block_start&&(F(e,!1),e.strm.avail_out),E)}),new j(4,4,8,4,U),new j(4,5,16,8,U),new j(4,6,32,32,U),new j(4,4,16,16,G),new j(8,16,32,32,G),new j(8,16,128,128,G),new j(8,32,128,256,G),new j(32,128,258,1024,G),new j(32,258,258,4096,G)],s.deflateInit=function(e,t){return q(e,t,g,15,8,0)},s.deflateInit2=q,s.deflateReset=H,s.deflateResetKeep=W,s.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?d:(e.state.gzhead=t,c):d},s.deflate=function(e,t){var s,r,o,l;if(!e||!e.state||5<t||t<0)return e?B(e,d):d;if(r=e.state,!e.output||!e.input&&0!==e.avail_in||666===r.status&&t!==u)return B(e,0===e.avail_out?-5:d);if(r.strm=e,s=r.last_flush,r.last_flush=t,r.status===A)if(2===r.wrap)e.adler=0,O(r,31),O(r,139),O(r,8),r.gzhead?(O(r,(r.gzhead.text?1:0)+(r.gzhead.hcrc?2:0)+(r.gzhead.extra?4:0)+(r.gzhead.name?8:0)+(r.gzhead.comment?16:0)),O(r,255&r.gzhead.time),O(r,r.gzhead.time>>8&255),O(r,r.gzhead.time>>16&255),O(r,r.gzhead.time>>24&255),O(r,9===r.level?2:2<=r.strategy||r.level<2?4:0),O(r,255&r.gzhead.os),r.gzhead.extra&&r.gzhead.extra.length&&(O(r,255&r.gzhead.extra.length),O(r,r.gzhead.extra.length>>8&255)),r.gzhead.hcrc&&(e.adler=a(e.adler,r.pending_buf,r.pending,0)),r.gzindex=0,r.status=69):(O(r,0),O(r,0),O(r,0),O(r,0),O(r,0),O(r,9===r.level?2:2<=r.strategy||r.level<2?4:0),O(r,3),r.status=N);else{var p=g+(r.w_bits-8<<4)<<8;p|=(2<=r.strategy||r.level<2?0:r.level<6?1:6===r.level?2:3)<<6,0!==r.strstart&&(p|=32),p+=31-p%31,r.status=N,V(r,p),0!==r.strstart&&(V(r,e.adler>>>16),V(r,65535&e.adler)),e.adler=1}if(69===r.status)if(r.gzhead.extra){for(o=r.pending;r.gzindex<(65535&r.gzhead.extra.length)&&(r.pending!==r.pending_buf_size||(r.gzhead.hcrc&&r.pending>o&&(e.adler=a(e.adler,r.pending_buf,r.pending-o,o)),L(e),o=r.pending,r.pending!==r.pending_buf_size));)O(r,255&r.gzhead.extra[r.gzindex]),r.gzindex++;r.gzhead.hcrc&&r.pending>o&&(e.adler=a(e.adler,r.pending_buf,r.pending-o,o)),r.gzindex===r.gzhead.extra.length&&(r.gzindex=0,r.status=73)}else r.status=73;if(73===r.status)if(r.gzhead.name){o=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=a(e.adler,r.pending_buf,r.pending-o,o)),L(e),o=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindex<r.gzhead.name.length?255&r.gzhead.name.charCodeAt(r.gzindex++):0,O(r,l)}while(0!==l);r.gzhead.hcrc&&r.pending>o&&(e.adler=a(e.adler,r.pending_buf,r.pending-o,o)),0===l&&(r.gzindex=0,r.status=91)}else r.status=91;if(91===r.status)if(r.gzhead.comment){o=r.pending;do{if(r.pending===r.pending_buf_size&&(r.gzhead.hcrc&&r.pending>o&&(e.adler=a(e.adler,r.pending_buf,r.pending-o,o)),L(e),o=r.pending,r.pending===r.pending_buf_size)){l=1;break}l=r.gzindex<r.gzhead.comment.length?255&r.gzhead.comment.charCodeAt(r.gzindex++):0,O(r,l)}while(0!==l);r.gzhead.hcrc&&r.pending>o&&(e.adler=a(e.adler,r.pending_buf,r.pending-o,o)),0===l&&(r.status=103)}else r.status=103;if(103===r.status&&(r.gzhead.hcrc?(r.pending+2>r.pending_buf_size&&L(e),r.pending+2<=r.pending_buf_size&&(O(r,255&e.adler),O(r,e.adler>>8&255),e.adler=0,r.status=N)):r.status=N),0!==r.pending){if(L(e),0===e.avail_out)return r.last_flush=-1,c}else if(0===e.avail_in&&I(t)<=I(s)&&t!==u)return B(e,-5);if(666===r.status&&0!==e.avail_in)return B(e,-5);if(0!==e.avail_in||0!==r.lookahead||t!==h&&666!==r.status){var m=2===r.strategy?function(e,t){for(var s;;){if(0===e.lookahead&&(k(e),0===e.lookahead)){if(t===h)return E;break}if(e.match_length=0,s=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,s&&(F(e,!1),0===e.strm.avail_out))return E}return e.insert=0,t===u?(F(e,!0),0===e.strm.avail_out?R:P):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?E:C}(r,t):3===r.strategy?function(e,t){for(var s,i,r,o,a=e.window;;){if(e.lookahead<=S){if(k(e),e.lookahead<=S&&t===h)return E;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=T&&0<e.strstart&&(i=a[r=e.strstart-1])===a[++r]&&i===a[++r]&&i===a[++r]){o=e.strstart+S;do{}while(i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&i===a[++r]&&r<o);e.match_length=S-(o-r),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=T?(s=n._tr_tally(e,1,e.match_length-T),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(s=n._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),s&&(F(e,!1),0===e.strm.avail_out))return E}return e.insert=0,t===u?(F(e,!0),0===e.strm.avail_out?R:P):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?E:C}(r,t):i[r.level].func(r,t);if(m!==R&&m!==P||(r.status=666),m===E||m===R)return 0===e.avail_out&&(r.last_flush=-1),c;if(m===C&&(1===t?n._tr_align(r):5!==t&&(n._tr_stored_block(r,0,0,!1),3===t&&(D(r.head),0===r.lookahead&&(r.strstart=0,r.block_start=0,r.insert=0))),L(e),0===e.avail_out))return r.last_flush=-1,c}return t!==u?c:r.wrap<=0?1:(2===r.wrap?(O(r,255&e.adler),O(r,e.adler>>8&255),O(r,e.adler>>16&255),O(r,e.adler>>24&255),O(r,255&e.total_in),O(r,e.total_in>>8&255),O(r,e.total_in>>16&255),O(r,e.total_in>>24&255)):(V(r,e.adler>>>16),V(r,65535&e.adler)),L(e),0<r.wrap&&(r.wrap=-r.wrap),0!==r.pending?c:1)},s.deflateEnd=function(e){var t;return e&&e.state?(t=e.state.status)!==A&&69!==t&&73!==t&&91!==t&&103!==t&&t!==N&&666!==t?B(e,d):(e.state=null,t===N?B(e,-3):c):d},s.deflateSetDictionary=function(e,t){var s,i,n,a,l,h,u,p,m=t.length;if(!e||!e.state)return d;if(2===(a=(s=e.state).wrap)||1===a&&s.status!==A||s.lookahead)return d;for(1===a&&(e.adler=o(e.adler,t,m,0)),s.wrap=0,m>=s.w_size&&(0===a&&(D(s.head),s.strstart=0,s.block_start=0,s.insert=0),p=new r.Buf8(s.w_size),r.arraySet(p,t,m-s.w_size,s.w_size,0),t=p,m=s.w_size),l=e.avail_in,h=e.next_in,u=e.input,e.avail_in=m,e.next_in=0,e.input=t,k(s);s.lookahead>=T;){for(i=s.strstart,n=s.lookahead-(T-1);s.ins_h=(s.ins_h<<s.hash_shift^s.window[i+T-1])&s.hash_mask,s.prev[i&s.w_mask]=s.head[s.ins_h],s.head[s.ins_h]=i,i++,--n;);s.strstart=i,s.lookahead=T-1,k(s)}return s.strstart+=s.lookahead,s.block_start=s.strstart,s.insert=s.lookahead,s.lookahead=0,s.match_length=s.prev_length=T-1,s.match_available=0,e.next_in=h,e.input=u,e.avail_in=l,s.wrap=a,c},s.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(e,t,s){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(e,t,s){t.exports=function(e,t){var s,i,r,n,o,a,l,h,u,c,d,p,m,f,g,y,x,b,_,w,v,T,S,M,A;s=e.state,i=e.next_in,M=e.input,r=i+(e.avail_in-5),n=e.next_out,A=e.output,o=n-(t-e.avail_out),a=n+(e.avail_out-257),l=s.dmax,h=s.wsize,u=s.whave,c=s.wnext,d=s.window,p=s.hold,m=s.bits,f=s.lencode,g=s.distcode,y=(1<<s.lenbits)-1,x=(1<<s.distbits)-1;e:do{m<15&&(p+=M[i++]<<m,m+=8,p+=M[i++]<<m,m+=8),b=f[p&y];t:for(;;){if(p>>>=_=b>>>24,m-=_,0==(_=b>>>16&255))A[n++]=65535&b;else{if(!(16&_)){if(!(64&_)){b=f[(65535&b)+(p&(1<<_)-1)];continue t}if(32&_){s.mode=12;break e}e.msg="invalid literal/length code",s.mode=30;break e}w=65535&b,(_&=15)&&(m<_&&(p+=M[i++]<<m,m+=8),w+=p&(1<<_)-1,p>>>=_,m-=_),m<15&&(p+=M[i++]<<m,m+=8,p+=M[i++]<<m,m+=8),b=g[p&x];s:for(;;){if(p>>>=_=b>>>24,m-=_,!(16&(_=b>>>16&255))){if(!(64&_)){b=g[(65535&b)+(p&(1<<_)-1)];continue s}e.msg="invalid distance code",s.mode=30;break e}if(v=65535&b,m<(_&=15)&&(p+=M[i++]<<m,(m+=8)<_&&(p+=M[i++]<<m,m+=8)),l<(v+=p&(1<<_)-1)){e.msg="invalid distance too far back",s.mode=30;break e}if(p>>>=_,m-=_,(_=n-o)<v){if(u<(_=v-_)&&s.sane){e.msg="invalid distance too far back",s.mode=30;break e}if(S=d,(T=0)===c){if(T+=h-_,_<w){for(w-=_;A[n++]=d[T++],--_;);T=n-v,S=A}}else if(c<_){if(T+=h+c-_,(_-=c)<w){for(w-=_;A[n++]=d[T++],--_;);if(T=0,c<w){for(w-=_=c;A[n++]=d[T++],--_;);T=n-v,S=A}}}else if(T+=c-_,_<w){for(w-=_;A[n++]=d[T++],--_;);T=n-v,S=A}for(;2<w;)A[n++]=S[T++],A[n++]=S[T++],A[n++]=S[T++],w-=3;w&&(A[n++]=S[T++],1<w&&(A[n++]=S[T++]))}else{for(T=n-v;A[n++]=A[T++],A[n++]=A[T++],A[n++]=A[T++],2<(w-=3););w&&(A[n++]=A[T++],1<w&&(A[n++]=A[T++]))}break}}break}}while(i<r&&n<a);i-=w=m>>3,p&=(1<<(m-=w<<3))-1,e.next_in=i,e.next_out=n,e.avail_in=i<r?r-i+5:5-(i-r),e.avail_out=n<a?a-n+257:257-(n-a),s.hold=p,s.bits=m}},{}],49:[function(e,t,s){var i=e("../utils/common"),r=e("./adler32"),n=e("./crc32"),o=e("./inffast"),a=e("./inftrees"),l=1,h=2,u=0,c=-2,d=1,p=852,m=592;function f(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new i.Buf16(320),this.work=new i.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function y(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=d,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new i.Buf32(p),t.distcode=t.distdyn=new i.Buf32(m),t.sane=1,t.back=-1,u):c}function x(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,y(e)):c}function b(e,t){var s,i;return e&&e.state?(i=e.state,t<0?(s=0,t=-t):(s=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?c:(null!==i.window&&i.wbits!==t&&(i.window=null),i.wrap=s,i.wbits=t,x(e))):c}function _(e,t){var s,i;return e?(i=new g,(e.state=i).window=null,(s=b(e,t))!==u&&(e.state=null),s):c}var w,v,T=!0;function S(e){if(T){var t;for(w=new i.Buf32(512),v=new i.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(l,e.lens,0,288,w,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(h,e.lens,0,32,v,0,e.work,{bits:5}),T=!1}e.lencode=w,e.lenbits=9,e.distcode=v,e.distbits=5}function M(e,t,s,r){var n,o=e.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new i.Buf8(o.wsize)),r>=o.wsize?(i.arraySet(o.window,t,s-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(r<(n=o.wsize-o.wnext)&&(n=r),i.arraySet(o.window,t,s-r,n,o.wnext),(r-=n)?(i.arraySet(o.window,t,s-r,r,0),o.wnext=r,o.whave=o.wsize):(o.wnext+=n,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=n))),0}s.inflateReset=x,s.inflateReset2=b,s.inflateResetKeep=y,s.inflateInit=function(e){return _(e,15)},s.inflateInit2=_,s.inflate=function(e,t){var s,p,m,g,y,x,b,_,w,v,T,A,N,E,C,R,P,B,I,D,L,F,O,V,z=0,k=new i.Buf8(4),U=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return c;12===(s=e.state).mode&&(s.mode=13),y=e.next_out,m=e.output,b=e.avail_out,g=e.next_in,p=e.input,x=e.avail_in,_=s.hold,w=s.bits,v=x,T=b,F=u;e:for(;;)switch(s.mode){case d:if(0===s.wrap){s.mode=13;break}for(;w<16;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(2&s.wrap&&35615===_){k[s.check=0]=255&_,k[1]=_>>>8&255,s.check=n(s.check,k,2,0),w=_=0,s.mode=2;break}if(s.flags=0,s.head&&(s.head.done=!1),!(1&s.wrap)||(((255&_)<<8)+(_>>8))%31){e.msg="incorrect header check",s.mode=30;break}if(8!=(15&_)){e.msg="unknown compression method",s.mode=30;break}if(w-=4,L=8+(15&(_>>>=4)),0===s.wbits)s.wbits=L;else if(L>s.wbits){e.msg="invalid window size",s.mode=30;break}s.dmax=1<<L,e.adler=s.check=1,s.mode=512&_?10:12,w=_=0;break;case 2:for(;w<16;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(s.flags=_,8!=(255&s.flags)){e.msg="unknown compression method",s.mode=30;break}if(57344&s.flags){e.msg="unknown header flags set",s.mode=30;break}s.head&&(s.head.text=_>>8&1),512&s.flags&&(k[0]=255&_,k[1]=_>>>8&255,s.check=n(s.check,k,2,0)),w=_=0,s.mode=3;case 3:for(;w<32;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}s.head&&(s.head.time=_),512&s.flags&&(k[0]=255&_,k[1]=_>>>8&255,k[2]=_>>>16&255,k[3]=_>>>24&255,s.check=n(s.check,k,4,0)),w=_=0,s.mode=4;case 4:for(;w<16;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}s.head&&(s.head.xflags=255&_,s.head.os=_>>8),512&s.flags&&(k[0]=255&_,k[1]=_>>>8&255,s.check=n(s.check,k,2,0)),w=_=0,s.mode=5;case 5:if(1024&s.flags){for(;w<16;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}s.length=_,s.head&&(s.head.extra_len=_),512&s.flags&&(k[0]=255&_,k[1]=_>>>8&255,s.check=n(s.check,k,2,0)),w=_=0}else s.head&&(s.head.extra=null);s.mode=6;case 6:if(1024&s.flags&&(x<(A=s.length)&&(A=x),A&&(s.head&&(L=s.head.extra_len-s.length,s.head.extra||(s.head.extra=new Array(s.head.extra_len)),i.arraySet(s.head.extra,p,g,A,L)),512&s.flags&&(s.check=n(s.check,p,A,g)),x-=A,g+=A,s.length-=A),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===x)break e;for(A=0;L=p[g+A++],s.head&&L&&s.length<65536&&(s.head.name+=String.fromCharCode(L)),L&&A<x;);if(512&s.flags&&(s.check=n(s.check,p,A,g)),x-=A,g+=A,L)break e}else s.head&&(s.head.name=null);s.length=0,s.mode=8;case 8:if(4096&s.flags){if(0===x)break e;for(A=0;L=p[g+A++],s.head&&L&&s.length<65536&&(s.head.comment+=String.fromCharCode(L)),L&&A<x;);if(512&s.flags&&(s.check=n(s.check,p,A,g)),x-=A,g+=A,L)break e}else s.head&&(s.head.comment=null);s.mode=9;case 9:if(512&s.flags){for(;w<16;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(_!==(65535&s.check)){e.msg="header crc mismatch",s.mode=30;break}w=_=0}s.head&&(s.head.hcrc=s.flags>>9&1,s.head.done=!0),e.adler=s.check=0,s.mode=12;break;case 10:for(;w<32;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}e.adler=s.check=f(_),w=_=0,s.mode=11;case 11:if(0===s.havedict)return e.next_out=y,e.avail_out=b,e.next_in=g,e.avail_in=x,s.hold=_,s.bits=w,2;e.adler=s.check=1,s.mode=12;case 12:if(5===t||6===t)break e;case 13:if(s.last){_>>>=7&w,w-=7&w,s.mode=27;break}for(;w<3;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}switch(s.last=1&_,w-=1,3&(_>>>=1)){case 0:s.mode=14;break;case 1:if(S(s),s.mode=20,6!==t)break;_>>>=2,w-=2;break e;case 2:s.mode=17;break;case 3:e.msg="invalid block type",s.mode=30}_>>>=2,w-=2;break;case 14:for(_>>>=7&w,w-=7&w;w<32;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if((65535&_)!=(_>>>16^65535)){e.msg="invalid stored block lengths",s.mode=30;break}if(s.length=65535&_,w=_=0,s.mode=15,6===t)break e;case 15:s.mode=16;case 16:if(A=s.length){if(x<A&&(A=x),b<A&&(A=b),0===A)break e;i.arraySet(m,p,g,A,y),x-=A,g+=A,b-=A,y+=A,s.length-=A;break}s.mode=12;break;case 17:for(;w<14;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(s.nlen=257+(31&_),_>>>=5,w-=5,s.ndist=1+(31&_),_>>>=5,w-=5,s.ncode=4+(15&_),_>>>=4,w-=4,286<s.nlen||30<s.ndist){e.msg="too many length or distance symbols",s.mode=30;break}s.have=0,s.mode=18;case 18:for(;s.have<s.ncode;){for(;w<3;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}s.lens[U[s.have++]]=7&_,_>>>=3,w-=3}for(;s.have<19;)s.lens[U[s.have++]]=0;if(s.lencode=s.lendyn,s.lenbits=7,O={bits:s.lenbits},F=a(0,s.lens,0,19,s.lencode,0,s.work,O),s.lenbits=O.bits,F){e.msg="invalid code lengths set",s.mode=30;break}s.have=0,s.mode=19;case 19:for(;s.have<s.nlen+s.ndist;){for(;R=(z=s.lencode[_&(1<<s.lenbits)-1])>>>16&255,P=65535&z,!((C=z>>>24)<=w);){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(P<16)_>>>=C,w-=C,s.lens[s.have++]=P;else{if(16===P){for(V=C+2;w<V;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(_>>>=C,w-=C,0===s.have){e.msg="invalid bit length repeat",s.mode=30;break}L=s.lens[s.have-1],A=3+(3&_),_>>>=2,w-=2}else if(17===P){for(V=C+3;w<V;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}w-=C,L=0,A=3+(7&(_>>>=C)),_>>>=3,w-=3}else{for(V=C+7;w<V;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}w-=C,L=0,A=11+(127&(_>>>=C)),_>>>=7,w-=7}if(s.have+A>s.nlen+s.ndist){e.msg="invalid bit length repeat",s.mode=30;break}for(;A--;)s.lens[s.have++]=L}}if(30===s.mode)break;if(0===s.lens[256]){e.msg="invalid code -- missing end-of-block",s.mode=30;break}if(s.lenbits=9,O={bits:s.lenbits},F=a(l,s.lens,0,s.nlen,s.lencode,0,s.work,O),s.lenbits=O.bits,F){e.msg="invalid literal/lengths set",s.mode=30;break}if(s.distbits=6,s.distcode=s.distdyn,O={bits:s.distbits},F=a(h,s.lens,s.nlen,s.ndist,s.distcode,0,s.work,O),s.distbits=O.bits,F){e.msg="invalid distances set",s.mode=30;break}if(s.mode=20,6===t)break e;case 20:s.mode=21;case 21:if(6<=x&&258<=b){e.next_out=y,e.avail_out=b,e.next_in=g,e.avail_in=x,s.hold=_,s.bits=w,o(e,T),y=e.next_out,m=e.output,b=e.avail_out,g=e.next_in,p=e.input,x=e.avail_in,_=s.hold,w=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;R=(z=s.lencode[_&(1<<s.lenbits)-1])>>>16&255,P=65535&z,!((C=z>>>24)<=w);){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(R&&!(240&R)){for(B=C,I=R,D=P;R=(z=s.lencode[D+((_&(1<<B+I)-1)>>B)])>>>16&255,P=65535&z,!(B+(C=z>>>24)<=w);){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}_>>>=B,w-=B,s.back+=B}if(_>>>=C,w-=C,s.back+=C,s.length=P,0===R){s.mode=26;break}if(32&R){s.back=-1,s.mode=12;break}if(64&R){e.msg="invalid literal/length code",s.mode=30;break}s.extra=15&R,s.mode=22;case 22:if(s.extra){for(V=s.extra;w<V;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}s.length+=_&(1<<s.extra)-1,_>>>=s.extra,w-=s.extra,s.back+=s.extra}s.was=s.length,s.mode=23;case 23:for(;R=(z=s.distcode[_&(1<<s.distbits)-1])>>>16&255,P=65535&z,!((C=z>>>24)<=w);){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(!(240&R)){for(B=C,I=R,D=P;R=(z=s.distcode[D+((_&(1<<B+I)-1)>>B)])>>>16&255,P=65535&z,!(B+(C=z>>>24)<=w);){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}_>>>=B,w-=B,s.back+=B}if(_>>>=C,w-=C,s.back+=C,64&R){e.msg="invalid distance code",s.mode=30;break}s.offset=P,s.extra=15&R,s.mode=24;case 24:if(s.extra){for(V=s.extra;w<V;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}s.offset+=_&(1<<s.extra)-1,_>>>=s.extra,w-=s.extra,s.back+=s.extra}if(s.offset>s.dmax){e.msg="invalid distance too far back",s.mode=30;break}s.mode=25;case 25:if(0===b)break e;if(A=T-b,s.offset>A){if((A=s.offset-A)>s.whave&&s.sane){e.msg="invalid distance too far back",s.mode=30;break}N=A>s.wnext?(A-=s.wnext,s.wsize-A):s.wnext-A,A>s.length&&(A=s.length),E=s.window}else E=m,N=y-s.offset,A=s.length;for(b<A&&(A=b),b-=A,s.length-=A;m[y++]=E[N++],--A;);0===s.length&&(s.mode=21);break;case 26:if(0===b)break e;m[y++]=s.length,b--,s.mode=21;break;case 27:if(s.wrap){for(;w<32;){if(0===x)break e;x--,_|=p[g++]<<w,w+=8}if(T-=b,e.total_out+=T,s.total+=T,T&&(e.adler=s.check=s.flags?n(s.check,m,T,y-T):r(s.check,m,T,y-T)),T=b,(s.flags?_:f(_))!==s.check){e.msg="incorrect data check",s.mode=30;break}w=_=0}s.mode=28;case 28:if(s.wrap&&s.flags){for(;w<32;){if(0===x)break e;x--,_+=p[g++]<<w,w+=8}if(_!==(4294967295&s.total)){e.msg="incorrect length check",s.mode=30;break}w=_=0}s.mode=29;case 29:F=1;break e;case 30:F=-3;break e;case 31:return-4;default:return c}return e.next_out=y,e.avail_out=b,e.next_in=g,e.avail_in=x,s.hold=_,s.bits=w,(s.wsize||T!==e.avail_out&&s.mode<30&&(s.mode<27||4!==t))&&M(e,e.output,e.next_out,T-e.avail_out)?(s.mode=31,-4):(v-=e.avail_in,T-=e.avail_out,e.total_in+=v,e.total_out+=T,s.total+=T,s.wrap&&T&&(e.adler=s.check=s.flags?n(s.check,m,T,e.next_out-T):r(s.check,m,T,e.next_out-T)),e.data_type=s.bits+(s.last?64:0)+(12===s.mode?128:0)+(20===s.mode||15===s.mode?256:0),(0==v&&0===T||4===t)&&F===u&&(F=-5),F)},s.inflateEnd=function(e){if(!e||!e.state)return c;var t=e.state;return t.window&&(t.window=null),e.state=null,u},s.inflateGetHeader=function(e,t){var s;return e&&e.state&&2&(s=e.state).wrap?((s.head=t).done=!1,u):c},s.inflateSetDictionary=function(e,t){var s,i=t.length;return e&&e.state?0!==(s=e.state).wrap&&11!==s.mode?c:11===s.mode&&r(1,t,i,0)!==s.check?-3:M(e,t,i,i)?(s.mode=31,-4):(s.havedict=1,u):c},s.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(e,t,s){var i=e("../utils/common"),r=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],n=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],o=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,s,l,h,u,c,d){var p,m,f,g,y,x,b,_,w,v=d.bits,T=0,S=0,M=0,A=0,N=0,E=0,C=0,R=0,P=0,B=0,I=null,D=0,L=new i.Buf16(16),F=new i.Buf16(16),O=null,V=0;for(T=0;T<=15;T++)L[T]=0;for(S=0;S<l;S++)L[t[s+S]]++;for(N=v,A=15;1<=A&&0===L[A];A--);if(A<N&&(N=A),0===A)return h[u++]=20971520,h[u++]=20971520,d.bits=1,0;for(M=1;M<A&&0===L[M];M++);for(N<M&&(N=M),T=R=1;T<=15;T++)if(R<<=1,(R-=L[T])<0)return-1;if(0<R&&(0===e||1!==A))return-1;for(F[1]=0,T=1;T<15;T++)F[T+1]=F[T]+L[T];for(S=0;S<l;S++)0!==t[s+S]&&(c[F[t[s+S]]++]=S);if(x=0===e?(I=O=c,19):1===e?(I=r,D-=257,O=n,V-=257,256):(I=o,O=a,-1),T=M,y=u,C=S=B=0,f=-1,g=(P=1<<(E=N))-1,1===e&&852<P||2===e&&592<P)return 1;for(;;){for(b=T-C,w=c[S]<x?(_=0,c[S]):c[S]>x?(_=O[V+c[S]],I[D+c[S]]):(_=96,0),p=1<<T-C,M=m=1<<E;h[y+(B>>C)+(m-=p)]=b<<24|_<<16|w,0!==m;);for(p=1<<T-1;B&p;)p>>=1;if(0!==p?(B&=p-1,B+=p):B=0,S++,0==--L[T]){if(T===A)break;T=t[s+c[S]]}if(N<T&&(B&g)!==f){for(0===C&&(C=N),y+=M,R=1<<(E=T-C);E+C<A&&!((R-=L[E+C])<=0);)E++,R<<=1;if(P+=1<<E,1===e&&852<P||2===e&&592<P)return 1;h[f=B&g]=N<<24|E<<16|y-u}}return 0!==B&&(h[y+B]=T-C<<24|64<<16),d.bits=N,0}},{"../utils/common":41}],51:[function(e,t,s){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(e,t,s){var i=e("../utils/common"),r=0,n=1;function o(e){for(var t=e.length;0<=--t;)e[t]=0}var a=0,l=29,h=256,u=h+1+l,c=30,d=19,p=2*u+1,m=15,f=16,g=7,y=256,x=16,b=17,_=18,w=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],v=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],T=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],S=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],M=new Array(2*(u+2));o(M);var A=new Array(2*c);o(A);var N=new Array(512);o(N);var E=new Array(256);o(E);var C=new Array(l);o(C);var R,P,B,I=new Array(c);function D(e,t,s,i,r){this.static_tree=e,this.extra_bits=t,this.extra_base=s,this.elems=i,this.max_length=r,this.has_stree=e&&e.length}function L(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function F(e){return e<256?N[e]:N[256+(e>>>7)]}function O(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function V(e,t,s){e.bi_valid>f-s?(e.bi_buf|=t<<e.bi_valid&65535,O(e,e.bi_buf),e.bi_buf=t>>f-e.bi_valid,e.bi_valid+=s-f):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=s)}function z(e,t,s){V(e,s[2*t],s[2*t+1])}function k(e,t){for(var s=0;s|=1&e,e>>>=1,s<<=1,0<--t;);return s>>>1}function U(e,t,s){var i,r,n=new Array(m+1),o=0;for(i=1;i<=m;i++)n[i]=o=o+s[i-1]<<1;for(r=0;r<=t;r++){var a=e[2*r+1];0!==a&&(e[2*r]=k(n[a]++,a))}}function G(e){var t;for(t=0;t<u;t++)e.dyn_ltree[2*t]=0;for(t=0;t<c;t++)e.dyn_dtree[2*t]=0;for(t=0;t<d;t++)e.bl_tree[2*t]=0;e.dyn_ltree[2*y]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function j(e){8<e.bi_valid?O(e,e.bi_buf):0<e.bi_valid&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function $(e,t,s,i){var r=2*t,n=2*s;return e[r]<e[n]||e[r]===e[n]&&i[t]<=i[s]}function W(e,t,s){for(var i=e.heap[s],r=s<<1;r<=e.heap_len&&(r<e.heap_len&&$(t,e.heap[r+1],e.heap[r],e.depth)&&r++,!$(t,i,e.heap[r],e.depth));)e.heap[s]=e.heap[r],s=r,r<<=1;e.heap[s]=i}function H(e,t,s){var i,r,n,o,a=0;if(0!==e.last_lit)for(;i=e.pending_buf[e.d_buf+2*a]<<8|e.pending_buf[e.d_buf+2*a+1],r=e.pending_buf[e.l_buf+a],a++,0===i?z(e,r,t):(z(e,(n=E[r])+h+1,t),0!==(o=w[n])&&V(e,r-=C[n],o),z(e,n=F(--i),s),0!==(o=v[n])&&V(e,i-=I[n],o)),a<e.last_lit;);z(e,y,t)}function q(e,t){var s,i,r,n=t.dyn_tree,o=t.stat_desc.static_tree,a=t.stat_desc.has_stree,l=t.stat_desc.elems,h=-1;for(e.heap_len=0,e.heap_max=p,s=0;s<l;s++)0!==n[2*s]?(e.heap[++e.heap_len]=h=s,e.depth[s]=0):n[2*s+1]=0;for(;e.heap_len<2;)n[2*(r=e.heap[++e.heap_len]=h<2?++h:0)]=1,e.depth[r]=0,e.opt_len--,a&&(e.static_len-=o[2*r+1]);for(t.max_code=h,s=e.heap_len>>1;1<=s;s--)W(e,n,s);for(r=l;s=e.heap[1],e.heap[1]=e.heap[e.heap_len--],W(e,n,1),i=e.heap[1],e.heap[--e.heap_max]=s,e.heap[--e.heap_max]=i,n[2*r]=n[2*s]+n[2*i],e.depth[r]=(e.depth[s]>=e.depth[i]?e.depth[s]:e.depth[i])+1,n[2*s+1]=n[2*i+1]=r,e.heap[1]=r++,W(e,n,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var s,i,r,n,o,a,l=t.dyn_tree,h=t.max_code,u=t.stat_desc.static_tree,c=t.stat_desc.has_stree,d=t.stat_desc.extra_bits,f=t.stat_desc.extra_base,g=t.stat_desc.max_length,y=0;for(n=0;n<=m;n++)e.bl_count[n]=0;for(l[2*e.heap[e.heap_max]+1]=0,s=e.heap_max+1;s<p;s++)g<(n=l[2*l[2*(i=e.heap[s])+1]+1]+1)&&(n=g,y++),l[2*i+1]=n,h<i||(e.bl_count[n]++,o=0,f<=i&&(o=d[i-f]),a=l[2*i],e.opt_len+=a*(n+o),c&&(e.static_len+=a*(u[2*i+1]+o)));if(0!==y){do{for(n=g-1;0===e.bl_count[n];)n--;e.bl_count[n]--,e.bl_count[n+1]+=2,e.bl_count[g]--,y-=2}while(0<y);for(n=g;0!==n;n--)for(i=e.bl_count[n];0!==i;)h<(r=e.heap[--s])||(l[2*r+1]!==n&&(e.opt_len+=(n-l[2*r+1])*l[2*r],l[2*r+1]=n),i--)}}(e,t),U(n,h,e.bl_count)}function X(e,t,s){var i,r,n=-1,o=t[1],a=0,l=7,h=4;for(0===o&&(l=138,h=3),t[2*(s+1)+1]=65535,i=0;i<=s;i++)r=o,o=t[2*(i+1)+1],++a<l&&r===o||(a<h?e.bl_tree[2*r]+=a:0!==r?(r!==n&&e.bl_tree[2*r]++,e.bl_tree[2*x]++):a<=10?e.bl_tree[2*b]++:e.bl_tree[2*_]++,n=r,h=(a=0)===o?(l=138,3):r===o?(l=6,3):(l=7,4))}function Y(e,t,s){var i,r,n=-1,o=t[1],a=0,l=7,h=4;for(0===o&&(l=138,h=3),i=0;i<=s;i++)if(r=o,o=t[2*(i+1)+1],!(++a<l&&r===o)){if(a<h)for(;z(e,r,e.bl_tree),0!=--a;);else 0!==r?(r!==n&&(z(e,r,e.bl_tree),a--),z(e,x,e.bl_tree),V(e,a-3,2)):a<=10?(z(e,b,e.bl_tree),V(e,a-3,3)):(z(e,_,e.bl_tree),V(e,a-11,7));n=r,h=(a=0)===o?(l=138,3):r===o?(l=6,3):(l=7,4)}}o(I);var Z=!1;function Q(e,t,s,r){var n,o,l;V(e,(a<<1)+(r?1:0),3),o=t,l=s,j(n=e),O(n,l),O(n,~l),i.arraySet(n.pending_buf,n.window,o,l,n.pending),n.pending+=l}s._tr_init=function(e){Z||(function(){var e,t,s,i,r,n=new Array(m+1);for(i=s=0;i<l-1;i++)for(C[i]=s,e=0;e<1<<w[i];e++)E[s++]=i;for(E[s-1]=i,i=r=0;i<16;i++)for(I[i]=r,e=0;e<1<<v[i];e++)N[r++]=i;for(r>>=7;i<c;i++)for(I[i]=r<<7,e=0;e<1<<v[i]-7;e++)N[256+r++]=i;for(t=0;t<=m;t++)n[t]=0;for(e=0;e<=143;)M[2*e+1]=8,e++,n[8]++;for(;e<=255;)M[2*e+1]=9,e++,n[9]++;for(;e<=279;)M[2*e+1]=7,e++,n[7]++;for(;e<=287;)M[2*e+1]=8,e++,n[8]++;for(U(M,u+1,n),e=0;e<c;e++)A[2*e+1]=5,A[2*e]=k(e,5);R=new D(M,w,h+1,u,m),P=new D(A,v,0,c,m),B=new D(new Array(0),T,0,d,g)}(),Z=!0),e.l_desc=new L(e.dyn_ltree,R),e.d_desc=new L(e.dyn_dtree,P),e.bl_desc=new L(e.bl_tree,B),e.bi_buf=0,e.bi_valid=0,G(e)},s._tr_stored_block=Q,s._tr_flush_block=function(e,t,s,i){var o,a,l=0;0<e.level?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,s=4093624447;for(t=0;t<=31;t++,s>>>=1)if(1&s&&0!==e.dyn_ltree[2*t])return r;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return n;for(t=32;t<h;t++)if(0!==e.dyn_ltree[2*t])return n;return r}(e)),q(e,e.l_desc),q(e,e.d_desc),l=function(e){var t;for(X(e,e.dyn_ltree,e.l_desc.max_code),X(e,e.dyn_dtree,e.d_desc.max_code),q(e,e.bl_desc),t=d-1;3<=t&&0===e.bl_tree[2*S[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),o=e.opt_len+3+7>>>3,(a=e.static_len+3+7>>>3)<=o&&(o=a)):o=a=s+5,s+4<=o&&-1!==t?Q(e,t,s,i):4===e.strategy||a===o?(V(e,2+(i?1:0),3),H(e,M,A)):(V(e,4+(i?1:0),3),function(e,t,s,i){var r;for(V(e,t-257,5),V(e,s-1,5),V(e,i-4,4),r=0;r<i;r++)V(e,e.bl_tree[2*S[r]+1],3);Y(e,e.dyn_ltree,t-1),Y(e,e.dyn_dtree,s-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,l+1),H(e,e.dyn_ltree,e.dyn_dtree)),G(e),i&&j(e)},s._tr_tally=function(e,t,s){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&s,e.last_lit++,0===t?e.dyn_ltree[2*s]++:(e.matches++,t--,e.dyn_ltree[2*(E[s]+h+1)]++,e.dyn_dtree[2*F(t)]++),e.last_lit===e.lit_bufsize-1},s._tr_align=function(e){var t;V(e,2,3),z(e,y,M),16===(t=e).bi_valid?(O(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):8<=t.bi_valid&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}},{"../utils/common":41}],53:[function(e,t,s){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,s){(function(e){!function(e,t){if(!e.setImmediate){var s,i,r,n,o=1,a={},l=!1,h=e.document,u=Object.getPrototypeOf&&Object.getPrototypeOf(e);u=u&&u.setTimeout?u:e,s="[object process]"==={}.toString.call(e.process)?function(e){process.nextTick(function(){d(e)})}:function(){if(e.postMessage&&!e.importScripts){var t=!0,s=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=s,t}}()?(n="setImmediate$"+Math.random()+"$",e.addEventListener?e.addEventListener("message",p,!1):e.attachEvent("onmessage",p),function(t){e.postMessage(n+t,"*")}):e.MessageChannel?((r=new MessageChannel).port1.onmessage=function(e){d(e.data)},function(e){r.port2.postMessage(e)}):h&&"onreadystatechange"in h.createElement("script")?(i=h.documentElement,function(e){var t=h.createElement("script");t.onreadystatechange=function(){d(e),t.onreadystatechange=null,i.removeChild(t),t=null},i.appendChild(t)}):function(e){setTimeout(d,0,e)},u.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),i=0;i<t.length;i++)t[i]=arguments[i+1];var r={callback:e,args:t};return a[o]=r,s(o),o++},u.clearImmediate=c}function c(e){delete a[e]}function d(e){if(l)setTimeout(d,0,e);else{var s=a[e];if(s){l=!0;try{!function(e){var s=e.callback,i=e.args;switch(i.length){case 0:s();break;case 1:s(i[0]);break;case 2:s(i[0],i[1]);break;case 3:s(i[0],i[1],i[2]);break;default:s.apply(t,i)}}(s)}finally{c(e),l=!1}}}}function p(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(n)&&d(+t.data.slice(n.length))}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,void 0!==IO?IO:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10));class VO{constructor(e,s){t(this,"date",new Date),t(this,"author"),t(this,"guid",w.create()),t(this,"viewpoint"),t(this,"modifiedAuthor"),t(this,"modifiedDate"),t(this,"topic"),t(this,"_components"),t(this,"_comment",""),this._components=e,this._comment=s;const i=this._components.get($O);this.author=i.config.author}set comment(e){var t;const s=this._components.get($O);this._comment=e,this.modifiedDate=new Date,this.modifiedAuthor=s.config.author,null==(t=this.topic)||t.comments.set(this.guid,this)}get comment(){return this._comment}toJSON(){var e,t;const s={guid:this.guid,date:this.date.toISOString(),author:this.author,comment:this.comment,topic_guid:null==(e=this.topic)?void 0:e.guid,viewpoint_guid:this.viewpoint,modified_date:null==(t=this.modifiedDate)?void 0:t.toISOString(),modified_author:this.modifiedAuthor};for(const[e,t]of Object.entries(s))void 0===t&&delete s[e];return s}}const zO=class e{constructor(i){t(this,"guid",w.create()),t(this,"title",e.default.title),t(this,"creationDate",new Date),t(this,"creationAuthor",""),t(this,"viewpoints",new s.DataSet),t(this,"relatedTopics",new s.DataSet),t(this,"comments",new s.DataMap),t(this,"documentReferences",new s.DataSet),t(this,"customData",{}),t(this,"description"),t(this,"serverAssignedId"),t(this,"dueDate"),t(this,"modifiedAuthor"),t(this,"modifiedDate"),t(this,"index"),t(this,"_type",e.default.type),t(this,"_status",e.default.status),t(this,"_priority",e.default.priority),t(this,"_stage",e.default.stage),t(this,"_assignedTo",e.default.assignedTo),t(this,"_labels",e.default.labels??new Set),t(this,"_components"),this._components=i;const r=i.get($O);this.creationAuthor=r.config.author,this.relatedTopics.guard=e=>e!==this.guid}set type(e){const t=this._components.get($O),{strict:s,types:i}=t.config;(!s||i.has(e))&&(this._type=e)}get type(){return this._type}set status(e){const t=this._components.get($O),{strict:s,statuses:i}=t.config;(!s||i.has(e))&&(this._status=e)}get status(){return this._status}set priority(e){const t=this._components.get($O);if(e){const{strict:s,priorities:i}=t.config;if(!(!s||i.has(e)))return;this._priority=e}else this._priority=e}get priority(){return this._priority}set stage(e){const t=this._components.get($O);if(e){const{strict:s,stages:i}=t.config;if(!(!s||i.has(e)))return;this._stage=e}else this._stage=e}get stage(){return this._stage}set assignedTo(e){const t=this._components.get($O);if(e){const{strict:s,users:i}=t.config;if(!(!s||i.has(e)))return;this._assignedTo=e}else this._assignedTo=e}get assignedTo(){return this._assignedTo}set labels(e){const t=this._components.get($O),{strict:s,labels:i}=t.config;if(s){const t=new Set;for(const r of e){(!s||i.has(r))&&t.add(r)}this._labels=t}else this._labels=e}get labels(){return this._labels}get _managerVersion(){return this._components.get($O).config.version}set(e){const t=e,s=this;for(const i in e){if("guid"===i)continue;const e=t[i];i in this&&(s[i]=e)}return this._components.get($O).list.set(this.guid,this),this}createComment(e,t){const s=new VO(this._components,e);return s.viewpoint=t,s.topic=this,this.comments.set(s.guid,s),s}createLabelTags(){const e=[...this.labels];if(this._components.get($O).config.exportCustomDataAsLabels)for(const t in this.customData){const s=this.customData[t];"string"==typeof s&&e.push(s)}return e}createCommentTags(){return[...this.comments.values()].map(e=>{var t;return{$Guid:e.guid,Date:e.date.toISOString(),Author:e.author,Comment:e.comment,ModifiedAuthor:e.modifiedAuthor,ModifiedDate:null==(t=e.modifiedDate)?void 0:t.toISOString(),Viewpoint:e.viewpoint?{$Guid:e.viewpoint}:void 0}})}createViewpointTags(){const e=this._components.get(PV);return[...this.viewpoints].map(t=>e.list.get(t)).filter(e=>e).map(t=>{const s={$Guid:t.guid,Viewpoint:`${t.title??t.guid}.bcfv`};if(e.snapshots.get(t.snapshot)){const i=e.getSnapshotExtension(t.snapshot);s.Snapshot=`${t.snapshot}.${i}`}return s})}createRelatedTopicTags(){return[...this.relatedTopics].map(e=>({$Guid:e}))}createDocumentReferencesTag(e=this._managerVersion){const t=[];if("3"!==e&&"2.1"!==e)return t;const s=this._components.get($O);for(const i of this.documentReferences){const r=s.documents.get(i);if(!r)continue;let n={$Guid:w.create(),Description:r.description};"2.1"===e&&(n={...n,$isExternal:"external"===r.type||void 0,ReferencedDocument:"external"===r.type?r.url:`../${r.fileName}`}),"3"===e&&(n={...n,DocumentGuid:"internal"===r.type?i:void 0,Url:"external"===r.type?r.url:void 0}),Object.keys(n).length>0&&t.push(n)}return t}toJSON(){var e,t;const s={guid:this.guid,server_assigned_id:this.serverAssignedId,topic_type:this.type,topic_status:this.status,title:this.title,priority:this.priority,index:this.index,labels:[...this.labels],creation_date:this.creationDate.toISOString(),creation_author:this.creationAuthor,modified_date:null==(e=this.modifiedDate)?void 0:e.toISOString(),modified_author:this.modifiedAuthor,assigned_to:this.assignedTo,stage:this.stage,description:this.description,due_date:null==(t=this.dueDate)?void 0:t.toISOString(),comments:[...this.comments].map(([e,t])=>t.toJSON()),relatedTopics:[...this.relatedTopics].map(e=>({related_topic_guid:e}))},i=this._components.get(PV);for(const e of this.viewpoints){const t=i.list.get(e);t&&(s.viewpoints||(s.viewpoints=[]),s.viewpoints.push(t.toJSON()))}const r=this._components.get($O);for(const e of this.documentReferences){const t=r.documents.get(e);t&&(s.document_references||(s.document_references=[]),"external"===t.type?s.document_references.push({guid:w.create(),description:t.description,url:t.url}):s.document_references.push({guid:w.create(),description:t.description,document_guid:e}))}for(const[e,t]of Object.entries(s))(void 0===t||Array.isArray(t)&&0===t.length)&&delete s[e];return s}serialize(){var e,t;const s=this._managerVersion,i={$Guid:this.guid,$TopicType:this.type,$TopicStatus:this.status,$ServerAssignedId:this.serverAssignedId,Title:this.title,CreationAuthor:this.creationAuthor,CreationDate:this.creationDate.toISOString(),Priority:this.priority,Index:"2.1"===s?this.index:void 0,ModifiedDate:null==(e=this.modifiedDate)?void 0:e.toISOString(),ModifiedAuthor:this.modifiedAuthor,DueDate:null==(t=this.dueDate)?void 0:t.toISOString(),AssignedTo:this.assignedTo,Description:this.description,Stage:this.stage,DocumentReferences:"3"===s?{DocumentReference:this.createDocumentReferencesTag(s)}:void 0,RelatedTopics:"3"===s?{RelatedTopic:this.createRelatedTopicTags()}:void 0,RelatedTopic:"2.1"===s?this.createRelatedTopicTags():void 0,Labels:"3"===s?{Label:this.createLabelTags()}:void 0,Viewpoints:"3"===s?{ViewPoint:this.createViewpointTags()}:void 0,Comments:"3"===s?{Comment:this.createCommentTags()}:void 0};"2.1"===s&&(i.Labels=this.createLabelTags(),i.DocumentReference=this.createDocumentReferencesTag(s));const r={Markup:{Topic:i}};return"2.1"===s&&(r.Markup.Viewpoints=this.createViewpointTags(),r.Markup.Comment=this.createCommentTags()),`<?xml version="1.0" encoding="UTF-8"?>\n ${Fe.builder.build(r)}`}};t(zO,"default",{title:"BCF Topic",type:"Issue",status:"Active"});let kO=zO;const UO=(e,t)=>{if(""===t.trim())return;const s=$O.xmlParser.parse(t).Extensions;if(!s)return;const{Priorities:i,TopicStatuses:r,TopicTypes:n,Users:o}=s;if(i&&i.Priority){const t=Array.isArray(i.Priority)?i.Priority:[i.Priority];for(const s of t)e.config.priorities.add(s)}if(r&&r.TopicStatus){const t=Array.isArray(r.TopicStatus)?r.TopicStatus:[r.TopicStatus];for(const s of t)e.config.statuses.add(s)}if(n&&n.TopicType){const t=Array.isArray(n.TopicType)?n.TopicType:[n.TopicType];for(const s of t)e.config.types.add(s)}if(o&&o.User){const t=Array.isArray(o.User)?o.User:[o.User];for(const s of t)e.config.users.add(s)}};class GO extends ke{constructor(){super(...arguments),t(this,"_config",{version:{type:"Select",options:new Set(["2.1","3"]),multiple:!1,value:""},author:{type:"Text",value:""},types:{type:"TextSet",value:new Set},statuses:{type:"TextSet",value:new Set},priorities:{type:"TextSet",value:new Set},labels:{type:"TextSet",value:new Set},stages:{type:"TextSet",value:new Set},users:{type:"TextSet",value:new Set},includeSelectionTag:{type:"Boolean",value:!1},updateExtensionsOnImport:{type:"Boolean",value:!1},strict:{type:"Boolean",value:!1},includeAllExtensionsOnExport:{type:"Boolean",value:!1},fallbackVersionOnImport:{type:"Select",multiple:!1,options:new Set(["2.1","3"]),value:""},ignoreIncompleteTopicsOnImport:{type:"Boolean",value:!1},exportCustomDataAsLabels:{type:"Boolean",value:!1}})}get version(){return this._config.version.value}set version(e){this._config.version.value=e}get author(){return this._config.author.value}set author(e){this._config.author.value=e}get types(){return this._config.types.value}set types(e){this._config.types.value=e}get statuses(){return this._config.statuses.value}set statuses(e){this._config.statuses.value=e}get priorities(){return this._config.priorities.value}set priorities(e){this._config.priorities.value=e}get labels(){return this._config.labels.value}set labels(e){this._config.labels.value=e}get stages(){return this._config.stages.value}set stages(e){this._config.stages.value=e}get users(){return this._config.users.value}set users(e){this._config.users.value=e}get includeSelectionTag(){return this._config.includeSelectionTag.value}set includeSelectionTag(e){this._config.includeSelectionTag.value=e}get updateExtensionsOnImport(){return this._config.updateExtensionsOnImport.value}set updateExtensionsOnImport(e){this._config.updateExtensionsOnImport.value=e}get strict(){return this._config.strict.value}set strict(e){this._config.strict.value=e}get includeAllExtensionsOnExport(){return this._config.includeAllExtensionsOnExport.value}set includeAllExtensionsOnExport(e){this._config.includeAllExtensionsOnExport.value=e}get fallbackVersionOnImport(){return this._config.fallbackVersionOnImport.value}set fallbackVersionOnImport(e){this._config.fallbackVersionOnImport.value=e}get ignoreIncompleteTopicsOnImport(){return this._config.ignoreIncompleteTopicsOnImport.value}set ignoreIncompleteTopicsOnImport(e){this._config.ignoreIncompleteTopicsOnImport.value=e}get exportCustomDataAsLabels(){return this._config.exportCustomDataAsLabels.value}set exportCustomDataAsLabels(e){this._config.exportCustomDataAsLabels.value=e}}const jO=class e extends d{constructor(){super(...arguments),t(this,"enabled",!1),t(this,"_defaultConfig",{author:"jhon.doe@example.com",version:"2.1",types:new Set(["Clash","Failure","Fault","Inquiry","Issue","Remark","Request"]),statuses:new Set(["Active","In Progress","Done","In Review","Closed"]),priorities:new Set(["On hold","Minor","Normal","Major","Critical"]),labels:new Set,stages:new Set,users:new Set,includeSelectionTag:!1,updateExtensionsOnImport:!0,strict:!1,includeAllExtensionsOnExport:!0,fallbackVersionOnImport:"2.1",ignoreIncompleteTopicsOnImport:!1,exportCustomDataAsLabels:!1}),t(this,"config",new GO(this,this.components,"BCF Topics",e.uuid)),t(this,"list",new s.DataMap),t(this,"documents",new s.DataMap),t(this,"onSetup",new u),t(this,"isSetup",!1),t(this,"onBCFImported",new u),t(this,"onDisposed",new u)}setup(e){if(this.isSetup)return;const t={...this._defaultConfig,...e};this.config.version=t.version,this.config.author=t.author,this.config.types=t.types,this.config.statuses=t.statuses,this.config.priorities=t.priorities,this.config.labels=t.labels,this.config.stages=t.stages,this.config.users=t.users,this.config.includeSelectionTag=t.includeSelectionTag,this.config.updateExtensionsOnImport=t.updateExtensionsOnImport,this.config.strict=t.strict,this.config.includeAllExtensionsOnExport=t.includeAllExtensionsOnExport,this.config.fallbackVersionOnImport=t.fallbackVersionOnImport||"",this.config.ignoreIncompleteTopicsOnImport=t.ignoreIncompleteTopicsOnImport,this.isSetup=!0,this.enabled=!0,this.onSetup.trigger()}create(e){const t=new kO(this.components);return e?(t.guid=e.guid??t.guid,t.set(e)):this.list.set(t.guid,t),t}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}get usedTypes(){const e=[...this.list].map(([e,t])=>t.type);return new Set(e)}get usedStatuses(){const e=[...this.list].map(([e,t])=>t.status);return new Set(e)}get usedPriorities(){const e=[...this.list].map(([e,t])=>t.priority).filter(e=>e);return new Set(e)}get usedStages(){const e=[...this.list].map(([e,t])=>t.stage).filter(e=>e);return new Set(e)}get usedUsers(){const e=[];for(const[t,s]of this.list){e.push(s.creationAuthor),s.assignedTo&&e.push(s.assignedTo),s.modifiedAuthor&&e.push(s.modifiedAuthor);for(const[t,i]of s.comments)e.push(i.author),i.modifiedAuthor&&e.push(i.modifiedAuthor)}return new Set(e)}get usedLabels(){const e=[];for(const[t,s]of this.list)e.push(...s.labels);return new Set(e)}updateExtensions(){for(const[e,t]of this.list){for(const e of t.labels)this.config.labels.add(e);this.config.types.add(t.type),t.priority&&this.config.priorities.add(t.priority),t.stage&&this.config.stages.add(t.stage),this.config.statuses.add(t.status),this.config.users.add(t.creationAuthor),t.assignedTo&&this.config.users.add(t.assignedTo),t.modifiedAuthor&&this.config.users.add(t.modifiedAuthor);for(const[e,s]of t.comments)this.config.users.add(s.author),s.modifiedAuthor&&this.config.users.add(s.modifiedAuthor)}}updateViewpointReferences(){const e=this.components.get(PV);for(const[t,s]of this.list)for(const t of s.viewpoints){e.list.has(t)||s.viewpoints.delete(t)}}async export(e=this.list.values()){const t=new OO;t.file("bcf.version",`<?xml version="1.0" encoding="UTF-8"?>\n <Version VersionId="${this.config.version}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/release_3_0/Schemas/version.xsd"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n </Version>`);for(const[e,s]of this.documents.entries())"external"!==s.type&&t.file("2.1"===this.config.version?s.fileName:`documents/${e}`,s.data);if("3"===this.config.version){const e=[];for(const[t,s]of this.documents.entries()){const{type:i,description:r}=s;"external"!==i&&e.push(`<Document Guid="${t}">\n <Filename>${s.fileName}</Filename>\n ${r?`<Description>${r}</Description>`:""}\n </Document>`)}e.length>0&&t.file("documents.xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n <DocumentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="documents.xsd">\n <Documents>\n ${e.join("\n")}\n </Documents>\n </DocumentInfo>`)}t.file("bcf.extensions",this.serializeExtensions());const s=this.components.get(PV);for(const i of e){const e=t.folder(i.guid);e.file("markup.bcf",i.serialize());for(const t of i.viewpoints){const i=s.list.get(t);if(!i)continue;const r=i.title??i.guid;e.file(`${r}.bcfv`,await i.serialize());const n=s.snapshots.get(i.snapshot);if(!n)continue;const o=n?i.snapshot:i.guid,a=s.getSnapshotExtension(i.snapshot);e.file(`${o}.${a}`,n,{binary:!0})}}return await t.generateAsync({type:"blob"})}serializeExtensions(){const e=[...this.config.types].map(e=>`<TopicType>${e}</TopicType>`).join("\n"),t=[...this.config.statuses].map(e=>`<TopicStatus>${e}</TopicStatus>`).join("\n"),s=[...this.config.priorities].map(e=>`<Priority>${e}</Priority>`).join("\n"),i=[...this.config.labels].map(e=>`<TopicLabel>${e}</TopicLabel>`).join("\n"),r=[...this.config.stages].map(e=>`<Stage>${e}</Stage>`).join("\n"),n=[...this.config.users].map(e=>`<User>${e}</User>`).join("\n");return`\n <?xml version="1.0" encoding="UTF-8"?>\n <Extensions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-schema-location.xsd">\n ${0!==e.length?`<TopicTypes>\n${e}\n</TopicTypes>`:""}\n ${0!==t.length?`<TopicStatuses>\n${t}\n</TopicStatuses>`:""}\n ${0!==s.length?`<Priorities>\n${s}\n</Priorities>`:""}\n ${0!==i.length?`<TopicLabels>\n${i}\n</TopicLabels>`:""}\n ${0!==r.length?`<Stages>\n${r}\n</Stages>`:""}\n ${0!==n.length?`<Users>\n${n}\n</Users>`:""}\n </Extensions>\n `}processMarkupComment(e){const{Guid:t,Date:s,Author:i,Comment:r,Viewpoint:n}=e;if(!(t&&s&&i&&(VO||n)))return null;const o=new VO(this.components,r??"");return o.guid=t,o.date=new Date(s),o.author=i,o.viewpoint=null==n?void 0:n.Guid,o.modifiedAuthor=e.ModifiedAuthor,o.modifiedDate=e.ModifiedDate?new Date(e.ModifiedDate):void 0,o}getMarkupComments(e,t){var s;let i;if("2.1"===t&&(i=e.Comment),"3"===t&&(i=null==(s=e.Topic.Comments)?void 0:s.Comment),!i)return[];i=Array.isArray(i)?i:[i];const r=i.map(e=>this.processMarkupComment(e)).filter(e=>e);return Array.isArray(r)?r:[r]}getMarkupLabels(e,t){var s;let i;if("2.1"===t&&(i=e.Topic.Labels),"3"===t&&(i=null==(s=e.Topic.Labels)?void 0:s.Label),!i)return[];return Array.isArray(i)?i:[i]}getMarkupViewpoints(e,t){var s;let i;return"2.1"===t&&(i=e.Viewpoints),"3"===t&&(i=null==(s=e.Topic.Viewpoints)?void 0:s.ViewPoint),i?(i=Array.isArray(i)?i:[i],i):[]}getMarkupRelatedTopics(e,t){var s;let i;if("2.1"===t&&(i=e.Topic.RelatedTopic),"3"===t&&(i=null==(s=e.Topic.RelatedTopics)?void 0:s.RelatedTopic),!i)return[];return(Array.isArray(i)?i:[i]).map(e=>e.Guid)}getMarkupDocumentReferences(e,t){var s;let i;if("2.1"===t&&(i=e.Topic.DocumentReference),"3"===t&&(i=null==(s=e.Topic.DocumentReferences)?void 0:s.DocumentReference),!i)return[];return Array.isArray(i)?i:[i]}async load(t){var s,i,r;const{fallbackVersionOnImport:n,ignoreIncompleteTopicsOnImport:o,updateExtensionsOnImport:a}=this.config,h=new OO;await h.loadAsync(t);const u=Object.values(h.files);let c=n;const d=u.find(e=>e.name.endsWith(".version"));if(d){const t=await d.async("string"),s=e.xmlParser.parse(t).Version.VersionId;c=String(s)}if(!c||"2.1"!==c&&"3"!==c)throw new Error(`BCFTopics: ${c} is not supported.`);const p=u.find(e=>e.name.endsWith(".extensions"));if(a&&p){const e=await p.async("string");UO(this,e)}const m=[],f=this.components.get(PV),g=u.filter(e=>e.name.endsWith(".bcfv"));for(const t of g){const i=await t.async("string"),r=e.xmlParser.parse(i).VisualizationInfo;if(!r){console.warn("Missing VisualizationInfo in Viewpoint");continue}const n={},{Guid:o,ClippingPlanes:a,Components:h,OrthogonalCamera:u,PerspectiveCamera:d}=r;if(o&&(n.guid=o),h){const e={selection:[],coloring:[],visibility:{default_visibility:!1,exceptions:[],view_setup_hints:{spaces_visible:!1,space_boundaries_visible:!1,openings_visible:!1}}};n.components=e;const{Selection:t,Visibility:i}=h;if(t&&t.Component){const s=Array.isArray(t.Component)?t.Component:[t.Component];e.selection=s.map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e)}if(i&&"DefaultVisibility"in i&&(e.visibility.default_visibility=i.DefaultVisibility),i&&i.Exceptions&&"Component"in i.Exceptions){const{Component:t}=i.Exceptions,s=Array.isArray(t)?t:[t];e.visibility.exceptions=s.map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e)}let r;"2.1"===c&&(r=h.ViewSetupHints),"3"===c&&(r=null==(s=h.Visibility)?void 0:s.ViewSetupHints),r&&("OpeningsVisible"in r&&(e.visibility.view_setup_hints.openings_visible=r.OpeningsVisible),"SpacesVisible"in r&&(e.visibility.view_setup_hints.spaces_visible=r.SpacesVisible),"SpaceBoundariesVisible"in r&&(e.visibility.view_setup_hints.space_boundaries_visible=r.SpaceBoundariesVisible));const{Coloring:o}=h;if(o&&o.Color){const t=Array.isArray(o.Color)?o.Color:[o.Color];for(const s of t){const{Color:t,Component:i}=s;if(6!==t.length&&8!==t.length)continue;const r=6===t.length?t:t.slice(2),n=(Array.isArray(i)?i:[i]).map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e);e.coloring.push({color:r,components:n})}}}if(u||d){const e=r.PerspectiveCamera??r.OrthogonalCamera,{CameraViewPoint:t,CameraDirection:s}=e,i=new l.Vector3(Number(t.X),Number(t.Z),Number(-t.Y)),o=new l.Vector3(Number(s.X),Number(s.Z),Number(-s.Y)),a={camera_view_point:{x:i.x,y:i.y,z:i.z},camera_direction:{x:o.x,y:o.y,z:o.z},aspect_ratio:"AspectRatio"in e?e.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in e&&(n.orthogonal_camera={...a,view_to_world_scale:e.ViewToWorldScale}),"FieldOfView"in e&&(n.perspective_camera={...a,field_of_view:e.FieldOfView})}if(a){const e=(Array.isArray(a.ClippingPlane)?a.ClippingPlane:[a.ClippingPlane]).map(({Location:e,Direction:t})=>({location:{x:e.x,y:e.y,z:e.z},direction:{x:t.x,y:t.y,z:t.z}}));n.clipping_planes=e}const p=new EV(this.components,n);m.push(p)}const y={},x=[],b=u.filter(e=>e.name.endsWith(".bcf"));for(const t of b){const s=await t.async("string"),n=e.xmlParser.parse(s).Markup,a=n.Topic,{Guid:l,TopicType:h,TopicStatus:d,Title:p,CreationDate:m,CreationAuthor:g}=a;if(o&&!(l&&h&&d&&p&&m&&g))continue;const b=new kO(this.components);b.guid=l??b.guid;const _=this.getMarkupRelatedTopics(n,c);y[b.guid]=new Set(_),b.type=h??b.type,b.status=d??b.status,b.title=p??b.title,b.creationDate=m?new Date(m):b.creationDate,b.creationAuthor=g??b.creationAuthor,b.serverAssignedId=a.ServerAssignedId,b.priority=a.Priority,b.index=a.Index,b.modifiedDate=a.ModifiedDate?new Date(a.ModifiedDate):void 0,b.modifiedAuthor=a.ModifiedAuthor,b.dueDate=a.DueDate?new Date(a.DueDate):void 0,b.assignedTo=a.AssignedTo,b.description=a.Description,b.stage=a.Stage;const w=this.getMarkupLabels(n,c);for(const e of w)b.labels.add(e);const v=this.getMarkupComments(n,c);for(const e of v)b.comments.set(e.guid,e);const T=this.getMarkupViewpoints(n,c);for(const e of T){if(!e||!e.Guid)continue;const t=f.list.get(e.Guid);if(!t)continue;b.viewpoints.add(t.guid);const s=`${b.guid}/${e.Snapshot}`,i=u.find(({name:e})=>e===s);if(i){const e=await i.async("arraybuffer"),s=new Uint8Array(e);f.snapshots.set(t.guid,s),t.snapshot=t.guid??null}}const S=this.getMarkupDocumentReferences(n,c),M=u.find(e=>"documents.xml"===e.name);let A=[];const N=await(null==M?void 0:M.async("string"));if(N){const e=null==(r=null==(i=Fe.parser.parse(N).DocumentInfo)?void 0:i.Documents)?void 0:r.Document;A=Array.isArray(e)?e:[e]}for(const e of S){const{Description:t,DocumentGuid:s,Url:i,isExternal:r,ReferencedDocument:n}=e;if(s&&A.length>0){const e=A.find(({Guid:e})=>e===s),t=u.find(e=>e.name.endsWith(s)),i=await(null==t?void 0:t.async("uint8array"));if(!e||!i)continue;const{Description:r,Filename:n}=e;this.documents.set(s,{type:"internal",fileName:n,description:r,data:i}),b.documentReferences.add(s)}if(i){const e=this.documents.add({type:"external",url:i,description:t});b.documentReferences.add(e)}if(n){let e=null;if(r)e=this.documents.add({type:"external",url:n,description:t});else{const s=n.split("/"),i=s[s.length-1],r=u.find(e=>e.name.endsWith(i)),o=await(null==r?void 0:r.async("uint8array"));if(!o)continue;e=this.documents.add({type:"internal",fileName:i,data:o,description:t})}b.documentReferences.add(e)}}this.list.set(b.guid,b),x.push(b)}for(const e in y){const t=this.list.get(e);if(!t)continue;const s=y[e];for(const e of s)t.relatedTopics.add(e)}return this.onBCFImported.trigger(x),{viewpoints:m,topics:x}}};t(jO,"uuid","de977976-e4f6-4e4f-a01a-204727839802"),t(jO,"xmlParser",new Se({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let $O=jO;const WO=new i.Raycaster,HO=new i.Vector3,qO=new i.Vector3,XO=new i.Quaternion,YO={X:new i.Vector3(1,0,0),Y:new i.Vector3(0,1,0),Z:new i.Vector3(0,0,1)},ZO={type:"change"},QO={type:"mouseDown",mode:null},KO={type:"mouseUp",mode:null},JO={type:"objectChange"};class eV extends i.Controls{constructor(e,t=null){super(void 0,t);const s=new wV(this);this._root=s;const r=new vV;this._gizmo=r,s.add(r);const n=new TV;this._plane=n,s.add(n);const o=this;function a(e,t){let s=t;Object.defineProperty(o,e,{get:function(){return void 0!==s?s:t},set:function(t){s!==t&&(s=t,n[e]=t,r[e]=t,o.dispatchEvent({type:e+"-changed",value:t}),o.dispatchEvent(ZO))}}),o[e]=t,n[e]=t,r[e]=t}a("camera",e),a("object",void 0),a("enabled",!0),a("axis",null),a("mode","translate"),a("translationSnap",null),a("rotationSnap",null),a("scaleSnap",null),a("space","world"),a("size",1),a("dragging",!1),a("showX",!0),a("showY",!0),a("showZ",!0),a("minX",-1/0),a("maxX",1/0),a("minY",-1/0),a("maxY",1/0),a("minZ",-1/0),a("maxZ",1/0);const l=new i.Vector3,h=new i.Vector3,u=new i.Quaternion,c=new i.Quaternion,d=new i.Vector3,p=new i.Quaternion,m=new i.Vector3,f=new i.Vector3,g=new i.Vector3,y=new i.Vector3;a("worldPosition",l),a("worldPositionStart",h),a("worldQuaternion",u),a("worldQuaternionStart",c),a("cameraPosition",d),a("cameraQuaternion",p),a("pointStart",m),a("pointEnd",f),a("rotationAxis",g),a("rotationAngle",0),a("eye",y),this._offset=new i.Vector3,this._startNorm=new i.Vector3,this._endNorm=new i.Vector3,this._cameraScale=new i.Vector3,this._parentPosition=new i.Vector3,this._parentQuaternion=new i.Quaternion,this._parentQuaternionInv=new i.Quaternion,this._parentScale=new i.Vector3,this._worldScaleStart=new i.Vector3,this._worldQuaternionInv=new i.Quaternion,this._worldScale=new i.Vector3,this._positionStart=new i.Vector3,this._quaternionStart=new i.Quaternion,this._scaleStart=new i.Vector3,this._getPointer=tV.bind(this),this._onPointerDown=iV.bind(this),this._onPointerHover=sV.bind(this),this._onPointerMove=rV.bind(this),this._onPointerUp=nV.bind(this),null!==t&&this.connect(t)}connect(e){super.connect(e),this.domElement.addEventListener("pointerdown",this._onPointerDown),this.domElement.addEventListener("pointermove",this._onPointerHover),this.domElement.addEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="none"}disconnect(){this.domElement.removeEventListener("pointerdown",this._onPointerDown),this.domElement.removeEventListener("pointermove",this._onPointerHover),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.domElement.removeEventListener("pointerup",this._onPointerUp),this.domElement.style.touchAction="auto"}getHelper(){return this._root}pointerHover(e){if(void 0===this.object||!0===this.dragging)return;null!==e&&WO.setFromCamera(e,this.camera);const t=oV(this._gizmo.picker[this.mode],WO);this.axis=t?t.object.name:null}pointerDown(e){if(void 0!==this.object&&!0!==this.dragging&&(null==e||0===e.button)&&null!==this.axis){null!==e&&WO.setFromCamera(e,this.camera);const t=oV(this._plane,WO,!0);t&&(this.object.updateMatrixWorld(),this.object.parent.updateMatrixWorld(),this._positionStart.copy(this.object.position),this._quaternionStart.copy(this.object.quaternion),this._scaleStart.copy(this.object.scale),this.object.matrixWorld.decompose(this.worldPositionStart,this.worldQuaternionStart,this._worldScaleStart),this.pointStart.copy(t.point).sub(this.worldPositionStart)),this.dragging=!0,QO.mode=this.mode,this.dispatchEvent(QO)}}pointerMove(e){const t=this.axis,s=this.mode,i=this.object;let r=this.space;if("scale"===s?r="local":"E"!==t&&"XYZE"!==t&&"XYZ"!==t||(r="world"),void 0===i||null===t||!1===this.dragging||null!==e&&-1!==e.button)return;null!==e&&WO.setFromCamera(e,this.camera);const n=oV(this._plane,WO,!0);if(n){if(this.pointEnd.copy(n.point).sub(this.worldPositionStart),"translate"===s)this._offset.copy(this.pointEnd).sub(this.pointStart),"local"===r&&"XYZ"!==t&&this._offset.applyQuaternion(this._worldQuaternionInv),-1===t.indexOf("X")&&(this._offset.x=0),-1===t.indexOf("Y")&&(this._offset.y=0),-1===t.indexOf("Z")&&(this._offset.z=0),"local"===r&&"XYZ"!==t?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),i.position.copy(this._offset).add(this._positionStart),this.translationSnap&&("local"===r&&(i.position.applyQuaternion(XO.copy(this._quaternionStart).invert()),-1!==t.search("X")&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),-1!==t.search("Y")&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),-1!==t.search("Z")&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.position.applyQuaternion(this._quaternionStart)),"world"===r&&(i.parent&&i.position.add(HO.setFromMatrixPosition(i.parent.matrixWorld)),-1!==t.search("X")&&(i.position.x=Math.round(i.position.x/this.translationSnap)*this.translationSnap),-1!==t.search("Y")&&(i.position.y=Math.round(i.position.y/this.translationSnap)*this.translationSnap),-1!==t.search("Z")&&(i.position.z=Math.round(i.position.z/this.translationSnap)*this.translationSnap),i.parent&&i.position.sub(HO.setFromMatrixPosition(i.parent.matrixWorld)))),i.position.x=Math.max(this.minX,Math.min(this.maxX,i.position.x)),i.position.y=Math.max(this.minY,Math.min(this.maxY,i.position.y)),i.position.z=Math.max(this.minZ,Math.min(this.maxZ,i.position.z));else if("scale"===s){if(-1!==t.search("XYZ")){let e=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(e*=-1),qO.set(e,e,e)}else HO.copy(this.pointStart),qO.copy(this.pointEnd),HO.applyQuaternion(this._worldQuaternionInv),qO.applyQuaternion(this._worldQuaternionInv),qO.divide(HO),-1===t.search("X")&&(qO.x=1),-1===t.search("Y")&&(qO.y=1),-1===t.search("Z")&&(qO.z=1);i.scale.copy(this._scaleStart).multiply(qO),this.scaleSnap&&(-1!==t.search("X")&&(i.scale.x=Math.round(i.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),-1!==t.search("Y")&&(i.scale.y=Math.round(i.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),-1!==t.search("Z")&&(i.scale.z=Math.round(i.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if("rotate"===s){this._offset.copy(this.pointEnd).sub(this.pointStart);const e=20/this.worldPosition.distanceTo(HO.setFromMatrixPosition(this.camera.matrixWorld));let s=!1;"XYZE"===t?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(HO.copy(this.rotationAxis).cross(this.eye))*e):"X"!==t&&"Y"!==t&&"Z"!==t||(this.rotationAxis.copy(YO[t]),HO.copy(YO[t]),"local"===r&&HO.applyQuaternion(this.worldQuaternion),HO.cross(this.eye),0===HO.length()?s=!0:this.rotationAngle=this._offset.dot(HO.normalize())*e),("E"===t||s)&&(this.rotationAxis.copy(this.eye),this.rotationAngle=this.pointEnd.angleTo(this.pointStart),this._startNorm.copy(this.pointStart).normalize(),this._endNorm.copy(this.pointEnd).normalize(),this.rotationAngle*=this._endNorm.cross(this._startNorm).dot(this.eye)<0?1:-1),this.rotationSnap&&(this.rotationAngle=Math.round(this.rotationAngle/this.rotationSnap)*this.rotationSnap),"local"===r&&"E"!==t&&"XYZE"!==t?(i.quaternion.copy(this._quaternionStart),i.quaternion.multiply(XO.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),i.quaternion.copy(XO.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),i.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(ZO),this.dispatchEvent(JO)}}pointerUp(e){null!==e&&0!==e.button||(this.dragging&&null!==this.axis&&(KO.mode=this.mode,this.dispatchEvent(KO)),this.dragging=!1,this.axis=null)}dispose(){this.disconnect(),this._root.dispose()}attach(e){return this.object=e,this._root.visible=!0,this}detach(){return this.object=void 0,this.axis=null,this._root.visible=!1,this}reset(){this.enabled&&this.dragging&&(this.object.position.copy(this._positionStart),this.object.quaternion.copy(this._quaternionStart),this.object.scale.copy(this._scaleStart),this.dispatchEvent(ZO),this.dispatchEvent(JO),this.pointStart.copy(this.pointEnd))}getRaycaster(){return WO}getMode(){return this.mode}setMode(e){this.mode=e}setTranslationSnap(e){this.translationSnap=e}setRotationSnap(e){this.rotationSnap=e}setScaleSnap(e){this.scaleSnap=e}setSize(e){this.size=e}setSpace(e){this.space=e}setColors(e,t,s,i){const r=this._gizmo.materialLib;r.xAxis.color.set(e),r.yAxis.color.set(t),r.zAxis.color.set(s),r.active.color.set(i),r.xAxisTransparent.color.set(e),r.yAxisTransparent.color.set(t),r.zAxisTransparent.color.set(s),r.activeTransparent.color.set(i),r.xAxis._color&&r.xAxis._color.set(e),r.yAxis._color&&r.yAxis._color.set(t),r.zAxis._color&&r.zAxis._color.set(s),r.active._color&&r.active._color.set(i),r.xAxisTransparent._color&&r.xAxisTransparent._color.set(e),r.yAxisTransparent._color&&r.yAxisTransparent._color.set(t),r.zAxisTransparent._color&&r.zAxisTransparent._color.set(s),r.activeTransparent._color&&r.activeTransparent._color.set(i)}}function tV(e){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:e.button};{const t=this.domElement.getBoundingClientRect();return{x:(e.clientX-t.left)/t.width*2-1,y:-(e.clientY-t.top)/t.height*2+1,button:e.button}}}function sV(e){if(this.enabled)switch(e.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(e))}}function iV(e){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(e.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(e)),this.pointerDown(this._getPointer(e)))}function rV(e){this.enabled&&this.pointerMove(this._getPointer(e))}function nV(e){this.enabled&&(this.domElement.releasePointerCapture(e.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(e)))}function oV(e,t,s){const i=t.intersectObject(e,!0);for(let e=0;e<i.length;e++)if(i[e].object.visible||s)return i[e];return!1}const aV=new i.Euler,lV=new i.Vector3(0,1,0),hV=new i.Vector3(0,0,0),uV=new i.Matrix4,cV=new i.Quaternion,dV=new i.Quaternion,pV=new i.Vector3,mV=new i.Matrix4,fV=new i.Vector3(1,0,0),gV=new i.Vector3(0,1,0),yV=new i.Vector3(0,0,1),xV=new i.Vector3,bV=new i.Vector3,_V=new i.Vector3;class wV extends i.Object3D{constructor(e){super(),this.isTransformControlsRoot=!0,this.controls=e,this.visible=!1}updateMatrixWorld(e){const t=this.controls;void 0!==t.object&&(t.object.updateMatrixWorld(),null===t.object.parent?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):t.object.parent.matrixWorld.decompose(t._parentPosition,t._parentQuaternion,t._parentScale),t.object.matrixWorld.decompose(t.worldPosition,t.worldQuaternion,t._worldScale),t._parentQuaternionInv.copy(t._parentQuaternion).invert(),t._worldQuaternionInv.copy(t.worldQuaternion).invert()),t.camera.updateMatrixWorld(),t.camera.matrixWorld.decompose(t.cameraPosition,t.cameraQuaternion,t._cameraScale),t.camera.isOrthographicCamera?t.camera.getWorldDirection(t.eye).negate():t.eye.copy(t.cameraPosition).sub(t.worldPosition).normalize(),super.updateMatrixWorld(e)}dispose(){this.traverse(function(e){e.geometry&&e.geometry.dispose(),e.material&&e.material.dispose()})}}class vV extends i.Object3D{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new i.MeshBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new i.LineBasicMaterial({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),s=e.clone();s.opacity=.15;const r=t.clone();r.opacity=.5;const n=e.clone();n.color.setHex(16711680);const o=e.clone();o.color.setHex(65280);const a=e.clone();a.color.setHex(255);const l=e.clone();l.color.setHex(16711680),l.opacity=.5;const h=e.clone();h.color.setHex(65280),h.opacity=.5;const u=e.clone();u.color.setHex(255),u.opacity=.5;const c=e.clone();c.opacity=.25;const d=e.clone();d.color.setHex(16776960),d.opacity=.25;const p=e.clone();p.color.setHex(16776960);const m=e.clone();m.color.setHex(7895160),this.materialLib={xAxis:n,yAxis:o,zAxis:a,active:p,xAxisTransparent:l,yAxisTransparent:h,zAxisTransparent:u,activeTransparent:d};const f=new i.CylinderGeometry(0,.04,.1,12);f.translate(0,.05,0);const g=new i.BoxGeometry(.08,.08,.08);g.translate(0,.04,0);const y=new i.BufferGeometry;y.setAttribute("position",new i.Float32BufferAttribute([0,0,0,1,0,0],3));const x=new i.CylinderGeometry(.0075,.0075,.5,3);function b(e,t){const s=new i.TorusGeometry(e,.0075,3,64,t*Math.PI*2);return s.rotateY(Math.PI/2),s.rotateX(Math.PI/2),s}x.translate(0,.25,0);const _={X:[[new i.Mesh(f,n),[.5,0,0],[0,0,-Math.PI/2]],[new i.Mesh(f,n),[-.5,0,0],[0,0,Math.PI/2]],[new i.Mesh(x,n),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new i.Mesh(f,o),[0,.5,0]],[new i.Mesh(f,o),[0,-.5,0],[Math.PI,0,0]],[new i.Mesh(x,o)]],Z:[[new i.Mesh(f,a),[0,0,.5],[Math.PI/2,0,0]],[new i.Mesh(f,a),[0,0,-.5],[-Math.PI/2,0,0]],[new i.Mesh(x,a),null,[Math.PI/2,0,0]]],XYZ:[[new i.Mesh(new i.OctahedronGeometry(.1,0),c),[0,0,0]]],XY:[[new i.Mesh(new i.BoxGeometry(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new i.Mesh(new i.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new i.Mesh(new i.BoxGeometry(.15,.15,.01),h),[.15,0,.15],[-Math.PI/2,0,0]]]},w={X:[[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new i.Mesh(new i.OctahedronGeometry(.2,0),s)]],XY:[[new i.Mesh(new i.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new i.Mesh(new i.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new i.Mesh(new i.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]]},v={START:[[new i.Mesh(new i.OctahedronGeometry(.01,2),r),null,null,null,"helper"]],END:[[new i.Mesh(new i.OctahedronGeometry(.01,2),r),null,null,null,"helper"]],DELTA:[[new i.Line(function(){const e=new i.BufferGeometry;return e.setAttribute("position",new i.Float32BufferAttribute([0,0,0,1,1,1],3)),e}(),r),null,null,null,"helper"]],X:[[new i.Line(y,r),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new i.Line(y,r),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new i.Line(y,r),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},T={XYZE:[[new i.Mesh(b(.5,1),m),null,[0,Math.PI/2,0]]],X:[[new i.Mesh(b(.5,.5),n)]],Y:[[new i.Mesh(b(.5,.5),o),null,[0,0,-Math.PI/2]]],Z:[[new i.Mesh(b(.5,.5),a),null,[0,Math.PI/2,0]]],E:[[new i.Mesh(b(.75,1),d),null,[0,Math.PI/2,0]]]},S={AXIS:[[new i.Line(y,r),[-1e3,0,0],null,[1e6,1,1],"helper"]]},M={XYZE:[[new i.Mesh(new i.SphereGeometry(.25,10,8),s)]],X:[[new i.Mesh(new i.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new i.Mesh(new i.TorusGeometry(.5,.1,4,24),s),[0,0,0],[Math.PI/2,0,0]]],Z:[[new i.Mesh(new i.TorusGeometry(.5,.1,4,24),s),[0,0,0],[0,0,-Math.PI/2]]],E:[[new i.Mesh(new i.TorusGeometry(.75,.1,2,24),s)]]},A={X:[[new i.Mesh(g,n),[.5,0,0],[0,0,-Math.PI/2]],[new i.Mesh(x,n),[0,0,0],[0,0,-Math.PI/2]],[new i.Mesh(g,n),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new i.Mesh(g,o),[0,.5,0]],[new i.Mesh(x,o)],[new i.Mesh(g,o),[0,-.5,0],[0,0,Math.PI]]],Z:[[new i.Mesh(g,a),[0,0,.5],[Math.PI/2,0,0]],[new i.Mesh(x,a),[0,0,0],[Math.PI/2,0,0]],[new i.Mesh(g,a),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new i.Mesh(new i.BoxGeometry(.15,.15,.01),u),[.15,.15,0]]],YZ:[[new i.Mesh(new i.BoxGeometry(.15,.15,.01),l),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new i.Mesh(new i.BoxGeometry(.15,.15,.01),h),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new i.Mesh(new i.BoxGeometry(.1,.1,.1),c)]]},N={X:[[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,.3,0]],[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new i.Mesh(new i.CylinderGeometry(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new i.Mesh(new i.BoxGeometry(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new i.Mesh(new i.BoxGeometry(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new i.Mesh(new i.BoxGeometry(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new i.Mesh(new i.BoxGeometry(.2,.2,.2),s),[0,0,0]]]},E={X:[[new i.Line(y,r),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new i.Line(y,r),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new i.Line(y,r),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function C(e){const t=new i.Object3D;for(const s in e)for(let i=e[s].length;i--;){const r=e[s][i][0].clone(),n=e[s][i][1],o=e[s][i][2],a=e[s][i][3],l=e[s][i][4];r.name=s,r.tag=l,n&&r.position.set(n[0],n[1],n[2]),o&&r.rotation.set(o[0],o[1],o[2]),a&&r.scale.set(a[0],a[1],a[2]),r.updateMatrix();const h=r.geometry.clone();h.applyMatrix4(r.matrix),r.geometry=h,r.renderOrder=1/0,r.position.set(0,0,0),r.rotation.set(0,0,0),r.scale.set(1,1,1),t.add(r)}return t}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=C(_)),this.add(this.gizmo.rotate=C(T)),this.add(this.gizmo.scale=C(A)),this.add(this.picker.translate=C(w)),this.add(this.picker.rotate=C(M)),this.add(this.picker.scale=C(N)),this.add(this.helper.translate=C(v)),this.add(this.helper.rotate=C(S)),this.add(this.helper.scale=C(E)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(e){const t="local"===("scale"===this.mode?"local":this.space)?this.worldQuaternion:dV;this.gizmo.translate.visible="translate"===this.mode,this.gizmo.rotate.visible="rotate"===this.mode,this.gizmo.scale.visible="scale"===this.mode,this.helper.translate.visible="translate"===this.mode,this.helper.rotate.visible="rotate"===this.mode,this.helper.scale.visible="scale"===this.mode;let s=[];s=s.concat(this.picker[this.mode].children),s=s.concat(this.gizmo[this.mode].children),s=s.concat(this.helper[this.mode].children);for(let e=0;e<s.length;e++){const i=s[e];let r;if(i.visible=!0,i.rotation.set(0,0,0),i.position.copy(this.worldPosition),r=this.camera.isOrthographicCamera?(this.camera.top-this.camera.bottom)/this.camera.zoom:this.worldPosition.distanceTo(this.cameraPosition)*Math.min(1.9*Math.tan(Math.PI*this.camera.fov/360)/this.camera.zoom,7),i.scale.set(1,1,1).multiplyScalar(r*this.size/4),"helper"!==i.tag){if(i.quaternion.copy(t),"translate"===this.mode||"scale"===this.mode){const e=.99,s=.2;"X"===i.name&&Math.abs(lV.copy(fV).applyQuaternion(t).dot(this.eye))>e&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"Y"===i.name&&Math.abs(lV.copy(gV).applyQuaternion(t).dot(this.eye))>e&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"Z"===i.name&&Math.abs(lV.copy(yV).applyQuaternion(t).dot(this.eye))>e&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"XY"===i.name&&Math.abs(lV.copy(yV).applyQuaternion(t).dot(this.eye))<s&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"YZ"===i.name&&Math.abs(lV.copy(fV).applyQuaternion(t).dot(this.eye))<s&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"XZ"===i.name&&Math.abs(lV.copy(gV).applyQuaternion(t).dot(this.eye))<s&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1)}else"rotate"===this.mode&&(cV.copy(t),lV.copy(this.eye).applyQuaternion(XO.copy(t).invert()),-1!==i.name.search("E")&&i.quaternion.setFromRotationMatrix(uV.lookAt(this.eye,hV,gV)),"X"===i.name&&(XO.setFromAxisAngle(fV,Math.atan2(-lV.y,lV.z)),XO.multiplyQuaternions(cV,XO),i.quaternion.copy(XO)),"Y"===i.name&&(XO.setFromAxisAngle(gV,Math.atan2(lV.x,lV.z)),XO.multiplyQuaternions(cV,XO),i.quaternion.copy(XO)),"Z"===i.name&&(XO.setFromAxisAngle(yV,Math.atan2(lV.y,lV.x)),XO.multiplyQuaternions(cV,XO),i.quaternion.copy(XO)));i.visible=i.visible&&(-1===i.name.indexOf("X")||this.showX),i.visible=i.visible&&(-1===i.name.indexOf("Y")||this.showY),i.visible=i.visible&&(-1===i.name.indexOf("Z")||this.showZ),i.visible=i.visible&&(-1===i.name.indexOf("E")||this.showX&&this.showY&&this.showZ),i.material._color=i.material._color||i.material.color.clone(),i.material._opacity=i.material._opacity||i.material.opacity,i.material.color.copy(i.material._color),i.material.opacity=i.material._opacity,this.enabled&&this.axis&&(i.name===this.axis||this.axis.split("").some(function(e){return i.name===e}))&&(i.material.color.copy(this.materialLib.active.color),i.material.opacity=1)}else i.visible=!1,"AXIS"===i.name?(i.visible=!!this.axis,"X"===this.axis&&(XO.setFromEuler(aV.set(0,0,0)),i.quaternion.copy(t).multiply(XO),Math.abs(lV.copy(fV).applyQuaternion(t).dot(this.eye))>.9&&(i.visible=!1)),"Y"===this.axis&&(XO.setFromEuler(aV.set(0,0,Math.PI/2)),i.quaternion.copy(t).multiply(XO),Math.abs(lV.copy(gV).applyQuaternion(t).dot(this.eye))>.9&&(i.visible=!1)),"Z"===this.axis&&(XO.setFromEuler(aV.set(0,Math.PI/2,0)),i.quaternion.copy(t).multiply(XO),Math.abs(lV.copy(yV).applyQuaternion(t).dot(this.eye))>.9&&(i.visible=!1)),"XYZE"===this.axis&&(XO.setFromEuler(aV.set(0,Math.PI/2,0)),lV.copy(this.rotationAxis),i.quaternion.setFromRotationMatrix(uV.lookAt(hV,lV,gV)),i.quaternion.multiply(XO),i.visible=this.dragging),"E"===this.axis&&(i.visible=!1)):"START"===i.name?(i.position.copy(this.worldPositionStart),i.visible=this.dragging):"END"===i.name?(i.position.copy(this.worldPosition),i.visible=this.dragging):"DELTA"===i.name?(i.position.copy(this.worldPositionStart),i.quaternion.copy(this.worldQuaternionStart),HO.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),HO.applyQuaternion(this.worldQuaternionStart.clone().invert()),i.scale.copy(HO),i.visible=this.dragging):(i.quaternion.copy(t),this.dragging?i.position.copy(this.worldPositionStart):i.position.copy(this.worldPosition),this.axis&&(i.visible=-1!==this.axis.search(i.name)))}super.updateMatrixWorld(e)}}class TV extends i.Mesh{constructor(){super(new i.PlaneGeometry(1e5,1e5,2,2),new i.MeshBasicMaterial({visible:!1,wireframe:!0,side:i.DoubleSide,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(e){let t=this.space;switch(this.position.copy(this.worldPosition),"scale"===this.mode&&(t="local"),xV.copy(fV).applyQuaternion("local"===t?this.worldQuaternion:dV),bV.copy(gV).applyQuaternion("local"===t?this.worldQuaternion:dV),_V.copy(yV).applyQuaternion("local"===t?this.worldQuaternion:dV),lV.copy(bV),this.mode){case"translate":case"scale":switch(this.axis){case"X":lV.copy(this.eye).cross(xV),pV.copy(xV).cross(lV);break;case"Y":lV.copy(this.eye).cross(bV),pV.copy(bV).cross(lV);break;case"Z":lV.copy(this.eye).cross(_V),pV.copy(_V).cross(lV);break;case"XY":pV.copy(_V);break;case"YZ":pV.copy(xV);break;case"XZ":lV.copy(_V),pV.copy(bV);break;case"XYZ":case"E":pV.set(0,0,0)}break;default:pV.set(0,0,0)}0===pV.length()?this.quaternion.copy(this.cameraQuaternion):(mV.lookAt(HO.set(0,0,0),pV,lV),this.quaternion.setFromRotationMatrix(mV)),super.updateMatrixWorld(e)}}class SV{constructor(e,s,i,r,n,o=5,a=!0){var h;if(t(this,"onDraggingStarted",new u),t(this,"onDraggingEnded",new u),t(this,"onDisposed",new u),t(this,"normal"),t(this,"origin"),t(this,"three",new l.Plane),t(this,"components"),t(this,"world"),t(this,"type","default"),t(this,"_title","Clipping Plane"),t(this,"_helper"),t(this,"_visible",!0),t(this,"_enabled",!0),t(this,"_controlsActive",!1),t(this,"_arrowBoundBox",new l.Mesh),t(this,"_planeMesh"),t(this,"_controls"),t(this,"_hiddenMaterial",new l.MeshBasicMaterial({visible:!1})),t(this,"_sizeMultiplier",5),t(this,"_autoScale",!0),t(this,"_visibilityBeforeDisabled",!0),t(this,"notifyManager",()=>{const e=this.components.get(NV),t=e.list.getKey(this);t&&e.list.set(t,this)}),t(this,"update",()=>{this._enabled&&(this.three.setFromNormalAndCoplanarPoint(this.normal,this._helper.position),this.updateScale())}),t(this,"updateScale",()=>{var e;if(!this.autoScale)return;const t=null==(e=this.world.camera)?void 0:e.three;if(!t)return;if(!(t instanceof l.PerspectiveCamera))return;const s=new l.Vector3;t.getWorldPosition(s);const i=s.distanceTo(this._helper.position)/7*this._sizeMultiplier;this._planeMesh.scale.set(i,i,i)}),t(this,"changeDrag",e=>{this._visible=!e.value,this.preventCameraMovement(),this.notifyDraggingChanged(e)}),this.components=e,this.world=s,!s.renderer)throw new Error("The given world must have a renderer!");this.normal=r,this.origin=i,this._sizeMultiplier=o,s.renderer.setPlane(!0,this.three),this._planeMesh=SV.newPlaneMesh(o,n),this._helper=this.newHelper(),this._controls=this.newTransformControls(),this.three.setFromNormalAndCoplanarPoint(r,i),a&&this.toggleControls(!0),this.updateScale(),(null==(h=s.camera)?void 0:h.controls)&&s.camera.controls.addEventListener("update",this.updateScale)}set title(e){this._title=e,this.notifyManager()}get title(){return this._title}get autoScale(){return this._autoScale}set autoScale(e){this._autoScale=e,e&&this.updateScale()}get enabled(){return this._enabled}set enabled(e){if(!this.world.isDisposing){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");this._enabled=e,e?this.visible=this._visibilityBeforeDisabled:(this._visibilityBeforeDisabled=this.visible,this.visible=!1),this.world.renderer.setPlane(e,this.three),this.notifyManager()}}get visible(){return this._visible}set visible(e){this._visible=e,this._controls.getHelper().visible=e,this._helper.visible=e,this.toggleControls(e),this.notifyManager()}get meshes(){return[this._planeMesh,this._arrowBoundBox]}get planeMaterial(){return this._planeMesh.material}set planeMaterial(e){this._planeMesh.material=e}get size(){return this._sizeMultiplier}set size(e){this._sizeMultiplier=e,this.autoScale?this.updateScale():this._planeMesh.scale.set(e,e,e)}get helper(){return this._helper}get controls(){return this._controls}setFromNormalAndCoplanarPoint(e,t){this.reset(),this.normal.equals(e)||(this.normal.copy(e),this._helper.lookAt(e)),this.origin.copy(t),this._helper.position.copy(t),this._helper.updateMatrix(),this.update()}dispose(){var e;this._enabled=!1,(null==(e=this.world.camera)?void 0:e.controls)&&this.world.camera.controls.removeEventListener("update",this.updateScale),this.onDraggingStarted.reset(),this.onDraggingEnded.reset(),this._helper.removeFromParent(),this.world.renderer&&this.world.renderer.setPlane(!1,this.three),this._arrowBoundBox.removeFromParent(),this._arrowBoundBox.geometry.dispose(),this._planeMesh.geometry.dispose(),this._controls.getHelper().removeFromParent(),this._controls.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}reset(){const e=new l.Vector3(1,0,0),t=new l.Vector3;this.normal.equals(e)||(this.normal.copy(e),this._helper.lookAt(e)),this.origin.copy(t),this._helper.position.copy(t),this._helper.updateMatrix()}toggleControls(e){if(e){if(this._controlsActive)return;this._controls.addEventListener("change",this.update),this._controls.addEventListener("dragging-changed",this.changeDrag)}else this._controls.removeEventListener("change",this.update),this._controls.removeEventListener("dragging-changed",this.changeDrag);this._controlsActive=e}newTransformControls(){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");const e=this.world.camera.three,t=this.world.renderer.three.domElement,s=new eV(e,t);return this.initializeControls(s),this.world.scene.three.add(s.getHelper()),s}initializeControls(e){e.attach(this._helper),e.showX=!1,e.showY=!1,e.setSpace("local"),this.createArrowBoundingBox(),e.getHelper().children[0].children[0].add(this._arrowBoundBox)}createArrowBoundingBox(){this._arrowBoundBox.geometry=new l.CylinderGeometry(.18,.18,1.2),this._arrowBoundBox.material=this._hiddenMaterial,this._arrowBoundBox.rotateX(Math.PI/2),this._arrowBoundBox.updateMatrix(),this._arrowBoundBox.geometry.applyMatrix4(this._arrowBoundBox.matrix)}notifyDraggingChanged(e){e.value?this.onDraggingStarted.trigger():this.onDraggingEnded.trigger()}preventCameraMovement(){this.world.camera.enabled=this._visible}newHelper(){const e=new l.Object3D;return e.lookAt(this.normal),e.position.copy(this.origin),this._planeMesh.position.z+=.01,e.add(this._planeMesh),this.world.scene.three.add(e),e}static newPlaneMesh(e,t){const s=new l.PlaneGeometry(1),i=new l.Mesh(s,t);return i.scale.set(e,e,e),i}}class MV extends ke{constructor(){super(...arguments),t(this,"_config",{enabled:{value:!0,type:"Boolean"},visible:{value:!0,type:"Boolean"},color:{value:new l.Color,type:"Color"},opacity:{type:"Number",interpolable:!0,value:1,min:0,max:1},size:{type:"Number",interpolable:!0,value:2,min:0,max:100}})}get enabled(){return this._config.enabled.value}set enabled(e){this._config.enabled.value=e,this._component.enabled=e}get visible(){return this._config.visible.value}set visible(e){this._config.visible.value=e,this._component.visible=e}get color(){return this._config.color.value}set color(e){this._config.color.value=e,this._component.material.color.copy(e)}get opacity(){return this._config.opacity.value}set opacity(e){this._config.opacity.value=e,this._component.material.opacity=e}get size(){return this._config.size.value}set size(e){this._config.size.value=e,this._component.size=e}}const AV=class e extends d{constructor(s){super(s),t(this,"onSetup",new u),t(this,"onBeforeDrag",new u),t(this,"onAfterDrag",new u),t(this,"onBeforeCreate",new u),t(this,"onBeforeCancel",new u),t(this,"onAfterCancel",new u),t(this,"onBeforeDelete",new u),t(this,"onAfterCreate",new u),t(this,"onAfterDelete",new u),t(this,"onDisposed",new u),t(this,"isSetup",!1),t(this,"orthogonalY",!1),t(this,"toleranceOrthogonalY",.7),t(this,"autoScalePlanes",!0),t(this,"Type",SV),t(this,"list",new a.DataMap),t(this,"config",new MV(this,this.components,"Clipper",e.uuid)),t(this,"_defaultConfig",{color:new l.Color(12255487),opacity:.2,size:2}),t(this,"_material",new l.MeshBasicMaterial({color:12255487,side:l.DoubleSide,transparent:!0,opacity:.2})),t(this,"_size",5),t(this,"_enabled",!1),t(this,"_visible",!0),t(this,"onStateChanged",new u),this.components.add(e.uuid,this),this.setEvents()}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this.onStateChanged.trigger(["enabled"])}get visible(){return this._visible}set visible(e){this._visible=e;for(const[t,s]of this.list)s.visible=e;this.onStateChanged.trigger(["visibility"])}get material(){return this._material}set material(e){this._material=e;for(const[t,s]of this.list)s.planeMaterial=e;this.onStateChanged.trigger(["material"])}get size(){return this._size}set size(e){this._size=e;for(const[t,s]of this.list)s.size=e;this.onStateChanged.trigger(["size"])}setEvents(){this.list.onBeforeDelete.add(({value:e})=>{if(!e.world.renderer)throw new Error("Renderer not found for this plane's world!");e.world.renderer.setPlane(!1,e.three),e.dispose(),this.updateMaterialsAndPlanes(),this.onAfterDelete.trigger(e)})}dispose(){this._enabled=!1;this.components.get(Ge).list.delete(this.config.uuid),this.list.clear(),this._material.dispose(),this.onBeforeCreate.reset(),this.onBeforeCancel.reset(),this.onBeforeDelete.reset(),this.onBeforeDrag.reset(),this.onAfterCreate.reset(),this.onAfterCancel.reset(),this.onAfterDelete.reset(),this.onAfterDrag.reset(),this.onDisposed.trigger(e.uuid),this.onDisposed.reset()}async create(e){const t=this.components.get(dO).get(e),s=await t.castRay();return s?this.createPlaneFromIntersection(e,s):null}createFromNormalAndCoplanarPoint(e,t,s){const i=this.newPlane(e,s,t);return this.updateMaterialsAndPlanes(),i}async delete(e,t){if(!t){const s=await this.pickPlane(e);if(!s)return;t=this.list.getKey(s)}t&&this.list.delete(t)}deleteAll(e){for(const[t,s]of this.list)e&&!e.has(s.type)||this.list.delete(t)}setup(e){const t={...this._defaultConfig,...e};this.config.color=t.color,this.config.opacity=t.opacity,this.config.size=t.size,this.isSetup=!0,this.onSetup.trigger()}pickPlane(e){const t=this.components.get(dO).get(e),s=this.getAllPlaneMeshes(),i=t.castRayToObjects(s);if(i){const e=i.object;return[...this.list.values()].find(t=>t.meshes.includes(e))}}getAllPlaneMeshes(){const e=[];for(const[t,s]of this.list)e.push(...s.meshes);return e}createPlaneFromIntersection(e,t){var s;if(!e.renderer)throw new Error("The given world must have a renderer!");const i=t.point.distanceTo(new l.Vector3(0,0,0)),r=t.normal||(null==(s=t.face)?void 0:s.normal);if(!i||!r)return null;const n=this.getWorldNormal(t,r),o=this.newPlane(e,t.point,n.negate()),a=this.list.get(o);return a.visible=this._visible,a.size=this._size,e.renderer.setPlane(!0,a.three),this.updateMaterialsAndPlanes(),a}getWorldNormal(e,t){const s=e.object;let i=e.object.matrixWorld.clone();if(s instanceof l.InstancedMesh&&void 0!==e.instanceId){const t=new l.Matrix4;s.getMatrixAt(e.instanceId,t),i=t.multiply(i)}const r=(new l.Matrix3).getNormalMatrix(i),n=t.clone().applyMatrix3(r).normalize();return this.normalizePlaneDirectionY(n),n}normalizePlaneDirectionY(e){this.orthogonalY&&(e.y>this.toleranceOrthogonalY&&(e.x=0,e.y=1,e.z=0),e.y<-this.toleranceOrthogonalY&&(e.x=0,e.y=-1,e.z=0))}newPlane(e,t,s){const i=new this.Type(this.components,e,t,s,this._material);i.autoScale=this.autoScalePlanes,i.onDraggingStarted.add(()=>this.onBeforeDrag.trigger(i)),i.onDraggingEnded.add(()=>this.onAfterDrag.trigger(i));const r=w.create();return this.list.set(r,i),this.onAfterCreate.trigger(i),r}updateMaterialsAndPlanes(){const e=this.components.get(wO);for(const[t,s]of e.list){if(!s.renderer)continue;s.renderer.updateClippingPlanes();const{clippingPlanes:e}=s.renderer;for(const t of s.meshes)if(t.material)if(Array.isArray(t.material))for(const s of t.material)s.clippingPlanes=e;else t.material.clippingPlanes=e}}};t(AV,"uuid","66290bc5-18c4-4cd1-9379-2e17a0617611");let NV=AV;class EV{constructor(e,s){t(this,"title"),t(this,"guid",w.create()),t(this,"clippingPlanes",new a.DataSet),t(this,"camera",{aspect_ratio:1,field_of_view:60,camera_direction:{x:0,y:0,z:0},camera_view_point:{x:0,y:0,z:0},camera_up_vector:{x:0,y:1,z:0}}),t(this,"customData",{}),t(this,"exceptionComponents",new a.DataSet),t(this,"selectionComponents",new a.DataSet),t(this,"componentColors",new a.DataMap),t(this,"spacesVisible",!1),t(this,"spaceBoundariesVisible",!1),t(this,"openingsVisible",!1),t(this,"defaultVisibility",!0),t(this,"snapshot",this.guid),t(this,"_components"),t(this,"_world",null),t(this,"notifyUpdate",()=>{this._components.get(PV).list.set(this.guid,this)}),this._components=e,s&&(this.guid=s.guid??this.guid,this.set(s)),this.setEvents()}async getSelectionMap(){const e=this._components.get(ji);return await e.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const e=this._components.get(ji);return await e.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const e=this._components.get(ji),{camera_view_point:t}=this.camera,{x:s,y:i,z:r}=t,n=new l.Vector3(s,i,r);return e.applyBaseCoordinateSystem(n,new l.Matrix4),n}set position(e){const t=e.clone(),s=this._components.get(ji);e.clone().applyMatrix4(s.baseCoordinationMatrix.clone().invert()),this.camera.camera_view_point={x:t.x,y:t.y,z:t.z}}get direction(){const{camera_direction:e}=this.camera,{x:t,y:s,z:i}=e;return new l.Vector3(t,s,i)}set world(e){this._world=e}get world(){return this._world}get _managerVersion(){return this._components.get($O).config.version}get topics(){return[...this._components.get($O).list.values()].filter(e=>e.viewpoints.has(this.guid))}setEvents(){this.selectionComponents.onUpdated.add(this.notifyUpdate),this.exceptionComponents.onUpdated.add(this.notifyUpdate),this.clippingPlanes.onUpdated.add(this.notifyUpdate),this.componentColors.onItemSet.add(this.notifyUpdate),this.componentColors.onItemDeleted.add(this.notifyUpdate),this.componentColors.onItemUpdated.add(this.notifyUpdate),this.componentColors.onCleared.add(this.notifyUpdate)}set(e){this.title=e.title;const{components:t,perspective_camera:s,orthogonal_camera:i,clipping_planes:r}=e;if(t){const{selection:e,visibility:s,coloring:i}=t;if(e){this.selectionComponents.clear();for(const{ifc_guid:t}of e)t&&this.selectionComponents.add(t)}if(s){const{default_visibility:e,exceptions:t,view_setup_hints:i}=s;if(void 0!==e&&(this.defaultVisibility=e),t){this.exceptionComponents.clear();for(const{ifc_guid:e}of t)e&&this.exceptionComponents.add(e)}if(i){const{spaces_visible:e,space_boundaries_visible:t,openings_visible:s}=i;void 0!==e&&(this.spacesVisible=e),void 0!==t&&(this.spaceBoundariesVisible=t),void 0!==s&&(this.openingsVisible=s)}}if(i){this.componentColors.clear();for(const e of i){const{color:t,components:s}=e,i=s.map(e=>e.ifc_guid).filter(e=>null!==e);this.componentColors.set(t,i)}}}if((s||i)&&(this.camera=s??i),r&&this.world){const e=this._components.get(NV);for(const t of r){const{location:s,direction:i}=t,r=new l.Vector3(s.x,s.z,-s.y),n=new l.Vector3(i.x,i.z,-i.y),o=e.createFromNormalAndCoplanarPoint(this.world,n,r);this.clippingPlanes.add(o),e.list.get(o).enabled=!1,e.list.get(o).visible=!1}}this.notifyUpdate()}async go(e){if(!this.world)return;const{camera:t}=this.world;if(!(t instanceof BO))throw new Error("Viewpoint: the world's camera component must be of type OrthoPerspectiveCamera to switch between perspective and orthographic projections.");const{transition:s,applyClippings:i,applyVisibility:r,clippingsVisibility:n}={transition:!0,applyClippings:!0,applyVisibility:!0,clippingsVisibility:!0,...e};t.projection.set(this.projection);const o=new l.Vector3(this.camera.camera_view_point.x,this.camera.camera_view_point.y,this.camera.camera_view_point.z),a=new l.Vector3(this.camera.camera_direction.x,this.camera.camera_direction.y,this.camera.camera_direction.z);if(o.equals(new l.Vector3)&&a.equals(new l.Vector3))return;const h=this.position,u=this.direction,c={x:h.x+80*u.x,y:h.y+80*u.y,z:h.z+80*u.z},d=[];i&&this.setClippingState(!0),r&&d.push(this.applyVisibility()),this.setClippingVisibility(n),d.push(t.controls.setLookAt(h.x,h.y,h.z,c.x,c.y,c.z,s)),await Promise.all(d)}async updateCamera(e=!0){return new Promise(t=>{if(!this.world)return void t(!1);const{camera:s,renderer:i}=this.world;if(!i)throw new Error("Viewpoint: the world needs to have a renderer!");if(!s.hasCameraControls())throw new Error("Viewpoint: world's camera need camera controls!");const r=new l.Vector3;s.controls.getPosition(r);const n=s.three,o=new l.Vector3(0,0,-1).applyEuler(n.rotation),{width:a,height:h}=i.getSize();let u=a/h;Number.isNaN(u)&&(u=1);const c=this._components.get(ji);r.applyMatrix4(c.baseCoordinationMatrix.clone().invert());const d={aspect_ratio:u,camera_view_point:{x:r.x,y:r.y,z:r.z},camera_direction:{x:o.x,y:o.y,z:o.z},camera_up_vector:{x:0,y:1,z:0}};if(n instanceof l.PerspectiveCamera?this.camera={...d,field_of_view:n.fov}:n instanceof l.OrthographicCamera&&(this.camera={...d,view_to_world_scale:n.top-n.bottom}),e){const e=this._components.get(PV),r=i.three.domElement;i.three.render(this.world.scene.three,s.three),r.toBlob(async s=>{if(s){const t=await s.arrayBuffer(),i=new Uint8Array(t);e.snapshots.set(this.guid,i)}this.notifyUpdate(),t(!0)})}else this.notifyUpdate(),t(!0)})}takeSnapshot(){return new Promise(e=>{if(!this.world)return void e(!1);const{camera:t,renderer:s}=this.world;if(!s)throw new Error("Viewpoint: the world needs to have a renderer!");const i=this._components.get(PV),r=s.three.domElement;s.three.render(this.world.scene.three,t.three),r.toBlob(async t=>{if(t){const e=await t.arrayBuffer(),s=new Uint8Array(e);i.snapshots.set(this.guid,s)}this.notifyUpdate(),e(!0)})})}updateClippingPlanes(){this.clippingPlanes.clear();const e=this._components.get(NV);for(const[t,s]of e.list)s.enabled&&this.clippingPlanes.add(t)}async applyVisibility(){const e=this._components.get(JF);e.set(this.defaultVisibility);const t=await this.getExceptionMap();e.set(!this.defaultVisibility,t);const s=await this.getSelectionMap();e.set(!0,s)}async setColorizationState(e){const t=this._components.get(ji),s=[];if(e)for(const[e,i]of this.componentColors){const r=`#${e}`,n=await t.guidsToModelIdMap(i);for(const[e,i]of Object.entries(n)){const n=t.list.get(e);n&&s.push(n.highlight([...i],{customId:r,color:new l.Color(r),renderedFaces:a.RenderedFaces.ONE,opacity:1,transparent:!1}))}}else for(const[e,i]of this.componentColors){const e=await t.guidsToModelIdMap(i);for(const[i,r]of Object.entries(e)){const e=t.list.get(i);e&&s.push(e.resetHighlight([...r]))}}s.push(t.core.update(!0)),await Promise.all(s)}setClippingState(e){const t=this._components.get(NV);for(const[s,i]of t.list)i.enabled=e&&this.clippingPlanes.has(s)}setClippingVisibility(e){const t=this._components.get(NV);for(const s of this.clippingPlanes){const i=t.list.get(s);i&&(i.visible=e)}}async createComponentTags(e){var t;const s=this._components.get(ji);let i="";if(this._components.get($O).config.includeSelectionTag){const r="selection"===e?await this.getSelectionMap():await this.getExceptionMap();for(const e in r){const n=s.list.get(e);if(!n)continue;const o=r[e];for(const e of o){const s=n.getItem(e),r=await s.getGuid();if(!r)continue;const o=null==(t=await s.getAttributes())?void 0:t.getValue("Tag");let a=null;o&&(a=`AuthoringToolId="${o}"`),i+=`\n<Component IfcGuid="${r}" ${a??""} />`}}}else i=[...this.selectionComponents].map(e=>`<Component IfcGuid="${e}" />`).join("\n");return i}createColorTags(){let e="";for(const[t,s]of this.componentColors.entries()){e+=`<Color Color="${t}">\n${s.map(e=>`\n<Component IfcGuid="${e}" />`).join("\n")}\n</Color>`}return 0!==e.length?`<Coloring>\n${e}\n</Coloring>`:"<Coloring />"}toJSON(){const e=this._components.get(NV),t={guid:this.guid,components:{selection:[...this.selectionComponents].map(e=>({ifc_guid:e,authoring_tool_id:null})),coloring:[...this.componentColors].map(([e,t])=>({color:e,components:t.map(e=>({ifc_guid:e,authoring_tool_id:null}))})),visibility:{default_visibility:this.defaultVisibility,exceptions:[...this.exceptionComponents].map(e=>({ifc_guid:e,authoring_tool_id:null})),view_setup_hints:{spaces_visible:this.spacesVisible,space_boundaries_visible:this.spaceBoundariesVisible,openings_visible:this.openingsVisible}}},clipping_planes:[...this.clippingPlanes].map(t=>{const s=e.list.get(t);if(!s)return null;const i=s._controls.worldPosition??s.origin,{normal:r}=s;return{location:{x:i.x,y:-i.z,z:i.y},direction:{x:r.x,y:-r.z,z:r.y}}}).filter(e=>null!==e)};"field_of_view"in this.camera?t.perspective_camera=this.camera:t.orthogonal_camera=this.camera;const s=this._components.get(PV),i=s.snapshots.get(this.snapshot);if(i){const e=i.toString(),r=btoa(e),n=s.getSnapshotExtension(this.snapshot);t.snapshot={snapshot_type:n,snapshot_data:r}}return t}async serialize(e=this._managerVersion){const t=this._components.get(ji),s=this.position;s.applyMatrix4(t.baseCoordinationMatrix.clone().invert());const i=this.direction;i.normalize();const r=(new l.Matrix4).makeRotationX(Math.PI/2),n=i.clone().applyMatrix4(r);n.normalize();const o=`<CameraViewPoint>\n <X>${s.x}</X>\n <Y>${-s.z}</Y>\n <Z>${s.y}</Z>\n </CameraViewPoint>`,a=`<CameraDirection>\n <X>${i.x}</X>\n <Y>${-i.z}</Y>\n <Z>${i.y}</Z>\n </CameraDirection>`,h=`<CameraUpVector>\n <X>${n.x}</X>\n <Y>${-n.z}</Y>\n <Z>${n.y}</Z>\n </CameraUpVector>`,u=`<AspectRatio>${this.camera.aspect_ratio}</AspectRatio>`;let c="";"view_to_world_scale"in this.camera?c=`<OrthogonalCamera>\n ${o}\n ${a}\n ${h}\n ${u}\n <ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>\n </OrthogonalCamera>`:"field_of_view"in this.camera&&(c=`<PerspectiveCamera>\n ${o}\n ${a}\n ${h}\n ${u}\n <FieldOfView>${this.camera.field_of_view}</FieldOfView>\n </PerspectiveCamera>`);const d=`<ViewSetupHints SpacesVisible="${this.spacesVisible??!1}" SpaceBoundariesVisible="${this.spaceBoundariesVisible??!1}" OpeningsVisible="${this.openingsVisible??!1}" />`,p=(await this.createComponentTags("selection")).trim(),m=(await this.createComponentTags("exception")).trim(),f=this.createColorTags();return`<?xml version="1.0" encoding="UTF-8"?>\n <VisualizationInfo Guid="${this.guid}">\n <Components>\n ${"2.1"===e?d:""}\n ${0!==p.length?`<Selection>${p}</Selection>`:""}\n <Visibility DefaultVisibility="${this.defaultVisibility}">\n ${"3"===e?d:""}\n ${0!==m.length?`<Exceptions>${m}</Exceptions>`:""}\n </Visibility>\n ${f}\n </Components>\n ${c}\n </VisualizationInfo>`}}class CV extends ke{constructor(){super(...arguments),t(this,"_config",{overwriteColors:{value:!1,type:"Boolean"}})}get overwriteColors(){return this._config.overwriteColors.value}set overwriteColors(e){this._config.overwriteColors.value=e}}const RV=class e extends d{constructor(i){super(i),t(this,"enabled",!0),t(this,"world",null),t(this,"list",new s.DataMap),t(this,"snapshots",new s.DataMap),t(this,"isSetup",!1),t(this,"onSetup",new u),t(this,"config",new CV(this,this.components,"Viewpoints",e.uuid)),t(this,"onDisposed",new u),i.add(e.uuid,this)}create(e){const t=new EV(this.components,e);return t.world=this.world,e||this.list.set(t.guid,t),t}getSnapshotExtension(e){let t="jpeg";const s=this.snapshots.get(e);if(!s)return t;const i=s.subarray(0,4);let r="";for(let e=0;e<i.length;e++)r+=i[e].toString(16);return r.startsWith("89504e47")&&(t="png"),r.startsWith("ffd8ffe")&&(t="jpeg"),t}setup(){}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}};t(RV,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");let PV=RV;class BV{constructor(e,s){t(this,"_components"),t(this,"_cameraOffset",10),t(this,"_planeHelper"),t(this,"_farPlaneHelper"),t(this,"_cameraHelper"),t(this,"onStateChanged",new u),t(this,"onUpdated",new u),t(this,"onDisposed",new u),t(this,"camera"),t(this,"plane",new l.Plane),t(this,"farPlane",new l.Plane),t(this,"id",w.create()),t(this,"_open",!1),t(this,"_range",DV.defaultRange),t(this,"_world",null),t(this,"_helpersVisible",!1),t(this,"_planesEnabled",!1),this._components=e,this.camera=new BO(this._components);const{threeOrtho:i}=this.camera;if((null==s?void 0:s.id)&&(this.id=s.id),(null==s?void 0:s.normal)&&(null==s?void 0:s.point)){const{normal:e,point:t}=s;this.plane.setFromNormalAndCoplanarPoint(e,t)}this._cameraHelper=new l.CameraHelper(i),this._planeHelper=new l.PlaneHelper(this.plane,50),this._farPlaneHelper=new l.PlaneHelper(this.farPlane,50),this.farPlaneHelperColor=new l.Color("blue"),this.update()}get _planeNormalOpposite(){return this.plane.normal.clone().negate()}get _planePosition(){return this.plane.normal.clone().multiplyScalar(-this.plane.constant)}get _cameraPosition(){return this._planePosition.addScaledVector(this._planeNormalOpposite,this._cameraOffset)}set open(e){this._open=e,this.onStateChanged.trigger(["open"])}get open(){return this._open}set planeHelperColor(e){!Array.isArray(this._planeHelper.material)&&"color"in this._planeHelper.material&&this._planeHelper.material.color instanceof l.Color&&(this._planeHelper.material.color=e)}set farPlaneHelperColor(e){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof l.Color&&(this._farPlaneHelper.material.color=e)}set range(e){this._range=e,this.update()}get range(){return this._range}set distance(e){this.plane.constant=e,this.update()}get distance(){return this.plane.constant}set world(e){this._world=e,this.camera.currentWorld=e,e&&(this.camera.projection.set("Orthographic"),this.camera.set("Plan"),this.camera.controls.dollySpeed=6,this.camera.controls.restThreshold=.005,this.update())}get world(){return this._world}set helpersVisible(e){if(!e)return this._helpersVisible=e,this._planeHelper.removeFromParent(),this._farPlaneHelper.removeFromParent(),void this._cameraHelper.removeFromParent();this.world&&(this._helpersVisible=e,this.world.scene.three.add(this._planeHelper,this._farPlaneHelper))}get helpersVisible(){return this._helpersVisible}set planesEnabled(e){const{world:t}=this;if(!t)return;const{renderer:s}=t;s&&(s.setPlane(e,this.plane),s.setPlane(e,this.farPlane),this._planesEnabled=e)}get planesEnabled(){return this._planesEnabled}dispose(){this.helpersVisible=!1;const e=this._components.get(y);e.destroy(this._planeHelper),e.destroy(this._farPlaneHelper),e.destroy(this._cameraHelper),this.camera.dispose(),this.onDisposed.trigger()}update(){if(this.world){const e=this._cameraPosition,t=this._planePosition;this.camera.controls.setLookAt(e.x,e.y,e.z,t.x,t.y,t.z,!1)}this.farPlane.normal.copy(this._planeNormalOpposite),this.farPlane.constant=this.range-this.plane.constant,this.onUpdated.trigger()}flip(){this.plane.normal.negate(),this.update()}}const IV=class e extends d{constructor(i){super(i),t(this,"list",new s.DataMap),t(this,"enabled",!0),t(this,"world",null),t(this,"_fragmentsUpdateEvent",()=>{this.components.get(ji).core.update(!0)}),i.add(e.uuid,this),this.setupEvents()}get hasOpenViews(){return[...this.list.values()].some(e=>e.open)}setupEvents(){this.list.onBeforeDelete.add(({key:e,value:t})=>{t.open&&this.close(e),t.dispose()})}create(e,t,s){const i=new BV(this.components,{id:null==s?void 0:s.id,normal:e,point:t});return i.world=(null==s?void 0:s.world)??this.world,this.list.set(i.id,i),i}createFromPlane(e,t){const s=new BV(this.components,{id:null==t?void 0:t.id});return s.plane.copy(e),s.update(),s.world=(null==t?void 0:t.world)??this.world,this.list.set(s.id,s),s}async createFromIfcStoreys(e){const t=[],s=this.components.get(ji),i=void 0===(null==e?void 0:e.offset)?.25:e.offset;for(const[r,n]of s.list){if(e&&e.modelIds&&!e.modelIds.some(e=>e.test(r)))continue;const s=Object.values(await n.getItemsOfCategories([/BUILDINGSTOREY/])).flat();if(0===s.length)continue;const o=await n.getItemsData(s),[,a]=await n.getCoordinates(),h=new l.Vector3(0,-1,0);for(const s of o){if(!("value"in s.Name)||!("value"in s.Elevation))continue;const{value:r}=s.Name;if((null==e?void 0:e.storeyNames)&&!e.storeyNames.some(e=>e.test(r)))continue;const n=s.Elevation.value+a+i,o=new l.Plane(h,n),u=this.createFromPlane(o,{id:r,world:null==e?void 0:e.world});t.push(u)}}return t}createElevations(e){const t=[],s=this.components.get(ji),i=void 0!==(null==e?void 0:e.combine)&&e.combine,r=(null==e?void 0:e.namingCallback)??(e=>({front:""+(i?"Front":`${e}: Front`),back:""+(i?"Back":`${e}: Back`),left:""+(i?"Left":`${e}: Left`),right:""+(i?"Right":`${e}: Right`)}));let n=[];for(const[t,i]of s.list)e&&e.modelIds&&!e.modelIds.some(e=>e.test(t))||n.push({id:t,box:i.box});if(0===n.length)return t;if(i){const e=this.components.get(tO);e.list.clear(),e.list.add(...n.map(e=>e.box));n=[{id:"combined",box:e.get()}]}for(const{id:s,box:i}of n){const{min:n,max:o}=i,a=Math.abs(o.x-n.x),h=Math.abs(o.z-n.z),u=new l.Vector3;i.getCenter(u);const c=new l.Plane(new l.Vector3(0,0,-1),o.z),d=new l.Plane(new l.Vector3(0,0,1),-n.z),p=new l.Plane(new l.Vector3(-1,0,0),o.x),m=new l.Plane(new l.Vector3(1,0,0),-n.x),{front:f,back:g,left:y,right:x}=r(s),b=this.createFromPlane(c,{id:f,world:null==e?void 0:e.world});b.range=h;const _=this.createFromPlane(d,{id:g,world:null==e?void 0:e.world});_.range=h;const w=this.createFromPlane(p,{id:y,world:null==e?void 0:e.world});w.range=a;const v=this.createFromPlane(m,{id:x,world:null==e?void 0:e.world});v.range=a,t.push(b,_,w,v)}return t}open(e){const t=this.list.get(e);if(!t)throw new Error(`Views: the view with id ${e} doesn't exist.`);if(t.open)return;const{world:s}=t;if(!s)throw new Error(`Views: no world found for view with id ${e}.`);const{renderer:i}=s;if(!i)throw new Error(`Views: no renderer found for world with id ${s.uuid}.`);for(const[,e]of this.list)e.world===s&&this.close(e.id);i.setPlane(!0,t.plane),i.setPlane(!0,t.farPlane),t.camera.controls.addEventListener("rest",this._fragmentsUpdateEvent),s.camera=t.camera,t.open=!0}close(e){let t;if(t=e?this.list.get(e):[...this.list.values()].find(e=>e.open),e&&!t)throw new Error(`Views: the view with id ${e} doesn't exist.`);if(!t)return;if(!t.open)return;const{world:s}=t;if(!s)throw new Error(`Views: no world found for view with id ${e}.`);const{renderer:i}=s;if(!i)throw new Error(`Views: no renderer found for world with id ${s.uuid}.`);i.setPlane(!1,t.plane),i.setPlane(!1,t.farPlane),t.camera.controls.removeEventListener("rest",this._fragmentsUpdateEvent),s.useDefaultCamera(),t.open=!1}};t(IV,"uuid","fb22f1f5-6598-4664-a11d-de8963ae420f"),t(IV,"defaultRange",15);let DV=IV;async function LV(e,t,s,i,r,n,o){const a=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),await function(e,t,s,i){return new Promise((r,n)=>{!function o(){const a=e.clientWaitSync(t,s,0);a!==e.WAIT_FAILED?a!==e.TIMEOUT_EXPIRED?r():setTimeout(o,i):n()}()})}(e,a,0,10),e.deleteSync(a),e.bindBuffer(t,s),e.getBufferSubData(t,i,r,n,o),e.bindBuffer(t,null)}class FV{constructor(e,s){if(t(this,"onDisposed",new u),t(this,"onDistanceComputed",new u),t(this,"excludedObjects",new Set),t(this,"enabled",!0),t(this,"renderDebugFrame",!1),t(this,"components"),t(this,"scene",new l.Scene),t(this,"camera",new l.OrthographicCamera(-1,1,1,-1,0,1)),t(this,"depthMaterial"),t(this,"world"),t(this,"worker"),t(this,"_width",512),t(this,"_height",512),t(this,"_postQuad"),t(this,"tempRT"),t(this,"resultRT"),t(this,"bufferSize"),t(this,"_buffer"),t(this,"_isWorkerBusy",!1),t(this,"compute",async()=>{if(!this.enabled||this.world.isDisposing)return;if(this._isWorkerBusy)return;this._isWorkerBusy=!0,this.world.camera.three.updateMatrix();const e=this.world.renderer.three;e.setRenderTarget(this.tempRT);const t="visibilityBeforeDistanceCheck";for(const e of this.excludedObjects)e.userData[t]=e.visible,e.visible=!1;e.render(this.world.scene.three,this.world.camera.three);for(const e of this.excludedObjects)void 0!==e.userData[t]&&(e.visible=e.userData[t]);this.depthMaterial.uniforms.tDiffuse.value=this.tempRT.texture,this.depthMaterial.uniforms.tDepth.value=this.tempRT.depthTexture,e.setRenderTarget(this.resultRT),e.render(this.scene,this.camera);const s=e.getContext();try{await async function(e,t,s,i,r,n,o,a){const l=e.createBuffer();return e.bindBuffer(e.PIXEL_PACK_BUFFER,l),e.bufferData(e.PIXEL_PACK_BUFFER,a.byteLength,e.STREAM_READ),e.readPixels(t,s,i,r,n,o,0),e.bindBuffer(e.PIXEL_PACK_BUFFER,null),await LV(e,e.PIXEL_PACK_BUFFER,l,0,a),e.deleteBuffer(l),a}(s,0,0,this._width,this._height,s.RGBA,s.UNSIGNED_BYTE,this._buffer)}catch(t){return e.setRenderTarget(null),void(this._isWorkerBusy=!1)}e.setRenderTarget(null),this.renderDebugFrame&&e.render(this.scene,this.camera),this.worker.postMessage({buffer:this._buffer})}),t(this,"handleWorkerMessage",e=>{if(!this.enabled||this.world.isDisposing)return;const t=e.data.colors;let s=Number.MAX_VALUE;for(const e of t)0!==e&&e<s&&(s=e);const i=this.world.camera.three||l.OrthographicCamera,r=-1*(s/255-1)*(i.far-i.near),n=Math.min(r,i.far);this.onDistanceComputed.trigger(n),this._isWorkerBusy=!1}),!s.renderer)throw new Error("The given world must have a renderer!");this.components=e,this.world=s;const i=s.camera.three;this.tempRT=new l.WebGLRenderTarget(this._width,this._height),this.bufferSize=this._width*this._height*4,this._buffer=new Uint8Array(this.bufferSize),this.tempRT.texture.minFilter=l.NearestFilter,this.tempRT.texture.magFilter=l.NearestFilter,this.tempRT.stencilBuffer=!1,this.tempRT.samples=0,this.tempRT.depthTexture=new l.DepthTexture(this._width,this._height),this.tempRT.depthTexture.format=l.DepthFormat,this.tempRT.depthTexture.type=l.UnsignedShortType,this.resultRT=new l.WebGLRenderTarget(this._width,this._height),this.depthMaterial=new l.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n ",fragmentShader:"\n#include <packing>\n\nvarying vec2 vUv;\nuniform sampler2D tDiffuse;\nuniform sampler2D tDepth;\nuniform float cameraNear;\nuniform float cameraFar;\n\n\nfloat readDepth( sampler2D depthSampler, vec2 coord ) {\n float fragCoordZ = texture2D( depthSampler, coord ).x;\n float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );\n return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );\n}\n\nvoid main() {\n //vec3 diffuse = texture2D( tDiffuse, vUv ).rgb;\n float depth = readDepth( tDepth, vUv );\n\n gl_FragColor.rgb = 1.0 - vec3( depth );\n gl_FragColor.a = 1.0;\n}\n ",uniforms:{cameraNear:{value:i.near},cameraFar:{value:i.far},tDiffuse:{value:null},tDepth:{value:null}}});const r=new l.PlaneGeometry(2,2);this._postQuad=new l.Mesh(r,this.depthMaterial),this.scene.add(this._postQuad);const n=new Blob(['\n addEventListener("message", (event) => {\n const { buffer } = event.data;\n const colors = new Set();\n for (let i = 0; i < buffer.length; i += 4) {\n const r = buffer[i];\n colors.add(r);\n }\n postMessage({ colors });\n });\n '],{type:"application/javascript"});this.worker=new Worker(URL.createObjectURL(n)),this.worker.addEventListener("message",this.handleWorkerMessage)}dispose(){this.enabled=!1,this.onDistanceComputed.reset(),this.worker.terminate(),this.tempRT.dispose(),this.resultRT.dispose();const e=[...this.scene.children];this.excludedObjects.clear();for(const t of e)t.removeFromParent();this._postQuad.geometry.dispose(),this._postQuad.removeFromParent(),this._buffer=null,this.onDisposed.reset()}}class OV{constructor(e){t(this,"cardinality","required"),t(this,"instructions"),t(this,"evalRequirement",(e,t,s,i)=>{const r={parameter:s,currentValue:e,requiredValue:t,pass:!1};i&&this.addCheckResult(r,i);let n=!1;if("simple"===t.type&&(n=e===t.parameter),"enumeration"===t.type&&(n=t.parameter.includes(e)),"pattern"===t.type){n=new RegExp(t.parameter).test(String(e))}if("length"===t.type){const{min:s,length:i,max:r}=t.parameter;void 0!==i&&(n=String(e).length===i),void 0!==s&&(n=String(e).length>=s),void 0!==r&&(n=String(e).length<=r)}if("bounds"===t.type&&"number"==typeof e){const{min:s,minInclusive:i,max:r,maxInclusive:o}=t.parameter;let a=!0,l=!0;void 0!==s&&(a=i?e>=s:e>s),void 0!==r&&(l=o?e<=r:e<r),n=a&&l}return"prohibited"===this.cardinality&&(n=!n),"optional"===this.cardinality&&(n=!0),r.pass=n,r.pass}),this._components=e}addCheckResult(e,t){const s=t.findIndex(({parameter:t})=>t===e.parameter);-1!==s?t[s]=e:t.push(e)}getItemChecks(e,t,s,i){if(!("value"in s._localId)||"number"!=typeof s._localId.value)return null;let r=e.get(t);r||(r=new a.DataMap,e.set(t,r));let n=r.get(s._localId.value);if(n&&i&&!n.pass)return null;if(!n){const e=[];n={guid:Array.isArray(s._guid)?void 0:s._guid.value,pass:!1,checks:e},Object.defineProperty(n,"pass",{get:()=>e.every(({pass:e})=>e)}),r.set(s._localId.value,n)}const o=[],l={facetType:this.facetType,cardinality:this.cardinality,checks:o,pass:!1};return Object.defineProperty(l,"pass",{get:()=>o.every(({pass:e})=>e)}),n.checks.push(l),l.checks}}const VV=(e,t)=>{let s="";if(!t)return s;if("simple"===t.type&&(s=`<simpleValue>${t.parameter}</simpleValue>`),"enumeration"===t.type){s=`<xs:restriction base="xs:string">\n ${t.parameter.map(e=>`<xs:enumeration value="${e}" />`).join("\n")}\n </xs:restriction>`}if("pattern"===t.type){s=`<xs:restriction base="xs:string">\n <xs:pattern value="${t.parameter}" />\n </xs:restriction>`}if("bounds"===t.type){const{min:e,minInclusive:i,max:r,maxInclusive:n}=t.parameter;let o="";void 0!==e&&(o=`<xs:min${i?"Inclusive":"Exclusive"} value="${e}">`);let a="";void 0!==r&&(a=`<xs:max${n?"Inclusive":"Exclusive"} value="${r}">`),s=`<xs:restriction base="xs:double">\n ${o}\n ${a}\n </xs:restriction>`}if("length"===t.type){const{length:e,min:i,max:r}=t.parameter;let n="";void 0!==e&&void 0===i&&void 0===r&&(n=`<xs:length value="${e}" />`);let o="";void 0!==i&&void 0===e&&(o=`<xs:minLength value="${i}" />`);let a="";void 0!==r&&void 0===e&&(a=`<xs:maxLength value="${r}" />`),s=`<xs:restriction base="xs:string">\n ${n}\n ${o}\n ${a}\n </xs:restriction>`}return`<${e[0].toLowerCase()+e.slice(1)}>\n ${s}\n </${e[0].toLowerCase()+e.slice(1)}>`};class zV extends OV{constructor(e,s){super(e),t(this,"facetType","Attribute"),t(this,"name"),t(this,"value"),this.name=s}serialize(e){const t=VV("Name",this.name),s=VV("Value",this.value);let i="";return"requirement"===e&&(i+=`cardinality="${this.cardinality}"`,i+=this.instructions?`instructions="${this.instructions}"`:""),`<attribute ${i}>\n ${t}\n ${s}\n</attribute>`}async getEntities(){}async test(e,t,s={skipIfFails:!0}){const i=this._components.get(ji);for(const[r,n]of Object.entries(e)){const e=i.list.get(r);if(!e)continue;const o=await e.getItemsData([...n]);for(const e of o){const i=this.getItemChecks(t,r,e,s.skipIfFails);if(!i)continue;const n=Object.keys(e).filter(t=>{const s=this.evalRequirement(t,this.name,"Name");if(!s)return!1;const i=e[t];return!!Array.isArray(i)||(null===i||null===i.value?"optional"===this.cardinality||"prohibited"===this.cardinality:(!Array.isArray(i.value)||0!==i.value.length)&&(("string"!=typeof i.value||""!==i.value.trim())&&s))}),o=n.length>0;if(i.push({parameter:"Name",currentValue:o?n[0]:null,requiredValue:this.name,pass:"prohibited"===this.cardinality?!o:o}),this.value)if(n[0]){const t=e[n[0]];if(Array.isArray(t))i.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality});else{Array.isArray(t.value)?i.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality}):this.evalRequirement(t.value,this.value,"Value",i)}}else i.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality})}}}}class kV extends OV{constructor(e,s){super(e),t(this,"facetType","Classification"),t(this,"system"),t(this,"value"),t(this,"uri"),this.system=s}serialize(e){const t=VV("System",this.system),s=VV("Value",this.value);let i="";return"requirement"===e&&(i+=`cardinality="${this.cardinality}"`,i+=this.uri?`uri=${this.uri}`:"",i+=this.instructions?`instructions="${this.instructions}"`:""),`<classification ${i}>\n ${t}\n ${s}\n</classification>`}async getEntities(e,t){}async test(e,t){}}class UV extends OV{constructor(e,s){super(e),t(this,"facetType","Entity"),t(this,"name"),t(this,"predefinedType"),this.name=s}serialize(e){const t=VV("Name",this.name),s=VV("Name",this.predefinedType);let i="";return"requirement"===e&&(i+=`cardinality="${this.cardinality}"`,i+=this.instructions?`instructions="${this.instructions}"`:""),`<entity ${i}>\n ${t}\n ${s}\n</entity>`}async getEntities(e,t){const s=this._components.get(ji),i=new Map;for(const[t,r]of s.list){if(!e.find(e=>e.test(t)))continue;const s=await r.getCategories();for(const e of s){if(!await this.evalName(e))continue;let s=i.get(t);s||(s=[],i.set(t,s)),s.push(e)}}const r={};if(await Promise.all(Array.from(i.entries()).map(async([e,t])=>{const i=s.list.get(e);if(!i)return;const n=t.map(e=>new RegExp(`^${e}$`)),o=await i.getItemsOfCategories(n),a=Object.values(o).flat();r[e]=new Set(a)})),this.predefinedType)for(const[e,i]of Object.entries(r)){const r=s.list.get(e);if(!r)continue;const n=await r.getItemsData([...i]);for(const s of n){if(!("value"in s._localId))continue;await this.evalPredefinedType(e,s)&&Oe.append(t,e,s._localId.value)}}else Oe.add(t,r)}async test(e,t,s){const i=this._components.get(ji);for(const[r,n]of Object.entries(e)){const e=i.list.get(r);if(!e)continue;const o=await e.getItemsData([...n]);for(const e of o){if(!("value"in e._category))continue;const i=this.getItemChecks(t,r,e,s.skipIfFails);i&&(await this.evalName(e._category.value,i),await this.evalPredefinedType(r,e,i))}}}async evalName(e,t){return this.evalRequirement(e,this.name,"Name",t)}async evalPredefinedType(e,t,s){if(!this.predefinedType)return null;if(!("value"in t.PredefinedType))return null;const i="string"==typeof this.predefinedType.parameter&&"USERDEFINED"===this.predefinedType.parameter;let r=t.PredefinedType.value;if("USERDEFINED"===r&&!i){const e=Object.keys(t).find(e=>/^((?!Predefined).)*Type$/.test(e));if(e){const s=t[e];"value"in s&&(r=s.value)}else r="USERDEFINED"}if(!r){const s=this._components.get(ji).list.get(e);if(s&&"value"in t._localId){const[e]=await s.getItemsData([t._localId.value],{relations:{IsTypedBy:{attributes:!0,relations:!1}}});if(Array.isArray(e.IsTypedBy)){const t=e.IsTypedBy[0];if(t&&"value"in t.PredefinedType&&(r=t.PredefinedType.value,"USERDEFINED"===r&&!i)){const e=Object.keys(t).find(e=>/^((?!Predefined).)*Type$/.test(e));if(e){const s=t[e];"value"in s&&(r=s.value)}else r="USERDEFINED"}}}}return this.evalRequirement(r,this.predefinedType,"PredefinedType",s)}}class GV extends OV{constructor(e,s,i){super(e),t(this,"facetType","Property"),t(this,"propertySet"),t(this,"baseName"),t(this,"value"),t(this,"dataType"),t(this,"uri"),t(this,"_unsupportedTypes",["IFCCOMPLEXPROPERTY","IFCPHYSICALCOMPLEXQUANTITY"]),this.propertySet=s,this.baseName=i}serialize(e){const t=VV("PropertySet",this.propertySet),s=VV("BaseName",this.baseName),i=VV("Value",this.value),r=this.dataType?`dataType=${this.dataType}`:"";let n="";return"requirement"===e&&(n+=`cardinality="${this.cardinality}"`,n+=this.uri?`uri=${this.uri}`:"",n+=this.instructions?`instructions="${this.instructions}"`:""),`<property ${r} ${n}>\n ${t}\n ${s}\n ${i}\n</property>`}async getEntities(e,t){const s=this._components.get(ji);for(const[i,r]of s.list){if(!e.find(e=>e.test(i)))continue;const s=await r.getItemsOfCategories([/PROPERTYSET/,/ELEMENTQUANTITY/]),n=Object.values(s).flat();if(0===n.length)continue;const o=await r.getItemsData(n,{relations:{HasProperties:{attributes:!0,relations:!1},DefinesOcurrence:{attributes:!0,relations:!1}}});for(const e of o){if(!("value"in e._localId&&"value"in e._category&&"value"in e.Name&&Array.isArray(e.DefinesOcurrence)))continue;if(!this.evalRequirement(e.Name.value,this.propertySet,"PropertySet"))continue;let s;if("IFCPROPERTYSET"===e._category.value&&(s="HasProperties"),"IFCELEMENTQUANTITY"===e._category.value&&(s="Quantities"),!s)continue;const r=e[s];if(Array.isArray(r))for(const s of r){const r=Object.keys(s),n=r.find(e=>/Name/.test(e));if(!n||!("value"in s[n]))continue;const o=s[n];if(!("value"in o))continue;if(!this.evalRequirement(o.value,this.baseName,"BaseName"))continue;if(this.value){const e=r.find(e=>/Value/.test(e));if(!e)continue;const t=s[e];if(!("value"in t))continue;if(!this.evalRequirement(t.value,this.value,"Value"))continue}const a=e.DefinesOcurrence.map(e=>"value"in e._localId&&"number"==typeof e._localId.value?e._localId.value:null).filter(e=>null!==e);Oe.append(t,i,...a)}}}}async test(e,t,s={skipIfFails:!0}){const i=this._components.get(ji);for(const[r,n]of Object.entries(e)){const e=i.list.get(r);if(!e)continue;const o=await e.getItemsData([...n],{relations:{IsDefinedBy:{attributes:!0,relations:!0},IsTypedBy:{attributes:!0,relations:!1},HasPropertySets:{attributes:!0,relations:!0},DefinesOcurrence:{attributes:!1,relations:!1}}});for(const e of o){const i=this.getItemChecks(t,r,e,s.skipIfFails);if(!i)continue;const n=(await this.getPsets(e)).filter(e=>{if(!("value"in e.Name))return!1;return!!this.evalRequirement(e.Name.value,this.propertySet,"PropertySet")&&(i.push({currentValue:e.Name.value,parameter:"PropertySet",pass:!0,requiredValue:this.propertySet}),!0)});if(0!==n.length)for(const e of n){const t=this.getPropertyListName(e);if(!t)continue;const s=e[t];if(!Array.isArray(s)){i.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}const r=s.filter(e=>{if(!("value"in e._category)||!("value"in e.Name))return!1;if(this._unsupportedTypes.includes(e._category.value))return!1;return!!this.evalRequirement(e.Name.value,this.baseName,"BaseName")&&(i.push({currentValue:e.Name.value,parameter:"BaseName",pass:!0,requiredValue:this.baseName}),!0)});if(0!==r.length)for(const e of r)this.evalValue(e,i),this.evalDataType(e,i),this.evalURI();else i.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName})}else i.push({currentValue:null,parameter:"PropertySet",pass:!1,requiredValue:this.propertySet})}}}getPropertyListName(e){let t;return"value"in e._category?("IFCPROPERTYSET"===e._category.value&&(t="HasProperties"),"IFCELEMENTQUANTITY"===e._category.value&&(t="Quantities"),t):t}getValueKey(e){return Object.keys(e).find(e=>/Value/.test(e)||/Values/.test(e))}getTypePsets(e){if(!Array.isArray(e.IsTypedBy))return[];const[t]=e.IsTypedBy;return t&&Array.isArray(t.HasPropertySets)?t.HasPropertySets:[]}async getPsets(e){const t=this.getTypePsets(e);if(!Array.isArray(e.IsDefinedBy))return t;const s=[];for(const i of e.IsDefinedBy){if(!("value"in i.Name))continue;const e=i.Name.value,r=this.getPropertyListName(i);if(!e||!r)continue;const n=t.find(t=>"value"in t.Name&&t.Name.value===e);if(n&&Array.isArray(n.HasProperties)&&Array.isArray(i.HasProperties))for(const e of n.HasProperties){if(!("value"in e.Name))continue;const t=e.Name.value;i.HasProperties.find(e=>"value"in e.Name&&e.Name.value===t)||i.HasProperties.push(e)}s.push(i)}return s}evalValue(e,t){const s=this.getValueKey(e),i=e[s];if(!("value"in i))return!1;if(this.value){if(!s)return null==t||t.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;const e=structuredClone(this.value);"IFCLABEL"===i.type&&"simple"===e.type&&(e.parameter=String(e.parameter));return this.evalRequirement(i.value,e,"Value",t)}return!s||("string"!=typeof i.value||""!==i.value.trim()||(null==t||t.push({parameter:"Value",currentValue:"",pass:!1,requiredValue:this.value}),!1))}evalDataType(e,t){if(!this.dataType)return!0;const s=this.getValueKey(e);if(!s||!("value"in e[s]))return null==t||t.push({parameter:"DataType",currentValue:null,pass:!1,requiredValue:this.dataType}),!1;const i=e[s];return this.evalRequirement(i.type??null,{type:"simple",parameter:this.dataType},"DataType",t)}evalURI(){return!0}}class jV extends OV{constructor(){super(...arguments),t(this,"_ifcMaterialEntities",[/^IFCMATERIALLAYERSETUSAGE$/,/^IFCMATERIALCONSTITUENTSET$/,/^IFCMATERIAL$/,/^IFCMATERIALLIST$/]),t(this,"facetType","Material"),t(this,"value"),t(this,"uri")}serialize(e){if(!this.value||!this.uri)return"<material />";const t=VV("Value",this.value);let s="";return"requirement"===e&&(s+=`cardinality="${this.cardinality}"`,s+=this.uri?`uri=${this.uri}`:"",s+=this.instructions?`instructions="${this.instructions}"`:""),`<material ${s}>\n ${t}\n</material>`}async getEntities(e,t){const s=this._components.get(ji);for(const[i,r]of s.list){if(!e.find(e=>e.test(i)))continue;const s=await r.getItemsOfCategories(this._ifcMaterialEntities),n=Object.values(s).flat();if(0===n.length)continue;const o=await r.getItemsData(n,{relations:{AssociatedTo:{attributes:!0,relations:!1},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const e of o){if(!("value"in e._localId&&"value"in e._category&&Array.isArray(e.AssociatedTo)))continue;if(!this.hasValidMaterial(e))continue;const s=e.AssociatedTo.map(e=>"value"in e._localId&&e._localId.value?e._localId.value:null).filter(e=>null!==e);Oe.append(t,i,...s)}}}async test(e,t,s={skipIfFails:!0}){const i=this._components.get(ji);for(const[r,n]of Object.entries(e)){const e=i.list.get(r);if(!e)continue;const o=await e.getItemsData([[...n][0]],{relations:{AssociatedTo:{attributes:!1,relations:!1},HasAssociations:{attributes:!0,relations:!0},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const e of o){const i=this.getItemChecks(t,r,e,s.skipIfFails);if(i)if(Array.isArray(e.HasAssociations))for(const t of e.HasAssociations){if(!this._ifcMaterialEntities.some(e=>"value"in t._category&&e.test(t._category.value)))continue;if(this.hasValidMaterial(t,i))break}else i.push({parameter:null,currentValue:null,requiredValue:this.value,pass:!1})}}}hasValidMaterial(e,t){let s=!1;if("value"in e._category&&"IFCMATERIAL"===e._category.value){this.evalValue(e,t)&&(s=!0)}else for(const[i,r]of Object.entries(e))if(["ForLayerSet","MaterialLayers","Material","MaterialConstituents","Materials"].includes(i)&&Array.isArray(r))for(const e of r){if("value"in e._category&&"IFCMATERIAL"===e._category.value){if(this.evalValue(e,t)){s=!0;break}}else{if(this.hasValidMaterial(e)){s=!0;break}}}return s}evalValue(e,t){if(!this.value)return null==t||t.push({parameter:null,currentValue:e.Name&&"value"in e.Name?e.Name.value:null,pass:!0}),!0;if(!("value"in e._category)||"IFCMATERIAL"!==e._category.value)return null;let s=!1;return e.Name&&"value"in e.Name&&(s=this.evalRequirement(e.Name.value,this.value,"Value",t)),s||(e.Category&&"value"in e.Category&&(s=this.evalRequirement(e.Category.value,this.value,"Value",t)),s)}}class $V extends OV{constructor(e,s){super(e),t(this,"facetType","PartOf"),t(this,"_entityFacet"),t(this,"_entity"),t(this,"relation"),t(this,"cardinality","required"),this._entity=s,this._entityFacet=new UV(e,s.name),this._entityFacet.predefinedType=s.predefinedType}set entity(e){this._entity=e;const{name:t,predefinedType:s}=e;this._entityFacet=new UV(this._components,t),this._entityFacet.predefinedType=s}get entity(){return this._entity}serialize(){return""}async getEntities(e,t){}async test(e){}}class WV{constructor(e,s,i){t(this,"name"),t(this,"ifcVersion",new Set),t(this,"identifier",w.create()),t(this,"description"),t(this,"instructions"),t(this,"requirementsDescription"),t(this,"applicability",new a.DataSet),t(this,"requirements",new a.DataSet),t(this,"components"),this.components=e,this.name=s;for(const e of i)this.ifcVersion.add(e)}set(e){const t=e,s=this;for(const i in e){if("identifier"===i)continue;const e=t[i];i in this&&(s[i]=e)}return this.components.get(ez).list.set(this.identifier,this),this}async test(e,t={skipIfFails:!0}){const s=new a.DataMap;if(0===this.requirements.size)return s;const i={},r=[];for(const t of this.applicability)r.push(t.getEntities(e,i));await Promise.all(r);const n=[];for(const e of this.requirements)n.push(e.test(i,s,t));return await Promise.all(n),s}serialize(){const e=`name="${this.name}"`,t=this.identifier?`identifier="${this.identifier}"`:"",s=this.description?`description="${this.description}"`:"",i=this.instructions?`instructions="${this.instructions}"`:"";return`<specification ifcVersion="${[...this.ifcVersion].join(" ")}" ${e} ${t} ${s} ${i}>\n <applicability minOccurs="1" maxOccurs="unbounded">\n ${[...this.applicability].map(e=>e.serialize("applicability")).join("\n")}\n </applicability>\n <requirements>\n ${[...this.requirements].map(e=>e.serialize("requirement")).join("\n")}\n </requirements>\n </specification>`}}const HV=e=>{if(!e)return;const t={};if("simpleValue"in e&&(t.type="simple",t.parameter=e.simpleValue),"restriction"in e){const s=e.restriction,i=Object.keys(s);if("pattern"in s&&(t.type="pattern",t.parameter=s.pattern.value),"enumeration"in s){t.type="enumeration";const e=s.enumeration.map(({value:e})=>s.base.includes("string")?String(e):s.base.includes("integer")||s.base.includes("double")?Number(e):e);t.parameter=e}if(i.some(e=>["minInclusive","minExclusive","maxInclusive","maxExclusive"].includes(e))){t.type="bounds";const e={},r=i.find(e=>e.includes("min")),n=i.find(e=>e.includes("max"));r&&(e.minInclusive="minInclusive"===r,e.min=s[r].value),n&&(e.maxInclusive="maxInclusive"===n,e.max=s[n].value),t.parameter=e}if(i.some(e=>["minLength","length","maxLength"].includes(e))){t.type="length";const e={};void 0!==s.length&&(e.length=s.length.value),void 0!==s.minLength&&(e.min=s.minLength.value),void 0!==s.maxLength&&(e.max=s.maxLength.value),t.parameter=e}}return void 0!==t.parameter?t:void 0},qV=(e,t)=>{const s=[];for(const i of t){const t=i.name,r=HV(t);if(!r)continue;const n=new UV(e,r);i.cardinality&&(n.cardinality=i.cardinality),n.predefinedType=HV(i.predefinedType),n.instructions=i.instructions,s.push(n)}return s},XV=(e,t)=>{const s=[];for(const i of t){const t=i.name,r=HV(t);if(!r)continue;const n=new zV(e,r);i.cardinality&&(n.cardinality=i.cardinality),n.value=HV(i.value),n.instructions=i.instructions,s.push(n)}return s},YV=(e,t)=>{const s=[];for(const i of t){const t=new jV(e);i.cardinality&&(t.cardinality=i.cardinality);const r=HV(i.value);"enumeration"===(null==r?void 0:r.type)&&Array.isArray(r.parameter)&&(r.parameter=r.parameter.map(String)),t.value=r,t.uri=i.uri,t.instructions=i.instructions,s.push(t)}return s},ZV=(e,t)=>{const s=[];for(const i of t){const t=i.propertySet,r=i.baseName,n=HV(t),o=HV(r);if(!o||!n)continue;const a=new GV(e,n,o);i.cardinality&&(a.cardinality=i.cardinality);const l=HV(i.value);a.value=l,a.dataType=i.dataType,a.uri=i.uri,a.instructions=i.instructions,s.push(a)}return s},QV=(e,t)=>{const s=[];for(const i of t){const t=i.system,r=HV(t);if(!r)continue;const n=new kV(e,r);i.cardinality&&(n.cardinality=i.cardinality);const o=HV(i.value);"simple"===(null==o?void 0:o.type)&&(o.parameter=String(o.parameter)),"enumeration"===(null==o?void 0:o.type)&&Array.isArray(o.parameter)&&(o.parameter=o.parameter.map(String)),n.value=o,n.uri=i.uri,n.instructions=i.instructions,s.push(n)}return s},KV=(e,t)=>{const s=[];for(const i of t){const t=HV(i.entity.name);if(!t)continue;const r=HV(i.entity.predefinedType),n=new $V(e,{name:t,predefinedType:r});n.relation=i.relation,i.cardinality&&(n.cardinality=i.cardinality),n.instructions=i.instructions,s.push(n)}return s},JV=class e extends d{constructor(i){super(i),t(this,"enabled",!0),t(this,"IDSInfo"),t(this,"list",new s.DataMap),i.add(e.uuid,this)}getModelIdMap(e){const t={},s={};for(const[i,r]of e){const e=[...r].filter(([,e])=>e.pass).map(([e])=>e);Oe.append(t,i,...e);const n=[...r].filter(([,e])=>!e.pass).map(([e])=>e);Oe.append(s,i,...n)}return{pass:t,fail:s}}create(e,t,s){const i=new WV(this.components,e,t);return s&&(i.identifier=s),this.list.set(i.identifier,i),i}load(t){const s=[],i=e.xmlParser.parse(t).ids,{specifications:r,info:n}=i;if(this.IDSInfo={...n},r&&r.specification){const e=Array.isArray(r.specification)?r.specification:[r.specification];for(const t of e){const{name:e,ifcVersion:i,description:r,instructions:n,identifier:o}=t;if(!e||!i)continue;const a=[],l=[],{applicability:h,requirements:u}=t;if(h){const{maxOccurs:e,...t}=h,s=Array.isArray(t)?t:[t];for(const e of s)for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];if("entity"===t){const e=qV(this.components,s);a.push(...e)}if("attribute"===t){const e=XV(this.components,s);a.push(...e)}if("material"===t){const e=YV(this.components,s);a.push(...e)}if("classification"===t){const e=QV(this.components,s);a.push(...e)}if("property"===t){const e=ZV(this.components,s);a.push(...e)}if("partOf"===t){const e=KV(this.components,s);a.push(...e)}}}let c;if(u){const{maxOccurs:e,...t}=u;c=u.description;const s=Array.isArray(t)?t:[t];for(const e of s)for(const t in e){const s=Array.isArray(e[t])?e[t]:[e[t]];if("entity"===t){const e=qV(this.components,s);l.push(...e)}if("attribute"===t){const e=XV(this.components,s);l.push(...e)}if("material"===t){const e=YV(this.components,s);l.push(...e)}if("classification"===t){const e=QV(this.components,s);l.push(...e)}if("property"===t){const e=ZV(this.components,s);l.push(...e)}if("partOf"===t){const e=KV(this.components,s);l.push(...e)}}}const d=this.create(e,i.split(/\s+/),o);d.description=r,d.instructions=n,d.requirementsDescription=c,d.applicability.add(...a),d.requirements.add(...l),s.push(d)}}return s}export(e,t=this.list.values()){const s=t??this.list;return`<ids xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://standards.buildingsmart.org/IDS http://standards.buildingsmart.org/IDS/1.0/ids.xsd" xmlns:ids="http://standards.buildingsmart.org/IDS">\n \x3c!-- Made with That Open Engine ${NO.release} (https://github.com/thatopen/engine_components) --\x3e\n <info>\n <title>${e.title}</title>\n ${e.copyright?`<copyright>${e.copyright}</copyright>`:""}\n ${e.version?`<version>${e.version}</version>`:""}\n ${e.description?`<description>${e.description}</description>`:""}\n ${e.author?`<author>${e.author}</author>`:""}\n ${e.date?`<date>${e.date.toISOString().split("T")[0]}</date>`:""}\n ${e.purpose?`<purpose>${e.purpose}</purpose>`:""}\n ${e.milestone?`<milestone>${e.milestone}</milestone>`:""}\n </info>\n <specifications>\n ${[...s].map(e=>e.serialize()).join("\n")}\n </specifications>\n</ids>`}};t(JV,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c"),t(JV,"xmlParser",new Se({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let ez=JV;const tz=class e extends d{constructor(s){super(s),t(this,"enabled",!0),s.add(e.uuid,this)}static distanceFromPointToLine(e,t,s,i=!1){const r=new l.Line3,n=new l.Vector3;return r.set(t,s),r.closestPointToPoint(e,i,n),n.distanceTo(e)}round(e){const t=1e3;e.x=Math.trunc(e.x*t)/t,e.y=Math.trunc(e.y*t)/t,e.z=Math.trunc(e.z*t)/t}async getVolumeFromFragments(e){return console.warn("getVolumeFromFragments is deprecated. Use getItemsVolume instead."),this.getItemsVolume(e)}async getItemsVolume(e){let t=0;const s=this.components.get(ji);for(const[i,r]of Object.entries(e)){const e=s.list.get(i);e&&(t+=await e.getItemsVolume([...r]))}return t}static convertUnits(e,t,s,i=2){const r={m:1,cm:.01,mm:.001,km:1e3,m2:1,cm2:1e-4,mm2:1e-6,km2:1e6,m3:1,cm3:1e-6,mm3:1e-9,km3:1e9};if(!r[t]||!r[s])throw new Error("Invalid units provided for conversion.");if(!Number.isInteger(i)||i<0||i>5)throw new Error("Precision must be an integer between 0 and 5.");const n=e*(r[t]/r[s]),o=10**i;return Math.round(n*o)/o}};t(tz,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");let sz=tz;const iz=(e,t,s)=>{const i=new l.Vector3(-t.z,0,t.x),r=new l.Vector3(t.x+i.x,0,t.z+i.z).normalize().multiplyScalar(s/2);return[e.x+r.x,e.y,e.z+r.z,e.x-r.x,e.y,e.z-r.z]},rz=(e,t,s)=>{const i=new l.Vector3(-t.z,0,t.x),r=e.x-t.x*s+i.x*s*.4,n=e.z-t.z*s+i.z*s*.4,o=e.x-t.x*s-i.x*s*.4,a=e.z-t.z*s-i.z*s*.4;return[e.x,e.y,e.z,r,e.y,n,e.x,e.y,e.z,o,e.y,a]},nz=()=>[],oz=(e,t,s)=>{const i=new l.Vector3(-t.z,0,t.x),r=e.clone().addScaledVector(t,-s),n=r.clone().addScaledVector(i,.4*s),o=r.clone().addScaledVector(i,.4*-s);return[e.x,e.y,e.z,n.x,n.y,n.z,o.x,o.y,o.z]};class az extends a.DataMap{getBySystem(e){const t=new Map;for(const[s,i]of this)i.system===e&&t.set(s,i.data);return t}}class lz extends a.DataMap{constructor(e){super(),t(this,"_container"),this._container=e,this.deleteGuard=e=>"0"!==e,this.set("0",{name:"0",visible:!0,material:new l.LineBasicMaterial({color:0})})}create(e,t){if(!this.has(e)){const s={name:e,visible:(null==t?void 0:t.visible)??!0,material:(null==t?void 0:t.material)??new l.LineBasicMaterial({color:0})};this.set(e,s)}return this.get(e)}setColor(e,t){const s=this.get(e);s&&(s.material.color.setHex(t),this.set(e,s))}setMaterial(e,t){const s=this.get(e);if(!s)return;const i=s.material;s.material=t,this._container.traverse(s=>{s.userData.layer===e&&(s.userData.isDimension||s.isLineSegments&&(s.material=t))}),i.dispose(),this.set(e,s)}setVisibility(e,t){const s=this.get(e);s&&(s.visible=t,this._container.traverse(s=>{s.userData.layer===e&&(s.visible=t)}),this.set(e,s))}assign(e,t){const s=this.get(t);s&&(e.userData.layer=t,s.visible||(e.visible=!1),e.isLineSegments&&(e.material=s.material))}resolveColor(e){const t=this.get(e);if(t)return t.material.color.getHex()}}const hz=class e extends l.Group{constructor(s){super(),t(this,"_viewport"),t(this,"_border"),t(this,"_handles",[]),t(this,"_raycaster",new l.Raycaster),t(this,"_resizable",!1),t(this,"_movable",!1),t(this,"_dragHandle",null),t(this,"_dragConstraints",[]),t(this,"_hoveredHandle",null),t(this,"_moveDrag",null),t(this,"_hoveringBorder",!1),t(this,"_normalMat"),t(this,"_hoverMat"),t(this,"_borderMat"),this._viewport=s,this._borderMat=new l.LineBasicMaterial({color:e._BORDER_COLOR,depthTest:!1});const i=new l.BufferGeometry;i.setAttribute("position",new l.BufferAttribute(new Float32Array(24),3)),this._border=new l.LineSegments(i,this._borderMat),this._border.renderOrder=999,this._border.frustumCulled=!1,this._border.userData.isDimension=!0,this.add(this._border),this._normalMat=new l.MeshBasicMaterial({color:e._BORDER_COLOR}),this._hoverMat=new l.MeshBasicMaterial({color:e._BORDER_HOVER_COLOR});const r=new l.SphereGeometry(.05,8,6);for(const t of e._HANDLE_DEFS){const e=new l.Mesh(r,this._normalMat);e.renderOrder=1e3,e.visible=!1,e.userData.constraints=t.constraints,e.userData.isDimension=!0,this.add(e),this._handles.push(e)}this.update()}get resizable(){return this._resizable}set resizable(e){this._resizable=e;for(const t of this._handles)t.visible=e;e||(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat,this._hoveredHandle=null),this._dragHandle=null,this._dragConstraints=[])}get movable(){return this._movable}set movable(e){this._movable=e,e||(this._moveDrag=null,this._setBorderHover(!1))}get isDragging(){return null!==this._dragHandle||null!==this._moveDrag}update(){const e=this._viewport,t=e.left,s=e.right,i=-e.top,r=-e.bottom,n=.005,o=this._border.geometry.attributes.position;o.setXYZ(0,t,n,i),o.setXYZ(1,s,n,i),o.setXYZ(2,s,n,i),o.setXYZ(3,s,n,r),o.setXYZ(4,s,n,r),o.setXYZ(5,t,n,r),o.setXYZ(6,t,n,r),o.setXYZ(7,t,n,i),o.needsUpdate=!0,this._border.geometry.computeBoundingSphere();const a=(t+s)/2,l=(i+r)/2,h=.01,u=[[t,h,i],[s,h,i],[s,h,r],[t,h,r],[a,h,i],[s,h,l],[a,h,r],[t,h,l]];for(let e=0;e<this._handles.length;e++)this._handles[e].position.set(...u[e])}onPointerMove(t){if(this._dragHandle){const e=this._projectToLocal(t);if(!e)return;for(const t of this._dragConstraints)switch(t){case"left":this._viewport.left=e.x;break;case"right":this._viewport.right=e.x;break;case"top":this._viewport.top=-e.z;break;case"bottom":this._viewport.bottom=-e.z}return this._viewport.right<this._viewport.left&&([this._viewport.left,this._viewport.right]=[this._viewport.right,this._viewport.left],this._dragConstraints=this._dragConstraints.map(e=>"right"===e?"left":"left"===e?"right":e)),this._viewport.top<this._viewport.bottom&&([this._viewport.top,this._viewport.bottom]=[this._viewport.bottom,this._viewport.top],this._dragConstraints=this._dragConstraints.map(e=>"top"===e?"bottom":"bottom"===e?"top":e)),void this.update()}if(this._moveDrag){const e=this._projectToLocal(t);if(!e)return;const s=e.x-this._moveDrag.origin.x,i=e.z-this._moveDrag.origin.z;return this._viewport.left=this._moveDrag.left0+s,this._viewport.right=this._moveDrag.right0+s,this._viewport.top=this._moveDrag.top0-i,this._viewport.bottom=this._moveDrag.bottom0-i,void this.update()}if(!this._resizable&&!this._movable)return;this._raycaster.set(t.origin,t.direction);let s=null;if(this._resizable){const e=this._handles.filter(e=>e.visible),t=this._raycaster.intersectObjects(e,!1);s=t.length>0?t[0].object:null}if(s!==this._hoveredHandle&&(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat),s&&(s.material=this._hoverMat),this._hoveredHandle=s),this._movable&&!this._hoveredHandle){this._raycaster.params.Line={threshold:e._LINE_THRESHOLD};const t=this._raycaster.intersectObject(this._border,!1).length>0;this._setBorderHover(t)}else this._setBorderHover(!1)}onPointerDown(t){if(this._resizable||this._movable){if(this._raycaster.set(t.origin,t.direction),this._resizable){const e=this._handles.filter(e=>e.visible),t=this._raycaster.intersectObjects(e,!1);if(t.length>0)return this._dragHandle=t[0].object,void(this._dragConstraints=[...this._dragHandle.userData.constraints])}if(this._movable){this._raycaster.params.Line={threshold:e._LINE_THRESHOLD};if(this._raycaster.intersectObject(this._border,!1).length>0){const e=this._projectToLocal(t);if(!e)return;this._moveDrag={origin:e,left0:this._viewport.left,right0:this._viewport.right,top0:this._viewport.top,bottom0:this._viewport.bottom}}}}}onPointerUp(){this._dragHandle=null,this._dragConstraints=[],this._moveDrag=null}dispose(){this._border.geometry.dispose(),this._borderMat.dispose(),this._normalMat.dispose(),this._hoverMat.dispose(),this._handles.length>0&&this._handles[0].geometry.dispose(),this.removeFromParent()}_projectToLocal(e){this.updateWorldMatrix(!0,!1);const t=new l.Vector3(0,1,0).transformDirection(this.matrixWorld),s=(new l.Vector3).setFromMatrixPosition(this.matrixWorld),i=(new l.Plane).setFromNormalAndCoplanarPoint(t,s),r=new l.Vector3;return e.intersectPlane(i,r)?this.worldToLocal(r):null}_setBorderHover(t){t!==this._hoveringBorder&&(this._hoveringBorder=t,this._borderMat.color.setHex(t?e._BORDER_HOVER_COLOR:e._BORDER_COLOR))}};t(hz,"_BORDER_COLOR",22015),t(hz,"_BORDER_HOVER_COLOR",16746496),t(hz,"_LINE_THRESHOLD",.06),t(hz,"_HANDLE_DEFS",[{constraints:["left","top"]},{constraints:["right","top"]},{constraints:["right","bottom"]},{constraints:["left","bottom"]},{constraints:["top"]},{constraints:["right"]},{constraints:["bottom"]},{constraints:["left"]}]);let uz=hz;class cz{constructor(e){t(this,"uuid",l.MathUtils.generateUUID()),t(this,"name"),t(this,"camera"),t(this,"onDisposed",new u),t(this,"_left"),t(this,"_right"),t(this,"_top"),t(this,"_bottom"),t(this,"_drawingScale"),t(this,"_container",null),t(this,"_helper",null),t(this,"_helperVisible",!1),this._left=e.left,this._right=e.right,this._top=e.top,this._bottom=e.bottom,this._drawingScale=e.scale??100,this.name=e.name??"Drawing Viewport",this.camera=new l.OrthographicCamera(this._left,this._right,this._top,this._bottom,.1,30),this.camera.up.set(0,0,-1),this.camera.position.set(0,10,0),this.camera.lookAt(0,0,0),this.camera.layers.set(1)}get left(){return this._left}set left(e){var t;this._left=e,this.camera.left=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get right(){return this._right}set right(e){var t;this._right=e,this.camera.right=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get top(){return this._top}set top(e){var t;this._top=e,this.camera.top=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get bottom(){return this._bottom}set bottom(e){var t;this._bottom=e,this.camera.bottom=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get drawingScale(){return this._drawingScale}set drawingScale(e){this._drawingScale=e}get helper(){return this._helper||(this._helper=new uz(this)),this._helper}get helperVisible(){return this._helperVisible}set helperVisible(e){var t,s;this._helperVisible=e,e?null==(t=this._container)||t.add(this.helper):null==(s=this._helper)||s.removeFromParent()}get bbox(){const e=new l.Vector3(this._left,0,-this._top),t=new l.Vector3(this._right,0,-this._bottom);return new l.Box3(e,t)}get size(){const e=new l.Vector3;return this.bbox.getSize(e),new l.Vector2(1e3*e.x,1e3*e.z)}get localXAxis(){return new l.Vector3(1,0,0)}get localYAxis(){return new l.Vector3(0,0,-1)}get normal(){return new l.Vector3(0,1,0)}setContainer(e){this._container=e,this._helperVisible&&this._helper&&e.add(this._helper)}clipLine(e){const t=this.bbox,{start:s,end:i}=e,r=t.containsPoint(s),n=t.containsPoint(i);if(r&&n)return e;if(!r&&!n){const t=this.getPlaneIntersections(e);return t.length<2?null:new l.Line3(t[0],t[1])}const o=this.getPlaneIntersections(e);return 0===o.length?null:r?new l.Line3(s,o[0]):new l.Line3(o[0],i)}dispose(){var e;null==(e=this._helper)||e.dispose(),this._helper=null,this.onDisposed.trigger(),this.onDisposed.reset()}get bboxPlanes(){const e=this.bbox;return[new l.Plane(new l.Vector3(1,0,0),-e.min.x),new l.Plane(new l.Vector3(-1,0,0),e.max.x),new l.Plane(new l.Vector3(0,0,1),-e.min.z),new l.Plane(new l.Vector3(0,0,-1),e.max.z)]}getPlaneIntersections(e){const t=[];for(const s of this.bboxPlanes){const i=new l.Vector3;s.intersectLine(e,i)&&this.bbox.containsPoint(i)&&t.push(i)}return t}}class dz extends a.DataMap{constructor(e){super(),t(this,"_container"),this._container=e,this.onBeforeDelete.add(({value:e})=>{this._container.remove(e.camera),e.dispose()})}create(e){const t=new cz(e);return this._container.add(t.camera),t.setContainer(this._container),this.set(t.uuid,t),t}}const pz=class e extends l.Group{constructor(s){super(),t(this,"_drawing"),t(this,"_topFrame"),t(this,"_pillars"),t(this,"_bottomFrame"),t(this,"_topPlane"),t(this,"_bottomPlane"),t(this,"_frameMat"),t(this,"_depthMat"),t(this,"_planeMat"),t(this,"width",10),t(this,"height",10),t(this,"farHandle",new l.Object3D),t(this,"widthHandle",new l.Object3D),t(this,"heightHandle",new l.Object3D),this._drawing=s,this._frameMat=new l.LineBasicMaterial({color:e._FRAME_COLOR,depthTest:!1}),this._depthMat=new l.LineBasicMaterial({color:e._DEPTH_COLOR,depthTest:!1,transparent:!0,opacity:.4}),this._planeMat=new l.MeshBasicMaterial({color:e._FRAME_COLOR,transparent:!0,opacity:.07,side:l.DoubleSide,depthTest:!1});const i=()=>{const e=new l.BufferGeometry;return e.setAttribute("position",new l.BufferAttribute(new Float32Array(12),3)),e.setIndex([0,1,2,0,2,3]),e};this._topPlane=new l.Mesh(i(),this._planeMat),this._topPlane.renderOrder=998,this._topPlane.frustumCulled=!1,this._topPlane.userData.isDimension=!0,this._bottomPlane=new l.Mesh(i(),this._planeMat),this._bottomPlane.renderOrder=998,this._bottomPlane.frustumCulled=!1,this._bottomPlane.userData.isDimension=!0;const r=new l.BufferGeometry;r.setAttribute("position",new l.BufferAttribute(new Float32Array(24),3)),this._topFrame=new l.LineSegments(r,this._frameMat),this._topFrame.renderOrder=999,this._topFrame.frustumCulled=!1,this._topFrame.userData.isDimension=!0;const n=new l.BufferGeometry;n.setAttribute("position",new l.BufferAttribute(new Float32Array(24),3)),this._pillars=new l.LineSegments(n,this._depthMat),this._pillars.renderOrder=999,this._pillars.frustumCulled=!1,this._pillars.userData.isDimension=!0;const o=new l.BufferGeometry;o.setAttribute("position",new l.BufferAttribute(new Float32Array(24),3)),this._bottomFrame=new l.LineSegments(o,this._depthMat),this._bottomFrame.renderOrder=999,this._bottomFrame.frustumCulled=!1,this._bottomFrame.userData.isDimension=!0,this.add(this._topPlane,this._bottomPlane),this.add(this._topFrame,this._pillars,this._bottomFrame),this.add(this.farHandle,this.widthHandle,this.heightHandle),this.farHandle.rotation.x=Math.PI,this.update()}update(){const e=this.width/2,t=this.height/2,s=-this._drawing.far,i=.005,r=-e,n=e,o=-t,a=t,l=this._topFrame.geometry.attributes.position;l.setXYZ(0,r,i,o),l.setXYZ(1,n,i,o),l.setXYZ(2,n,i,o),l.setXYZ(3,n,i,a),l.setXYZ(4,n,i,a),l.setXYZ(5,r,i,a),l.setXYZ(6,r,i,a),l.setXYZ(7,r,i,o),l.needsUpdate=!0,this._topFrame.geometry.computeBoundingSphere();const h=this._pillars.geometry.attributes.position;h.setXYZ(0,r,i,o),h.setXYZ(1,r,s,o),h.setXYZ(2,n,i,o),h.setXYZ(3,n,s,o),h.setXYZ(4,n,i,a),h.setXYZ(5,n,s,a),h.setXYZ(6,r,i,a),h.setXYZ(7,r,s,a),h.needsUpdate=!0,this._pillars.geometry.computeBoundingSphere();const u=this._bottomFrame.geometry.attributes.position;u.setXYZ(0,r,s,o),u.setXYZ(1,n,s,o),u.setXYZ(2,n,s,o),u.setXYZ(3,n,s,a),u.setXYZ(4,n,s,a),u.setXYZ(5,r,s,a),u.setXYZ(6,r,s,a),u.setXYZ(7,r,s,o),u.needsUpdate=!0,this._bottomFrame.geometry.computeBoundingSphere();const c=(e,t)=>{const s=e.geometry.attributes.position;s.setXYZ(0,r,t,o),s.setXYZ(1,n,t,o),s.setXYZ(2,n,t,a),s.setXYZ(3,r,t,a),s.needsUpdate=!0,e.geometry.computeBoundingSphere()};c(this._topPlane,i),c(this._bottomPlane,s),this.farHandle.position.set(0,s,0),this.widthHandle.position.set(n,i,0),this.heightHandle.position.set(0,i,a)}attachFarGizmo(e){e.attach(this.farHandle),e.setSpace("local"),e.showX=!1,e.showZ=!1,e.addEventListener("objectChange",()=>{this.farHandle.position.x=0,this.farHandle.position.z=0;const e=Math.max(.1,-this.farHandle.position.y);this._drawing.far=e,this.farHandle.position.y=-e,this.update()})}attachWidthGizmo(e){e.attach(this.widthHandle),e.setSpace("local"),e.showY=!1,e.showZ=!1,e.addEventListener("objectChange",()=>{this.widthHandle.position.y=.005,this.widthHandle.position.z=0,this.width=Math.max(.1,2*this.widthHandle.position.x),this.widthHandle.position.x=this.width/2,this.update()})}attachHeightGizmo(e){e.attach(this.heightHandle),e.setSpace("local"),e.showX=!1,e.showY=!1,e.addEventListener("objectChange",()=>{this.heightHandle.position.x=0,this.heightHandle.position.y=.005,this.height=Math.max(.1,2*this.heightHandle.position.z),this.heightHandle.position.z=this.height/2,this.update()})}dispose(){this._topPlane.geometry.dispose(),this._bottomPlane.geometry.dispose(),this._topFrame.geometry.dispose(),this._pillars.geometry.dispose(),this._bottomFrame.geometry.dispose(),this._planeMat.dispose(),this._frameMat.dispose(),this._depthMat.dispose(),this.removeFromParent()}};t(pz,"_FRAME_COLOR",22015),t(pz,"_DEPTH_COLOR",22015);let mz=pz;function fz(e,t){if(3!==e.length||3!==t.length)throw new Error("computeAlignmentMatrix requires exactly 3 point pairs.");const s=(e,t)=>{const s=(new l.Vector3).subVectors(e[1],e[0]),i=(new l.Vector3).subVectors(e[2],e[0]);if((new l.Vector3).crossVectors(s,i).length()<1e-6)throw new Error(`${t} points are collinear — three non-collinear points are required to define a plane.`)};s(e,"Drawing"),s(t,"World");const i=(e,t,s)=>{const i=(new l.Vector3).subVectors(t,e),r=(new l.Vector3).subVectors(s,e),n=i.clone().normalize(),o=(new l.Vector3).crossVectors(i,r).normalize(),a=(new l.Vector3).crossVectors(n,o).normalize();return(new l.Matrix4).makeBasis(n,o,a)},r=i(e[0],e[1],e[2]),n=i(t[0],t[1],t[2]).clone().multiply(r.clone().invert()),o=e[0].distanceTo(e[1]);if(o<1e-10)throw new Error("The first two drawing points are coincident — cannot compute scale.");const a=t[0].distanceTo(t[1])/o,h=e[0].clone().multiplyScalar(a).applyMatrix4(n),u=(new l.Vector3).subVectors(t[0],h),c=(new l.Quaternion).setFromRotationMatrix(n),d=new l.Matrix4;return d.compose(u,c,new l.Vector3(a,a,a)),d}class gz{constructor(e){t(this,"uuid",l.MathUtils.generateUUID()),t(this,"_raycaster",new l.Raycaster),t(this,"_components"),t(this,"world",null),t(this,"three",new l.Group),t(this,"annotations",new az),t(this,"layers",new lz(this.three)),t(this,"activeLayer","0"),t(this,"far",10),t(this,"viewports",new dz(this.three)),t(this,"onDisposed",new u),this._components=e}raycast(e,t=null){this._raycaster.set(e.origin,e.direction),this._raycaster.layers.set(1),this._raycaster.params.Line&&(this._raycaster.params.Line.threshold=.1);const s=[];this.three.traverse(e=>{e instanceof l.LineSegments&&!e.userData.isDimension&&s.push(e)});const i=this._raycaster.intersectObjects(s,!1);if(0===i.length)return null;const r=i[0],n=this.three.worldToLocal(r.point.clone());let o=null;if(r.object instanceof l.LineSegments&&void 0!==r.index){const e=r.object.geometry.attributes.position,t=r.index,s=new l.Vector3(e.getX(t),e.getY(t),e.getZ(t)),i=new l.Vector3(e.getX(t+1),e.getY(t+1),e.getZ(t+1));s.applyMatrix4(r.object.matrixWorld),this.three.worldToLocal(s),i.applyMatrix4(r.object.matrixWorld),this.three.worldToLocal(i),o=new l.Line3(s,i)}return{point:n,object:r.object,viewport:t,line:o}}alignTo(e,t){fz(e,t).decompose(this.three.position,this.three.quaternion,this.three.scale)}static toDrawingSpace(e,t){e.updateWorldMatrix(!0,!1),t.three.updateWorldMatrix(!0,!1);const s=(new l.Matrix4).copy(t.three.matrixWorld).invert().multiply(e.matrixWorld),i=e.geometry.attributes.position,r=i.count,n=new Float32Array(3*r),o=new l.Vector3;for(let e=0;e<r;e++)o.fromBufferAttribute(i,e).applyMatrix4(s),n[3*e]=o.x,n[3*e+1]=0,n[3*e+2]=o.z;const a=new l.BufferGeometry;return a.setAttribute("position",new l.BufferAttribute(n,3)),new l.LineSegments(a)}addProjectionLines(e,t="0"){return this.layers.has(t)||(console.warn(`[TechnicalDrawing] Layer "${t}" does not exist. Falling back to "0".`),t="0"),this.layers.assign(e,t),e.layers.set(1),e.material instanceof l.LineDashedMaterial&&e.computeLineDistances(),e.geometry.computeBoundsTree({strategy:0,indirect:!0,type:Ii}),this.three.add(e),e}async addProjectionFromItems(e,t){if(!this.world)return void console.warn("[TechnicalDrawing] addProjectionFromItems: drawing has no world assigned.");for(const e of[t.layers.visible,t.layers.hidden])if(!this.layers.has(e))return void console.warn(`[TechnicalDrawing] Layer "${e}" does not exist — create it before calling addProjectionFromItems.`);const s=this._components.get(XF),i=s.projectionDirection.clone(),r=s.nearPlane,n=s.farPlane;try{this.three.updateWorldMatrix(!0,!1);const i=new l.Vector3(0,-1,0).transformDirection(this.three.matrixWorld).normalize();s.projectionDirection.copy(i);const r=(new l.Matrix4).makeRotationFromQuaternion((new l.Quaternion).setFromUnitVectors(i,new l.Vector3(0,-1,0))),n=(new l.Vector3).setFromMatrixPosition(this.three.matrixWorld).applyMatrix4(r).y;s.farPlane=n,s.nearPlane=n-this.far;const o=await s.get(e,this.world,{onProgress:t.onProgress}),a=e=>gz.toDrawingSpace(new l.LineSegments(e),this);this.addProjectionLines(a(o.visible),t.layers.visible),this.addProjectionLines(a(o.hidden),t.layers.hidden)}finally{s.projectionDirection.copy(i),s.nearPlane=r,s.farPlane=n}}orientTo(e){const t=e.clone().normalize(),s=Math.SQRT1_2;t.x>.999?this.three.quaternion.set(.5,-.5,.5,.5):t.x<-.999?this.three.quaternion.set(.5,.5,-.5,.5):t.y>.999?this.three.quaternion.set(0,0,1,0):t.y<-.999?this.three.quaternion.set(0,0,0,1):t.z>.999?this.three.quaternion.set(0,s,-s,0):t.z<-.999?this.three.quaternion.set(s,0,0,s):console.warn("[TechnicalDrawing] orientTo: direction does not match any of the 6 standard axes.")}dispose(){this.viewports.clear(),this.layers.clear(),this.annotations.clear();this._components.get(y).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset()}}class yz{constructor(e){t(this,"styles",new a.DataMap),t(this,"activeStyle","default"),t(this,"onCommit",new u),t(this,"onUpdate",new u),t(this,"onDelete",new u),t(this,"onDisposed",new u),t(this,"_knownDrawings",new Set),t(this,"_previewMaterial",new l.LineBasicMaterial({color:16737894,depthTest:!1})),t(this,"_previewObject",null),t(this,"_previewDrawing",null),t(this,"_materialCache",new a.DataMap),t(this,"_meshMaterialCache",new a.DataMap),t(this,"_ownsChildGeometry",!0),this._components=e,this.styles.onItemUpdated.add(({key:e})=>{const t=this._materialCache.get(e);t&&t.color.setHex(this._resolveStyle(e).color);const s=this._meshMaterialCache.get(e);s&&s.color.setHex(this._resolveStyle(e).color);const i=this._components.get(sk),r=i?[...i.list.values()]:[...this._knownDrawings];for(const t of r){const s=[...t.annotations.getBySystem(this)].filter(([,t])=>t.style===e).map(([e])=>e);s.length>0&&this.update(t,s,{})}})}_onAfterPersist(e,t){}_onDispose(){}_updatePreview(){}get(e){const t=new a.DataMap;for(const s of e)for(const[e,i]of s.annotations.getBySystem(this))t.set(e,{drawingUuid:s.uuid,item:i});return t}add(e,t){const s={uuid:l.MathUtils.generateUUID(),style:this.activeStyle,...t},i=this._persist(e,s);return this.onCommit.trigger([i]),s}update(e,t,s){for(const i of t){const t=e.annotations.get(i);if(!t||t.system!==this)continue;const r=t.data;Object.assign(r,s),this._redraw(r,t.three),this.onUpdate.trigger({item:r,group:t.three})}}pick(e,t=.05){const s=new l.Raycaster;s.ray.copy(e),s.params.Line={threshold:t},s.params.LineSegments={threshold:t};const i=l.Line.prototype.raycast;let r=null,n=1/0;for(const e of this._knownDrawings)for(const[t,o]of e.annotations){if(o.system!==this)continue;const e=o.three;e.updateWorldMatrix(!0,!0),e.traverse(o=>{if(o===e)return;const a=[];if(o instanceof l.LineSegments&&o.userData.isDimension)i.call(o,s,a),a.length>0&&a[0].distance<n&&(n=a[0].distance,r=t);else if(o instanceof l.Mesh){const e=(new l.Box3).setFromObject(o),i=new l.Vector3;if(s.ray.intersectBox(e,i)){const e=s.ray.origin.distanceTo(i);e<n&&(n=e,r=t)}}})}return r}delete(e,t){const s=[];for(const i of t){const t=e.annotations.get(i);t&&t.system===this&&(this._disposeGroup(t.three),e.annotations.delete(i),s.push(i))}s.length&&this.onDelete.trigger(s)}clear(e){const t=e??[...this._knownDrawings];for(const e of t){const t=[];for(const[s,i]of e.annotations)i.system===this&&t.push(s);for(const s of t){const t=e.annotations.get(s);this._disposeGroup(t.three),e.annotations.delete(s)}}}dispose(){this._clearPreview(),this._onDispose(),this.clear();for(const e of this._materialCache.values())e.dispose();this._materialCache.clear();for(const e of this._meshMaterialCache.values())e.dispose();this._meshMaterialCache.clear(),this._previewMaterial.dispose(),this.onCommit.reset(),this.onUpdate.reset(),this.onDelete.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}_trackDrawing(e){this._knownDrawings.has(e)||(this._knownDrawings.add(e),e.onDisposed.add(()=>this._knownDrawings.delete(e)))}_resolveStyle(e){return this.styles.get(e)??this.styles.get("default")}_getMaterial(e){const t=this._materialCache.get(e);if(t)return t;const s=new l.LineBasicMaterial({color:this._resolveStyle(e).color});return this._materialCache.set(e,s),s}_getMeshMaterial(e){const t=this._meshMaterialCache.get(e);if(t)return t;const s=new l.MeshBasicMaterial({color:this._resolveStyle(e).color,side:l.DoubleSide});return this._meshMaterialCache.set(e,s),s}_disposeGroup(e){if(e.removeFromParent(),this._ownsChildGeometry)e.traverse(e=>{e.geometry instanceof l.BufferGeometry&&e.geometry.dispose()});else for(;e.children.length>0;)e.remove(e.children[0])}_clearPreview(){this._previewObject&&(this._previewObject.removeFromParent(),this._previewObject.geometry.dispose(),this._previewObject=null)}_persist(e,t){this._trackDrawing(e);const s=this._resolveStyle(t.style),i=this._buildGroup(t,s);return i.userData.isDimension=!0,i.userData.annotationUuid=t.uuid,i.userData.layer=e.activeLayer,e.three.add(i),e.annotations.set(t.uuid,{system:this,data:t,three:i}),this._onAfterPersist(t,i),{drawing:e,item:t,group:i}}_redraw(e,t){for(;t.children.length>0;){const e=t.children[0];this._ownsChildGeometry&&e.geometry instanceof l.BufferGeometry&&e.geometry.dispose(),t.remove(e)}const s=this._resolveStyle(e.style),i=this._buildGroup(e,s);for(;i.children.length>0;)t.add(i.children[0]);this._onAfterPersist(e,t)}}function xz(e,t){const s=e[0],i=e[e.length-1],r=(new l.Vector3).subVectors(i,s);if(r.lengthSq()<1e-10)return 0;r.normalize();const n=new l.Vector3(-r.z,0,r.x);return t.clone().sub(s).dot(n)}function bz(e,t){const s=[];for(let i=0;i<e.length-1;i++)s.push({uuid:l.MathUtils.generateUUID(),pointA:e[i].clone(),pointB:e[i+1].clone(),offset:t,style:""});return s}function _z(e,t){switch(e.kind){case"awaitingFirstPoint":if("CLICK"===t.type){if(!t.line)return e;const s=(new l.Vector3).subVectors(t.line.end,t.line.start).normalize();return{kind:"placingPoints",points:[t.point.clone()],cursor:null,lineDir:s,firstLine:t.line.clone()}}return"SELECT_LINE"===t.type?{kind:"positioningOffset",points:[t.line.start.clone(),t.line.end.clone()],cursor:null}:e;case"placingPoints":if("MOUSE_MOVE"===t.type){const s=new l.Vector3(-e.lineDir.z,0,e.lineDir.x),i=e.points[e.points.length-1],r=t.point.clone().sub(i).dot(s),n=i.clone().addScaledVector(s,r);return{...e,cursor:n}}if("CLICK"===t.type){if(!t.line)return e;if(function(e,t){const s=1e-6;return e.start.distanceTo(t.start)<s&&e.end.distanceTo(t.end)<s||e.start.distanceTo(t.end)<s&&e.end.distanceTo(t.start)<s}(t.line,e.firstLine))return e;const r=(new l.Vector3).subVectors(t.line.end,t.line.start).normalize();if(s=r,i=e.lineDir,!(Math.abs(s.dot(i))>.999))return e;const n=function(e,t,s){const i=e.clone().sub(t.start).dot(s);return t.start.clone().addScaledVector(s,i)}(e.points[0],t.line,e.lineDir),o=[...e.points,n];return{...e,points:o,cursor:e.cursor}}return"CONFIRM"===t.type&&e.points.length>=2?{kind:"positioningOffset",points:e.points,cursor:null}:"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e;case"positioningOffset":if("MOUSE_MOVE"===t.type)return{...e,cursor:t.point.clone()};if("CLICK"===t.type){const s=xz(e.points,t.point);return{kind:"committed",dimensions:bz(e.points,s)}}return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e}var s,i}function wz(e){const{pointA:t,pointB:s,offset:i}=e,r=(new l.Vector3).subVectors(s,t),n=new l.Vector3(-r.z,0,r.x).normalize(),o=t.clone().addScaledVector(n,i),a=s.clone().addScaledVector(n,i),h=(new l.Vector3).subVectors(a,o).normalize();return[{tip:o,dir:h},{tip:a,dir:h.clone().negate()}]}function vz(e,t){const{pointA:s,pointB:i,offset:r}=e,n=(new l.Vector3).subVectors(i,s),o=new l.Vector3(-n.z,0,n.x).normalize(),a=r>=0?1:-1,h=Math.abs(r),u=s.clone().addScaledVector(o,t.extensionGap*a),c=s.clone().addScaledVector(o,(h+t.extensionOvershoot)*a),d=i.clone().addScaledVector(o,t.extensionGap*a),p=i.clone().addScaledVector(o,(h+t.extensionOvershoot)*a),m=s.clone().addScaledVector(o,r),f=i.clone().addScaledVector(o,r),g=(new l.Vector3).subVectors(f,m).normalize(),y=t.lineTick(m,g,t.tickSize),x=t.lineTick(f,g.clone().negate(),t.tickSize);return[u.x,u.y,u.z,c.x,c.y,c.z,d.x,d.y,d.z,p.x,p.y,p.z,m.x,m.y,m.z,f.x,f.y,f.z,...y,...x]}function Tz(e,t,s,i){if("placingPoints"===e){const e=[];for(let s=0;s<t.length-1;s++){const i=t[s],r=t[s+1];e.push(i.x,i.y,i.z,r.x,r.y,r.z)}if(s){const i=t[t.length-1];e.push(i.x,i.y,i.z,s.x,s.y,s.z)}return e}if(!s||t.length<2)return[];const r=xz(t,s),n=[];for(let e=0;e<t.length-1;e++)n.push(...vz({pointA:t[e],pointB:t[e+1],offset:r},i));return n}class Sz extends yz{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingFirstPoint"}),t(this,"onMachineStateChanged",new u),this.styles.set("default",{lineTick:iz,tickSize:.4,extensionGap:.05,extensionOvershoot:.2,color:0,textOffset:.4,fontSize:.45})}pickHandle(e,t,s=.1){const i=(new l.Matrix4).copy(e.three.matrixWorld).invert(),r=t.origin.clone().applyMatrix4(i),n=t.direction.clone().transformDirection(i).normalize(),o=new l.Ray(r,n),a=new l.Plane(new l.Vector3(0,1,0),0),h=o.intersectPlane(a,new l.Vector3);if(!h)return null;let u=null,c=s;for(const[t,s]of e.annotations.getBySystem(this)){const e=(new l.Vector3).subVectors(s.pointB,s.pointA),i=new l.Vector3(-e.z,0,e.x).normalize(),r=(new l.Vector3).addVectors(s.pointA,s.pointB).multiplyScalar(.5).addScaledVector(i,s.offset);for(const[e,i]of[["pointA",s.pointA],["pointB",s.pointB],["offset",r]]){const s=Math.hypot(h.x-i.x,h.z-i.z);s<c&&(c=s,u={uuid:t,handle:e})}}return u}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const s=_z(this.machineState,e);if(s!==this.machineState){if(this.machineState=s,this._updatePreview(),"committed"===s.kind){if(!this._previewDrawing)return console.warn("LinearAnnotations: no drawing context — send a CLICK or SELECT_LINE with `drawing` first. Skipping."),void this._resetMachine();for(const e of s.dimensions)e.style=this.activeStyle;const e=s.dimensions.map(e=>this._persist(this._previewDrawing,e));this.onCommit.trigger(e)}this.onMachineStateChanged.trigger(this.machineState),"committed"===s.kind&&this._resetMachine()}}_buildGroup(e,t){const s=new l.Group,i=vz(e,t),r=new l.BufferGeometry;r.setAttribute("position",new l.BufferAttribute(new Float32Array(i),3));const n=new l.LineSegments(r,this._getMaterial(e.style));if(n.layers.set(1),n.userData.isDimension=!0,s.add(n),t.meshTick)for(const{tip:i,dir:r}of wz(e)){const n=t.meshTick(i,r,t.tickSize),o=new l.BufferGeometry;o.setAttribute("position",new l.BufferAttribute(new Float32Array(n),3));const a=new l.Mesh(o,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isMeshTick=!0,s.add(a)}return s}_updatePreview(){const e=this.machineState;if("placingPoints"!==e.kind&&"positioningOffset"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle);this._previewMaterial.color.setHex(t.color);const s=Tz(e.kind,e.points,e.cursor,t);if(0===s.length)return void this._clearPreview();const i=s.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==i){this._clearPreview();const e=new l.BufferGeometry;e.setAttribute("position",new l.BufferAttribute(new Float32Array(s),3)),this._previewObject=new l.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(s),e.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingFirstPoint"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}}const Mz=Math.PI/180;function Az(e,t,s,i){const r=function(e,t,s){const i=(new l.Vector3).subVectors(e,t).normalize(),r=(new l.Vector3).subVectors(s,t).normalize();return(new l.Vector3).addVectors(i,r).normalize()}(e,t,s);return(new l.Vector3).subVectors(i,t).setY(0).dot(r)}function Nz(e,t,s,i){return Az(e,t,s,i)<0}function Ez(e,t){switch(e.kind){case"awaitingFirstLine":return"CLICK"===t.type&&t.line?{kind:"awaitingSecondLine",line1:t.line.clone(),pointA:t.point.clone()}:e;case"awaitingSecondLine":if("CLICK"===t.type&&t.line){const s=(new l.Vector3).subVectors(e.line1.end,e.line1.start).normalize(),i=(new l.Vector3).subVectors(t.line.end,t.line.start).normalize();if(Math.abs(s.dot(i))>Math.cos(Mz))return e;const r=function(e,t,s,i){const r=t.x*i.z-t.z*i.x;if(Math.abs(r)<1e-10)return null;const n=(new l.Vector3).subVectors(s,e),o=(n.x*i.z-n.z*i.x)/r;return new l.Vector3(e.x+t.x*o,0,e.z+t.z*o)}(e.line1.start,s,t.line.start,i);return r?{kind:"positioningArc",pointA:e.pointA.clone(),vertex:r,pointB:t.point.clone(),cursor:null,flipped:!1}:e}return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e;case"positioningArc":if("MOUSE_MOVE"===t.type){const s=Nz(e.pointA,e.vertex,e.pointB,t.point);return{...e,cursor:t.point.clone(),flipped:s}}if("CLICK"===t.type){const s=Nz(e.pointA,e.vertex,e.pointB,t.point),i=Math.max(.05,Math.abs(Az(e.pointA,e.vertex,e.pointB,t.point)));return{kind:"committed",dimension:{uuid:l.MathUtils.generateUUID(),pointA:e.pointA.clone(),vertex:e.vertex.clone(),pointB:e.pointB.clone(),arcRadius:i,flipped:s,style:""}}}return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e}}function Cz(e){const t=(new l.Vector3).subVectors(e.pointA,e.vertex).normalize(),s=(new l.Vector3).subVectors(e.pointB,e.vertex).normalize(),i=Math.atan2(t.z,t.x);let r=Math.atan2(s.z,s.x)-i;for(;r>Math.PI;)r-=2*Math.PI;for(;r<-Math.PI;)r+=2*Math.PI;e.flipped&&(r-=2*Math.sign(r)*Math.PI);const n=new l.Vector3(e.vertex.x+Math.cos(i)*e.arcRadius,0,e.vertex.z+Math.sin(i)*e.arcRadius),o=i+r,a=new l.Vector3(e.vertex.x+Math.cos(o)*e.arcRadius,0,e.vertex.z+Math.sin(o)*e.arcRadius),h=Math.sign(r);return[{tip:n,dir:new l.Vector3(-Math.sin(i)*h,0,Math.cos(i)*h)},{tip:a,dir:new l.Vector3(Math.sin(o)*h,0,-Math.cos(o)*h)}]}function Rz(e){const t=(new l.Vector3).subVectors(e.pointA,e.vertex).normalize(),s=(new l.Vector3).subVectors(e.pointB,e.vertex).normalize(),i=Math.acos(l.MathUtils.clamp(t.dot(s),-1,1));return e.flipped?2*Math.PI-i:i}function Pz(e){const t=(new l.Vector3).subVectors(e.pointA,e.vertex).normalize(),s=(new l.Vector3).subVectors(e.pointB,e.vertex).normalize(),i=Math.atan2(t.z,t.x);let r=Math.atan2(s.z,s.x)-i;for(;r>Math.PI;)r-=2*Math.PI;for(;r<-Math.PI;)r+=2*Math.PI;const n=i+r/2;return e.flipped?n+Math.PI:n}function Bz(e,t,s,i,r,n=!1){const o=Math.atan2(t.z,t.x);let a=Math.atan2(s.z,s.x)-o;for(;a>Math.PI;)a-=2*Math.PI;for(;a<-Math.PI;)a+=2*Math.PI;n&&(a-=2*Math.sign(a)*Math.PI);const h=[];for(let t=0;t<8;t++){const s=o+a*(t/8),r=o+a*((t+1)/8);h.push(e.x+Math.cos(s)*i,0,e.z+Math.sin(s)*i,e.x+Math.cos(r)*i,0,e.z+Math.sin(r)*i)}const u=new l.Vector3(e.x+Math.cos(o)*i,0,e.z+Math.sin(o)*i),c=new l.Vector3(e.x+Math.cos(o+a)*i,0,e.z+Math.sin(o+a)*i),d=e.clone().addScaledVector(t,r.extensionGap),p=e.clone().addScaledVector(s,r.extensionGap);h.push(d.x,d.y,d.z,u.x,u.y,u.z,p.x,p.y,p.z,c.x,c.y,c.z);const m=Math.sign(a),f=new l.Vector3(-Math.sin(o)*m,0,Math.cos(o)*m),g=o+a,y=new l.Vector3(Math.sin(g)*m,0,-Math.cos(g)*m);return h.push(...r.lineTick(u,f,r.tickSize),...r.lineTick(c,y,r.tickSize)),h}function Iz(e,t){const s=(new l.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new l.Vector3).subVectors(e.pointB,e.vertex).normalize();return Bz(e.vertex,s,i,e.arcRadius,t,e.flipped??!1)}function Dz(e,t,s,i,r,n=!1){if(!i)return[];const o=Math.max(.05,(new l.Vector3).subVectors(i,t).setY(0).length());return Bz(t,(new l.Vector3).subVectors(e,t).normalize(),(new l.Vector3).subVectors(s,t).normalize(),o,r,n)}class Lz extends yz{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingFirstLine"}),t(this,"onMachineStateChanged",new u),t(this,"_secondLinePreviewObject",null),this.styles.set("default",{lineTick:iz,tickSize:.4,extensionGap:.05,color:0,textOffset:.25,fontSize:.45})}pickHandle(e,t,s){return null}sendMachineEvent(e){const t=e.drawing??null;if("awaitingSecondLine"===this.machineState.kind&&"MOUSE_MOVE"===e.type)return t&&(this._previewDrawing=t),void this._updateSecondLinePreview(e.point,e.line??null);const s=Ez(this.machineState,e);if(s!==this.machineState){if("awaitingSecondLine"===this.machineState.kind&&this._clearSecondLinePreview(),this.machineState=s,t&&(this._previewDrawing=t),this._updatePreview(),"committed"===s.kind){if(!this._previewDrawing)return console.warn("AngleAnnotations: CLICK that commits must include `drawing`. Skipping."),void this._resetMachine();s.dimension.style=this.activeStyle;const e=this._persist(this._previewDrawing,s.dimension);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===s.kind&&this._resetMachine()}}_buildGroup(e,t){const s=new l.Group,i=Iz(e,t),r=new l.BufferGeometry;r.setAttribute("position",new l.BufferAttribute(new Float32Array(i),3));const n=new l.LineSegments(r,this._getMaterial(e.style));if(n.layers.set(1),n.userData.isDimension=!0,s.add(n),t.meshTick)for(const{tip:i,dir:r}of Cz(e)){const n=t.meshTick(i,r,t.tickSize),o=new l.BufferGeometry;o.setAttribute("position",new l.BufferAttribute(new Float32Array(n),3));const a=new l.Mesh(o,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isMeshTick=!0,s.add(a)}return s}_updatePreview(){const e=this.machineState;if("positioningArc"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle),s=Dz(e.pointA,e.vertex,e.pointB,e.cursor,t,e.flipped);if(0===s.length)return void this._clearPreview();const i=s.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==i){this._clearPreview();const e=new l.BufferGeometry;e.setAttribute("position",new l.BufferAttribute(new Float32Array(s),3)),this._previewObject=new l.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(s),e.needsUpdate=!0}}_onDispose(){this._clearSecondLinePreview()}_resetMachine(){this.machineState={kind:"awaitingFirstLine"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearSecondLinePreview(){this._secondLinePreviewObject&&(this._secondLinePreviewObject.removeFromParent(),this._secondLinePreviewObject.geometry.dispose(),this._secondLinePreviewObject=null)}_updateSecondLinePreview(e,t){if("awaitingSecondLine"!==this.machineState.kind)return void this._clearSecondLinePreview();if(!this._previewDrawing)return void this._clearSecondLinePreview();const s=this.machineState,i=(new l.Vector3).subVectors(s.line1.end,s.line1.start).normalize();if(!t)return void this._clearSecondLinePreview();const r=(new l.Vector3).subVectors(t.end,t.start).normalize(),n=function(e,t,s,i){const r=t.x*i.z-t.z*i.x;if(Math.abs(r)<1e-6)return null;const n=s.x-e.x,o=s.z-e.z,a=(n*i.z-o*i.x)/r;return new l.Vector3(e.x+a*t.x,0,e.z+a*t.z)}(s.line1.start,i,t.start,r);if(!n)return void this._clearSecondLinePreview();const o=e.clone(),a=(new l.Vector3).subVectors(o,n).setY(0);if(a.length()<.01)return void this._clearSecondLinePreview();const h=(new l.Vector3).subVectors(s.pointA,n).normalize(),u=a.normalize(),c=Math.atan2(h.z,h.x);let d=Math.atan2(u.z,u.x)-c;for(;d>Math.PI;)d-=2*Math.PI;for(;d<-Math.PI;)d+=2*Math.PI;const p=c+d/2,m=Math.max(.1,.4*Math.min(s.pointA.distanceTo(n),o.distanceTo(n))),f=new l.Vector3(n.x+Math.cos(p)*m,0,n.z+Math.sin(p)*m),g=this._resolveStyle(this.activeStyle),y=Dz(s.pointA,n,o,f,g);if(0===y.length)return void this._clearSecondLinePreview();const x=y.length/3;if(!this._secondLinePreviewObject||this._secondLinePreviewObject.geometry.attributes.position.count!==x){this._clearSecondLinePreview();const e=new l.BufferGeometry;e.setAttribute("position",new l.BufferAttribute(new Float32Array(y),3)),this._secondLinePreviewObject=new l.LineSegments(e,this._previewMaterial),this._secondLinePreviewObject.layers.set(1),this._secondLinePreviewObject.renderOrder=1,this._secondLinePreviewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._secondLinePreviewObject)}else{const e=this._secondLinePreviewObject.geometry.attributes.position;e.set(y),e.needsUpdate=!0}}}function Fz(e,t){const s=t.x-e.x,i=t.z-e.z,r=Math.sqrt(s*s+i*i);if(0===r)return e.clone();const n=Math.atan2(i,s),o=Math.round(n/(Math.PI/4))*(Math.PI/4);return new l.Vector3(e.x+Math.cos(o)*r,0,e.z+Math.sin(o)*r)}function Oz(e,t){switch(e.kind){case"awaitingArrowTip":return"CLICK"===t.type?{kind:"placingElbow",arrowTip:t.point.clone(),cursor:null}:e;case"placingElbow":return"MOUSE_MOVE"===t.type?{...e,cursor:t.point.clone()}:"CLICK"===t.type?{kind:"placingExtension",arrowTip:e.arrowTip,elbow:t.point.clone(),cursor:null}:"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"placingExtension":return"MOUSE_MOVE"===t.type?{...e,cursor:Fz(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",arrowTip:e.arrowTip,elbow:e.elbow,extensionEnd:Fz(e.elbow,t.point)}:"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"enteringText":if("SUBMIT_TEXT"===t.type&&t.text.trim().length>0){return{kind:"committed",annotation:{uuid:l.MathUtils.generateUUID(),arrowTip:e.arrowTip.clone(),elbow:e.elbow.clone(),extensionEnd:e.extensionEnd.clone(),text:t.text.trim(),style:""}}}return"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e}}function Vz(e,t,s,i){return"curved"===i.leaderShape?function(e,t,s,i){const r=new l.QuadraticBezierCurve3(e,t,s).getPoints(24),n=[];for(let e=0;e<r.length-1;e++){const t=r[e],s=r[e+1];n.push(t.x,t.y,t.z,s.x,s.y,s.z)}if(i.lineTick){const s=(new l.Vector3).subVectors(e,t);s.lengthSq()>1e-10&&n.push(...i.lineTick(e,s.normalize(),i.tickSize))}return n}(e,t,s,i):function(e,t,s,i){const r=[e.x,e.y,e.z,t.x,t.y,t.z,t.x,t.y,t.z,s.x,s.y,s.z];if(i.lineTick){const s=(new l.Vector3).subVectors(e,t);s.lengthSq()>1e-10&&r.push(...i.lineTick(e,s.normalize(),i.tickSize))}return r}(e,t,s,i)}function zz(e,t){return Vz(e.arrowTip,e.elbow,e.extensionEnd,t)}function kz(e,t,s,i,r){return i?Vz(t,"placingElbow"===e?i:s,i,r):[]}class Uz extends yz{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingArrowTip"}),t(this,"onMachineStateChanged",new u),t(this,"_previewMeshMaterial",new l.MeshBasicMaterial({color:16737894,side:l.DoubleSide,depthTest:!1})),t(this,"_previewMeshObject",null),this.styles.set("default",{tickSize:.4,color:0,textOffset:.1,fontSize:.45,lineTick:rz})}pickHandle(e,t,s=.1){const i=(new l.Matrix4).copy(e.three.matrixWorld).invert(),r=t.origin.clone().applyMatrix4(i),n=t.direction.clone().transformDirection(i).normalize(),o=new l.Ray(r,n),a=new l.Plane(new l.Vector3(0,1,0),0),h=o.intersectPlane(a,new l.Vector3);if(!h)return null;let u=null,c=s;for(const[t,s]of e.annotations.getBySystem(this))for(const[e,i]of[["elbow",s.elbow],["extensionEnd",s.extensionEnd]]){const s=Math.hypot(h.x-i.x,h.z-i.z);s<c&&(c=s,u={uuid:t,handle:e})}return u}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const s=Oz(this.machineState,e);if(s!==this.machineState){if(this.machineState=s,this._updatePreview(),"committed"===s.kind){if(!this._previewDrawing)return console.warn("LeaderAnnotations: commit requires a drawing. Skipping."),void this._resetMachine();s.annotation.style=this.activeStyle;const e=this._persist(this._previewDrawing,s.annotation);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===s.kind&&this._resetMachine()}}_buildGroup(e,t){const s=new l.Group,i=zz(e,t),r=new l.BufferGeometry;r.setAttribute("position",new l.BufferAttribute(new Float32Array(i),3));const n=new l.LineSegments(r,this._getMaterial(e.style));if(n.layers.set(1),n.userData.isDimension=!0,s.add(n),t.meshTick){const i=(new l.Vector3).subVectors(e.arrowTip,e.elbow);if(i.lengthSq()>1e-10){i.normalize();const r=t.meshTick(e.arrowTip,i,t.tickSize),n=new l.BufferGeometry;n.setAttribute("position",new l.BufferAttribute(new Float32Array(r),3));const o=new l.Mesh(n,this._getMeshMaterial(e.style));o.layers.set(1),o.userData.isMeshArrow=!0,s.add(o)}}return s}_updatePreview(){const e=this.machineState;if("placingElbow"!==e.kind&&"placingExtension"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle),s="placingElbow"===e.kind?kz("placingElbow",e.arrowTip,null,e.cursor,t):kz("placingExtension",e.arrowTip,e.elbow,e.cursor,t);if(0===s.length)return void this._clearPreview();const i=s.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==i){this._clearPreview();const e=new l.BufferGeometry;e.setAttribute("position",new l.BufferAttribute(new Float32Array(s),3)),this._previewObject=new l.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(s),e.needsUpdate=!0}if(t.meshTick){const s="placingElbow"===e.kind?e.cursor:e.elbow,i=s?(new l.Vector3).subVectors(e.arrowTip,s):null;if(i&&i.lengthSq()>1e-10){i.normalize();const s=t.meshTick(e.arrowTip,i,t.tickSize);if(this._previewMeshObject){const e=this._previewMeshObject.geometry.attributes.position;e.set(s),e.needsUpdate=!0}else{const e=new l.BufferGeometry;e.setAttribute("position",new l.BufferAttribute(new Float32Array(s),3)),this._previewMeshObject=new l.Mesh(e,this._previewMeshMaterial),this._previewMeshObject.layers.set(1),this._previewMeshObject.renderOrder=1,this._previewMeshObject.frustumCulled=!1,this._previewDrawing.three.add(this._previewMeshObject)}}else this._clearPreviewMesh()}else this._clearPreviewMesh()}_clearPreview(){super._clearPreview(),this._clearPreviewMesh()}_onDispose(){this._clearPreviewMesh(),this._previewMeshMaterial.dispose()}_resetMachine(){this.machineState={kind:"awaitingArrowTip"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearPreviewMesh(){this._previewMeshObject&&(this._previewMeshObject.removeFromParent(),this._previewMeshObject.geometry.dispose(),this._previewMeshObject=null)}}class Gz extends yz{constructor(e){super(e),t(this,"enabled",!0),t(this,"_ownsChildGeometry",!1),t(this,"definitions",new a.DataMap),this.styles.set("default",{color:0,textOffset:0,fontSize:0})}pickHandle(e,t,s){return null}pick(e,t=.05){const s=new l.Raycaster;s.ray.copy(e),s.params.Line={threshold:t},s.params.LineSegments={threshold:t};let i=null,r=1/0;for(const e of this._knownDrawings)for(const[t,n]of e.annotations){if(n.system!==this)continue;const e=n.three;e.updateWorldMatrix(!0,!0),e.traverse(n=>{if(n===e)return;if(!(n instanceof l.LineSegments))return;const o=[];n.raycast(s,o),o.length>0&&o[0].distance<r&&(r=o[0].distance,i=t)})}return i}define(e,t){this.definitions.set(e,t)}_buildGroup(e,t){const s=this.definitions.get(e.blockName);if(!s)throw new Error(`BlockAnnotations: block "${e.blockName}" is not defined.`);const i=new l.Group;if(s.lines){const t=new l.LineSegments(s.lines,this._getMaterial(e.style));t.layers.set(1),t.userData.isDimension=!0,i.add(t)}if(s.mesh){const t=new l.Mesh(s.mesh,this._getMeshMaterial(e.style));t.layers.set(1),t.userData.isBlockMesh=!0,i.add(t)}return i}_onAfterPersist(e,t){t.position.set(e.position.x,0,e.position.z),t.rotation.set(0,e.rotation,0),t.scale.setScalar(e.scale)}_onDispose(){var e,t;for(const s of this.definitions.values())null==(e=s.lines)||e.dispose(),null==(t=s.mesh)||t.dispose();this.definitions.clear()}}function jz(e,t){const{position:s,direction:i}=e,{length:r}=t,n=new l.Vector3(s.x+i.x*r,0,s.z+i.z*r),o=new l.Vector3(i.x,0,i.z),a=t.lineTick(n,o,t.tickSize),h=[s.x,0,s.z,n.x,0,n.z];return new Float32Array([...h,...a])}function $z(e,t){return new l.Vector3(e.position.x+e.direction.x*t,0,e.position.z+e.direction.z*t)}function Wz(e,t){switch(t){case"percentage":return`${(100*e).toFixed(2)} %`;case"ratio":return 0===e?"1:∞":`1:${(1/e).toFixed(2)}`;case"degrees":return`${(180*Math.atan(e)/Math.PI).toFixed(2)}°`}}class Hz extends yz{constructor(e){super(e),t(this,"enabled",!0),this.styles.set("default",{lineTick:nz,meshTick:oz,tickSize:.4,length:3,color:0,textOffset:.1,fontSize:.45,format:"percentage"})}pickHandle(e,t,s){return null}_buildGroup(e,t){const s=new l.Group,i=jz(e,t),r=new l.BufferGeometry;r.setAttribute("position",new l.BufferAttribute(i,3));const n=new l.LineSegments(r,this._getMaterial(e.style));if(n.layers.set(1),n.userData.isDimension=!0,s.add(n),t.meshTick){const i=$z(e,t.length),r=t.meshTick(i,e.direction,t.tickSize),n=new l.BufferGeometry;n.setAttribute("position",new l.BufferAttribute(new Float32Array(r),3));const o=new l.Mesh(n,this._getMeshMaterial(e.style));o.layers.set(1),o.userData.isDimension=!0,s.add(o)}return s}}function qz(e,t){const s=t.x-e.x,i=t.z-e.z,r=Math.sqrt(s*s+i*i);if(0===r)return e.clone();const n=Math.atan2(i,s),o=Math.round(n/(Math.PI/4))*(Math.PI/4);return new l.Vector3(e.x+Math.cos(o)*r,0,e.z+Math.sin(o)*r)}function Xz(e,t){switch(e.kind){case"awaitingCenter":return"CLICK"===t.type?{kind:"awaitingRadius",center:t.point.clone(),cursor:null}:e;case"awaitingRadius":if("MOUSE_MOVE"===t.type)return{...e,cursor:t.point.clone()};if("CLICK"===t.type){const s=Math.max(.1,Math.abs(t.point.x-e.center.x)),i=Math.max(.1,Math.abs(t.point.z-e.center.z));return{kind:"awaitingElbow",center:e.center,halfW:s,halfH:i,cursor:null}}return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"awaitingElbow":return"MOUSE_MOVE"===t.type?{...e,cursor:t.point.clone()}:"CLICK"===t.type?{kind:"awaitingExtension",center:e.center,halfW:e.halfW,halfH:e.halfH,elbow:t.point.clone(),cursor:null}:"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"awaitingExtension":return"MOUSE_MOVE"===t.type?{...e,cursor:qz(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",center:e.center,halfW:e.halfW,halfH:e.halfH,elbow:e.elbow,extensionEnd:qz(e.elbow,t.point)}:"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"enteringText":if("SUBMIT_TEXT"===t.type&&t.text.trim().length>0){return{kind:"committed",annotation:{uuid:l.MathUtils.generateUUID(),center:e.center.clone(),halfW:e.halfW,halfH:e.halfH,elbow:e.elbow.clone(),extensionEnd:e.extensionEnd.clone(),text:t.text.trim(),style:""}}}return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e}}function Yz(e,t){const s=[];s.push(...t.enclosure.buildGeometry(e.center,e.halfW,e.halfH));const i=(new l.Vector3).subVectors(e.elbow,e.center),r=i.lengthSq()>1e-10?i.clone().normalize():new l.Vector3(1,0,0),n=t.enclosure.getAttachmentPoint(e.center,e.halfW,e.halfH,r);if(s.push(n.x,n.y,n.z,e.elbow.x,e.elbow.y,e.elbow.z,e.elbow.x,e.elbow.y,e.elbow.z,e.extensionEnd.x,e.extensionEnd.y,e.extensionEnd.z),t.lineTick){const i=(new l.Vector3).subVectors(e.extensionEnd,e.elbow);i.lengthSq()>1e-10&&s.push(...t.lineTick(e.extensionEnd,i.normalize(),t.tickSize))}return s}function Zz(e,t,s,i,r,n,o){const a="awaitingRadius"===e?n?Math.max(.05,Math.abs(n.x-t.x)):0:s,h="awaitingRadius"===e?n?Math.max(.05,Math.abs(n.z-t.z)):0:i;if(a<1e-10||h<1e-10)return[];const u=[];if(u.push(...o.enclosure.buildGeometry(t,a,h)),"awaitingRadius"===e)return u;const c="awaitingElbow"===e?n:r;if(!c)return u;const d=(new l.Vector3).subVectors(c,t),p=d.lengthSq()>1e-10?d.clone().normalize():new l.Vector3(1,0,0),m=o.enclosure.getAttachmentPoint(t,a,h,p);return"awaitingElbow"===e?(u.push(m.x,0,m.z,c.x,0,c.z),u):n?(u.push(m.x,0,m.z,r.x,0,r.z,r.x,0,r.z,n.x,0,n.z),u):u}const Qz={buildGeometry(e,t,s){const i=.25*Math.min(t,s),r=new l.Vector3(e.x-t,0,e.z-s),n=new l.Vector3(e.x+t,0,e.z-s),o=new l.Vector3(e.x+t,0,e.z+s),a=new l.Vector3(e.x-t,0,e.z+s),h=[[r,n,new l.Vector3(0,0,-1)],[n,o,new l.Vector3(1,0,0)],[o,a,new l.Vector3(0,0,1)],[a,r,new l.Vector3(-1,0,0)]],u=[];for(const[e,t,s]of h){const r=e.distanceTo(t),n=Math.max(1,Math.round(r/(2*i))),o=r/n,a=o/2,h=(new l.Vector3).subVectors(t,e).normalize();for(let t=0;t<n;t++){const i=e.clone().addScaledVector(h,(t+.5)*o),r=e.clone().addScaledVector(h,t*o),n=(new l.Vector3).subVectors(r,i);let c=r.clone();for(let e=1;e<=8;e++){const t=e/8*Math.PI,r=i.x+n.x*Math.cos(t)+s.x*a*Math.sin(t),o=i.z+n.z*Math.cos(t)+s.z*a*Math.sin(t),h=new l.Vector3(r,0,o);u.push(c.x,0,c.z,h.x,0,h.z),c=h}}}return u},getAttachmentPoint(e,t,s,i){const r=Math.abs(i.x)>1e-10?t/Math.abs(i.x):1/0,n=Math.abs(i.z)>1e-10?s/Math.abs(i.z):1/0,o=Math.min(r,n);return new l.Vector3(e.x+i.x*o,0,e.z+i.z*o)}},Kz={buildGeometry(e,t,s){const i=new l.Vector3(e.x-t,0,e.z-s),r=new l.Vector3(e.x+t,0,e.z-s),n=new l.Vector3(e.x+t,0,e.z+s),o=new l.Vector3(e.x-t,0,e.z+s);return[i.x,0,i.z,r.x,0,r.z,r.x,0,r.z,n.x,0,n.z,n.x,0,n.z,o.x,0,o.z,o.x,0,o.z,i.x,0,i.z]},getAttachmentPoint(e,t,s,i){const r=Math.abs(i.x)>1e-10?t/Math.abs(i.x):1/0,n=Math.abs(i.z)>1e-10?s/Math.abs(i.z):1/0,o=Math.min(r,n);return new l.Vector3(e.x+i.x*o,0,e.z+i.z*o)}},Jz={buildGeometry(e,t,s){const i=[];for(let r=0;r<32;r++){const n=r/32*Math.PI*2,o=(r+1)/32*Math.PI*2;i.push(e.x+Math.cos(n)*t,0,e.z+Math.sin(n)*s,e.x+Math.cos(o)*t,0,e.z+Math.sin(o)*s)}return i},getAttachmentPoint(e,t,s,i){const r=i.x/t,n=i.z/s,o=Math.sqrt(r*r+n*n),a=o>1e-10?1/o:t;return new l.Vector3(e.x+i.x*a,0,e.z+i.z*a)}};class ek extends yz{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingCenter"}),t(this,"onMachineStateChanged",new u),this.styles.set("default",{enclosure:Qz,lineTick:rz,tickSize:.4,color:22015,textOffset:.1,fontSize:.45})}pickHandle(e,t,s){return null}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const s=Xz(this.machineState,e);if(s!==this.machineState){if(this.machineState=s,this._updatePreview(),"committed"===s.kind){if(!this._previewDrawing)return console.warn("CalloutAnnotations: commit requires a drawing. Pass `drawing` on the first CLICK."),void this._resetMachine();s.annotation.style=this.activeStyle;const e=this._persist(this._previewDrawing,s.annotation);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===s.kind&&this._resetMachine()}}_buildGroup(e,t){const s=new l.Group,i=Yz(e,t),r=new l.BufferGeometry;r.setAttribute("position",new l.BufferAttribute(new Float32Array(i),3));const n=new l.LineSegments(r,this._getMaterial(e.style));if(n.layers.set(1),n.userData.isDimension=!0,s.add(n),t.meshTick){const i=(new l.Vector3).subVectors(e.extensionEnd,e.elbow);if(i.lengthSq()>1e-10){i.normalize();const r=t.meshTick(e.extensionEnd,i,t.tickSize),n=new l.BufferGeometry;n.setAttribute("position",new l.BufferAttribute(new Float32Array(r),3));const o=new l.Mesh(n,this._getMeshMaterial(e.style));o.layers.set(1),o.userData.isMeshArrow=!0,s.add(o)}}return s}_updatePreview(){const e=this.machineState;if("awaitingRadius"!==e.kind&&"awaitingElbow"!==e.kind&&"awaitingExtension"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return;const t=this._resolveStyle(this.activeStyle),s=(()=>{switch(e.kind){case"awaitingRadius":return Zz("awaitingRadius",e.center,0,0,null,e.cursor,t);case"awaitingElbow":return Zz("awaitingElbow",e.center,e.halfW,e.halfH,null,e.cursor,t);case"awaitingExtension":return Zz("awaitingExtension",e.center,e.halfW,e.halfH,e.elbow,e.cursor,t)}})();if(0===s.length)return void this._clearPreview();const i=s.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==i){this._clearPreview();const e=new l.BufferGeometry;e.setAttribute("position",new l.BufferAttribute(new Float32Array(s),3)),this._previewObject=new l.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(s),e.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingCenter"},this._clearPreview(),this._previewDrawing=null,this.onMachineStateChanged.trigger(this.machineState)}}const tk=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"list",new a.DataMap),t(this,"systems",new a.DataMap),t(this,"onDisposed",new u),s.add(e.uuid,this),this.list.onBeforeDelete.add(({value:e})=>e.dispose()),this.systems.onBeforeDelete.add(({value:e})=>e.dispose())}use(e){if(this.systems.has(e))return this.systems.get(e);const t=new e(this.components);return this.systems.set(e,t),t}create(e){const t=new gz(this.components);t.world=e,e.scene.three.add(t.three),e.onDisposed.add(()=>this.list.delete(t.uuid));const s=e.camera;return s.three.layers.enable(1),s instanceof BO&&(s.threePersp.layers.enable(1),s.threeOrtho.layers.enable(1)),this.list.set(t.uuid,t),t}dispose(){this.list.clear(),this.systems.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};t(tk,"uuid","5c7d3b9a-4e8f-4a2b-9c1d-0e3f2a5b7c8d");let sk=tk;const ik=[[16711680,1],[16776960,2],[65280,3],[65535,4],[255,5],[16711935,6],[16777215,7],[0,7]];function rk(e){const t=e>>16&255,s=e>>8&255,i=255&e;let r=7,n=1/0;for(const[e,o]of ik){const a=(t-(e>>16&255))**2+(s-(e>>8&255))**2+(i-(255&e))**2;a<n&&(n=a,r=o)}return r}class nk{constructor(){t(this,"_lines",[]),t(this,"_handleCounter",1)}p(e,t){return this._lines.push(String(e),String(t)),this}n(e,t,s=6){return this._lines.push(String(e),t.toFixed(s)),this}handle(){return(this._handleCounter++).toString(16).toUpperCase()}build(){return this._lines.join("\n")+"\n"}}class ok{constructor(e){t(this,"precision",2),t(this,"config",{trueColor:!1}),t(this,"_viewport",null),t(this,"_paperSlot",null),t(this,"_annotationLayers",new Map),t(this,"_systemExporters",new Map),this._components=e}registerSystemExporter(e,t){this._systemExporters.set(e,t)}export(e,t){const s=!!t,i=new nk,r=new Map;for(const t of e)for(const e of t.drawing.layers.values())r.has(e.name)||r.set(e.name,e);const n=[...r.values()],o=this._components.get(sk).systems.get(Gz),a=o?[...o.definitions.keys()]:[];this._writeHeader(i,s),this._writeTables(i,n,a),this._writeBlocks(i,o??null),i.p(0,"SECTION").p(2,"ENTITIES"),s&&t&&this._writePaperBorders(i,t);for(const r of e){r.drawing.three.traverse(e=>{e.userData.isDimension&&e.userData.annotationUuid&&this._annotationLayers.set(e.userData.annotationUuid,e.userData.layer??"0")});for(const e of r.viewports){if(this._viewport=e.viewport??null,s&&e.viewport){const s=e.viewport,i=t.heightMm-2*t.margin;this._paperSlot={x:e.x??0,y:i-(e.y??0),mmPerUnit:1e3/s.drawingScale,vpLeft:s.left,vpTop:s.top}}else this._paperSlot=null;this._writeViewportBorder(i),this._writeRawLines(i,r.drawing),this._writeLinearAnnotations(i,r.drawing),this._writeAngleAnnotations(i,r.drawing),this._writeLeaderAnnotations(i,r.drawing),this._writeSlopeAnnotations(i,r.drawing),this._writeCalloutAnnotations(i,r.drawing),this._writeBlockInsertions(i,r.drawing),this._writeCustomSystems(i,r.drawing)}this._annotationLayers.clear()}return i.p(0,"ENDSEC"),this._writeObjects(i),i.p(0,"EOF"),this._viewport=null,this._paperSlot=null,i.build()}_writeHeader(e,t){e.p(0,"SECTION").p(2,"HEADER"),e.p(9,"$ACADVER").p(1,this.config.trueColor?"AC1018":"AC1015"),e.p(9,"$INSUNITS").p(70,t?4:6),e.p(0,"ENDSEC")}_writeTables(e,t,s){e.p(0,"SECTION").p(2,"TABLES"),e.p(0,"TABLE").p(2,"VPORT").p(70,0).p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"LTYPE").p(70,1),e.p(0,"LTYPE").p(2,"CONTINUOUS").p(70,0).p(3,"Solid line").p(72,65).p(73,0).n(40,0),e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"LAYER").p(70,t.length);for(const s of t){const t=rk(s.material.color.getHex());e.p(0,"LAYER").p(2,s.name).p(70,0).p(62,t).p(6,"CONTINUOUS")}e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"STYLE").p(70,1),e.p(0,"STYLE").p(2,"STANDARD").p(70,0).n(40,0).n(41,1).n(50,0).p(71,0).n(42,.2).p(3,"txt").p(4,""),e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"VIEW").p(70,0).p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"UCS").p(70,0).p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"APPID").p(70,1),e.p(0,"APPID").p(2,"ACAD").p(70,0),e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"DIMSTYLE").p(70,0).p(0,"ENDTAB");const i=["*Model_Space","*Paper_Space",...s];e.p(0,"TABLE").p(2,"BLOCK_RECORD").p(70,i.length);for(const t of i)e.p(0,"BLOCK_RECORD").p(5,e.handle()).p(2,t);e.p(0,"ENDTAB"),e.p(0,"ENDSEC")}_writeBlocks(e,t){if(e.p(0,"SECTION").p(2,"BLOCKS"),this._writeBlock(e,"*Model_Space",null),this._writeBlock(e,"*Paper_Space",null),t)for(const[s,i]of t.definitions)this._writeBlock(e,s,i.lines??null);e.p(0,"ENDSEC")}_writeBlock(e,t,s){if(e.p(0,"BLOCK").p(5,e.handle()).p(8,"0").p(2,t).p(70,0).n(10,0).n(20,0).n(30,0).p(3,t).p(1,""),s){const t=this._viewport,i=this._paperSlot;this._viewport=null,this._paperSlot=null,this._writeGeoAsLines(e,s,"0"),this._viewport=t,this._paperSlot=i}e.p(0,"ENDBLK").p(5,e.handle()).p(8,"0")}_writeViewportBorder(e){if(!this._viewport)return;const t=this._viewport,s=this._tx(t.left),i=this._tx(t.right),r=this._ty(-t.bottom),n=this._ty(-t.top);this._writeRawLine(e,s,r,i,r,"0",7),this._writeRawLine(e,i,r,i,n,"0",7),this._writeRawLine(e,i,n,s,n,"0",7),this._writeRawLine(e,s,n,s,r,"0",7)}_writePaperBorders(e,t){const{margin:s,widthMm:i,heightMm:r}=t,n=i-2*s,o=r-2*s;this._writeRawLine(e,0,0,n,0,"0",7),this._writeRawLine(e,n,0,n,o,"0",7),this._writeRawLine(e,n,o,0,o,"0",7),this._writeRawLine(e,0,o,0,0,"0",7),this._writeRawLine(e,-s,-s,n+s,-s,"0",7),this._writeRawLine(e,n+s,-s,n+s,o+s,"0",7),this._writeRawLine(e,n+s,o+s,-s,o+s,"0",7),this._writeRawLine(e,-s,o+s,-s,-s,"0",7)}_writeObjects(e){e.p(0,"SECTION").p(2,"OBJECTS"),e.p(0,"DICTIONARY").p(5,e.handle()).p(330,0).p(100,"AcDbRootDictionary"),e.p(0,"ENDSEC")}_writeRawLines(e,t){t.three.traverse(t=>{var s;if(!(t instanceof l.LineSegments))return;if(t.userData.isDimension)return;if(null==(s=t.parent)?void 0:s.userData.blockUuid)return;if(!t.visible)return;const i=t.userData.layer??"0",r=t.material.color.getHex();this._writeGeoAsLines(e,t.geometry,i,rk(r),r)})}_writeLinearAnnotations(e,t){var s;const i=this._components.get(sk).systems.get(Sz);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),o=rk(n.color),a=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(a))?void 0:s.visible))continue;const h=vz(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,a,o,n.color),n.meshTick)for(const{tip:t,dir:s}of wz(r))this._writeMeshTriangles(e,n.meshTick(t,s,n.tickSize),a,o,n.color);const u=(new l.Vector3).subVectors(r.pointB,r.pointA),c=new l.Vector3(-u.z,0,u.x).normalize(),d=r.offset>=0?1:-1,p=r.pointA.clone().addScaledVector(c,r.offset),m=r.pointB.clone().addScaledVector(c,r.offset),f=p.clone().add(m).multiplyScalar(.5).addScaledVector(c,(n.textOffset+.5*n.fontSize)*d),g=n.unit??{factor:1,suffix:"m"},y=`${(r.pointA.distanceTo(r.pointB)*g.factor).toFixed(this.precision)} ${g.suffix}`;this._writeText(e,y,f.x,f.z,n.fontSize,a,o,this._textAngle(u.x,u.z),1,2,n.color)}}_writeAngleAnnotations(e,t){var s;const i=this._components.get(sk).systems.get(Lz);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),o=rk(n.color),a=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(a))?void 0:s.visible))continue;const h=Iz(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,a,o,n.color),n.meshTick)for(const{tip:t,dir:s}of Cz(r))this._writeMeshTriangles(e,n.meshTick(t,s,n.tickSize),a,o,n.color);const u=Pz(r),c=r.arcRadius+n.textOffset,d=r.vertex.x+Math.cos(u)*c,p=r.vertex.z+Math.sin(u)*c,m=l.MathUtils.radToDeg(Rz(r));this._writeText(e,`${m.toFixed(this.precision)}°`,d,p,n.fontSize,a,o,0,1,0,n.color)}}_writeLeaderAnnotations(e,t){var s;const i=this._components.get(sk).systems.get(Uz);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),o=rk(n.color),a=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(a))?void 0:s.visible))continue;const h=zz(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,a,o,n.color),n.meshTick){const t=(new l.Vector3).subVectors(r.arrowTip,r.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,n.meshTick(r.arrowTip,t.normalize(),n.tickSize),a,o,n.color)}const u=(new l.Vector3).subVectors(r.extensionEnd,r.elbow).setY(0).normalize(),c=u.x<-.1?2:u.x>.1?0:1,d=1===c?.5*n.fontSize:0,p=r.extensionEnd.clone().addScaledVector(u,n.textOffset+d);this._writeText(e,r.text,p.x,p.z,n.fontSize,a,o,0,c,2,n.color)}}_writeSlopeAnnotations(e,t){var s;const i=this._components.get(sk).systems.get(Hz);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),o=rk(n.color),a=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(a))?void 0:s.visible))continue;const h=jz(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,a,o,n.color),n.meshTick){const t=$z(r,n.length);this._writeMeshTriangles(e,n.meshTick(t,r.direction,n.tickSize),a,o,n.color)}const u=new l.Vector3(r.position.x+r.direction.x*n.length,0,r.position.z+r.direction.z*n.length),c=r.position.clone().add(u).multiplyScalar(.5).addScaledVector(new l.Vector3(-r.direction.z,0,r.direction.x),n.textOffset+n.fontSize);this._writeText(e,Wz(r.slope,n.format),c.x,c.z,n.fontSize,a,o,this._textAngle(r.direction.x,r.direction.z),1,0,n.color)}}_writeCalloutAnnotations(e,t){var s;const i=this._components.get(sk).systems.get(ek);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),o=rk(n.color),a=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(a))?void 0:s.visible))continue;const h=Yz(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,a,o,n.color),n.meshTick){const t=(new l.Vector3).subVectors(r.extensionEnd,r.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,n.meshTick(r.extensionEnd,t.normalize(),n.tickSize),a,o,n.color)}const u=(new l.Vector3).subVectors(r.extensionEnd,r.elbow).setY(0).normalize(),c=u.x<-.1?2:u.x>.1?0:1,d=1===c?.5*n.fontSize:0,p=r.extensionEnd.clone().addScaledVector(u,n.textOffset+d);this._writeText(e,r.text,p.x,p.z,n.fontSize,a,o,0,c,2,n.color)}}_writeBlockInsertions(e,t){const s=this._components.get(sk).systems.get(Gz);if(s)for(const[,i]of t.annotations.getBySystem(s)){if(!this._inViewport(i.position.x,i.position.z))continue;const t=s.styles.get(i.style)??s.styles.get("default"),r=rk(t.color),n=-l.MathUtils.radToDeg(i.rotation),o=i.scale*this._scale();e.p(0,"INSERT").p(5,e.handle()).p(8,"0").p(62,r),this._emitTrueColor(e,t.color),e.p(2,i.blockName).n(10,this._tx(i.position.x)).n(20,this._ty(i.position.z)).n(30,0).n(41,o).n(42,o).n(43,o).n(50,n)}}_writeGeoAsLines(e,t,s,i=7,r){const n=t.attributes.position;if(n)for(let t=0;t+1<n.count;t+=2){const o=this._clipSegment(new l.Vector3(n.getX(t),0,n.getZ(t)),new l.Vector3(n.getX(t+1),0,n.getZ(t+1)));o&&this._writeLine(e,o.start.x,o.start.z,o.end.x,o.end.z,s,i,r)}}_writePairsAsLines(e,t,s,i=7,r){for(let n=0;n+5<t.length;n+=6){const o=this._clipSegment(new l.Vector3(t[n],0,t[n+2]),new l.Vector3(t[n+3],0,t[n+5]));o&&this._writeLine(e,o.start.x,o.start.z,o.end.x,o.end.z,s,i,r)}}_emitTrueColor(e,t){this.config.trueColor&&void 0!==t&&e.p(420,t)}_writeLine(e,t,s,i,r,n,o,a){e.p(0,"LINE").p(5,e.handle()).p(8,n).p(62,o),this._emitTrueColor(e,a),e.n(10,this._tx(t)).n(20,this._ty(s)).n(30,0).n(11,this._tx(i)).n(21,this._ty(r)).n(31,0)}_writeRawLine(e,t,s,i,r,n,o){e.p(0,"LINE").p(5,e.handle()).p(8,n).p(62,o).n(10,t).n(20,s).n(30,0).n(11,i).n(21,r).n(31,0)}_writeSolid(e,t,s,i,r,n,o,a,l,h){e.p(0,"SOLID").p(5,e.handle()).p(8,a).p(62,l),this._emitTrueColor(e,h),e.n(10,this._tx(t)).n(20,this._ty(s)).n(30,0).n(11,this._tx(i)).n(21,this._ty(r)).n(31,0).n(12,this._tx(n)).n(22,this._ty(o)).n(32,0).n(13,this._tx(n)).n(23,this._ty(o)).n(33,0)}_writeMeshTriangles(e,t,s,i,r){for(let n=0;n+8<t.length;n+=9)this._writeSolid(e,t[n],t[n+2],t[n+3],t[n+5],t[n+6],t[n+8],s,i,r)}_writeText(e,t,s,i,r,n,o,a=0,l=0,h=0,u){const c=this._tx(s),d=this._ty(i);e.p(0,"TEXT").p(5,e.handle()).p(8,n).p(62,o),this._emitTrueColor(e,u),e.n(10,c).n(20,d).n(30,0).n(40,r*this._scale()).n(50,a).p(1,t),0===l&&0===h||(0!==l&&e.p(72,l),0!==h&&e.p(73,h),e.n(11,c).n(21,d).n(31,0))}_tx(e){return this._paperSlot?this._paperSlot.x+(e-this._paperSlot.vpLeft)*this._paperSlot.mmPerUnit:this._viewport?e-this._viewport.left:e}_ty(e){return this._paperSlot?this._paperSlot.y-(e+this._paperSlot.vpTop)*this._paperSlot.mmPerUnit:this._viewport?-e-this._viewport.bottom:-e}_scale(){return this._paperSlot?this._paperSlot.mmPerUnit:1}_clipSegment(e,t){return this._viewport?this._viewport.clipLine(new l.Line3(e,t)):new l.Line3(e,t)}_inViewport(e,t){return!this._viewport||this._viewport.bbox.containsPoint(new l.Vector3(e,0,t))}_bboxFromPositions(e){const t=new l.Box3;for(let s=0;s+2<e.length;s+=3)t.expandByPoint(new l.Vector3(e[s],0,e[s+2]));return t}_fullyInViewport(e){return!this._viewport||this._viewport.bbox.containsBox(e)}_textAngle(e,t){let s=Math.atan2(-t,e);return(s>Math.PI/2||s<=-Math.PI/2)&&(s+=Math.PI),l.MathUtils.radToDeg(s)}_writeCustomSystems(e,t){if(0===this._systemExporters.size)return;const s=this._makeContext(e);for(const[e,t]of this._systemExporters){const i=this._components.get(sk).systems.get(e);i&&t(i,s)}}_makeContext(e){return{writeLine:(t,s,i,r,n="0",o=7)=>{this._writeLine(e,t,s,i,r,n,o)},writePairs:(t,s="0",i=7)=>{this._writePairsAsLines(e,t,s,i)},writeMeshTriangles:(t,s="0",i=7)=>{this._writeMeshTriangles(e,t,s,i)},writeText:(t,s,i,r,n={})=>{this._writeText(e,t,s,i,r,n.layer??"0",n.aciColor??7,n.rotDeg??0,n.hAlign??0)},hexToAci:rk,textAngle:(e,t)=>this._textAngle(e,t)}}}const ak=class e extends d{constructor(s){super(s),t(this,"enabled",!0),t(this,"exporter",new ok(this.components)),s.add(e.uuid,this)}};t(ak,"uuid","e9a2c3d4-5f67-4b89-a012-1c3d5e7f9b2a");let lk=ak;exports.AngleAnnotations=Lz,exports.AnnotationSystem=yz,exports.ArrowTick=(e,t,s)=>{const i=new l.Vector3(-t.z,0,t.x),r=e.x-t.x*s+i.x*s*.4,n=e.z-t.z*s+i.z*s*.4,o=e.x-t.x*s-i.x*s*.4,a=e.z-t.z*s-i.z*s*.4;return[e.x,e.y,e.z,r,e.y,n,e.x,e.y,e.z,o,e.y,a,r,e.y,n,o,e.y,a]},exports.AsyncEvent=class{constructor(){t(this,"enabled",!0),t(this,"trigger",async e=>{if(!this.enabled)return;const t=this.handlers.slice(0);for(const s of t)await s(e)}),t(this,"handlers",[])}add(e){this.handlers.push(e)}remove(e){this.handlers=this.handlers.filter(t=>t!==e)}reset(){this.handlers.length=0}},exports.BCFTopics=$O,exports.BCFTopicsConfigManager=GO,exports.Base=c,exports.BaseCamera=m,exports.BaseRenderer=f,exports.BaseScene=x,exports.BaseWorldItem=p,exports.BlockAnnotations=Gz,exports.BoundingBoxer=tO,exports.CalloutAnnotations=ek,exports.CircleEnclosure=Jz,exports.Classifier=oO,exports.Clipper=NV,exports.CloudEnclosure=Qz,exports.Comment=VO,exports.Component=d,exports.Components=NO,exports.ConfigManager=Ge,exports.Configurator=ke,exports.ControlsUtils=ze,exports.DataMap=Ve,exports.DataSet=b,exports.DiagonalTick=iz,exports.Disposer=y,exports.DotTick=(e,t,s)=>{const i=.4*s,r=[];for(let t=0;t<12;t++){const s=t/12*Math.PI*2,n=(t+1)/12*Math.PI*2;r.push(e.x+Math.cos(s)*i,e.y,e.z+Math.sin(s)*i,e.x+Math.cos(n)*i,e.y,e.z+Math.sin(n)*i)}return r},exports.DrawingAnnotations=az,exports.DrawingLayers=lz,exports.DrawingSystem=yz,exports.DrawingViewport=cz,exports.DrawingViewportHelper=uz,exports.DrawingViewports=dz,exports.DxfExporter=ok,exports.DxfManager=lk,exports.EdgeProjector=XF,exports.Event=u,exports.EventManager=class{constructor(){t(this,"list",new Set)}add(e){for(const t of e)this.list.add(t)}remove(e){for(const t of e)this.list.delete(t)}set(e){for(const t of this.list)t.enabled=e}reset(){for(const e of this.list)e.reset()}},exports.FastModelPicker=aO,exports.FastModelPickers=hO,exports.FilledArrowTick=oz,exports.FilledCircleTick=(e,t,s)=>{const i=.4*s,r=[];for(let t=0;t<16;t++){const s=t/16*Math.PI*2,n=(t+1)/16*Math.PI*2;r.push(e.x,e.y,e.z,e.x+Math.cos(s)*i,e.y,e.z+Math.sin(s)*i,e.x+Math.cos(n)*i,e.y,e.z+Math.sin(n)*i)}return r},exports.FilledSquareTick=(e,t,s)=>{const i=new l.Vector3(-t.z,0,t.x),r=.4*s,n=e.clone().addScaledVector(t,r).addScaledVector(i,r),o=e.clone().addScaledVector(t,r).addScaledVector(i,-r),a=e.clone().addScaledVector(t,-r).addScaledVector(i,-r),h=e.clone().addScaledVector(t,-r).addScaledVector(i,r);return[n.x,n.y,n.z,o.x,o.y,o.z,a.x,a.y,a.z,n.x,n.y,n.z,a.x,a.y,a.z,h.x,h.y,h.z]},exports.FinderQuery=sO,exports.FirstPersonMode=EO,exports.FragmentsManager=ji,exports.Grids=MO,exports.Hider=JF,exports.IDSAttribute=zV,exports.IDSClassification=kV,exports.IDSEntity=UV,exports.IDSFacet=OV,exports.IDSMaterial=jV,exports.IDSPartOf=$V,exports.IDSProperty=GV,exports.IDSSpecification=WV,exports.IDSSpecifications=ez,exports.IfcFragmentSettings=YF,exports.IfcLoader=QF,exports.ItemsFinder=rO,exports.LeaderAnnotations=Uz,exports.LinearAnnotations=Sz,exports.MeasurementUtils=sz,exports.ModelIdMapUtils=Oe,exports.Mouse=je,exports.NoTick=nz,exports.OpenArrowTick=rz,exports.OrbitMode=CO,exports.OrthoPerspectiveCamera=BO,exports.PlanMode=RO,exports.ProjectionManager=PO,exports.Raycasters=dO,exports.RectEnclosure=Kz,exports.RendererMode=xO,exports.ShadowedScene=class extends yO{constructor(){super(...arguments),t(this,"_distanceRenderer"),t(this,"autoBias",!0),t(this,"_defaultShadowConfig",{cascade:1,resolution:512}),t(this,"_lightsWithShadow",new Map),t(this,"_isComputingShadows",!1),t(this,"_shadowsEnabled",!0),t(this,"_bias",0),t(this,"recomputeShadows",e=>{if(!this._shadowsEnabled)return;this.autoBias&&(this.bias=-.005);if(e*=1.5,!this.currentWorld)throw new Error("A world needs to be assigned to the scene before computing shadows!");if(!this._lightsWithShadow.size)throw new Error("No shadows found!");const t=this.currentWorld.camera.three;if(!(t instanceof l.PerspectiveCamera||t instanceof l.OrthographicCamera))throw new Error("Invalid camera type!");const s=new l.Vector3;t.getWorldDirection(s);let i=e;const r=new l.Vector3;r.copy(this.config.directionalLight.position),r.normalize();for(const[e,n]of this._lightsWithShadow){const o=this.directionalLights.get(n);if(!o)throw new Error("Light not found.");const a=new l.Vector3;a.copy(s);const h=e===this._lightsWithShadow.size-1,u=h?i/2:2*i/3;a.multiplyScalar(u),a.add(t.position);const c=i-u,d=new l.Vector3;d.copy(r),d.multiplyScalar(c),o.target.position.copy(a),o.position.copy(a),o.position.add(d),o.shadow.camera.right=c,o.shadow.camera.left=-c,o.shadow.camera.top=c,o.shadow.camera.bottom=-c,o.shadow.camera.far=2*c,o.shadow.camera.updateProjectionMatrix(),o.shadow.camera.updateMatrix(),h||(i/=3)}this._isComputingShadows=!1})}get bias(){return this._bias}set bias(e){this._bias=e;for(const[,t]of this._lightsWithShadow){const s=this.directionalLights.get(t);s&&(s.shadow.bias=e)}}get shadowsEnabled(){return this._shadowsEnabled}set shadowsEnabled(e){this._shadowsEnabled=e;for(const[,t]of this.directionalLights)t.castShadow=e}get distanceRenderer(){if(!this._distanceRenderer)throw new Error("You must set up this component before accessing the distance renderer!");return this._distanceRenderer}setup(e){super.setup(e);const t={...this._defaultConfig,...this._defaultShadowConfig,...e};if(t.cascade<=0)throw new Error("Config.shadows.cascade must be a natural number greater than 0!");if(t.cascade>1)throw new Error("Multiple shadows not supported yet!");if(!this.currentWorld)throw new Error("A world needs to be assigned to the scene before setting it up!");for(const[,e]of this.directionalLights)e.target.removeFromParent(),e.removeFromParent(),e.dispose();this.directionalLights.clear(),this._distanceRenderer||(this._distanceRenderer=new FV(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let e=0;e<t.cascade;e++){const s=new l.DirectionalLight;s.intensity=this.config.directionalLight.intensity,s.color=this.config.directionalLight.color,s.position.copy(this.config.directionalLight.position),s.shadow.mapSize.width=t.resolution,s.shadow.mapSize.height=t.resolution,this.three.add(s,s.target),this.directionalLights.set(s.uuid,s),this._lightsWithShadow.set(e,s.uuid),s.castShadow=!0,s.shadow.bias=this._bias}}dispose(){super.dispose(),this._distanceRenderer&&this._distanceRenderer.dispose(),this._lightsWithShadow.clear()}async updateShadows(){!this._isComputingShadows&&this._shadowsEnabled&&(this._isComputingShadows=!0,await this.distanceRenderer.compute())}},exports.SimpleCamera=bO,exports.SimpleGrid=TO,exports.SimpleGridConfigManager=vO,exports.SimplePlane=SV,exports.SimpleRaycaster=uO,exports.SimpleRenderer=class extends f{constructor(e,s,i){super(e),t(this,"enabled",!0),t(this,"container"),t(this,"three"),t(this,"mode",1),t(this,"needsUpdate",!1),t(this,"_canvas"),t(this,"_parameters"),t(this,"_resizeObserver",null),t(this,"onContainerUpdated",new u),t(this,"_resizing",!1),t(this,"resize",e=>{if(this._resizing)return;this._resizing=!0,this.onContainerUpdated.trigger();const t=e?e.x:this.container.clientWidth,s=e?e.y:this.container.clientHeight;this.three.setSize(t,s),this.onResize.trigger(new l.Vector2(t,s)),this._resizing=!1}),t(this,"resizeEvent",()=>{this.resize()}),t(this,"onContextLost",e=>{e.preventDefault(),this.enabled=!1}),t(this,"onContextBack",()=>{this.three.setRenderTarget(null),this.three.dispose(),this.three=new l.WebGLRenderer({canvas:this._canvas,antialias:!0,alpha:!0,...this._parameters}),this.enabled=!0}),this.container=s,this._parameters=i,this.three=new l.WebGLRenderer({antialias:!0,alpha:!0,...i}),this.three.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.setupRenderer(),this.setupEvents(!0),this.resize(),this._canvas=this.three.domElement;const r=this.three.getContext(),{canvas:n}=r;n.addEventListener("webglcontextlost",this.onContextLost,!1),n.addEventListener("webglcontextrestored",this.onContextBack,!1)}update(){if(!this.enabled||!this.currentWorld)return;if(0===this.mode&&!this.needsUpdate)return;this.needsUpdate=!1,this.onBeforeUpdate.trigger(this);const e=this.currentWorld.scene.three,t=this.currentWorld.camera.three;this.three.render(e,t),this.onAfterUpdate.trigger(this)}dispose(){this.enabled=!1,this.setupEvents(!1),this.three.domElement.remove(),this.three.forceContextLoss(),this.three.dispose(),this.onResize.reset(),this.onAfterUpdate.reset(),this.onBeforeUpdate.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}getSize(){return new l.Vector2(this.three.domElement.clientWidth,this.three.domElement.clientHeight)}setupEvents(e){const t=this.three.domElement.parentElement;if(!t)throw new Error("This renderer needs to have an HTML container!");this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),window.removeEventListener("resize",this.resizeEvent),e&&(this._resizeObserver=new ResizeObserver(this.resizeEvent),this._resizeObserver.observe(t),window.addEventListener("resize",this.resizeEvent))}setupRenderer(){this.three.localClippingEnabled=!0,this.container&&this.container.appendChild(this.three.domElement),this.onContainerUpdated.trigger()}},exports.SimpleScene=yO,exports.SimpleSceneConfigManager=gO,exports.SimpleWorld=pO,exports.SlopeAnnotations=Hz,exports.TechnicalDrawing=gz,exports.TechnicalDrawingHelper=mz,exports.TechnicalDrawings=sk,exports.Topic=kO,exports.UUID=w,exports.Units={m:{factor:1,suffix:"m"},cm:{factor:100,suffix:"cm"},mm:{factor:1e3,suffix:"mm"},ft:{factor:3.28084,suffix:"ft"},in:{factor:39.3701,suffix:"in"}},exports.VertexPicker=class extends d{constructor(e,s){super(e),t(this,"onDisposed",new u),t(this,"onVertexFound",new u),t(this,"onVertexLost",new u),t(this,"onEnabled",new u),t(this,"components"),t(this,"workingPlane",null),t(this,"_pickedPoint",null),t(this,"_config"),t(this,"_enabled",!1),this.components=e,this.config={snapDistance:.25,showOnlyVertex:!1,...s},this.enabled=!1}set enabled(e){this._enabled=e,e||(this._pickedPoint=null),this.onEnabled.trigger(e)}get enabled(){return this._enabled}set config(e){this._config={...this._config,...e}}get config(){return this._config}dispose(){this.onVertexFound.reset(),this.onVertexLost.reset(),this.components=null,this.onDisposed.trigger(),this.onDisposed.reset()}async get(e){if(!this.enabled)return this._pickedPoint;const t=this.components.get(dO).get(e),s=await t.castRay();if(!s)return null!==this._pickedPoint&&(this.onVertexLost.trigger(),this._pickedPoint=null),this._pickedPoint;const i=s.point;return null!==this._pickedPoint&&this._pickedPoint.equals(i)||(this._pickedPoint=i.clone(),this.onVertexFound.trigger(this._pickedPoint)),this._pickedPoint}},exports.View=BV,exports.Viewpoint=EV,exports.Viewpoints=PV,exports.Views=DV,exports.Worlds=wO,exports.XML=Fe,exports.angleDimensionMachine=Ez,exports.buildAnglePositions=Iz,exports.buildAnglePreviewPositions=Dz,exports.buildCalloutPositions=Yz,exports.buildCalloutPreviewPositions=Zz,exports.buildDimensionPositions=vz,exports.buildDimensions=bz,exports.buildLeaderPositions=zz,exports.buildLeaderPreviewPositions=kz,exports.buildPreviewPositions=Tz,exports.buildSlopePositions=jz,exports.calloutAnnotationMachine=Xz,exports.computeAlignmentMatrix=fz,exports.computeAngle=Rz,exports.computeBisectorAngle=Pz,exports.computeOffset=xz,exports.extensionsImporter=UO,exports.formatSlope=Wz,exports.getAngleTickEndpoints=Cz,exports.getDimensionTickEndpoints=wz,exports.getSlopeTip=$z,exports.leaderAnnotationMachine=Oz,exports.linearDimensionMachine=_z;
12
+ */const Jr=Xr(Qr.exports=function e(t,i,n){function s(o,a){if(!i[o]){if(!t[o]){if(!a&&Kr)return Kr(o);if(r)return r(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var c=i[o]={exports:{}};t[o][0].call(c.exports,function(e){return s(t[o][1][e]||e)},c,c.exports,e,t,i,n)}return i[o].exports}for(var r=Kr,o=0;o<n.length;o++)s(n[o]);return s}({1:[function(e,t,i){var n=e("./utils"),s=e("./support"),r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(e){for(var t,i,s,o,a,l,c,h=[],d=0,u=e.length,p=u,f="string"!==n.getTypeOf(e);d<e.length;)p=u-d,s=f?(t=e[d++],i=d<u?e[d++]:0,d<u?e[d++]:0):(t=e.charCodeAt(d++),i=d<u?e.charCodeAt(d++):0,d<u?e.charCodeAt(d++):0),o=t>>2,a=(3&t)<<4|i>>4,l=1<p?(15&i)<<2|s>>6:64,c=2<p?63&s:64,h.push(r.charAt(o)+r.charAt(a)+r.charAt(l)+r.charAt(c));return h.join("")},i.decode=function(e){var t,i,n,o,a,l,c=0,h=0,d="data:";if(e.substr(0,d.length)===d)throw new Error("Invalid base64 input, it looks like a data url.");var u,p=3*(e=e.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(e.charAt(e.length-1)===r.charAt(64)&&p--,e.charAt(e.length-2)===r.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(u=s.uint8array?new Uint8Array(0|p):new Array(0|p);c<e.length;)t=r.indexOf(e.charAt(c++))<<2|(o=r.indexOf(e.charAt(c++)))>>4,i=(15&o)<<4|(a=r.indexOf(e.charAt(c++)))>>2,n=(3&a)<<6|(l=r.indexOf(e.charAt(c++))),u[h++]=t,64!==a&&(u[h++]=i),64!==l&&(u[h++]=n);return u}},{"./support":30,"./utils":32}],2:[function(e,t,i){var n=e("./external"),s=e("./stream/DataWorker"),r=e("./stream/Crc32Probe"),o=e("./stream/DataLengthProbe");function a(e,t,i,n,s){this.compressedSize=e,this.uncompressedSize=t,this.crc32=i,this.compression=n,this.compressedContent=s}a.prototype={getContentWorker:function(){var e=new s(n.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o("data_length")),t=this;return e.on("end",function(){if(this.streamInfo.data_length!==t.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),e},getCompressedWorker:function(){return new s(n.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(e,t,i){return e.pipe(new r).pipe(new o("uncompressedSize")).pipe(t.compressWorker(i)).pipe(new o("compressedSize")).withStreamInfo("compression",t)},t.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(e,t,i){var n=e("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new n("STORE compression")},uncompressWorker:function(){return new n("STORE decompression")}},i.DEFLATE=e("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(e,t,i){var n=e("./utils"),s=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t){return void 0!==e&&e.length?"string"!==n.getTypeOf(e)?function(e,t,i,n){var r=s,o=n+i;e^=-1;for(var a=n;a<o;a++)e=e>>>8^r[255&(e^t[a])];return-1^e}(0|t,e,e.length,0):function(e,t,i,n){var r=s,o=n+i;e^=-1;for(var a=n;a<o;a++)e=e>>>8^r[255&(e^t.charCodeAt(a))];return-1^e}(0|t,e,e.length,0):0}},{"./utils":32}],5:[function(e,t,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(e,t,i){var n=null;n="undefined"!=typeof Promise?Promise:e("lie"),t.exports={Promise:n}},{lie:37}],7:[function(e,t,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,s=e("pako"),r=e("./utils"),o=e("./stream/GenericWorker"),a=n?"uint8array":"array";function l(e,t){o.call(this,"FlateWorker/"+e),this._pako=null,this._pakoAction=e,this._pakoOptions=t,this.meta={}}i.magic="\b\0",r.inherits(l,o),l.prototype.processChunk=function(e){this.meta=e.meta,null===this._pako&&this._createPako(),this._pako.push(r.transformTo(a,e.data),!1)},l.prototype.flush=function(){o.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},l.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this._pako=null},l.prototype._createPako=function(){this._pako=new s[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var e=this;this._pako.onData=function(t){e.push({data:t,meta:e.meta})}},i.compressWorker=function(e){return new l("Deflate",e)},i.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(e,t,i){function n(e,t){var i,n="";for(i=0;i<t;i++)n+=String.fromCharCode(255&e),e>>>=8;return n}function s(e,t,i,s,o,h){var d,u,p=e.file,f=e.compression,m=h!==a.utf8encode,g=r.transformTo("string",h(p.name)),w=r.transformTo("string",a.utf8encode(p.name)),y=p.comment,_=r.transformTo("string",h(y)),b=r.transformTo("string",a.utf8encode(y)),v=w.length!==p.name.length,x=b.length!==y.length,S="",C="",T="",A=p.dir,E=p.date,M={crc32:0,compressedSize:0,uncompressedSize:0};t&&!i||(M.crc32=e.crc32,M.compressedSize=e.compressedSize,M.uncompressedSize=e.uncompressedSize);var P=0;t&&(P|=8),m||!v&&!x||(P|=2048);var I,z,D,k=0,B=0;A&&(k|=16),"UNIX"===o?(B=798,k|=(I=p.unixPermissions,z=A,D=I,I||(D=z?16893:33204),(65535&D)<<16)):(B=20,k|=function(e){return 63&(e||0)}(p.dosPermissions)),d=E.getUTCHours(),d<<=6,d|=E.getUTCMinutes(),d<<=5,d|=E.getUTCSeconds()/2,u=E.getUTCFullYear()-1980,u<<=4,u|=E.getUTCMonth()+1,u<<=5,u|=E.getUTCDate(),v&&(C=n(1,1)+n(l(g),4)+w,S+="up"+n(C.length,2)+C),x&&(T=n(1,1)+n(l(_),4)+b,S+="uc"+n(T.length,2)+T);var O="";return O+="\n\0",O+=n(P,2),O+=f.magic,O+=n(d,2),O+=n(u,2),O+=n(M.crc32,4),O+=n(M.compressedSize,4),O+=n(M.uncompressedSize,4),O+=n(g.length,2),O+=n(S.length,2),{fileRecord:c.LOCAL_FILE_HEADER+O+g+S,dirRecord:c.CENTRAL_FILE_HEADER+n(B,2)+O+n(_.length,2)+"\0\0\0\0"+n(k,4)+n(s,4)+g+S+_}}var r=e("../utils"),o=e("../stream/GenericWorker"),a=e("../utf8"),l=e("../crc32"),c=e("../signature");function h(e,t,i,n){o.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=t,this.zipPlatform=i,this.encodeFileName=n,this.streamFiles=e,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}r.inherits(h,o),h.prototype.push=function(e){var t=e.meta.percent||0,i=this.entriesCount,n=this._sources.length;this.accumulate?this.contentBuffer.push(e):(this.bytesWritten+=e.data.length,o.prototype.push.call(this,{data:e.data,meta:{currentFile:this.currentFile,percent:i?(t+100*(i-n-1))/i:100}}))},h.prototype.openedSource=function(e){this.currentSourceOffset=this.bytesWritten,this.currentFile=e.file.name;var t=this.streamFiles&&!e.file.dir;if(t){var i=s(e,t,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0},h.prototype.closedSource=function(e){this.accumulate=!1;var t,i=this.streamFiles&&!e.file.dir,r=s(e,i,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),i)this.push({data:(t=e,c.DATA_DESCRIPTOR+n(t.crc32,4)+n(t.compressedSize,4)+n(t.uncompressedSize,4)),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},h.prototype.flush=function(){for(var e=this.bytesWritten,t=0;t<this.dirRecords.length;t++)this.push({data:this.dirRecords[t],meta:{percent:100}});var i,s,o,a,l,h,d=this.bytesWritten-e,u=(i=this.dirRecords.length,s=d,o=e,a=this.zipComment,l=this.encodeFileName,h=r.transformTo("string",l(a)),c.CENTRAL_DIRECTORY_END+"\0\0\0\0"+n(i,2)+n(i,2)+n(s,4)+n(o,4)+n(h.length,2)+h);this.push({data:u,meta:{percent:100}})},h.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},h.prototype.registerPrevious=function(e){this._sources.push(e);var t=this;return e.on("data",function(e){t.processChunk(e)}),e.on("end",function(){t.closedSource(t.previous.streamInfo),t._sources.length?t.prepareNextSource():t.end()}),e.on("error",function(e){t.error(e)}),this},h.prototype.resume=function(){return!!o.prototype.resume.call(this)&&(!this.previous&&this._sources.length?(this.prepareNextSource(),!0):this.previous||this._sources.length||this.generatedError?void 0:(this.end(),!0))},h.prototype.error=function(e){var t=this._sources;if(!o.prototype.error.call(this,e))return!1;for(var i=0;i<t.length;i++)try{t[i].error(e)}catch(e){}return!0},h.prototype.lock=function(){o.prototype.lock.call(this);for(var e=this._sources,t=0;t<e.length;t++)e[t].lock()},t.exports=h},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(e,t,i){var n=e("../compressions"),s=e("./ZipFileWorker");i.generateWorker=function(e,t,i){var r=new s(t.streamFiles,i,t.platform,t.encodeFileName),o=0;try{e.forEach(function(e,i){o++;var s=function(e,t){var i=e||t,s=n[i];if(!s)throw new Error(i+" is not a valid compression method !");return s}(i.options.compression,t.compression),a=i.options.compressionOptions||t.compressionOptions||{},l=i.dir,c=i.date;i._compressWorker(s,a).withStreamInfo("file",{name:e,dir:l,date:c,comment:i.comment||"",unixPermissions:i.unixPermissions,dosPermissions:i.dosPermissions}).pipe(r)}),r.entriesCount=o}catch(e){r.error(e)}return r}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(e,t,i){function n(){if(!(this instanceof n))return new n;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var e=new n;for(var t in this)"function"!=typeof this[t]&&(e[t]=this[t]);return e}}(n.prototype=e("./object")).loadAsync=e("./load"),n.support=e("./support"),n.defaults=e("./defaults"),n.version="3.10.1",n.loadAsync=function(e,t){return(new n).loadAsync(e,t)},n.external=e("./external"),t.exports=n},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(e,t,i){var n=e("./utils"),s=e("./external"),r=e("./utf8"),o=e("./zipEntries"),a=e("./stream/Crc32Probe"),l=e("./nodejsUtils");function c(e){return new s.Promise(function(t,i){var n=e.decompressed.getContentWorker().pipe(new a);n.on("error",function(e){i(e)}).on("end",function(){n.streamInfo.crc32!==e.decompressed.crc32?i(new Error("Corrupted zip : CRC32 mismatch")):t()}).resume()})}t.exports=function(e,t){var i=this;return t=n.extend(t||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:r.utf8decode}),l.isNode&&l.isStream(e)?s.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):n.prepareContent("the loaded zip file",e,!0,t.optimizedBinaryString,t.base64).then(function(e){var i=new o(t);return i.load(e),i}).then(function(e){var i=[s.Promise.resolve(e)],n=e.files;if(t.checkCRC32)for(var r=0;r<n.length;r++)i.push(c(n[r]));return s.Promise.all(i)}).then(function(e){for(var s=e.shift(),r=s.files,o=0;o<r.length;o++){var a=r[o],l=a.fileNameStr,c=n.resolve(a.fileNameStr);i.file(c,a.decompressed,{binary:!0,optimizedBinaryString:!0,date:a.date,dir:a.dir,comment:a.fileCommentStr.length?a.fileCommentStr:null,unixPermissions:a.unixPermissions,dosPermissions:a.dosPermissions,createFolders:t.createFolders}),a.dir||(i.file(c).unsafeOriginalName=l)}return s.zipComment.length&&(i.comment=s.zipComment),i})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(e,t,i){var n=e("../utils"),s=e("../stream/GenericWorker");function r(e,t){s.call(this,"Nodejs stream input adapter for "+e),this._upstreamEnded=!1,this._bindStream(t)}n.inherits(r,s),r.prototype._bindStream=function(e){var t=this;(this._stream=e).pause(),e.on("data",function(e){t.push({data:e,meta:{percent:0}})}).on("error",function(e){t.isPaused?this.generatedError=e:t.error(e)}).on("end",function(){t.isPaused?t._upstreamEnded=!0:t.end()})},r.prototype.pause=function(){return!!s.prototype.pause.call(this)&&(this._stream.pause(),!0)},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},t.exports=r},{"../stream/GenericWorker":28,"../utils":32}],13:[function(e,t,i){var n=e("readable-stream").Readable;function s(e,t,i){n.call(this,t),this._helper=e;var s=this;e.on("data",function(e,t){s.push(e)||s._helper.pause(),i&&i(t)}).on("error",function(e){s.emit("error",e)}).on("end",function(){s.push(null)})}e("../utils").inherits(s,n),s.prototype._read=function(){this._helper.resume()},t.exports=s},{"../utils":32,"readable-stream":16}],14:[function(e,t,i){t.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(e,t){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(e,t);if("number"==typeof e)throw new Error('The "data" argument must not be a number');return new Buffer(e,t)},allocBuffer:function(e){if(Buffer.alloc)return Buffer.alloc(e);var t=new Buffer(e);return t.fill(0),t},isBuffer:function(e){return Buffer.isBuffer(e)},isStream:function(e){return e&&"function"==typeof e.on&&"function"==typeof e.pause&&"function"==typeof e.resume}}},{}],15:[function(e,t,i){function n(e,t,i){var n,s=r.getTypeOf(t),a=r.extend(i||{},l);a.date=a.date||new Date,null!==a.compression&&(a.compression=a.compression.toUpperCase()),"string"==typeof a.unixPermissions&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&16384&a.unixPermissions&&(a.dir=!0),a.dosPermissions&&16&a.dosPermissions&&(a.dir=!0),a.dir&&(e=m(e)),a.createFolders&&(n=f(e))&&g.call(this,n,!0);var d="string"===s&&!1===a.binary&&!1===a.base64;i&&void 0!==i.binary||(a.binary=!d),(t instanceof c&&0===t.uncompressedSize||a.dir||!t||0===t.length)&&(a.base64=!1,a.binary=!0,t="",a.compression="STORE",s="string");var w=null;w=t instanceof c||t instanceof o?t:u.isNode&&u.isStream(t)?new p(e,t):r.prepareContent(e,t,a.binary,a.optimizedBinaryString,a.base64);var y=new h(e,w,a);this.files[e]=y}var s=e("./utf8"),r=e("./utils"),o=e("./stream/GenericWorker"),a=e("./stream/StreamHelper"),l=e("./defaults"),c=e("./compressedObject"),h=e("./zipObject"),d=e("./generate"),u=e("./nodejsUtils"),p=e("./nodejs/NodejsStreamInputAdapter"),f=function(e){"/"===e.slice(-1)&&(e=e.substring(0,e.length-1));var t=e.lastIndexOf("/");return 0<t?e.substring(0,t):""},m=function(e){return"/"!==e.slice(-1)&&(e+="/"),e},g=function(e,t){return t=void 0!==t?t:l.createFolders,e=m(e),this.files[e]||n.call(this,e,null,{dir:!0,createFolders:t}),this.files[e]};function w(e){return"[object RegExp]"===Object.prototype.toString.call(e)}var y={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(e){var t,i,n;for(t in this.files)n=this.files[t],(i=t.slice(this.root.length,t.length))&&t.slice(0,this.root.length)===this.root&&e(i,n)},filter:function(e){var t=[];return this.forEach(function(i,n){e(i,n)&&t.push(n)}),t},file:function(e,t,i){if(1!==arguments.length)return e=this.root+e,n.call(this,e,t,i),this;if(w(e)){var s=e;return this.filter(function(e,t){return!t.dir&&s.test(e)})}var r=this.files[this.root+e];return r&&!r.dir?r:null},folder:function(e){if(!e)return this;if(w(e))return this.filter(function(t,i){return i.dir&&e.test(t)});var t=this.root+e,i=g.call(this,t),n=this.clone();return n.root=i.name,n},remove:function(e){e=this.root+e;var t=this.files[e];if(t||("/"!==e.slice(-1)&&(e+="/"),t=this.files[e]),t&&!t.dir)delete this.files[e];else for(var i=this.filter(function(t,i){return i.name.slice(0,e.length)===e}),n=0;n<i.length;n++)delete this.files[i[n].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(e){var t,i={};try{if((i=r.extend(e||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:s.utf8encode})).type=i.type.toLowerCase(),i.compression=i.compression.toUpperCase(),"binarystring"===i.type&&(i.type="string"),!i.type)throw new Error("No output type specified.");r.checkSupport(i.type),"darwin"!==i.platform&&"freebsd"!==i.platform&&"linux"!==i.platform&&"sunos"!==i.platform||(i.platform="UNIX"),"win32"===i.platform&&(i.platform="DOS");var n=i.comment||this.comment||"";t=d.generateWorker(this,i,n)}catch(e){(t=new o("error")).error(e)}return new a(t,i.type||"string",i.mimeType)},generateAsync:function(e,t){return this.generateInternalStream(e).accumulate(t)},generateNodeStream:function(e,t){return(e=e||{}).type||(e.type="nodebuffer"),this.generateInternalStream(e).toNodejsStream(t)}};t.exports=y},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(e,t,i){t.exports=e("stream")},{stream:void 0}],17:[function(e,t,i){var n=e("./DataReader");function s(e){n.call(this,e);for(var t=0;t<this.data.length;t++)e[t]=255&e[t]}e("../utils").inherits(s,n),s.prototype.byteAt=function(e){return this.data[this.zero+e]},s.prototype.lastIndexOfSignature=function(e){for(var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),s=e.charCodeAt(3),r=this.length-4;0<=r;--r)if(this.data[r]===t&&this.data[r+1]===i&&this.data[r+2]===n&&this.data[r+3]===s)return r-this.zero;return-1},s.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),i=e.charCodeAt(1),n=e.charCodeAt(2),s=e.charCodeAt(3),r=this.readData(4);return t===r[0]&&i===r[1]&&n===r[2]&&s===r[3]},s.prototype.readData=function(e){if(this.checkOffset(e),0===e)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./DataReader":18}],18:[function(e,t,i){var n=e("../utils");function s(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}s.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length<this.zero+e||e<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+e+"). Corrupted zip ?")},setIndex:function(e){this.checkIndex(e),this.index=e},skip:function(e){this.setIndex(this.index+e)},byteAt:function(){},readInt:function(e){var t,i=0;for(this.checkOffset(e),t=this.index+e-1;t>=this.index;t--)i=(i<<8)+this.byteAt(t);return this.index+=e,i},readString:function(e){return n.transformTo("string",this.readData(e))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},t.exports=s},{"../utils":32}],19:[function(e,t,i){var n=e("./Uint8ArrayReader");function s(e){n.call(this,e)}e("../utils").inherits(s,n),s.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(e,t,i){var n=e("./DataReader");function s(e){n.call(this,e)}e("../utils").inherits(s,n),s.prototype.byteAt=function(e){return this.data.charCodeAt(this.zero+e)},s.prototype.lastIndexOfSignature=function(e){return this.data.lastIndexOf(e)-this.zero},s.prototype.readAndCheckSignature=function(e){return e===this.readData(4)},s.prototype.readData=function(e){this.checkOffset(e);var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./DataReader":18}],21:[function(e,t,i){var n=e("./ArrayReader");function s(e){n.call(this,e)}e("../utils").inherits(s,n),s.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},t.exports=s},{"../utils":32,"./ArrayReader":17}],22:[function(e,t,i){var n=e("../utils"),s=e("../support"),r=e("./ArrayReader"),o=e("./StringReader"),a=e("./NodeBufferReader"),l=e("./Uint8ArrayReader");t.exports=function(e){var t=n.getTypeOf(e);return n.checkSupport(t),"string"!==t||s.uint8array?"nodebuffer"===t?new a(e):s.uint8array?new l(n.transformTo("uint8array",e)):new r(n.transformTo("array",e)):new o(e)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(e,t,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\b"},{}],24:[function(e,t,i){var n=e("./GenericWorker"),s=e("../utils");function r(e){n.call(this,"ConvertWorker to "+e),this.destType=e}s.inherits(r,n),r.prototype.processChunk=function(e){this.push({data:s.transformTo(this.destType,e.data),meta:e.meta})},t.exports=r},{"../utils":32,"./GenericWorker":28}],25:[function(e,t,i){var n=e("./GenericWorker"),s=e("../crc32");function r(){n.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}e("../utils").inherits(r,n),r.prototype.processChunk=function(e){this.streamInfo.crc32=s(e.data,this.streamInfo.crc32||0),this.push(e)},t.exports=r},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(e,t,i){var n=e("../utils"),s=e("./GenericWorker");function r(e){s.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}n.inherits(r,s),r.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}s.prototype.processChunk.call(this,e)},t.exports=r},{"../utils":32,"./GenericWorker":28}],27:[function(e,t,i){var n=e("../utils"),s=e("./GenericWorker");function r(e){s.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=n.getTypeOf(e),t.isPaused||t._tickAndRepeat()},function(e){t.error(e)})}n.inherits(r,s),r.prototype.cleanUp=function(){s.prototype.cleanUp.call(this),this.data=null},r.prototype.resume=function(){return!!s.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,n.delay(this._tickAndRepeat,[],this)),!0)},r.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(n.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},r.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},t.exports=r},{"../utils":32,"./GenericWorker":28}],28:[function(e,t,i){function n(e){this.name=e||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}n.prototype={push:function(e){this.emit("data",e)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(e){this.emit("error",e)}return!0},error:function(e){return!this.isFinished&&(this.isPaused?this.generatedError=e:(this.isFinished=!0,this.emit("error",e),this.previous&&this.previous.error(e),this.cleanUp()),!0)},on:function(e,t){return this._listeners[e].push(t),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(e,t){if(this._listeners[e])for(var i=0;i<this._listeners[e].length;i++)this._listeners[e][i].call(this,t)},pipe:function(e){return e.registerPrevious(this)},registerPrevious:function(e){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=e.streamInfo,this.mergeStreamInfo(),this.previous=e;var t=this;return e.on("data",function(e){t.processChunk(e)}),e.on("end",function(){t.end()}),e.on("error",function(e){t.error(e)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var e=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),e=!0),this.previous&&this.previous.resume(),!e},flush:function(){},processChunk:function(e){this.push(e)},withStreamInfo:function(e,t){return this.extraStreamInfo[e]=t,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var e in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,e)&&(this.streamInfo[e]=this.extraStreamInfo[e])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var e="Worker "+this.name;return this.previous?this.previous+" -> "+e:e}},t.exports=n},{}],29:[function(e,t,i){var n=e("../utils"),s=e("./ConvertWorker"),r=e("./GenericWorker"),o=e("../base64"),a=e("../support"),l=e("../external"),c=null;if(a.nodestream)try{c=e("../nodejs/NodejsStreamOutputAdapter")}catch(e){}function h(e,t){return new l.Promise(function(i,s){var r=[],a=e._internalType,l=e._outputType,c=e._mimeType;e.on("data",function(e,i){r.push(e),t&&t(i)}).on("error",function(e){r=[],s(e)}).on("end",function(){try{var e=function(e,t,i){switch(e){case"blob":return n.newBlob(n.transformTo("arraybuffer",t),i);case"base64":return o.encode(t);default:return n.transformTo(e,t)}}(l,function(e,t){var i,n=0,s=null,r=0;for(i=0;i<t.length;i++)r+=t[i].length;switch(e){case"string":return t.join("");case"array":return Array.prototype.concat.apply([],t);case"uint8array":for(s=new Uint8Array(r),i=0;i<t.length;i++)s.set(t[i],n),n+=t[i].length;return s;case"nodebuffer":return Buffer.concat(t);default:throw new Error("concat : unsupported type '"+e+"'")}}(a,r),c);i(e)}catch(e){s(e)}r=[]}).resume()})}function d(e,t,i){var o=t;switch(t){case"blob":case"arraybuffer":o="uint8array";break;case"base64":o="string"}try{this._internalType=o,this._outputType=t,this._mimeType=i,n.checkSupport(o),this._worker=e.pipe(new s(o)),e.lock()}catch(e){this._worker=new r("error"),this._worker.error(e)}}d.prototype={accumulate:function(e){return h(this,e)},on:function(e,t){var i=this;return"data"===e?this._worker.on(e,function(e){t.call(i,e.data,e.meta)}):this._worker.on(e,function(){n.delay(t,arguments,i)}),this},resume:function(){return n.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(e){if(n.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new c(this,{objectMode:"nodebuffer"!==this._outputType},e)}},t.exports=d},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(e,t,i){if(i.base64=!0,i.array=!0,i.string=!0,i.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,i.nodebuffer="undefined"!=typeof Buffer,i.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)i.blob=!1;else{var n=new ArrayBuffer(0);try{i.blob=0===new Blob([n],{type:"application/zip"}).size}catch(e){try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);s.append(n),i.blob=0===s.getBlob("application/zip").size}catch(e){i.blob=!1}}}try{i.nodestream=!!e("readable-stream").Readable}catch(e){i.nodestream=!1}},{"readable-stream":16}],31:[function(e,t,i){for(var n=e("./utils"),s=e("./support"),r=e("./nodejsUtils"),o=e("./stream/GenericWorker"),a=new Array(256),l=0;l<256;l++)a[l]=252<=l?6:248<=l?5:240<=l?4:224<=l?3:192<=l?2:1;function c(){o.call(this,"utf-8 decode"),this.leftOver=null}function h(){o.call(this,"utf-8 encode")}a[254]=a[254]=1,i.utf8encode=function(e){return s.nodebuffer?r.newBufferFrom(e,"utf-8"):function(e){var t,i,n,r,o,a=e.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(t=s.uint8array?new Uint8Array(l):new Array(l),r=o=0;o<l;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),i<128?t[o++]=i:(i<2048?t[o++]=192|i>>>6:(i<65536?t[o++]=224|i>>>12:(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63),t[o++]=128|i>>>6&63),t[o++]=128|63&i);return t}(e)},i.utf8decode=function(e){return s.nodebuffer?n.transformTo("nodebuffer",e).toString("utf-8"):function(e){var t,i,s,r,o=e.length,l=new Array(2*o);for(t=i=0;t<o;)if((s=e[t++])<128)l[i++]=s;else if(4<(r=a[s]))l[i++]=65533,t+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&t<o;)s=s<<6|63&e[t++],r--;1<r?l[i++]=65533:s<65536?l[i++]=s:(s-=65536,l[i++]=55296|s>>10&1023,l[i++]=56320|1023&s)}return l.length!==i&&(l.subarray?l=l.subarray(0,i):l.length=i),n.applyFromCharCode(l)}(e=n.transformTo(s.uint8array?"uint8array":"array",e))},n.inherits(c,o),c.prototype.processChunk=function(e){var t=n.transformTo(s.uint8array?"uint8array":"array",e.data);if(this.leftOver&&this.leftOver.length){if(s.uint8array){var r=t;(t=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),t.set(r,this.leftOver.length)}else t=this.leftOver.concat(t);this.leftOver=null}var o=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;0<=i&&128==(192&e[i]);)i--;return i<0||0===i?t:i+a[e[i]]>t?i:t}(t),l=t;o!==t.length&&(s.uint8array?(l=t.subarray(0,o),this.leftOver=t.subarray(o,t.length)):(l=t.slice(0,o),this.leftOver=t.slice(o,t.length))),this.push({data:i.utf8decode(l),meta:e.meta})},c.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=c,n.inherits(h,o),h.prototype.processChunk=function(e){this.push({data:i.utf8encode(e.data),meta:e.meta})},i.Utf8EncodeWorker=h},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(e,t,i){var n=e("./support"),s=e("./base64"),r=e("./nodejsUtils"),o=e("./external");function a(e){return e}function l(e,t){for(var i=0;i<e.length;++i)t[i]=255&e.charCodeAt(i);return t}e("setimmediate"),i.newBlob=function(e,t){i.checkSupport("blob");try{return new Blob([e],{type:t})}catch(i){try{var n=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return n.append(e),n.getBlob(t)}catch(e){throw new Error("Bug : can't construct the Blob.")}}};var c={stringifyByChunk:function(e,t,i){var n=[],s=0,r=e.length;if(r<=i)return String.fromCharCode.apply(null,e);for(;s<r;)"array"===t||"nodebuffer"===t?n.push(String.fromCharCode.apply(null,e.slice(s,Math.min(s+i,r)))):n.push(String.fromCharCode.apply(null,e.subarray(s,Math.min(s+i,r)))),s+=i;return n.join("")},stringifyByChar:function(e){for(var t="",i=0;i<e.length;i++)t+=String.fromCharCode(e[i]);return t},applyCanBeUsed:{uint8array:function(){try{return n.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(e){return!1}}(),nodebuffer:function(){try{return n.nodebuffer&&1===String.fromCharCode.apply(null,r.allocBuffer(1)).length}catch(e){return!1}}()}};function h(e){var t=65536,n=i.getTypeOf(e),s=!0;if("uint8array"===n?s=c.applyCanBeUsed.uint8array:"nodebuffer"===n&&(s=c.applyCanBeUsed.nodebuffer),s)for(;1<t;)try{return c.stringifyByChunk(e,n,t)}catch(e){t=Math.floor(t/2)}return c.stringifyByChar(e)}function d(e,t){for(var i=0;i<e.length;i++)t[i]=e[i];return t}i.applyFromCharCode=h;var u={};u.string={string:a,array:function(e){return l(e,new Array(e.length))},arraybuffer:function(e){return u.string.uint8array(e).buffer},uint8array:function(e){return l(e,new Uint8Array(e.length))},nodebuffer:function(e){return l(e,r.allocBuffer(e.length))}},u.array={string:h,array:a,arraybuffer:function(e){return new Uint8Array(e).buffer},uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return r.newBufferFrom(e)}},u.arraybuffer={string:function(e){return h(new Uint8Array(e))},array:function(e){return d(new Uint8Array(e),new Array(e.byteLength))},arraybuffer:a,uint8array:function(e){return new Uint8Array(e)},nodebuffer:function(e){return r.newBufferFrom(new Uint8Array(e))}},u.uint8array={string:h,array:function(e){return d(e,new Array(e.length))},arraybuffer:function(e){return e.buffer},uint8array:a,nodebuffer:function(e){return r.newBufferFrom(e)}},u.nodebuffer={string:h,array:function(e){return d(e,new Array(e.length))},arraybuffer:function(e){return u.nodebuffer.uint8array(e).buffer},uint8array:function(e){return d(e,new Uint8Array(e.length))},nodebuffer:a},i.transformTo=function(e,t){if(t=t||"",!e)return t;i.checkSupport(e);var n=i.getTypeOf(t);return u[n][e](t)},i.resolve=function(e){for(var t=e.split("/"),i=[],n=0;n<t.length;n++){var s=t[n];"."===s||""===s&&0!==n&&n!==t.length-1||(".."===s?i.pop():i.push(s))}return i.join("/")},i.getTypeOf=function(e){return"string"==typeof e?"string":"[object Array]"===Object.prototype.toString.call(e)?"array":n.nodebuffer&&r.isBuffer(e)?"nodebuffer":n.uint8array&&e instanceof Uint8Array?"uint8array":n.arraybuffer&&e instanceof ArrayBuffer?"arraybuffer":void 0},i.checkSupport=function(e){if(!n[e.toLowerCase()])throw new Error(e+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(e){var t,i,n="";for(i=0;i<(e||"").length;i++)n+="\\x"+((t=e.charCodeAt(i))<16?"0":"")+t.toString(16).toUpperCase();return n},i.delay=function(e,t,i){setImmediate(function(){e.apply(i||null,t||[])})},i.inherits=function(e,t){function i(){}i.prototype=t.prototype,e.prototype=new i},i.extend=function(){var e,t,i={};for(e=0;e<arguments.length;e++)for(t in arguments[e])Object.prototype.hasOwnProperty.call(arguments[e],t)&&void 0===i[t]&&(i[t]=arguments[e][t]);return i},i.prepareContent=function(e,t,r,a,c){return o.Promise.resolve(t).then(function(e){return n.blob&&(e instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(e)))&&"undefined"!=typeof FileReader?new o.Promise(function(t,i){var n=new FileReader;n.onload=function(e){t(e.target.result)},n.onerror=function(e){i(e.target.error)},n.readAsArrayBuffer(e)}):e}).then(function(t){var h,d=i.getTypeOf(t);return d?("arraybuffer"===d?t=i.transformTo("uint8array",t):"string"===d&&(c?t=s.decode(t):r&&!0!==a&&(t=l(h=t,n.uint8array?new Uint8Array(h.length):new Array(h.length)))),t):o.Promise.reject(new Error("Can't read the data of '"+e+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(e,t,i){var n=e("./reader/readerFor"),s=e("./utils"),r=e("./signature"),o=e("./zipEntry"),a=e("./support");function l(e){this.files=[],this.loadOptions=e}l.prototype={checkSignature:function(e){if(!this.reader.readAndCheckSignature(e)){this.reader.index-=4;var t=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+s.pretty(t)+", expected "+s.pretty(e)+")")}},isSignature:function(e,t){var i=this.reader.index;this.reader.setIndex(e);var n=this.reader.readString(4)===t;return this.reader.setIndex(i),n},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var e=this.reader.readData(this.zipCommentLength),t=a.uint8array?"uint8array":"array",i=s.transformTo(t,e);this.zipComment=this.loadOptions.decodeFileName(i)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var e,t,i,n=this.zip64EndOfCentralSize-44;0<n;)e=this.reader.readInt(2),t=this.reader.readInt(4),i=this.reader.readData(t),this.zip64ExtensibleData[e]={id:e,length:t,value:i}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var e,t;for(e=0;e<this.files.length;e++)t=this.files[e],this.reader.setIndex(t.localHeaderOffset),this.checkSignature(r.LOCAL_FILE_HEADER),t.readLocalPart(this.reader),t.handleUTF8(),t.processAttributes()},readCentralDir:function(){var e;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(r.CENTRAL_FILE_HEADER);)(e=new o({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(e);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var e=this.reader.lastIndexOfSignature(r.CENTRAL_DIRECTORY_END);if(e<0)throw this.isSignature(0,r.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(e);var t=e;if(this.checkSignature(r.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===s.MAX_VALUE_16BITS||this.diskWithCentralDirStart===s.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===s.MAX_VALUE_16BITS||this.centralDirRecords===s.MAX_VALUE_16BITS||this.centralDirSize===s.MAX_VALUE_32BITS||this.centralDirOffset===s.MAX_VALUE_32BITS){if(this.zip64=!0,(e=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(e),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,r.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var i=this.centralDirOffset+this.centralDirSize;this.zip64&&(i+=20,i+=12+this.zip64EndOfCentralSize);var n=t-i;if(0<n)this.isSignature(t,r.CENTRAL_FILE_HEADER)||(this.reader.zero=n);else if(n<0)throw new Error("Corrupted zip: missing "+Math.abs(n)+" bytes.")},prepareReader:function(e){this.reader=n(e)},load:function(e){this.prepareReader(e),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},t.exports=l},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(e,t,i){var n=e("./reader/readerFor"),s=e("./utils"),r=e("./compressedObject"),o=e("./crc32"),a=e("./utf8"),l=e("./compressions"),c=e("./support");function h(e,t){this.options=e,this.loadOptions=t}h.prototype={isEncrypted:function(){return!(1&~this.bitFlag)},useUTF8:function(){return!(2048&~this.bitFlag)},readLocalPart:function(e){var t,i;if(e.skip(22),this.fileNameLength=e.readInt(2),i=e.readInt(2),this.fileName=e.readData(this.fileNameLength),e.skip(i),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(t=function(e){for(var t in l)if(Object.prototype.hasOwnProperty.call(l,t)&&l[t].magic===e)return l[t];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+s.pretty(this.compressionMethod)+" unknown (inner file : "+s.transformTo("string",this.fileName)+")");this.decompressed=new r(this.compressedSize,this.uncompressedSize,this.crc32,t,e.readData(this.compressedSize))},readCentralPart:function(e){this.versionMadeBy=e.readInt(2),e.skip(2),this.bitFlag=e.readInt(2),this.compressionMethod=e.readString(2),this.date=e.readDate(),this.crc32=e.readInt(4),this.compressedSize=e.readInt(4),this.uncompressedSize=e.readInt(4);var t=e.readInt(2);if(this.extraFieldsLength=e.readInt(2),this.fileCommentLength=e.readInt(2),this.diskNumberStart=e.readInt(2),this.internalFileAttributes=e.readInt(2),this.externalFileAttributes=e.readInt(4),this.localHeaderOffset=e.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");e.skip(t),this.readExtraFields(e),this.parseZIP64ExtraField(e),this.fileComment=e.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var e=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==e&&(this.dosPermissions=63&this.externalFileAttributes),3==e&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var e=n(this.extraFields[1].value);this.uncompressedSize===s.MAX_VALUE_32BITS&&(this.uncompressedSize=e.readInt(8)),this.compressedSize===s.MAX_VALUE_32BITS&&(this.compressedSize=e.readInt(8)),this.localHeaderOffset===s.MAX_VALUE_32BITS&&(this.localHeaderOffset=e.readInt(8)),this.diskNumberStart===s.MAX_VALUE_32BITS&&(this.diskNumberStart=e.readInt(4))}},readExtraFields:function(e){var t,i,n,s=e.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});e.index+4<s;)t=e.readInt(2),i=e.readInt(2),n=e.readData(i),this.extraFields[t]={id:t,length:i,value:n};e.setIndex(s)},handleUTF8:function(){var e=c.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var t=this.findExtraFieldUnicodePath();if(null!==t)this.fileNameStr=t;else{var i=s.transformTo(e,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(i)}var n=this.findExtraFieldUnicodeComment();if(null!==n)this.fileCommentStr=n;else{var r=s.transformTo(e,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(r)}}},findExtraFieldUnicodePath:function(){var e=this.extraFields[28789];if(e){var t=n(e.value);return 1!==t.readInt(1)||o(this.fileName)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null},findExtraFieldUnicodeComment:function(){var e=this.extraFields[25461];if(e){var t=n(e.value);return 1!==t.readInt(1)||o(this.fileComment)!==t.readInt(4)?null:a.utf8decode(t.readData(e.length-5))}return null}},t.exports=h},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(e,t,i){function n(e,t,i){this.name=e,this.dir=i.dir,this.date=i.date,this.comment=i.comment,this.unixPermissions=i.unixPermissions,this.dosPermissions=i.dosPermissions,this._data=t,this._dataBinary=i.binary,this.options={compression:i.compression,compressionOptions:i.compressionOptions}}var s=e("./stream/StreamHelper"),r=e("./stream/DataWorker"),o=e("./utf8"),a=e("./compressedObject"),l=e("./stream/GenericWorker");n.prototype={internalStream:function(e){var t=null,i="string";try{if(!e)throw new Error("No output type specified.");var n="string"===(i=e.toLowerCase())||"text"===i;"binarystring"!==i&&"text"!==i||(i="string"),t=this._decompressWorker();var r=!this._dataBinary;r&&!n&&(t=t.pipe(new o.Utf8EncodeWorker)),!r&&n&&(t=t.pipe(new o.Utf8DecodeWorker))}catch(e){(t=new l("error")).error(e)}return new s(t,i,"")},async:function(e,t){return this.internalStream(e).accumulate(t)},nodeStream:function(e,t){return this.internalStream(e||"nodebuffer").toNodejsStream(t)},_compressWorker:function(e,t){if(this._data instanceof a&&this._data.compression.magic===e.magic)return this._data.getCompressedWorker();var i=this._decompressWorker();return this._dataBinary||(i=i.pipe(new o.Utf8EncodeWorker)),a.createWorkerFrom(i,e,t)},_decompressWorker:function(){return this._data instanceof a?this._data.getContentWorker():this._data instanceof l?this._data:new r(this._data)}};for(var c=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],h=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},d=0;d<c.length;d++)n.prototype[c[d]]=h;t.exports=n},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(e,t,i){(function(e){var i,n,s=e.MutationObserver||e.WebKitMutationObserver;if(s){var r=0,o=new s(h),a=e.document.createTextNode("");o.observe(a,{characterData:!0}),i=function(){a.data=r=++r%2}}else if(e.setImmediate||void 0===e.MessageChannel)i="document"in e&&"onreadystatechange"in e.document.createElement("script")?function(){var t=e.document.createElement("script");t.onreadystatechange=function(){h(),t.onreadystatechange=null,t.parentNode.removeChild(t),t=null},e.document.documentElement.appendChild(t)}:function(){setTimeout(h,0)};else{var l=new e.MessageChannel;l.port1.onmessage=h,i=function(){l.port2.postMessage(0)}}var c=[];function h(){var e,t;n=!0;for(var i=c.length;i;){for(t=c,c=[],e=-1;++e<i;)t[e]();i=c.length}n=!1}t.exports=function(e){1!==c.push(e)||n||i()}}).call(this,void 0!==Yr?Yr:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(e,t,i){var n=e("immediate");function s(){}var r={},o=["REJECTED"],a=["FULFILLED"],l=["PENDING"];function c(e){if("function"!=typeof e)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,e!==s&&p(this,e)}function h(e,t,i){this.promise=e,"function"==typeof t&&(this.onFulfilled=t,this.callFulfilled=this.otherCallFulfilled),"function"==typeof i&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}function d(e,t,i){n(function(){var n;try{n=t(i)}catch(t){return r.reject(e,t)}n===e?r.reject(e,new TypeError("Cannot resolve promise with itself")):r.resolve(e,n)})}function u(e){var t=e&&e.then;if(e&&("object"==typeof e||"function"==typeof e)&&"function"==typeof t)return function(){t.apply(e,arguments)}}function p(e,t){var i=!1;function n(t){i||(i=!0,r.reject(e,t))}function s(t){i||(i=!0,r.resolve(e,t))}var o=f(function(){t(s,n)});"error"===o.status&&n(o.value)}function f(e,t){var i={};try{i.value=e(t),i.status="success"}catch(e){i.status="error",i.value=e}return i}(t.exports=c).prototype.finally=function(e){if("function"!=typeof e)return this;var t=this.constructor;return this.then(function(i){return t.resolve(e()).then(function(){return i})},function(i){return t.resolve(e()).then(function(){throw i})})},c.prototype.catch=function(e){return this.then(null,e)},c.prototype.then=function(e,t){if("function"!=typeof e&&this.state===a||"function"!=typeof t&&this.state===o)return this;var i=new this.constructor(s);return this.state!==l?d(i,this.state===a?e:t,this.outcome):this.queue.push(new h(i,e,t)),i},h.prototype.callFulfilled=function(e){r.resolve(this.promise,e)},h.prototype.otherCallFulfilled=function(e){d(this.promise,this.onFulfilled,e)},h.prototype.callRejected=function(e){r.reject(this.promise,e)},h.prototype.otherCallRejected=function(e){d(this.promise,this.onRejected,e)},r.resolve=function(e,t){var i=f(u,t);if("error"===i.status)return r.reject(e,i.value);var n=i.value;if(n)p(e,n);else{e.state=a,e.outcome=t;for(var s=-1,o=e.queue.length;++s<o;)e.queue[s].callFulfilled(t)}return e},r.reject=function(e,t){e.state=o,e.outcome=t;for(var i=-1,n=e.queue.length;++i<n;)e.queue[i].callRejected(t);return e},c.resolve=function(e){return e instanceof this?e:r.resolve(new this(s),e)},c.reject=function(e){var t=new this(s);return r.reject(t,e)},c.all=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.length,n=!1;if(!i)return this.resolve([]);for(var o=new Array(i),a=0,l=-1,c=new this(s);++l<i;)h(e[l],l);return c;function h(e,s){t.resolve(e).then(function(e){o[s]=e,++a!==i||n||(n=!0,r.resolve(c,o))},function(e){n||(n=!0,r.reject(c,e))})}},c.race=function(e){var t=this;if("[object Array]"!==Object.prototype.toString.call(e))return this.reject(new TypeError("must be an array"));var i=e.length,n=!1;if(!i)return this.resolve([]);for(var o,a=-1,l=new this(s);++a<i;)o=e[a],t.resolve(o).then(function(e){n||(n=!0,r.resolve(l,e))},function(e){n||(n=!0,r.reject(l,e))});return l}},{immediate:36}],38:[function(e,t,i){var n={};(0,e("./lib/utils/common").assign)(n,e("./lib/deflate"),e("./lib/inflate"),e("./lib/zlib/constants")),t.exports=n},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(e,t,i){var n=e("./zlib/deflate"),s=e("./utils/common"),r=e("./utils/strings"),o=e("./zlib/messages"),a=e("./zlib/zstream"),l=Object.prototype.toString,c=0,h=-1,d=0,u=8;function p(e){if(!(this instanceof p))return new p(e);this.options=s.assign({level:h,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:d,to:""},e||{});var t=this.options;t.raw&&0<t.windowBits?t.windowBits=-t.windowBits:t.gzip&&0<t.windowBits&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var i=n.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==c)throw new Error(o[i]);if(t.header&&n.deflateSetHeader(this.strm,t.header),t.dictionary){var f;if(f="string"==typeof t.dictionary?r.string2buf(t.dictionary):"[object ArrayBuffer]"===l.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,(i=n.deflateSetDictionary(this.strm,f))!==c)throw new Error(o[i]);this._dict_set=!0}}function f(e,t){var i=new p(t);if(i.push(e,!0),i.err)throw i.msg||o[i.err];return i.result}p.prototype.push=function(e,t){var i,o,a=this.strm,h=this.options.chunkSize;if(this.ended)return!1;o=t===~~t?t:!0===t?4:0,"string"==typeof e?a.input=r.string2buf(e):"[object ArrayBuffer]"===l.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new s.Buf8(h),a.next_out=0,a.avail_out=h),1!==(i=n.deflate(a,o))&&i!==c)return this.onEnd(i),!(this.ended=!0);0!==a.avail_out&&(0!==a.avail_in||4!==o&&2!==o)||("string"===this.options.to?this.onData(r.buf2binstring(s.shrinkBuf(a.output,a.next_out))):this.onData(s.shrinkBuf(a.output,a.next_out)))}while((0<a.avail_in||0===a.avail_out)&&1!==i);return 4===o?(i=n.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===c):2!==o||(this.onEnd(c),!(a.avail_out=0))},p.prototype.onData=function(e){this.chunks.push(e)},p.prototype.onEnd=function(e){e===c&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Deflate=p,i.deflate=f,i.deflateRaw=function(e,t){return(t=t||{}).raw=!0,f(e,t)},i.gzip=function(e,t){return(t=t||{}).gzip=!0,f(e,t)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(e,t,i){var n=e("./zlib/inflate"),s=e("./utils/common"),r=e("./utils/strings"),o=e("./zlib/constants"),a=e("./zlib/messages"),l=e("./zlib/zstream"),c=e("./zlib/gzheader"),h=Object.prototype.toString;function d(e){if(!(this instanceof d))return new d(e);this.options=s.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&0<=t.windowBits&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(0<=t.windowBits&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),15<t.windowBits&&t.windowBits<48&&!(15&t.windowBits)&&(t.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var i=n.inflateInit2(this.strm,t.windowBits);if(i!==o.Z_OK)throw new Error(a[i]);this.header=new c,n.inflateGetHeader(this.strm,this.header)}function u(e,t){var i=new d(t);if(i.push(e,!0),i.err)throw i.msg||a[i.err];return i.result}d.prototype.push=function(e,t){var i,a,l,c,d,u,p=this.strm,f=this.options.chunkSize,m=this.options.dictionary,g=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof e?p.input=r.binstring2buf(e):"[object ArrayBuffer]"===h.call(e)?p.input=new Uint8Array(e):p.input=e,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new s.Buf8(f),p.next_out=0,p.avail_out=f),(i=n.inflate(p,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&m&&(u="string"==typeof m?r.string2buf(m):"[object ArrayBuffer]"===h.call(m)?new Uint8Array(m):m,i=n.inflateSetDictionary(this.strm,u)),i===o.Z_BUF_ERROR&&!0===g&&(i=o.Z_OK,g=!1),i!==o.Z_STREAM_END&&i!==o.Z_OK)return this.onEnd(i),!(this.ended=!0);p.next_out&&(0!==p.avail_out&&i!==o.Z_STREAM_END&&(0!==p.avail_in||a!==o.Z_FINISH&&a!==o.Z_SYNC_FLUSH)||("string"===this.options.to?(l=r.utf8border(p.output,p.next_out),c=p.next_out-l,d=r.buf2string(p.output,l),p.next_out=c,p.avail_out=f-c,c&&s.arraySet(p.output,p.output,l,c,0),this.onData(d)):this.onData(s.shrinkBuf(p.output,p.next_out)))),0===p.avail_in&&0===p.avail_out&&(g=!0)}while((0<p.avail_in||0===p.avail_out)&&i!==o.Z_STREAM_END);return i===o.Z_STREAM_END&&(a=o.Z_FINISH),a===o.Z_FINISH?(i=n.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===o.Z_OK):a!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),!(p.avail_out=0))},d.prototype.onData=function(e){this.chunks.push(e)},d.prototype.onEnd=function(e){e===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},i.Inflate=d,i.inflate=u,i.inflateRaw=function(e,t){return(t=t||{}).raw=!0,u(e,t)},i.ungzip=u},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(e,t,i){var n="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;i.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var n in i)i.hasOwnProperty(n)&&(e[n]=i[n])}}return e},i.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var s={arraySet:function(e,t,i,n,s){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+n),s);else for(var r=0;r<n;r++)e[s+r]=t[i+r]},flattenChunks:function(e){var t,i,n,s,r,o;for(t=n=0,i=e.length;t<i;t++)n+=e[t].length;for(o=new Uint8Array(n),t=s=0,i=e.length;t<i;t++)r=e[t],o.set(r,s),s+=r.length;return o}},r={arraySet:function(e,t,i,n,s){for(var r=0;r<n;r++)e[s+r]=t[i+r]},flattenChunks:function(e){return[].concat.apply([],e)}};i.setTyped=function(e){e?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,s)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,r))},i.setTyped(n)},{}],42:[function(e,t,i){var n=e("./common"),s=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch(e){s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){r=!1}for(var o=new n.Buf8(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function l(e,t){if(t<65537&&(e.subarray&&r||!e.subarray&&s))return String.fromCharCode.apply(null,n.shrinkBuf(e,t));for(var i="",o=0;o<t;o++)i+=String.fromCharCode(e[o]);return i}o[254]=o[254]=1,i.string2buf=function(e){var t,i,s,r,o,a=e.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(t=new n.Buf8(l),r=o=0;o<l;r++)55296==(64512&(i=e.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=e.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),i<128?t[o++]=i:(i<2048?t[o++]=192|i>>>6:(i<65536?t[o++]=224|i>>>12:(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63),t[o++]=128|i>>>6&63),t[o++]=128|63&i);return t},i.buf2binstring=function(e){return l(e,e.length)},i.binstring2buf=function(e){for(var t=new n.Buf8(e.length),i=0,s=t.length;i<s;i++)t[i]=e.charCodeAt(i);return t},i.buf2string=function(e,t){var i,n,s,r,a=t||e.length,c=new Array(2*a);for(i=n=0;i<a;)if((s=e[i++])<128)c[n++]=s;else if(4<(r=o[s]))c[n++]=65533,i+=r-1;else{for(s&=2===r?31:3===r?15:7;1<r&&i<a;)s=s<<6|63&e[i++],r--;1<r?c[n++]=65533:s<65536?c[n++]=s:(s-=65536,c[n++]=55296|s>>10&1023,c[n++]=56320|1023&s)}return l(c,n)},i.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;0<=i&&128==(192&e[i]);)i--;return i<0||0===i?t:i+o[e[i]]>t?i:t}},{"./common":41}],43:[function(e,t,i){t.exports=function(e,t,i,n){for(var s=65535&e,r=e>>>16&65535,o=0;0!==i;){for(i-=o=2e3<i?2e3:i;r=r+(s=s+t[n++]|0)|0,--o;);s%=65521,r%=65521}return s|r<<16}},{}],44:[function(e,t,i){t.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(e,t,i){var n=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var n=0;n<8;n++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();t.exports=function(e,t,i,s){var r=n,o=s+i;e^=-1;for(var a=s;a<o;a++)e=e>>>8^r[255&(e^t[a])];return-1^e}},{}],46:[function(e,t,i){var n,s=e("../utils/common"),r=e("./trees"),o=e("./adler32"),a=e("./crc32"),l=e("./messages"),c=0,h=4,d=0,u=-2,p=-1,f=4,m=2,g=8,w=9,y=286,_=30,b=19,v=2*y+1,x=15,S=3,C=258,T=C+S+1,A=42,E=113,M=1,P=2,I=3,z=4;function D(e,t){return e.msg=l[t],t}function k(e){return(e<<1)-(4<e?9:0)}function B(e){for(var t=e.length;0<=--t;)e[t]=0}function O(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(s.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function V(e,t){r._tr_flush_block(e,0<=e.block_start?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,O(e.strm)}function L(e,t){e.pending_buf[e.pending++]=t}function N(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function F(e,t){var i,n,s=e.max_chain_length,r=e.strstart,o=e.prev_length,a=e.nice_match,l=e.strstart>e.w_size-T?e.strstart-(e.w_size-T):0,c=e.window,h=e.w_mask,d=e.prev,u=e.strstart+C,p=c[r+o-1],f=c[r+o];e.prev_length>=e.good_match&&(s>>=2),a>e.lookahead&&(a=e.lookahead);do{if(c[(i=t)+o]===f&&c[i+o-1]===p&&c[i]===c[r]&&c[++i]===c[r+1]){r+=2,i++;do{}while(c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&c[++r]===c[++i]&&r<u);if(n=C-(u-r),r=u-C,o<n){if(e.match_start=t,a<=(o=n))break;p=c[r+o-1],f=c[r+o]}}}while((t=d[t&h])>l&&0!=--s);return o<=e.lookahead?o:e.lookahead}function R(e){var t,i,n,r,l,c,h,d,u,p,f=e.w_size;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=f+(f-T)){for(s.arraySet(e.window,e.window,f,f,0),e.match_start-=f,e.strstart-=f,e.block_start-=f,t=i=e.hash_size;n=e.head[--t],e.head[t]=f<=n?n-f:0,--i;);for(t=i=f;n=e.prev[--t],e.prev[t]=f<=n?n-f:0,--i;);r+=f}if(0===e.strm.avail_in)break;if(c=e.strm,h=e.window,d=e.strstart+e.lookahead,p=void 0,(u=r)<(p=c.avail_in)&&(p=u),i=0===p?0:(c.avail_in-=p,s.arraySet(h,c.input,c.next_in,p,d),1===c.state.wrap?c.adler=o(c.adler,h,p,d):2===c.state.wrap&&(c.adler=a(c.adler,h,p,d)),c.next_in+=p,c.total_in+=p,p),e.lookahead+=i,e.lookahead+e.insert>=S)for(l=e.strstart-e.insert,e.ins_h=e.window[l],e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+1])&e.hash_mask;e.insert&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[l+S-1])&e.hash_mask,e.prev[l&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=l,l++,e.insert--,!(e.lookahead+e.insert<S)););}while(e.lookahead<T&&0!==e.strm.avail_in)}function U(e,t){for(var i,n;;){if(e.lookahead<T){if(R(e),e.lookahead<T&&t===c)return M;if(0===e.lookahead)break}if(i=0,e.lookahead>=S&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+S-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-T&&(e.match_length=F(e,i)),e.match_length>=S)if(n=r._tr_tally(e,e.strstart-e.match_start,e.match_length-S),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=S){for(e.match_length--;e.strstart++,e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+S-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart,0!=--e.match_length;);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+1])&e.hash_mask;else n=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(n&&(V(e,!1),0===e.strm.avail_out))return M}return e.insert=e.strstart<S-1?e.strstart:S-1,t===h?(V(e,!0),0===e.strm.avail_out?I:z):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?M:P}function j(e,t){for(var i,n,s;;){if(e.lookahead<T){if(R(e),e.lookahead<T&&t===c)return M;if(0===e.lookahead)break}if(i=0,e.lookahead>=S&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+S-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=S-1,0!==i&&e.prev_length<e.max_lazy_match&&e.strstart-i<=e.w_size-T&&(e.match_length=F(e,i),e.match_length<=5&&(1===e.strategy||e.match_length===S&&4096<e.strstart-e.match_start)&&(e.match_length=S-1)),e.prev_length>=S&&e.match_length<=e.prev_length){for(s=e.strstart+e.lookahead-S,n=r._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-S),e.lookahead-=e.prev_length-1,e.prev_length-=2;++e.strstart<=s&&(e.ins_h=(e.ins_h<<e.hash_shift^e.window[e.strstart+S-1])&e.hash_mask,i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!=--e.prev_length;);if(e.match_available=0,e.match_length=S-1,e.strstart++,n&&(V(e,!1),0===e.strm.avail_out))return M}else if(e.match_available){if((n=r._tr_tally(e,0,e.window[e.strstart-1]))&&V(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return M}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(n=r._tr_tally(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<S-1?e.strstart:S-1,t===h?(V(e,!0),0===e.strm.avail_out?I:z):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?M:P}function $(e,t,i,n,s){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=n,this.func=s}function W(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=g,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new s.Buf16(2*v),this.dyn_dtree=new s.Buf16(2*(2*_+1)),this.bl_tree=new s.Buf16(2*(2*b+1)),B(this.dyn_ltree),B(this.dyn_dtree),B(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new s.Buf16(x+1),this.heap=new s.Buf16(2*y+1),B(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new s.Buf16(2*y+1),B(this.depth),this.l_buf=0,this.lit_bufsize=0,this.last_lit=0,this.d_buf=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}function G(e){var t;return e&&e.state?(e.total_in=e.total_out=0,e.data_type=m,(t=e.state).pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=t.wrap?A:E,e.adler=2===t.wrap?0:1,t.last_flush=c,r._tr_init(t),d):D(e,u)}function H(e){var t,i=G(e);return i===d&&((t=e.state).window_size=2*t.w_size,B(t.head),t.max_lazy_match=n[t.level].max_lazy,t.good_match=n[t.level].good_length,t.nice_match=n[t.level].nice_length,t.max_chain_length=n[t.level].max_chain,t.strstart=0,t.block_start=0,t.lookahead=0,t.insert=0,t.match_length=t.prev_length=S-1,t.match_available=0,t.ins_h=0),i}function q(e,t,i,n,r,o){if(!e)return u;var a=1;if(t===p&&(t=6),n<0?(a=0,n=-n):15<n&&(a=2,n-=16),r<1||w<r||i!==g||n<8||15<n||t<0||9<t||o<0||f<o)return D(e,u);8===n&&(n=9);var l=new W;return(e.state=l).strm=e,l.wrap=a,l.gzhead=null,l.w_bits=n,l.w_size=1<<l.w_bits,l.w_mask=l.w_size-1,l.hash_bits=r+7,l.hash_size=1<<l.hash_bits,l.hash_mask=l.hash_size-1,l.hash_shift=~~((l.hash_bits+S-1)/S),l.window=new s.Buf8(2*l.w_size),l.head=new s.Buf16(l.hash_size),l.prev=new s.Buf16(l.w_size),l.lit_bufsize=1<<r+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new s.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=t,l.strategy=o,l.method=i,H(e)}n=[new $(0,0,0,0,function(e,t){var i=65535;for(i>e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(R(e),0===e.lookahead&&t===c)return M;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var n=e.block_start+i;if((0===e.strstart||e.strstart>=n)&&(e.lookahead=e.strstart-n,e.strstart=n,V(e,!1),0===e.strm.avail_out))return M;if(e.strstart-e.block_start>=e.w_size-T&&(V(e,!1),0===e.strm.avail_out))return M}return e.insert=0,t===h?(V(e,!0),0===e.strm.avail_out?I:z):(e.strstart>e.block_start&&(V(e,!1),e.strm.avail_out),M)}),new $(4,4,8,4,U),new $(4,5,16,8,U),new $(4,6,32,32,U),new $(4,4,16,16,j),new $(8,16,32,32,j),new $(8,16,128,128,j),new $(8,32,128,256,j),new $(32,128,258,1024,j),new $(32,258,258,4096,j)],i.deflateInit=function(e,t){return q(e,t,g,15,8,0)},i.deflateInit2=q,i.deflateReset=H,i.deflateResetKeep=G,i.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?u:(e.state.gzhead=t,d):u},i.deflate=function(e,t){var i,s,o,l;if(!e||!e.state||5<t||t<0)return e?D(e,u):u;if(s=e.state,!e.output||!e.input&&0!==e.avail_in||666===s.status&&t!==h)return D(e,0===e.avail_out?-5:u);if(s.strm=e,i=s.last_flush,s.last_flush=t,s.status===A)if(2===s.wrap)e.adler=0,L(s,31),L(s,139),L(s,8),s.gzhead?(L(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),L(s,255&s.gzhead.time),L(s,s.gzhead.time>>8&255),L(s,s.gzhead.time>>16&255),L(s,s.gzhead.time>>24&255),L(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),L(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(L(s,255&s.gzhead.extra.length),L(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(e.adler=a(e.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69):(L(s,0),L(s,0),L(s,0),L(s,0),L(s,0),L(s,9===s.level?2:2<=s.strategy||s.level<2?4:0),L(s,3),s.status=E);else{var p=g+(s.w_bits-8<<4)<<8;p|=(2<=s.strategy||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(p|=32),p+=31-p%31,s.status=E,N(s,p),0!==s.strstart&&(N(s,e.adler>>>16),N(s,65535&e.adler)),e.adler=1}if(69===s.status)if(s.gzhead.extra){for(o=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),O(e),o=s.pending,s.pending!==s.pending_buf_size));)L(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=73)}else s.status=73;if(73===s.status)if(s.gzhead.name){o=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),O(e),o=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.name.length?255&s.gzhead.name.charCodeAt(s.gzindex++):0,L(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),0===l&&(s.gzindex=0,s.status=91)}else s.status=91;if(91===s.status)if(s.gzhead.comment){o=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),O(e),o=s.pending,s.pending===s.pending_buf_size)){l=1;break}l=s.gzindex<s.gzhead.comment.length?255&s.gzhead.comment.charCodeAt(s.gzindex++):0,L(s,l)}while(0!==l);s.gzhead.hcrc&&s.pending>o&&(e.adler=a(e.adler,s.pending_buf,s.pending-o,o)),0===l&&(s.status=103)}else s.status=103;if(103===s.status&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&O(e),s.pending+2<=s.pending_buf_size&&(L(s,255&e.adler),L(s,e.adler>>8&255),e.adler=0,s.status=E)):s.status=E),0!==s.pending){if(O(e),0===e.avail_out)return s.last_flush=-1,d}else if(0===e.avail_in&&k(t)<=k(i)&&t!==h)return D(e,-5);if(666===s.status&&0!==e.avail_in)return D(e,-5);if(0!==e.avail_in||0!==s.lookahead||t!==c&&666!==s.status){var f=2===s.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(R(e),0===e.lookahead)){if(t===c)return M;break}if(e.match_length=0,i=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(V(e,!1),0===e.strm.avail_out))return M}return e.insert=0,t===h?(V(e,!0),0===e.strm.avail_out?I:z):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?M:P}(s,t):3===s.strategy?function(e,t){for(var i,n,s,o,a=e.window;;){if(e.lookahead<=C){if(R(e),e.lookahead<=C&&t===c)return M;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=S&&0<e.strstart&&(n=a[s=e.strstart-1])===a[++s]&&n===a[++s]&&n===a[++s]){o=e.strstart+C;do{}while(n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&n===a[++s]&&s<o);e.match_length=C-(o-s),e.match_length>e.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=S?(i=r._tr_tally(e,1,e.match_length-S),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=r._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(V(e,!1),0===e.strm.avail_out))return M}return e.insert=0,t===h?(V(e,!0),0===e.strm.avail_out?I:z):e.last_lit&&(V(e,!1),0===e.strm.avail_out)?M:P}(s,t):n[s.level].func(s,t);if(f!==I&&f!==z||(s.status=666),f===M||f===I)return 0===e.avail_out&&(s.last_flush=-1),d;if(f===P&&(1===t?r._tr_align(s):5!==t&&(r._tr_stored_block(s,0,0,!1),3===t&&(B(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),O(e),0===e.avail_out))return s.last_flush=-1,d}return t!==h?d:s.wrap<=0?1:(2===s.wrap?(L(s,255&e.adler),L(s,e.adler>>8&255),L(s,e.adler>>16&255),L(s,e.adler>>24&255),L(s,255&e.total_in),L(s,e.total_in>>8&255),L(s,e.total_in>>16&255),L(s,e.total_in>>24&255)):(N(s,e.adler>>>16),N(s,65535&e.adler)),O(e),0<s.wrap&&(s.wrap=-s.wrap),0!==s.pending?d:1)},i.deflateEnd=function(e){var t;return e&&e.state?(t=e.state.status)!==A&&69!==t&&73!==t&&91!==t&&103!==t&&t!==E&&666!==t?D(e,u):(e.state=null,t===E?D(e,-3):d):u},i.deflateSetDictionary=function(e,t){var i,n,r,a,l,c,h,p,f=t.length;if(!e||!e.state)return u;if(2===(a=(i=e.state).wrap)||1===a&&i.status!==A||i.lookahead)return u;for(1===a&&(e.adler=o(e.adler,t,f,0)),i.wrap=0,f>=i.w_size&&(0===a&&(B(i.head),i.strstart=0,i.block_start=0,i.insert=0),p=new s.Buf8(i.w_size),s.arraySet(p,t,f-i.w_size,i.w_size,0),t=p,f=i.w_size),l=e.avail_in,c=e.next_in,h=e.input,e.avail_in=f,e.next_in=0,e.input=t,R(i);i.lookahead>=S;){for(n=i.strstart,r=i.lookahead-(S-1);i.ins_h=(i.ins_h<<i.hash_shift^i.window[n+S-1])&i.hash_mask,i.prev[n&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=n,n++,--r;);i.strstart=n,i.lookahead=S-1,R(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=S-1,i.match_available=0,e.next_in=c,e.input=h,e.avail_in=l,i.wrap=a,d},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(e,t,i){t.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(e,t,i){t.exports=function(e,t){var i,n,s,r,o,a,l,c,h,d,u,p,f,m,g,w,y,_,b,v,x,S,C,T,A;i=e.state,n=e.next_in,T=e.input,s=n+(e.avail_in-5),r=e.next_out,A=e.output,o=r-(t-e.avail_out),a=r+(e.avail_out-257),l=i.dmax,c=i.wsize,h=i.whave,d=i.wnext,u=i.window,p=i.hold,f=i.bits,m=i.lencode,g=i.distcode,w=(1<<i.lenbits)-1,y=(1<<i.distbits)-1;e:do{f<15&&(p+=T[n++]<<f,f+=8,p+=T[n++]<<f,f+=8),_=m[p&w];t:for(;;){if(p>>>=b=_>>>24,f-=b,0==(b=_>>>16&255))A[r++]=65535&_;else{if(!(16&b)){if(!(64&b)){_=m[(65535&_)+(p&(1<<b)-1)];continue t}if(32&b){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}v=65535&_,(b&=15)&&(f<b&&(p+=T[n++]<<f,f+=8),v+=p&(1<<b)-1,p>>>=b,f-=b),f<15&&(p+=T[n++]<<f,f+=8,p+=T[n++]<<f,f+=8),_=g[p&y];i:for(;;){if(p>>>=b=_>>>24,f-=b,!(16&(b=_>>>16&255))){if(!(64&b)){_=g[(65535&_)+(p&(1<<b)-1)];continue i}e.msg="invalid distance code",i.mode=30;break e}if(x=65535&_,f<(b&=15)&&(p+=T[n++]<<f,(f+=8)<b&&(p+=T[n++]<<f,f+=8)),l<(x+=p&(1<<b)-1)){e.msg="invalid distance too far back",i.mode=30;break e}if(p>>>=b,f-=b,(b=r-o)<x){if(h<(b=x-b)&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(C=u,(S=0)===d){if(S+=c-b,b<v){for(v-=b;A[r++]=u[S++],--b;);S=r-x,C=A}}else if(d<b){if(S+=c+d-b,(b-=d)<v){for(v-=b;A[r++]=u[S++],--b;);if(S=0,d<v){for(v-=b=d;A[r++]=u[S++],--b;);S=r-x,C=A}}}else if(S+=d-b,b<v){for(v-=b;A[r++]=u[S++],--b;);S=r-x,C=A}for(;2<v;)A[r++]=C[S++],A[r++]=C[S++],A[r++]=C[S++],v-=3;v&&(A[r++]=C[S++],1<v&&(A[r++]=C[S++]))}else{for(S=r-x;A[r++]=A[S++],A[r++]=A[S++],A[r++]=A[S++],2<(v-=3););v&&(A[r++]=A[S++],1<v&&(A[r++]=A[S++]))}break}}break}}while(n<s&&r<a);n-=v=f>>3,p&=(1<<(f-=v<<3))-1,e.next_in=n,e.next_out=r,e.avail_in=n<s?s-n+5:5-(n-s),e.avail_out=r<a?a-r+257:257-(r-a),i.hold=p,i.bits=f}},{}],49:[function(e,t,i){var n=e("../utils/common"),s=e("./adler32"),r=e("./crc32"),o=e("./inffast"),a=e("./inftrees"),l=1,c=2,h=0,d=-2,u=1,p=852,f=592;function m(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new n.Buf16(320),this.work=new n.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function w(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=u,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new n.Buf32(p),t.distcode=t.distdyn=new n.Buf32(f),t.sane=1,t.back=-1,h):d}function y(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,w(e)):d}function _(e,t){var i,n;return e&&e.state?(n=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||15<t)?d:(null!==n.window&&n.wbits!==t&&(n.window=null),n.wrap=i,n.wbits=t,y(e))):d}function b(e,t){var i,n;return e?(n=new g,(e.state=n).window=null,(i=_(e,t))!==h&&(e.state=null),i):d}var v,x,S=!0;function C(e){if(S){var t;for(v=new n.Buf32(512),x=new n.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(l,e.lens,0,288,v,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(c,e.lens,0,32,x,0,e.work,{bits:5}),S=!1}e.lencode=v,e.lenbits=9,e.distcode=x,e.distbits=5}function T(e,t,i,s){var r,o=e.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new n.Buf8(o.wsize)),s>=o.wsize?(n.arraySet(o.window,t,i-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(s<(r=o.wsize-o.wnext)&&(r=s),n.arraySet(o.window,t,i-s,r,o.wnext),(s-=r)?(n.arraySet(o.window,t,i-s,s,0),o.wnext=s,o.whave=o.wsize):(o.wnext+=r,o.wnext===o.wsize&&(o.wnext=0),o.whave<o.wsize&&(o.whave+=r))),0}i.inflateReset=y,i.inflateReset2=_,i.inflateResetKeep=w,i.inflateInit=function(e){return b(e,15)},i.inflateInit2=b,i.inflate=function(e,t){var i,p,f,g,w,y,_,b,v,x,S,A,E,M,P,I,z,D,k,B,O,V,L,N,F=0,R=new n.Buf8(4),U=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return d;12===(i=e.state).mode&&(i.mode=13),w=e.next_out,f=e.output,_=e.avail_out,g=e.next_in,p=e.input,y=e.avail_in,b=i.hold,v=i.bits,x=y,S=_,V=h;e:for(;;)switch(i.mode){case u:if(0===i.wrap){i.mode=13;break}for(;v<16;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(2&i.wrap&&35615===b){R[i.check=0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0),v=b=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&b)<<8)+(b>>8))%31){e.msg="incorrect header check",i.mode=30;break}if(8!=(15&b)){e.msg="unknown compression method",i.mode=30;break}if(v-=4,O=8+(15&(b>>>=4)),0===i.wbits)i.wbits=O;else if(O>i.wbits){e.msg="invalid window size",i.mode=30;break}i.dmax=1<<O,e.adler=i.check=1,i.mode=512&b?10:12,v=b=0;break;case 2:for(;v<16;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(i.flags=b,8!=(255&i.flags)){e.msg="unknown compression method",i.mode=30;break}if(57344&i.flags){e.msg="unknown header flags set",i.mode=30;break}i.head&&(i.head.text=b>>8&1),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0,i.mode=3;case 3:for(;v<32;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}i.head&&(i.head.time=b),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,R[2]=b>>>16&255,R[3]=b>>>24&255,i.check=r(i.check,R,4,0)),v=b=0,i.mode=4;case 4:for(;v<16;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}i.head&&(i.head.xflags=255&b,i.head.os=b>>8),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0,i.mode=5;case 5:if(1024&i.flags){for(;v<16;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}i.length=b,i.head&&(i.head.extra_len=b),512&i.flags&&(R[0]=255&b,R[1]=b>>>8&255,i.check=r(i.check,R,2,0)),v=b=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(y<(A=i.length)&&(A=y),A&&(i.head&&(O=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),n.arraySet(i.head.extra,p,g,A,O)),512&i.flags&&(i.check=r(i.check,p,A,g)),y-=A,g+=A,i.length-=A),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===y)break e;for(A=0;O=p[g+A++],i.head&&O&&i.length<65536&&(i.head.name+=String.fromCharCode(O)),O&&A<y;);if(512&i.flags&&(i.check=r(i.check,p,A,g)),y-=A,g+=A,O)break e}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===y)break e;for(A=0;O=p[g+A++],i.head&&O&&i.length<65536&&(i.head.comment+=String.fromCharCode(O)),O&&A<y;);if(512&i.flags&&(i.check=r(i.check,p,A,g)),y-=A,g+=A,O)break e}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;v<16;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(b!==(65535&i.check)){e.msg="header crc mismatch",i.mode=30;break}v=b=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=12;break;case 10:for(;v<32;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}e.adler=i.check=m(b),v=b=0,i.mode=11;case 11:if(0===i.havedict)return e.next_out=w,e.avail_out=_,e.next_in=g,e.avail_in=y,i.hold=b,i.bits=v,2;e.adler=i.check=1,i.mode=12;case 12:if(5===t||6===t)break e;case 13:if(i.last){b>>>=7&v,v-=7&v,i.mode=27;break}for(;v<3;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}switch(i.last=1&b,v-=1,3&(b>>>=1)){case 0:i.mode=14;break;case 1:if(C(i),i.mode=20,6!==t)break;b>>>=2,v-=2;break e;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=30}b>>>=2,v-=2;break;case 14:for(b>>>=7&v,v-=7&v;v<32;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if((65535&b)!=(b>>>16^65535)){e.msg="invalid stored block lengths",i.mode=30;break}if(i.length=65535&b,v=b=0,i.mode=15,6===t)break e;case 15:i.mode=16;case 16:if(A=i.length){if(y<A&&(A=y),_<A&&(A=_),0===A)break e;n.arraySet(f,p,g,A,w),y-=A,g+=A,_-=A,w+=A,i.length-=A;break}i.mode=12;break;case 17:for(;v<14;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(i.nlen=257+(31&b),b>>>=5,v-=5,i.ndist=1+(31&b),b>>>=5,v-=5,i.ncode=4+(15&b),b>>>=4,v-=4,286<i.nlen||30<i.ndist){e.msg="too many length or distance symbols",i.mode=30;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;v<3;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}i.lens[U[i.have++]]=7&b,b>>>=3,v-=3}for(;i.have<19;)i.lens[U[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,L={bits:i.lenbits},V=a(0,i.lens,0,19,i.lencode,0,i.work,L),i.lenbits=L.bits,V){e.msg="invalid code lengths set",i.mode=30;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;I=(F=i.lencode[b&(1<<i.lenbits)-1])>>>16&255,z=65535&F,!((P=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(z<16)b>>>=P,v-=P,i.lens[i.have++]=z;else{if(16===z){for(N=P+2;v<N;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(b>>>=P,v-=P,0===i.have){e.msg="invalid bit length repeat",i.mode=30;break}O=i.lens[i.have-1],A=3+(3&b),b>>>=2,v-=2}else if(17===z){for(N=P+3;v<N;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}v-=P,O=0,A=3+(7&(b>>>=P)),b>>>=3,v-=3}else{for(N=P+7;v<N;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}v-=P,O=0,A=11+(127&(b>>>=P)),b>>>=7,v-=7}if(i.have+A>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=30;break}for(;A--;)i.lens[i.have++]=O}}if(30===i.mode)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=30;break}if(i.lenbits=9,L={bits:i.lenbits},V=a(l,i.lens,0,i.nlen,i.lencode,0,i.work,L),i.lenbits=L.bits,V){e.msg="invalid literal/lengths set",i.mode=30;break}if(i.distbits=6,i.distcode=i.distdyn,L={bits:i.distbits},V=a(c,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,L),i.distbits=L.bits,V){e.msg="invalid distances set",i.mode=30;break}if(i.mode=20,6===t)break e;case 20:i.mode=21;case 21:if(6<=y&&258<=_){e.next_out=w,e.avail_out=_,e.next_in=g,e.avail_in=y,i.hold=b,i.bits=v,o(e,S),w=e.next_out,f=e.output,_=e.avail_out,g=e.next_in,p=e.input,y=e.avail_in,b=i.hold,v=i.bits,12===i.mode&&(i.back=-1);break}for(i.back=0;I=(F=i.lencode[b&(1<<i.lenbits)-1])>>>16&255,z=65535&F,!((P=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(I&&!(240&I)){for(D=P,k=I,B=z;I=(F=i.lencode[B+((b&(1<<D+k)-1)>>D)])>>>16&255,z=65535&F,!(D+(P=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}b>>>=D,v-=D,i.back+=D}if(b>>>=P,v-=P,i.back+=P,i.length=z,0===I){i.mode=26;break}if(32&I){i.back=-1,i.mode=12;break}if(64&I){e.msg="invalid literal/length code",i.mode=30;break}i.extra=15&I,i.mode=22;case 22:if(i.extra){for(N=i.extra;v<N;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}i.length+=b&(1<<i.extra)-1,b>>>=i.extra,v-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;I=(F=i.distcode[b&(1<<i.distbits)-1])>>>16&255,z=65535&F,!((P=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(!(240&I)){for(D=P,k=I,B=z;I=(F=i.distcode[B+((b&(1<<D+k)-1)>>D)])>>>16&255,z=65535&F,!(D+(P=F>>>24)<=v);){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}b>>>=D,v-=D,i.back+=D}if(b>>>=P,v-=P,i.back+=P,64&I){e.msg="invalid distance code",i.mode=30;break}i.offset=z,i.extra=15&I,i.mode=24;case 24:if(i.extra){for(N=i.extra;v<N;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}i.offset+=b&(1<<i.extra)-1,b>>>=i.extra,v-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=30;break}i.mode=25;case 25:if(0===_)break e;if(A=S-_,i.offset>A){if((A=i.offset-A)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=30;break}E=A>i.wnext?(A-=i.wnext,i.wsize-A):i.wnext-A,A>i.length&&(A=i.length),M=i.window}else M=f,E=w-i.offset,A=i.length;for(_<A&&(A=_),_-=A,i.length-=A;f[w++]=M[E++],--A;);0===i.length&&(i.mode=21);break;case 26:if(0===_)break e;f[w++]=i.length,_--,i.mode=21;break;case 27:if(i.wrap){for(;v<32;){if(0===y)break e;y--,b|=p[g++]<<v,v+=8}if(S-=_,e.total_out+=S,i.total+=S,S&&(e.adler=i.check=i.flags?r(i.check,f,S,w-S):s(i.check,f,S,w-S)),S=_,(i.flags?b:m(b))!==i.check){e.msg="incorrect data check",i.mode=30;break}v=b=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;v<32;){if(0===y)break e;y--,b+=p[g++]<<v,v+=8}if(b!==(4294967295&i.total)){e.msg="incorrect length check",i.mode=30;break}v=b=0}i.mode=29;case 29:V=1;break e;case 30:V=-3;break e;case 31:return-4;default:return d}return e.next_out=w,e.avail_out=_,e.next_in=g,e.avail_in=y,i.hold=b,i.bits=v,(i.wsize||S!==e.avail_out&&i.mode<30&&(i.mode<27||4!==t))&&T(e,e.output,e.next_out,S-e.avail_out)?(i.mode=31,-4):(x-=e.avail_in,S-=e.avail_out,e.total_in+=x,e.total_out+=S,i.total+=S,i.wrap&&S&&(e.adler=i.check=i.flags?r(i.check,f,S,e.next_out-S):s(i.check,f,S,e.next_out-S)),e.data_type=i.bits+(i.last?64:0)+(12===i.mode?128:0)+(20===i.mode||15===i.mode?256:0),(0==x&&0===S||4===t)&&V===h&&(V=-5),V)},i.inflateEnd=function(e){if(!e||!e.state)return d;var t=e.state;return t.window&&(t.window=null),e.state=null,h},i.inflateGetHeader=function(e,t){var i;return e&&e.state&&2&(i=e.state).wrap?((i.head=t).done=!1,h):d},i.inflateSetDictionary=function(e,t){var i,n=t.length;return e&&e.state?0!==(i=e.state).wrap&&11!==i.mode?d:11===i.mode&&s(1,t,n,0)!==i.check?-3:T(e,t,n,n)?(i.mode=31,-4):(i.havedict=1,h):d},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(e,t,i){var n=e("../utils/common"),s=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],r=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],o=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];t.exports=function(e,t,i,l,c,h,d,u){var p,f,m,g,w,y,_,b,v,x=u.bits,S=0,C=0,T=0,A=0,E=0,M=0,P=0,I=0,z=0,D=0,k=null,B=0,O=new n.Buf16(16),V=new n.Buf16(16),L=null,N=0;for(S=0;S<=15;S++)O[S]=0;for(C=0;C<l;C++)O[t[i+C]]++;for(E=x,A=15;1<=A&&0===O[A];A--);if(A<E&&(E=A),0===A)return c[h++]=20971520,c[h++]=20971520,u.bits=1,0;for(T=1;T<A&&0===O[T];T++);for(E<T&&(E=T),S=I=1;S<=15;S++)if(I<<=1,(I-=O[S])<0)return-1;if(0<I&&(0===e||1!==A))return-1;for(V[1]=0,S=1;S<15;S++)V[S+1]=V[S]+O[S];for(C=0;C<l;C++)0!==t[i+C]&&(d[V[t[i+C]]++]=C);if(y=0===e?(k=L=d,19):1===e?(k=s,B-=257,L=r,N-=257,256):(k=o,L=a,-1),S=T,w=h,P=C=D=0,m=-1,g=(z=1<<(M=E))-1,1===e&&852<z||2===e&&592<z)return 1;for(;;){for(_=S-P,v=d[C]<y?(b=0,d[C]):d[C]>y?(b=L[N+d[C]],k[B+d[C]]):(b=96,0),p=1<<S-P,T=f=1<<M;c[w+(D>>P)+(f-=p)]=_<<24|b<<16|v,0!==f;);for(p=1<<S-1;D&p;)p>>=1;if(0!==p?(D&=p-1,D+=p):D=0,C++,0==--O[S]){if(S===A)break;S=t[i+d[C]]}if(E<S&&(D&g)!==m){for(0===P&&(P=E),w+=T,I=1<<(M=S-P);M+P<A&&!((I-=O[M+P])<=0);)M++,I<<=1;if(z+=1<<M,1===e&&852<z||2===e&&592<z)return 1;c[m=D&g]=E<<24|M<<16|w-h}}return 0!==D&&(c[w+D]=S-P<<24|64<<16),u.bits=E,0}},{"../utils/common":41}],51:[function(e,t,i){t.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(e,t,i){var n=e("../utils/common"),s=0,r=1;function o(e){for(var t=e.length;0<=--t;)e[t]=0}var a=0,l=29,c=256,h=c+1+l,d=30,u=19,p=2*h+1,f=15,m=16,g=7,w=256,y=16,_=17,b=18,v=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],x=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],S=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],C=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],T=new Array(2*(h+2));o(T);var A=new Array(2*d);o(A);var E=new Array(512);o(E);var M=new Array(256);o(M);var P=new Array(l);o(P);var I,z,D,k=new Array(d);function B(e,t,i,n,s){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=n,this.max_length=s,this.has_stree=e&&e.length}function O(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function V(e){return e<256?E[e]:E[256+(e>>>7)]}function L(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function N(e,t,i){e.bi_valid>m-i?(e.bi_buf|=t<<e.bi_valid&65535,L(e,e.bi_buf),e.bi_buf=t>>m-e.bi_valid,e.bi_valid+=i-m):(e.bi_buf|=t<<e.bi_valid&65535,e.bi_valid+=i)}function F(e,t,i){N(e,i[2*t],i[2*t+1])}function R(e,t){for(var i=0;i|=1&e,e>>>=1,i<<=1,0<--t;);return i>>>1}function U(e,t,i){var n,s,r=new Array(f+1),o=0;for(n=1;n<=f;n++)r[n]=o=o+i[n-1]<<1;for(s=0;s<=t;s++){var a=e[2*s+1];0!==a&&(e[2*s]=R(r[a]++,a))}}function j(e){var t;for(t=0;t<h;t++)e.dyn_ltree[2*t]=0;for(t=0;t<d;t++)e.dyn_dtree[2*t]=0;for(t=0;t<u;t++)e.bl_tree[2*t]=0;e.dyn_ltree[2*w]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function $(e){8<e.bi_valid?L(e,e.bi_buf):0<e.bi_valid&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function W(e,t,i,n){var s=2*t,r=2*i;return e[s]<e[r]||e[s]===e[r]&&n[t]<=n[i]}function G(e,t,i){for(var n=e.heap[i],s=i<<1;s<=e.heap_len&&(s<e.heap_len&&W(t,e.heap[s+1],e.heap[s],e.depth)&&s++,!W(t,n,e.heap[s],e.depth));)e.heap[i]=e.heap[s],i=s,s<<=1;e.heap[i]=n}function H(e,t,i){var n,s,r,o,a=0;if(0!==e.last_lit)for(;n=e.pending_buf[e.d_buf+2*a]<<8|e.pending_buf[e.d_buf+2*a+1],s=e.pending_buf[e.l_buf+a],a++,0===n?F(e,s,t):(F(e,(r=M[s])+c+1,t),0!==(o=v[r])&&N(e,s-=P[r],o),F(e,r=V(--n),i),0!==(o=x[r])&&N(e,n-=k[r],o)),a<e.last_lit;);F(e,w,t)}function q(e,t){var i,n,s,r=t.dyn_tree,o=t.stat_desc.static_tree,a=t.stat_desc.has_stree,l=t.stat_desc.elems,c=-1;for(e.heap_len=0,e.heap_max=p,i=0;i<l;i++)0!==r[2*i]?(e.heap[++e.heap_len]=c=i,e.depth[i]=0):r[2*i+1]=0;for(;e.heap_len<2;)r[2*(s=e.heap[++e.heap_len]=c<2?++c:0)]=1,e.depth[s]=0,e.opt_len--,a&&(e.static_len-=o[2*s+1]);for(t.max_code=c,i=e.heap_len>>1;1<=i;i--)G(e,r,i);for(s=l;i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],G(e,r,1),n=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=n,r[2*s]=r[2*i]+r[2*n],e.depth[s]=(e.depth[i]>=e.depth[n]?e.depth[i]:e.depth[n])+1,r[2*i+1]=r[2*n+1]=s,e.heap[1]=s++,G(e,r,1),2<=e.heap_len;);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,n,s,r,o,a,l=t.dyn_tree,c=t.max_code,h=t.stat_desc.static_tree,d=t.stat_desc.has_stree,u=t.stat_desc.extra_bits,m=t.stat_desc.extra_base,g=t.stat_desc.max_length,w=0;for(r=0;r<=f;r++)e.bl_count[r]=0;for(l[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<p;i++)g<(r=l[2*l[2*(n=e.heap[i])+1]+1]+1)&&(r=g,w++),l[2*n+1]=r,c<n||(e.bl_count[r]++,o=0,m<=n&&(o=u[n-m]),a=l[2*n],e.opt_len+=a*(r+o),d&&(e.static_len+=a*(h[2*n+1]+o)));if(0!==w){do{for(r=g-1;0===e.bl_count[r];)r--;e.bl_count[r]--,e.bl_count[r+1]+=2,e.bl_count[g]--,w-=2}while(0<w);for(r=g;0!==r;r--)for(n=e.bl_count[r];0!==n;)c<(s=e.heap[--i])||(l[2*s+1]!==r&&(e.opt_len+=(r-l[2*s+1])*l[2*s],l[2*s+1]=r),n--)}}(e,t),U(r,c,e.bl_count)}function Z(e,t,i){var n,s,r=-1,o=t[1],a=0,l=7,c=4;for(0===o&&(l=138,c=3),t[2*(i+1)+1]=65535,n=0;n<=i;n++)s=o,o=t[2*(n+1)+1],++a<l&&s===o||(a<c?e.bl_tree[2*s]+=a:0!==s?(s!==r&&e.bl_tree[2*s]++,e.bl_tree[2*y]++):a<=10?e.bl_tree[2*_]++:e.bl_tree[2*b]++,r=s,c=(a=0)===o?(l=138,3):s===o?(l=6,3):(l=7,4))}function Y(e,t,i){var n,s,r=-1,o=t[1],a=0,l=7,c=4;for(0===o&&(l=138,c=3),n=0;n<=i;n++)if(s=o,o=t[2*(n+1)+1],!(++a<l&&s===o)){if(a<c)for(;F(e,s,e.bl_tree),0!=--a;);else 0!==s?(s!==r&&(F(e,s,e.bl_tree),a--),F(e,y,e.bl_tree),N(e,a-3,2)):a<=10?(F(e,_,e.bl_tree),N(e,a-3,3)):(F(e,b,e.bl_tree),N(e,a-11,7));r=s,c=(a=0)===o?(l=138,3):s===o?(l=6,3):(l=7,4)}}o(k);var X=!1;function K(e,t,i,s){var r,o,l;N(e,(a<<1)+(s?1:0),3),o=t,l=i,$(r=e),L(r,l),L(r,~l),n.arraySet(r.pending_buf,r.window,o,l,r.pending),r.pending+=l}i._tr_init=function(e){X||(function(){var e,t,i,n,s,r=new Array(f+1);for(n=i=0;n<l-1;n++)for(P[n]=i,e=0;e<1<<v[n];e++)M[i++]=n;for(M[i-1]=n,n=s=0;n<16;n++)for(k[n]=s,e=0;e<1<<x[n];e++)E[s++]=n;for(s>>=7;n<d;n++)for(k[n]=s<<7,e=0;e<1<<x[n]-7;e++)E[256+s++]=n;for(t=0;t<=f;t++)r[t]=0;for(e=0;e<=143;)T[2*e+1]=8,e++,r[8]++;for(;e<=255;)T[2*e+1]=9,e++,r[9]++;for(;e<=279;)T[2*e+1]=7,e++,r[7]++;for(;e<=287;)T[2*e+1]=8,e++,r[8]++;for(U(T,h+1,r),e=0;e<d;e++)A[2*e+1]=5,A[2*e]=R(e,5);I=new B(T,v,c+1,h,f),z=new B(A,x,0,d,f),D=new B(new Array(0),S,0,u,g)}(),X=!0),e.l_desc=new O(e.dyn_ltree,I),e.d_desc=new O(e.dyn_dtree,z),e.bl_desc=new O(e.bl_tree,D),e.bi_buf=0,e.bi_valid=0,j(e)},i._tr_stored_block=K,i._tr_flush_block=function(e,t,i,n){var o,a,l=0;0<e.level?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return s;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return r;for(t=32;t<c;t++)if(0!==e.dyn_ltree[2*t])return r;return s}(e)),q(e,e.l_desc),q(e,e.d_desc),l=function(e){var t;for(Z(e,e.dyn_ltree,e.l_desc.max_code),Z(e,e.dyn_dtree,e.d_desc.max_code),q(e,e.bl_desc),t=u-1;3<=t&&0===e.bl_tree[2*C[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),o=e.opt_len+3+7>>>3,(a=e.static_len+3+7>>>3)<=o&&(o=a)):o=a=i+5,i+4<=o&&-1!==t?K(e,t,i,n):4===e.strategy||a===o?(N(e,2+(n?1:0),3),H(e,T,A)):(N(e,4+(n?1:0),3),function(e,t,i,n){var s;for(N(e,t-257,5),N(e,i-1,5),N(e,n-4,4),s=0;s<n;s++)N(e,e.bl_tree[2*C[s]+1],3);Y(e,e.dyn_ltree,t-1),Y(e,e.dyn_dtree,i-1)}(e,e.l_desc.max_code+1,e.d_desc.max_code+1,l+1),H(e,e.dyn_ltree,e.dyn_dtree)),j(e),n&&$(e)},i._tr_tally=function(e,t,i){return e.pending_buf[e.d_buf+2*e.last_lit]=t>>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(M[i]+c+1)]++,e.dyn_dtree[2*V(t)]++),e.last_lit===e.lit_bufsize-1},i._tr_align=function(e){var t;N(e,2,3),F(e,w,T),16===(t=e).bi_valid?(L(t,t.bi_buf),t.bi_buf=0,t.bi_valid=0):8<=t.bi_valid&&(t.pending_buf[t.pending++]=255&t.bi_buf,t.bi_buf>>=8,t.bi_valid-=8)}},{"../utils/common":41}],53:[function(e,t,i){t.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(e,t,i){(function(e){!function(e,t){if(!e.setImmediate){var i,n,s,r,o=1,a={},l=!1,c=e.document,h=Object.getPrototypeOf&&Object.getPrototypeOf(e);h=h&&h.setTimeout?h:e,i="[object process]"==={}.toString.call(e.process)?function(e){process.nextTick(function(){u(e)})}:function(){if(e.postMessage&&!e.importScripts){var t=!0,i=e.onmessage;return e.onmessage=function(){t=!1},e.postMessage("","*"),e.onmessage=i,t}}()?(r="setImmediate$"+Math.random()+"$",e.addEventListener?e.addEventListener("message",p,!1):e.attachEvent("onmessage",p),function(t){e.postMessage(r+t,"*")}):e.MessageChannel?((s=new MessageChannel).port1.onmessage=function(e){u(e.data)},function(e){s.port2.postMessage(e)}):c&&"onreadystatechange"in c.createElement("script")?(n=c.documentElement,function(e){var t=c.createElement("script");t.onreadystatechange=function(){u(e),t.onreadystatechange=null,n.removeChild(t),t=null},n.appendChild(t)}):function(e){setTimeout(u,0,e)},h.setImmediate=function(e){"function"!=typeof e&&(e=new Function(""+e));for(var t=new Array(arguments.length-1),n=0;n<t.length;n++)t[n]=arguments[n+1];var s={callback:e,args:t};return a[o]=s,i(o),o++},h.clearImmediate=d}function d(e){delete a[e]}function u(e){if(l)setTimeout(u,0,e);else{var i=a[e];if(i){l=!0;try{!function(e){var i=e.callback,n=e.args;switch(n.length){case 0:i();break;case 1:i(n[0]);break;case 2:i(n[0],n[1]);break;case 3:i(n[0],n[1],n[2]);break;default:i.apply(t,n)}}(i)}finally{d(e),l=!1}}}}function p(t){t.source===e&&"string"==typeof t.data&&0===t.data.indexOf(r)&&u(+t.data.slice(r.length))}}("undefined"==typeof self?void 0===e?this:e:self)}).call(this,void 0!==Yr?Yr:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10));class eo{constructor(e,i){t(this,"date",new Date),t(this,"author"),t(this,"guid",T.create()),t(this,"viewpoint"),t(this,"modifiedAuthor"),t(this,"modifiedDate"),t(this,"topic"),t(this,"_components"),t(this,"_comment",""),this._components=e,this._comment=i;const n=this._components.get(oo);this.author=n.config.author}set comment(e){var t;const i=this._components.get(oo);this._comment=e,this.modifiedDate=new Date,this.modifiedAuthor=i.config.author,null==(t=this.topic)||t.comments.set(this.guid,this)}get comment(){return this._comment}toJSON(){var e,t;const i={guid:this.guid,date:this.date.toISOString(),author:this.author,comment:this.comment,topic_guid:null==(e=this.topic)?void 0:e.guid,viewpoint_guid:this.viewpoint,modified_date:null==(t=this.modifiedDate)?void 0:t.toISOString(),modified_author:this.modifiedAuthor};for(const[e,t]of Object.entries(i))void 0===t&&delete i[e];return i}}const to=class e{constructor(n){t(this,"guid",T.create()),t(this,"title",e.default.title),t(this,"creationDate",new Date),t(this,"creationAuthor",""),t(this,"viewpoints",new i.DataSet),t(this,"relatedTopics",new i.DataSet),t(this,"comments",new i.DataMap),t(this,"documentReferences",new i.DataSet),t(this,"customData",{}),t(this,"description"),t(this,"serverAssignedId"),t(this,"dueDate"),t(this,"modifiedAuthor"),t(this,"modifiedDate"),t(this,"index"),t(this,"_type",e.default.type),t(this,"_status",e.default.status),t(this,"_priority",e.default.priority),t(this,"_stage",e.default.stage),t(this,"_assignedTo",e.default.assignedTo),t(this,"_labels",e.default.labels??new Set),t(this,"_components"),this._components=n;const s=n.get(oo);this.creationAuthor=s.config.author,this.relatedTopics.guard=e=>e!==this.guid}set type(e){const t=this._components.get(oo),{strict:i,types:n}=t.config;(!i||n.has(e))&&(this._type=e)}get type(){return this._type}set status(e){const t=this._components.get(oo),{strict:i,statuses:n}=t.config;(!i||n.has(e))&&(this._status=e)}get status(){return this._status}set priority(e){const t=this._components.get(oo);if(e){const{strict:i,priorities:n}=t.config;if(!(!i||n.has(e)))return;this._priority=e}else this._priority=e}get priority(){return this._priority}set stage(e){const t=this._components.get(oo);if(e){const{strict:i,stages:n}=t.config;if(!(!i||n.has(e)))return;this._stage=e}else this._stage=e}get stage(){return this._stage}set assignedTo(e){const t=this._components.get(oo);if(e){const{strict:i,users:n}=t.config;if(!(!i||n.has(e)))return;this._assignedTo=e}else this._assignedTo=e}get assignedTo(){return this._assignedTo}set labels(e){const t=this._components.get(oo),{strict:i,labels:n}=t.config;if(i){const t=new Set;for(const s of e){(!i||n.has(s))&&t.add(s)}this._labels=t}else this._labels=e}get labels(){return this._labels}get _managerVersion(){return this._components.get(oo).config.version}set(e){const t=e,i=this;for(const n in e){if("guid"===n)continue;const e=t[n];n in this&&(i[n]=e)}return this._components.get(oo).list.set(this.guid,this),this}createComment(e,t){const i=new eo(this._components,e);return i.viewpoint=t,i.topic=this,this.comments.set(i.guid,i),i}createLabelTags(){const e=[...this.labels];if(this._components.get(oo).config.exportCustomDataAsLabels)for(const t in this.customData){const i=this.customData[t];"string"==typeof i&&e.push(i)}return e}createCommentTags(){return[...this.comments.values()].map(e=>{var t;return{$Guid:e.guid,Date:e.date.toISOString(),Author:e.author,Comment:e.comment,ModifiedAuthor:e.modifiedAuthor,ModifiedDate:null==(t=e.modifiedDate)?void 0:t.toISOString(),Viewpoint:e.viewpoint?{$Guid:e.viewpoint}:void 0}})}createViewpointTags(){const e=this._components.get(mo);return[...this.viewpoints].map(t=>e.list.get(t)).filter(e=>e).map(t=>{const i={$Guid:t.guid,Viewpoint:`${t.title??t.guid}.bcfv`};if(e.snapshots.get(t.snapshot)){const n=e.getSnapshotExtension(t.snapshot);i.Snapshot=`${t.snapshot}.${n}`}return i})}createRelatedTopicTags(){return[...this.relatedTopics].map(e=>({$Guid:e}))}createDocumentReferencesTag(e=this._managerVersion){const t=[];if("3"!==e&&"2.1"!==e)return t;const i=this._components.get(oo);for(const n of this.documentReferences){const s=i.documents.get(n);if(!s)continue;let r={$Guid:T.create(),Description:s.description};"2.1"===e&&(r={...r,$isExternal:"external"===s.type||void 0,ReferencedDocument:"external"===s.type?s.url:`../${s.fileName}`}),"3"===e&&(r={...r,DocumentGuid:"internal"===s.type?n:void 0,Url:"external"===s.type?s.url:void 0}),Object.keys(r).length>0&&t.push(r)}return t}toJSON(){var e,t;const i={guid:this.guid,server_assigned_id:this.serverAssignedId,topic_type:this.type,topic_status:this.status,title:this.title,priority:this.priority,index:this.index,labels:[...this.labels],creation_date:this.creationDate.toISOString(),creation_author:this.creationAuthor,modified_date:null==(e=this.modifiedDate)?void 0:e.toISOString(),modified_author:this.modifiedAuthor,assigned_to:this.assignedTo,stage:this.stage,description:this.description,due_date:null==(t=this.dueDate)?void 0:t.toISOString(),comments:[...this.comments].map(([e,t])=>t.toJSON()),relatedTopics:[...this.relatedTopics].map(e=>({related_topic_guid:e}))},n=this._components.get(mo);for(const e of this.viewpoints){const t=n.list.get(e);t&&(i.viewpoints||(i.viewpoints=[]),i.viewpoints.push(t.toJSON()))}const s=this._components.get(oo);for(const e of this.documentReferences){const t=s.documents.get(e);t&&(i.document_references||(i.document_references=[]),"external"===t.type?i.document_references.push({guid:T.create(),description:t.description,url:t.url}):i.document_references.push({guid:T.create(),description:t.description,document_guid:e}))}for(const[e,t]of Object.entries(i))(void 0===t||Array.isArray(t)&&0===t.length)&&delete i[e];return i}serialize(){var e,t;const i=this._managerVersion,n={$Guid:this.guid,$TopicType:this.type,$TopicStatus:this.status,$ServerAssignedId:this.serverAssignedId,Title:this.title,CreationAuthor:this.creationAuthor,CreationDate:this.creationDate.toISOString(),Priority:this.priority,Index:"2.1"===i?this.index:void 0,ModifiedDate:null==(e=this.modifiedDate)?void 0:e.toISOString(),ModifiedAuthor:this.modifiedAuthor,DueDate:null==(t=this.dueDate)?void 0:t.toISOString(),AssignedTo:this.assignedTo,Description:this.description,Stage:this.stage,DocumentReferences:"3"===i?{DocumentReference:this.createDocumentReferencesTag(i)}:void 0,RelatedTopics:"3"===i?{RelatedTopic:this.createRelatedTopicTags()}:void 0,RelatedTopic:"2.1"===i?this.createRelatedTopicTags():void 0,Labels:"3"===i?{Label:this.createLabelTags()}:void 0,Viewpoints:"3"===i?{ViewPoint:this.createViewpointTags()}:void 0,Comments:"3"===i?{Comment:this.createCommentTags()}:void 0};"2.1"===i&&(n.Labels=this.createLabelTags(),n.DocumentReference=this.createDocumentReferencesTag(i));const s={Markup:{Topic:n}};return"2.1"===i&&(s.Markup.Viewpoints=this.createViewpointTags(),s.Markup.Comment=this.createCommentTags()),`<?xml version="1.0" encoding="UTF-8"?>\n ${Re.builder.build(s)}`}};t(to,"default",{title:"BCF Topic",type:"Issue",status:"Active"});let io=to;const no=(e,t)=>{if(""===t.trim())return;const i=oo.xmlParser.parse(t).Extensions;if(!i)return;const{Priorities:n,TopicStatuses:s,TopicTypes:r,Users:o}=i;if(n&&n.Priority){const t=Array.isArray(n.Priority)?n.Priority:[n.Priority];for(const i of t)e.config.priorities.add(i)}if(s&&s.TopicStatus){const t=Array.isArray(s.TopicStatus)?s.TopicStatus:[s.TopicStatus];for(const i of t)e.config.statuses.add(i)}if(r&&r.TopicType){const t=Array.isArray(r.TopicType)?r.TopicType:[r.TopicType];for(const i of t)e.config.types.add(i)}if(o&&o.User){const t=Array.isArray(o.User)?o.User:[o.User];for(const i of t)e.config.users.add(i)}};class so extends We{constructor(){super(...arguments),t(this,"_config",{version:{type:"Select",options:new Set(["2.1","3"]),multiple:!1,value:""},author:{type:"Text",value:""},types:{type:"TextSet",value:new Set},statuses:{type:"TextSet",value:new Set},priorities:{type:"TextSet",value:new Set},labels:{type:"TextSet",value:new Set},stages:{type:"TextSet",value:new Set},users:{type:"TextSet",value:new Set},includeSelectionTag:{type:"Boolean",value:!1},updateExtensionsOnImport:{type:"Boolean",value:!1},strict:{type:"Boolean",value:!1},includeAllExtensionsOnExport:{type:"Boolean",value:!1},fallbackVersionOnImport:{type:"Select",multiple:!1,options:new Set(["2.1","3"]),value:""},ignoreIncompleteTopicsOnImport:{type:"Boolean",value:!1},exportCustomDataAsLabels:{type:"Boolean",value:!1}})}get version(){return this._config.version.value}set version(e){this._config.version.value=e}get author(){return this._config.author.value}set author(e){this._config.author.value=e}get types(){return this._config.types.value}set types(e){this._config.types.value=e}get statuses(){return this._config.statuses.value}set statuses(e){this._config.statuses.value=e}get priorities(){return this._config.priorities.value}set priorities(e){this._config.priorities.value=e}get labels(){return this._config.labels.value}set labels(e){this._config.labels.value=e}get stages(){return this._config.stages.value}set stages(e){this._config.stages.value=e}get users(){return this._config.users.value}set users(e){this._config.users.value=e}get includeSelectionTag(){return this._config.includeSelectionTag.value}set includeSelectionTag(e){this._config.includeSelectionTag.value=e}get updateExtensionsOnImport(){return this._config.updateExtensionsOnImport.value}set updateExtensionsOnImport(e){this._config.updateExtensionsOnImport.value=e}get strict(){return this._config.strict.value}set strict(e){this._config.strict.value=e}get includeAllExtensionsOnExport(){return this._config.includeAllExtensionsOnExport.value}set includeAllExtensionsOnExport(e){this._config.includeAllExtensionsOnExport.value=e}get fallbackVersionOnImport(){return this._config.fallbackVersionOnImport.value}set fallbackVersionOnImport(e){this._config.fallbackVersionOnImport.value=e}get ignoreIncompleteTopicsOnImport(){return this._config.ignoreIncompleteTopicsOnImport.value}set ignoreIncompleteTopicsOnImport(e){this._config.ignoreIncompleteTopicsOnImport.value=e}get exportCustomDataAsLabels(){return this._config.exportCustomDataAsLabels.value}set exportCustomDataAsLabels(e){this._config.exportCustomDataAsLabels.value=e}}const ro=class e extends g{constructor(){super(...arguments),t(this,"enabled",!1),t(this,"_defaultConfig",{author:"jhon.doe@example.com",version:"2.1",types:new Set(["Clash","Failure","Fault","Inquiry","Issue","Remark","Request"]),statuses:new Set(["Active","In Progress","Done","In Review","Closed"]),priorities:new Set(["On hold","Minor","Normal","Major","Critical"]),labels:new Set,stages:new Set,users:new Set,includeSelectionTag:!1,updateExtensionsOnImport:!0,strict:!1,includeAllExtensionsOnExport:!0,fallbackVersionOnImport:"2.1",ignoreIncompleteTopicsOnImport:!1,exportCustomDataAsLabels:!1}),t(this,"config",new so(this,this.components,"BCF Topics",e.uuid)),t(this,"list",new i.DataMap),t(this,"documents",new i.DataMap),t(this,"onSetup",new f),t(this,"isSetup",!1),t(this,"onBCFImported",new f),t(this,"onDisposed",new f)}setup(e){if(this.isSetup)return;const t={...this._defaultConfig,...e};this.config.version=t.version,this.config.author=t.author,this.config.types=t.types,this.config.statuses=t.statuses,this.config.priorities=t.priorities,this.config.labels=t.labels,this.config.stages=t.stages,this.config.users=t.users,this.config.includeSelectionTag=t.includeSelectionTag,this.config.updateExtensionsOnImport=t.updateExtensionsOnImport,this.config.strict=t.strict,this.config.includeAllExtensionsOnExport=t.includeAllExtensionsOnExport,this.config.fallbackVersionOnImport=t.fallbackVersionOnImport||"",this.config.ignoreIncompleteTopicsOnImport=t.ignoreIncompleteTopicsOnImport,this.isSetup=!0,this.enabled=!0,this.onSetup.trigger()}create(e){const t=new io(this.components);return e?(t.guid=e.guid??t.guid,t.set(e)):this.list.set(t.guid,t),t}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}get usedTypes(){const e=[...this.list].map(([e,t])=>t.type);return new Set(e)}get usedStatuses(){const e=[...this.list].map(([e,t])=>t.status);return new Set(e)}get usedPriorities(){const e=[...this.list].map(([e,t])=>t.priority).filter(e=>e);return new Set(e)}get usedStages(){const e=[...this.list].map(([e,t])=>t.stage).filter(e=>e);return new Set(e)}get usedUsers(){const e=[];for(const[t,i]of this.list){e.push(i.creationAuthor),i.assignedTo&&e.push(i.assignedTo),i.modifiedAuthor&&e.push(i.modifiedAuthor);for(const[t,n]of i.comments)e.push(n.author),n.modifiedAuthor&&e.push(n.modifiedAuthor)}return new Set(e)}get usedLabels(){const e=[];for(const[t,i]of this.list)e.push(...i.labels);return new Set(e)}updateExtensions(){for(const[e,t]of this.list){for(const e of t.labels)this.config.labels.add(e);this.config.types.add(t.type),t.priority&&this.config.priorities.add(t.priority),t.stage&&this.config.stages.add(t.stage),this.config.statuses.add(t.status),this.config.users.add(t.creationAuthor),t.assignedTo&&this.config.users.add(t.assignedTo),t.modifiedAuthor&&this.config.users.add(t.modifiedAuthor);for(const[e,i]of t.comments)this.config.users.add(i.author),i.modifiedAuthor&&this.config.users.add(i.modifiedAuthor)}}updateViewpointReferences(){const e=this.components.get(mo);for(const[t,i]of this.list)for(const t of i.viewpoints){e.list.has(t)||i.viewpoints.delete(t)}}async export(e=this.list.values()){const t=new Jr;t.file("bcf.version",`<?xml version="1.0" encoding="UTF-8"?>\n <Version VersionId="${this.config.version}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/release_3_0/Schemas/version.xsd"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n </Version>`);for(const[e,i]of this.documents.entries())"external"!==i.type&&t.file("2.1"===this.config.version?i.fileName:`documents/${e}`,i.data);if("3"===this.config.version){const e=[];for(const[t,i]of this.documents.entries()){const{type:n,description:s}=i;"external"!==n&&e.push(`<Document Guid="${t}">\n <Filename>${i.fileName}</Filename>\n ${s?`<Description>${s}</Description>`:""}\n </Document>`)}e.length>0&&t.file("documents.xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n <DocumentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="documents.xsd">\n <Documents>\n ${e.join("\n")}\n </Documents>\n </DocumentInfo>`)}t.file("bcf.extensions",this.serializeExtensions());const i=this.components.get(mo);for(const n of e){const e=t.folder(n.guid);e.file("markup.bcf",n.serialize());for(const t of n.viewpoints){const n=i.list.get(t);if(!n)continue;const s=n.title??n.guid;e.file(`${s}.bcfv`,await n.serialize());const r=i.snapshots.get(n.snapshot);if(!r)continue;const o=r?n.snapshot:n.guid,a=i.getSnapshotExtension(n.snapshot);e.file(`${o}.${a}`,r,{binary:!0})}}return await t.generateAsync({type:"blob"})}serializeExtensions(){const e=[...this.config.types].map(e=>`<TopicType>${e}</TopicType>`).join("\n"),t=[...this.config.statuses].map(e=>`<TopicStatus>${e}</TopicStatus>`).join("\n"),i=[...this.config.priorities].map(e=>`<Priority>${e}</Priority>`).join("\n"),n=[...this.config.labels].map(e=>`<TopicLabel>${e}</TopicLabel>`).join("\n"),s=[...this.config.stages].map(e=>`<Stage>${e}</Stage>`).join("\n"),r=[...this.config.users].map(e=>`<User>${e}</User>`).join("\n");return`\n <?xml version="1.0" encoding="UTF-8"?>\n <Extensions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-schema-location.xsd">\n ${0!==e.length?`<TopicTypes>\n${e}\n</TopicTypes>`:""}\n ${0!==t.length?`<TopicStatuses>\n${t}\n</TopicStatuses>`:""}\n ${0!==i.length?`<Priorities>\n${i}\n</Priorities>`:""}\n ${0!==n.length?`<TopicLabels>\n${n}\n</TopicLabels>`:""}\n ${0!==s.length?`<Stages>\n${s}\n</Stages>`:""}\n ${0!==r.length?`<Users>\n${r}\n</Users>`:""}\n </Extensions>\n `}processMarkupComment(e){const{Guid:t,Date:i,Author:n,Comment:s,Viewpoint:r}=e;if(!(t&&i&&n&&(eo||r)))return null;const o=new eo(this.components,s??"");return o.guid=t,o.date=new Date(i),o.author=n,o.viewpoint=null==r?void 0:r.Guid,o.modifiedAuthor=e.ModifiedAuthor,o.modifiedDate=e.ModifiedDate?new Date(e.ModifiedDate):void 0,o}getMarkupComments(e,t){var i;let n;if("2.1"===t&&(n=e.Comment),"3"===t&&(n=null==(i=e.Topic.Comments)?void 0:i.Comment),!n)return[];n=Array.isArray(n)?n:[n];const s=n.map(e=>this.processMarkupComment(e)).filter(e=>e);return Array.isArray(s)?s:[s]}getMarkupLabels(e,t){var i;let n;if("2.1"===t&&(n=e.Topic.Labels),"3"===t&&(n=null==(i=e.Topic.Labels)?void 0:i.Label),!n)return[];return Array.isArray(n)?n:[n]}getMarkupViewpoints(e,t){var i;let n;return"2.1"===t&&(n=e.Viewpoints),"3"===t&&(n=null==(i=e.Topic.Viewpoints)?void 0:i.ViewPoint),n?(n=Array.isArray(n)?n:[n],n):[]}getMarkupRelatedTopics(e,t){var i;let n;if("2.1"===t&&(n=e.Topic.RelatedTopic),"3"===t&&(n=null==(i=e.Topic.RelatedTopics)?void 0:i.RelatedTopic),!n)return[];return(Array.isArray(n)?n:[n]).map(e=>e.Guid)}getMarkupDocumentReferences(e,t){var i;let n;if("2.1"===t&&(n=e.Topic.DocumentReference),"3"===t&&(n=null==(i=e.Topic.DocumentReferences)?void 0:i.DocumentReference),!n)return[];return Array.isArray(n)?n:[n]}async load(t){var i,n,s;const{fallbackVersionOnImport:r,ignoreIncompleteTopicsOnImport:o,updateExtensionsOnImport:a}=this.config,l=new Jr;await l.loadAsync(t);const c=Object.values(l.files);let h=r;const u=c.find(e=>e.name.endsWith(".version"));if(u){const t=await u.async("string"),i=e.xmlParser.parse(t).Version.VersionId;h=String(i)}if(!h||"2.1"!==h&&"3"!==h)throw new Error(`BCFTopics: ${h} is not supported.`);const p=c.find(e=>e.name.endsWith(".extensions"));if(a&&p){const e=await p.async("string");no(this,e)}const f=[],m=this.components.get(mo),g=c.filter(e=>e.name.endsWith(".bcfv"));for(const t of g){const n=await t.async("string"),s=e.xmlParser.parse(n).VisualizationInfo;if(!s){console.warn("Missing VisualizationInfo in Viewpoint");continue}const r={},{Guid:o,ClippingPlanes:a,Components:l,OrthogonalCamera:c,PerspectiveCamera:u}=s;if(o&&(r.guid=o),l){const e={selection:[],coloring:[],visibility:{default_visibility:!1,exceptions:[],view_setup_hints:{spaces_visible:!1,space_boundaries_visible:!1,openings_visible:!1}}};r.components=e;const{Selection:t,Visibility:n}=l;if(t&&t.Component){const i=Array.isArray(t.Component)?t.Component:[t.Component];e.selection=i.map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e)}if(n&&"DefaultVisibility"in n&&(e.visibility.default_visibility=n.DefaultVisibility),n&&n.Exceptions&&"Component"in n.Exceptions){const{Component:t}=n.Exceptions,i=Array.isArray(t)?t:[t];e.visibility.exceptions=i.map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e)}let s;"2.1"===h&&(s=l.ViewSetupHints),"3"===h&&(s=null==(i=l.Visibility)?void 0:i.ViewSetupHints),s&&("OpeningsVisible"in s&&(e.visibility.view_setup_hints.openings_visible=s.OpeningsVisible),"SpacesVisible"in s&&(e.visibility.view_setup_hints.spaces_visible=s.SpacesVisible),"SpaceBoundariesVisible"in s&&(e.visibility.view_setup_hints.space_boundaries_visible=s.SpaceBoundariesVisible));const{Coloring:o}=l;if(o&&o.Color){const t=Array.isArray(o.Color)?o.Color:[o.Color];for(const i of t){const{Color:t,Component:n}=i;if(6!==t.length&&8!==t.length)continue;const s=6===t.length?t:t.slice(2),r=(Array.isArray(n)?n:[n]).map(e=>e.IfcGuid?{ifc_guid:e.IfcGuid}:null).filter(e=>null!==e);e.coloring.push({color:s,components:r})}}}if(c||u){const e=s.PerspectiveCamera??s.OrthogonalCamera,{CameraViewPoint:t,CameraDirection:i}=e,n=new d.Vector3(Number(t.X),Number(t.Z),Number(-t.Y)),o=new d.Vector3(Number(i.X),Number(i.Z),Number(-i.Y)),a={camera_view_point:{x:n.x,y:n.y,z:n.z},camera_direction:{x:o.x,y:o.y,z:o.z},aspect_ratio:"AspectRatio"in e?e.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in e&&(r.orthogonal_camera={...a,view_to_world_scale:e.ViewToWorldScale}),"FieldOfView"in e&&(r.perspective_camera={...a,field_of_view:e.FieldOfView})}if(a){const e=(Array.isArray(a.ClippingPlane)?a.ClippingPlane:[a.ClippingPlane]).map(({Location:e,Direction:t})=>({location:{x:e.x,y:e.y,z:e.z},direction:{x:t.x,y:t.y,z:t.z}}));r.clipping_planes=e}const p=new uo(this.components,r);f.push(p)}const w={},y=[],_=c.filter(e=>e.name.endsWith(".bcf"));for(const t of _){const i=await t.async("string"),r=e.xmlParser.parse(i).Markup,a=r.Topic,{Guid:l,TopicType:d,TopicStatus:u,Title:p,CreationDate:f,CreationAuthor:g}=a;if(o&&!(l&&d&&u&&p&&f&&g))continue;const _=new io(this.components);_.guid=l??_.guid;const b=this.getMarkupRelatedTopics(r,h);w[_.guid]=new Set(b),_.type=d??_.type,_.status=u??_.status,_.title=p??_.title,_.creationDate=f?new Date(f):_.creationDate,_.creationAuthor=g??_.creationAuthor,_.serverAssignedId=a.ServerAssignedId,_.priority=a.Priority,_.index=a.Index,_.modifiedDate=a.ModifiedDate?new Date(a.ModifiedDate):void 0,_.modifiedAuthor=a.ModifiedAuthor,_.dueDate=a.DueDate?new Date(a.DueDate):void 0,_.assignedTo=a.AssignedTo,_.description=a.Description,_.stage=a.Stage;const v=this.getMarkupLabels(r,h);for(const e of v)_.labels.add(e);const x=this.getMarkupComments(r,h);for(const e of x)_.comments.set(e.guid,e);const S=this.getMarkupViewpoints(r,h);for(const e of S){if(!e||!e.Guid)continue;const t=m.list.get(e.Guid);if(!t)continue;_.viewpoints.add(t.guid);const i=`${_.guid}/${e.Snapshot}`,n=c.find(({name:e})=>e===i);if(n){const e=await n.async("arraybuffer"),i=new Uint8Array(e);m.snapshots.set(t.guid,i),t.snapshot=t.guid??null}}const C=this.getMarkupDocumentReferences(r,h),T=c.find(e=>"documents.xml"===e.name);let A=[];const E=await(null==T?void 0:T.async("string"));if(E){const e=null==(s=null==(n=Re.parser.parse(E).DocumentInfo)?void 0:n.Documents)?void 0:s.Document;A=Array.isArray(e)?e:[e]}for(const e of C){const{Description:t,DocumentGuid:i,Url:n,isExternal:s,ReferencedDocument:r}=e;if(i&&A.length>0){const e=A.find(({Guid:e})=>e===i),t=c.find(e=>e.name.endsWith(i)),n=await(null==t?void 0:t.async("uint8array"));if(!e||!n)continue;const{Description:s,Filename:r}=e;this.documents.set(i,{type:"internal",fileName:r,description:s,data:n}),_.documentReferences.add(i)}if(n){const e=this.documents.add({type:"external",url:n,description:t});_.documentReferences.add(e)}if(r){let e=null;if(s)e=this.documents.add({type:"external",url:r,description:t});else{const i=r.split("/"),n=i[i.length-1],s=c.find(e=>e.name.endsWith(n)),o=await(null==s?void 0:s.async("uint8array"));if(!o)continue;e=this.documents.add({type:"internal",fileName:n,data:o,description:t})}_.documentReferences.add(e)}}this.list.set(_.guid,_),y.push(_)}for(const e in w){const t=this.list.get(e);if(!t)continue;const i=w[e];for(const e of i)t.relatedTopics.add(e)}return this.onBCFImported.trigger(y),{viewpoints:f,topics:y}}};t(ro,"uuid","de977976-e4f6-4e4f-a01a-204727839802"),t(ro,"xmlParser",new Me({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let oo=ro;class ao{constructor(e,i,n,s,r,o=5,a=!0){var l;if(t(this,"onDraggingStarted",new f),t(this,"onDraggingEnded",new f),t(this,"onDisposed",new f),t(this,"normal"),t(this,"origin"),t(this,"three",new d.Plane),t(this,"components"),t(this,"world"),t(this,"type","default"),t(this,"_title","Clipping Plane"),t(this,"_helper"),t(this,"_visible",!0),t(this,"_enabled",!0),t(this,"_controlsActive",!1),t(this,"_arrowBoundBox",new d.Mesh),t(this,"_planeMesh"),t(this,"_controls"),t(this,"_hiddenMaterial",new d.MeshBasicMaterial({visible:!1})),t(this,"_sizeMultiplier",5),t(this,"_autoScale",!0),t(this,"_visibilityBeforeDisabled",!0),t(this,"notifyManager",()=>{const e=this.components.get(ho),t=e.list.getKey(this);t&&e.list.set(t,this)}),t(this,"update",()=>{this._enabled&&(this.three.setFromNormalAndCoplanarPoint(this.normal,this._helper.position),this.updateScale())}),t(this,"updateScale",()=>{var e;if(!this.autoScale)return;const t=null==(e=this.world.camera)?void 0:e.three;if(!t)return;if(!(t instanceof d.PerspectiveCamera))return;const i=new d.Vector3;t.getWorldPosition(i);const n=i.distanceTo(this._helper.position)/7*this._sizeMultiplier;this._planeMesh.scale.set(n,n,n)}),t(this,"changeDrag",e=>{this._visible=!e.value,this.preventCameraMovement(),this.notifyDraggingChanged(e)}),this.components=e,this.world=i,!i.renderer)throw new Error("The given world must have a renderer!");this.normal=s,this.origin=n,this._sizeMultiplier=o,i.renderer.setPlane(!0,this.three),this._planeMesh=ao.newPlaneMesh(o,r),this._helper=this.newHelper(),this._controls=this.newTransformControls(),this.three.setFromNormalAndCoplanarPoint(s,n),a&&this.toggleControls(!0),this.updateScale(),(null==(l=i.camera)?void 0:l.controls)&&i.camera.controls.addEventListener("update",this.updateScale)}set title(e){this._title=e,this.notifyManager()}get title(){return this._title}get autoScale(){return this._autoScale}set autoScale(e){this._autoScale=e,e&&this.updateScale()}get enabled(){return this._enabled}set enabled(e){if(!this.world.isDisposing){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");this._enabled=e,e?this.visible=this._visibilityBeforeDisabled:(this._visibilityBeforeDisabled=this.visible,this.visible=!1),this.world.renderer.setPlane(e,this.three),this.notifyManager()}}get visible(){return this._visible}set visible(e){this._visible=e,this._controls.getHelper().visible=e,this._helper.visible=e,this.toggleControls(e),this.notifyManager()}get meshes(){return[this._planeMesh,this._arrowBoundBox]}get planeMaterial(){return this._planeMesh.material}set planeMaterial(e){this._planeMesh.material=e}get size(){return this._sizeMultiplier}set size(e){this._sizeMultiplier=e,this.autoScale?this.updateScale():this._planeMesh.scale.set(e,e,e)}get helper(){return this._helper}get controls(){return this._controls}setFromNormalAndCoplanarPoint(e,t){this.reset(),this.normal.equals(e)||(this.normal.copy(e),this._helper.lookAt(e)),this.origin.copy(t),this._helper.position.copy(t),this._helper.updateMatrix(),this.update()}dispose(){var e;this._enabled=!1,(null==(e=this.world.camera)?void 0:e.controls)&&this.world.camera.controls.removeEventListener("update",this.updateScale),this.onDraggingStarted.reset(),this.onDraggingEnded.reset(),this._helper.removeFromParent(),this.world.renderer&&this.world.renderer.setPlane(!1,this.three),this._arrowBoundBox.removeFromParent(),this._arrowBoundBox.geometry.dispose(),this._planeMesh.geometry.dispose(),this._controls.getHelper().removeFromParent(),this._controls.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}reset(){const e=new d.Vector3(1,0,0),t=new d.Vector3;this.normal.equals(e)||(this.normal.copy(e),this._helper.lookAt(e)),this.origin.copy(t),this._helper.position.copy(t),this._helper.updateMatrix()}toggleControls(e){if(e){if(this._controlsActive)return;this._controls.addEventListener("change",this.update),this._controls.addEventListener("dragging-changed",this.changeDrag)}else this._controls.removeEventListener("change",this.update),this._controls.removeEventListener("dragging-changed",this.changeDrag);this._controlsActive=e}newTransformControls(){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");const e=this.world.camera.three,t=this.world.renderer.three.domElement,i=new l.TransformControls(e,t);return this.initializeControls(i),this.world.scene.three.add(i.getHelper()),i}initializeControls(e){e.attach(this._helper),e.showX=!1,e.showY=!1,e.setSpace("local"),this.createArrowBoundingBox(),e.getHelper().children[0].children[0].add(this._arrowBoundBox)}createArrowBoundingBox(){this._arrowBoundBox.geometry=new d.CylinderGeometry(.18,.18,1.2),this._arrowBoundBox.material=this._hiddenMaterial,this._arrowBoundBox.rotateX(Math.PI/2),this._arrowBoundBox.updateMatrix(),this._arrowBoundBox.geometry.applyMatrix4(this._arrowBoundBox.matrix)}notifyDraggingChanged(e){e.value?this.onDraggingStarted.trigger():this.onDraggingEnded.trigger()}preventCameraMovement(){this.world.camera.enabled=this._visible}newHelper(){const e=new d.Object3D;return e.lookAt(this.normal),e.position.copy(this.origin),this._planeMesh.position.z+=.01,e.add(this._planeMesh),this.world.scene.three.add(e),e}static newPlaneMesh(e,t){const i=new d.PlaneGeometry(1),n=new d.Mesh(i,t);return n.scale.set(e,e,e),n}}class lo extends We{constructor(){super(...arguments),t(this,"_config",{enabled:{value:!0,type:"Boolean"},visible:{value:!0,type:"Boolean"},color:{value:new d.Color,type:"Color"},opacity:{type:"Number",interpolable:!0,value:1,min:0,max:1},size:{type:"Number",interpolable:!0,value:2,min:0,max:100}})}get enabled(){return this._config.enabled.value}set enabled(e){this._config.enabled.value=e,this._component.enabled=e}get visible(){return this._config.visible.value}set visible(e){this._config.visible.value=e,this._component.visible=e}get color(){return this._config.color.value}set color(e){this._config.color.value=e,this._component.material.color.copy(e)}get opacity(){return this._config.opacity.value}set opacity(e){this._config.opacity.value=e,this._component.material.opacity=e}get size(){return this._config.size.value}set size(e){this._config.size.value=e,this._component.size=e}}const co=class e extends g{constructor(i){super(i),t(this,"onSetup",new f),t(this,"onBeforeDrag",new f),t(this,"onAfterDrag",new f),t(this,"onBeforeCreate",new f),t(this,"onBeforeCancel",new f),t(this,"onAfterCancel",new f),t(this,"onBeforeDelete",new f),t(this,"onAfterCreate",new f),t(this,"onAfterDelete",new f),t(this,"onDisposed",new f),t(this,"isSetup",!1),t(this,"orthogonalY",!1),t(this,"toleranceOrthogonalY",.7),t(this,"autoScalePlanes",!0),t(this,"Type",ao),t(this,"list",new h.DataMap),t(this,"config",new lo(this,this.components,"Clipper",e.uuid)),t(this,"_defaultConfig",{color:new d.Color(12255487),opacity:.2,size:2}),t(this,"_material",new d.MeshBasicMaterial({color:12255487,side:d.DoubleSide,transparent:!0,opacity:.2})),t(this,"_size",5),t(this,"_enabled",!1),t(this,"_visible",!0),t(this,"onStateChanged",new f),this.components.add(e.uuid,this),this.setEvents()}get enabled(){return this._enabled}set enabled(e){this._enabled=e,this.onStateChanged.trigger(["enabled"])}get visible(){return this._visible}set visible(e){this._visible=e;for(const[t,i]of this.list)i.visible=e;this.onStateChanged.trigger(["visibility"])}get material(){return this._material}set material(e){this._material=e;for(const[t,i]of this.list)i.planeMaterial=e;this.onStateChanged.trigger(["material"])}get size(){return this._size}set size(e){this._size=e;for(const[t,i]of this.list)i.size=e;this.onStateChanged.trigger(["size"])}setEvents(){this.list.onBeforeDelete.add(({value:e})=>{if(!e.world.renderer)throw new Error("Renderer not found for this plane's world!");e.world.renderer.setPlane(!1,e.three),e.dispose(),this.updateMaterialsAndPlanes(),this.onAfterDelete.trigger(e)})}dispose(){this._enabled=!1;this.components.get(He).list.delete(this.config.uuid),this.list.clear(),this._material.dispose(),this.onBeforeCreate.reset(),this.onBeforeCancel.reset(),this.onBeforeDelete.reset(),this.onBeforeDrag.reset(),this.onAfterCreate.reset(),this.onAfterCancel.reset(),this.onAfterDelete.reset(),this.onAfterDrag.reset(),this.onDisposed.trigger(e.uuid),this.onDisposed.reset()}async create(e){const t=this.components.get(Mr).get(e),i=await t.castRay();return i?this.createPlaneFromIntersection(e,i):null}createFromNormalAndCoplanarPoint(e,t,i){const n=this.newPlane(e,i,t);return this.updateMaterialsAndPlanes(),n}async delete(e,t){if(!t){const i=await this.pickPlane(e);if(!i)return;t=this.list.getKey(i)}t&&this.list.delete(t)}deleteAll(e){for(const[t,i]of this.list)e&&!e.has(i.type)||this.list.delete(t)}setup(e){const t={...this._defaultConfig,...e};this.config.color=t.color,this.config.opacity=t.opacity,this.config.size=t.size,this.isSetup=!0,this.onSetup.trigger()}pickPlane(e){const t=this.components.get(Mr).get(e),i=this.getAllPlaneMeshes(),n=t.castRayToObjects(i);if(n){const e=n.object;return[...this.list.values()].find(t=>t.meshes.includes(e))}}getAllPlaneMeshes(){const e=[];for(const[t,i]of this.list)e.push(...i.meshes);return e}createPlaneFromIntersection(e,t){var i;if(!e.renderer)throw new Error("The given world must have a renderer!");const n=t.point.distanceTo(new d.Vector3(0,0,0)),s=t.normal||(null==(i=t.face)?void 0:i.normal);if(!n||!s)return null;const r=this.getWorldNormal(t,s),o=this.newPlane(e,t.point,r.negate()),a=this.list.get(o);return a.visible=this._visible,a.size=this._size,e.renderer.setPlane(!0,a.three),this.updateMaterialsAndPlanes(),a}getWorldNormal(e,t){const i=e.object;let n=e.object.matrixWorld.clone();if(i instanceof d.InstancedMesh&&void 0!==e.instanceId){const t=new d.Matrix4;i.getMatrixAt(e.instanceId,t),n=t.multiply(n)}const s=(new d.Matrix3).getNormalMatrix(n),r=t.clone().applyMatrix3(s).normalize();return this.normalizePlaneDirectionY(r),r}normalizePlaneDirectionY(e){this.orthogonalY&&(e.y>this.toleranceOrthogonalY&&(e.x=0,e.y=1,e.z=0),e.y<-this.toleranceOrthogonalY&&(e.x=0,e.y=-1,e.z=0))}newPlane(e,t,i){const n=new this.Type(this.components,e,t,i,this._material);n.autoScale=this.autoScalePlanes,n.onDraggingStarted.add(()=>this.onBeforeDrag.trigger(n)),n.onDraggingEnded.add(()=>this.onAfterDrag.trigger(n));const s=T.create();return this.list.set(s,n),this.onAfterCreate.trigger(n),s}updateMaterialsAndPlanes(){const e=this.components.get(Lr);for(const[t,i]of e.list){if(!i.renderer)continue;i.renderer.updateClippingPlanes();const{clippingPlanes:e}=i.renderer;for(const t of i.meshes)if(t.material)if(Array.isArray(t.material))for(const i of t.material)i.clippingPlanes=e;else t.material.clippingPlanes=e}}};t(co,"uuid","66290bc5-18c4-4cd1-9379-2e17a0617611");let ho=co;class uo{constructor(e,i){t(this,"title"),t(this,"guid",T.create()),t(this,"clippingPlanes",new h.DataSet),t(this,"camera",{aspect_ratio:1,field_of_view:60,camera_direction:{x:0,y:0,z:0},camera_view_point:{x:0,y:0,z:0},camera_up_vector:{x:0,y:1,z:0}}),t(this,"customData",{}),t(this,"exceptionComponents",new h.DataSet),t(this,"selectionComponents",new h.DataSet),t(this,"componentColors",new h.DataMap),t(this,"spacesVisible",!1),t(this,"spaceBoundariesVisible",!1),t(this,"openingsVisible",!1),t(this,"defaultVisibility",!0),t(this,"snapshot",this.guid),t(this,"_components"),t(this,"_world",null),t(this,"notifyUpdate",()=>{this._components.get(mo).list.set(this.guid,this)}),this._components=e,i&&(this.guid=i.guid??this.guid,this.set(i)),this.setEvents()}async getSelectionMap(){const e=this._components.get(Zn);return await e.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const e=this._components.get(Zn);return await e.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const e=this._components.get(Zn),{camera_view_point:t}=this.camera,{x:i,y:n,z:s}=t,r=new d.Vector3(i,n,s);return e.applyBaseCoordinateSystem(r,new d.Matrix4),r}set position(e){const t=e.clone(),i=this._components.get(Zn);e.clone().applyMatrix4(i.baseCoordinationMatrix.clone().invert()),this.camera.camera_view_point={x:t.x,y:t.y,z:t.z}}get direction(){const{camera_direction:e}=this.camera,{x:t,y:i,z:n}=e;return new d.Vector3(t,i,n)}set world(e){this._world=e}get world(){return this._world}get _managerVersion(){return this._components.get(oo).config.version}get topics(){return[...this._components.get(oo).list.values()].filter(e=>e.viewpoints.has(this.guid))}setEvents(){this.selectionComponents.onUpdated.add(this.notifyUpdate),this.exceptionComponents.onUpdated.add(this.notifyUpdate),this.clippingPlanes.onUpdated.add(this.notifyUpdate),this.componentColors.onItemSet.add(this.notifyUpdate),this.componentColors.onItemDeleted.add(this.notifyUpdate),this.componentColors.onItemUpdated.add(this.notifyUpdate),this.componentColors.onCleared.add(this.notifyUpdate)}set(e){this.title=e.title;const{components:t,perspective_camera:i,orthogonal_camera:n,clipping_planes:s}=e;if(t){const{selection:e,visibility:i,coloring:n}=t;if(e){this.selectionComponents.clear();for(const{ifc_guid:t}of e)t&&this.selectionComponents.add(t)}if(i){const{default_visibility:e,exceptions:t,view_setup_hints:n}=i;if(void 0!==e&&(this.defaultVisibility=e),t){this.exceptionComponents.clear();for(const{ifc_guid:e}of t)e&&this.exceptionComponents.add(e)}if(n){const{spaces_visible:e,space_boundaries_visible:t,openings_visible:i}=n;void 0!==e&&(this.spacesVisible=e),void 0!==t&&(this.spaceBoundariesVisible=t),void 0!==i&&(this.openingsVisible=i)}}if(n){this.componentColors.clear();for(const e of n){const{color:t,components:i}=e,n=i.map(e=>e.ifc_guid).filter(e=>null!==e);this.componentColors.set(t,n)}}}if((i||n)&&(this.camera=i??n),s&&this.world){const e=this._components.get(ho);for(const t of s){const{location:i,direction:n}=t,s=new d.Vector3(i.x,i.z,-i.y),r=new d.Vector3(n.x,n.z,-n.y),o=e.createFromNormalAndCoplanarPoint(this.world,r,s);this.clippingPlanes.add(o),e.list.get(o).enabled=!1,e.list.get(o).visible=!1}}this.notifyUpdate()}async go(e){if(!this.world)return;const{camera:t}=this.world;if(!(t instanceof Zr))throw new Error("Viewpoint: the world's camera component must be of type OrthoPerspectiveCamera to switch between perspective and orthographic projections.");const{transition:i,applyClippings:n,applyVisibility:s,clippingsVisibility:r}={transition:!0,applyClippings:!0,applyVisibility:!0,clippingsVisibility:!0,...e};t.projection.set(this.projection);const o=new d.Vector3(this.camera.camera_view_point.x,this.camera.camera_view_point.y,this.camera.camera_view_point.z),a=new d.Vector3(this.camera.camera_direction.x,this.camera.camera_direction.y,this.camera.camera_direction.z);if(o.equals(new d.Vector3)&&a.equals(new d.Vector3))return;const l=this.position,c=this.direction,h={x:l.x+80*c.x,y:l.y+80*c.y,z:l.z+80*c.z},u=[];n&&this.setClippingState(!0),s&&u.push(this.applyVisibility()),this.setClippingVisibility(r),u.push(t.controls.setLookAt(l.x,l.y,l.z,h.x,h.y,h.z,i)),await Promise.all(u)}async updateCamera(e=!0){return new Promise(t=>{if(!this.world)return void t(!1);const{camera:i,renderer:n}=this.world;if(!n)throw new Error("Viewpoint: the world needs to have a renderer!");if(!i.hasCameraControls())throw new Error("Viewpoint: world's camera need camera controls!");const s=new d.Vector3;i.controls.getPosition(s);const r=i.three,o=new d.Vector3(0,0,-1).applyEuler(r.rotation),{width:a,height:l}=n.getSize();let c=a/l;Number.isNaN(c)&&(c=1);const h=this._components.get(Zn);s.applyMatrix4(h.baseCoordinationMatrix.clone().invert());const u={aspect_ratio:c,camera_view_point:{x:s.x,y:s.y,z:s.z},camera_direction:{x:o.x,y:o.y,z:o.z},camera_up_vector:{x:0,y:1,z:0}};if(r instanceof d.PerspectiveCamera?this.camera={...u,field_of_view:r.fov}:r instanceof d.OrthographicCamera&&(this.camera={...u,view_to_world_scale:r.top-r.bottom}),e){const e=this._components.get(mo),s=n.three.domElement;n.three.render(this.world.scene.three,i.three),s.toBlob(async i=>{if(i){const t=await i.arrayBuffer(),n=new Uint8Array(t);e.snapshots.set(this.guid,n)}this.notifyUpdate(),t(!0)})}else this.notifyUpdate(),t(!0)})}takeSnapshot(){return new Promise(e=>{if(!this.world)return void e(!1);const{camera:t,renderer:i}=this.world;if(!i)throw new Error("Viewpoint: the world needs to have a renderer!");const n=this._components.get(mo),s=i.three.domElement;i.three.render(this.world.scene.three,t.three),s.toBlob(async t=>{if(t){const e=await t.arrayBuffer(),i=new Uint8Array(e);n.snapshots.set(this.guid,i)}this.notifyUpdate(),e(!0)})})}updateClippingPlanes(){this.clippingPlanes.clear();const e=this._components.get(ho);for(const[t,i]of e.list)i.enabled&&this.clippingPlanes.add(t)}async applyVisibility(){const e=this._components.get(mr);e.set(this.defaultVisibility);const t=await this.getExceptionMap();e.set(!this.defaultVisibility,t);const i=await this.getSelectionMap();e.set(!0,i)}async setColorizationState(e){const t=this._components.get(Zn),i=[];if(e)for(const[e,n]of this.componentColors){const s=`#${e}`,r=await t.guidsToModelIdMap(n);for(const[e,n]of Object.entries(r)){const r=t.list.get(e);r&&i.push(r.highlight([...n],{customId:s,color:new d.Color(s),renderedFaces:h.RenderedFaces.ONE,opacity:1,transparent:!1}))}}else for(const[e,n]of this.componentColors){const e=await t.guidsToModelIdMap(n);for(const[n,s]of Object.entries(e)){const e=t.list.get(n);e&&i.push(e.resetHighlight([...s]))}}i.push(t.core.update(!0)),await Promise.all(i)}setClippingState(e){const t=this._components.get(ho);for(const[i,n]of t.list)n.enabled=e&&this.clippingPlanes.has(i)}setClippingVisibility(e){const t=this._components.get(ho);for(const i of this.clippingPlanes){const n=t.list.get(i);n&&(n.visible=e)}}async createComponentTags(e){var t;const i=this._components.get(Zn);let n="";if(this._components.get(oo).config.includeSelectionTag){const s="selection"===e?await this.getSelectionMap():await this.getExceptionMap();for(const e in s){const r=i.list.get(e);if(!r)continue;const o=s[e];for(const e of o){const i=r.getItem(e),s=await i.getGuid();if(!s)continue;const o=null==(t=await i.getAttributes())?void 0:t.getValue("Tag");let a=null;o&&(a=`AuthoringToolId="${o}"`),n+=`\n<Component IfcGuid="${s}" ${a??""} />`}}}else n=[...this.selectionComponents].map(e=>`<Component IfcGuid="${e}" />`).join("\n");return n}createColorTags(){let e="";for(const[t,i]of this.componentColors.entries()){e+=`<Color Color="${t}">\n${i.map(e=>`\n<Component IfcGuid="${e}" />`).join("\n")}\n</Color>`}return 0!==e.length?`<Coloring>\n${e}\n</Coloring>`:"<Coloring />"}toJSON(){const e=this._components.get(ho),t={guid:this.guid,components:{selection:[...this.selectionComponents].map(e=>({ifc_guid:e,authoring_tool_id:null})),coloring:[...this.componentColors].map(([e,t])=>({color:e,components:t.map(e=>({ifc_guid:e,authoring_tool_id:null}))})),visibility:{default_visibility:this.defaultVisibility,exceptions:[...this.exceptionComponents].map(e=>({ifc_guid:e,authoring_tool_id:null})),view_setup_hints:{spaces_visible:this.spacesVisible,space_boundaries_visible:this.spaceBoundariesVisible,openings_visible:this.openingsVisible}}},clipping_planes:[...this.clippingPlanes].map(t=>{const i=e.list.get(t);if(!i)return null;const n=i._controls.worldPosition??i.origin,{normal:s}=i;return{location:{x:n.x,y:-n.z,z:n.y},direction:{x:s.x,y:-s.z,z:s.y}}}).filter(e=>null!==e)};"field_of_view"in this.camera?t.perspective_camera=this.camera:t.orthogonal_camera=this.camera;const i=this._components.get(mo),n=i.snapshots.get(this.snapshot);if(n){const e=n.toString(),s=btoa(e),r=i.getSnapshotExtension(this.snapshot);t.snapshot={snapshot_type:r,snapshot_data:s}}return t}async serialize(e=this._managerVersion){const t=this._components.get(Zn),i=this.position;i.applyMatrix4(t.baseCoordinationMatrix.clone().invert());const n=this.direction;n.normalize();const s=(new d.Matrix4).makeRotationX(Math.PI/2),r=n.clone().applyMatrix4(s);r.normalize();const o=`<CameraViewPoint>\n <X>${i.x}</X>\n <Y>${-i.z}</Y>\n <Z>${i.y}</Z>\n </CameraViewPoint>`,a=`<CameraDirection>\n <X>${n.x}</X>\n <Y>${-n.z}</Y>\n <Z>${n.y}</Z>\n </CameraDirection>`,l=`<CameraUpVector>\n <X>${r.x}</X>\n <Y>${-r.z}</Y>\n <Z>${r.y}</Z>\n </CameraUpVector>`,c=`<AspectRatio>${this.camera.aspect_ratio}</AspectRatio>`;let h="";"view_to_world_scale"in this.camera?h=`<OrthogonalCamera>\n ${o}\n ${a}\n ${l}\n ${c}\n <ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>\n </OrthogonalCamera>`:"field_of_view"in this.camera&&(h=`<PerspectiveCamera>\n ${o}\n ${a}\n ${l}\n ${c}\n <FieldOfView>${this.camera.field_of_view}</FieldOfView>\n </PerspectiveCamera>`);const u=`<ViewSetupHints SpacesVisible="${this.spacesVisible??!1}" SpaceBoundariesVisible="${this.spaceBoundariesVisible??!1}" OpeningsVisible="${this.openingsVisible??!1}" />`,p=(await this.createComponentTags("selection")).trim(),f=(await this.createComponentTags("exception")).trim(),m=this.createColorTags();return`<?xml version="1.0" encoding="UTF-8"?>\n <VisualizationInfo Guid="${this.guid}">\n <Components>\n ${"2.1"===e?u:""}\n ${0!==p.length?`<Selection>${p}</Selection>`:""}\n <Visibility DefaultVisibility="${this.defaultVisibility}">\n ${"3"===e?u:""}\n ${0!==f.length?`<Exceptions>${f}</Exceptions>`:""}\n </Visibility>\n ${m}\n </Components>\n ${h}\n </VisualizationInfo>`}}class po extends We{constructor(){super(...arguments),t(this,"_config",{overwriteColors:{value:!1,type:"Boolean"}})}get overwriteColors(){return this._config.overwriteColors.value}set overwriteColors(e){this._config.overwriteColors.value=e}}const fo=class e extends g{constructor(n){super(n),t(this,"enabled",!0),t(this,"world",null),t(this,"list",new i.DataMap),t(this,"snapshots",new i.DataMap),t(this,"isSetup",!1),t(this,"onSetup",new f),t(this,"config",new po(this,this.components,"Viewpoints",e.uuid)),t(this,"onDisposed",new f),n.add(e.uuid,this)}create(e){const t=new uo(this.components,e);return t.world=this.world,e||this.list.set(t.guid,t),t}getSnapshotExtension(e){let t="jpeg";const i=this.snapshots.get(e);if(!i)return t;const n=i.subarray(0,4);let s="";for(let e=0;e<n.length;e++)s+=n[e].toString(16);return s.startsWith("89504e47")&&(t="png"),s.startsWith("ffd8ffe")&&(t="jpeg"),t}setup(){}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}};t(fo,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");let mo=fo;class go{constructor(e,i){t(this,"_components"),t(this,"_cameraOffset",10),t(this,"_planeHelper"),t(this,"_farPlaneHelper"),t(this,"_cameraHelper"),t(this,"onStateChanged",new f),t(this,"onUpdated",new f),t(this,"onDisposed",new f),t(this,"camera"),t(this,"plane",new d.Plane),t(this,"farPlane",new d.Plane),t(this,"id",T.create()),t(this,"_open",!1),t(this,"_range",yo.defaultRange),t(this,"_world",null),t(this,"_helpersVisible",!1),t(this,"_planesEnabled",!1),this._components=e,this.camera=new Zr(this._components);const{threeOrtho:n}=this.camera;if((null==i?void 0:i.id)&&(this.id=i.id),(null==i?void 0:i.normal)&&(null==i?void 0:i.point)){const{normal:e,point:t}=i;this.plane.setFromNormalAndCoplanarPoint(e,t)}this._cameraHelper=new d.CameraHelper(n),this._planeHelper=new d.PlaneHelper(this.plane,50),this._farPlaneHelper=new d.PlaneHelper(this.farPlane,50),this.farPlaneHelperColor=new d.Color("blue"),this.update()}get _planeNormalOpposite(){return this.plane.normal.clone().negate()}get _planePosition(){return this.plane.normal.clone().multiplyScalar(-this.plane.constant)}get _cameraPosition(){return this._planePosition.addScaledVector(this._planeNormalOpposite,this._cameraOffset)}set open(e){this._open=e,this.onStateChanged.trigger(["open"])}get open(){return this._open}set planeHelperColor(e){!Array.isArray(this._planeHelper.material)&&"color"in this._planeHelper.material&&this._planeHelper.material.color instanceof d.Color&&(this._planeHelper.material.color=e)}set farPlaneHelperColor(e){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof d.Color&&(this._farPlaneHelper.material.color=e)}set range(e){this._range=e,this.update()}get range(){return this._range}set distance(e){this.plane.constant=e,this.update()}get distance(){return this.plane.constant}set world(e){this._world=e,this.camera.currentWorld=e,e&&(this.camera.projection.set("Orthographic"),this.camera.set("Plan"),this.camera.controls.dollySpeed=6,this.camera.controls.restThreshold=.005,this.update())}get world(){return this._world}set helpersVisible(e){if(!e)return this._helpersVisible=e,this._planeHelper.removeFromParent(),this._farPlaneHelper.removeFromParent(),void this._cameraHelper.removeFromParent();this.world&&(this._helpersVisible=e,this.world.scene.three.add(this._planeHelper,this._farPlaneHelper))}get helpersVisible(){return this._helpersVisible}set planesEnabled(e){const{world:t}=this;if(!t)return;const{renderer:i}=t;i&&(i.setPlane(e,this.plane),i.setPlane(e,this.farPlane),this._planesEnabled=e)}get planesEnabled(){return this._planesEnabled}dispose(){this.helpersVisible=!1;const e=this._components.get(v);e.destroy(this._planeHelper),e.destroy(this._farPlaneHelper),e.destroy(this._cameraHelper),this.camera.dispose(),this.onDisposed.trigger()}update(){if(this.world){const e=this._cameraPosition,t=this._planePosition;this.camera.controls.setLookAt(e.x,e.y,e.z,t.x,t.y,t.z,!1)}this.farPlane.normal.copy(this._planeNormalOpposite),this.farPlane.constant=this.range-this.plane.constant,this.onUpdated.trigger()}flip(){this.plane.normal.negate(),this.update()}}const wo=class e extends g{constructor(n){super(n),t(this,"list",new i.DataMap),t(this,"enabled",!0),t(this,"world",null),t(this,"_fragmentsUpdateEvent",()=>{this.components.get(Zn).core.update(!0)}),n.add(e.uuid,this),this.setupEvents()}get hasOpenViews(){return[...this.list.values()].some(e=>e.open)}setupEvents(){this.list.onBeforeDelete.add(({key:e,value:t})=>{t.open&&this.close(e),t.dispose()})}create(e,t,i){const n=new go(this.components,{id:null==i?void 0:i.id,normal:e,point:t});return n.world=(null==i?void 0:i.world)??this.world,this.list.set(n.id,n),n}createFromPlane(e,t){const i=new go(this.components,{id:null==t?void 0:t.id});return i.plane.copy(e),i.update(),i.world=(null==t?void 0:t.world)??this.world,this.list.set(i.id,i),i}async createFromIfcStoreys(e){const t=[],i=this.components.get(Zn),n=void 0===(null==e?void 0:e.offset)?.25:e.offset;for(const[s,r]of i.list){if(e&&e.modelIds&&!e.modelIds.some(e=>e.test(s)))continue;const i=Object.values(await r.getItemsOfCategories([/BUILDINGSTOREY/])).flat();if(0===i.length)continue;const o=await r.getItemsData(i),[,a]=await r.getCoordinates(),l=new d.Vector3(0,-1,0);for(const i of o){if(!("value"in i.Name)||!("value"in i.Elevation))continue;const{value:s}=i.Name;if((null==e?void 0:e.storeyNames)&&!e.storeyNames.some(e=>e.test(s)))continue;const r=i.Elevation.value+a+n,o=new d.Plane(l,r),c=this.createFromPlane(o,{id:s,world:null==e?void 0:e.world});t.push(c)}}return t}createElevations(e){const t=[],i=this.components.get(Zn),n=void 0!==(null==e?void 0:e.combine)&&e.combine,s=(null==e?void 0:e.namingCallback)??(e=>({front:""+(n?"Front":`${e}: Front`),back:""+(n?"Back":`${e}: Back`),left:""+(n?"Left":`${e}: Left`),right:""+(n?"Right":`${e}: Right`)}));let r=[];for(const[t,n]of i.list)e&&e.modelIds&&!e.modelIds.some(e=>e.test(t))||r.push({id:t,box:n.box});if(0===r.length)return t;if(n){const e=this.components.get(wr);e.list.clear(),e.list.add(...r.map(e=>e.box));r=[{id:"combined",box:e.get()}]}for(const{id:i,box:n}of r){const{min:r,max:o}=n,a=Math.abs(o.x-r.x),l=Math.abs(o.z-r.z),c=new d.Vector3;n.getCenter(c);const h=new d.Plane(new d.Vector3(0,0,-1),o.z),u=new d.Plane(new d.Vector3(0,0,1),-r.z),p=new d.Plane(new d.Vector3(-1,0,0),o.x),f=new d.Plane(new d.Vector3(1,0,0),-r.x),{front:m,back:g,left:w,right:y}=s(i),_=this.createFromPlane(h,{id:m,world:null==e?void 0:e.world});_.range=l;const b=this.createFromPlane(u,{id:g,world:null==e?void 0:e.world});b.range=l;const v=this.createFromPlane(p,{id:w,world:null==e?void 0:e.world});v.range=a;const x=this.createFromPlane(f,{id:y,world:null==e?void 0:e.world});x.range=a,t.push(_,b,v,x)}return t}open(e){const t=this.list.get(e);if(!t)throw new Error(`Views: the view with id ${e} doesn't exist.`);if(t.open)return;const{world:i}=t;if(!i)throw new Error(`Views: no world found for view with id ${e}.`);const{renderer:n}=i;if(!n)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);for(const[,e]of this.list)e.world===i&&this.close(e.id);n.setPlane(!0,t.plane),n.setPlane(!0,t.farPlane),t.camera.controls.addEventListener("rest",this._fragmentsUpdateEvent),i.camera=t.camera,t.open=!0}close(e){let t;if(t=e?this.list.get(e):[...this.list.values()].find(e=>e.open),e&&!t)throw new Error(`Views: the view with id ${e} doesn't exist.`);if(!t)return;if(!t.open)return;const{world:i}=t;if(!i)throw new Error(`Views: no world found for view with id ${e}.`);const{renderer:n}=i;if(!n)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);n.setPlane(!1,t.plane),n.setPlane(!1,t.farPlane),t.camera.controls.removeEventListener("rest",this._fragmentsUpdateEvent),i.useDefaultCamera(),t.open=!1}};t(wo,"uuid","fb22f1f5-6598-4664-a11d-de8963ae420f"),t(wo,"defaultRange",15);let yo=wo;async function _o(e,t,i,n,s,r,o){const a=e.fenceSync(e.SYNC_GPU_COMMANDS_COMPLETE,0);e.flush(),await function(e,t,i,n){return new Promise((s,r)=>{!function o(){const a=e.clientWaitSync(t,i,0);a!==e.WAIT_FAILED?a!==e.TIMEOUT_EXPIRED?s():setTimeout(o,n):r()}()})}(e,a,0,10),e.deleteSync(a),e.bindBuffer(t,i),e.getBufferSubData(t,n,s,r,o),e.bindBuffer(t,null)}class bo{constructor(e,i){if(t(this,"onDisposed",new f),t(this,"onDistanceComputed",new f),t(this,"excludedObjects",new Set),t(this,"enabled",!0),t(this,"renderDebugFrame",!1),t(this,"components"),t(this,"scene",new d.Scene),t(this,"camera",new d.OrthographicCamera(-1,1,1,-1,0,1)),t(this,"depthMaterial"),t(this,"world"),t(this,"worker"),t(this,"_width",512),t(this,"_height",512),t(this,"_postQuad"),t(this,"tempRT"),t(this,"resultRT"),t(this,"bufferSize"),t(this,"_buffer"),t(this,"_isWorkerBusy",!1),t(this,"compute",async()=>{if(!this.enabled||this.world.isDisposing)return;if(this._isWorkerBusy)return;this._isWorkerBusy=!0,this.world.camera.three.updateMatrix();const e=this.world.renderer.three;e.setRenderTarget(this.tempRT);const t="visibilityBeforeDistanceCheck";for(const e of this.excludedObjects)e.userData[t]=e.visible,e.visible=!1;e.render(this.world.scene.three,this.world.camera.three);for(const e of this.excludedObjects)void 0!==e.userData[t]&&(e.visible=e.userData[t]);this.depthMaterial.uniforms.tDiffuse.value=this.tempRT.texture,this.depthMaterial.uniforms.tDepth.value=this.tempRT.depthTexture,e.setRenderTarget(this.resultRT),e.render(this.scene,this.camera);const i=e.getContext();try{await async function(e,t,i,n,s,r,o,a){const l=e.createBuffer();return e.bindBuffer(e.PIXEL_PACK_BUFFER,l),e.bufferData(e.PIXEL_PACK_BUFFER,a.byteLength,e.STREAM_READ),e.readPixels(t,i,n,s,r,o,0),e.bindBuffer(e.PIXEL_PACK_BUFFER,null),await _o(e,e.PIXEL_PACK_BUFFER,l,0,a),e.deleteBuffer(l),a}(i,0,0,this._width,this._height,i.RGBA,i.UNSIGNED_BYTE,this._buffer)}catch(t){return e.setRenderTarget(null),void(this._isWorkerBusy=!1)}e.setRenderTarget(null),this.renderDebugFrame&&e.render(this.scene,this.camera),this.worker.postMessage({buffer:this._buffer})}),t(this,"handleWorkerMessage",e=>{if(!this.enabled||this.world.isDisposing)return;const t=e.data.colors;let i=Number.MAX_VALUE;for(const e of t)0!==e&&e<i&&(i=e);const n=this.world.camera.three||d.OrthographicCamera,s=-1*(i/255-1)*(n.far-n.near),r=Math.min(s,n.far);this.onDistanceComputed.trigger(r),this._isWorkerBusy=!1}),!i.renderer)throw new Error("The given world must have a renderer!");this.components=e,this.world=i;const n=i.camera.three;this.tempRT=new d.WebGLRenderTarget(this._width,this._height),this.bufferSize=this._width*this._height*4,this._buffer=new Uint8Array(this.bufferSize),this.tempRT.texture.minFilter=d.NearestFilter,this.tempRT.texture.magFilter=d.NearestFilter,this.tempRT.stencilBuffer=!1,this.tempRT.samples=0,this.tempRT.depthTexture=new d.DepthTexture(this._width,this._height),this.tempRT.depthTexture.format=d.DepthFormat,this.tempRT.depthTexture.type=d.UnsignedShortType,this.resultRT=new d.WebGLRenderTarget(this._width,this._height),this.depthMaterial=new d.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n ",fragmentShader:"\n#include <packing>\n\nvarying vec2 vUv;\nuniform sampler2D tDiffuse;\nuniform sampler2D tDepth;\nuniform float cameraNear;\nuniform float cameraFar;\n\n\nfloat readDepth( sampler2D depthSampler, vec2 coord ) {\n float fragCoordZ = texture2D( depthSampler, coord ).x;\n float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );\n return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );\n}\n\nvoid main() {\n //vec3 diffuse = texture2D( tDiffuse, vUv ).rgb;\n float depth = readDepth( tDepth, vUv );\n\n gl_FragColor.rgb = 1.0 - vec3( depth );\n gl_FragColor.a = 1.0;\n}\n ",uniforms:{cameraNear:{value:n.near},cameraFar:{value:n.far},tDiffuse:{value:null},tDepth:{value:null}}});const s=new d.PlaneGeometry(2,2);this._postQuad=new d.Mesh(s,this.depthMaterial),this.scene.add(this._postQuad);const r=new Blob(['\n addEventListener("message", (event) => {\n const { buffer } = event.data;\n const colors = new Set();\n for (let i = 0; i < buffer.length; i += 4) {\n const r = buffer[i];\n colors.add(r);\n }\n postMessage({ colors });\n });\n '],{type:"application/javascript"});this.worker=new Worker(URL.createObjectURL(r)),this.worker.addEventListener("message",this.handleWorkerMessage)}dispose(){this.enabled=!1,this.onDistanceComputed.reset(),this.worker.terminate(),this.tempRT.dispose(),this.resultRT.dispose();const e=[...this.scene.children];this.excludedObjects.clear();for(const t of e)t.removeFromParent();this._postQuad.geometry.dispose(),this._postQuad.removeFromParent(),this._buffer=null,this.onDisposed.reset()}}class vo{constructor(e){t(this,"cardinality","required"),t(this,"instructions"),t(this,"evalRequirement",(e,t,i,n)=>{const s={parameter:i,currentValue:e,requiredValue:t,pass:!1};n&&this.addCheckResult(s,n);let r=!1;if("simple"===t.type&&(r=e===t.parameter),"enumeration"===t.type&&(r=t.parameter.includes(e)),"pattern"===t.type){r=new RegExp(t.parameter).test(String(e))}if("length"===t.type){const{min:i,length:n,max:s}=t.parameter;void 0!==n&&(r=String(e).length===n),void 0!==i&&(r=String(e).length>=i),void 0!==s&&(r=String(e).length<=s)}if("bounds"===t.type&&"number"==typeof e){const{min:i,minInclusive:n,max:s,maxInclusive:o}=t.parameter;let a=!0,l=!0;void 0!==i&&(a=n?e>=i:e>i),void 0!==s&&(l=o?e<=s:e<s),r=a&&l}return"prohibited"===this.cardinality&&(r=!r),"optional"===this.cardinality&&(r=!0),s.pass=r,s.pass}),this._components=e}addCheckResult(e,t){const i=t.findIndex(({parameter:t})=>t===e.parameter);-1!==i?t[i]=e:t.push(e)}getItemChecks(e,t,i,n){if(!("value"in i._localId)||"number"!=typeof i._localId.value)return null;let s=e.get(t);s||(s=new h.DataMap,e.set(t,s));let r=s.get(i._localId.value);if(r&&n&&!r.pass)return null;if(!r){const e=[];r={guid:Array.isArray(i._guid)?void 0:i._guid.value,pass:!1,checks:e},Object.defineProperty(r,"pass",{get:()=>e.every(({pass:e})=>e)}),s.set(i._localId.value,r)}const o=[],a={facetType:this.facetType,cardinality:this.cardinality,checks:o,pass:!1};return Object.defineProperty(a,"pass",{get:()=>o.every(({pass:e})=>e)}),r.checks.push(a),a.checks}}const xo=(e,t)=>{let i="";if(!t)return i;if("simple"===t.type&&(i=`<simpleValue>${t.parameter}</simpleValue>`),"enumeration"===t.type){i=`<xs:restriction base="xs:string">\n ${t.parameter.map(e=>`<xs:enumeration value="${e}" />`).join("\n")}\n </xs:restriction>`}if("pattern"===t.type){i=`<xs:restriction base="xs:string">\n <xs:pattern value="${t.parameter}" />\n </xs:restriction>`}if("bounds"===t.type){const{min:e,minInclusive:n,max:s,maxInclusive:r}=t.parameter;let o="";void 0!==e&&(o=`<xs:min${n?"Inclusive":"Exclusive"} value="${e}">`);let a="";void 0!==s&&(a=`<xs:max${r?"Inclusive":"Exclusive"} value="${s}">`),i=`<xs:restriction base="xs:double">\n ${o}\n ${a}\n </xs:restriction>`}if("length"===t.type){const{length:e,min:n,max:s}=t.parameter;let r="";void 0!==e&&void 0===n&&void 0===s&&(r=`<xs:length value="${e}" />`);let o="";void 0!==n&&void 0===e&&(o=`<xs:minLength value="${n}" />`);let a="";void 0!==s&&void 0===e&&(a=`<xs:maxLength value="${s}" />`),i=`<xs:restriction base="xs:string">\n ${r}\n ${o}\n ${a}\n </xs:restriction>`}return`<${e[0].toLowerCase()+e.slice(1)}>\n ${i}\n </${e[0].toLowerCase()+e.slice(1)}>`};class So extends vo{constructor(e,i){super(e),t(this,"facetType","Attribute"),t(this,"name"),t(this,"value"),this.name=i}serialize(e){const t=xo("Name",this.name),i=xo("Value",this.value);let n="";return"requirement"===e&&(n+=`cardinality="${this.cardinality}"`,n+=this.instructions?`instructions="${this.instructions}"`:""),`<attribute ${n}>\n ${t}\n ${i}\n</attribute>`}async getEntities(){}async test(e,t,i={skipIfFails:!0}){const n=this._components.get(Zn);for(const[s,r]of Object.entries(e)){const e=n.list.get(s);if(!e)continue;const o=await e.getItemsData([...r]);for(const e of o){const n=this.getItemChecks(t,s,e,i.skipIfFails);if(!n)continue;const r=Object.keys(e).filter(t=>{const i=this.evalRequirement(t,this.name,"Name");if(!i)return!1;const n=e[t];return!!Array.isArray(n)||(null===n||null===n.value?"optional"===this.cardinality||"prohibited"===this.cardinality:(!Array.isArray(n.value)||0!==n.value.length)&&(("string"!=typeof n.value||""!==n.value.trim())&&i))}),o=r.length>0;if(n.push({parameter:"Name",currentValue:o?r[0]:null,requiredValue:this.name,pass:"prohibited"===this.cardinality?!o:o}),this.value)if(r[0]){const t=e[r[0]];if(Array.isArray(t))n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality});else{Array.isArray(t.value)?n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality}):this.evalRequirement(t.value,this.value,"Value",n)}}else n.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality})}}}}class Co extends vo{constructor(e,i){super(e),t(this,"facetType","Classification"),t(this,"system"),t(this,"value"),t(this,"uri"),this.system=i}serialize(e){const t=xo("System",this.system),i=xo("Value",this.value);let n="";return"requirement"===e&&(n+=`cardinality="${this.cardinality}"`,n+=this.uri?`uri=${this.uri}`:"",n+=this.instructions?`instructions="${this.instructions}"`:""),`<classification ${n}>\n ${t}\n ${i}\n</classification>`}async getEntities(e,t){}async test(e,t){}}class To extends vo{constructor(e,i){super(e),t(this,"facetType","Entity"),t(this,"name"),t(this,"predefinedType"),this.name=i}serialize(e){const t=xo("Name",this.name),i=xo("Name",this.predefinedType);let n="";return"requirement"===e&&(n+=`cardinality="${this.cardinality}"`,n+=this.instructions?`instructions="${this.instructions}"`:""),`<entity ${n}>\n ${t}\n ${i}\n</entity>`}async getEntities(e,t){const i=this._components.get(Zn),n=new Map;for(const[t,s]of i.list){if(!e.find(e=>e.test(t)))continue;const i=await s.getCategories();for(const e of i){if(!await this.evalName(e))continue;let i=n.get(t);i||(i=[],n.set(t,i)),i.push(e)}}const s={};if(await Promise.all(Array.from(n.entries()).map(async([e,t])=>{const n=i.list.get(e);if(!n)return;const r=t.map(e=>new RegExp(`^${e}$`)),o=await n.getItemsOfCategories(r),a=Object.values(o).flat();s[e]=new Set(a)})),this.predefinedType)for(const[e,n]of Object.entries(s)){const s=i.list.get(e);if(!s)continue;const r=await s.getItemsData([...n]);for(const i of r){if(!("value"in i._localId))continue;await this.evalPredefinedType(e,i)&&Ue.append(t,e,i._localId.value)}}else Ue.add(t,s)}async test(e,t,i){const n=this._components.get(Zn);for(const[s,r]of Object.entries(e)){const e=n.list.get(s);if(!e)continue;const o=await e.getItemsData([...r]);for(const e of o){if(!("value"in e._category))continue;const n=this.getItemChecks(t,s,e,i.skipIfFails);n&&(await this.evalName(e._category.value,n),await this.evalPredefinedType(s,e,n))}}}async evalName(e,t){return this.evalRequirement(e,this.name,"Name",t)}async evalPredefinedType(e,t,i){if(!this.predefinedType)return null;if(!("value"in t.PredefinedType))return null;const n="string"==typeof this.predefinedType.parameter&&"USERDEFINED"===this.predefinedType.parameter;let s=t.PredefinedType.value;if("USERDEFINED"===s&&!n){const e=Object.keys(t).find(e=>/^((?!Predefined).)*Type$/.test(e));if(e){const i=t[e];"value"in i&&(s=i.value)}else s="USERDEFINED"}if(!s){const i=this._components.get(Zn).list.get(e);if(i&&"value"in t._localId){const[e]=await i.getItemsData([t._localId.value],{relations:{IsTypedBy:{attributes:!0,relations:!1}}});if(Array.isArray(e.IsTypedBy)){const t=e.IsTypedBy[0];if(t&&"value"in t.PredefinedType&&(s=t.PredefinedType.value,"USERDEFINED"===s&&!n)){const e=Object.keys(t).find(e=>/^((?!Predefined).)*Type$/.test(e));if(e){const i=t[e];"value"in i&&(s=i.value)}else s="USERDEFINED"}}}}return this.evalRequirement(s,this.predefinedType,"PredefinedType",i)}}class Ao extends vo{constructor(e,i,n){super(e),t(this,"facetType","Property"),t(this,"propertySet"),t(this,"baseName"),t(this,"value"),t(this,"dataType"),t(this,"uri"),t(this,"_unsupportedTypes",["IFCCOMPLEXPROPERTY","IFCPHYSICALCOMPLEXQUANTITY"]),this.propertySet=i,this.baseName=n}serialize(e){const t=xo("PropertySet",this.propertySet),i=xo("BaseName",this.baseName),n=xo("Value",this.value),s=this.dataType?`dataType=${this.dataType}`:"";let r="";return"requirement"===e&&(r+=`cardinality="${this.cardinality}"`,r+=this.uri?`uri=${this.uri}`:"",r+=this.instructions?`instructions="${this.instructions}"`:""),`<property ${s} ${r}>\n ${t}\n ${i}\n ${n}\n</property>`}async getEntities(e,t){const i=this._components.get(Zn);for(const[n,s]of i.list){if(!e.find(e=>e.test(n)))continue;const i=await s.getItemsOfCategories([/PROPERTYSET/,/ELEMENTQUANTITY/]),r=Object.values(i).flat();if(0===r.length)continue;const o=await s.getItemsData(r,{relations:{HasProperties:{attributes:!0,relations:!1},DefinesOcurrence:{attributes:!0,relations:!1}}});for(const e of o){if(!("value"in e._localId&&"value"in e._category&&"value"in e.Name&&Array.isArray(e.DefinesOcurrence)))continue;if(!this.evalRequirement(e.Name.value,this.propertySet,"PropertySet"))continue;let i;if("IFCPROPERTYSET"===e._category.value&&(i="HasProperties"),"IFCELEMENTQUANTITY"===e._category.value&&(i="Quantities"),!i)continue;const s=e[i];if(Array.isArray(s))for(const i of s){const s=Object.keys(i),r=s.find(e=>/Name/.test(e));if(!r||!("value"in i[r]))continue;const o=i[r];if(!("value"in o))continue;if(!this.evalRequirement(o.value,this.baseName,"BaseName"))continue;if(this.value){const e=s.find(e=>/Value/.test(e));if(!e)continue;const t=i[e];if(!("value"in t))continue;if(!this.evalRequirement(t.value,this.value,"Value"))continue}const a=e.DefinesOcurrence.map(e=>"value"in e._localId&&"number"==typeof e._localId.value?e._localId.value:null).filter(e=>null!==e);Ue.append(t,n,...a)}}}}async test(e,t,i={skipIfFails:!0}){const n=this._components.get(Zn);for(const[s,r]of Object.entries(e)){const e=n.list.get(s);if(!e)continue;const o=await e.getItemsData([...r],{relations:{IsDefinedBy:{attributes:!0,relations:!0},IsTypedBy:{attributes:!0,relations:!1},HasPropertySets:{attributes:!0,relations:!0},DefinesOcurrence:{attributes:!1,relations:!1}}});for(const e of o){const n=this.getItemChecks(t,s,e,i.skipIfFails);if(!n)continue;const r=(await this.getPsets(e)).filter(e=>{if(!("value"in e.Name))return!1;return!!this.evalRequirement(e.Name.value,this.propertySet,"PropertySet")&&(n.push({currentValue:e.Name.value,parameter:"PropertySet",pass:!0,requiredValue:this.propertySet}),!0)});if(0!==r.length)for(const e of r){const t=this.getPropertyListName(e);if(!t)continue;const i=e[t];if(!Array.isArray(i)){n.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}const s=i.filter(e=>{if(!("value"in e._category)||!("value"in e.Name))return!1;if(this._unsupportedTypes.includes(e._category.value))return!1;return!!this.evalRequirement(e.Name.value,this.baseName,"BaseName")&&(n.push({currentValue:e.Name.value,parameter:"BaseName",pass:!0,requiredValue:this.baseName}),!0)});if(0!==s.length)for(const e of s)this.evalValue(e,n),this.evalDataType(e,n),this.evalURI();else n.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName})}else n.push({currentValue:null,parameter:"PropertySet",pass:!1,requiredValue:this.propertySet})}}}getPropertyListName(e){let t;return"value"in e._category?("IFCPROPERTYSET"===e._category.value&&(t="HasProperties"),"IFCELEMENTQUANTITY"===e._category.value&&(t="Quantities"),t):t}getValueKey(e){return Object.keys(e).find(e=>/Value/.test(e)||/Values/.test(e))}getTypePsets(e){if(!Array.isArray(e.IsTypedBy))return[];const[t]=e.IsTypedBy;return t&&Array.isArray(t.HasPropertySets)?t.HasPropertySets:[]}async getPsets(e){const t=this.getTypePsets(e);if(!Array.isArray(e.IsDefinedBy))return t;const i=[];for(const n of e.IsDefinedBy){if(!("value"in n.Name))continue;const e=n.Name.value,s=this.getPropertyListName(n);if(!e||!s)continue;const r=t.find(t=>"value"in t.Name&&t.Name.value===e);if(r&&Array.isArray(r.HasProperties)&&Array.isArray(n.HasProperties))for(const e of r.HasProperties){if(!("value"in e.Name))continue;const t=e.Name.value;n.HasProperties.find(e=>"value"in e.Name&&e.Name.value===t)||n.HasProperties.push(e)}i.push(n)}return i}evalValue(e,t){const i=this.getValueKey(e),n=e[i];if(!("value"in n))return!1;if(this.value){if(!i)return null==t||t.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;const e=structuredClone(this.value);"IFCLABEL"===n.type&&"simple"===e.type&&(e.parameter=String(e.parameter));return this.evalRequirement(n.value,e,"Value",t)}return!i||("string"!=typeof n.value||""!==n.value.trim()||(null==t||t.push({parameter:"Value",currentValue:"",pass:!1,requiredValue:this.value}),!1))}evalDataType(e,t){if(!this.dataType)return!0;const i=this.getValueKey(e);if(!i||!("value"in e[i]))return null==t||t.push({parameter:"DataType",currentValue:null,pass:!1,requiredValue:this.dataType}),!1;const n=e[i];return this.evalRequirement(n.type??null,{type:"simple",parameter:this.dataType},"DataType",t)}evalURI(){return!0}}class Eo extends vo{constructor(){super(...arguments),t(this,"_ifcMaterialEntities",[/^IFCMATERIALLAYERSETUSAGE$/,/^IFCMATERIALCONSTITUENTSET$/,/^IFCMATERIAL$/,/^IFCMATERIALLIST$/]),t(this,"facetType","Material"),t(this,"value"),t(this,"uri")}serialize(e){if(!this.value||!this.uri)return"<material />";const t=xo("Value",this.value);let i="";return"requirement"===e&&(i+=`cardinality="${this.cardinality}"`,i+=this.uri?`uri=${this.uri}`:"",i+=this.instructions?`instructions="${this.instructions}"`:""),`<material ${i}>\n ${t}\n</material>`}async getEntities(e,t){const i=this._components.get(Zn);for(const[n,s]of i.list){if(!e.find(e=>e.test(n)))continue;const i=await s.getItemsOfCategories(this._ifcMaterialEntities),r=Object.values(i).flat();if(0===r.length)continue;const o=await s.getItemsData(r,{relations:{AssociatedTo:{attributes:!0,relations:!1},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const e of o){if(!("value"in e._localId&&"value"in e._category&&Array.isArray(e.AssociatedTo)))continue;if(!this.hasValidMaterial(e))continue;const i=e.AssociatedTo.map(e=>"value"in e._localId&&e._localId.value?e._localId.value:null).filter(e=>null!==e);Ue.append(t,n,...i)}}}async test(e,t,i={skipIfFails:!0}){const n=this._components.get(Zn);for(const[s,r]of Object.entries(e)){const e=n.list.get(s);if(!e)continue;const o=await e.getItemsData([[...r][0]],{relations:{AssociatedTo:{attributes:!1,relations:!1},HasAssociations:{attributes:!0,relations:!0},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const e of o){const n=this.getItemChecks(t,s,e,i.skipIfFails);if(n)if(Array.isArray(e.HasAssociations))for(const t of e.HasAssociations){if(!this._ifcMaterialEntities.some(e=>"value"in t._category&&e.test(t._category.value)))continue;if(this.hasValidMaterial(t,n))break}else n.push({parameter:null,currentValue:null,requiredValue:this.value,pass:!1})}}}hasValidMaterial(e,t){let i=!1;if("value"in e._category&&"IFCMATERIAL"===e._category.value){this.evalValue(e,t)&&(i=!0)}else for(const[n,s]of Object.entries(e))if(["ForLayerSet","MaterialLayers","Material","MaterialConstituents","Materials"].includes(n)&&Array.isArray(s))for(const e of s){if("value"in e._category&&"IFCMATERIAL"===e._category.value){if(this.evalValue(e,t)){i=!0;break}}else{if(this.hasValidMaterial(e)){i=!0;break}}}return i}evalValue(e,t){if(!this.value)return null==t||t.push({parameter:null,currentValue:e.Name&&"value"in e.Name?e.Name.value:null,pass:!0}),!0;if(!("value"in e._category)||"IFCMATERIAL"!==e._category.value)return null;let i=!1;return e.Name&&"value"in e.Name&&(i=this.evalRequirement(e.Name.value,this.value,"Value",t)),i||(e.Category&&"value"in e.Category&&(i=this.evalRequirement(e.Category.value,this.value,"Value",t)),i)}}class Mo extends vo{constructor(e,i){super(e),t(this,"facetType","PartOf"),t(this,"_entityFacet"),t(this,"_entity"),t(this,"relation"),t(this,"cardinality","required"),this._entity=i,this._entityFacet=new To(e,i.name),this._entityFacet.predefinedType=i.predefinedType}set entity(e){this._entity=e;const{name:t,predefinedType:i}=e;this._entityFacet=new To(this._components,t),this._entityFacet.predefinedType=i}get entity(){return this._entity}serialize(){return""}async getEntities(e,t){}async test(e){}}class Po{constructor(e,i,n){t(this,"name"),t(this,"ifcVersion",new Set),t(this,"identifier",T.create()),t(this,"description"),t(this,"instructions"),t(this,"requirementsDescription"),t(this,"applicability",new h.DataSet),t(this,"requirements",new h.DataSet),t(this,"components"),this.components=e,this.name=i;for(const e of n)this.ifcVersion.add(e)}set(e){const t=e,i=this;for(const n in e){if("identifier"===n)continue;const e=t[n];n in this&&(i[n]=e)}return this.components.get(No).list.set(this.identifier,this),this}async test(e,t={skipIfFails:!0}){const i=new h.DataMap;if(0===this.requirements.size)return i;const n={},s=[];for(const t of this.applicability)s.push(t.getEntities(e,n));await Promise.all(s);const r=[];for(const e of this.requirements)r.push(e.test(n,i,t));return await Promise.all(r),i}serialize(){const e=`name="${this.name}"`,t=this.identifier?`identifier="${this.identifier}"`:"",i=this.description?`description="${this.description}"`:"",n=this.instructions?`instructions="${this.instructions}"`:"";return`<specification ifcVersion="${[...this.ifcVersion].join(" ")}" ${e} ${t} ${i} ${n}>\n <applicability minOccurs="1" maxOccurs="unbounded">\n ${[...this.applicability].map(e=>e.serialize("applicability")).join("\n")}\n </applicability>\n <requirements>\n ${[...this.requirements].map(e=>e.serialize("requirement")).join("\n")}\n </requirements>\n </specification>`}}const Io=e=>{if(!e)return;const t={};if("simpleValue"in e&&(t.type="simple",t.parameter=e.simpleValue),"restriction"in e){const i=e.restriction,n=Object.keys(i);if("pattern"in i&&(t.type="pattern",t.parameter=i.pattern.value),"enumeration"in i){t.type="enumeration";const e=i.enumeration.map(({value:e})=>i.base.includes("string")?String(e):i.base.includes("integer")||i.base.includes("double")?Number(e):e);t.parameter=e}if(n.some(e=>["minInclusive","minExclusive","maxInclusive","maxExclusive"].includes(e))){t.type="bounds";const e={},s=n.find(e=>e.includes("min")),r=n.find(e=>e.includes("max"));s&&(e.minInclusive="minInclusive"===s,e.min=i[s].value),r&&(e.maxInclusive="maxInclusive"===r,e.max=i[r].value),t.parameter=e}if(n.some(e=>["minLength","length","maxLength"].includes(e))){t.type="length";const e={};void 0!==i.length&&(e.length=i.length.value),void 0!==i.minLength&&(e.min=i.minLength.value),void 0!==i.maxLength&&(e.max=i.maxLength.value),t.parameter=e}}return void 0!==t.parameter?t:void 0},zo=(e,t)=>{const i=[];for(const n of t){const t=n.name,s=Io(t);if(!s)continue;const r=new To(e,s);n.cardinality&&(r.cardinality=n.cardinality),r.predefinedType=Io(n.predefinedType),r.instructions=n.instructions,i.push(r)}return i},Do=(e,t)=>{const i=[];for(const n of t){const t=n.name,s=Io(t);if(!s)continue;const r=new So(e,s);n.cardinality&&(r.cardinality=n.cardinality),r.value=Io(n.value),r.instructions=n.instructions,i.push(r)}return i},ko=(e,t)=>{const i=[];for(const n of t){const t=new Eo(e);n.cardinality&&(t.cardinality=n.cardinality);const s=Io(n.value);"enumeration"===(null==s?void 0:s.type)&&Array.isArray(s.parameter)&&(s.parameter=s.parameter.map(String)),t.value=s,t.uri=n.uri,t.instructions=n.instructions,i.push(t)}return i},Bo=(e,t)=>{const i=[];for(const n of t){const t=n.propertySet,s=n.baseName,r=Io(t),o=Io(s);if(!o||!r)continue;const a=new Ao(e,r,o);n.cardinality&&(a.cardinality=n.cardinality);const l=Io(n.value);a.value=l,a.dataType=n.dataType,a.uri=n.uri,a.instructions=n.instructions,i.push(a)}return i},Oo=(e,t)=>{const i=[];for(const n of t){const t=n.system,s=Io(t);if(!s)continue;const r=new Co(e,s);n.cardinality&&(r.cardinality=n.cardinality);const o=Io(n.value);"simple"===(null==o?void 0:o.type)&&(o.parameter=String(o.parameter)),"enumeration"===(null==o?void 0:o.type)&&Array.isArray(o.parameter)&&(o.parameter=o.parameter.map(String)),r.value=o,r.uri=n.uri,r.instructions=n.instructions,i.push(r)}return i},Vo=(e,t)=>{const i=[];for(const n of t){const t=Io(n.entity.name);if(!t)continue;const s=Io(n.entity.predefinedType),r=new Mo(e,{name:t,predefinedType:s});r.relation=n.relation,n.cardinality&&(r.cardinality=n.cardinality),r.instructions=n.instructions,i.push(r)}return i},Lo=class e extends g{constructor(n){super(n),t(this,"enabled",!0),t(this,"IDSInfo"),t(this,"list",new i.DataMap),n.add(e.uuid,this)}getModelIdMap(e){const t={},i={};for(const[n,s]of e){const e=[...s].filter(([,e])=>e.pass).map(([e])=>e);Ue.append(t,n,...e);const r=[...s].filter(([,e])=>!e.pass).map(([e])=>e);Ue.append(i,n,...r)}return{pass:t,fail:i}}create(e,t,i){const n=new Po(this.components,e,t);return i&&(n.identifier=i),this.list.set(n.identifier,n),n}load(t){const i=[],n=e.xmlParser.parse(t).ids,{specifications:s,info:r}=n;if(this.IDSInfo={...r},s&&s.specification){const e=Array.isArray(s.specification)?s.specification:[s.specification];for(const t of e){const{name:e,ifcVersion:n,description:s,instructions:r,identifier:o}=t;if(!e||!n)continue;const a=[],l=[],{applicability:c,requirements:h}=t;if(c){const{maxOccurs:e,...t}=c,i=Array.isArray(t)?t:[t];for(const e of i)for(const t in e){const i=Array.isArray(e[t])?e[t]:[e[t]];if("entity"===t){const e=zo(this.components,i);a.push(...e)}if("attribute"===t){const e=Do(this.components,i);a.push(...e)}if("material"===t){const e=ko(this.components,i);a.push(...e)}if("classification"===t){const e=Oo(this.components,i);a.push(...e)}if("property"===t){const e=Bo(this.components,i);a.push(...e)}if("partOf"===t){const e=Vo(this.components,i);a.push(...e)}}}let d;if(h){const{maxOccurs:e,...t}=h;d=h.description;const i=Array.isArray(t)?t:[t];for(const e of i)for(const t in e){const i=Array.isArray(e[t])?e[t]:[e[t]];if("entity"===t){const e=zo(this.components,i);l.push(...e)}if("attribute"===t){const e=Do(this.components,i);l.push(...e)}if("material"===t){const e=ko(this.components,i);l.push(...e)}if("classification"===t){const e=Oo(this.components,i);l.push(...e)}if("property"===t){const e=Bo(this.components,i);l.push(...e)}if("partOf"===t){const e=Vo(this.components,i);l.push(...e)}}}const u=this.create(e,n.split(/\s+/),o);u.description=s,u.instructions=r,u.requirementsDescription=d,u.applicability.add(...a),u.requirements.add(...l),i.push(u)}}return i}export(e,t=this.list.values()){const i=t??this.list;return`<ids xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://standards.buildingsmart.org/IDS http://standards.buildingsmart.org/IDS/1.0/ids.xsd" xmlns:ids="http://standards.buildingsmart.org/IDS">\n \x3c!-- Made with That Open Engine ${$r.release} (https://github.com/thatopen/engine_components) --\x3e\n <info>\n <title>${e.title}</title>\n ${e.copyright?`<copyright>${e.copyright}</copyright>`:""}\n ${e.version?`<version>${e.version}</version>`:""}\n ${e.description?`<description>${e.description}</description>`:""}\n ${e.author?`<author>${e.author}</author>`:""}\n ${e.date?`<date>${e.date.toISOString().split("T")[0]}</date>`:""}\n ${e.purpose?`<purpose>${e.purpose}</purpose>`:""}\n ${e.milestone?`<milestone>${e.milestone}</milestone>`:""}\n </info>\n <specifications>\n ${[...i].map(e=>e.serialize()).join("\n")}\n </specifications>\n</ids>`}};t(Lo,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c"),t(Lo,"xmlParser",new Me({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0}));let No=Lo;const Fo=class e extends g{constructor(i){super(i),t(this,"enabled",!0),i.add(e.uuid,this)}static distanceFromPointToLine(e,t,i,n=!1){const s=new d.Line3,r=new d.Vector3;return s.set(t,i),s.closestPointToPoint(e,n,r),r.distanceTo(e)}round(e){const t=1e3;e.x=Math.trunc(e.x*t)/t,e.y=Math.trunc(e.y*t)/t,e.z=Math.trunc(e.z*t)/t}async getVolumeFromFragments(e){return console.warn("getVolumeFromFragments is deprecated. Use getItemsVolume instead."),this.getItemsVolume(e)}async getItemsVolume(e){let t=0;const i=this.components.get(Zn);for(const[n,s]of Object.entries(e)){const e=i.list.get(n);e&&(t+=await e.getItemsVolume([...s]))}return t}static convertUnits(e,t,i,n=2){const s={m:1,cm:.01,mm:.001,km:1e3,m2:1,cm2:1e-4,mm2:1e-6,km2:1e6,m3:1,cm3:1e-6,mm3:1e-9,km3:1e9};if(!s[t]||!s[i])throw new Error("Invalid units provided for conversion.");if(!Number.isInteger(n)||n<0||n>5)throw new Error("Precision must be an integer between 0 and 5.");const r=e*(s[t]/s[i]),o=10**n;return Math.round(r*o)/o}};t(Fo,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");let Ro=Fo;const Uo=(e,t,i)=>{const n=new d.Vector3(-t.z,0,t.x),s=new d.Vector3(t.x+n.x,0,t.z+n.z).normalize().multiplyScalar(i/2);return[e.x+s.x,e.y,e.z+s.z,e.x-s.x,e.y,e.z-s.z]},jo=(e,t,i)=>{const n=new d.Vector3(-t.z,0,t.x),s=e.x-t.x*i+n.x*i*.4,r=e.z-t.z*i+n.z*i*.4,o=e.x-t.x*i-n.x*i*.4,a=e.z-t.z*i-n.z*i*.4;return[e.x,e.y,e.z,s,e.y,r,e.x,e.y,e.z,o,e.y,a]},$o=()=>[],Wo=(e,t,i)=>{const n=new d.Vector3(-t.z,0,t.x),s=e.clone().addScaledVector(t,-i),r=s.clone().addScaledVector(n,.4*i),o=s.clone().addScaledVector(n,.4*-i);return[e.x,e.y,e.z,r.x,r.y,r.z,o.x,o.y,o.z]};class Go extends h.DataMap{constructor(){super()}getBySystem(e){const t=new Map;for(const[i,n]of this)n.system===e&&t.set(i,n.data);return t}}class Ho extends h.DataMap{constructor(e){super(),t(this,"_container"),this._container=e,this.deleteGuard=e=>"0"!==e,this.set("0",{name:"0",visible:!0,material:new d.LineBasicMaterial({color:0})})}create(e,t){if(!this.has(e)){const i={name:e,visible:(null==t?void 0:t.visible)??!0,material:(null==t?void 0:t.material)??new d.LineBasicMaterial({color:0})};this.set(e,i)}return this.get(e)}setColor(e,t){const i=this.get(e);i&&(i.material.color.setHex(t),this.set(e,i))}setMaterial(e,t){const i=this.get(e);if(!i)return;const n=i.material;i.material=t,this._container.traverse(i=>{i.userData.layer===e&&(i.userData.isDimension||i.isLineSegments&&(i.material=t))}),n.dispose(),this.set(e,i)}setVisibility(e,t){const i=this.get(e);i&&(i.visible=t,this._container.traverse(i=>{i.userData.layer===e&&(i.visible=t)}),this.set(e,i))}assign(e,t){const i=this.get(t);i&&(e.userData.layer=t,i.visible||(e.visible=!1),e.isLineSegments&&(e.material=i.material))}resolveColor(e){const t=this.get(e);if(t)return t.material.color.getHex()}}const qo=class e extends d.Group{constructor(i){super(),t(this,"_viewport"),t(this,"_border"),t(this,"_handles",[]),t(this,"_raycaster",new d.Raycaster),t(this,"_resizable",!1),t(this,"_movable",!1),t(this,"_dragHandle",null),t(this,"_dragConstraints",[]),t(this,"_hoveredHandle",null),t(this,"_moveDrag",null),t(this,"_hoveringBorder",!1),t(this,"_normalMat"),t(this,"_hoverMat"),t(this,"_borderMat"),this._viewport=i,this._borderMat=new d.LineBasicMaterial({color:e._BORDER_COLOR,depthTest:!1});const n=new d.BufferGeometry;n.setAttribute("position",new d.BufferAttribute(new Float32Array(24),3)),this._border=new d.LineSegments(n,this._borderMat),this._border.renderOrder=999,this._border.frustumCulled=!1,this._border.userData.isDimension=!0,this.add(this._border),this._normalMat=new d.MeshBasicMaterial({color:e._BORDER_COLOR}),this._hoverMat=new d.MeshBasicMaterial({color:e._BORDER_HOVER_COLOR});const s=new d.SphereGeometry(.05,8,6);for(const t of e._HANDLE_DEFS){const e=new d.Mesh(s,this._normalMat);e.renderOrder=1e3,e.visible=!1,e.userData.constraints=t.constraints,e.userData.isDimension=!0,this.add(e),this._handles.push(e)}this.update()}get resizable(){return this._resizable}set resizable(e){this._resizable=e;for(const t of this._handles)t.visible=e;e||(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat,this._hoveredHandle=null),this._dragHandle=null,this._dragConstraints=[])}get movable(){return this._movable}set movable(e){this._movable=e,e||(this._moveDrag=null,this._setBorderHover(!1))}get isDragging(){return null!==this._dragHandle||null!==this._moveDrag}update(){const e=this._viewport,t=e.left,i=e.right,n=-e.top,s=-e.bottom,r=.005,o=this._border.geometry.attributes.position;o.setXYZ(0,t,r,n),o.setXYZ(1,i,r,n),o.setXYZ(2,i,r,n),o.setXYZ(3,i,r,s),o.setXYZ(4,i,r,s),o.setXYZ(5,t,r,s),o.setXYZ(6,t,r,s),o.setXYZ(7,t,r,n),o.needsUpdate=!0,this._border.geometry.computeBoundingSphere();const a=(t+i)/2,l=(n+s)/2,c=.01,h=[[t,c,n],[i,c,n],[i,c,s],[t,c,s],[a,c,n],[i,c,l],[a,c,s],[t,c,l]];for(let e=0;e<this._handles.length;e++)this._handles[e].position.set(...h[e])}onPointerMove(t){if(this._dragHandle){const e=this._projectToLocal(t);if(!e)return;for(const t of this._dragConstraints)switch(t){case"left":this._viewport.left=e.x;break;case"right":this._viewport.right=e.x;break;case"top":this._viewport.top=-e.z;break;case"bottom":this._viewport.bottom=-e.z}return this._viewport.right<this._viewport.left&&([this._viewport.left,this._viewport.right]=[this._viewport.right,this._viewport.left],this._dragConstraints=this._dragConstraints.map(e=>"right"===e?"left":"left"===e?"right":e)),this._viewport.top<this._viewport.bottom&&([this._viewport.top,this._viewport.bottom]=[this._viewport.bottom,this._viewport.top],this._dragConstraints=this._dragConstraints.map(e=>"top"===e?"bottom":"bottom"===e?"top":e)),void this.update()}if(this._moveDrag){const e=this._projectToLocal(t);if(!e)return;const i=e.x-this._moveDrag.origin.x,n=e.z-this._moveDrag.origin.z;return this._viewport.left=this._moveDrag.left0+i,this._viewport.right=this._moveDrag.right0+i,this._viewport.top=this._moveDrag.top0-n,this._viewport.bottom=this._moveDrag.bottom0-n,void this.update()}if(!this._resizable&&!this._movable)return;this._raycaster.set(t.origin,t.direction);let i=null;if(this._resizable){const e=this._handles.filter(e=>e.visible),t=this._raycaster.intersectObjects(e,!1);i=t.length>0?t[0].object:null}if(i!==this._hoveredHandle&&(this._hoveredHandle&&(this._hoveredHandle.material=this._normalMat),i&&(i.material=this._hoverMat),this._hoveredHandle=i),this._movable&&!this._hoveredHandle){this._raycaster.params.Line={threshold:e._LINE_THRESHOLD};const t=this._raycaster.intersectObject(this._border,!1).length>0;this._setBorderHover(t)}else this._setBorderHover(!1)}onPointerDown(t){if(this._resizable||this._movable){if(this._raycaster.set(t.origin,t.direction),this._resizable){const e=this._handles.filter(e=>e.visible),t=this._raycaster.intersectObjects(e,!1);if(t.length>0)return this._dragHandle=t[0].object,void(this._dragConstraints=[...this._dragHandle.userData.constraints])}if(this._movable){this._raycaster.params.Line={threshold:e._LINE_THRESHOLD};if(this._raycaster.intersectObject(this._border,!1).length>0){const e=this._projectToLocal(t);if(!e)return;this._moveDrag={origin:e,left0:this._viewport.left,right0:this._viewport.right,top0:this._viewport.top,bottom0:this._viewport.bottom}}}}}onPointerUp(){this._dragHandle=null,this._dragConstraints=[],this._moveDrag=null}dispose(){this._border.geometry.dispose(),this._borderMat.dispose(),this._normalMat.dispose(),this._hoverMat.dispose(),this._handles.length>0&&this._handles[0].geometry.dispose(),this.removeFromParent()}_projectToLocal(e){this.updateWorldMatrix(!0,!1);const t=new d.Vector3(0,1,0).transformDirection(this.matrixWorld),i=(new d.Vector3).setFromMatrixPosition(this.matrixWorld),n=(new d.Plane).setFromNormalAndCoplanarPoint(t,i),s=new d.Vector3;return e.intersectPlane(n,s)?this.worldToLocal(s):null}_setBorderHover(t){t!==this._hoveringBorder&&(this._hoveringBorder=t,this._borderMat.color.setHex(t?e._BORDER_HOVER_COLOR:e._BORDER_COLOR))}};t(qo,"_BORDER_COLOR",22015),t(qo,"_BORDER_HOVER_COLOR",16746496),t(qo,"_LINE_THRESHOLD",.06),t(qo,"_HANDLE_DEFS",[{constraints:["left","top"]},{constraints:["right","top"]},{constraints:["right","bottom"]},{constraints:["left","bottom"]},{constraints:["top"]},{constraints:["right"]},{constraints:["bottom"]},{constraints:["left"]}]);let Zo=qo;class Yo{constructor(e){t(this,"uuid",d.MathUtils.generateUUID()),t(this,"name"),t(this,"camera"),t(this,"onDisposed",new f),t(this,"_left"),t(this,"_right"),t(this,"_top"),t(this,"_bottom"),t(this,"_drawingScale"),t(this,"_container",null),t(this,"_helper",null),t(this,"_helperVisible",!1),this._left=e.left,this._right=e.right,this._top=e.top,this._bottom=e.bottom,this._drawingScale=e.scale??100,this.name=e.name??"Drawing Viewport",this.camera=new d.OrthographicCamera(this._left,this._right,this._top,this._bottom,.1,30),this.camera.up.set(0,0,-1),this.camera.position.set(0,10,0),this.camera.lookAt(0,0,0),this.camera.layers.set(1)}get left(){return this._left}set left(e){var t;this._left=e,this.camera.left=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get right(){return this._right}set right(e){var t;this._right=e,this.camera.right=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get top(){return this._top}set top(e){var t;this._top=e,this.camera.top=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get bottom(){return this._bottom}set bottom(e){var t;this._bottom=e,this.camera.bottom=e,this.camera.updateProjectionMatrix(),null==(t=this._helper)||t.update()}get drawingScale(){return this._drawingScale}set drawingScale(e){this._drawingScale=e}get helper(){return this._helper||(this._helper=new Zo(this)),this._helper}get helperVisible(){return this._helperVisible}set helperVisible(e){var t,i;this._helperVisible=e,e?null==(t=this._container)||t.add(this.helper):null==(i=this._helper)||i.removeFromParent()}get bbox(){const e=new d.Vector3(this._left,0,-this._top),t=new d.Vector3(this._right,0,-this._bottom);return new d.Box3(e,t)}get size(){const e=new d.Vector3;return this.bbox.getSize(e),new d.Vector2(1e3*e.x,1e3*e.z)}get localXAxis(){return new d.Vector3(1,0,0)}get localYAxis(){return new d.Vector3(0,0,-1)}get normal(){return new d.Vector3(0,1,0)}setContainer(e){this._container=e,this._helperVisible&&this._helper&&e.add(this._helper)}clipLine(e){const t=this.bbox,{start:i,end:n}=e,s=t.containsPoint(i),r=t.containsPoint(n);if(s&&r)return e;if(!s&&!r){const t=this.getPlaneIntersections(e);return t.length<2?null:new d.Line3(t[0],t[1])}const o=this.getPlaneIntersections(e);return 0===o.length?null:s?new d.Line3(i,o[0]):new d.Line3(o[0],n)}dispose(){var e;null==(e=this._helper)||e.dispose(),this._helper=null,this.onDisposed.trigger(),this.onDisposed.reset()}get bboxPlanes(){const e=this.bbox;return[new d.Plane(new d.Vector3(1,0,0),-e.min.x),new d.Plane(new d.Vector3(-1,0,0),e.max.x),new d.Plane(new d.Vector3(0,0,1),-e.min.z),new d.Plane(new d.Vector3(0,0,-1),e.max.z)]}getPlaneIntersections(e){const t=[];for(const i of this.bboxPlanes){const n=new d.Vector3;i.intersectLine(e,n)&&this.bbox.containsPoint(n)&&t.push(n)}return t}}class Xo extends h.DataMap{constructor(e){super(),t(this,"_container"),this._container=e,this.onBeforeDelete.add(({value:e})=>{this._container.remove(e.camera),e.dispose()})}create(e){const t=new Yo(e);return this._container.add(t.camera),t.setContainer(this._container),this.set(t.uuid,t),t}}const Ko=class e extends d.Group{constructor(i){super(),t(this,"_drawing"),t(this,"_topFrame"),t(this,"_pillars"),t(this,"_bottomFrame"),t(this,"_topPlane"),t(this,"_bottomPlane"),t(this,"_frameMat"),t(this,"_depthMat"),t(this,"_planeMat"),t(this,"width",10),t(this,"height",10),t(this,"farHandle",new d.Object3D),t(this,"widthHandle",new d.Object3D),t(this,"heightHandle",new d.Object3D),this._drawing=i,this._frameMat=new d.LineBasicMaterial({color:e._FRAME_COLOR,depthTest:!1}),this._depthMat=new d.LineBasicMaterial({color:e._DEPTH_COLOR,depthTest:!1,transparent:!0,opacity:.4}),this._planeMat=new d.MeshBasicMaterial({color:e._FRAME_COLOR,transparent:!0,opacity:.07,side:d.DoubleSide,depthTest:!1});const n=()=>{const e=new d.BufferGeometry;return e.setAttribute("position",new d.BufferAttribute(new Float32Array(12),3)),e.setIndex([0,1,2,0,2,3]),e};this._topPlane=new d.Mesh(n(),this._planeMat),this._topPlane.renderOrder=998,this._topPlane.frustumCulled=!1,this._topPlane.userData.isDimension=!0,this._bottomPlane=new d.Mesh(n(),this._planeMat),this._bottomPlane.renderOrder=998,this._bottomPlane.frustumCulled=!1,this._bottomPlane.userData.isDimension=!0;const s=new d.BufferGeometry;s.setAttribute("position",new d.BufferAttribute(new Float32Array(24),3)),this._topFrame=new d.LineSegments(s,this._frameMat),this._topFrame.renderOrder=999,this._topFrame.frustumCulled=!1,this._topFrame.userData.isDimension=!0;const r=new d.BufferGeometry;r.setAttribute("position",new d.BufferAttribute(new Float32Array(24),3)),this._pillars=new d.LineSegments(r,this._depthMat),this._pillars.renderOrder=999,this._pillars.frustumCulled=!1,this._pillars.userData.isDimension=!0;const o=new d.BufferGeometry;o.setAttribute("position",new d.BufferAttribute(new Float32Array(24),3)),this._bottomFrame=new d.LineSegments(o,this._depthMat),this._bottomFrame.renderOrder=999,this._bottomFrame.frustumCulled=!1,this._bottomFrame.userData.isDimension=!0,this.add(this._topPlane,this._bottomPlane),this.add(this._topFrame,this._pillars,this._bottomFrame),this.add(this.farHandle,this.widthHandle,this.heightHandle),this.farHandle.rotation.x=Math.PI,this.update()}update(){const e=this.width/2,t=this.height/2,i=-this._drawing.far,n=.005,s=-e,r=e,o=-t,a=t,l=this._topFrame.geometry.attributes.position;l.setXYZ(0,s,n,o),l.setXYZ(1,r,n,o),l.setXYZ(2,r,n,o),l.setXYZ(3,r,n,a),l.setXYZ(4,r,n,a),l.setXYZ(5,s,n,a),l.setXYZ(6,s,n,a),l.setXYZ(7,s,n,o),l.needsUpdate=!0,this._topFrame.geometry.computeBoundingSphere();const c=this._pillars.geometry.attributes.position;c.setXYZ(0,s,n,o),c.setXYZ(1,s,i,o),c.setXYZ(2,r,n,o),c.setXYZ(3,r,i,o),c.setXYZ(4,r,n,a),c.setXYZ(5,r,i,a),c.setXYZ(6,s,n,a),c.setXYZ(7,s,i,a),c.needsUpdate=!0,this._pillars.geometry.computeBoundingSphere();const h=this._bottomFrame.geometry.attributes.position;h.setXYZ(0,s,i,o),h.setXYZ(1,r,i,o),h.setXYZ(2,r,i,o),h.setXYZ(3,r,i,a),h.setXYZ(4,r,i,a),h.setXYZ(5,s,i,a),h.setXYZ(6,s,i,a),h.setXYZ(7,s,i,o),h.needsUpdate=!0,this._bottomFrame.geometry.computeBoundingSphere();const d=(e,t)=>{const i=e.geometry.attributes.position;i.setXYZ(0,s,t,o),i.setXYZ(1,r,t,o),i.setXYZ(2,r,t,a),i.setXYZ(3,s,t,a),i.needsUpdate=!0,e.geometry.computeBoundingSphere()};d(this._topPlane,n),d(this._bottomPlane,i),this.farHandle.position.set(0,i,0),this.widthHandle.position.set(r,n,0),this.heightHandle.position.set(0,n,a)}attachFarGizmo(e){e.attach(this.farHandle),e.setSpace("local"),e.showX=!1,e.showZ=!1,e.addEventListener("objectChange",()=>{this.farHandle.position.x=0,this.farHandle.position.z=0;const e=Math.max(.1,-this.farHandle.position.y);this._drawing.far=e,this.farHandle.position.y=-e,this.update()})}attachWidthGizmo(e){e.attach(this.widthHandle),e.setSpace("local"),e.showY=!1,e.showZ=!1,e.addEventListener("objectChange",()=>{this.widthHandle.position.y=.005,this.widthHandle.position.z=0,this.width=Math.max(.1,2*this.widthHandle.position.x),this.widthHandle.position.x=this.width/2,this.update()})}attachHeightGizmo(e){e.attach(this.heightHandle),e.setSpace("local"),e.showX=!1,e.showY=!1,e.addEventListener("objectChange",()=>{this.heightHandle.position.x=0,this.heightHandle.position.y=.005,this.height=Math.max(.1,2*this.heightHandle.position.z),this.heightHandle.position.z=this.height/2,this.update()})}dispose(){this._topPlane.geometry.dispose(),this._bottomPlane.geometry.dispose(),this._topFrame.geometry.dispose(),this._pillars.geometry.dispose(),this._bottomFrame.geometry.dispose(),this._planeMat.dispose(),this._frameMat.dispose(),this._depthMat.dispose(),this.removeFromParent()}};t(Ko,"_FRAME_COLOR",22015),t(Ko,"_DEPTH_COLOR",22015);let Qo=Ko;function Jo(e,t){if(3!==e.length||3!==t.length)throw new Error("computeAlignmentMatrix requires exactly 3 point pairs.");const i=(e,t)=>{const i=(new d.Vector3).subVectors(e[1],e[0]),n=(new d.Vector3).subVectors(e[2],e[0]);if((new d.Vector3).crossVectors(i,n).length()<1e-6)throw new Error(`${t} points are collinear — three non-collinear points are required to define a plane.`)};i(e,"Drawing"),i(t,"World");const n=(e,t,i)=>{const n=(new d.Vector3).subVectors(t,e),s=(new d.Vector3).subVectors(i,e),r=n.clone().normalize(),o=(new d.Vector3).crossVectors(n,s).normalize(),a=(new d.Vector3).crossVectors(r,o).normalize();return(new d.Matrix4).makeBasis(r,o,a)},s=n(e[0],e[1],e[2]),r=n(t[0],t[1],t[2]).clone().multiply(s.clone().invert()),o=e[0].distanceTo(e[1]);if(o<1e-10)throw new Error("The first two drawing points are coincident — cannot compute scale.");const a=t[0].distanceTo(t[1])/o,l=e[0].clone().multiplyScalar(a).applyMatrix4(r),c=(new d.Vector3).subVectors(t[0],l),h=(new d.Quaternion).setFromRotationMatrix(r),u=new d.Matrix4;return u.compose(c,h,new d.Vector3(a,a,a)),u}class ea{constructor(e){t(this,"uuid",d.MathUtils.generateUUID()),t(this,"_raycaster",new d.Raycaster),t(this,"_components"),t(this,"world",null),t(this,"three",new d.Group),t(this,"annotations",new Go),t(this,"layers",new Ho(this.three)),t(this,"activeLayer","0"),t(this,"far",10),t(this,"viewports",new Xo(this.three)),t(this,"onDisposed",new f),this._components=e}raycast(e,t=null){this._raycaster.set(e.origin,e.direction),this._raycaster.layers.set(1),this._raycaster.params.Line&&(this._raycaster.params.Line.threshold=.1);const i=[];this.three.traverse(e=>{e instanceof d.LineSegments&&!e.userData.isDimension&&i.push(e)});const n=this._raycaster.intersectObjects(i,!1);if(0===n.length)return null;const s=n[0],r=this.three.worldToLocal(s.point.clone());let o=null;if(s.object instanceof d.LineSegments&&void 0!==s.index){const e=s.object.geometry.attributes.position,t=s.index,i=new d.Vector3(e.getX(t),e.getY(t),e.getZ(t)),n=new d.Vector3(e.getX(t+1),e.getY(t+1),e.getZ(t+1));i.applyMatrix4(s.object.matrixWorld),this.three.worldToLocal(i),n.applyMatrix4(s.object.matrixWorld),this.three.worldToLocal(n),o=new d.Line3(i,n)}return{point:r,object:s.object,viewport:t,line:o}}alignTo(e,t){Jo(e,t).decompose(this.three.position,this.three.quaternion,this.three.scale)}static toDrawingSpace(e,t){e.updateWorldMatrix(!0,!1),t.three.updateWorldMatrix(!0,!1);const i=(new d.Matrix4).copy(t.three.matrixWorld).invert().multiply(e.matrixWorld),n=e.geometry.attributes.position,s=n.count,r=new Float32Array(3*s),o=new d.Vector3;for(let e=0;e<s;e++)o.fromBufferAttribute(n,e).applyMatrix4(i),r[3*e]=o.x,r[3*e+1]=0,r[3*e+2]=o.z;const a=new d.BufferGeometry;return a.setAttribute("position",new d.BufferAttribute(r,3)),new d.LineSegments(a)}addProjectionLines(e,t="0"){return this.layers.has(t)||(console.warn(`[TechnicalDrawing] Layer "${t}" does not exist. Falling back to "0".`),t="0"),this.layers.assign(e,t),e.layers.set(1),e.material instanceof d.LineDashedMaterial&&e.computeLineDistances(),e.geometry.computeBoundsTree({strategy:0,indirect:!0,type:Nn}),this.three.add(e),e}async addProjectionFromItems(e,t){if(!this.world)return void console.warn("[TechnicalDrawing] addProjectionFromItems: drawing has no world assigned.");for(const e of[t.layers.visible,t.layers.hidden])if(!this.layers.has(e))return void console.warn(`[TechnicalDrawing] Layer "${e}" does not exist — create it before calling addProjectionFromItems.`);const i=this._components.get(hr),n=i.projectionDirection.clone(),s=i.nearPlane,r=i.farPlane;try{this.three.updateWorldMatrix(!0,!1);const n=new d.Vector3(0,-1,0).transformDirection(this.three.matrixWorld).normalize();i.projectionDirection.copy(n);const s=(new d.Matrix4).makeRotationFromQuaternion((new d.Quaternion).setFromUnitVectors(n,new d.Vector3(0,-1,0))),r=(new d.Vector3).setFromMatrixPosition(this.three.matrixWorld).applyMatrix4(s).y;i.farPlane=r,i.nearPlane=r-this.far;const o=await i.get(e,this.world,{onProgress:t.onProgress}),a=e=>ea.toDrawingSpace(new d.LineSegments(e),this);this.addProjectionLines(a(o.visible),t.layers.visible),this.addProjectionLines(a(o.hidden),t.layers.hidden)}finally{i.projectionDirection.copy(n),i.nearPlane=s,i.farPlane=r}}orientTo(e){const t=e.clone().normalize(),i=Math.SQRT1_2;t.x>.999?this.three.quaternion.set(.5,-.5,.5,.5):t.x<-.999?this.three.quaternion.set(.5,.5,-.5,.5):t.y>.999?this.three.quaternion.set(0,0,1,0):t.y<-.999?this.three.quaternion.set(0,0,0,1):t.z>.999?this.three.quaternion.set(0,i,-i,0):t.z<-.999?this.three.quaternion.set(i,0,0,i):console.warn("[TechnicalDrawing] orientTo: direction does not match any of the 6 standard axes.")}dispose(){this.viewports.clear(),this.layers.clear(),this.annotations.clear();this._components.get(v).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset()}}class ta{constructor(e){t(this,"styles",new h.DataMap),t(this,"activeStyle","default"),t(this,"onCommit",new f),t(this,"onUpdate",new f),t(this,"onDelete",new f),t(this,"onDisposed",new f),t(this,"_knownDrawings",new Set),t(this,"_previewMaterial",new d.LineBasicMaterial({color:16737894,depthTest:!1})),t(this,"_previewObject",null),t(this,"_previewDrawing",null),t(this,"_materialCache",new h.DataMap),t(this,"_meshMaterialCache",new h.DataMap),t(this,"_ownsChildGeometry",!0),this._components=e,this.styles.onItemUpdated.add(({key:e})=>{const t=this._materialCache.get(e);t&&t.color.setHex(this._resolveStyle(e).color);const i=this._meshMaterialCache.get(e);i&&i.color.setHex(this._resolveStyle(e).color);const n=this._components.get(Ra),s=n?[...n.list.values()]:[...this._knownDrawings];for(const t of s){const i=[...t.annotations.getBySystem(this)].filter(([,t])=>t.style===e).map(([e])=>e);i.length>0&&this.update(t,i,{})}})}_onAfterPersist(e,t){}_onDispose(){}_updatePreview(){}get(e){const t=new h.DataMap;for(const i of e)for(const[e,n]of i.annotations.getBySystem(this))t.set(e,{drawingUuid:i.uuid,item:n});return t}add(e,t){const i={uuid:d.MathUtils.generateUUID(),style:this.activeStyle,...t},n=this._persist(e,i);return this.onCommit.trigger([n]),i}update(e,t,i){for(const n of t){const t=e.annotations.get(n);if(!t||t.system!==this)continue;const s=t.data;Object.assign(s,i),this._redraw(s,t.three),this.onUpdate.trigger({item:s,group:t.three})}}pick(e,t=.05){const i=new d.Raycaster;i.ray.copy(e),i.params.Line={threshold:t},i.params.LineSegments={threshold:t};const n=d.Line.prototype.raycast;let s=null,r=1/0;for(const e of this._knownDrawings)for(const[t,o]of e.annotations){if(o.system!==this)continue;const e=o.three;e.updateWorldMatrix(!0,!0),e.traverse(o=>{if(o===e)return;const a=[];if(o instanceof d.LineSegments&&o.userData.isDimension)n.call(o,i,a),a.length>0&&a[0].distance<r&&(r=a[0].distance,s=t);else if(o instanceof d.Mesh){const e=(new d.Box3).setFromObject(o),n=new d.Vector3;if(i.ray.intersectBox(e,n)){const e=i.ray.origin.distanceTo(n);e<r&&(r=e,s=t)}}})}return s}delete(e,t){const i=[];for(const n of t){const t=e.annotations.get(n);t&&t.system===this&&(this._disposeGroup(t.three),e.annotations.delete(n),i.push(n))}i.length&&this.onDelete.trigger(i)}clear(e){const t=e??[...this._knownDrawings];for(const e of t){const t=[];for(const[i,n]of e.annotations)n.system===this&&t.push(i);for(const i of t){const t=e.annotations.get(i);this._disposeGroup(t.three),e.annotations.delete(i)}}}dispose(){this._clearPreview(),this._onDispose(),this.clear();for(const e of this._materialCache.values())e.dispose();this._materialCache.clear();for(const e of this._meshMaterialCache.values())e.dispose();this._meshMaterialCache.clear(),this._previewMaterial.dispose(),this.onCommit.reset(),this.onUpdate.reset(),this.onDelete.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}_trackDrawing(e){this._knownDrawings.has(e)||(this._knownDrawings.add(e),e.onDisposed.add(()=>this._knownDrawings.delete(e)))}_resolveStyle(e){return this.styles.get(e)??this.styles.get("default")}_getMaterial(e){const t=this._materialCache.get(e);if(t)return t;const i=new d.LineBasicMaterial({color:this._resolveStyle(e).color});return this._materialCache.set(e,i),i}_getMeshMaterial(e){const t=this._meshMaterialCache.get(e);if(t)return t;const i=new d.MeshBasicMaterial({color:this._resolveStyle(e).color,side:d.DoubleSide});return this._meshMaterialCache.set(e,i),i}_disposeGroup(e){if(e.removeFromParent(),this._ownsChildGeometry)e.traverse(e=>{e.geometry instanceof d.BufferGeometry&&e.geometry.dispose()});else for(;e.children.length>0;)e.remove(e.children[0])}_clearPreview(){this._previewObject&&(this._previewObject.removeFromParent(),this._previewObject.geometry.dispose(),this._previewObject=null)}_persist(e,t){this._trackDrawing(e);const i=this._resolveStyle(t.style),n=this._buildGroup(t,i);return n.userData.isDimension=!0,n.userData.annotationUuid=t.uuid,n.userData.layer=e.activeLayer,e.three.add(n),e.annotations.set(t.uuid,{system:this,data:t,three:n}),this._onAfterPersist(t,n),{drawing:e,item:t,group:n}}_redraw(e,t){for(;t.children.length>0;){const e=t.children[0];this._ownsChildGeometry&&e.geometry instanceof d.BufferGeometry&&e.geometry.dispose(),t.remove(e)}const i=this._resolveStyle(e.style),n=this._buildGroup(e,i);for(;n.children.length>0;)t.add(n.children[0]);this._onAfterPersist(e,t)}}function ia(e,t){const i=e[0],n=e[e.length-1],s=(new d.Vector3).subVectors(n,i);if(s.lengthSq()<1e-10)return 0;s.normalize();const r=new d.Vector3(-s.z,0,s.x);return t.clone().sub(i).dot(r)}function na(e,t){const i=[];for(let n=0;n<e.length-1;n++)i.push({uuid:d.MathUtils.generateUUID(),pointA:e[n].clone(),pointB:e[n+1].clone(),offset:t,style:""});return i}function sa(e,t){switch(e.kind){case"awaitingFirstPoint":if("CLICK"===t.type){if(!t.line)return e;const i=(new d.Vector3).subVectors(t.line.end,t.line.start).normalize();return{kind:"placingPoints",points:[t.point.clone()],cursor:null,lineDir:i,firstLine:t.line.clone()}}return"SELECT_LINE"===t.type?{kind:"positioningOffset",points:[t.line.start.clone(),t.line.end.clone()],cursor:null}:e;case"placingPoints":if("MOUSE_MOVE"===t.type){const i=new d.Vector3(-e.lineDir.z,0,e.lineDir.x),n=e.points[e.points.length-1],s=t.point.clone().sub(n).dot(i),r=n.clone().addScaledVector(i,s);return{...e,cursor:r}}if("CLICK"===t.type){if(!t.line)return e;if(function(e,t){const i=1e-6;return e.start.distanceTo(t.start)<i&&e.end.distanceTo(t.end)<i||e.start.distanceTo(t.end)<i&&e.end.distanceTo(t.start)<i}(t.line,e.firstLine))return e;const s=(new d.Vector3).subVectors(t.line.end,t.line.start).normalize();if(i=s,n=e.lineDir,!(Math.abs(i.dot(n))>.999))return e;const r=function(e,t,i){const n=e.clone().sub(t.start).dot(i);return t.start.clone().addScaledVector(i,n)}(e.points[0],t.line,e.lineDir),o=[...e.points,r];return{...e,points:o,cursor:e.cursor}}return"CONFIRM"===t.type&&e.points.length>=2?{kind:"positioningOffset",points:e.points,cursor:null}:"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e;case"positioningOffset":if("MOUSE_MOVE"===t.type)return{...e,cursor:t.point.clone()};if("CLICK"===t.type){const i=ia(e.points,t.point);return{kind:"committed",dimensions:na(e.points,i)}}return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e}var i,n}function ra(e){const{pointA:t,pointB:i,offset:n}=e,s=(new d.Vector3).subVectors(i,t),r=new d.Vector3(-s.z,0,s.x).normalize(),o=t.clone().addScaledVector(r,n),a=i.clone().addScaledVector(r,n),l=(new d.Vector3).subVectors(a,o).normalize();return[{tip:o,dir:l},{tip:a,dir:l.clone().negate()}]}function oa(e,t){const{pointA:i,pointB:n,offset:s}=e,r=(new d.Vector3).subVectors(n,i),o=new d.Vector3(-r.z,0,r.x).normalize(),a=s>=0?1:-1,l=Math.abs(s),c=i.clone().addScaledVector(o,t.extensionGap*a),h=i.clone().addScaledVector(o,(l+t.extensionOvershoot)*a),u=n.clone().addScaledVector(o,t.extensionGap*a),p=n.clone().addScaledVector(o,(l+t.extensionOvershoot)*a),f=i.clone().addScaledVector(o,s),m=n.clone().addScaledVector(o,s),g=(new d.Vector3).subVectors(m,f).normalize(),w=t.lineTick(f,g,t.tickSize),y=t.lineTick(m,g.clone().negate(),t.tickSize);return[c.x,c.y,c.z,h.x,h.y,h.z,u.x,u.y,u.z,p.x,p.y,p.z,f.x,f.y,f.z,m.x,m.y,m.z,...w,...y]}function aa(e,t,i,n){if("placingPoints"===e){const e=[];for(let i=0;i<t.length-1;i++){const n=t[i],s=t[i+1];e.push(n.x,n.y,n.z,s.x,s.y,s.z)}if(i){const n=t[t.length-1];e.push(n.x,n.y,n.z,i.x,i.y,i.z)}return e}if(!i||t.length<2)return[];const s=ia(t,i),r=[];for(let e=0;e<t.length-1;e++)r.push(...oa({pointA:t[e],pointB:t[e+1],offset:s},n));return r}class la extends ta{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingFirstPoint"}),t(this,"onMachineStateChanged",new f),this.styles.set("default",{lineTick:Uo,tickSize:.4,extensionGap:.05,extensionOvershoot:.2,color:0,textOffset:.4,fontSize:.45})}pickHandle(e,t,i=.1){const n=(new d.Matrix4).copy(e.three.matrixWorld).invert(),s=t.origin.clone().applyMatrix4(n),r=t.direction.clone().transformDirection(n).normalize(),o=new d.Ray(s,r),a=new d.Plane(new d.Vector3(0,1,0),0),l=o.intersectPlane(a,new d.Vector3);if(!l)return null;let c=null,h=i;for(const[t,i]of e.annotations.getBySystem(this)){const e=(new d.Vector3).subVectors(i.pointB,i.pointA),n=new d.Vector3(-e.z,0,e.x).normalize(),s=(new d.Vector3).addVectors(i.pointA,i.pointB).multiplyScalar(.5).addScaledVector(n,i.offset);for(const[e,n]of[["pointA",i.pointA],["pointB",i.pointB],["offset",s]]){const i=Math.hypot(l.x-n.x,l.z-n.z);i<h&&(h=i,c={uuid:t,handle:e})}}return c}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const i=sa(this.machineState,e);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("LinearAnnotations: no drawing context — send a CLICK or SELECT_LINE with `drawing` first. Skipping."),void this._resetMachine();for(const e of i.dimensions)e.style=this.activeStyle;const e=i.dimensions.map(e=>this._persist(this._previewDrawing,e));this.onCommit.trigger(e)}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(e,t){const i=new d.Group,n=oa(e,t),s=new d.BufferGeometry;s.setAttribute("position",new d.BufferAttribute(new Float32Array(n),3));const r=new d.LineSegments(s,this._getMaterial(e.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),t.meshTick)for(const{tip:n,dir:s}of ra(e)){const r=t.meshTick(n,s,t.tickSize),o=new d.BufferGeometry;o.setAttribute("position",new d.BufferAttribute(new Float32Array(r),3));const a=new d.Mesh(o,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isMeshTick=!0,i.add(a)}return i}_updatePreview(){const e=this.machineState;if("placingPoints"!==e.kind&&"positioningOffset"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle);this._previewMaterial.color.setHex(t.color);const i=aa(e.kind,e.points,e.cursor,t);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const e=new d.BufferGeometry;e.setAttribute("position",new d.BufferAttribute(new Float32Array(i),3)),this._previewObject=new d.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingFirstPoint"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}}const ca=Math.PI/180;function ha(e,t,i,n){const s=function(e,t,i){const n=(new d.Vector3).subVectors(e,t).normalize(),s=(new d.Vector3).subVectors(i,t).normalize();return(new d.Vector3).addVectors(n,s).normalize()}(e,t,i);return(new d.Vector3).subVectors(n,t).setY(0).dot(s)}function da(e,t,i,n){return ha(e,t,i,n)<0}function ua(e,t){switch(e.kind){case"awaitingFirstLine":return"CLICK"===t.type&&t.line?{kind:"awaitingSecondLine",line1:t.line.clone(),pointA:t.point.clone()}:e;case"awaitingSecondLine":if("CLICK"===t.type&&t.line){const i=(new d.Vector3).subVectors(e.line1.end,e.line1.start).normalize(),n=(new d.Vector3).subVectors(t.line.end,t.line.start).normalize();if(Math.abs(i.dot(n))>Math.cos(ca))return e;const s=function(e,t,i,n){const s=t.x*n.z-t.z*n.x;if(Math.abs(s)<1e-10)return null;const r=(new d.Vector3).subVectors(i,e),o=(r.x*n.z-r.z*n.x)/s;return new d.Vector3(e.x+t.x*o,0,e.z+t.z*o)}(e.line1.start,i,t.line.start,n);return s?{kind:"positioningArc",pointA:e.pointA.clone(),vertex:s,pointB:t.point.clone(),cursor:null,flipped:!1}:e}return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e;case"positioningArc":if("MOUSE_MOVE"===t.type){const i=da(e.pointA,e.vertex,e.pointB,t.point);return{...e,cursor:t.point.clone(),flipped:i}}if("CLICK"===t.type){const i=da(e.pointA,e.vertex,e.pointB,t.point),n=Math.max(.05,Math.abs(ha(e.pointA,e.vertex,e.pointB,t.point)));return{kind:"committed",dimension:{uuid:d.MathUtils.generateUUID(),pointA:e.pointA.clone(),vertex:e.vertex.clone(),pointB:e.pointB.clone(),arcRadius:n,flipped:i,style:""}}}return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingFirstLine"}:e}}function pa(e){const t=(new d.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new d.Vector3).subVectors(e.pointB,e.vertex).normalize(),n=Math.atan2(t.z,t.x);let s=Math.atan2(i.z,i.x)-n;for(;s>Math.PI;)s-=2*Math.PI;for(;s<-Math.PI;)s+=2*Math.PI;e.flipped&&(s-=2*Math.sign(s)*Math.PI);const r=new d.Vector3(e.vertex.x+Math.cos(n)*e.arcRadius,0,e.vertex.z+Math.sin(n)*e.arcRadius),o=n+s,a=new d.Vector3(e.vertex.x+Math.cos(o)*e.arcRadius,0,e.vertex.z+Math.sin(o)*e.arcRadius),l=Math.sign(s);return[{tip:r,dir:new d.Vector3(-Math.sin(n)*l,0,Math.cos(n)*l)},{tip:a,dir:new d.Vector3(Math.sin(o)*l,0,-Math.cos(o)*l)}]}function fa(e){const t=(new d.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new d.Vector3).subVectors(e.pointB,e.vertex).normalize(),n=Math.acos(d.MathUtils.clamp(t.dot(i),-1,1));return e.flipped?2*Math.PI-n:n}function ma(e){const t=(new d.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new d.Vector3).subVectors(e.pointB,e.vertex).normalize(),n=Math.atan2(t.z,t.x);let s=Math.atan2(i.z,i.x)-n;for(;s>Math.PI;)s-=2*Math.PI;for(;s<-Math.PI;)s+=2*Math.PI;const r=n+s/2;return e.flipped?r+Math.PI:r}function ga(e,t,i,n,s,r=!1){const o=Math.atan2(t.z,t.x);let a=Math.atan2(i.z,i.x)-o;for(;a>Math.PI;)a-=2*Math.PI;for(;a<-Math.PI;)a+=2*Math.PI;r&&(a-=2*Math.sign(a)*Math.PI);const l=[];for(let t=0;t<8;t++){const i=o+a*(t/8),s=o+a*((t+1)/8);l.push(e.x+Math.cos(i)*n,0,e.z+Math.sin(i)*n,e.x+Math.cos(s)*n,0,e.z+Math.sin(s)*n)}const c=new d.Vector3(e.x+Math.cos(o)*n,0,e.z+Math.sin(o)*n),h=new d.Vector3(e.x+Math.cos(o+a)*n,0,e.z+Math.sin(o+a)*n),u=e.clone().addScaledVector(t,s.extensionGap),p=e.clone().addScaledVector(i,s.extensionGap);l.push(u.x,u.y,u.z,c.x,c.y,c.z,p.x,p.y,p.z,h.x,h.y,h.z);const f=Math.sign(a),m=new d.Vector3(-Math.sin(o)*f,0,Math.cos(o)*f),g=o+a,w=new d.Vector3(Math.sin(g)*f,0,-Math.cos(g)*f);return l.push(...s.lineTick(c,m,s.tickSize),...s.lineTick(h,w,s.tickSize)),l}function wa(e,t){const i=(new d.Vector3).subVectors(e.pointA,e.vertex).normalize(),n=(new d.Vector3).subVectors(e.pointB,e.vertex).normalize();return ga(e.vertex,i,n,e.arcRadius,t,e.flipped??!1)}function ya(e,t,i,n,s,r=!1){if(!n)return[];const o=Math.max(.05,(new d.Vector3).subVectors(n,t).setY(0).length());return ga(t,(new d.Vector3).subVectors(e,t).normalize(),(new d.Vector3).subVectors(i,t).normalize(),o,s,r)}class _a extends ta{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingFirstLine"}),t(this,"onMachineStateChanged",new f),t(this,"_secondLinePreviewObject",null),this.styles.set("default",{lineTick:Uo,tickSize:.4,extensionGap:.05,color:0,textOffset:.25,fontSize:.45})}pickHandle(e,t,i){return null}sendMachineEvent(e){const t=e.drawing??null;if("awaitingSecondLine"===this.machineState.kind&&"MOUSE_MOVE"===e.type)return t&&(this._previewDrawing=t),void this._updateSecondLinePreview(e.point,e.line??null);const i=ua(this.machineState,e);if(i!==this.machineState){if("awaitingSecondLine"===this.machineState.kind&&this._clearSecondLinePreview(),this.machineState=i,t&&(this._previewDrawing=t),this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("AngleAnnotations: CLICK that commits must include `drawing`. Skipping."),void this._resetMachine();i.dimension.style=this.activeStyle;const e=this._persist(this._previewDrawing,i.dimension);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(e,t){const i=new d.Group,n=wa(e,t),s=new d.BufferGeometry;s.setAttribute("position",new d.BufferAttribute(new Float32Array(n),3));const r=new d.LineSegments(s,this._getMaterial(e.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),t.meshTick)for(const{tip:n,dir:s}of pa(e)){const r=t.meshTick(n,s,t.tickSize),o=new d.BufferGeometry;o.setAttribute("position",new d.BufferAttribute(new Float32Array(r),3));const a=new d.Mesh(o,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isMeshTick=!0,i.add(a)}return i}_updatePreview(){const e=this.machineState;if("positioningArc"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle),i=ya(e.pointA,e.vertex,e.pointB,e.cursor,t,e.flipped);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const e=new d.BufferGeometry;e.setAttribute("position",new d.BufferAttribute(new Float32Array(i),3)),this._previewObject=new d.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}}_onDispose(){this._clearSecondLinePreview()}_resetMachine(){this.machineState={kind:"awaitingFirstLine"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearSecondLinePreview(){this._secondLinePreviewObject&&(this._secondLinePreviewObject.removeFromParent(),this._secondLinePreviewObject.geometry.dispose(),this._secondLinePreviewObject=null)}_updateSecondLinePreview(e,t){if("awaitingSecondLine"!==this.machineState.kind)return void this._clearSecondLinePreview();if(!this._previewDrawing)return void this._clearSecondLinePreview();const i=this.machineState,n=(new d.Vector3).subVectors(i.line1.end,i.line1.start).normalize();if(!t)return void this._clearSecondLinePreview();const s=(new d.Vector3).subVectors(t.end,t.start).normalize(),r=function(e,t,i,n){const s=t.x*n.z-t.z*n.x;if(Math.abs(s)<1e-6)return null;const r=i.x-e.x,o=i.z-e.z,a=(r*n.z-o*n.x)/s;return new d.Vector3(e.x+a*t.x,0,e.z+a*t.z)}(i.line1.start,n,t.start,s);if(!r)return void this._clearSecondLinePreview();const o=e.clone(),a=(new d.Vector3).subVectors(o,r).setY(0);if(a.length()<.01)return void this._clearSecondLinePreview();const l=(new d.Vector3).subVectors(i.pointA,r).normalize(),c=a.normalize(),h=Math.atan2(l.z,l.x);let u=Math.atan2(c.z,c.x)-h;for(;u>Math.PI;)u-=2*Math.PI;for(;u<-Math.PI;)u+=2*Math.PI;const p=h+u/2,f=Math.max(.1,.4*Math.min(i.pointA.distanceTo(r),o.distanceTo(r))),m=new d.Vector3(r.x+Math.cos(p)*f,0,r.z+Math.sin(p)*f),g=this._resolveStyle(this.activeStyle),w=ya(i.pointA,r,o,m,g);if(0===w.length)return void this._clearSecondLinePreview();const y=w.length/3;if(!this._secondLinePreviewObject||this._secondLinePreviewObject.geometry.attributes.position.count!==y){this._clearSecondLinePreview();const e=new d.BufferGeometry;e.setAttribute("position",new d.BufferAttribute(new Float32Array(w),3)),this._secondLinePreviewObject=new d.LineSegments(e,this._previewMaterial),this._secondLinePreviewObject.layers.set(1),this._secondLinePreviewObject.renderOrder=1,this._secondLinePreviewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._secondLinePreviewObject)}else{const e=this._secondLinePreviewObject.geometry.attributes.position;e.set(w),e.needsUpdate=!0}}}function ba(e,t){const i=t.x-e.x,n=t.z-e.z,s=Math.sqrt(i*i+n*n);if(0===s)return e.clone();const r=Math.atan2(n,i),o=Math.round(r/(Math.PI/4))*(Math.PI/4);return new d.Vector3(e.x+Math.cos(o)*s,0,e.z+Math.sin(o)*s)}function va(e,t){switch(e.kind){case"awaitingArrowTip":return"CLICK"===t.type?{kind:"placingElbow",arrowTip:t.point.clone(),cursor:null}:e;case"placingElbow":return"MOUSE_MOVE"===t.type?{...e,cursor:t.point.clone()}:"CLICK"===t.type?{kind:"placingExtension",arrowTip:e.arrowTip,elbow:t.point.clone(),cursor:null}:"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"placingExtension":return"MOUSE_MOVE"===t.type?{...e,cursor:ba(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",arrowTip:e.arrowTip,elbow:e.elbow,extensionEnd:ba(e.elbow,t.point)}:"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"enteringText":if("SUBMIT_TEXT"===t.type&&t.text.trim().length>0){return{kind:"committed",annotation:{uuid:d.MathUtils.generateUUID(),arrowTip:e.arrowTip.clone(),elbow:e.elbow.clone(),extensionEnd:e.extensionEnd.clone(),text:t.text.trim(),style:""}}}return"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingArrowTip"}:e}}function xa(e,t,i,n){return"curved"===n.leaderShape?function(e,t,i,n){const s=new d.QuadraticBezierCurve3(e,t,i).getPoints(24),r=[];for(let e=0;e<s.length-1;e++){const t=s[e],i=s[e+1];r.push(t.x,t.y,t.z,i.x,i.y,i.z)}if(n.lineTick){const i=(new d.Vector3).subVectors(e,t);i.lengthSq()>1e-10&&r.push(...n.lineTick(e,i.normalize(),n.tickSize))}return r}(e,t,i,n):function(e,t,i,n){const s=[e.x,e.y,e.z,t.x,t.y,t.z,t.x,t.y,t.z,i.x,i.y,i.z];if(n.lineTick){const i=(new d.Vector3).subVectors(e,t);i.lengthSq()>1e-10&&s.push(...n.lineTick(e,i.normalize(),n.tickSize))}return s}(e,t,i,n)}function Sa(e,t){return xa(e.arrowTip,e.elbow,e.extensionEnd,t)}function Ca(e,t,i,n,s){return n?xa(t,"placingElbow"===e?n:i,n,s):[]}class Ta extends ta{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingArrowTip"}),t(this,"onMachineStateChanged",new f),t(this,"_previewMeshMaterial",new d.MeshBasicMaterial({color:16737894,side:d.DoubleSide,depthTest:!1})),t(this,"_previewMeshObject",null),this.styles.set("default",{tickSize:.4,color:0,textOffset:.1,fontSize:.45,lineTick:jo})}pickHandle(e,t,i=.1){const n=(new d.Matrix4).copy(e.three.matrixWorld).invert(),s=t.origin.clone().applyMatrix4(n),r=t.direction.clone().transformDirection(n).normalize(),o=new d.Ray(s,r),a=new d.Plane(new d.Vector3(0,1,0),0),l=o.intersectPlane(a,new d.Vector3);if(!l)return null;let c=null,h=i;for(const[t,i]of e.annotations.getBySystem(this))for(const[e,n]of[["elbow",i.elbow],["extensionEnd",i.extensionEnd]]){const i=Math.hypot(l.x-n.x,l.z-n.z);i<h&&(h=i,c={uuid:t,handle:e})}return c}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const i=va(this.machineState,e);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("LeaderAnnotations: commit requires a drawing. Skipping."),void this._resetMachine();i.annotation.style=this.activeStyle;const e=this._persist(this._previewDrawing,i.annotation);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(e,t){const i=new d.Group,n=Sa(e,t),s=new d.BufferGeometry;s.setAttribute("position",new d.BufferAttribute(new Float32Array(n),3));const r=new d.LineSegments(s,this._getMaterial(e.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),t.meshTick){const n=(new d.Vector3).subVectors(e.arrowTip,e.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=t.meshTick(e.arrowTip,n,t.tickSize),r=new d.BufferGeometry;r.setAttribute("position",new d.BufferAttribute(new Float32Array(s),3));const o=new d.Mesh(r,this._getMeshMaterial(e.style));o.layers.set(1),o.userData.isMeshArrow=!0,i.add(o)}}return i}_updatePreview(){const e=this.machineState;if("placingElbow"!==e.kind&&"placingExtension"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return void this._clearPreview();const t=this._resolveStyle(this.activeStyle),i="placingElbow"===e.kind?Ca("placingElbow",e.arrowTip,null,e.cursor,t):Ca("placingExtension",e.arrowTip,e.elbow,e.cursor,t);if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const e=new d.BufferGeometry;e.setAttribute("position",new d.BufferAttribute(new Float32Array(i),3)),this._previewObject=new d.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}if(t.meshTick){const i="placingElbow"===e.kind?e.cursor:e.elbow,n=i?(new d.Vector3).subVectors(e.arrowTip,i):null;if(n&&n.lengthSq()>1e-10){n.normalize();const i=t.meshTick(e.arrowTip,n,t.tickSize);if(this._previewMeshObject){const e=this._previewMeshObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}else{const e=new d.BufferGeometry;e.setAttribute("position",new d.BufferAttribute(new Float32Array(i),3)),this._previewMeshObject=new d.Mesh(e,this._previewMeshMaterial),this._previewMeshObject.layers.set(1),this._previewMeshObject.renderOrder=1,this._previewMeshObject.frustumCulled=!1,this._previewDrawing.three.add(this._previewMeshObject)}}else this._clearPreviewMesh()}else this._clearPreviewMesh()}_clearPreview(){super._clearPreview(),this._clearPreviewMesh()}_onDispose(){this._clearPreviewMesh(),this._previewMeshMaterial.dispose()}_resetMachine(){this.machineState={kind:"awaitingArrowTip"},this._previewDrawing=null,this._updatePreview(),this.onMachineStateChanged.trigger(this.machineState)}_clearPreviewMesh(){this._previewMeshObject&&(this._previewMeshObject.removeFromParent(),this._previewMeshObject.geometry.dispose(),this._previewMeshObject=null)}}class Aa extends ta{constructor(e){super(e),t(this,"enabled",!0),t(this,"_ownsChildGeometry",!1),t(this,"definitions",new h.DataMap),this.styles.set("default",{color:0,textOffset:0,fontSize:0})}pickHandle(e,t,i){return null}pick(e,t=.05){const i=new d.Raycaster;i.ray.copy(e),i.params.Line={threshold:t},i.params.LineSegments={threshold:t};let n=null,s=1/0;for(const e of this._knownDrawings)for(const[t,r]of e.annotations){if(r.system!==this)continue;const e=r.three;e.updateWorldMatrix(!0,!0),e.traverse(r=>{if(r===e)return;if(!(r instanceof d.LineSegments))return;const o=[];r.raycast(i,o),o.length>0&&o[0].distance<s&&(s=o[0].distance,n=t)})}return n}define(e,t){this.definitions.set(e,t)}_buildGroup(e,t){const i=this.definitions.get(e.blockName);if(!i)throw new Error(`BlockAnnotations: block "${e.blockName}" is not defined.`);const n=new d.Group;if(i.lines){const t=new d.LineSegments(i.lines,this._getMaterial(e.style));t.layers.set(1),t.userData.isDimension=!0,n.add(t)}if(i.mesh){const t=new d.Mesh(i.mesh,this._getMeshMaterial(e.style));t.layers.set(1),t.userData.isBlockMesh=!0,n.add(t)}return n}_onAfterPersist(e,t){t.position.set(e.position.x,0,e.position.z),t.rotation.set(0,e.rotation,0),t.scale.setScalar(e.scale)}_onDispose(){var e,t;for(const i of this.definitions.values())null==(e=i.lines)||e.dispose(),null==(t=i.mesh)||t.dispose();this.definitions.clear()}}function Ea(e,t){const{position:i,direction:n}=e,{length:s}=t,r=new d.Vector3(i.x+n.x*s,0,i.z+n.z*s),o=new d.Vector3(n.x,0,n.z),a=t.lineTick(r,o,t.tickSize),l=[i.x,0,i.z,r.x,0,r.z];return new Float32Array([...l,...a])}function Ma(e,t){return new d.Vector3(e.position.x+e.direction.x*t,0,e.position.z+e.direction.z*t)}function Pa(e,t){switch(t){case"percentage":return`${(100*e).toFixed(2)} %`;case"ratio":return 0===e?"1:∞":`1:${(1/e).toFixed(2)}`;case"degrees":return`${(180*Math.atan(e)/Math.PI).toFixed(2)}°`}}class Ia extends ta{constructor(e){super(e),t(this,"enabled",!0),this.styles.set("default",{lineTick:$o,meshTick:Wo,tickSize:.4,length:3,color:0,textOffset:.1,fontSize:.45,format:"percentage"})}pickHandle(e,t,i){return null}_buildGroup(e,t){const i=new d.Group,n=Ea(e,t),s=new d.BufferGeometry;s.setAttribute("position",new d.BufferAttribute(n,3));const r=new d.LineSegments(s,this._getMaterial(e.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),t.meshTick){const n=Ma(e,t.length),s=t.meshTick(n,e.direction,t.tickSize),r=new d.BufferGeometry;r.setAttribute("position",new d.BufferAttribute(new Float32Array(s),3));const o=new d.Mesh(r,this._getMeshMaterial(e.style));o.layers.set(1),o.userData.isDimension=!0,i.add(o)}return i}}function za(e,t){const i=t.x-e.x,n=t.z-e.z,s=Math.sqrt(i*i+n*n);if(0===s)return e.clone();const r=Math.atan2(n,i),o=Math.round(r/(Math.PI/4))*(Math.PI/4);return new d.Vector3(e.x+Math.cos(o)*s,0,e.z+Math.sin(o)*s)}function Da(e,t){switch(e.kind){case"awaitingCenter":return"CLICK"===t.type?{kind:"awaitingRadius",center:t.point.clone(),cursor:null}:e;case"awaitingRadius":if("MOUSE_MOVE"===t.type)return{...e,cursor:t.point.clone()};if("CLICK"===t.type){const i=Math.max(.1,Math.abs(t.point.x-e.center.x)),n=Math.max(.1,Math.abs(t.point.z-e.center.z));return{kind:"awaitingElbow",center:e.center,halfW:i,halfH:n,cursor:null}}return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"awaitingElbow":return"MOUSE_MOVE"===t.type?{...e,cursor:t.point.clone()}:"CLICK"===t.type?{kind:"awaitingExtension",center:e.center,halfW:e.halfW,halfH:e.halfH,elbow:t.point.clone(),cursor:null}:"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"awaitingExtension":return"MOUSE_MOVE"===t.type?{...e,cursor:za(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",center:e.center,halfW:e.halfW,halfH:e.halfH,elbow:e.elbow,extensionEnd:za(e.elbow,t.point)}:"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"enteringText":if("SUBMIT_TEXT"===t.type&&t.text.trim().length>0){return{kind:"committed",annotation:{uuid:d.MathUtils.generateUUID(),center:e.center.clone(),halfW:e.halfW,halfH:e.halfH,elbow:e.elbow.clone(),extensionEnd:e.extensionEnd.clone(),text:t.text.trim(),style:""}}}return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingCenter"}:e}}function ka(e,t){const i=[];i.push(...t.enclosure.buildGeometry(e.center,e.halfW,e.halfH));const n=(new d.Vector3).subVectors(e.elbow,e.center),s=n.lengthSq()>1e-10?n.clone().normalize():new d.Vector3(1,0,0),r=t.enclosure.getAttachmentPoint(e.center,e.halfW,e.halfH,s);if(i.push(r.x,r.y,r.z,e.elbow.x,e.elbow.y,e.elbow.z,e.elbow.x,e.elbow.y,e.elbow.z,e.extensionEnd.x,e.extensionEnd.y,e.extensionEnd.z),t.lineTick){const n=(new d.Vector3).subVectors(e.extensionEnd,e.elbow);n.lengthSq()>1e-10&&i.push(...t.lineTick(e.extensionEnd,n.normalize(),t.tickSize))}return i}function Ba(e,t,i,n,s,r,o){const a="awaitingRadius"===e?r?Math.max(.05,Math.abs(r.x-t.x)):0:i,l="awaitingRadius"===e?r?Math.max(.05,Math.abs(r.z-t.z)):0:n;if(a<1e-10||l<1e-10)return[];const c=[];if(c.push(...o.enclosure.buildGeometry(t,a,l)),"awaitingRadius"===e)return c;const h="awaitingElbow"===e?r:s;if(!h)return c;const u=(new d.Vector3).subVectors(h,t),p=u.lengthSq()>1e-10?u.clone().normalize():new d.Vector3(1,0,0),f=o.enclosure.getAttachmentPoint(t,a,l,p);return"awaitingElbow"===e?(c.push(f.x,0,f.z,h.x,0,h.z),c):r?(c.push(f.x,0,f.z,s.x,0,s.z,s.x,0,s.z,r.x,0,r.z),c):c}const Oa={buildGeometry(e,t,i){const n=.25*Math.min(t,i),s=new d.Vector3(e.x-t,0,e.z-i),r=new d.Vector3(e.x+t,0,e.z-i),o=new d.Vector3(e.x+t,0,e.z+i),a=new d.Vector3(e.x-t,0,e.z+i),l=[[s,r,new d.Vector3(0,0,-1)],[r,o,new d.Vector3(1,0,0)],[o,a,new d.Vector3(0,0,1)],[a,s,new d.Vector3(-1,0,0)]],c=[];for(const[e,t,i]of l){const s=e.distanceTo(t),r=Math.max(1,Math.round(s/(2*n))),o=s/r,a=o/2,l=(new d.Vector3).subVectors(t,e).normalize();for(let t=0;t<r;t++){const n=e.clone().addScaledVector(l,(t+.5)*o),s=e.clone().addScaledVector(l,t*o),r=(new d.Vector3).subVectors(s,n);let h=s.clone();for(let e=1;e<=8;e++){const t=e/8*Math.PI,s=n.x+r.x*Math.cos(t)+i.x*a*Math.sin(t),o=n.z+r.z*Math.cos(t)+i.z*a*Math.sin(t),l=new d.Vector3(s,0,o);c.push(h.x,0,h.z,l.x,0,l.z),h=l}}}return c},getAttachmentPoint(e,t,i,n){const s=Math.abs(n.x)>1e-10?t/Math.abs(n.x):1/0,r=Math.abs(n.z)>1e-10?i/Math.abs(n.z):1/0,o=Math.min(s,r);return new d.Vector3(e.x+n.x*o,0,e.z+n.z*o)}},Va={buildGeometry(e,t,i){const n=new d.Vector3(e.x-t,0,e.z-i),s=new d.Vector3(e.x+t,0,e.z-i),r=new d.Vector3(e.x+t,0,e.z+i),o=new d.Vector3(e.x-t,0,e.z+i);return[n.x,0,n.z,s.x,0,s.z,s.x,0,s.z,r.x,0,r.z,r.x,0,r.z,o.x,0,o.z,o.x,0,o.z,n.x,0,n.z]},getAttachmentPoint(e,t,i,n){const s=Math.abs(n.x)>1e-10?t/Math.abs(n.x):1/0,r=Math.abs(n.z)>1e-10?i/Math.abs(n.z):1/0,o=Math.min(s,r);return new d.Vector3(e.x+n.x*o,0,e.z+n.z*o)}},La={buildGeometry(e,t,i){const n=[];for(let s=0;s<32;s++){const r=s/32*Math.PI*2,o=(s+1)/32*Math.PI*2;n.push(e.x+Math.cos(r)*t,0,e.z+Math.sin(r)*i,e.x+Math.cos(o)*t,0,e.z+Math.sin(o)*i)}return n},getAttachmentPoint(e,t,i,n){const s=n.x/t,r=n.z/i,o=Math.sqrt(s*s+r*r),a=o>1e-10?1/o:t;return new d.Vector3(e.x+n.x*a,0,e.z+n.z*a)}};class Na extends ta{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingCenter"}),t(this,"onMachineStateChanged",new f),this.styles.set("default",{enclosure:Oa,lineTick:jo,tickSize:.4,color:22015,textOffset:.1,fontSize:.45})}pickHandle(e,t,i){return null}sendMachineEvent(e){const t=e.drawing??null;t&&(this._previewDrawing=t);const i=Da(this.machineState,e);if(i!==this.machineState){if(this.machineState=i,this._updatePreview(),"committed"===i.kind){if(!this._previewDrawing)return console.warn("CalloutAnnotations: commit requires a drawing. Pass `drawing` on the first CLICK."),void this._resetMachine();i.annotation.style=this.activeStyle;const e=this._persist(this._previewDrawing,i.annotation);this.onCommit.trigger([e])}this.onMachineStateChanged.trigger(this.machineState),"committed"===i.kind&&this._resetMachine()}}_buildGroup(e,t){const i=new d.Group,n=ka(e,t),s=new d.BufferGeometry;s.setAttribute("position",new d.BufferAttribute(new Float32Array(n),3));const r=new d.LineSegments(s,this._getMaterial(e.style));if(r.layers.set(1),r.userData.isDimension=!0,i.add(r),t.meshTick){const n=(new d.Vector3).subVectors(e.extensionEnd,e.elbow);if(n.lengthSq()>1e-10){n.normalize();const s=t.meshTick(e.extensionEnd,n,t.tickSize),r=new d.BufferGeometry;r.setAttribute("position",new d.BufferAttribute(new Float32Array(s),3));const o=new d.Mesh(r,this._getMeshMaterial(e.style));o.layers.set(1),o.userData.isMeshArrow=!0,i.add(o)}}return i}_updatePreview(){const e=this.machineState;if("awaitingRadius"!==e.kind&&"awaitingElbow"!==e.kind&&"awaitingExtension"!==e.kind)return void this._clearPreview();if(!this._previewDrawing)return;const t=this._resolveStyle(this.activeStyle),i=(()=>{switch(e.kind){case"awaitingRadius":return Ba("awaitingRadius",e.center,0,0,null,e.cursor,t);case"awaitingElbow":return Ba("awaitingElbow",e.center,e.halfW,e.halfH,null,e.cursor,t);case"awaitingExtension":return Ba("awaitingExtension",e.center,e.halfW,e.halfH,e.elbow,e.cursor,t)}})();if(0===i.length)return void this._clearPreview();const n=i.length/3;if(!this._previewObject||this._previewObject.geometry.attributes.position.count!==n){this._clearPreview();const e=new d.BufferGeometry;e.setAttribute("position",new d.BufferAttribute(new Float32Array(i),3)),this._previewObject=new d.LineSegments(e,this._previewMaterial),this._previewObject.layers.set(1),this._previewObject.renderOrder=1,this._previewObject.frustumCulled=!1,this._previewObject.userData.isDimension=!0,this._previewDrawing.three.add(this._previewObject)}else{const e=this._previewObject.geometry.attributes.position;e.set(i),e.needsUpdate=!0}}_resetMachine(){this.machineState={kind:"awaitingCenter"},this._clearPreview(),this._previewDrawing=null,this.onMachineStateChanged.trigger(this.machineState)}}const Fa=class e extends g{constructor(i){super(i),t(this,"enabled",!0),t(this,"list",new h.DataMap),t(this,"systems",new h.DataMap),t(this,"onDisposed",new f),i.add(e.uuid,this),this.list.onBeforeDelete.add(({value:e})=>e.dispose()),this.systems.onBeforeDelete.add(({value:e})=>e.dispose())}use(e){if(this.systems.has(e))return this.systems.get(e);const t=new e(this.components);return this.systems.set(e,t),t}create(e){const t=new ea(this.components);t.world=e,e.scene.three.add(t.three),e.onDisposed.add(()=>this.list.delete(t.uuid));const i=e.camera;return i.three.layers.enable(1),i instanceof Zr&&(i.threePersp.layers.enable(1),i.threeOrtho.layers.enable(1)),this.list.set(t.uuid,t),t}dispose(){this.list.clear(),this.systems.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};t(Fa,"uuid","5c7d3b9a-4e8f-4a2b-9c1d-0e3f2a5b7c8d");let Ra=Fa;const Ua=[[16711680,1],[16776960,2],[65280,3],[65535,4],[255,5],[16711935,6],[16777215,7],[0,7]];function ja(e){const t=e>>16&255,i=e>>8&255,n=255&e;let s=7,r=1/0;for(const[e,o]of Ua){const a=(t-(e>>16&255))**2+(i-(e>>8&255))**2+(n-(255&e))**2;a<r&&(r=a,s=o)}return s}class $a{constructor(){t(this,"_lines",[]),t(this,"_handleCounter",1)}p(e,t){return this._lines.push(String(e),String(t)),this}n(e,t,i=6){return this._lines.push(String(e),t.toFixed(i)),this}handle(){return(this._handleCounter++).toString(16).toUpperCase()}build(){return this._lines.join("\n")+"\n"}}class Wa{constructor(e){t(this,"precision",2),t(this,"config",{trueColor:!1}),t(this,"_viewport",null),t(this,"_paperSlot",null),t(this,"_annotationLayers",new Map),t(this,"_systemExporters",new Map),this._components=e}registerSystemExporter(e,t){this._systemExporters.set(e,t)}export(e,t){const i=!!t,n=new $a,s=new Map;for(const t of e)for(const e of t.drawing.layers.values())s.has(e.name)||s.set(e.name,e);const r=[...s.values()],o=this._components.get(Ra).systems.get(Aa),a=o?[...o.definitions.keys()]:[];this._writeHeader(n,i),this._writeTables(n,r,a),this._writeBlocks(n,o??null),n.p(0,"SECTION").p(2,"ENTITIES"),i&&t&&this._writePaperBorders(n,t);for(const s of e){s.drawing.three.traverse(e=>{e.userData.isDimension&&e.userData.annotationUuid&&this._annotationLayers.set(e.userData.annotationUuid,e.userData.layer??"0")});for(const e of s.viewports){if(this._viewport=e.viewport??null,i&&e.viewport){const i=e.viewport,n=t.heightMm-2*t.margin;this._paperSlot={x:e.x??0,y:n-(e.y??0),mmPerUnit:1e3/i.drawingScale,vpLeft:i.left,vpTop:i.top}}else this._paperSlot=null;this._writeViewportBorder(n),this._writeRawLines(n,s.drawing),this._writeLinearAnnotations(n,s.drawing),this._writeAngleAnnotations(n,s.drawing),this._writeLeaderAnnotations(n,s.drawing),this._writeSlopeAnnotations(n,s.drawing),this._writeCalloutAnnotations(n,s.drawing),this._writeBlockInsertions(n,s.drawing),this._writeCustomSystems(n,s.drawing)}this._annotationLayers.clear()}return n.p(0,"ENDSEC"),this._writeObjects(n),n.p(0,"EOF"),this._viewport=null,this._paperSlot=null,n.build()}_writeHeader(e,t){e.p(0,"SECTION").p(2,"HEADER"),e.p(9,"$ACADVER").p(1,this.config.trueColor?"AC1018":"AC1015"),e.p(9,"$INSUNITS").p(70,t?4:6),e.p(0,"ENDSEC")}_writeTables(e,t,i){e.p(0,"SECTION").p(2,"TABLES"),e.p(0,"TABLE").p(2,"VPORT").p(70,0).p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"LTYPE").p(70,1),e.p(0,"LTYPE").p(2,"CONTINUOUS").p(70,0).p(3,"Solid line").p(72,65).p(73,0).n(40,0),e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"LAYER").p(70,t.length);for(const i of t){const t=ja(i.material.color.getHex());e.p(0,"LAYER").p(2,i.name).p(70,0).p(62,t).p(6,"CONTINUOUS")}e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"STYLE").p(70,1),e.p(0,"STYLE").p(2,"STANDARD").p(70,0).n(40,0).n(41,1).n(50,0).p(71,0).n(42,.2).p(3,"txt").p(4,""),e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"VIEW").p(70,0).p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"UCS").p(70,0).p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"APPID").p(70,1),e.p(0,"APPID").p(2,"ACAD").p(70,0),e.p(0,"ENDTAB"),e.p(0,"TABLE").p(2,"DIMSTYLE").p(70,0).p(0,"ENDTAB");const n=["*Model_Space","*Paper_Space",...i];e.p(0,"TABLE").p(2,"BLOCK_RECORD").p(70,n.length);for(const t of n)e.p(0,"BLOCK_RECORD").p(5,e.handle()).p(2,t);e.p(0,"ENDTAB"),e.p(0,"ENDSEC")}_writeBlocks(e,t){if(e.p(0,"SECTION").p(2,"BLOCKS"),this._writeBlock(e,"*Model_Space",null),this._writeBlock(e,"*Paper_Space",null),t)for(const[i,n]of t.definitions)this._writeBlock(e,i,n.lines??null);e.p(0,"ENDSEC")}_writeBlock(e,t,i){if(e.p(0,"BLOCK").p(5,e.handle()).p(8,"0").p(2,t).p(70,0).n(10,0).n(20,0).n(30,0).p(3,t).p(1,""),i){const t=this._viewport,n=this._paperSlot;this._viewport=null,this._paperSlot=null,this._writeGeoAsLines(e,i,"0"),this._viewport=t,this._paperSlot=n}e.p(0,"ENDBLK").p(5,e.handle()).p(8,"0")}_writeViewportBorder(e){if(!this._viewport)return;const t=this._viewport,i=this._tx(t.left),n=this._tx(t.right),s=this._ty(-t.bottom),r=this._ty(-t.top);this._writeRawLine(e,i,s,n,s,"0",7),this._writeRawLine(e,n,s,n,r,"0",7),this._writeRawLine(e,n,r,i,r,"0",7),this._writeRawLine(e,i,r,i,s,"0",7)}_writePaperBorders(e,t){const{margin:i,widthMm:n,heightMm:s}=t,r=n-2*i,o=s-2*i;this._writeRawLine(e,0,0,r,0,"0",7),this._writeRawLine(e,r,0,r,o,"0",7),this._writeRawLine(e,r,o,0,o,"0",7),this._writeRawLine(e,0,o,0,0,"0",7),this._writeRawLine(e,-i,-i,r+i,-i,"0",7),this._writeRawLine(e,r+i,-i,r+i,o+i,"0",7),this._writeRawLine(e,r+i,o+i,-i,o+i,"0",7),this._writeRawLine(e,-i,o+i,-i,-i,"0",7)}_writeObjects(e){e.p(0,"SECTION").p(2,"OBJECTS"),e.p(0,"DICTIONARY").p(5,e.handle()).p(330,0).p(100,"AcDbRootDictionary"),e.p(0,"ENDSEC")}_writeRawLines(e,t){t.three.traverse(t=>{var i;if(!(t instanceof d.LineSegments))return;if(t.userData.isDimension)return;if(null==(i=t.parent)?void 0:i.userData.blockUuid)return;if(!t.visible)return;const n=t.userData.layer??"0",s=t.material.color.getHex();this._writeGeoAsLines(e,t.geometry,n,ja(s),s)})}_writeLinearAnnotations(e,t){var i;const n=this._components.get(Ra).systems.get(la);if(n)for(const[,s]of t.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=ja(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=t.layers.get(a))?void 0:i.visible))continue;const l=oa(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick)for(const{tip:t,dir:i}of ra(s))this._writeMeshTriangles(e,r.meshTick(t,i,r.tickSize),a,o,r.color);const c=(new d.Vector3).subVectors(s.pointB,s.pointA),h=new d.Vector3(-c.z,0,c.x).normalize(),u=s.offset>=0?1:-1,p=s.pointA.clone().addScaledVector(h,s.offset),f=s.pointB.clone().addScaledVector(h,s.offset),m=p.clone().add(f).multiplyScalar(.5).addScaledVector(h,(r.textOffset+.5*r.fontSize)*u),g=r.unit??{factor:1,suffix:"m"},w=`${(s.pointA.distanceTo(s.pointB)*g.factor).toFixed(this.precision)} ${g.suffix}`;this._writeText(e,w,m.x,m.z,r.fontSize,a,o,this._textAngle(c.x,c.z),1,2,r.color)}}_writeAngleAnnotations(e,t){var i;const n=this._components.get(Ra).systems.get(_a);if(n)for(const[,s]of t.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=ja(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=t.layers.get(a))?void 0:i.visible))continue;const l=wa(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick)for(const{tip:t,dir:i}of pa(s))this._writeMeshTriangles(e,r.meshTick(t,i,r.tickSize),a,o,r.color);const c=ma(s),h=s.arcRadius+r.textOffset,u=s.vertex.x+Math.cos(c)*h,p=s.vertex.z+Math.sin(c)*h,f=d.MathUtils.radToDeg(fa(s));this._writeText(e,`${f.toFixed(this.precision)}°`,u,p,r.fontSize,a,o,0,1,0,r.color)}}_writeLeaderAnnotations(e,t){var i;const n=this._components.get(Ra).systems.get(Ta);if(n)for(const[,s]of t.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=ja(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=t.layers.get(a))?void 0:i.visible))continue;const l=Sa(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick){const t=(new d.Vector3).subVectors(s.arrowTip,s.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,r.meshTick(s.arrowTip,t.normalize(),r.tickSize),a,o,r.color)}const c=(new d.Vector3).subVectors(s.extensionEnd,s.elbow).setY(0).normalize(),h=c.x<-.1?2:c.x>.1?0:1,u=1===h?.5*r.fontSize:0,p=s.extensionEnd.clone().addScaledVector(c,r.textOffset+u);this._writeText(e,s.text,p.x,p.z,r.fontSize,a,o,0,h,2,r.color)}}_writeSlopeAnnotations(e,t){var i;const n=this._components.get(Ra).systems.get(Ia);if(n)for(const[,s]of t.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=ja(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=t.layers.get(a))?void 0:i.visible))continue;const l=Ea(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick){const t=Ma(s,r.length);this._writeMeshTriangles(e,r.meshTick(t,s.direction,r.tickSize),a,o,r.color)}const c=new d.Vector3(s.position.x+s.direction.x*r.length,0,s.position.z+s.direction.z*r.length),h=s.position.clone().add(c).multiplyScalar(.5).addScaledVector(new d.Vector3(-s.direction.z,0,s.direction.x),r.textOffset+r.fontSize);this._writeText(e,Pa(s.slope,r.format),h.x,h.z,r.fontSize,a,o,this._textAngle(s.direction.x,s.direction.z),1,0,r.color)}}_writeCalloutAnnotations(e,t){var i;const n=this._components.get(Ra).systems.get(Na);if(n)for(const[,s]of t.annotations.getBySystem(n)){const r=n.styles.get(s.style)??n.styles.get("default"),o=ja(r.color),a=this._annotationLayers.get(s.uuid)??"0";if(!1===(null==(i=t.layers.get(a))?void 0:i.visible))continue;const l=ka(s,r);if(!this._fullyInViewport(this._bboxFromPositions(l)))continue;if(this._writePairsAsLines(e,l,a,o,r.color),r.meshTick){const t=(new d.Vector3).subVectors(s.extensionEnd,s.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,r.meshTick(s.extensionEnd,t.normalize(),r.tickSize),a,o,r.color)}const c=(new d.Vector3).subVectors(s.extensionEnd,s.elbow).setY(0).normalize(),h=c.x<-.1?2:c.x>.1?0:1,u=1===h?.5*r.fontSize:0,p=s.extensionEnd.clone().addScaledVector(c,r.textOffset+u);this._writeText(e,s.text,p.x,p.z,r.fontSize,a,o,0,h,2,r.color)}}_writeBlockInsertions(e,t){const i=this._components.get(Ra).systems.get(Aa);if(i)for(const[,n]of t.annotations.getBySystem(i)){if(!this._inViewport(n.position.x,n.position.z))continue;const t=i.styles.get(n.style)??i.styles.get("default"),s=ja(t.color),r=-d.MathUtils.radToDeg(n.rotation),o=n.scale*this._scale();e.p(0,"INSERT").p(5,e.handle()).p(8,"0").p(62,s),this._emitTrueColor(e,t.color),e.p(2,n.blockName).n(10,this._tx(n.position.x)).n(20,this._ty(n.position.z)).n(30,0).n(41,o).n(42,o).n(43,o).n(50,r)}}_writeGeoAsLines(e,t,i,n=7,s){const r=t.attributes.position;if(r)for(let t=0;t+1<r.count;t+=2){const o=this._clipSegment(new d.Vector3(r.getX(t),0,r.getZ(t)),new d.Vector3(r.getX(t+1),0,r.getZ(t+1)));o&&this._writeLine(e,o.start.x,o.start.z,o.end.x,o.end.z,i,n,s)}}_writePairsAsLines(e,t,i,n=7,s){for(let r=0;r+5<t.length;r+=6){const o=this._clipSegment(new d.Vector3(t[r],0,t[r+2]),new d.Vector3(t[r+3],0,t[r+5]));o&&this._writeLine(e,o.start.x,o.start.z,o.end.x,o.end.z,i,n,s)}}_emitTrueColor(e,t){this.config.trueColor&&void 0!==t&&e.p(420,t)}_writeLine(e,t,i,n,s,r,o,a){e.p(0,"LINE").p(5,e.handle()).p(8,r).p(62,o),this._emitTrueColor(e,a),e.n(10,this._tx(t)).n(20,this._ty(i)).n(30,0).n(11,this._tx(n)).n(21,this._ty(s)).n(31,0)}_writeRawLine(e,t,i,n,s,r,o){e.p(0,"LINE").p(5,e.handle()).p(8,r).p(62,o).n(10,t).n(20,i).n(30,0).n(11,n).n(21,s).n(31,0)}_writeSolid(e,t,i,n,s,r,o,a,l,c){e.p(0,"SOLID").p(5,e.handle()).p(8,a).p(62,l),this._emitTrueColor(e,c),e.n(10,this._tx(t)).n(20,this._ty(i)).n(30,0).n(11,this._tx(n)).n(21,this._ty(s)).n(31,0).n(12,this._tx(r)).n(22,this._ty(o)).n(32,0).n(13,this._tx(r)).n(23,this._ty(o)).n(33,0)}_writeMeshTriangles(e,t,i,n,s){for(let r=0;r+8<t.length;r+=9)this._writeSolid(e,t[r],t[r+2],t[r+3],t[r+5],t[r+6],t[r+8],i,n,s)}_writeText(e,t,i,n,s,r,o,a=0,l=0,c=0,h){const d=this._tx(i),u=this._ty(n);e.p(0,"TEXT").p(5,e.handle()).p(8,r).p(62,o),this._emitTrueColor(e,h),e.n(10,d).n(20,u).n(30,0).n(40,s*this._scale()).n(50,a).p(1,t),0===l&&0===c||(0!==l&&e.p(72,l),0!==c&&e.p(73,c),e.n(11,d).n(21,u).n(31,0))}_tx(e){return this._paperSlot?this._paperSlot.x+(e-this._paperSlot.vpLeft)*this._paperSlot.mmPerUnit:this._viewport?e-this._viewport.left:e}_ty(e){return this._paperSlot?this._paperSlot.y-(e+this._paperSlot.vpTop)*this._paperSlot.mmPerUnit:this._viewport?-e-this._viewport.bottom:-e}_scale(){return this._paperSlot?this._paperSlot.mmPerUnit:1}_clipSegment(e,t){return this._viewport?this._viewport.clipLine(new d.Line3(e,t)):new d.Line3(e,t)}_inViewport(e,t){return!this._viewport||this._viewport.bbox.containsPoint(new d.Vector3(e,0,t))}_bboxFromPositions(e){const t=new d.Box3;for(let i=0;i+2<e.length;i+=3)t.expandByPoint(new d.Vector3(e[i],0,e[i+2]));return t}_fullyInViewport(e){return!this._viewport||this._viewport.bbox.containsBox(e)}_textAngle(e,t){let i=Math.atan2(-t,e);return(i>Math.PI/2||i<=-Math.PI/2)&&(i+=Math.PI),d.MathUtils.radToDeg(i)}_writeCustomSystems(e,t){if(0===this._systemExporters.size)return;const i=this._makeContext(e);for(const[e,t]of this._systemExporters){const n=this._components.get(Ra).systems.get(e);n&&t(n,i)}}_makeContext(e){return{writeLine:(t,i,n,s,r="0",o=7)=>{this._writeLine(e,t,i,n,s,r,o)},writePairs:(t,i="0",n=7)=>{this._writePairsAsLines(e,t,i,n)},writeMeshTriangles:(t,i="0",n=7)=>{this._writeMeshTriangles(e,t,i,n)},writeText:(t,i,n,s,r={})=>{this._writeText(e,t,i,n,s,r.layer??"0",r.aciColor??7,r.rotDeg??0,r.hAlign??0)},hexToAci:ja,textAngle:(e,t)=>this._textAngle(e,t)}}}const Ga=class e extends g{constructor(i){super(i),t(this,"enabled",!0),t(this,"exporter",new Wa(this.components)),i.add(e.uuid,this)}};t(Ga,"uuid","e9a2c3d4-5f67-4b89-a012-1c3d5e7f9b2a");let Ha=Ga;exports.AngleAnnotations=_a,exports.AnnotationSystem=ta,exports.ArrowTick=(e,t,i)=>{const n=new d.Vector3(-t.z,0,t.x),s=e.x-t.x*i+n.x*i*.4,r=e.z-t.z*i+n.z*i*.4,o=e.x-t.x*i-n.x*i*.4,a=e.z-t.z*i-n.z*i*.4;return[e.x,e.y,e.z,s,e.y,r,e.x,e.y,e.z,o,e.y,a,s,e.y,r,o,e.y,a]},exports.AsyncEvent=class{constructor(){t(this,"enabled",!0),t(this,"trigger",async e=>{if(!this.enabled)return;const t=this.handlers.slice(0);for(const i of t)await i(e)}),t(this,"handlers",[])}add(e){this.handlers.push(e)}remove(e){this.handlers=this.handlers.filter(t=>t!==e)}reset(){this.handlers.length=0}},exports.BCFTopics=oo,exports.BCFTopicsConfigManager=so,exports.Base=m,exports.BaseCamera=y,exports.BaseRenderer=_,exports.BaseScene=x,exports.BaseWorldItem=w,exports.BlockAnnotations=Aa,exports.BoundingBoxer=wr,exports.CalloutAnnotations=Na,exports.CircleEnclosure=La,exports.Classifier=xr,exports.Clipper=ho,exports.CloudEnclosure=Oa,exports.Comment=eo,exports.Component=g,exports.Components=$r,exports.ConfigManager=He,exports.Configurator=We,exports.ControlsUtils=$e,exports.DataMap=je,exports.DataSet=S,exports.DiagonalTick=Uo,exports.Disposer=v,exports.DotTick=(e,t,i)=>{const n=.4*i,s=[];for(let t=0;t<12;t++){const i=t/12*Math.PI*2,r=(t+1)/12*Math.PI*2;s.push(e.x+Math.cos(i)*n,e.y,e.z+Math.sin(i)*n,e.x+Math.cos(r)*n,e.y,e.z+Math.sin(r)*n)}return s},exports.DrawingAnnotations=Go,exports.DrawingLayers=Ho,exports.DrawingSystem=ta,exports.DrawingViewport=Yo,exports.DrawingViewportHelper=Zo,exports.DrawingViewports=Xo,exports.DxfExporter=Wa,exports.DxfManager=Ha,exports.EdgeProjector=hr,exports.Event=f,exports.EventManager=class{constructor(){t(this,"list",new Set)}add(e){for(const t of e)this.list.add(t)}remove(e){for(const t of e)this.list.delete(t)}set(e){for(const t of this.list)t.enabled=e}reset(){for(const e of this.list)e.reset()}},exports.FastModelPicker=Sr,exports.FastModelPickers=Tr,exports.FilledArrowTick=Wo,exports.FilledCircleTick=(e,t,i)=>{const n=.4*i,s=[];for(let t=0;t<16;t++){const i=t/16*Math.PI*2,r=(t+1)/16*Math.PI*2;s.push(e.x,e.y,e.z,e.x+Math.cos(i)*n,e.y,e.z+Math.sin(i)*n,e.x+Math.cos(r)*n,e.y,e.z+Math.sin(r)*n)}return s},exports.FilledSquareTick=(e,t,i)=>{const n=new d.Vector3(-t.z,0,t.x),s=.4*i,r=e.clone().addScaledVector(t,s).addScaledVector(n,s),o=e.clone().addScaledVector(t,s).addScaledVector(n,-s),a=e.clone().addScaledVector(t,-s).addScaledVector(n,-s),l=e.clone().addScaledVector(t,-s).addScaledVector(n,s);return[r.x,r.y,r.z,o.x,o.y,o.z,a.x,a.y,a.z,r.x,r.y,r.z,a.x,a.y,a.z,l.x,l.y,l.z]},exports.FinderQuery=yr,exports.FirstPersonMode=Wr,exports.FragmentsManager=Zn,exports.Grids=Ur,exports.Hider=mr,exports.IDSAttribute=So,exports.IDSClassification=Co,exports.IDSEntity=To,exports.IDSFacet=vo,exports.IDSMaterial=Eo,exports.IDSPartOf=Mo,exports.IDSProperty=Ao,exports.IDSSpecification=Po,exports.IDSSpecifications=No,exports.IfcFragmentSettings=dr,exports.IfcLoader=pr,exports.ItemsFinder=br,exports.LeaderAnnotations=Ta,exports.LinearAnnotations=la,exports.MeasurementUtils=Ro,exports.ModelIdMapUtils=Ue,exports.Mouse=qe,exports.NoTick=$o,exports.OpenArrowTick=jo,exports.OrbitMode=Gr,exports.OrthoPerspectiveCamera=Zr,exports.PlanMode=Hr,exports.ProjectionManager=qr,exports.Raycasters=Mr,exports.RectEnclosure=Va,exports.RendererMode=Br,exports.ShadowedScene=class extends kr{constructor(){super(...arguments),t(this,"_distanceRenderer"),t(this,"autoBias",!0),t(this,"_defaultShadowConfig",{cascade:1,resolution:512}),t(this,"_lightsWithShadow",new Map),t(this,"_isComputingShadows",!1),t(this,"_shadowsEnabled",!0),t(this,"_bias",0),t(this,"recomputeShadows",e=>{if(!this._shadowsEnabled)return;this.autoBias&&(this.bias=-.005);if(e*=1.5,!this.currentWorld)throw new Error("A world needs to be assigned to the scene before computing shadows!");if(!this._lightsWithShadow.size)throw new Error("No shadows found!");const t=this.currentWorld.camera.three;if(!(t instanceof d.PerspectiveCamera||t instanceof d.OrthographicCamera))throw new Error("Invalid camera type!");const i=new d.Vector3;t.getWorldDirection(i);let n=e;const s=new d.Vector3;s.copy(this.config.directionalLight.position),s.normalize();for(const[e,r]of this._lightsWithShadow){const o=this.directionalLights.get(r);if(!o)throw new Error("Light not found.");const a=new d.Vector3;a.copy(i);const l=e===this._lightsWithShadow.size-1,c=l?n/2:2*n/3;a.multiplyScalar(c),a.add(t.position);const h=n-c,u=new d.Vector3;u.copy(s),u.multiplyScalar(h),o.target.position.copy(a),o.position.copy(a),o.position.add(u),o.shadow.camera.right=h,o.shadow.camera.left=-h,o.shadow.camera.top=h,o.shadow.camera.bottom=-h,o.shadow.camera.far=2*h,o.shadow.camera.updateProjectionMatrix(),o.shadow.camera.updateMatrix(),l||(n/=3)}this._isComputingShadows=!1})}get bias(){return this._bias}set bias(e){this._bias=e;for(const[,t]of this._lightsWithShadow){const i=this.directionalLights.get(t);i&&(i.shadow.bias=e)}}get shadowsEnabled(){return this._shadowsEnabled}set shadowsEnabled(e){this._shadowsEnabled=e;for(const[,t]of this.directionalLights)t.castShadow=e}get distanceRenderer(){if(!this._distanceRenderer)throw new Error("You must set up this component before accessing the distance renderer!");return this._distanceRenderer}setup(e){super.setup(e);const t={...this._defaultConfig,...this._defaultShadowConfig,...e};if(t.cascade<=0)throw new Error("Config.shadows.cascade must be a natural number greater than 0!");if(t.cascade>1)throw new Error("Multiple shadows not supported yet!");if(!this.currentWorld)throw new Error("A world needs to be assigned to the scene before setting it up!");for(const[,e]of this.directionalLights)e.target.removeFromParent(),e.removeFromParent(),e.dispose();this.directionalLights.clear(),this._distanceRenderer||(this._distanceRenderer=new bo(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let e=0;e<t.cascade;e++){const i=new d.DirectionalLight;i.intensity=this.config.directionalLight.intensity,i.color=this.config.directionalLight.color,i.position.copy(this.config.directionalLight.position),i.shadow.mapSize.width=t.resolution,i.shadow.mapSize.height=t.resolution,this.three.add(i,i.target),this.directionalLights.set(i.uuid,i),this._lightsWithShadow.set(e,i.uuid),i.castShadow=!0,i.shadow.bias=this._bias}}dispose(){super.dispose(),this._distanceRenderer&&this._distanceRenderer.dispose(),this._lightsWithShadow.clear()}async updateShadows(){!this._isComputingShadows&&this._shadowsEnabled&&(this._isComputingShadows=!0,await this.distanceRenderer.compute())}},exports.SimpleCamera=Or,exports.SimpleGrid=Fr,exports.SimpleGridConfigManager=Nr,exports.SimplePlane=ao,exports.SimpleRaycaster=Ar,exports.SimpleRenderer=class extends _{constructor(e,i,n){super(e),t(this,"enabled",!0),t(this,"container"),t(this,"three"),t(this,"mode",1),t(this,"needsUpdate",!1),t(this,"_canvas"),t(this,"_parameters"),t(this,"_resizeObserver",null),t(this,"onContainerUpdated",new f),t(this,"_resizing",!1),t(this,"resize",e=>{if(this._resizing)return;this._resizing=!0,this.onContainerUpdated.trigger();const t=e?e.x:this.container.clientWidth,i=e?e.y:this.container.clientHeight;this.three.setSize(t,i),this.onResize.trigger(new d.Vector2(t,i)),this._resizing=!1}),t(this,"resizeEvent",()=>{this.resize()}),t(this,"onContextLost",e=>{e.preventDefault(),this.enabled=!1}),t(this,"onContextBack",()=>{this.three.setRenderTarget(null),this.three.dispose(),this.three=new d.WebGLRenderer({canvas:this._canvas,antialias:!0,alpha:!0,...this._parameters}),this.enabled=!0}),this.container=i,this._parameters=n,this.three=new d.WebGLRenderer({antialias:!0,alpha:!0,...n}),this.three.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.setupRenderer(),this.setupEvents(!0),this.resize(),this._canvas=this.three.domElement;const s=this.three.getContext(),{canvas:r}=s;r.addEventListener("webglcontextlost",this.onContextLost,!1),r.addEventListener("webglcontextrestored",this.onContextBack,!1)}update(){if(!this.enabled||!this.currentWorld)return;if(0===this.mode&&!this.needsUpdate)return;this.needsUpdate=!1,this.onBeforeUpdate.trigger(this);const e=this.currentWorld.scene.three,t=this.currentWorld.camera.three;this.three.render(e,t),this.onAfterUpdate.trigger(this)}dispose(){this.enabled=!1,this.setupEvents(!1),this.three.domElement.remove(),this.three.forceContextLoss(),this.three.dispose(),this.onResize.reset(),this.onAfterUpdate.reset(),this.onBeforeUpdate.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}getSize(){return new d.Vector2(this.three.domElement.clientWidth,this.three.domElement.clientHeight)}setupEvents(e){const t=this.three.domElement.parentElement;if(!t)throw new Error("This renderer needs to have an HTML container!");this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),window.removeEventListener("resize",this.resizeEvent),e&&(this._resizeObserver=new ResizeObserver(this.resizeEvent),this._resizeObserver.observe(t),window.addEventListener("resize",this.resizeEvent))}setupRenderer(){this.three.localClippingEnabled=!0,this.container&&this.container.appendChild(this.three.domElement),this.onContainerUpdated.trigger()}},exports.SimpleScene=kr,exports.SimpleSceneConfigManager=Dr,exports.SimpleWorld=Pr,exports.SlopeAnnotations=Ia,exports.TechnicalDrawing=ea,exports.TechnicalDrawingHelper=Qo,exports.TechnicalDrawings=Ra,exports.Topic=io,exports.UUID=T,exports.Units={m:{factor:1,suffix:"m"},cm:{factor:100,suffix:"cm"},mm:{factor:1e3,suffix:"mm"},ft:{factor:3.28084,suffix:"ft"},in:{factor:39.3701,suffix:"in"}},exports.VertexPicker=class extends g{constructor(e,i){super(e),t(this,"onDisposed",new f),t(this,"onVertexFound",new f),t(this,"onVertexLost",new f),t(this,"onEnabled",new f),t(this,"components"),t(this,"workingPlane",null),t(this,"_pickedPoint",null),t(this,"_config"),t(this,"_enabled",!1),this.components=e,this.config={snapDistance:.25,showOnlyVertex:!1,...i},this.enabled=!1}set enabled(e){this._enabled=e,e||(this._pickedPoint=null),this.onEnabled.trigger(e)}get enabled(){return this._enabled}set config(e){this._config={...this._config,...e}}get config(){return this._config}dispose(){this.onVertexFound.reset(),this.onVertexLost.reset(),this.components=null,this.onDisposed.trigger(),this.onDisposed.reset()}async get(e){if(!this.enabled)return this._pickedPoint;const t=this.components.get(Mr).get(e),i=await t.castRay();if(!i)return null!==this._pickedPoint&&(this.onVertexLost.trigger(),this._pickedPoint=null),this._pickedPoint;const n=i.point;return null!==this._pickedPoint&&this._pickedPoint.equals(n)||(this._pickedPoint=n.clone(),this.onVertexFound.trigger(this._pickedPoint)),this._pickedPoint}},exports.View=go,exports.Viewpoint=uo,exports.Viewpoints=mo,exports.Views=yo,exports.Worlds=Lr,exports.XML=Re,exports.angleDimensionMachine=ua,exports.buildAnglePositions=wa,exports.buildAnglePreviewPositions=ya,exports.buildCalloutPositions=ka,exports.buildCalloutPreviewPositions=Ba,exports.buildDimensionPositions=oa,exports.buildDimensions=na,exports.buildLeaderPositions=Sa,exports.buildLeaderPreviewPositions=Ca,exports.buildPreviewPositions=aa,exports.buildSlopePositions=Ea,exports.calloutAnnotationMachine=Da,exports.computeAlignmentMatrix=Jo,exports.computeAngle=fa,exports.computeBisectorAngle=ma,exports.computeOffset=ia,exports.extensionsImporter=no,exports.formatSlope=Pa,exports.getAngleTickEndpoints=pa,exports.getDimensionTickEndpoints=ra,exports.getSlopeTip=Ma,exports.leaderAnnotationMachine=va,exports.linearDimensionMachine=sa;