@thatopen/components 3.3.2 → 3.4.0

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,10 +1,19 @@
1
- var t=Object.defineProperty,e=(e,i,s)=>(((e,i,s)=>{i in e?t(e,i,{enumerable:!0,configurable:!0,writable:!0,value:s}):e[i]=s})(e,"symbol"!=typeof i?i+"":i,s),s);import*as i from"@thatopen/fragments";import{DataMap as s,FragmentsModels as n,DataSet as r}from"@thatopen/fragments";import*as o from"three";import{BufferAttribute as a,Vector3 as l,Plane as h,Line3 as c,Vector2 as d,Triangle as u,Sphere as p,Matrix4 as f,Box3 as m,BackSide as g,DoubleSide as _,FrontSide as y,Ray as w,Mesh as v,Controls as b,Quaternion as x,Raycaster as T,Object3D as E,MeshBasicMaterial as C,LineBasicMaterial as S,CylinderGeometry as A,BoxGeometry as O,BufferGeometry as P,Float32BufferAttribute as I,OctahedronGeometry as k,Line as D,TorusGeometry as z,SphereGeometry as M,Euler as B,PlaneGeometry as N}from"three";import*as U from"web-ifc";class L{constructor(){e(this,"enabled",!0),e(this,"trigger",t=>{if(!this.enabled)return;const e=this.handlers.slice(0);for(const i of e)i(t)}),e(this,"handlers",[])}add(t){this.handlers.push(t)}remove(t){this.handlers=this.handlers.filter(e=>e!==t)}reset(){this.handlers.length=0}}class R{constructor(){e(this,"enabled",!0),e(this,"trigger",async t=>{if(!this.enabled)return;const e=this.handlers.slice(0);for(const i of e)await i(t)}),e(this,"handlers",[])}add(t){this.handlers.push(t)}remove(t){this.handlers=this.handlers.filter(e=>e!==t)}reset(){this.handlers.length=0}}class F{constructor(t){e(this,"isDisposeable",()=>"dispose"in this&&"onDisposed"in this),e(this,"isResizeable",()=>"resize"in this&&"getSize"in this),e(this,"isUpdateable",()=>"onAfterUpdate"in this&&"onBeforeUpdate"in this&&"update"in this),e(this,"isHideable",()=>"visible"in this),e(this,"isConfigurable",()=>"setup"in this&&"config"in this&&"onSetup"in this),e(this,"isSerializable",()=>"import"in this&&"export"in this),this.components=t}}class V extends F{}class j extends F{constructor(t){super(t),e(this,"worlds",new s),e(this,"onWorldChanged",new L),e(this,"_currentWorld",null),this.onWorldChanged.add(({world:t,action:e})=>{"removed"===e&&this.worlds.delete(t.uuid)})}set currentWorld(t){this._currentWorld=t}get currentWorld(){return this._currentWorld}}class Z extends j{constructor(){super(...arguments),e(this,"hasCameraControls",()=>"controls"in this)}}class H extends j{constructor(){super(...arguments),e(this,"onAfterUpdate",new L),e(this,"onBeforeUpdate",new L),e(this,"onDisposed",new L),e(this,"onResize",new L),e(this,"onClippingPlanesUpdated",new L),e(this,"clippingPlanes",[])}updateClippingPlanes(){this.onClippingPlanesUpdated.trigger()}setPlane(t,e,i){e.isLocal=i;const s=this.clippingPlanes.indexOf(e);t&&-1===s?this.clippingPlanes.push(e):!t&&s>-1&&this.clippingPlanes.splice(s,1),this.three.clippingPlanes=this.clippingPlanes.filter(t=>!t.isLocal)}}const $=class t extends V{constructor(i){super(i),e(this,"_disposedComponents",new Set),e(this,"enabled",!0),i.add(t.uuid,this)}get(){return this._disposedComponents}destroy(t,e=!0,i=!0){t.removeFromParent();const s=t;s.dispose&&s.dispose(),this.disposeGeometryAndMaterials(t,e),i&&s.children&&s.children.length&&this.disposeChildren(s),t.children.length=0}disposeGeometry(t){t.boundsTree&&t.disposeBoundsTree&&t.disposeBoundsTree(),t.dispose()}disposeGeometryAndMaterials(e,i){const s=e;s.geometry&&this.disposeGeometry(s.geometry),i&&s.material&&t.disposeMaterial(s),s.material=[],s.geometry=null}disposeChildren(t){for(const e of t.children)this.destroy(e)}static disposeMaterial(t){if(t.material)if(Array.isArray(t.material))for(const e of t.material)e.dispose();else t.material.dispose()}};e($,"uuid","76e9cd8e-ad8f-4753-9ef6-cbc60f7247fe");let Y=$;class W extends j{constructor(t){super(t),e(this,"onDisposed",new L),e(this,"directionalLights",new Map),e(this,"ambientLights",new Map)}dispose(){const t=this.components.get(Y);for(const e of this.three.children){const i=e;i.geometry&&t.destroy(i)}this.deleteAllLights(),this.three.children=[],this.onDisposed.trigger(),this.onDisposed.reset()}deleteAllLights(){for(const[,t]of this.directionalLights)t.removeFromParent(),t.target.removeFromParent(),t.dispose();this.directionalLights.clear();for(const[,t]of this.ambientLights)t.removeFromParent(),t.dispose();this.ambientLights.clear()}}class X extends Set{constructor(t){super(t),e(this,"onItemAdded",new L),e(this,"onItemDeleted",new L),e(this,"onCleared",new L),e(this,"guard",()=>!0)}clear(){super.clear(),this.onCleared.trigger()}add(...t){for(const e of t){if(this.has(e))continue;this.guard(e)&&(super.add(e),this.onItemAdded||(this.onItemAdded=new L),this.onItemAdded.trigger(e))}return this}delete(t){const e=super.delete(t);return e&&this.onItemDeleted.trigger(),e}dispose(){this.clear(),this.onItemAdded.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}const q=class t{static create(){const e=4294967295*Math.random()|0,i=4294967295*Math.random()|0,s=4294967295*Math.random()|0,n=4294967295*Math.random()|0;return`${t._lut[255&e]+t._lut[e>>8&255]+t._lut[e>>16&255]+t._lut[e>>24&255]}-${t._lut[255&i]}${t._lut[i>>8&255]}-${t._lut[i>>16&15|64]}${t._lut[i>>24&255]}-${t._lut[63&s|128]}${t._lut[s>>8&255]}-${t._lut[s>>16&255]}${t._lut[s>>24&255]}${t._lut[255&n]}${t._lut[n>>8&255]}${t._lut[n>>16&255]}${t._lut[n>>24&255]}`.toLowerCase()}static validate(e){if(!t._pattern.test(e))throw new Error(`${e} is not a valid UUID v4.\n\n- If you're the tool creator, you can take one from https://www.uuidgenerator.net/.\n\n- If you're using a platform tool, verify the uuid isn't misspelled or contact the tool creator.`)}};e(q,"_pattern",/^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-4[0-9a-fA-F]{3}-[89abAB][0-9a-fA-F]{3}-[0-9a-fA-F]{12}$/),e(q,"_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 G=q;var Q="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function K(t){return t&&t.__esModule&&Object.prototype.hasOwnProperty.call(t,"default")?t.default:t}var J={},tt={};!function(t){const e=":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",i="["+e+"]["+(e+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*",s=new RegExp("^"+i+"$");t.isExist=function(t){return void 0!==t},t.isEmptyObject=function(t){return 0===Object.keys(t).length},t.merge=function(t,e,i){if(e){const s=Object.keys(e),n=s.length;for(let r=0;r<n;r++)t[s[r]]="strict"===i?[e[s[r]]]:e[s[r]]}},t.getValue=function(e){return t.isExist(e)?e:""},t.isName=function(t){const e=s.exec(t);return!(null==e)},t.getAllMatches=function(t,e){const i=[];let s=e.exec(t);for(;s;){const n=[];n.startIndex=e.lastIndex-s[0].length;const r=s.length;for(let t=0;t<r;t++)n.push(s[t]);i.push(n),s=e.exec(t)}return i},t.nameRegexp=i}(tt);const et=tt,it={allowBooleanAttributes:!1,unpairedTags:[]};function st(t){return" "===t||"\t"===t||"\n"===t||"\r"===t}function nt(t,e){const i=e;for(;e<t.length;e++)if("?"==t[e]||" "==t[e]){const s=t.substr(i,e-i);if(e>5&&"xml"===s)return ut("InvalidXml","XML declaration allowed only at the start of the document.",mt(t,e));if("?"==t[e]&&">"==t[e+1]){e++;break}continue}return e}function rt(t,e){if(t.length>e+5&&"-"===t[e+1]&&"-"===t[e+2]){for(e+=3;e<t.length;e++)if("-"===t[e]&&"-"===t[e+1]&&">"===t[e+2]){e+=2;break}}else if(t.length>e+8&&"D"===t[e+1]&&"O"===t[e+2]&&"C"===t[e+3]&&"T"===t[e+4]&&"Y"===t[e+5]&&"P"===t[e+6]&&"E"===t[e+7]){let i=1;for(e+=8;e<t.length;e++)if("<"===t[e])i++;else if(">"===t[e]&&(i--,0===i))break}else if(t.length>e+9&&"["===t[e+1]&&"C"===t[e+2]&&"D"===t[e+3]&&"A"===t[e+4]&&"T"===t[e+5]&&"A"===t[e+6]&&"["===t[e+7])for(e+=8;e<t.length;e++)if("]"===t[e]&&"]"===t[e+1]&&">"===t[e+2]){e+=2;break}return e}J.validate=function(t,e){e=Object.assign({},it,e);const i=[];let s=!1,n=!1;"\ufeff"===t[0]&&(t=t.substr(1));for(let r=0;r<t.length;r++)if("<"===t[r]&&"?"===t[r+1]){if(r+=2,r=nt(t,r),r.err)return r}else{if("<"!==t[r]){if(st(t[r]))continue;return ut("InvalidChar","char '"+t[r]+"' is not expected.",mt(t,r))}{let o=r;if(r++,"!"===t[r]){r=rt(t,r);continue}{let a=!1;"/"===t[r]&&(a=!0,r++);let l="";for(;r<t.length&&">"!==t[r]&&" "!==t[r]&&"\t"!==t[r]&&"\n"!==t[r]&&"\r"!==t[r];r++)l+=t[r];if(l=l.trim(),"/"===l[l.length-1]&&(l=l.substring(0,l.length-1),r--),!ft(l)){let e;return e=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",ut("InvalidTag",e,mt(t,r))}const h=lt(t,r);if(!1===h)return ut("InvalidAttr","Attributes for '"+l+"' have open quote.",mt(t,r));let c=h.value;if(r=h.index,"/"===c[c.length-1]){const i=r-c.length;c=c.substring(0,c.length-1);const n=ct(c,e);if(!0!==n)return ut(n.err.code,n.err.msg,mt(t,i+n.err.line));s=!0}else if(a){if(!h.tagClosed)return ut("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",mt(t,r));if(c.trim().length>0)return ut("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",mt(t,o));if(0===i.length)return ut("InvalidTag","Closing tag '"+l+"' has not been opened.",mt(t,o));{const e=i.pop();if(l!==e.tagName){let i=mt(t,e.tagStartPos);return ut("InvalidTag","Expected closing tag '"+e.tagName+"' (opened in line "+i.line+", col "+i.col+") instead of closing tag '"+l+"'.",mt(t,o))}0==i.length&&(n=!0)}}else{const a=ct(c,e);if(!0!==a)return ut(a.err.code,a.err.msg,mt(t,r-c.length+a.err.line));if(!0===n)return ut("InvalidXml","Multiple possible root nodes found.",mt(t,r));-1!==e.unpairedTags.indexOf(l)||i.push({tagName:l,tagStartPos:o}),s=!0}for(r++;r<t.length;r++)if("<"===t[r]){if("!"===t[r+1]){r++,r=rt(t,r);continue}if("?"!==t[r+1])break;if(r=nt(t,++r),r.err)return r}else if("&"===t[r]){const e=dt(t,r);if(-1==e)return ut("InvalidChar","char '&' is not expected.",mt(t,r));r=e}else if(!0===n&&!st(t[r]))return ut("InvalidXml","Extra text at the end",mt(t,r));"<"===t[r]&&r--}}}return s?1==i.length?ut("InvalidTag","Unclosed tag '"+i[0].tagName+"'.",mt(t,i[0].tagStartPos)):!(i.length>0)||ut("InvalidXml","Invalid '"+JSON.stringify(i.map(t=>t.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):ut("InvalidXml","Start tag expected.",1)};const ot='"',at="'";function lt(t,e){let i="",s="",n=!1;for(;e<t.length;e++){if(t[e]===ot||t[e]===at)""===s?s=t[e]:s!==t[e]||(s="");else if(">"===t[e]&&""===s){n=!0;break}i+=t[e]}return""===s&&{value:i,index:e,tagClosed:n}}const ht=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function ct(t,e){const i=et.getAllMatches(t,ht),s={};for(let t=0;t<i.length;t++){if(0===i[t][1].length)return ut("InvalidAttr","Attribute '"+i[t][2]+"' has no space in starting.",gt(i[t]));if(void 0!==i[t][3]&&void 0===i[t][4])return ut("InvalidAttr","Attribute '"+i[t][2]+"' is without value.",gt(i[t]));if(void 0===i[t][3]&&!e.allowBooleanAttributes)return ut("InvalidAttr","boolean attribute '"+i[t][2]+"' is not allowed.",gt(i[t]));const n=i[t][2];if(!pt(n))return ut("InvalidAttr","Attribute '"+n+"' is an invalid name.",gt(i[t]));if(s.hasOwnProperty(n))return ut("InvalidAttr","Attribute '"+n+"' is repeated.",gt(i[t]));s[n]=1}return!0}function dt(t,e){if(";"===t[++e])return-1;if("#"===t[e])return function(t,e){let i=/\d/;for("x"===t[e]&&(e++,i=/[\da-fA-F]/);e<t.length;e++){if(";"===t[e])return e;if(!t[e].match(i))break}return-1}(t,++e);let i=0;for(;e<t.length;e++,i++)if(!(t[e].match(/\w/)&&i<20)){if(";"===t[e])break;return-1}return e}function ut(t,e,i){return{err:{code:t,msg:e,line:i.line||i,col:i.col}}}function pt(t){return et.isName(t)}function ft(t){return et.isName(t)}function mt(t,e){const i=t.substring(0,e).split(/\r?\n/);return{line:i.length,col:i[i.length-1].length+1}}function gt(t){return t.startIndex+t[1].length}var _t={};const yt={preserveOrder:!1,attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,removeNSPrefix:!1,allowBooleanAttributes:!1,parseTagValue:!0,parseAttributeValue:!1,trimValues:!0,cdataPropName:!1,numberParseOptions:{hex:!0,leadingZeros:!0,eNotation:!0},tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},stopNodes:[],alwaysCreateTextNode:!1,isArray:()=>!1,commentPropName:!1,unpairedTags:[],processEntities:!0,htmlEntities:!1,ignoreDeclaration:!1,ignorePiTags:!1,transformTagName:!1,transformAttributeName:!1,updateTag:function(t,e,i){return t}};_t.buildOptions=function(t){return Object.assign({},yt,t)},_t.defaultOptions=yt;const wt=tt;function vt(t,e){let i="";for(;e<t.length&&"'"!==t[e]&&'"'!==t[e];e++)i+=t[e];if(i=i.trim(),-1!==i.indexOf(" "))throw new Error("External entites are not supported");const s=t[e++];let n="";for(;e<t.length&&t[e]!==s;e++)n+=t[e];return[i,n,e]}function bt(t,e){return"!"===t[e+1]&&"-"===t[e+2]&&"-"===t[e+3]}function xt(t,e){return"!"===t[e+1]&&"E"===t[e+2]&&"N"===t[e+3]&&"T"===t[e+4]&&"I"===t[e+5]&&"T"===t[e+6]&&"Y"===t[e+7]}function Tt(t,e){return"!"===t[e+1]&&"E"===t[e+2]&&"L"===t[e+3]&&"E"===t[e+4]&&"M"===t[e+5]&&"E"===t[e+6]&&"N"===t[e+7]&&"T"===t[e+8]}function Et(t,e){return"!"===t[e+1]&&"A"===t[e+2]&&"T"===t[e+3]&&"T"===t[e+4]&&"L"===t[e+5]&&"I"===t[e+6]&&"S"===t[e+7]&&"T"===t[e+8]}function Ct(t,e){return"!"===t[e+1]&&"N"===t[e+2]&&"O"===t[e+3]&&"T"===t[e+4]&&"A"===t[e+5]&&"T"===t[e+6]&&"I"===t[e+7]&&"O"===t[e+8]&&"N"===t[e+9]}function St(t){if(wt.isName(t))return t;throw new Error(`Invalid entity name ${t}`)}const At=/^[-+]?0x[a-fA-F0-9]+$/,Ot=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Pt={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};const It=tt,kt=class{constructor(t){this.tagname=t,this.child=[],this[":@"]={}}add(t,e){"__proto__"===t&&(t="#__proto__"),this.child.push({[t]:e})}addChild(t){"__proto__"===t.tagname&&(t.tagname="#__proto__"),t[":@"]&&Object.keys(t[":@"]).length>0?this.child.push({[t.tagname]:t.child,":@":t[":@"]}):this.child.push({[t.tagname]:t.child})}},Dt=function(t,e){const i={};if("O"!==t[e+3]||"C"!==t[e+4]||"T"!==t[e+5]||"Y"!==t[e+6]||"P"!==t[e+7]||"E"!==t[e+8])throw new Error("Invalid Tag instead of DOCTYPE");{e+=9;let s=1,n=!1,r=!1,o="";for(;e<t.length;e++)if("<"!==t[e]||r)if(">"===t[e]){if(r?"-"===t[e-1]&&"-"===t[e-2]&&(r=!1,s--):s--,0===s)break}else"["===t[e]?n=!0:o+=t[e];else{if(n&&xt(t,e))e+=7,[entityName,val,e]=vt(t,e+1),-1===val.indexOf("&")&&(i[St(entityName)]={regx:RegExp(`&${entityName};`,"g"),val:val});else if(n&&Tt(t,e))e+=8;else if(n&&Et(t,e))e+=8;else if(n&&Ct(t,e))e+=9;else{if(!bt)throw new Error("Invalid DOCTYPE");r=!0}s++,o=""}if(0!==s)throw new Error("Unclosed DOCTYPE")}return{entities:i,i:e}},zt=function(t,e={}){if(e=Object.assign({},Pt,e),!t||"string"!=typeof t)return t;let i=t.trim();if(void 0!==e.skipLike&&e.skipLike.test(i))return t;if("0"===t)return 0;if(e.hex&&At.test(i))return function(t,e){if(parseInt)return parseInt(t,e);if(Number.parseInt)return Number.parseInt(t,e);if(window&&window.parseInt)return window.parseInt(t,e);throw new Error("parseInt, Number.parseInt, window.parseInt are not supported")}(i,16);if(-1!==i.search(/[eE]/)){const s=i.match(/^([-\+])?(0*)([0-9]*(\.[0-9]*)?[eE][-\+]?[0-9]+)$/);if(s){if(e.leadingZeros)i=(s[1]||"")+s[3];else if("0"!==s[2]||"."!==s[3][0])return t;return e.eNotation?Number(i):t}return t}{const s=Ot.exec(i);if(s){const n=s[1],r=s[2];let o=function(t){if(t&&-1!==t.indexOf("."))return"."===(t=t.replace(/0+$/,""))?t="0":"."===t[0]?t="0"+t:"."===t[t.length-1]&&(t=t.substr(0,t.length-1)),t;return t}(s[3]);if(!e.leadingZeros&&r.length>0&&n&&"."!==i[2])return t;if(!e.leadingZeros&&r.length>0&&!n&&"."!==i[1])return t;if(e.leadingZeros&&r===t)return 0;{const s=Number(i),a=""+s;return-1!==a.search(/[eE]/)?e.eNotation?s:t:-1!==i.indexOf(".")?"0"===a&&""===o||a===o||n&&a==="-"+o?s:t:r?o===a||n+o===a?s:t:i===a||i===n+a?s:t}}return t}};function Mt(t){const e=Object.keys(t);for(let i=0;i<e.length;i++){const s=e[i];this.lastEntities[s]={regex:new RegExp("&"+s+";","g"),val:t[s]}}}function Bt(t,e,i,s,n,r,o){if(void 0!==t&&(this.options.trimValues&&!s&&(t=t.trim()),t.length>0)){o||(t=this.replaceEntitiesValue(t));const s=this.options.tagValueProcessor(e,t,i,n,r);if(null==s)return t;if(typeof s!=typeof t||s!==t)return s;if(this.options.trimValues)return Wt(t,this.options.parseTagValue,this.options.numberParseOptions);return t.trim()===t?Wt(t,this.options.parseTagValue,this.options.numberParseOptions):t}}function Nt(t){if(this.options.removeNSPrefix){const e=t.split(":"),i="/"===t.charAt(0)?"/":"";if("xmlns"===e[0])return"";2===e.length&&(t=i+e[1])}return t}const Ut=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function Lt(t,e,i){if(!this.options.ignoreAttributes&&"string"==typeof t){const i=It.getAllMatches(t,Ut),s=i.length,n={};for(let t=0;t<s;t++){const s=this.resolveNameSpace(i[t][1]);let r=i[t][4],o=this.options.attributeNamePrefix+s;if(s.length)if(this.options.transformAttributeName&&(o=this.options.transformAttributeName(o)),"__proto__"===o&&(o="#__proto__"),void 0!==r){this.options.trimValues&&(r=r.trim()),r=this.replaceEntitiesValue(r);const t=this.options.attributeValueProcessor(s,r,e);n[o]=null==t?r:typeof t!=typeof r||t!==r?t:Wt(r,this.options.parseAttributeValue,this.options.numberParseOptions)}else this.options.allowBooleanAttributes&&(n[o]=!0)}if(!Object.keys(n).length)return;if(this.options.attributesGroupName){const t={};return t[this.options.attributesGroupName]=n,t}return n}}const Rt=function(t){t=t.replace(/\r\n?/g,"\n");const e=new kt("!xml");let i=e,s="",n="";for(let r=0;r<t.length;r++){if("<"===t[r])if("/"===t[r+1]){const e=Ht(t,">",r,"Closing Tag is not closed.");let o=t.substring(r+2,e).trim();if(this.options.removeNSPrefix){const t=o.indexOf(":");-1!==t&&(o=o.substr(t+1))}this.options.transformTagName&&(o=this.options.transformTagName(o)),i&&(s=this.saveTextToParentTag(s,i,n));const a=n.substring(n.lastIndexOf(".")+1);if(o&&-1!==this.options.unpairedTags.indexOf(o))throw new Error(`Unpaired tag can not be used as closing tag: </${o}>`);let l=0;a&&-1!==this.options.unpairedTags.indexOf(a)?(l=n.lastIndexOf(".",n.lastIndexOf(".")-1),this.tagsNodeStack.pop()):l=n.lastIndexOf("."),n=n.substring(0,l),i=this.tagsNodeStack.pop(),s="",r=e}else if("?"===t[r+1]){let e=$t(t,r,!1,"?>");if(!e)throw new Error("Pi Tag is not closed.");if(s=this.saveTextToParentTag(s,i,n),this.options.ignoreDeclaration&&"?xml"===e.tagName||this.options.ignorePiTags);else{const t=new kt(e.tagName);t.add(this.options.textNodeName,""),e.tagName!==e.tagExp&&e.attrExpPresent&&(t[":@"]=this.buildAttributesMap(e.tagExp,n,e.tagName)),this.addChild(i,t,n)}r=e.closeIndex+1}else if("!--"===t.substr(r+1,3)){const e=Ht(t,"--\x3e",r+4,"Comment is not closed.");if(this.options.commentPropName){const o=t.substring(r+4,e-2);s=this.saveTextToParentTag(s,i,n),i.add(this.options.commentPropName,[{[this.options.textNodeName]:o}])}r=e}else if("!D"===t.substr(r+1,2)){const e=Dt(t,r);this.docTypeEntities=e.entities,r=e.i}else if("!["===t.substr(r+1,2)){const e=Ht(t,"]]>",r,"CDATA is not closed.")-2,o=t.substring(r+9,e);s=this.saveTextToParentTag(s,i,n);let a=this.parseTextData(o,i.tagname,n,!0,!1,!0,!0);null==a&&(a=""),this.options.cdataPropName?i.add(this.options.cdataPropName,[{[this.options.textNodeName]:o}]):i.add(this.options.textNodeName,a),r=e+2}else{let o=$t(t,r,this.options.removeNSPrefix),a=o.tagName;const l=o.rawTagName;let h=o.tagExp,c=o.attrExpPresent,d=o.closeIndex;this.options.transformTagName&&(a=this.options.transformTagName(a)),i&&s&&"!xml"!==i.tagname&&(s=this.saveTextToParentTag(s,i,n,!1));const u=i;if(u&&-1!==this.options.unpairedTags.indexOf(u.tagname)&&(i=this.tagsNodeStack.pop(),n=n.substring(0,n.lastIndexOf("."))),a!==e.tagname&&(n+=n?"."+a:a),this.isItStopNode(this.options.stopNodes,n,a)){let e="";if(h.length>0&&h.lastIndexOf("/")===h.length-1)"/"===a[a.length-1]?(a=a.substr(0,a.length-1),n=n.substr(0,n.length-1),h=a):h=h.substr(0,h.length-1),r=o.closeIndex;else if(-1!==this.options.unpairedTags.indexOf(a))r=o.closeIndex;else{const i=this.readStopNodeData(t,l,d+1);if(!i)throw new Error(`Unexpected end of ${l}`);r=i.i,e=i.tagContent}const s=new kt(a);a!==h&&c&&(s[":@"]=this.buildAttributesMap(h,n,a)),e&&(e=this.parseTextData(e,a,n,!0,c,!0,!0)),n=n.substr(0,n.lastIndexOf(".")),s.add(this.options.textNodeName,e),this.addChild(i,s,n)}else{if(h.length>0&&h.lastIndexOf("/")===h.length-1){"/"===a[a.length-1]?(a=a.substr(0,a.length-1),n=n.substr(0,n.length-1),h=a):h=h.substr(0,h.length-1),this.options.transformTagName&&(a=this.options.transformTagName(a));const t=new kt(a);a!==h&&c&&(t[":@"]=this.buildAttributesMap(h,n,a)),this.addChild(i,t,n),n=n.substr(0,n.lastIndexOf("."))}else{const t=new kt(a);this.tagsNodeStack.push(i),a!==h&&c&&(t[":@"]=this.buildAttributesMap(h,n,a)),this.addChild(i,t,n),i=t}s="",r=d}}else s+=t[r]}return e.child};function Ft(t,e,i){const s=this.options.updateTag(e.tagname,i,e[":@"]);!1===s||("string"==typeof s?(e.tagname=s,t.addChild(e)):t.addChild(e))}const Vt=function(t){if(this.options.processEntities){for(let e in this.docTypeEntities){const i=this.docTypeEntities[e];t=t.replace(i.regx,i.val)}for(let e in this.lastEntities){const i=this.lastEntities[e];t=t.replace(i.regex,i.val)}if(this.options.htmlEntities)for(let e in this.htmlEntities){const i=this.htmlEntities[e];t=t.replace(i.regex,i.val)}t=t.replace(this.ampEntity.regex,this.ampEntity.val)}return t};function jt(t,e,i,s){return t&&(void 0===s&&(s=0===Object.keys(e.child).length),void 0!==(t=this.parseTextData(t,e.tagname,i,!1,!!e[":@"]&&0!==Object.keys(e[":@"]).length,s))&&""!==t&&e.add(this.options.textNodeName,t),t=""),t}function Zt(t,e,i){const s="*."+i;for(const i in t){const n=t[i];if(s===n||e===n)return!0}return!1}function Ht(t,e,i,s){const n=t.indexOf(e,i);if(-1===n)throw new Error(s);return n+e.length-1}function $t(t,e,i,s=">"){const n=function(t,e,i=">"){let s,n="";for(let r=e;r<t.length;r++){let e=t[r];if(s)e===s&&(s="");else if('"'===e||"'"===e)s=e;else if(e===i[0]){if(!i[1])return{data:n,index:r};if(t[r+1]===i[1])return{data:n,index:r}}else"\t"===e&&(e=" ");n+=e}}(t,e+1,s);if(!n)return;let r=n.data;const o=n.index,a=r.search(/\s/);let l=r,h=!0;-1!==a&&(l=r.substring(0,a),r=r.substring(a+1).trimStart());const c=l;if(i){const t=l.indexOf(":");-1!==t&&(l=l.substr(t+1),h=l!==n.data.substr(t+1))}return{tagName:l,tagExp:r,closeIndex:o,attrExpPresent:h,rawTagName:c}}function Yt(t,e,i){const s=i;let n=1;for(;i<t.length;i++)if("<"===t[i])if("/"===t[i+1]){const r=Ht(t,">",i,`${e} is not closed`);if(t.substring(i+2,r).trim()===e&&(n--,0===n))return{tagContent:t.substring(s,i),i:r};i=r}else if("?"===t[i+1]){i=Ht(t,"?>",i+1,"StopNode is not closed.")}else if("!--"===t.substr(i+1,3)){i=Ht(t,"--\x3e",i+3,"StopNode is not closed.")}else if("!["===t.substr(i+1,2)){i=Ht(t,"]]>",i,"StopNode is not closed.")-2}else{const s=$t(t,i,">");if(s){(s&&s.tagName)===e&&"/"!==s.tagExp[s.tagExp.length-1]&&n++,i=s.closeIndex}}}function Wt(t,e,i){if(e&&"string"==typeof t){const e=t.trim();return"true"===e||"false"!==e&&zt(t,i)}return It.isExist(t)?t:""}var Xt=class{constructor(t){this.options=t,this.currentNode=null,this.tagsNodeStack=[],this.docTypeEntities={},this.lastEntities={apos:{regex:/&(apos|#39|#x27);/g,val:"'"},gt:{regex:/&(gt|#62|#x3E);/g,val:">"},lt:{regex:/&(lt|#60|#x3C);/g,val:"<"},quot:{regex:/&(quot|#34|#x22);/g,val:'"'}},this.ampEntity={regex:/&(amp|#38|#x26);/g,val:"&"},this.htmlEntities={space:{regex:/&(nbsp|#160);/g,val:" "},cent:{regex:/&(cent|#162);/g,val:"¢"},pound:{regex:/&(pound|#163);/g,val:"£"},yen:{regex:/&(yen|#165);/g,val:"¥"},euro:{regex:/&(euro|#8364);/g,val:"€"},copyright:{regex:/&(copy|#169);/g,val:"©"},reg:{regex:/&(reg|#174);/g,val:"®"},inr:{regex:/&(inr|#8377);/g,val:"₹"},num_dec:{regex:/&#([0-9]{1,7});/g,val:(t,e)=>String.fromCharCode(Number.parseInt(e,10))},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(t,e)=>String.fromCharCode(Number.parseInt(e,16))}},this.addExternalEntities=Mt,this.parseXml=Rt,this.parseTextData=Bt,this.resolveNameSpace=Nt,this.buildAttributesMap=Lt,this.isItStopNode=Zt,this.replaceEntitiesValue=Vt,this.readStopNodeData=Yt,this.saveTextToParentTag=jt,this.addChild=Ft}},qt={};function Gt(t,e,i){let s;const n={};for(let r=0;r<t.length;r++){const o=t[r],a=Qt(o);let l="";if(l=void 0===i?a:i+"."+a,a===e.textNodeName)void 0===s?s=o[a]:s+=""+o[a];else{if(void 0===a)continue;if(o[a]){let t=Gt(o[a],e,l);const i=Jt(t,e);o[":@"]?Kt(t,o[":@"],l,e):1!==Object.keys(t).length||void 0===t[e.textNodeName]||e.alwaysCreateTextNode?0===Object.keys(t).length&&(e.alwaysCreateTextNode?t[e.textNodeName]="":t=""):t=t[e.textNodeName],void 0!==n[a]&&n.hasOwnProperty(a)?(Array.isArray(n[a])||(n[a]=[n[a]]),n[a].push(t)):e.isArray(a,l,i)?n[a]=[t]:n[a]=t}}}return"string"==typeof s?s.length>0&&(n[e.textNodeName]=s):void 0!==s&&(n[e.textNodeName]=s),n}function Qt(t){const e=Object.keys(t);for(let t=0;t<e.length;t++){const i=e[t];if(":@"!==i)return i}}function Kt(t,e,i,s){if(e){const n=Object.keys(e),r=n.length;for(let o=0;o<r;o++){const r=n[o];s.isArray(r,i+"."+r,!0,!0)?t[r]=[e[r]]:t[r]=e[r]}}}function Jt(t,e){const{textNodeName:i}=e,s=Object.keys(t).length;return 0===s||!(1!==s||!t[i]&&"boolean"!=typeof t[i]&&0!==t[i])}qt.prettify=function(t,e){return Gt(t,e)};const{buildOptions:te}=_t,ee=Xt,{prettify:ie}=qt,se=J;var ne=class{constructor(t){this.externalEntities={},this.options=te(t)}parse(t,e){if("string"==typeof t);else{if(!t.toString)throw new Error("XML data is accepted in String or Bytes[] form.");t=t.toString()}if(e){!0===e&&(e={});const i=se.validate(t,e);if(!0!==i)throw Error(`${i.err.msg}:${i.err.line}:${i.err.col}`)}const i=new ee(this.options);i.addExternalEntities(this.externalEntities);const s=i.parseXml(t);return this.options.preserveOrder||void 0===s?s:ie(s,this.options)}addEntity(t,e){if(-1!==e.indexOf("&"))throw new Error("Entity value can't have '&'");if(-1!==t.indexOf("&")||-1!==t.indexOf(";"))throw new Error("An entity must be set without '&' and ';'. Eg. use '#xD' for '&#xD;'");if("&"===e)throw new Error("An entity with value '&' is not permitted");this.externalEntities[t]=e}};function re(t,e,i,s){let n="",r=!1;for(let o=0;o<t.length;o++){const a=t[o],l=oe(a);if(void 0===l)continue;let h="";if(h=0===i.length?l:`${i}.${l}`,l===e.textNodeName){let t=a[l];le(h,e)||(t=e.tagValueProcessor(l,t),t=he(t,e)),r&&(n+=s),n+=t,r=!1;continue}if(l===e.cdataPropName){r&&(n+=s),n+=`<![CDATA[${a[l][0][e.textNodeName]}]]>`,r=!1;continue}if(l===e.commentPropName){n+=s+`\x3c!--${a[l][0][e.textNodeName]}--\x3e`,r=!0;continue}if("?"===l[0]){const t=ae(a[":@"],e),i="?xml"===l?"":s;let o=a[l][0][e.textNodeName];o=0!==o.length?" "+o:"",n+=i+`<${l}${o}${t}?>`,r=!0;continue}let c=s;""!==c&&(c+=e.indentBy);const d=s+`<${l}${ae(a[":@"],e)}`,u=re(a[l],e,h,c);-1!==e.unpairedTags.indexOf(l)?e.suppressUnpairedNode?n+=d+">":n+=d+"/>":u&&0!==u.length||!e.suppressEmptyNode?u&&u.endsWith(">")?n+=d+`>${u}${s}</${l}>`:(n+=d+">",u&&""!==s&&(u.includes("/>")||u.includes("</"))?n+=s+e.indentBy+u+s:n+=u,n+=`</${l}>`):n+=d+"/>",r=!0}return n}function oe(t){const e=Object.keys(t);for(let i=0;i<e.length;i++){const s=e[i];if(t.hasOwnProperty(s)&&":@"!==s)return s}}function ae(t,e){let i="";if(t&&!e.ignoreAttributes)for(let s in t){if(!t.hasOwnProperty(s))continue;let n=e.attributeValueProcessor(s,t[s]);n=he(n,e),!0===n&&e.suppressBooleanAttributes?i+=` ${s.substr(e.attributeNamePrefix.length)}`:i+=` ${s.substr(e.attributeNamePrefix.length)}="${n}"`}return i}function le(t,e){let i=(t=t.substr(0,t.length-e.textNodeName.length-1)).substr(t.lastIndexOf(".")+1);for(let s in e.stopNodes)if(e.stopNodes[s]===t||e.stopNodes[s]==="*."+i)return!0;return!1}function he(t,e){if(t&&t.length>0&&e.processEntities)for(let i=0;i<e.entities.length;i++){const s=e.entities[i];t=t.replace(s.regex,s.val)}return t}const ce=function(t,e){let i="";return e.format&&e.indentBy.length>0&&(i="\n"),re(t,e,"",i)},de={attributeNamePrefix:"@_",attributesGroupName:!1,textNodeName:"#text",ignoreAttributes:!0,cdataPropName:!1,format:!1,indentBy:" ",suppressEmptyNode:!1,suppressUnpairedNode:!0,suppressBooleanAttributes:!0,tagValueProcessor:function(t,e){return e},attributeValueProcessor:function(t,e){return e},preserveOrder:!1,commentPropName:!1,unpairedTags:[],entities:[{regex:new RegExp("&","g"),val:"&amp;"},{regex:new RegExp(">","g"),val:"&gt;"},{regex:new RegExp("<","g"),val:"&lt;"},{regex:new RegExp("'","g"),val:"&apos;"},{regex:new RegExp('"',"g"),val:"&quot;"}],processEntities:!0,stopNodes:[],oneListGroup:!1};function ue(t){this.options=Object.assign({},de,t),this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=me),this.processTextOrObjNode=pe,this.options.format?(this.indentate=fe,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function pe(t,e,i){const s=this.j2x(t,i+1);return void 0!==t[this.options.textNodeName]&&1===Object.keys(t).length?this.buildTextValNode(t[this.options.textNodeName],e,s.attrStr,i):this.buildObjectNode(s.val,e,s.attrStr,i)}function fe(t){return this.options.indentBy.repeat(t)}function me(t){return!(!t.startsWith(this.options.attributeNamePrefix)||t===this.options.textNodeName)&&t.substr(this.attrPrefixLen)}ue.prototype.build=function(t){return this.options.preserveOrder?ce(t,this.options):(Array.isArray(t)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(t={[this.options.arrayNodeName]:t}),this.j2x(t,0).val)},ue.prototype.j2x=function(t,e){let i="",s="";for(let n in t)if(Object.prototype.hasOwnProperty.call(t,n))if(void 0===t[n])this.isAttribute(n)&&(s+="");else if(null===t[n])this.isAttribute(n)?s+="":"?"===n[0]?s+=this.indentate(e)+"<"+n+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+n+"/"+this.tagEndChar;else if(t[n]instanceof Date)s+=this.buildTextValNode(t[n],n,"",e);else if("object"!=typeof t[n]){const r=this.isAttribute(n);if(r)i+=this.buildAttrPairStr(r,""+t[n]);else if(n===this.options.textNodeName){let e=this.options.tagValueProcessor(n,""+t[n]);s+=this.replaceEntitiesValue(e)}else s+=this.buildTextValNode(t[n],n,"",e)}else if(Array.isArray(t[n])){const i=t[n].length;let r="",o="";for(let a=0;a<i;a++){const i=t[n][a];if(void 0===i);else if(null===i)"?"===n[0]?s+=this.indentate(e)+"<"+n+"?"+this.tagEndChar:s+=this.indentate(e)+"<"+n+"/"+this.tagEndChar;else if("object"==typeof i)if(this.options.oneListGroup){const t=this.j2x(i,e+1);r+=t.val,this.options.attributesGroupName&&i.hasOwnProperty(this.options.attributesGroupName)&&(o+=t.attrStr)}else r+=this.processTextOrObjNode(i,n,e);else if(this.options.oneListGroup){let t=this.options.tagValueProcessor(n,i);t=this.replaceEntitiesValue(t),r+=t}else r+=this.buildTextValNode(i,n,"",e)}this.options.oneListGroup&&(r=this.buildObjectNode(r,n,o,e)),s+=r}else if(this.options.attributesGroupName&&n===this.options.attributesGroupName){const e=Object.keys(t[n]),s=e.length;for(let r=0;r<s;r++)i+=this.buildAttrPairStr(e[r],""+t[n][e[r]])}else s+=this.processTextOrObjNode(t[n],n,e);return{attrStr:i,val:s}},ue.prototype.buildAttrPairStr=function(t,e){return e=this.options.attributeValueProcessor(t,""+e),e=this.replaceEntitiesValue(e),this.options.suppressBooleanAttributes&&"true"===e?" "+t:" "+t+'="'+e+'"'},ue.prototype.buildObjectNode=function(t,e,i,s){if(""===t)return"?"===e[0]?this.indentate(s)+"<"+e+i+"?"+this.tagEndChar:this.indentate(s)+"<"+e+i+this.closeTag(e)+this.tagEndChar;{let n="</"+e+this.tagEndChar,r="";return"?"===e[0]&&(r="?",n=""),!i&&""!==i||-1!==t.indexOf("<")?!1!==this.options.commentPropName&&e===this.options.commentPropName&&0===r.length?this.indentate(s)+`\x3c!--${t}--\x3e`+this.newLine:this.indentate(s)+"<"+e+i+r+this.tagEndChar+t+this.indentate(s)+n:this.indentate(s)+"<"+e+i+r+">"+t+n}},ue.prototype.closeTag=function(t){let e="";return-1!==this.options.unpairedTags.indexOf(t)?this.options.suppressUnpairedNode||(e="/"):e=this.options.suppressEmptyNode?"/":`></${t}`,e},ue.prototype.buildTextValNode=function(t,e,i,s){if(!1!==this.options.cdataPropName&&e===this.options.cdataPropName)return this.indentate(s)+`<![CDATA[${t}]]>`+this.newLine;if(!1!==this.options.commentPropName&&e===this.options.commentPropName)return this.indentate(s)+`\x3c!--${t}--\x3e`+this.newLine;if("?"===e[0])return this.indentate(s)+"<"+e+i+"?"+this.tagEndChar;{let n=this.options.tagValueProcessor(e,t);return n=this.replaceEntitiesValue(n),""===n?this.indentate(s)+"<"+e+i+this.closeTag(e)+this.tagEndChar:this.indentate(s)+"<"+e+i+">"+n+"</"+e+this.tagEndChar}},ue.prototype.replaceEntitiesValue=function(t){if(t&&t.length>0&&this.options.processEntities)for(let e=0;e<this.options.entities.length;e++){const i=this.options.entities[e];t=t.replace(i.regex,i.val)}return t};var ge={XMLParser:ne,XMLValidator:J,XMLBuilder:ue};class _e{}e(_e,"parser",new ge.XMLParser({allowBooleanAttributes:!0,attributeNamePrefix:"",ignoreAttributes:!1,ignoreDeclaration:!0,ignorePiTags:!0,numberParseOptions:{leadingZeros:!0,hex:!0},parseAttributeValue:!0,preserveOrder:!1,processEntities:!1,removeNSPrefix:!0,trimValues:!0})),e(_e,"builder",new ge.XMLBuilder({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1}));class ye extends V{constructor(t,i){super(t),e(this,"onDisposed",new L),e(this,"onVertexFound",new L),e(this,"onVertexLost",new L),e(this,"onEnabled",new L),e(this,"components"),e(this,"workingPlane",null),e(this,"_pickedPoint",null),e(this,"_config"),e(this,"_enabled",!1),this.components=t,this.config={snapDistance:.25,showOnlyVertex:!1,...i},this.enabled=!1}set enabled(t){this._enabled=t,t||(this._pickedPoint=null),this.onEnabled.trigger(t)}get enabled(){return this._enabled}set config(t){this._config={...this._config,...t}}get config(){return this._config}dispose(){this.onVertexFound.reset(),this.onVertexLost.reset(),this.components=null,this.onDisposed.trigger(),this.onDisposed.reset()}async get(t){if(!this.enabled)return this._pickedPoint;const e=this.components.get(Ye).get(t),i=await e.castRay();if(!i)return null!==this._pickedPoint&&(this.onVertexLost.trigger(),this._pickedPoint=null),this._pickedPoint;const s=i.point;return null!==this._pickedPoint&&this._pickedPoint.equals(s)||(this._pickedPoint=s.clone(),this.onVertexFound.trigger(this._pickedPoint)),this._pickedPoint}}class we{static join(t){const e={};for(const i of t)for(const t in i)if(e[t])for(const s of i[t])e[t].add(s);else e[t]=new Set(i[t]);return e}static intersect(t){if(0===t.length)return{};let e=we.clone(t[0]);for(let i=1;i<t.length;i++){const s=t[i],n={};for(const t in e)if(s[t]){const i=new Set;for(const n of e[t])s[t].has(n)&&i.add(n);i.size>0&&(n[t]=i)}e=n}return e}static clone(t){const e={};for(const i in t)e[i]=new Set(t[i]);return e}static remove(t,e,i=!1){i&&(t=we.clone(t));for(const i in e)if(t[i]){for(const s of e[i])t[i].delete(s);0===t[i].size&&delete t[i]}}static add(t,e,i=!1){i&&(t=we.clone(t));for(const i in e)if(t[i])for(const s of e[i])t[i].add(s);else t[i]=new Set(e[i])}static append(t,e,...i){let s=t[e];s||(s=new Set,t[e]=s);for(const t of i)s.add(t)}static isEqual(t,e){const i=Object.keys(t),s=Object.keys(e);if(i.length!==s.length)return!1;for(const s of i){if(!e[s])return!1;if(t[s].size!==e[s].size)return!1;for(const i of t[s])if(!e[s].has(i))return!1}return!0}static isEmpty(t){return 0===Object.values(t).reduce((t,e)=>t+e.size,0)}static toRaw(t){const e={};for(const i in t)e[i]=Array.from(t[i]);return e}static fromRaw(t){const e={};for(const i in t)e[i]=new Set(t[i]);return e}}class ve extends Map{constructor(t){super(t),e(this,"onItemSet",new L),e(this,"onItemUpdated",new L),e(this,"onItemDeleted",new L),e(this,"onCleared",new L),e(this,"guard",()=>!0)}clear(){super.clear(),this.onCleared.trigger()}set(t,e){const i=this.has(t);if(!(this.guard??(()=>!0))(t,e))return this;const s=super.set(t,e);return i?(this.onItemUpdated||(this.onItemUpdated=new L),this.onItemUpdated.trigger({key:t,value:e})):(this.onItemSet||(this.onItemSet=new L),this.onItemSet.trigger({key:t,value:e})),s}add(t){const e=G.create();return this.set(e,t),e}delete(t){const e=super.delete(t);return e&&this.onItemDeleted.trigger(t),e}dispose(){this.clear(),this.onItemSet.reset(),this.onItemDeleted.reset(),this.onCleared.reset()}}class be{static isEntry(t){return new Set(["Boolean","Color","Text","Number","Select","Vector3","TextSet","None"]).has(t.type)}static copySchema(t,e={}){for(const i in t){const s=t[i];this.isEntry(s)?e[i]=this.copyEntry(s):(e[i]={},this.copySchema(s,e[i]))}return e}static copyEntry(t){if("Boolean"===t.type){const e=t;return{type:e.type,value:e.value}}if("Color"===t.type){const e=t;return{type:e.type,value:e.value.clone()}}if("Text"===t.type){const e=t;return{type:e.type,value:e.value}}if("Number"===t.type){const e=t;return{type:e.type,value:e.value,min:e.min,max:e.max,interpolable:e.interpolable}}if("Select"===t.type){const e=t;return{type:e.type,value:e.value,multiple:e.multiple,options:new Set(e.options)}}if("Vector3"===t.type){const e=t;return{type:e.type,value:e.value.clone()}}if("TextSet"===t.type){const e=t;return{type:e.type,value:new Set(e.value)}}if("None"===t.type){const e=t;return{type:e.type,value:e.value}}throw new Error("Invalid entry!")}}class xe{constructor(){e(this,"list",new Set)}add(t){for(const e of t)this.list.add(e)}remove(t){for(const e of t)this.list.delete(e)}set(t){for(const e of this.list)e.enabled=t}reset(){for(const t of this.list)t.reset()}}class Te{constructor(t,i,s,n){e(this,"_component"),e(this,"name"),e(this,"uuid"),this._component=t,this.name=s,this.uuid=n??G.create();i.get(Ce).list.set(this.uuid,this)}get controls(){return be.copySchema(this._config)}set(t){for(const e in t)if(e in this){this[e]=t[e].value}}export(t=this._config,e={}){for(const i in t){const s=t[i];if(be.isEntry(s))if("Color"===s.type){const{r:t,g:n,b:r}=s.value;e[i]={...s,value:{r:t,g:n,b:r}}}else if("Vector3"===s.type){const{x:t,y:n,z:r}=s.value;e[i]={...s,value:{x:t,y:n,z:r}}}else if("TextSet"===s.type){const t=Array.from(s.value);e[i]={...s,value:t}}else if("Select"===s.type){const t=Array.from(s.options);e[i]={...s,options:t}}else e[i]={...s};else e[i]={},this.export(s,e[i])}return e}import(t,e={},i=!0){for(const i in t){const s=t[i];if(be.isEntry(s))if("Color"===s.type){const{r:t,g:n,b:r}=s.value;e[i]={...s,value:new o.Color(t,n,r)}}else if("Vector3"===s.type){const{x:t,y:n,z:r}=s.value;e[i]={...s,value:new o.Vector3(t,n,r)}}else"TextSet"===s.type?e[i]={...s,value:new Set(s.value)}:"Select"===s.type?e[i]={...s,options:new Set(s.options)}:e[i]={...s};else e[i]={},this.import(s,e[i],!1)}i&&this.set(e)}}const Ee=class t extends V{constructor(i){super(i),e(this,"list",new s),e(this,"enabled",!0),i.add(t.uuid,this)}};e(Ee,"uuid","b8c764e0-6b24-4e77-9a32-35fa728ee5b4");let Ce=Ee;class Se{constructor(t){e(this,"_event"),e(this,"_position",new o.Vector2),e(this,"onDisposed",new L),e(this,"updateMouseInfo",t=>{this._event=t}),this.dom=t,this.setupEvents(!0)}get position(){return this.updatePosition(!1),this._position.clone()}get rawPosition(){return this.updatePosition(!0),this._position.clone()}dispose(){this.setupEvents(!1),this.onDisposed.trigger(),this.onDisposed.reset()}updatePosition(t){if(this._event){const e=this.dom.getBoundingClientRect();this._position.x=this.getPositionX(e,this._event,t),this._position.y=this.getPositionY(e,this._event,t)}}getPositionY(t,e,i){const s=this.getDataObject(e);return i?s.clientY:-(s.clientY-t.top)/(t.bottom-t.top)*2+1}getPositionX(t,e,i){const s=this.getDataObject(e);return i?s.clientX:(s.clientX-t.left)/(t.right-t.left)*2-1}getDataObject(t){return t instanceof MouseEvent?t:t.touches[0]}setupEvents(t){t?(this.dom.addEventListener("pointermove",this.updateMouseInfo),this.dom.addEventListener("touchstart",this.updateMouseInfo)):(this.dom.removeEventListener("pointermove",this.updateMouseInfo),this.dom.removeEventListener("touchstart",this.updateMouseInfo))}}const Ae=class t extends V{constructor(i){super(i),e(this,"onDisposed",new L),e(this,"onBeforeDispose",new L),e(this,"onFragmentsLoaded",new L),e(this,"baseCoordinationModel",""),e(this,"baseCoordinationMatrix",new o.Matrix4),e(this,"enabled",!0),e(this,"_core"),this.components.add(t.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(t,e){this._core=new n(t,e),this.core.onModelLoaded.add(async()=>{if(this._hasCoordinationModel)return;const t=[...this.list.values()][0];t&&(this.baseCoordinationModel=t.modelId,this.baseCoordinationMatrix=await t.getCoordinationMatrix())}),this.list.onItemDeleted.add(()=>{this.list.size>0||(this.baseCoordinationModel="",this.baseCoordinationMatrix=new o.Matrix4)})}async raycast(t){const e=[];for(const i of this.core.models.list.values())if(t.snappingClasses&&t.snappingClasses.length>0){const s=await i.raycastWithSnapping(t);if(s&&s.length>0)e.push(s[0]);else{const s=await i.raycast(t);s&&e.push(s)}}else{const s=await i.raycast(t);s&&e.push(s)}if(await Promise.all(e),0===e.length)return;let i=e[0],s=i.distance;for(let t=1;t<e.length;t++)e[t].distance<s&&(s=e[t].distance,i=e[t]);return i}async getPositions(t){const e=[],i=async(t,i)=>{const s=await t.getPositions(i);for(const t of s)e.push(t)},s=[];for(const e in t){const n=this.core.models.list.get(e);n&&s.push(i(n,Array.from(t[e])))}return await Promise.all(s),e}async getBBoxes(t){const e=[],i=async(t,i)=>{const s=await t.getBoxes(i);if(s)for(const t of s)e.push(t)},s=[];for(const e in t){const n=this.core.models.list.get(e);n&&s.push(i(n,Array.from(t[e])))}return await Promise.all(s),e}async highlight(t,e){await this.forEachModel(e,"highlight",t)}async getData(t,e){const i={};for(const[s,n]of Object.entries(t)){const t=this.list.get(s);if(!t)continue;if(0===n.size){i[s]=[];continue}const r=await t.getItemsData([...n],e);i[s]=r}return i}async resetHighlight(t){await this.forEachModel(t,"resetHighlight")}async forEachModel(t,e,...i){const s={};if(t)for(const e in t){const i=t[e];s[e]=Array.from(i)}else for(const t of this.core.models.list.keys())s[t]=void 0;const n=[];for(const t in s){const r=this.core.models.list.get(t);if(r){const o=s[t],a=r[e](o,...i);n.push(a)}}await Promise.all(n)}async guidsToModelIdMap(t){const e={};for(const[i,s]of this.list){const n=(await s.getLocalIdsByGuids([...t])).filter(t=>null!==t);e[i]=new Set(n)}return e}async modelIdMapToGuids(t){const e=[];for(const[i,s]of Object.entries(t)){const t=this.list.get(i);if(!t)continue;const n=(await t.getGuidsByLocalIds([...s])).filter(t=>null!==t);e.push(...n)}return e}applyBaseCoordinateSystem(t,e){const i=new o.Matrix4;return e&&i.copy(e.clone()).invert(),i.multiply(this.baseCoordinationMatrix),t.applyMatrix4(i),i}};e(Ae,"uuid","fef46874-46a3-461b-8c44-2922ab77c806");let Oe=Ae;class Pe{constructor(){e(this,"wasm",{path:"",absolute:!1,logLevel:U.LogLevel.LOG_LEVEL_OFF}),e(this,"webIfc",{COORDINATE_TO_ORIGIN:!0}),e(this,"autoSetWasm",!0),e(this,"customLocateFileHandler",null)}}const Ie=class t extends V{constructor(i){super(i),e(this,"onDisposed",new L),e(this,"onIfcStartedLoading",new L),e(this,"onIfcImporterInitialized",new L),e(this,"onSetup",new L),e(this,"settings",new Pe),e(this,"webIfc",new U.IfcAPI),e(this,"enabled",!0),this.components.add(t.uuid,this)}dispose(){this.webIfc=null,this.onDisposed.trigger(t.uuid),this.onDisposed.reset()}async setup(t){this.settings={...this.settings,...t},this.settings.autoSetWasm&&await this.autoSetWasm(),this.onSetup.trigger()}async load(t,e,s,n){const r=this.components.get(Oe);if(!r.initialized)throw new Error("You need to initialize fragments first.");this.settings.autoSetWasm&&await this.autoSetWasm(),r.core.settings.autoCoordinate=e;const o=new i.IfcImporter;o.wasm.path=this.settings.wasm.path,o.wasm.absolute=this.settings.wasm.absolute,o.webIfcSettings=this.settings.webIfc,this.onIfcImporterInitialized.trigger(o),(null==n?void 0:n.instanceCallback)&&n.instanceCallback(o);const a=await o.process({...null==n?void 0:n.processData,bytes:t});return await r.core.load(a,{modelId:s,userData:null==n?void 0:n.userData})}async readIfcFile(t){const{path:e,absolute:i,logLevel:s}=this.settings.wasm;return this.webIfc.SetWasmPath(e,i),await this.webIfc.Init(this.settings.customLocateFileHandler||void 0),s&&this.webIfc.SetLogLevel(s),this.webIfc.OpenModel(t,this.settings.webIfc)}cleanUp(){try{this.webIfc.Dispose()}catch(t){console.log("Web-ifc wasn't disposed.")}this.webIfc=null,this.webIfc=new U.IfcAPI}async autoSetWasm(){const t=await fetch(`https://unpkg.com/@thatopen/components@${kr.release}/package.json`);if(!t.ok)return void console.warn("Couldn't get openbim-components package.json. Set wasm settings manually.");const e=await t.json();if("web-ifc"in e.peerDependencies){const t=e.peerDependencies["web-ifc"];this.settings.wasm.path=`https://unpkg.com/web-ifc@${t}/`,this.settings.wasm.absolute=!0}else console.warn("Couldn't get web-ifc from peer dependencies in openbim-components. Set wasm settings manually.")}};e(Ie,"uuid","a659add7-1418-4771-a0d6-7d4d438e4624");let ke=Ie;const De=class t extends V{constructor(i){super(i),e(this,"enabled",!0),this.components.add(t.uuid,this)}async set(t,e){const i=this.components.get(Oe),s=[];if(e)for(const[n,r]of Object.entries(e)){const e=i.list.get(n);e&&s.push(e.setVisible([...r],t))}else for(const e of i.list.values())s.push(e.setVisible(void 0,t));await Promise.all(s),await i.core.update(!0)}async isolate(t){await Promise.all([this.set(!1),this.set(!0,t)])}async toggle(t){const e=[],i=this.components.get(Oe);for(const[s,n]of Object.entries(t)){const t=i.list.get(s);t&&e.push(t.toggleVisible([...n]))}await Promise.all(e),await i.core.update(!0)}async getVisibilityMap(t,e){const i=[],s=[],n=this.components.get(Oe);if(e)for(const r of e){const e=n.list.get(r);e&&(i.push(e.modelId),s.push(e.getItemsByVisibility(t)))}else for(const e of n.list.values())i.push(e.modelId),s.push(e.getItemsByVisibility(t));const r=await Promise.all(s),o={};for(const[t,e]of i.entries())o[e]=r[t];return o}};e(De,"uuid","dd9ccf2d-8a21-4821-b7f6-2949add16a29");let ze=De;const Me=class t extends V{constructor(s){super(s),e(this,"enabled",!0),e(this,"onDisposed",new L),e(this,"list",new i.DataSet),this.components.add(t.uuid,this)}dispose(e=!0){this.list.clear(),this.onDisposed.trigger(t.uuid),e&&(this.onDisposed.reset(),this.list.eventsEnabled=!1,this.list.dispose())}get(){const t=new o.Box3;for(const e of this.list)t.union(e);return t}async addFromModelIdMap(t){const e=this.components.get(Oe),i=new o.Box3;for(const[s,n]of Object.entries(t)){const t=e.list.get(s);if(!t)continue;const r=await t.getMergedBox([...n]);i.union(r)}this.list.add(i)}addFromModels(t){const e=this.components.get(Oe);for(const[i,s]of e.list)t&&!t.some(t=>t.test(i))||this.list.add(s.box)}async getCenter(t){this.list.clear(),await this.addFromModelIdMap(t);const e=this.get();this.list.clear();const i=new o.Vector3;return e.getCenter(i),i}async getCameraOrientation(t,e=1){const i=this.components.get(Oe);this.list.clear();for(const[t,e]of i.list)this.list.add(e.box);const s=this.get();this.list.clear();const n=new o.Vector3;s.getCenter(n);const r=new o.Vector3;s.getSize(r);const a=Math.max(r.x,r.y,r.z)*e,l=new o.Vector3;switch(t){case"front":default:l.set(n.x,n.y,n.z+a);break;case"back":l.set(n.x,n.y,n.z-a);break;case"left":l.set(n.x-a,n.y,n.z);break;case"right":l.set(n.x+a,n.y,n.z);break;case"top":l.set(n.x,n.y+a,n.z);break;case"bottom":l.set(n.x,n.y-a,n.z)}return{position:l,target:n}}};e(Me,"uuid","d1444724-dba6-4cdd-a0c7-68ee1450d166");let Be=Me;class Ne{constructor(t,i){e(this,"name","Query"),e(this,"customData",{}),e(this,"_components"),e(this,"_queries",[]),e(this,"_aggregation","exclusive"),e(this,"result",null),e(this,"cache",!0),e(this,"serializeQueryParameters",t=>{var e;return{categories:null==(e=t.categories)?void 0:e.map(t=>t.source),attributes:t.attributes?{aggregation:t.attributes.aggregation,queries:t.attributes.queries.map(this.serializeAttributeQuery)}:void 0,relation:t.relation?{name:t.relation.name,query:t.relation.query?this.serializeQueryParameters(t.relation.query):void 0}:void 0}}),e(this,"deserializeQueryParameters",t=>{var e;return{categories:null==(e=t.categories)?void 0:e.map(t=>new RegExp(t)),attributes:t.attributes?{aggregation:t.attributes.aggregation,queries:t.attributes.queries.map(this.deserializeAttributeQuery)}:void 0,relation:t.relation?{name:t.relation.name,query:t.relation.query?this.deserializeQueryParameters(t.relation.query):void 0}:void 0}}),this._components=t,this.queries=i}set queries(t){this._queries=t,this.clearCache()}get queries(){return this._queries}set aggregation(t){t!==this._aggregation&&this.clearCache(),this._aggregation=t}get aggregation(){return this._aggregation}async test(t){const{modelIds:e,force:i}={force:!1,...t};if(this.result&&!i)return this.result;const s=this._components.get(Le),n=await s.getItems(this.queries,{modelIds:e,aggregation:this.aggregation});return this.cache&&(this.result=n),n}clearCache(){this.result=null}serializeAttributeQuery(t){let e;e=Array.isArray(t.value)?t.value.map(t=>t.source):t.value instanceof RegExp?t.value.source:t.value;return{name:t.name.source,value:e,type:t.type instanceof RegExp?t.type.source:t.type,negate:t.negate,itemIds:t.itemIds}}toJSON(){return{guid:this._components.get(Le).list.getKey(this)??G.create(),name:this.name,customData:this.customData,queries:this.queries.map(this.serializeQueryParameters),aggregation:this.aggregation,cache:this.cache}}deserializeAttributeQuery(t){let e;e=Array.isArray(t.value)?t.value.map(t=>new RegExp(t)):"string"==typeof t.value?new RegExp(t.value):t.value;return{name:new RegExp(t.name),value:e,type:t.type?new RegExp(t.type):void 0,negate:t.negate,itemIds:t.itemIds}}fromJSON(t){return this.name=t.name,this.customData=t.customData,this.aggregation=t.aggregation,this.cache=t.cache,this.queries=t.queries.map(this.deserializeQueryParameters),this}}const Ue=class t extends V{constructor(s){super(s),e(this,"enabled",!0),e(this,"list",new i.DataMap),s.add(t.uuid,this)}async getItems(t,e){let i;if(e){const{modelIds:t,items:s}=e;if(s){const t=Object.keys(s);t.length>0&&(i=t.map(t=>new RegExp(`^${t}$`)))}else t&&(i=t)}const s=(null==e?void 0:e.aggregation)??"exclusive",n=this.components.get(Oe),r=await Promise.all(t.map(async t=>{const s={};return await Promise.all(Array.from(n.list).map(async([n,r])=>{var o;if(i&&!i.some(t=>t.test(n)))return;const a=null==(o=null==e?void 0:e.items)?void 0:o[n],l=await r.getItemsByQuery(t,{localIds:a?[...a]:void 0});s[n]=new Set(l)})),s}));return"inclusive"===s?we.join(r):we.intersect(r)}create(t,e){const i=new Ne(this.components,e);return this.list.set(t,i),i}async addFromCategories(t){const e=new Set,i=this.components.get(Oe);for(const[s,n]of i.list){if(t&&!t.some(t=>t.test(s)))continue;const i=(await n.getItemsWithGeometryCategories()).filter(t=>null!==t),r=new Set(i);for(const t of r)this.list.has(t)||(this.create(t,[{categories:[new RegExp(`^${t}$`)]}]),e.add(t))}return[...e]}import(t){const{data:e}=t,i=[];if(!e)return i;for(const t of e){const e=this.create(t.guid,[]);e.fromJSON(t),i.push(e)}return i}export(){const t=[];for(const[e,i]of this.list.entries()){const s={...i.toJSON(),name:e};t.push(s)}return{data:t}}};e(Ue,"uuid","0da7ad77-f734-42ca-942f-a074adfd1e3a");let Le=Ue;const Re=class t extends V{constructor(s){super(s),e(this,"enabled",!0),e(this,"onDisposed",new L),e(this,"list",new i.DataMap),e(this,"defaultSaveFunction",t=>"value"in t.Name?t.Name.value:null),e(this,"onBeforeFragmentsDispose",async t=>{const{key:e,value:i}=t,s=await i.getLocalIds(),n={[e]:new Set(s)};this.removeItems(n)}),s.add(t.uuid,this),this.setupEvents();s.get(Oe).list.onBeforeDelete.add(this.onBeforeFragmentsDispose)}setupEvents(){this.list.onBeforeDelete.add(({value:t})=>t.dispose())}getClassificationGroups(t){let e=this.list.get(t);return e||(e=new i.DataMap,this.list.set(t,e)),e}getModelItems(t,e,i){const{map:s}=this.getGroupData(t,e);let n=s[i];return n||(n=new Set,s[i]=n),n}getGroupData(t,e){const i=this.components.get(Le),s=this.getClassificationGroups(t);let n=s.get(e);return n||(n={map:{},get:()=>new Promise(t=>{if(n)if(n.query){const{name:e,config:s}=n.query,r=i.list.get(e);if(!r)throw new Error("Classifier: the query name associated with the group doesn't exist in the ItemsFinder component");r.test(s).then(e=>{if(!n)return void t({});const i=we.join([e,n.map]);t(i)})}else t(n.map);else t({})})},s.set(e,n)),n}async aggregateItems(t,e,i){const s=(null==i?void 0:i.data)??void 0,n=(null==i?void 0:i.aggregationCallback)??this.defaultSaveFunction,r=this.components.get(Oe),o=this.components.get(Le),a=await o.getItems([e],{modelIds:null==i?void 0:i.modelIds});for(const[e,i]of Object.entries(a)){const o=r.list.get(e);if(!o)continue;const a=(i,...s)=>{const n=this.getModelItems(t,i,e);for(const t of s)n.add(t)},l=await o.getItemsData([...i],s);for(const t of l)n(t,a)}}addGroupItems(t,e,i){const{map:s}=this.getGroupData(t,e);we.add(s,i)}setGroupQuery(t,e,i){this.getGroupData(t,e).query=i}async find(t){const e=[];for(const[i,s]of Object.entries(t)){const t=[],n=this.list.get(i);if(!n)continue;for(const e of s){const i=n.get(e);if(!i)continue;const s=await i.get();t.push(s)}const r=we.join(t);e.push(r)}return we.intersect(e)}async aggregateItemRelations(t,e,i,s){const n=(null==s?void 0:s.attribute)??"Name",r={relations:{[i]:{attributes:!0,relations:!1}}};await this.aggregateItems(t,e,{modelIds:null==s?void 0:s.modelIds,data:r,aggregationCallback:(t,e)=>{if(!(null==t?void 0:t[n]))return;const s=t[n];if(!("value"in s))return;const r=t[i];if(Array.isArray(r))for(const t of r)"value"in t._localId&&e(s.value,t._localId.value)}})}async byIfcBuildingStorey(t){await this.aggregateItemRelations((null==t?void 0:t.classificationName)??"Storeys",{categories:[/BUILDINGSTOREY/]},"ContainsElements",{modelIds:null==t?void 0:t.modelIds})}async byCategory(t){const e=this.components.get(Le),i=await e.addFromCategories(null==t?void 0:t.modelIds);for(const e of i)this.setGroupQuery((null==t?void 0:t.classificationName)??"Categories",e,{name:e})}dispose(){this.list.clear();this.components.get(Oe).list.onBeforeDelete.remove(this.onBeforeFragmentsDispose),this.onDisposed.trigger()}removeItems(t,e){if(e&&e.classificationName){const i=this.list.get(e.classificationName);if(!i)return;if(e.groupName){if(!i.get(e.groupName))return}for(const[,e]of i)we.remove(e.map,t);return}for(const[,e]of this.list.entries())for(const[,i]of e)we.remove(i.map,t)}async byModel(t){const e=this.components.get(Oe),i=(null==t?void 0:t.classificationName)??"Models";for(const[s,n]of e.list){if(t&&t.modelIds&&!t.modelIds.some(t=>t.test(s)))continue;const e=await n.getItemsIdsWithGeometry(),r={[s]:new Set(e)};this.getGroupData(i,s),this.addGroupItems(i,s,r)}}};e(Re,"uuid","e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7");let Fe=Re;class Ve{constructor(t,i){e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new L),e(this,"mouse"),e(this,"world"),e(this,"debugMode",!1),e(this,"colorToModelId",new Map),e(this,"modelIdToColor",new Map),e(this,"renderTarget"),e(this,"renderTargetSize",new o.Vector2),e(this,"debugCanvas"),e(this,"debugContainer"),e(this,"colorMaterials",new Map),e(this,"originalMaterials",new Map),e(this,"originalLodColors",new Map),e(this,"colorsNeedUpdate",!0);const s=i.renderer;if(!s)throw new Error("A renderer is needed for the FastModelPicker to work!");this.world=i,this.mouse=new Se(s.three.domElement),this.components=t,this.setupRenderTarget(),this.setupFragmentListeners()}setupFragmentListeners(){const t=this.components.get(Oe);t.list.onItemSet.add(()=>{this.colorsNeedUpdate=!0}),t.list.onItemDeleted.add(()=>{this.colorsNeedUpdate=!0})}setupRenderTarget(){const t=this.world.renderer.three.getSize(new o.Vector2);this.renderTargetSize.copy(t),this.renderTarget=new o.WebGLRenderTarget(t.x,t.y),this.renderTarget.texture.format=o.RGBAFormat,this.renderTarget.texture.type=o.UnsignedByteType,this.debugMode&&this.setupDebugCanvas(),this.world.renderer.onResize.add(t=>{this.renderTargetSize.copy(t),this.renderTarget.setSize(t.x,t.y),this.debugCanvas&&(this.debugCanvas.width=t.x,this.debugCanvas.height=t.y)})}setupDebugCanvas(){if(this.debugCanvas)return;const t=this.world.renderer.three.getSize(new o.Vector2);this.debugContainer=document.createElement("div"),this.debugContainer.style.position="fixed",this.debugContainer.style.top="10px",this.debugContainer.style.right="10px",this.debugContainer.style.width="300px",this.debugContainer.style.height="300px",this.debugContainer.style.border="2px solid #fff",this.debugContainer.style.backgroundColor="#000",this.debugContainer.style.zIndex="10000",this.debugContainer.style.pointerEvents="none",this.debugCanvas=document.createElement("canvas"),this.debugCanvas.width=t.x,this.debugCanvas.height=t.y,this.debugCanvas.style.width="100%",this.debugCanvas.style.height="100%",this.debugCanvas.style.imageRendering="pixelated",this.debugContainer.appendChild(this.debugCanvas),document.body.appendChild(this.debugContainer)}generateColorForModel(t){let e=0;for(let i=0;i<t.length;i++)e=(e<<5)-e+t.charCodeAt(i),e&=e;let i=Math.abs(e)%16777215;0===i&&(i=1);const s=i>>16&255||1,n=i>>8&255||1,r=255&i||1;return new o.Color(s/255,n/255,r/255)}colorToId(t){return Math.round(255*t.r)<<16|Math.round(255*t.g)<<8|Math.round(255*t.b)}assignColors(){const t=this.components.get(Oe);if(t.initialized){if(!this.colorsNeedUpdate){const e=new Set(t.list.keys()),i=new Set(this.modelIdToColor.keys());(e.size!==i.size||[...e].some(t=>!i.has(t)))&&(this.colorsNeedUpdate=!0)}if(this.colorsNeedUpdate){this.colorToModelId.clear(),this.modelIdToColor.clear();for(const t of this.colorMaterials.values())t.dispose();this.colorMaterials.clear();for(const[e]of t.list){const t=this.generateColorForModel(e),i=this.colorToId(t);this.colorToModelId.set(i,e),this.modelIdToColor.set(e,t);const s=new o.MeshBasicMaterial({color:t,depthTest:!0,depthWrite:!0});this.colorMaterials.set(e,s)}this.colorsNeedUpdate=!1}}}applyColorMaterials(){const t=this.components.get(Oe);if(t.initialized)for(const[e,i]of t.list){const t=this.colorMaterials.get(e);t&&i.object.traverse(e=>{if(e instanceof o.Mesh){if("isLODGeometry"in e.geometry){const i=e.material[0].uniforms.lodColor;return this.originalLodColors.has(i)||this.originalLodColors.set(i,i.value),void(i.value=t.color)}this.originalMaterials.has(e)||this.originalMaterials.set(e,e.material),e.material=t}})}}restoreOriginalMaterials(){for(const[t,e]of this.originalMaterials)t.material=e;for(const[t,e]of this.originalLodColors)t.value=e;this.originalMaterials.clear()}renderColorCoded(){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const t=this.world.renderer.three,e=this.world.scene.three,i=this.world.camera.three,s=t.getRenderTarget(),n=t.autoClear,r=new o.Color,a=t.getClearAlpha();t.getClearColor(r),this.applyColorMaterials(),t.setRenderTarget(this.renderTarget),t.autoClear=!0,t.setClearColor(0,1),t.clear(!0,!0,!1),t.render(e,i),t.setRenderTarget(s),t.autoClear=n,t.setClearColor(r,a),this.restoreOriginalMaterials(),this.debugMode&&this.debugCanvas&&this.updateDebugCanvas()}updateDebugCanvas(){if(!this.debugCanvas||!this.renderTarget||!this.world.renderer)return;const t=this.world.renderer.three,e=this.renderTargetSize,i=new Uint8Array(e.x*e.y*4);t.readRenderTargetPixels(this.renderTarget,0,0,e.x,e.y,i);const s=this.debugCanvas.getContext("2d");if(!s)return;const n=s.createImageData(e.x,e.y),r=4*e.x;for(let t=0;t<e.y;t++){const s=t*r,o=(e.y-1-t)*r;n.data.set(i.subarray(s,s+r),o)}s.putImageData(n,0,0)}async getModelAt(t){if(!this.renderTarget||!this.world.renderer)throw new Error("Render target not initialized!");const e=this.components.get(Oe);if(!e.initialized||0===e.list.size)return null;this.assignColors(),this.renderColorCoded();const i=t||this.mouse.position,s=this.renderTargetSize,n=Math.floor(.5*(i.x+1)*s.x),r=Math.floor(.5*(i.y+1)*(s.y-1)),o=Math.max(0,Math.min(s.x-1,n)),a=Math.max(0,Math.min(s.y-1,r)),l=this.world.renderer.three,h=new Uint8Array(4);l.readRenderTargetPixels(this.renderTarget,o,a,1,1,h);const c=h[0]<<16|h[1]<<8|h[2];return this.colorToModelId.get(c)||null}setDebugMode(t){this.debugMode=t,t?this.setupDebugCanvas():this.removeDebugCanvas()}removeDebugCanvas(){this.debugContainer&&(this.debugContainer.remove(),this.debugContainer=void 0,this.debugCanvas=void 0)}dispose(){this.mouse.dispose(),this.removeDebugCanvas();for(const t of this.colorMaterials.values())t.dispose();this.colorMaterials.clear(),this.renderTarget&&this.renderTarget.dispose(),this.colorToModelId.clear(),this.modelIdToColor.clear(),this.originalMaterials.clear(),this.originalLodColors.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}}const je=class t extends V{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new Map),e(this,"onDisposed",new L),i.add(t.uuid,this)}get(t){if(this.list.has(t.uuid))return this.list.get(t.uuid);const e=new Ve(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add(()=>{this.delete(t)}),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}};e(je,"uuid","4a82430c-7ff2-49ea-9401-60807502dad6");let Ze=je;class He{constructor(t,i){e(this,"enabled",!0),e(this,"components"),e(this,"onDisposed",new L),e(this,"mouse"),e(this,"three",new o.Raycaster),e(this,"world"),e(this,"useFastModelPicking",!1);const s=i.renderer;if(!s)throw new Error("A renderer is needed for the raycaster to work!");this.world=i,this.mouse=new Se(s.three.domElement),this.components=t}dispose(){this.mouse.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}castRayToObjects(t=Array.from(this.world.meshes),e=this.mouse.position){if(!this.world)throw new Error("A world is needed to cast rays!");const i=this.world.camera.three;return this.three.setFromCamera(e,i),this.intersect(t)}async castRay(t){const e=null==t?void 0:t.snappingClasses,i=(null==t?void 0:t.items)??Array.from(this.world.meshes),s=(null==t?void 0:t.position)??this.mouse.position;if(!this.world)throw new Error("A world is needed to cast rays!");const n=this.world.camera.three,r=this.components.get(Oe),o=this.world.renderer.three.domElement,a=this.mouse.rawPosition;let l=null;if(r.initialized){if(this.useFastModelPicking){const t=this.components.get(Ze).get(this.world),i=await t.getModelAt(s);if(i){const t=r.list.get(i);if(t)if(e&&e.length>0){const i=await t.raycastWithSnapping({camera:n,dom:o,mouse:a,snappingClasses:e});l=i&&i.length>0?i[0]:await t.raycast({camera:n,dom:o,mouse:a})}else l=await t.raycast({camera:n,dom:o,mouse:a})}}else l=await r.raycast({camera:n,dom:o,mouse:a,snappingClasses:e});if(0===i.length)return l}this.three.setFromCamera(s,n);const h=this.intersect(i);return l?h&&h.distance<l.distance?h:l:h}castRayFromVector(t,e,i=Array.from(this.world.meshes)){return this.three.set(t,e),this.intersect(i)}intersect(t=Array.from(this.world.meshes)){const e=this.three.intersectObjects(t),i=this.filterClippingPlanes(e);return i.length>0?i[0]:null}filterClippingPlanes(t){if(!this.world.renderer)throw new Error("Renderer not found!");const e=this.world.renderer.three;if(!e.clippingPlanes)return t;const i=e.clippingPlanes;return t.length<=0||!i||(null==i?void 0:i.length)<=0?t:t.filter(t=>i.every(e=>e.distanceToPoint(t.point)>0))}}const $e=class t extends V{constructor(i){super(i),e(this,"enabled",!0),e(this,"list",new Map),e(this,"onDisposed",new L),i.add(t.uuid,this)}get(t){if(this.list.has(t.uuid))return this.list.get(t.uuid);const e=new He(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add(()=>{this.delete(t)}),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}};e($e,"uuid","d5d8bdf0-db25-4952-b951-b643af207ace");let Ye=$e;class We extends F{constructor(){super(...arguments),e(this,"onCameraChanged",new L),e(this,"meshes",new Set),e(this,"onAfterUpdate",new L),e(this,"onBeforeUpdate",new L),e(this,"onDisposed",new L),e(this,"isDisposing",!1),e(this,"enabled",!0),e(this,"_dynamicAnchor",!1),e(this,"uuid",G.create()),e(this,"name"),e(this,"_scene"),e(this,"_camera"),e(this,"_renderer",null),e(this,"onPointerDown",async t=>{if(!this.camera.hasCameraControls())throw new Error("World: can't set dynamic anchor if the camera doesn't have controls.");const e=this.components.get(Ye).get(this),i=await e.castRay();i&&i.point&&0===t.button&&this.camera.controls.setOrbitPoint(i.point.x,i.point.y,i.point.z)}),e(this,"_defaultCamera")}set dynamicAnchor(t){var e;const i=null==(e=this.renderer)?void 0:e.three.domElement.parentElement;if(!i)throw new Error("World: the renderer must have a parentElement to set dynamic anchoring.");t?(this.camera.controls&&(this.camera.controls.minDistance=.01),i.addEventListener("pointerdown",this.onPointerDown)):i.removeEventListener("pointerdown",this.onPointerDown)}get dynamicAnchor(){return this._dynamicAnchor}get defaultCamera(){if(!this._defaultCamera)throw new Error("World: there is no default camera defined.");return this._defaultCamera}set defaultCamera(t){this._defaultCamera=t}get scene(){if(!this._scene)throw new Error("No scene initialized!");return this._scene}set scene(t){this._scene=t,t.worlds.set(this.uuid,this),t.currentWorld=this,t.onWorldChanged.trigger({world:this,action:"added"})}get camera(){if(!this._camera)throw new Error("No camera initialized!");return this._camera}set camera(t){this._camera||(this.defaultCamera=t),this._camera=t,t.currentWorld=this,this.onCameraChanged.trigger(t)}get renderer(){return this._renderer}set renderer(t){this._renderer=t,t&&(t.worlds.set(this.uuid,this),t.currentWorld=this,t.onWorldChanged.trigger({world:this,action:"added"}))}useDefaultCamera(){this.camera=this.defaultCamera}update(t){this.enabled&&this._scene&&this._camera&&(this.scene.currentWorld=this,this.camera.currentWorld=this,this.renderer&&(this.renderer.currentWorld=this),this.onBeforeUpdate.trigger(),this.scene.isUpdateable()&&this.scene.update(t),this.camera.isUpdateable()&&this.camera.update(t),this.renderer&&this.renderer.update(t),this.onAfterUpdate.trigger())}dispose(t=!0){if(this.enabled=!1,this.isDisposing=!0,this.scene.onWorldChanged.trigger({world:this,action:"removed"}),this.camera.onWorldChanged.trigger({world:this,action:"removed"}),this.renderer&&this.renderer.onWorldChanged.trigger({world:this,action:"removed"}),t){const t=this.components.get(Y);this.scene.dispose(),this.camera.isDisposeable()&&this.camera.dispose(),this.renderer&&this.renderer.dispose();for(const e of this.meshes)t.destroy(e);this.meshes.clear()}this._scene=null,this._camera=null,this._renderer=null;this.components.get(Ki).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class Xe{constructor(t,i){e(this,"_list"),e(this,"_scene"),this._list=t,this._scene=i}get color(){return this._list.directionalLight.color.value}set color(t){this._list.directionalLight.color.value=t;for(const[,e]of this._scene.directionalLights)e.color.copy(t)}get intensity(){return this._list.directionalLight.intensity.value}set intensity(t){this._list.directionalLight.intensity.value=t;for(const[,e]of this._scene.directionalLights)e.intensity=t}get position(){return this._list.directionalLight.position.value.clone()}set position(t){this._list.directionalLight.position.value=t;for(const[,e]of this._scene.directionalLights)e.position.copy(t)}}class qe{constructor(t,i){e(this,"_list"),e(this,"_scene"),this._list=t,this._scene=i}get color(){return this._list.ambientLight.color.value}set color(t){this._list.ambientLight.color.value=t;for(const[,e]of this._scene.ambientLights)e.color.copy(t)}get intensity(){return this._list.ambientLight.intensity.value}set intensity(t){this._list.ambientLight.intensity.value=t;for(const[,e]of this._scene.ambientLights)e.intensity=t}}class Ge extends Te{constructor(){super(...arguments),e(this,"_config",{backgroundColor:{value:new o.Color,type:"Color"},ambientLight:{color:{type:"Color",value:new o.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2}},directionalLight:{color:{type:"Color",value:new o.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2},position:{type:"Vector3",value:new o.Vector3}}}),e(this,"ambientLight",new qe(this._config,this._component)),e(this,"directionalLight",new Xe(this._config,this._component))}get backgroundColor(){return this._config.backgroundColor.value}set backgroundColor(t){this._config.backgroundColor.value=t,this._component.three.background=t}}class Qe extends W{constructor(t){super(t),e(this,"onSetup",new L),e(this,"isSetup",!1),e(this,"three"),e(this,"config",new Ge(this,this.components,"Scene")),e(this,"_defaultConfig",{backgroundColor:new o.Color(2107698),directionalLight:{color:new o.Color("white"),intensity:1.5,position:new o.Vector3(5,10,3)},ambientLight:{color:new o.Color("white"),intensity:1}}),this.three=new o.Scene,this.three.background=new o.Color(2107698)}setup(t){const e={...this._defaultConfig,...t};this.config.backgroundColor=e.backgroundColor;const i=e.ambientLight;this.config.ambientLight.color=i.color,this.config.ambientLight.intensity=i.intensity;const s=e.directionalLight;this.config.directionalLight.color=s.color,this.config.directionalLight.intensity=s.intensity,this.config.directionalLight.position=s.position,this.deleteAllLights();const{color:n,intensity:r}=this.config.directionalLight,a=new o.DirectionalLight(n,r);a.position.copy(s.position);const{color:l,intensity:h}=this.config.directionalLight,c=new o.AmbientLight(l,h);this.three.add(a,c),this.directionalLights.set(a.uuid,a),this.ambientLights.set(c.uuid,c),this.isSetup=!0,this.onSetup.trigger()}dispose(){super.dispose();this.components.get(Ce).list.delete(this.config.uuid)}}var Ke=(t=>(t[t.MANUAL=0]="MANUAL",t[t.AUTO=1]="AUTO",t))(Ke||{});class Je extends H{constructor(t,i,s){super(t),e(this,"enabled",!0),e(this,"container"),e(this,"three"),e(this,"mode",1),e(this,"needsUpdate",!1),e(this,"_canvas"),e(this,"_parameters"),e(this,"_resizeObserver",null),e(this,"onContainerUpdated",new L),e(this,"_resizing",!1),e(this,"resize",t=>{if(this._resizing)return;this._resizing=!0,this.onContainerUpdated.trigger();const e=t?t.x:this.container.clientWidth,i=t?t.y:this.container.clientHeight;this.three.setSize(e,i),this.onResize.trigger(new o.Vector2(e,i)),this._resizing=!1}),e(this,"resizeEvent",()=>{this.resize()}),e(this,"onContextLost",t=>{t.preventDefault(),this.enabled=!1}),e(this,"onContextBack",()=>{this.three.setRenderTarget(null),this.three.dispose(),this.three=new o.WebGLRenderer({canvas:this._canvas,antialias:!0,alpha:!0,...this._parameters}),this.enabled=!0}),this.container=i,this._parameters=s,this.three=new o.WebGLRenderer({antialias:!0,alpha:!0,...s}),this.three.setPixelRatio(Math.min(window.devicePixelRatio,2)),this.setupRenderer(),this.setupEvents(!0),this.resize(),this._canvas=this.three.domElement;const n=this.three.getContext(),{canvas:r}=n;r.addEventListener("webglcontextlost",this.onContextLost,!1),r.addEventListener("webglcontextrestored",this.onContextBack,!1)}update(){if(!this.enabled||!this.currentWorld)return;if(0===this.mode&&!this.needsUpdate)return;this.needsUpdate=!1,this.onBeforeUpdate.trigger(this);const t=this.currentWorld.scene.three,e=this.currentWorld.camera.three;this.three.render(t,e),this.onAfterUpdate.trigger(this)}dispose(){this.enabled=!1,this.setupEvents(!1),this.three.domElement.remove(),this.three.forceContextLoss(),this.three.dispose(),this.onResize.reset(),this.onAfterUpdate.reset(),this.onBeforeUpdate.reset(),this.onDisposed.trigger(),this.onDisposed.reset()}getSize(){return new o.Vector2(this.three.domElement.clientWidth,this.three.domElement.clientHeight)}setupEvents(t){const e=this.three.domElement.parentElement;if(!e)throw new Error("This renderer needs to have an HTML container!");this._resizeObserver&&(this._resizeObserver.disconnect(),this._resizeObserver=null),window.removeEventListener("resize",this.resizeEvent),t&&(this._resizeObserver=new ResizeObserver(this.resizeEvent),this._resizeObserver.observe(e),window.addEventListener("resize",this.resizeEvent))}setupRenderer(){this.three.localClippingEnabled=!0,this.container&&this.container.appendChild(this.three.domElement),this.onContainerUpdated.trigger()}}
2
- /*!
3
- * camera-controls
4
- * https://github.com/yomotsu/camera-controls
5
- * (c) 2017 @yomotsu
6
- * Released under the MIT License.
7
- */const ti=1,ei=2,ii=4,si=Object.freeze({NONE:0,ROTATE:1,TRUCK:2,SCREEN_PAN:4,OFFSET:8,DOLLY:16,ZOOM:32,TOUCH_ROTATE:64,TOUCH_TRUCK:128,TOUCH_SCREEN_PAN:256,TOUCH_OFFSET:512,TOUCH_DOLLY:1024,TOUCH_ZOOM:2048,TOUCH_DOLLY_TRUCK:4096,TOUCH_DOLLY_SCREEN_PAN:8192,TOUCH_DOLLY_OFFSET:16384,TOUCH_DOLLY_ROTATE:32768,TOUCH_ZOOM_TRUCK:65536,TOUCH_ZOOM_OFFSET:131072,TOUCH_ZOOM_SCREEN_PAN:262144,TOUCH_ZOOM_ROTATE:524288}),ni=0,ri=1,oi=-1;function ai(t){return t.isPerspectiveCamera}function li(t){return t.isOrthographicCamera}const hi=2*Math.PI,ci=Math.PI/2,di=Math.PI/180;function ui(t,e,i){return Math.max(e,Math.min(i,t))}function pi(t,e=1e-5){return Math.abs(t)<e}function fi(t,e,i=1e-5){return pi(t-e,i)}function mi(t,e){return Math.round(t/e)*e}function gi(t){return isFinite(t)?t:t<0?-Number.MAX_VALUE:Number.MAX_VALUE}function _i(t){return Math.abs(t)<Number.MAX_VALUE?t:t*(1/0)}function yi(t,e,i,s,n=1/0,r){const o=2/(s=Math.max(1e-4,s)),a=o*r,l=1/(1+a+.48*a*a+.235*a*a*a);let h=t-e;const c=e,d=n*s;h=ui(h,-d,d),e=t-h;const u=(i.value+o*h)*r;i.value=(i.value-o*u)*l;let p=e+(h+u)*l;return c-t>0==p>c&&(p=c,i.value=(p-c)/r),p}function wi(t,e,i,s,n=1/0,r,o){const a=2/(s=Math.max(1e-4,s)),l=a*r,h=1/(1+l+.48*l*l+.235*l*l*l);let c=e.x,d=e.y,u=e.z,p=t.x-c,f=t.y-d,m=t.z-u;const g=c,_=d,y=u,w=n*s,v=p*p+f*f+m*m;if(v>w*w){const t=Math.sqrt(v);p=p/t*w,f=f/t*w,m=m/t*w}c=t.x-p,d=t.y-f,u=t.z-m;const b=(i.x+a*p)*r,x=(i.y+a*f)*r,T=(i.z+a*m)*r;i.x=(i.x-a*b)*h,i.y=(i.y-a*x)*h,i.z=(i.z-a*T)*h,o.x=c+(p+b)*h,o.y=d+(f+x)*h,o.z=u+(m+T)*h;const E=g-t.x,C=_-t.y,S=y-t.z;return E*(o.x-g)+C*(o.y-_)+S*(o.z-y)>0&&(o.x=g,o.y=_,o.z=y,i.x=(o.x-g)/r,i.y=(o.y-_)/r,i.z=(o.z-y)/r),o}function vi(t,e){e.set(0,0),t.forEach(t=>{e.x+=t.clientX,e.y+=t.clientY}),e.x/=t.length,e.y/=t.length}function bi(t,e){return!!li(t)&&(console.warn(`${e} is not supported in OrthographicCamera`),!0)}class xi{constructor(){this._listeners={}}addEventListener(t,e){const i=this._listeners;void 0===i[t]&&(i[t]=[]),-1===i[t].indexOf(e)&&i[t].push(e)}hasEventListener(t,e){const i=this._listeners;return void 0!==i[t]&&-1!==i[t].indexOf(e)}removeEventListener(t,e){const i=this._listeners[t];if(void 0!==i){const t=i.indexOf(e);-1!==t&&i.splice(t,1)}}removeAllEventListeners(t){t?Array.isArray(this._listeners[t])&&(this._listeners[t].length=0):this._listeners={}}dispatchEvent(t){const e=this._listeners[t.type];if(void 0!==e){t.target=this;const i=e.slice(0);for(let e=0,s=i.length;e<s;e++)i[e].call(this,t)}}}var Ti;const Ei=1/8,Ci=/Mac/.test(null===(Ti=null===globalThis||void 0===globalThis?void 0:globalThis.navigator)||void 0===Ti?void 0:Ti.platform);let Si,Ai,Oi,Pi,Ii,ki,Di,zi,Mi,Bi,Ni,Ui,Li,Ri,Fi,Vi,ji,Zi,Hi,$i,Yi,Wi,Xi;class qi extends xi{static install(t){Si=t.THREE,Ai=Object.freeze(new Si.Vector3(0,0,0)),Oi=Object.freeze(new Si.Vector3(0,1,0)),Pi=Object.freeze(new Si.Vector3(0,0,1)),Ii=new Si.Vector2,ki=new Si.Vector3,Di=new Si.Vector3,zi=new Si.Vector3,Mi=new Si.Vector3,Bi=new Si.Vector3,Ni=new Si.Vector3,Ui=new Si.Vector3,Li=new Si.Vector3,Ri=new Si.Vector3,Fi=new Si.Spherical,Vi=new Si.Spherical,ji=new Si.Box3,Zi=new Si.Box3,Hi=new Si.Sphere,$i=new Si.Quaternion,Yi=new Si.Quaternion,Wi=new Si.Matrix4,Xi=new Si.Raycaster}static get ACTION(){return si}set verticalDragToForward(t){console.warn("camera-controls: `verticalDragToForward` was removed. Use `mouseButtons.left = CameraControls.ACTION.SCREEN_PAN` instead.")}constructor(t,e){super(),this.minPolarAngle=0,this.maxPolarAngle=Math.PI,this.minAzimuthAngle=-1/0,this.maxAzimuthAngle=1/0,this.minDistance=Number.EPSILON,this.maxDistance=1/0,this.infinityDolly=!1,this.minZoom=.01,this.maxZoom=1/0,this.smoothTime=.25,this.draggingSmoothTime=.125,this.maxSpeed=1/0,this.azimuthRotateSpeed=1,this.polarRotateSpeed=1,this.dollySpeed=1,this.dollyDragInverted=!1,this.truckSpeed=2,this.dollyToCursor=!1,this.dragToOffset=!1,this.boundaryFriction=0,this.restThreshold=.01,this.colliderMeshes=[],this.cancel=()=>{},this._enabled=!0,this._state=si.NONE,this._viewport=null,this._changedDolly=0,this._changedZoom=0,this._hasRested=!0,this._boundaryEnclosesCamera=!1,this._needsUpdate=!0,this._updatedLastTime=!1,this._elementRect=new DOMRect,this._isDragging=!1,this._dragNeedsUpdate=!0,this._activePointers=[],this._lockedPointer=null,this._interactiveArea=new DOMRect(0,0,1,1),this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._isUserControllingOffset=!1,this._isUserControllingZoom=!1,this._lastDollyDirection=ni,this._thetaVelocity={value:0},this._phiVelocity={value:0},this._radiusVelocity={value:0},this._targetVelocity=new Si.Vector3,this._focalOffsetVelocity=new Si.Vector3,this._zoomVelocity={value:0},this._truckInternal=(t,e,i,s)=>{let n,r;if(ai(this._camera)){const i=ki.copy(this._camera.position).sub(this._target),s=this._camera.getEffectiveFOV()*di,o=i.length()*Math.tan(.5*s);n=this.truckSpeed*t*o/this._elementRect.height,r=this.truckSpeed*e*o/this._elementRect.height}else{if(!li(this._camera))return;{const i=this._camera;n=this.truckSpeed*t*(i.right-i.left)/i.zoom/this._elementRect.width,r=this.truckSpeed*e*(i.top-i.bottom)/i.zoom/this._elementRect.height}}s?(i?this.setFocalOffset(this._focalOffsetEnd.x+n,this._focalOffsetEnd.y,this._focalOffsetEnd.z,!0):this.truck(n,0,!0),this.forward(-r,!0)):i?this.setFocalOffset(this._focalOffsetEnd.x+n,this._focalOffsetEnd.y+r,this._focalOffsetEnd.z,!0):this.truck(n,r,!0)},this._rotateInternal=(t,e)=>{const i=hi*this.azimuthRotateSpeed*t/this._elementRect.height,s=hi*this.polarRotateSpeed*e/this._elementRect.height;this.rotate(i,s,!0)},this._dollyInternal=(t,e,i)=>{const s=Math.pow(.95,-t*this.dollySpeed),n=this._sphericalEnd.radius,r=this._sphericalEnd.radius*s,o=ui(r,this.minDistance,this.maxDistance),a=o-r;this.infinityDolly&&this.dollyToCursor?this._dollyToNoClamp(r,!0):this.infinityDolly&&!this.dollyToCursor?(this.dollyInFixed(a,!0),this._dollyToNoClamp(o,!0)):this._dollyToNoClamp(o,!0),this.dollyToCursor&&(this._changedDolly+=(this.infinityDolly?r:o)-n,this._dollyControlCoord.set(e,i)),this._lastDollyDirection=Math.sign(-t)},this._zoomInternal=(t,e,i)=>{const s=Math.pow(.95,t*this.dollySpeed),n=this._zoom,r=this._zoom*s;this.zoomTo(r,!0),this.dollyToCursor&&(this._changedZoom+=r-n,this._dollyControlCoord.set(e,i))},void 0===Si&&console.error("camera-controls: `THREE` is undefined. You must first run `CameraControls.install( { THREE: THREE } )`. Check the docs for further information."),this._camera=t,this._yAxisUpSpace=(new Si.Quaternion).setFromUnitVectors(this._camera.up,Oi),this._yAxisUpSpaceInverse=this._yAxisUpSpace.clone().invert(),this._state=si.NONE,this._target=new Si.Vector3,this._targetEnd=this._target.clone(),this._focalOffset=new Si.Vector3,this._focalOffsetEnd=this._focalOffset.clone(),this._spherical=(new Si.Spherical).setFromVector3(ki.copy(this._camera.position).applyQuaternion(this._yAxisUpSpace)),this._sphericalEnd=this._spherical.clone(),this._lastDistance=this._spherical.radius,this._zoom=this._camera.zoom,this._zoomEnd=this._zoom,this._lastZoom=this._zoom,this._nearPlaneCorners=[new Si.Vector3,new Si.Vector3,new Si.Vector3,new Si.Vector3],this._updateNearPlaneCorners(),this._boundary=new Si.Box3(new Si.Vector3(-1/0,-1/0,-1/0),new Si.Vector3(1/0,1/0,1/0)),this._cameraUp0=this._camera.up.clone(),this._target0=this._target.clone(),this._position0=this._camera.position.clone(),this._zoom0=this._zoom,this._focalOffset0=this._focalOffset.clone(),this._dollyControlCoord=new Si.Vector2,this.mouseButtons={left:si.ROTATE,middle:si.DOLLY,right:si.TRUCK,wheel:ai(this._camera)?si.DOLLY:li(this._camera)?si.ZOOM:si.NONE},this.touches={one:si.TOUCH_ROTATE,two:ai(this._camera)?si.TOUCH_DOLLY_TRUCK:li(this._camera)?si.TOUCH_ZOOM_TRUCK:si.NONE,three:si.TOUCH_TRUCK};const i=new Si.Vector2,s=new Si.Vector2,n=new Si.Vector2,r=t=>{if(!this._enabled||!this._domElement)return;if(0!==this._interactiveArea.left||0!==this._interactiveArea.top||1!==this._interactiveArea.width||1!==this._interactiveArea.height){const e=this._domElement.getBoundingClientRect(),i=t.clientX/e.width,s=t.clientY/e.height;if(i<this._interactiveArea.left||i>this._interactiveArea.right||s<this._interactiveArea.top||s>this._interactiveArea.bottom)return}const e="mouse"!==t.pointerType?null:(t.buttons&ti)===ti?ti:(t.buttons&ii)===ii?ii:(t.buttons&ei)===ei?ei:null;if(null!==e){const t=this._findPointerByMouseButton(e);t&&this._disposePointer(t)}if((t.buttons&ti)===ti&&this._lockedPointer)return;const i={pointerId:t.pointerId,clientX:t.clientX,clientY:t.clientY,deltaX:0,deltaY:0,mouseButton:e};this._activePointers.push(i),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",a),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",a),this._isDragging=!0,d(t)},o=t=>{t.cancelable&&t.preventDefault();const e=t.pointerId,i=this._lockedPointer||this._findPointerById(e);if(i){if(i.clientX=t.clientX,i.clientY=t.clientY,i.deltaX=t.movementX,i.deltaY=t.movementY,this._state=0,"touch"===t.pointerType)switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three}else(!this._isDragging&&this._lockedPointer||this._isDragging&&(t.buttons&ti)===ti)&&(this._state=this._state|this.mouseButtons.left),this._isDragging&&(t.buttons&ii)===ii&&(this._state=this._state|this.mouseButtons.middle),this._isDragging&&(t.buttons&ei)===ei&&(this._state=this._state|this.mouseButtons.right);u()}},a=t=>{const e=this._findPointerById(t.pointerId);if(!e||e!==this._lockedPointer){if(e&&this._disposePointer(e),"touch"===t.pointerType)switch(this._activePointers.length){case 0:this._state=si.NONE;break;case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three}else this._state=si.NONE;p()}};let l=-1;const h=t=>{if(!this._domElement)return;if(!this._enabled||this.mouseButtons.wheel===si.NONE)return;if(0!==this._interactiveArea.left||0!==this._interactiveArea.top||1!==this._interactiveArea.width||1!==this._interactiveArea.height){const e=this._domElement.getBoundingClientRect(),i=t.clientX/e.width,s=t.clientY/e.height;if(i<this._interactiveArea.left||i>this._interactiveArea.right||s<this._interactiveArea.top||s>this._interactiveArea.bottom)return}if(t.preventDefault(),this.dollyToCursor||this.mouseButtons.wheel===si.ROTATE||this.mouseButtons.wheel===si.TRUCK){const t=performance.now();l-t<1e3&&this._getClientRect(this._elementRect),l=t}const e=Ci?-1:-3,i=1===t.deltaMode||t.ctrlKey?t.deltaY/e:t.deltaY/(10*e),s=this.dollyToCursor?(t.clientX-this._elementRect.x)/this._elementRect.width*2-1:0,n=this.dollyToCursor?(t.clientY-this._elementRect.y)/this._elementRect.height*-2+1:0;switch(this.mouseButtons.wheel){case si.ROTATE:this._rotateInternal(t.deltaX,t.deltaY),this._isUserControllingRotate=!0;break;case si.TRUCK:this._truckInternal(t.deltaX,t.deltaY,!1,!1),this._isUserControllingTruck=!0;break;case si.SCREEN_PAN:this._truckInternal(t.deltaX,t.deltaY,!1,!0),this._isUserControllingTruck=!0;break;case si.OFFSET:this._truckInternal(t.deltaX,t.deltaY,!0,!1),this._isUserControllingOffset=!0;break;case si.DOLLY:this._dollyInternal(-i,s,n),this._isUserControllingDolly=!0;break;case si.ZOOM:this._zoomInternal(-i,s,n),this._isUserControllingZoom=!0}this.dispatchEvent({type:"control"})},c=t=>{if(this._domElement&&this._enabled){if(this.mouseButtons.right===qi.ACTION.NONE){const e=t instanceof PointerEvent?t.pointerId:0,i=this._findPointerById(e);return i&&this._disposePointer(i),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),void this._domElement.ownerDocument.removeEventListener("pointerup",a)}t.preventDefault()}},d=t=>{if(!this._enabled)return;vi(this._activePointers,Ii),this._getClientRect(this._elementRect),i.copy(Ii),s.copy(Ii);if(this._activePointers.length>=2){const t=Ii.x-this._activePointers[1].clientX,e=Ii.y-this._activePointers[1].clientY,i=Math.sqrt(t*t+e*e);n.set(0,i);const r=.5*(this._activePointers[0].clientX+this._activePointers[1].clientX),o=.5*(this._activePointers[0].clientY+this._activePointers[1].clientY);s.set(r,o)}if(this._state=0,t)if("pointerType"in t&&"touch"===t.pointerType)switch(this._activePointers.length){case 1:this._state=this.touches.one;break;case 2:this._state=this.touches.two;break;case 3:this._state=this.touches.three}else this._lockedPointer||(t.buttons&ti)!==ti||(this._state=this._state|this.mouseButtons.left),(t.buttons&ii)===ii&&(this._state=this._state|this.mouseButtons.middle),(t.buttons&ei)===ei&&(this._state=this._state|this.mouseButtons.right);else this._lockedPointer&&(this._state=this._state|this.mouseButtons.left);(this._state&si.ROTATE)!==si.ROTATE&&(this._state&si.TOUCH_ROTATE)!==si.TOUCH_ROTATE&&(this._state&si.TOUCH_DOLLY_ROTATE)!==si.TOUCH_DOLLY_ROTATE&&(this._state&si.TOUCH_ZOOM_ROTATE)!==si.TOUCH_ZOOM_ROTATE||(this._sphericalEnd.theta=this._spherical.theta,this._sphericalEnd.phi=this._spherical.phi,this._thetaVelocity.value=0,this._phiVelocity.value=0),(this._state&si.TRUCK)!==si.TRUCK&&(this._state&si.SCREEN_PAN)!==si.SCREEN_PAN&&(this._state&si.TOUCH_TRUCK)!==si.TOUCH_TRUCK&&(this._state&si.TOUCH_SCREEN_PAN)!==si.TOUCH_SCREEN_PAN&&(this._state&si.TOUCH_DOLLY_TRUCK)!==si.TOUCH_DOLLY_TRUCK&&(this._state&si.TOUCH_DOLLY_SCREEN_PAN)!==si.TOUCH_DOLLY_SCREEN_PAN&&(this._state&si.TOUCH_ZOOM_TRUCK)!==si.TOUCH_ZOOM_TRUCK&&(this._state&si.TOUCH_ZOOM_SCREEN_PAN)!==si.TOUCH_DOLLY_SCREEN_PAN||(this._targetEnd.copy(this._target),this._targetVelocity.set(0,0,0)),(this._state&si.DOLLY)!==si.DOLLY&&(this._state&si.TOUCH_DOLLY)!==si.TOUCH_DOLLY&&(this._state&si.TOUCH_DOLLY_TRUCK)!==si.TOUCH_DOLLY_TRUCK&&(this._state&si.TOUCH_DOLLY_SCREEN_PAN)!==si.TOUCH_DOLLY_SCREEN_PAN&&(this._state&si.TOUCH_DOLLY_OFFSET)!==si.TOUCH_DOLLY_OFFSET&&(this._state&si.TOUCH_DOLLY_ROTATE)!==si.TOUCH_DOLLY_ROTATE||(this._sphericalEnd.radius=this._spherical.radius,this._radiusVelocity.value=0),(this._state&si.ZOOM)!==si.ZOOM&&(this._state&si.TOUCH_ZOOM)!==si.TOUCH_ZOOM&&(this._state&si.TOUCH_ZOOM_TRUCK)!==si.TOUCH_ZOOM_TRUCK&&(this._state&si.TOUCH_ZOOM_SCREEN_PAN)!==si.TOUCH_ZOOM_SCREEN_PAN&&(this._state&si.TOUCH_ZOOM_OFFSET)!==si.TOUCH_ZOOM_OFFSET&&(this._state&si.TOUCH_ZOOM_ROTATE)!==si.TOUCH_ZOOM_ROTATE||(this._zoomEnd=this._zoom,this._zoomVelocity.value=0),(this._state&si.OFFSET)!==si.OFFSET&&(this._state&si.TOUCH_OFFSET)!==si.TOUCH_OFFSET&&(this._state&si.TOUCH_DOLLY_OFFSET)!==si.TOUCH_DOLLY_OFFSET&&(this._state&si.TOUCH_ZOOM_OFFSET)!==si.TOUCH_ZOOM_OFFSET||(this._focalOffsetEnd.copy(this._focalOffset),this._focalOffsetVelocity.set(0,0,0)),this.dispatchEvent({type:"controlstart"})},u=()=>{if(!this._enabled||!this._dragNeedsUpdate)return;this._dragNeedsUpdate=!1,vi(this._activePointers,Ii);const t=this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement?this._lockedPointer||this._activePointers[0]:null,e=t?-t.deltaX:s.x-Ii.x,r=t?-t.deltaY:s.y-Ii.y;if(s.copy(Ii),(this._state&si.ROTATE)!==si.ROTATE&&(this._state&si.TOUCH_ROTATE)!==si.TOUCH_ROTATE&&(this._state&si.TOUCH_DOLLY_ROTATE)!==si.TOUCH_DOLLY_ROTATE&&(this._state&si.TOUCH_ZOOM_ROTATE)!==si.TOUCH_ZOOM_ROTATE||(this._rotateInternal(e,r),this._isUserControllingRotate=!0),(this._state&si.DOLLY)===si.DOLLY||(this._state&si.ZOOM)===si.ZOOM){const t=this.dollyToCursor?(i.x-this._elementRect.x)/this._elementRect.width*2-1:0,e=this.dollyToCursor?(i.y-this._elementRect.y)/this._elementRect.height*-2+1:0,s=this.dollyDragInverted?-1:1;(this._state&si.DOLLY)===si.DOLLY?(this._dollyInternal(s*r*Ei,t,e),this._isUserControllingDolly=!0):(this._zoomInternal(s*r*Ei,t,e),this._isUserControllingZoom=!0)}if((this._state&si.TOUCH_DOLLY)===si.TOUCH_DOLLY||(this._state&si.TOUCH_ZOOM)===si.TOUCH_ZOOM||(this._state&si.TOUCH_DOLLY_TRUCK)===si.TOUCH_DOLLY_TRUCK||(this._state&si.TOUCH_ZOOM_TRUCK)===si.TOUCH_ZOOM_TRUCK||(this._state&si.TOUCH_DOLLY_SCREEN_PAN)===si.TOUCH_DOLLY_SCREEN_PAN||(this._state&si.TOUCH_ZOOM_SCREEN_PAN)===si.TOUCH_ZOOM_SCREEN_PAN||(this._state&si.TOUCH_DOLLY_OFFSET)===si.TOUCH_DOLLY_OFFSET||(this._state&si.TOUCH_ZOOM_OFFSET)===si.TOUCH_ZOOM_OFFSET||(this._state&si.TOUCH_DOLLY_ROTATE)===si.TOUCH_DOLLY_ROTATE||(this._state&si.TOUCH_ZOOM_ROTATE)===si.TOUCH_ZOOM_ROTATE){const t=Ii.x-this._activePointers[1].clientX,e=Ii.y-this._activePointers[1].clientY,i=Math.sqrt(t*t+e*e),r=n.y-i;n.set(0,i);const o=this.dollyToCursor?(s.x-this._elementRect.x)/this._elementRect.width*2-1:0,a=this.dollyToCursor?(s.y-this._elementRect.y)/this._elementRect.height*-2+1:0;(this._state&si.TOUCH_DOLLY)===si.TOUCH_DOLLY||(this._state&si.TOUCH_DOLLY_ROTATE)===si.TOUCH_DOLLY_ROTATE||(this._state&si.TOUCH_DOLLY_TRUCK)===si.TOUCH_DOLLY_TRUCK||(this._state&si.TOUCH_DOLLY_SCREEN_PAN)===si.TOUCH_DOLLY_SCREEN_PAN||(this._state&si.TOUCH_DOLLY_OFFSET)===si.TOUCH_DOLLY_OFFSET?(this._dollyInternal(r*Ei,o,a),this._isUserControllingDolly=!0):(this._zoomInternal(r*Ei,o,a),this._isUserControllingZoom=!0)}(this._state&si.TRUCK)!==si.TRUCK&&(this._state&si.TOUCH_TRUCK)!==si.TOUCH_TRUCK&&(this._state&si.TOUCH_DOLLY_TRUCK)!==si.TOUCH_DOLLY_TRUCK&&(this._state&si.TOUCH_ZOOM_TRUCK)!==si.TOUCH_ZOOM_TRUCK||(this._truckInternal(e,r,!1,!1),this._isUserControllingTruck=!0),(this._state&si.SCREEN_PAN)!==si.SCREEN_PAN&&(this._state&si.TOUCH_SCREEN_PAN)!==si.TOUCH_SCREEN_PAN&&(this._state&si.TOUCH_DOLLY_SCREEN_PAN)!==si.TOUCH_DOLLY_SCREEN_PAN&&(this._state&si.TOUCH_ZOOM_SCREEN_PAN)!==si.TOUCH_ZOOM_SCREEN_PAN||(this._truckInternal(e,r,!1,!0),this._isUserControllingTruck=!0),(this._state&si.OFFSET)!==si.OFFSET&&(this._state&si.TOUCH_OFFSET)!==si.TOUCH_OFFSET&&(this._state&si.TOUCH_DOLLY_OFFSET)!==si.TOUCH_DOLLY_OFFSET&&(this._state&si.TOUCH_ZOOM_OFFSET)!==si.TOUCH_ZOOM_OFFSET||(this._truckInternal(e,r,!0,!1),this._isUserControllingOffset=!0),this.dispatchEvent({type:"control"})},p=()=>{vi(this._activePointers,Ii),s.copy(Ii),this._dragNeedsUpdate=!1,(0===this._activePointers.length||1===this._activePointers.length&&this._activePointers[0]===this._lockedPointer)&&(this._isDragging=!1),0===this._activePointers.length&&this._domElement&&(this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",a),this.dispatchEvent({type:"controlend"}))};this.lockPointer=()=>{this._enabled&&this._domElement&&(this.cancel(),this._lockedPointer={pointerId:-1,clientX:0,clientY:0,deltaX:0,deltaY:0,mouseButton:null},this._activePointers.push(this._lockedPointer),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",a),this._domElement.requestPointerLock(),this._domElement.ownerDocument.addEventListener("pointerlockchange",f),this._domElement.ownerDocument.addEventListener("pointerlockerror",m),this._domElement.ownerDocument.addEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.addEventListener("pointerup",a),d())},this.unlockPointer=()=>{var t,e,i;null!==this._lockedPointer&&(this._disposePointer(this._lockedPointer),this._lockedPointer=null),null===(t=this._domElement)||void 0===t||t.ownerDocument.exitPointerLock(),null===(e=this._domElement)||void 0===e||e.ownerDocument.removeEventListener("pointerlockchange",f),null===(i=this._domElement)||void 0===i||i.ownerDocument.removeEventListener("pointerlockerror",m),this.cancel()};const f=()=>{this._domElement&&this._domElement.ownerDocument.pointerLockElement===this._domElement||this.unlockPointer()},m=()=>{this.unlockPointer()};this._addAllEventListeners=t=>{this._domElement=t,this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none",this._domElement.addEventListener("pointerdown",r),this._domElement.addEventListener("pointercancel",a),this._domElement.addEventListener("wheel",h,{passive:!1}),this._domElement.addEventListener("contextmenu",c)},this._removeAllEventListeners=()=>{this._domElement&&(this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect="",this._domElement.removeEventListener("pointerdown",r),this._domElement.removeEventListener("pointercancel",a),this._domElement.removeEventListener("wheel",h,{passive:!1}),this._domElement.removeEventListener("contextmenu",c),this._domElement.ownerDocument.removeEventListener("pointermove",o,{passive:!1}),this._domElement.ownerDocument.removeEventListener("pointerup",a),this._domElement.ownerDocument.removeEventListener("pointerlockchange",f),this._domElement.ownerDocument.removeEventListener("pointerlockerror",m))},this.cancel=()=>{this._state!==si.NONE&&(this._state=si.NONE,this._activePointers.length=0,p())},e&&this.connect(e),this.update(0)}get camera(){return this._camera}set camera(t){this._camera=t,this.updateCameraUp(),this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0}get enabled(){return this._enabled}set enabled(t){this._enabled=t,this._domElement&&(t?(this._domElement.style.touchAction="none",this._domElement.style.userSelect="none",this._domElement.style.webkitUserSelect="none"):(this.cancel(),this._domElement.style.touchAction="",this._domElement.style.userSelect="",this._domElement.style.webkitUserSelect=""))}get active(){return!this._hasRested}get currentAction(){return this._state}get distance(){return this._spherical.radius}set distance(t){this._spherical.radius===t&&this._sphericalEnd.radius===t||(this._spherical.radius=t,this._sphericalEnd.radius=t,this._needsUpdate=!0)}get azimuthAngle(){return this._spherical.theta}set azimuthAngle(t){this._spherical.theta===t&&this._sphericalEnd.theta===t||(this._spherical.theta=t,this._sphericalEnd.theta=t,this._needsUpdate=!0)}get polarAngle(){return this._spherical.phi}set polarAngle(t){this._spherical.phi===t&&this._sphericalEnd.phi===t||(this._spherical.phi=t,this._sphericalEnd.phi=t,this._needsUpdate=!0)}get boundaryEnclosesCamera(){return this._boundaryEnclosesCamera}set boundaryEnclosesCamera(t){this._boundaryEnclosesCamera=t,this._needsUpdate=!0}set interactiveArea(t){this._interactiveArea.width=ui(t.width,0,1),this._interactiveArea.height=ui(t.height,0,1),this._interactiveArea.x=ui(t.x,0,1-this._interactiveArea.width),this._interactiveArea.y=ui(t.y,0,1-this._interactiveArea.height)}addEventListener(t,e){super.addEventListener(t,e)}removeEventListener(t,e){super.removeEventListener(t,e)}rotate(t,e,i=!1){return this.rotateTo(this._sphericalEnd.theta+t,this._sphericalEnd.phi+e,i)}rotateAzimuthTo(t,e=!1){return this.rotateTo(t,this._sphericalEnd.phi,e)}rotatePolarTo(t,e=!1){return this.rotateTo(this._sphericalEnd.theta,t,e)}rotateTo(t,e,i=!1){this._isUserControllingRotate=!1;const s=ui(t,this.minAzimuthAngle,this.maxAzimuthAngle),n=ui(e,this.minPolarAngle,this.maxPolarAngle);this._sphericalEnd.theta=s,this._sphericalEnd.phi=n,this._sphericalEnd.makeSafe(),this._needsUpdate=!0,i||(this._spherical.theta=this._sphericalEnd.theta,this._spherical.phi=this._sphericalEnd.phi);const r=!i||fi(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&fi(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold);return this._createOnRestPromise(r)}dolly(t,e=!1){return this.dollyTo(this._sphericalEnd.radius-t,e)}dollyTo(t,e=!1){return this._isUserControllingDolly=!1,this._lastDollyDirection=ni,this._changedDolly=0,this._dollyToNoClamp(ui(t,this.minDistance,this.maxDistance),e)}_dollyToNoClamp(t,e=!1){const i=this._sphericalEnd.radius;if(this.colliderMeshes.length>=1){const e=this._collisionTest(),s=fi(e,this._spherical.radius);if(!(i>t)&&s)return Promise.resolve();this._sphericalEnd.radius=Math.min(t,e)}else this._sphericalEnd.radius=t;this._needsUpdate=!0,e||(this._spherical.radius=this._sphericalEnd.radius);const s=!e||fi(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(s)}dollyInFixed(t,e=!1){this._targetEnd.add(this._getCameraDirection(Mi).multiplyScalar(t)),e||this._target.copy(this._targetEnd);const i=!e||fi(this._target.x,this._targetEnd.x,this.restThreshold)&&fi(this._target.y,this._targetEnd.y,this.restThreshold)&&fi(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(i)}zoom(t,e=!1){return this.zoomTo(this._zoomEnd+t,e)}zoomTo(t,e=!1){this._isUserControllingZoom=!1,this._zoomEnd=ui(t,this.minZoom,this.maxZoom),this._needsUpdate=!0,e||(this._zoom=this._zoomEnd);const i=!e||fi(this._zoom,this._zoomEnd,this.restThreshold);return this._changedZoom=0,this._createOnRestPromise(i)}pan(t,e,i=!1){return console.warn("`pan` has been renamed to `truck`"),this.truck(t,e,i)}truck(t,e,i=!1){this._camera.updateMatrix(),Bi.setFromMatrixColumn(this._camera.matrix,0),Ni.setFromMatrixColumn(this._camera.matrix,1),Bi.multiplyScalar(t),Ni.multiplyScalar(-e);const s=ki.copy(Bi).add(Ni),n=Di.copy(this._targetEnd).add(s);return this.moveTo(n.x,n.y,n.z,i)}forward(t,e=!1){ki.setFromMatrixColumn(this._camera.matrix,0),ki.crossVectors(this._camera.up,ki),ki.multiplyScalar(t);const i=Di.copy(this._targetEnd).add(ki);return this.moveTo(i.x,i.y,i.z,e)}elevate(t,e=!1){return ki.copy(this._camera.up).multiplyScalar(t),this.moveTo(this._targetEnd.x+ki.x,this._targetEnd.y+ki.y,this._targetEnd.z+ki.z,e)}moveTo(t,e,i,s=!1){this._isUserControllingTruck=!1;const n=ki.set(t,e,i).sub(this._targetEnd);this._encloseToBoundary(this._targetEnd,n,this.boundaryFriction),this._needsUpdate=!0,s||this._target.copy(this._targetEnd);const r=!s||fi(this._target.x,this._targetEnd.x,this.restThreshold)&&fi(this._target.y,this._targetEnd.y,this.restThreshold)&&fi(this._target.z,this._targetEnd.z,this.restThreshold);return this._createOnRestPromise(r)}lookInDirectionOf(t,e,i,s=!1){const n=ki.set(t,e,i).sub(this._targetEnd).normalize().multiplyScalar(-this._sphericalEnd.radius).add(this._targetEnd);return this.setPosition(n.x,n.y,n.z,s)}fitToBox(t,e,{cover:i=!1,paddingLeft:s=0,paddingRight:n=0,paddingBottom:r=0,paddingTop:o=0}={}){const a=[],l=t.isBox3?ji.copy(t):ji.setFromObject(t);l.isEmpty()&&(console.warn("camera-controls: fitTo() cannot be used with an empty box. Aborting"),Promise.resolve());const h=mi(this._sphericalEnd.theta,ci),c=mi(this._sphericalEnd.phi,ci);a.push(this.rotateTo(h,c,e));const d=ki.setFromSpherical(this._sphericalEnd).normalize(),u=$i.setFromUnitVectors(d,Pi),p=fi(Math.abs(d.y),1);p&&u.multiply(Yi.setFromAxisAngle(Oi,h)),u.multiply(this._yAxisUpSpaceInverse);const f=Zi.makeEmpty();Di.copy(l.min).applyQuaternion(u),f.expandByPoint(Di),Di.copy(l.min).setX(l.max.x).applyQuaternion(u),f.expandByPoint(Di),Di.copy(l.min).setY(l.max.y).applyQuaternion(u),f.expandByPoint(Di),Di.copy(l.max).setZ(l.min.z).applyQuaternion(u),f.expandByPoint(Di),Di.copy(l.min).setZ(l.max.z).applyQuaternion(u),f.expandByPoint(Di),Di.copy(l.max).setY(l.min.y).applyQuaternion(u),f.expandByPoint(Di),Di.copy(l.max).setX(l.min.x).applyQuaternion(u),f.expandByPoint(Di),Di.copy(l.max).applyQuaternion(u),f.expandByPoint(Di),f.min.x-=s,f.min.y-=r,f.max.x+=n,f.max.y+=o,u.setFromUnitVectors(Pi,d),p&&u.premultiply(Yi.invert()),u.premultiply(this._yAxisUpSpace);const m=f.getSize(ki),g=f.getCenter(Di).applyQuaternion(u);if(ai(this._camera)){const t=this.getDistanceToFitBox(m.x,m.y,m.z,i);a.push(this.moveTo(g.x,g.y,g.z,e)),a.push(this.dollyTo(t,e)),a.push(this.setFocalOffset(0,0,0,e))}else if(li(this._camera)){const t=this._camera,s=t.right-t.left,n=t.top-t.bottom,r=i?Math.max(s/m.x,n/m.y):Math.min(s/m.x,n/m.y);a.push(this.moveTo(g.x,g.y,g.z,e)),a.push(this.zoomTo(r,e)),a.push(this.setFocalOffset(0,0,0,e))}return Promise.all(a)}fitToSphere(t,e){const i=[],s="isObject3D"in t?qi.createBoundingSphere(t,Hi):Hi.copy(t);if(i.push(this.moveTo(s.center.x,s.center.y,s.center.z,e)),ai(this._camera)){const t=this.getDistanceToFitSphere(s.radius);i.push(this.dollyTo(t,e))}else if(li(this._camera)){const t=this._camera.right-this._camera.left,n=this._camera.top-this._camera.bottom,r=2*s.radius,o=Math.min(t/r,n/r);i.push(this.zoomTo(o,e))}return i.push(this.setFocalOffset(0,0,0,e)),Promise.all(i)}setLookAt(t,e,i,s,n,r,o=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=ni,this._changedDolly=0;const a=Di.set(s,n,r),l=ki.set(t,e,i);this._targetEnd.copy(a),this._sphericalEnd.setFromVector3(l.sub(a).applyQuaternion(this._yAxisUpSpace)),this.normalizeRotations(),this._needsUpdate=!0,o||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const h=!o||fi(this._target.x,this._targetEnd.x,this.restThreshold)&&fi(this._target.y,this._targetEnd.y,this.restThreshold)&&fi(this._target.z,this._targetEnd.z,this.restThreshold)&&fi(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&fi(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&fi(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(h)}lerpLookAt(t,e,i,s,n,r,o,a,l,h,c,d,u,p=!1){this._isUserControllingRotate=!1,this._isUserControllingDolly=!1,this._isUserControllingTruck=!1,this._lastDollyDirection=ni,this._changedDolly=0;const f=ki.set(s,n,r),m=Di.set(t,e,i);Fi.setFromVector3(m.sub(f).applyQuaternion(this._yAxisUpSpace));const g=zi.set(h,c,d),_=Di.set(o,a,l);Vi.setFromVector3(_.sub(g).applyQuaternion(this._yAxisUpSpace)),this._targetEnd.copy(f.lerp(g,u));const y=Vi.theta-Fi.theta,w=Vi.phi-Fi.phi,v=Vi.radius-Fi.radius;this._sphericalEnd.set(Fi.radius+v*u,Fi.phi+w*u,Fi.theta+y*u),this.normalizeRotations(),this._needsUpdate=!0,p||(this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd));const b=!p||fi(this._target.x,this._targetEnd.x,this.restThreshold)&&fi(this._target.y,this._targetEnd.y,this.restThreshold)&&fi(this._target.z,this._targetEnd.z,this.restThreshold)&&fi(this._spherical.theta,this._sphericalEnd.theta,this.restThreshold)&&fi(this._spherical.phi,this._sphericalEnd.phi,this.restThreshold)&&fi(this._spherical.radius,this._sphericalEnd.radius,this.restThreshold);return this._createOnRestPromise(b)}setPosition(t,e,i,s=!1){return this.setLookAt(t,e,i,this._targetEnd.x,this._targetEnd.y,this._targetEnd.z,s)}setTarget(t,e,i,s=!1){const n=this.getPosition(ki),r=this.setLookAt(n.x,n.y,n.z,t,e,i,s);return this._sphericalEnd.phi=ui(this._sphericalEnd.phi,this.minPolarAngle,this.maxPolarAngle),r}setFocalOffset(t,e,i,s=!1){this._isUserControllingOffset=!1,this._focalOffsetEnd.set(t,e,i),this._needsUpdate=!0,s||this._focalOffset.copy(this._focalOffsetEnd);const n=!s||fi(this._focalOffset.x,this._focalOffsetEnd.x,this.restThreshold)&&fi(this._focalOffset.y,this._focalOffsetEnd.y,this.restThreshold)&&fi(this._focalOffset.z,this._focalOffsetEnd.z,this.restThreshold);return this._createOnRestPromise(n)}setOrbitPoint(t,e,i){this._camera.updateMatrixWorld(),Bi.setFromMatrixColumn(this._camera.matrixWorldInverse,0),Ni.setFromMatrixColumn(this._camera.matrixWorldInverse,1),Ui.setFromMatrixColumn(this._camera.matrixWorldInverse,2);const s=ki.set(t,e,i),n=s.distanceTo(this._camera.position),r=s.sub(this._camera.position);Bi.multiplyScalar(r.x),Ni.multiplyScalar(r.y),Ui.multiplyScalar(r.z),ki.copy(Bi).add(Ni).add(Ui),ki.z=ki.z+n,this.dollyTo(n,!1),this.setFocalOffset(-ki.x,ki.y,-ki.z,!1),this.moveTo(t,e,i,!1)}setBoundary(t){if(!t)return this._boundary.min.set(-1/0,-1/0,-1/0),this._boundary.max.set(1/0,1/0,1/0),void(this._needsUpdate=!0);this._boundary.copy(t),this._boundary.clampPoint(this._targetEnd,this._targetEnd),this._needsUpdate=!0}setViewport(t,e,i,s){null!==t?(this._viewport=this._viewport||new Si.Vector4,"number"==typeof t?this._viewport.set(t,e,i,s):this._viewport.copy(t)):this._viewport=null}getDistanceToFitBox(t,e,i,s=!1){if(bi(this._camera,"getDistanceToFitBox"))return this._spherical.radius;const n=t/e,r=this._camera.getEffectiveFOV()*di,o=this._camera.aspect;return.5*((s?n>o:n<o)?e:t/o)/Math.tan(.5*r)+.5*i}getDistanceToFitSphere(t){if(bi(this._camera,"getDistanceToFitSphere"))return this._spherical.radius;const e=this._camera.getEffectiveFOV()*di,i=2*Math.atan(Math.tan(.5*e)*this._camera.aspect),s=1<this._camera.aspect?e:i;return t/Math.sin(.5*s)}getTarget(t,e=!0){return(t&&t.isVector3?t:new Si.Vector3).copy(e?this._targetEnd:this._target)}getPosition(t,e=!0){return(t&&t.isVector3?t:new Si.Vector3).setFromSpherical(e?this._sphericalEnd:this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(e?this._targetEnd:this._target)}getSpherical(t,e=!0){return(t||new Si.Spherical).copy(e?this._sphericalEnd:this._spherical)}getFocalOffset(t,e=!0){return(t&&t.isVector3?t:new Si.Vector3).copy(e?this._focalOffsetEnd:this._focalOffset)}normalizeRotations(){this._sphericalEnd.theta=this._sphericalEnd.theta%hi,this._sphericalEnd.theta<0&&(this._sphericalEnd.theta+=hi),this._spherical.theta+=hi*Math.round((this._sphericalEnd.theta-this._spherical.theta)/hi)}stop(){this._focalOffset.copy(this._focalOffsetEnd),this._target.copy(this._targetEnd),this._spherical.copy(this._sphericalEnd),this._zoom=this._zoomEnd}reset(t=!1){if(!fi(this._camera.up.x,this._cameraUp0.x)||!fi(this._camera.up.y,this._cameraUp0.y)||!fi(this._camera.up.z,this._cameraUp0.z)){this._camera.up.copy(this._cameraUp0);const t=this.getPosition(ki);this.updateCameraUp(),this.setPosition(t.x,t.y,t.z)}const e=[this.setLookAt(this._position0.x,this._position0.y,this._position0.z,this._target0.x,this._target0.y,this._target0.z,t),this.setFocalOffset(this._focalOffset0.x,this._focalOffset0.y,this._focalOffset0.z,t),this.zoomTo(this._zoom0,t)];return Promise.all(e)}saveState(){this._cameraUp0.copy(this._camera.up),this.getTarget(this._target0),this.getPosition(this._position0),this._zoom0=this._zoom,this._focalOffset0.copy(this._focalOffset)}updateCameraUp(){this._yAxisUpSpace.setFromUnitVectors(this._camera.up,Oi),this._yAxisUpSpaceInverse.copy(this._yAxisUpSpace).invert()}applyCameraUp(){const t=ki.subVectors(this._target,this._camera.position).normalize(),e=Di.crossVectors(t,this._camera.up);this._camera.up.crossVectors(e,t).normalize(),this._camera.updateMatrixWorld();const i=this.getPosition(ki);this.updateCameraUp(),this.setPosition(i.x,i.y,i.z)}update(t){const e=this._sphericalEnd.theta-this._spherical.theta,i=this._sphericalEnd.phi-this._spherical.phi,s=this._sphericalEnd.radius-this._spherical.radius,n=Li.subVectors(this._targetEnd,this._target),r=Ri.subVectors(this._focalOffsetEnd,this._focalOffset),o=this._zoomEnd-this._zoom;if(pi(e))this._thetaVelocity.value=0,this._spherical.theta=this._sphericalEnd.theta;else{const e=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.theta=yi(this._spherical.theta,this._sphericalEnd.theta,this._thetaVelocity,e,1/0,t),this._needsUpdate=!0}if(pi(i))this._phiVelocity.value=0,this._spherical.phi=this._sphericalEnd.phi;else{const e=this._isUserControllingRotate?this.draggingSmoothTime:this.smoothTime;this._spherical.phi=yi(this._spherical.phi,this._sphericalEnd.phi,this._phiVelocity,e,1/0,t),this._needsUpdate=!0}if(pi(s))this._radiusVelocity.value=0,this._spherical.radius=this._sphericalEnd.radius;else{const e=this._isUserControllingDolly?this.draggingSmoothTime:this.smoothTime;this._spherical.radius=yi(this._spherical.radius,this._sphericalEnd.radius,this._radiusVelocity,e,this.maxSpeed,t),this._needsUpdate=!0}if(pi(n.x)&&pi(n.y)&&pi(n.z))this._targetVelocity.set(0,0,0),this._target.copy(this._targetEnd);else{const e=this._isUserControllingTruck?this.draggingSmoothTime:this.smoothTime;wi(this._target,this._targetEnd,this._targetVelocity,e,this.maxSpeed,t,this._target),this._needsUpdate=!0}if(pi(r.x)&&pi(r.y)&&pi(r.z))this._focalOffsetVelocity.set(0,0,0),this._focalOffset.copy(this._focalOffsetEnd);else{const e=this._isUserControllingOffset?this.draggingSmoothTime:this.smoothTime;wi(this._focalOffset,this._focalOffsetEnd,this._focalOffsetVelocity,e,this.maxSpeed,t,this._focalOffset),this._needsUpdate=!0}if(pi(o))this._zoomVelocity.value=0,this._zoom=this._zoomEnd;else{const e=this._isUserControllingZoom?this.draggingSmoothTime:this.smoothTime;this._zoom=yi(this._zoom,this._zoomEnd,this._zoomVelocity,e,1/0,t)}if(this.dollyToCursor)if(ai(this._camera)&&0!==this._changedDolly){const t=this._spherical.radius-this._lastDistance,e=this._camera,i=this._getCameraDirection(Mi),s=ki.copy(i).cross(e.up).normalize();0===s.lengthSq()&&(s.x=1);const n=Di.crossVectors(s,i),r=this._sphericalEnd.radius*Math.tan(e.getEffectiveFOV()*di*.5),o=(this._sphericalEnd.radius-t-this._sphericalEnd.radius)/this._sphericalEnd.radius,a=zi.copy(this._targetEnd).add(s.multiplyScalar(this._dollyControlCoord.x*r*e.aspect)).add(n.multiplyScalar(this._dollyControlCoord.y*r)),l=ki.copy(this._targetEnd).lerp(a,o),h=this._lastDollyDirection===ri&&this._spherical.radius<=this.minDistance,c=this._lastDollyDirection===oi&&this.maxDistance<=this._spherical.radius;if(this.infinityDolly&&(h||c)){this._sphericalEnd.radius-=t,this._spherical.radius-=t;const e=Di.copy(i).multiplyScalar(-t);l.add(e)}this._boundary.clampPoint(l,l);const d=Di.subVectors(l,this._targetEnd);this._targetEnd.copy(l),this._target.add(d),this._changedDolly-=t,pi(this._changedDolly)&&(this._changedDolly=0)}else if(li(this._camera)&&0!==this._changedZoom){const t=this._zoom-this._lastZoom,e=this._camera,i=ki.set(this._dollyControlCoord.x,this._dollyControlCoord.y,(e.near+e.far)/(e.near-e.far)).unproject(e),s=Di.set(0,0,-1).applyQuaternion(e.quaternion),n=zi.copy(i).add(s.multiplyScalar(-i.dot(e.up))),r=-(this._zoom-t-this._zoom)/this._zoom,o=this._getCameraDirection(Mi),a=this._targetEnd.dot(o),l=ki.copy(this._targetEnd).lerp(n,r),h=l.dot(o),c=o.multiplyScalar(h-a);l.sub(c),this._boundary.clampPoint(l,l);const d=Di.subVectors(l,this._targetEnd);this._targetEnd.copy(l),this._target.add(d),this._changedZoom-=t,pi(this._changedZoom)&&(this._changedZoom=0)}this._camera.zoom!==this._zoom&&(this._camera.zoom=this._zoom,this._camera.updateProjectionMatrix(),this._updateNearPlaneCorners(),this._needsUpdate=!0),this._dragNeedsUpdate=!0;const a=this._collisionTest();this._spherical.radius=Math.min(this._spherical.radius,a),this._spherical.makeSafe(),this._camera.position.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse).add(this._target),this._camera.lookAt(this._target);(!pi(this._focalOffset.x)||!pi(this._focalOffset.y)||!pi(this._focalOffset.z))&&(Bi.setFromMatrixColumn(this._camera.matrix,0),Ni.setFromMatrixColumn(this._camera.matrix,1),Ui.setFromMatrixColumn(this._camera.matrix,2),Bi.multiplyScalar(this._focalOffset.x),Ni.multiplyScalar(-this._focalOffset.y),Ui.multiplyScalar(this._focalOffset.z),ki.copy(Bi).add(Ni).add(Ui),this._camera.position.add(ki),this._camera.updateMatrixWorld()),this._boundaryEnclosesCamera&&this._encloseToBoundary(this._camera.position.copy(this._target),ki.setFromSpherical(this._spherical).applyQuaternion(this._yAxisUpSpaceInverse),1);const l=this._needsUpdate;return l&&!this._updatedLastTime?(this._hasRested=!1,this.dispatchEvent({type:"wake"}),this.dispatchEvent({type:"update"})):l?(this.dispatchEvent({type:"update"}),pi(e,this.restThreshold)&&pi(i,this.restThreshold)&&pi(s,this.restThreshold)&&pi(n.x,this.restThreshold)&&pi(n.y,this.restThreshold)&&pi(n.z,this.restThreshold)&&pi(r.x,this.restThreshold)&&pi(r.y,this.restThreshold)&&pi(r.z,this.restThreshold)&&pi(o,this.restThreshold)&&!this._hasRested&&(this._hasRested=!0,this.dispatchEvent({type:"rest"}))):!l&&this._updatedLastTime&&this.dispatchEvent({type:"sleep"}),this._lastDistance=this._spherical.radius,this._lastZoom=this._zoom,this._updatedLastTime=l,this._needsUpdate=!1,l}toJSON(){return JSON.stringify({enabled:this._enabled,minDistance:this.minDistance,maxDistance:gi(this.maxDistance),minZoom:this.minZoom,maxZoom:gi(this.maxZoom),minPolarAngle:this.minPolarAngle,maxPolarAngle:gi(this.maxPolarAngle),minAzimuthAngle:gi(this.minAzimuthAngle),maxAzimuthAngle:gi(this.maxAzimuthAngle),smoothTime:this.smoothTime,draggingSmoothTime:this.draggingSmoothTime,dollySpeed:this.dollySpeed,truckSpeed:this.truckSpeed,dollyToCursor:this.dollyToCursor,target:this._targetEnd.toArray(),position:ki.setFromSpherical(this._sphericalEnd).add(this._targetEnd).toArray(),zoom:this._zoomEnd,focalOffset:this._focalOffsetEnd.toArray(),target0:this._target0.toArray(),position0:this._position0.toArray(),zoom0:this._zoom0,focalOffset0:this._focalOffset0.toArray()})}fromJSON(t,e=!1){const i=JSON.parse(t);this.enabled=i.enabled,this.minDistance=i.minDistance,this.maxDistance=_i(i.maxDistance),this.minZoom=i.minZoom,this.maxZoom=_i(i.maxZoom),this.minPolarAngle=i.minPolarAngle,this.maxPolarAngle=_i(i.maxPolarAngle),this.minAzimuthAngle=_i(i.minAzimuthAngle),this.maxAzimuthAngle=_i(i.maxAzimuthAngle),this.smoothTime=i.smoothTime,this.draggingSmoothTime=i.draggingSmoothTime,this.dollySpeed=i.dollySpeed,this.truckSpeed=i.truckSpeed,this.dollyToCursor=i.dollyToCursor,this._target0.fromArray(i.target0),this._position0.fromArray(i.position0),this._zoom0=i.zoom0,this._focalOffset0.fromArray(i.focalOffset0),this.moveTo(i.target[0],i.target[1],i.target[2],e),Fi.setFromVector3(ki.fromArray(i.position).sub(this._targetEnd).applyQuaternion(this._yAxisUpSpace)),this.rotateTo(Fi.theta,Fi.phi,e),this.dollyTo(Fi.radius,e),this.zoomTo(i.zoom,e),this.setFocalOffset(i.focalOffset[0],i.focalOffset[1],i.focalOffset[2],e),this._needsUpdate=!0}connect(t){this._domElement?console.warn("camera-controls is already connected."):(t.setAttribute("data-camera-controls-version","2.10.1"),this._addAllEventListeners(t),this._getClientRect(this._elementRect))}disconnect(){this.cancel(),this._removeAllEventListeners(),this._domElement&&(this._domElement.removeAttribute("data-camera-controls-version"),this._domElement=void 0)}dispose(){this.removeAllEventListeners(),this.disconnect()}_getTargetDirection(t){return t.setFromSpherical(this._spherical).divideScalar(this._spherical.radius).applyQuaternion(this._yAxisUpSpaceInverse)}_getCameraDirection(t){return this._getTargetDirection(t).negate()}_findPointerById(t){return this._activePointers.find(e=>e.pointerId===t)}_findPointerByMouseButton(t){return this._activePointers.find(e=>e.mouseButton===t)}_disposePointer(t){this._activePointers.splice(this._activePointers.indexOf(t),1)}_encloseToBoundary(t,e,i){const s=e.lengthSq();if(0===s)return t;const n=Di.copy(e).add(t),r=this._boundary.clampPoint(n,zi).sub(n),o=r.lengthSq();if(0===o)return t.add(e);if(o===s)return t;if(0===i)return t.add(e).add(r);{const s=1+i*o/e.dot(r);return t.add(Di.copy(e).multiplyScalar(s)).add(r.multiplyScalar(1-i))}}_updateNearPlaneCorners(){if(ai(this._camera)){const t=this._camera,e=t.near,i=t.getEffectiveFOV()*di,s=Math.tan(.5*i)*e,n=s*t.aspect;this._nearPlaneCorners[0].set(-n,-s,0),this._nearPlaneCorners[1].set(n,-s,0),this._nearPlaneCorners[2].set(n,s,0),this._nearPlaneCorners[3].set(-n,s,0)}else if(li(this._camera)){const t=this._camera,e=1/t.zoom,i=t.left*e,s=t.right*e,n=t.top*e,r=t.bottom*e;this._nearPlaneCorners[0].set(i,n,0),this._nearPlaneCorners[1].set(s,n,0),this._nearPlaneCorners[2].set(s,r,0),this._nearPlaneCorners[3].set(i,r,0)}}_collisionTest(){let t=1/0;if(!(this.colliderMeshes.length>=1))return t;if(bi(this._camera,"_collisionTest"))return t;const e=this._getTargetDirection(Mi);Wi.lookAt(Ai,e,this._camera.up);for(let i=0;i<4;i++){const s=Di.copy(this._nearPlaneCorners[i]);s.applyMatrix4(Wi);const n=zi.addVectors(this._target,s);Xi.set(n,e),Xi.far=this._spherical.radius+1;const r=Xi.intersectObjects(this.colliderMeshes);0!==r.length&&r[0].distance<t&&(t=r[0].distance)}return t}_getClientRect(t){if(!this._domElement)return;const e=this._domElement.getBoundingClientRect();return t.x=e.left,t.y=e.top,this._viewport?(t.x+=this._viewport.x,t.y+=e.height-this._viewport.w-this._viewport.y,t.width=this._viewport.z,t.height=this._viewport.w):(t.width=e.width,t.height=e.height),t}_createOnRestPromise(t){return t?Promise.resolve():(this._hasRested=!1,this.dispatchEvent({type:"transitionstart"}),new Promise(t=>{const e=()=>{this.removeEventListener("rest",e),t()};this.addEventListener("rest",e)}))}_addAllEventListeners(t){}_removeAllEventListeners(){}get dampingFactor(){return console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead."),0}set dampingFactor(t){console.warn(".dampingFactor has been deprecated. use smoothTime (in seconds) instead.")}get draggingDampingFactor(){return console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead."),0}set draggingDampingFactor(t){console.warn(".draggingDampingFactor has been deprecated. use draggingSmoothTime (in seconds) instead.")}static createBoundingSphere(t,e=new Si.Sphere){const i=e,s=i.center;ji.makeEmpty(),t.traverseVisible(t=>{t.isMesh&&ji.expandByObject(t)}),ji.getCenter(s);let n=0;return t.traverseVisible(t=>{if(!t.isMesh)return;const e=t;if(!e.geometry)return;const i=e.geometry.clone();i.applyMatrix4(e.matrixWorld);const r=i.attributes.position;for(let t=0,e=r.count;t<e;t++)ki.fromBufferAttribute(r,t),n=Math.max(n,s.distanceToSquared(ki))}),i.radius=Math.sqrt(n),i}}class Gi extends Z{constructor(t){super(t),e(this,"onBeforeUpdate",new L),e(this,"onAfterUpdate",new L),e(this,"onAspectUpdated",new L),e(this,"onDisposed",new L),e(this,"three"),e(this,"_allControls",new Map),e(this,"updateAspect",()=>{var t;if(this.currentWorld&&this.currentWorld.renderer)if(this.three instanceof o.OrthographicCamera)this.onAspectUpdated.trigger();else if(null==(t=this.currentWorld.renderer)?void 0:t.isResizeable()){const t=this.currentWorld.renderer.getSize();this.three.aspect=t.width/t.height,this.three.updateProjectionMatrix(),this.onAspectUpdated.trigger()}}),this.three=this.setupCamera(),this.setupEvents(!0),this.worlds.onItemSet.add(({value:t})=>{const e=this.newCameraControls();this._allControls.set(t.uuid,e)}),this.worlds.onBeforeDelete.add(({value:t})=>{const e=this._allControls.get(t.uuid);e&&(e.dispose(),this._allControls.delete(t.uuid))})}get controls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");const t=this._allControls.get(this.currentWorld.uuid);if(!t)throw new Error("Controls not found!");return t}get enabled(){return null!==this.currentWorld&&this.controls.enabled}set enabled(t){null!==this.currentWorld&&(this.controls.enabled=t)}set currentWorld(t){if(super.currentWorld=t,!t)return;this.worlds.get(t.uuid)||this.worlds.set(t.uuid,t)}get currentWorld(){return this._currentWorld}dispose(){this.setupEvents(!1),this.onAspectUpdated.reset(),this.onBeforeUpdate.reset(),this.onAfterUpdate.reset(),this.three.removeFromParent(),this.onDisposed.trigger(),this.onDisposed.reset();for(const[t,e]of this._allControls)e.dispose();this.worlds.clear()}async fitToItems(t){const e=await this.getItemsBounding(t);await this.controls.fitToSphere(e,!0)}async setOrbitToItems(t){const e=await this.getItemsBounding(t);this.controls.setOrbitPoint(e.center.x,e.center.y,e.center.z)}update(t){this.enabled&&(this.onBeforeUpdate.trigger(this),this.controls.update(t),this.onAfterUpdate.trigger(this))}async getItemsBounding(t){const e=this.components.get(Oe),i=this.components.get(Be);i.list.clear();const s=new o.Sphere;if(t)await i.addFromModelIdMap(t);else for(const[,t]of e.list)i.list.add(t.box);return i.get().getBoundingSphere(s),i.list.clear(),s}setupCamera(){const t=window.innerWidth/window.innerHeight,e=new o.PerspectiveCamera(60,t,1,1e3);return e.position.set(50,50,50),e.lookAt(new o.Vector3(0,0,0)),e}newCameraControls(){if(!this.currentWorld)throw new Error("This camera needs a world to work!");if(!this.currentWorld.renderer)throw new Error("This camera needs a renderer to work!");qi.install({THREE:Gi.getSubsetOfThree()});const{domElement:t}=this.currentWorld.renderer.three,e=new qi(this.three,t);return e.smoothTime=.2,e.dollyToCursor=!0,e.infinityDolly=!0,e.minDistance=6,e}setupEvents(t){t?window.addEventListener("resize",this.updateAspect):window.removeEventListener("resize",this.updateAspect)}static getSubsetOfThree(){return{MOUSE:o.MOUSE,Vector2:o.Vector2,Vector3:o.Vector3,Vector4:o.Vector4,Quaternion:o.Quaternion,Matrix4:o.Matrix4,Spherical:o.Spherical,Box3:o.Box3,Sphere:o.Sphere,Raycaster:o.Raycaster,MathUtils:o.MathUtils}}}const Qi=class t extends V{constructor(i){super(i),e(this,"onAfterUpdate",new L),e(this,"onBeforeUpdate",new L),e(this,"onDisposed",new L),e(this,"list",new s),e(this,"enabled",!0),i.add(t.uuid,this)}create(){const t=new We(this.components),e=t.uuid;if(this.list.has(e))throw new Error("There is already a world with this name!");return this.list.set(e,t),t}delete(t){if(!this.list.has(t.uuid))throw new Error("The provided world is not found in the list!");this.list.delete(t.uuid),t.dispose()}dispose(){this.enabled=!1;for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger()}update(t){if(this.enabled)for(const[e,i]of this.list)i.update(t)}};e(Qi,"uuid","fdb61dc4-2ec1-4966-b83d-54ea795fad4a");let Ki=Qi;class Ji extends Te{constructor(){super(...arguments),e(this,"_config",{visible:{value:!0,type:"Boolean"},color:{value:new o.Color,type:"Color"},primarySize:{type:"Number",interpolable:!0,value:1,min:0,max:1e3},secondarySize:{type:"Number",interpolable:!0,value:10,min:0,max:1e3},distance:{type:"Number",interpolable:!0,value:500,min:0,max:500}})}get visible(){return this._config.visible.value}set visible(t){this._config.visible.value=t,this._component.visible=t}get color(){return this._config.color.value}set color(t){this._config.color.value=t,this._component.material.uniforms.uColor.value=t,this._component.material.uniformsNeedUpdate=!0}get primarySize(){return this._config.primarySize.value}set primarySize(t){this._config.primarySize.value=t,this._component.material.uniforms.uSize1.value=t,this._component.material.uniformsNeedUpdate=!0}get secondarySize(){return this._config.secondarySize.value}set secondarySize(t){this._config.secondarySize.value=t,this._component.material.uniforms.uSize2.value=t,this._component.material.uniformsNeedUpdate=!0}get distance(){return this._config.distance.value}set distance(t){this._config.distance.value=t,this._component.material.uniforms.uDistance.value=t,this._component.material.uniformsNeedUpdate=!0}}class ts{constructor(t,i){e(this,"onDisposed",new L),e(this,"onSetup",new L),e(this,"isSetup",!1),e(this,"world"),e(this,"components"),e(this,"config"),e(this,"_defaultConfig",{visible:!0,color:new o.Color(12303291),primarySize:1,secondarySize:10,distance:500}),e(this,"three"),e(this,"_fade",3),e(this,"updateZoom",()=>{this.world.camera instanceof Gi&&(this.material.uniforms.uZoom.value=this.world.camera.three.zoom)}),this.world=i;const{color:s,primarySize:n,secondarySize:r,distance:a}=this._defaultConfig;this.components=t,this.config=new Ji(this,this.components,"Grid");const l=new o.PlaneGeometry(2,2,1,1),h=new o.ShaderMaterial({side:o.DoubleSide,uniforms:{uSize1:{value:n},uSize2:{value:r},uColor:{value:s},uDistance:{value:a},uFade:{value:this._fade},uZoom:{value:1}},transparent:!0,vertexShader:"\n \n varying vec3 worldPosition;\n \n uniform float uDistance;\n \n void main() {\n \n vec3 pos = position.xzy * uDistance;\n pos.xz += cameraPosition.xz;\n \n worldPosition = pos;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);\n \n }\n ",fragmentShader:"\n \n varying vec3 worldPosition;\n \n uniform float uZoom;\n uniform float uFade;\n uniform float uSize1;\n uniform float uSize2;\n uniform vec3 uColor;\n uniform float uDistance;\n \n \n \n float getGrid(float size) {\n \n vec2 r = worldPosition.xz / size;\n \n \n vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);\n float line = min(grid.x, grid.y);\n \n \n return 1.0 - min(line, 1.0);\n }\n \n void main() {\n \n \n float d = 1.0 - min(distance(cameraPosition.xz, worldPosition.xz) / uDistance, 1.0);\n \n float g1 = getGrid(uSize1);\n float g2 = getGrid(uSize2);\n \n // Ortho camera fades the grid away when zooming out\n float minZoom = step(0.2, uZoom);\n float zoomFactor = pow(min(uZoom, 1.), 2.) * minZoom;\n \n gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, uFade));\n gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2) * zoomFactor;\n \n if ( gl_FragColor.a <= 0.0 ) discard;\n \n \n }\n \n ",extensions:{derivatives:!0}});this.three=new o.Mesh(l,h),this.three.frustumCulled=!1,i.scene.three.add(this.three),this.setupEvents(!0)}get visible(){return this.three.visible}set visible(t){if(this.three.visible=t,t){this.world.scene.three.add(this.three)}else this.three.removeFromParent()}get material(){return this.three.material}get fade(){return 3===this._fade}set fade(t){this._fade=t?3:0,this.material.uniforms.uFade.value=this._fade}setup(t){const e={...this._defaultConfig,...t};this.config.visible=!0,this.config.color=e.color,this.config.primarySize=e.primarySize,this.config.secondarySize=e.secondarySize,this.config.distance=e.distance,this.isSetup=!0,this.onSetup.trigger()}dispose(){this.setupEvents(!1);this.components.get(Ce).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(t){if(this.world.isDisposing)return;if(!(this.world.camera instanceof Gi))return;const e=this.world.camera.controls;t?e.addEventListener("update",this.updateZoom):e.removeEventListener("update",this.updateZoom)}}const es=class t extends V{constructor(i){super(i),e(this,"list",new Map),e(this,"onDisposed",new L),e(this,"enabled",!0),i.add(t.uuid,this)}create(t){if(this.list.has(t.uuid))throw new Error("This world already has a grid!");const e=new ts(this.components,t);return this.list.set(t.uuid,e),t.onDisposed.add(()=>{this.delete(t)}),e}delete(t){const e=this.list.get(t.uuid);e&&e.dispose(),this.list.delete(t.uuid)}dispose(){for(const[t,e]of this.list)e.dispose();this.list.clear(),this.onDisposed.trigger(),this.onDisposed.reset()}};e(es,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");let is=es;const ss=1.25,ns=65535,rs=Math.pow(2,-24),os=Symbol("SKIP_GENERATION");function as(t){return function(t){return t.index?t.index.count:t.attributes.position.count}(t)/3}function ls(t,e){if(!t.index){const i=t.attributes.position.count,s=function(t,e=ArrayBuffer){return t>65535?new Uint32Array(new e(4*t)):new Uint16Array(new e(2*t))}(i,e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer);t.setIndex(new a(s,1));for(let t=0;t<i;t++)s[t]=t}}function hs(t){const e=as(t),i=t.drawRange,s=i.start/3,n=(i.start+i.count)/3,r=Math.max(0,s),o=Math.min(e,n)-r;return[{offset:Math.floor(r),count:Math.floor(o)}]}function cs(t){if(!t.groups||!t.groups.length)return hs(t);const e=[],i=new Set,s=t.drawRange,n=s.start/3,r=(s.start+s.count)/3;for(const e of t.groups){const t=e.start/3,s=(e.start+e.count)/3;i.add(Math.max(n,t)),i.add(Math.min(r,s))}const o=Array.from(i.values()).sort((t,e)=>t-e);for(let t=0;t<o.length-1;t++){const i=o[t],s=o[t+1];e.push({offset:Math.floor(i),count:Math.floor(s-i)})}return e}function ds(t,e,i){return i.min.x=e[t],i.min.y=e[t+1],i.min.z=e[t+2],i.max.x=e[t+3],i.max.y=e[t+4],i.max.z=e[t+5],i}function us(t){let e=-1,i=-1/0;for(let s=0;s<3;s++){const n=t[s+3]-t[s];n>i&&(i=n,e=s)}return e}function ps(t,e){e.set(t)}function fs(t,e,i){let s,n;for(let r=0;r<3;r++){const o=r+3;s=t[r],n=e[r],i[r]=s<n?s:n,s=t[o],n=e[o],i[o]=s>n?s:n}}function ms(t,e,i){for(let s=0;s<3;s++){const n=e[t+2*s],r=e[t+2*s+1],o=n-r,a=n+r;o<i[s]&&(i[s]=o),a>i[s+3]&&(i[s+3]=a)}}function gs(t){const e=t[3]-t[0],i=t[4]-t[1],s=t[5]-t[2];return 2*(e*i+i*s+s*e)}function _s(t,e,i,s,n=null){let r=1/0,o=1/0,a=1/0,l=-1/0,h=-1/0,c=-1/0,d=1/0,u=1/0,p=1/0,f=-1/0,m=-1/0,g=-1/0;const _=null!==n;for(let s=6*e,n=6*(e+i);s<n;s+=6){const e=t[s+0],i=t[s+1],n=e-i,y=e+i;n<r&&(r=n),y>l&&(l=y),_&&e<d&&(d=e),_&&e>f&&(f=e);const w=t[s+2],v=t[s+3],b=w-v,x=w+v;b<o&&(o=b),x>h&&(h=x),_&&w<u&&(u=w),_&&w>m&&(m=w);const T=t[s+4],E=t[s+5],C=T-E,S=T+E;C<a&&(a=C),S>c&&(c=S),_&&T<p&&(p=T),_&&T>g&&(g=T)}s[0]=r,s[1]=o,s[2]=a,s[3]=l,s[4]=h,s[5]=c,_&&(n[0]=d,n[1]=u,n[2]=p,n[3]=f,n[4]=m,n[5]=g)}const ys=32,ws=(t,e)=>t.candidate-e.candidate,vs=new Array(ys).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),bs=new Float32Array(6);class xs{constructor(){}}function Ts(t,e,i,s,n,r){let o=s,a=s+n-1;const l=r.pos,h=2*r.axis;for(;;){for(;o<=a&&i[6*o+h]<l;)o++;for(;o<=a&&i[6*a+h]>=l;)a--;if(!(o<a))return o;for(let t=0;t<3;t++){let i=e[3*o+t];e[3*o+t]=e[3*a+t],e[3*a+t]=i}for(let t=0;t<6;t++){let e=i[6*o+t];i[6*o+t]=i[6*a+t],i[6*a+t]=e}o++,a--}}function Es(t,e,i,s,n,r){let o=s,a=s+n-1;const l=r.pos,h=2*r.axis;for(;;){for(;o<=a&&i[6*o+h]<l;)o++;for(;o<=a&&i[6*a+h]>=l;)a--;if(!(o<a))return o;{let e=t[o];t[o]=t[a],t[a]=e;for(let t=0;t<6;t++){let e=i[6*o+t];i[6*o+t]=i[6*a+t],i[6*a+t]=e}o++,a--}}}function Cs(t,e){const i=t.geometry,s=i.index?i.index.array:null,n=e.maxDepth,r=e.verbose,o=e.maxLeafTris,a=e.strategy,l=e.onProgress,h=as(i),c=t._indirectBuffer;let d=!1;const u=new Float32Array(6),p=new Float32Array(6),f=function(t,e){var i;(i=e)[0]=i[1]=i[2]=1/0,i[3]=i[4]=i[5]=-1/0;const s=t.attributes.position,n=t.index?t.index.array:null,r=as(t),o=new Float32Array(6*r),a=s.normalized,l=s.array,h=s.offset||0;let c=3;s.isInterleavedBufferAttribute&&(c=s.data.stride);const d=["getX","getY","getZ"];for(let t=0;t<r;t++){const i=3*t,r=6*t;let u=i+0,p=i+1,f=i+2;n&&(u=n[u],p=n[p],f=n[f]),a||(u=u*c+h,p=p*c+h,f=f*c+h);for(let t=0;t<3;t++){let i,n,h;a?(i=s[d[t]](u),n=s[d[t]](p),h=s[d[t]](f)):(i=l[u+t],n=l[p+t],h=l[f+t]);let c=i;n<c&&(c=n),h<c&&(c=h);let m=i;n>m&&(m=n),h>m&&(m=h);const g=(m-c)/2,_=2*t;o[r+_+0]=c+g,o[r+_+1]=g+(Math.abs(c)+g)*rs,c<e[t]&&(e[t]=c),m>e[t+3]&&(e[t+3]=m)}}return o}(i,u),m=e.indirect?Es:Ts,g=[],_=e.indirect?hs(i):cs(i);if(1===_.length){const t=_[0],e=new xs;e.boundingData=u,function(t,e,i,s){let n=1/0,r=1/0,o=1/0,a=-1/0,l=-1/0,h=-1/0;for(let s=6*e,c=6*(e+i);s<c;s+=6){const e=t[s+0];e<n&&(n=e),e>a&&(a=e);const i=t[s+2];i<r&&(r=i),i>l&&(l=i);const c=t[s+4];c<o&&(o=c),c>h&&(h=c)}s[0]=n,s[1]=r,s[2]=o,s[3]=a,s[4]=l,s[5]=h}(f,t.offset,t.count,p),w(e,t.offset,t.count,p),g.push(e)}else for(let t of _){const e=new xs;e.boundingData=new Float32Array(6),_s(f,t.offset,t.count,e.boundingData,p),w(e,t.offset,t.count,p),g.push(e)}return g;function y(t){l&&l(t/h)}function w(t,e,l,h=null,u=0){if(!d&&u>=n&&(d=!0,r&&(console.warn(`MeshBVH: Max depth of ${n} reached when generating BVH. Consider increasing maxDepth.`),console.warn(i))),l<=o||u>=n)return y(e+l),t.offset=e,t.count=l,t;const g=function(t,e,i,s,n,r){let o=-1,a=0;if(0===r)o=us(e),-1!==o&&(a=(e[o]+e[o+3])/2);else if(1===r)o=us(t),-1!==o&&(a=function(t,e,i,s){let n=0;for(let r=e,o=e+i;r<o;r++)n+=t[6*r+2*s];return n/i}(i,s,n,o));else if(2===r){const r=gs(t);let l=ss*n;const h=6*s,c=6*(s+n);for(let t=0;t<3;t++){const s=e[t],d=(e[t+3]-s)/ys;if(n<8){const e=[...vs];e.length=n;let s=0;for(let n=h;n<c;n+=6,s++){const r=e[s];r.candidate=i[n+2*t],r.count=0;const{bounds:o,leftCacheBounds:a,rightCacheBounds:l}=r;for(let t=0;t<3;t++)l[t]=1/0,l[t+3]=-1/0,a[t]=1/0,a[t+3]=-1/0,o[t]=1/0,o[t+3]=-1/0;ms(n,i,o)}e.sort(ws);let d=n;for(let t=0;t<d;t++){const i=e[t];for(;t+1<d&&e[t+1].candidate===i.candidate;)e.splice(t+1,1),d--}for(let s=h;s<c;s+=6){const n=i[s+2*t];for(let t=0;t<d;t++){const r=e[t];n>=r.candidate?ms(s,i,r.rightCacheBounds):(ms(s,i,r.leftCacheBounds),r.count++)}}for(let i=0;i<d;i++){const s=e[i],h=s.count,c=n-s.count,d=s.leftCacheBounds,u=s.rightCacheBounds;let p=0;0!==h&&(p=gs(d)/r);let f=0;0!==c&&(f=gs(u)/r);const m=1+ss*(p*h+f*c);m<l&&(o=t,l=m,a=s.candidate)}}else{for(let t=0;t<ys;t++){const e=vs[t];e.count=0,e.candidate=s+d+t*d;const i=e.bounds;for(let t=0;t<3;t++)i[t]=1/0,i[t+3]=-1/0}for(let e=h;e<c;e+=6){let n=~~((i[e+2*t]-s)/d);n>=ys&&(n=31);const r=vs[n];r.count++,ms(e,i,r.bounds)}const e=vs[31];ps(e.bounds,e.rightCacheBounds);for(let t=30;t>=0;t--){const e=vs[t],i=vs[t+1];fs(e.bounds,i.rightCacheBounds,e.rightCacheBounds)}let u=0;for(let e=0;e<31;e++){const i=vs[e],s=i.count,h=i.bounds,c=vs[e+1].rightCacheBounds;0!==s&&(0===u?ps(h,bs):fs(h,bs,bs)),u+=s;let d=0,p=0;0!==u&&(d=gs(bs)/r);const f=n-u;0!==f&&(p=gs(c)/r);const m=1+ss*(d*u+p*f);m<l&&(o=t,l=m,a=i.candidate)}}}}else console.warn(`MeshBVH: Invalid build strategy value ${r} used.`);return{axis:o,pos:a}}(t.boundingData,h,f,e,l,a);if(-1===g.axis)return y(e+l),t.offset=e,t.count=l,t;const _=m(c,s,f,e,l,g);if(_===e||_===e+l)y(e+l),t.offset=e,t.count=l;else{t.splitAxis=g.axis;const i=new xs,s=e,n=_-e;t.left=i,i.boundingData=new Float32Array(6),_s(f,s,n,i.boundingData,p),w(i,s,n,p,u+1);const r=new xs,o=_,a=l-n;t.right=r,r.boundingData=new Float32Array(6),_s(f,o,a,r.boundingData,p),w(r,o,a,p,u+1)}return t}}function Ss(t,e){const i=t.geometry;e.indirect&&(t._indirectBuffer=function(t,e){const i=(t.index?t.index.count:t.attributes.position.count)/3,s=i>65536,n=s?4:2,r=e?new SharedArrayBuffer(i*n):new ArrayBuffer(i*n),o=s?new Uint32Array(r):new Uint16Array(r);for(let t=0,e=o.length;t<e;t++)o[t]=t;return o}(i,e.useSharedArrayBuffer),function(t){if(0===t.groups.length)return!1;const e=as(t),i=cs(t).sort((t,e)=>t.offset-e.offset),s=i[i.length-1];s.count=Math.min(e-s.offset,s.count);let n=0;return i.forEach(({count:t})=>n+=t),e!==n}(i)&&!e.verbose&&console.warn('MeshBVH: Provided geometry contains groups that do not fully span the vertex contents while using the "indirect" option. BVH may incorrectly report intersections on unrendered portions of the geometry.')),t._indirectBuffer||ls(i,e);const s=Cs(t,e);let n,r,o;const a=[],l=e.useSharedArrayBuffer?SharedArrayBuffer:ArrayBuffer;for(let t=0;t<s.length;t++){const e=s[t];const i=new l(32*h(e));n=new Float32Array(i),r=new Uint32Array(i),o=new Uint16Array(i),c(0,e),a.push(i)}return void(t._roots=a);function h(t){return t.count?1:1+h(t.left)+h(t.right)}function c(t,e){const i=t/4,s=t/2,a=!!e.count,l=e.boundingData;for(let t=0;t<6;t++)n[i+t]=l[t];if(a){const n=e.offset,a=e.count;return r[i+6]=n,o[s+14]=a,o[s+15]=ns,t+32}{const s=e.left,n=e.right,o=e.splitAxis;let a;if(a=c(t+32,s),a/4>Math.pow(2,32))throw new Error("MeshBVH: Cannot store child pointer greater than 32 bits.");return r[i+6]=a/4,a=c(a,n),r[i+7]=o,a}}}class As{constructor(){this.min=1/0,this.max=-1/0}setFromPointsField(t,e){let i=1/0,s=-1/0;for(let n=0,r=t.length;n<r;n++){const r=t[n][e];i=r<i?r:i,s=r>s?r:s}this.min=i,this.max=s}setFromPoints(t,e){let i=1/0,s=-1/0;for(let n=0,r=e.length;n<r;n++){const r=e[n],o=t.dot(r);i=o<i?o:i,s=o>s?o:s}this.min=i,this.max=s}isSeparated(t){return this.min>t.max||t.min>this.max}}As.prototype.setFromBox=function(){const t=new l;return function(e,i){const s=i.min,n=i.max;let r=1/0,o=-1/0;for(let i=0;i<=1;i++)for(let a=0;a<=1;a++)for(let l=0;l<=1;l++){t.x=s.x*i+n.x*(1-i),t.y=s.y*a+n.y*(1-a),t.z=s.z*l+n.z*(1-l);const h=e.dot(t);r=Math.min(h,r),o=Math.max(h,o)}this.min=r,this.max=o}}();const Os=function(){const t=new l,e=new l,i=new l;return function(s,n,r){const o=s.start,a=t,l=n.start,h=e;i.subVectors(o,l),t.subVectors(s.end,s.start),e.subVectors(n.end,n.start);const c=i.dot(h),d=h.dot(a),u=h.dot(h),p=i.dot(a),f=a.dot(a)*u-d*d;let m,g;m=0!==f?(c*d-p*u)/f:0,g=(c+m*d)/u,r.x=m,r.y=g}}(),Ps=function(){const t=new d,e=new l,i=new l;return function(s,n,r,o){Os(s,n,t);let a=t.x,l=t.y;if(a>=0&&a<=1&&l>=0&&l<=1)return s.at(a,r),void n.at(l,o);if(a>=0&&a<=1)return l<0?n.at(0,o):n.at(1,o),void s.closestPointToPoint(o,!0,r);if(l>=0&&l<=1)return a<0?s.at(0,r):s.at(1,r),void n.closestPointToPoint(r,!0,o);{let t,h;t=a<0?s.start:s.end,h=l<0?n.start:n.end;const c=e,d=i;return s.closestPointToPoint(h,!0,e),n.closestPointToPoint(t,!0,i),c.distanceToSquared(h)<=d.distanceToSquared(t)?(r.copy(c),void o.copy(h)):(r.copy(t),void o.copy(d))}}}(),Is=function(){const t=new l,e=new l,i=new h,s=new c;return function(n,r){const{radius:o,center:a}=n,{a:l,b:h,c:c}=r;s.start=l,s.end=h;if(s.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;s.start=l,s.end=c;if(s.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;s.start=h,s.end=c;if(s.closestPointToPoint(a,!0,t).distanceTo(a)<=o)return!0;const d=r.getPlane(i);if(Math.abs(d.distanceToPoint(a))<=o){const t=d.projectPoint(a,e);if(r.containsPoint(t))return!0}return!1}}();function ks(t){return Math.abs(t)<1e-15}class Ds extends u{constructor(...t){super(...t),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new l),this.satBounds=new Array(4).fill().map(()=>new As),this.points=[this.a,this.b,this.c],this.sphere=new p,this.plane=new h,this.needsUpdate=!0}intersectsSphere(t){return Is(t,this)}update(){const t=this.a,e=this.b,i=this.c,s=this.points,n=this.satAxes,r=this.satBounds,o=n[0],a=r[0];this.getNormal(o),a.setFromPoints(o,s);const l=n[1],h=r[1];l.subVectors(t,e),h.setFromPoints(l,s);const c=n[2],d=r[2];c.subVectors(e,i),d.setFromPoints(c,s);const u=n[3],p=r[3];u.subVectors(i,t),p.setFromPoints(u,s),this.sphere.setFromPoints(this.points),this.plane.setFromNormalAndCoplanarPoint(o,t),this.needsUpdate=!1}}Ds.prototype.closestPointToSegment=function(){const t=new l,e=new l,i=new c;return function(s,n=null,r=null){const{start:o,end:a}=s,l=this.points;let h,c=1/0;for(let o=0;o<3;o++){const a=(o+1)%3;i.start.copy(l[o]),i.end.copy(l[a]),Ps(i,s,t,e),h=t.distanceToSquared(e),h<c&&(c=h,n&&n.copy(t),r&&r.copy(e))}return this.closestPointToPoint(o,t),h=o.distanceToSquared(t),h<c&&(c=h,n&&n.copy(t),r&&r.copy(o)),this.closestPointToPoint(a,t),h=a.distanceToSquared(t),h<c&&(c=h,n&&n.copy(t),r&&r.copy(a)),Math.sqrt(c)}}(),Ds.prototype.intersectsTriangle=function(){const t=new Ds,e=new Array(3),i=new Array(3),s=new As,n=new As,r=new l,o=new l,a=new l,h=new l,d=new l,u=new c,p=new c,f=new c,m=new l;function g(t,e,i){const s=t.points;let n=0,r=-1;for(let t=0;t<3;t++){const{start:a,end:l}=u;a.copy(s[t]),l.copy(s[(t+1)%3]),u.delta(o);const h=ks(e.distanceToPoint(a));if(ks(e.normal.dot(o))&&h){i.copy(u),n=2;break}const c=e.intersectLine(u,m);if(!c&&h&&m.copy(a),(c||h)&&!ks(m.distanceTo(l))){if(n<=1){(1===n?i.start:i.end).copy(m),h&&(r=n)}else if(n>=2){(1===r?i.start:i.end).copy(m),n=2;break}if(n++,2===n&&-1===r)break}}return n}return function(o,l=null,c=!1){this.needsUpdate&&this.update(),o.isExtendedTriangle?o.needsUpdate&&o.update():(t.copy(o),t.update(),o=t);const u=this.plane,m=o.plane;if(Math.abs(u.normal.dot(m.normal))>1-1e-10){const t=this.satBounds,a=this.satAxes;i[0]=o.a,i[1]=o.b,i[2]=o.c;for(let e=0;e<4;e++){const n=t[e],r=a[e];if(s.setFromPoints(r,i),n.isSeparated(s))return!1}const h=o.satBounds,d=o.satAxes;e[0]=this.a,e[1]=this.b,e[2]=this.c;for(let t=0;t<4;t++){const i=h[t],n=d[t];if(s.setFromPoints(n,e),i.isSeparated(s))return!1}for(let t=0;t<4;t++){const o=a[t];for(let t=0;t<4;t++){const a=d[t];if(r.crossVectors(o,a),s.setFromPoints(r,e),n.setFromPoints(r,i),s.isSeparated(n))return!1}}return l&&(c||console.warn("ExtendedTriangle.intersectsTriangle: Triangles are coplanar which does not support an output edge. Setting edge to 0, 0, 0."),l.start.set(0,0,0),l.end.set(0,0,0)),!0}{const t=g(this,m,p);if(1===t&&o.containsPoint(p.end))return l&&(l.start.copy(p.end),l.end.copy(p.end)),!0;if(2!==t)return!1;const e=g(o,u,f);if(1===e&&this.containsPoint(f.end))return l&&(l.start.copy(f.end),l.end.copy(f.end)),!0;if(2!==e)return!1;if(p.delta(a),f.delta(h),a.dot(h)<0){let t=f.start;f.start=f.end,f.end=t}const i=p.start.dot(a),s=p.end.dot(a),n=f.start.dot(a),r=f.end.dot(a);return(i===r||n===s||s<n!==i<r)&&(l&&(d.subVectors(p.start,f.start),d.dot(a)>0?l.start.copy(p.start):l.start.copy(f.start),d.subVectors(p.end,f.end),d.dot(a)<0?l.end.copy(p.end):l.end.copy(f.end)),!0)}}}(),Ds.prototype.distanceToPoint=function(){const t=new l;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),Ds.prototype.distanceToTriangle=function(){const t=new l,e=new l,i=["a","b","c"],s=new c,n=new c;return function(r,o=null,a=null){const l=o||a?s:null;if(this.intersectsTriangle(r,l))return(o||a)&&(o&&l.getCenter(o),a&&l.getCenter(a)),0;let h=1/0;for(let e=0;e<3;e++){let s;const n=i[e],l=r[n];this.closestPointToPoint(l,t),s=l.distanceToSquared(t),s<h&&(h=s,o&&o.copy(t),a&&a.copy(l));const c=this[n];r.closestPointToPoint(c,t),s=c.distanceToSquared(t),s<h&&(h=s,o&&o.copy(c),a&&a.copy(t))}for(let l=0;l<3;l++){const c=i[l],d=i[(l+1)%3];s.set(this[c],this[d]);for(let l=0;l<3;l++){const c=i[l],d=i[(l+1)%3];n.set(r[c],r[d]),Ps(s,n,t,e);const u=t.distanceToSquared(e);u<h&&(h=u,o&&o.copy(t),a&&a.copy(e))}}return Math.sqrt(h)}}();class zs{constructor(t,e,i){this.isOrientedBox=!0,this.min=new l,this.max=new l,this.matrix=new f,this.invMatrix=new f,this.points=new Array(8).fill().map(()=>new l),this.satAxes=new Array(3).fill().map(()=>new l),this.satBounds=new Array(3).fill().map(()=>new As),this.alignedSatBounds=new Array(3).fill().map(()=>new As),this.needsUpdate=!1,t&&this.min.copy(t),e&&this.max.copy(e),i&&this.matrix.copy(i)}set(t,e,i){this.min.copy(t),this.max.copy(e),this.matrix.copy(i),this.needsUpdate=!0}copy(t){this.min.copy(t.min),this.max.copy(t.max),this.matrix.copy(t.matrix),this.needsUpdate=!0}}zs.prototype.update=function(){return function(){const t=this.matrix,e=this.min,i=this.max,s=this.points;for(let n=0;n<=1;n++)for(let r=0;r<=1;r++)for(let o=0;o<=1;o++){const a=s[1*n|2*r|4*o];a.x=n?i.x:e.x,a.y=r?i.y:e.y,a.z=o?i.z:e.z,a.applyMatrix4(t)}const n=this.satBounds,r=this.satAxes,o=s[0];for(let t=0;t<3;t++){const e=r[t],i=n[t],a=s[1<<t];e.subVectors(o,a),i.setFromPoints(e,s)}const a=this.alignedSatBounds;a[0].setFromPointsField(s,"x"),a[1].setFromPointsField(s,"y"),a[2].setFromPointsField(s,"z"),this.invMatrix.copy(this.matrix).invert(),this.needsUpdate=!1}}(),zs.prototype.intersectsBox=function(){const t=new As;return function(e){this.needsUpdate&&this.update();const i=e.min,s=e.max,n=this.satBounds,r=this.satAxes,o=this.alignedSatBounds;if(t.min=i.x,t.max=s.x,o[0].isSeparated(t))return!1;if(t.min=i.y,t.max=s.y,o[1].isSeparated(t))return!1;if(t.min=i.z,t.max=s.z,o[2].isSeparated(t))return!1;for(let i=0;i<3;i++){const s=r[i],o=n[i];if(t.setFromBox(s,e),o.isSeparated(t))return!1}return!0}}(),zs.prototype.intersectsTriangle=function(){const t=new Ds,e=new Array(3),i=new As,s=new As,n=new l;return function(r){this.needsUpdate&&this.update(),r.isExtendedTriangle?r.needsUpdate&&r.update():(t.copy(r),t.update(),r=t);const o=this.satBounds,a=this.satAxes;e[0]=r.a,e[1]=r.b,e[2]=r.c;for(let t=0;t<3;t++){const s=o[t],n=a[t];if(i.setFromPoints(n,e),s.isSeparated(i))return!1}const l=r.satBounds,h=r.satAxes,c=this.points;for(let t=0;t<3;t++){const e=l[t],s=h[t];if(i.setFromPoints(s,c),e.isSeparated(i))return!1}for(let t=0;t<3;t++){const r=a[t];for(let t=0;t<4;t++){const o=h[t];if(n.crossVectors(r,o),i.setFromPoints(n,e),s.setFromPoints(n,c),i.isSeparated(s))return!1}}return!0}}(),zs.prototype.closestPointToPoint=function(){return function(t,e){return this.needsUpdate&&this.update(),e.copy(t).applyMatrix4(this.invMatrix).clamp(this.min,this.max).applyMatrix4(this.matrix),e}}(),zs.prototype.distanceToPoint=function(){const t=new l;return function(e){return this.closestPointToPoint(e,t),e.distanceTo(t)}}(),zs.prototype.distanceToBox=function(){const t=["x","y","z"],e=new Array(12).fill().map(()=>new c),i=new Array(12).fill().map(()=>new c),s=new l,n=new l;return function(r,o=0,a=null,l=null){if(this.needsUpdate&&this.update(),this.intersectsBox(r))return(a||l)&&(r.getCenter(n),this.closestPointToPoint(n,s),r.closestPointToPoint(s,n),a&&a.copy(s),l&&l.copy(n)),0;const h=o*o,c=r.min,d=r.max,u=this.points;let p=1/0;for(let t=0;t<8;t++){const e=u[t];n.copy(e).clamp(c,d);const i=e.distanceToSquared(n);if(i<p&&(p=i,a&&a.copy(e),l&&l.copy(n),i<h))return Math.sqrt(i)}let f=0;for(let s=0;s<3;s++)for(let n=0;n<=1;n++)for(let r=0;r<=1;r++){const o=(s+1)%3,a=(s+2)%3,l=1<<s|n<<o|r<<a,h=u[n<<o|r<<a],p=u[l];e[f].set(h,p);const m=t[s],g=t[o],_=t[a],y=i[f],w=y.start,v=y.end;w[m]=c[m],w[g]=n?c[g]:d[g],w[_]=r?c[_]:d[g],v[m]=d[m],v[g]=n?c[g]:d[g],v[_]=r?c[_]:d[g],f++}for(let t=0;t<=1;t++)for(let e=0;e<=1;e++)for(let i=0;i<=1;i++){n.x=t?d.x:c.x,n.y=e?d.y:c.y,n.z=i?d.z:c.z,this.closestPointToPoint(n,s);const r=n.distanceToSquared(s);if(r<p&&(p=r,a&&a.copy(s),l&&l.copy(n),r<h))return Math.sqrt(r)}for(let t=0;t<12;t++){const r=e[t];for(let t=0;t<12;t++){const e=i[t];Ps(r,e,s,n);const o=s.distanceToSquared(n);if(o<p&&(p=o,a&&a.copy(s),l&&l.copy(n),o<h))return Math.sqrt(o)}}return Math.sqrt(p)}}();class Ms{constructor(t){this._getNewPrimitive=t,this._primitives=[]}getPrimitive(){const t=this._primitives;return 0===t.length?this._getNewPrimitive():t.pop()}releasePrimitive(t){this._primitives.push(t)}}class Bs extends Ms{constructor(){super(()=>new Ds)}}const Ns=new Bs;function Us(t,e){return 65535===e[t+15]}function Ls(t,e){return e[t+6]}function Rs(t,e){return e[t+14]}function Fs(t){return t+8}function Vs(t,e){return e[t+6]}function js(t,e){return e[t+7]}function Zs(t){return t}const Hs=new class{constructor(){this.float32Array=null,this.uint16Array=null,this.uint32Array=null;const t=[];let e=null;this.setBuffer=i=>{e&&t.push(e),e=i,this.float32Array=new Float32Array(i),this.uint16Array=new Uint16Array(i),this.uint32Array=new Uint32Array(i)},this.clearBuffer=()=>{e=null,this.float32Array=null,this.uint16Array=null,this.uint32Array=null,0!==t.length&&this.setBuffer(t.pop())}}};let $s,Ys;const Ws=[],Xs=new Ms(()=>new m);function qs(t,e,i,s,n,r){$s=Xs.getPrimitive(),Ys=Xs.getPrimitive(),Ws.push($s,Ys),Hs.setBuffer(t._roots[e]);const o=Gs(0,t.geometry,i,s,n,r);Hs.clearBuffer(),Xs.releasePrimitive($s),Xs.releasePrimitive(Ys),Ws.pop(),Ws.pop();const a=Ws.length;return a>0&&(Ys=Ws[a-1],$s=Ws[a-2]),o}function Gs(t,e,i,s,n=null,r=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:h}=Hs;let c=2*t;if(Us(c,l)){const e=Ls(t,h),i=Rs(c,l);return ds(t,a,$s),s(e,i,!1,o,r+t,$s)}{let c=function(t){const{uint16Array:e,uint32Array:i}=Hs;let s=2*t;for(;!Us(s,e);)s=2*(t=Fs(t));return Ls(t,i)},d=function(t){const{uint16Array:e,uint32Array:i}=Hs;let s=2*t;for(;!Us(s,e);)s=2*(t=Vs(t,i));return Ls(t,i)+Rs(s,e)};const u=Fs(t),p=Vs(t,h);let f,m,g,_,y=u,w=p;if(n&&(g=$s,_=Ys,ds(y,a,g),ds(w,a,_),f=n(g),m=n(_),m<f)){y=p,w=u;const t=f;f=m,m=t,g=_}g||(g=$s,ds(y,a,g));const v=i(g,Us(2*y,l),f,o+1,r+y);let b;if(2===v){const t=c(y);b=s(t,d(y)-t,!0,o+1,r+y,g)}else b=v&&Gs(y,e,i,s,n,r,o+1);if(b)return!0;_=Ys,ds(w,a,_);const x=i(_,Us(2*w,l),m,o+1,r+w);let T;if(2===x){const t=c(w);T=s(t,d(w)-t,!0,o+1,r+w,_)}else T=x&&Gs(w,e,i,s,n,r,o+1);return!!T}}const Qs=new l,Ks=new l;const Js=new l,tn=new l,en=new l,sn=new d,nn=new d,rn=new d,on=new l,an=new l,ln=new l,hn=new l;function cn(t,e,i,s,n,r,o,a,h){Js.fromBufferAttribute(e,r),tn.fromBufferAttribute(e,o),en.fromBufferAttribute(e,a);const c=function(t,e,i,s,n,r){let o;return o=r===g?t.intersectTriangle(s,i,e,!0,n):t.intersectTriangle(e,i,s,r!==_,n),null===o?null:{distance:t.origin.distanceTo(n),point:n.clone()}}(t,Js,tn,en,hn,h);if(c){s&&(sn.fromBufferAttribute(s,r),nn.fromBufferAttribute(s,o),rn.fromBufferAttribute(s,a),c.uv=u.getInterpolation(hn,Js,tn,en,sn,nn,rn,new d)),n&&(sn.fromBufferAttribute(n,r),nn.fromBufferAttribute(n,o),rn.fromBufferAttribute(n,a),c.uv1=u.getInterpolation(hn,Js,tn,en,sn,nn,rn,new d)),i&&(on.fromBufferAttribute(i,r),an.fromBufferAttribute(i,o),ln.fromBufferAttribute(i,a),c.normal=u.getInterpolation(hn,Js,tn,en,on,an,ln,new l),c.normal.dot(t.direction)>0&&c.normal.multiplyScalar(-1));const e={a:r,b:o,c:a,normal:new l,materialIndex:0};u.getNormal(Js,tn,en,e.normal),c.face=e,c.faceIndex=r}return c}function dn(t,e,i,s,n){const r=3*s;let o=r+0,a=r+1,l=r+2;const h=t.index;t.index&&(o=h.getX(o),a=h.getX(a),l=h.getX(l));const{position:c,normal:d,uv:u,uv1:p}=t.attributes,f=cn(i,c,d,u,p,o,a,l,e);return f?(f.faceIndex=s,n&&n.push(f),f):null}function un(t,e,i,s){const n=t.a,r=t.b,o=t.c;let a=e,l=e+1,h=e+2;i&&(a=i.getX(a),l=i.getX(l),h=i.getX(h)),n.x=s.getX(a),n.y=s.getY(a),n.z=s.getZ(a),r.x=s.getX(l),r.y=s.getY(l),r.z=s.getZ(l),o.x=s.getX(h),o.y=s.getY(h),o.z=s.getZ(h)}function pn(t,e,i,s,n,r,o){const{geometry:a}=i,{index:l}=a,h=a.attributes.position;for(let i=t,a=e+t;i<a;i++){let t;if(t=i,un(o,3*t,l,h),o.needsUpdate=!0,s(o,t,n,r))return!0}return!1}function fn(t,e=null){e&&Array.isArray(e)&&(e=new Set(e));const i=t.geometry,s=i.index?i.index.array:null,n=i.attributes.position;let r,o,a,l,h=0;const c=t._roots;for(let t=0,e=c.length;t<e;t++)r=c[t],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),d(0,h),h+=r.byteLength;function d(t,i,r=!1){const h=2*t;if(a[h+15]===ns){const e=o[t+6];let i=1/0,r=1/0,c=1/0,d=-1/0,u=-1/0,p=-1/0;for(let t=3*e,o=3*(e+a[h+14]);t<o;t++){let e=s[t];const o=n.getX(e),a=n.getY(e),l=n.getZ(e);o<i&&(i=o),o>d&&(d=o),a<r&&(r=a),a>u&&(u=a),l<c&&(c=l),l>p&&(p=l)}return(l[t+0]!==i||l[t+1]!==r||l[t+2]!==c||l[t+3]!==d||l[t+4]!==u||l[t+5]!==p)&&(l[t+0]=i,l[t+1]=r,l[t+2]=c,l[t+3]=d,l[t+4]=u,l[t+5]=p,!0)}{const s=t+8,n=o[t+6],a=s+i,h=n+i;let c=r,u=!1,p=!1;e?c||(u=e.has(a),p=e.has(h),c=!u&&!p):(u=!0,p=!0);const f=c||p;let m=!1;(c||u)&&(m=d(s,i,c));let g=!1;f&&(g=d(n,i,c));const _=m||g;if(_)for(let e=0;e<3;e++){const i=s+e,r=n+e,o=l[i],a=l[i+3],h=l[r],c=l[r+3];l[t+e]=o<h?o:h,l[t+e+3]=a>c?a:c}return _}}}const mn=new m;function gn(t,e,i,s){return ds(t,e,mn),i.intersectBox(mn,s)}function _n(t,e,i,s,n,r,o){const{geometry:a}=i,{index:l}=a,h=a.attributes.position;for(let a=t,c=e+t;a<c;a++){let t;if(t=i.resolveTriangleIndex(a),un(o,3*t,l,h),o.needsUpdate=!0,s(o,t,n,r))return!0}return!1}const yn=new l;function wn(t,e,i,s,n){Hs.setBuffer(t._roots[e]),vn(0,t,i,s,n),Hs.clearBuffer()}function vn(t,e,i,s,n){const{float32Array:r,uint16Array:o,uint32Array:a}=Hs,l=2*t;if(Us(l,o)){!function(t,e,i,s,n,r){const{geometry:o,_indirectBuffer:a}=t;for(let t=s,a=s+n;t<a;t++)dn(o,e,i,t,r)}(e,i,s,Ls(t,a),Rs(l,o),n)}else{const o=Fs(t);gn(o,r,s,yn)&&vn(o,e,i,s,n);const l=Vs(t,a);gn(l,r,s,yn)&&vn(l,e,i,s,n)}}const bn=new l,xn=["x","y","z"];function Tn(t,e,i,s){Hs.setBuffer(t._roots[e]);const n=En(0,t,i,s);return Hs.clearBuffer(),n}function En(t,e,i,s){const{float32Array:n,uint16Array:r,uint32Array:o}=Hs;let a=2*t;if(Us(a,r)){return function(t,e,i,s,n){const{geometry:r,_indirectBuffer:o}=t;let a=1/0,l=null;for(let t=s,o=s+n;t<o;t++){let s;s=dn(r,e,i,t),s&&s.distance<a&&(l=s,a=s.distance)}return l}(e,i,s,Ls(t,o),Rs(a,r))}{const r=js(t,o),a=xn[r],l=s.direction[a]>=0;let h,c;l?(h=Fs(t),c=Vs(t,o)):(h=Vs(t,o),c=Fs(t));const d=gn(h,n,s,bn)?En(h,e,i,s):null;if(d){const t=d.point[a];if(l?t<=n[c+r]:t>=n[c+r+3])return d}const u=gn(c,n,s,bn)?En(c,e,i,s):null;return d&&u?d.distance<=u.distance?d:u:d||u||null}}const Cn=new m,Sn=new Ds,An=new Ds,On=new f,Pn=new zs,In=new zs;function kn(t,e,i,s){Hs.setBuffer(t._roots[e]);const n=Dn(0,t,i,s);return Hs.clearBuffer(),n}function Dn(t,e,i,s,n=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Hs;let l=2*t;null===n&&(i.boundingBox||i.computeBoundingBox(),Pn.set(i.boundingBox.min,i.boundingBox.max,s),n=Pn);if(!Us(l,o)){const o=t+8,l=a[t+6];ds(o,r,Cn);if(n.intersectsBox(Cn)&&Dn(o,e,i,s,n))return!0;ds(l,r,Cn);return!!(n.intersectsBox(Cn)&&Dn(l,e,i,s,n))}{const n=e.geometry,h=n.index,c=n.attributes.position,d=i.index,u=i.attributes.position,p=Ls(t,a),f=Rs(l,o);if(On.copy(s).invert(),i.boundsTree){ds(t,r,In),In.matrix.copy(On),In.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>In.intersectsBox(t),intersectsTriangle:t=>{t.a.applyMatrix4(s),t.b.applyMatrix4(s),t.c.applyMatrix4(s),t.needsUpdate=!0;for(let e=3*p,i=3*(f+p);e<i;e+=3)if(un(An,e,h,c),An.needsUpdate=!0,t.intersectsTriangle(An))return!0;return!1}})}for(let t=3*p,e=3*(f+p);t<e;t+=3){un(Sn,t,h,c),Sn.a.applyMatrix4(On),Sn.b.applyMatrix4(On),Sn.c.applyMatrix4(On),Sn.needsUpdate=!0;for(let t=0,e=d.count;t<e;t+=3)if(un(An,t,d,u),An.needsUpdate=!0,Sn.intersectsTriangle(An))return!0}}}const zn=new f,Mn=new zs,Bn=new zs,Nn=new l,Un=new l,Ln=new l,Rn=new l;function Fn(t,e,i,s={},n={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),Mn.set(e.boundingBox.min,e.boundingBox.max,i),Mn.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,h=a.index,c=e.attributes.position,d=e.index,u=Ns.getPrimitive(),p=Ns.getPrimitive();let f=Nn,m=Un,g=null,_=null;n&&(g=Ln,_=Rn);let y=1/0,w=null,v=null;return zn.copy(i).invert(),Bn.matrix.copy(zn),t.shapecast({boundsTraverseOrder:t=>Mn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(Bn.min.copy(t.min),Bn.max.copy(t.max),Bn.needsUpdate=!0),!0),intersectsRange:(t,s)=>{if(e.boundsTree){return e.boundsTree.shapecast({boundsTraverseOrder:t=>Bn.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,n)=>{for(let o=e,a=e+n;o<a;o++){un(p,3*o,d,c),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=t,i=t+s;e<i;e++){un(u,3*e,h,l),u.needsUpdate=!0;const t=u.distanceToTriangle(p,f,g);if(t<y&&(m.copy(f),_&&_.copy(g),y=t,w=e,v=o),t<r)return!0}}}})}for(let n=0,o=as(e);n<o;n++){un(p,3*n,d,c),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=t,i=t+s;e<i;e++){un(u,3*e,h,l),u.needsUpdate=!0;const t=u.distanceToTriangle(p,f,g);if(t<y&&(m.copy(f),_&&_.copy(g),y=t,w=e,v=n),t<r)return!0}}}}),Ns.releasePrimitive(u),Ns.releasePrimitive(p),y===1/0?null:(s.point?s.point.copy(m):s.point=m.clone(),s.distance=y,s.faceIndex=w,n&&(n.point?n.point.copy(_):n.point=_.clone(),n.point.applyMatrix4(zn),m.applyMatrix4(zn),n.distance=m.sub(n.point).length(),n.faceIndex=v),s)}function Vn(t,e=null){e&&Array.isArray(e)&&(e=new Set(e));const i=t.geometry,s=i.index?i.index.array:null,n=i.attributes.position;let r,o,a,l,h=0;const c=t._roots;for(let t=0,e=c.length;t<e;t++)r=c[t],o=new Uint32Array(r),a=new Uint16Array(r),l=new Float32Array(r),d(0,h),h+=r.byteLength;function d(i,r,h=!1){const c=2*i;if(a[c+15]===ns){const e=o[i+6];let r=1/0,h=1/0,d=1/0,u=-1/0,p=-1/0,f=-1/0;for(let i=e,o=e+a[c+14];i<o;i++){const e=3*t.resolveTriangleIndex(i);for(let t=0;t<3;t++){let i=e+t;i=s?s[i]:i;const o=n.getX(i),a=n.getY(i),l=n.getZ(i);o<r&&(r=o),o>u&&(u=o),a<h&&(h=a),a>p&&(p=a),l<d&&(d=l),l>f&&(f=l)}}return(l[i+0]!==r||l[i+1]!==h||l[i+2]!==d||l[i+3]!==u||l[i+4]!==p||l[i+5]!==f)&&(l[i+0]=r,l[i+1]=h,l[i+2]=d,l[i+3]=u,l[i+4]=p,l[i+5]=f,!0)}{const t=i+8,s=o[i+6],n=t+r,a=s+r;let c=h,u=!1,p=!1;e?c||(u=e.has(n),p=e.has(a),c=!u&&!p):(u=!0,p=!0);const f=c||p;let m=!1;(c||u)&&(m=d(t,r,c));let g=!1;f&&(g=d(s,r,c));const _=m||g;if(_)for(let e=0;e<3;e++){const n=t+e,r=s+e,o=l[n],a=l[n+3],h=l[r],c=l[r+3];l[i+e]=o<h?o:h,l[i+e+3]=a>c?a:c}return _}}}const jn=new l;function Zn(t,e,i,s,n){Hs.setBuffer(t._roots[e]),Hn(0,t,i,s,n),Hs.clearBuffer()}function Hn(t,e,i,s,n){const{float32Array:r,uint16Array:o,uint32Array:a}=Hs,l=2*t;if(Us(l,o)){!function(t,e,i,s,n,r){const{geometry:o,_indirectBuffer:a}=t;for(let t=s,l=s+n;t<l;t++)dn(o,e,i,a?a[t]:t,r)}(e,i,s,Ls(t,a),Rs(l,o),n)}else{const o=Fs(t);gn(o,r,s,jn)&&Hn(o,e,i,s,n);const l=Vs(t,a);gn(l,r,s,jn)&&Hn(l,e,i,s,n)}}const $n=new l,Yn=["x","y","z"];function Wn(t,e,i,s){Hs.setBuffer(t._roots[e]);const n=Xn(0,t,i,s);return Hs.clearBuffer(),n}function Xn(t,e,i,s){const{float32Array:n,uint16Array:r,uint32Array:o}=Hs;let a=2*t;if(Us(a,r)){return function(t,e,i,s,n){const{geometry:r,_indirectBuffer:o}=t;let a=1/0,l=null;for(let t=s,h=s+n;t<h;t++){let s;s=dn(r,e,i,o?o[t]:t),s&&s.distance<a&&(l=s,a=s.distance)}return l}(e,i,s,Ls(t,o),Rs(a,r))}{const r=js(t,o),a=Yn[r],l=s.direction[a]>=0;let h,c;l?(h=Fs(t),c=Vs(t,o)):(h=Vs(t,o),c=Fs(t));const d=gn(h,n,s,$n)?Xn(h,e,i,s):null;if(d){const t=d.point[a];if(l?t<=n[c+r]:t>=n[c+r+3])return d}const u=gn(c,n,s,$n)?Xn(c,e,i,s):null;return d&&u?d.distance<=u.distance?d:u:d||u||null}}const qn=new m,Gn=new Ds,Qn=new Ds,Kn=new f,Jn=new zs,tr=new zs;function er(t,e,i,s){Hs.setBuffer(t._roots[e]);const n=ir(0,t,i,s);return Hs.clearBuffer(),n}function ir(t,e,i,s,n=null){const{float32Array:r,uint16Array:o,uint32Array:a}=Hs;let l=2*t;null===n&&(i.boundingBox||i.computeBoundingBox(),Jn.set(i.boundingBox.min,i.boundingBox.max,s),n=Jn);if(!Us(l,o)){const o=t+8,l=a[t+6];ds(o,r,qn);if(n.intersectsBox(qn)&&ir(o,e,i,s,n))return!0;ds(l,r,qn);return!!(n.intersectsBox(qn)&&ir(l,e,i,s,n))}{const n=e.geometry,h=n.index,c=n.attributes.position,d=i.index,u=i.attributes.position,p=Ls(t,a),f=Rs(l,o);if(Kn.copy(s).invert(),i.boundsTree){ds(t,r,tr),tr.matrix.copy(Kn),tr.needsUpdate=!0;return i.boundsTree.shapecast({intersectsBounds:t=>tr.intersectsBox(t),intersectsTriangle:t=>{t.a.applyMatrix4(s),t.b.applyMatrix4(s),t.c.applyMatrix4(s),t.needsUpdate=!0;for(let i=p,s=f+p;i<s;i++)if(un(Qn,3*e.resolveTriangleIndex(i),h,c),Qn.needsUpdate=!0,t.intersectsTriangle(Qn))return!0;return!1}})}for(let t=p,i=f+p;t<i;t++){const i=e.resolveTriangleIndex(t);un(Gn,3*i,h,c),Gn.a.applyMatrix4(Kn),Gn.b.applyMatrix4(Kn),Gn.c.applyMatrix4(Kn),Gn.needsUpdate=!0;for(let t=0,e=d.count;t<e;t+=3)if(un(Qn,t,d,u),Qn.needsUpdate=!0,Gn.intersectsTriangle(Qn))return!0}}}const sr=new f,nr=new zs,rr=new zs,or=new l,ar=new l,lr=new l,hr=new l;function cr(t,e,i,s={},n={},r=0,o=1/0){e.boundingBox||e.computeBoundingBox(),nr.set(e.boundingBox.min,e.boundingBox.max,i),nr.needsUpdate=!0;const a=t.geometry,l=a.attributes.position,h=a.index,c=e.attributes.position,d=e.index,u=Ns.getPrimitive(),p=Ns.getPrimitive();let f=or,m=ar,g=null,_=null;n&&(g=lr,_=hr);let y=1/0,w=null,v=null;return sr.copy(i).invert(),rr.matrix.copy(sr),t.shapecast({boundsTraverseOrder:t=>nr.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o&&(e&&(rr.min.copy(t.min),rr.max.copy(t.max),rr.needsUpdate=!0),!0),intersectsRange:(s,n)=>{if(e.boundsTree){const a=e.boundsTree;return a.shapecast({boundsTraverseOrder:t=>rr.distanceToBox(t),intersectsBounds:(t,e,i)=>i<y&&i<o,intersectsRange:(e,o)=>{for(let b=e,x=e+o;b<x;b++){const e=a.resolveTriangleIndex(b);un(p,3*e,d,c),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=s,i=s+n;e<i;e++){const i=t.resolveTriangleIndex(e);un(u,3*i,h,l),u.needsUpdate=!0;const s=u.distanceToTriangle(p,f,g);if(s<y&&(m.copy(f),_&&_.copy(g),y=s,w=e,v=b),s<r)return!0}}}})}for(let o=0,a=as(e);o<a;o++){un(p,3*o,d,c),p.a.applyMatrix4(i),p.b.applyMatrix4(i),p.c.applyMatrix4(i),p.needsUpdate=!0;for(let e=s,i=s+n;e<i;e++){const i=t.resolveTriangleIndex(e);un(u,3*i,h,l),u.needsUpdate=!0;const s=u.distanceToTriangle(p,f,g);if(s<y&&(m.copy(f),_&&_.copy(g),y=s,w=e,v=o),s<r)return!0}}}}),Ns.releasePrimitive(u),Ns.releasePrimitive(p),y===1/0?null:(s.point?s.point.copy(m):s.point=m.clone(),s.distance=y,s.faceIndex=w,n&&(n.point?n.point.copy(_):n.point=_.clone(),n.point.applyMatrix4(sr),m.applyMatrix4(sr),n.distance=m.sub(n.point).length(),n.faceIndex=v),s)}const dr=new Hs.constructor,ur=new Hs.constructor,pr=new Ms(()=>new m),fr=new m,mr=new m,gr=new m,_r=new m;let yr=!1;function wr(t,e,i,s,n,r=0,o=0,a=0,l=0,h=null,c=!1){let d,u;c?(d=ur,u=dr):(d=dr,u=ur);const p=d.float32Array,f=d.uint32Array,m=d.uint16Array,g=u.float32Array,_=u.uint32Array,y=u.uint16Array,w=2*e,v=Us(2*t,m),b=Us(w,y);let x=!1;if(b&&v)x=c?n(Ls(e,_),Rs(2*e,y),Ls(t,f),Rs(2*t,m),l,o+e,a,r+t):n(Ls(t,f),Rs(2*t,m),Ls(e,_),Rs(2*e,y),a,r+t,l,o+e);else if(b){const h=pr.getPrimitive();ds(e,g,h),h.applyMatrix4(i);const d=Fs(t),u=Vs(t,f);ds(d,p,fr),ds(u,p,mr);const m=h.intersectsBox(fr),_=h.intersectsBox(mr);x=m&&wr(e,d,s,i,n,o,r,l,a+1,h,!c)||_&&wr(e,u,s,i,n,o,r,l,a+1,h,!c),pr.releasePrimitive(h)}else{const d=Fs(e),u=Vs(e,_);ds(d,g,gr),ds(u,g,_r);const m=h.intersectsBox(gr),y=h.intersectsBox(_r);if(m&&y)x=wr(t,d,i,s,n,r,o,a,l+1,h,c)||wr(t,u,i,s,n,r,o,a,l+1,h,c);else if(m)if(v)x=wr(t,d,i,s,n,r,o,a,l+1,h,c);else{const e=pr.getPrimitive();e.copy(gr).applyMatrix4(i);const h=Fs(t),u=Vs(t,f);ds(h,p,fr),ds(u,p,mr);const m=e.intersectsBox(fr),g=e.intersectsBox(mr);x=m&&wr(d,h,s,i,n,o,r,l,a+1,e,!c)||g&&wr(d,u,s,i,n,o,r,l,a+1,e,!c),pr.releasePrimitive(e)}else if(y)if(v)x=wr(t,u,i,s,n,r,o,a,l+1,h,c);else{const e=pr.getPrimitive();e.copy(_r).applyMatrix4(i);const h=Fs(t),d=Vs(t,f);ds(h,p,fr),ds(d,p,mr);const m=e.intersectsBox(fr),g=e.intersectsBox(mr);x=m&&wr(u,h,s,i,n,o,r,l,a+1,e,!c)||g&&wr(u,d,s,i,n,o,r,l,a+1,e,!c),pr.releasePrimitive(e)}}return x}const vr=new zs,br=new m;class xr{static serialize(t,e={}){e={cloneBuffers:!0,...e};const i=t.geometry,s=t._roots,n=t._indirectBuffer,r=i.getIndex();let o;return o=e.cloneBuffers?{roots:s.map(t=>t.slice()),index:r.array.slice(),indirectBuffer:n?n.slice():null}:{roots:s,index:r.array,indirectBuffer:n},o}static deserialize(t,e,i={}){i={setIndex:!0,indirect:Boolean(t.indirectBuffer),...i};const{index:s,roots:n,indirectBuffer:r}=t,o=new xr(e,{...i,[os]:!0});if(o._roots=n,o._indirectBuffer=r||null,i.setIndex){const i=e.getIndex();if(null===i){const i=new a(t.index,1,!1);e.setIndex(i)}else i.array!==s&&(i.array.set(s),i.needsUpdate=!0)}return o}get indirect(){return!!this._indirectBuffer}constructor(t,e={}){if(!t.isBufferGeometry)throw new Error("MeshBVH: Only BufferGeometries are supported.");if(t.index&&t.index.isInterleavedBufferAttribute)throw new Error("MeshBVH: InterleavedBufferAttribute is not supported for the index attribute.");if((e=Object.assign({strategy:0,maxDepth:40,maxLeafTris:10,verbose:!0,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,[os]:!1},e)).useSharedArrayBuffer&&"undefined"==typeof SharedArrayBuffer)throw new Error("MeshBVH: SharedArrayBuffer is not available.");this.geometry=t,this._roots=null,this._indirectBuffer=null,e[os]||(Ss(this,e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new m)));const{_indirectBuffer:i}=this;this.resolveTriangleIndex=e.indirect?t=>i[t]:t=>t}refit(t=null){return(this.indirect?Vn:fn)(this,t)}traverse(t,e=0){const i=this._roots[e],s=new Uint32Array(i),n=new Uint16Array(i);!function e(r,o=0){const a=2*r,l=n[a+15]===ns;if(l){const e=s[r+6],h=n[a+14];t(o,l,new Float32Array(i,4*r,6),e,h)}else{const n=r+8,a=s[r+6],h=s[r+7];t(o,l,new Float32Array(i,4*r,6),h)||(e(n,o+1),e(a,o+1))}}(0)}raycast(t,e=y){const i=this._roots,s=this.geometry,n=[],r=e.isMaterial,o=Array.isArray(e),a=s.groups,l=r?e.side:e,h=this.indirect?Zn:wn;for(let s=0,r=i.length;s<r;s++){const i=o?e[a[s].materialIndex].side:l,r=n.length;if(h(this,s,i,t,n),o){const t=a[s].materialIndex;for(let e=r,i=n.length;e<i;e++)n[e].face.materialIndex=t}}return n}raycastFirst(t,e=y){const i=this._roots,s=this.geometry,n=e.isMaterial,r=Array.isArray(e);let o=null;const a=s.groups,l=n?e.side:e,h=this.indirect?Wn:Tn;for(let s=0,n=i.length;s<n;s++){const i=h(this,s,r?e[a[s].materialIndex].side:l,t);null!=i&&(null==o||i.distance<o.distance)&&(o=i,r&&(i.face.materialIndex=a[s].materialIndex))}return o}intersectsGeometry(t,e){let i=!1;const s=this._roots,n=this.indirect?er:kn;for(let r=0,o=s.length;r<o&&(i=n(this,r,t,e),!i);r++);return i}shapecast(t){const e=Ns.getPrimitive(),i=this.indirect?_n:pn;let{boundsTraverseOrder:s,intersectsBounds:n,intersectsRange:r,intersectsTriangle:o}=t;if(r&&o){const t=r;r=(s,n,r,a,l)=>!!t(s,n,r,a,l)||i(s,n,this,o,r,a,e)}else r||(r=o?(t,s,n,r)=>i(t,s,this,o,n,r,e):(t,e,i)=>i);let a=!1,l=0;const h=this._roots;for(let t=0,e=h.length;t<e;t++){const e=h[t];if(a=qs(this,t,n,r,s,l),a)break;l+=e.byteLength}return Ns.releasePrimitive(e),a}bvhcast(t,e,i){let{intersectsRanges:s,intersectsTriangles:n}=i;const r=Ns.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?t=>{const e=this.resolveTriangleIndex(t);un(r,3*e,o,a)}:t=>{un(r,3*t,o,a)},h=Ns.getPrimitive(),c=t.geometry.index,d=t.geometry.attributes.position,u=t.indirect?e=>{const i=t.resolveTriangleIndex(e);un(h,3*i,c,d)}:t=>{un(h,3*t,c,d)};if(n){const t=(t,i,s,o,a,c,d,p)=>{for(let f=s,m=s+o;f<m;f++){u(f),h.a.applyMatrix4(e),h.b.applyMatrix4(e),h.c.applyMatrix4(e),h.needsUpdate=!0;for(let e=t,s=t+i;e<s;e++)if(l(e),r.needsUpdate=!0,n(r,h,e,f,a,c,d,p))return!0}return!1};if(s){const e=s;s=function(i,s,n,r,o,a,l,h){return!!e(i,s,n,r,o,a,l,h)||t(i,s,n,r,o,a,l,h)}}else s=t}return function(t,e,i,s){if(yr)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");yr=!0;const n=t._roots,r=e._roots;let o,a=0,l=0;const h=(new f).copy(i).invert();for(let t=0,e=n.length;t<e;t++){dr.setBuffer(n[t]),l=0;const e=pr.getPrimitive();ds(Zs(0),dr.float32Array,e),e.applyMatrix4(h);for(let n=0,c=r.length;n<c&&(ur.setBuffer(r[t]),o=wr(0,0,i,h,s,a,l,0,0,e),ur.clearBuffer(),l+=r[n].length,!o);n++);if(pr.releasePrimitive(e),dr.clearBuffer(),a+=n[t].length,o)break}return yr=!1,o}(this,t,e,s)}intersectsBox(t,e){return vr.set(t.min,t.max,e),vr.needsUpdate=!0,this.shapecast({intersectsBounds:t=>vr.intersectsBox(t),intersectsTriangle:t=>vr.intersectsTriangle(t)})}intersectsSphere(t){return this.shapecast({intersectsBounds:e=>t.intersectsBox(e),intersectsTriangle:e=>e.intersectsSphere(t)})}closestPointToGeometry(t,e,i={},s={},n=0,r=1/0){return(this.indirect?cr:Fn)(this,t,e,i,s,n,r)}closestPointToPoint(t,e={},i=0,s=1/0){return function(t,e,i={},s=0,n=1/0){const r=s*s,o=n*n;let a=1/0,l=null;if(t.shapecast({boundsTraverseOrder:t=>(Qs.copy(e).clamp(t.min,t.max),Qs.distanceToSquared(e)),intersectsBounds:(t,e,i)=>i<a&&i<o,intersectsTriangle:(t,i)=>{t.closestPointToPoint(e,Qs);const s=e.distanceToSquared(Qs);return s<a&&(Ks.copy(Qs),a=s,l=i),s<r}}),a===1/0)return null;const h=Math.sqrt(a);return i.point?i.point.copy(Ks):i.point=Ks.clone(),i.distance=h,i.faceIndex=l,i}(this,t,e,i,s)}getBoundingBox(t){t.makeEmpty();return this._roots.forEach(e=>{ds(0,new Float32Array(e),br),t.union(br)}),t}}function Tr(t,e,i){return null===t?null:(t.point.applyMatrix4(e.matrixWorld),t.distance=t.point.distanceTo(i.ray.origin),t.object=e,t.distance<i.near||t.distance>i.far?null:t)}const Er=new w,Cr=new f,Sr=v.prototype.raycast;function Ar(t,e){if(this.geometry.boundsTree){if(void 0===this.material)return;Cr.copy(this.matrixWorld).invert(),Er.copy(t.ray).applyMatrix4(Cr);const i=this.geometry.boundsTree;if(!0===t.firstHitOnly){const s=Tr(i.raycastFirst(Er,this.material),this,t);s&&e.push(s)}else{const s=i.raycast(Er,this.material);for(let i=0,n=s.length;i<n;i++){const n=Tr(s[i],this,t);n&&e.push(n)}}}else Sr.call(this,t,e)}function Or(t){return this.boundsTree=new xr(this,t),this.boundsTree}function Pr(){this.boundsTree=null}const Ir=class t{constructor(){e(this,"onDisposed",new L),e(this,"list",new s),e(this,"enabled",!1),e(this,"_clock"),e(this,"onInit",new L),e(this,"update",()=>{if(!this.enabled)return;const t=this._clock.getDelta();for(const[e,i]of this.list)i.enabled&&i.isUpdateable()&&i.update(t);requestAnimationFrame(this.update)}),this._clock=new o.Clock,t.setupBVH()}add(t,e){if(this.list.has(t))throw new Error("You're trying to add a component that already exists in the components instance. Use Components.get() instead.");G.validate(t),this.list.set(t,e)}get(t){var e;const i=t.uuid;if(!this.list.has(i)){const s=new t(this);return(null==(e=s.isDisposeable)?void 0:e.call(s))&&s.onDisposed.add(()=>this.list.delete(i)),this.list.has(i)||this.add(i,s),s}return this.list.get(i)}init(){this.enabled=!0;for(const[t,e]of this.list.entries())e.enabled=!0;this._clock.start(),this.update(),this.onInit.trigger()}dispose(){let t;this.enabled=!1;for(const[e,i]of this.list)i.enabled=!1,e!==Oe.uuid?i.isDisposeable()&&i.dispose():t=i;null==t||t.dispose(),this._clock.stop(),this.onDisposed.trigger()}static setupBVH(){o.BufferGeometry.prototype.computeBoundsTree=Or,o.BufferGeometry.prototype.disposeBoundsTree=Pr,o.Mesh.prototype.raycast=Ar}};e(Ir,"release","2.4.3");let kr=Ir;class Dr{constructor(t){e(this,"enabled",!1),e(this,"id","FirstPerson"),this.camera=t}set(t){if(this.enabled=t,t){if("Perspective"!==this.camera.projection.current)return void this.camera.set("Orbit");this.setupFirstPersonCamera()}}setupFirstPersonCamera(){const t=this.camera.controls,e=new o.Vector3;t.distance--,t.getPosition(e),t.minDistance=1,t.maxDistance=1,t.distance=1,t.moveTo(e.x,e.y,e.z),t.truckSpeed=50,t.mouseButtons.wheel=qi.ACTION.DOLLY,t.touches.two=qi.ACTION.TOUCH_ZOOM_TRUCK}}class zr{constructor(t){e(this,"enabled",!0),e(this,"id","Orbit"),this.camera=t,this.activateOrbitControls()}set(t){this.enabled=t,t&&this.activateOrbitControls()}activateOrbitControls(){const t=this.camera.controls;t.minDistance=1,t.maxDistance=300;const e=new o.Vector3;t.getPosition(e);const i=e.length();t.distance=i,t.truckSpeed=2;const{rotation:s}=this.camera.three,n=new o.Vector3(0,0,-1).applyEuler(s),r=e.addScaledVector(n,i);t.moveTo(r.x,r.y,r.z)}}class Mr{constructor(t){e(this,"enabled",!1),e(this,"id","Plan"),e(this,"mouseAction1"),e(this,"mouseAction2"),e(this,"mouseInitialized",!1),e(this,"defaultAzimuthSpeed"),e(this,"defaultPolarSpeed"),this.camera=t,this.defaultAzimuthSpeed=t.controls.azimuthRotateSpeed,this.defaultPolarSpeed=t.controls.polarRotateSpeed}set(t){this.enabled=t;const e=this.camera.controls;e.azimuthRotateSpeed=t?0:this.defaultAzimuthSpeed,e.polarRotateSpeed=t?0:this.defaultPolarSpeed,this.mouseInitialized||(this.mouseAction1=e.touches.one,this.mouseAction2=e.touches.two,this.mouseInitialized=!0),t?(e.mouseButtons.left=qi.ACTION.TRUCK,e.touches.one=qi.ACTION.TOUCH_TRUCK,e.touches.two=qi.ACTION.TOUCH_ZOOM):(e.mouseButtons.left=qi.ACTION.ROTATE,e.touches.one=this.mouseAction1,e.touches.two=this.mouseAction2)}}class Br{constructor(t){e(this,"onChanged",new L),e(this,"current","Perspective"),e(this,"camera"),e(this,"matchOrthoDistanceEnabled",!1),e(this,"_component"),e(this,"_previousDistance",-1),this._component=t,this.camera=t.three}async set(t){this.current!==t&&("Orthographic"===t?this.setOrthoCamera():await this.setPerspectiveCamera(),this.onChanged.trigger(this.camera))}async toggle(){const t="Perspective"===this.current?"Orthographic":"Perspective";await this.set(t)}setOrthoCamera(){if(null===this._component.mode)return;if("FirstPerson"===this._component.mode.id)return;this._previousDistance=this._component.controls.distance,this._component.controls.distance=200;const t=this.getPerspectiveDims();if(!t)return;const{width:e,height:i}=t;this.setupOrthoCamera(i,e),this.camera=this._component.threeOrtho,this.current="Orthographic"}getPerspectiveDims(){const t=this._component.currentWorld;if(!t||!t.renderer)return null;const e=new o.Vector3;this._component.threePersp.getWorldDirection(e);const i=new o.Vector3;this._component.controls.getTarget(i);const s=i.clone().sub(this._component.threePersp.position).dot(e),n=t.renderer.getSize(),r=n.x/n.y,a=this._component.threePersp,l=2*s*Math.atan(a.fov*(Math.PI/180)/2);return{width:l*r,height:l}}setupOrthoCamera(t,e){this._component.controls.mouseButtons.wheel=qi.ACTION.ZOOM,this._component.controls.mouseButtons.middle=qi.ACTION.ZOOM;const i=this._component.threePersp,s=this._component.threeOrtho;s.zoom=1,s.left=e/-2,s.right=e/2,s.top=t/2,s.bottom=t/-2,s.updateProjectionMatrix(),s.position.copy(i.position),s.quaternion.copy(i.quaternion),this._component.controls.camera=s}getDistance(){const t=this._component.threePersp,e=this._component.threeOrtho;return(e.top-e.bottom)/e.zoom/(2*Math.atan(t.fov*(Math.PI/180)/2))}async setPerspectiveCamera(){this._component.controls.mouseButtons.wheel=qi.ACTION.DOLLY,this._component.controls.mouseButtons.middle=qi.ACTION.DOLLY;const t=this._component.threePersp,e=this._component.threeOrtho;t.position.copy(e.position),t.quaternion.copy(e.quaternion),this._component.controls.mouseButtons.wheel=qi.ACTION.DOLLY,this.matchOrthoDistanceEnabled?this._component.controls.distance=this.getDistance():this._component.controls.distance=this._previousDistance,await this._component.controls.zoomTo(1),t.updateProjectionMatrix(),this._component.controls.camera=t,this.camera=t,this.current="Perspective"}}class Nr extends Gi{constructor(t){super(t),e(this,"projection"),e(this,"threeOrtho"),e(this,"threePersp"),e(this,"_userInputButtons",{}),e(this,"_frustumSize",50),e(this,"_navigationModes",new Map),e(this,"_mode",null),e(this,"previousSize",null),this.threePersp=this.three,this.threeOrtho=this.newOrthoCamera(),this.projection=new Br(this),this.onAspectUpdated.add(()=>{this.setOrthoPerspCameraAspect()}),this.projection.onChanged.add(t=>{this.three=t,this.updateAspect()}),this.worlds.onItemSet.add(()=>{this._navigationModes.clear(),this._navigationModes.set("Orbit",new zr(this)),this._navigationModes.set("FirstPerson",new Dr(this)),this._navigationModes.set("Plan",new Mr(this)),this._mode=this._navigationModes.get("Orbit"),this.mode.set(!0,{preventTargetAdjustment:!0}),this.currentWorld&&this.currentWorld.renderer&&(this.previousSize=this.currentWorld.renderer.getSize().clone())}),this.worlds.onItemDeleted.add(()=>{this._navigationModes.clear()})}get mode(){if(!this._mode)throw new Error("Mode not found, camera not initialized");return this._mode}dispose(){super.dispose(),this.threeOrtho.removeFromParent()}set(t){if(null!==this.mode&&this.mode.id!==t){if(this.mode.set(!1),!this._navigationModes.has(t))throw new Error("The specified mode does not exist!");this._mode=this._navigationModes.get(t),this.mode.set(!0)}}async fit(t,e=1.5){if(!this.enabled)return;const i=Number.MAX_VALUE,s=Number.MIN_VALUE,n=new o.Vector3(i,i,i),r=new o.Vector3(s,s,s);for(const e of t){const t=(new o.Box3).setFromObject(e);t.min.x<n.x&&(n.x=t.min.x),t.min.y<n.y&&(n.y=t.min.y),t.min.z<n.z&&(n.z=t.min.z),t.max.x>r.x&&(r.x=t.max.x),t.max.y>r.y&&(r.y=t.max.y),t.max.z>r.z&&(r.z=t.max.z)}const a=new o.Box3(n,r),l=this.components.get(Oe);if(l.initialized)for(const[,t]of l.list){const e=t.box;e.min.x<n.x&&(n.x=e.min.x),e.min.y<n.y&&(n.y=e.min.y),e.min.z<n.z&&(n.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 h=new o.Vector3;a.getSize(h);const c=new o.Vector3;a.getCenter(c);const d=Math.max(h.x,h.y,h.z)*e,u=new o.Sphere(c,d);await this.controls.fitToSphere(u,!0)}setUserInput(t){t?this.enableUserInput():this.disableUserInput()}addCustomNavigationMode(t){this._navigationModes.set(t.id,t)}disableUserInput(){this._userInputButtons.left=this.controls.mouseButtons.left,this._userInputButtons.right=this.controls.mouseButtons.right,this._userInputButtons.middle=this.controls.mouseButtons.middle,this._userInputButtons.wheel=this.controls.mouseButtons.wheel,this.controls.mouseButtons.left=0,this.controls.mouseButtons.right=0,this.controls.mouseButtons.middle=0,this.controls.mouseButtons.wheel=0}enableUserInput(){0!==Object.keys(this._userInputButtons).length&&(this.controls.mouseButtons.left=this._userInputButtons.left,this.controls.mouseButtons.right=this._userInputButtons.right,this.controls.mouseButtons.middle=this._userInputButtons.middle,this.controls.mouseButtons.wheel=this._userInputButtons.wheel)}newOrthoCamera(){const t=window.innerWidth/window.innerHeight;return new o.OrthographicCamera(this._frustumSize*t/-2,this._frustumSize*t/2,this._frustumSize/2,this._frustumSize/-2,.1,1e3)}setOrthoPerspCameraAspect(){if(!this.currentWorld||!this.currentWorld.renderer)return;if(!this.previousSize)return;const t=this.currentWorld.renderer.getSize(),e=this.threeOrtho.top,i=this.threeOrtho.right,s=e*(t.y/this.previousSize.y),n=i*(t.x/this.previousSize.x);this.threeOrtho.left=-n,this.threeOrtho.right=n,this.threeOrtho.top=s,this.threeOrtho.bottom=-s,this.threeOrtho.updateProjectionMatrix(),this.previousSize.copy(t)}}function Ur(t){throw new Error('Could not dynamically require "'+t+'". Please configure the dynamicRequireTargets or/and ignoreDynamicRequires option of @rollup/plugin-commonjs appropriately for this require call to work.')}var Lr={exports:{}};
1
+ 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);import*as s from"@thatopen/fragments";import{DataMap as i,FragmentsModels as r,DataSet as n}from"@thatopen/fragments";import*as o from"three";import{Box3 as a,Matrix4 as l,BufferAttribute as h,Vector3 as u,Line3 as c,Plane as d,Vector2 as p,Triangle as m,BackSide as f,DoubleSide as g,REVISION as y,Ray as b,FrontSide as x,Mesh as _,LineSegments as w,LineLoop as v,Line as T,Points as S,Sphere as M,BatchedMesh as A,OrthographicCamera as N,WebGLRenderTarget as E,Scene as C,Color as R,ShaderMaterial as P,Vector4 as B,NoBlending as I,GLSL3 as D,MathUtils as L,BufferGeometry as F,Controls as O,Quaternion as z,Raycaster as V,Object3D as k,MeshBasicMaterial as U,LineBasicMaterial as G,CylinderGeometry as j,BoxGeometry as $,Float32BufferAttribute as W,OctahedronGeometry as H,TorusGeometry as q,SphereGeometry as X,Euler as Y,PlaneGeometry as Z}from"three";import*as Q from"web-ifc";import K from"camera-controls";class J{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 ee{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}}class te{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 se extends te{}class ie extends te{constructor(e){super(e),t(this,"worlds",new i),t(this,"onWorldChanged",new J),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 re extends ie{constructor(){super(...arguments),t(this,"hasCameraControls",()=>"controls"in this)}}class ne extends ie{constructor(){super(...arguments),t(this,"onAfterUpdate",new J),t(this,"onBeforeUpdate",new J),t(this,"onDisposed",new J),t(this,"onResize",new J),t(this,"onClippingPlanesUpdated",new J),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 oe=class e extends se{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(oe,"uuid","76e9cd8e-ad8f-4753-9ef6-cbc60f7247fe");let ae=oe;class le extends ie{constructor(e){super(e),t(this,"onDisposed",new J),t(this,"directionalLights",new Map),t(this,"ambientLights",new Map)}dispose(){const e=this.components.get(ae);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 he extends Set{constructor(e){super(e),t(this,"onItemAdded",new J),t(this,"onItemDeleted",new J),t(this,"onCleared",new J),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 J),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 ue=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(ue,"_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(ue,"_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 ce=ue;const de=":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",pe=new RegExp("^"+("["+de+"]["+(de+"\\-.\\d\\u00B7\\u0300-\\u036F\\u203F-\\u2040")+"]*")+"$");function me(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 fe=function(e){const t=pe.exec(e);return!(null==t)};const ge={allowBooleanAttributes:!1,unpairedTags:[]};function ye(e){return" "===e||"\t"===e||"\n"===e||"\r"===e}function be(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 Ae("InvalidXml","XML declaration allowed only at the start of the document.",Ce(e,t));if("?"==e[t]&&">"==e[t+1]){t++;break}continue}return t}function xe(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 _e='"',we="'";function ve(e,t){let s="",i="",r=!1;for(;t<e.length;t++){if(e[t]===_e||e[t]===we)""===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 Te=new RegExp("(\\s*)([^\\s=]+)(\\s*=)?(\\s*(['\"])(([\\s\\S])*?)\\5)?","g");function Se(e,t){const s=me(e,Te),i={};for(let e=0;e<s.length;e++){if(0===s[e][1].length)return Ae("InvalidAttr","Attribute '"+s[e][2]+"' has no space in starting.",Re(s[e]));if(void 0!==s[e][3]&&void 0===s[e][4])return Ae("InvalidAttr","Attribute '"+s[e][2]+"' is without value.",Re(s[e]));if(void 0===s[e][3]&&!t.allowBooleanAttributes)return Ae("InvalidAttr","boolean attribute '"+s[e][2]+"' is not allowed.",Re(s[e]));const r=s[e][2];if(!Ne(r))return Ae("InvalidAttr","Attribute '"+r+"' is an invalid name.",Re(s[e]));if(i.hasOwnProperty(r))return Ae("InvalidAttr","Attribute '"+r+"' is repeated.",Re(s[e]));i[r]=1}return!0}function Me(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 Ae(e,t,s){return{err:{code:e,msg:t,line:s.line||s,col:s.col}}}function Ne(e){return fe(e)}function Ee(e){return fe(e)}function Ce(e,t){const s=e.substring(0,t).split(/\r?\n/);return{line:s.length,col:s[s.length-1].length+1}}function Re(e){return e.startIndex+e[1].length}const Pe={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 Be(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}:Be(!0)}const Ie=function(e){const t=Object.assign({},Pe,e);return t.processEntities=Be(t.processEntities),t};let De;De="function"!=typeof Symbol?"@@xmlMetadata":Symbol("XML Node Metadata");class Le{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][De]={startIndex:t})}static getMetaDataSymbol(){return De}}class Fe{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&&ze(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&&ze(e,"!ELEMENT",t)){t+=8;const{index:s}=this.readElementExp(e,t+1);t=s}else if(r&&ze(e,"!ATTLIST",t))t+=8;else if(r&&ze(e,"!NOTATION",t)){t+=9;const{index:s}=this.readNotationExp(e,t+1,this.suppressValidationErr);t=s}else{if(!ze(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=Oe(e,t);let s="";for(;t<e.length&&!/\s/.test(e[t])&&'"'!==e[t]&&"'"!==e[t];)s+=e[t],t++;if(Ve(s),t=Oe(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=Oe(e,t);let s="";for(;t<e.length&&!/\s/.test(e[t]);)s+=e[t],t++;!this.suppressValidationErr&&Ve(s),t=Oe(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=Oe(e,t);let r=null,n=null;if("PUBLIC"===i)[t,r]=this.readIdentifierVal(e,t,"publicIdentifier"),'"'!==e[t=Oe(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=Oe(e,t);let s="";for(;t<e.length&&!/\s/.test(e[t]);)s+=e[t],t++;if(!this.suppressValidationErr&&!fe(s))throw new Error(`Invalid element name: "${s}"`);let i="";if("E"===e[t=Oe(e,t)]&&ze(e,"MPTY",t))t+=4;else if("A"===e[t]&&ze(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=Oe(e,t);let s="";for(;t<e.length&&!/\s/.test(e[t]);)s+=e[t],t++;Ve(s),t=Oe(e,t);let i="";for(;t<e.length&&!/\s/.test(e[t]);)i+=e[t],t++;if(!Ve(i))throw new Error(`Invalid attribute name: "${i}"`);t=Oe(e,t);let r="";if("NOTATION"===e.substring(t,t+8).toUpperCase()){if(r="NOTATION","("!==e[t=Oe(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(),!Ve(i))throw new Error(`Invalid notation name: "${i}"`);s.push(i),"|"===e[t]&&(t++,t=Oe(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=Oe(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 Oe=(e,t)=>{for(;t<e.length&&/\s/.test(e[t]);)t++;return t};function ze(e,t,s){for(let i=0;i<t.length;i++)if(t[i]!==e[s+i+1])return!1;return!0}function Ve(e){if(fe(e))return e;throw new Error(`Invalid entity name ${e}`)}const ke=/^[-+]?0x[a-fA-F0-9]+$/,Ue=/^([\-\+])?(0*)([0-9]*(\.[0-9]*)?)$/,Ge={hex:!0,leadingZeros:!0,decimalPoint:".",eNotation:!0};function je(e,t={}){if(t=Object.assign({},Ge,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&&ke.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($e);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=Ue.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 $e=/^([-+])?(0*)(\d*(\.\d*)?[eE][-\+]?\d+)$/;function We(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 He{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)=>at(t,10,"&#")},num_hex:{regex:/&#x([0-9a-fA-F]{1,6});/g,val:(e,t)=>at(t,16,"&#x")}},this.addExternalEntities=qe,this.parseXml=Ke,this.parseTextData=Xe,this.resolveNameSpace=Ye,this.buildAttributesMap=Qe,this.isItStopNode=st,this.replaceEntitiesValue=et,this.readStopNodeData=nt,this.saveTextToParentTag=tt,this.addChild=Je,this.ignoreAttributesFn=We(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 qe(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 Xe(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 ot(e,this.options.parseTagValue,this.options.numberParseOptions);return e.trim()===e?ot(e,this.options.parseTagValue,this.options.numberParseOptions):e}}function Ye(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 Ze=new RegExp("([^\\s=]+)\\s*(=\\s*(['\"])([\\s\\S]*?)\\3)?","gm");function Qe(e,t,s){if(!0!==this.options.ignoreAttributes&&"string"==typeof e){const i=me(e,Ze),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:ot(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 Ke=function(e){e=e.replace(/\r\n?/g,"\n");const t=new Le("!xml");let s=t,i="",r="";this.entityExpansionCount=0,this.currentExpandedLength=0;const n=new Fe(this.options.processEntities);for(let o=0;o<e.length;o++){if("<"===e[o])if("/"===e[o+1]){const t=it(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=rt(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 Le(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=it(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=it(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=rt(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 Le(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 Le(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 Le(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 Je(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 et=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 tt(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 st(e,t,s,i){return!(!t||!t.has(i))||!(!e||!e.has(s))}function it(e,t,s,i){const r=e.indexOf(t,s);if(-1===r)throw new Error(i);return r+t.length-1}function rt(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 nt(e,t,s){const i=s;let r=1;for(;s<e.length;s++)if("<"===e[s])if("/"===e[s+1]){const n=it(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=it(e,"?>",s+1,"StopNode is not closed.")}else if("!--"===e.substr(s+1,3)){s=it(e,"--\x3e",s+3,"StopNode is not closed.")}else if("!["===e.substr(s+1,2)){s=it(e,"]]>",s,"StopNode is not closed.")-2}else{const i=rt(e,s,">");if(i){(i&&i.tagName)===t&&"/"!==i.tagExp[i.tagExp.length-1]&&r++,s=i.closeIndex}}}function ot(e,t,s){if(t&&"string"==typeof e){const t=e.trim();return"true"===t||"false"!==t&&je(e,s)}return void 0!==e?e:""}function at(e,t,s){const i=Number.parseInt(e,t);return i>=0&&i<=1114111?String.fromCodePoint(i):s+e+";"}const lt=Le.getMetaDataSymbol();function ht(e,t){return ut(e,t)}function ut(e,t,s){let i;const r={};for(let n=0;n<e.length;n++){const o=e[n],a=ct(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=ut(o[a],t,l);const s=pt(e,t);void 0!==o[lt]&&(e[lt]=o[lt]),o[":@"]?dt(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 ct(e){const t=Object.keys(e);for(let e=0;e<t.length;e++){const s=t[e];if(":@"!==s)return s}}function dt(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 pt(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 mt{constructor(e){this.externalEntities={},this.options=Ie(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({},ge,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=be(e,n),n.err)return n}else{if("<"!==e[n]){if(ye(e[n]))continue;return Ae("InvalidChar","char '"+e[n]+"' is not expected.",Ce(e,n))}{let o=n;if(n++,"!"===e[n]){n=xe(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--),!Ee(l)){let t;return t=0===l.trim().length?"Invalid space after '<'.":"Tag '"+l+"' is an invalid name.",Ae("InvalidTag",t,Ce(e,n))}const h=ve(e,n);if(!1===h)return Ae("InvalidAttr","Attributes for '"+l+"' have open quote.",Ce(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=Se(u,t);if(!0!==r)return Ae(r.err.code,r.err.msg,Ce(e,s+r.err.line));i=!0}else if(a){if(!h.tagClosed)return Ae("InvalidTag","Closing tag '"+l+"' doesn't have proper closing.",Ce(e,n));if(u.trim().length>0)return Ae("InvalidTag","Closing tag '"+l+"' can't have attributes or invalid starting.",Ce(e,o));if(0===s.length)return Ae("InvalidTag","Closing tag '"+l+"' has not been opened.",Ce(e,o));{const t=s.pop();if(l!==t.tagName){let s=Ce(e,t.tagStartPos);return Ae("InvalidTag","Expected closing tag '"+t.tagName+"' (opened in line "+s.line+", col "+s.col+") instead of closing tag '"+l+"'.",Ce(e,o))}0==s.length&&(r=!0)}}else{const a=Se(u,t);if(!0!==a)return Ae(a.err.code,a.err.msg,Ce(e,n-u.length+a.err.line));if(!0===r)return Ae("InvalidXml","Multiple possible root nodes found.",Ce(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=xe(e,n);continue}if("?"!==e[n+1])break;if(n=be(e,++n),n.err)return n}else if("&"===e[n]){const t=Me(e,n);if(-1==t)return Ae("InvalidChar","char '&' is not expected.",Ce(e,n));n=t}else if(!0===r&&!ye(e[n]))return Ae("InvalidXml","Extra text at the end",Ce(e,n));"<"===e[n]&&n--}}}return i?1==s.length?Ae("InvalidTag","Unclosed tag '"+s[0].tagName+"'.",Ce(e,s[0].tagStartPos)):!(s.length>0)||Ae("InvalidXml","Invalid '"+JSON.stringify(s.map(e=>e.tagName),null,4).replace(/\r?\n/g,"")+"' found.",{line:1,col:1}):Ae("InvalidXml","Start tag expected.",1)}(e,t);if(!0!==s)throw Error(`${s.err.msg}:${s.err.line}:${s.err.col}`)}const s=new He(this.options);s.addExternalEntities(this.externalEntities);const i=s.parseXml(e);return this.options.preserveOrder||void 0===i?i:ht(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 Le.getMetaDataSymbol()}}function ft(e,t){let s="";return t.format&&t.indentBy.length>0&&(s="\n"),gt(e,t,"",s)}function gt(e,t,s,i){let r="",n=!1;for(let o=0;o<e.length;o++){const a=e[o],l=yt(a);if(void 0===l)continue;let h="";if(h=0===s.length?l:`${s}.${l}`,l===t.textNodeName){let e=a[l];xt(h,t)||(e=t.tagValueProcessor(l,e),e=_t(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=bt(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}${bt(a[":@"],t)}`,d=gt(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 yt(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 bt(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=_t(r,t),!0===r&&t.suppressBooleanAttributes?s+=` ${i.substr(t.attributeNamePrefix.length)}`:s+=` ${i.substr(t.attributeNamePrefix.length)}="${r}"`}return s}function xt(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 _t(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 wt={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 vt(e){this.options=Object.assign({},wt,e),!0===this.options.ignoreAttributes||this.options.attributesGroupName?this.isAttribute=function(){return!1}:(this.ignoreAttributesFn=We(this.options.ignoreAttributes),this.attrPrefixLen=this.options.attributeNamePrefix.length,this.isAttribute=Mt),this.processTextOrObjNode=Tt,this.options.format?(this.indentate=St,this.tagEndChar=">\n",this.newLine="\n"):(this.indentate=function(){return""},this.tagEndChar=">",this.newLine="")}function Tt(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 St(e){return this.options.indentBy.repeat(e)}function Mt(e){return!(!e.startsWith(this.options.attributeNamePrefix)||e===this.options.textNodeName)&&e.substr(this.attrPrefixLen)}vt.prototype.build=function(e){return this.options.preserveOrder?ft(e,this.options):(Array.isArray(e)&&this.options.arrayNodeName&&this.options.arrayNodeName.length>1&&(e={[this.options.arrayNodeName]:e}),this.j2x(e,0,[]).val)},vt.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}},vt.prototype.buildAttrPairStr=function(e,t){return t=this.options.attributeValueProcessor(e,""+t),t=this.replaceEntitiesValue(t),this.options.suppressBooleanAttributes&&"true"===t?" "+e:" "+e+'="'+t+'"'},vt.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}},vt.prototype.closeTag=function(e){let t="";return-1!==this.options.unpairedTags.indexOf(e)?this.options.suppressUnpairedNode||(t="/"):t=this.options.suppressEmptyNode?"/":`></${e}`,t},vt.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}},vt.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 At{}t(At,"parser",new mt({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(At,"builder",new vt({attributeNamePrefix:"$",ignoreAttributes:!1,suppressBooleanAttributes:!1}));class Nt extends se{constructor(e,s){super(e),t(this,"onDisposed",new J),t(this,"onVertexFound",new J),t(this,"onVertexLost",new J),t(this,"onEnabled",new J),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(rz).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}}class Et{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=Et.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=Et.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=Et.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 Ct=class extends Map{constructor(e){super(e),t(this,"onItemSet",new J),t(this,"onItemUpdated",new J),t(this,"onItemDeleted",new J),t(this,"onCleared",new J),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 J),this.onItemUpdated.trigger({key:e,value:t})):(this.onItemSet||(this.onItemSet=new J),this.onItemSet.trigger({key:e,value:t})),i}add(e){const t=ce.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 Rt{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 Pt{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()}}class Bt{constructor(e,s,i,r){t(this,"_component"),t(this,"name"),t(this,"uuid"),this._component=e,this.name=i,this.uuid=r??ce.create();s.get(Dt).list.set(this.uuid,this)}get controls(){return Rt.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(Rt.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(Rt.isEntry(i))if("Color"===i.type){const{r:e,g:r,b:n}=i.value;t[s]={...i,value:new o.Color(e,r,n)}}else if("Vector3"===i.type){const{x:e,y:r,z:n}=i.value;t[s]={...i,value:new o.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 It=class e extends se{constructor(s){super(s),t(this,"list",new i),t(this,"enabled",!0),s.add(e.uuid,this)}};t(It,"uuid","b8c764e0-6b24-4e77-9a32-35fa728ee5b4");let Dt=It;class Lt{constructor(e){t(this,"_event"),t(this,"_position",new o.Vector2),t(this,"onDisposed",new J),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 Ft=1.25,Ot=32,zt=Math.pow(2,-24),Vt=Symbol("SKIP_GENERATION"),kt={strategy:0,maxDepth:40,maxLeafSize:10,useSharedArrayBuffer:!1,setBoundingBox:!0,onProgress:null,indirect:!1,verbose:!0,range:null,[Vt]:!1};function Ut(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 Gt(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 jt(e,t){t.set(e)}function $t(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 Wt(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 Ht(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 qt(e,t){return 65535===t[e+15]}function Xt(e,t){return t[e+6]}function Yt(e,t){return t[e+14]}function Zt(e){return e+8}function Qt(e,t){return e+8*t[e+6]}function Kt(e,t){return t[e+7]}function Jt(e){return e}function es(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 b=e[i+2],x=e[i+3],_=b-x,w=b+x;_<o&&(o=_),w>h&&(h=w),b<d&&(d=b),b>f&&(f=b);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 ts=32,ss=(e,t)=>e.candidate-t.candidate,is=new Array(ts).fill().map(()=>({count:0,bounds:new Float32Array(6),rightCacheBounds:new Float32Array(6),leftCacheBounds:new Float32Array(6),candidate:0})),rs=new Float32Array(6);class ns{constructor(){this.boundingData=new Float32Array(6)}}let os,as,ls,hs;const us=Math.pow(2,32);function cs(e){return"count"in e?1:1+cs(e.left)+cs(e.right)}function ds(e,t,s){return os=new Float32Array(s),as=new Uint32Array(s),ls=new Uint16Array(s),hs=new Uint8Array(s),ps(e,t)}function ps(e,t){const s=e/4,i=e/2,r="count"in t,n=t.boundingData;for(let e=0;e<6;e++)os[s+e]=n[e];if(r)return t.buffer?(hs.set(new Uint8Array(t.buffer),e),e+t.buffer.byteLength):(as[s+6]=t.offset,ls[i+14]=t.count,ls[i+15]=65535,e+Ot);{const{left:i,right:r,splitAxis:n}=t;let o=ps(e+Ot,i);const a=o/Ot-e/Ot;if(a>us)throw new Error("MeshBVH: Cannot store relative child node offset greater than 32 bits.");return as[s+6]=a,as[s+7]=n,ps(o,r)}}function ms(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 ns;return es(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=Gt(t),-1!==o&&(a=(t[o]+t[o+3])/2);else if(1===n)o=Gt(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=Ht(e);let l=Ft*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)/ts;if(r<8){const t=[...is];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;Wt(r,s,o)}t.sort(ss);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?Wt(i,s,n.rightCacheBounds):(Wt(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=Ht(c)/n);let m=0;0!==u&&(m=Ht(d)/n);const f=1+Ft*(p*h+m*u);f<l&&(o=e,l=f,a=i.candidate)}}else{for(let e=0;e<ts;e++){const t=is[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>=ts&&(r=31);const n=is[r];n.count++,Wt(t,s,n.bounds)}const t=is[31];jt(t.bounds,t.rightCacheBounds);for(let e=30;e>=0;e--){const t=is[e],s=is[e+1];$t(t.bounds,s.rightCacheBounds,t.rightCacheBounds)}let d=0;for(let t=0;t<31;t++){const s=is[t],i=s.count,h=s.bounds,u=is[t+1].rightCacheBounds;0!==i&&(0===d?jt(h,rs):$t(h,rs,rs)),d+=i;let c=0,p=0;0!==d&&(c=Ht(rs)/n);const m=r-d;0!==m&&(p=Ht(u)/n);const f=1+Ft*(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 ns,o=i,a=y-i;s.left=n,es(t,o,a,n.boundingData,p),e(n,o,a,p,u+1);const l=new ns,h=y,c=r-a;s.right=l,es(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 fs(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=ms(e,a,i.offset,i.count,t,o),n=cs(r),l=new s(Ot*n);return ds(0,r,l),l})}class gs{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 ys{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 bs=new ys;let xs,_s;const ws=[],vs=new gs(()=>new a);function Ts(e,t,s,i,r,n){xs=vs.getPrimitive(),_s=vs.getPrimitive(),ws.push(xs,_s),bs.setBuffer(e._roots[t]);const o=Ss(0,e.geometry,s,i,r,n);bs.clearBuffer(),vs.releasePrimitive(xs),vs.releasePrimitive(_s),ws.pop(),ws.pop();const a=ws.length;return a>0&&(_s=ws[a-1],xs=ws[a-2]),o}function Ss(e,t,s,i,r=null,n=0,o=0){const{float32Array:a,uint16Array:l,uint32Array:h}=bs;let u=2*e;if(qt(u,l)){const t=Xt(e,h),s=Yt(u,l);return Ut(e,a,xs),i(t,s,!1,o,n+e/8,xs)}{let u=function(e){const{uint16Array:t,uint32Array:s}=bs;let i=2*e;for(;!qt(i,t);)i=2*(e=Zt(e));return Xt(e,s)},c=function(e){const{uint16Array:t,uint32Array:s}=bs;let i=2*e;for(;!qt(i,t);)i=2*(e=Qt(e,s));return Xt(e,s)+Yt(i,t)};const d=Zt(e),p=Qt(e,h);let m,f,g,y,b=d,x=p;if(r&&(g=xs,y=_s,Ut(b,a,g),Ut(x,a,y),m=r(g),f=r(y),f<m)){b=p,x=d;const e=m;m=f,f=e,g=y}g||(g=xs,Ut(b,a,g));const _=s(g,qt(2*b,l),m,o+1,n+b/8);let w;if(2===_){const e=u(b);w=i(e,c(b)-e,!0,o+1,n+b/8,g)}else w=_&&Ss(b,t,s,i,r,n,o+1);if(w)return!0;y=_s,Ut(x,a,y);const v=s(y,qt(2*x,l),f,o+1,n+x/8);let T;if(2===v){const e=u(x);T=i(e,c(x)-e,!0,o+1,n+x/8,y)}else T=v&&Ss(x,t,s,i,r,n,o+1);return!!T}}const Ms=new bs.constructor,As=new bs.constructor,Ns=new gs(()=>new a),Es=new a,Cs=new a,Rs=new a,Ps=new a;let Bs=!1;function Is(e,t,s,i,r,n=0,o=0,a=0,l=0,h=null,u=!1){let c,d;u?(c=As,d=Ms):(c=Ms,d=As);const p=c.float32Array,m=c.uint32Array,f=c.uint16Array,g=d.float32Array,y=d.uint32Array,b=d.uint16Array,x=2*t,_=qt(2*e,f),w=qt(x,b);let v=!1;if(w&&_)v=u?r(Xt(t,y),Yt(2*t,b),Xt(e,m),Yt(2*e,f),l,o+t/8,a,n+e/8):r(Xt(e,m),Yt(2*e,f),Xt(t,y),Yt(2*t,b),a,n+e/8,l,o+t/8);else if(w){const h=Ns.getPrimitive();Ut(t,g,h),h.applyMatrix4(s);const c=Zt(e),d=Qt(e,m);Ut(c,p,Es),Ut(d,p,Cs);const f=h.intersectsBox(Es),y=h.intersectsBox(Cs);v=f&&Is(t,c,i,s,r,o,n,l,a+1,h,!u)||y&&Is(t,d,i,s,r,o,n,l,a+1,h,!u),Ns.releasePrimitive(h)}else{const c=Zt(t),d=Qt(t,y);Ut(c,g,Rs),Ut(d,g,Ps);const f=h.intersectsBox(Rs),b=h.intersectsBox(Ps);if(f&&b)v=Is(e,c,s,i,r,n,o,a,l+1,h,u)||Is(e,d,s,i,r,n,o,a,l+1,h,u);else if(f)if(_)v=Is(e,c,s,i,r,n,o,a,l+1,h,u);else{const t=Ns.getPrimitive();t.copy(Rs).applyMatrix4(s);const h=Zt(e),d=Qt(e,m);Ut(h,p,Es),Ut(d,p,Cs);const f=t.intersectsBox(Es),g=t.intersectsBox(Cs);v=f&&Is(c,h,i,s,r,o,n,l,a+1,t,!u)||g&&Is(c,d,i,s,r,o,n,l,a+1,t,!u),Ns.releasePrimitive(t)}else if(b)if(_)v=Is(e,d,s,i,r,n,o,a,l+1,h,u);else{const t=Ns.getPrimitive();t.copy(Ps).applyMatrix4(s);const h=Zt(e),c=Qt(e,m);Ut(h,p,Es),Ut(c,p,Cs);const f=t.intersectsBox(Es),g=t.intersectsBox(Cs);v=f&&Is(d,h,i,s,r,o,n,l,a+1,t,!u)||g&&Is(d,c,i,s,r,o,n,l,a+1,t,!u),Ns.releasePrimitive(t)}}return v}const Ds=new a,Ls=new Float32Array(6);class Fs{constructor(){this._roots=null,this.primitiveBuffer=null,this.primitiveBufferStride=null}init(e){fs(this,e={...kt,...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,Ls,0);const[e,t,i,u,c,d]=Ls;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,Ls,0);const[e,t,n,o,a,l]=Ls,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)*zt,s[f+2]=u,s[f+3]=p+(Math.abs(u)+p)*zt,s[f+4]=c,s[f+5]=m+(Math.abs(c)+m)*zt}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/Ot;for(let t=0;t<o;t++){const s=8*t;qt(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=qt(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=Zt(n),a=Qt(n,i),h=Kt(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/Ot-1;e>=0;e--){const t=8*e,s=2*t;if(qt(s,r)){const e=Xt(t,i),o=Yt(s,r);this.writePrimitiveRangeBounds(e,o,Ls,0),n.set(Ls,t)}else{const e=Zt(t),s=Qt(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=>{Ut(0,new Float32Array(t),Ds),e.union(Ds)}),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=Ts(this,e,s,i,t,l),a)break;l+=r.byteLength/Ot}return a}bvhcast(e,t,s){let{intersectsRanges:i}=s;return function(e,t,s,i){if(Bs)throw new Error("MeshBVH: Recursive calls to bvhcast not supported.");Bs=!0;const r=e._roots,n=t._roots;let o,a=0,h=0;const u=(new l).copy(s).invert();for(let e=0,t=r.length;e<t;e++){Ms.setBuffer(r[e]),h=0;const t=Ns.getPrimitive();Ut(Jt(0),Ms.float32Array,t),t.applyMatrix4(u);for(let e=0,r=n.length;e<r&&(As.setBuffer(n[e]),o=Is(0,0,s,u,i,a,h,0,0,t),As.clearBuffer(),h+=n[e].byteLength/Ot,!o);e++);if(Ns.releasePrimitive(t),Ms.clearBuffer(),a+=r[e].byteLength/Ot,o)break}return Bs=!1,o}(this,e,t,i)}}function Os(e){return e.index?e.index.count:e.attributes.position.count}function zs(e){return Os(e)/3}function Vs(e,t){if(!e.index){const s=e.attributes.position.count,i=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 h(i,1));for(let e=0;e<s;e++)i[e]=e}}function ks(e,t,s){const i=function(e,t,s){const i=Os(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=Os(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 Us extends Fs{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={...kt,...t})[Vt]||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}(ks(t,e.range,s),e.useSharedArrayBuffer);this._indirectBuffer=i}else Vs(t,e);super.init(e),!t.boundingBox&&e.setBoundingBox&&(t.boundingBox=this.getBoundingBox(new a))}getRootRanges(e){return this.indirect?[{offset:0,count:this._indirectBuffer.length}]:ks(this.geometry,e,this.primitiveStride)}raycastObject3D(){throw new Error("BVH: raycastObject3D() not implemented")}}class Gs{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}}Gs.prototype.setFromBox=function(){const e=new u;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 js=function(){const e=new u,t=new u,s=new u;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}}(),$s=function(){const e=new p,t=new u,s=new u;return function(i,r,n,o){js(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))}}}(),Ws=function(){const e=new u,t=new u,s=new d,i=new c;return function(r,n){const{radius:o,center:a}=r,{a:l,b:h,c:u}=n;i.start=l,i.end=h;if(i.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;i.start=l,i.end=u;if(i.closestPointToPoint(a,!0,e).distanceTo(a)<=o)return!0;i.start=h,i.end=u;if(i.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}}(),Hs=["x","y","z"],qs=1e-15;function Xs(e){return Math.abs(e)<qs}class Ys extends m{constructor(...e){super(...e),this.isExtendedTriangle=!0,this.satAxes=new Array(4).fill().map(()=>new u),this.satBounds=new Array(4).fill().map(()=>new Gs),this.points=[this.a,this.b,this.c],this.plane=new d,this.isDegenerateIntoSegment=!1,this.isDegenerateIntoPoint=!1,this.degenerateSegment=new c,this.needsUpdate=!0}intersectsSphere(e){return Ws(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<qs?f<qs||g<qs?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(e),this.degenerateSegment.end.copy(s)):f<qs?g<qs?this.isDegenerateIntoPoint=!0:(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(t),this.degenerateSegment.end.copy(e)):g<qs&&(this.isDegenerateIntoSegment=!0,this.degenerateSegment.start.copy(s),this.degenerateSegment.end.copy(t)),this.plane.setFromNormalAndCoplanarPoint(o,e),this.needsUpdate=!1}}Ys.prototype.closestPointToSegment=function(){const e=new u,t=new u,s=new c;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]),$s(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)}}(),Ys.prototype.intersectsTriangle=function(){const e=new Ys,t=new Gs,s=new Gs,i=new u,r=new u,n=new u,o=new u,a=new c,l=new c,h=new u,d=new p,m=new p;function f(e,r,n,a){const l=i;e.isDegenerateIntoPoint||e.isDegenerateIntoSegment?l.copy(r.plane.normal):l.copy(e.plane.normal);const h=e.satBounds,u=e.satAxes;for(let i=1;i<4;i++){const n=h[i],a=u[i];if(t.setFromPoints(a,r.points),n.isSeparated(t))return!1;if(o.copy(l).cross(a),t.setFromPoints(o,e.points),s.setFromPoints(o,r.points),t.isSeparated(s))return!1}const c=r.satBounds,d=r.satAxes;for(let i=1;i<4;i++){const n=c[i],a=d[i];if(t.setFromPoints(a,e.points),n.isSeparated(t))return!1;if(o.crossVectors(l,a),t.setFromPoints(o,e.points),s.setFromPoints(o,r.points),t.isSeparated(s))return!1}return n&&(a||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 g(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 y(e,t,s,i,r,n,o,a,l,h,u){if(r>0)g(e.c,e.a,e.b,i,t,s,l,o,a,h,u);else if(n>0)g(e.b,e.a,e.c,s,t,i,a,o,l,h,u);else if(a*l>0||0!=o)g(e.a,e.b,e.c,t,s,i,o,a,l,h,u);else if(0!=a)g(e.b,e.a,e.c,s,t,i,a,o,l,h,u);else{if(0==l)return!0;g(e.c,e.a,e.b,i,t,s,l,o,a,h,u)}return!1}function b(e,t,s,r){const n=t.degenerateSegment,o=e.plane.distanceToPoint(n.start),a=e.plane.distanceToPoint(n.end);return Xs(o)?Xs(a)?f(e,t,s,r):(s&&(s.start.copy(n.start),s.end.copy(n.start)),e.containsPoint(n.start)):Xs(a)?(s&&(s.start.copy(n.end),s.end.copy(n.end)),e.containsPoint(n.end)):null!=e.plane.intersectLine(n,i)&&(s&&(s.start.copy(i),s.end.copy(i)),e.containsPoint(i))}function x(e,t,s){const i=t.a;return!(!Xs(e.plane.distanceToPoint(i))||!e.containsPoint(i))&&(s&&(s.start.copy(i),s.end.copy(i)),!0)}function _(e,t,s){const r=e.degenerateSegment,n=t.a;return r.closestPointToPoint(n,!0,i),n.distanceToSquared(i)<1e-30&&(s&&(s.start.copy(n),s.end.copy(n)),!0)}return function(t,s=null,o=!1){this.needsUpdate&&this.update(),t.isExtendedTriangle?t.needsUpdate&&t.update():(e.copy(t),e.update(),t=e);const u=function(e,t,s,o){if(e.isDegenerateIntoSegment){if(t.isDegenerateIntoSegment){const o=e.degenerateSegment,a=t.degenerateSegment,l=r,h=n;o.delta(l),a.delta(h);const u=i.subVectors(a.start,o.start),c=l.x*h.y-l.y*h.x;if(Xs(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)&&(!!Xs(o.start.z+l.z*d-(a.start.z+h.z*p))&&(s&&(s.start.copy(o.start).addScaledVector(l,d),s.end.copy(o.start).addScaledVector(l,d)),!0))}return t.isDegenerateIntoPoint?_(e,t,s):b(t,e,s,o)}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?_(t,e,s):x(t,e,s):t.isDegenerateIntoPoint?x(e,t,s):t.isDegenerateIntoSegment?b(e,t,s,o):void 0}(this,t,s,o);if(void 0!==u)return u;const c=this.plane,p=t.plane;let g=p.distanceToPoint(this.a),w=p.distanceToPoint(this.b),v=p.distanceToPoint(this.c);Xs(g)&&(g=0),Xs(w)&&(w=0),Xs(v)&&(v=0);const T=g*w,S=g*v;if(T>0&&S>0)return!1;let M=c.distanceToPoint(t.a),A=c.distanceToPoint(t.b),N=c.distanceToPoint(t.c);Xs(M)&&(M=0),Xs(A)&&(A=0),Xs(N)&&(N=0);const E=M*A,C=M*N;if(E>0&&C>0)return!1;r.copy(c.normal),n.copy(p.normal);const R=r.cross(n);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=Hs[P],L=this.a[D],F=this.b[D],O=this.c[D],z=t.a[D],V=t.b[D],k=t.c[D];if(y(this,L,F,O,T,S,g,w,v,d,a))return f(this,t,s,o);if(y(t,z,V,k,E,C,M,A,N,m,l))return f(this,t,s,o);if(d.y<d.x){const e=d.y;d.y=d.x,d.x=e,h.copy(a.start),a.start.copy(a.end),a.end.copy(h)}if(m.y<m.x){const e=m.y;m.y=m.x,m.x=e,h.copy(l.start),l.start.copy(l.end),l.end.copy(h)}return!(d.y<m.x||m.y<d.x)&&(s&&(m.x>d.x?s.start.copy(l.start):s.start.copy(a.start),m.y<d.y?s.end.copy(l.end):s.end.copy(a.end)),!0)}}(),Ys.prototype.distanceToPoint=function(){const e=new u;return function(t){return this.closestPointToPoint(t,e),t.distanceTo(e)}}(),Ys.prototype.distanceToTriangle=function(){const e=new u,t=new u,s=["a","b","c"],i=new c,r=new c;return function(n,o=null,a=null){const l=o||a?i:null;if(this.intersectsTriangle(n,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 i;const r=s[t],l=n[r];this.closestPointToPoint(l,e),i=l.distanceToSquared(e),i<h&&(h=i,o&&o.copy(e),a&&a.copy(l));const u=this[r];n.closestPointToPoint(u,e),i=u.distanceToSquared(e),i<h&&(h=i,o&&o.copy(u),a&&a.copy(e))}for(let l=0;l<3;l++){const u=s[l],c=s[(l+1)%3];i.set(this[u],this[c]);for(let l=0;l<3;l++){const u=s[l],c=s[(l+1)%3];r.set(n[u],n[c]),$s(i,r,e,t);const d=e.distanceToSquared(t);d<h&&(h=d,o&&o.copy(e),a&&a.copy(t))}}return Math.sqrt(h)}}();class Zs{constructor(e,t,s){this.isOrientedBox=!0,this.min=new u,this.max=new u,this.matrix=new l,this.invMatrix=new l,this.points=new Array(8).fill().map(()=>new u),this.satAxes=new Array(3).fill().map(()=>new u),this.satBounds=new Array(3).fill().map(()=>new Gs),this.alignedSatBounds=new Array(3).fill().map(()=>new Gs),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}}Zs.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}}(),Zs.prototype.intersectsBox=function(){const e=new Gs;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}}(),Zs.prototype.intersectsTriangle=function(){const e=new Ys,t=new Array(3),s=new Gs,i=new Gs,r=new u;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 i=o[e],r=a[e];if(s.setFromPoints(r,t),i.isSeparated(s))return!1}const l=n.satBounds,h=n.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 n=a[e];for(let e=0;e<4;e++){const o=h[e];if(r.crossVectors(n,o),s.setFromPoints(r,t),i.setFromPoints(r,u),s.isSeparated(i))return!1}}return!0}}(),Zs.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}}(),Zs.prototype.distanceToPoint=function(){const e=new u;return function(t){return this.closestPointToPoint(t,e),t.distanceTo(e)}}(),Zs.prototype.distanceToBox=function(){const e=["x","y","z"],t=new Array(12).fill().map(()=>new c),s=new Array(12).fill().map(()=>new c),i=new u,r=new u;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,i),n.closestPointToPoint(i,r),a&&a.copy(i),l&&l.copy(r)),0;const h=o*o,u=n.min,c=n.max,d=this.points;let p=1/0;for(let e=0;e<8;e++){const t=d[e];r.copy(t).clamp(u,c);const s=t.distanceToSquared(r);if(s<p&&(p=s,a&&a.copy(t),l&&l.copy(r),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],b=s[m],x=b.start,_=b.end;x[f]=u[f],x[g]=r?u[g]:c[g],x[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++){r.x=e?c.x:u.x,r.y=t?c.y:u.y,r.z=s?c.z:u.z,this.closestPointToPoint(r,i);const n=r.distanceToSquared(i);if(n<p&&(p=n,a&&a.copy(i),l&&l.copy(r),n<h))return Math.sqrt(n)}for(let e=0;e<12;e++){const n=t[e];for(let e=0;e<12;e++){const t=s[e];$s(n,t,i,r);const o=i.distanceToSquared(r);if(o<p&&(p=o,a&&a.copy(i),l&&l.copy(r),o<h))return Math.sqrt(o)}}return Math.sqrt(p)}}();class Qs extends gs{constructor(){super(()=>new Ys)}}const Ks=new Qs,Js=new u,ei=new u;const ti=parseInt(y)>=169,si=parseInt(y)<=161,ii=new u,ri=new u,ni=new u,oi=new p,ai=new p,li=new p,hi=new u,ui=new u,ci=new u,di=new u;function pi(e,t,s,i,r,n,o,a,l,h,c){ii.fromBufferAttribute(t,n),ri.fromBufferAttribute(t,o),ni.fromBufferAttribute(t,a);const d=function(e,t,s,i,r,n,o,a){let l;if(l=n===f?e.intersectTriangle(i,s,t,!0,r):e.intersectTriangle(t,s,i,n!==g,r),null===l)return null;const h=e.origin.distanceTo(r);return h<o||h>a?null:{distance:h,point:r.clone()}}(e,ii,ri,ni,di,l,h,c);if(d){if(i){oi.fromBufferAttribute(i,n),ai.fromBufferAttribute(i,o),li.fromBufferAttribute(i,a),d.uv=new p;const e=m.getInterpolation(di,ii,ri,ni,oi,ai,li,d.uv);ti||(d.uv=e)}if(r){oi.fromBufferAttribute(r,n),ai.fromBufferAttribute(r,o),li.fromBufferAttribute(r,a),d.uv1=new p;const e=m.getInterpolation(di,ii,ri,ni,oi,ai,li,d.uv1);ti||(d.uv1=e),si&&(d.uv2=d.uv1)}if(s){hi.fromBufferAttribute(s,n),ui.fromBufferAttribute(s,o),ci.fromBufferAttribute(s,a),d.normal=new u;const t=m.getInterpolation(di,ii,ri,ni,hi,ui,ci,d.normal);d.normal.dot(e.direction)>0&&d.normal.multiplyScalar(-1),ti||(d.normal=t)}const t={a:n,b:o,c:a,normal:new u,materialIndex:0};if(m.getNormal(ii,ri,ni,t.normal),d.face=t,d.faceIndex=n,ti){const e=new u;m.getBarycoord(di,ii,ri,ni,e),d.barycoord=e}}return d}function mi(e){return e&&e.isMaterial?e.side:e}function fi(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:b}=d[a];if(e>=c&&e<c+y){const e=pi(s,p,m,f,g,l,h,u,mi(t[b]),n,o);if(e){if(e.faceIndex=i,e.face.materialIndex=b,!r)return e;r.push(e)}}}}else{const e=pi(s,p,m,f,g,l,h,u,mi(t),n,o);if(e){if(e.faceIndex=i,e.face.materialIndex=0,!r)return e;r.push(e)}}return null}function gi(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 yi(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,gi(o,3*e,l,h),o.needsUpdate=!0,i(o,e,r,n))return!0}return!1}function bi(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(qt(h,a)){const t=Xt(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+Yt(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=Zt(e),r=Qt(e,o);let a=n,h=!1,u=!1;if(t){if(!a){const e=i/8+s/Ot,n=r/8+s/Ot;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 xi(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],b=t[e+3],x=t[e+1],_=t[e+3+1],w=t[e+2],v=t[e+3+2];return c>=0?(n=(y-m)*c,o=(b-m)*c):(n=(b-m)*c,o=(y-m)*c),d>=0?(a=(x-f)*d,l=(_-f)*d):(a=(_-f)*d,l=(x-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 _i(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),gi(o,3*e,l,h),o.needsUpdate=!0,i(o,e,r,n))return!0}return!1}function wi(e,t,s,i,r,n,o){bs.setBuffer(e._roots[t]),vi(0,e,s,i,r,n,o),bs.clearBuffer()}function vi(e,t,s,i,r,n,o){const{float32Array:a,uint16Array:l,uint32Array:h}=bs,u=2*e;if(qt(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++)fi(l,t,s,e,n,o,a)}(t,s,i,Xt(e,h),Yt(u,l),r,n,o)}else{const l=Zt(e);xi(l,a,i,n,o)&&vi(l,t,s,i,r,n,o);const u=Qt(e,h);xi(u,a,i,n,o)&&vi(u,t,s,i,r,n,o)}}const Ti=["x","y","z"];function Si(e,t,s,i,r,n){bs.setBuffer(e._roots[t]);const o=Mi(0,e,s,i,r,n);return bs.clearBuffer(),o}function Mi(e,t,s,i,r,n){const{float32Array:o,uint16Array:a,uint32Array:l}=bs;let h=2*e;if(qt(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=fi(a,t,s,e,null,n,o),i&&i.distance<h&&(u=i,h=i.distance)}return u}(t,s,i,Xt(e,l),Yt(h,a),r,n)}{const a=Kt(e,l),h=Ti[a],u=i.direction[h]>=0;let c,d;u?(c=Zt(e),d=Qt(e,l)):(c=Qt(e,l),d=Zt(e));const p=xi(c,o,i,r,n)?Mi(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=xi(d,o,i,r,n)?Mi(d,t,s,i,r,n):null;return p&&m?p.distance<=m.distance?p:m:p||m||null}}const Ai=new a,Ni=new Ys,Ei=new Ys,Ci=new l,Ri=new Zs,Pi=new Zs;function Bi(e,t,s,i){bs.setBuffer(e._roots[t]);const r=Ii(0,e,s,i);return bs.clearBuffer(),r}function Ii(e,t,s,i,r=null){const{float32Array:n,uint16Array:o,uint32Array:a}=bs;let l=2*e;null===r&&(s.boundingBox||s.computeBoundingBox(),Ri.set(s.boundingBox.min,s.boundingBox.max,i),r=Ri);if(!qt(l,o)){const o=Zt(e),l=Qt(e,a);Ut(o,n,Ai);if(r.intersectsBox(Ai)&&Ii(o,t,s,i,r))return!0;Ut(l,n,Ai);return!!(r.intersectsBox(Ai)&&Ii(l,t,s,i,r))}{const r=t.geometry,h=r.index,u=r.attributes.position,c=s.index,d=s.attributes.position,p=Xt(e,a),m=Yt(l,o);if(Ci.copy(i).invert(),s.boundsTree){Ut(e,n,Pi),Pi.matrix.copy(Ci),Pi.needsUpdate=!0;return s.boundsTree.shapecast({intersectsBounds:e=>Pi.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(gi(Ei,t,h,u),Ei.needsUpdate=!0,e.intersectsTriangle(Ei))return!0;return!1}})}{const e=zs(s);for(let t=3*p,s=3*(m+p);t<s;t+=3){gi(Ni,t,h,u),Ni.a.applyMatrix4(Ci),Ni.b.applyMatrix4(Ci),Ni.c.applyMatrix4(Ci),Ni.needsUpdate=!0;for(let t=0,s=3*e;t<s;t+=3)if(gi(Ei,t,c,d),Ei.needsUpdate=!0,Ni.intersectsTriangle(Ei))return!0}}}}const Di=new l,Li=new Zs,Fi=new Zs,Oi=new u,zi=new u,Vi=new u,ki=new u;function Ui(e,t,s,i={},r={},n=0,o=1/0){t.boundingBox||t.computeBoundingBox(),Li.set(t.boundingBox.min,t.boundingBox.max,s),Li.needsUpdate=!0;const a=e.geometry,l=a.attributes.position,h=a.index,u=t.attributes.position,c=t.index,d=Ks.getPrimitive(),p=Ks.getPrimitive();let m=Oi,f=zi,g=null,y=null;r&&(g=Vi,y=ki);let b=1/0,x=null,_=null;return Di.copy(s).invert(),Fi.matrix.copy(Di),e.shapecast({boundsTraverseOrder:e=>Li.distanceToBox(e),intersectsBounds:(e,t,s)=>s<b&&s<o&&(t&&(Fi.min.copy(e.min),Fi.max.copy(e.max),Fi.needsUpdate=!0),!0),intersectsRange:(e,i)=>{if(t.boundsTree){return t.boundsTree.shapecast({boundsTraverseOrder:e=>Fi.distanceToBox(e),intersectsBounds:(e,t,s)=>s<b&&s<o,intersectsRange:(t,r)=>{for(let o=t,a=t+r;o<a;o++){gi(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++){gi(d,3*t,h,l),d.needsUpdate=!0;const e=d.distanceToTriangle(p,m,g);if(e<b&&(f.copy(m),y&&y.copy(g),b=e,x=t,_=o),e<n)return!0}}}})}for(let r=0,o=zs(t);r<o;r++){gi(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++){gi(d,3*t,h,l),d.needsUpdate=!0;const e=d.distanceToTriangle(p,m,g);if(e<b&&(f.copy(m),y&&y.copy(g),b=e,x=t,_=r),e<n)return!0}}}}),Ks.releasePrimitive(d),Ks.releasePrimitive(p),b===1/0?null:(i.point?i.point.copy(f):i.point=f.clone(),i.distance=b,i.faceIndex=x,r&&(r.point?r.point.copy(y):r.point=y.clone(),r.point.applyMatrix4(Di),f.applyMatrix4(Di),r.distance=f.sub(r.point).length(),r.faceIndex=_),i)}function Gi(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(qt(u,a)){const t=Xt(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+Yt(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=Zt(s),i=Qt(s,o);let r=h,a=!1,u=!1;if(t){if(!r){const s=e/8+n/Ot,o=i/8+n/Ot;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 ji(e,t,s,i,r,n,o){bs.setBuffer(e._roots[t]),$i(0,e,s,i,r,n,o),bs.clearBuffer()}function $i(e,t,s,i,r,n,o){const{float32Array:a,uint16Array:l,uint32Array:h}=bs,u=2*e;if(qt(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++)fi(l,t,s,h?h[e]:e,n,o,a)}(t,s,i,Xt(e,h),Yt(u,l),r,n,o)}else{const l=Zt(e);xi(l,a,i,n,o)&&$i(l,t,s,i,r,n,o);const u=Qt(e,h);xi(u,a,i,n,o)&&$i(u,t,s,i,r,n,o)}}const Wi=["x","y","z"];function Hi(e,t,s,i,r,n){bs.setBuffer(e._roots[t]);const o=qi(0,e,s,i,r,n);return bs.clearBuffer(),o}function qi(e,t,s,i,r,n){const{float32Array:o,uint16Array:a,uint32Array:l}=bs;let h=2*e;if(qt(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=fi(a,t,s,l?l[e]:e,null,n,o),i&&i.distance<h&&(u=i,h=i.distance)}return u}(t,s,i,Xt(e,l),Yt(h,a),r,n)}{const a=Kt(e,l),h=Wi[a],u=i.direction[h]>=0;let c,d;u?(c=Zt(e),d=Qt(e,l)):(c=Qt(e,l),d=Zt(e));const p=xi(c,o,i,r,n)?qi(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=xi(d,o,i,r,n)?qi(d,t,s,i,r,n):null;return p&&m?p.distance<=m.distance?p:m:p||m||null}}const Xi=new a,Yi=new Ys,Zi=new Ys,Qi=new l,Ki=new Zs,Ji=new Zs;function er(e,t,s,i){bs.setBuffer(e._roots[t]);const r=tr(0,e,s,i);return bs.clearBuffer(),r}function tr(e,t,s,i,r=null){const{float32Array:n,uint16Array:o,uint32Array:a}=bs;let l=2*e;null===r&&(s.boundingBox||s.computeBoundingBox(),Ki.set(s.boundingBox.min,s.boundingBox.max,i),r=Ki);if(!qt(l,o)){const o=Zt(e),l=Qt(e,a);Ut(o,n,Xi);if(r.intersectsBox(Xi)&&tr(o,t,s,i,r))return!0;Ut(l,n,Xi);return!!(r.intersectsBox(Xi)&&tr(l,t,s,i,r))}{const r=t.geometry,h=r.index,u=r.attributes.position,c=s.index,d=s.attributes.position,p=Xt(e,a),m=Yt(l,o);if(Qi.copy(i).invert(),s.boundsTree){Ut(e,n,Ji),Ji.matrix.copy(Qi),Ji.needsUpdate=!0;return s.boundsTree.shapecast({intersectsBounds:e=>Ji.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(gi(Zi,3*t.resolveTriangleIndex(s),h,u),Zi.needsUpdate=!0,e.intersectsTriangle(Zi))return!0;return!1}})}{const e=zs(s);for(let s=p,i=m+p;s<i;s++){const i=t.resolveTriangleIndex(s);gi(Yi,3*i,h,u),Yi.a.applyMatrix4(Qi),Yi.b.applyMatrix4(Qi),Yi.c.applyMatrix4(Qi),Yi.needsUpdate=!0;for(let t=0,s=3*e;t<s;t+=3)if(gi(Zi,t,c,d),Zi.needsUpdate=!0,Yi.intersectsTriangle(Zi))return!0}}}}const sr=new l,ir=new Zs,rr=new Zs,nr=new u,or=new u,ar=new u,lr=new u;function hr(e,t,s,i={},r={},n=0,o=1/0){t.boundingBox||t.computeBoundingBox(),ir.set(t.boundingBox.min,t.boundingBox.max,s),ir.needsUpdate=!0;const a=e.geometry,l=a.attributes.position,h=a.index,u=t.attributes.position,c=t.index,d=Ks.getPrimitive(),p=Ks.getPrimitive();let m=nr,f=or,g=null,y=null;r&&(g=ar,y=lr);let b=1/0,x=null,_=null;return sr.copy(s).invert(),rr.matrix.copy(sr),e.shapecast({boundsTraverseOrder:e=>ir.distanceToBox(e),intersectsBounds:(e,t,s)=>s<b&&s<o&&(t&&(rr.min.copy(e.min),rr.max.copy(e.max),rr.needsUpdate=!0),!0),intersectsRange:(i,r)=>{if(t.boundsTree){const a=t.boundsTree;return a.shapecast({boundsTraverseOrder:e=>rr.distanceToBox(e),intersectsBounds:(e,t,s)=>s<b&&s<o,intersectsRange:(t,o)=>{for(let w=t,v=t+o;w<v;w++){const t=a.resolveTriangleIndex(w);gi(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);gi(d,3*s,h,l),d.needsUpdate=!0;const i=d.distanceToTriangle(p,m,g);if(i<b&&(f.copy(m),y&&y.copy(g),b=i,x=t,_=w),i<n)return!0}}}})}for(let o=0,a=zs(t);o<a;o++){gi(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);gi(d,3*s,h,l),d.needsUpdate=!0;const i=d.distanceToTriangle(p,m,g);if(i<b&&(f.copy(m),y&&y.copy(g),b=i,x=t,_=o),i<n)return!0}}}}),Ks.releasePrimitive(d),Ks.releasePrimitive(p),b===1/0?null:(i.point?i.point.copy(f):i.point=f.clone(),i.distance=b,i.faceIndex=x,r&&(r.point?r.point.copy(y):r.point=y.clone(),r.point.applyMatrix4(sr),f.applyMatrix4(sr),r.distance=f.sub(r.point).length(),r.faceIndex=_),i)}function ur(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 cr=new Zs,dr=new b,pr=new u,mr=new l,fr=new u,gr=["getX","getY","getZ"];class yr extends Us{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:i,roots:r,indirectBuffer:n}=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/Ot;e<t;e++){const t=8*e;qt(2*t,r)||(i[t+6]=i[t+6]/8-e)}}}(r));const o=new yr(t,{...s,[Vt]:!0});if(o._roots=r,o._indirectBuffer=n||null,s.setIndex){const s=t.getIndex();if(null===s){const s=new h(e.index,1,!1);t.setIndex(s)}else s.array!==i&&(s.array.set(i),s.needsUpdate=!0)}return o}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[gr[e]](l),r=n[gr[e]](h),o=n[gr[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)*zt}}return s}raycastObject3D(e,t,s=[]){const{material:i}=e;if(void 0===i)return;mr.copy(e.matrixWorld).invert(),dr.copy(t.ray).applyMatrix4(mr),fr.setFromMatrixScale(e.matrixWorld),pr.copy(dr.direction).multiply(fr);const r=pr.length(),n=t.near/r,o=t.far/r;if(!0===t.firstHitOnly){let r=this.raycastFirst(dr,i,n,o);r=ur(r,e,t),r&&s.push(r)}else{const r=this.raycast(dr,i,n,o);for(let i=0,n=r.length;i<n;i++){const n=ur(r[i],e,t);n&&s.push(n)}}return s}refit(e=null){return(this.indirect?Gi:bi)(this,e)}raycast(e,t=x,s=0,i=1/0){const r=this._roots,n=[],o=this.indirect?ji:wi;for(let a=0,l=r.length;a<l;a++)o(this,a,t,e,n,s,i);return n}raycastFirst(e,t=x,s=0,i=1/0){const r=this._roots;let n=null;const o=this.indirect?Hi:Si;for(let a=0,l=r.length;a<l;a++){const r=o(this,a,t,e,s,i);null!=r&&(null==n||r.distance<n.distance)&&(n=r)}return n}intersectsGeometry(e,t){let s=!1;const i=this._roots,r=this.indirect?er:Bi;for(let n=0,o=i.length;n<o&&(s=r(this,n,e,t),!s);n++);return s}shapecast(e){const t=Ks.getPrimitive(),s=super.shapecast({...e,intersectsPrimitive:e.intersectsTriangle,scratchPrimitive:t,iterate:this.indirect?_i:yi});return Ks.releasePrimitive(t),s}bvhcast(e,t,s){let{intersectsRanges:i,intersectsTriangles:r}=s;const n=Ks.getPrimitive(),o=this.geometry.index,a=this.geometry.attributes.position,l=this.indirect?e=>{const t=this.resolveTriangleIndex(e);gi(n,3*t,o,a)}:e=>{gi(n,3*e,o,a)},h=Ks.getPrimitive(),u=e.geometry.index,c=e.geometry.attributes.position,d=e.indirect?t=>{const s=e.resolveTriangleIndex(t);gi(h,3*s,u,c)}:e=>{gi(h,3*e,u,c)};if(r){if(!(e instanceof yr))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 cr.set(e.min,e.max,t),cr.needsUpdate=!0,this.shapecast({intersectsBounds:e=>cr.intersectsBox(e),intersectsTriangle:e=>cr.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?hr:Ui)(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=>(Js.copy(t).clamp(e.min,e.max),Js.distanceToSquared(t)),intersectsBounds:(e,t,s)=>s<a&&s<o,intersectsTriangle:(e,s)=>{e.closestPointToPoint(t,Js);const i=t.distanceToSquared(Js);return i<a&&(ei.copy(Js),a=i,l=s),i<n}}),a===1/0)return null;const h=Math.sqrt(a);return s.point?s.point.copy(ei):s.point=ei.clone(),s.distance=h,s.faceIndex=l,s}(this,e,t,s,i)}}const br=new l,xr=new b,_r=new gs(()=>new c),wr=new u,vr=new u,Tr=new a,Sr=["getX","getY","getZ"];class Mr extends Us{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[Sr[e]](h),r=o[Sr[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=_r.getPrimitive(),s=super.shapecast({...e,intersectsPrimitive:e.intersectsLine,scratchPrimitive:t,iterate:Ar});return _r.releasePrimitive(t),s}raycastObject3D(e,t,s=[]){const{matrixWorld:i}=e,{firstHitOnly:r}=t;br.copy(i).invert(),xr.copy(t.ray).applyMatrix4(br);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(xr.origin),intersectsBounds:e=>(Tr.copy(e).expandByScalar(Math.abs(n)),xr.intersectsBox(Tr)?1:0),intersectsLine:(n,h)=>{if(xr.distanceSqToSegment(n.start,n.end,wr,vr)>o)return;wr.applyMatrix4(e.matrixWorld);const u=t.ray.origin.distanceTo(wr);u<t.near||u>t.far||r&&u>=l||(l=u,h=this.resolvePrimitiveIndex(h),a={distance:u,point:vr.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 Ar(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 Nr={Mesh:_.prototype.raycast,Line:T.prototype.raycast,LineSegments:w.prototype.raycast,LineLoop:v.prototype.raycast,Points:S.prototype.raycast,BatchedMesh:A.prototype.raycast},Er=new _,Cr=[];function Rr(e,t){if(this.isBatchedMesh)Pr.call(this,e,t);else{const{geometry:s}=this;if(s.boundsTree)s.boundsTree.raycastObject3D(this,e,t);else{let s;if(this instanceof _)s=Nr.Mesh;else if(this instanceof w)s=Nr.LineSegments;else if(this instanceof v)s=Nr.LineLoop;else if(this instanceof T)s=Nr.Line;else{if(!(this instanceof S))throw new Error("BVH: Fallback raycast function not found.");s=Nr.Points}s.call(this,e,t)}}}function Pr(e,t){if(this.boundsTrees){const s=this.boundsTrees,i=this._drawInfo||this._instanceInfo,r=this._drawRanges||this._geometryInfo,n=this.matrixWorld;Er.material=this.material,Er.geometry=this.geometry;const o=Er.geometry.boundsTree,a=Er.geometry.drawRange;null===Er.geometry.boundingSphere&&(Er.geometry.boundingSphere=new M);for(let o=0,a=i.length;o<a;o++){if(!this.getVisibleAt(o))continue;const a=i[o].geometryIndex;if(Er.geometry.boundsTree=s[a],this.getMatrixAt(o,Er.matrixWorld).premultiply(n),!Er.geometry.boundsTree){this.getBoundingBoxAt(a,Er.geometry.boundingBox),this.getBoundingSphereAt(a,Er.geometry.boundingSphere);const e=r[a];Er.geometry.setDrawRange(e.start,e.count)}Er.raycast(e,Cr);for(let e=0,s=Cr.length;e<s;e++){const s=Cr[e];s.object=this,s.batchId=o,t.push(s)}Cr.length=0}Er.geometry.boundsTree=o,Er.geometry.drawRange=a,Er.material=null,Er.geometry=null}else Nr.BatchedMesh.call(this,e,t)}function Br(e={}){const{type:t=yr}=e;return this.boundsTree=new t(this,e),this.boundsTree}function Ir(){this.boundsTree=null}const Dr=class e extends se{constructor(s){super(s),t(this,"onDisposed",new J),t(this,"onBeforeDispose",new J),t(this,"onFragmentsLoaded",new J),t(this,"baseCoordinationModel",""),t(this,"baseCoordinationMatrix",new o.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 r(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 o.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 o.Matrix4;return t&&s.copy(t.clone()).invert(),s.multiply(this.baseCoordinationMatrix),e.applyMatrix4(s),s}};t(Dr,"uuid","fef46874-46a3-461b-8c44-2922ab77c806");let Lr=Dr;function Fr(e,t){return e[t]|e[t+1]<<8|e[t+2]<<16}class Or{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,i=new u,r=new N,n=new a,o=new E(1,1);n.makeEmpty(),e.forEach(e=>{n.expandByObject(e)}),n.getSize(i);const l=Math.min(t.capabilities.maxTextureSize,8192),h=Math.ceil(i.x/s),c=Math.ceil(i.z/s),d=Math.ceil(h/l),p=Math.ceil(c/l);o.setSize(Math.ceil(h/d),Math.ceil(c/p)),r.rotation.x=-Math.PI/2,r.far=n.max.y-n.min.y+r.near,r.position.y=n.max.y+r.near;const m=new C,f=new Map,g=new Map,y=[];for(let t=0;t<e.length;t++){const s=e[t];f.set(s,s.material),g.set(s,s.parent);const i=new zr;i.objectId=t,y.push(i),s.material=i,m.add(s)}const b=t.getClearColor(new R),x=t.getClearAlpha(),_=t.getRenderTarget(),w=t.autoClear;t.autoClear=!0,t.setClearColor(0,0),t.setRenderTarget(o);const v=new Uint8Array(o.width*o.height*4),T=new Set,S=i.x/d,M=i.z/p;for(let s=0;s<d;s++)for(let i=0;i<p;i++){const a=n.min.x+S*s,l=a+S,h=n.min.z+M*i,u=(a+l)/2,c=(h+(h+M))/2;r.position.set(u,n.max.y,c);const d=S/2,p=M/2;r.left=-d,r.right=d,r.top=p,r.bottom=-p,r.updateProjectionMatrix(),t.render(m,r);const f=await t.readRenderTargetPixelsAsync(o,0,0,o.width,o.height,v);for(let t=0,s=f.length;t<s;t+=4){if(0===f[t+3])continue;const s=Fr(f,t);T.add(e[s])}}for(const t of e){t.material=f.get(t);const e=g.get(t);e?e.add(t):m.remove(t)}t.setClearColor(b,x),t.setRenderTarget(_),t.autoClear=w;for(const e of y)e.dispose();return o.dispose(),Array.from(T)}}class zr extends P{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:D,blending:I,uniforms:{objectId:{value:new B}},vertexShader:"\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tgl_Position = projectionMatrix * modelViewMatrix * vec4( position, 1.0 );\n\n\t\t\t\t}\n\t\t\t",fragmentShader:"\n\t\t\t\tlayout(location = 0) out vec4 out_id;\n\t\t\t\tuniform vec4 objectId;\n\n\t\t\t\tvoid main() {\n\n\t\t\t\t\tout_id = objectId;\n\n\t\t\t\t}\n\t\t\t"}),this._objectId=0,this.setValues(e)}}const Vr=1e-16,kr=new u(0,1,0),Ur=new u;function Gr(e){return e.delta(Ur).normalize(),Math.abs(Ur.dot(kr))>=1-Vr}function jr(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)<=Vr&&(n=!0),!o&&i.distanceToSquared(t)<=Vr&&(o=!0),n&&o)return!0}return n&&o}const $r=new c;function Wr(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;$r.start.lerpVectors(s,n,r[t][0]),$r.end.lerpVectors(s,n,r[t][1]),i.push(new Float32Array([$r.start.x,$r.start.y,$r.start.z,$r.end.x,$r.end.y,$r.end.z]))}return i}const Hr=new u(0,1,0),qr=new u,Xr=new u,Yr=new u,Zr=new m;function*Qr(e,t=[],s={}){const{projectionDirection:i=Hr,thresholdAngle:r=1,iterationTime:n=30}=s,o=Math.pow(10,4),a=Math.cos(L.DEG2RAD*r),l=e.getIndex(),h=e.getAttribute("position"),u=l?l.count:h.count,d=[0,0,0],p=["a","b","c"],m=new Array(3),f={};let g=performance.now();for(let e=0;e<u;e+=3){performance.now()-g>n&&(yield,g=performance.now()),l?(d[0]=l.getX(e),d[1]=l.getX(e+1),d[2]=l.getX(e+2)):(d[0]=e,d[1]=e+1,d[2]=e+2);const{a:s,b:r,c:u}=Zr;if(s.fromBufferAttribute(h,d[0]),r.fromBufferAttribute(h,d[1]),u.fromBufferAttribute(h,d[2]),Zr.getNormal(Yr),m[0]=`${Math.round(s.x*o)},${Math.round(s.y*o)},${Math.round(s.z*o)}`,m[1]=`${Math.round(r.x*o)},${Math.round(r.y*o)},${Math.round(r.z*o)}`,m[2]=`${Math.round(u.x*o)},${Math.round(u.y*o)},${Math.round(u.z*o)}`,m[0]!==m[1]&&m[1]!==m[2]&&m[2]!==m[0])for(let e=0;e<3;e++){const s=(e+1)%3,r=m[e],n=m[s],o=Zr[p[e]],l=Zr[p[s]],h=`${r}_${n}`,u=`${n}_${r}`;if(u in f&&f[u]){const e=f[u].normal,s=Yr.dot(e)<=a;let r=!1;if(null!==i){let t=i.dot(Yr);t=Math.abs(t)<1e-10?0:t;let s=i.dot(e);s=Math.abs(s)<1e-10?0:s,r=Math.sign(t)!==Math.sign(s)}if(s||r){const e=new c;e.start.copy(o),e.end.copy(l),t.push(e)}f[u]=null}else h in f||(f[h]={index0:d[e],index1:d[s],normal:Yr.clone()})}}for(const e in f)if(f[e]){const{index0:s,index1:i}=f[e];qr.fromBufferAttribute(h,s),Xr.fromBufferAttribute(h,i);const r=new c;r.start.copy(qr),r.end.copy(Xr),t.push(r)}return t}const Kr=new c;function Jr(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++){en(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,Kr,!0)||jr(e,Kr)||jr(t,Kr)||i.push(Kr.clone())))}),i}function en(e,t){return e.distanceTo(t)<1e-10}function tn(e){sn(e);let t=[];return e.traverse(e=>{e.geometry&&e.visible&&t.push(e)}),t}const sn=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):sn(s)},rn=new l,nn=new l;class on{constructor(){this.projectionDirection=new u(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:i,thresholdAngle:r,iterationTime:n}=this;if(e.isObject3D){const o=tn(e);let a=null;i&&(a=new u);let l=performance.now();for(let e=0;e<o.length;e++){l-performance.now()>n&&(yield);const h=o[e];a&&(nn.copy(h.matrixWorld).invert(),a.copy(i).transformDirection(nn).normalize());const u=yield*Qr(h.geometry,[],{projectionDirection:a,thresholdAngle:r,iterationTime:n});an(u,h.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(h)}return t}return yield*Qr(e,t,{projectionDirection:i,thresholdAngle:r,iterationTime:n})}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=tn(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 yr(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);rn.copy(l.matrixWorld).invert().multiply(h.matrixWorld);const d=Jr(u,c,rn,[]);an(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 yr(e,{maxLeafSize:1}):(s=e,e=s.geometry),rn.identity(),Jr(s,s,rn,t)}}}function an(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 ln extends Fs{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 hn=new u(0,1,0),un=new d,cn=new u,dn=new u;function pn(e,t,s){e.needsUpdate&&e.update(),un.copy(e.plane),un.normal.dot(hn)<0&&(un.normal.multiplyScalar(-1),un.constant*=-1);const i=un.distanceToPoint(t.start),r=un.distanceToPoint(t.end),n=Math.abs(i)<1e-16,o=i<0,a=r<0;if(t.delta(dn).normalize(),Math.abs(un.normal.dot(dn))<1e-16)return!(n||!o)&&(s.copy(t),!0);if(o&&a)return s.copy(t),!0;if(!o&&!a)return!1;{const e=L.mapLinear(0,i,r,0,1);if(t.at(e,cn),o)return s.start.copy(t.start),s.end.copy(cn),!0;if(a)return s.end.copy(t.end),s.start.copy(cn),!0}return!1}const mn=new d,fn=new u,gn=new u,yn=new Ys,bn=new c,xn=new c,_n=new u,wn=new u,vn=new u;function Tn(e,t,s=new c){if(yn.copy(t),yn.a.y=0,yn.b.y=0,yn.c.y=0,yn.update(),bn.copy(e),bn.start.y=0,bn.end.y=0,yn.getArea()<=1e-16)return null;const i=bn.distance();bn.delta(_n).divideScalar(i),wn.copy(_n).cross(yn.plane.normal).normalize(),mn.setFromNormalAndCoplanarPoint(wn,bn.start);let r=0;const{points:n}=yn;for(let e=0;e<3;e++){const t=n[e],s=n[(e+1)%3],i=mn.distanceToPoint(t),o=mn.distanceToPoint(s),a=Math.abs(i)<1e-16,l=Math.abs(o)<1e-16;let h=!1;if(!a&&!l&&i*o<0){const e=i/(i-o);fn.lerpVectors(t,s,e),h=!0}if((h&&!l||a)&&(a&&!h&&fn.copy(t),0===r?xn.start.copy(fn):xn.end.copy(fn),r++,2===r))break}if(2===r){if(xn.delta(vn).normalize(),_n.dot(vn)<0){const e=xn.start;xn.start=xn.end,xn.end=e}const t=0,r=gn.subVectors(bn.end,bn.start).dot(_n),n=gn.subVectors(xn.start,bn.start).dot(_n),o=gn.subVectors(xn.end,bn.start).dot(_n);return r<=n||o<=t?null:(e.at(Math.max(t,n)/i,s.start),e.at(Math.min(r,o)/i,s.end),s)}return null}const Sn=new u,Mn=new u,An=new u;function Nn(e,t,s){const i=function(e,t){e.delta(Sn),Mn.subVectors(t.start,e.start),An.subVectors(t.end,e.start);const s=Sn.length();let i=Mn.length()/s,r=An.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&&(En(i,s),!0)}function En(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 Cn=new u(0,1,0),Rn=new c,Pn=new c,Bn=new Ys;function In(e,t,s,i,r=null){const{geometry:n,matrixWorld:o,material:a}=s,l=a.side,h=o.determinant()<0,u=e.lines;e.bvhcast(t,o,{intersectsRanges:(e,t,s,a)=>{r&&(r.candidates+=t*a);for(let c=s,d=a+s;c<d;c++){let s=3*c+0,a=3*c+1,d=3*c+2;n.index&&(s=n.index.getX(s),a=n.index.getX(a),d=n.index.getX(d));const{a:p,b:m,c:y}=Bn;if(p.fromBufferAttribute(n.attributes.position,s).applyMatrix4(o),m.fromBufferAttribute(n.attributes.position,a).applyMatrix4(o),y.fromBufferAttribute(n.attributes.position,d).applyMatrix4(o),Bn.needsUpdate=!0,Bn.update(),l!==g){if(Bn.plane.normal.dot(Cn)!==h===(l===f)){r&&(r.backFaceCulled+=t);continue}}const b=Math.max(p.y,m.y,y.y),x=Math.min(p.y,m.y,y.y),_=Bn.plane.normal;let w=_.x,v=_.y,T=_.z,S=Bn.plane.constant;v<0&&(w=-w,v=-v,T=-T,S=-S);for(let s=e,n=t+e;s<n;s++){const e=u[s],t=Math.min(e.start.y,e.end.y),n=Math.max(e.start.y,e.end.y);if(b<=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),s=o*t,i=a*t,n=-i,h=s,u=p.x-e.start.x,c=p.z-e.start.z,d=m.x-e.start.x,f=m.z-e.start.z,g=y.x-e.start.x,b=y.z-e.start.z,x=u*s+c*i,_=d*s+f*i,w=g*s+b*i,v=1/t,T=Math.min(x,_,w);if(Math.max(x,_,w)<0||T>v){r&&r.xzBoundsCulled++;continue}const S=u*n+c*h,M=d*n+f*h,A=g*n+b*h,N=Math.min(S,M,A),E=Math.max(S,M,A);if(N>0||E<0){r&&r.xzBoundsCulled++;continue}}const h=w*e.start.x+v*e.start.y+T*e.start.z+S,c=w*e.end.x+v*e.end.y+T*e.end.z+S;if(h>=0&&c>=0)r&&r.planeTrimCulled++;else if(jr(Bn,e))r&&r.triangleEdgeCulled++;else{if(n<x)Rn.copy(e);else if(!pn(Bn,e,Rn)){r&&r.planeTrimCulled++;continue}Rn.distance()<1e-10?r&&r.distThresholdCulled++:Tn(Rn,Bn,Pn)?(r&&r.used++,Nn(e,Pn,i[s])):r&&r.noOverlapCulled++}}}}})}Bn.update=()=>{Bn.plane.setFromCoplanarPoints(...Bn.points)};let Dn=!1;const Ln={},Fn={};let On=null,zn=0,Vn=0;const kn={get enabled(){return Dn},set enabled(e){Dn=e},reset(){for(const e in Ln)delete Ln[e];for(const e in Fn)delete Fn[e];On=null,zn=0,Vn=0},setStat(e,t){Fn[e]=t},startTotal(){Dn&&(Vn=performance.now())},startStep(e){Dn&&(null!==On&&this.endStep(),On=e,zn=performance.now())},endStep(){if(!Dn||null===On)return;const e=performance.now()-zn;Ln[On]=e,On=null},printSummary(){if(!Dn)return;null!==On&&this.endStep();const e=performance.now()-Vn;console.log("\n=== Projection Summary ==="),console.log(`Total time: ${e.toFixed(1)}ms\n`);for(const[t,s]of Object.entries(Ln)){const i=(s/e*100).toFixed(1);console.log(` ${t}: ${s.toFixed(1)}ms (${i}%)`)}if(Object.keys(Fn).length>0){console.log("\n--- Stats ---");for(const[e,t]of Object.entries(Fn))console.log(` ${e}: ${t}`)}console.log("")}},Un="182",Gn=100,jn=101,$n=102,Wn=200,Hn=201,qn=202,Xn=203,Yn=204,Zn=205,Qn=206,Kn=207,Jn=208,eo=209,to=210,so=301,io=302,ro=1e3,no=1001,oo=1002,ao=1003,lo=1004,ho=1005,uo=1006,co=1007,po=1008,mo=1009,fo=1010,go=1011,yo=1012,bo=1013,xo=1014,_o=1015,wo=1016,vo=1017,To=1018,So=1020,Mo=35902,Ao=35899,No=1022,Eo=1023,Co=1026,Ro=1027,Po=1028,Bo=1029,Io=1030,Do=1031,Lo=1033,Fo=33776,Oo=33777,zo=33778,Vo=33779,ko=35840,Uo=35841,Go=35842,jo=35843,$o=36196,Wo=37492,Ho=37496,qo=37488,Xo=37489,Yo=37490,Zo=37491,Qo=37808,Ko=37809,Jo=37810,ea=37811,ta=37812,sa=37813,ia=37814,ra=37815,na=37816,oa=37817,aa=37818,la=37819,ha=37820,ua=37821,ca=36492,da=36283,pa=36284,ma=36285,fa=36286,ga="",ya="srgb",ba="srgb-linear",xa="linear",_a="srgb",wa=7680,va=512,Ta=513,Sa=514,Ma=515,Aa=516,Na=517,Ea=518,Ca=519,Ra=35044,Pa=35048,Ba=2e3,Ia=2001,Da="compute",La="render";
2
+ /**
3
+ * @license
4
+ * Copyright 2010-2025 Three.js Authors
5
+ * SPDX-License-Identifier: MIT
6
+ */function Fa(e){for(let t=e.length-1;t>=0;--t)if(e[t]>=65535)return!0;return!1}function Oa(e){return ArrayBuffer.isView(e)&&!(e instanceof DataView)}function za(e){return document.createElementNS("http://www.w3.org/1999/xhtml",e)}const Va={};function ka(...e){const t="THREE."+e.shift();console.log(t,...e)}function Ua(...e){const t="THREE."+e.shift();console.warn(t,...e)}function Ga(...e){const t="THREE."+e.shift();console.error(t,...e)}function ja(...e){const t=e.join(" ");t in Va||(Va[t]=!0,Ua(...e))}class $a{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 Wa=["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 Ha=1234567;const qa=Math.PI/180,Xa=180/Math.PI;function Ya(){const e=4294967295*Math.random()|0,t=4294967295*Math.random()|0,s=4294967295*Math.random()|0,i=4294967295*Math.random()|0;return(Wa[255&e]+Wa[e>>8&255]+Wa[e>>16&255]+Wa[e>>24&255]+"-"+Wa[255&t]+Wa[t>>8&255]+"-"+Wa[t>>16&15|64]+Wa[t>>24&255]+"-"+Wa[63&s|128]+Wa[s>>8&255]+"-"+Wa[s>>16&255]+Wa[s>>24&255]+Wa[255&i]+Wa[i>>8&255]+Wa[i>>16&255]+Wa[i>>24&255]).toLowerCase()}function Za(e,t,s){return Math.max(t,Math.min(s,e))}function Qa(e,t){return(e%t+t)%t}function Ka(e,t,s){return(1-s)*e+s*t}function Ja(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 el(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 tl={DEG2RAD:qa,RAD2DEG:Xa,generateUUID:Ya,clamp:Za,euclideanModulo:Qa,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:Ka,damp:function(e,t,s,i){return Ka(e,t,1-Math.exp(-s*i))},pingpong:function(e,t=1){return t-Math.abs(Qa(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&&(Ha=e);let t=Ha+=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*qa},radToDeg:function(e){return e*Xa},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:Ua("MathUtils: .setQuaternionFromProperEuler() encountered an unknown order: "+r)}},normalize:el,denormalize:Ja};class sl{constructor(e=0,t=0){sl.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=Za(this.x,e.x,t.x),this.y=Za(this.y,e.y,t.y),this}clampScalar(e,t){return this.x=Za(this.x,e,t),this.y=Za(this.y,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Za(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(Za(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 il{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:Ua("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(Za(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 rl{constructor(e=0,t=0,s=0){rl.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(ol.setFromEuler(e))}applyAxisAngle(e,t){return this.applyQuaternion(ol.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=Za(this.x,e.x,t.x),this.y=Za(this.y,e.y,t.y),this.z=Za(this.z,e.z,t.z),this}clampScalar(e,t){return this.x=Za(this.x,e,t),this.y=Za(this.y,e,t),this.z=Za(this.z,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Za(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 nl.copy(this).projectOnVector(e),this.sub(nl)}reflect(e){return this.sub(nl.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(Za(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 nl=new rl,ol=new il;class al{constructor(e,t,s,i,r,n,o,a,l){al.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],b=i[4],x=i[7],_=i[2],w=i[5],v=i[8];return r[0]=n*m+o*y+a*_,r[3]=n*f+o*b+a*w,r[6]=n*g+o*x+a*v,r[1]=l*m+h*y+u*_,r[4]=l*f+h*b+u*w,r[7]=l*g+h*x+u*v,r[2]=c*m+d*y+p*_,r[5]=c*f+d*b+p*w,r[8]=c*g+d*x+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(ll.makeScale(e,t)),this}rotate(e){return this.premultiply(ll.makeRotation(-e)),this}translate(e,t){return this.premultiply(ll.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 ll=new al,hl=(new al).set(.4123908,.3575843,.1804808,.212639,.7151687,.0721923,.0193308,.1191948,.9505322),ul=(new al).set(3.2409699,-1.5373832,-.4986108,-.9692436,1.8759675,.0415551,.0556301,-.203977,1.0569715);function cl(){const e={enabled:!0,workingColorSpace:ba,spaces:{},convert:function(e,t,s){return!1!==this.enabled&&t!==s&&t&&s?(this.spaces[t].transfer===_a&&(e.r=pl(e.r),e.g=pl(e.g),e.b=pl(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===_a&&(e.r=ml(e.r),e.g=ml(e.g),e.b=ml(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===ga?xa: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 ja("ColorManagement: .fromWorkingColorSpace() has been renamed to .workingToColorSpace()."),e.workingToColorSpace(t,s)},toWorkingColorSpace:function(t,s){return ja("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({[ba]:{primaries:t,whitePoint:i,transfer:xa,toXYZ:hl,fromXYZ:ul,luminanceCoefficients:s,workingColorSpaceConfig:{unpackColorSpace:ya},outputColorSpaceConfig:{drawingBufferColorSpace:ya}},[ya]:{primaries:t,whitePoint:i,transfer:_a,toXYZ:hl,fromXYZ:ul,luminanceCoefficients:s,outputColorSpaceConfig:{drawingBufferColorSpace:ya}}}),e}const dl=cl();function pl(e){return e<.04045?.0773993808*e:Math.pow(.9478672986*e+.0521327014,2.4)}function ml(e){return e<.0031308?12.92*e:1.055*Math.pow(e,.41666)-.055}let fl;class gl{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===fl&&(fl=za("canvas")),fl.width=e.width,fl.height=e.height;const t=fl.getContext("2d");e instanceof ImageData?t.putImageData(e,0,0):t.drawImage(e,0,0,e.width,e.height),s=fl}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=za("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*pl(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*pl(t[e]/255)):t[e]=pl(t[e]);return{data:t,width:e.width,height:e.height}}return Ua("ImageUtils.sRGBToLinear(): Unsupported image type. No color space conversion applied."),e}}let yl=0;class bl{constructor(e=null){this.isSource=!0,Object.defineProperty(this,"id",{value:yl++}),this.uuid=Ya(),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(xl(i[t].image)):e.push(xl(i[t]))}else e=xl(i);s.url=e}return t||(e.images[this.uuid]=s),s}}function xl(e){return"undefined"!=typeof HTMLImageElement&&e instanceof HTMLImageElement||"undefined"!=typeof HTMLCanvasElement&&e instanceof HTMLCanvasElement||"undefined"!=typeof ImageBitmap&&e instanceof ImageBitmap?gl.getDataURL(e):e.data?{data:Array.from(e.data),width:e.width,height:e.height,type:e.data.constructor.name}:(Ua("Texture: Unable to serialize Texture."),{})}let _l=0;const wl=new rl;class vl extends $a{constructor(e=vl.DEFAULT_IMAGE,t=vl.DEFAULT_MAPPING,s=1001,i=1001,r=1006,n=1008,o=1023,a=1009,l=vl.DEFAULT_ANISOTROPY,h=""){super(),this.isTexture=!0,Object.defineProperty(this,"id",{value:_l++}),this.uuid=Ya(),this.name="",this.source=new bl(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 sl(0,0),this.repeat=new sl(1,1),this.center=new sl(0,0),this.rotation=0,this.matrixAutoUpdate=!0,this.matrix=new al,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(wl).x}get height(){return this.source.getSize(wl).y}get depth(){return this.source.getSize(wl).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){Ua(`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:Ua(`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 ro:e.x=e.x-Math.floor(e.x);break;case no:e.x=e.x<0?0:1;break;case oo: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 ro:e.y=e.y-Math.floor(e.y);break;case no:e.y=e.y<0?0:1;break;case oo: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++}}vl.DEFAULT_IMAGE=null,vl.DEFAULT_MAPPING=300,vl.DEFAULT_ANISOTROPY=1;class Tl{constructor(e=0,t=0,s=0,i=1){Tl.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,b=(h+c)/4,x=(u+m)/4,_=(p+f)/4;return e>a&&e>y?e<n?(s=0,i=.707106781,r=.707106781):(s=Math.sqrt(e),i=b/s,r=x/s):a>y?a<n?(s=.707106781,i=0,r=.707106781):(i=Math.sqrt(a),s=b/i,r=_/i):y<n?(s=.707106781,i=.707106781,r=0):(r=Math.sqrt(y),s=x/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=Za(this.x,e.x,t.x),this.y=Za(this.y,e.y,t.y),this.z=Za(this.z,e.z,t.z),this.w=Za(this.w,e.w,t.w),this}clampScalar(e,t){return this.x=Za(this.x,e,t),this.y=Za(this.y,e,t),this.z=Za(this.z,e,t),this.w=Za(this.w,e,t),this}clampLength(e,t){const s=this.length();return this.divideScalar(s||1).multiplyScalar(Za(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 Sl extends $a{constructor(e=1,t=1,s={}){super(),s=Object.assign({generateMipmaps:!1,internalFormat:null,minFilter:uo,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 Tl(0,0,e,t),this.scissorTest=!1,this.viewport=new Tl(0,0,e,t);const i={width:e,height:t,depth:s.depth},r=new vl(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:uo,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 bl(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 Ml extends Sl{constructor(e=1,t=1,s={}){super(e,t,s),this.isWebGLRenderTarget=!0}}class Al extends vl{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=ao,this.minFilter=ao,this.wrapR=no,this.generateMipmaps=!1,this.flipY=!1,this.unpackAlignment=1,this.layerUpdates=new Set}addLayerUpdate(e){this.layerUpdates.add(e)}clearLayerUpdates(){this.layerUpdates.clear()}}class Nl{constructor(e=new rl(1/0,1/0,1/0),t=new rl(-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(Cl.fromArray(e,t));return this}setFromBufferAttribute(e){this.makeEmpty();for(let t=0,s=e.count;t<s;t++)this.expandByPoint(Cl.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=Cl.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,Cl):Cl.fromBufferAttribute(i,t),Cl.applyMatrix4(e.matrixWorld),this.expandByPoint(Cl);else void 0!==e.boundingBox?(null===e.boundingBox&&e.computeBoundingBox(),Rl.copy(e.boundingBox)):(null===s.boundingBox&&s.computeBoundingBox(),Rl.copy(s.boundingBox)),Rl.applyMatrix4(e.matrixWorld),this.union(Rl)}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,Cl),Cl.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(Ol),zl.subVectors(this.max,Ol),Pl.subVectors(e.a,Ol),Bl.subVectors(e.b,Ol),Il.subVectors(e.c,Ol),Dl.subVectors(Bl,Pl),Ll.subVectors(Il,Bl),Fl.subVectors(Pl,Il);let t=[0,-Dl.z,Dl.y,0,-Ll.z,Ll.y,0,-Fl.z,Fl.y,Dl.z,0,-Dl.x,Ll.z,0,-Ll.x,Fl.z,0,-Fl.x,-Dl.y,Dl.x,0,-Ll.y,Ll.x,0,-Fl.y,Fl.x,0];return!!Ul(t,Pl,Bl,Il,zl)&&(t=[1,0,0,0,1,0,0,0,1],!!Ul(t,Pl,Bl,Il,zl)&&(Vl.crossVectors(Dl,Ll),t=[Vl.x,Vl.y,Vl.z],Ul(t,Pl,Bl,Il,zl)))}clampPoint(e,t){return t.copy(e).clamp(this.min,this.max)}distanceToPoint(e){return this.clampPoint(e,Cl).distanceTo(e)}getBoundingSphere(e){return this.isEmpty()?e.makeEmpty():(this.getCenter(e.center),e.radius=.5*this.getSize(Cl).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()||(El[0].set(this.min.x,this.min.y,this.min.z).applyMatrix4(e),El[1].set(this.min.x,this.min.y,this.max.z).applyMatrix4(e),El[2].set(this.min.x,this.max.y,this.min.z).applyMatrix4(e),El[3].set(this.min.x,this.max.y,this.max.z).applyMatrix4(e),El[4].set(this.max.x,this.min.y,this.min.z).applyMatrix4(e),El[5].set(this.max.x,this.min.y,this.max.z).applyMatrix4(e),El[6].set(this.max.x,this.max.y,this.min.z).applyMatrix4(e),El[7].set(this.max.x,this.max.y,this.max.z).applyMatrix4(e),this.setFromPoints(El)),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 El=[new rl,new rl,new rl,new rl,new rl,new rl,new rl,new rl],Cl=new rl,Rl=new Nl,Pl=new rl,Bl=new rl,Il=new rl,Dl=new rl,Ll=new rl,Fl=new rl,Ol=new rl,zl=new rl,Vl=new rl,kl=new rl;function Ul(e,t,s,i,r){for(let n=0,o=e.length-3;n<=o;n+=3){kl.fromArray(e,n);const o=r.x*Math.abs(kl.x)+r.y*Math.abs(kl.y)+r.z*Math.abs(kl.z),a=t.dot(kl),l=s.dot(kl),h=i.dot(kl);if(Math.max(-Math.max(a,l,h),Math.min(a,l,h))>o)return!1}return!0}const Gl=new Nl,jl=new rl,$l=new rl;class Wl{constructor(e=new rl,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):Gl.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;jl.subVectors(e,this.center);const t=jl.lengthSq();if(t>this.radius*this.radius){const e=Math.sqrt(t),s=.5*(e-this.radius);this.center.addScaledVector(jl,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):($l.subVectors(e.center,this.center).setLength(e.radius),this.expandByPoint(jl.copy(e.center).add($l)),this.expandByPoint(jl.copy(e.center).sub($l))),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 Hl=new rl,ql=new rl,Xl=new rl,Yl=new rl,Zl=new rl,Ql=new rl,Kl=new rl;class Jl{constructor(e=new rl,t=new rl(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,Hl)),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=Hl.subVectors(e,this.origin).dot(this.direction);return t<0?this.origin.distanceToSquared(e):(Hl.copy(this.origin).addScaledVector(this.direction,t),Hl.distanceToSquared(e))}distanceSqToSegment(e,t,s,i){ql.copy(e).add(t).multiplyScalar(.5),Xl.copy(t).sub(e).normalize(),Yl.copy(this.origin).sub(ql);const r=.5*e.distanceTo(t),n=-this.direction.dot(Xl),o=Yl.dot(this.direction),a=-Yl.dot(Xl),l=Yl.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(ql).addScaledVector(Xl,c),d}intersectSphere(e,t){Hl.subVectors(e.center,this.origin);const s=Hl.dot(this.direction),i=Hl.dot(Hl)-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,Hl)}intersectTriangle(e,t,s,i,r){Zl.subVectors(t,e),Ql.subVectors(s,e),Kl.crossVectors(Zl,Ql);let n,o=this.direction.dot(Kl);if(o>0){if(i)return null;n=1}else{if(!(o<0))return null;n=-1,o=-o}Yl.subVectors(this.origin,e);const a=n*this.direction.dot(Ql.crossVectors(Yl,Ql));if(a<0)return null;const l=n*this.direction.dot(Zl.cross(Yl));if(l<0)return null;if(a+l>o)return null;const h=-n*Yl.dot(Kl);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 eh{constructor(e,t,s,i,r,n,o,a,l,h,u,c,d,p,m,f){eh.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 eh).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/th.setFromMatrixColumn(e,0).length(),r=1/th.setFromMatrixColumn(e,1).length(),n=1/th.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(ih,e,rh)}lookAt(e,t,s){const i=this.elements;return ah.subVectors(e,t),0===ah.lengthSq()&&(ah.z=1),ah.normalize(),nh.crossVectors(s,ah),0===nh.lengthSq()&&(1===Math.abs(s.z)?ah.x+=1e-4:ah.z+=1e-4,ah.normalize(),nh.crossVectors(s,ah)),nh.normalize(),oh.crossVectors(ah,nh),i[0]=nh.x,i[4]=oh.x,i[8]=ah.x,i[1]=nh.y,i[5]=oh.y,i[9]=ah.y,i[2]=nh.z,i[6]=oh.z,i[10]=ah.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],b=s[7],x=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+b*M+x*C+_*I,r[7]=y*v+b*A+x*R+_*D,r[11]=y*T+b*N+x*P+_*L,r[15]=y*S+b*E+x*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,b=o*d-l*u,x=o*c-a*u,_=n*d-l*h,w=n*c-a*h,v=n*u-o*h;return t*(m*y-f*b+g*x)-s*(p*y-f*_+g*w)+i*(p*b-m*_+g*v)-r*(p*x-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,b=p*c*l-h*f*l-p*a*d+n*f*d+h*a*g-n*c*g,x=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*b+i*x+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]=b*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]=x*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,b=a*h,x=a*u,_=s.x,w=s.y,v=s.z;return i[0]=(1-(m+g))*_,i[1]=(d+x)*_,i[2]=(p-b)*_,i[3]=0,i[4]=(d-x)*w,i[5]=(1-(c+g))*w,i[6]=(f+y)*w,i[7]=0,i[8]=(p+b)*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=th.set(i[0],i[1],i[2]).length();const n=th.set(i[4],i[5],i[6]).length(),o=th.set(i[8],i[9],i[10]).length();this.determinant()<0&&(r=-r),sh.copy(this);const a=1/r,l=1/n,h=1/o;return sh.elements[0]*=a,sh.elements[1]*=a,sh.elements[2]*=a,sh.elements[4]*=l,sh.elements[5]*=l,sh.elements[6]*=l,sh.elements[8]*=h,sh.elements[9]*=h,sh.elements[10]*=h,t.setFromRotationMatrix(sh),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===Ba)p=-(n+r)/(n-r),m=-2*n*r/(n-r);else{if(o!==Ia)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===Ba)p=-2/(n-r),m=-(n+r)/(n-r);else{if(o!==Ia)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 th=new rl,sh=new eh,ih=new rl(0,0,0),rh=new rl(1,1,1),nh=new rl,oh=new rl,ah=new rl,lh=new eh,hh=new il;class uh{constructor(e=0,t=0,s=0,i=uh.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(Za(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(-Za(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(Za(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(-Za(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(Za(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(-Za(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:Ua("Euler: .setFromRotationMatrix() encountered an unknown order: "+t)}return this._order=t,!0===s&&this._onChangeCallback(),this}setFromQuaternion(e,t,s){return lh.makeRotationFromQuaternion(e),this.setFromRotationMatrix(lh,t,s)}setFromVector3(e,t=this._order){return this.set(e.x,e.y,e.z,t)}reorder(e){return hh.setFromEuler(this),this.setFromQuaternion(hh,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}}uh.DEFAULT_ORDER="XYZ";class ch{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 dh=0;const ph=new rl,mh=new il,fh=new eh,gh=new rl,yh=new rl,bh=new rl,xh=new il,_h=new rl(1,0,0),wh=new rl(0,1,0),vh=new rl(0,0,1),Th={type:"added"},Sh={type:"removed"},Mh={type:"childadded",child:null},Ah={type:"childremoved",child:null};class Nh extends $a{constructor(){super(),this.isObject3D=!0,Object.defineProperty(this,"id",{value:dh++}),this.uuid=Ya(),this.name="",this.type="Object3D",this.parent=null,this.children=[],this.up=Nh.DEFAULT_UP.clone();const e=new rl,t=new uh,s=new il,i=new rl(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 eh},normalMatrix:{value:new al}}),this.matrix=new eh,this.matrixWorld=new eh,this.matrixAutoUpdate=Nh.DEFAULT_MATRIX_AUTO_UPDATE,this.matrixWorldAutoUpdate=Nh.DEFAULT_MATRIX_WORLD_AUTO_UPDATE,this.matrixWorldNeedsUpdate=!1,this.layers=new ch,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 mh.setFromAxisAngle(e,t),this.quaternion.multiply(mh),this}rotateOnWorldAxis(e,t){return mh.setFromAxisAngle(e,t),this.quaternion.premultiply(mh),this}rotateX(e){return this.rotateOnAxis(_h,e)}rotateY(e){return this.rotateOnAxis(wh,e)}rotateZ(e){return this.rotateOnAxis(vh,e)}translateOnAxis(e,t){return ph.copy(e).applyQuaternion(this.quaternion),this.position.add(ph.multiplyScalar(t)),this}translateX(e){return this.translateOnAxis(_h,e)}translateY(e){return this.translateOnAxis(wh,e)}translateZ(e){return this.translateOnAxis(vh,e)}localToWorld(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(this.matrixWorld)}worldToLocal(e){return this.updateWorldMatrix(!0,!1),e.applyMatrix4(fh.copy(this.matrixWorld).invert())}lookAt(e,t,s){e.isVector3?gh.copy(e):gh.set(e,t,s);const i=this.parent;this.updateWorldMatrix(!0,!1),yh.setFromMatrixPosition(this.matrixWorld),this.isCamera||this.isLight?fh.lookAt(yh,gh,this.up):fh.lookAt(gh,yh,this.up),this.quaternion.setFromRotationMatrix(fh),i&&(fh.extractRotation(i.matrixWorld),mh.setFromRotationMatrix(fh),this.quaternion.premultiply(mh.invert()))}add(e){if(arguments.length>1){for(let e=0;e<arguments.length;e++)this.add(arguments[e]);return this}return e===this?(Ga("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(Th),Mh.child=e,this.dispatchEvent(Mh),Mh.child=null):Ga("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(Sh),Ah.child=e,this.dispatchEvent(Ah),Ah.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),fh.copy(this.matrixWorld).invert(),null!==e.parent&&(e.parent.updateWorldMatrix(!0,!1),fh.multiply(e.parent.matrixWorld)),e.applyMatrix4(fh),e.removeFromParent(),e.parent=this,this.children.push(e),e.updateWorldMatrix(!1,!0),e.dispatchEvent(Th),Mh.child=e,this.dispatchEvent(Mh),Mh.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(yh,e,bh),e}getWorldScale(e){return this.updateWorldMatrix(!0,!1),this.matrixWorld.decompose(yh,xh,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}}Nh.DEFAULT_UP=new rl(0,1,0),Nh.DEFAULT_MATRIX_AUTO_UPDATE=!0,Nh.DEFAULT_MATRIX_WORLD_AUTO_UPDATE=!0;const Eh=new rl,Ch=new rl,Rh=new rl,Ph=new rl,Bh=new rl,Ih=new rl,Dh=new rl,Lh=new rl,Fh=new rl,Oh=new rl,zh=new Tl,Vh=new Tl,kh=new Tl;class Uh{constructor(e=new rl,t=new rl,s=new rl){this.a=e,this.b=t,this.c=s}static getNormal(e,t,s,i){i.subVectors(s,t),Eh.subVectors(e,t),i.cross(Eh);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){Eh.subVectors(i,t),Ch.subVectors(s,t),Rh.subVectors(e,t);const n=Eh.dot(Eh),o=Eh.dot(Ch),a=Eh.dot(Rh),l=Ch.dot(Ch),h=Ch.dot(Rh),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,Ph)&&(Ph.x>=0&&Ph.y>=0&&Ph.x+Ph.y<=1)}static getInterpolation(e,t,s,i,r,n,o,a){return null===this.getBarycoord(e,t,s,i,Ph)?(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,Ph.x),a.addScaledVector(n,Ph.y),a.addScaledVector(o,Ph.z),a)}static getInterpolatedAttribute(e,t,s,i,r,n){return zh.setScalar(0),Vh.setScalar(0),kh.setScalar(0),zh.fromBufferAttribute(e,t),Vh.fromBufferAttribute(e,s),kh.fromBufferAttribute(e,i),n.setScalar(0),n.addScaledVector(zh,r.x),n.addScaledVector(Vh,r.y),n.addScaledVector(kh,r.z),n}static isFrontFacing(e,t,s,i){return Eh.subVectors(s,t),Ch.subVectors(e,t),Eh.cross(Ch).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 Eh.subVectors(this.c,this.b),Ch.subVectors(this.a,this.b),.5*Eh.cross(Ch).length()}getMidpoint(e){return e.addVectors(this.a,this.b).add(this.c).multiplyScalar(1/3)}getNormal(e){return Uh.getNormal(this.a,this.b,this.c,e)}getPlane(e){return e.setFromCoplanarPoints(this.a,this.b,this.c)}getBarycoord(e,t){return Uh.getBarycoord(e,this.a,this.b,this.c,t)}getInterpolation(e,t,s,i,r){return Uh.getInterpolation(e,this.a,this.b,this.c,t,s,i,r)}containsPoint(e){return Uh.containsPoint(e,this.a,this.b,this.c)}isFrontFacing(e){return Uh.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;Bh.subVectors(i,s),Ih.subVectors(r,s),Lh.subVectors(e,s);const a=Bh.dot(Lh),l=Ih.dot(Lh);if(a<=0&&l<=0)return t.copy(s);Fh.subVectors(e,i);const h=Bh.dot(Fh),u=Ih.dot(Fh);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(Bh,n);Oh.subVectors(e,r);const d=Bh.dot(Oh),p=Ih.dot(Oh);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(Ih,o);const f=h*p-d*u;if(f<=0&&u-h>=0&&d-p>=0)return Dh.subVectors(r,i),o=(u-h)/(u-h+(d-p)),t.copy(i).addScaledVector(Dh,o);const g=1/(f+m+c);return n=m*g,o=c*g,t.copy(s).addScaledVector(Bh,n).addScaledVector(Ih,o)}equals(e){return e.a.equals(this.a)&&e.b.equals(this.b)&&e.c.equals(this.c)}}const Gh={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},jh={h:0,s:0,l:0},$h={h:0,s:0,l:0};function Wh(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 Hh{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=ya){return e=Math.floor(e),this.r=(e>>16&255)/255,this.g=(e>>8&255)/255,this.b=(255&e)/255,dl.colorSpaceToWorking(this,t),this}setRGB(e,t,s,i=dl.workingColorSpace){return this.r=e,this.g=t,this.b=s,dl.colorSpaceToWorking(this,i),this}setHSL(e,t,s,i=dl.workingColorSpace){if(e=Qa(e,1),t=Za(t,0,1),s=Za(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=Wh(r,i,e+1/3),this.g=Wh(r,i,e),this.b=Wh(r,i,e-1/3)}return dl.colorSpaceToWorking(this,i),this}setStyle(e,t=ya){function s(t){void 0!==t&&parseFloat(t)<1&&Ua("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:Ua("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);Ua("Color: Invalid hex color "+e)}else if(e&&e.length>0)return this.setColorName(e,t);return this}setColorName(e,t=ya){const s=Gh[e.toLowerCase()];return void 0!==s?this.setHex(s,t):Ua("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=pl(e.r),this.g=pl(e.g),this.b=pl(e.b),this}copyLinearToSRGB(e){return this.r=ml(e.r),this.g=ml(e.g),this.b=ml(e.b),this}convertSRGBToLinear(){return this.copySRGBToLinear(this),this}convertLinearToSRGB(){return this.copyLinearToSRGB(this),this}getHex(e=ya){return dl.workingToColorSpace(qh.copy(this),e),65536*Math.round(Za(255*qh.r,0,255))+256*Math.round(Za(255*qh.g,0,255))+Math.round(Za(255*qh.b,0,255))}getHexString(e=ya){return("000000"+this.getHex(e).toString(16)).slice(-6)}getHSL(e,t=dl.workingColorSpace){dl.workingToColorSpace(qh.copy(this),t);const s=qh.r,i=qh.g,r=qh.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=dl.workingColorSpace){return dl.workingToColorSpace(qh.copy(this),t),e.r=qh.r,e.g=qh.g,e.b=qh.b,e}getStyle(e=ya){dl.workingToColorSpace(qh.copy(this),e);const t=qh.r,s=qh.g,i=qh.b;return e!==ya?`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(jh),this.setHSL(jh.h+e,jh.s+t,jh.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(jh),e.getHSL($h);const s=Ka(jh.h,$h.h,t),i=Ka(jh.s,$h.s,t),r=Ka(jh.l,$h.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 qh=new Hh;Hh.NAMES=Gh;let Xh=0;class Yh extends $a{constructor(){super(),this.isMaterial=!0,Object.defineProperty(this,"id",{value:Xh++}),this.uuid=Ya(),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=Yn,this.blendDst=Zn,this.blendEquation=Gn,this.blendSrcAlpha=null,this.blendDstAlpha=null,this.blendEquationAlpha=null,this.blendColor=new Hh(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=wa,this.stencilZFail=wa,this.stencilZPass=wa,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){Ua(`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:Ua(`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!==Yn&&(s.blendSrc=this.blendSrc),this.blendDst!==Zn&&(s.blendDst=this.blendDst),this.blendEquation!==Gn&&(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!==wa&&(s.stencilFail=this.stencilFail),this.stencilZFail!==wa&&(s.stencilZFail=this.stencilZFail),this.stencilZPass!==wa&&(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 Zh extends Yh{constructor(e){super(),this.isMeshBasicMaterial=!0,this.type="MeshBasicMaterial",this.color=new Hh(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 uh,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 Qh=Kh();function Kh(){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 Jh(e){Math.abs(e)>65504&&Ua("DataUtils.toHalfFloat(): Value out of range."),e=Za(e,-65504,65504),Qh.floatView[0]=e;const t=Qh.uint32View[0],s=t>>23&511;return Qh.baseTable[s]+((8388607&t)>>Qh.shiftTable[s])}function eu(e){const t=e>>10;return Qh.uint32View[0]=Qh.mantissaTable[Qh.offsetTable[t]+(1023&e)]+Qh.exponentTable[t],Qh.floatView[0]}const tu=new rl,su=new sl;let iu=0;class ru{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:iu++}),this.name="",this.array=e,this.itemSize=t,this.count=void 0!==e?e.length/t:0,this.normalized=s,this.usage=Ra,this.updateRanges=[],this.gpuType=_o,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++)su.fromBufferAttribute(this,t),su.applyMatrix3(e),this.setXY(t,su.x,su.y);else if(3===this.itemSize)for(let t=0,s=this.count;t<s;t++)tu.fromBufferAttribute(this,t),tu.applyMatrix3(e),this.setXYZ(t,tu.x,tu.y,tu.z);return this}applyMatrix4(e){for(let t=0,s=this.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}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=Ja(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=el(s,this.array)),this.array[e*this.itemSize+t]=s,this}getX(e){let t=this.array[e*this.itemSize];return this.normalized&&(t=Ja(t,this.array)),t}setX(e,t){return this.normalized&&(t=el(t,this.array)),this.array[e*this.itemSize]=t,this}getY(e){let t=this.array[e*this.itemSize+1];return this.normalized&&(t=Ja(t,this.array)),t}setY(e,t){return this.normalized&&(t=el(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=Ja(t,this.array)),t}setZ(e,t){return this.normalized&&(t=el(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=Ja(t,this.array)),t}setW(e,t){return this.normalized&&(t=el(t,this.array)),this.array[e*this.itemSize+3]=t,this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=el(t,this.array),s=el(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=el(t,this.array),s=el(s,this.array),i=el(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=el(t,this.array),s=el(s,this.array),i=el(i,this.array),r=el(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!==Ra&&(e.usage=this.usage),e}}class nu extends ru{constructor(e,t,s){super(new Uint16Array(e),t,s)}}class ou extends ru{constructor(e,t,s){super(new Uint32Array(e),t,s)}}class au extends ru{constructor(e,t,s){super(new Uint16Array(e),t,s),this.isFloat16BufferAttribute=!0}getX(e){let t=eu(this.array[e*this.itemSize]);return this.normalized&&(t=Ja(t,this.array)),t}setX(e,t){return this.normalized&&(t=el(t,this.array)),this.array[e*this.itemSize]=Jh(t),this}getY(e){let t=eu(this.array[e*this.itemSize+1]);return this.normalized&&(t=Ja(t,this.array)),t}setY(e,t){return this.normalized&&(t=el(t,this.array)),this.array[e*this.itemSize+1]=Jh(t),this}getZ(e){let t=eu(this.array[e*this.itemSize+2]);return this.normalized&&(t=Ja(t,this.array)),t}setZ(e,t){return this.normalized&&(t=el(t,this.array)),this.array[e*this.itemSize+2]=Jh(t),this}getW(e){let t=eu(this.array[e*this.itemSize+3]);return this.normalized&&(t=Ja(t,this.array)),t}setW(e,t){return this.normalized&&(t=el(t,this.array)),this.array[e*this.itemSize+3]=Jh(t),this}setXY(e,t,s){return e*=this.itemSize,this.normalized&&(t=el(t,this.array),s=el(s,this.array)),this.array[e+0]=Jh(t),this.array[e+1]=Jh(s),this}setXYZ(e,t,s,i){return e*=this.itemSize,this.normalized&&(t=el(t,this.array),s=el(s,this.array),i=el(i,this.array)),this.array[e+0]=Jh(t),this.array[e+1]=Jh(s),this.array[e+2]=Jh(i),this}setXYZW(e,t,s,i,r){return e*=this.itemSize,this.normalized&&(t=el(t,this.array),s=el(s,this.array),i=el(i,this.array),r=el(r,this.array)),this.array[e+0]=Jh(t),this.array[e+1]=Jh(s),this.array[e+2]=Jh(i),this.array[e+3]=Jh(r),this}}class lu extends ru{constructor(e,t,s){super(new Float32Array(e),t,s)}}let hu=0;const uu=new eh,cu=new Nh,du=new rl,pu=new Nl,mu=new Nl,fu=new rl;class gu extends $a{constructor(){super(),this.isBufferGeometry=!0,Object.defineProperty(this,"id",{value:hu++}),this.uuid=Ya(),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(Fa(e)?ou:nu)(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 al).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 uu.makeRotationFromQuaternion(e),this.applyMatrix4(uu),this}rotateX(e){return uu.makeRotationX(e),this.applyMatrix4(uu),this}rotateY(e){return uu.makeRotationY(e),this.applyMatrix4(uu),this}rotateZ(e){return uu.makeRotationZ(e),this.applyMatrix4(uu),this}translate(e,t,s){return uu.makeTranslation(e,t,s),this.applyMatrix4(uu),this}scale(e,t,s){return uu.makeScale(e,t,s),this.applyMatrix4(uu),this}lookAt(e){return cu.lookAt(e),cu.updateMatrix(),this.applyMatrix4(cu.matrix),this}center(){return this.computeBoundingBox(),this.boundingBox.getCenter(du).negate(),this.translate(du.x,du.y,du.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 lu(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&&Ua("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 Nl);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return Ga("BufferGeometry.computeBoundingBox(): GLBufferAttribute requires a manual bounding box.",this),void this.boundingBox.set(new rl(-1/0,-1/0,-1/0),new rl(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];pu.setFromBufferAttribute(s),this.morphTargetsRelative?(fu.addVectors(this.boundingBox.min,pu.min),this.boundingBox.expandByPoint(fu),fu.addVectors(this.boundingBox.max,pu.max),this.boundingBox.expandByPoint(fu)):(this.boundingBox.expandByPoint(pu.min),this.boundingBox.expandByPoint(pu.max))}}else this.boundingBox.makeEmpty();(isNaN(this.boundingBox.min.x)||isNaN(this.boundingBox.min.y)||isNaN(this.boundingBox.min.z))&&Ga('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 Wl);const e=this.attributes.position,t=this.morphAttributes.position;if(e&&e.isGLBufferAttribute)return Ga("BufferGeometry.computeBoundingSphere(): GLBufferAttribute requires a manual bounding sphere.",this),void this.boundingSphere.set(new rl,1/0);if(e){const s=this.boundingSphere.center;if(pu.setFromBufferAttribute(e),t)for(let e=0,s=t.length;e<s;e++){const s=t[e];mu.setFromBufferAttribute(s),this.morphTargetsRelative?(fu.addVectors(pu.min,mu.min),pu.expandByPoint(fu),fu.addVectors(pu.max,mu.max),pu.expandByPoint(fu)):(pu.expandByPoint(mu.min),pu.expandByPoint(mu.max))}pu.getCenter(s);let i=0;for(let t=0,r=e.count;t<r;t++)fu.fromBufferAttribute(e,t),i=Math.max(i,s.distanceToSquared(fu));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++)fu.fromBufferAttribute(n,t),o&&(du.fromBufferAttribute(e,t),fu.add(du)),i=Math.max(i,s.distanceToSquared(fu))}this.boundingSphere.radius=Math.sqrt(i),isNaN(this.boundingSphere.radius)&&Ga('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 Ga("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 ru(new Float32Array(4*s.count),4));const n=this.getAttribute("tangent"),o=[],a=[];for(let e=0;e<s.count;e++)o[e]=new rl,a[e]=new rl;const l=new rl,h=new rl,u=new rl,c=new sl,d=new sl,p=new sl,m=new rl,f=new rl;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 b=new rl,x=new rl,_=new rl,w=new rl;function v(e){_.fromBufferAttribute(i,e),w.copy(_);const t=o[e];b.copy(t),b.sub(_.multiplyScalar(_.dot(t))).normalize(),x.crossVectors(w,t);const s=x.dot(a[e])<0?-1:1;n.setXYZW(e,b.x,b.y,b.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 ru(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 rl,r=new rl,n=new rl,o=new rl,a=new rl,l=new rl,h=new rl,u=new rl;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++)fu.fromBufferAttribute(e,t),fu.normalize(),e.setXYZ(t,fu.x,fu.y,fu.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 ru(n,i,r)}if(null===this.index)return Ua("BufferGeometry.toNonIndexed(): BufferGeometry is already non-indexed."),this;const t=new gu,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 yu=new eh,bu=new Jl,xu=new Wl,_u=new rl,wu=new rl,vu=new rl,Tu=new rl,Su=new rl,Mu=new rl,Au=new rl,Nu=new rl;class Eu extends Nh{constructor(e=new gu,t=new Zh){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){Mu.set(0,0,0);for(let s=0,i=r.length;s<i;s++){const i=o[s],a=r[s];0!==i&&(Su.fromBufferAttribute(a,e),n?Mu.addScaledVector(Su,i):Mu.addScaledVector(Su.sub(t),i))}t.add(Mu)}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(),xu.copy(s.boundingSphere),xu.applyMatrix4(r),bu.copy(e.ray).recast(e.near),!1===xu.containsPoint(bu.origin)){if(null===bu.intersectSphere(xu,_u))return;if(bu.origin.distanceToSquared(_u)>(e.far-e.near)**2)return}yu.copy(r).invert(),bu.copy(e.ray).applyMatrix4(yu),null!==s.boundingBox&&!1===bu.intersectsBox(s.boundingBox)||this._computeIntersections(e,t,bu)}}_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=Cu(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=Cu(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=Cu(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=Cu(this,n,e,s,l,h,u,r,r+1,r+2),i&&(i.faceIndex=Math.floor(r/3),t.push(i))}}}}function Cu(e,t,s,i,r,n,o,a,l,h){e.getVertexPosition(a,wu),e.getVertexPosition(l,vu),e.getVertexPosition(h,Tu);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;Nu.copy(a),Nu.applyMatrix4(e.matrixWorld);const h=s.ray.origin.distanceTo(Nu);return h<s.near||h>s.far?null:{distance:h,point:Nu.clone(),object:e}}(e,t,s,i,wu,vu,Tu,Au);if(u){const e=new rl;Uh.getBarycoord(Au,wu,vu,Tu,e),r&&(u.uv=Uh.getInterpolatedAttribute(r,a,l,h,e,new sl)),n&&(u.uv1=Uh.getInterpolatedAttribute(n,a,l,h,e,new sl)),o&&(u.normal=Uh.getInterpolatedAttribute(o,a,l,h,e,new rl),u.normal.dot(i.direction)>0&&u.normal.multiplyScalar(-1));const t={a:a,b:l,c:h,normal:new rl,materialIndex:0};Uh.getNormal(wu,vu,Tu,t.normal),u.face=t,u.barycoord=e}return u}class Ru extends gu{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 b=n/f,x=p/g,_=n/2,w=p/2,v=m/2,T=f+1,S=g+1;let M=0,A=0;const N=new rl;for(let n=0;n<S;n++){const o=n*x-w;for(let a=0;a<T;a++){const c=a*b-_;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 lu(l,3)),this.setAttribute("normal",new lu(h,3)),this.setAttribute("uv",new lu(u,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new Ru(e.width,e.height,e.depth,e.widthSegments,e.heightSegments,e.depthSegments)}}function Pu(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?(Ua("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 Bu extends Yh{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=Pu(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 Iu extends Nh{constructor(){super(),this.isCamera=!0,this.type="Camera",this.matrixWorldInverse=new eh,this.projectionMatrix=new eh,this.projectionMatrixInverse=new eh,this.coordinateSystem=Ba,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 Du=new rl,Lu=new sl,Fu=new sl;class Ou extends Iu{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*Xa*Math.atan(t),this.updateProjectionMatrix()}getFocalLength(){const e=Math.tan(.5*qa*this.fov);return.5*this.getFilmHeight()/e}getEffectiveFOV(){return 2*Xa*Math.atan(Math.tan(.5*qa*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){Du.set(-1,-1,.5).applyMatrix4(this.projectionMatrixInverse),t.set(Du.x,Du.y).multiplyScalar(-e/Du.z),Du.set(1,1,.5).applyMatrix4(this.projectionMatrixInverse),s.set(Du.x,Du.y).multiplyScalar(-e/Du.z)}getViewSize(e,t){return this.getViewBounds(e,Lu,Fu),t.subVectors(Fu,Lu)}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*qa*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 zu=-90;class Vu extends Nh{constructor(e,t,s){super(),this.type="CubeCamera",this.renderTarget=s,this.coordinateSystem=null,this.activeMipmapLevel=0;const i=new Ou(zu,1,e,t);i.layers=this.layers,this.add(i);const r=new Ou(zu,1,e,t);r.layers=this.layers,this.add(r);const n=new Ou(zu,1,e,t);n.layers=this.layers,this.add(n);const o=new Ou(zu,1,e,t);o.layers=this.layers,this.add(o);const a=new Ou(zu,1,e,t);a.layers=this.layers,this.add(a);const l=new Ou(zu,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===Ba)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!==Ia)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 ku extends vl{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 Uu extends Ml{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 ku(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 Ru(5,5,5),r=new Bu({name:"CubemapFromEquirect",uniforms:Pu(s.uniforms),vertexShader:s.vertexShader,fragmentShader:s.fragmentShader,side:1,blending:0});r.uniforms.tEquirect.value=t;const n=new Eu(i,r),o=t.minFilter;t.minFilter===po&&(t.minFilter=uo);return new Vu(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 Gu extends Nh{constructor(){super(),this.isGroup=!0,this.type="Group"}}const ju={type:"move"};class $u{constructor(){this._targetRay=null,this._grip=null,this._hand=null}getHandSpace(){return null===this._hand&&(this._hand=new Gu,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 Gu,this._targetRay.matrixAutoUpdate=!1,this._targetRay.visible=!1,this._targetRay.hasLinearVelocity=!1,this._targetRay.linearVelocity=new rl,this._targetRay.hasAngularVelocity=!1,this._targetRay.angularVelocity=new rl),this._targetRay}getGripSpace(){return null===this._grip&&(this._grip=new Gu,this._grip.matrixAutoUpdate=!1,this._grip.visible=!1,this._grip.hasLinearVelocity=!1,this._grip.linearVelocity=new rl,this._grip.hasAngularVelocity=!1,this._grip.angularVelocity=new rl),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(ju)))}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 Gu;s.matrixAutoUpdate=!1,s.visible=!1,e.joints[t.jointName]=s,e.add(s)}return e.joints[t.jointName]}}class Wu extends Nh{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 uh,this.environmentIntensity=1,this.environmentRotation=new uh,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 Hu{constructor(e,t){this.isInterleavedBuffer=!0,this.array=e,this.stride=t,this.count=void 0!==e?e.length/t:0,this.usage=Ra,this.updateRanges=[],this.version=0,this.uuid=Ya()}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=Ya()),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=Ya()),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 qu=new rl;class Xu{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++)qu.fromBufferAttribute(this,t),qu.applyMatrix4(e),this.setXYZ(t,qu.x,qu.y,qu.z);return this}applyNormalMatrix(e){for(let t=0,s=this.count;t<s;t++)qu.fromBufferAttribute(this,t),qu.applyNormalMatrix(e),this.setXYZ(t,qu.x,qu.y,qu.z);return this}transformDirection(e){for(let t=0,s=this.count;t<s;t++)qu.fromBufferAttribute(this,t),qu.transformDirection(e),this.setXYZ(t,qu.x,qu.y,qu.z);return this}getComponent(e,t){let s=this.array[e*this.data.stride+this.offset+t];return this.normalized&&(s=Ja(s,this.array)),s}setComponent(e,t,s){return this.normalized&&(s=el(s,this.array)),this.data.array[e*this.data.stride+this.offset+t]=s,this}setX(e,t){return this.normalized&&(t=el(t,this.array)),this.data.array[e*this.data.stride+this.offset]=t,this}setY(e,t){return this.normalized&&(t=el(t,this.array)),this.data.array[e*this.data.stride+this.offset+1]=t,this}setZ(e,t){return this.normalized&&(t=el(t,this.array)),this.data.array[e*this.data.stride+this.offset+2]=t,this}setW(e,t){return this.normalized&&(t=el(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=Ja(t,this.array)),t}getY(e){let t=this.data.array[e*this.data.stride+this.offset+1];return this.normalized&&(t=Ja(t,this.array)),t}getZ(e){let t=this.data.array[e*this.data.stride+this.offset+2];return this.normalized&&(t=Ja(t,this.array)),t}getW(e){let t=this.data.array[e*this.data.stride+this.offset+3];return this.normalized&&(t=Ja(t,this.array)),t}setXY(e,t,s){return e=e*this.data.stride+this.offset,this.normalized&&(t=el(t,this.array),s=el(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=el(t,this.array),s=el(s,this.array),i=el(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=el(t,this.array),s=el(s,this.array),i=el(i,this.array),r=el(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){ka("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 ru(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 Xu(e.interleavedBuffers[this.data.uuid],this.itemSize,this.offset,this.normalized)}toJSON(e){if(void 0===e){ka("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 Yu extends Yh{constructor(e){super(),this.isSpriteMaterial=!0,this.type="SpriteMaterial",this.color=new Hh(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 Zu extends vl{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 Qu extends ru{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 Ku=new rl,Ju=new rl,ec=new al;class tc{constructor(e=new rl(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=Ku.subVectors(s,t).cross(Ju.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(Ku),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||ec.getNormalMatrix(e),i=this.coplanarPoint(Ku).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 sc=new Wl,ic=new sl(.5,.5),rc=new rl;class nc{constructor(e=new tc,t=new tc,s=new tc,i=new tc,r=new tc,n=new tc){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],b=r[13],x=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,_+b).normalize(),i[3].setComponents(l-o,d-u,g-m,_-b).normalize(),s)i[4].setComponents(a,c,f,x).normalize(),i[5].setComponents(l-a,d-c,g-f,_-x).normalize();else if(i[4].setComponents(l-a,d-c,g-f,_-x).normalize(),t===Ba)i[5].setComponents(l+a,d+c,g+f,_+x).normalize();else{if(t!==Ia)throw new Error("THREE.Frustum.setFromProjectionMatrix(): Invalid coordinate system: "+t);i[5].setComponents(a,c,f,x).normalize()}return this}intersectsObject(e){if(void 0!==e.boundingSphere)null===e.boundingSphere&&e.computeBoundingSphere(),sc.copy(e.boundingSphere).applyMatrix4(e.matrixWorld);else{const t=e.geometry;null===t.boundingSphere&&t.computeBoundingSphere(),sc.copy(t.boundingSphere).applyMatrix4(e.matrixWorld)}return this.intersectsSphere(sc)}intersectsSprite(e){sc.center.set(0,0,0);const t=ic.distanceTo(e.center);return sc.radius=.7071067811865476+t,sc.applyMatrix4(e.matrixWorld),this.intersectsSphere(sc)}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(rc.x=i.normal.x>0?e.max.x:e.min.x,rc.y=i.normal.y>0?e.max.y:e.min.y,rc.z=i.normal.z>0?e.max.z:e.min.z,i.distanceToPoint(rc)<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 oc=new eh,ac=new nc;class lc{constructor(){this.coordinateSystem=Ba}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(oc.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),ac.setFromProjectionMatrix(oc,i.coordinateSystem,i.reversedDepth),ac.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(oc.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),ac.setFromProjectionMatrix(oc,i.coordinateSystem,i.reversedDepth),ac.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(oc.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),ac.setFromProjectionMatrix(oc,i.coordinateSystem,i.reversedDepth),ac.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(oc.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),ac.setFromProjectionMatrix(oc,i.coordinateSystem,i.reversedDepth),ac.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(oc.multiplyMatrices(i.projectionMatrix,i.matrixWorldInverse),ac.setFromProjectionMatrix(oc,i.coordinateSystem,i.reversedDepth),ac.containsPoint(e))return!0}return!1}clone(){return new lc}}class hc extends Yh{constructor(e){super(),this.isLineBasicMaterial=!0,this.type="LineBasicMaterial",this.color=new Hh(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 uc extends Yh{constructor(e){super(),this.isPointsMaterial=!0,this.type="PointsMaterial",this.color=new Hh(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 cc extends vl{constructor(e,t){super({width:e,height:t}),this.isFramebufferTexture=!0,this.magFilter=ao,this.minFilter=ao,this.generateMipmaps=!1,this.needsUpdate=!0}}class dc extends vl{constructor(e,t,s=1014,i,r,n,o=1003,a=1003,l,h=1026,u=1){if(h!==Co&&h!==Ro)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 bl(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 pc extends dc{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 mc extends gu{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 sl,m=new rl;let y=0;const b=!0===s?e:t,x=!0===s?1:-1;for(let e=1;e<=i;e++)u.push(0,f*x,0),c.push(0,x,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=b*r,m.y=f*x,m.z=b*s,u.push(m.x,m.y,m.z),c.push(0,x,0),n.x=.5*s+.5,n.y=.5*r*x+.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 rl,y=new rl;let b=0;const x=(t-e)/s;for(let l=0;l<=r;l++){const h=[],g=l/r,b=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=b*l,y.y=-g*s+f,y.z=b*m,u.push(y.x,y.y,y.z),n.set(l,x,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),b+=3),(t>0||i!==r-1)&&(h.push(o,a,l),b+=3)}l.addGroup(g,b,0),g+=b}(),!1===n&&(e>0&&y(!0),t>0&&y(!1)),this.setIndex(h),this.setAttribute("position",new lu(u,3)),this.setAttribute("normal",new lu(c,3)),this.setAttribute("uv",new lu(d,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new mc(e.radiusTop,e.radiusBottom,e.height,e.radialSegments,e.heightSegments,e.openEnded,e.thetaStart,e.thetaLength)}}class fc extends gu{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 lu(p,3)),this.setAttribute("normal",new lu(m,3)),this.setAttribute("uv",new lu(f,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new fc(e.width,e.height,e.widthSegments,e.heightSegments)}}class gc extends gu{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 rl,c=new rl,d=[],p=[],m=[],f=[];for(let d=0;d<=s;d++){const g=[],y=d/s;let b=0;0===d&&0===n?b=.5/t:d===s&&a===Math.PI&&(b=-.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+b,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 lu(p,3)),this.setAttribute("normal",new lu(m,3)),this.setAttribute("uv",new lu(f,2))}copy(e){return super.copy(e),this.parameters=Object.assign({},e.parameters),this}static fromJSON(e){return new gc(e.radius,e.widthSegments,e.heightSegments,e.phiStart,e.phiLength,e.thetaStart,e.thetaLength)}}class yc extends Yh{constructor(e){super(),this.isShadowMaterial=!0,this.type="ShadowMaterial",this.color=new Hh(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 bc extends Yh{constructor(e){super(),this.isMeshStandardMaterial=!0,this.type="MeshStandardMaterial",this.defines={STANDARD:""},this.color=new Hh(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 Hh(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new sl(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 uh,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 xc extends bc{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 sl(1,1),this.clearcoatNormalMap=null,this.ior=1.5,Object.defineProperty(this,"reflectivity",{get:function(){return Za(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 Hh(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 Hh(1,1,1),this.specularIntensity=1,this.specularIntensityMap=null,this.specularColor=new Hh(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 _c extends Yh{constructor(e){super(),this.isMeshPhongMaterial=!0,this.type="MeshPhongMaterial",this.color=new Hh(16777215),this.specular=new Hh(1118481),this.shininess=30,this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Hh(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new sl(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new uh,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 wc extends Yh{constructor(e){super(),this.isMeshToonMaterial=!0,this.defines={TOON:""},this.type="MeshToonMaterial",this.color=new Hh(16777215),this.map=null,this.gradientMap=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Hh(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new sl(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 vc extends Yh{constructor(e){super(),this.isMeshNormalMaterial=!0,this.type="MeshNormalMaterial",this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new sl(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 Tc extends Yh{constructor(e){super(),this.isMeshLambertMaterial=!0,this.type="MeshLambertMaterial",this.color=new Hh(16777215),this.map=null,this.lightMap=null,this.lightMapIntensity=1,this.aoMap=null,this.aoMapIntensity=1,this.emissive=new Hh(0),this.emissiveIntensity=1,this.emissiveMap=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new sl(1,1),this.displacementMap=null,this.displacementScale=1,this.displacementBias=0,this.specularMap=null,this.alphaMap=null,this.envMap=null,this.envMapRotation=new uh,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 Sc extends Yh{constructor(e){super(),this.isMeshMatcapMaterial=!0,this.defines={MATCAP:""},this.type="MeshMatcapMaterial",this.color=new Hh(16777215),this.matcap=null,this.map=null,this.bumpMap=null,this.bumpScale=1,this.normalMap=null,this.normalMapType=0,this.normalScale=new sl(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 Mc extends hc{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 Ac extends Nh{constructor(e,t=1){super(),this.isLight=!0,this.type="Light",this.color=new Hh(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 Nc extends Ac{constructor(e,t,s){super(e,s),this.isHemisphereLight=!0,this.type="HemisphereLight",this.position.copy(Nh.DEFAULT_UP),this.updateMatrix(),this.groundColor=new Hh(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 Ec=new eh,Cc=new rl,Rc=new rl;class Pc{constructor(e){this.camera=e,this.intensity=1,this.bias=0,this.normalBias=0,this.radius=1,this.blurSamples=8,this.mapSize=new sl(512,512),this.mapType=mo,this.map=null,this.mapPass=null,this.matrix=new eh,this.autoUpdate=!0,this.needsUpdate=!1,this._frustum=new nc,this._frameExtents=new sl(1,1),this._viewportCount=1,this._viewports=[new Tl(0,0,1,1)]}getViewportCount(){return this._viewportCount}getFrustum(){return this._frustum}updateMatrices(e){const t=this.camera,s=this.matrix;Cc.setFromMatrixPosition(e.matrixWorld),t.position.copy(Cc),Rc.setFromMatrixPosition(e.target.matrixWorld),t.lookAt(Rc),t.updateMatrixWorld(),Ec.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),this._frustum.setFromProjectionMatrix(Ec,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(Ec)}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 Bc extends Pc{constructor(){super(new Ou(50,1,.5,500)),this.isSpotLightShadow=!0,this.focus=1,this.aspect=1}updateMatrices(e){const t=this.camera,s=2*Xa*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 Ic extends Ac{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(Nh.DEFAULT_UP),this.updateMatrix(),this.target=new Nh,this.distance=s,this.angle=i,this.penumbra=r,this.decay=n,this.map=null,this.shadow=new Bc}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 Dc extends Pc{constructor(){super(new Ou(90,1,.5,500)),this.isPointLightShadow=!0}}class Lc extends Ac{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 Dc}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 Fc extends Iu{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 Oc extends Pc{constructor(){super(new Fc(-5,5,5,-5,.5,500)),this.isDirectionalLightShadow=!0}}class zc extends Ac{constructor(e,t){super(e,t),this.isDirectionalLight=!0,this.type="DirectionalLight",this.position.copy(Nh.DEFAULT_UP),this.updateMatrix(),this.target=new Nh,this.shadow=new Oc}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 Vc extends Ac{constructor(e,t){super(e,t),this.isAmbientLight=!0,this.type="AmbientLight"}}class kc extends Ac{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 Uc{constructor(){this.isSphericalHarmonics3=!0,this.coefficients=[];for(let e=0;e<9;e++)this.coefficients.push(new rl)}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 Gc extends Ac{constructor(e=new Uc,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 jc extends Ou{constructor(e=[]){super(),this.isArrayCamera=!0,this.isMultiViewCamera=!1,this.cameras=e}}class $c extends Hu{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 Wc{constructor(e,t,s,i){Wc.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 Hc(e,t,s,i){const r=function(e){switch(e){case mo:case fo:return{byteLength:1,components:1};case yo:case go:case wo:return{byteLength:2,components:1};case vo:case To:return{byteLength:2,components:4};case xo:case bo:case _o:return{byteLength:4,components:1};case Mo:case Ao:return{byteLength:4,components:3}}throw new Error(`Unknown texture type ${e}.`)}(i);switch(s){case 1021:return e*t;case Po:case Bo:return e*t/r.components*r.byteLength;case Io:case Do:return e*t*2/r.components*r.byteLength;case No:return e*t*3/r.components*r.byteLength;case Eo:case Lo:return e*t*4/r.components*r.byteLength;case Fo:case Oo:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case zo:case Vo:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Uo:case jo:return Math.max(e,16)*Math.max(t,8)/4;case ko:case Go:return Math.max(e,8)*Math.max(t,8)/2;case $o:case Wo:case qo:case Xo:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*8;case Ho:case Yo:case Zo:case Qo:return Math.floor((e+3)/4)*Math.floor((t+3)/4)*16;case Ko:return Math.floor((e+4)/5)*Math.floor((t+3)/4)*16;case Jo:return Math.floor((e+4)/5)*Math.floor((t+4)/5)*16;case ea:return Math.floor((e+5)/6)*Math.floor((t+4)/5)*16;case ta:return Math.floor((e+5)/6)*Math.floor((t+5)/6)*16;case sa:return Math.floor((e+7)/8)*Math.floor((t+4)/5)*16;case ia:return Math.floor((e+7)/8)*Math.floor((t+5)/6)*16;case ra:return Math.floor((e+7)/8)*Math.floor((t+7)/8)*16;case na:return Math.floor((e+9)/10)*Math.floor((t+4)/5)*16;case oa:return Math.floor((e+9)/10)*Math.floor((t+5)/6)*16;case aa:return Math.floor((e+9)/10)*Math.floor((t+7)/8)*16;case la:return Math.floor((e+9)/10)*Math.floor((t+9)/10)*16;case ha:return Math.floor((e+11)/12)*Math.floor((t+9)/10)*16;case ua:return Math.floor((e+11)/12)*Math.floor((t+11)/12)*16;case ca:case 36494:case 36495:return Math.ceil(e/4)*Math.ceil(t/4)*16;case da:case pa:return Math.ceil(e/4)*Math.ceil(t/4)*8;case ma:case fa: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:Un}})),"undefined"!=typeof window&&(window.__THREE__?Ua("WARNING: Multiple instances of Three.js being imported."):window.__THREE__=Un)
7
+ /**
8
+ * @license
9
+ * Copyright 2010-2025 Three.js Authors
10
+ * SPDX-License-Identifier: MIT
11
+ */;const qc=["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"],Xc=new WeakMap;class Yc{constructor(e){this.renderObjects=new WeakMap,this.hasNode=this.containsNode(e),this.hasAnimation=!0===e.object.isSkinnedMesh,this.refreshUniforms=qc,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(Xc.has(e)){const s=Xc.get(e);if(s.renderId===t)return s.lightsData}const s=this.getLightsData(e.getLights());return Xc.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 Zc(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 Qc=e=>Zc(e),Kc=e=>Zc(e),Jc=(...e)=>Zc(e),ed=new Map([[1,"float"],[2,"vec2"],[3,"vec3"],[4,"vec4"],[9,"mat3"],[16,"mat4"]]),td=new WeakMap;function sd(e){return ed.get(e)}function id(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 rd(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 Ga("TSL: Unsupported type:",e)}function nd(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 Ga("TSL: Unsupported type:",e)}function od(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 Ga("TSL: Unsupported type:",e)}function ad(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 ld(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 Hh(...t):"vec2"===s?new sl(...t):"vec3"===s?new rl(...t):"vec4"===s?new Tl(...t):"mat2"===s?new Wc(...t):"mat3"===s?new al(...t):"mat4"===s?new eh(...t):"bool"===e?t[0]||!1:"float"===e||"int"===e||"uint"===e?t[0]||0:"string"===e?t[0]||"":"ArrayBuffer"===e?cd(t[0]):null}function hd(e){let t=td.get(e);return void 0===t&&(t={},td.set(e,t)),t}function ud(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 cd(e){return Uint8Array.from(atob(e),e=>e.charCodeAt(0)).buffer}const dd={VERTEX:"vertex",FRAGMENT:"fragment"},pd={NONE:"none",FRAME:"frame",RENDER:"render",OBJECT:"object"},md={READ_ONLY:"readOnly",WRITE_ONLY:"writeOnly",READ_WRITE:"readWrite"},fd=["fragment","vertex"],gd=["setup","analyze","generate"],yd=[...fd,"compute"],bd=["x","y","z","w"],xd={analyze:"setup",generate:"analyze"};let _d=0;class wd extends $a{static get type(){return"Node"}constructor(e=null){super(),this.nodeType=e,this.updateType=pd.NONE,this.updateBeforeType=pd.NONE,this.updateAfterType=pd.NONE,this.uuid=tl.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:_d++})}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,pd.FRAME)}onRenderUpdate(e){return this.onUpdate(e,pd.RENDER)}onObjectUpdate(e){return this.onUpdate(e,pd.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(Qc(i.slice(0,-4)),r.getCacheKey(e,t));this._cacheKey=Jc(Kc(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(){Ua("Abstract function.")}updateAfter(){Ua("Abstract function.")}update(){Ua("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=xd[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):(Ua("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&&(Ga(`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 vd extends wd{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 Td extends wd{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 Sd extends wd{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 Md extends Sd{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){Ga(`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&&(Ga(`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 Ad=bd.join("");class Nd extends wd{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(bd.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===Ad.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 Ed extends Sd{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=bd[e];t===s[0]?(u.push(a),e+=s.length-1):u.push(l+"."+t)}return`${e.getType(r)}( ${u.join(", ")} )`}}class Cd extends Sd{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=bd[e];s===t[h]?(l.push("1.0 - "+o+"."+s),h++):l.push(o+"."+s)}return`${e.getType(i)}( ${l.join(", ")} )`}}class Rd extends wd{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?ad(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=ad(this.value),e.nodeType=this.nodeType,"ArrayBuffer"===e.valueType&&(e.value=ud(e.value)),e.precision=this.precision}deserialize(e){super.deserialize(e),this.nodeType=e.nodeType,this.value=Array.isArray(e.value)?ld(e.valueType,...e.value):e.value,this.precision=e.precision||null,this.value&&this.value.fromArray&&(this.value=this.value.fromArray(e.value))}generate(){Ua("Abstract function.")}}const Pd=/float|u?int/;class Bd extends Rd{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 Pd.test(s)&&Pd.test(t)?e.generateConst(t,this.value):e.format(this.generateConst(e),s,t)}}class Id extends wd{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)){Ua(`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 Dd=null;const Ld=new Map;function Fd(e,t){if(Ld.has(e))Ua(`TSL: Redefinition of method chaining '${e}'.`);else{if("function"!=typeof t)throw new Error(`THREE.TSL: Node element ${e} is not a function`);Ld.set(e,t),"assign"!==e&&(wd.prototype[e]=function(...e){return this.isStackNode?this.addToStack(t(...e)):t(this,...e)},wd.prototype[e+"Assign"]=function(...e){return this.isStackNode?this.assign(e[0],t(...e)):this.assign(t(this,...e))})}}const Od=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("");wd.prototype.assign=function(...e){if(!0!==this.isStackNode)return null!==Dd?Dd.assign(this,...e):Ga("TSL: No stack defined for assign operation. Make sure the assign is inside a Fn()."),this;{const t=Ld.get("assign");return this.addToStack(t(...e))}},wd.prototype.toVarIntent=function(){return this},wd.prototype.get=function(e){return new Id(this,e)};const zd={};function Vd(e,t,s){zd[e]=zd[t]=zd[s]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new Nd(this,e),this._cache[e]=t),t},set(t){this[e].assign(cp(t))}};const i=e.toUpperCase(),r=t.toUpperCase(),n=s.toUpperCase();wd.prototype["set"+i]=wd.prototype["set"+r]=wd.prototype["set"+n]=function(t){const s=Od(e);return new Ed(this,s,cp(t))},wd.prototype["flip"+i]=wd.prototype["flip"+r]=wd.prototype["flip"+n]=function(){const t=Od(e);return new Cd(this,t)}}const kd=["x","y","z","w"],Ud=["r","g","b","a"],Gd=["s","t","p","q"];for(let e=0;e<4;e++){let t=kd[e],s=Ud[e],i=Gd[e];Vd(t,s,i);for(let r=0;r<4;r++){t=kd[e]+kd[r],s=Ud[e]+Ud[r],i=Gd[e]+Gd[r],Vd(t,s,i);for(let n=0;n<4;n++){t=kd[e]+kd[r]+kd[n],s=Ud[e]+Ud[r]+Ud[n],i=Gd[e]+Gd[r]+Gd[n],Vd(t,s,i);for(let o=0;o<4;o++)t=kd[e]+kd[r]+kd[n]+kd[o],s=Ud[e]+Ud[r]+Ud[n]+Ud[o],i=Gd[e]+Gd[r]+Gd[n]+Gd[o],Vd(t,s,i)}}}for(let e=0;e<32;e++)zd[e]={get(){this._cache=this._cache||{};let t=this._cache[e];return void 0===t&&(t=new vd(this,new Bd(e,"uint")),this._cache[e]=t),t},set(t){this[e].assign(cp(t))}};Object.defineProperties(wd.prototype,zd);const jd=new WeakMap,$d=function(e,t=null){for(const s in e)e[s]=cp(e[s],t);return e},Wd=function(e,t=null){const s=e.length;for(let i=0;i<s;i++)e[i]=cp(e[i],t);return e},Hd=function(e,t=null,s=null,i=null){function r(e){return null!==i?(e=cp(Object.assign(e,i)),!0===i.intent&&(e=e.toVarIntent())):e=cp(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?(Ga(`TSL: "${s}" parameter length is less than minimum required.`),t.concat(new Array(o-t.length).fill(0))):void 0!==a&&t.length>a?(Ga(`TSL: "${s}" parameter length exceeds limit.`),t.slice(0,a)):t}return null===t?n=(...t)=>r(new e(...mp(h(t)))):null!==s?(s=cp(s),n=(...i)=>r(new e(t,...mp(h(i)),s))):n=(...s)=>r(new e(t,...mp(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},qd=function(e,...t){return new e(...mp(t))};class Xd extends wd{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=jd.get(e.constructor);void 0===i&&(i=new WeakMap,jd.set(e.constructor,i));let r=i.get(t);void 0===r&&(r=cp(e.buildFunctionNode(t)),i.set(t,r)),e.addInclude(r);const n=s?function(e){let t;pp(e);t=e[0]&&(e[0].isNode||Object.getPrototypeOf(e[0])!==Object.prototype)?[...e]:e[0];return t}(s):null;l=cp(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 pp(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 cp(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 wd&&(n=void 0===e[i]?e[t++]:Reflect.get(e,i,r));else n=Reflect.get(s,i,r);n=cp(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=cp(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 Yd extends wd{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 Xd(this,e)}setup(){return this.call()}}const Zd=[!1,!0],Qd=[0,1,2,3],Kd=[-1,-2],Jd=[.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],ep=new Map;for(const e of Zd)ep.set(e,new Bd(e));const tp=new Map;for(const e of Qd)tp.set(e,new Bd(e,"uint"));const sp=new Map([...tp].map(e=>new Bd(e.value,"int")));for(const e of Kd)sp.set(e,new Bd(e,"int"));const ip=new Map([...sp].map(e=>new Bd(e.value)));for(const e of Jd)ip.set(e,new Bd(e));for(const e of Jd)ip.set(-e,new Bd(-e));const rp={bool:ep,uint:tp,ints:sp,float:ip},np=new Map([...ep,...ip]),op=(e,t)=>np.has(e)?np.get(e):!0===e.isNode?e:new Bd(e,t),ap=function(e,t=null){return(...s)=>{for(const t of s)if(void 0===t)return Ga(`TSL: Invalid parameter for the type "${e}".`),new Bd(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=[ld(e,...s)]),1===s.length&&null!==t&&t.has(s[0]))return dp(t.get(s[0]));if(1===s.length){const t=op(s[0],e);return t.nodeType===e?dp(t):dp(new Td(t,e))}const i=s.map(e=>op(e));return dp(new Md(i,e))}},lp=e=>"object"==typeof e&&null!==e?e.value:e,hp=e=>null!=e?e.nodeType||e.convertTo||("string"==typeof e?e:null):null;function up(e,t){return new Yd(e,t)}const cp=(e,t=null)=>function(e,t=null){const s=ad(e);return"node"===s?e:null===t&&("float"===s||"boolean"===s)||s&&"shader"!==s&&"string"!==s?cp(op(e,t)):"shader"===s?e.isFn?e:_p(e):e}(e,t),dp=(e,t=null)=>cp(e,t).toVarIntent(),pp=(e,t=null)=>new $d(e,t),mp=(e,t=null)=>new Wd(e,t),fp=(e,t=null,s=null,i=null)=>new Hd(e,t,s,i),gp=(e,...t)=>new qd(e,...t),yp=(e,t=null,s=null,i={})=>new Hd(e,t,s,{...i,intent:!0});let bp=0;class xp extends wd{constructor(e,t=null){super();let s=null;null!==t&&("object"==typeof t?s=t.return:("string"==typeof t?s=t:Ga("TSL: Invalid layout type."),t=null)),this.shaderNode=new up(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"+bp++,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 Ga('TSL: "Fn()" was declared but not invoked. Try calling it like "Fn()( ...params )".'),e.generateConst(t)}}function _p(e,t=null){const s=new xp(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 wp=e=>{Dd=e},vp=()=>Dd,Tp=(...e)=>Dd.If(...e);function Sp(e){return Dd&&Dd.addToStack(e),e}Fd("toStack",Sp);const Mp=new ap("color"),Ap=new ap("float",rp.float),Np=new ap("int",rp.ints),Ep=new ap("uint",rp.uint),Cp=new ap("bool",rp.bool),Rp=new ap("vec2"),Pp=new ap("ivec2"),Bp=new ap("uvec2"),Ip=new ap("bvec2"),Dp=new ap("vec3"),Lp=new ap("ivec3"),Fp=new ap("uvec3"),Op=new ap("bvec3"),zp=new ap("vec4"),Vp=new ap("ivec4"),kp=new ap("uvec4"),Up=new ap("bvec4"),Gp=new ap("mat2"),jp=new ap("mat3"),$p=new ap("mat4");Fd("toColor",Mp),Fd("toFloat",Ap),Fd("toInt",Np),Fd("toUint",Ep),Fd("toBool",Cp),Fd("toVec2",Rp),Fd("toIVec2",Pp),Fd("toUVec2",Bp),Fd("toBVec2",Ip),Fd("toVec3",Dp),Fd("toIVec3",Lp),Fd("toUVec3",Fp),Fd("toBVec3",Op),Fd("toVec4",zp),Fd("toIVec4",Vp),Fd("toUVec4",kp),Fd("toBVec4",Up),Fd("toMat2",Gp),Fd("toMat3",jp),Fd("toMat4",$p);const Wp=fp(vd).setParameterLength(2),Hp=(e,t)=>cp(new Td(cp(e),t));Fd("element",Wp),Fd("convert",Hp);Fd("append",e=>(Ua("TSL: .append() has been renamed to .toStack()."),Sp(e)));class qp extends wd{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 Qc(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 Xp=(e,t)=>new qp(e,t),Yp=(e,t)=>new qp(e,t,!0),Zp=gp(qp,"vec4","DiffuseColor"),Qp=gp(qp,"vec3","DiffuseContribution"),Kp=gp(qp,"vec3","EmissiveColor"),Jp=gp(qp,"float","Roughness"),em=gp(qp,"float","Metalness"),tm=gp(qp,"float","Clearcoat"),sm=gp(qp,"float","ClearcoatRoughness"),im=gp(qp,"vec3","Sheen"),rm=gp(qp,"float","SheenRoughness"),nm=gp(qp,"float","Iridescence"),om=gp(qp,"float","IridescenceIOR"),am=gp(qp,"float","IridescenceThickness"),lm=gp(qp,"float","AlphaT"),hm=gp(qp,"float","Anisotropy"),um=gp(qp,"vec3","AnisotropyT"),cm=gp(qp,"vec3","AnisotropyB"),dm=gp(qp,"color","SpecularColor"),pm=gp(qp,"color","SpecularColorBlended"),mm=gp(qp,"float","SpecularF90"),fm=gp(qp,"float","Shininess"),gm=gp(qp,"vec4","Output"),ym=gp(qp,"float","dashSize"),bm=gp(qp,"float","gapSize"),xm=gp(qp,"float","pointWidth"),_m=gp(qp,"float","IOR"),wm=gp(qp,"float","Transmission"),vm=gp(qp,"float","Thickness"),Tm=gp(qp,"float","AttenuationDistance"),Sm=gp(qp,"color","AttenuationColor"),Mm=gp(qp,"float","Dispersion");class Am extends wd{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 Nm=e=>new Am(e),Em=(e,t=0)=>new Am(e,!0,t),Cm=Em("frame"),Rm=Em("render"),Pm=Nm("object");class Bm extends Rd{static get type(){return"UniformNode"}constructor(e,t=null){super(e,t),this.isUniformNode=!0,this.name="",this.groupNode=Pm}setName(e){return this.name=e,this}label(e){return Ua('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 Im=(e,t)=>{const s=hp(t||e);if(s===e&&(e=ld(s)),e&&!0===e.isNode){let t=e.value;e.traverse(e=>{!0===e.isConstNode&&(t=e.value)}),e=t}return new Bm(e,s)};class Dm extends Sd{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 Lm=(...e)=>{let t;if(1===e.length){const s=e[0];t=new Dm(null,s.length,s)}else{const s=e[0],i=e[1];t=new Dm(s,i)}return cp(t)};Fd("toArray",(e,t)=>Lm(Array(t).fill(e)));class Fm extends Sd{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 bd.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 Om=fp(Fm).setParameterLength(2);Fd("assign",Om);class zm extends Sd{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)Ga("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(Ga("TSL: The number of provided parameters is less than the expected number of inputs in 'Fn()'.");r.length<i.length;)r.push(Ap(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)):(Ga(`TSL: Input '${e.name}' not found in 'Fn()'.`),t.push(n(Ap(0),e)))}return`${s.build(e,"property")}( ${t.join(", ")} )`}}const Vm=(e,...t)=>(t=t.length>1||t[0]&&!0===t[0].isNode?mp(t):pp(t[0]),new zm(cp(e),t));Fd("call",Vm);const km={"==":"equal","!=":"notEqual","<":"lessThan",">":"greaterThan","<=":"lessThanEqual",">=":"greaterThanEqual","%":"mod"};class Um extends Sd{static get type(){return"OperatorNode"}constructor(e,t,s,...i){if(super(),i.length>0){let r=new Um(e,t,s);for(let t=0;t<i.length-1;t++)r=new Um(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(km[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===Ba;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 Gm=yp(Um,"+").setParameterLength(2,1/0).setName("add"),jm=yp(Um,"-").setParameterLength(2,1/0).setName("sub"),$m=yp(Um,"*").setParameterLength(2,1/0).setName("mul"),Wm=yp(Um,"/").setParameterLength(2,1/0).setName("div"),Hm=yp(Um,"%").setParameterLength(2).setName("mod"),qm=yp(Um,"==").setParameterLength(2).setName("equal"),Xm=yp(Um,"!=").setParameterLength(2).setName("notEqual"),Ym=yp(Um,"<").setParameterLength(2).setName("lessThan"),Zm=yp(Um,">").setParameterLength(2).setName("greaterThan"),Qm=yp(Um,"<=").setParameterLength(2).setName("lessThanEqual"),Km=yp(Um,">=").setParameterLength(2).setName("greaterThanEqual"),Jm=yp(Um,"&&").setParameterLength(2,1/0).setName("and"),ef=yp(Um,"||").setParameterLength(2,1/0).setName("or"),tf=yp(Um,"!").setParameterLength(1).setName("not"),sf=yp(Um,"^^").setParameterLength(2).setName("xor"),rf=yp(Um,"&").setParameterLength(2).setName("bitAnd"),nf=yp(Um,"~").setParameterLength(1).setName("bitNot"),of=yp(Um,"|").setParameterLength(2).setName("bitOr"),af=yp(Um,"^").setParameterLength(2).setName("bitXor"),lf=yp(Um,"<<").setParameterLength(2).setName("shiftLeft"),hf=yp(Um,">>").setParameterLength(2).setName("shiftRight"),uf=_p(([e])=>(e.addAssign(1),e)),cf=_p(([e])=>(e.subAssign(1),e)),df=_p(([e])=>{const t=Np(e).toConst();return e.addAssign(1),t}),pf=_p(([e])=>{const t=Np(e).toConst();return e.subAssign(1),t});Fd("add",Gm),Fd("sub",jm),Fd("mul",$m),Fd("div",Wm),Fd("mod",Hm),Fd("equal",qm),Fd("notEqual",Xm),Fd("lessThan",Ym),Fd("greaterThan",Zm),Fd("lessThanEqual",Qm),Fd("greaterThanEqual",Km),Fd("and",Jm),Fd("or",ef),Fd("not",tf),Fd("xor",sf),Fd("bitAnd",rf),Fd("bitNot",nf),Fd("bitOr",of),Fd("bitXor",af),Fd("shiftLeft",lf),Fd("shiftRight",hf),Fd("incrementBefore",uf),Fd("decrementBefore",cf),Fd("increment",df),Fd("decrement",pf);const mf=(e,t)=>(Ua('TSL: "modInt()" is deprecated. Use "mod( int( ... ) )" instead.'),Hm(Np(e),Np(t)));Fd("modInt",mf);class ff extends Sd{static get type(){return"MathNode"}constructor(e,t,s=null,i=null){if(super(),(e===ff.MAX||e===ff.MIN)&&arguments.length>3){let r=new ff(e,t,s);for(let t=2;t<arguments.length-1;t++)r=new ff(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===ff.LENGTH||t===ff.DISTANCE||t===ff.DOT?"float":t===ff.CROSS?"vec3":t===ff.ALL||t===ff.ANY?"bool":t===ff.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===ff.ONE_MINUS)r=jm(1,t);else if(i===ff.RECIPROCAL)r=Wm(1,t);else if(i===ff.DIFFERENCE)r=Gf(jm(t,s));else if(i===ff.TRANSFORM_DIRECTION){let i=t,n=s;e.isMatrix(i.getNodeType(e))?n=zp(Dp(n),0):i=zp(Dp(i),0);const o=$m(i,n).xyz;r=Df(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===ff.NEGATE)return e.format("( - "+n.build(e,r)+" )",i,t);{const h=[];return s===ff.CROSS?h.push(n.build(e,i),o.build(e,i)):l===Ba&&s===ff.STEP?h.push(n.build(e,1===e.getTypeLength(n.getNodeType(e))?"float":r),o.build(e,r)):l!==Ba||s!==ff.MIN&&s!==ff.MAX?s===ff.REFRACT?h.push(n.build(e,r),o.build(e,r),a.build(e,"float")):s===ff.MIX?h.push(n.build(e,r),o.build(e,r),a.build(e,1===e.getTypeLength(a.getNodeType(e))?"float":r)):(l===Ia&&s===ff.ATAN&&null!==o&&(s="atan2"),"fragment"===e.shaderStage||s!==ff.DFDX&&s!==ff.DFDY||(Ua(`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}}ff.ALL="all",ff.ANY="any",ff.RADIANS="radians",ff.DEGREES="degrees",ff.EXP="exp",ff.EXP2="exp2",ff.LOG="log",ff.LOG2="log2",ff.SQRT="sqrt",ff.INVERSE_SQRT="inversesqrt",ff.FLOOR="floor",ff.CEIL="ceil",ff.NORMALIZE="normalize",ff.FRACT="fract",ff.SIN="sin",ff.COS="cos",ff.TAN="tan",ff.ASIN="asin",ff.ACOS="acos",ff.ATAN="atan",ff.ABS="abs",ff.SIGN="sign",ff.LENGTH="length",ff.NEGATE="negate",ff.ONE_MINUS="oneMinus",ff.DFDX="dFdx",ff.DFDY="dFdy",ff.ROUND="round",ff.RECIPROCAL="reciprocal",ff.TRUNC="trunc",ff.FWIDTH="fwidth",ff.TRANSPOSE="transpose",ff.DETERMINANT="determinant",ff.INVERSE="inverse",ff.EQUALS="equals",ff.MIN="min",ff.MAX="max",ff.STEP="step",ff.REFLECT="reflect",ff.DISTANCE="distance",ff.DIFFERENCE="difference",ff.DOT="dot",ff.CROSS="cross",ff.POW="pow",ff.TRANSFORM_DIRECTION="transformDirection",ff.MIX="mix",ff.CLAMP="clamp",ff.REFRACT="refract",ff.SMOOTHSTEP="smoothstep",ff.FACEFORWARD="faceforward";const gf=Ap(1e-6),yf=Ap(1e6),bf=Ap(Math.PI),xf=Ap(2*Math.PI),_f=Ap(2*Math.PI),wf=Ap(.5*Math.PI),vf=yp(ff,ff.ALL).setParameterLength(1),Tf=yp(ff,ff.ANY).setParameterLength(1),Sf=yp(ff,ff.RADIANS).setParameterLength(1),Mf=yp(ff,ff.DEGREES).setParameterLength(1),Af=yp(ff,ff.EXP).setParameterLength(1),Nf=yp(ff,ff.EXP2).setParameterLength(1),Ef=yp(ff,ff.LOG).setParameterLength(1),Cf=yp(ff,ff.LOG2).setParameterLength(1),Rf=yp(ff,ff.SQRT).setParameterLength(1),Pf=yp(ff,ff.INVERSE_SQRT).setParameterLength(1),Bf=yp(ff,ff.FLOOR).setParameterLength(1),If=yp(ff,ff.CEIL).setParameterLength(1),Df=yp(ff,ff.NORMALIZE).setParameterLength(1),Lf=yp(ff,ff.FRACT).setParameterLength(1),Ff=yp(ff,ff.SIN).setParameterLength(1),Of=yp(ff,ff.COS).setParameterLength(1),zf=yp(ff,ff.TAN).setParameterLength(1),Vf=yp(ff,ff.ASIN).setParameterLength(1),kf=yp(ff,ff.ACOS).setParameterLength(1),Uf=yp(ff,ff.ATAN).setParameterLength(1,2),Gf=yp(ff,ff.ABS).setParameterLength(1),jf=yp(ff,ff.SIGN).setParameterLength(1),$f=yp(ff,ff.LENGTH).setParameterLength(1),Wf=yp(ff,ff.NEGATE).setParameterLength(1),Hf=yp(ff,ff.ONE_MINUS).setParameterLength(1),qf=yp(ff,ff.DFDX).setParameterLength(1),Xf=yp(ff,ff.DFDY).setParameterLength(1),Yf=yp(ff,ff.ROUND).setParameterLength(1),Zf=yp(ff,ff.RECIPROCAL).setParameterLength(1),Qf=yp(ff,ff.TRUNC).setParameterLength(1),Kf=yp(ff,ff.FWIDTH).setParameterLength(1),Jf=yp(ff,ff.TRANSPOSE).setParameterLength(1),eg=yp(ff,ff.DETERMINANT).setParameterLength(1),tg=yp(ff,ff.INVERSE).setParameterLength(1),sg=(e,t)=>(Ua('TSL: "equals" is deprecated. Use "equal" inside a vector instead, like: "bvec*( equal( ... ) )"'),qm(e,t)),ig=yp(ff,ff.MIN).setParameterLength(2,1/0),rg=yp(ff,ff.MAX).setParameterLength(2,1/0),ng=yp(ff,ff.STEP).setParameterLength(2),og=yp(ff,ff.REFLECT).setParameterLength(2),ag=yp(ff,ff.DISTANCE).setParameterLength(2),lg=yp(ff,ff.DIFFERENCE).setParameterLength(2),hg=yp(ff,ff.DOT).setParameterLength(2),ug=yp(ff,ff.CROSS).setParameterLength(2),cg=yp(ff,ff.POW).setParameterLength(2),dg=e=>$m(e,e),pg=e=>$m(e,e,e),mg=e=>$m(e,e,e,e),fg=yp(ff,ff.TRANSFORM_DIRECTION).setParameterLength(2),gg=e=>$m(jf(e),cg(Gf(e),1/3)),yg=e=>hg(e,e),bg=yp(ff,ff.MIX).setParameterLength(3),xg=(e,t=0,s=1)=>cp(new ff(ff.CLAMP,cp(e),cp(t),cp(s))),_g=e=>xg(e),wg=yp(ff,ff.REFRACT).setParameterLength(3),vg=yp(ff,ff.SMOOTHSTEP).setParameterLength(3),Tg=yp(ff,ff.FACEFORWARD).setParameterLength(3),Sg=_p(([e])=>{const t=hg(e.xy,Rp(12.9898,78.233)),s=Hm(t,bf);return Lf(Ff(s).mul(43758.5453))}),Mg=(e,t,s)=>bg(t,s,e),Ag=(e,t,s)=>vg(t,s,e),Ng=(e,t)=>ng(t,e),Eg=(e,t)=>(Ua('TSL: "atan2" is overloaded. Use "atan" instead.'),Uf(e,t)),Cg=Tg,Rg=Pf;Fd("all",vf),Fd("any",Tf),Fd("equals",sg),Fd("radians",Sf),Fd("degrees",Mf),Fd("exp",Af),Fd("exp2",Nf),Fd("log",Ef),Fd("log2",Cf),Fd("sqrt",Rf),Fd("inverseSqrt",Pf),Fd("floor",Bf),Fd("ceil",If),Fd("normalize",Df),Fd("fract",Lf),Fd("sin",Ff),Fd("cos",Of),Fd("tan",zf),Fd("asin",Vf),Fd("acos",kf),Fd("atan",Uf),Fd("abs",Gf),Fd("sign",jf),Fd("length",$f),Fd("lengthSq",yg),Fd("negate",Wf),Fd("oneMinus",Hf),Fd("dFdx",qf),Fd("dFdy",Xf),Fd("round",Yf),Fd("reciprocal",Zf),Fd("trunc",Qf),Fd("fwidth",Kf),Fd("atan2",Eg),Fd("min",ig),Fd("max",rg),Fd("step",Ng),Fd("reflect",og),Fd("distance",ag),Fd("dot",hg),Fd("cross",ug),Fd("pow",cg),Fd("pow2",dg),Fd("pow3",pg),Fd("pow4",mg),Fd("transformDirection",fg),Fd("mix",Mg),Fd("clamp",xg),Fd("refract",wg),Fd("smoothstep",Ag),Fd("faceForward",Tg),Fd("difference",lg),Fd("saturate",_g),Fd("cbrt",gg),Fd("transpose",Jf),Fd("determinant",eg),Fd("inverse",tg),Fd("rand",Sg);class Pg extends wd{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?Xp(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&&(Ua("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&&(Ua("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 Bg=fp(Pg).setParameterLength(2,3);Fd("select",Bg);class Ig extends wd{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 Dg=(e=null,t={})=>{let s=e;return null!==s&&!0===s.isNode||(t=s||t,s=null),new Ig(s,t)},Lg=e=>Dg(e,{uniformFlow:!0}),Fg=(e,t)=>Dg(e,{nodeName:t});function Og(e,t,s=null){return Dg(s,{getShadow:({light:s,shadowColorNode:i})=>t===s?i.mul(e):i})}function zg(e,t=null){return Dg(t,{getAO:(t,{material:s})=>!0===s.transparent?t:null!==t?t.mul(e):e})}function Vg(e,t){return Ua('TSL: "label()" has been deprecated. Use "setName()" instead.'),Fg(e,t)}Fd("context",Dg),Fd("label",Vg),Fd("uniformFlow",Lg),Fd("setName",Fg),Fd("builtinShadowContext",(e,t,s)=>Og(t,s,e)),Fd("builtinAOContext",(e,t)=>zg(t,e));class kg extends wd{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)&&Ga('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 Ug=fp(kg),Gg=(e,t=null)=>Ug(e,t).toStack(),jg=(e,t=null)=>Ug(e,t,!0).toStack(),$g=e=>Ug(e).setIntent(!0).toStack();Fd("toVar",Gg),Fd("toConst",jg),Fd("toVarIntent",$g);class Wg extends wd{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 Hg=(e,t,s=null)=>cp(new Wg(cp(e),t,s));class qg extends wd{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=Hg(this.node,"VERTEX")}return s.needsInterpolation||(s.needsInterpolation="fragment"===e.shaderStage),s}setup(e){this.setupVarying(e),e.flowNodeFromShaderStage(dd.VERTEX,this.node)}analyze(e){this.setupVarying(e),e.flowNodeFromShaderStage(dd.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,dd.VERTEX);e.flowNodeFromShaderStage(dd.VERTEX,s.node,r,n),s[t]=n}return e.getPropertyName(i)}}const Xg=fp(qg).setParameterLength(1,2),Yg=e=>Xg(e);Fd("toVarying",Xg),Fd("toVertexStage",Yg),Fd("varying",(...e)=>(Ua("TSL: .varying() has been renamed to .toVarying()."),Xg(...e))),Fd("vertexStage",(...e)=>(Ua("TSL: .vertexStage() has been renamed to .toVertexStage()."),Xg(...e)));const Zg=_p(([e])=>{const t=e.mul(.9478672986).add(.0521327014).pow(2.4),s=e.mul(.0773993808),i=e.lessThanEqual(.04045);return bg(t,s,i)}).setLayout({name:"sRGBTransferEOTF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Qg=_p(([e])=>{const t=e.pow(.41666).mul(1.055).sub(.055),s=e.mul(12.92),i=e.lessThanEqual(.0031308);return bg(t,s,i)}).setLayout({name:"sRGBTransferOETF",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),Kg="WorkingColorSpace";class Jg extends Sd{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===Kg?dl.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!==dl.enabled&&s!==i&&s&&i?(dl.getTransfer(s)===_a&&(r=zp(Zg(r.rgb),r.a)),dl.getPrimaries(s)!==dl.getPrimaries(i)&&(r=zp(jp(dl._getMatrix(new al,s,i)).mul(r.rgb),r.a)),dl.getTransfer(i)===_a&&(r=zp(Qg(r.rgb),r.a)),r):r}}const ey=(e,t)=>cp(new Jg(cp(e),Kg,t)),ty=(e,t)=>cp(new Jg(cp(e),t,Kg));Fd("workingToColorSpace",ey),Fd("colorSpaceToWorking",ty);let sy=class extends vd{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 iy extends wd{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=pd.OBJECT}setGroup(e){return this.group=e,this}element(e){return new sy(this,cp(e))}setNodeType(e){const t=Im(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 ry extends iy{static get type(){return"RendererReferenceNode"}constructor(e,t,s=null){super(e,t,s),this.renderer=s,this.setGroup(Rm)}updateReference(e){return this.reference=null!==this.renderer?this.renderer:e.renderer,this.reference}}const ny=(e,t,s=null)=>new ry(e,t,s);class oy extends Sd{static get type(){return"ToneMappingNode"}constructor(e,t=ly,s=null){super("vec3"),this._toneMapping=e,this.exposureNode=t,this.colorNode=s}customCacheKey(){return Jc(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=zp(r(t.rgb,this.exposureNode),t.a):(Ga("ToneMappingNode: Unsupported Tone Mapping configuration.",s),i=t),i}}const ay=(e,t,s)=>cp(new oy(e,cp(t),cp(s))),ly=ny("toneMappingExposure","float");Fd("toneMapping",(e,t,s)=>ay(t,s,e));const hy=new WeakMap;function uy(e,t){let s=hy.get(e);return void 0===s&&(s=new Hu(e,t),hy.set(e,s)),s}class cy extends Rd{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=Ra,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?uy(i.array,r):uy(i,r);const a=new Xu(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=Xg(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 dy(e,t=null,s=0,i=0,r=35044,n=!1){return"mat3"===t||null===t&&9===e.itemSize?jp(new cy(e,"vec3",9,0).setUsage(r).setInstanced(n),new cy(e,"vec3",9,3).setUsage(r).setInstanced(n),new cy(e,"vec3",9,6).setUsage(r).setInstanced(n)):"mat4"===t||null===t&&16===e.itemSize?$p(new cy(e,"vec4",16,0).setUsage(r).setInstanced(n),new cy(e,"vec4",16,4).setUsage(r).setInstanced(n),new cy(e,"vec4",16,8).setUsage(r).setInstanced(n),new cy(e,"vec4",16,12).setUsage(r).setInstanced(n)):new cy(e,t,s,i)}const py=(e,t=null,s=0,i=0)=>dy(e,t,s,i),my=(e,t=null,s=0,i=0)=>dy(e,t,s,i,Ra,!0),fy=(e,t=null,s=0,i=0)=>dy(e,t,s,i,Pa,!0);Fd("toAttribute",e=>py(e.value));class gy extends wd{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=pd.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 Ua('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 yy=(e,t=[64])=>{(0===t.length||t.length>3)&&Ga("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))&&Ga(`TSL: compute() workgroupSize element at index [ ${e} ] must be a positive integer`)}for(;t.length<3;)t.push(1);return cp(new gy(cp(e),t))},by=(e,t,s)=>yy(e,s).setCount(t);Fd("compute",by),Fd("computeKernel",yy);class xy extends wd{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 _y=e=>new xy(cp(e));function wy(e,t=!0){return Ua('TSL: "cache()" has been deprecated. Use "isolate()" instead.'),_y(e).setParent(t)}Fd("cache",wy),Fd("isolate",_y);class vy extends wd{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 Ty=fp(vy).setParameterLength(2);Fd("bypass",Ty);class Sy extends wd{static get type(){return"RemapNode"}constructor(e,t,s,i=Ap(0),r=Ap(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 My=fp(Sy,null,null,{doClamp:!1}).setParameterLength(3,5),Ay=fp(Sy).setParameterLength(3,5);Fd("remap",My),Fd("remapClamp",Ay);class Ny extends wd{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 Ey=fp(Ny).setParameterLength(1,2),Cy=e=>(e?Bg(e,Ey("discard")):Ey("discard")).toStack();Fd("discard",Cy);class Ry extends Sd{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)||ga;return 0!==s&&(t=t.toneMapping(s)),i!==ga&&i!==dl.workingColorSpace&&(t=t.workingToColorSpace(i)),t}}const Py=(e,t=null,s=null)=>cp(new Ry(cp(e),t,s));Fd("renderOutput",Py);class By extends Sd{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):ka(n),s}}const Iy=(e,t=null)=>cp(new By(cp(e),t)).toStack();Fd("debug",Iy);class Dy{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 Ly extends wd{static get type(){return"InspectorNode"}constructor(e,t="",s=null){super(),this.node=e,this.name=t,this.callback=s,this.updateType=pd.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!==Dy&&ja('TSL: ".toInspector()" is only available with WebGPU.'),t}}function Fy(e,t="",s=null){return(e=cp(e)).before(new Ly(e,t,s))}Fd("toInspector",Fy);class Oy extends wd{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 Xg(this).build(e,s)}return Ua(`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 zy=(e,t=null)=>new Oy(e,t),Vy=(e=0)=>zy("uv"+(e>0?e:""),"vec2");class ky extends wd{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 Uy=fp(ky).setParameterLength(1,2);class Gy extends Bm{static get type(){return"MaxMipLevelNode"}constructor(e){super(0),this._textureNode=e,this.updateType=pd.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 jy=fp(Gy).setParameterLength(1),$y=new vl;class Wy extends Bm{static get type(){return"TextureNode"}constructor(e=$y,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=pd.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===xo?"uvec4":this.value.type===bo?"ivec4":"vec4"}getInputType(){return"texture"}getDefaultUV(){return Vy(this.value.channel)}updateReference(){return this.value}getTransformedUV(e){return null===this._matrixUniform&&(this._matrixUniform=Im(this.value.matrix)),this._matrixUniform.mul(Dp(e,1)).xy}setUpdateMatrix(e){return this.updateMatrix=e,this}setupUV(e,t){return e.isFlipY()&&(null===this._flipYUniform&&(this._flipYUniform=Im(!1)),t=t.toVar(),t=this.sampler?this._flipYUniform.select(t.flipY(),t):this._flipYUniform.select(t.setY(Np(Uy(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=_p(()=>{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?pd.OBJECT:pd.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,b=c?this.generateOffset(e,c):null,x=e.getVarFromNode(this);o=e.getPropertyName(x);const _=this.generateSnippet(e,r,d,p,m,f,g,y,b);e.addLineFlowCode(`${o} = ${_}`,this),n.snippet=_,n.propertyName=o}let a=o;const l=this.getNodeType(e);return e.needsToWorkingColorSpace(s)&&(a=ty(Ey(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 Ua("TextureNode: .uv() has been renamed. Use .sample() instead."),this.sample(e)}sample(e){const t=this.clone();return t.uvNode=cp(e),t.referenceNode=this.getBase(),cp(t)}load(e){return this.sample(e).setSampler(!1)}blur(e){const t=this.clone();t.biasNode=cp(e).mul(jy(t)),t.referenceNode=this.getBase();const s=t.value;return!1===t.generateMipmaps&&(s&&!1===s.generateMipmaps||s.minFilter===ao||s.magFilter===ao)&&(Ua("TSL: texture().blur() requires mipmaps and sampling. Use .generateMipmaps=true and .minFilter/.magFilter=THREE.LinearFilter in the Texture."),t.biasNode=null),cp(t)}level(e){const t=this.clone();return t.levelNode=cp(e),t.referenceNode=this.getBase(),cp(t)}size(e){return Uy(this,e)}bias(e){const t=this.clone();return t.biasNode=cp(e),t.referenceNode=this.getBase(),cp(t)}getBase(){return this.referenceNode?this.referenceNode.getBase():this}compare(e){const t=this.clone();return t.compareNode=cp(e),t.referenceNode=this.getBase(),cp(t)}grad(e,t){const s=this.clone();return s.gradNode=[cp(e),cp(t)],s.referenceNode=this.getBase(),cp(s)}depth(e){const t=this.clone();return t.depthNode=cp(e),t.referenceNode=this.getBase(),cp(t)}offset(e){const t=this.clone();return t.offsetNode=cp(e),t.referenceNode=this.getBase(),cp(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 Hy=fp(Wy).setParameterLength(1,4).setName("texture"),qy=(e=$y,t=null,s=null,i=null)=>{let r;return e&&!0===e.isTextureNode?(r=cp(e.clone()),r.referenceNode=e.getBase(),null!==t&&(r.uvNode=cp(t)),null!==s&&(r.levelNode=cp(s)),null!==i&&(r.biasNode=cp(i))):r=Hy(e,t,s,i),r},Xy=(...e)=>qy(...e).setSampler(!1);class Yy extends Bm{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 Zy=(e,t,s)=>new Yy(e,t,s);class Qy extends vd{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 Ky extends Yy{static get type(){return"UniformArrayNode"}constructor(e,t=null){super(null),this.array=e,this.elementType=null===t?ad(e[0]):t,this.paddedType=this.getPaddedType(),this.updateType=pd.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 Qy(this,cp(e))}}const Jy=(e,t)=>new Ky(e,t);const eb=fp(class extends wd{constructor(e){super("float"),this.name=e,this.isBuiltinNode=!0}generate(){return this.name}}).setParameterLength(1);let tb,sb;class ib extends wd{static get type(){return"ScreenNode"}constructor(e){super(),this.scope=e,this._output=null,this.isViewportNode=!0}getNodeType(){return this.scope===ib.DPR?"float":this.scope===ib.VIEWPORT?"vec4":"vec2"}getUpdateType(){let e=pd.NONE;return this.scope!==ib.SIZE&&this.scope!==ib.VIEWPORT&&this.scope!==ib.DPR||(e=pd.RENDER),this.updateType=e,e}update({renderer:e}){const t=e.getRenderTarget();this.scope===ib.VIEWPORT?null!==t?sb.copy(t.viewport):(e.getViewport(sb),sb.multiplyScalar(e.getPixelRatio())):this.scope===ib.DPR?this._output.value=e.getPixelRatio():null!==t?(tb.width=t.width,tb.height=t.height):e.getDrawingBufferSize(tb)}setup(){const e=this.scope;let t=null;return t=e===ib.SIZE?Im(tb||(tb=new sl)):e===ib.VIEWPORT?Im(sb||(sb=new Tl)):e===ib.DPR?Im(1):Rp(ab.div(ob)),this._output=t,t}generate(e){if(this.scope===ib.COORDINATE){let t=e.getFragCoord();if(e.isFlipY()){const s=e.getNodeProperties(ob).outputNode.build(e);t=`${e.getType("vec2")}( ${t}.x, ${s}.y - ${t}.y )`}return t}return super.generate(e)}}ib.COORDINATE="coordinate",ib.VIEWPORT="viewport",ib.SIZE="size",ib.UV="uv",ib.DPR="dpr";const rb=gp(ib,ib.DPR),nb=gp(ib,ib.UV),ob=gp(ib,ib.SIZE),ab=gp(ib,ib.COORDINATE),lb=gp(ib,ib.VIEWPORT),hb=lb.zw,ub=ab.sub(lb.xy),cb=ub.div(hb),db=_p(()=>(Ua('TSL: "viewportResolution" is deprecated. Use "screenSize" instead.'),ob),"vec2").once()(),pb=Im(0,"uint").setName("u_cameraIndex").setGroup(Em("cameraIndex")).toVarying("v_cameraIndex"),mb=Im("float").setName("cameraNear").setGroup(Rm).onRenderUpdate(({camera:e})=>e.near),fb=Im("float").setName("cameraFar").setGroup(Rm).onRenderUpdate(({camera:e})=>e.far),gb=_p(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrix);t=Jy(s).setGroup(Rm).setName("cameraProjectionMatrices").element(e.isMultiViewCamera?eb("gl_ViewID_OVR"):pb).toConst("cameraProjectionMatrix")}else t=Im("mat4").setName("cameraProjectionMatrix").setGroup(Rm).onRenderUpdate(({camera:e})=>e.projectionMatrix);return t}).once()(),yb=_p(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.projectionMatrixInverse);t=Jy(s).setGroup(Rm).setName("cameraProjectionMatricesInverse").element(e.isMultiViewCamera?eb("gl_ViewID_OVR"):pb).toConst("cameraProjectionMatrixInverse")}else t=Im("mat4").setName("cameraProjectionMatrixInverse").setGroup(Rm).onRenderUpdate(({camera:e})=>e.projectionMatrixInverse);return t}).once()(),bb=_p(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.matrixWorldInverse);t=Jy(s).setGroup(Rm).setName("cameraViewMatrices").element(e.isMultiViewCamera?eb("gl_ViewID_OVR"):pb).toConst("cameraViewMatrix")}else t=Im("mat4").setName("cameraViewMatrix").setGroup(Rm).onRenderUpdate(({camera:e})=>e.matrixWorldInverse);return t}).once()(),xb=_p(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.matrixWorld);t=Jy(s).setGroup(Rm).setName("cameraWorldMatrices").element(e.isMultiViewCamera?eb("gl_ViewID_OVR"):pb).toConst("cameraWorldMatrix")}else t=Im("mat4").setName("cameraWorldMatrix").setGroup(Rm).onRenderUpdate(({camera:e})=>e.matrixWorld);return t}).once()(),_b=_p(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.normalMatrix);t=Jy(s).setGroup(Rm).setName("cameraNormalMatrices").element(e.isMultiViewCamera?eb("gl_ViewID_OVR"):pb).toConst("cameraNormalMatrix")}else t=Im("mat3").setName("cameraNormalMatrix").setGroup(Rm).onRenderUpdate(({camera:e})=>e.normalMatrix);return t}).once()(),wb=_p(({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 rl);t=Jy(s).setGroup(Rm).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?eb("gl_ViewID_OVR"):pb).toConst("cameraPosition")}else t=Im(new rl).setName("cameraPosition").setGroup(Rm).onRenderUpdate(({camera:e},t)=>t.value.setFromMatrixPosition(e.matrixWorld));return t}).once()(),vb=_p(({camera:e})=>{let t;if(e.isArrayCamera&&e.cameras.length>0){const s=[];for(const t of e.cameras)s.push(t.viewport);t=Jy(s,"vec4").setGroup(Rm).setName("cameraViewports").element(pb).toConst("cameraViewport")}else t=zp(0,0,ob.x,ob.y).toConst("cameraViewport");return t}).once()(),Tb=new Wl;class Sb extends wd{static get type(){return"Object3DNode"}constructor(e,t=null){super(),this.scope=e,this.object3d=t,this.updateType=pd.OBJECT,this.uniformNode=new Bm(null)}getNodeType(){const e=this.scope;return e===Sb.WORLD_MATRIX?"mat4":e===Sb.POSITION||e===Sb.VIEW_POSITION||e===Sb.DIRECTION||e===Sb.SCALE?"vec3":e===Sb.RADIUS?"float":void 0}update(e){const t=this.object3d,s=this.uniformNode,i=this.scope;if(i===Sb.WORLD_MATRIX)s.value=t.matrixWorld;else if(i===Sb.POSITION)s.value=s.value||new rl,s.value.setFromMatrixPosition(t.matrixWorld);else if(i===Sb.SCALE)s.value=s.value||new rl,s.value.setFromMatrixScale(t.matrixWorld);else if(i===Sb.DIRECTION)s.value=s.value||new rl,t.getWorldDirection(s.value);else if(i===Sb.VIEW_POSITION){const i=e.camera;s.value=s.value||new rl,s.value.setFromMatrixPosition(t.matrixWorld),s.value.applyMatrix4(i.matrixWorldInverse)}else if(i===Sb.RADIUS){const i=e.object.geometry;null===i.boundingSphere&&i.computeBoundingSphere(),Tb.copy(i.boundingSphere).applyMatrix4(t.matrixWorld),s.value=Tb.radius}}generate(e){const t=this.scope;return t===Sb.WORLD_MATRIX?this.uniformNode.nodeType="mat4":t===Sb.POSITION||t===Sb.VIEW_POSITION||t===Sb.DIRECTION||t===Sb.SCALE?this.uniformNode.nodeType="vec3":t===Sb.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}}Sb.WORLD_MATRIX="worldMatrix",Sb.POSITION="position",Sb.SCALE="scale",Sb.VIEW_POSITION="viewPosition",Sb.DIRECTION="direction",Sb.RADIUS="radius";const Mb=fp(Sb,Sb.DIRECTION).setParameterLength(1),Ab=fp(Sb,Sb.WORLD_MATRIX).setParameterLength(1),Nb=fp(Sb,Sb.POSITION).setParameterLength(1),Eb=fp(Sb,Sb.SCALE).setParameterLength(1),Cb=fp(Sb,Sb.VIEW_POSITION).setParameterLength(1),Rb=fp(Sb,Sb.RADIUS).setParameterLength(1);class Pb extends Sb{static get type(){return"ModelNode"}constructor(e){super(e)}update(e){this.object3d=e.object,super.update(e)}}const Bb=gp(Pb,Pb.DIRECTION),Ib=gp(Pb,Pb.WORLD_MATRIX),Db=gp(Pb,Pb.POSITION),Lb=gp(Pb,Pb.SCALE),Fb=gp(Pb,Pb.VIEW_POSITION),Ob=gp(Pb,Pb.RADIUS),zb=Im(new al).onObjectUpdate(({object:e},t)=>t.value.getNormalMatrix(e.matrixWorld)),Vb=Im(new eh).onObjectUpdate(({object:e},t)=>t.value.copy(e.matrixWorld).invert()),kb=_p(e=>e.context.modelViewMatrix||Ub).once()().toVar("modelViewMatrix"),Ub=bb.mul(Ib),Gb=_p(e=>(e.context.isHighPrecisionModelViewMatrix=!0,Im("mat4").onObjectUpdate(({object:e,camera:t})=>e.modelViewMatrix.multiplyMatrices(t.matrixWorldInverse,e.matrixWorld)))).once()().toVar("highpModelViewMatrix"),jb=_p(e=>{const t=e.context.isHighPrecisionModelViewMatrix;return Im("mat3").onObjectUpdate(({object:e,camera:s})=>(!0!==t&&e.modelViewMatrix.multiplyMatrices(s.matrixWorldInverse,e.matrixWorld),e.normalMatrix.getNormalMatrix(e.modelViewMatrix)))}).once()().toVar("highpModelNormalViewMatrix"),$b=zy("position","vec3"),Wb=$b.toVarying("positionLocal"),Hb=$b.toVarying("positionPrevious"),qb=_p(e=>Ib.mul(Wb).xyz.toVarying(e.getSubBuildProperty("v_positionWorld")),"vec3").once(["POSITION"])(),Xb=_p(()=>Wb.transformDirection(Ib).toVarying("v_positionWorldDirection").normalize().toVar("positionWorldDirection"),"vec3").once(["POSITION"])(),Yb=_p(e=>e.context.setupPositionView().toVarying("v_positionView"),"vec3").once(["POSITION"])(),Zb=_p(e=>{let t;return t=e.camera.isOrthographicCamera?Dp(0,0,1):Yb.negate().toVarying("v_positionViewDirection").normalize(),t.toVar("positionViewDirection")},"vec3").once(["POSITION"])();class Qb extends wd{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 Kb=gp(Qb),Jb=Ap(Kb).mul(2).sub(1),ex=_p(([e],{material:t})=>{const s=t.side;return 1===s?e=e.mul(-1):2===s&&(e=e.mul(Jb)),e}),tx=zy("normal","vec3"),sx=_p(e=>!1===e.geometry.hasAttribute("normal")?(Ua('TSL: Vertex attribute "normal" not found on geometry.'),Dp(0,1,0)):tx,"vec3").once()().toVar("normalLocal"),ix=Yb.dFdx().cross(Yb.dFdy()).normalize().toVar("normalFlat"),rx=_p(e=>{let t;return t=!0===e.material.flatShading?ix:ux(sx).toVarying("v_normalViewGeometry").normalize(),t},"vec3").once()().toVar("normalViewGeometry"),nx=_p(e=>{let t=rx.transformDirection(bb);return!0!==e.material.flatShading&&(t=t.toVarying("v_normalWorldGeometry")),t.normalize().toVar("normalWorldGeometry")},"vec3").once()(),ox=_p(({subBuildFn:e,material:t,context:s})=>{let i;return"NORMAL"===e||"VERTEX"===e?(i=rx,!0!==t.flatShading&&(i=ex(i))):i=s.setupNormal().context({getUV:null}),i},"vec3").once(["NORMAL","VERTEX"])().toVar("normalView"),ax=ox.transformDirection(bb).toVar("normalWorld"),lx=_p(({subBuildFn:e,context:t})=>{let s;return s="NORMAL"===e||"VERTEX"===e?ox:t.setupClearcoatNormal().context({getUV:null}),s},"vec3").once(["NORMAL","VERTEX"])().toVar("clearcoatNormalView"),hx=_p(([e,t=Ib])=>{const s=jp(t),i=e.div(Dp(s[0].dot(s[0]),s[1].dot(s[1]),s[2].dot(s[2])));return s.mul(i).xyz}),ux=_p(([e],t)=>{const s=t.context.modelNormalViewMatrix;if(s)return s.transformDirection(e);const i=zb.mul(e);return bb.transformDirection(i)}),cx=_p(()=>(Ua('TSL: "transformedNormalView" is deprecated. Use "normalView" instead.'),ox)).once(["NORMAL","VERTEX"])(),dx=_p(()=>(Ua('TSL: "transformedNormalWorld" is deprecated. Use "normalWorld" instead.'),ax)).once(["NORMAL","VERTEX"])(),px=_p(()=>(Ua('TSL: "transformedClearcoatNormalView" is deprecated. Use "clearcoatNormalView" instead.'),lx)).once(["NORMAL","VERTEX"])(),mx=new uh,fx=new eh,gx=Im(0).onReference(({material:e})=>e).onObjectUpdate(({material:e})=>e.refractionRatio),yx=Im(1).onReference(({material:e})=>e).onObjectUpdate(function({material:e,scene:t}){return e.envMap?e.envMapIntensity:t.environmentIntensity}),bx=Im(new eh).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?(mx.copy(s),fx.makeRotationFromEuler(mx)):fx.identity(),fx}),xx=Zb.negate().reflect(ox),_x=Zb.negate().refract(ox,gx),wx=xx.transformDirection(bb).toVar("reflectVector"),vx=_x.transformDirection(bb).toVar("reflectVector"),Tx=new ku;class Sx extends Wy{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===so?wx:e.mapping===io?vx:(Ga('CubeTextureNode: Mapping "%s" not supported.',e.mapping),Dp(0,0,0))}setUpdateMatrix(){}setupUV(e,t){const s=this.value;return!0===s.isDepthTexture?e.renderer.coordinateSystem===Ia?Dp(t.x,t.y.negate(),t.z):t:(e.renderer.coordinateSystem!==Ia&&s.isRenderTargetTexture||(t=Dp(t.x.negate(),t.yz)),bx.mul(t))}generateUV(e,t){return t.build(e,!0===this.sampler?"vec3":"ivec3")}}const Mx=fp(Sx).setParameterLength(1,4).setName("cubeTexture"),Ax=(e=Tx,t=null,s=null,i=null)=>{let r;return e&&!0===e.isCubeTextureNode?(r=cp(e.clone()),r.referenceNode=e,null!==t&&(r.uvNode=cp(t)),null!==s&&(r.levelNode=cp(s)),null!==i&&(r.biasNode=cp(i))):r=Mx(e,t,s,i),r};class Nx extends vd{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 Ex extends wd{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=pd.OBJECT}element(e){return new Nx(this,cp(e))}setGroup(e){return this.group=e,this}setName(e){return this.name=e,this}label(e){return Ua('TSL: "label()" has been deprecated. Use "setName()" instead.'),this.setName(e)}setNodeType(e){let t=null;t=null!==this.count?Zy(null,e,this.count):Array.isArray(this.getValueFromReference())?Jy(null,e):"texture"===e?qy(null):"cubeTexture"===e?Ax(null):Im(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 Cx=(e,t,s)=>new Ex(e,t,s),Rx=(e,t,s,i)=>new Ex(e,t,i,s);class Px extends Ex{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 Bx=(e,t,s=null)=>new Px(e,t,s),Ix=Vy(),Dx=Yb.dFdx(),Lx=Yb.dFdy(),Fx=Ix.dFdx(),Ox=Ix.dFdy(),zx=ox,Vx=Lx.cross(zx),kx=zx.cross(Dx),Ux=Vx.mul(Fx.x).add(kx.mul(Ox.x)),Gx=Vx.mul(Fx.y).add(kx.mul(Ox.y)),jx=Ux.dot(Ux).max(Gx.dot(Gx)),$x=jx.equal(0).select(0,jx.inverseSqrt()),Wx=Ux.mul($x).toVar("tangentViewFrame"),Hx=Gx.mul($x).toVar("bitangentViewFrame"),qx=zy("tangent","vec4"),Xx=qx.xyz.toVar("tangentLocal"),Yx=_p(({subBuildFn:e,geometry:t,material:s})=>{let i;return i="VERTEX"===e||t.hasAttribute("tangent")?kb.mul(zp(Xx,0)).xyz.toVarying("v_tangentView").normalize():Wx,!0!==s.flatShading&&(i=ex(i)),i},"vec3").once(["NORMAL","VERTEX"])().toVar("tangentView"),Zx=Yx.transformDirection(bb).toVarying("v_tangentWorld").normalize().toVar("tangentWorld"),Qx=_p(([e,t],{subBuildFn:s,material:i})=>{let r=e.mul(qx.w).xyz;return"NORMAL"===s&&!0!==i.flatShading&&(r=r.toVarying(t)),r}).once(["NORMAL"]),Kx=Qx(tx.cross(qx),"v_bitangentGeometry").normalize().toVar("bitangentGeometry"),Jx=Qx(sx.cross(Xx),"v_bitangentLocal").normalize().toVar("bitangentLocal"),e_=_p(({subBuildFn:e,geometry:t,material:s})=>{let i;return i="VERTEX"===e||t.hasAttribute("tangent")?Qx(ox.cross(Yx),"v_bitangentView").normalize():Hx,!0!==s.flatShading&&(i=ex(i)),i},"vec3").once(["NORMAL","VERTEX"])().toVar("bitangentView"),t_=Qx(ax.cross(Zx),"v_bitangentWorld").normalize().toVar("bitangentWorld"),s_=jp(Yx,e_,ox).toVar("TBNViewMatrix"),i_=Zb.mul(s_),r_=_p(()=>{let e=cm.cross(Zb);return e=e.cross(cm).normalize(),e=bg(e,ox,hm.mul(Jp.oneMinus()).oneMinus().pow2().pow2()).normalize(),e}).once()(),n_=e=>cp(e).mul(.5).add(.5),o_=e=>Dp(e,Rf(_g(Ap(1).sub(hg(e,e)))));class a_ extends Sd{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=o_(r.xy):"ga"===i?r=o_(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=ex(t)),r=Dp(r.xy.mul(t),r.z)}let n=null;return 1===t?n=ux(r):0===t?n=s_.mul(r).normalize():(Ga(`NodeMaterial: Unsupported normal map type: ${t}`),n=ox),n}}const l_=fp(a_).setParameterLength(1,2),h_=_p(({textureNode:e,bumpScale:t})=>{const s=t=>e.isolate().context({getUV:e=>t(e.uvNode||Vy()),forceUVContext:!0}),i=Ap(s(e=>e));return Rp(Ap(s(e=>e.add(e.dFdx()))).sub(i),Ap(s(e=>e.add(e.dFdy()))).sub(i)).mul(t)}),u_=_p(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(Jb),h=l.sign().mul(i.x.mul(o).add(i.y.mul(a)));return l.abs().mul(s).sub(h).normalize()});class c_ extends Sd{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=h_({textureNode:this.textureNode,bumpScale:e});return u_({surf_pos:Yb,surf_norm:ox,dHdxy:t})}}const d_=fp(c_).setParameterLength(1,2),p_=new Map;class m_ extends wd{static get type(){return"MaterialNode"}constructor(e){super(),this.scope=e}getCache(e,t){let s=p_.get(e);return void 0===s&&(s=Bx(e,t),p_.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===m_.COLOR){const e=void 0!==t.color?this.getColor(s):Dp();i=t.map&&!0===t.map.isTexture?e.mul(this.getTexture("map")):e}else if(s===m_.OPACITY){const e=this.getFloat(s);i=t.alphaMap&&!0===t.alphaMap.isTexture?e.mul(this.getTexture("alpha")):e}else if(s===m_.SPECULAR_STRENGTH)i=t.specularMap&&!0===t.specularMap.isTexture?this.getTexture("specular").r:Ap(1);else if(s===m_.SPECULAR_INTENSITY){const e=this.getFloat(s);i=t.specularIntensityMap&&!0===t.specularIntensityMap.isTexture?e.mul(this.getTexture(s).a):e}else if(s===m_.SPECULAR_COLOR){const e=this.getColor(s);i=t.specularColorMap&&!0===t.specularColorMap.isTexture?e.mul(this.getTexture(s).rgb):e}else if(s===m_.ROUGHNESS){const e=this.getFloat(s);i=t.roughnessMap&&!0===t.roughnessMap.isTexture?e.mul(this.getTexture(s).g):e}else if(s===m_.METALNESS){const e=this.getFloat(s);i=t.metalnessMap&&!0===t.metalnessMap.isTexture?e.mul(this.getTexture(s).b):e}else if(s===m_.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===m_.NORMAL)t.normalMap?(i=l_(this.getTexture("normal"),this.getCache("normalScale","vec2")),i.normalMapType=t.normalMapType,t.normalMap.format!=Io&&t.normalMap.format!=ma&&t.normalMap.format!=Yo||(i.unpackNormalMode="rg")):i=t.bumpMap?d_(this.getTexture("bump").r,this.getFloat("bumpScale")):ox;else if(s===m_.CLEARCOAT){const e=this.getFloat(s);i=t.clearcoatMap&&!0===t.clearcoatMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===m_.CLEARCOAT_ROUGHNESS){const e=this.getFloat(s);i=t.clearcoatRoughnessMap&&!0===t.clearcoatRoughnessMap.isTexture?e.mul(this.getTexture(s).r):e}else if(s===m_.CLEARCOAT_NORMAL)i=t.clearcoatNormalMap?l_(this.getTexture(s),this.getCache(s+"Scale","vec2")):ox;else if(s===m_.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===m_.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===m_.ANISOTROPY)if(t.anisotropyMap&&!0===t.anisotropyMap.isTexture){const e=this.getTexture(s);i=Gp(K_.x,K_.y,K_.y.negate(),K_.x).mul(e.rg.mul(2).sub(Rp(1)).normalize().mul(e.b))}else i=K_;else if(s===m_.IRIDESCENCE_THICKNESS){const e=Cx("1","float",t.iridescenceThicknessRange);if(t.iridescenceThicknessMap){const r=Cx("0","float",t.iridescenceThicknessRange);i=e.sub(r).mul(this.getTexture(s).g).add(r)}else i=e}else if(s===m_.TRANSMISSION){const e=this.getFloat(s);i=t.transmissionMap?e.mul(this.getTexture(s).r):e}else if(s===m_.THICKNESS){const e=this.getFloat(s);i=t.thicknessMap?e.mul(this.getTexture(s).g):e}else if(s===m_.IOR)i=this.getFloat(s);else if(s===m_.LIGHT_MAP)i=this.getTexture(s).rgb.mul(this.getFloat("lightMapIntensity"));else if(s===m_.AO)i=this.getTexture(s).r.sub(1).mul(this.getFloat("aoMapIntensity")).add(1);else if(s===m_.LINE_DASH_OFFSET)i=t.dashOffset?this.getFloat(s):Ap(0);else{const t=this.getNodeType(e);i=this.getCache(s,t)}return i}}m_.ALPHA_TEST="alphaTest",m_.COLOR="color",m_.OPACITY="opacity",m_.SHININESS="shininess",m_.SPECULAR="specular",m_.SPECULAR_STRENGTH="specularStrength",m_.SPECULAR_INTENSITY="specularIntensity",m_.SPECULAR_COLOR="specularColor",m_.REFLECTIVITY="reflectivity",m_.ROUGHNESS="roughness",m_.METALNESS="metalness",m_.NORMAL="normal",m_.CLEARCOAT="clearcoat",m_.CLEARCOAT_ROUGHNESS="clearcoatRoughness",m_.CLEARCOAT_NORMAL="clearcoatNormal",m_.EMISSIVE="emissive",m_.ROTATION="rotation",m_.SHEEN="sheen",m_.SHEEN_ROUGHNESS="sheenRoughness",m_.ANISOTROPY="anisotropy",m_.IRIDESCENCE="iridescence",m_.IRIDESCENCE_IOR="iridescenceIOR",m_.IRIDESCENCE_THICKNESS="iridescenceThickness",m_.IOR="ior",m_.TRANSMISSION="transmission",m_.THICKNESS="thickness",m_.ATTENUATION_DISTANCE="attenuationDistance",m_.ATTENUATION_COLOR="attenuationColor",m_.LINE_SCALE="scale",m_.LINE_DASH_SIZE="dashSize",m_.LINE_GAP_SIZE="gapSize",m_.LINE_WIDTH="linewidth",m_.LINE_DASH_OFFSET="dashOffset",m_.POINT_SIZE="size",m_.DISPERSION="dispersion",m_.LIGHT_MAP="light",m_.AO="ao";const f_=gp(m_,m_.ALPHA_TEST),g_=gp(m_,m_.COLOR),y_=gp(m_,m_.SHININESS),b_=gp(m_,m_.EMISSIVE),x_=gp(m_,m_.OPACITY),__=gp(m_,m_.SPECULAR),w_=gp(m_,m_.SPECULAR_INTENSITY),v_=gp(m_,m_.SPECULAR_COLOR),T_=gp(m_,m_.SPECULAR_STRENGTH),S_=gp(m_,m_.REFLECTIVITY),M_=gp(m_,m_.ROUGHNESS),A_=gp(m_,m_.METALNESS),N_=gp(m_,m_.NORMAL),E_=gp(m_,m_.CLEARCOAT),C_=gp(m_,m_.CLEARCOAT_ROUGHNESS),R_=gp(m_,m_.CLEARCOAT_NORMAL),P_=gp(m_,m_.ROTATION),B_=gp(m_,m_.SHEEN),I_=gp(m_,m_.SHEEN_ROUGHNESS),D_=gp(m_,m_.ANISOTROPY),L_=gp(m_,m_.IRIDESCENCE),F_=gp(m_,m_.IRIDESCENCE_IOR),O_=gp(m_,m_.IRIDESCENCE_THICKNESS),z_=gp(m_,m_.TRANSMISSION),V_=gp(m_,m_.THICKNESS),k_=gp(m_,m_.IOR),U_=gp(m_,m_.ATTENUATION_DISTANCE),G_=gp(m_,m_.ATTENUATION_COLOR),j_=gp(m_,m_.LINE_SCALE),$_=gp(m_,m_.LINE_DASH_SIZE),W_=gp(m_,m_.LINE_GAP_SIZE),H_=gp(m_,m_.LINE_WIDTH),q_=gp(m_,m_.LINE_DASH_OFFSET),X_=gp(m_,m_.POINT_SIZE),Y_=gp(m_,m_.DISPERSION),Z_=gp(m_,m_.LIGHT_MAP),Q_=gp(m_,m_.AO),K_=Im(new sl).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))}),J_=_p(e=>e.context.setupModelViewProjection(),"vec4").once()().toVarying("v_modelViewProjection");class ew extends vd{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 tw=fp(ew).setParameterLength(2);class sw extends Yy{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=sd(e.itemSize),s=e.count):i=t,super(e,i,s),this.isStorageBufferNode=!0,this.structTypeNode=r,this.access=md.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 tw(this,e)}setPBO(e){return this.isPBO=e,this}getPBO(){return this.isPBO}setAccess(e){return this.access=e,this}toReadOnly(){return this.setAccess(md.READ_ONLY)}setAtomic(e){return this.isAtomic=e,this}toAtomic(){return this.setAtomic(!0)}getAttributeData(){return null===this._attribute&&(this._attribute=py(this.value),this._varying=Xg(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 iw=(e,t=null,s=0)=>new sw(e,t,s);class rw extends wd{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===rw.VERTEX)i=e.getVertexIndex();else if(s===rw.INSTANCE)i=e.getInstanceIndex();else if(s===rw.DRAW)i=e.getDrawIndex();else if(s===rw.INVOCATION_LOCAL)i=e.getInvocationLocalIndex();else if(s===rw.INVOCATION_SUBGROUP)i=e.getInvocationSubgroupIndex();else{if(s!==rw.SUBGROUP)throw new Error("THREE.IndexNode: Unknown scope: "+s);i=e.getSubgroupIndex()}if("vertex"===e.shaderStage||"compute"===e.shaderStage)r=i;else{r=Xg(this).build(e,t)}return r}}rw.VERTEX="vertex",rw.INSTANCE="instance",rw.SUBGROUP="subgroup",rw.INVOCATION_LOCAL="invocationLocal",rw.INVOCATION_SUBGROUP="invocationSubgroup",rw.DRAW="draw";const nw=gp(rw,rw.VERTEX),ow=gp(rw,rw.INSTANCE),aw=gp(rw,rw.SUBGROUP),lw=gp(rw,rw.INVOCATION_SUBGROUP),hw=gp(rw,rw.INVOCATION_LOCAL),uw=gp(rw,rw.DRAW);class cw extends wd{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=pd.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=iw(t,"mat4",Math.max(n,1)).element(ow);else if(n<=1e3)o=Zy(t.array,"mat4",Math.max(n,1)).element(ow);else{const e=new $c(t.array,16,1);this.buffer=e;const s=t.usage===Pa?fy:my,i=[s(e,"vec4",16,0),s(e,"vec4",16,4),s(e,"vec4",16,8),s(e,"vec4",16,12)];o=$p(...i)}this.instanceMatrixNode=o}if(s&&null===a){if(r)a=iw(s,"vec3",Math.max(s.count,1)).element(ow);else{const e=new Qu(s.array,3),t=s.usage===Pa?fy:my;this.bufferColor=e,a=Dp(t(e,"vec3",3,0))}this.instanceColorNode=a}const l=o.mul(Wb).xyz;if(Wb.assign(l),e.hasGeometryAttribute("normal")){const e=hx(sx,o);sx.assign(e)}null!==this.instanceColorNode&&Yp("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!==Pa&&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!==Pa&&this.instanceColor.version!==this.bufferColor.version&&(this.bufferColor.version=this.instanceColor.version))}}const dw=fp(cw).setParameterLength(2,3);class pw extends cw{static get type(){return"InstancedMeshNode"}constructor(e){const{count:t,instanceMatrix:s,instanceColor:i}=e;super(t,s,i),this.instancedMesh=e}}const mw=fp(pw).setParameterLength(1);class fw extends wd{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=ow:this.batchingIdNode=uw);const t=_p(([e])=>{const t=Np(Uy(Xy(this.batchMesh._indirectTexture),0).x).toConst(),s=Np(e).mod(t).toConst(),i=Np(e).div(t).toConst();return Xy(this.batchMesh._indirectTexture,Pp(s,i)).x}).setLayout({name:"getIndirectIndex",type:"uint",inputs:[{name:"id",type:"int"}]})(Np(this.batchingIdNode)),s=this.batchMesh._matricesTexture,i=Np(Uy(Xy(s),0).x).toConst(),r=Ap(t).mul(4).toInt().toConst(),n=r.mod(i).toConst(),o=r.div(i).toConst(),a=$p(Xy(s,Pp(n,o)),Xy(s,Pp(n.add(1),o)),Xy(s,Pp(n.add(2),o)),Xy(s,Pp(n.add(3),o))),l=this.batchMesh._colorsTexture;if(null!==l){const e=_p(([e])=>{const t=Np(Uy(Xy(l),0).x).toConst(),s=e,i=s.mod(t).toConst(),r=s.div(t).toConst();return Xy(l,Pp(i,r)).rgb}).setLayout({name:"getBatchingColor",type:"vec3",inputs:[{name:"id",type:"int"}]})(t);Yp("vec3","vBatchColor").assign(e)}const h=jp(a);Wb.assign(a.mul(Wb));const u=sx.div(Dp(h[0].dot(h[0]),h[1].dot(h[1]),h[2].dot(h[2]))),c=h.mul(u).xyz;sx.assign(c),e.hasGeometryAttribute("tangent")&&Xx.mulAssign(h)}}const gw=fp(fw).setParameterLength(1),yw=new WeakMap;class bw extends wd{static get type(){return"SkinningNode"}constructor(e){super("void"),this.skinnedMesh=e,this.updateType=pd.OBJECT,this.skinIndexNode=zy("skinIndex","uvec4"),this.skinWeightNode=zy("skinWeight","vec4"),this.bindMatrixNode=Cx("bindMatrix","mat4"),this.bindMatrixInverseNode=Cx("bindMatrixInverse","mat4"),this.boneMatricesNode=Rx("skeleton.boneMatrices","mat4",e.skeleton.bones.length),this.positionNode=Wb,this.toPositionNode=Wb,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=Gm(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=sx){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=Gm(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=Rx("skeleton.previousBoneMatrices","mat4",t.skeleton.bones.length)),this.getSkinnedPosition(this.previousBoneMatricesNode,Hb)}needsPreviousBoneMatrices(e){const t=e.renderer.getMRT();return t&&t.has("velocity")||!0===hd(e.object).useVelocity}setup(e){this.needsPreviousBoneMatrices(e)&&Hb.assign(this.getPreviousSkinnedPosition(e));const t=this.getSkinnedPosition();if(this.toPositionNode&&this.toPositionNode.assign(t),e.hasGeometryAttribute("normal")){const t=this.getSkinnedNormal();sx.assign(t),e.hasGeometryAttribute("tangent")&&Xx.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;yw.get(t)!==e.frameId&&(yw.set(t,e.frameId),null!==this.previousBoneMatricesNode&&(null===t.previousBoneMatrices&&(t.previousBoneMatrices=new Float32Array(t.boneMatrices)),t.previousBoneMatrices.set(t.boneMatrices)),t.update())}}const xw=e=>new bw(e);class _w extends wd{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]=Ey(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=_p(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):(Ga("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 ww=(...e)=>new _w(mp(e,"int")).toStack(),vw=()=>Ey("break").toStack(),Tw=new WeakMap,Sw=new Tl,Mw=_p(({bufferMap:e,influence:t,stride:s,width:i,depth:r,offset:n})=>{const o=Np(nw).mul(s).add(n),a=o.div(i),l=o.sub(a.mul(i));return Xy(e,Pp(l,a)).depth(r).xyz.mul(t)});class Aw extends wd{static get type(){return"MorphNode"}constructor(e){super("void"),this.mesh=e,this.morphBaseInfluence=Im(1),this.updateType=pd.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=Tw.get(e);if(void 0===o||o.count!==n){let r=function(){f.dispose(),Tw.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 Al(m,c,d,n);f.type=_o,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&&(Sw.fromBufferAttribute(r,e),m[u+a+0]=Sw.x,m[u+a+1]=Sw.y,m[u+a+2]=Sw.z,m[u+a+3]=0),!0===s&&(Sw.fromBufferAttribute(n,e),m[u+a+4]=Sw.x,m[u+a+5]=Sw.y,m[u+a+6]=Sw.z,m[u+a+7]=0),!0===i&&(Sw.fromBufferAttribute(o,e),m[u+a+8]=Sw.x,m[u+a+9]=Sw.y,m[u+a+10]=Sw.z,m[u+a+11]=4===o.itemSize?Sw.w:1)}}o={count:n,texture:f,stride:u,size:new sl(c,d)},Tw.set(e,o),e.addEventListener("dispose",r)}return o}(t);!0===s&&Wb.mulAssign(this.morphBaseInfluence),!0===i&&sx.mulAssign(this.morphBaseInfluence);const h=Np(l.width);ww(n,({i:e})=>{const t=Ap(0).toVar();this.mesh.count>1&&null!==this.mesh.morphTexture&&void 0!==this.mesh.morphTexture?t.assign(Xy(this.mesh.morphTexture,Pp(Np(e).add(1),Np(ow))).r):t.assign(Cx("morphTargetInfluences","float").element(e).toVar()),Tp(t.notEqual(0),()=>{!0===s&&Wb.addAssign(Mw({bufferMap:o,influence:t,stride:a,width:h,depth:e,offset:Np(0)})),!0===i&&sx.addAssign(Mw({bufferMap:o,influence:t,stride:a,width:h,depth:e,offset:Np(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 Nw=fp(Aw).setParameterLength(1);class Ew extends wd{static get type(){return"LightingNode"}constructor(){super("vec3"),this.isLightingNode=!0}}class Cw extends Ew{static get type(){return"AONode"}constructor(e=null){super(),this.aoNode=e}setup(e){e.context.ambientOcclusion.mulAssign(this.aoNode)}}class Rw extends Ig{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:Dp().toVar("directDiffuse"),directSpecular:Dp().toVar("directSpecular"),indirectDiffuse:Dp().toVar("indirectDiffuse"),indirectSpecular:Dp().toVar("indirectSpecular")};return{radiance:Dp().toVar("radiance"),irradiance:Dp().toVar("irradiance"),iblIrradiance:Dp().toVar("iblIrradiance"),ambientOcclusion:Ap(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 Pw=fp(Rw);class Bw extends Ew{static get type(){return"IrradianceNode"}constructor(e){super(),this.node=e}setup(e){e.context.irradiance.addAssign(this.node)}}const Iw=new sl;class Dw extends Wy{static get type(){return"ViewportTextureNode"}constructor(e=nb,t=null,s=null){let i=null;null===s?(i=new cc,i.minFilter=po,s=i):i=s,super(s,e,t),this.generateMipmaps=!1,this.defaultFramebuffer=i,this.isOutputTextureNode=!0,this.updateBeforeType=pd.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(Iw):Iw.set(s.width,s.height);const i=this.getTextureForReference(s);i.image.width===Iw.width&&i.image.height===Iw.height||(i.image.width=Iw.width,i.image.height=Iw.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 Lw=fp(Dw).setParameterLength(0,3),Fw=fp(Dw,null,null,{generateMipmaps:!0}).setParameterLength(0,3);let Ow=null;class zw extends Dw{static get type(){return"ViewportDepthTextureNode"}constructor(e=nb,t=null){null===Ow&&(Ow=new dc),super(e,t,Ow)}getTextureForReference(){return Ow}}const Vw=fp(zw).setParameterLength(0,2);class kw extends wd{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===kw.DEPTH_BASE?e.getFragDepth():super.generate(e)}setup({camera:e}){const{scope:t}=this,s=this.valueNode;let i=null;if(t===kw.DEPTH_BASE)null!==s&&(i=Ww().assign(s));else if(t===kw.DEPTH)i=e.isPerspectiveCamera?Gw(Yb.z,mb,fb):Uw(Yb.z,mb,fb);else if(t===kw.LINEAR_DEPTH)if(null!==s)if(e.isPerspectiveCamera){const e=jw(s,mb,fb);i=Uw(e,mb,fb)}else i=s;else i=Uw(Yb.z,mb,fb);return i}}kw.DEPTH_BASE="depthBase",kw.DEPTH="depth",kw.LINEAR_DEPTH="linearDepth";const Uw=(e,t,s)=>e.add(t).div(t.sub(s)),Gw=(e,t,s)=>t.add(e).mul(s).div(s.sub(t).mul(e)),jw=(e,t,s)=>t.mul(s).div(s.sub(t).mul(e).sub(s)),$w=(e,t,s)=>{t=t.max(1e-6).toVar();const i=Cf(e.negate().div(t)),r=Cf(s.div(t));return i.div(r)},Ww=fp(kw,kw.DEPTH_BASE),Hw=gp(kw,kw.DEPTH),qw=fp(kw,kw.LINEAR_DEPTH).setParameterLength(0,1),Xw=qw(Vw());Hw.assign=e=>Ww(e);class Yw extends wd{static get type(){return"ClippingNode"}constructor(e=Yw.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===Yw.ALPHA_TO_COVERAGE?this.setupAlphaToCoverage(s,i):this.scope===Yw.HARDWARE?this.setupHardwareClipping(i,e):this.setupDefault(s,i)}setupAlphaToCoverage(e,t){return _p(()=>{const s=Ap().toVar("distanceToPlane"),i=Ap().toVar("distanceToGradient"),r=Ap(1).toVar("clipOpacity"),n=t.length;if(!1===this.hardwareClipping&&n>0){const e=Jy(t).setGroup(Rm);ww(n,({i:t})=>{const n=e.element(t);s.assign(Yb.dot(n.xyz).negate().add(n.w)),i.assign(s.fwidth().div(2)),r.mulAssign(vg(i.negate(),i,s))})}const o=e.length;if(o>0){const t=Jy(e).setGroup(Rm),n=Ap(1).toVar("intersectionClipOpacity");ww(o,({i:e})=>{const r=t.element(e);s.assign(Yb.dot(r.xyz).negate().add(r.w)),i.assign(s.fwidth().div(2)),n.mulAssign(vg(i.negate(),i,s).oneMinus())}),r.mulAssign(n.oneMinus())}Zp.a.mulAssign(r),Zp.a.equal(0).discard()})()}setupDefault(e,t){return _p(()=>{const s=t.length;if(!1===this.hardwareClipping&&s>0){const e=Jy(t).setGroup(Rm);ww(s,({i:t})=>{const s=e.element(t);Yb.dot(s.xyz).greaterThan(s.w).discard()})}const i=e.length;if(i>0){const t=Jy(e).setGroup(Rm),s=Cp(!0).toVar("clipped");ww(i,({i:e})=>{const i=t.element(e);s.assign(Yb.dot(i.xyz).greaterThan(i.w).and(s))}),s.discard()}})()}setupHardwareClipping(e,t){const s=e.length;return t.enableHardwareClipping(s),_p(()=>{const i=Jy(e).setGroup(Rm),r=eb(t.getClipDistance());ww(s,({i:e})=>{const t=i.element(e),s=Yb.dot(t.xyz).sub(t.w).negate();r.element(e).assign(s)})})()}}Yw.ALPHA_TO_COVERAGE="alphaToCoverage",Yw.DEFAULT="default",Yw.HARDWARE="hardware";const Zw=_p(([e])=>Lf($m(1e4,Ff($m(17,e.x).add($m(.1,e.y)))).mul(Gm(.1,Gf(Ff($m(13,e.y).add(e.x))))))),Qw=_p(([e])=>Zw(Rp(Zw(e.xy),e.z))),Kw=_p(([e])=>{const t=rg($f(qf(e.xyz)),$f(Xf(e.xyz))),s=Ap(1).div(Ap(.05).mul(t)).toVar("pixScale"),i=Rp(Nf(Bf(Cf(s))),Nf(If(Cf(s)))),r=Rp(Qw(Bf(i.x.mul(e.xyz))),Qw(Bf(i.y.mul(e.xyz)))),n=Lf(Cf(s)),o=Gm($m(n.oneMinus(),r.x),$m(n,r.y)),a=ig(n,n.oneMinus()),l=Dp(o.mul(o).div($m(2,a).mul(jm(1,a))),o.sub($m(.5,a)).div(jm(1,a)),jm(1,jm(1,o).mul(jm(1,o)).div($m(2,a).mul(jm(1,a))))),h=o.lessThan(a.oneMinus()).select(o.lessThan(a).select(l.x,l.y),l.z);return xg(h,1e-6,1)}).setLayout({name:"getAlphaHashThreshold",type:"float",inputs:[{name:"position",type:"vec3"}]});class Jw extends Oy{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 Tl(1,1,1,1)),s}serialize(e){super.serialize(e),e.index=this.index}deserialize(e){super.deserialize(e),this.index=e.index}}const ev=(e=0)=>new Jw(e),tv=_p(([e,t])=>ig(1,e.oneMinus().div(t)).oneMinus()).setLayout({name:"blendBurn",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),sv=_p(([e,t])=>ig(e.div(t.oneMinus()),1)).setLayout({name:"blendDodge",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),iv=_p(([e,t])=>e.oneMinus().mul(t.oneMinus()).oneMinus()).setLayout({name:"blendScreen",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),rv=_p(([e,t])=>bg(e.mul(2).mul(t),e.oneMinus().mul(2).mul(t.oneMinus()).oneMinus(),ng(.5,e))).setLayout({name:"blendOverlay",type:"vec3",inputs:[{name:"base",type:"vec3"},{name:"blend",type:"vec3"}]}),nv=_p(([e,t])=>{const s=t.a.add(e.a.mul(t.a.oneMinus()));return zp(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"}]}),ov=_p(([e])=>zp(e.rgb.mul(e.a),e.a),{color:"vec4",return:"vec4"}),av=_p(([e])=>(Tp(e.a.equal(0),()=>zp(0)),zp(e.rgb.div(e.a),e.a)),{color:"vec4",return:"vec4"});class lv extends Yh{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=>{Ua('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(Qc(t.slice(0,-4)),s.getCacheKey());return this.type+Kc(e)}build(e){this.setup(e)}setupObserver(e){return new Yc(e)}setup(e){e.context.setupNormal=()=>Hg(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()}:Ga('NodeMaterial: "renderer.contextNode" must be an instance of `context()`.'),null!==this.contextNode&&(!0===this.contextNode.isContextNode?e.context={...e.context,...this.contextNode.getFlowContextData()}:Ga('NodeMaterial: "material.contextNode" must be an instance of `context()`.')),e.addStack();const i=Hg(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=zp(i,Zp.a).max(0);n=this.setupOutput(e,r),gm.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&&gm.assign(n),n=e,null!==s&&(n=e.merge(s))):null!==s&&(n=s)}}else{let t=this.fragmentNode;!0!==t.isOutputStructNode&&(t=zp(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 Yw(Yw.ALPHA_TO_COVERAGE):e.stack.addToStack(new Yw)}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 Yw(Yw.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?$w(Yb.z,mb,fb):Uw(Yb.z,mb,fb))}null!==i&&Hw.assign(i).toStack()}setupPositionView(){return kb.mul(Wb).xyz}setupModelViewProjection(){return gb.mul(Yb)}setupVertex(e){return e.addStack(),this.setupPosition(e),e.context.vertex=e.removeStack(),J_}setupPosition(e){const{object:t,geometry:s}=e;if((s.morphAttributes.position||s.morphAttributes.normal||s.morphAttributes.color)&&Nw(t).toStack(),!0===t.isSkinnedMesh&&xw(t).toStack(),this.displacementMap){const e=Bx("displacementMap","texture"),t=Bx("displacementScale","float"),s=Bx("displacementBias","float");Wb.addAssign(sx.normalize().mul(e.x.mul(t).add(s)))}return t.isBatchedMesh&&gw(t).toStack(),t.isInstancedMesh&&t.instanceMatrix&&!0===t.instanceMatrix.isInstancedBufferAttribute&&mw(t).toStack(),null!==this.positionNode&&Wb.assign(Hg(this.positionNode,"POSITION","vec3")),Wb}setupDiffuseColor(e){const{object:t,geometry:s}=e;null!==this.maskNode&&Cp(this.maskNode).not().discard();let i=this.colorNode?zp(this.colorNode):g_;if(!0===this.vertexColors&&s.hasAttribute("color")&&(i=i.mul(ev())),t.instanceColor){i=Yp("vec3","vInstanceColor").mul(i)}if(t.isBatchedMesh&&t._colorsTexture){i=Yp("vec3","vBatchColor").mul(i)}Zp.assign(i);const r=this.opacityNode?Ap(this.opacityNode):x_;Zp.a.assign(Zp.a.mul(r));let n=null;(null!==this.alphaTestNode||this.alphaTest>0)&&(n=null!==this.alphaTestNode?Ap(this.alphaTestNode):f_,!0===this.alphaToCoverage?(Zp.a=vg(n,n.add(Kf(Zp.a)),Zp.a),Zp.a.lessThanEqual(0).discard()):Zp.a.lessThanEqual(n).discard()),!0===this.alphaHash&&Zp.a.lessThan(Kw(Wb)).discard(),e.isOpaque()&&Zp.a.assign(1)}setupVariants(){}setupOutgoingLight(){return!0===this.lights?Dp(0):Zp.rgb}setupNormal(){return this.normalNode?Dp(this.normalNode):N_}setupEnvironment(){let e=null;return this.envNode?e=this.envNode:this.envMap&&(e=this.envMap.isCubeTexture?Bx("envMap","cubeTexture"):Bx("envMap","texture")),e}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Bw(Z_)),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=Q_),e.context.getAO&&(r=e.context.getAO(r,e)),r&&t.push(new Cw(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=Pw(n,t,s,i)}else null!==s&&(o=Dp(null!==i?bg(o,s,i):s));return(r&&!0===r.isNode||t.emissive&&!0===t.emissive.isColor)&&(Kp.assign(Dp(r||b_)),o=o.add(Kp)),o}setupFog(e,t){const s=e.fogNode;return s&&(gm.assign(t),t=zp(s.toVar())),t}setupPremultipliedAlpha(e,t){return ov(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=Yh.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 hv=new hc;class uv extends lv{static get type(){return"LineBasicNodeMaterial"}constructor(e){super(),this.isLineBasicNodeMaterial=!0,this.setDefaultValues(hv),this.setValues(e)}}const cv=new Mc;class dv extends lv{static get type(){return"LineDashedNodeMaterial"}constructor(e){super(),this.isLineDashedNodeMaterial=!0,this.setDefaultValues(cv),this.dashOffset=0,this.offsetNode=null,this.dashScaleNode=null,this.dashSizeNode=null,this.gapSizeNode=null,this.setValues(e)}setupVariants(){const e=this.offsetNode?Ap(this.offsetNode):q_,t=this.dashScaleNode?Ap(this.dashScaleNode):j_,s=this.dashSizeNode?Ap(this.dashSizeNode):$_,i=this.gapSizeNode?Ap(this.gapSizeNode):W_;ym.assign(s),bm.assign(i);const r=Xg(zy("lineDistance").mul(t));(e?r.add(e):r).mod(ym.add(bm)).greaterThan(ym).discard()}}let pv=null;class mv extends Dw{static get type(){return"ViewportSharedTextureNode"}constructor(e=nb,t=null){null===pv&&(pv=new cc),super(e,t,pv)}getTextureForReference(){return pv}updateReference(){return this}}const fv=fp(mv).setParameterLength(0,2),gv=new vc;class yv extends lv{static get type(){return"MeshNormalNodeMaterial"}constructor(e){super(),this.isMeshNormalNodeMaterial=!0,this.setDefaultValues(gv),this.setValues(e)}setupDiffuseColor(){const e=this.opacityNode?Ap(this.opacityNode):x_;Zp.assign(ty(zp(n_(ox),e),ya))}}const bv=_p(([e=Xb])=>{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 Rp(t,s)});class xv extends Uu{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 Ru(5,5,5),n=bv(Xb),o=new lv;o.colorNode=qy(t,n,0),o.side=1,o.blending=0;const a=new Eu(r,o),l=new Wu;l.add(a),t.minFilter===po&&(t.minFilter=uo);const h=new Vu(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 _v=new WeakMap;class wv extends Sd{static get type(){return"CubeMapNode"}constructor(e){super("vec3"),this.envNode=e,this._cubeTexture=null,this._cubeTextureNode=Ax(null);const t=new ku;t.isRenderTargetTexture=!0,this._defaultTexture=t,this.updateBeforeType=pd.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(_v.has(e)){const t=_v.get(e);Tv(t,e.mapping),this._cubeTexture=t}else{const s=e.image;if(function(e){return null!=e&&e.height>0}(s)){const i=new xv(s.height);i.fromEquirectangularTexture(t,e),Tv(i.texture,e.mapping),this._cubeTexture=i.texture,_v.set(e,i.texture),e.addEventListener("dispose",vv)}else this._cubeTexture=this._defaultTexture}this._cubeTextureNode.value=this._cubeTexture}else this._cubeTextureNode=this.envNode}}}setup(e){return this.updateBefore(e),this._cubeTextureNode}}function vv(e){const t=e.target;t.removeEventListener("dispose",vv);const s=_v.get(t);void 0!==s&&(_v.delete(t),s.dispose())}function Tv(e,t){303===t?e.mapping=so:304===t&&(e.mapping=io)}const Sv=fp(wv).setParameterLength(1);class Mv extends Ew{static get type(){return"BasicEnvironmentNode"}constructor(e=null){super(),this.envNode=e}setup(e){e.context.environment=Sv(this.envNode)}}class Av extends Ew{static get type(){return"BasicLightMapNode"}constructor(e=null){super(),this.lightMapNode=e}setup(e){const t=Ap(1/Math.PI);e.context.irradianceLightMap=this.lightMapNode.mul(t)}}class Nv{start(e){e.lightsNode.setupLights(e,e.lightsNode.getLightNodes(e)),this.indirect(e)}finish(){}direct(){}directRectArea(){}indirect(){}ambientOcclusion(){}}class Ev extends Nv{constructor(){super()}indirect({context:e}){const t=e.ambientOcclusion,s=e.reflectedLight,i=e.irradianceLightMap;s.indirectDiffuse.assign(zp(0)),i?s.indirectDiffuse.addAssign(i):s.indirectDiffuse.addAssign(zp(1,1,1,0)),s.indirectDiffuse.mulAssign(t),s.indirectDiffuse.mulAssign(Zp.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(bg(i.rgb,i.rgb.mul(r.rgb),T_.mul(S_)));break;case 1:i.rgb.assign(bg(i.rgb,r.rgb,T_.mul(S_)));break;case 2:i.rgb.addAssign(r.rgb.mul(T_.mul(S_)));break;default:Ua("BasicLightingModel: Unsupported .combine value:",t.combine)}}}const Cv=new Zh;class Rv extends lv{static get type(){return"MeshBasicNodeMaterial"}constructor(e){super(),this.isMeshBasicNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Cv),this.setValues(e)}setupNormal(){return ex(rx)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Mv(t):null}setupLightMap(e){let t=null;return e.material.lightMap&&(t=new Av(Z_)),t}setupOutgoingLight(){return Zp.rgb}setupLightingModel(){return new Ev}}const Pv=_p(({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))}),Bv=_p(e=>e.diffuseColor.mul(1/Math.PI)),Iv=_p(({dotNH:e})=>fm.mul(Ap(.5)).add(1).mul(Ap(1/Math.PI)).mul(e.pow(fm))),Dv=_p(({lightDirection:e})=>{const t=e.add(Zb).normalize(),s=ox.dot(t).clamp(),i=Zb.dot(t).clamp(),r=Pv({f0:dm,f90:1,dotVH:i}),n=Ap(.25),o=Iv({dotNH:s});return r.mul(n).mul(o)});class Lv extends Ev{constructor(e=!0){super(),this.specular=e}direct({lightDirection:e,lightColor:t,reflectedLight:s}){const i=ox.dot(e).clamp().mul(t);s.directDiffuse.addAssign(i.mul(Bv({diffuseColor:Zp.rgb}))),!0===this.specular&&s.directSpecular.addAssign(i.mul(Dv({lightDirection:e})).mul(T_))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(Bv({diffuseColor:Zp}))),i.indirectDiffuse.mulAssign(t)}}const Fv=new Tc;class Ov extends lv{static get type(){return"MeshLambertNodeMaterial"}constructor(e){super(),this.isMeshLambertNodeMaterial=!0,this.lights=!0,this.setDefaultValues(Fv),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Mv(t):null}setupLightingModel(){return new Lv(!1)}}const zv=new _c;class Vv extends lv{static get type(){return"MeshPhongNodeMaterial"}constructor(e){super(),this.isMeshPhongNodeMaterial=!0,this.lights=!0,this.shininessNode=null,this.specularNode=null,this.setDefaultValues(zv),this.setValues(e)}setupEnvironment(e){const t=super.setupEnvironment(e);return t?new Mv(t):null}setupLightingModel(){return new Lv}setupVariants(){const e=(this.shininessNode?Ap(this.shininessNode):y_).max(1e-4);fm.assign(e);const t=this.specularNode||__;dm.assign(t)}copy(e){return this.shininessNode=e.shininessNode,this.specularNode=e.specularNode,super.copy(e)}}const kv=_p(e=>{if(!1===e.geometry.hasAttribute("normal"))return Ap(0);const t=rx.dFdx().abs().max(rx.dFdy().abs());return t.x.max(t.y).max(t.z)}),Uv=_p(e=>{const{roughness:t}=e,s=kv();let i=t.max(.0525);return i=i.add(s),i=i.min(1),i}),Gv=_p(({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 Wm(.5,r.add(n).max(gf))}).setLayout({name:"V_GGX_SmithCorrelated",type:"float",inputs:[{name:"alpha",type:"float"},{name:"dotNL",type:"float"},{name:"dotNV",type:"float"}]}),jv=_p(({alphaT:e,alphaB:t,dotTV:s,dotBV:i,dotTL:r,dotBL:n,dotNV:o,dotNL:a})=>{const l=a.mul(Dp(e.mul(s),t.mul(i),o).length()),h=o.mul(Dp(e.mul(r),t.mul(n),a).length());return Wm(.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"}]}),$v=_p(({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"}]}),Wv=Ap(1/Math.PI),Hv=_p(({alphaT:e,alphaB:t,dotNH:s,dotTH:i,dotBH:r})=>{const n=e.mul(t),o=Dp(t.mul(i),e.mul(r),n.mul(s)),a=o.dot(o),l=n.div(a);return Wv.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"}]}),qv=_p(({lightDirection:e,f0:t,f90:s,roughness:i,f:r,normalView:n=ox,USE_IRIDESCENCE:o,USE_ANISOTROPY:a})=>{const l=i.pow2(),h=e.add(Zb).normalize(),u=n.dot(e).clamp(),c=n.dot(Zb).clamp(),d=n.dot(h).clamp(),p=Zb.dot(h).clamp();let m,f,g=Pv({f0:t,f90:s,dotVH:p});if(lp(o)&&(g=nm.mix(g,r)),lp(a)){const t=um.dot(e),s=um.dot(Zb),i=um.dot(h),r=cm.dot(e),n=cm.dot(Zb),o=cm.dot(h);m=jv({alphaT:lm,alphaB:l,dotTV:s,dotBV:n,dotTL:t,dotBL:r,dotNV:c,dotNL:u}),f=Hv({alphaT:lm,alphaB:l,dotNH:d,dotTH:i,dotBH:o})}else m=Gv({alpha:l,dotNL:u,dotNV:c}),f=$v({alpha:l,dotNH:d});return g.mul(m).mul(f)}),Xv=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 Yv=null;const Zv=_p(({roughness:e,dotNV:t})=>{null===Yv&&(Yv=new Zu(Xv,16,16,Io,wo),Yv.name="DFG_LUT",Yv.minFilter=uo,Yv.magFilter=uo,Yv.wrapS=no,Yv.wrapT=no,Yv.generateMipmaps=!1,Yv.needsUpdate=!0);const s=Rp(e,t);return qy(Yv,s).rg}),Qv=_p(({lightDirection:e,f0:t,f90:s,roughness:i,f:r,USE_IRIDESCENCE:n,USE_ANISOTROPY:o})=>{const a=qv({lightDirection:e,f0:t,f90:s,roughness:i,f:r,USE_IRIDESCENCE:n,USE_ANISOTROPY:o}),l=ox.dot(e).clamp(),h=ox.dot(Zb).clamp(),u=Zv({roughness:i,dotNV:h}),c=Zv({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=Ap(1).sub(m),y=Ap(1).sub(f),b=t.add(t.oneMinus().mul(.047619)),x=d.mul(p).mul(b).div(Ap(1).sub(g.mul(y).mul(b).mul(b)).add(gf)),_=g.mul(y),w=x.mul(_);return a.add(w)}),Kv=_p(e=>{const{dotNV:t,specularColor:s,specularF90:i,roughness:r}=e,n=Zv({dotNV:t,roughness:r});return s.mul(n.x).add(i.mul(n.y))}),Jv=_p(({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(Dp(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"}]}),eT=_p(({roughness:e,dotNH:t})=>{const s=e.pow2(),i=Ap(1).div(s),r=t.pow2().oneMinus().max(.0078125);return Ap(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"}]}),tT=_p(({dotNV:e,dotNL:t})=>Ap(1).div(Ap(4).mul(t.add(e).sub(t.mul(e))))).setLayout({name:"V_Neubelt",type:"float",inputs:[{name:"dotNV",type:"float"},{name:"dotNL",type:"float"}]}),sT=_p(({lightDirection:e})=>{const t=e.add(Zb).normalize(),s=ox.dot(e).clamp(),i=ox.dot(Zb).clamp(),r=ox.dot(t).clamp(),n=eT({roughness:rm,dotNH:r}),o=tT({dotNV:i,dotNL:s});return im.mul(n).mul(o)}),iT=_p(({N:e,V:t,roughness:s})=>{const i=e.dot(t).saturate(),r=Rp(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"}]}),rT=_p(({f:e})=>{const t=e.length();return rg(t.mul(t).add(e.z).div(t.add(1)),0)}).setLayout({name:"LTC_ClippedSphereFormFactor",type:"float",inputs:[{name:"f",type:"vec3"}]}),nT=_p(({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,rg(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"}]}),oT=_p(({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=Dp().toVar();return Tp(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(jp(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=Dp(0).toVar();g.addAssign(nT({v1:d,v2:p})),g.addAssign(nT({v1:p,v2:m})),g.addAssign(nT({v1:m,v2:f})),g.addAssign(nT({v1:f,v2:d})),c.assign(Dp(rT({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"}]}),aT=1/6,lT=e=>$m(aT,$m(e,$m(e,e.negate().add(3)).sub(3)).add(1)),hT=e=>$m(aT,$m(e,$m(e,$m(3,e).sub(6))).add(4)),uT=e=>$m(aT,$m(e,$m(e,$m(-3,e).add(3)).add(3)).add(1)),cT=e=>$m(aT,cg(e,3)),dT=e=>lT(e).add(hT(e)),pT=e=>uT(e).add(cT(e)),mT=e=>Gm(-1,hT(e).div(lT(e).add(hT(e)))),fT=e=>Gm(1,cT(e).div(uT(e).add(cT(e)))),gT=(e,t,s)=>{const i=e.uvNode,r=$m(i,t.zw).add(.5),n=Bf(r),o=Lf(r),a=dT(o.x),l=pT(o.x),h=mT(o.x),u=fT(o.x),c=mT(o.y),d=fT(o.y),p=Rp(n.x.add(h),n.y.add(c)).sub(.5).mul(t.xy),m=Rp(n.x.add(u),n.y.add(c)).sub(.5).mul(t.xy),f=Rp(n.x.add(h),n.y.add(d)).sub(.5).mul(t.xy),g=Rp(n.x.add(u),n.y.add(d)).sub(.5).mul(t.xy),y=dT(o.y).mul(Gm(a.mul(e.sample(p).level(s)),l.mul(e.sample(m).level(s)))),b=pT(o.y).mul(Gm(a.mul(e.sample(f).level(s)),l.mul(e.sample(g).level(s))));return y.add(b)},yT=_p(([e,t])=>{const s=Rp(e.size(Np(t))),i=Rp(e.size(Np(t.add(1)))),r=Wm(1,s),n=Wm(1,i),o=gT(e,zp(r,s),Bf(t)),a=gT(e,zp(n,i),If(t));return Lf(t).mix(o,a)}),bT=_p(([e,t])=>{const s=t.mul(jy(e));return yT(e,s)}),xT=_p(([e,t,s,i,r])=>{const n=Dp(wg(t.negate(),Df(e),Wm(1,i))),o=Dp($f(r[0].xyz),$f(r[1].xyz),$f(r[2].xyz));return Df(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"}]}),_T=_p(([e,t])=>e.mul(xg(t.mul(2).sub(2),0,1))).setLayout({name:"applyIorToRoughness",type:"float",inputs:[{name:"roughness",type:"float"},{name:"ior",type:"float"}]}),wT=Fw(),vT=Fw(),TT=_p(([e,t,s],{material:i})=>{const r=(1===i.side?wT:vT).sample(e),n=Cf(ob.x).mul(_T(t,s));return yT(r,n)}),ST=_p(([e,t,s])=>(Tp(s.notEqual(0),()=>{const i=Ef(t).negate().div(s);return Af(i.negate().mul(e))}),Dp(1))).setLayout({name:"volumeAttenuation",type:"vec3",inputs:[{name:"transmissionDistance",type:"float"},{name:"attenuationColor",type:"vec3"},{name:"attenuationDistance",type:"float"}]}),MT=_p(([e,t,s,i,r,n,o,a,l,h,u,c,d,p,m])=>{let f,g;if(m){f=zp().toVar(),g=Dp().toVar();const r=u.sub(1).mul(m.mul(.025)),n=Dp(u.sub(r),u,u.add(r));ww({start:0,end:3},({i:r})=>{const u=n.element(r),m=xT(e,t,c,u,a),y=o.add(m),b=h.mul(l.mul(zp(y,1))),x=Rp(b.xy.div(b.w)).toVar();x.addAssign(1),x.divAssign(2),x.assign(Rp(x.x,x.y.oneMinus()));const _=TT(x,s,u);f.element(r).assign(_.element(r)),f.a.addAssign(_.a),g.element(r).assign(i.element(r).mul(ST($f(m),d,p).element(r)))}),f.a.divAssign(3)}else{const r=xT(e,t,c,u,a),n=o.add(r),m=h.mul(l.mul(zp(n,1))),y=Rp(m.xy.div(m.w)).toVar();y.addAssign(1),y.divAssign(2),y.assign(Rp(y.x,y.y.oneMinus())),f=TT(y,s,u),g=i.mul(ST($f(r),d,p))}const y=g.rgb.mul(f.rgb),b=e.dot(t).clamp(),x=Dp(Kv({dotNV:b,specularColor:r,specularF90:n,roughness:s})),_=g.r.add(g.g,g.b).div(3);return zp(x.oneMinus().mul(y),f.a.oneMinus().mul(_).oneMinus())}),AT=jp(3.2404542,-.969266,.0556434,-1.5371385,1.8760108,-.2040259,-.4985314,.041556,1.0572252),NT=(e,t)=>e.sub(t).div(e.add(t)).pow2(),ET=_p(({outsideIOR:e,eta2:t,cosTheta1:s,thinFilmThickness:i,baseF0:r})=>{const n=bg(e,t,vg(0,.03,i)),o=e.div(n).pow2().mul(s.pow2().oneMinus()).oneMinus();Tp(o.lessThan(0),()=>Dp(1));const a=o.sqrt(),l=NT(n,e),h=Pv({f0:l,f90:1,dotVH:s}),u=h.oneMinus(),c=n.lessThan(e).select(Math.PI,0),d=Ap(Math.PI).sub(c),p=(e=>{const t=e.sqrt();return Dp(1).add(t).div(Dp(1).sub(t))})(r.clamp(0,.9999)),m=NT(p,n.toVec3()),f=Pv({f0:m,f90:1,dotVH:a}),g=Dp(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),b=Dp(d).add(g),x=h.mul(f).clamp(1e-5,.9999),_=x.sqrt(),w=u.pow2().mul(f).div(Dp(1).sub(x)),v=h.add(w).toVar(),T=w.sub(u).toVar();return ww({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=Dp(54856e-17,44201e-17,52481e-17),r=Dp(1681e3,1795300,2208400),n=Dp(43278e5,93046e5,66121e5),o=Ap(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=Dp(a.x.add(o),a.y,a.z).div(1.0685e-7),AT.mul(a)})(Ap(e).mul(y),Ap(e).mul(b)).mul(2);v.addAssign(T.mul(t))}),v.max(Dp(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"}]}),CT=_p(({normal:e,viewDir:t,roughness:s})=>{const i=e.dot(t).saturate(),r=s.mul(s),n=s.add(.1).reciprocal(),o=Ap(-1.9362).add(s.mul(1.0678)).add(r.mul(.4573)).sub(n.mul(.8469)),a=Ap(-.6014).add(s.mul(.5538)).sub(r.mul(.467)).sub(n.mul(.1255));return o.mul(i).add(a).exp().saturate()}),RT=Dp(.04),PT=Ap(1);class BT extends Nv{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=Dp().toVar("clearcoatRadiance"),this.clearcoatSpecularDirect=Dp().toVar("clearcoatSpecularDirect"),this.clearcoatSpecularIndirect=Dp().toVar("clearcoatSpecularIndirect")),!0===this.sheen&&(this.sheenSpecularDirect=Dp().toVar("sheenSpecularDirect"),this.sheenSpecularIndirect=Dp().toVar("sheenSpecularIndirect")),!0===this.iridescence){const e=ox.dot(Zb).clamp(),t=ET({outsideIOR:Ap(1),eta2:om,cosTheta1:e,thinFilmThickness:am,baseF0:dm}),s=ET({outsideIOR:Ap(1),eta2:om,cosTheta1:e,thinFilmThickness:am,baseF0:Zp.rgb});this.iridescenceFresnel=bg(t,s,em),this.iridescenceF0Dielectric=Jv({f:t,f90:1,dotVH:e}),this.iridescenceF0Metallic=Jv({f:s,f90:1,dotVH:e}),this.iridescenceF0=bg(this.iridescenceF0Dielectric,this.iridescenceF0Metallic,em)}if(!0===this.transmission){const t=qb,s=wb.sub(qb).normalize(),i=ax,r=e.context;r.backdrop=MT(i,s,Jp,Qp,pm,mm,t,Ib,bb,gb,_m,vm,Sm,Tm,this.dispersion?Mm:null),r.backdropAlpha=wm,Zp.a.mulAssign(bg(1,r.backdrop.a,wm))}super.start(e)}computeMultiscattering(e,t,s,i,r=null){const n=ox.dot(Zb).clamp(),o=Zv({roughness:Jp,dotNV:n}),a=r?nm.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=ox.dot(e).clamp().mul(t).toVar();if(!0===this.sheen){this.sheenSpecularDirect.addAssign(i.mul(sT({lightDirection:e})));const t=CT({normal:ox,viewDir:Zb,roughness:rm}),s=CT({normal:ox,viewDir:e,roughness:rm}),r=im.r.max(im.g).max(im.b).mul(t.max(s)).oneMinus();i.mulAssign(r)}if(!0===this.clearcoat){const s=lx.dot(e).clamp().mul(t);this.clearcoatSpecularDirect.addAssign(s.mul(qv({lightDirection:e,f0:RT,f90:PT,roughness:sm,normalView:lx})))}s.directDiffuse.addAssign(i.mul(Bv({diffuseColor:Qp}))),s.directSpecular.addAssign(i.mul(Qv({lightDirection:e,f0:pm,f90:1,roughness:Jp,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=ox,d=Zb,p=Yb.toVar(),m=iT({N:c,V:d,roughness:Jp}),f=n.sample(m).toVar(),g=o.sample(m).toVar(),y=jp(Dp(f.x,0,f.y),Dp(0,1,0),Dp(f.z,0,f.w)).toVar(),b=pm.mul(g.x).add(pm.oneMinus().mul(g.y)).toVar();r.directSpecular.addAssign(e.mul(b).mul(oT({N:c,V:d,P:p,mInv:y,p0:a,p1:l,p2:h,p3:u}))),r.directDiffuse.addAssign(e.mul(Qp).mul(oT({N:c,V:d,P:p,mInv:jp(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(Bv({diffuseColor:Qp})).toVar();if(!0===this.sheen){const e=CT({normal:ox,viewDir:Zb,roughness:rm}),t=im.r.max(im.g).max(im.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(im,CT({normal:ox,viewDir:Zb,roughness:rm}))),!0===this.clearcoat){const e=lx.dot(Zb).clamp(),t=Kv({dotNV:e,specularColor:RT,specularF90:PT,roughness:sm});this.clearcoatSpecularIndirect.addAssign(this.clearcoatRadiance.mul(t))}const r=Dp().toVar("singleScatteringDielectric"),n=Dp().toVar("multiScatteringDielectric"),o=Dp().toVar("singleScatteringMetallic"),a=Dp().toVar("multiScatteringMetallic");this.computeMultiscattering(r,n,mm,dm,this.iridescenceF0Dielectric),this.computeMultiscattering(o,a,mm,Zp.rgb,this.iridescenceF0Metallic);const l=bg(r,o,em),h=bg(n,a,em),u=r.add(n),c=Qp.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=CT({normal:ox,viewDir:Zb,roughness:rm}),t=im.r.max(im.g).max(im.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=ox.dot(Zb).clamp().add(t),r=Jp.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=lx.dot(Zb).clamp(),s=Pv({dotVH:e,f0:RT,f90:PT}),i=t.mul(tm.mul(s).oneMinus()).add(this.clearcoatSpecularDirect.add(this.clearcoatSpecularIndirect).mul(tm));t.assign(i)}if(!0===this.sheen){const e=t.add(this.sheenSpecularDirect,this.sheenSpecularIndirect.mul(1/Math.PI));t.assign(e)}}}const IT=Ap(1),DT=Ap(-2),LT=Ap(.8),FT=Ap(-1),OT=Ap(.4),zT=Ap(2),VT=Ap(.305),kT=Ap(3),UT=Ap(.21),GT=Ap(4),jT=Ap(4),$T=Ap(16),WT=_p(([e])=>{const t=Dp(Gf(e)).toVar(),s=Ap(-1).toVar();return Tp(t.x.greaterThan(t.z),()=>{Tp(t.x.greaterThan(t.y),()=>{s.assign(Bg(e.x.greaterThan(0),0,3))}).Else(()=>{s.assign(Bg(e.y.greaterThan(0),1,4))})}).Else(()=>{Tp(t.z.greaterThan(t.y),()=>{s.assign(Bg(e.z.greaterThan(0),2,5))}).Else(()=>{s.assign(Bg(e.y.greaterThan(0),1,4))})}),s}).setLayout({name:"getFace",type:"float",inputs:[{name:"direction",type:"vec3"}]}),HT=_p(([e,t])=>{const s=Rp().toVar();return Tp(t.equal(0),()=>{s.assign(Rp(e.z,e.y).div(Gf(e.x)))}).ElseIf(t.equal(1),()=>{s.assign(Rp(e.x.negate(),e.z.negate()).div(Gf(e.y)))}).ElseIf(t.equal(2),()=>{s.assign(Rp(e.x.negate(),e.y).div(Gf(e.z)))}).ElseIf(t.equal(3),()=>{s.assign(Rp(e.z.negate(),e.y).div(Gf(e.x)))}).ElseIf(t.equal(4),()=>{s.assign(Rp(e.x.negate(),e.z).div(Gf(e.y)))}).Else(()=>{s.assign(Rp(e.x,e.y).div(Gf(e.z)))}),$m(.5,s.add(1))}).setLayout({name:"getUV",type:"vec2",inputs:[{name:"direction",type:"vec3"},{name:"face",type:"float"}]}),qT=_p(([e])=>{const t=Ap(0).toVar();return Tp(e.greaterThanEqual(LT),()=>{t.assign(IT.sub(e).mul(FT.sub(DT)).div(IT.sub(LT)).add(DT))}).ElseIf(e.greaterThanEqual(OT),()=>{t.assign(LT.sub(e).mul(zT.sub(FT)).div(LT.sub(OT)).add(FT))}).ElseIf(e.greaterThanEqual(VT),()=>{t.assign(OT.sub(e).mul(kT.sub(zT)).div(OT.sub(VT)).add(zT))}).ElseIf(e.greaterThanEqual(UT),()=>{t.assign(VT.sub(e).mul(GT.sub(kT)).div(VT.sub(UT)).add(kT))}).Else(()=>{t.assign(Ap(-2).mul(Cf($m(1.16,e))))}),t}).setLayout({name:"roughnessToMip",type:"float",inputs:[{name:"roughness",type:"float"}]}),XT=_p(([e,t])=>{const s=e.toVar();s.assign($m(2,s).sub(1));const i=Dp(s,1).toVar();return Tp(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"}]}),YT=_p(([e,t,s,i,r,n])=>{const o=Ap(s),a=Dp(t),l=xg(qT(o),DT,n),h=Lf(l),u=Bf(l),c=Dp(ZT(e,a,u,i,r,n)).toVar();return Tp(h.notEqual(0),()=>{const t=Dp(ZT(e,a,u.add(1),i,r,n)).toVar();c.assign(bg(c,t,h))}),c}),ZT=_p(([e,t,s,i,r,n])=>{const o=Ap(s).toVar(),a=Dp(t),l=Ap(WT(a)).toVar(),h=Ap(rg(jT.sub(o),0)).toVar();o.assign(rg(o,jT));const u=Ap(Nf(o)).toVar(),c=Rp(HT(a,l).mul(u.sub(2)).add(1)).toVar();return Tp(l.greaterThan(2),()=>{c.y.addAssign(u),l.subAssign(3)}),c.x.addAssign(l.mul(u)),c.x.addAssign(h.mul($m(3,$T))),c.y.addAssign($m(4,Nf(n).sub(u))),c.x.mulAssign(i),c.y.mulAssign(r),e.sample(c).grad(Rp(),Rp())}),QT=_p(({envMap:e,mipInt:t,outputDirection:s,theta:i,axis:r,CUBEUV_TEXEL_WIDTH:n,CUBEUV_TEXEL_HEIGHT:o,CUBEUV_MAX_MIP:a})=>{const l=Of(i),h=s.mul(l).add(r.cross(s).mul(Ff(i))).add(r.mul(r.dot(s).mul(l.oneMinus())));return ZT(e,h,t,n,o,a)}),KT=_p(({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=Dp(Bg(t,s,ug(s,i))).toVar();Tp(d.equal(Dp(0)),()=>{d.assign(Dp(i.z,0,i.x.negate()))}),d.assign(Df(d));const p=Dp().toVar();return p.addAssign(r.element(0).mul(QT({theta:0,axis:d,outputDirection:i,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c}))),ww({start:Np(1),end:e},({i:e})=>{Tp(e.greaterThanEqual(n),()=>{vw()});const t=Ap(o.mul(Ap(e))).toVar();p.addAssign(r.element(e).mul(QT({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(QT({theta:t,axis:d,outputDirection:i,mipInt:a,envMap:l,CUBEUV_TEXEL_WIDTH:h,CUBEUV_TEXEL_HEIGHT:u,CUBEUV_MAX_MIP:c})))}),zp(p,1)}),JT=_p(([e])=>{const t=Ep(e).toVar();return t.assign(t.shiftLeft(Ep(16)).bitOr(t.shiftRight(Ep(16)))),t.assign(t.bitAnd(Ep(1431655765)).shiftLeft(Ep(1)).bitOr(t.bitAnd(Ep(2863311530)).shiftRight(Ep(1)))),t.assign(t.bitAnd(Ep(858993459)).shiftLeft(Ep(2)).bitOr(t.bitAnd(Ep(3435973836)).shiftRight(Ep(2)))),t.assign(t.bitAnd(Ep(252645135)).shiftLeft(Ep(4)).bitOr(t.bitAnd(Ep(4042322160)).shiftRight(Ep(4)))),t.assign(t.bitAnd(Ep(16711935)).shiftLeft(Ep(8)).bitOr(t.bitAnd(Ep(4278255360)).shiftRight(Ep(8)))),Ap(t).mul(2.3283064365386963e-10)}),eS=_p(([e,t])=>Rp(Ap(e).div(Ap(t)),JT(e))),tS=_p(([e,t,s])=>{const i=Dp(t).toVar(),r=Ap(s),n=r.mul(r).toVar(),o=Df(Dp(n.mul(i.x),n.mul(i.y),i.z)).toVar(),a=o.x.mul(o.x).add(o.y.mul(o.y)),l=Bg(a.greaterThan(0),Dp(o.y.negate(),o.x,0).div(Rf(a)),Dp(1,0,0)).toVar(),h=ug(o,l).toVar(),u=Rf(e.x),c=$m(2,3.14159265359).mul(e.y),d=u.mul(Of(c)).toVar(),p=u.mul(Ff(c)).toVar(),m=$m(.5,o.z.add(1));p.assign(m.oneMinus().mul(Rf(d.mul(d).oneMinus())).add(m.mul(p)));const f=l.mul(d).add(h.mul(p)).add(o.mul(Rf(rg(0,d.mul(d).add(p.mul(p)).oneMinus()))));return Df(Dp(n.mul(f.x),n.mul(f.y),rg(0,f.z)))}),sS=_p(({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=Dp(i).toVar(),h=Dp(0).toVar(),u=Ap(0).toVar();return Tp(e.lessThan(.001),()=>{h.assign(ZT(s,l,t,n,o,a))}).Else(()=>{const i=Bg(Gf(l.z).lessThan(.999),Dp(0,0,1),Dp(1,0,0)),c=Df(ug(i,l)).toVar(),d=ug(l,c).toVar();ww({start:Ep(0),end:r},({i:i})=>{const p=eS(i,r),m=tS(p,Dp(0,0,1),e),f=Df(c.mul(m.x).add(d.mul(m.y)).add(l.mul(m.z))),g=Df(f.mul(hg(l,f).mul(2)).sub(l)),y=rg(hg(l,g),0);Tp(y.greaterThan(0),()=>{const e=ZT(s,g,t,n,o,a);h.addAssign(e.mul(y)),u.addAssign(y)})}),Tp(u.greaterThan(0),()=>{h.assign(h.div(u))})}),zp(h,1)}),iS=[.125,.215,.35,.446,.526,.582],rS=20,nS=new Fc(-1,1,1,-1,0,1),oS=new Ou(90,1),aS=new Hh;let lS=null,hS=0,uS=0;const cS=new rl,dS=new WeakMap,pS=[3,1,5,0,4,2],mS=XT(Vy(),zy("faceIndex")).normalize(),fS=Dp(mS.x,mS.y,mS.z);class gS{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=cS,renderTarget:a=null}=r;if(this._setSize(n),!1===this._hasInitialized){Ua('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}lS=this._renderer.getRenderTarget(),hS=this._renderer.getActiveCubeFace(),uS=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 ja('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){Ua('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 ja('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){Ua("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 ja('PMREMGenerator: ".fromCubemapAsync()" is deprecated. Use "await renderer.init()" instead.'),await this._renderer.init(),this._fromTexture(e,t)}async compileCubemapShader(){null===this._cubemapMaterial&&(this._cubemapMaterial=_S(),await this._compileMaterial(this._cubemapMaterial))}async compileEquirectangularShader(){null===this._equirectMaterial&&(this._equirectMaterial=wS(),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===so||e.mapping===io?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(lS,hS,uS),e.scissorTest=!1,bS(e,0,0,e.width,e.height)}_fromTexture(e,t){this._setSizeFromTexture(e),lS=this._renderer.getRenderTarget(),hS=this._renderer.getActiveCubeFace(),uS=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 yS(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=yS(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+iS.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=iS[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),b=new Float32Array(f*p*d),x=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=pS[e];y.set(i,m*p*r),b.set(c,f*p*r);const n=[r,r,r,r,r,r];x.set(n,g*p*r)}const _=new gu;_.setAttribute("position",new ru(y,m)),_.setAttribute("uv",new ru(b,f)),_.setAttribute("faceIndex",new ru(x,g)),i.push(new Eu(_,null)),r>4&&r--}return{lodMeshes:i,sizeLods:t,sigmas:s}}(t)),this._blurMaterial=function(e,t,s){const i=Jy(new Array(rS).fill(0)),r=Im(new rl(0,1,0)),n=Im(0),o=Ap(rS),a=Im(0),l=Im(1),h=qy(),u=Im(0),c=Ap(1/t),d=Ap(1/s),p=Ap(e),m={n:o,latitudinal:a,weights:i,poleAxis:r,outputDirection:fS,dTheta:n,samples:l,envMap:h,mipInt:u,CUBEUV_TEXEL_WIDTH:c,CUBEUV_TEXEL_HEIGHT:d,CUBEUV_MAX_MIP:p},f=xS("blur");return f.fragmentNode=KT({...m,latitudinal:a.equal(1)}),dS.set(f,m),f}(t,e.width,e.height),this._ggxMaterial=function(e,t,s){const i=qy(),r=Im(0),n=Im(0),o=Ap(1/t),a=Ap(1/s),l=Ap(e),h={envMap:i,roughness:r,mipInt:n,CUBEUV_TEXEL_WIDTH:o,CUBEUV_TEXEL_HEIGHT:a,CUBEUV_MAX_MIP:l},u=xS("ggx");return u.fragmentNode=sS({...h,N_immutable:fS,GGX_SAMPLES:Ep(512)}),dS.set(u,h),u}(t,e.width,e.height)}}async _compileMaterial(e){const t=new Eu(new gu,e);await this._renderer.compile(t,nS)}_sceneToCubeUV(e,t,s,i,r){const n=oS;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(aS),l.autoClear=!1,null===this._backgroundBox&&(this._backgroundBox=new Eu(new Ru,new Zh({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(aS),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;bS(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===so||e.mapping===io;i?null===this._cubemapMaterial&&(this._cubemapMaterial=_S(e)):null===this._equirectMaterial&&(this._equirectMaterial=wS(e));const r=i?this._cubemapMaterial:this._equirectMaterial;r.fragmentNode.value=e;const n=this._lodMeshes[0];n.material=r;const o=this._cubeSize;bS(t,0,0,3*o,2*o),s.setRenderTarget(t),s.render(n,nS)}_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=dS.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,bS(r,p,m,3*d,2*d),i.setRenderTarget(r),i.render(o,nS),r.texture.frame=(r.texture.frame||0)+1,a.envMap.value=r.texture,a.roughness.value=0,a.mipInt.value=c-s,bS(e,p,m,3*d,2*d),i.setRenderTarget(e),i.render(o,nS)}_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&&Ga("blur direction must be either latitudinal or longitudinal!");const h=this._lodMeshes[i];h.material=l;const u=dS.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):rS;m>rS&&Ua(`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<rS;++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 b=this._sizeLods[i];bS(t,3*b*(i>y-4?i-y+4:0),4*(this._cubeSize-b),3*b,2*b),a.setRenderTarget(t),a.render(h,nS)}}function yS(e,t){const s=new Sl(e,t,{magFilter:uo,minFilter:uo,generateMipmaps:!1,type:wo,format:Eo,colorSpace:ba});return s.texture.mapping=306,s.texture.name="PMREM.cubeUv",s.texture.isPMREMTexture=!0,s.scissorTest=!0,s}function bS(e,t,s,i,r){e.viewport.set(t,s,i,r),e.scissor.set(t,s,i,r)}function xS(e){const t=new lv;return t.depthTest=!1,t.depthWrite=!1,t.blending=0,t.name=`PMREM_${e}`,t}function _S(e){const t=xS("cubemap");return t.fragmentNode=Ax(e,fS),t}function wS(e){const t=xS("equirect");return t.fragmentNode=qy(e,bv(fS),0),t}const vS=new WeakMap;function TS(e,t,s){const i=function(e){let t=vS.get(e);void 0===t&&(t=new WeakMap,vS.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 SS extends Sd{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 vl;i.isRenderTargetTexture=!0,this._texture=qy(i),this._width=Im(0),this._height=Im(0),this._maxMip=Im(0),this.updateBeforeType=pd.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:TS(i,e.renderer,this._generator),null!==t&&(this._pmrem=t,this.updateFromTexture(t)))}setup(e){null===this._generator&&(this._generator=new gS(e.renderer)),this.updateBefore(e);let t=this.uvNode;null===t&&e.context.getUV&&(t=e.context.getUV(this,e)),t=bx.mul(Dp(t.x,t.y.negate(),t.z));let s=this.levelNode;return null===s&&e.context.getTextureLevel&&(s=e.context.getTextureLevel(this)),YT(this._texture,t,s,this._width,this._height,this._maxMip)}dispose(){super.dispose(),null!==this._generator&&this._generator.dispose()}}const MS=fp(SS).setParameterLength(1,3),AS=new WeakMap;class NS extends Ew{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=AS.get(e);void 0===i&&(i=MS(e),AS.set(e,i)),s=i}const i=!0===t.useAnisotropy||t.anisotropy>0?r_:ox,r=s.context(ES(Jp,i)).mul(yx),n=s.context(CS(ax)).mul(Math.PI).mul(yx),o=_y(r),a=_y(n);e.context.radiance.addAssign(o),e.context.iblIrradiance.addAssign(a);const l=e.context.lightingModel.clearcoatRadiance;if(l){const e=s.context(ES(sm,lx)).mul(yx),t=_y(e);l.addAssign(t)}}}const ES=(e,t)=>{let s=null;return{getUV:()=>(null===s&&(s=Zb.negate().reflect(t),s=mg(e).mix(s,t).normalize(),s=s.transformDirection(bb)),s),getTextureLevel:()=>e}},CS=e=>({getUV:()=>e,getTextureLevel:()=>Ap(1)}),RS=new bc;class PS extends lv{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(RS),this.setValues(e)}setupEnvironment(e){let t=super.setupEnvironment(e);return null===t&&e.environmentNode&&(t=e.environmentNode),t?new NS(t):null}setupLightingModel(){return new BT}setupSpecular(){const e=bg(Dp(.04),Zp.rgb,em);dm.assign(Dp(.04)),pm.assign(e),mm.assign(1)}setupVariants(){const e=this.metalnessNode?Ap(this.metalnessNode):A_;em.assign(e);let t=this.roughnessNode?Ap(this.roughnessNode):M_;t=Uv({roughness:t}),Jp.assign(t),this.setupSpecular(),Qp.assign(Zp.rgb.mul(e.oneMinus()))}copy(e){return this.emissiveNode=e.emissiveNode,this.metalnessNode=e.metalnessNode,this.roughnessNode=e.roughnessNode,super.copy(e)}}const BS=new xc;class IS extends PS{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(BS),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?Ap(this.iorNode):k_;_m.assign(e),dm.assign(ig(dg(_m.sub(1).div(_m.add(1))).mul(v_),Dp(1)).mul(w_)),pm.assign(bg(dm,Zp.rgb,em)),mm.assign(bg(w_,1,em))}setupLightingModel(){return new BT(this.useClearcoat,this.useSheen,this.useIridescence,this.useAnisotropy,this.useTransmission,this.useDispersion)}setupVariants(e){if(super.setupVariants(e),this.useClearcoat){const e=this.clearcoatNode?Ap(this.clearcoatNode):E_,t=this.clearcoatRoughnessNode?Ap(this.clearcoatRoughnessNode):C_;tm.assign(e),sm.assign(Uv({roughness:t}))}if(this.useSheen){const e=this.sheenNode?Dp(this.sheenNode):B_,t=this.sheenRoughnessNode?Ap(this.sheenRoughnessNode):I_;im.assign(e),rm.assign(t)}if(this.useIridescence){const e=this.iridescenceNode?Ap(this.iridescenceNode):L_,t=this.iridescenceIORNode?Ap(this.iridescenceIORNode):F_,s=this.iridescenceThicknessNode?Ap(this.iridescenceThicknessNode):O_;nm.assign(e),om.assign(t),am.assign(s)}if(this.useAnisotropy){const e=(this.anisotropyNode?Rp(this.anisotropyNode):D_).toVar();hm.assign(e.length()),Tp(hm.equal(0),()=>{e.assign(Rp(1,0))}).Else(()=>{e.divAssign(Rp(hm)),hm.assign(hm.saturate())}),lm.assign(hm.pow2().mix(Jp.pow2(),1)),um.assign(s_[0].mul(e.x).add(s_[1].mul(e.y))),cm.assign(s_[1].mul(e.x).sub(s_[0].mul(e.y)))}if(this.useTransmission){const e=this.transmissionNode?Ap(this.transmissionNode):z_,t=this.thicknessNode?Ap(this.thicknessNode):V_,s=this.attenuationDistanceNode?Ap(this.attenuationDistanceNode):U_,i=this.attenuationColorNode?Dp(this.attenuationColorNode):G_;if(wm.assign(e),vm.assign(t),Tm.assign(s),Sm.assign(i),this.useDispersion){const e=this.dispersionNode?Ap(this.dispersionNode):Y_;Mm.assign(e)}}}setupClearcoatNormal(){return this.clearcoatNormalNode?Dp(this.clearcoatNormalNode):R_}setup(e){e.context.setupClearcoatNormal=()=>Hg(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 DS=_p(({normal:e,lightDirection:t,builder:s})=>{const i=e.dot(t),r=Rp(i.mul(.5).add(.5),0);if(s.material.gradientMap){const e=Bx("gradientMap","texture").context({getUV:()=>r});return Dp(e.r)}{const e=r.fwidth().mul(.5);return bg(Dp(.7),Dp(1),vg(Ap(.7).sub(e.x),Ap(.7).add(e.x),r.x))}});class LS extends Nv{direct({lightDirection:e,lightColor:t,reflectedLight:s},i){const r=DS({normal:tx,lightDirection:e,builder:i}).mul(t);s.directDiffuse.addAssign(r.mul(Bv({diffuseColor:Zp.rgb})))}indirect(e){const{ambientOcclusion:t,irradiance:s,reflectedLight:i}=e.context;i.indirectDiffuse.addAssign(s.mul(Bv({diffuseColor:Zp}))),i.indirectDiffuse.mulAssign(t)}}const FS=new wc;class OS extends lv{static get type(){return"MeshToonNodeMaterial"}constructor(e){super(),this.isMeshToonNodeMaterial=!0,this.lights=!0,this.setDefaultValues(FS),this.setValues(e)}setupLightingModel(){return new LS}}const zS=_p(()=>{const e=Dp(Zb.z,0,Zb.x.negate()).normalize(),t=Zb.cross(e);return Rp(e.dot(ox),t.dot(ox)).mul(.495).add(.5)}).once(["NORMAL","VERTEX"])().toVar("matcapUV"),VS=new Sc;class kS extends lv{static get type(){return"MeshMatcapNodeMaterial"}constructor(e){super(),this.isMeshMatcapNodeMaterial=!0,this.setDefaultValues(VS),this.setValues(e)}setupVariants(e){const t=zS;let s;s=e.material.matcap?Bx("matcap","texture").context({getUV:()=>t}):Dp(bg(.2,.8,t.y)),Zp.rgb.mulAssign(s.rgb)}}class US extends Sd{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 Gp(e,i,i.negate(),e).mul(s)}{const e=t,i=$p(zp(1,0,0,0),zp(0,Of(e.x),Ff(e.x).negate(),0),zp(0,Ff(e.x),Of(e.x),0),zp(0,0,0,1)),r=$p(zp(Of(e.y),0,Ff(e.y),0),zp(0,1,0,0),zp(Ff(e.y).negate(),0,Of(e.y),0),zp(0,0,0,1)),n=$p(zp(Of(e.z),Ff(e.z).negate(),0,0),zp(Ff(e.z),Of(e.z),0,0),zp(0,0,1,0),zp(0,0,0,1));return i.mul(r).mul(n).mul(zp(s,1)).xyz}}}const GS=fp(US).setParameterLength(2),jS=new Yu;class $S extends lv{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(jS),this.setValues(e)}setupPositionView(e){const{object:t,camera:s}=e,{positionNode:i,rotationNode:r,scaleNode:n,sizeAttenuation:o}=this,a=kb.mul(Dp(i||0));let l=Rp(Ib[0].xyz.length(),Ib[1].xyz.length());null!==n&&(l=l.mul(Rp(n))),s.isPerspectiveCamera&&!1===o&&(l=l.mul(a.z.negate()));let h=$b.xy;if(t.center&&!0===t.center.isVector2){const e=((e,t,s)=>new iy(e,t,s))("center","vec2",t);h=h.sub(e.sub(.5))}h=h.mul(l);const u=Ap(r||P_),c=GS(h,u);return zp(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 WS=new uc,HS=new sl;class qS extends $S{static get type(){return"PointsNodeMaterial"}constructor(e){super(),this.sizeNode=null,this.isPointsNodeMaterial=!0,this.setDefaultValues(WS),this.setValues(e)}setupPositionView(){const{positionNode:e}=this;return kb.mul(Dp(e||Wb)).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?Rp(n):X_;l=l.mul(rb),s.isPerspectiveCamera&&!0===o&&(l=l.mul(XS.div(Yb.z.negate()))),r&&r.isNode&&(l=l.mul(Rp(r)));let h=$b.xy;if(i&&i.isNode){const e=Ap(i);h=GS(h,e)}return h=h.mul(l),h=h.div(hb.div(2)),h=h.mul(a.w),a=a.add(zp(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 XS=Im(1).onFrameUpdate(function({renderer:e}){const t=e.getSize(HS);this.value=.5*t.y});class YS extends Nv{constructor(){super(),this.shadowNode=Ap(1).toVar("shadowMask")}direct({lightNode:e}){null!==e.shadowNode&&this.shadowNode.mulAssign(e.shadowNode)}finish({context:e}){Zp.a.mulAssign(this.shadowNode.oneMinus()),e.outgoingLight.rgb.assign(Zp.rgb)}}const ZS=new yc;class QS extends lv{static get type(){return"ShadowNodeMaterial"}constructor(e){super(),this.isShadowNodeMaterial=!0,this.lights=!0,this.transparent=!0,this.setDefaultValues(ZS),this.setValues(e)}setupLightingModel(){return new YS}}Xp("vec3"),Xp("vec3"),Xp("vec3");class KS{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 JS{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 eM=0;class tM{constructor(e,t,s,i,r,n,o,a,l,h){this.id=eM++,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+",",Qc(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=Jc(e,this.camera.cameras.length)),this.object.receiveShadow&&(e=Jc(e,1)),e=Jc(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 sM=[];class iM{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);sM[0]=e,sM[1]=t,sM[2]=n,sM[3]=r;let h=l.get(sM);return void 0===h?(h=this.createRenderObject(this.nodes,this.geometries,this.renderer,e,t,s,i,r,n,o,a),l.set(sM,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)),sM.length=0,h}getChainMap(e="default"){return this.chainMaps[e]||(this.chainMaps[e]=new JS)}dispose(){this.chainMaps={}}createRenderObject(e,t,s,i,r,n,o,a,l,h,u){const c=this.getChainMap(u),d=new tM(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 rM{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 nM=1,oM=2,aM=3,lM=4,hM=16;class uM extends rM{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===nM?this.backend.createAttribute(e):t===oM?this.backend.createIndexAttribute(e):t===aM?this.backend.createStorageAttribute(e):t===lM&&this.backend.createIndirectStorageAttribute(e),s.version=this._getBufferAttribute(e).version;else{const t=this._getBufferAttribute(e);(s.version<t.version||t.usage===Pa)&&(this.backend.updateAttribute(e),s.version=t.version)}}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}function cM(e){return null!==e.index?e.index.version:e.attributes.position.version}function dM(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(Fa(t)?ou:nu)(t,1);return r.version=cM(e),r}class pM extends rM{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,aM):this.updateAttribute(e,nM);const s=this.getIndex(e);null!==s&&this.updateAttribute(s,oM);const i=e.geometry.indirect;null!==i&&this.updateAttribute(i,lM)}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=dM(t),e.set(t,s)):s.version!==cM(t)&&(this.attributes.delete(s),s=dM(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 mM{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):Ga("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 fM{constructor(e){this.cacheKey=e,this.usedTimes=0}}class gM extends fM{constructor(e,t,s){super(e),this.vertexProgram=t,this.fragmentProgram=s}}class yM extends fM{constructor(e,t){super(e),this.computeProgram=t,this.isComputePipeline=!0}}let bM=0;class xM{constructor(e,t,s,i=null,r=null){this.id=bM++,this.code=e,this.stage=t,this.name=s,this.transforms=i,this.attributes=r,this.usedTimes=0}}class _M extends rM{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 xM(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 xM(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 xM(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 yM(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 gM(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 wM extends rM{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?lM:aM;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?lM:aM;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 vM(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 TM(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 SM(e){return(e.transmission>0||e.transmissionNode&&e.transmissionNode.isNode)&&2===e.side&&!1===e.forceSinglePass}class MM{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?(SM(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?(SM(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||vM),this.transparentDoublePass.length>1&&this.transparentDoublePass.sort(t||TM),this.transparent.length>1&&this.transparent.sort(t||TM)}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 AM=[];class NM{constructor(e){this.lighting=e,this.lists=new JS}get(e,t){const s=this.lists;AM[0]=e,AM[1]=t;let i=s.get(AM);return void 0===i&&(i=new MM(this.lighting,e,t),s.set(AM,i)),AM.length=0,i}dispose(){this.lists=new JS}}let EM=0;class CM{constructor(){this.id=EM++,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 Tl,this.scissor=!1,this.scissorValue=new Tl,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 RM(this)}}function RM(e){const{textures:t,activeCubeFace:s,activeMipmapLevel:i}=e,r=[s,i];for(const e of t)r.push(e.id);return Kc(r)}const PM=[],BM=new Wu,IM=new Iu;class DM{constructor(){this.chainMaps={}}get(e,t,s=null,i=null){let r;if(PM[0]=e,PM[1]=t,null!==i&&(PM[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(PM);return void 0===o&&(o=new CM,n.set(PM,o)),PM.length=0,null!==s&&(o.sampleCount=0===s.samples?1:s.samples),o}getForClear(e=null){return this.get(BM,IM,e)}_getChainMap(e){return this.chainMaps[e]||(this.chainMaps[e]=new JS)}dispose(){this.chainMaps={}}}const LM=new rl;class FM extends rM{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 dc,h.format=e.stencilBuffer?Ro:Co,h.type=e.stencilBuffer?So:xo,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:mo}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)Ua("Renderer: Texture marked for update but image is undefined.");else if(!1===i.complete)Ua("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===dl.enabled&&dl.getTransfer(e.colorSpace)!==_a&&Ua("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=LM){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 OM extends Hh{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 zM extends qp{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):(Ga(`TSL: Member "${t}" not found in struct "${s}".`),r="float"),r}getHash(){return this.uuid}generate(){return this.name}}class VM extends wd{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?(Ga("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 up(t);return this._currentCond=Bg(e,s),this.addToStack(this._currentCond)}ElseIf(e,t){const s=new up(t),i=Bg(e,s);return this._currentCond.elseNode=i,this._currentCond=i,this}Else(e){return this._currentCond.elseNode=new up(e),this}Switch(e){return this._expressionNode=cp(e),this}Case(...e){const t=[];if(e.length>=2)for(let s=0;s<e.length-1;s++)t.push(this._expressionNode.equal(cp(e[s])));else Ga("TSL: Invalid parameter length. Case() requires at least two parameters.");const s=new up(e[e.length-1]);let i=t[0];for(let e=1;e<t.length;e++)i=i.or(t[e]);const r=Bg(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=vp(),i=e.buildStage;wp(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),wp(s),e.removeActiveStack(this),a}}const kM=fp(VM).setParameterLength(0,1);class UM extends wd{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=nd(r),o=od(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 GM extends wd{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 jM extends wd{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 $M=fp(jM);function WM(e,t){for(let s=0;s<e.length;s++)if(e[s].name===t)return s;return-1}class HM extends jM{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 qM(t)}setup(e){const t=this.outputNodes,s=[],i=e.renderer.getRenderTarget().textures;for(const e in t){s[WM(i,e)]=zp(t[e])}return this.members=s,super.setup(e)}}const qM=fp(HM);class XM extends Sd{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 YM=yp(XM).setParameterLength(2),ZM=e=>new XM(e,"uint","float"),QM={};class KM extends ff{static get type(){return"BitcountNode"}constructor(e,t){super(e,t),this.isBitcountNode=!0}_resolveElementType(e,t,s){"int"===s?t.assign(YM(e,"uint")):t.assign(e)}_returnDataNode(e){switch(e){case"uint":return Ep;case"int":return Np;case"uvec2":return Bp;case"uvec3":return Fp;case"uvec4":return kp;case"ivec2":return Pp;case"ivec3":return Lp;case"ivec4":return Vp}}_createTrailingZerosBaseLayout(e,t){const s=this._returnDataNode(t);return _p(([e])=>{const i=Ep(0);this._resolveElementType(e,i,t);const r=Ap(i.bitAnd(Wf(i))),n=ZM(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 _p(([e])=>{Tp(e.equal(Ep(0)),()=>Ep(32));const i=Ep(0),r=Ep(0);return this._resolveElementType(e,i,t),Tp(i.shiftRight(16).equal(0),()=>{r.addAssign(16),i.shiftLeftAssign(16)}),Tp(i.shiftRight(24).equal(0),()=>{r.addAssign(8),i.shiftLeftAssign(8)}),Tp(i.shiftRight(28).equal(0),()=>{r.addAssign(4),i.shiftLeftAssign(4)}),Tp(i.shiftRight(30).equal(0),()=>{r.addAssign(2),i.shiftLeftAssign(2)}),Tp(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 _p(([e])=>{const i=Ep(0);this._resolveElementType(e,i,t),i.assign(i.sub(i.shiftRight(Ep(1)).bitAnd(Ep(1431655765)))),i.assign(i.bitAnd(Ep(858993459)).add(i.shiftRight(Ep(2)).bitAnd(Ep(858993459))));const r=i.add(i.shiftRight(Ep(4))).bitAnd(Ep(252645135)).mul(Ep(16843009)).shiftRight(Ep(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 _p(([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=QM[a];if(void 0===h){switch(t){case KM.COUNT_LEADING_ZEROS:h=this._createLeadingZerosBaseLayout(a,n);break;case KM.COUNT_TRAILING_ZEROS:h=this._createTrailingZerosBaseLayout(a,n);break;case KM.COUNT_ONE_BITS:h=this._createOneBitsBaseLayout(a,n)}QM[a]=h}let u=QM[l];void 0===u&&(u=this._createMainLayout(l,r,o,h),QM[l]=u);return _p(()=>u(s))()}}KM.COUNT_TRAILING_ZEROS="countTrailingZeros",KM.COUNT_LEADING_ZEROS="countLeadingZeros",KM.COUNT_ONE_BITS="countOneBits";const JM=yp(KM,KM.COUNT_TRAILING_ZEROS).setParameterLength(1),eA=yp(KM,KM.COUNT_LEADING_ZEROS).setParameterLength(1),tA=yp(KM,KM.COUNT_ONE_BITS).setParameterLength(1),sA=_p(([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)}),iA=(e,t)=>cg($m(4,e.mul(jm(1,e))),t);class rA extends Sd{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 nA=yp(rA,"snorm").setParameterLength(1),oA=yp(rA,"unorm").setParameterLength(1),aA=yp(rA,"float16").setParameterLength(1);class lA extends Sd{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 hA=yp(lA,"snorm").setParameterLength(1),uA=yp(lA,"unorm").setParameterLength(1),cA=yp(lA,"float16").setParameterLength(1),dA=_p(([e])=>e.fract().sub(.5).abs()).setLayout({name:"tri",type:"float",inputs:[{name:"x",type:"float"}]}),pA=_p(([e])=>Dp(dA(e.z.add(dA(e.y.mul(1)))),dA(e.z.add(dA(e.x.mul(1)))),dA(e.y.add(dA(e.x.mul(1)))))).setLayout({name:"tri3",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),mA=_p(([e,t,s])=>{const i=Dp(e).toVar(),r=Ap(1.4).toVar(),n=Ap(0).toVar(),o=Dp(i).toVar();return ww({start:Ap(0),end:Ap(3),type:"float",condition:"<="},()=>{const e=Dp(pA(o.mul(2))).toVar();i.addAssign(e.add(s.mul(Ap(.1).mul(t)))),o.mulAssign(1.8),r.mulAssign(1.5),i.mulAssign(1.2);const a=Ap(dA(i.z.add(dA(i.x.add(dA(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 fA extends wd{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 gA=fp(fA),yA=e=>(...t)=>gA(e,...t),bA=Im(0).setGroup(Rm).onRenderUpdate(e=>e.time),xA=Im(0).setGroup(Rm).onRenderUpdate(e=>e.deltaTime),_A=Im(0,"uint").setGroup(Rm).onRenderUpdate(e=>e.frameId);const wA=_p(([e,t,s=Rp(.5)])=>GS(e.sub(s),t).add(s)),vA=_p(([e,t,s=Rp(.5)])=>{const i=e.sub(s),r=i.dot(i),n=r.mul(r).mul(t);return e.add(i.mul(n))}),TA=_p(({position:e=null,horizontal:t=!0,vertical:s=!1})=>{let i;null!==e?(i=Ib.toVar(),i[3][0]=e.x,i[3][1]=e.y,i[3][2]=e.z):i=Ib;const r=bb.mul(i);return lp(t)&&(r[0][0]=Ib[0].length(),r[0][1]=0,r[0][2]=0),lp(s)&&(r[1][0]=0,r[1][1]=Ib[1].length(),r[1][2]=0),r[2][0]=0,r[2][1]=0,r[2][2]=1,gb.mul(r).mul(Wb)}),SA=_p(([e=null])=>{const t=qw();return qw(Vw(e)).sub(t).lessThan(0).select(nb,e)});class MA extends wd{static get type(){return"SpriteSheetUVNode"}constructor(e,t=Vy(),s=Ap(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=Rp(o,a);return t.add(h).mul(l)}}const AA=fp(MA).setParameterLength(3),NA=_p(([e,t=null,s=null,i=Ap(1),r=Wb,n=sx])=>{let o=n.abs().normalize();o=o.div(o.dot(Dp(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=qy(u,a).mul(o.x),m=qy(c,l).mul(o.y),f=qy(d,h).mul(o.z);return Gm(p,m,f)}),EA=new tc,CA=new rl,RA=new rl,PA=new rl,BA=new eh,IA=new rl(0,0,-1),DA=new Tl,LA=new rl,FA=new rl,OA=new Tl,zA=new sl,VA=new Sl,kA=nb.flipX();VA.depthTexture=new dc(1,1);let UA=!1;class GA extends Wy{static get type(){return"ReflectorNode"}constructor(e={}){super(e.defaultTexture||VA.texture,kA),this._reflectorBaseNode=e.reflector||new jA(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=cp(new GA({defaultTexture:VA.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 jA extends wd{static get type(){return"ReflectorBaseNode"}constructor(e,t={}){super();const{target:s=new Nh,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&&(ja('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?pd.RENDER:pd.FRAME,this.virtualCameras=new WeakMap,this.renderTargets=new Map,this.forceUpdate=!1,this.hasOutput=!1}_updateResolution(e,t){const s=this.resolutionScale;t.getDrawingBufferSize(zA),e.setSize(Math.round(zA.width*s),Math.round(zA.height*s))}setup(e){return this._updateResolution(VA,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 Sl(0,0,{type:wo,samples:this.samples}),!0===this.generateMipmaps&&(t.texture.minFilter=1008,t.texture.generateMipmaps=!0),!0===this.depth&&(t.depthTexture=new dc),this.renderTargets.set(e,t)),t}updateBefore(e){if(!1===this.bounces&&UA)return!1;UA=!0;const{scene:t,camera:s,renderer:i,material:r}=e,{target:n}=this,o=this.getVirtualCamera(s),a=this.getRenderTarget(o);i.getDrawingBufferSize(zA),this._updateResolution(a,i),RA.setFromMatrixPosition(n.matrixWorld),PA.setFromMatrixPosition(s.matrixWorld),BA.extractRotation(n.matrixWorld),CA.set(0,0,1),CA.applyMatrix4(BA),LA.subVectors(RA,PA);let l=!1;if(!0===LA.dot(CA)>0&&!1===this.forceUpdate){if(!1===this.hasOutput)return void(UA=!1);l=!0}LA.reflect(CA).negate(),LA.add(RA),BA.extractRotation(s.matrixWorld),IA.set(0,0,-1),IA.applyMatrix4(BA),IA.add(PA),FA.subVectors(RA,IA),FA.reflect(CA).negate(),FA.add(RA),o.coordinateSystem=s.coordinateSystem,o.position.copy(LA),o.up.set(0,1,0),o.up.applyMatrix4(BA),o.up.reflect(CA),o.lookAt(FA),o.near=s.near,o.far=s.far,o.updateMatrixWorld(),o.projectionMatrix.copy(s.projectionMatrix),EA.setFromNormalAndCoplanarPoint(CA,RA),EA.applyMatrix4(o.matrixWorldInverse),DA.set(EA.normal.x,EA.normal.y,EA.normal.z,EA.constant);const h=o.projectionMatrix;OA.x=(Math.sign(DA.x)+h.elements[8])/h.elements[0],OA.y=(Math.sign(DA.y)+h.elements[9])/h.elements[5],OA.z=-1,OA.w=(1+h.elements[10])/h.elements[14],DA.multiplyScalar(1/DA.dot(OA));h.elements[2]=DA.x,h.elements[6]=DA.y,h.elements[10]=i.coordinateSystem===Ia?DA.z-0:DA.z+1-0,h.elements[14]=DA.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,UA=!1,this.forceUpdate=!1}get resolution(){return ja('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale}set resolution(e){ja('ReflectorNode: The "resolution" property has been renamed to "resolutionScale".'),this.resolutionScale=e}}const $A=new Fc(-1,1,1,-1,0,1);class WA extends gu{constructor(e=!1){super();const t=!1===e?[0,-1,0,1,2,1]:[0,2,0,0,2,0];this.setAttribute("position",new lu([-1,3,0,-1,-1,0,3,-1,0],3)),this.setAttribute("uv",new lu(t,2))}}const HA=new WA;class qA extends Eu{constructor(e=null){super(HA,e),this.camera=$A,this.isQuadMesh=!0}async renderAsync(e){ja('QuadMesh: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await e.init(),e.render(this,$A)}render(e){e.render(this,$A)}}const XA=new sl;class YA extends Wy{static get type(){return"RTTNode"}constructor(e,t=null,s=null,i={type:wo}){const r=new Sl(t,s,i);super(r.texture,Vy()),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 qA(new lv),this.updateBeforeType=pd.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(XA),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 Wy(this.value,this.uvNode,this.levelNode);return e.sampler=this.sampler,e.referenceNode=this,e}}const ZA=(e,...t)=>cp(new YA(cp(e),...t)),QA=_p(([e,t,s],i)=>{let r;i.renderer.coordinateSystem===Ia?(e=Rp(e.x,e.y.oneMinus()).mul(2).sub(1),r=zp(Dp(e,t),1)):r=zp(Dp(e.x,e.y.oneMinus(),t).mul(2).sub(1),1);const n=zp(s.mul(r));return n.xyz.div(n.w)}),KA=_p(([e,t])=>{const s=t.mul(zp(e,1)),i=s.xy.div(s.w).mul(.5).add(.5).toVar();return Rp(i.x,i.y.oneMinus())}),JA=_p(([e,t,s])=>{const i=Uy(Xy(t)),r=Pp(e.mul(i)).toVar(),n=Xy(t,r).toVar(),o=Xy(t,r.sub(Pp(2,0))).toVar(),a=Xy(t,r.sub(Pp(1,0))).toVar(),l=Xy(t,r.add(Pp(1,0))).toVar(),h=Xy(t,r.add(Pp(2,0))).toVar(),u=Xy(t,r.add(Pp(0,2))).toVar(),c=Xy(t,r.add(Pp(0,1))).toVar(),d=Xy(t,r.sub(Pp(0,1))).toVar(),p=Xy(t,r.sub(Pp(0,2))).toVar(),m=Gf(jm(Ap(2).mul(a).sub(o),n)).toVar(),f=Gf(jm(Ap(2).mul(l).sub(h),n)).toVar(),g=Gf(jm(Ap(2).mul(c).sub(u),n)).toVar(),y=Gf(jm(Ap(2).mul(d).sub(p),n)).toVar(),b=QA(e,n,s).toVar(),x=m.lessThan(f).select(b.sub(QA(e.sub(Rp(Ap(1).div(i.x),0)),a,s)),b.negate().add(QA(e.add(Rp(Ap(1).div(i.x),0)),l,s))),_=g.lessThan(y).select(b.sub(QA(e.add(Rp(0,Ap(1).div(i.y))),c,s)),b.negate().add(QA(e.sub(Rp(0,Ap(1).div(i.y))),d,s)));return Df(ug(x,_))}),eN=_p(([e])=>Lf(Ap(52.9829189).mul(Lf(hg(e,Rp(.06711056,.00583715)))))).setLayout({name:"interleavedGradientNoise",type:"float",inputs:[{name:"position",type:"vec2"}]}),tN=_p(([e,t,s])=>{const i=Ap(2.399963229728653),r=Rf(Ap(e).add(.5).div(Ap(t))),n=Ap(e).mul(i).add(s);return Rp(Of(n),Ff(n)).mul(r)}).setLayout({name:"vogelDiskSample",type:"vec2",inputs:[{name:"sampleIndex",type:"int"},{name:"samplesCount",type:"int"},{name:"phi",type:"float"}]});class sN extends wd{static get type(){return"SampleNode"}constructor(e,t=null){super(),this.callback=e,this.uvNode=t,this.isSampleNode=!0}setup(){return this.sample(Vy())}sample(e){return this.callback(e)}}class iN extends wd{static get type(){return"EventNode"}constructor(e,t){super("void"),this.eventType=e,this.callback=t,e===iN.OBJECT?this.updateType=pd.OBJECT:e===iN.MATERIAL?this.updateType=pd.RENDER:e===iN.BEFORE_OBJECT?this.updateBeforeType=pd.OBJECT:e===iN.BEFORE_MATERIAL&&(this.updateBeforeType=pd.RENDER)}update(e){this.callback(e)}updateBefore(e){this.callback(e)}}iN.OBJECT="object",iN.MATERIAL="material",iN.BEFORE_OBJECT="beforeObject",iN.BEFORE_MATERIAL="beforeMaterial";const rN=(e,t)=>new iN(e,t).toStack();class nN extends Qu{constructor(e,t,s=Float32Array){super(ArrayBuffer.isView(e)?e:new s(e*t),t),this.isStorageInstancedBufferAttribute=!0}}class oN extends ru{constructor(e,t,s=Float32Array){super(ArrayBuffer.isView(e)?e:new s(e*t),t),this.isStorageBufferAttribute=!0}}class aN extends wd{static get type(){return"PointUVNode"}constructor(){super("vec2"),this.isPointUVNode=!0}generate(){return"vec2( gl_PointCoord.x, 1.0 - gl_PointCoord.y )"}}const lN=gp(aN),hN=new uh,uN=new eh;class cN extends wd{static get type(){return"SceneNode"}constructor(e=cN.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===cN.BACKGROUND_BLURRINESS?i=Cx("backgroundBlurriness","float",s):t===cN.BACKGROUND_INTENSITY?i=Cx("backgroundIntensity","float",s):t===cN.BACKGROUND_ROTATION?i=Im("mat4").setName("backgroundRotation").setGroup(Rm).onRenderUpdate(()=>{const e=s.background;return null!==e&&e.isTexture&&300!==e.mapping?(hN.copy(s.backgroundRotation),hN.x*=-1,hN.y*=-1,hN.z*=-1,uN.makeRotationFromEuler(hN)):uN.identity(),uN}):Ga("SceneNode: Unknown scope:",t),i}}cN.BACKGROUND_BLURRINESS="backgroundBlurriness",cN.BACKGROUND_INTENSITY="backgroundIntensity",cN.BACKGROUND_ROTATION="backgroundRotation";const dN=gp(cN,cN.BACKGROUND_BLURRINESS),pN=gp(cN,cN.BACKGROUND_INTENSITY),mN=gp(cN,cN.BACKGROUND_ROTATION);class fN extends Wy{static get type(){return"StorageTextureNode"}constructor(e,t,s=null){super(e,t),this.storeNode=s,this.mipLevel=0,this.isStorageTextureNode=!0,this.access=md.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(md.READ_WRITE)}toReadOnly(){return this.setAccess(md.READ_ONLY)}toWriteOnly(){return this.setAccess(md.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 gN=fp(fN).setParameterLength(1,3),yN=_p(({texture:e,uv:t})=>{const s=1e-4,i=Dp().toVar();return Tp(t.x.lessThan(s),()=>{i.assign(Dp(1,0,0))}).ElseIf(t.y.lessThan(s),()=>{i.assign(Dp(0,1,0))}).ElseIf(t.z.lessThan(s),()=>{i.assign(Dp(0,0,1))}).ElseIf(t.x.greaterThan(.9999),()=>{i.assign(Dp(-1,0,0))}).ElseIf(t.y.greaterThan(.9999),()=>{i.assign(Dp(0,-1,0))}).ElseIf(t.z.greaterThan(.9999),()=>{i.assign(Dp(0,0,-1))}).Else(()=>{const s=.01,r=e.sample(t.add(Dp(-.01,0,0))).r.sub(e.sample(t.add(Dp(s,0,0))).r),n=e.sample(t.add(Dp(0,-.01,0))).r.sub(e.sample(t.add(Dp(0,s,0))).r),o=e.sample(t.add(Dp(0,0,-.01))).r.sub(e.sample(t.add(Dp(0,0,s))).r);i.assign(Dp(r,n,o))}),i.normalize()});class bN extends Wy{static get type(){return"Texture3DNode"}constructor(e,t=null,s=null){super(e,t,s),this.isTexture3DNode=!0}getInputType(){return"texture3D"}getDefaultUV(){return Dp(.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(Np(Uy(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 yN({texture:this,uv:e})}}const xN=fp(bN).setParameterLength(1,3);class _N extends Ex{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 wN=new WeakMap;class vN extends Sd{static get type(){return"VelocityNode"}constructor(){super("vec2"),this.projectionMatrix=null,this.updateType=pd.OBJECT,this.updateAfterType=pd.OBJECT,this.previousModelWorldMatrix=Im(new eh),this.previousProjectionMatrix=Im(new eh).setGroup(Rm),this.previousCameraViewMatrix=Im(new eh)}setProjectionMatrix(e){this.projectionMatrix=e}update({frameId:e,camera:t,object:s}){const i=SN(s);this.previousModelWorldMatrix.value.copy(i);const r=TN(t);r.frameId!==e&&(r.frameId=e,void 0===r.previousProjectionMatrix?(r.previousProjectionMatrix=new eh,r.previousCameraViewMatrix=new eh,r.currentProjectionMatrix=new eh,r.currentCameraViewMatrix=new eh,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}){SN(e).copy(e.matrixWorld)}setup(){const e=null===this.projectionMatrix?gb:Im(this.projectionMatrix),t=this.previousCameraViewMatrix.mul(this.previousModelWorldMatrix),s=e.mul(kb).mul(Wb),i=this.previousProjectionMatrix.mul(t).mul(Hb),r=s.xy.div(s.w),n=i.xy.div(i.w);return jm(r,n)}}function TN(e){let t=wN.get(e);return void 0===t&&(t={},wN.set(e,t)),t}function SN(e,t=0){const s=TN(e);let i=s[t];return void 0===i&&(s[t]=i=new eh,s[t].copy(e.matrixWorld)),i}const MN=gp(vN),AN=_p(([e])=>RN(e.rgb)),NN=_p(([e,t=Ap(1)])=>t.mix(RN(e.rgb),e.rgb)),EN=_p(([e,t=Ap(1)])=>{const s=Gm(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 bg(e.rgb,i,r)}),CN=_p(([e,t=Ap(1)])=>{const s=Dp(.57735,.57735,.57735),i=t.cos();return Dp(e.rgb.mul(i).add(s.cross(e.rgb).mul(t.sin()).add(s.mul(hg(s,e.rgb).mul(i.oneMinus())))))}),RN=(e,t=Dp(dl.getLuminanceCoefficients(new rl)))=>hg(e,t),PN=_p(([e,t=Dp(1),s=Dp(0),i=Dp(1),r=Ap(1),n=Dp(dl.getLuminanceCoefficients(new rl,ba))])=>{const o=e.rgb.dot(Dp(n)),a=rg(e.rgb.mul(t).add(s),0).toVar(),l=a.pow(i).toVar();return Tp(a.r.greaterThan(0),()=>{a.r.assign(l.r)}),Tp(a.g.greaterThan(0),()=>{a.g.assign(l.g)}),Tp(a.b.greaterThan(0),()=>{a.b.assign(l.b)}),a.assign(o.add(a.sub(o).mul(r))),zp(a.rgb,e.a)});class BN extends Sd{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 IN=fp(BN).setParameterLength(2),DN=new sl;class LN extends Wy{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 FN extends LN{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 ON extends Sd{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 dc;r.isRenderTargetTexture=!0,r.name="depth";const n=new Sl(this._width*this._pixelRatio,this._height*this._pixelRatio,{type:wo,...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=Im(0),this._cameraFar=Im(0),this._mrt=null,this._layers=null,this._resolutionScale=1,this._viewport=null,this._scissor=null,this.isPassNode=!0,this.updateBeforeType=pd.FRAME,this.global=!0}setResolutionScale(e){return this._resolutionScale=e,this}getResolutionScale(){return this._resolutionScale}setResolution(e){return Ua("PassNode: .setResolution() is deprecated. Use .setResolutionScale() instead."),this.setResolutionScale(e)}getResolution(){return Ua("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 FN(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 FN(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=jw(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=Uw(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===ON.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),DN.set(n.width,n.height)):(i=this.camera,r=t.getPixelRatio(),t.getSize(DN)),this._pixelRatio=r,this.setSize(DN.width,DN.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:Dg({...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 Tl),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 Tl),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()}}ON.COLOR="color",ON.DEPTH="depth";class zN extends ON{static get type(){return"ToonOutlinePassNode"}constructor(e,t,s,i,r){super(ON.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 lv;e.isMeshToonOutlineMaterial=!0,e.name="Toon_Outline",e.side=1;const t=sx.negate(),s=gb.mul(kb),i=Ap(1),r=s.mul(zp(Wb,1)),n=s.mul(zp(Wb.add(t),1)),o=Df(r.sub(n));return e.vertexNode=r.add(o.mul(this.thicknessNode).mul(r.w).mul(i)),e.colorNode=zp(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 VN=_p(([e,t])=>e.mul(t).clamp()).setLayout({name:"linearToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),kN=_p(([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"}]}),UN=_p(([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"}]}),GN=_p(([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)}),jN=_p(([e,t])=>{const s=jp(.59719,.35458,.04823,.076,.90834,.01566,.0284,.13383,.83777),i=jp(1.60475,-.53108,-.07367,-.10208,1.10813,-.00605,-.00327,-.07276,1.07602);return e=e.mul(t).div(.6),e=s.mul(e),e=GN(e),(e=i.mul(e)).clamp()}).setLayout({name:"acesFilmicToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),$N=jp(Dp(1.6605,-.1246,-.0182),Dp(-.5876,1.1329,-.1006),Dp(-.0728,-.0083,1.1187)),WN=jp(Dp(.6274,.0691,.0164),Dp(.3293,.9195,.088),Dp(.0433,.0113,.8956)),HN=_p(([e])=>{const t=Dp(e).toVar(),s=Dp(t.mul(t)).toVar(),i=Dp(s.mul(s)).toVar();return Ap(15.5).mul(i.mul(s)).sub($m(40.14,i.mul(t))).add($m(31.96,i).sub($m(6.868,s.mul(t))).add($m(.4298,s).add($m(.1191,t).sub(.00232))))}),qN=_p(([e,t])=>{const s=Dp(e).toVar(),i=jp(Dp(.856627153315983,.137318972929847,.11189821299995),Dp(.0951212405381588,.761241990602591,.0767994186031903),Dp(.0482516061458583,.101439036467562,.811302368396859)),r=jp(Dp(1.1271005818144368,-.1413297634984383,-.14132976349843826),Dp(-.11060664309660323,1.157823702216272,-.11060664309660294),Dp(-.016493938717834573,-.016493938717834257,1.2519364065950405)),n=Ap(-12.47393),o=Ap(4.026069);return s.mulAssign(t),s.assign(WN.mul(s)),s.assign(i.mul(s)),s.assign(rg(s,1e-10)),s.assign(Cf(s)),s.assign(s.sub(n).div(o.sub(n))),s.assign(xg(s,0,1)),s.assign(HN(s)),s.assign(r.mul(s)),s.assign(cg(rg(Dp(0),s),Dp(2.2))),s.assign($N.mul(s)),s.assign(xg(s,0,1)),s}).setLayout({name:"agxToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]}),XN=_p(([e,t])=>{const s=Ap(.76),i=Ap(.15);e=e.mul(t);const r=ig(e.r,ig(e.g,e.b)),n=Bg(r.lessThan(.08),r.sub($m(6.25,r.mul(r))),.04);e.subAssign(n);const o=rg(e.r,rg(e.g,e.b));Tp(o.lessThan(s),()=>e);const a=jm(1,s),l=jm(1,a.mul(a).div(o.add(a.sub(s))));e.mulAssign(l.div(o));const h=jm(1,Wm(1,i.mul(o.sub(l)).add(1)));return bg(e,Dp(l),h)}).setLayout({name:"neutralToneMapping",type:"vec3",inputs:[{name:"color",type:"vec3"},{name:"exposure",type:"float"}]});class YN extends wd{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 ZN=fp(YN).setParameterLength(1,3);class QN extends YN{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 KN=(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 QN(e,t,s),r=(...e)=>i.call(...e);return r.functionNode=i,r};class JN extends wd{static get type(){return"ScriptableValueNode"}constructor(e=null){super(),this._value=e,this._cache=null,this.inputType=null,this.outputType=null,this.events=new $a,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:Ap()}serialize(e){super.serialize(e),null!==this.value?"ArrayBuffer"===this.inputType?e.value=ud(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?cd(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 eE=fp(JN).setParameterLength(1);class tE 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 sE{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 iE=new tE;class rE extends wd{static get type(){return"ScriptableNode"}constructor(e=null,t={}){super(),this.codeNode=e,this.parameters=t,this._local=new tE,this._output=eE(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]=eE(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]=eE(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 sE(this),t=iE.get("THREE"),s=iE.get("TSL"),i=this.getMethod(),r=[e,this._local,iE,()=>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:Ap()}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=[Qc(this.source),this.getDefaultOutputNode().getCacheKey(e)];for(const s in this.parameters)t.push(this.parameters[s].getCacheKey(e));return Kc(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 nE=fp(rE).setParameterLength(1,2);function oE(e){let t;const s=e.context.getViewZ;return void 0!==s&&(t=s(this)),(t||Yb.z).negate()}const aE=_p(([e,t],s)=>{const i=oE(s);return vg(e,t,i)}),lE=_p(([e],t)=>{const s=oE(t);return e.mul(e,s,s).negate().exp().oneMinus()}),hE=_p(([e,t])=>zp(t.toFloat().mix(gm.rgb,e.toVec3()),gm.a));let uE=null,cE=null;class dE extends wd{static get type(){return"RangeNode"}constructor(e=Ap(),t=Ap()){super(),this.minNode=e,this.maxNode=t}getVectorLength(e){const t=this.getConstNode(this.minNode),s=this.getConstNode(this.maxNode),i=e.getTypeLength(ad(t.value)),r=e.getTypeLength(ad(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(ad(n)),l=e.getTypeLength(ad(o));uE=uE||new Tl,cE=cE||new Tl,uE.setScalar(0),cE.setScalar(0),1===a?uE.setScalar(n):n.isColor?uE.set(n.r,n.g,n.b,1):uE.set(n.x,n.y,n.z||0,n.w||0),1===l?cE.setScalar(o):o.isColor?cE.set(o.r,o.g,o.b,1):cE.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=uE.getComponent(t),i=cE.getComponent(t);c[e]=tl.lerp(s,i,Math.random())}const d=this.getNodeType(e);if(t.count<=4096)s=Zy(c,"vec4",t.count).element(ow).convert(d);else{const t=new Qu(c,4);e.geometry.setAttribute("__range"+this.id,t),s=my(t).convert(d)}}else s=Ap(0);return s}}const pE=fp(dE).setParameterLength(2);class mE extends wd{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):(Ua(`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 fE=(e,t)=>new mE(e,t),gE=fE("numWorkgroups","uvec3"),yE=fE("workgroupId","uvec3"),bE=fE("globalId","uvec3"),xE=fE("localId","uvec3"),_E=fE("subgroupSize","uint");const wE=fp(class extends wd{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 vE extends vd{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 TE extends wd{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 Ua('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 vE(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 SE extends wd{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=Ey(h,r).toConst()),t.constNode.build(e);e.addLineFlowCode(h,this)}}SE.ATOMIC_LOAD="atomicLoad",SE.ATOMIC_STORE="atomicStore",SE.ATOMIC_ADD="atomicAdd",SE.ATOMIC_SUB="atomicSub",SE.ATOMIC_MAX="atomicMax",SE.ATOMIC_MIN="atomicMin",SE.ATOMIC_AND="atomicAnd",SE.ATOMIC_OR="atomicOr",SE.ATOMIC_XOR="atomicXor";const ME=fp(SE),AE=(e,t,s)=>ME(e,t,s).toStack();class NE extends Sd{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===NE.SUBGROUP_ELECT?"bool":t===NE.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===NE.SUBGROUP_BROADCAST||s===NE.SUBGROUP_SHUFFLE||s===NE.QUAD_BROADCAST){const t=o.getNodeType(e);a.push(n.build(e,i),o.build(e,"float"===t?"int":i))}else s===NE.SUBGROUP_SHUFFLE_XOR||s===NE.SUBGROUP_SHUFFLE_DOWN||s===NE.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}}NE.SUBGROUP_ELECT="subgroupElect",NE.SUBGROUP_BALLOT="subgroupBallot",NE.SUBGROUP_ADD="subgroupAdd",NE.SUBGROUP_INCLUSIVE_ADD="subgroupInclusiveAdd",NE.SUBGROUP_EXCLUSIVE_AND="subgroupExclusiveAdd",NE.SUBGROUP_MUL="subgroupMul",NE.SUBGROUP_INCLUSIVE_MUL="subgroupInclusiveMul",NE.SUBGROUP_EXCLUSIVE_MUL="subgroupExclusiveMul",NE.SUBGROUP_AND="subgroupAnd",NE.SUBGROUP_OR="subgroupOr",NE.SUBGROUP_XOR="subgroupXor",NE.SUBGROUP_MIN="subgroupMin",NE.SUBGROUP_MAX="subgroupMax",NE.SUBGROUP_ALL="subgroupAll",NE.SUBGROUP_ANY="subgroupAny",NE.SUBGROUP_BROADCAST_FIRST="subgroupBroadcastFirst",NE.QUAD_SWAP_X="quadSwapX",NE.QUAD_SWAP_Y="quadSwapY",NE.QUAD_SWAP_DIAGONAL="quadSwapDiagonal",NE.SUBGROUP_BROADCAST="subgroupBroadcast",NE.SUBGROUP_SHUFFLE="subgroupShuffle",NE.SUBGROUP_SHUFFLE_XOR="subgroupShuffleXor",NE.SUBGROUP_SHUFFLE_UP="subgroupShuffleUp",NE.SUBGROUP_SHUFFLE_DOWN="subgroupShuffleDown",NE.QUAD_BROADCAST="quadBroadcast";const EE=yp(NE,NE.SUBGROUP_ELECT).setParameterLength(0),CE=yp(NE,NE.SUBGROUP_BALLOT).setParameterLength(1),RE=yp(NE,NE.SUBGROUP_ADD).setParameterLength(1),PE=yp(NE,NE.SUBGROUP_INCLUSIVE_ADD).setParameterLength(1),BE=yp(NE,NE.SUBGROUP_EXCLUSIVE_AND).setParameterLength(1),IE=yp(NE,NE.SUBGROUP_MUL).setParameterLength(1),DE=yp(NE,NE.SUBGROUP_INCLUSIVE_MUL).setParameterLength(1),LE=yp(NE,NE.SUBGROUP_EXCLUSIVE_MUL).setParameterLength(1),FE=yp(NE,NE.SUBGROUP_AND).setParameterLength(1),OE=yp(NE,NE.SUBGROUP_OR).setParameterLength(1),zE=yp(NE,NE.SUBGROUP_XOR).setParameterLength(1),VE=yp(NE,NE.SUBGROUP_MIN).setParameterLength(1),kE=yp(NE,NE.SUBGROUP_MAX).setParameterLength(1),UE=yp(NE,NE.SUBGROUP_ALL).setParameterLength(0),GE=yp(NE,NE.SUBGROUP_ANY).setParameterLength(0),jE=yp(NE,NE.SUBGROUP_BROADCAST_FIRST).setParameterLength(2),$E=yp(NE,NE.QUAD_SWAP_X).setParameterLength(1),WE=yp(NE,NE.QUAD_SWAP_Y).setParameterLength(1),HE=yp(NE,NE.QUAD_SWAP_DIAGONAL).setParameterLength(1),qE=yp(NE,NE.SUBGROUP_BROADCAST).setParameterLength(2),XE=yp(NE,NE.SUBGROUP_SHUFFLE).setParameterLength(2),YE=yp(NE,NE.SUBGROUP_SHUFFLE_XOR).setParameterLength(2),ZE=yp(NE,NE.SUBGROUP_SHUFFLE_UP).setParameterLength(2),QE=yp(NE,NE.SUBGROUP_SHUFFLE_DOWN).setParameterLength(2),KE=yp(NE,NE.QUAD_BROADCAST).setParameterLength(1);let JE;function eC(e){JE=JE||new WeakMap;let t=JE.get(e);return void 0===t&&JE.set(e,t={}),t}function tC(e){const t=eC(e);return t.shadowMatrix||(t.shadowMatrix=Im("mat4").setGroup(Rm).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 sC(e,t=qb){const s=tC(e).mul(t);return s.xyz.div(s.w)}function iC(e){const t=eC(e);return t.position||(t.position=Im(new rl).setGroup(Rm).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.matrixWorld)))}function rC(e){const t=eC(e);return t.targetPosition||(t.targetPosition=Im(new rl).setGroup(Rm).onRenderUpdate((t,s)=>s.value.setFromMatrixPosition(e.target.matrixWorld)))}function nC(e){const t=eC(e);return t.viewPosition||(t.viewPosition=Im(new rl).setGroup(Rm).onRenderUpdate(({camera:t},s)=>{s.value=s.value||new rl,s.value.setFromMatrixPosition(e.matrixWorld),s.value.applyMatrix4(t.matrixWorldInverse)}))}const oC=e=>bb.transformDirection(iC(e).sub(rC(e))),aC=(e,t)=>{for(const s of t)if(s.isAnalyticLightNode&&s.light.id===e)return s;return null},lC=new WeakMap,hC=[];class uC extends wd{static get type(){return"LightsNode"}constructor(){super("vec3"),this.totalDiffuseNode=Xp("vec3","totalDiffuse"),this.totalSpecularNode=Xp("vec3","totalSpecular"),this.outgoingLightNode=Xp("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(hC.push(s.id),hC.push(s.castShadow?1:0),!0===s.isSpotLight){const e=null!==s.map?s.map.id:-1,t=s.colorNode?s.colorNode.getCacheKey():-1;hC.push(e,t)}}const t=Kc(hC);return hC.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(cp(e));else{let i=null;if(null!==s&&(i=aC(e.id,s)),null===i){const s=r.getLightNodeClass(e.constructor);if(null===s){Ua(`LightsNode.setupNodeLights: Light node not found for ${e.constructor.name}`);continue}let i=null;lC.has(e)?i=lC.get(e):(i=new s(e),lC.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=Dp(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 cC extends wd{static get type(){return"ShadowBaseNode"}constructor(e){super(),this.light=e,this.updateBeforeType=pd.RENDER,this.isShadowBaseNode=!0}setupShadowPosition({context:e,material:t}){dC.assign(t.receivedShadowPositionNode||e.shadowPositionWorld||qb)}}const dC=Xp("vec3","shadowPositionWorld");function pC(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 Hh),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 mC=new WeakMap,fC=_p(({depthTexture:e,shadowCoord:t,depthLayer:s})=>{let i=qy(e,t.xy).setName("t_basic");return e.isArrayTexture&&(i=i.depth(s)),i.compare(t.z)}),gC=_p(({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=qy(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(s)},n=Cx("mapSize","vec2",s).setGroup(Rm),o=Cx("radius","float",s).setGroup(Rm),a=Rp(1).div(n),l=o.mul(a.x),h=eN(ab.xy).mul(6.28318530718);return Gm(r(t.xy.add(tN(0,5,h).mul(l)),t.z),r(t.xy.add(tN(1,5,h).mul(l)),t.z),r(t.xy.add(tN(2,5,h).mul(l)),t.z),r(t.xy.add(tN(3,5,h).mul(l)),t.z),r(t.xy.add(tN(4,5,h).mul(l)),t.z)).mul(.2)}),yC=_p(({depthTexture:e,shadowCoord:t,shadow:s,depthLayer:i})=>{const r=(t,s)=>{let r=qy(e,t);return e.isArrayTexture&&(r=r.depth(i)),r.compare(s)},n=Cx("mapSize","vec2",s).setGroup(Rm),o=Rp(1).div(n),a=o.x,l=o.y,h=t.xy,u=Lf(h.mul(n).add(.5));return h.subAssign(u.mul(o)),Gm(r(h,t.z),r(h.add(Rp(a,0)),t.z),r(h.add(Rp(0,l)),t.z),r(h.add(o),t.z),bg(r(h.add(Rp(a.negate(),0)),t.z),r(h.add(Rp(a.mul(2),0)),t.z),u.x),bg(r(h.add(Rp(a.negate(),l)),t.z),r(h.add(Rp(a.mul(2),l)),t.z),u.x),bg(r(h.add(Rp(0,l.negate())),t.z),r(h.add(Rp(0,l.mul(2))),t.z),u.y),bg(r(h.add(Rp(a,l.negate())),t.z),r(h.add(Rp(a,l.mul(2))),t.z),u.y),bg(bg(r(h.add(Rp(a.negate(),l.negate())),t.z),r(h.add(Rp(a.mul(2),l.negate())),t.z),u.x),bg(r(h.add(Rp(a.negate(),l.mul(2))),t.z),r(h.add(Rp(a.mul(2),l.mul(2))),t.z),u.x),u.y)).mul(1/9)}),bC=_p(({depthTexture:e,shadowCoord:t,depthLayer:s})=>{let i=qy(e).sample(t.xy);e.isArrayTexture&&(i=i.depth(s)),i=i.rg;const r=i.x,n=rg(1e-7,i.y.mul(i.y)),o=ng(t.z,r);Tp(o.equal(1),()=>Ap(1));const a=t.z.sub(r);let l=n.div(n.add(a.mul(a)));return l=xg(jm(l,.3).div(.65)),rg(o,l)}),xC=_p(([e,t,s])=>{let i=qb.sub(e).length();return i=i.sub(t).div(s.sub(t)),i=i.saturate(),i}),_C=e=>{let t=mC.get(e);if(void 0===t){const s=e.isPointLight?(e=>{const t=e.shadow.camera,s=Cx("near","float",t).setGroup(Rm),i=Cx("far","float",t).setGroup(Rm),r=Nb(e);return xC(r,s,i)})(e):null;t=new lv,t.colorNode=zp(0,0,0,1),t.depthNode=s,t.isShadowPassMaterial=!0,t.name="ShadowMaterial",t.fog=!1,mC.set(e,t)}return t},wC=e=>{const t=mC.get(e);void 0!==t&&(t.dispose(),mC.delete(e))},vC=new JS,TC=[],SC=(e,t,s,i)=>{TC[0]=e,TC[1]=t;let r=vC.get(TC);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&&(hd(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,vC.set(TC,r)),TC[0]=null,TC[1]=null,r},MC=_p(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=Ap(0).toVar("meanVertical"),o=Ap(0).toVar("squareMeanVertical"),a=e.lessThanEqual(Ap(1)).select(Ap(0),Ap(2).div(e.sub(1))),l=e.lessThanEqual(Ap(1)).select(Ap(0),Ap(-1));ww({start:Np(0),end:Np(e),type:"int",condition:"<"},({i:e})=>{const h=l.add(Ap(e).mul(a));let u=i.sample(Gm(ab.xy,Rp(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=Rf(o.sub(n.mul(n)).max(0));return Rp(n,h)}),AC=_p(({samples:e,radius:t,size:s,shadowPass:i,depthLayer:r})=>{const n=Ap(0).toVar("meanHorizontal"),o=Ap(0).toVar("squareMeanHorizontal"),a=e.lessThanEqual(Ap(1)).select(Ap(0),Ap(2).div(e.sub(1))),l=e.lessThanEqual(Ap(1)).select(Ap(0),Ap(-1));ww({start:Np(0),end:Np(e),type:"int",condition:"<"},({i:e})=>{const h=l.add(Ap(e).mul(a));let u=i.sample(Gm(ab.xy,Rp(h,0).mul(t)).div(s));i.value.isArrayTexture&&(u=u.depth(r)),n.addAssign(u.x),o.addAssign(Gm(u.y.mul(u.y),u.x.mul(u.x)))}),n.divAssign(e),o.divAssign(e);const h=Rf(o.sub(n.mul(n)).max(0));return Rp(n,h)}),NC=[fC,gC,yC,bC];let EC;const CC=new qA;class RC extends cC{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,Ap(1))}setupShadowCoord(e,t){const{shadow:s}=this,{renderer:i}=e,r=Cx("bias","float",s).setGroup(Rm);let n,o=t;if(s.camera.isOrthographicCamera||!0!==i.logarithmicDepthBuffer)o=o.xyz.div(o.w),n=o.z,i.coordinateSystem===Ia&&(n=n.mul(2).sub(1));else{const e=o.w;o=o.xy.div(e);const t=Cx("near","float",s.camera).setGroup(Rm),i=Cx("far","float",s.camera).setGroup(Rm);n=$w(e.negate(),t,i)}return o=Dp(o.x,o.y.oneMinus(),n.add(r)),o}getShadowFilterFn(e){return NC[e]}setupRenderTarget(e,t){const s=new dc(e.mapSize.width,e.mapSize.height);s.name="ShadowDepthTexture",s.compareFunction=Ta;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:Io,type:wo,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:Io,type:wo,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:Io,type:wo,depthBuffer:!1}),this.vsmShadowMapHorizontal=e.createRenderTarget(r.mapSize.width,r.mapSize.height,{format:Io,type:wo,depthBuffer:!1}));let t=qy(o);o.isArrayTexture&&(t=t.depth(this.depthLayer));let s=qy(this.vsmShadowMapVertical.texture);o.isArrayTexture&&(s=s.depth(this.depthLayer));const i=Cx("blurSamples","float",r).setGroup(Rm),n=Cx("radius","float",r).setGroup(Rm),l=Cx("mapSize","vec2",r).setGroup(Rm);let h=this.vsmMaterialVertical||(this.vsmMaterialVertical=new lv);h.fragmentNode=MC({samples:i,radius:n,size:l,shadowPass:t,depthLayer:this.depthLayer}).context(e.getSharedContext()),h.name="VSMVertical",h=this.vsmMaterialHorizontal||(this.vsmMaterialHorizontal=new lv),h.fragmentNode=AC({samples:i,radius:n,size:l,shadowPass:s,depthLayer:this.depthLayer}).context(e.getSharedContext()),h.name="VSMHorizontal"}const l=Cx("intensity","float",r).setGroup(Rm),h=Cx("normalBias","float",r).setGroup(Rm),u=tC(i).mul(dC.add(ax.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=Ax(a.texture,c.xyz):(f=qy(a.texture,c),o.isArrayTexture&&(f=f.depth(this.depthLayer)));const g=bg(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?Ax(this.shadowMap.texture):qy(this.shadowMap.texture)).toInspector(`${y} / Depth`,()=>this.shadowMap.texture.isCubeTexture?Ax(this.shadowMap.texture).r.oneMinus():Xy(this.shadowMap.depthTexture,Vy().mul(Uy(qy(this.shadowMap.depthTexture)))).r.oneMinus())}setup(e){if(!1!==e.renderer.shadowMap.enabled)return _p(()=>{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&&Ua('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");EC=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=pC(e,s)),s}(r,n,EC),n.overrideMaterial=_C(s),r.setRenderObjectFunction(SC(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,EC)}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),CC.material=this.vsmMaterialVertical,CC.render(e),e.setRenderTarget(this.vsmShadowMapHorizontal),CC.material=this.vsmMaterialHorizontal,CC.render(e)}dispose(){this._reset(),super.dispose()}_reset(){this._currentShadowType=null,wC(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 PC=(e,t)=>new RC(e,t),BC=new Hh,IC=new eh,DC=new rl,LC=new rl,FC=[new rl(1,0,0),new rl(-1,0,0),new rl(0,-1,0),new rl(0,1,0),new rl(0,0,1),new rl(0,0,-1)],OC=[new rl(0,-1,0),new rl(0,-1,0),new rl(0,0,-1),new rl(0,0,1),new rl(0,-1,0),new rl(0,-1,0)],zC=[new rl(1,0,0),new rl(-1,0,0),new rl(0,1,0),new rl(0,-1,0),new rl(0,0,1),new rl(0,0,-1)],VC=[new rl(0,-1,0),new rl(0,-1,0),new rl(0,0,1),new rl(0,0,-1),new rl(0,-1,0),new rl(0,-1,0)],kC=_p(({depthTexture:e,bd3D:t,dp:s})=>Ax(e,t).compare(s)),UC=_p(({depthTexture:e,bd3D:t,dp:s,shadow:i})=>{const r=Cx("radius","float",i).setGroup(Rm),n=Cx("mapSize","vec2",i).setGroup(Rm),o=r.div(n.x),a=Gf(t),l=Df(ug(t,a.x.greaterThan(a.z).select(Dp(0,1,0),Dp(1,0,0)))),h=ug(t,l),u=eN(ab.xy).mul(6.28318530718),c=tN(0,5,u),d=tN(1,5,u),p=tN(2,5,u),m=tN(3,5,u),f=tN(4,5,u);return Ax(e,t.add(l.mul(c.x).add(h.mul(c.y)).mul(o))).compare(s).add(Ax(e,t.add(l.mul(d.x).add(h.mul(d.y)).mul(o))).compare(s)).add(Ax(e,t.add(l.mul(p.x).add(h.mul(p.y)).mul(o))).compare(s)).add(Ax(e,t.add(l.mul(m.x).add(h.mul(m.y)).mul(o))).compare(s)).add(Ax(e,t.add(l.mul(f.x).add(h.mul(f.y)).mul(o))).compare(s)).mul(.2)}),GC=_p(({filterFn:e,depthTexture:t,shadowCoord:s,shadow:i})=>{const r=s.xyz.toVar(),n=r.length(),o=Im("float").setGroup(Rm).onRenderUpdate(()=>i.camera.near),a=Im("float").setGroup(Rm).onRenderUpdate(()=>i.camera.far),l=Cx("bias","float",i).setGroup(Rm),h=Ap(1).toVar();return Tp(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 jC extends RC{static get type(){return"PointShadowNode"}constructor(e,t=null){super(e,t)}getShadowFilterFn(e){return 0===e?kC:UC}setupShadowCoord(e,t){return t}setupShadowFilter(e,{filterFn:t,depthTexture:s,shadowCoord:i,shadow:r}){return GC({filterFn:t,depthTexture:s,shadowCoord:i,shadow:r})}setupRenderTarget(e,t){const s=new pc(e.mapSize.width);s.name="PointShadowDepthTexture",s.compareFunction=Ta;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===Ia,h=l?FC:zC,u=l?OC:VC;s.setSize(t.mapSize.width,t.mapSize.width);const c=r.autoClear,d=r.getClearColor(BC),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()),DC.setFromMatrixPosition(i.matrixWorld),o.position.copy(DC),LC.copy(o.position),LC.add(h[e]),o.up.copy(u[e]),o.lookAt(LC),o.updateMatrixWorld(),a.makeTranslation(-DC.x,-DC.y,-DC.z),IC.multiplyMatrices(o.projectionMatrix,o.matrixWorldInverse),t._frustum.setFromProjectionMatrix(IC,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 $C=(e,t)=>new jC(e,t);class WC extends Ew{static get type(){return"AnalyticLightNode"}constructor(e=null){super(),this.light=e,this.color=new Hh,this.colorNode=e&&e.colorNode||Im(this.color).setGroup(Rm),this.baseColorNode=null,this.shadowNode=null,this.shadowColorNode=null,this.isAnalyticLightNode=!0,this.updateType=pd.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 nC(this.light).sub(e.context.positionView||Yb)}setupDirect(){}setupDirectRectArea(){}setupShadowNode(){return PC(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?cp(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 HC=_p(({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)}),qC=({color:e,lightVector:t,cutoffDistance:s,decayExponent:i})=>{const r=t.normalize(),n=t.length(),o=HC({lightDistance:n,cutoffDistance:s,decayExponent:i});return{lightDirection:r,lightColor:e.mul(o)}};class XC extends WC{static get type(){return"PointLightNode"}constructor(e=null){super(e),this.cutoffDistanceNode=Im(0).setGroup(Rm),this.decayExponentNode=Im(2).setGroup(Rm)}update(e){const{light:t}=this;super.update(e),this.cutoffDistanceNode.value=t.distance,this.decayExponentNode.value=t.decay}setupShadowNode(){return $C(this.light)}setupDirect(e){return qC({color:this.colorNode,lightVector:this.getLightVector(e),cutoffDistance:this.cutoffDistanceNode,decayExponent:this.decayExponentNode})}}const YC=_p(([e=Vy()])=>{const t=e.mul(2),s=t.x.floor(),i=t.y.floor();return s.add(i).mod(2).sign()}),ZC=_p(([e=Vy()],{renderer:t,material:s})=>{const i=yg(e.mul(2).sub(1));let r;if(s.alphaToCoverage&&t.currentSamples>0){const e=Ap(i.fwidth()).toVar();r=vg(e.oneMinus(),e.add(1),i).oneMinus()}else r=Bg(i.greaterThan(1),0,1);return r}),QC=_p(([e,t,s])=>{const i=Ap(s).toVar(),r=Ap(t).toVar(),n=Cp(e).toVar();return Bg(n,r,i)}).setLayout({name:"mx_select",type:"float",inputs:[{name:"b",type:"bool"},{name:"t",type:"float"},{name:"f",type:"float"}]}),KC=_p(([e,t])=>{const s=Cp(t).toVar(),i=Ap(e).toVar();return Bg(s,i.negate(),i)}).setLayout({name:"mx_negate_if",type:"float",inputs:[{name:"val",type:"float"},{name:"b",type:"bool"}]}),JC=_p(([e])=>{const t=Ap(e).toVar();return Np(Bf(t))}).setLayout({name:"mx_floor",type:"int",inputs:[{name:"x",type:"float"}]}),eR=_p(([e,t])=>{const s=Ap(e).toVar();return t.assign(JC(s)),s.sub(Ap(t))}),tR=yA([_p(([e,t,s,i,r,n])=>{const o=Ap(n).toVar(),a=Ap(r).toVar(),l=Ap(i).toVar(),h=Ap(s).toVar(),u=Ap(t).toVar(),c=Ap(e).toVar(),d=Ap(jm(1,a)).toVar();return jm(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"}]}),_p(([e,t,s,i,r,n])=>{const o=Ap(n).toVar(),a=Ap(r).toVar(),l=Dp(i).toVar(),h=Dp(s).toVar(),u=Dp(t).toVar(),c=Dp(e).toVar(),d=Ap(jm(1,a)).toVar();return jm(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"}]})]),sR=yA([_p(([e,t,s,i,r,n,o,a,l,h,u])=>{const c=Ap(u).toVar(),d=Ap(h).toVar(),p=Ap(l).toVar(),m=Ap(a).toVar(),f=Ap(o).toVar(),g=Ap(n).toVar(),y=Ap(r).toVar(),b=Ap(i).toVar(),x=Ap(s).toVar(),_=Ap(t).toVar(),w=Ap(e).toVar(),v=Ap(jm(1,p)).toVar(),T=Ap(jm(1,d)).toVar();return Ap(jm(1,c)).toVar().mul(T.mul(w.mul(v).add(_.mul(p))).add(d.mul(x.mul(v).add(b.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"}]}),_p(([e,t,s,i,r,n,o,a,l,h,u])=>{const c=Ap(u).toVar(),d=Ap(h).toVar(),p=Ap(l).toVar(),m=Dp(a).toVar(),f=Dp(o).toVar(),g=Dp(n).toVar(),y=Dp(r).toVar(),b=Dp(i).toVar(),x=Dp(s).toVar(),_=Dp(t).toVar(),w=Dp(e).toVar(),v=Ap(jm(1,p)).toVar(),T=Ap(jm(1,d)).toVar();return Ap(jm(1,c)).toVar().mul(T.mul(w.mul(v).add(_.mul(p))).add(d.mul(x.mul(v).add(b.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"}]})]),iR=yA([_p(([e,t,s])=>{const i=Ap(s).toVar(),r=Ap(t).toVar(),n=Ep(e).toVar(),o=Ep(n.bitAnd(Ep(7))).toVar(),a=Ap(QC(o.lessThan(Ep(4)),r,i)).toVar(),l=Ap($m(2,QC(o.lessThan(Ep(4)),i,r))).toVar();return KC(a,Cp(o.bitAnd(Ep(1)))).add(KC(l,Cp(o.bitAnd(Ep(2)))))}).setLayout({name:"mx_gradient_float_0",type:"float",inputs:[{name:"hash",type:"uint"},{name:"x",type:"float"},{name:"y",type:"float"}]}),_p(([e,t,s,i])=>{const r=Ap(i).toVar(),n=Ap(s).toVar(),o=Ap(t).toVar(),a=Ep(e).toVar(),l=Ep(a.bitAnd(Ep(15))).toVar(),h=Ap(QC(l.lessThan(Ep(8)),o,n)).toVar(),u=Ap(QC(l.lessThan(Ep(4)),n,QC(l.equal(Ep(12)).or(l.equal(Ep(14))),o,r))).toVar();return KC(h,Cp(l.bitAnd(Ep(1)))).add(KC(u,Cp(l.bitAnd(Ep(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"}]})]),rR=yA([_p(([e,t,s])=>{const i=Ap(s).toVar(),r=Ap(t).toVar(),n=Fp(e).toVar();return Dp(iR(n.x,r,i),iR(n.y,r,i),iR(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"}]}),_p(([e,t,s,i])=>{const r=Ap(i).toVar(),n=Ap(s).toVar(),o=Ap(t).toVar(),a=Fp(e).toVar();return Dp(iR(a.x,o,n,r),iR(a.y,o,n,r),iR(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"}]})]),nR=_p(([e])=>{const t=Ap(e).toVar();return $m(.6616,t)}).setLayout({name:"mx_gradient_scale2d_0",type:"float",inputs:[{name:"v",type:"float"}]}),oR=_p(([e])=>{const t=Ap(e).toVar();return $m(.982,t)}).setLayout({name:"mx_gradient_scale3d_0",type:"float",inputs:[{name:"v",type:"float"}]}),aR=yA([nR,_p(([e])=>{const t=Dp(e).toVar();return $m(.6616,t)}).setLayout({name:"mx_gradient_scale2d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),lR=yA([oR,_p(([e])=>{const t=Dp(e).toVar();return $m(.982,t)}).setLayout({name:"mx_gradient_scale3d_1",type:"vec3",inputs:[{name:"v",type:"vec3"}]})]),hR=_p(([e,t])=>{const s=Np(t).toVar(),i=Ep(e).toVar();return i.shiftLeft(s).bitOr(i.shiftRight(Np(32).sub(s)))}).setLayout({name:"mx_rotl32",type:"uint",inputs:[{name:"x",type:"uint"},{name:"k",type:"int"}]}),uR=_p(([e,t,s])=>{e.subAssign(s),e.bitXorAssign(hR(s,Np(4))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(hR(e,Np(6))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(hR(t,Np(8))),t.addAssign(e),e.subAssign(s),e.bitXorAssign(hR(s,Np(16))),s.addAssign(t),t.subAssign(e),t.bitXorAssign(hR(e,Np(19))),e.addAssign(s),s.subAssign(t),s.bitXorAssign(hR(t,Np(4))),t.addAssign(e)}),cR=_p(([e,t,s])=>{const i=Ep(s).toVar(),r=Ep(t).toVar(),n=Ep(e).toVar();return i.bitXorAssign(r),i.subAssign(hR(r,Np(14))),n.bitXorAssign(i),n.subAssign(hR(i,Np(11))),r.bitXorAssign(n),r.subAssign(hR(n,Np(25))),i.bitXorAssign(r),i.subAssign(hR(r,Np(16))),n.bitXorAssign(i),n.subAssign(hR(i,Np(4))),r.bitXorAssign(n),r.subAssign(hR(n,Np(14))),i.bitXorAssign(r),i.subAssign(hR(r,Np(24))),i}).setLayout({name:"mx_bjfinal",type:"uint",inputs:[{name:"a",type:"uint"},{name:"b",type:"uint"},{name:"c",type:"uint"}]}),dR=_p(([e])=>{const t=Ep(e).toVar();return Ap(t).div(Ap(Ep(Np(4294967295))))}).setLayout({name:"mx_bits_to_01",type:"float",inputs:[{name:"bits",type:"uint"}]}),pR=_p(([e])=>{const t=Ap(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"}]}),mR=yA([_p(([e])=>{const t=Np(e).toVar(),s=Ep(Ep(1)).toVar(),i=Ep(Ep(Np(3735928559)).add(s.shiftLeft(Ep(2))).add(Ep(13))).toVar();return cR(i.add(Ep(t)),i,i)}).setLayout({name:"mx_hash_int_0",type:"uint",inputs:[{name:"x",type:"int"}]}),_p(([e,t])=>{const s=Np(t).toVar(),i=Np(e).toVar(),r=Ep(Ep(2)).toVar(),n=Ep().toVar(),o=Ep().toVar(),a=Ep().toVar();return n.assign(o.assign(a.assign(Ep(Np(3735928559)).add(r.shiftLeft(Ep(2))).add(Ep(13))))),n.addAssign(Ep(i)),o.addAssign(Ep(s)),cR(n,o,a)}).setLayout({name:"mx_hash_int_1",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),_p(([e,t,s])=>{const i=Np(s).toVar(),r=Np(t).toVar(),n=Np(e).toVar(),o=Ep(Ep(3)).toVar(),a=Ep().toVar(),l=Ep().toVar(),h=Ep().toVar();return a.assign(l.assign(h.assign(Ep(Np(3735928559)).add(o.shiftLeft(Ep(2))).add(Ep(13))))),a.addAssign(Ep(n)),l.addAssign(Ep(r)),h.addAssign(Ep(i)),cR(a,l,h)}).setLayout({name:"mx_hash_int_2",type:"uint",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]}),_p(([e,t,s,i])=>{const r=Np(i).toVar(),n=Np(s).toVar(),o=Np(t).toVar(),a=Np(e).toVar(),l=Ep(Ep(4)).toVar(),h=Ep().toVar(),u=Ep().toVar(),c=Ep().toVar();return h.assign(u.assign(c.assign(Ep(Np(3735928559)).add(l.shiftLeft(Ep(2))).add(Ep(13))))),h.addAssign(Ep(a)),u.addAssign(Ep(o)),c.addAssign(Ep(n)),uR(h,u,c),h.addAssign(Ep(r)),cR(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"}]}),_p(([e,t,s,i,r])=>{const n=Np(r).toVar(),o=Np(i).toVar(),a=Np(s).toVar(),l=Np(t).toVar(),h=Np(e).toVar(),u=Ep(Ep(5)).toVar(),c=Ep().toVar(),d=Ep().toVar(),p=Ep().toVar();return c.assign(d.assign(p.assign(Ep(Np(3735928559)).add(u.shiftLeft(Ep(2))).add(Ep(13))))),c.addAssign(Ep(h)),d.addAssign(Ep(l)),p.addAssign(Ep(a)),uR(c,d,p),c.addAssign(Ep(o)),d.addAssign(Ep(n)),cR(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"}]})]),fR=yA([_p(([e,t])=>{const s=Np(t).toVar(),i=Np(e).toVar(),r=Ep(mR(i,s)).toVar(),n=Fp().toVar();return n.x.assign(r.bitAnd(Np(255))),n.y.assign(r.shiftRight(Np(8)).bitAnd(Np(255))),n.z.assign(r.shiftRight(Np(16)).bitAnd(Np(255))),n}).setLayout({name:"mx_hash_vec3_0",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"}]}),_p(([e,t,s])=>{const i=Np(s).toVar(),r=Np(t).toVar(),n=Np(e).toVar(),o=Ep(mR(n,r,i)).toVar(),a=Fp().toVar();return a.x.assign(o.bitAnd(Np(255))),a.y.assign(o.shiftRight(Np(8)).bitAnd(Np(255))),a.z.assign(o.shiftRight(Np(16)).bitAnd(Np(255))),a}).setLayout({name:"mx_hash_vec3_1",type:"uvec3",inputs:[{name:"x",type:"int"},{name:"y",type:"int"},{name:"z",type:"int"}]})]),gR=yA([_p(([e])=>{const t=Rp(e).toVar(),s=Np().toVar(),i=Np().toVar(),r=Ap(eR(t.x,s)).toVar(),n=Ap(eR(t.y,i)).toVar(),o=Ap(pR(r)).toVar(),a=Ap(pR(n)).toVar(),l=Ap(tR(iR(mR(s,i),r,n),iR(mR(s.add(Np(1)),i),r.sub(1),n),iR(mR(s,i.add(Np(1))),r,n.sub(1)),iR(mR(s.add(Np(1)),i.add(Np(1))),r.sub(1),n.sub(1)),o,a)).toVar();return aR(l)}).setLayout({name:"mx_perlin_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"}]}),_p(([e])=>{const t=Dp(e).toVar(),s=Np().toVar(),i=Np().toVar(),r=Np().toVar(),n=Ap(eR(t.x,s)).toVar(),o=Ap(eR(t.y,i)).toVar(),a=Ap(eR(t.z,r)).toVar(),l=Ap(pR(n)).toVar(),h=Ap(pR(o)).toVar(),u=Ap(pR(a)).toVar(),c=Ap(sR(iR(mR(s,i,r),n,o,a),iR(mR(s.add(Np(1)),i,r),n.sub(1),o,a),iR(mR(s,i.add(Np(1)),r),n,o.sub(1),a),iR(mR(s.add(Np(1)),i.add(Np(1)),r),n.sub(1),o.sub(1),a),iR(mR(s,i,r.add(Np(1))),n,o,a.sub(1)),iR(mR(s.add(Np(1)),i,r.add(Np(1))),n.sub(1),o,a.sub(1)),iR(mR(s,i.add(Np(1)),r.add(Np(1))),n,o.sub(1),a.sub(1)),iR(mR(s.add(Np(1)),i.add(Np(1)),r.add(Np(1))),n.sub(1),o.sub(1),a.sub(1)),l,h,u)).toVar();return lR(c)}).setLayout({name:"mx_perlin_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"}]})]),yR=yA([_p(([e])=>{const t=Rp(e).toVar(),s=Np().toVar(),i=Np().toVar(),r=Ap(eR(t.x,s)).toVar(),n=Ap(eR(t.y,i)).toVar(),o=Ap(pR(r)).toVar(),a=Ap(pR(n)).toVar(),l=Dp(tR(rR(fR(s,i),r,n),rR(fR(s.add(Np(1)),i),r.sub(1),n),rR(fR(s,i.add(Np(1))),r,n.sub(1)),rR(fR(s.add(Np(1)),i.add(Np(1))),r.sub(1),n.sub(1)),o,a)).toVar();return aR(l)}).setLayout({name:"mx_perlin_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),_p(([e])=>{const t=Dp(e).toVar(),s=Np().toVar(),i=Np().toVar(),r=Np().toVar(),n=Ap(eR(t.x,s)).toVar(),o=Ap(eR(t.y,i)).toVar(),a=Ap(eR(t.z,r)).toVar(),l=Ap(pR(n)).toVar(),h=Ap(pR(o)).toVar(),u=Ap(pR(a)).toVar(),c=Dp(sR(rR(fR(s,i,r),n,o,a),rR(fR(s.add(Np(1)),i,r),n.sub(1),o,a),rR(fR(s,i.add(Np(1)),r),n,o.sub(1),a),rR(fR(s.add(Np(1)),i.add(Np(1)),r),n.sub(1),o.sub(1),a),rR(fR(s,i,r.add(Np(1))),n,o,a.sub(1)),rR(fR(s.add(Np(1)),i,r.add(Np(1))),n.sub(1),o,a.sub(1)),rR(fR(s,i.add(Np(1)),r.add(Np(1))),n,o.sub(1),a.sub(1)),rR(fR(s.add(Np(1)),i.add(Np(1)),r.add(Np(1))),n.sub(1),o.sub(1),a.sub(1)),l,h,u)).toVar();return lR(c)}).setLayout({name:"mx_perlin_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"}]})]),bR=yA([_p(([e])=>{const t=Ap(e).toVar(),s=Np(JC(t)).toVar();return dR(mR(s))}).setLayout({name:"mx_cell_noise_float_0",type:"float",inputs:[{name:"p",type:"float"}]}),_p(([e])=>{const t=Rp(e).toVar(),s=Np(JC(t.x)).toVar(),i=Np(JC(t.y)).toVar();return dR(mR(s,i))}).setLayout({name:"mx_cell_noise_float_1",type:"float",inputs:[{name:"p",type:"vec2"}]}),_p(([e])=>{const t=Dp(e).toVar(),s=Np(JC(t.x)).toVar(),i=Np(JC(t.y)).toVar(),r=Np(JC(t.z)).toVar();return dR(mR(s,i,r))}).setLayout({name:"mx_cell_noise_float_2",type:"float",inputs:[{name:"p",type:"vec3"}]}),_p(([e])=>{const t=zp(e).toVar(),s=Np(JC(t.x)).toVar(),i=Np(JC(t.y)).toVar(),r=Np(JC(t.z)).toVar(),n=Np(JC(t.w)).toVar();return dR(mR(s,i,r,n))}).setLayout({name:"mx_cell_noise_float_3",type:"float",inputs:[{name:"p",type:"vec4"}]})]),xR=yA([_p(([e])=>{const t=Ap(e).toVar(),s=Np(JC(t)).toVar();return Dp(dR(mR(s,Np(0))),dR(mR(s,Np(1))),dR(mR(s,Np(2))))}).setLayout({name:"mx_cell_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"float"}]}),_p(([e])=>{const t=Rp(e).toVar(),s=Np(JC(t.x)).toVar(),i=Np(JC(t.y)).toVar();return Dp(dR(mR(s,i,Np(0))),dR(mR(s,i,Np(1))),dR(mR(s,i,Np(2))))}).setLayout({name:"mx_cell_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec2"}]}),_p(([e])=>{const t=Dp(e).toVar(),s=Np(JC(t.x)).toVar(),i=Np(JC(t.y)).toVar(),r=Np(JC(t.z)).toVar();return Dp(dR(mR(s,i,r,Np(0))),dR(mR(s,i,r,Np(1))),dR(mR(s,i,r,Np(2))))}).setLayout({name:"mx_cell_noise_vec3_2",type:"vec3",inputs:[{name:"p",type:"vec3"}]}),_p(([e])=>{const t=zp(e).toVar(),s=Np(JC(t.x)).toVar(),i=Np(JC(t.y)).toVar(),r=Np(JC(t.z)).toVar(),n=Np(JC(t.w)).toVar();return Dp(dR(mR(s,i,r,n,Np(0))),dR(mR(s,i,r,n,Np(1))),dR(mR(s,i,r,n,Np(2))))}).setLayout({name:"mx_cell_noise_vec3_3",type:"vec3",inputs:[{name:"p",type:"vec4"}]})]),_R=_p(([e,t,s,i])=>{const r=Ap(i).toVar(),n=Ap(s).toVar(),o=Np(t).toVar(),a=Dp(e).toVar(),l=Ap(0).toVar(),h=Ap(1).toVar();return ww(o,()=>{l.addAssign(h.mul(gR(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"}]}),wR=_p(([e,t,s,i])=>{const r=Ap(i).toVar(),n=Ap(s).toVar(),o=Np(t).toVar(),a=Dp(e).toVar(),l=Dp(0).toVar(),h=Ap(1).toVar();return ww(o,()=>{l.addAssign(h.mul(yR(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"}]}),vR=_p(([e,t,s,i])=>{const r=Ap(i).toVar(),n=Ap(s).toVar(),o=Np(t).toVar(),a=Dp(e).toVar();return Rp(_R(a,o,n,r),_R(a.add(Dp(Np(19),Np(193),Np(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"}]}),TR=_p(([e,t,s,i])=>{const r=Ap(i).toVar(),n=Ap(s).toVar(),o=Np(t).toVar(),a=Dp(e).toVar(),l=Dp(wR(a,o,n,r)).toVar(),h=Ap(_R(a.add(Dp(Np(19),Np(193),Np(17))),o,n,r)).toVar();return zp(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"}]}),SR=yA([_p(([e,t,s,i,r,n,o])=>{const a=Np(o).toVar(),l=Ap(n).toVar(),h=Np(r).toVar(),u=Np(i).toVar(),c=Np(s).toVar(),d=Np(t).toVar(),p=Rp(e).toVar(),m=Dp(xR(Rp(d.add(u),c.add(h)))).toVar(),f=Rp(m.x,m.y).toVar();f.subAssign(.5),f.mulAssign(l),f.addAssign(.5);const g=Rp(Rp(Ap(d),Ap(c)).add(f)).toVar(),y=Rp(g.sub(p)).toVar();return Tp(a.equal(Np(2)),()=>Gf(y.x).add(Gf(y.y))),Tp(a.equal(Np(3)),()=>rg(Gf(y.x),Gf(y.y))),hg(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"}]}),_p(([e,t,s,i,r,n,o,a,l])=>{const h=Np(l).toVar(),u=Ap(a).toVar(),c=Np(o).toVar(),d=Np(n).toVar(),p=Np(r).toVar(),m=Np(i).toVar(),f=Np(s).toVar(),g=Np(t).toVar(),y=Dp(e).toVar(),b=Dp(xR(Dp(g.add(p),f.add(d),m.add(c)))).toVar();b.subAssign(.5),b.mulAssign(u),b.addAssign(.5);const x=Dp(Dp(Ap(g),Ap(f),Ap(m)).add(b)).toVar(),_=Dp(x.sub(y)).toVar();return Tp(h.equal(Np(2)),()=>Gf(_.x).add(Gf(_.y)).add(Gf(_.z))),Tp(h.equal(Np(3)),()=>rg(Gf(_.x),Gf(_.y),Gf(_.z))),hg(_,_)}).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"}]})]),MR=_p(([e,t,s])=>{const i=Np(s).toVar(),r=Ap(t).toVar(),n=Rp(e).toVar(),o=Np().toVar(),a=Np().toVar(),l=Rp(eR(n.x,o),eR(n.y,a)).toVar(),h=Ap(1e6).toVar();return ww({start:-1,end:Np(1),name:"x",condition:"<="},({x:e})=>{ww({start:-1,end:Np(1),name:"y",condition:"<="},({y:t})=>{const s=Ap(SR(l,e,t,o,a,r,i)).toVar();h.assign(ig(h,s))})}),Tp(i.equal(Np(0)),()=>{h.assign(Rf(h))}),h}).setLayout({name:"mx_worley_noise_float_0",type:"float",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),AR=_p(([e,t,s])=>{const i=Np(s).toVar(),r=Ap(t).toVar(),n=Rp(e).toVar(),o=Np().toVar(),a=Np().toVar(),l=Rp(eR(n.x,o),eR(n.y,a)).toVar(),h=Rp(1e6,1e6).toVar();return ww({start:-1,end:Np(1),name:"x",condition:"<="},({x:e})=>{ww({start:-1,end:Np(1),name:"y",condition:"<="},({y:t})=>{const s=Ap(SR(l,e,t,o,a,r,i)).toVar();Tp(s.lessThan(h.x),()=>{h.y.assign(h.x),h.x.assign(s)}).ElseIf(s.lessThan(h.y),()=>{h.y.assign(s)})})}),Tp(i.equal(Np(0)),()=>{h.assign(Rf(h))}),h}).setLayout({name:"mx_worley_noise_vec2_0",type:"vec2",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),NR=_p(([e,t,s])=>{const i=Np(s).toVar(),r=Ap(t).toVar(),n=Rp(e).toVar(),o=Np().toVar(),a=Np().toVar(),l=Rp(eR(n.x,o),eR(n.y,a)).toVar(),h=Dp(1e6,1e6,1e6).toVar();return ww({start:-1,end:Np(1),name:"x",condition:"<="},({x:e})=>{ww({start:-1,end:Np(1),name:"y",condition:"<="},({y:t})=>{const s=Ap(SR(l,e,t,o,a,r,i)).toVar();Tp(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)})})}),Tp(i.equal(Np(0)),()=>{h.assign(Rf(h))}),h}).setLayout({name:"mx_worley_noise_vec3_0",type:"vec3",inputs:[{name:"p",type:"vec2"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]}),ER=yA([MR,_p(([e,t,s])=>{const i=Np(s).toVar(),r=Ap(t).toVar(),n=Dp(e).toVar(),o=Np().toVar(),a=Np().toVar(),l=Np().toVar(),h=Dp(eR(n.x,o),eR(n.y,a),eR(n.z,l)).toVar(),u=Ap(1e6).toVar();return ww({start:-1,end:Np(1),name:"x",condition:"<="},({x:e})=>{ww({start:-1,end:Np(1),name:"y",condition:"<="},({y:t})=>{ww({start:-1,end:Np(1),name:"z",condition:"<="},({z:s})=>{const n=Ap(SR(h,e,t,s,o,a,l,r,i)).toVar();u.assign(ig(u,n))})})}),Tp(i.equal(Np(0)),()=>{u.assign(Rf(u))}),u}).setLayout({name:"mx_worley_noise_float_1",type:"float",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),CR=yA([AR,_p(([e,t,s])=>{const i=Np(s).toVar(),r=Ap(t).toVar(),n=Dp(e).toVar(),o=Np().toVar(),a=Np().toVar(),l=Np().toVar(),h=Dp(eR(n.x,o),eR(n.y,a),eR(n.z,l)).toVar(),u=Rp(1e6,1e6).toVar();return ww({start:-1,end:Np(1),name:"x",condition:"<="},({x:e})=>{ww({start:-1,end:Np(1),name:"y",condition:"<="},({y:t})=>{ww({start:-1,end:Np(1),name:"z",condition:"<="},({z:s})=>{const n=Ap(SR(h,e,t,s,o,a,l,r,i)).toVar();Tp(n.lessThan(u.x),()=>{u.y.assign(u.x),u.x.assign(n)}).ElseIf(n.lessThan(u.y),()=>{u.y.assign(n)})})})}),Tp(i.equal(Np(0)),()=>{u.assign(Rf(u))}),u}).setLayout({name:"mx_worley_noise_vec2_1",type:"vec2",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),RR=yA([NR,_p(([e,t,s])=>{const i=Np(s).toVar(),r=Ap(t).toVar(),n=Dp(e).toVar(),o=Np().toVar(),a=Np().toVar(),l=Np().toVar(),h=Dp(eR(n.x,o),eR(n.y,a),eR(n.z,l)).toVar(),u=Dp(1e6,1e6,1e6).toVar();return ww({start:-1,end:Np(1),name:"x",condition:"<="},({x:e})=>{ww({start:-1,end:Np(1),name:"y",condition:"<="},({y:t})=>{ww({start:-1,end:Np(1),name:"z",condition:"<="},({z:s})=>{const n=Ap(SR(h,e,t,s,o,a,l,r,i)).toVar();Tp(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)})})})}),Tp(i.equal(Np(0)),()=>{u.assign(Rf(u))}),u}).setLayout({name:"mx_worley_noise_vec3_1",type:"vec3",inputs:[{name:"p",type:"vec3"},{name:"jitter",type:"float"},{name:"metric",type:"int"}]})]),PR=_p(([e,t,s,i,r,n,o,a,l,h,u])=>{const c=Np(e).toVar(),d=Rp(t).toVar(),p=Rp(s).toVar(),m=Rp(i).toVar(),f=Ap(r).toVar(),g=Ap(n).toVar(),y=Ap(o).toVar(),b=Cp(a).toVar(),x=Np(l).toVar(),_=Ap(h).toVar(),w=Ap(u).toVar(),v=d.mul(p).add(m),T=Ap(0).toVar();return Tp(c.equal(Np(0)),()=>{T.assign(yR(v))}),Tp(c.equal(Np(1)),()=>{T.assign(xR(v))}),Tp(c.equal(Np(2)),()=>{T.assign(RR(v,f,Np(0)))}),Tp(c.equal(Np(3)),()=>{T.assign(wR(Dp(v,0),x,_,w))}),T.assign(T.mul(y.sub(g)).add(g)),Tp(b,()=>{T.assign(xg(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"}]}),BR=_p(([e,t,s,i,r,n,o,a,l,h,u])=>{const c=Np(e).toVar(),d=Dp(t).toVar(),p=Dp(s).toVar(),m=Dp(i).toVar(),f=Ap(r).toVar(),g=Ap(n).toVar(),y=Ap(o).toVar(),b=Cp(a).toVar(),x=Np(l).toVar(),_=Ap(h).toVar(),w=Ap(u).toVar(),v=d.mul(p).add(m),T=Ap(0).toVar();return Tp(c.equal(Np(0)),()=>{T.assign(yR(v))}),Tp(c.equal(Np(1)),()=>{T.assign(xR(v))}),Tp(c.equal(Np(2)),()=>{T.assign(RR(v,f,Np(0)))}),Tp(c.equal(Np(3)),()=>{T.assign(wR(v,x,_,w))}),T.assign(T.mul(y.sub(g)).add(g)),Tp(b,()=>{T.assign(xg(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"}]}),IR=_p(([e])=>{const t=e.y,s=e.z,i=Dp().toVar();return Tp(t.lessThan(1e-4),()=>{i.assign(Dp(s,s,s))}).Else(()=>{let r=e.x;r=r.sub(Bf(r)).mul(6).toVar();const n=Np(Qf(r)),o=r.sub(Ap(n)),a=s.mul(t.oneMinus()),l=s.mul(t.mul(o).oneMinus()),h=s.mul(t.mul(o.oneMinus()).oneMinus());Tp(n.equal(Np(0)),()=>{i.assign(Dp(s,h,a))}).ElseIf(n.equal(Np(1)),()=>{i.assign(Dp(l,s,a))}).ElseIf(n.equal(Np(2)),()=>{i.assign(Dp(a,s,h))}).ElseIf(n.equal(Np(3)),()=>{i.assign(Dp(a,l,s))}).ElseIf(n.equal(Np(4)),()=>{i.assign(Dp(h,a,s))}).Else(()=>{i.assign(Dp(s,a,l))})}),i}).setLayout({name:"mx_hsvtorgb",type:"vec3",inputs:[{name:"hsv",type:"vec3"}]}),DR=_p(([e])=>{const t=Dp(e).toVar(),s=Ap(t.x).toVar(),i=Ap(t.y).toVar(),r=Ap(t.z).toVar(),n=Ap(ig(s,ig(i,r))).toVar(),o=Ap(rg(s,rg(i,r))).toVar(),a=Ap(o.sub(n)).toVar(),l=Ap().toVar(),h=Ap().toVar(),u=Ap().toVar();return u.assign(o),Tp(o.greaterThan(0),()=>{h.assign(a.div(o))}).Else(()=>{h.assign(0)}),Tp(h.lessThanEqual(0),()=>{l.assign(0)}).Else(()=>{Tp(s.greaterThanEqual(o),()=>{l.assign(i.sub(r).div(a))}).ElseIf(i.greaterThanEqual(o),()=>{l.assign(Gm(2,r.sub(s).div(a)))}).Else(()=>{l.assign(Gm(4,s.sub(i).div(a)))}),l.mulAssign(1/6),Tp(l.lessThan(0),()=>{l.addAssign(1)})}),Dp(l,h,u)}).setLayout({name:"mx_rgbtohsv",type:"vec3",inputs:[{name:"c",type:"vec3"}]}),LR=_p(([e])=>{const t=Dp(e).toVar(),s=Op(Zm(t,Dp(.04045))).toVar(),i=Dp(t.div(12.92)).toVar(),r=Dp(cg(rg(t.add(Dp(.055)),Dp(0)).div(1.055),Dp(2.4))).toVar();return bg(i,r,s)}).setLayout({name:"mx_srgb_texture_to_lin_rec709",type:"vec3",inputs:[{name:"color",type:"vec3"}]}),FR=(e,t)=>{e=Ap(e),t=Ap(t);const s=Rp(t.dFdx(),t.dFdy()).length().mul(.7071067811865476);return vg(e.sub(s),e.add(s),t)},OR=(e,t,s,i)=>bg(e,t,s[i].clamp()),zR=(e,t,s,i,r)=>bg(e,t,FR(s,i[r])),VR=_p(([e,t,s])=>{const i=Df(e).toVar(),r=jm(Ap(.5).mul(t.sub(s)),qb).div(i).toVar(),n=jm(Ap(-.5).mul(t.sub(s)),qb).div(i).toVar(),o=Dp().toVar();o.x=i.x.greaterThan(Ap(0)).select(r.x,n.x),o.y=i.y.greaterThan(Ap(0)).select(r.y,n.y),o.z=i.z.greaterThan(Ap(0)).select(r.z,n.z);const a=ig(o.x,o.y,o.z).toVar();return qb.add(i.mul(a)).toVar().sub(s)}),kR=_p(([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($m(s,s).sub($m(i,i)))),n});var UR=Object.freeze({__proto__:null,BRDF_GGX:qv,BRDF_Lambert:Bv,BasicPointShadowFilter:kC,BasicShadowFilter:fC,Break:vw,Const:jg,Continue:()=>Ey("continue").toStack(),DFGLUT:Zv,D_GGX:$v,Discard:Cy,EPSILON:gf,F_Schlick:Pv,Fn:_p,HALF_PI:wf,INFINITY:yf,If:Tp,Loop:ww,NodeAccess:md,NodeShaderStage:dd,NodeType:{BOOLEAN:"bool",INTEGER:"int",FLOAT:"float",VECTOR2:"vec2",VECTOR3:"vec3",VECTOR4:"vec4",MATRIX2:"mat2",MATRIX3:"mat3",MATRIX4:"mat4"},NodeUpdateType:pd,OnBeforeMaterialUpdate:e=>rN(iN.BEFORE_MATERIAL,e),OnBeforeObjectUpdate:e=>rN(iN.BEFORE_OBJECT,e),OnMaterialUpdate:e=>rN(iN.MATERIAL,e),OnObjectUpdate:e=>rN(iN.OBJECT,e),PCFShadowFilter:gC,PCFSoftShadowFilter:yC,PI:bf,PI2:xf,PointShadowFilter:UC,Return:()=>Ey("return").toStack(),Schlick_to_F0:Jv,ScriptableNodeResources:iE,ShaderNode:up,Stack:Sp,Switch:(...e)=>Dd.Switch(...e),TBNViewMatrix:s_,TWO_PI:_f,VSMShadowFilter:bC,V_GGX_SmithCorrelated:Gv,Var:Gg,VarIntent:$g,abs:Gf,acesFilmicToneMapping:jN,acos:kf,add:Gm,addMethodChaining:Fd,addNodeElement:function(e){Ua("TSL: AddNodeElement has been removed in favor of tree-shaking. Trying add",e)},agxToneMapping:qN,all:vf,alphaT:lm,and:Jm,anisotropy:hm,anisotropyB:cm,anisotropyT:um,any:Tf,append:e=>(Ua("TSL: append() has been renamed to Stack()."),Sp(e)),array:Lm,arrayBuffer:e=>new Bd(e,"ArrayBuffer"),asin:Vf,assign:Om,atan:Uf,atan2:Eg,atomicAdd:(e,t)=>AE(SE.ATOMIC_ADD,e,t),atomicAnd:(e,t)=>AE(SE.ATOMIC_AND,e,t),atomicFunc:AE,atomicLoad:e=>AE(SE.ATOMIC_LOAD,e,null),atomicMax:(e,t)=>AE(SE.ATOMIC_MAX,e,t),atomicMin:(e,t)=>AE(SE.ATOMIC_MIN,e,t),atomicOr:(e,t)=>AE(SE.ATOMIC_OR,e,t),atomicStore:(e,t)=>AE(SE.ATOMIC_STORE,e,t),atomicSub:(e,t)=>AE(SE.ATOMIC_SUB,e,t),atomicXor:(e,t)=>AE(SE.ATOMIC_XOR,e,t),attenuationColor:Sm,attenuationDistance:Tm,attribute:zy,attributeArray:(e,t="float")=>{let s,i;!0===t.isStruct?(s=t.layout.getLength(),i=id("float")):(s=rd(t),i=id(t));const r=new oN(e,s,i);return iw(r,t,e)},backgroundBlurriness:dN,backgroundIntensity:pN,backgroundRotation:mN,batch:gw,bentNormalView:r_,billboarding:TA,bitAnd:rf,bitNot:nf,bitOr:of,bitXor:af,bitangentGeometry:Kx,bitangentLocal:Jx,bitangentView:e_,bitangentWorld:t_,bitcast:YM,blendBurn:tv,blendColor:nv,blendDodge:sv,blendOverlay:rv,blendScreen:iv,blur:KT,bool:Cp,buffer:Zy,bufferAttribute:py,builtin:eb,builtinAOContext:zg,builtinShadowContext:Og,bumpMap:d_,burn:(...e)=>(Ua('TSL: "burn" has been renamed. Use "blendBurn" instead.'),tv(e)),bvec2:Ip,bvec3:Op,bvec4:Up,bypass:Ty,cache:wy,call:Vm,cameraFar:fb,cameraIndex:pb,cameraNear:mb,cameraNormalMatrix:_b,cameraPosition:wb,cameraProjectionMatrix:gb,cameraProjectionMatrixInverse:yb,cameraViewMatrix:bb,cameraViewport:vb,cameraWorldMatrix:xb,cbrt:gg,cdl:PN,ceil:If,checker:YC,cineonToneMapping:UN,clamp:xg,clearcoat:tm,clearcoatNormalView:lx,clearcoatRoughness:sm,code:ZN,color:Mp,colorSpaceToWorking:ty,colorToDirection:e=>cp(e).mul(2).sub(1),compute:by,computeKernel:yy,computeSkinning:(e,t=null)=>{const s=new bw(e);return s.positionNode=iw(new Qu(e.geometry.getAttribute("position").array,3),"vec3").setPBO(!0).toReadOnly().element(ow).toVar(),s.skinIndexNode=iw(new Qu(new Uint32Array(e.geometry.getAttribute("skinIndex").array),4),"uvec4").setPBO(!0).toReadOnly().element(ow).toVar(),s.skinWeightNode=iw(new Qu(e.geometry.getAttribute("skinWeight").array,4),"vec4").setPBO(!0).toReadOnly().element(ow).toVar(),s.bindMatrixNode=Im(e.bindMatrix,"mat4"),s.bindMatrixInverseNode=Im(e.bindMatrixInverse,"mat4"),s.boneMatricesNode=Zy(e.skeleton.boneMatrices,"mat4",e.skeleton.bones.length),s.toPositionNode=t,cp(s)},context:Dg,convert:Hp,convertColorSpace:(e,t,s)=>cp(new Jg(cp(e),t,s)),convertToTexture:(e,...t)=>e.isSampleNode||e.isTextureNode?e:e.isPassNode?e.getTextureNode():ZA(e,...t),cos:Of,countLeadingZeros:eA,countOneBits:tA,countTrailingZeros:JM,cross:ug,cubeTexture:Ax,cubeTextureBase:Mx,dFdx:qf,dFdy:Xf,dashSize:ym,debug:Iy,decrement:pf,decrementBefore:cf,defaultBuildStages:gd,defaultShaderStages:fd,defined:lp,degrees:Mf,deltaTime:xA,densityFog:function(e,t){return Ua('TSL: "densityFog( color, density )" is deprecated. Use "fog( color, densityFogFactor( density ) )" instead.'),hE(e,lE(t))},densityFogFactor:lE,depth:Hw,depthPass:(e,t,s)=>new ON(ON.DEPTH,e,t,s),determinant:eg,difference:lg,diffuseColor:Zp,diffuseContribution:Qp,directPointLight:qC,directionToColor:n_,directionToFaceDirection:ex,dispersion:Mm,disposeShadowMaterial:wC,distance:ag,div:Wm,dodge:(...e)=>(Ua('TSL: "dodge" has been renamed. Use "blendDodge" instead.'),sv(e)),dot:hg,drawIndex:uw,dynamicBufferAttribute:(e,t=null,s=0,i=0)=>dy(e,t,s,i,Pa),element:Wp,emissive:Kp,equal:qm,equals:sg,equirectUV:bv,exp:Af,exp2:Nf,expression:Ey,faceDirection:Jb,faceForward:Tg,faceforward:Cg,float:Ap,floatBitsToInt:e=>new XM(e,"int","float"),floatBitsToUint:ZM,floor:Bf,fog:hE,fract:Lf,frameGroup:Cm,frameId:_A,frontFacing:Kb,fwidth:Kf,gain:(e,t)=>e.lessThan(.5)?iA(e.mul(2),t).div(2):jm(1,iA($m(jm(1,e),2),t).div(2)),gapSize:bm,getConstNodeType:hp,getCurrentStack:vp,getDirection:XT,getDistanceAttenuation:HC,getGeometryRoughness:kv,getNormalFromDepth:JA,getParallaxCorrectNormal:VR,getRoughness:Uv,getScreenPosition:KA,getShIrradianceAt:kR,getShadowMaterial:_C,getShadowRenderObjectFunction:SC,getTextureIndex:WM,getViewPosition:QA,ggxConvolution:sS,globalId:bE,glsl:(e,t)=>ZN(e,t,"glsl"),glslFn:(e,t)=>KN(e,t,"glsl"),grayscale:AN,greaterThan:Zm,greaterThanEqual:Km,hash:sA,highpModelNormalViewMatrix:jb,highpModelViewMatrix:Gb,hue:CN,increment:df,incrementBefore:uf,inspector:Fy,instance:dw,instanceIndex:ow,instancedArray:(e,t="float")=>{let s,i;!0===t.isStruct?(s=t.layout.getLength(),i=id("float")):(s=rd(t),i=id(t));const r=new nN(e,s,i);return iw(r,t,e)},instancedBufferAttribute:my,instancedDynamicBufferAttribute:fy,instancedMesh:mw,int:Np,intBitsToFloat:e=>new XM(e,"float","int"),interleavedGradientNoise:eN,inverse:tg,inverseSqrt:Pf,inversesqrt:Rg,invocationLocalIndex:hw,invocationSubgroupIndex:lw,ior:_m,iridescence:nm,iridescenceIOR:om,iridescenceThickness:am,isolate:_y,ivec2:Pp,ivec3:Lp,ivec4:Vp,js:(e,t)=>ZN(e,t,"js"),label:Vg,length:$f,lengthSq:yg,lessThan:Ym,lessThanEqual:Qm,lightPosition:iC,lightProjectionUV:sC,lightShadowMatrix:tC,lightTargetDirection:oC,lightTargetPosition:rC,lightViewPosition:nC,lightingContext:Pw,lights:(e=[])=>(new uC).setLights(e),linearDepth:qw,linearToneMapping:VN,localId:xE,log:Ef,log2:Cf,logarithmicDepthToViewZ:(e,t,s)=>{const i=e.mul(Ef(s.div(t)));return Ap(Math.E).pow(i).mul(t).negate()},luminance:RN,mat2:Gp,mat3:jp,mat4:$p,matcapUV:zS,materialAO:Q_,materialAlphaTest:f_,materialAnisotropy:D_,materialAnisotropyVector:K_,materialAttenuationColor:G_,materialAttenuationDistance:U_,materialClearcoat:E_,materialClearcoatNormal:R_,materialClearcoatRoughness:C_,materialColor:g_,materialDispersion:Y_,materialEmissive:b_,materialEnvIntensity:yx,materialEnvRotation:bx,materialIOR:k_,materialIridescence:L_,materialIridescenceIOR:F_,materialIridescenceThickness:O_,materialLightMap:Z_,materialLineDashOffset:q_,materialLineDashSize:$_,materialLineGapSize:W_,materialLineScale:j_,materialLineWidth:H_,materialMetalness:A_,materialNormal:N_,materialOpacity:x_,materialPointSize:X_,materialReference:Bx,materialReflectivity:S_,materialRefractionRatio:gx,materialRotation:P_,materialRoughness:M_,materialSheen:B_,materialSheenRoughness:I_,materialShininess:y_,materialSpecular:__,materialSpecularColor:v_,materialSpecularIntensity:w_,materialSpecularStrength:T_,materialThickness:V_,materialTransmission:z_,max:rg,maxMipLevel:jy,mediumpModelViewMatrix:Ub,metalness:em,min:ig,mix:bg,mixElement:Mg,mod:Hm,modInt:mf,modelDirection:Bb,modelNormalMatrix:zb,modelPosition:Db,modelRadius:Ob,modelScale:Lb,modelViewMatrix:kb,modelViewPosition:Fb,modelViewProjection:J_,modelWorldMatrix:Ib,modelWorldMatrixInverse:Vb,morphReference:Nw,mrt:qM,mul:$m,mx_aastep:FR,mx_add:(e,t=Ap(0))=>Gm(e,t),mx_atan2:(e=Ap(0),t=Ap(1))=>Uf(e,t),mx_cell_noise_float:(e=Vy())=>bR(e.convert("vec2|vec3")),mx_contrast:(e,t=1,s=.5)=>Ap(e).sub(s).mul(t).add(s),mx_divide:(e,t=Ap(1))=>Wm(e,t),mx_fractal_noise_float:(e=Vy(),t=3,s=2,i=.5,r=1)=>_R(e,Np(t),s,i).mul(r),mx_fractal_noise_vec2:(e=Vy(),t=3,s=2,i=.5,r=1)=>vR(e,Np(t),s,i).mul(r),mx_fractal_noise_vec3:(e=Vy(),t=3,s=2,i=.5,r=1)=>wR(e,Np(t),s,i).mul(r),mx_fractal_noise_vec4:(e=Vy(),t=3,s=2,i=.5,r=1)=>TR(e,Np(t),s,i).mul(r),mx_frame:()=>_A,mx_heighttonormal:(e,t)=>(e=Dp(e),t=Ap(t),d_(e,t)),mx_hsvtorgb:IR,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=Ap(1))=>jm(t,e),mx_modulo:(e,t=Ap(1))=>Hm(e,t),mx_multiply:(e,t=Ap(1))=>$m(e,t),mx_noise_float:(e=Vy(),t=1,s=0)=>gR(e.convert("vec2|vec3")).mul(t).add(s),mx_noise_vec3:(e=Vy(),t=1,s=0)=>yR(e.convert("vec2|vec3")).mul(t).add(s),mx_noise_vec4:(e=Vy(),t=1,s=0)=>{e=e.convert("vec2|vec3");return zp(yR(e),gR(e.add(Rp(19,73)))).mul(t).add(s)},mx_place2d:(e,t=Rp(.5,.5),s=Rp(1,1),i=Ap(0),r=Rp(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=Rp(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=Ap(1))=>cg(e,t),mx_ramp4:(e,t,s,i,r=Vy())=>{const n=r.x.clamp(),o=r.y.clamp(),a=bg(e,t,n),l=bg(s,i,n);return bg(a,l,o)},mx_ramplr:(e,t,s=Vy())=>OR(e,t,s,"x"),mx_ramptb:(e,t,s=Vy())=>OR(e,t,s,"y"),mx_rgbtohsv:DR,mx_rotate2d:(e,t)=>{e=Rp(e);const s=(t=Ap(t)).mul(Math.PI/180);return GS(e,s)},mx_rotate3d:(e,t,s)=>{e=Dp(e),t=Ap(t),s=Dp(s);const i=t.mul(Math.PI/180),r=s.normalize(),n=i.cos(),o=i.sin(),a=Ap(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=Ap(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=Vy())=>zR(e,t,s,i,"x"),mx_splittb:(e,t,s,i=Vy())=>zR(e,t,s,i,"y"),mx_srgb_texture_to_lin_rec709:LR,mx_subtract:(e,t=Ap(0))=>jm(e,t),mx_timer:()=>bA,mx_transform_uv:(e=1,t=0,s=Vy())=>s.mul(e).add(t),mx_unifiednoise2d:(e,t=Vy(),s=Rp(1,1),i=Rp(0,0),r=1,n=0,o=1,a=!1,l=1,h=2,u=.5)=>PR(e,t.convert("vec2|vec3"),s,i,r,n,o,a,l,h,u),mx_unifiednoise3d:(e,t=Vy(),s=Rp(1,1),i=Rp(0,0),r=1,n=0,o=1,a=!1,l=1,h=2,u=.5)=>BR(e,t.convert("vec2|vec3"),s,i,r,n,o,a,l,h,u),mx_worley_noise_float:(e=Vy(),t=1)=>ER(e.convert("vec2|vec3"),t,Np(1)),mx_worley_noise_vec2:(e=Vy(),t=1)=>CR(e.convert("vec2|vec3"),t,Np(1)),mx_worley_noise_vec3:(e=Vy(),t=1)=>RR(e.convert("vec2|vec3"),t,Np(1)),negate:Wf,neutralToneMapping:XN,nodeArray:mp,nodeImmutable:gp,nodeObject:cp,nodeObjectIntent:dp,nodeObjects:pp,nodeProxy:fp,nodeProxyIntent:yp,normalFlat:ix,normalGeometry:tx,normalLocal:sx,normalMap:l_,normalView:ox,normalViewGeometry:rx,normalWorld:ax,normalWorldGeometry:nx,normalize:Df,not:tf,notEqual:Xm,numWorkgroups:gE,objectDirection:Mb,objectGroup:Pm,objectPosition:Nb,objectRadius:Rb,objectScale:Eb,objectViewPosition:Cb,objectWorldMatrix:Ab,oneMinus:Hf,or:ef,orthographicDepthToViewZ:(e,t,s)=>t.sub(s).mul(e).sub(t),oscSawtooth:(e=bA)=>e.fract(),oscSine:(e=bA)=>e.add(.75).mul(2*Math.PI).sin().mul(.5).add(.5),oscSquare:(e=bA)=>e.fract().round(),oscTriangle:(e=bA)=>e.add(.5).fract().mul(2).sub(1).abs(),output:gm,outputStruct:$M,overlay:(...e)=>(Ua('TSL: "overlay" has been renamed. Use "blendOverlay" instead.'),rv(e)),overloadingFn:yA,packHalf2x16:aA,packSnorm2x16:nA,packUnorm2x16:oA,parabola:iA,parallaxDirection:i_,parallaxUV:(e,t)=>e.sub(i_.mul(t)),parameter:(e,t)=>new zM(e,t),pass:(e,t,s)=>new ON(ON.COLOR,e,t,s),passTexture:(e,t)=>new LN(e,t),pcurve:(e,t,s)=>cg(Wm(cg(e,t),Gm(cg(e,t),cg(jm(1,e),s))),1/t),perspectiveDepthToViewZ:jw,pmremTexture:MS,pointShadow:$C,pointUV:lN,pointWidth:xm,positionGeometry:$b,positionLocal:Wb,positionPrevious:Hb,positionView:Yb,positionViewDirection:Zb,positionWorld:qb,positionWorldDirection:Xb,posterize:IN,pow:cg,pow2:dg,pow3:pg,pow4:mg,premultiplyAlpha:ov,property:Xp,quadBroadcast:KE,quadSwapDiagonal:HE,quadSwapX:$E,quadSwapY:WE,radians:Sf,rand:Sg,range:pE,rangeFog:function(e,t,s){return Ua('TSL: "rangeFog( color, near, far )" is deprecated. Use "fog( color, rangeFogFactor( near, far ) )" instead.'),hE(e,aE(t,s))},rangeFogFactor:aE,reciprocal:Zf,reference:Cx,referenceBuffer:Rx,reflect:og,reflectVector:wx,reflectView:xx,reflector:e=>new GA(e),refract:wg,refractVector:vx,refractView:_x,reinhardToneMapping:kN,remap:My,remapClamp:Ay,renderGroup:Rm,renderOutput:Py,rendererReference:ny,replaceDefaultUV:function(e,t=null){return Dg(t,{getUV:e})},rotate:GS,rotateUV:wA,roughness:Jp,round:Yf,rtt:ZA,sRGBTransferEOTF:Zg,sRGBTransferOETF:Qg,sample:(e,t=null)=>new sN(e,cp(t)),sampler:e=>(!0===e.isNode?e:qy(e)).convert("sampler"),samplerComparison:e=>(!0===e.isNode?e:qy(e)).convert("samplerComparison"),saturate:_g,saturation:NN,screen:(...e)=>(Ua('TSL: "screen" has been renamed. Use "blendScreen" instead.'),iv(e)),screenCoordinate:ab,screenDPR:rb,screenSize:ob,screenUV:nb,scriptable:nE,scriptableValue:eE,select:Bg,setCurrentStack:wp,setName:Fg,shaderStages:yd,shadow:PC,shadowPositionWorld:dC,shapeCircle:ZC,sharedUniformGroup:Em,sheen:im,sheenRoughness:rm,shiftLeft:lf,shiftRight:hf,shininess:fm,sign:jf,sin:Ff,sinc:(e,t)=>Ff(bf.mul(t.mul(e).sub(1))).div(bf.mul(t.mul(e).sub(1))),skinning:xw,smoothstep:vg,smoothstepElement:Ag,specularColor:dm,specularColorBlended:pm,specularF90:mm,spherizeUV:vA,split:(e,t)=>cp(new Nd(cp(e),t)),spritesheetUV:AA,sqrt:Rf,stack:kM,step:ng,stepElement:Ng,storage:iw,storageBarrier:()=>wE("storage").toStack(),storageObject:(e,t,s)=>(Ua('TSL: "storageObject()" is deprecated. Use "storage().setPBO( true )" instead.'),iw(e,t,s).setPBO(!0)),storageTexture:gN,string:(e="")=>new Bd(e,"string"),struct:(e,t=null)=>{const s=new UM(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 GM(s,i)};return i.layout=s,i.isStruct=!0,i},sub:jm,subBuild:Hg,subgroupAdd:RE,subgroupAll:UE,subgroupAnd:FE,subgroupAny:GE,subgroupBallot:CE,subgroupBroadcast:qE,subgroupBroadcastFirst:jE,subgroupElect:EE,subgroupExclusiveAdd:BE,subgroupExclusiveMul:LE,subgroupInclusiveAdd:PE,subgroupInclusiveMul:DE,subgroupIndex:aw,subgroupMax:kE,subgroupMin:VE,subgroupMul:IE,subgroupOr:OE,subgroupShuffle:XE,subgroupShuffleDown:QE,subgroupShuffleUp:ZE,subgroupShuffleXor:YE,subgroupSize:_E,subgroupXor:zE,tan:zf,tangentGeometry:qx,tangentLocal:Xx,tangentView:Yx,tangentWorld:Zx,texture:qy,texture3D:xN,texture3DLevel:(e,t,s)=>xN(e,t).level(s),texture3DLoad:(...e)=>xN(...e).setSampler(!1),textureBarrier:()=>wE("texture").toStack(),textureBicubic:bT,textureBicubicLevel:yT,textureCubeUV:YT,textureLevel:(e,t,s)=>qy(e,t).level(s),textureLoad:Xy,textureSize:Uy,textureStore:(e,t,s)=>{const i=gN(e,t,s);return null!==s&&i.toStack(),i},thickness:vm,time:bA,toneMapping:ay,toneMappingExposure:ly,toonOutlinePass:(e,t,s=new Hh(0,0,0),i=.003,r=1)=>cp(new zN(e,t,cp(s),cp(i),cp(r))),transformDirection:fg,transformNormal:hx,transformNormalToView:ux,transformedClearcoatNormalView:px,transformedNormalView:cx,transformedNormalWorld:dx,transmission:wm,transpose:Jf,triNoise3D:mA,triplanarTexture:(...e)=>NA(...e),triplanarTextures:NA,trunc:Qf,uint:Ep,uintBitsToFloat:e=>new XM(e,"float","uint"),uniform:Im,uniformArray:Jy,uniformCubeTexture:(e=Tx)=>Mx(e),uniformFlow:Lg,uniformGroup:Nm,uniformTexture:(e=$y)=>qy(e),unpackHalf2x16:cA,unpackNormal:o_,unpackSnorm2x16:hA,unpackUnorm2x16:uA,unpremultiplyAlpha:av,userData:(e,t,s)=>new _N(e,t,s),uv:Vy,uvec2:Bp,uvec3:Fp,uvec4:kp,varying:Xg,varyingProperty:Yp,vec2:Rp,vec3:Dp,vec4:zp,vectorComponents:bd,velocity:MN,vertexColor:ev,vertexIndex:nw,vertexStage:Yg,vibrance:EN,viewZToLogarithmicDepth:$w,viewZToOrthographicDepth:Uw,viewZToPerspectiveDepth:Gw,viewport:lb,viewportCoordinate:ub,viewportDepthTexture:Vw,viewportLinearDepth:Xw,viewportMipTexture:Fw,viewportResolution:db,viewportSafeUV:SA,viewportSharedTexture:fv,viewportSize:hb,viewportTexture:Lw,viewportUV:cb,vogelDiskSample:tN,wgsl:(e,t)=>ZN(e,t,"wgsl"),wgslFn:(e,t)=>KN(e,t,"wgsl"),workgroupArray:(e,t)=>new TE("Workgroup",e,t),workgroupBarrier:()=>wE("workgroup").toStack(),workgroupId:yE,workingToColorSpace:ey,xor:sf});const GR=new OM;class jR extends rM{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(GR),GR.a=i._clearColor.a;else if(!0===r.isColor)r.getRGB(GR),GR.a=1,n=!0;else if(!0===r.isNode){const s=this.get(e),n=r;GR.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=zp(n).mul(pN).context({getUV:()=>mN.mul(nx),getTextureLevel:()=>dN}),i=gb.element(3).element(3).equal(1),a=Wm(1,gb.element(1).element(1)).mul(3),l=i.select(Wb.mul(a),Wb);let h=gb.mul(kb.mul(zp(l,0)));h=h.setZ(h.w);const u=new lv;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 Eu(new gc(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=zp(n).mul(pN),s.backgroundMeshNode.needsUpdate=!0,o.material.needsUpdate=!0,s.backgroundCacheKey=a),t.unshift(o,o.geometry,o.material,0,0,null,null)}else Ga("Renderer: Unsupported background configuration.",r);const o=i.xr.getEnvironmentBlendMode();if("additive"===o?GR.set(0,0,0,1):"alpha-blend"===o&&GR.set(0,0,0,0),!0===i.autoClear||!0===n){const e=s.clearColorValue;e.r=GR.r,e.g=GR.g,e.b=GR.b,e.a=GR.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 $R=0;class WR{constructor(e="",t=[],s=0,i=[]){this.name=e,this.bindings=t,this.index=s,this.bindingsReference=i,this.id=$R++}}class HR{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 WR(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 qR{constructor(e,t,s=null){this.isNodeAttribute=!0,this.name=e,this.type=t,this.node=s}}class XR{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 YR{constructor(e,t,s=!1,i=null){this.isNodeVar=!0,this.name=e,this.type=t,this.readOnly=s,this.count=i}}class ZR extends YR{constructor(e,t,s=null,i=null){super(e,t),this.needsInterpolation=!1,this.isNodeVarying=!0,this.interpolationType=s,this.interpolationSampling=i}}class QR{constructor(e,t,s=""){this.name=e,this.type=t,this.code=s,Object.defineProperty(this,"isNodeCode",{value:!0})}}let KR=0;class JR{constructor(e=null){this.id=KR++,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 eP{constructor(e,t){this.name=e,this.members=t,this.output=!1}}class tP{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 sP extends tP{constructor(e,t=0){super(e,t),this.isNumberUniform=!0,this.boundary=4,this.itemSize=1}}class iP extends tP{constructor(e,t=new sl){super(e,t),this.isVector2Uniform=!0,this.boundary=8,this.itemSize=2}}class rP extends tP{constructor(e,t=new rl){super(e,t),this.isVector3Uniform=!0,this.boundary=16,this.itemSize=3}}class nP extends tP{constructor(e,t=new Tl){super(e,t),this.isVector4Uniform=!0,this.boundary=16,this.itemSize=4}}class oP extends tP{constructor(e,t=new Hh){super(e,t),this.isColorUniform=!0,this.boundary=16,this.itemSize=3}}class aP extends tP{constructor(e,t=new Wc){super(e,t),this.isMatrix2Uniform=!0,this.boundary=8,this.itemSize=4}}class lP extends tP{constructor(e,t=new al){super(e,t),this.isMatrix3Uniform=!0,this.boundary=48,this.itemSize=12}}class hP extends tP{constructor(e,t=new eh){super(e,t),this.isMatrix4Uniform=!0,this.boundary=64,this.itemSize=16}}class uP extends sP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class cP extends iP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class dP extends rP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class pP extends nP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class mP extends oP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class fP extends aP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class gP extends lP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}class yP extends hP{constructor(e){super(e.name,e.value),this.nodeUniform=e}getValue(){return this.nodeUniform.value}getType(){return this.nodeUniform.type}}let bP=0;const xP=new WeakMap,_P=new WeakMap,wP=new Map([[Int8Array,"int"],[Int16Array,"int"],[Int32Array,"int"],[Uint8Array,"uint"],[Uint16Array,"uint"],[Uint32Array,"uint"],[Float32Array,"float"]]),vP=e=>/e/g.test(e)?String(e).replace(/\+/g,""):(e=Number(e))+(e%1?"":".0");class TP{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=kM(),this.stacks=[],this.tab="\t",this.currentFunctionNode=null,this.context={material:this.material},this.cache=new JR,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:bP++})}isOpaque(){const e=this.material;return!1===e.transparent&&1===e.blending&&!1===e.alphaToCoverage}getBindGroupsCache(){let e=_P.get(this.renderer);return void 0===e&&(e=new JS,_P.set(this.renderer,e)),e}createRenderTarget(e,t,s){return new Sl(e,t,s)}createCubeRenderTarget(e,t){return new xv(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 WR(e,i,this.bindingsIndexes[e].group,i),s.set(i,r))):r=new WR(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 yd)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()!==pd.NONE&&this.updateNodes.push(e)}for(const e of this.sequentialNodes){const t=e.getUpdateBeforeType(),s=e.getUpdateAfterType();t!==pd.NONE&&this.updateBeforeNodes.push(e),s!==pd.NONE&&this.updateAfterNodes.push(e)}}get currentNode(){return this.chaining[this.chaining.length-1]}isFilteredTexture(e){return e.magFilter===uo||e.magFilter===co||e.magFilter===ho||e.magFilter===po||e.minFilter===uo||e.minFilter===co||e.minFilter===ho||e.minFilter===po}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 JR(t?this.getCache():null)),s.cache}isAvailable(){return!1}getVertexIndex(){Ua("Abstract function.")}getInstanceIndex(){Ua("Abstract function.")}getDrawIndex(){Ua("Abstract function.")}getFrontFacing(){Ua("Abstract function.")}getFragCoord(){Ua("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(){Ua("Abstract function.")}generateTextureLod(){Ua("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 Hh:"vec2"===e||"uvec2"===e||"ivec2"===e?t=new sl:"vec3"===e||"uvec3"===e||"ivec3"===e?t=new rl:"vec4"!==e&&"uvec4"!==e&&"ivec4"!==e||(t=new Tl)),"float"===e)return vP(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")}( ${vP(t.r)}, ${vP(t.g)}, ${vP(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 qR(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===bo)return"int";if(t===xo)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=sd(e);const i="float"===t?"":t[0];return!0===/mat2/.test(t)&&(s=s.replace("vec","mat")),i+s}getTypeFromArray(e){return wP.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 au||!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=kM(this.stack);const e=vp();return this.stacks.push(e),wp(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,wp(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 qR("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 eP(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 XR(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 YR(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 ZR(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,Ua(`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 QR("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 QN,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 zM(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 JR,this.stack=kM();for(const s of gd)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(){Ua("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(){Ua("Abstract function.")}getVaryings(){Ua("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(){Ua("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(){Ua("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&&(Ga(`NodeMaterial: Material "${t.type}" is not compatible.`),e=new lv),e.build(this)}else this.addFlow("compute",e);for(const e of gd){this.setBuildStage(e),this.context.vertex&&this.context.vertex.isNode&&this.flowNodeFromShaderStage("vertex",this.context.vertex);for(const t of yd){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=xP.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 uP(e);else if("vec2"===t||"ivec2"===t||"uvec2"===t)i=new cP(e);else if("vec3"===t||"ivec3"===t||"uvec3"===t)i=new dP(e);else if("vec4"===t||"ivec4"===t||"uvec4"===t)i=new pP(e);else if("color"===t)i=new mP(e);else if("mat2"===t)i=new fP(e);else if("mat3"===t)i=new gP(e);else{if("mat4"!==t)throw new Error(`Uniform "${t}" not implemented.`);i=new yP(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${Un} - Node System\n`}}class SP{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===pd.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===pd.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===pd.OBJECT&&e.updateBefore(this)}updateAfterNode(e){const t=e.getUpdateAfterType(),s=e.updateReference(this);if(t===pd.FRAME){const t=this._getMaps(this.updateAfterMap,s);t.frameId!==this.frameId&&!1!==e.updateAfter(this)&&(t.frameId=this.frameId)}else if(t===pd.RENDER){const t=this._getMaps(this.updateAfterMap,s);t.renderId!==this.renderId&&!1!==e.updateAfter(this)&&(t.renderId=this.renderId)}else t===pd.OBJECT&&e.updateAfter(this)}updateNode(e){const t=e.getUpdateType(),s=e.updateReference(this);if(t===pd.FRAME){const t=this._getMaps(this.updateMap,s);t.frameId!==this.frameId&&!1!==e.update(this)&&(t.frameId=this.frameId)}else if(t===pd.RENDER){const t=this._getMaps(this.updateMap,s);t.renderId!==this.renderId&&!1!==e.update(this)&&(t.renderId=this.renderId)}else t===pd.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 MP{constructor(e,t,s=null,i="",r=!1){this.type=e,this.name=t,this.count=s,this.qualifier=i,this.isConst=r}}MP.isNodeFunctionInput=!0;class AP extends WC{static get type(){return"DirectionalLightNode"}constructor(e=null){super(e)}setupDirect(){const e=this.colorNode;return{lightDirection:oC(this.light),lightColor:e}}}const NP=new eh,EP=new eh;let CP=null;class RP extends WC{static get type(){return"RectAreaLightNode"}constructor(e=null){super(e),this.halfHeight=Im(new rl).setGroup(Rm),this.halfWidth=Im(new rl).setGroup(Rm),this.updateType=pd.RENDER}update(e){super.update(e);const{light:t}=this,s=e.camera.matrixWorldInverse;EP.identity(),NP.copy(t.matrixWorld),NP.premultiply(s),EP.extractRotation(NP),this.halfWidth.value.set(.5*t.width,0,0),this.halfHeight.value.set(0,.5*t.height,0),this.halfWidth.value.applyMatrix4(EP),this.halfHeight.value.applyMatrix4(EP)}setupDirectRectArea(e){let t,s;e.isAvailable("float32Filterable")?(t=qy(CP.LTC_FLOAT_1),s=qy(CP.LTC_FLOAT_2)):(t=qy(CP.LTC_HALF_1),s=qy(CP.LTC_HALF_2));const{colorNode:i,light:r}=this;return{lightColor:i,lightPosition:nC(r),halfWidth:this.halfWidth,halfHeight:this.halfHeight,ltc_1:t,ltc_2:s}}static setLTC(e){CP=e}}class PP extends WC{static get type(){return"SpotLightNode"}constructor(e=null){super(e),this.coneCosNode=Im(0).setGroup(Rm),this.penumbraCosNode=Im(0).setGroup(Rm),this.cutoffDistanceNode=Im(0).setGroup(Rm),this.decayExponentNode=Im(0).setGroup(Rm),this.colorNode=Im(this.color).setGroup(Rm)}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 vg(s,i,t)}getLightCoord(e){const t=e.getNodeProperties(this);let s=t.projectionUV;return void 0===s&&(s=sC(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(oC(r)),l=this.getSpotAttenuation(e,a),h=n.length(),u=HC({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=qy(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 BP extends PP{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=qy(s,Rp(e,0),0).r}else i=super.getSpotAttenuation(t);return i}}const IP=_p(([e,t])=>{const s=e.abs().sub(t);return $f(rg(s,0)).add(ig(rg(s.x,s.y),0))});class DP extends PP{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=Ap(0),s=this.penumbraCosNode,i=tC(this.light).mul(e.context.positionWorld||qb);return Tp(i.w.greaterThan(0),()=>{const e=i.xyz.div(i.w),r=IP(e.xy.sub(Rp(.5)),Rp(.5)),n=Wm(-1,jm(1,kf(s)).sub(1));t.assign(_g(r.mul(-2).mul(n)))}),t}}class LP extends WC{static get type(){return"AmbientLightNode"}constructor(e=null){super(e)}setup({context:e}){e.irradiance.addAssign(this.colorNode)}}class FP extends WC{static get type(){return"HemisphereLightNode"}constructor(e=null){super(e),this.lightPositionNode=iC(e),this.lightDirectionNode=this.lightPositionNode.normalize(),this.groundColorNode=Im(new Hh).setGroup(Rm)}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=ax.dot(i).mul(.5).add(.5),n=bg(s,t,r);e.context.irradiance.addAssign(n)}}class OP extends WC{static get type(){return"LightProbeNode"}constructor(e=null){super(e);const t=[];for(let e=0;e<9;e++)t.push(new rl);this.lightProbe=Jy(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=kR(ax,this.lightProbe);e.context.irradiance.addAssign(t)}}class zP{parseFunction(){Ua("Abstract function.")}}class VP{constructor(e,t,s="",i=""){this.type=e,this.inputs=t,this.name=s,this.precision=i}getCode(){Ua("Abstract function.")}}VP.isNodeFunction=!0;const kP=/^\s*(highp|mediump|lowp)?\s*([a-z_0-9]+)\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)/i,UP=/[a-z_0-9]+/gi,GP="#pragma main";class jP extends VP{constructor(e){const{type:t,inputs:s,name:i,precision:r,inputsCode:n,blockCode:o,headerCode:a}=(e=>{const t=(e=e.trim()).indexOf(GP),s=-1!==t?e.slice(t+12):e,i=s.match(kP);if(null!==i&&5===i.length){const r=i[4],n=[];let o=null;for(;null!==(o=UP.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 MP(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 $P extends zP{parseFunction(e){return new jP(e)}}const WP=new WeakMap,HP=[],qP=[];class XP extends rM{constructor(e,t){super(),this.renderer=e,this.backend=t,this.nodeFrame=new SP,this.nodeBuilderCache=new Map,this.callHashCache=new JS,this.groupsData=new JS,this.cacheLib={}}updateGroup(e){const t=e.groupNode,s=t.name;if(s===Pm.name)return!0;if(s===Rm.name){const t=this.get(e),s=this.nodeFrame.renderId;return t.renderId!==s&&(t.renderId=s,!0)}if(s===Cm.name){const t=this.get(e),s=this.nodeFrame.frameId;return t.frameId!==s&&(t.frameId=s,!0)}HP[0]=t,HP[1]=e;let i=this.groupsData.get(HP);return void 0===i&&this.groupsData.set(HP,i={}),HP.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 lv),n.build(),Ga("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 HR(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){HP[0]=e,HP[1]=t;const s=this.renderer.info.calls,i=this.callHashCache.get(HP)||{};if(i.callId!==s){const r=this.getEnvironmentNode(e),n=this.getFogNode(e);t&&qP.push(t.getCacheKey(!0)),r&&qP.push(r.getCacheKey()),n&&qP.push(n.getCacheKey()),qP.push(this.renderer.getOutputRenderTarget()&&this.renderer.getOutputRenderTarget().multiview?1:0),qP.push(this.renderer.shadowMap.enabled?1:0),qP.push(this.renderer.shadowMap.type),i.callId=s,i.cacheKey=Kc(qP),this.callHashCache.set(HP,i),qP.length=0}return HP.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 MS(s);{let e;return e=!0===s.isCubeTexture?Ax(s):qy(s),Sv(e)}}if(!0===s.isTexture)return qy(s,nb.flipY()).setUpdateMatrix(!0);!0!==s.isColor&&Ga("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=Cx("color","color",s).setGroup(Rm),t=Cx("density","float",s).setGroup(Rm);return hE(e,lE(t))}if(s.isFog){const e=Cx("color","color",s).setGroup(Rm),t=Cx("near","float",s).setGroup(Rm),i=Cx("far","float",s).setGroup(Rm);return hE(e,aE(t,i))}Ga("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?Ax(s):!0===s.isTexture?qy(s):void Ga("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 WP.get(e)!==this.getOutputCacheKey()}getOutputNode(e){const t=this.renderer,s=this.getOutputCacheKey(),i=e.isArrayTexture?xN(e,Dp(nb,eb("gl_ViewID_OVR"))).renderOutput(t.toneMapping,t.currentColorSpace):qy(e,nb).renderOutput(t.toneMapping,t.currentColorSpace);return WP.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 SP,this.nodeBuilderCache=new Map,this.cacheLib={}}}const YP=new tc;class ZP{constructor(e=null){this.version=0,this.clipIntersection=null,this.cacheKey="",this.shadowPass=!1,this.viewNormalMatrix=new al,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++){YP.copy(e[r]).applyMatrix4(this.viewMatrix,this.viewNormalMatrix);const i=t[s+r],n=YP.normal;i.x=-n.x,i.y=-n.y,i.z=-n.z,i.w=YP.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 Tl;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 ZP(this),this.clippingGroupContexts.set(e,t)),t.update(this,e),t}get unionClippingCount(){return this.unionPlanes.length}}class QP{constructor(e,t){this.bundleGroup=e,this.camera=t}}const KP=[];class JP{constructor(){this.bundles=new JS}get(e,t){const s=this.bundles;KP[0]=e,KP[1]=t;let i=s.get(KP);return void 0===i&&(i=new QP(e,t),s.set(KP,i)),KP.length=0,i}dispose(){this.bundles=new JS}}class eB{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))Ua(`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))Ua(`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 tB=new uC,sB=[];class iB extends JS{constructor(){super()}createNode(e=[]){return(new uC).setLights(e)}getNode(e,t){if(e.isQuadMesh)return tB;sB[0]=e,sB[1]=t;let s=this.get(sB);return void 0===s&&(s=this.createNode(),this.set(sB,s)),sB.length=0,s}}class rB extends Sl{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 nB=new rl,oB=new rl;class aB extends $a{constructor(e,t=!1){super(),this.enabled=!1,this.isPresenting=!1,this.cameraAutoUpdate=!0,this._renderer=e,this._cameraL=new Ou,this._cameraL.viewport=new Tl,this._cameraR=new Ou,this._cameraR.viewport=new Tl,this._cameras=[this._cameraL,this._cameraR],this._cameraXR=new jc,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=dB.bind(this),this._gl=null,this._currentAnimationContext=null,this._currentAnimationLoop=null,this._currentPixelRatio=null,this._currentSize=new sl,this._onSessionEvent=hB.bind(this),this._onSessionEnd=uB.bind(this),this._onInputSourcesChange=cB.bind(this),this._onAnimationFrame=pB.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&&Ua("XRManager: Cannot change framebuffer scale while presenting.")}getReferenceSpaceType(){return this._referenceSpaceType}setReferenceSpaceType(e){this._referenceSpaceType=e,!0===this.isPresenting&&Ua("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 fc(e,t),h=new rB(r,n,{format:Eo,type:mo,depthTexture:new dc(r,n,a.stencil?So:xo,void 0,void 0,void 0,void 0,void 0,void 0,a.stencil?Ro:Co),stencilBuffer:a.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});h._autoAllocateDepthBuffer=!0;const u=new Zh({color:16777215,side:0});u.map=h.texture,u.map.offset.y=1,u.map.repeat.y=-1;const c=new Eu(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 Zh({color:16777215,side:0}),d.plane.material.blending=5,d.plane.material.blendEquation=Gn,d.plane.material.blendSrc=Wn,d.plane.material.blendDst=Wn,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 mc(e,e,e*t/s,64,64,!0,Math.PI-t/2,t),u=new rB(n,o,{format:Eo,type:mo,depthTexture:new dc(n,o,l.stencil?So:xo,void 0,void 0,void 0,void 0,void 0,void 0,l.stencil?Ro:Co),stencilBuffer:l.stencil,resolveDepthBuffer:!1,resolveStencilBuffer:!1});u._autoAllocateDepthBuffer=!0;const c=new Zh({color:16777215,side:1});c.map=u.texture,c.map.offset.y=1,c.map.repeat.y=-1;const d=new Eu(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 Zh({color:16777215,side:1}),p.plane.material.blending=5,p.plane.material.blendEquation=Gn,p.plane.material.blendSrc=Wn,p.plane.material.blendDst=Wn,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 rl,t=new il,s=this._renderer,i=this.isPresenting,r=s.getOutputRenderTarget(),n=s._frameBufferTarget;this.isPresenting=!1;const o=new sl;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 qA(new lv),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?Ro:Co,n=t.stencil?So:xo);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 dc(l.textureWidth,l.textureHeight,n,void 0,void 0,void 0,void 0,void 0,void 0,s,u);if(this._xrRenderTarget=new rB(l.textureWidth,l.textureHeight,{format:Eo,type:mo,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 Zh({color:16777215,side:"cylinder"===e.type?1:0}),e.plane.material.blending=5,e.plane.material.blendEquation=Gn,e.plane.material.blendSrc=Wn,e.plane.material.blendDst=Wn,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 rB(r.framebufferWidth,r.framebufferHeight,{format:Eo,type:mo,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;lB(r,a);for(let e=0;e<l.length;e++)lB(l[e],a);2===l.length?function(e,t,s){nB.setFromMatrixPosition(t.matrixWorld),oB.setFromMatrixPosition(s.matrixWorld);const i=nB.distanceTo(oB),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*Xa*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 $u,this._controllers[e]=t),t}}function lB(e,t){null===t?e.matrixWorld.copy(e.matrix):e.matrixWorld.multiplyMatrices(t.matrixWorld,e.matrix),e.matrixWorldInverse.copy(e.matrixWorld).invert()}function hB(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 uB(){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 rB(e.pixelwidth,e.pixelheight,{format:Eo,type:mo,depthTexture:new dc(e.pixelwidth,e.pixelheight,e.stencilBuffer?So:xo,void 0,void 0,void 0,void 0,void 0,void 0,e.stencilBuffer?Ro:Co),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 cB(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 dB(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 pB(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 Ou,l.layers.enable(i),l.viewport=new Tl,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 mB extends $a{constructor(e){super(),this.domElement=e,this._pixelRatio=1,this._width=this.domElement.width,this._height=this.domElement.height,this._viewport=new Tl(0,0,this._width,this._height),this._scissor=new Tl(0,0,this._width,this._height),this._scissorTest=!1,this.colorTexture=new cc,this.depthTexture=new dc}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 fB=new Wu,gB=new sl,yB=new Tl,bB=new nc,xB=new lc,_B=new eh,wB=new Tl;class vB{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=wo,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=ya,this.toneMapping=0,this.toneMappingExposure=1,this.sortObjects=!0,this.depth=r,this.stencil=n,this.info=new mM,this.contextNode=Dg(),this.library=new eB,this.lighting=new iB,this._samples=a||!0===o?4:0,this._onCanvasTargetResize=this._onCanvasTargetResize.bind(this),this._canvasTarget=new mB(e.getDomElement()),this._canvasTarget.addEventListener("resize",this._onCanvasTargetResize),this._canvasTarget.isDefaultCanvasTarget=!0,this._inspector=new Dy,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 qA(new lv),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 OM(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 aB(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 XP(this,s),this._animation=new KS(this,this._nodes,this.info),this._attributes=new uM(s),this._background=new jR(this,this._nodes),this._geometries=new pM(this._attributes,this.info),this._textures=new FM(this,s,this.info),this._pipelines=new _M(s,this._nodes),this._bindings=new wM(s,this._nodes,this._textures,this._attributes,this._pipelines,this.info),this._objects=new iM(this,this._nodes,this._geometries,this._pipelines,this._bindings,this.info),this._renderLists=new NM(this.lighting),this._bundles=new JP,this._renderContexts=new DM,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:fB;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 ZP),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){ja('Renderer: "renderAsync()" has been deprecated. Use "render()" and "await renderer.init();" when creating the renderer.'),await this.init(),this.render(e,t)}async waitForGPU(){Ga("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=Gb,t.modelNormalViewMatrix=jb):this.highPrecision&&(delete t.modelViewMatrix,delete t.modelNormalViewMatrix)}get highPrecision(){const e=this.contextNode.value;return e.modelViewMatrix===Gb&&e.modelNormalViewMatrix===jb}setMRT(e){return this._mrt=e,this}getMRT(){return this._mrt}getOutputBufferType(){return this._outputBufferType}getColorBufferType(){return ja('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}`),Ga(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!==dl.workingColorSpace;if(!1===s&&!1===i)return null;const{width:r,height:n}=this.getDrawingBufferSize(gB),{depth:o,stencil:a}=this;let l=this._frameBufferTarget;null===l&&(l=new Sl(r,n,{depthBuffer:o,stencilBuffer:a,type:this._outputBufferType,format:Eo,colorSpace:dl.workingColorSpace,generateMipmaps:!1,minFilter:uo,magFilter:uo,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:fB,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,b=g._scissor,x=g._pixelRatio;null!==d&&(y=d.viewport,b=d.scissor,x=1),this.getDrawingBufferSize(gB),yB.set(0,0,gB.width,gB.height);const _=void 0===y.minDepth?0:y.minDepth,w=void 0===y.maxDepth?1:y.maxDepth;p.viewportValue.copy(y).multiplyScalar(x).floor(),p.viewportValue.width>>=c,p.viewportValue.height>>=c,p.viewportValue.minDepth=_,p.viewportValue.maxDepth=w,p.viewport=!1===p.viewportValue.equals(yB),p.scissorValue.copy(b).multiplyScalar(x).floor(),p.scissor=g._scissorTest&&!1===p.scissorValue.equals(yB),p.scissorValue.width>>=c,p.scissorValue.height>>=c,p.clippingContext||(p.clippingContext=new ZP),p.clippingContext.updateGlobal(l,t),l.onBeforeRender(this,e,t,d);const v=t.isArrayCamera?xB:bB;t.isArrayCamera||(_B.multiplyMatrices(t.projectionMatrix,t.matrixWorldInverse),v.setFromProjectionMatrix(_B,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=gB.width,p.height=gB.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(wB.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){ja('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(){ja('Renderer: "clearColorAsync()" has been deprecated. Use "clearColor()" and "await renderer.init();" when creating the renderer.'),this.clear(!0,!1,!1)}async clearDepthAsync(){ja('Renderer: "clearDepthAsync()" has been deprecated. Use "clearDepth()" and "await renderer.init();" when creating the renderer.'),this.clear(!1,!0,!1)}async clearStencilAsync(){ja('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!==dl.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:dl.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 Ua("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 ja('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){ja('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=wB.set(t.x,t.y,e.image.width,e.image.height).floor();else{if(!t.isVector4)return void Ga("Renderer.copyFramebufferToTexture: Invalid rectangle.");t=wB.copy(t).floor()}else t=wB.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?xB:bB;if(!e.frustumCulled||n.intersectsSprite(e,t)){!0===this.sortObjects&&wB.setFromMatrixPosition(e.matrixWorld).applyMatrix4(_B);const{geometry:t,material:n}=e;n.visible&&i.push(e,t,n,s,wB.z,null,r)}}else if(e.isLineLoop)Ga("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?xB:bB;if(!e.frustumCulled||n.intersectsObject(e,t)){const{geometry:t,material:n}=e;if(!0===this.sortObjects&&(null===t.boundingSphere&&t.computeBoundingSphere(),wB.copy(t.boundingSphere.center).applyMatrix4(e.matrixWorld).applyMatrix4(_B)),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,wB.z,l,r)}}else n.visible&&i.push(e,t,n,s,wB.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=Dp(0),s=Ap(1)),i&&(s=s.mul(Cx("map","texture",e).a)),r&&(s=s.mul(e.colorNode.a)),a=zp(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 TB{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 SB=class extends TB{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)+(hM-e%hM)%hM;var e}get buffer(){return this._buffer}update(){return!0}};class MB extends SB{constructor(e,t=null){super(e,t),this.isUniformBuffer=!0}}let AB=0;class NB extends MB{constructor(e,t){super("UniformBuffer_"+AB++,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 EB extends MB{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%hM,a=o%r,l=o+a;t+=a,0!==l&&hM-l<n&&(t+=hM-l),i.offset=t/e,t+=n}return Math.ceil(t/hM)*hM}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 Ga("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 CB=0;class RB extends EB{constructor(e,t){super(e),this.id=CB++,this.groupNode=t,this.isNodeUniformsGroup=!0}}class PB extends TB{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 BB=0;class IB extends PB{constructor(e,t){super(e,t),this.id=BB++,this.store=!1,this.mipLevel=0,this.isSampledTexture=!0}}class DB extends IB{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 LB extends DB{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledCubeTexture=!0}}class FB extends DB{constructor(e,t,s,i=null){super(e,t,s,i),this.isSampledTexture3D=!0}}const OB={bitcast_int_uint:new YN("uint tsl_bitcast_int_to_uint ( int x ) { return floatBitsToUint( intBitsToFloat ( x ) ); }"),bitcast_uint_int:new YN("uint tsl_bitcast_uint_to_int ( uint x ) { return floatBitsToInt( uintBitsToFloat ( x ) ); }")},zB={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"},VB={low:"lowp",medium:"mediump",high:"highp"},kB={swizzleAssign:!0,storageBuffer:!1},UB={perspective:"smooth",linear:"noperspective"},GB={centroid:"centroid"},jB="\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 $B extends TP{constructor(e,t){super(e,t,new $P),this.uniformGroups={},this.transforms=[],this.extensions={},this.builtins={vertex:[],fragment:[],compute:[]}}needsToWorkingColorSpace(e){return!0===e.isVideoTexture&&e.colorSpace!==ga}_include(e){const t=OB[e];return t.build(this),this.addInclude(t),t}getMethod(e){return void 0!==OB[e]&&this._include(e),zB[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?Bo:Po;2===i?n=r?Do:Io:3===i?n=r?1032:No:4===i&&(n=r?Lo:Eo);const o={Float32Array:_o,Uint8Array:mo,Uint16Array:yo,Uint32Array:xo,Int8Array:fo,Int16Array:go,Int32Array:bo,Uint8ClampedArray:mo},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 Zu(t.array,a,l,n,o[t.array.constructor.name]||_o);c.needsUpdate=!0,c.isPBOTexture=!0;const d=new Wy(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="."+bd.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===xo?m="uvec4":i.pbo.type===bo&&(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} ) )`;Ga(`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===xo?s="u":e.type===bo&&(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=VB[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!==bo){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+=`${UB[i.interpolationType]||i.interpolationType} ${GB[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+=`${UB[e.interpolationType]||e.interpolationType} ${GB[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(){Ga("GLSLNodeBuilder: WebGLBackend does not support the subgroupSize node")}getInvocationSubgroupIndex(){Ga("GLSLNodeBuilder: WebGLBackend does not support the invocationSubgroupIndex node")}getSubgroupIndex(){Ga("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=kB[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)}kB[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${jB}\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${jB}\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 DB(r.name,r.node,i),l.push(o);else if("cubeTexture"===t||"cubeDepthTexture"===t)o=new LB(r.name,r.node,i),l.push(o);else if("texture3D"===t)o=new FB(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 NB(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 RB(s+"_"+a,i),e[a]=n,l.push(n)),o=this.getNodeUniform(r,t),n.addUniform(o)}n.uniformGPU=o}return r}}let WB=null,HB=null;class qB{constructor(e={}){this.parameters=Object.assign({},e),this.data=new WeakMap,this.renderer=null,this.domElement=null,this.timestampQueryPool={[La]:null,[Da]: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:")?Da:La;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 ja("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 WB=WB||new sl,this.renderer.getDrawingBufferSize(WB)}setScissorTest(){}getClearColor(){const e=this.renderer;return HB=HB||new OM,e.getClearColor(HB),HB.getRGB(HB),HB}getDomElement(){let e=this.domElement;return null===e&&(e=void 0!==this.parameters.canvas?this.parameters.canvas:function(){const e=za("canvas");return e.style.display="block",e}(),"setAttribute"in e&&e.setAttribute("data-engine",`three.js r${Un} 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 XB,YB,ZB=0;class QB{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 KB{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===bo,id:ZB++};if(e.isStorageBufferAttribute||e.isStorageInstancedBufferAttribute){const e=this._createBuffer(i,t,r,n);u=new QB(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 JB{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;XB={[Gn]:e.FUNC_ADD,[jn]:e.FUNC_SUBTRACT,[$n]:e.FUNC_REVERSE_SUBTRACT},YB={[Wn]:e.ZERO,[Hn]:e.ONE,[qn]:e.SRC_COLOR,[Yn]:e.SRC_ALPHA,[to]:e.SRC_ALPHA_SATURATE,[Jn]:e.DST_COLOR,[Qn]:e.DST_ALPHA,[Xn]:e.ONE_MINUS_SRC_COLOR,[Zn]:e.ONE_MINUS_SRC_ALPHA,[eo]:e.ONE_MINUS_DST_COLOR,[Kn]:e.ONE_MINUS_DST_ALPHA};const t=e.getParameter(e.SCISSOR_BOX),s=e.getParameter(e.VIEWPORT);this.currentScissor=(new Tl).fromArray(t),this.currentViewport=(new Tl).fromArray(s),this._tempVec4=new Tl}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(XB[t],XB[r]),this.currentBlendEquation=t,this.currentBlendEquationAlpha=r),s===this.currentBlendSrc&&i===this.currentBlendDst&&n===this.currentBlendSrcAlpha&&o===this.currentBlendDstAlpha||(l.blendFuncSeparate(YB[s],YB[i],YB[n],YB[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===Gn&&this.currentBlendEquationAlpha===Gn||(l.blendEquation(l.FUNC_ADD),this.currentBlendEquation=Gn,this.currentBlendEquationAlpha=Gn),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:Ga("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:Ga("WebGLState: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:Ga("WebGLState: MultiplyBlending requires material.premultipliedAlpha = true");break;default:Ga("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 eI{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=dl.getTransfer(t);if(e===mo)return s.UNSIGNED_BYTE;if(e===vo)return s.UNSIGNED_SHORT_4_4_4_4;if(e===To)return s.UNSIGNED_SHORT_5_5_5_1;if(e===Mo)return s.UNSIGNED_INT_5_9_9_9_REV;if(e===Ao)return s.UNSIGNED_INT_10F_11F_11F_REV;if(e===fo)return s.BYTE;if(e===go)return s.SHORT;if(e===yo)return s.UNSIGNED_SHORT;if(e===bo)return s.INT;if(e===xo)return s.UNSIGNED_INT;if(e===_o)return s.FLOAT;if(e===wo)return s.HALF_FLOAT;if(1021===e)return s.ALPHA;if(e===No)return s.RGB;if(e===Eo)return s.RGBA;if(e===Co)return s.DEPTH_COMPONENT;if(e===Ro)return s.DEPTH_STENCIL;if(e===Po)return s.RED;if(e===Bo)return s.RED_INTEGER;if(e===Io)return s.RG;if(e===Do)return s.RG_INTEGER;if(e===Lo)return s.RGBA_INTEGER;if(e===Fo||e===Oo||e===zo||e===Vo)if(n===_a){if(r=i.get("WEBGL_compressed_texture_s3tc_srgb"),null===r)return null;if(e===Fo)return r.COMPRESSED_SRGB_S3TC_DXT1_EXT;if(e===Oo)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT1_EXT;if(e===zo)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT3_EXT;if(e===Vo)return r.COMPRESSED_SRGB_ALPHA_S3TC_DXT5_EXT}else{if(r=i.get("WEBGL_compressed_texture_s3tc"),null===r)return null;if(e===Fo)return r.COMPRESSED_RGB_S3TC_DXT1_EXT;if(e===Oo)return r.COMPRESSED_RGBA_S3TC_DXT1_EXT;if(e===zo)return r.COMPRESSED_RGBA_S3TC_DXT3_EXT;if(e===Vo)return r.COMPRESSED_RGBA_S3TC_DXT5_EXT}if(e===ko||e===Uo||e===Go||e===jo){if(r=i.get("WEBGL_compressed_texture_pvrtc"),null===r)return null;if(e===ko)return r.COMPRESSED_RGB_PVRTC_4BPPV1_IMG;if(e===Uo)return r.COMPRESSED_RGB_PVRTC_2BPPV1_IMG;if(e===Go)return r.COMPRESSED_RGBA_PVRTC_4BPPV1_IMG;if(e===jo)return r.COMPRESSED_RGBA_PVRTC_2BPPV1_IMG}if(e===$o||e===Wo||e===Ho||e===qo||e===Xo||e===Yo||e===Zo){if(r=i.get("WEBGL_compressed_texture_etc"),null===r)return null;if(e===$o||e===Wo)return n===_a?r.COMPRESSED_SRGB8_ETC2:r.COMPRESSED_RGB8_ETC2;if(e===Ho)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ETC2_EAC:r.COMPRESSED_RGBA8_ETC2_EAC;if(e===qo)return r.COMPRESSED_R11_EAC;if(e===Xo)return r.COMPRESSED_SIGNED_R11_EAC;if(e===Yo)return r.COMPRESSED_RG11_EAC;if(e===Zo)return r.COMPRESSED_SIGNED_RG11_EAC}if(e===Qo||e===Ko||e===Jo||e===ea||e===ta||e===sa||e===ia||e===ra||e===na||e===oa||e===aa||e===la||e===ha||e===ua){if(r=i.get("WEBGL_compressed_texture_astc"),null===r)return null;if(e===Qo)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_4x4_KHR:r.COMPRESSED_RGBA_ASTC_4x4_KHR;if(e===Ko)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x4_KHR:r.COMPRESSED_RGBA_ASTC_5x4_KHR;if(e===Jo)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_5x5_KHR:r.COMPRESSED_RGBA_ASTC_5x5_KHR;if(e===ea)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x5_KHR:r.COMPRESSED_RGBA_ASTC_6x5_KHR;if(e===ta)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_6x6_KHR:r.COMPRESSED_RGBA_ASTC_6x6_KHR;if(e===sa)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x5_KHR:r.COMPRESSED_RGBA_ASTC_8x5_KHR;if(e===ia)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x6_KHR:r.COMPRESSED_RGBA_ASTC_8x6_KHR;if(e===ra)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_8x8_KHR:r.COMPRESSED_RGBA_ASTC_8x8_KHR;if(e===na)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x5_KHR:r.COMPRESSED_RGBA_ASTC_10x5_KHR;if(e===oa)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x6_KHR:r.COMPRESSED_RGBA_ASTC_10x6_KHR;if(e===aa)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x8_KHR:r.COMPRESSED_RGBA_ASTC_10x8_KHR;if(e===la)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_10x10_KHR:r.COMPRESSED_RGBA_ASTC_10x10_KHR;if(e===ha)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x10_KHR:r.COMPRESSED_RGBA_ASTC_12x10_KHR;if(e===ua)return n===_a?r.COMPRESSED_SRGB8_ALPHA8_ASTC_12x12_KHR:r.COMPRESSED_RGBA_ASTC_12x12_KHR}if(e===ca){if(r=i.get("EXT_texture_compression_bptc"),null===r)return null;if(e===ca)return n===_a?r.COMPRESSED_SRGB_ALPHA_BPTC_UNORM_EXT:r.COMPRESSED_RGBA_BPTC_UNORM_EXT}if(e===da||e===pa||e===ma||e===fa){if(r=i.get("EXT_texture_compression_rgtc"),null===r)return null;if(e===da)return r.COMPRESSED_RED_RGTC1_EXT;if(e===pa)return r.COMPRESSED_SIGNED_RED_RGTC1_EXT;if(e===ma)return r.COMPRESSED_RED_GREEN_RGTC2_EXT;if(e===fa)return r.COMPRESSED_SIGNED_RED_GREEN_RGTC2_EXT}return e===So?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 tI,sI,iI,rI=!1;class nI{constructor(e){this.backend=e,this.gl=e.gl,this.extensions=e.extensions,this.defaultTextures={},this._srcFramebuffer=null,this._dstFramebuffer=null,!1===rI&&(this._init(),rI=!0)}_init(){const e=this.gl;tI={[ro]:e.REPEAT,[no]:e.CLAMP_TO_EDGE,[oo]:e.MIRRORED_REPEAT},sI={[ao]:e.NEAREST,[lo]:e.NEAREST_MIPMAP_NEAREST,[ho]:e.NEAREST_MIPMAP_LINEAR,[uo]:e.LINEAR,[co]:e.LINEAR_MIPMAP_NEAREST,[po]:e.LINEAR_MIPMAP_LINEAR},iI={[va]:e.NEVER,[Ca]:e.ALWAYS,[Ta]:e.LESS,[Ma]:e.LEQUAL,[Sa]:e.EQUAL,[Ea]:e.GEQUAL,[Aa]:e.GREATER,[Na]: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];Ua("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?xa:dl.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===_a?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?xa:dl.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===_a?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=dl.getPrimaries(dl.workingColorSpace),o=t.colorSpace===ga?null:dl.getPrimaries(t.colorSpace),a=t.colorSpace===ga||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,tI[t.wrapS]),s.texParameteri(e,s.TEXTURE_WRAP_T,tI[t.wrapT]),e!==s.TEXTURE_3D&&e!==s.TEXTURE_2D_ARRAY||t.isArrayTexture||s.texParameteri(e,s.TEXTURE_WRAP_R,tI[t.wrapR]),s.texParameteri(e,s.TEXTURE_MAG_FILTER,sI[t.magFilter]);const l=void 0!==t.mipmaps&&t.mipmaps.length>0,h=t.minFilter===uo&&l?po:t.minFilter;if(s.texParameteri(e,s.TEXTURE_MIN_FILTER,sI[h]),t.compareFunction&&(s.texParameteri(e,s.TEXTURE_COMPARE_MODE,s.COMPARE_REF_TO_TEXTURE),s.texParameteri(e,s.TEXTURE_COMPARE_FUNC,iI[t.compareFunction])),!0===i.has("EXT_texture_filter_anisotropic")){if(t.magFilter===ao)return;if(t.minFilter!==ho&&t.minFilter!==po)return;if(t.type===_o&&!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):Ua("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):Ua("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=oI(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=oI(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=Hc(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=oI(t);s.texSubImage2D(o,e,0,0,t.width,t.height,a,l,i)}else{const e=oI(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,b,x,_,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,b=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,b=0}null!==i?(x=i.x,_=i.y,w=i.z):(x=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,b);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,b+e),o.framebufferTextureLayer(o.DRAW_FRAMEBUFFER,o.COLOR_ATTACHMENT0,h,n,w+e)),o.blitFramebuffer(g,y,p,m,x,_,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,b+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,x,_,p,m,o.COLOR_BUFFER_BIT,o.NEAREST):C?o.copyTexSubImage3D(u,n,x,_,w+e,g,y,p,m):o.copyTexSubImage2D(u,n,x,_,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,x,_,w,p,m,f,d,c,v.data):t.isCompressedArrayTexture?o.compressedTexSubImage3D(u,n,x,_,w,p,m,f,d,v.data):o.texSubImage3D(u,n,x,_,w,p,m,f,d,c,v):e.isDataTexture?o.texSubImage2D(o.TEXTURE_2D,n,x,_,p,m,d,c,v.data):e.isCompressedTexture?o.compressedTexSubImage2D(o.TEXTURE_2D,n,x,_,v.width,v.height,d,v.data):o.texSubImage2D(o.TEXTURE_2D,n,x,_,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 oI(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 aI{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 lI{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 hI={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 uI{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 cI{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&&(Ua(`TimestampQueryPool: No timestamp available for uid ${e}.`),t=0),t}hasTimestamp(e){return this.timestamps.has(e)}allocateQueriesForContext(){}async resolveQueriesAsync(){}dispose(){}}class dI extends cI{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 Ua("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 ja(`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){Ga("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){Ga("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 Ga("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){Ga("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 pI extends qB{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 aI(this),this.capabilities=new lI(this),this.attributeUtils=new KB(this),this.textureUtils=new nI(this),this.bufferRenderer=new uI(this),this.state=new JB(this),this.utils=new eI(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 Ba}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&&Ua("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 dI(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(La,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(La,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(Da,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)?(ja("WebGLBackend.compute(): The count parameter must be a single number, not an array."),r=r[0]):r&&"object"==typeof r&&r.isIndirectStorageBufferAttribute&&(ja("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(Da,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 b=this.bufferRenderer;t.isPoints?b.mode=a.POINTS:t.isLineSegments?b.mode=a.LINES:t.isLine?b.mode=a.LINE_STRIP:t.isLineLoop?b.mode=a.LINE_LOOP:!0===i.wireframe?(l.setLineWidth(i.wireframeLinewidth*this.renderer.getPixelRatio()),b.mode=a.LINES):b.mode=a.TRIANGLES;const{vertexCount:x,instanceCount:_}=u;let{firstVertex:w}=u;if(b.object=t,null!==f){w*=f.array.BYTES_PER_ELEMENT;const e=this.get(f);b.index=f.count,b.type=e.type}else b.index=0;const v=()=>{t.isBatchedMesh?null!==t._multiDrawInstances?(ja("WebGLBackend: renderMultiDrawInstances has been deprecated and will be removed in r184. Append to renderMultiDraw arguments and use indirection."),b.renderMultiDrawInstances(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount,t._multiDrawInstances)):this.hasFeature("WEBGL_multi_draw")?b.renderMultiDraw(t._multiDrawStarts,t._multiDrawCounts,t._multiDrawCount):ja("WebGLBackend: WEBGL_multi_draw not supported."):_>1?b.renderInstances(w,x,_):b.render(w,x)};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 $B(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");Ga("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&&Ua("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=Oa(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=Oa(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(hI).filter(t=>hI[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"),b=this._useMultisampledExtension(r),x=RM(e);let _;if(h?(n.cubeFramebuffers||(n.cubeFramebuffers={}),_=n.cubeFramebuffers[x]):d&&!1===p?_=this._xrFramebuffer:(n.framebuffers||(n.framebuffers={}),_=n.framebuffers[x]),void 0===_){_=t.createFramebuffer(),s.bindFramebuffer(t.FRAMEBUFFER,_);const i=e.textures,a=[];if(h){n.cubeFramebuffers[x]=_;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[x]=_;for(let s=0;s<i.length;s++){const n=i[s],a=this.get(n);a.renderTarget=e.renderTarget,a.cacheKey=x;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(b)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,b),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=x,r.multiview)y.framebufferTextureMultisampleMultiviewOVR(t.FRAMEBUFFER,d,s.textureGPU,0,o,0,2);else if(p&&b)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||b||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):b?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):b?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===b&&!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 mI="point-list",fI="line-list",gI="line-strip",yI="triangle-list",bI="triangle-strip",xI="undefined"!=typeof self?self.GPUShaderStage:{VERTEX:1,FRAGMENT:2,COMPUTE:4},_I="never",wI="less",vI="equal",TI="less-equal",SI="greater",MI="not-equal",AI="greater-equal",NI="always",EI="store",CI="load",RI="clear",PI="ccw",BI="cw",II="none",DI="back",LI="uint16",FI="uint32",OI="r8unorm",zI="r8snorm",VI="r8uint",kI="r8sint",UI="r16uint",GI="r16sint",jI="r16float",$I="rg8unorm",WI="rg8snorm",HI="rg8uint",qI="rg8sint",XI="r32uint",YI="r32sint",ZI="r32float",QI="rg16uint",KI="rg16sint",JI="rg16float",eD="rgba8unorm",tD="rgba8unorm-srgb",sD="rgba8snorm",iD="rgba8uint",rD="rgba8sint",nD="bgra8unorm",oD="bgra8unorm-srgb",aD="rgb9e5ufloat",lD="rgb10a2unorm",hD="rg11b10ufloat",uD="rg32uint",cD="rg32sint",dD="rg32float",pD="rgba16uint",mD="rgba16sint",fD="rgba16float",gD="rgba32uint",yD="rgba32sint",bD="rgba32float",xD="depth16unorm",_D="depth24plus",wD="depth24plus-stencil8",vD="depth32float",TD="depth32float-stencil8",SD="bc1-rgba-unorm",MD="bc1-rgba-unorm-srgb",AD="bc2-rgba-unorm",ND="bc2-rgba-unorm-srgb",ED="bc3-rgba-unorm",CD="bc3-rgba-unorm-srgb",RD="bc4-r-unorm",PD="bc4-r-snorm",BD="bc5-rg-unorm",ID="bc5-rg-snorm",DD="bc6h-rgb-ufloat",LD="bc6h-rgb-float",FD="bc7-rgba-unorm",OD="bc7-rgba-unorm-srgb",zD="etc2-rgb8unorm",VD="etc2-rgb8unorm-srgb",kD="etc2-rgb8a1unorm",UD="etc2-rgb8a1unorm-srgb",GD="etc2-rgba8unorm",jD="etc2-rgba8unorm-srgb",$D="eac-r11unorm",WD="eac-r11snorm",HD="eac-rg11unorm",qD="eac-rg11snorm",XD="astc-4x4-unorm",YD="astc-4x4-unorm-srgb",ZD="astc-5x4-unorm",QD="astc-5x4-unorm-srgb",KD="astc-5x5-unorm",JD="astc-5x5-unorm-srgb",eL="astc-6x5-unorm",tL="astc-6x5-unorm-srgb",sL="astc-6x6-unorm",iL="astc-6x6-unorm-srgb",rL="astc-8x5-unorm",nL="astc-8x5-unorm-srgb",oL="astc-8x6-unorm",aL="astc-8x6-unorm-srgb",lL="astc-8x8-unorm",hL="astc-8x8-unorm-srgb",uL="astc-10x5-unorm",cL="astc-10x5-unorm-srgb",dL="astc-10x6-unorm",pL="astc-10x6-unorm-srgb",mL="astc-10x8-unorm",fL="astc-10x8-unorm-srgb",gL="astc-10x10-unorm",yL="astc-10x10-unorm-srgb",bL="astc-12x10-unorm",xL="astc-12x10-unorm-srgb",_L="astc-12x12-unorm",wL="astc-12x12-unorm-srgb",vL="clamp-to-edge",TL="repeat",SL="mirror-repeat",ML="linear",AL="nearest",NL="zero",EL="one",CL="src",RL="one-minus-src",PL="src-alpha",BL="one-minus-src-alpha",IL="dst",DL="one-minus-dst",LL="dst-alpha",FL="one-minus-dst-alpha",OL="src-alpha-saturated",zL="constant",VL="one-minus-constant",kL="add",UL="subtract",GL="reverse-subtract",jL="min",$L="max",WL=0,HL=15,qL="keep",XL="zero",YL="replace",ZL="invert",QL="increment-clamp",KL="decrement-clamp",JL="increment-wrap",eF="decrement-wrap",tF="storage",sF="read-only-storage",iF="write-only",rF="read-only",nF="read-write",oF="non-filtering",aF="comparison",lF="float",hF="unfilterable-float",uF="depth",cF="sint",dF="uint",pF="2d",mF="3d",fF="2d",gF="2d-array",yF="cube",bF="3d",xF="all",_F="vertex",wF="instance",vF={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"},TF={"texture-compression-s3tc":"texture-compression-bc","texture-compression-etc1":"texture-compression-etc2"};class SF extends PB{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 MF extends SB{constructor(e,t){super(e,t?t.array:null),this.attribute=t,this.isStorageBuffer=!0}}let AF=0;class NF extends MF{constructor(e,t){super("StorageBuffer_"+AF++,e?e.value:null),this.nodeUniform=e,this.access=e?e.access:md.READ_WRITE,this.groupNode=t}get buffer(){return this.nodeUniform.value}}class EF extends rM{constructor(e){super(),this.device=e;this.mipmapSampler=e.createSampler({minFilter:ML}),this.flipYSampler=e.createSampler({minFilter:AL}),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:bI,stripIndexFormat:FI},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:bI,stripIndexFormat:FI},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:fF,baseArrayLayer:s}),u=l.createView({baseMipLevel:0,mipLevelCount:1,dimension:fF,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:RI,storeOp:EI,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:fF,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:fF,baseArrayLayer:s}),u={colorAttachments:[{view:h,loadOp:RI,storeOp:EI,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 CF={[va]:"never",[Ta]:"less",[Sa]:"equal",[Ma]:"less-equal",[Aa]:"greater",[Ea]:"greater-equal",[Ca]:"always",[Na]:"not-equal"},RF=[0,1,3,2,4,5];class PF{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===ML&&r.minFilter===ML&&r.mipmapFilter===ML&&(r.maxAnisotropy=e.anisotropy),e.isDepthTexture&&null!==e.compareFunction&&(r.compare=CF[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=BF(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||BF(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!==aD&&(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 Ua("WebGPURenderer: Texture format not supported."),void this.createDefaultTexture(e);if(e.isCubeTexture&&(m.textureBindingViewDimension=yF),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=Ro,u=So):e&&(h=Co,u=xo),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 vl;s.minFilter=ao,s.magFilter=ao,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 ku;s.minFilter=ao,s.magFilter=ao,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?RF[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 EF(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===SD||e===MD?{byteLength:8,width:4,height:4}:e===AD||e===ND||e===ED||e===CD?{byteLength:16,width:4,height:4}:e===RD||e===PD?{byteLength:8,width:4,height:4}:e===BD||e===ID||e===DD||e===LD||e===FD||e===OD?{byteLength:16,width:4,height:4}:e===zD||e===VD||e===kD||e===UD?{byteLength:8,width:4,height:4}:e===GD||e===jD?{byteLength:16,width:4,height:4}:e===$D||e===WD?{byteLength:8,width:4,height:4}:e===HD||e===qD||e===XD||e===YD?{byteLength:16,width:4,height:4}:e===ZD||e===QD?{byteLength:16,width:5,height:4}:e===KD||e===JD?{byteLength:16,width:5,height:5}:e===eL||e===tL?{byteLength:16,width:6,height:5}:e===sL||e===iL?{byteLength:16,width:6,height:6}:e===rL||e===nL?{byteLength:16,width:8,height:5}:e===oL||e===aL?{byteLength:16,width:8,height:6}:e===lL||e===hL?{byteLength:16,width:8,height:8}:e===uL||e===cL?{byteLength:16,width:10,height:5}:e===dL||e===pL?{byteLength:16,width:10,height:6}:e===mL||e===fL?{byteLength:16,width:10,height:8}:e===gL||e===yL?{byteLength:16,width:10,height:10}:e===bL||e===xL?{byteLength:16,width:12,height:10}:e===_L||e===wL?{byteLength:16,width:12,height:12}:void 0}_convertAddressMode(e){let t=vL;return e===ro?t=TL:e===oo&&(t=SL),t}_convertFilterMode(e){let t=ML;return e!==ao&&1004!==e&&e!==ho||(t=AL),t}_getBytesPerTexel(e){return e===OI||e===zI||e===VI||e===kI?1:e===UI||e===GI||e===jI||e===$I||e===WI||e===HI||e===qI?2:e===XI||e===YI||e===ZI||e===QI||e===KI||e===JI||e===eD||e===tD||e===sD||e===iD||e===rD||e===nD||e===oD||e===aD||e===lD||e===hD||e===vD||e===_D||e===wD||e===TD?4:e===uD||e===cD||e===dD||e===pD||e===mD||e===fD?8:e===gD||e===yD||e===bD?16:void 0}_getTypedArrayType(e){return e===VI?Uint8Array:e===kI?Int8Array:e===OI?Uint8Array:e===zI?Int8Array:e===HI?Uint8Array:e===qI?Int8Array:e===$I?Uint8Array:e===WI?Int8Array:e===iD?Uint8Array:e===rD?Int8Array:e===eD||e===tD?Uint8Array:e===sD?Int8Array:e===UI?Uint16Array:e===GI?Int16Array:e===QI?Uint16Array:e===KI?Int16Array:e===pD?Uint16Array:e===mD?Int16Array:e===jI||e===JI||e===fD?Uint16Array:e===XI?Uint32Array:e===YI?Int32Array:e===ZI?Float32Array:e===uD?Uint32Array:e===cD?Int32Array:e===dD?Float32Array:e===gD?Uint32Array:e===yD?Int32Array:e===bD?Float32Array:e===nD||e===oD?Uint8Array:e===lD||e===aD||e===hD?Uint32Array:e===vD?Float32Array:e===_D||e===wD?Uint32Array:e===TD?Float32Array:void 0}_getDimension(e){let t;return t=e.is3DTexture||e.isData3DTexture?mF:pF,t}}function BF(e,t=null){const s=e.format,i=e.type,r=e.colorSpace,n=dl.getTransfer(r);let o;if(!0===e.isCompressedTexture||!0===e.isCompressedArrayTexture)switch(s){case Fo:case Oo:o=n===_a?MD:SD;break;case zo:o=n===_a?ND:AD;break;case Vo:o=n===_a?CD:ED;break;case da:o=RD;break;case pa:o=PD;break;case ma:o=BD;break;case fa:o=ID;break;case ca:o=n===_a?OD:FD;break;case Wo:case $o:o=n===_a?VD:zD;break;case Ho:o=n===_a?jD:GD;break;case qo:o=$D;break;case Xo:o=WD;break;case Yo:o=HD;break;case Zo:o=qD;break;case Qo:o=n===_a?YD:XD;break;case Ko:o=n===_a?QD:ZD;break;case Jo:o=n===_a?JD:KD;break;case ea:o=n===_a?tL:eL;break;case ta:o=n===_a?iL:sL;break;case sa:o=n===_a?nL:rL;break;case ia:o=n===_a?aL:oL;break;case ra:o=n===_a?hL:lL;break;case na:o=n===_a?cL:uL;break;case oa:o=n===_a?pL:dL;break;case aa:o=n===_a?fL:mL;break;case la:o=n===_a?yL:gL;break;case ha:o=n===_a?xL:bL;break;case ua:o=n===_a?wL:_L;break;case Eo:o=n===_a?tD:eD;break;default:Ga("WebGPURenderer: Unsupported texture format.",s)}else switch(s){case Eo:switch(i){case fo:o=sD;break;case go:o=mD;break;case yo:o=pD;break;case xo:o=gD;break;case bo:o=yD;break;case mo:o=n===_a?tD:eD;break;case wo:o=fD;break;case _o:o=bD;break;default:Ga("WebGPURenderer: Unsupported texture type with RGBAFormat.",i)}break;case No:switch(i){case Mo:o=aD;break;case Ao:o=hD;break;default:Ga("WebGPURenderer: Unsupported texture type with RGBFormat.",i)}break;case Po:switch(i){case fo:o=zI;break;case go:o=GI;break;case yo:o=UI;break;case xo:o=XI;break;case bo:o=YI;break;case mo:o=OI;break;case wo:o=jI;break;case _o:o=ZI;break;default:Ga("WebGPURenderer: Unsupported texture type with RedFormat.",i)}break;case Io:switch(i){case fo:o=WI;break;case go:o=KI;break;case yo:o=QI;break;case xo:o=uD;break;case bo:o=cD;break;case mo:o=$I;break;case wo:o=JI;break;case _o:o=dD;break;default:Ga("WebGPURenderer: Unsupported texture type with RGFormat.",i)}break;case Co:switch(i){case yo:o=xD;break;case xo:o=_D;break;case _o:o=vD;break;default:Ga("WebGPURenderer: Unsupported texture type with DepthFormat.",i)}break;case Ro:switch(i){case So:o=wD;break;case _o:t&&!1===t.features.has(vF.Depth32FloatStencil8)&&Ga('WebGPURenderer: Depth textures with DepthStencilFormat + FloatType can only be used with the "depth32float-stencil8" GPU feature.'),o=TD;break;default:Ga("WebGPURenderer: Unsupported texture type with DepthStencilFormat.",i)}break;case Bo:switch(i){case bo:o=YI;break;case xo:o=XI;break;default:Ga("WebGPURenderer: Unsupported texture type with RedIntegerFormat.",i)}break;case Do:switch(i){case bo:o=cD;break;case xo:o=uD;break;default:Ga("WebGPURenderer: Unsupported texture type with RGIntegerFormat.",i)}break;case Lo:switch(i){case bo:o=yD;break;case xo:o=gD;break;default:Ga("WebGPURenderer: Unsupported texture type with RGBAIntegerFormat.",i)}break;default:Ga("WebGPURenderer: Unsupported texture format.",s)}return o}const IF=/^[fn]*\s*([a-z_0-9]+)?\s*\(([\s\S]*?)\)\s*[\-\>]*\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/i,DF=/([a-z_0-9]+)\s*:\s*([a-z_0-9]+(?:<[\s\S]+?>)?)/gi,LF={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 FF extends VP{constructor(e){const{type:t,inputs:s,name:i,inputsCode:r,blockCode:n,outputType:o}=(e=>{const t=(e=e.trim()).match(IF);if(null!==t&&4===t.length){const s=t[2],i=[];let r=null;for(;null!==(r=DF.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=LF[r]),n.push(new MP(r,t))}const o=e.substring(t[0].length),a=t[3]||"void",l=void 0!==t[1]?t[1]:"";return{type:LF[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 OF extends zP{parseFunction(e){return new FF(e)}}const zF={[md.READ_ONLY]:"read",[md.WRITE_ONLY]:"write",[md.READ_WRITE]:"read_write"},VF={[ro]:"repeat",[no]:"clamp",[oo]:"mirror"},kF={vertex:xI.VERTEX,fragment:xI.FRAGMENT,compute:xI.COMPUTE},UF={instance:!0,swizzleAssign:!1,storageBuffer:!0},GF={"^^":"tsl_xor"},jF={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>"},$F={},WF={tsl_xor:new YN("fn tsl_xor( a : bool, b : bool ) -> bool { return ( a || b ) && !( a && b ); }"),mod_float:new YN("fn tsl_mod_float( x : f32, y : f32 ) -> f32 { return x - y * floor( x / y ); }"),mod_vec2:new YN("fn tsl_mod_vec2( x : vec2f, y : vec2f ) -> vec2f { return x - y * floor( x / y ); }"),mod_vec3:new YN("fn tsl_mod_vec3( x : vec3f, y : vec3f ) -> vec3f { return x - y * floor( x / y ); }"),mod_vec4:new YN("fn tsl_mod_vec4( x : vec4f, y : vec4f ) -> vec4f { return x - y * floor( x / y ); }"),equals_bool:new YN("fn tsl_equals_bool( a : bool, b : bool ) -> bool { return a == b; }"),equals_bvec2:new YN("fn tsl_equals_bvec2( a : vec2f, b : vec2f ) -> vec2<bool> { return vec2<bool>( a.x == b.x, a.y == b.y ); }"),equals_bvec3:new YN("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 YN("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 YN("fn tsl_repeatWrapping_float( coord: f32 ) -> f32 { return fract( coord ); }"),mirrorWrapping_float:new YN("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 YN("fn tsl_clampWrapping_float( coord: f32 ) -> f32 { return clamp( coord, 0.0, 1.0 ); }"),biquadraticTexture:new YN("\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")},HF={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 qF="";!0!==("undefined"!=typeof navigator&&/Firefox|Deno/g.test(navigator.userAgent))&&(qF+="diagnostic( off, derivative_uniformity );\n");class XF extends TP{constructor(e,t){super(e,t,new OF),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_${VF[e.wrapS]}S_${VF[e.wrapT]}_${e.is3DTexture||e.isData3DTexture?"3d":"2d"}T`;let s=$F[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===ro?(i.push(WF.repeatWrapping_float),n+=`\t\ttsl_repeatWrapping_float( coord.${t} )`):e===no?(i.push(WF.clampWrapping_float),n+=`\t\ttsl_clampWrapping_float( coord.${t} )`):e===oo?(i.push(WF.mirrorWrapping_float),n+=`\t\ttsl_mirrorWrapping_float( coord.${t} )`):(n+=`\t\tcoord.${t}`,Ua(`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",$F[t]=s=new YN(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 kg(new Ny(`textureDimensions( ${n} )`,o)),i.dimensionsSnippet[s]=r,(e.isArrayTexture||e.isDataArrayTexture||e.is3DTexture||e.isData3DTexture)&&(i.arrayLayerCount=new kg(new Ny(`textureNumLayers(${t})`,"u32"))),e.isTextureCube&&(i.cubeFaceCount=new kg(new Ny("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===_o||!1===this.isSampleCompare(e)&&e.minFilter===ao&&e.magFilter===ao||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]} )`;Ga(`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} )`;Ga(`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} )`;Ga(`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=GF[e];return void 0!==t?(this._include(t),t):null}getNodeAccess(e,t){return"compute"!==t?!0===e.isAtomic?(Ua("WebGPURenderer: Atomic operations are only supported in compute shaders."),md.READ_WRITE):md.READ_ONLY:e.access}getStorageAccess(e,t){return zF[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 FB(r.name,r.node,a,n):new DB(r.name,r.node,a,n):"cubeTexture"===t||"cubeDepthTexture"===t?i=new LB(r.name,r.node,a,n):"texture3D"===t&&(i=new FB(r.name,r.node,a,n)),i.store=!0===e.isStorageTextureNode,i.mipLevel=i.store?e.mipLevel:0,i.setVisibility(kF[s]),!1===this.isUnfilterable(e.value)&&!1===i.store){const e=new SF(`${r.name}_sampler`,r.node,a);e.setVisibility(kF[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?NB:NF)(e,a),n.buffer=l}l.setVisibility(l.getVisibility()|kF[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 RB(l,a),i.setVisibility(kF[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=BF(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 jF[e]||e}isAvailable(e){let t=UF[e];return void 0===t&&("float32Filterable"===e?t=this.renderer.hasFeature("float32-filterable"):"clipDistance"===e&&(t=this.renderer.hasFeature("clip-distances")),UF[e]=t),t}_getWGSLMethod(e){return void 0!==WF[e]&&this._include(e),HF[e]}_include(e){const t=WF[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${qF}\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 YF{constructor(e){this.backend=e}getCurrentDepthStencilFormat(e){let t;return null!==e.depthTexture?t=this.getTextureFormatGPU(e.depthTexture):e.depth&&e.stencil?t=wD:e.depth&&(t=_D),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?mI:e.isLineSegments||e.isMesh&&!0===t.wireframe?fI:e.isLine?gI:e.isMesh?yI: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===mo)return nD;if(e===wo)return fD;throw new Error("Unsupported output buffer type.")}}const ZF=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&&ZF.set(Float16Array,["float16"]);const QF=new Map([[au,["float16"]]]),KF=new Map([[Int32Array,"sint32"],[Int16Array,"sint32"],[Uint32Array,"uint32"],[Uint16Array,"uint32"],[Float32Array,"float32"]]);class JF{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=Oa(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?wF:_F):(e=i.itemSize*r,t=i.isInstancedBufferAttribute?wF:_F),!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=KF.get(i);else{const e=(QF.get(r)||ZF.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||Ga("WebGPUAttributeUtils: Vertex format not supported yet."),n}_getBufferAttribute(e){return e.isInterleavedBufferAttribute&&(e=e.data),e}}class eO{constructor(e){this.layoutGPU=e,this.usedTimes=0}}class tO{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 eO(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=Oa(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&xI.VERTEX&&n.push("vertex"),t.visibility&xI.FRAGMENT&&n.push("fragment"),t.visibility&xI.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=xF;let a;a=t.isSampledCubeTexture?yF:t.isSampledTexture3D?bF:t.texture.isArrayTexture||t.texture.isDataArrayTexture||t.texture.isCompressedArrayTexture?gF:fF,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&xI.COMPUTE&&(i.access===md.READ_WRITE||i.access===md.WRITE_ONLY)?e.type=tF:e.type=sF),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===md.READ_WRITE?nF:t===md.WRITE_ONLY?iF:rF,i.texture.isArrayTexture?e.viewDimension=gF:i.texture.is3DTexture&&(e.viewDimension=bF),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=hF)),i.texture.isDepthTexture)e.compatibilityMode&&null===i.texture.compareFunction?t.sampleType=hF:t.sampleType=uF;else if(i.texture.isDataTexture||i.texture.isDataArrayTexture||i.texture.isData3DTexture){const e=i.texture.type;e===bo?t.sampleType=cF:e===xo?t.sampleType=dF:e===_o&&(this.backend.hasFeature("float32-filterable")?t.sampleType=lF:t.sampleType=hF)}i.isSampledCubeTexture?t.viewDimension=yF:i.texture.isArrayTexture||i.texture.isDataArrayTexture||i.texture.isCompressedArrayTexture?t.viewDimension=gF:i.isSampledTexture3D&&(t.viewDimension=bF),r.texture=t}else if(i.isSampler){const t={};i.texture.isDepthTexture&&(null!==i.texture.compareFunction?t.type=aF:e.compatibilityMode&&(t.type=oF)),r.sampler=t}else Ga(`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 sO{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 b=l.get(o).module,x=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({},b,{buffers:p}),fragment:Object.assign({},x,{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,Ga(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,Ga(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:kL},s={srcFactor:r,dstFactor:n,operation:kL}};if(e.premultipliedAlpha)switch(i){case 1:r(EL,BL,EL,BL);break;case 2:r(EL,EL,EL,EL);break;case 3:r(NL,RL,NL,EL);break;case 4:r(IL,BL,NL,EL)}else switch(i){case 1:r(PL,BL,EL,BL);break;case 2:r(PL,EL,EL,EL);break;case 3:Ga("WebGPURenderer: SubtractiveBlending requires material.premultipliedAlpha = true");break;case 4:Ga("WebGPURenderer: MultiplyBlending requires material.premultipliedAlpha = true")}}if(void 0!==t&&void 0!==s)return{color:t,alpha:s};Ga("WebGPURenderer: Invalid blending: ",i)}_getBlendFactor(e){let t;switch(e){case Wn:t=NL;break;case 201:t=EL;break;case 202:t=CL;break;case 203:t=RL;break;case Yn:t=PL;break;case Zn:t=BL;break;case 208:t=IL;break;case 209:t=DL;break;case 206:t=LL;break;case 207:t=FL;break;case 210:t=OL;break;case 211:t=zL;break;case 212:t=VL;break;default:Ga("WebGPURenderer: Blend factor not supported.",e)}return t}_getStencilCompare(e){let t;const s=e.stencilFunc;switch(s){case 512:t=_I;break;case 519:t=NI;break;case 513:t=wI;break;case 515:t=TI;break;case 514:t=vI;break;case 518:t=AI;break;case 516:t=SI;break;case 517:t=MI;break;default:Ga("WebGPURenderer: Invalid stencil function.",s)}return t}_getStencilOperation(e){let t;switch(e){case wa:t=qL;break;case 0:t=XL;break;case 7681:t=YL;break;case 5386:t=ZL;break;case 7682:t=QL;break;case 7683:t=KL;break;case 34055:t=JL;break;case 34056:t=eF;break;default:Ga("WebGPURenderer: Invalid stencil operation.",t)}return t}_getBlendOperation(e){let t;switch(e){case Gn:t=kL;break;case 101:t=UL;break;case 102:t=GL;break;case 103:t=jL;break;case 104:t=$L;break;default:Ga("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?LI:FI);let n=1===s.side;return e.isMesh&&e.matrixWorld.determinant()<0&&(n=!n),i.frontFace=!0===n?BI:PI,i.cullMode=2===s.side?II:DI,i}_getColorWriteMask(e){return!0===e.colorWrite?HL:WL}_getDepthCompare(e){let t;if(!1===e.depthTest)t=NI;else{const s=e.depthFunc;switch(s){case 0:t=_I;break;case 1:t=NI;break;case 2:t=wI;break;case 3:t=TI;break;case 4:t=vI;break;case 5:t=AI;break;case 6:t=SI;break;case 7:t=MI;break;default:Ga("WebGPUPipelineUtils: Invalid depth function.",s)}}return t}}class iO extends cI{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 ja(`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 Ga("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){Ga("Error waiting for pending resolve:",e)}if(this.resultBuffer&&"mapped"===this.resultBuffer.mapState)try{this.resultBuffer.unmap()}catch(e){Ga("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 rO extends qB{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 YF(this),this.attributeUtils=new JF(this),this.bindingUtils=new tO(this),this.pipelineUtils=new sO(this),this.textureUtils=new PF(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(vF),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(vF.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${Un} webgpu`);const r=i.alpha?"premultiplied":"opaque",n=i.outputType===wo?"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 Ia}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:fF};if(s.isRenderTarget3D)l=e.activeCubeFace,n.baseArrayLayer=0,n.dimension=bF,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:fF},s=r.texture.createView(t);a.push({view:s,resolveTarget:void 0,depthSlice:void 0})}}else n.dimension=gF,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=fF,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||CI,storeOp:t.storeOp||EI,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:CI}),this.initTimestampQuery(La,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=RI):i.loadOp=CI,i.storeOp=EI}}else{const t=n.colorAttachments[0];e.clearColor?(t.clearValue=e.clearColorValue,t.loadOp=RI):t.loadOp=CI,t.storeOp=EI}e.depth&&(e.clearDepth?(o.depthClearValue=e.clearDepthValue,o.depthLoadOp=RI):o.depthLoadOp=CI,o.depthStoreOp=EI),e.stencil&&(e.clearStencil?(o.stencilClearValue=e.clearStencilValue,o.stencilLoadOp=RI):o.stencilLoadOp=CI,o.stencilStoreOp=EI);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:fF,baseArrayLayer:o,arrayLayerCount:1})),i.depthStencilAttachment={view:n.viewCache[t],depthLoadOp:r.depthLoadOp||RI,depthStoreOp:r.depthStoreOp||EI,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=RI):t.depthLoadOp=CI),e.stencil&&(e.clearStencil?(t.stencilClearValue=e.clearStencilValue,t.stencilLoadOp=RI):t.stencilLoadOp=CI)}}}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=RI,e.storeOp=EI}(l||h)&&(o=t.depthStencilAttachment)}else{l=i.depth,h=i.stencil;const r={loadOp:e?RI:CI,clearValue:e?a:void 0};l&&(r.depthLoadOp=t?RI:CI,r.depthClearValue=t?n.getClearDepth():void 0,r.depthStoreOp=EI),h&&(r.stencilLoadOp=s?RI:CI,r.stencilClearValue=s?n.getClearStencil():void 0,r.stencilStoreOp=EI);const c=this._getRenderPassDescriptor(i,r);u=c.colorAttachments,o=c.depthStencilAttachment}l&&o&&(t?(o.depthLoadOp=RI,o.depthClearValue=n.getClearDepth(),o.depthStoreOp=EI):(o.depthLoadOp=CI,o.depthStoreOp=EI)),h&&o&&(s?(o.stencilLoadOp=RI,o.stencilClearValue=n.getClearStencil(),o.stencilStoreOp=EI):(o.stencilLoadOp=CI,o.stencilStoreOp=EI));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(Da,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?LI:FI;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&&ja("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 iO(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 XF(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!==TF[e]&&(e=TF[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 Ga("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=CI;t.depth&&(e.depthStencilAttachment.depthLoadOp=CI),t.stencil&&(e.depthStencilAttachment.stencilLoadOp=CI),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 nO extends Ic{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 oO extends Ic{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 aO extends eB{constructor(){super(),this.addMaterial(Vv,"MeshPhongMaterial"),this.addMaterial(PS,"MeshStandardMaterial"),this.addMaterial(IS,"MeshPhysicalMaterial"),this.addMaterial(OS,"MeshToonMaterial"),this.addMaterial(Rv,"MeshBasicMaterial"),this.addMaterial(Ov,"MeshLambertMaterial"),this.addMaterial(yv,"MeshNormalMaterial"),this.addMaterial(kS,"MeshMatcapMaterial"),this.addMaterial(uv,"LineBasicMaterial"),this.addMaterial(dv,"LineDashedMaterial"),this.addMaterial(qS,"PointsMaterial"),this.addMaterial($S,"SpriteMaterial"),this.addMaterial(QS,"ShadowMaterial"),this.addLight(XC,Lc),this.addLight(AP,zc),this.addLight(RP,kc),this.addLight(PP,Ic),this.addLight(LP,Vc),this.addLight(FP,Nc),this.addLight(OP,Gc),this.addLight(BP,nO),this.addLight(DP,oO),this.addToneMapping(VN,1),this.addToneMapping(kN,2),this.addToneMapping(UN,3),this.addToneMapping(jN,4),this.addToneMapping(qN,6),this.addToneMapping(XN,7)}}class lO extends vB{constructor(e={}){let t;e.forceWebGL?t=pI:(t=rO,e.getFallback=()=>(Ua("WebGPURenderer: WebGPU is not available, running under WebGL2 backend."),new pI(e)));super(new t(e),e),this.library=new aO,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
+ */UR.BRDF_GGX,UR.BRDF_Lambert,UR.BasicPointShadowFilter,UR.BasicShadowFilter,UR.Break,UR.Const;const hO=UR.Continue;UR.DFGLUT,UR.D_GGX,UR.Discard,UR.EPSILON,UR.F_Schlick;const uO=UR.Fn;UR.INFINITY;const cO=UR.If,dO=UR.Loop;UR.NodeAccess,UR.NodeShaderStage,UR.NodeType,UR.NodeUpdateType,UR.PCFShadowFilter,UR.PCFSoftShadowFilter,UR.PI,UR.PI2,UR.TWO_PI,UR.HALF_PI,UR.PointShadowFilter,UR.Return,UR.Schlick_to_F0,UR.ScriptableNodeResources,UR.ShaderNode,UR.Stack,UR.Switch,UR.TBNViewMatrix,UR.VSMShadowFilter,UR.V_GGX_SmithCorrelated,UR.Var,UR.VarIntent;const pO=UR.abs;UR.acesFilmicToneMapping,UR.acos,UR.add,UR.addMethodChaining,UR.addNodeElement,UR.agxToneMapping,UR.all,UR.alphaT,UR.and,UR.anisotropy,UR.anisotropyB,UR.anisotropyT,UR.any,UR.append,UR.array,UR.arrayBuffer,UR.asin,UR.assign,UR.atan,UR.atan2;const mO=UR.atomicAdd;UR.atomicAnd,UR.atomicFunc,UR.atomicLoad,UR.atomicMax,UR.atomicMin,UR.atomicOr,UR.atomicStore,UR.atomicSub,UR.atomicXor,UR.attenuationColor,UR.attenuationDistance,UR.attribute,UR.attributeArray,UR.backgroundBlurriness,UR.backgroundIntensity,UR.backgroundRotation,UR.batch,UR.bentNormalView,UR.billboarding,UR.bitAnd,UR.bitNot,UR.bitOr,UR.bitXor,UR.bitangentGeometry,UR.bitangentLocal,UR.bitangentView,UR.bitangentWorld,UR.bitcast,UR.blendBurn,UR.blendColor,UR.blendDodge,UR.blendOverlay,UR.blendScreen,UR.blur,UR.bool,UR.buffer,UR.bufferAttribute,UR.bumpMap,UR.burn,UR.builtin,UR.builtinAOContext,UR.builtinShadowContext,UR.bvec2,UR.bvec3,UR.bvec4,UR.bypass,UR.cache,UR.call,UR.cameraFar,UR.cameraIndex,UR.cameraNear,UR.cameraNormalMatrix,UR.cameraPosition,UR.cameraProjectionMatrix,UR.cameraProjectionMatrixInverse,UR.cameraViewMatrix,UR.cameraViewport,UR.cameraWorldMatrix,UR.cbrt,UR.cdl,UR.ceil,UR.checker,UR.cineonToneMapping,UR.clamp,UR.clearcoat,UR.clearcoatNormalView,UR.clearcoatRoughness,UR.code,UR.color,UR.colorSpaceToWorking,UR.colorToDirection,UR.compute,UR.computeKernel,UR.computeSkinning,UR.context,UR.convert,UR.convertColorSpace,UR.convertToTexture,UR.countLeadingZeros,UR.countOneBits,UR.countTrailingZeros,UR.cos;const fO=UR.cross;UR.cubeTexture,UR.cubeTextureBase,UR.dFdx,UR.dFdy,UR.dashSize,UR.debug,UR.decrement,UR.decrementBefore,UR.defaultBuildStages,UR.defaultShaderStages,UR.defined,UR.degrees,UR.deltaTime,UR.densityFog,UR.densityFogFactor,UR.depth,UR.depthPass,UR.determinant,UR.difference,UR.diffuseColor,UR.directPointLight,UR.directionToColor,UR.directionToFaceDirection,UR.dispersion,UR.distance,UR.div,UR.dodge,UR.dot,UR.drawIndex,UR.dynamicBufferAttribute,UR.element,UR.emissive,UR.equal,UR.equals,UR.equirectUV,UR.exp,UR.exp2,UR.expression,UR.faceDirection,UR.faceForward,UR.faceforward;const gO=UR.float;UR.floatBitsToInt,UR.floatBitsToUint,UR.floor,UR.fog,UR.fract,UR.frameGroup,UR.frameId,UR.frontFacing,UR.fwidth,UR.gain,UR.gapSize,UR.getConstNodeType,UR.getCurrentStack,UR.getDirection,UR.getDistanceAttenuation,UR.getGeometryRoughness,UR.getNormalFromDepth,UR.interleavedGradientNoise,UR.vogelDiskSample,UR.getParallaxCorrectNormal,UR.getRoughness,UR.getScreenPosition,UR.getShIrradianceAt,UR.getShadowMaterial,UR.getShadowRenderObjectFunction,UR.getTextureIndex,UR.getViewPosition,UR.globalId,UR.glsl,UR.glslFn,UR.grayscale,UR.greaterThan,UR.greaterThanEqual,UR.hash,UR.highpModelNormalViewMatrix,UR.highpModelViewMatrix,UR.hue,UR.increment,UR.incrementBefore,UR.instance;const yO=UR.instanceIndex,bO=UR.instancedArray;UR.instancedBufferAttribute,UR.instancedDynamicBufferAttribute,UR.instancedMesh;const xO=UR.int;UR.intBitsToFloat,UR.inverse,UR.inverseSqrt,UR.inversesqrt,UR.invocationLocalIndex,UR.invocationSubgroupIndex,UR.ior,UR.iridescence,UR.iridescenceIOR,UR.iridescenceThickness,UR.ivec2,UR.ivec3,UR.ivec4,UR.js,UR.label,UR.length,UR.lengthSq,UR.lessThan,UR.lessThanEqual,UR.lightPosition,UR.lightProjectionUV,UR.lightShadowMatrix,UR.lightTargetDirection,UR.lightTargetPosition,UR.lightViewPosition,UR.lightingContext,UR.lights,UR.linearDepth,UR.linearToneMapping,UR.localId,UR.log,UR.log2,UR.logarithmicDepthToViewZ,UR.luminance,UR.mat2,UR.mat3;const _O=UR.mat4;UR.matcapUV,UR.materialAO,UR.materialAlphaTest,UR.materialAnisotropy,UR.materialAnisotropyVector,UR.materialAttenuationColor,UR.materialAttenuationDistance,UR.materialClearcoat,UR.materialClearcoatNormal,UR.materialClearcoatRoughness,UR.materialColor,UR.materialDispersion,UR.materialEmissive,UR.materialEnvIntensity,UR.materialEnvRotation,UR.materialIOR,UR.materialIridescence,UR.materialIridescenceIOR,UR.materialIridescenceThickness,UR.materialLightMap,UR.materialLineDashOffset,UR.materialLineDashSize,UR.materialLineGapSize,UR.materialLineScale,UR.materialLineWidth,UR.materialMetalness,UR.materialNormal,UR.materialOpacity,UR.materialPointSize,UR.materialReference,UR.materialReflectivity,UR.materialRefractionRatio,UR.materialRotation,UR.materialRoughness,UR.materialSheen,UR.materialSheenRoughness,UR.materialShininess,UR.materialSpecular,UR.materialSpecularColor,UR.materialSpecularIntensity,UR.materialSpecularStrength,UR.materialThickness,UR.materialTransmission;const wO=UR.max;UR.maxMipLevel,UR.mediumpModelViewMatrix,UR.metalness;const vO=UR.min,TO=UR.mix;UR.mixElement,UR.mod,UR.modInt,UR.modelDirection,UR.modelNormalMatrix,UR.modelPosition,UR.modelRadius,UR.modelScale,UR.modelViewMatrix,UR.modelViewPosition,UR.modelViewProjection,UR.modelWorldMatrix,UR.modelWorldMatrixInverse,UR.morphReference,UR.mrt,UR.mul,UR.mx_aastep,UR.mx_add,UR.mx_atan2,UR.mx_cell_noise_float,UR.mx_contrast,UR.mx_divide,UR.mx_fractal_noise_float,UR.mx_fractal_noise_vec2,UR.mx_fractal_noise_vec3,UR.mx_fractal_noise_vec4,UR.mx_frame,UR.mx_heighttonormal,UR.mx_hsvtorgb,UR.mx_ifequal,UR.mx_ifgreater,UR.mx_ifgreatereq,UR.mx_invert,UR.mx_modulo,UR.mx_multiply,UR.mx_noise_float,UR.mx_noise_vec3,UR.mx_noise_vec4,UR.mx_place2d,UR.mx_power,UR.mx_ramp4,UR.mx_ramplr,UR.mx_ramptb,UR.mx_rgbtohsv,UR.mx_rotate2d,UR.mx_rotate3d,UR.mx_safepower,UR.mx_separate,UR.mx_splitlr,UR.mx_splittb,UR.mx_srgb_texture_to_lin_rec709,UR.mx_subtract,UR.mx_timer,UR.mx_transform_uv,UR.mx_unifiednoise2d,UR.mx_unifiednoise3d,UR.mx_worley_noise_float,UR.mx_worley_noise_vec2,UR.mx_worley_noise_vec3,UR.negate,UR.neutralToneMapping,UR.nodeArray,UR.nodeImmutable,UR.nodeObject,UR.nodeObjectIntent,UR.nodeObjects,UR.nodeProxy,UR.nodeProxyIntent,UR.normalFlat,UR.normalGeometry,UR.normalLocal,UR.normalMap,UR.normalView,UR.normalViewGeometry,UR.normalWorld,UR.normalWorldGeometry;const SO=UR.normalize;UR.not,UR.notEqual,UR.numWorkgroups,UR.objectDirection,UR.objectGroup,UR.objectPosition,UR.objectRadius,UR.objectScale,UR.objectViewPosition,UR.objectWorldMatrix,UR.OnBeforeObjectUpdate,UR.OnBeforeMaterialUpdate,UR.OnObjectUpdate,UR.OnMaterialUpdate,UR.oneMinus,UR.or,UR.orthographicDepthToViewZ,UR.oscSawtooth,UR.oscSine,UR.oscSquare,UR.oscTriangle,UR.output,UR.outputStruct,UR.overlay,UR.overloadingFn,UR.packHalf2x16,UR.packSnorm2x16,UR.packUnorm2x16,UR.parabola,UR.parallaxDirection,UR.parallaxUV,UR.parameter,UR.pass,UR.passTexture,UR.pcurve,UR.perspectiveDepthToViewZ,UR.pmremTexture,UR.pointShadow,UR.pointUV,UR.pointWidth,UR.positionGeometry,UR.positionLocal,UR.positionPrevious,UR.positionView,UR.positionViewDirection,UR.positionWorld,UR.positionWorldDirection,UR.posterize,UR.pow,UR.pow2,UR.pow3,UR.pow4,UR.premultiplyAlpha,UR.property,UR.radians,UR.rand,UR.range,UR.rangeFog,UR.rangeFogFactor,UR.reciprocal,UR.reference,UR.referenceBuffer,UR.reflect,UR.reflectVector,UR.reflectView,UR.reflector,UR.refract,UR.refractVector,UR.refractView,UR.reinhardToneMapping,UR.remap,UR.remapClamp,UR.renderGroup,UR.renderOutput,UR.rendererReference,UR.replaceDefaultUV,UR.rotate,UR.rotateUV,UR.roughness,UR.round,UR.rtt,UR.sRGBTransferEOTF,UR.sRGBTransferOETF,UR.sample,UR.sampler,UR.samplerComparison,UR.saturate,UR.saturation,UR.screen,UR.screenCoordinate,UR.screenDPR,UR.screenSize,UR.screenUV,UR.scriptable,UR.scriptableValue;const MO=UR.select;UR.setCurrentStack,UR.setName,UR.shaderStages,UR.shadow,UR.shadowPositionWorld,UR.shapeCircle,UR.sharedUniformGroup,UR.sheen,UR.sheenRoughness,UR.shiftLeft,UR.shiftRight,UR.shininess,UR.sign,UR.sin,UR.sinc,UR.skinning,UR.smoothstep,UR.smoothstepElement,UR.specularColor,UR.specularF90,UR.spherizeUV,UR.split,UR.spritesheetUV,UR.sqrt,UR.stack,UR.step,UR.stepElement,UR.storage,UR.storageBarrier,UR.storageObject,UR.storageTexture,UR.string,UR.struct,UR.sub,UR.subgroupAdd,UR.subgroupAll,UR.subgroupAnd,UR.subgroupAny,UR.subgroupBallot,UR.subgroupBroadcast,UR.subgroupBroadcastFirst,UR.subBuild,UR.subgroupElect,UR.subgroupExclusiveAdd,UR.subgroupExclusiveMul,UR.subgroupInclusiveAdd,UR.subgroupInclusiveMul,UR.subgroupIndex,UR.subgroupMax,UR.subgroupMin,UR.subgroupMul,UR.subgroupOr,UR.subgroupShuffle,UR.subgroupShuffleDown,UR.subgroupShuffleUp,UR.subgroupShuffleXor,UR.subgroupSize,UR.subgroupXor,UR.tan,UR.tangentGeometry,UR.tangentLocal,UR.tangentView,UR.tangentWorld,UR.texture,UR.texture3D,UR.textureBarrier,UR.textureBicubic,UR.textureBicubicLevel,UR.textureCubeUV,UR.textureLoad,UR.textureSize,UR.textureLevel,UR.textureStore,UR.thickness,UR.time,UR.toneMapping,UR.toneMappingExposure,UR.toonOutlinePass,UR.transformDirection,UR.transformNormal,UR.transformNormalToView,UR.transformedClearcoatNormalView,UR.transformedNormalView,UR.transformedNormalWorld,UR.transmission,UR.transpose,UR.triNoise3D,UR.triplanarTexture,UR.triplanarTextures,UR.trunc;const AO=UR.uint;UR.uintBitsToFloat,UR.uniform,UR.uniformArray,UR.uniformCubeTexture,UR.uniformGroup,UR.uniformFlow,UR.uniformTexture,UR.unpackHalf2x16,UR.unpackSnorm2x16,UR.unpackUnorm2x16,UR.unpremultiplyAlpha,UR.userData,UR.uv,UR.uvec2,UR.uvec3,UR.uvec4,UR.varying,UR.varyingProperty,UR.vec2;const NO=UR.vec3,EO=UR.vec4;UR.vectorComponents,UR.velocity,UR.vertexColor,UR.vertexIndex,UR.vertexStage,UR.vibrance,UR.viewZToLogarithmicDepth,UR.viewZToOrthographicDepth,UR.viewZToPerspectiveDepth,UR.viewport,UR.viewportCoordinate,UR.viewportDepthTexture,UR.viewportLinearDepth,UR.viewportMipTexture,UR.viewportResolution,UR.viewportSafeUV,UR.viewportSharedTexture,UR.viewportSize,UR.viewportTexture,UR.viewportUV,UR.wgsl,UR.wgslFn,UR.workgroupArray,UR.workgroupBarrier,UR.workgroupId,UR.workingToColorSpace,UR.xor;const CO=1e-5,RO=1e-16,PO=1e-16;function BO(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 IO=null;async function DO(e,t,s,i,r=null){const n=await async function(){return null===IO&&(IO=new lO,await IO.init()),IO}();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=bO(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");kn.enabled&&console.log("Number of meshes:",t.length),kn.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}}kn.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;kn.enabled&&console.log(`Processing batch ${s+1}/${a.length} (meshes ${p}-${m-1})`);let g=0,y=0;const b=[];for(let e=p;e<m;e++){const s=t[e].geometry;b.push(y/3),g+=s.attributes.position.array.length,y+=s.index.array.length}const x=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;x.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=b[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){kn.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);kn.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=bO(x,"float"),B=bO(_,"uint"),I=bO(S,"float"),D=bO(A,"uint");let L=bO(new Uint32Array([0]),"uint").toAtomic(),F=bO(new Float32Array(3*C),"float");c+=performance.now()-R;const O=performance.now(),z=uO(()=>{const e=yO.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=_O(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)));dO({start:xO(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=NO(P.element(n.mul(3)),P.element(n.mul(3).add(1)),P.element(n.mul(3).add(2))),c=NO(P.element(l.mul(3)),P.element(l.mul(3).add(1)),P.element(l.mul(3).add(2))),d=NO(P.element(h.mul(3)),P.element(h.mul(3).add(1)),P.element(h.mul(3).add(2))),p=a.mul(EO(u,gO(1))).xyz,m=a.mul(EO(c,gO(1))).xyz,f=a.mul(EO(d,gO(1))).xyz,g=m.sub(p),y=f.sub(p),b=fO(g,y),x=b.dot(b);cO(x.lessThan(gO(4e-16*RO)),()=>{hO()}),cO(b.y.lessThan(0),()=>{hO()});const _=wO(p.y,wO(m.y,f.y));dO({start:xO(0),end:s.toInt(),type:"int",condition:"<",name:"edgeIdx"},({edgeIdx:e})=>{const s=t.add(e.toUint()),i=s.mul(6),r=NO(o.element(i),o.element(i.add(1)),o.element(i.add(2))),n=NO(o.element(i.add(3)),o.element(i.add(4)),o.element(i.add(5))),a=vO(r.y,n.y);cO(_.lessThanEqual(a),()=>{hO()});const l=SO(b),h=l.dot(p).negate(),u=l.y.lessThan(0),c=MO(u,l.negate(),l),d=MO(u,h.negate(),h),g=c.dot(r).add(d),y=c.dot(n).add(d),x=g.lessThan(0),w=y.lessThan(0),v=pO(g).lessThan(gO(CO)),T=x.not().and(w.not()),S=y.sub(g),M=pO(S).lessThan(gO(CO)),A=M.and(v.or(x.not()));cO(A,()=>{hO()}),cO(T.and(M.not()),()=>{hO()});const N=g.negate().div(S),E=TO(r,n,N),R=NO(MO(M.or(x),r.x,E.x),MO(M.or(x),r.y,E.y),MO(M.or(x),r.z,E.z)),P=NO(MO(M.or(w),n.x,E.x),MO(M.or(w),n.y,E.y),MO(M.or(w),n.z,E.z)),B=P.sub(R),I=B.dot(B);cO(I.lessThan(gO(CO)),()=>{hO()});const D=r.sub(p),O=r.sub(m),z=r.sub(f),V=n.sub(p),k=n.sub(m),U=n.sub(f),G=D.dot(D).lessThanEqual(gO(CO)),j=O.dot(O).lessThanEqual(gO(CO)),$=z.dot(z).lessThanEqual(gO(CO)),W=V.dot(V).lessThanEqual(gO(CO)),H=k.dot(k).lessThanEqual(gO(CO)),q=U.dot(U).lessThanEqual(gO(CO)),X=G.or(j).or($),Y=W.or(H).or(q),Z=X.and(Y);cO(Z,()=>{hO()});const Q=NO(p.x,gO(0),p.z),K=NO(m.x,gO(0),m.z),J=NO(f.x,gO(0),f.z),ee=NO(R.x,gO(0),R.z),te=NO(P.x,gO(0),P.z),se=NO(r.x,gO(0),r.z),ie=NO(n.x,gO(0),n.z).sub(se),re=ie.dot(ie);cO(re.lessThan(gO(CO)),()=>{hO()});const ne=re.sqrt(),oe=K.sub(Q),ae=J.sub(Q),le=fO(oe,ae),he=le.dot(le);cO(he.lessThanEqual(gO(4e-16*RO)),()=>{hO()});const ue=te.sub(ee),ce=ue.dot(ue);cO(ce.lessThan(gO(CO)),()=>{hO()});const de=ce.sqrt(),pe=ue.div(de),me=ie.div(ne),fe=SO(le),ge=fO(pe,fe),ye=gO(0).toVar(),be=gO(0).toVar(),xe=gO(0).toVar(),_e=gO(0).toVar(),we=AO(0).toVar(),ve=ge.dot(Q.sub(ee)),Te=ge.dot(K.sub(ee)),Se=pO(ve).lessThan(gO(PO)),Me=pO(Te).lessThan(gO(PO)),Ae=Se.not().and(Me.not()).and(ve.mul(Te).lessThan(0));cO(Ae,()=>{const e=ve.div(ve.sub(Te)),t=TO(Q.x,K.x,e),s=TO(Q.z,K.z,e);cO(we.equal(0),()=>{ye.assign(t),be.assign(s)}).Else(()=>{xe.assign(t),_e.assign(s)}),we.addAssign(1)}).ElseIf(Se,()=>{cO(we.equal(0),()=>{ye.assign(Q.x),be.assign(Q.z)}).Else(()=>{xe.assign(Q.x),_e.assign(Q.z)}),we.addAssign(1)});const Ne=Te,Ee=ge.dot(J.sub(ee)),Ce=Me,Re=pO(Ee).lessThan(gO(PO)),Pe=Ce.not().and(Re.not()).and(Ne.mul(Ee).lessThan(0));cO(we.lessThan(2),()=>{cO(Pe,()=>{const e=Ne.div(Ne.sub(Ee)),t=TO(K.x,J.x,e),s=TO(K.z,J.z,e);cO(we.equal(0),()=>{ye.assign(t),be.assign(s)}).Else(()=>{xe.assign(t),_e.assign(s)}),we.addAssign(1)}).ElseIf(Ce.and(Ae.not()).and(Se.not()),()=>{cO(we.equal(0),()=>{ye.assign(K.x),be.assign(K.z)}).Else(()=>{xe.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));cO(we.lessThan(2),()=>{cO(Fe,()=>{const e=Be.div(Be.sub(Ie)),t=TO(J.x,Q.x,e),s=TO(J.z,Q.z,e);cO(we.equal(0),()=>{ye.assign(t),be.assign(s)}).Else(()=>{xe.assign(t),_e.assign(s)}),we.addAssign(1)}).ElseIf(De.and(Pe.not()).and(Ce.not()),()=>{cO(we.equal(0),()=>{ye.assign(J.x),be.assign(J.z)}).Else(()=>{xe.assign(J.x),_e.assign(J.z)}),we.addAssign(1)})}),cO(we.notEqual(2),()=>{hO()});const Oe=NO(ye,gO(0),be),ze=NO(xe,gO(0),_e).sub(Oe).dot(pe),Ve=NO(ye,gO(0),be).toVar(),ke=NO(xe,gO(0),_e).toVar();cO(ze.lessThan(0),()=>{const e=ye,t=be;Ve.x.assign(xe),Ve.z.assign(_e),ke.x.assign(e),ke.z.assign(t)});const Ue=gO(0),Ge=de,je=Ve.sub(ee).dot(pe),$e=ke.sub(ee).dot(pe),We=Ge.lessThanEqual(je).or($e.lessThanEqual(Ue));cO(We,()=>{hO()});const He=wO(Ue,je),qe=vO(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=wO(gO(0),vO(gO(1),Ze)),Je=wO(gO(0),vO(gO(1),Qe)),et=pO(Je.sub(Ke));cO(et.lessThanEqual(gO(PO)),()=>{hO()});const tt=mO(L.element(0),1);cO(tt.lessThan(AO(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 V=performance.now();await n.computeAsync(z),l+=performance.now()-V;const k=performance.now(),U=await n.getArrayBufferAsync(L.value),G=new Uint32Array(U)[0];if(r&&(r.used+=Math.min(G,C)),kn.enabled&&console.log(` Batch ${s+1}: ${G} overlaps found (capacity: ${C})`),G>C&&kn.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]);En([t[s+1],t[s+2]],i[r])}u+=performance.now()-s,kn.enabled&&console.log(` Processed ${r} overlaps into hiddenOverlapMap`)}else h+=performance.now()-k}n.dispose(),IO=null;const p=c+d+l+h+u;kn.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 LO=new u(0,1,0);function FO(e,t=null){const s=new Float32Array(6*e.length);let i=0;for(let t=0,r=e.length;t<r;t++){const r=e[t];s[i++]=r[0],s[i++]=0,s[i++]=r[2],s[i++]=r[3],s[i++]=0,s[i++]=r[5]}const r=new F,n=new h(s,3,!0);if(r.setAttribute("position",n),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];r.setAttribute("group",new h(s,1))}return r}class OO{constructor(e,t=!0){this.meshes=tn(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 FO(this.visibleEdges,this.groupKeyToIndex?this.visibleGroupIndices:null)}getHiddenLineGeometry(){return FO(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();kn.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 yr(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]=[];kn.startStep("Building line BVH");const u=new ln(e,{maxLeafSize:2,strategy:2});kn.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?BO(u,i.get(r.geometry),r,p,e):In(u,i.get(r.geometry),r,h,c)}if(d){let e=!1;for(DO(p,s,u,h,c).then(()=>{e=!0});!e;)yield}const m=c.totalEdges*c.totalTriangles;if(kn.setStat("Total edges",c.totalEdges.toLocaleString()),kn.setStat("Total triangles",c.totalTriangles.toLocaleString()),kn.setStat("Brute-force pairs (edges × triangles)",m.toLocaleString()),kn.setStat("BVH candidate pairs",c.candidates.toLocaleString()),m>0&&kn.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||(kn.setStat("Rejected: back-face culling",c.backFaceCulled.toLocaleString()+" ("+t(c.backFaceCulled)+")"),kn.setStat("Rejected: Y-bounds (tri below edge)",c.yBoundsCulled.toLocaleString()+" ("+t(c.yBoundsCulled)+")"),kn.setStat("Rejected: XZ-bounds (no 2D overlap)",c.xzBoundsCulled.toLocaleString()+" ("+t(c.xzBoundsCulled)+")"),kn.setStat("Rejected: edge lies on triangle",c.triangleEdgeCulled.toLocaleString()+" ("+t(c.triangleEdgeCulled)+")"),kn.setStat("Rejected: line above tri plane",c.planeTrimCulled.toLocaleString()+" ("+t(c.planeTrimCulled)+")"),kn.setStat("Rejected: trimmed edge too small",c.distThresholdCulled.toLocaleString()+" ("+t(c.distThresholdCulled)+")"),kn.setStat("Rejected: no projected overlap",c.noOverlapCulled.toLocaleString()+" ("+t(c.noOverlapCulled)+")")),kn.setStat("Producing overlaps",c.used.toLocaleString()+" ("+t(c.used)+")")}kn.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(Wr(s,i,!1,r),Wr(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 zO{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:i,includeIntersectionEdges:r}=this,{onProgress:n=()=>{},visibilityCuller:o=null,groupFn:a=null}=t;if(kn.reset(),kn.startTotal(),e.isBufferGeometry&&(e=new _(e)),o){kn.startStep("Visibility culling");let t=!1;for(o.cull(e).then(s=>{(e=new C).children=s,t=!0});!t;)yield}const l=new on;l.iterationTime=s,l.thresholdAngle=i,l.projectionDirection.copy(LO),kn.startStep("Generating candidate edges"),n("Generating candidate edges");let h=[],u=a?[]:null;if(yield*l.getEdgesGenerator(e,h,u),r&&(kn.startStep("Generating intersection edges"),n("Generating intersection edges"),yield*l.getIntersectionEdgesGenerator(e,h,u)),kn.startStep("Pre-filtering edges"),n("Pre-filtering edges"),u){const e=[],t=[];for(let s=0;s<h.length;s++)Gr(h[s])||(e.push(h[s]),t.push(u[s]));h=e,u=t}else h=h.filter(e=>!Gr(e));yield;const c=new OO(e,this.useWebGPU);if(c.iterationTime=s,a&&u){const e=new Map;for(let t=0;t<h.length;t++){const s=a(u[t]);e.has(s)||e.set(s,e.size),h[t].groupIndex=e.get(s)}c.groupKeyToIndex=e,c.hasGroups=!0}return n("Building BVH & computing overlaps"),yield*c.addEdgesGenerator(h,{onProgress:n?(e,t)=>{n("Building BVH & computing overlaps",e/t,c)}:null}),kn.printSummary(),c}}new c,new c,new u;const VO=class e extends se{constructor(s){super(s),t(this,"enabled",!0),t(this,"onDisposed",new J),t(this,"generator",new zO),t(this,"cullerPixelsPerMeter",.05),t(this,"projectionDirection",new o.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(Lr),r=new o.Group,n=new Map;for(const[t,s]of Object.entries(e)){const e=i.list.get(t);if(!e)continue;const a=(await e.getItemsIdsWithGeometry()).filter(e=>s.has(e));if(0===a.length)continue;const l=await e.getItemsGeometry(a);for(const s in l){const i=l[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 o.BufferGeometry;e.setAttribute("position",new o.Float32BufferAttribute(s.positions,3)),s.normals&&e.setAttribute("normal",new o.Float32BufferAttribute(s.normals,3)),e.setIndex(Array.from(s.indices)),n.set(i,e)}const a=n.get(i),l=new o.Mesh(a);l.applyMatrix4(s.transform),l.applyMatrix4(e.object.matrixWorld),l.updateWorldMatrix(!0,!0),l.userData._edgeProjectorModelId=t,l.userData._edgeProjectorLocalId=s.localId,r.add(l)}}}const a=this.projectionDirection.clone().normalize(),l=new o.Vector3(0,-1,0),h=(new o.Quaternion).setFromUnitVectors(a,l),u=(new o.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 yr(t.geometry,{maxLeafSize:1,strategy:2})}}),this.nearPlane!==-1/0||this.farPlane!==1/0){const e=new o.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 Or(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(),b={};for(const[e,t]of Object.entries(y)){const s=e.lastIndexOf(":"),i=e.substring(0,s),r=Number(e.substring(s+1));b[t]={modelId:i,localId:r}}for(const e of n.values())e.dispose();return{visible:f,hidden:g,groups:b}}dispose(){this.onDisposed.trigger(e.uuid),this.onDisposed.reset()}};t(VO,"uuid","f2e76c3a-8b1d-4d5e-9a3f-7c6b2d4e8f1a");let kO=VO;class UO{constructor(){t(this,"wasm",{path:"",absolute:!1,logLevel:Q.LogLevel.LOG_LEVEL_OFF}),t(this,"webIfc",{COORDINATE_TO_ORIGIN:!0}),t(this,"autoSetWasm",!0),t(this,"customLocateFileHandler",null)}}const GO=class e extends se{constructor(s){super(s),t(this,"onDisposed",new J),t(this,"onIfcStartedLoading",new J),t(this,"onIfcImporterInitialized",new J),t(this,"onSetup",new J),t(this,"settings",new UO),t(this,"webIfc",new Q.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,r){const n=this.components.get(Lr);if(!n.initialized)throw new Error("You need to initialize fragments first.");this.settings.autoSetWasm&&await this.autoSetWasm(),n.core.settings.autoCoordinate=t;const o=new s.IfcImporter;o.wasm.path=this.settings.wasm.path,o.wasm.absolute=this.settings.wasm.absolute,o.webIfcSettings=this.settings.webIfc,this.onIfcImporterInitialized.trigger(o),(null==r?void 0:r.instanceCallback)&&r.instanceCallback(o);const a=await o.process({...null==r?void 0:r.processData,bytes:e});return await n.core.load(a,{modelId:i,userData:null==r?void 0:r.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 Q.IfcAPI}async autoSetWasm(){const e=await fetch(`https://unpkg.com/@thatopen/components@${_z.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(GO,"uuid","a659add7-1418-4771-a0d6-7d4d438e4624");let jO=GO;const $O=class e extends se{constructor(s){super(s),t(this,"enabled",!0),this.components.add(e.uuid,this)}async set(e,t){const s=this.components.get(Lr),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(Lr);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(Lr);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($O,"uuid","dd9ccf2d-8a21-4821-b7f6-2949add16a29");let WO=$O;const HO=class e extends se{constructor(i){super(i),t(this,"enabled",!0),t(this,"onDisposed",new J),t(this,"list",new s.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 o.Box3;for(const t of this.list)e.union(t);return e}async addFromModelIdMap(e){const t=this.components.get(Lr),s=new o.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(Lr);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 o.Vector3;return t.getCenter(s),s}async getCameraOrientation(e,t=1){const s=this.components.get(Lr);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 o.Vector3;i.getCenter(r);const n=new o.Vector3;i.getSize(n);const a=Math.max(n.x,n.y,n.z)*t,l=new o.Vector3;switch(e){case"front":default:l.set(r.x,r.y,r.z+a);break;case"back":l.set(r.x,r.y,r.z-a);break;case"left":l.set(r.x-a,r.y,r.z);break;case"right":l.set(r.x+a,r.y,r.z);break;case"top":l.set(r.x,r.y+a,r.z);break;case"bottom":l.set(r.x,r.y-a,r.z)}return{position:l,target:r}}};t(HO,"uuid","d1444724-dba6-4cdd-a0c7-68ee1450d166");let qO=HO;class XO{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(ZO),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(ZO).list.getKey(this)??ce.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 YO=class e extends se{constructor(i){super(i),t(this,"enabled",!0),t(this,"list",new s.DataMap),i.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(Lr),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?Et.join(n):Et.intersect(n)}create(e,t){const s=new XO(this.components,t);return this.list.set(e,s),s}async addFromCategories(e){const t=new Set,s=this.components.get(Lr);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(YO,"uuid","0da7ad77-f734-42ca-942f-a074adfd1e3a");let ZO=YO;const QO=class e extends se{constructor(i){super(i),t(this,"enabled",!0),t(this,"onDisposed",new J),t(this,"list",new s.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)}),i.add(e.uuid,this),this.setupEvents();i.get(Lr).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 s.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(ZO),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=Et.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(Lr),o=this.components.get(ZO),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);Et.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=Et.join(e);t.push(n)}return Et.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(ZO),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(Lr).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)Et.remove(t.map,e);return}for(const[,t]of this.list.entries())for(const[,s]of t)Et.remove(s.map,e)}async byModel(e){const t=this.components.get(Lr),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(QO,"uuid","e25a7f3c-46c4-4a14-9d3d-5115f24ebeb7");let KO=QO;class JO{constructor(e,s){t(this,"enabled",!0),t(this,"components"),t(this,"onDisposed",new J),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 o.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 Lt(i.three.domElement),this.components=e,this.setupRenderTarget(),this.setupFragmentListeners()}setupFragmentListeners(){const e=this.components.get(Lr);e.list.onItemSet.add(()=>{this.colorsNeedUpdate=!0}),e.list.onItemDeleted.add(()=>{this.colorsNeedUpdate=!0})}setupRenderTarget(){const e=this.world.renderer.three.getSize(new o.Vector2);this.renderTargetSize.copy(e),this.renderTarget=new o.WebGLRenderTarget(e.x,e.y),this.renderTarget.texture.format=o.RGBAFormat,this.renderTarget.texture.type=o.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 o.Vector2);this.debugContainer=document.createElement("div"),this.debugContainer.style.position="fixed",this.debugContainer.style.top="10px",this.debugContainer.style.right="10px",this.debugContainer.style.width="300px",this.debugContainer.style.height="300px",this.debugContainer.style.border="2px solid #fff",this.debugContainer.style.backgroundColor="#000",this.debugContainer.style.zIndex="10000",this.debugContainer.style.pointerEvents="none",this.debugCanvas=document.createElement("canvas"),this.debugCanvas.width=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 o.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(Lr);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 o.MeshBasicMaterial({color:e,depthTest:!0,depthWrite:!0});this.colorMaterials.set(t,i)}this.colorsNeedUpdate=!1}}}applyColorMaterials(){const e=this.components.get(Lr);if(e.initialized)for(const[t,s]of e.list){const e=this.colorMaterials.get(t);e&&s.object.traverse(t=>{if(t instanceof o.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 o.Color,a=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,a),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(Lr);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 ez=class e extends se{constructor(s){super(s),t(this,"enabled",!0),t(this,"list",new Map),t(this,"onDisposed",new J),s.add(e.uuid,this)}get(e){if(this.list.has(e.uuid))return this.list.get(e.uuid);const t=new JO(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(ez,"uuid","4a82430c-7ff2-49ea-9401-60807502dad6");let tz=ez;class sz{constructor(e,s){t(this,"enabled",!0),t(this,"components"),t(this,"onDisposed",new J),t(this,"mouse"),t(this,"three",new o.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 Lt(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(Lr),o=this.world.renderer.three.domElement,a=this.mouse.rawPosition;let l=null;if(n.initialized){if(this.useFastModelPicking){const e=this.components.get(tz).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 iz=class e extends se{constructor(s){super(s),t(this,"enabled",!0),t(this,"list",new Map),t(this,"onDisposed",new J),s.add(e.uuid,this)}get(e){if(this.list.has(e.uuid))return this.list.get(e.uuid);const t=new sz(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(iz,"uuid","d5d8bdf0-db25-4952-b951-b643af207ace");let rz=iz;class nz extends te{constructor(){super(...arguments),t(this,"onCameraChanged",new J),t(this,"meshes",new Set),t(this,"onAfterUpdate",new J),t(this,"onBeforeUpdate",new J),t(this,"onDisposed",new J),t(this,"isDisposing",!1),t(this,"enabled",!0),t(this,"_dynamicAnchor",!1),t(this,"uuid",ce.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(rz).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(ae);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(mz).list.delete(this.uuid),this.onDisposed.trigger(),this.onDisposed.reset()}}class oz{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 az{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 lz extends Bt{constructor(){super(...arguments),t(this,"_config",{backgroundColor:{value:new o.Color,type:"Color"},ambientLight:{color:{type:"Color",value:new o.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2}},directionalLight:{color:{type:"Color",value:new o.Color},intensity:{type:"Number",interpolable:!0,min:0,max:10,value:2},position:{type:"Vector3",value:new o.Vector3}}}),t(this,"ambientLight",new az(this._config,this._component)),t(this,"directionalLight",new oz(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 hz extends le{constructor(e){super(e),t(this,"onSetup",new J),t(this,"isSetup",!1),t(this,"three"),t(this,"config",new lz(this,this.components,"Scene")),t(this,"_defaultConfig",{backgroundColor:new o.Color(2107698),directionalLight:{color:new o.Color("white"),intensity:1.5,position:new o.Vector3(5,10,3)},ambientLight:{color:new o.Color("white"),intensity:1}}),this.three=new o.Scene,this.three.background=new o.Color(2107698)}setup(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,a=new o.DirectionalLight(r,n);a.position.copy(i.position);const{color:l,intensity:h}=this.config.directionalLight,u=new o.AmbientLight(l,h);this.three.add(a,u),this.directionalLights.set(a.uuid,a),this.ambientLights.set(u.uuid,u),this.isSetup=!0,this.onSetup.trigger()}dispose(){super.dispose();this.components.get(Dt).list.delete(this.config.uuid)}}var uz=(e=>(e[e.MANUAL=0]="MANUAL",e[e.AUTO=1]="AUTO",e))(uz||{});class cz extends ne{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 J),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 o.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 o.WebGLRenderer({canvas:this._canvas,antialias:!0,alpha:!0,...this._parameters}),this.enabled=!0}),this.container=s,this._parameters=i,this.three=new o.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 o.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()}}class dz extends re{constructor(e){super(e),t(this,"onBeforeUpdate",new J),t(this,"onAfterUpdate",new J),t(this,"onAspectUpdated",new J),t(this,"onDisposed",new J),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 o.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(Lr),s=this.components.get(qO);s.list.clear();const i=new o.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 o.PerspectiveCamera(60,e,1,1e3);return t.position.set(50,50,50),t.lookAt(new o.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!");K.install({THREE:dz.getSubsetOfThree()});const{domElement:e}=this.currentWorld.renderer.three,t=new K(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:o.MOUSE,Vector2:o.Vector2,Vector3:o.Vector3,Vector4:o.Vector4,Quaternion:o.Quaternion,Matrix4:o.Matrix4,Spherical:o.Spherical,Box3:o.Box3,Sphere:o.Sphere,Raycaster:o.Raycaster,MathUtils:o.MathUtils}}}const pz=class e extends se{constructor(s){super(s),t(this,"onAfterUpdate",new J),t(this,"onBeforeUpdate",new J),t(this,"onDisposed",new J),t(this,"list",new i),t(this,"enabled",!0),s.add(e.uuid,this)}create(){const e=new nz(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(pz,"uuid","fdb61dc4-2ec1-4966-b83d-54ea795fad4a");let mz=pz;class fz extends Bt{constructor(){super(...arguments),t(this,"_config",{visible:{value:!0,type:"Boolean"},color:{value:new o.Color,type:"Color"},primarySize:{type:"Number",interpolable:!0,value:1,min:0,max:1e3},secondarySize:{type:"Number",interpolable:!0,value:10,min:0,max:1e3},distance:{type:"Number",interpolable:!0,value:500,min:0,max:500}})}get visible(){return this._config.visible.value}set visible(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 gz{constructor(e,s){t(this,"onDisposed",new J),t(this,"onSetup",new J),t(this,"isSetup",!1),t(this,"world"),t(this,"components"),t(this,"config"),t(this,"_defaultConfig",{visible:!0,color:new o.Color(12303291),primarySize:1,secondarySize:10,distance:500}),t(this,"three"),t(this,"_fade",3),t(this,"updateZoom",()=>{this.world.camera instanceof dz&&(this.material.uniforms.uZoom.value=this.world.camera.three.zoom)}),this.world=s;const{color:i,primarySize:r,secondarySize:n,distance:a}=this._defaultConfig;this.components=e,this.config=new fz(this,this.components,"Grid");const l=new o.PlaneGeometry(2,2,1,1),h=new o.ShaderMaterial({side:o.DoubleSide,uniforms:{uSize1:{value:r},uSize2:{value:n},uColor:{value:i},uDistance:{value:a},uFade:{value:this._fade},uZoom:{value:1}},transparent:!0,vertexShader:"\n \n varying vec3 worldPosition;\n \n uniform float uDistance;\n \n void main() {\n \n vec3 pos = position.xzy * uDistance;\n pos.xz += cameraPosition.xz;\n \n worldPosition = pos;\n \n gl_Position = projectionMatrix * modelViewMatrix * vec4(pos, 1.0);\n \n }\n ",fragmentShader:"\n \n varying vec3 worldPosition;\n \n uniform float uZoom;\n uniform float uFade;\n uniform float uSize1;\n uniform float uSize2;\n uniform vec3 uColor;\n uniform float uDistance;\n \n \n \n float getGrid(float size) {\n \n vec2 r = worldPosition.xz / size;\n \n \n vec2 grid = abs(fract(r - 0.5) - 0.5) / fwidth(r);\n float line = min(grid.x, grid.y);\n \n \n return 1.0 - min(line, 1.0);\n }\n \n void main() {\n \n \n float d = 1.0 - min(distance(cameraPosition.xz, worldPosition.xz) / uDistance, 1.0);\n \n float g1 = getGrid(uSize1);\n float g2 = getGrid(uSize2);\n \n // Ortho camera fades the grid away when zooming out\n float minZoom = step(0.2, uZoom);\n float zoomFactor = pow(min(uZoom, 1.), 2.) * minZoom;\n \n gl_FragColor = vec4(uColor.rgb, mix(g2, g1, g1) * pow(d, uFade));\n gl_FragColor.a = mix(0.5 * gl_FragColor.a, gl_FragColor.a, g2) * zoomFactor;\n \n if ( gl_FragColor.a <= 0.0 ) discard;\n \n \n }\n \n ",extensions:{derivatives:!0}});this.three=new o.Mesh(l,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(Dt).list.delete(this.config.uuid);this.components.get(ae).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 dz))return;const t=this.world.camera.controls;e?t.addEventListener("update",this.updateZoom):t.removeEventListener("update",this.updateZoom)}}const yz=class e extends se{constructor(s){super(s),t(this,"list",new Map),t(this,"onDisposed",new J),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 gz(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(yz,"uuid","d1e814d5-b81c-4452-87a2-f039375e0489");let bz=yz;const xz=class e{constructor(){t(this,"onDisposed",new J),t(this,"list",new i),t(this,"enabled",!1),t(this,"_clock"),t(this,"onInit",new J),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 o.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.");ce.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!==Lr.uuid?s.isDisposeable()&&s.dispose():e=s;null==e||e.dispose(),this._clock.stop(),this.onDisposed.trigger()}static setupBVH(){o.BufferGeometry.prototype.computeBoundsTree=Br,o.BufferGeometry.prototype.disposeBoundsTree=Ir,o.Mesh.prototype.raycast=Rr,o.LineSegments.prototype.raycast=Rr}};t(xz,"release","2.4.3");let _z=xz;class wz{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 o.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=K.ACTION.DOLLY,e.touches.two=K.ACTION.TOUCH_ZOOM_TRUCK}}class vz{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 o.Vector3;e.getPosition(t);const s=t.length();e.distance=s,e.truckSpeed=2;const{rotation:i}=this.camera.three,r=new o.Vector3(0,0,-1).applyEuler(i),n=t.addScaledVector(r,s);e.moveTo(n.x,n.y,n.z)}}class Tz{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=K.ACTION.TRUCK,t.touches.one=K.ACTION.TOUCH_TRUCK,t.touches.two=K.ACTION.TOUCH_ZOOM):(t.mouseButtons.left=K.ACTION.ROTATE,t.touches.one=this.mouseAction1,t.touches.two=this.mouseAction2)}}class Sz{constructor(e){t(this,"onChanged",new J),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 o.Vector3;this._component.threePersp.getWorldDirection(t);const s=new o.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,a=this._component.threePersp,l=2*i*Math.atan(a.fov*(Math.PI/180)/2);return{width:l*n,height:l}}setupOrthoCamera(e,t){this._component.controls.mouseButtons.wheel=K.ACTION.ZOOM,this._component.controls.mouseButtons.middle=K.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=K.ACTION.DOLLY,this._component.controls.mouseButtons.middle=K.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=K.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 Mz extends dz{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 Sz(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 vz(this)),this._navigationModes.set("FirstPerson",new wz(this)),this._navigationModes.set("Plan",new Tz(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 o.Vector3(s,s,s),n=new o.Vector3(i,i,i);for(const t of e){const e=(new o.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 a=new o.Box3(r,n),l=this.components.get(Lr);if(l.initialized)for(const[,e]of l.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 o.Vector3;a.getSize(h);const u=new o.Vector3;a.getCenter(u);const c=Math.max(h.x,h.y,h.z)*t,d=new o.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 o.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 Az="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:{};function Nz(e){return e&&e.__esModule&&Object.prototype.hasOwnProperty.call(e,"default")?e.default:e}function Ez(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 Cz={exports:{}};
8
17
  /*!
9
18
 
10
19
  JSZip v3.10.1 - A JavaScript class for generating and reading zip files
@@ -15,4 +24,4 @@ Dual licenced under the MIT license or GPLv3. See https://raw.github.com/Stuk/js
15
24
 
16
25
  JSZip uses the library pako released under the MIT license :
17
26
  https://github.com/nodeca/pako/blob/main/LICENSE
18
- */const Rr=K(Lr.exports=function t(e,i,s){function n(o,a){if(!i[o]){if(!e[o]){if(!a&&Ur)return Ur(o);if(r)return r(o,!0);var l=new Error("Cannot find module '"+o+"'");throw l.code="MODULE_NOT_FOUND",l}var h=i[o]={exports:{}};e[o][0].call(h.exports,function(t){return n(e[o][1][t]||t)},h,h.exports,t,e,i,s)}return i[o].exports}for(var r=Ur,o=0;o<s.length;o++)n(s[o]);return n}({1:[function(t,e,i){var s=t("./utils"),n=t("./support"),r="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";i.encode=function(t){for(var e,i,n,o,a,l,h,c=[],d=0,u=t.length,p=u,f="string"!==s.getTypeOf(t);d<t.length;)p=u-d,n=f?(e=t[d++],i=d<u?t[d++]:0,d<u?t[d++]:0):(e=t.charCodeAt(d++),i=d<u?t.charCodeAt(d++):0,d<u?t.charCodeAt(d++):0),o=e>>2,a=(3&e)<<4|i>>4,l=1<p?(15&i)<<2|n>>6:64,h=2<p?63&n:64,c.push(r.charAt(o)+r.charAt(a)+r.charAt(l)+r.charAt(h));return c.join("")},i.decode=function(t){var e,i,s,o,a,l,h=0,c=0,d="data:";if(t.substr(0,d.length)===d)throw new Error("Invalid base64 input, it looks like a data url.");var u,p=3*(t=t.replace(/[^A-Za-z0-9+/=]/g,"")).length/4;if(t.charAt(t.length-1)===r.charAt(64)&&p--,t.charAt(t.length-2)===r.charAt(64)&&p--,p%1!=0)throw new Error("Invalid base64 input, bad content length.");for(u=n.uint8array?new Uint8Array(0|p):new Array(0|p);h<t.length;)e=r.indexOf(t.charAt(h++))<<2|(o=r.indexOf(t.charAt(h++)))>>4,i=(15&o)<<4|(a=r.indexOf(t.charAt(h++)))>>2,s=(3&a)<<6|(l=r.indexOf(t.charAt(h++))),u[c++]=e,64!==a&&(u[c++]=i),64!==l&&(u[c++]=s);return u}},{"./support":30,"./utils":32}],2:[function(t,e,i){var s=t("./external"),n=t("./stream/DataWorker"),r=t("./stream/Crc32Probe"),o=t("./stream/DataLengthProbe");function a(t,e,i,s,n){this.compressedSize=t,this.uncompressedSize=e,this.crc32=i,this.compression=s,this.compressedContent=n}a.prototype={getContentWorker:function(){var t=new n(s.Promise.resolve(this.compressedContent)).pipe(this.compression.uncompressWorker()).pipe(new o("data_length")),e=this;return t.on("end",function(){if(this.streamInfo.data_length!==e.uncompressedSize)throw new Error("Bug : uncompressed data size mismatch")}),t},getCompressedWorker:function(){return new n(s.Promise.resolve(this.compressedContent)).withStreamInfo("compressedSize",this.compressedSize).withStreamInfo("uncompressedSize",this.uncompressedSize).withStreamInfo("crc32",this.crc32).withStreamInfo("compression",this.compression)}},a.createWorkerFrom=function(t,e,i){return t.pipe(new r).pipe(new o("uncompressedSize")).pipe(e.compressWorker(i)).pipe(new o("compressedSize")).withStreamInfo("compression",e)},e.exports=a},{"./external":6,"./stream/Crc32Probe":25,"./stream/DataLengthProbe":26,"./stream/DataWorker":27}],3:[function(t,e,i){var s=t("./stream/GenericWorker");i.STORE={magic:"\0\0",compressWorker:function(){return new s("STORE compression")},uncompressWorker:function(){return new s("STORE decompression")}},i.DEFLATE=t("./flate")},{"./flate":7,"./stream/GenericWorker":28}],4:[function(t,e,i){var s=t("./utils"),n=function(){for(var t,e=[],i=0;i<256;i++){t=i;for(var s=0;s<8;s++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e}();e.exports=function(t,e){return void 0!==t&&t.length?"string"!==s.getTypeOf(t)?function(t,e,i,s){var r=n,o=s+i;t^=-1;for(var a=s;a<o;a++)t=t>>>8^r[255&(t^e[a])];return-1^t}(0|e,t,t.length,0):function(t,e,i,s){var r=n,o=s+i;t^=-1;for(var a=s;a<o;a++)t=t>>>8^r[255&(t^e.charCodeAt(a))];return-1^t}(0|e,t,t.length,0):0}},{"./utils":32}],5:[function(t,e,i){i.base64=!1,i.binary=!1,i.dir=!1,i.createFolders=!0,i.date=null,i.compression=null,i.compressionOptions=null,i.comment=null,i.unixPermissions=null,i.dosPermissions=null},{}],6:[function(t,e,i){var s=null;s="undefined"!=typeof Promise?Promise:t("lie"),e.exports={Promise:s}},{lie:37}],7:[function(t,e,i){var s="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Uint32Array,n=t("pako"),r=t("./utils"),o=t("./stream/GenericWorker"),a=s?"uint8array":"array";function l(t,e){o.call(this,"FlateWorker/"+t),this._pako=null,this._pakoAction=t,this._pakoOptions=e,this.meta={}}i.magic="\b\0",r.inherits(l,o),l.prototype.processChunk=function(t){this.meta=t.meta,null===this._pako&&this._createPako(),this._pako.push(r.transformTo(a,t.data),!1)},l.prototype.flush=function(){o.prototype.flush.call(this),null===this._pako&&this._createPako(),this._pako.push([],!0)},l.prototype.cleanUp=function(){o.prototype.cleanUp.call(this),this._pako=null},l.prototype._createPako=function(){this._pako=new n[this._pakoAction]({raw:!0,level:this._pakoOptions.level||-1});var t=this;this._pako.onData=function(e){t.push({data:e,meta:t.meta})}},i.compressWorker=function(t){return new l("Deflate",t)},i.uncompressWorker=function(){return new l("Inflate",{})}},{"./stream/GenericWorker":28,"./utils":32,pako:38}],8:[function(t,e,i){function s(t,e){var i,s="";for(i=0;i<e;i++)s+=String.fromCharCode(255&t),t>>>=8;return s}function n(t,e,i,n,o,c){var d,u,p=t.file,f=t.compression,m=c!==a.utf8encode,g=r.transformTo("string",c(p.name)),_=r.transformTo("string",a.utf8encode(p.name)),y=p.comment,w=r.transformTo("string",c(y)),v=r.transformTo("string",a.utf8encode(y)),b=_.length!==p.name.length,x=v.length!==y.length,T="",E="",C="",S=p.dir,A=p.date,O={crc32:0,compressedSize:0,uncompressedSize:0};e&&!i||(O.crc32=t.crc32,O.compressedSize=t.compressedSize,O.uncompressedSize=t.uncompressedSize);var P=0;e&&(P|=8),m||!b&&!x||(P|=2048);var I,k,D,z=0,M=0;S&&(z|=16),"UNIX"===o?(M=798,z|=(I=p.unixPermissions,k=S,D=I,I||(D=k?16893:33204),(65535&D)<<16)):(M=20,z|=function(t){return 63&(t||0)}(p.dosPermissions)),d=A.getUTCHours(),d<<=6,d|=A.getUTCMinutes(),d<<=5,d|=A.getUTCSeconds()/2,u=A.getUTCFullYear()-1980,u<<=4,u|=A.getUTCMonth()+1,u<<=5,u|=A.getUTCDate(),b&&(E=s(1,1)+s(l(g),4)+_,T+="up"+s(E.length,2)+E),x&&(C=s(1,1)+s(l(w),4)+v,T+="uc"+s(C.length,2)+C);var B="";return B+="\n\0",B+=s(P,2),B+=f.magic,B+=s(d,2),B+=s(u,2),B+=s(O.crc32,4),B+=s(O.compressedSize,4),B+=s(O.uncompressedSize,4),B+=s(g.length,2),B+=s(T.length,2),{fileRecord:h.LOCAL_FILE_HEADER+B+g+T,dirRecord:h.CENTRAL_FILE_HEADER+s(M,2)+B+s(w.length,2)+"\0\0\0\0"+s(z,4)+s(n,4)+g+T+w}}var r=t("../utils"),o=t("../stream/GenericWorker"),a=t("../utf8"),l=t("../crc32"),h=t("../signature");function c(t,e,i,s){o.call(this,"ZipFileWorker"),this.bytesWritten=0,this.zipComment=e,this.zipPlatform=i,this.encodeFileName=s,this.streamFiles=t,this.accumulate=!1,this.contentBuffer=[],this.dirRecords=[],this.currentSourceOffset=0,this.entriesCount=0,this.currentFile=null,this._sources=[]}r.inherits(c,o),c.prototype.push=function(t){var e=t.meta.percent||0,i=this.entriesCount,s=this._sources.length;this.accumulate?this.contentBuffer.push(t):(this.bytesWritten+=t.data.length,o.prototype.push.call(this,{data:t.data,meta:{currentFile:this.currentFile,percent:i?(e+100*(i-s-1))/i:100}}))},c.prototype.openedSource=function(t){this.currentSourceOffset=this.bytesWritten,this.currentFile=t.file.name;var e=this.streamFiles&&!t.file.dir;if(e){var i=n(t,e,!1,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);this.push({data:i.fileRecord,meta:{percent:0}})}else this.accumulate=!0},c.prototype.closedSource=function(t){this.accumulate=!1;var e,i=this.streamFiles&&!t.file.dir,r=n(t,i,!0,this.currentSourceOffset,this.zipPlatform,this.encodeFileName);if(this.dirRecords.push(r.dirRecord),i)this.push({data:(e=t,h.DATA_DESCRIPTOR+s(e.crc32,4)+s(e.compressedSize,4)+s(e.uncompressedSize,4)),meta:{percent:100}});else for(this.push({data:r.fileRecord,meta:{percent:0}});this.contentBuffer.length;)this.push(this.contentBuffer.shift());this.currentFile=null},c.prototype.flush=function(){for(var t=this.bytesWritten,e=0;e<this.dirRecords.length;e++)this.push({data:this.dirRecords[e],meta:{percent:100}});var i,n,o,a,l,c,d=this.bytesWritten-t,u=(i=this.dirRecords.length,n=d,o=t,a=this.zipComment,l=this.encodeFileName,c=r.transformTo("string",l(a)),h.CENTRAL_DIRECTORY_END+"\0\0\0\0"+s(i,2)+s(i,2)+s(n,4)+s(o,4)+s(c.length,2)+c);this.push({data:u,meta:{percent:100}})},c.prototype.prepareNextSource=function(){this.previous=this._sources.shift(),this.openedSource(this.previous.streamInfo),this.isPaused?this.previous.pause():this.previous.resume()},c.prototype.registerPrevious=function(t){this._sources.push(t);var e=this;return t.on("data",function(t){e.processChunk(t)}),t.on("end",function(){e.closedSource(e.previous.streamInfo),e._sources.length?e.prepareNextSource():e.end()}),t.on("error",function(t){e.error(t)}),this},c.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))},c.prototype.error=function(t){var e=this._sources;if(!o.prototype.error.call(this,t))return!1;for(var i=0;i<e.length;i++)try{e[i].error(t)}catch(t){}return!0},c.prototype.lock=function(){o.prototype.lock.call(this);for(var t=this._sources,e=0;e<t.length;e++)t[e].lock()},e.exports=c},{"../crc32":4,"../signature":23,"../stream/GenericWorker":28,"../utf8":31,"../utils":32}],9:[function(t,e,i){var s=t("../compressions"),n=t("./ZipFileWorker");i.generateWorker=function(t,e,i){var r=new n(e.streamFiles,i,e.platform,e.encodeFileName),o=0;try{t.forEach(function(t,i){o++;var n=function(t,e){var i=t||e,n=s[i];if(!n)throw new Error(i+" is not a valid compression method !");return n}(i.options.compression,e.compression),a=i.options.compressionOptions||e.compressionOptions||{},l=i.dir,h=i.date;i._compressWorker(n,a).withStreamInfo("file",{name:t,dir:l,date:h,comment:i.comment||"",unixPermissions:i.unixPermissions,dosPermissions:i.dosPermissions}).pipe(r)}),r.entriesCount=o}catch(t){r.error(t)}return r}},{"../compressions":3,"./ZipFileWorker":8}],10:[function(t,e,i){function s(){if(!(this instanceof s))return new s;if(arguments.length)throw new Error("The constructor with parameters has been removed in JSZip 3.0, please check the upgrade guide.");this.files=Object.create(null),this.comment=null,this.root="",this.clone=function(){var t=new s;for(var e in this)"function"!=typeof this[e]&&(t[e]=this[e]);return t}}(s.prototype=t("./object")).loadAsync=t("./load"),s.support=t("./support"),s.defaults=t("./defaults"),s.version="3.10.1",s.loadAsync=function(t,e){return(new s).loadAsync(t,e)},s.external=t("./external"),e.exports=s},{"./defaults":5,"./external":6,"./load":11,"./object":15,"./support":30}],11:[function(t,e,i){var s=t("./utils"),n=t("./external"),r=t("./utf8"),o=t("./zipEntries"),a=t("./stream/Crc32Probe"),l=t("./nodejsUtils");function h(t){return new n.Promise(function(e,i){var s=t.decompressed.getContentWorker().pipe(new a);s.on("error",function(t){i(t)}).on("end",function(){s.streamInfo.crc32!==t.decompressed.crc32?i(new Error("Corrupted zip : CRC32 mismatch")):e()}).resume()})}e.exports=function(t,e){var i=this;return e=s.extend(e||{},{base64:!1,checkCRC32:!1,optimizedBinaryString:!1,createFolders:!1,decodeFileName:r.utf8decode}),l.isNode&&l.isStream(t)?n.Promise.reject(new Error("JSZip can't accept a stream when loading a zip file.")):s.prepareContent("the loaded zip file",t,!0,e.optimizedBinaryString,e.base64).then(function(t){var i=new o(e);return i.load(t),i}).then(function(t){var i=[n.Promise.resolve(t)],s=t.files;if(e.checkCRC32)for(var r=0;r<s.length;r++)i.push(h(s[r]));return n.Promise.all(i)}).then(function(t){for(var n=t.shift(),r=n.files,o=0;o<r.length;o++){var a=r[o],l=a.fileNameStr,h=s.resolve(a.fileNameStr);i.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:e.createFolders}),a.dir||(i.file(h).unsafeOriginalName=l)}return n.zipComment.length&&(i.comment=n.zipComment),i})}},{"./external":6,"./nodejsUtils":14,"./stream/Crc32Probe":25,"./utf8":31,"./utils":32,"./zipEntries":33}],12:[function(t,e,i){var s=t("../utils"),n=t("../stream/GenericWorker");function r(t,e){n.call(this,"Nodejs stream input adapter for "+t),this._upstreamEnded=!1,this._bindStream(e)}s.inherits(r,n),r.prototype._bindStream=function(t){var e=this;(this._stream=t).pause(),t.on("data",function(t){e.push({data:t,meta:{percent:0}})}).on("error",function(t){e.isPaused?this.generatedError=t:e.error(t)}).on("end",function(){e.isPaused?e._upstreamEnded=!0:e.end()})},r.prototype.pause=function(){return!!n.prototype.pause.call(this)&&(this._stream.pause(),!0)},r.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(this._upstreamEnded?this.end():this._stream.resume(),!0)},e.exports=r},{"../stream/GenericWorker":28,"../utils":32}],13:[function(t,e,i){var s=t("readable-stream").Readable;function n(t,e,i){s.call(this,e),this._helper=t;var n=this;t.on("data",function(t,e){n.push(t)||n._helper.pause(),i&&i(e)}).on("error",function(t){n.emit("error",t)}).on("end",function(){n.push(null)})}t("../utils").inherits(n,s),n.prototype._read=function(){this._helper.resume()},e.exports=n},{"../utils":32,"readable-stream":16}],14:[function(t,e,i){e.exports={isNode:"undefined"!=typeof Buffer,newBufferFrom:function(t,e){if(Buffer.from&&Buffer.from!==Uint8Array.from)return Buffer.from(t,e);if("number"==typeof t)throw new Error('The "data" argument must not be a number');return new Buffer(t,e)},allocBuffer:function(t){if(Buffer.alloc)return Buffer.alloc(t);var e=new Buffer(t);return e.fill(0),e},isBuffer:function(t){return Buffer.isBuffer(t)},isStream:function(t){return t&&"function"==typeof t.on&&"function"==typeof t.pause&&"function"==typeof t.resume}}},{}],15:[function(t,e,i){function s(t,e,i){var s,n=r.getTypeOf(e),a=r.extend(i||{},l);a.date=a.date||new Date,null!==a.compression&&(a.compression=a.compression.toUpperCase()),"string"==typeof a.unixPermissions&&(a.unixPermissions=parseInt(a.unixPermissions,8)),a.unixPermissions&&16384&a.unixPermissions&&(a.dir=!0),a.dosPermissions&&16&a.dosPermissions&&(a.dir=!0),a.dir&&(t=m(t)),a.createFolders&&(s=f(t))&&g.call(this,s,!0);var d="string"===n&&!1===a.binary&&!1===a.base64;i&&void 0!==i.binary||(a.binary=!d),(e instanceof h&&0===e.uncompressedSize||a.dir||!e||0===e.length)&&(a.base64=!1,a.binary=!0,e="",a.compression="STORE",n="string");var _=null;_=e instanceof h||e instanceof o?e:u.isNode&&u.isStream(e)?new p(t,e):r.prepareContent(t,e,a.binary,a.optimizedBinaryString,a.base64);var y=new c(t,_,a);this.files[t]=y}var n=t("./utf8"),r=t("./utils"),o=t("./stream/GenericWorker"),a=t("./stream/StreamHelper"),l=t("./defaults"),h=t("./compressedObject"),c=t("./zipObject"),d=t("./generate"),u=t("./nodejsUtils"),p=t("./nodejs/NodejsStreamInputAdapter"),f=function(t){"/"===t.slice(-1)&&(t=t.substring(0,t.length-1));var e=t.lastIndexOf("/");return 0<e?t.substring(0,e):""},m=function(t){return"/"!==t.slice(-1)&&(t+="/"),t},g=function(t,e){return e=void 0!==e?e:l.createFolders,t=m(t),this.files[t]||s.call(this,t,null,{dir:!0,createFolders:e}),this.files[t]};function _(t){return"[object RegExp]"===Object.prototype.toString.call(t)}var y={load:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},forEach:function(t){var e,i,s;for(e in this.files)s=this.files[e],(i=e.slice(this.root.length,e.length))&&e.slice(0,this.root.length)===this.root&&t(i,s)},filter:function(t){var e=[];return this.forEach(function(i,s){t(i,s)&&e.push(s)}),e},file:function(t,e,i){if(1!==arguments.length)return t=this.root+t,s.call(this,t,e,i),this;if(_(t)){var n=t;return this.filter(function(t,e){return!e.dir&&n.test(t)})}var r=this.files[this.root+t];return r&&!r.dir?r:null},folder:function(t){if(!t)return this;if(_(t))return this.filter(function(e,i){return i.dir&&t.test(e)});var e=this.root+t,i=g.call(this,e),s=this.clone();return s.root=i.name,s},remove:function(t){t=this.root+t;var e=this.files[t];if(e||("/"!==t.slice(-1)&&(t+="/"),e=this.files[t]),e&&!e.dir)delete this.files[t];else for(var i=this.filter(function(e,i){return i.name.slice(0,t.length)===t}),s=0;s<i.length;s++)delete this.files[i[s].name];return this},generate:function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},generateInternalStream:function(t){var e,i={};try{if((i=r.extend(t||{},{streamFiles:!1,compression:"STORE",compressionOptions:null,type:"",platform:"DOS",comment:null,mimeType:"application/zip",encodeFileName:n.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 s=i.comment||this.comment||"";e=d.generateWorker(this,i,s)}catch(t){(e=new o("error")).error(t)}return new a(e,i.type||"string",i.mimeType)},generateAsync:function(t,e){return this.generateInternalStream(t).accumulate(e)},generateNodeStream:function(t,e){return(t=t||{}).type||(t.type="nodebuffer"),this.generateInternalStream(t).toNodejsStream(e)}};e.exports=y},{"./compressedObject":2,"./defaults":5,"./generate":9,"./nodejs/NodejsStreamInputAdapter":12,"./nodejsUtils":14,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31,"./utils":32,"./zipObject":35}],16:[function(t,e,i){e.exports=t("stream")},{stream:void 0}],17:[function(t,e,i){var s=t("./DataReader");function n(t){s.call(this,t);for(var e=0;e<this.data.length;e++)t[e]=255&t[e]}t("../utils").inherits(n,s),n.prototype.byteAt=function(t){return this.data[this.zero+t]},n.prototype.lastIndexOfSignature=function(t){for(var e=t.charCodeAt(0),i=t.charCodeAt(1),s=t.charCodeAt(2),n=t.charCodeAt(3),r=this.length-4;0<=r;--r)if(this.data[r]===e&&this.data[r+1]===i&&this.data[r+2]===s&&this.data[r+3]===n)return r-this.zero;return-1},n.prototype.readAndCheckSignature=function(t){var e=t.charCodeAt(0),i=t.charCodeAt(1),s=t.charCodeAt(2),n=t.charCodeAt(3),r=this.readData(4);return e===r[0]&&i===r[1]&&s===r[2]&&n===r[3]},n.prototype.readData=function(t){if(this.checkOffset(t),0===t)return[];var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=n},{"../utils":32,"./DataReader":18}],18:[function(t,e,i){var s=t("../utils");function n(t){this.data=t,this.length=t.length,this.index=0,this.zero=0}n.prototype={checkOffset:function(t){this.checkIndex(this.index+t)},checkIndex:function(t){if(this.length<this.zero+t||t<0)throw new Error("End of data reached (data length = "+this.length+", asked index = "+t+"). Corrupted zip ?")},setIndex:function(t){this.checkIndex(t),this.index=t},skip:function(t){this.setIndex(this.index+t)},byteAt:function(){},readInt:function(t){var e,i=0;for(this.checkOffset(t),e=this.index+t-1;e>=this.index;e--)i=(i<<8)+this.byteAt(e);return this.index+=t,i},readString:function(t){return s.transformTo("string",this.readData(t))},readData:function(){},lastIndexOfSignature:function(){},readAndCheckSignature:function(){},readDate:function(){var t=this.readInt(4);return new Date(Date.UTC(1980+(t>>25&127),(t>>21&15)-1,t>>16&31,t>>11&31,t>>5&63,(31&t)<<1))}},e.exports=n},{"../utils":32}],19:[function(t,e,i){var s=t("./Uint8ArrayReader");function n(t){s.call(this,t)}t("../utils").inherits(n,s),n.prototype.readData=function(t){this.checkOffset(t);var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=n},{"../utils":32,"./Uint8ArrayReader":21}],20:[function(t,e,i){var s=t("./DataReader");function n(t){s.call(this,t)}t("../utils").inherits(n,s),n.prototype.byteAt=function(t){return this.data.charCodeAt(this.zero+t)},n.prototype.lastIndexOfSignature=function(t){return this.data.lastIndexOf(t)-this.zero},n.prototype.readAndCheckSignature=function(t){return t===this.readData(4)},n.prototype.readData=function(t){this.checkOffset(t);var e=this.data.slice(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=n},{"../utils":32,"./DataReader":18}],21:[function(t,e,i){var s=t("./ArrayReader");function n(t){s.call(this,t)}t("../utils").inherits(n,s),n.prototype.readData=function(t){if(this.checkOffset(t),0===t)return new Uint8Array(0);var e=this.data.subarray(this.zero+this.index,this.zero+this.index+t);return this.index+=t,e},e.exports=n},{"../utils":32,"./ArrayReader":17}],22:[function(t,e,i){var s=t("../utils"),n=t("../support"),r=t("./ArrayReader"),o=t("./StringReader"),a=t("./NodeBufferReader"),l=t("./Uint8ArrayReader");e.exports=function(t){var e=s.getTypeOf(t);return s.checkSupport(e),"string"!==e||n.uint8array?"nodebuffer"===e?new a(t):n.uint8array?new l(s.transformTo("uint8array",t)):new r(s.transformTo("array",t)):new o(t)}},{"../support":30,"../utils":32,"./ArrayReader":17,"./NodeBufferReader":19,"./StringReader":20,"./Uint8ArrayReader":21}],23:[function(t,e,i){i.LOCAL_FILE_HEADER="PK",i.CENTRAL_FILE_HEADER="PK",i.CENTRAL_DIRECTORY_END="PK",i.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",i.ZIP64_CENTRAL_DIRECTORY_END="PK",i.DATA_DESCRIPTOR="PK\b"},{}],24:[function(t,e,i){var s=t("./GenericWorker"),n=t("../utils");function r(t){s.call(this,"ConvertWorker to "+t),this.destType=t}n.inherits(r,s),r.prototype.processChunk=function(t){this.push({data:n.transformTo(this.destType,t.data),meta:t.meta})},e.exports=r},{"../utils":32,"./GenericWorker":28}],25:[function(t,e,i){var s=t("./GenericWorker"),n=t("../crc32");function r(){s.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}t("../utils").inherits(r,s),r.prototype.processChunk=function(t){this.streamInfo.crc32=n(t.data,this.streamInfo.crc32||0),this.push(t)},e.exports=r},{"../crc32":4,"../utils":32,"./GenericWorker":28}],26:[function(t,e,i){var s=t("../utils"),n=t("./GenericWorker");function r(t){n.call(this,"DataLengthProbe for "+t),this.propName=t,this.withStreamInfo(t,0)}s.inherits(r,n),r.prototype.processChunk=function(t){if(t){var e=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=e+t.data.length}n.prototype.processChunk.call(this,t)},e.exports=r},{"../utils":32,"./GenericWorker":28}],27:[function(t,e,i){var s=t("../utils"),n=t("./GenericWorker");function r(t){n.call(this,"DataWorker");var e=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,t.then(function(t){e.dataIsReady=!0,e.data=t,e.max=t&&t.length||0,e.type=s.getTypeOf(t),e.isPaused||e._tickAndRepeat()},function(t){e.error(t)})}s.inherits(r,n),r.prototype.cleanUp=function(){n.prototype.cleanUp.call(this),this.data=null},r.prototype.resume=function(){return!!n.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,s.delay(this._tickAndRepeat,[],this)),!0)},r.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(s.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},r.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var t=null,e=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":t=this.data.substring(this.index,e);break;case"uint8array":t=this.data.subarray(this.index,e);break;case"array":case"nodebuffer":t=this.data.slice(this.index,e)}return this.index=e,this.push({data:t,meta:{percent:this.max?this.index/this.max*100:0}})},e.exports=r},{"../utils":32,"./GenericWorker":28}],28:[function(t,e,i){function s(t){this.name=t||"default",this.streamInfo={},this.generatedError=null,this.extraStreamInfo={},this.isPaused=!0,this.isFinished=!1,this.isLocked=!1,this._listeners={data:[],end:[],error:[]},this.previous=null}s.prototype={push:function(t){this.emit("data",t)},end:function(){if(this.isFinished)return!1;this.flush();try{this.emit("end"),this.cleanUp(),this.isFinished=!0}catch(t){this.emit("error",t)}return!0},error:function(t){return!this.isFinished&&(this.isPaused?this.generatedError=t:(this.isFinished=!0,this.emit("error",t),this.previous&&this.previous.error(t),this.cleanUp()),!0)},on:function(t,e){return this._listeners[t].push(e),this},cleanUp:function(){this.streamInfo=this.generatedError=this.extraStreamInfo=null,this._listeners=[]},emit:function(t,e){if(this._listeners[t])for(var i=0;i<this._listeners[t].length;i++)this._listeners[t][i].call(this,e)},pipe:function(t){return t.registerPrevious(this)},registerPrevious:function(t){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.streamInfo=t.streamInfo,this.mergeStreamInfo(),this.previous=t;var e=this;return t.on("data",function(t){e.processChunk(t)}),t.on("end",function(){e.end()}),t.on("error",function(t){e.error(t)}),this},pause:function(){return!this.isPaused&&!this.isFinished&&(this.isPaused=!0,this.previous&&this.previous.pause(),!0)},resume:function(){if(!this.isPaused||this.isFinished)return!1;var t=this.isPaused=!1;return this.generatedError&&(this.error(this.generatedError),t=!0),this.previous&&this.previous.resume(),!t},flush:function(){},processChunk:function(t){this.push(t)},withStreamInfo:function(t,e){return this.extraStreamInfo[t]=e,this.mergeStreamInfo(),this},mergeStreamInfo:function(){for(var t in this.extraStreamInfo)Object.prototype.hasOwnProperty.call(this.extraStreamInfo,t)&&(this.streamInfo[t]=this.extraStreamInfo[t])},lock:function(){if(this.isLocked)throw new Error("The stream '"+this+"' has already been used.");this.isLocked=!0,this.previous&&this.previous.lock()},toString:function(){var t="Worker "+this.name;return this.previous?this.previous+" -> "+t:t}},e.exports=s},{}],29:[function(t,e,i){var s=t("../utils"),n=t("./ConvertWorker"),r=t("./GenericWorker"),o=t("../base64"),a=t("../support"),l=t("../external"),h=null;if(a.nodestream)try{h=t("../nodejs/NodejsStreamOutputAdapter")}catch(t){}function c(t,e){return new l.Promise(function(i,n){var r=[],a=t._internalType,l=t._outputType,h=t._mimeType;t.on("data",function(t,i){r.push(t),e&&e(i)}).on("error",function(t){r=[],n(t)}).on("end",function(){try{var t=function(t,e,i){switch(t){case"blob":return s.newBlob(s.transformTo("arraybuffer",e),i);case"base64":return o.encode(e);default:return s.transformTo(t,e)}}(l,function(t,e){var i,s=0,n=null,r=0;for(i=0;i<e.length;i++)r+=e[i].length;switch(t){case"string":return e.join("");case"array":return Array.prototype.concat.apply([],e);case"uint8array":for(n=new Uint8Array(r),i=0;i<e.length;i++)n.set(e[i],s),s+=e[i].length;return n;case"nodebuffer":return Buffer.concat(e);default:throw new Error("concat : unsupported type '"+t+"'")}}(a,r),h);i(t)}catch(t){n(t)}r=[]}).resume()})}function d(t,e,i){var o=e;switch(e){case"blob":case"arraybuffer":o="uint8array";break;case"base64":o="string"}try{this._internalType=o,this._outputType=e,this._mimeType=i,s.checkSupport(o),this._worker=t.pipe(new n(o)),t.lock()}catch(t){this._worker=new r("error"),this._worker.error(t)}}d.prototype={accumulate:function(t){return c(this,t)},on:function(t,e){var i=this;return"data"===t?this._worker.on(t,function(t){e.call(i,t.data,t.meta)}):this._worker.on(t,function(){s.delay(e,arguments,i)}),this},resume:function(){return s.delay(this._worker.resume,[],this._worker),this},pause:function(){return this._worker.pause(),this},toNodejsStream:function(t){if(s.checkSupport("nodestream"),"nodebuffer"!==this._outputType)throw new Error(this._outputType+" is not supported by this method");return new h(this,{objectMode:"nodebuffer"!==this._outputType},t)}},e.exports=d},{"../base64":1,"../external":6,"../nodejs/NodejsStreamOutputAdapter":13,"../support":30,"../utils":32,"./ConvertWorker":24,"./GenericWorker":28}],30:[function(t,e,i){if(i.base64=!0,i.array=!0,i.string=!0,i.arraybuffer="undefined"!=typeof ArrayBuffer&&"undefined"!=typeof Uint8Array,i.nodebuffer="undefined"!=typeof Buffer,i.uint8array="undefined"!=typeof Uint8Array,"undefined"==typeof ArrayBuffer)i.blob=!1;else{var s=new ArrayBuffer(0);try{i.blob=0===new Blob([s],{type:"application/zip"}).size}catch(t){try{var n=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);n.append(s),i.blob=0===n.getBlob("application/zip").size}catch(t){i.blob=!1}}}try{i.nodestream=!!t("readable-stream").Readable}catch(t){i.nodestream=!1}},{"readable-stream":16}],31:[function(t,e,i){for(var s=t("./utils"),n=t("./support"),r=t("./nodejsUtils"),o=t("./stream/GenericWorker"),a=new Array(256),l=0;l<256;l++)a[l]=252<=l?6:248<=l?5:240<=l?4:224<=l?3:192<=l?2:1;function h(){o.call(this,"utf-8 decode"),this.leftOver=null}function c(){o.call(this,"utf-8 encode")}a[254]=a[254]=1,i.utf8encode=function(t){return n.nodebuffer?r.newBufferFrom(t,"utf-8"):function(t){var e,i,s,r,o,a=t.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(e=n.uint8array?new Uint8Array(l):new Array(l),r=o=0;o<l;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(s=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(s-56320),r++),i<128?e[o++]=i:(i<2048?e[o++]=192|i>>>6:(i<65536?e[o++]=224|i>>>12:(e[o++]=240|i>>>18,e[o++]=128|i>>>12&63),e[o++]=128|i>>>6&63),e[o++]=128|63&i);return e}(t)},i.utf8decode=function(t){return n.nodebuffer?s.transformTo("nodebuffer",t).toString("utf-8"):function(t){var e,i,n,r,o=t.length,l=new Array(2*o);for(e=i=0;e<o;)if((n=t[e++])<128)l[i++]=n;else if(4<(r=a[n]))l[i++]=65533,e+=r-1;else{for(n&=2===r?31:3===r?15:7;1<r&&e<o;)n=n<<6|63&t[e++],r--;1<r?l[i++]=65533:n<65536?l[i++]=n:(n-=65536,l[i++]=55296|n>>10&1023,l[i++]=56320|1023&n)}return l.length!==i&&(l.subarray?l=l.subarray(0,i):l.length=i),s.applyFromCharCode(l)}(t=s.transformTo(n.uint8array?"uint8array":"array",t))},s.inherits(h,o),h.prototype.processChunk=function(t){var e=s.transformTo(n.uint8array?"uint8array":"array",t.data);if(this.leftOver&&this.leftOver.length){if(n.uint8array){var r=e;(e=new Uint8Array(r.length+this.leftOver.length)).set(this.leftOver,0),e.set(r,this.leftOver.length)}else e=this.leftOver.concat(e);this.leftOver=null}var o=function(t,e){var i;for((e=e||t.length)>t.length&&(e=t.length),i=e-1;0<=i&&128==(192&t[i]);)i--;return i<0||0===i?e:i+a[t[i]]>e?i:e}(e),l=e;o!==e.length&&(n.uint8array?(l=e.subarray(0,o),this.leftOver=e.subarray(o,e.length)):(l=e.slice(0,o),this.leftOver=e.slice(o,e.length))),this.push({data:i.utf8decode(l),meta:t.meta})},h.prototype.flush=function(){this.leftOver&&this.leftOver.length&&(this.push({data:i.utf8decode(this.leftOver),meta:{}}),this.leftOver=null)},i.Utf8DecodeWorker=h,s.inherits(c,o),c.prototype.processChunk=function(t){this.push({data:i.utf8encode(t.data),meta:t.meta})},i.Utf8EncodeWorker=c},{"./nodejsUtils":14,"./stream/GenericWorker":28,"./support":30,"./utils":32}],32:[function(t,e,i){var s=t("./support"),n=t("./base64"),r=t("./nodejsUtils"),o=t("./external");function a(t){return t}function l(t,e){for(var i=0;i<t.length;++i)e[i]=255&t.charCodeAt(i);return e}t("setimmediate"),i.newBlob=function(t,e){i.checkSupport("blob");try{return new Blob([t],{type:e})}catch(i){try{var s=new(self.BlobBuilder||self.WebKitBlobBuilder||self.MozBlobBuilder||self.MSBlobBuilder);return s.append(t),s.getBlob(e)}catch(t){throw new Error("Bug : can't construct the Blob.")}}};var h={stringifyByChunk:function(t,e,i){var s=[],n=0,r=t.length;if(r<=i)return String.fromCharCode.apply(null,t);for(;n<r;)"array"===e||"nodebuffer"===e?s.push(String.fromCharCode.apply(null,t.slice(n,Math.min(n+i,r)))):s.push(String.fromCharCode.apply(null,t.subarray(n,Math.min(n+i,r)))),n+=i;return s.join("")},stringifyByChar:function(t){for(var e="",i=0;i<t.length;i++)e+=String.fromCharCode(t[i]);return e},applyCanBeUsed:{uint8array:function(){try{return s.uint8array&&1===String.fromCharCode.apply(null,new Uint8Array(1)).length}catch(t){return!1}}(),nodebuffer:function(){try{return s.nodebuffer&&1===String.fromCharCode.apply(null,r.allocBuffer(1)).length}catch(t){return!1}}()}};function c(t){var e=65536,s=i.getTypeOf(t),n=!0;if("uint8array"===s?n=h.applyCanBeUsed.uint8array:"nodebuffer"===s&&(n=h.applyCanBeUsed.nodebuffer),n)for(;1<e;)try{return h.stringifyByChunk(t,s,e)}catch(t){e=Math.floor(e/2)}return h.stringifyByChar(t)}function d(t,e){for(var i=0;i<t.length;i++)e[i]=t[i];return e}i.applyFromCharCode=c;var u={};u.string={string:a,array:function(t){return l(t,new Array(t.length))},arraybuffer:function(t){return u.string.uint8array(t).buffer},uint8array:function(t){return l(t,new Uint8Array(t.length))},nodebuffer:function(t){return l(t,r.allocBuffer(t.length))}},u.array={string:c,array:a,arraybuffer:function(t){return new Uint8Array(t).buffer},uint8array:function(t){return new Uint8Array(t)},nodebuffer:function(t){return r.newBufferFrom(t)}},u.arraybuffer={string:function(t){return c(new Uint8Array(t))},array:function(t){return d(new Uint8Array(t),new Array(t.byteLength))},arraybuffer:a,uint8array:function(t){return new Uint8Array(t)},nodebuffer:function(t){return r.newBufferFrom(new Uint8Array(t))}},u.uint8array={string:c,array:function(t){return d(t,new Array(t.length))},arraybuffer:function(t){return t.buffer},uint8array:a,nodebuffer:function(t){return r.newBufferFrom(t)}},u.nodebuffer={string:c,array:function(t){return d(t,new Array(t.length))},arraybuffer:function(t){return u.nodebuffer.uint8array(t).buffer},uint8array:function(t){return d(t,new Uint8Array(t.length))},nodebuffer:a},i.transformTo=function(t,e){if(e=e||"",!t)return e;i.checkSupport(t);var s=i.getTypeOf(e);return u[s][t](e)},i.resolve=function(t){for(var e=t.split("/"),i=[],s=0;s<e.length;s++){var n=e[s];"."===n||""===n&&0!==s&&s!==e.length-1||(".."===n?i.pop():i.push(n))}return i.join("/")},i.getTypeOf=function(t){return"string"==typeof t?"string":"[object Array]"===Object.prototype.toString.call(t)?"array":s.nodebuffer&&r.isBuffer(t)?"nodebuffer":s.uint8array&&t instanceof Uint8Array?"uint8array":s.arraybuffer&&t instanceof ArrayBuffer?"arraybuffer":void 0},i.checkSupport=function(t){if(!s[t.toLowerCase()])throw new Error(t+" is not supported by this platform")},i.MAX_VALUE_16BITS=65535,i.MAX_VALUE_32BITS=-1,i.pretty=function(t){var e,i,s="";for(i=0;i<(t||"").length;i++)s+="\\x"+((e=t.charCodeAt(i))<16?"0":"")+e.toString(16).toUpperCase();return s},i.delay=function(t,e,i){setImmediate(function(){t.apply(i||null,e||[])})},i.inherits=function(t,e){function i(){}i.prototype=e.prototype,t.prototype=new i},i.extend=function(){var t,e,i={};for(t=0;t<arguments.length;t++)for(e in arguments[t])Object.prototype.hasOwnProperty.call(arguments[t],e)&&void 0===i[e]&&(i[e]=arguments[t][e]);return i},i.prepareContent=function(t,e,r,a,h){return o.Promise.resolve(e).then(function(t){return s.blob&&(t instanceof Blob||-1!==["[object File]","[object Blob]"].indexOf(Object.prototype.toString.call(t)))&&"undefined"!=typeof FileReader?new o.Promise(function(e,i){var s=new FileReader;s.onload=function(t){e(t.target.result)},s.onerror=function(t){i(t.target.error)},s.readAsArrayBuffer(t)}):t}).then(function(e){var c,d=i.getTypeOf(e);return d?("arraybuffer"===d?e=i.transformTo("uint8array",e):"string"===d&&(h?e=n.decode(e):r&&!0!==a&&(e=l(c=e,s.uint8array?new Uint8Array(c.length):new Array(c.length)))),e):o.Promise.reject(new Error("Can't read the data of '"+t+"'. Is it in a supported JavaScript type (String, Blob, ArrayBuffer, etc) ?"))})}},{"./base64":1,"./external":6,"./nodejsUtils":14,"./support":30,setimmediate:54}],33:[function(t,e,i){var s=t("./reader/readerFor"),n=t("./utils"),r=t("./signature"),o=t("./zipEntry"),a=t("./support");function l(t){this.files=[],this.loadOptions=t}l.prototype={checkSignature:function(t){if(!this.reader.readAndCheckSignature(t)){this.reader.index-=4;var e=this.reader.readString(4);throw new Error("Corrupted zip or bug: unexpected signature ("+n.pretty(e)+", expected "+n.pretty(t)+")")}},isSignature:function(t,e){var i=this.reader.index;this.reader.setIndex(t);var s=this.reader.readString(4)===e;return this.reader.setIndex(i),s},readBlockEndOfCentral:function(){this.diskNumber=this.reader.readInt(2),this.diskWithCentralDirStart=this.reader.readInt(2),this.centralDirRecordsOnThisDisk=this.reader.readInt(2),this.centralDirRecords=this.reader.readInt(2),this.centralDirSize=this.reader.readInt(4),this.centralDirOffset=this.reader.readInt(4),this.zipCommentLength=this.reader.readInt(2);var t=this.reader.readData(this.zipCommentLength),e=a.uint8array?"uint8array":"array",i=n.transformTo(e,t);this.zipComment=this.loadOptions.decodeFileName(i)},readBlockZip64EndOfCentral:function(){this.zip64EndOfCentralSize=this.reader.readInt(8),this.reader.skip(4),this.diskNumber=this.reader.readInt(4),this.diskWithCentralDirStart=this.reader.readInt(4),this.centralDirRecordsOnThisDisk=this.reader.readInt(8),this.centralDirRecords=this.reader.readInt(8),this.centralDirSize=this.reader.readInt(8),this.centralDirOffset=this.reader.readInt(8),this.zip64ExtensibleData={};for(var t,e,i,s=this.zip64EndOfCentralSize-44;0<s;)t=this.reader.readInt(2),e=this.reader.readInt(4),i=this.reader.readData(e),this.zip64ExtensibleData[t]={id:t,length:e,value:i}},readBlockZip64EndOfCentralLocator:function(){if(this.diskWithZip64CentralDirStart=this.reader.readInt(4),this.relativeOffsetEndOfZip64CentralDir=this.reader.readInt(8),this.disksCount=this.reader.readInt(4),1<this.disksCount)throw new Error("Multi-volumes zip are not supported")},readLocalFiles:function(){var t,e;for(t=0;t<this.files.length;t++)e=this.files[t],this.reader.setIndex(e.localHeaderOffset),this.checkSignature(r.LOCAL_FILE_HEADER),e.readLocalPart(this.reader),e.handleUTF8(),e.processAttributes()},readCentralDir:function(){var t;for(this.reader.setIndex(this.centralDirOffset);this.reader.readAndCheckSignature(r.CENTRAL_FILE_HEADER);)(t=new o({zip64:this.zip64},this.loadOptions)).readCentralPart(this.reader),this.files.push(t);if(this.centralDirRecords!==this.files.length&&0!==this.centralDirRecords&&0===this.files.length)throw new Error("Corrupted zip or bug: expected "+this.centralDirRecords+" records in central dir, got "+this.files.length)},readEndOfCentral:function(){var t=this.reader.lastIndexOfSignature(r.CENTRAL_DIRECTORY_END);if(t<0)throw this.isSignature(0,r.LOCAL_FILE_HEADER)?new Error("Corrupted zip: can't find end of central directory"):new Error("Can't find end of central directory : is this a zip file ? If it is, see https://stuk.github.io/jszip/documentation/howto/read_zip.html");this.reader.setIndex(t);var e=t;if(this.checkSignature(r.CENTRAL_DIRECTORY_END),this.readBlockEndOfCentral(),this.diskNumber===n.MAX_VALUE_16BITS||this.diskWithCentralDirStart===n.MAX_VALUE_16BITS||this.centralDirRecordsOnThisDisk===n.MAX_VALUE_16BITS||this.centralDirRecords===n.MAX_VALUE_16BITS||this.centralDirSize===n.MAX_VALUE_32BITS||this.centralDirOffset===n.MAX_VALUE_32BITS){if(this.zip64=!0,(t=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR))<0)throw new Error("Corrupted zip: can't find the ZIP64 end of central directory locator");if(this.reader.setIndex(t),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_LOCATOR),this.readBlockZip64EndOfCentralLocator(),!this.isSignature(this.relativeOffsetEndOfZip64CentralDir,r.ZIP64_CENTRAL_DIRECTORY_END)&&(this.relativeOffsetEndOfZip64CentralDir=this.reader.lastIndexOfSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.relativeOffsetEndOfZip64CentralDir<0))throw new Error("Corrupted zip: can't find the ZIP64 end of central directory");this.reader.setIndex(this.relativeOffsetEndOfZip64CentralDir),this.checkSignature(r.ZIP64_CENTRAL_DIRECTORY_END),this.readBlockZip64EndOfCentral()}var i=this.centralDirOffset+this.centralDirSize;this.zip64&&(i+=20,i+=12+this.zip64EndOfCentralSize);var s=e-i;if(0<s)this.isSignature(e,r.CENTRAL_FILE_HEADER)||(this.reader.zero=s);else if(s<0)throw new Error("Corrupted zip: missing "+Math.abs(s)+" bytes.")},prepareReader:function(t){this.reader=s(t)},load:function(t){this.prepareReader(t),this.readEndOfCentral(),this.readCentralDir(),this.readLocalFiles()}},e.exports=l},{"./reader/readerFor":22,"./signature":23,"./support":30,"./utils":32,"./zipEntry":34}],34:[function(t,e,i){var s=t("./reader/readerFor"),n=t("./utils"),r=t("./compressedObject"),o=t("./crc32"),a=t("./utf8"),l=t("./compressions"),h=t("./support");function c(t,e){this.options=t,this.loadOptions=e}c.prototype={isEncrypted:function(){return!(1&~this.bitFlag)},useUTF8:function(){return!(2048&~this.bitFlag)},readLocalPart:function(t){var e,i;if(t.skip(22),this.fileNameLength=t.readInt(2),i=t.readInt(2),this.fileName=t.readData(this.fileNameLength),t.skip(i),-1===this.compressedSize||-1===this.uncompressedSize)throw new Error("Bug or corrupted zip : didn't get enough information from the central directory (compressedSize === -1 || uncompressedSize === -1)");if(null===(e=function(t){for(var e in l)if(Object.prototype.hasOwnProperty.call(l,e)&&l[e].magic===t)return l[e];return null}(this.compressionMethod)))throw new Error("Corrupted zip : compression "+n.pretty(this.compressionMethod)+" unknown (inner file : "+n.transformTo("string",this.fileName)+")");this.decompressed=new r(this.compressedSize,this.uncompressedSize,this.crc32,e,t.readData(this.compressedSize))},readCentralPart:function(t){this.versionMadeBy=t.readInt(2),t.skip(2),this.bitFlag=t.readInt(2),this.compressionMethod=t.readString(2),this.date=t.readDate(),this.crc32=t.readInt(4),this.compressedSize=t.readInt(4),this.uncompressedSize=t.readInt(4);var e=t.readInt(2);if(this.extraFieldsLength=t.readInt(2),this.fileCommentLength=t.readInt(2),this.diskNumberStart=t.readInt(2),this.internalFileAttributes=t.readInt(2),this.externalFileAttributes=t.readInt(4),this.localHeaderOffset=t.readInt(4),this.isEncrypted())throw new Error("Encrypted zip are not supported");t.skip(e),this.readExtraFields(t),this.parseZIP64ExtraField(t),this.fileComment=t.readData(this.fileCommentLength)},processAttributes:function(){this.unixPermissions=null,this.dosPermissions=null;var t=this.versionMadeBy>>8;this.dir=!!(16&this.externalFileAttributes),0==t&&(this.dosPermissions=63&this.externalFileAttributes),3==t&&(this.unixPermissions=this.externalFileAttributes>>16&65535),this.dir||"/"!==this.fileNameStr.slice(-1)||(this.dir=!0)},parseZIP64ExtraField:function(){if(this.extraFields[1]){var t=s(this.extraFields[1].value);this.uncompressedSize===n.MAX_VALUE_32BITS&&(this.uncompressedSize=t.readInt(8)),this.compressedSize===n.MAX_VALUE_32BITS&&(this.compressedSize=t.readInt(8)),this.localHeaderOffset===n.MAX_VALUE_32BITS&&(this.localHeaderOffset=t.readInt(8)),this.diskNumberStart===n.MAX_VALUE_32BITS&&(this.diskNumberStart=t.readInt(4))}},readExtraFields:function(t){var e,i,s,n=t.index+this.extraFieldsLength;for(this.extraFields||(this.extraFields={});t.index+4<n;)e=t.readInt(2),i=t.readInt(2),s=t.readData(i),this.extraFields[e]={id:e,length:i,value:s};t.setIndex(n)},handleUTF8:function(){var t=h.uint8array?"uint8array":"array";if(this.useUTF8())this.fileNameStr=a.utf8decode(this.fileName),this.fileCommentStr=a.utf8decode(this.fileComment);else{var e=this.findExtraFieldUnicodePath();if(null!==e)this.fileNameStr=e;else{var i=n.transformTo(t,this.fileName);this.fileNameStr=this.loadOptions.decodeFileName(i)}var s=this.findExtraFieldUnicodeComment();if(null!==s)this.fileCommentStr=s;else{var r=n.transformTo(t,this.fileComment);this.fileCommentStr=this.loadOptions.decodeFileName(r)}}},findExtraFieldUnicodePath:function(){var t=this.extraFields[28789];if(t){var e=s(t.value);return 1!==e.readInt(1)||o(this.fileName)!==e.readInt(4)?null:a.utf8decode(e.readData(t.length-5))}return null},findExtraFieldUnicodeComment:function(){var t=this.extraFields[25461];if(t){var e=s(t.value);return 1!==e.readInt(1)||o(this.fileComment)!==e.readInt(4)?null:a.utf8decode(e.readData(t.length-5))}return null}},e.exports=c},{"./compressedObject":2,"./compressions":3,"./crc32":4,"./reader/readerFor":22,"./support":30,"./utf8":31,"./utils":32}],35:[function(t,e,i){function s(t,e,i){this.name=t,this.dir=i.dir,this.date=i.date,this.comment=i.comment,this.unixPermissions=i.unixPermissions,this.dosPermissions=i.dosPermissions,this._data=e,this._dataBinary=i.binary,this.options={compression:i.compression,compressionOptions:i.compressionOptions}}var n=t("./stream/StreamHelper"),r=t("./stream/DataWorker"),o=t("./utf8"),a=t("./compressedObject"),l=t("./stream/GenericWorker");s.prototype={internalStream:function(t){var e=null,i="string";try{if(!t)throw new Error("No output type specified.");var s="string"===(i=t.toLowerCase())||"text"===i;"binarystring"!==i&&"text"!==i||(i="string"),e=this._decompressWorker();var r=!this._dataBinary;r&&!s&&(e=e.pipe(new o.Utf8EncodeWorker)),!r&&s&&(e=e.pipe(new o.Utf8DecodeWorker))}catch(t){(e=new l("error")).error(t)}return new n(e,i,"")},async:function(t,e){return this.internalStream(t).accumulate(e)},nodeStream:function(t,e){return this.internalStream(t||"nodebuffer").toNodejsStream(e)},_compressWorker:function(t,e){if(this._data instanceof a&&this._data.compression.magic===t.magic)return this._data.getCompressedWorker();var i=this._decompressWorker();return this._dataBinary||(i=i.pipe(new o.Utf8EncodeWorker)),a.createWorkerFrom(i,t,e)},_decompressWorker:function(){return this._data instanceof a?this._data.getContentWorker():this._data instanceof l?this._data:new r(this._data)}};for(var h=["asText","asBinary","asNodeBuffer","asUint8Array","asArrayBuffer"],c=function(){throw new Error("This method has been removed in JSZip 3.0, please check the upgrade guide.")},d=0;d<h.length;d++)s.prototype[h[d]]=c;e.exports=s},{"./compressedObject":2,"./stream/DataWorker":27,"./stream/GenericWorker":28,"./stream/StreamHelper":29,"./utf8":31}],36:[function(t,e,i){(function(t){var i,s,n=t.MutationObserver||t.WebKitMutationObserver;if(n){var r=0,o=new n(c),a=t.document.createTextNode("");o.observe(a,{characterData:!0}),i=function(){a.data=r=++r%2}}else if(t.setImmediate||void 0===t.MessageChannel)i="document"in t&&"onreadystatechange"in t.document.createElement("script")?function(){var e=t.document.createElement("script");e.onreadystatechange=function(){c(),e.onreadystatechange=null,e.parentNode.removeChild(e),e=null},t.document.documentElement.appendChild(e)}:function(){setTimeout(c,0)};else{var l=new t.MessageChannel;l.port1.onmessage=c,i=function(){l.port2.postMessage(0)}}var h=[];function c(){var t,e;s=!0;for(var i=h.length;i;){for(e=h,h=[],t=-1;++t<i;)e[t]();i=h.length}s=!1}e.exports=function(t){1!==h.push(t)||s||i()}}).call(this,void 0!==Q?Q:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}],37:[function(t,e,i){var s=t("immediate");function n(){}var r={},o=["REJECTED"],a=["FULFILLED"],l=["PENDING"];function h(t){if("function"!=typeof t)throw new TypeError("resolver must be a function");this.state=l,this.queue=[],this.outcome=void 0,t!==n&&p(this,t)}function c(t,e,i){this.promise=t,"function"==typeof e&&(this.onFulfilled=e,this.callFulfilled=this.otherCallFulfilled),"function"==typeof i&&(this.onRejected=i,this.callRejected=this.otherCallRejected)}function d(t,e,i){s(function(){var s;try{s=e(i)}catch(e){return r.reject(t,e)}s===t?r.reject(t,new TypeError("Cannot resolve promise with itself")):r.resolve(t,s)})}function u(t){var e=t&&t.then;if(t&&("object"==typeof t||"function"==typeof t)&&"function"==typeof e)return function(){e.apply(t,arguments)}}function p(t,e){var i=!1;function s(e){i||(i=!0,r.reject(t,e))}function n(e){i||(i=!0,r.resolve(t,e))}var o=f(function(){e(n,s)});"error"===o.status&&s(o.value)}function f(t,e){var i={};try{i.value=t(e),i.status="success"}catch(t){i.status="error",i.value=t}return i}(e.exports=h).prototype.finally=function(t){if("function"!=typeof t)return this;var e=this.constructor;return this.then(function(i){return e.resolve(t()).then(function(){return i})},function(i){return e.resolve(t()).then(function(){throw i})})},h.prototype.catch=function(t){return this.then(null,t)},h.prototype.then=function(t,e){if("function"!=typeof t&&this.state===a||"function"!=typeof e&&this.state===o)return this;var i=new this.constructor(n);return this.state!==l?d(i,this.state===a?t:e,this.outcome):this.queue.push(new c(i,t,e)),i},c.prototype.callFulfilled=function(t){r.resolve(this.promise,t)},c.prototype.otherCallFulfilled=function(t){d(this.promise,this.onFulfilled,t)},c.prototype.callRejected=function(t){r.reject(this.promise,t)},c.prototype.otherCallRejected=function(t){d(this.promise,this.onRejected,t)},r.resolve=function(t,e){var i=f(u,e);if("error"===i.status)return r.reject(t,i.value);var s=i.value;if(s)p(t,s);else{t.state=a,t.outcome=e;for(var n=-1,o=t.queue.length;++n<o;)t.queue[n].callFulfilled(e)}return t},r.reject=function(t,e){t.state=o,t.outcome=e;for(var i=-1,s=t.queue.length;++i<s;)t.queue[i].callRejected(e);return t},h.resolve=function(t){return t instanceof this?t:r.resolve(new this(n),t)},h.reject=function(t){var e=new this(n);return r.reject(e,t)},h.all=function(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,s=!1;if(!i)return this.resolve([]);for(var o=new Array(i),a=0,l=-1,h=new this(n);++l<i;)c(t[l],l);return h;function c(t,n){e.resolve(t).then(function(t){o[n]=t,++a!==i||s||(s=!0,r.resolve(h,o))},function(t){s||(s=!0,r.reject(h,t))})}},h.race=function(t){var e=this;if("[object Array]"!==Object.prototype.toString.call(t))return this.reject(new TypeError("must be an array"));var i=t.length,s=!1;if(!i)return this.resolve([]);for(var o,a=-1,l=new this(n);++a<i;)o=t[a],e.resolve(o).then(function(t){s||(s=!0,r.resolve(l,t))},function(t){s||(s=!0,r.reject(l,t))});return l}},{immediate:36}],38:[function(t,e,i){var s={};(0,t("./lib/utils/common").assign)(s,t("./lib/deflate"),t("./lib/inflate"),t("./lib/zlib/constants")),e.exports=s},{"./lib/deflate":39,"./lib/inflate":40,"./lib/utils/common":41,"./lib/zlib/constants":44}],39:[function(t,e,i){var s=t("./zlib/deflate"),n=t("./utils/common"),r=t("./utils/strings"),o=t("./zlib/messages"),a=t("./zlib/zstream"),l=Object.prototype.toString,h=0,c=-1,d=0,u=8;function p(t){if(!(this instanceof p))return new p(t);this.options=n.assign({level:c,method:u,chunkSize:16384,windowBits:15,memLevel:8,strategy:d,to:""},t||{});var e=this.options;e.raw&&0<e.windowBits?e.windowBits=-e.windowBits:e.gzip&&0<e.windowBits&&e.windowBits<16&&(e.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var i=s.deflateInit2(this.strm,e.level,e.method,e.windowBits,e.memLevel,e.strategy);if(i!==h)throw new Error(o[i]);if(e.header&&s.deflateSetHeader(this.strm,e.header),e.dictionary){var f;if(f="string"==typeof e.dictionary?r.string2buf(e.dictionary):"[object ArrayBuffer]"===l.call(e.dictionary)?new Uint8Array(e.dictionary):e.dictionary,(i=s.deflateSetDictionary(this.strm,f))!==h)throw new Error(o[i]);this._dict_set=!0}}function f(t,e){var i=new p(e);if(i.push(t,!0),i.err)throw i.msg||o[i.err];return i.result}p.prototype.push=function(t,e){var i,o,a=this.strm,c=this.options.chunkSize;if(this.ended)return!1;o=e===~~e?e:!0===e?4:0,"string"==typeof t?a.input=r.string2buf(t):"[object ArrayBuffer]"===l.call(t)?a.input=new Uint8Array(t):a.input=t,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new n.Buf8(c),a.next_out=0,a.avail_out=c),1!==(i=s.deflate(a,o))&&i!==h)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(n.shrinkBuf(a.output,a.next_out))):this.onData(n.shrinkBuf(a.output,a.next_out)))}while((0<a.avail_in||0===a.avail_out)&&1!==i);return 4===o?(i=s.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===h):2!==o||(this.onEnd(h),!(a.avail_out=0))},p.prototype.onData=function(t){this.chunks.push(t)},p.prototype.onEnd=function(t){t===h&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},i.Deflate=p,i.deflate=f,i.deflateRaw=function(t,e){return(e=e||{}).raw=!0,f(t,e)},i.gzip=function(t,e){return(e=e||{}).gzip=!0,f(t,e)}},{"./utils/common":41,"./utils/strings":42,"./zlib/deflate":46,"./zlib/messages":51,"./zlib/zstream":53}],40:[function(t,e,i){var s=t("./zlib/inflate"),n=t("./utils/common"),r=t("./utils/strings"),o=t("./zlib/constants"),a=t("./zlib/messages"),l=t("./zlib/zstream"),h=t("./zlib/gzheader"),c=Object.prototype.toString;function d(t){if(!(this instanceof d))return new d(t);this.options=n.assign({chunkSize:16384,windowBits:0,to:""},t||{});var e=this.options;e.raw&&0<=e.windowBits&&e.windowBits<16&&(e.windowBits=-e.windowBits,0===e.windowBits&&(e.windowBits=-15)),!(0<=e.windowBits&&e.windowBits<16)||t&&t.windowBits||(e.windowBits+=32),15<e.windowBits&&e.windowBits<48&&!(15&e.windowBits)&&(e.windowBits|=15),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new l,this.strm.avail_out=0;var i=s.inflateInit2(this.strm,e.windowBits);if(i!==o.Z_OK)throw new Error(a[i]);this.header=new h,s.inflateGetHeader(this.strm,this.header)}function u(t,e){var i=new d(e);if(i.push(t,!0),i.err)throw i.msg||a[i.err];return i.result}d.prototype.push=function(t,e){var i,a,l,h,d,u,p=this.strm,f=this.options.chunkSize,m=this.options.dictionary,g=!1;if(this.ended)return!1;a=e===~~e?e:!0===e?o.Z_FINISH:o.Z_NO_FLUSH,"string"==typeof t?p.input=r.binstring2buf(t):"[object ArrayBuffer]"===c.call(t)?p.input=new Uint8Array(t):p.input=t,p.next_in=0,p.avail_in=p.input.length;do{if(0===p.avail_out&&(p.output=new n.Buf8(f),p.next_out=0,p.avail_out=f),(i=s.inflate(p,o.Z_NO_FLUSH))===o.Z_NEED_DICT&&m&&(u="string"==typeof m?r.string2buf(m):"[object ArrayBuffer]"===c.call(m)?new Uint8Array(m):m,i=s.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),h=p.next_out-l,d=r.buf2string(p.output,l),p.next_out=h,p.avail_out=f-h,h&&n.arraySet(p.output,p.output,l,h,0),this.onData(d)):this.onData(n.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=s.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===o.Z_OK):a!==o.Z_SYNC_FLUSH||(this.onEnd(o.Z_OK),!(p.avail_out=0))},d.prototype.onData=function(t){this.chunks.push(t)},d.prototype.onEnd=function(t){t===o.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=n.flattenChunks(this.chunks)),this.chunks=[],this.err=t,this.msg=this.strm.msg},i.Inflate=d,i.inflate=u,i.inflateRaw=function(t,e){return(e=e||{}).raw=!0,u(t,e)},i.ungzip=u},{"./utils/common":41,"./utils/strings":42,"./zlib/constants":44,"./zlib/gzheader":47,"./zlib/inflate":49,"./zlib/messages":51,"./zlib/zstream":53}],41:[function(t,e,i){var s="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;i.assign=function(t){for(var e=Array.prototype.slice.call(arguments,1);e.length;){var i=e.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var s in i)i.hasOwnProperty(s)&&(t[s]=i[s])}}return t},i.shrinkBuf=function(t,e){return t.length===e?t:t.subarray?t.subarray(0,e):(t.length=e,t)};var n={arraySet:function(t,e,i,s,n){if(e.subarray&&t.subarray)t.set(e.subarray(i,i+s),n);else for(var r=0;r<s;r++)t[n+r]=e[i+r]},flattenChunks:function(t){var e,i,s,n,r,o;for(e=s=0,i=t.length;e<i;e++)s+=t[e].length;for(o=new Uint8Array(s),e=n=0,i=t.length;e<i;e++)r=t[e],o.set(r,n),n+=r.length;return o}},r={arraySet:function(t,e,i,s,n){for(var r=0;r<s;r++)t[n+r]=e[i+r]},flattenChunks:function(t){return[].concat.apply([],t)}};i.setTyped=function(t){t?(i.Buf8=Uint8Array,i.Buf16=Uint16Array,i.Buf32=Int32Array,i.assign(i,n)):(i.Buf8=Array,i.Buf16=Array,i.Buf32=Array,i.assign(i,r))},i.setTyped(s)},{}],42:[function(t,e,i){var s=t("./common"),n=!0,r=!0;try{String.fromCharCode.apply(null,[0])}catch(t){n=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(t){r=!1}for(var o=new s.Buf8(256),a=0;a<256;a++)o[a]=252<=a?6:248<=a?5:240<=a?4:224<=a?3:192<=a?2:1;function l(t,e){if(e<65537&&(t.subarray&&r||!t.subarray&&n))return String.fromCharCode.apply(null,s.shrinkBuf(t,e));for(var i="",o=0;o<e;o++)i+=String.fromCharCode(t[o]);return i}o[254]=o[254]=1,i.string2buf=function(t){var e,i,n,r,o,a=t.length,l=0;for(r=0;r<a;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),l+=i<128?1:i<2048?2:i<65536?3:4;for(e=new s.Buf8(l),r=o=0;o<l;r++)55296==(64512&(i=t.charCodeAt(r)))&&r+1<a&&56320==(64512&(n=t.charCodeAt(r+1)))&&(i=65536+(i-55296<<10)+(n-56320),r++),i<128?e[o++]=i:(i<2048?e[o++]=192|i>>>6:(i<65536?e[o++]=224|i>>>12:(e[o++]=240|i>>>18,e[o++]=128|i>>>12&63),e[o++]=128|i>>>6&63),e[o++]=128|63&i);return e},i.buf2binstring=function(t){return l(t,t.length)},i.binstring2buf=function(t){for(var e=new s.Buf8(t.length),i=0,n=e.length;i<n;i++)e[i]=t.charCodeAt(i);return e},i.buf2string=function(t,e){var i,s,n,r,a=e||t.length,h=new Array(2*a);for(i=s=0;i<a;)if((n=t[i++])<128)h[s++]=n;else if(4<(r=o[n]))h[s++]=65533,i+=r-1;else{for(n&=2===r?31:3===r?15:7;1<r&&i<a;)n=n<<6|63&t[i++],r--;1<r?h[s++]=65533:n<65536?h[s++]=n:(n-=65536,h[s++]=55296|n>>10&1023,h[s++]=56320|1023&n)}return l(h,s)},i.utf8border=function(t,e){var i;for((e=e||t.length)>t.length&&(e=t.length),i=e-1;0<=i&&128==(192&t[i]);)i--;return i<0||0===i?e:i+o[t[i]]>e?i:e}},{"./common":41}],43:[function(t,e,i){e.exports=function(t,e,i,s){for(var n=65535&t,r=t>>>16&65535,o=0;0!==i;){for(i-=o=2e3<i?2e3:i;r=r+(n=n+e[s++]|0)|0,--o;);n%=65521,r%=65521}return n|r<<16}},{}],44:[function(t,e,i){e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},{}],45:[function(t,e,i){var s=function(){for(var t,e=[],i=0;i<256;i++){t=i;for(var s=0;s<8;s++)t=1&t?3988292384^t>>>1:t>>>1;e[i]=t}return e}();e.exports=function(t,e,i,n){var r=s,o=n+i;t^=-1;for(var a=n;a<o;a++)t=t>>>8^r[255&(t^e[a])];return-1^t}},{}],46:[function(t,e,i){var s,n=t("../utils/common"),r=t("./trees"),o=t("./adler32"),a=t("./crc32"),l=t("./messages"),h=0,c=4,d=0,u=-2,p=-1,f=4,m=2,g=8,_=9,y=286,w=30,v=19,b=2*y+1,x=15,T=3,E=258,C=E+T+1,S=42,A=113,O=1,P=2,I=3,k=4;function D(t,e){return t.msg=l[e],e}function z(t){return(t<<1)-(4<t?9:0)}function M(t){for(var e=t.length;0<=--e;)t[e]=0}function B(t){var e=t.state,i=e.pending;i>t.avail_out&&(i=t.avail_out),0!==i&&(n.arraySet(t.output,e.pending_buf,e.pending_out,i,t.next_out),t.next_out+=i,e.pending_out+=i,t.total_out+=i,t.avail_out-=i,e.pending-=i,0===e.pending&&(e.pending_out=0))}function N(t,e){r._tr_flush_block(t,0<=t.block_start?t.block_start:-1,t.strstart-t.block_start,e),t.block_start=t.strstart,B(t.strm)}function U(t,e){t.pending_buf[t.pending++]=e}function L(t,e){t.pending_buf[t.pending++]=e>>>8&255,t.pending_buf[t.pending++]=255&e}function R(t,e){var i,s,n=t.max_chain_length,r=t.strstart,o=t.prev_length,a=t.nice_match,l=t.strstart>t.w_size-C?t.strstart-(t.w_size-C):0,h=t.window,c=t.w_mask,d=t.prev,u=t.strstart+E,p=h[r+o-1],f=h[r+o];t.prev_length>=t.good_match&&(n>>=2),a>t.lookahead&&(a=t.lookahead);do{if(h[(i=e)+o]===f&&h[i+o-1]===p&&h[i]===h[r]&&h[++i]===h[r+1]){r+=2,i++;do{}while(h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&h[++r]===h[++i]&&r<u);if(s=E-(u-r),r=u-E,o<s){if(t.match_start=e,a<=(o=s))break;p=h[r+o-1],f=h[r+o]}}}while((e=d[e&c])>l&&0!=--n);return o<=t.lookahead?o:t.lookahead}function F(t){var e,i,s,r,l,h,c,d,u,p,f=t.w_size;do{if(r=t.window_size-t.lookahead-t.strstart,t.strstart>=f+(f-C)){for(n.arraySet(t.window,t.window,f,f,0),t.match_start-=f,t.strstart-=f,t.block_start-=f,e=i=t.hash_size;s=t.head[--e],t.head[e]=f<=s?s-f:0,--i;);for(e=i=f;s=t.prev[--e],t.prev[e]=f<=s?s-f:0,--i;);r+=f}if(0===t.strm.avail_in)break;if(h=t.strm,c=t.window,d=t.strstart+t.lookahead,p=void 0,(u=r)<(p=h.avail_in)&&(p=u),i=0===p?0:(h.avail_in-=p,n.arraySet(c,h.input,h.next_in,p,d),1===h.state.wrap?h.adler=o(h.adler,c,p,d):2===h.state.wrap&&(h.adler=a(h.adler,c,p,d)),h.next_in+=p,h.total_in+=p,p),t.lookahead+=i,t.lookahead+t.insert>=T)for(l=t.strstart-t.insert,t.ins_h=t.window[l],t.ins_h=(t.ins_h<<t.hash_shift^t.window[l+1])&t.hash_mask;t.insert&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[l+T-1])&t.hash_mask,t.prev[l&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=l,l++,t.insert--,!(t.lookahead+t.insert<T)););}while(t.lookahead<C&&0!==t.strm.avail_in)}function V(t,e){for(var i,s;;){if(t.lookahead<C){if(F(t),t.lookahead<C&&e===h)return O;if(0===t.lookahead)break}if(i=0,t.lookahead>=T&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+T-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!==i&&t.strstart-i<=t.w_size-C&&(t.match_length=R(t,i)),t.match_length>=T)if(s=r._tr_tally(t,t.strstart-t.match_start,t.match_length-T),t.lookahead-=t.match_length,t.match_length<=t.max_lazy_match&&t.lookahead>=T){for(t.match_length--;t.strstart++,t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+T-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart,0!=--t.match_length;);t.strstart++}else t.strstart+=t.match_length,t.match_length=0,t.ins_h=t.window[t.strstart],t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+1])&t.hash_mask;else s=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++;if(s&&(N(t,!1),0===t.strm.avail_out))return O}return t.insert=t.strstart<T-1?t.strstart:T-1,e===c?(N(t,!0),0===t.strm.avail_out?I:k):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?O:P}function j(t,e){for(var i,s,n;;){if(t.lookahead<C){if(F(t),t.lookahead<C&&e===h)return O;if(0===t.lookahead)break}if(i=0,t.lookahead>=T&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+T-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),t.prev_length=t.match_length,t.prev_match=t.match_start,t.match_length=T-1,0!==i&&t.prev_length<t.max_lazy_match&&t.strstart-i<=t.w_size-C&&(t.match_length=R(t,i),t.match_length<=5&&(1===t.strategy||t.match_length===T&&4096<t.strstart-t.match_start)&&(t.match_length=T-1)),t.prev_length>=T&&t.match_length<=t.prev_length){for(n=t.strstart+t.lookahead-T,s=r._tr_tally(t,t.strstart-1-t.prev_match,t.prev_length-T),t.lookahead-=t.prev_length-1,t.prev_length-=2;++t.strstart<=n&&(t.ins_h=(t.ins_h<<t.hash_shift^t.window[t.strstart+T-1])&t.hash_mask,i=t.prev[t.strstart&t.w_mask]=t.head[t.ins_h],t.head[t.ins_h]=t.strstart),0!=--t.prev_length;);if(t.match_available=0,t.match_length=T-1,t.strstart++,s&&(N(t,!1),0===t.strm.avail_out))return O}else if(t.match_available){if((s=r._tr_tally(t,0,t.window[t.strstart-1]))&&N(t,!1),t.strstart++,t.lookahead--,0===t.strm.avail_out)return O}else t.match_available=1,t.strstart++,t.lookahead--}return t.match_available&&(s=r._tr_tally(t,0,t.window[t.strstart-1]),t.match_available=0),t.insert=t.strstart<T-1?t.strstart:T-1,e===c?(N(t,!0),0===t.strm.avail_out?I:k):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?O:P}function Z(t,e,i,s,n){this.good_length=t,this.max_lazy=e,this.nice_length=i,this.max_chain=s,this.func=n}function H(){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 n.Buf16(2*b),this.dyn_dtree=new n.Buf16(2*(2*w+1)),this.bl_tree=new n.Buf16(2*(2*v+1)),M(this.dyn_ltree),M(this.dyn_dtree),M(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new n.Buf16(x+1),this.heap=new n.Buf16(2*y+1),M(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new n.Buf16(2*y+1),M(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 $(t){var e;return t&&t.state?(t.total_in=t.total_out=0,t.data_type=m,(e=t.state).pending=0,e.pending_out=0,e.wrap<0&&(e.wrap=-e.wrap),e.status=e.wrap?S:A,t.adler=2===e.wrap?0:1,e.last_flush=h,r._tr_init(e),d):D(t,u)}function Y(t){var e,i=$(t);return i===d&&((e=t.state).window_size=2*e.w_size,M(e.head),e.max_lazy_match=s[e.level].max_lazy,e.good_match=s[e.level].good_length,e.nice_match=s[e.level].nice_length,e.max_chain_length=s[e.level].max_chain,e.strstart=0,e.block_start=0,e.lookahead=0,e.insert=0,e.match_length=e.prev_length=T-1,e.match_available=0,e.ins_h=0),i}function W(t,e,i,s,r,o){if(!t)return u;var a=1;if(e===p&&(e=6),s<0?(a=0,s=-s):15<s&&(a=2,s-=16),r<1||_<r||i!==g||s<8||15<s||e<0||9<e||o<0||f<o)return D(t,u);8===s&&(s=9);var l=new H;return(t.state=l).strm=t,l.wrap=a,l.gzhead=null,l.w_bits=s,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+T-1)/T),l.window=new n.Buf8(2*l.w_size),l.head=new n.Buf16(l.hash_size),l.prev=new n.Buf16(l.w_size),l.lit_bufsize=1<<r+6,l.pending_buf_size=4*l.lit_bufsize,l.pending_buf=new n.Buf8(l.pending_buf_size),l.d_buf=1*l.lit_bufsize,l.l_buf=3*l.lit_bufsize,l.level=e,l.strategy=o,l.method=i,Y(t)}s=[new Z(0,0,0,0,function(t,e){var i=65535;for(i>t.pending_buf_size-5&&(i=t.pending_buf_size-5);;){if(t.lookahead<=1){if(F(t),0===t.lookahead&&e===h)return O;if(0===t.lookahead)break}t.strstart+=t.lookahead,t.lookahead=0;var s=t.block_start+i;if((0===t.strstart||t.strstart>=s)&&(t.lookahead=t.strstart-s,t.strstart=s,N(t,!1),0===t.strm.avail_out))return O;if(t.strstart-t.block_start>=t.w_size-C&&(N(t,!1),0===t.strm.avail_out))return O}return t.insert=0,e===c?(N(t,!0),0===t.strm.avail_out?I:k):(t.strstart>t.block_start&&(N(t,!1),t.strm.avail_out),O)}),new Z(4,4,8,4,V),new Z(4,5,16,8,V),new Z(4,6,32,32,V),new Z(4,4,16,16,j),new Z(8,16,32,32,j),new Z(8,16,128,128,j),new Z(8,32,128,256,j),new Z(32,128,258,1024,j),new Z(32,258,258,4096,j)],i.deflateInit=function(t,e){return W(t,e,g,15,8,0)},i.deflateInit2=W,i.deflateReset=Y,i.deflateResetKeep=$,i.deflateSetHeader=function(t,e){return t&&t.state?2!==t.state.wrap?u:(t.state.gzhead=e,d):u},i.deflate=function(t,e){var i,n,o,l;if(!t||!t.state||5<e||e<0)return t?D(t,u):u;if(n=t.state,!t.output||!t.input&&0!==t.avail_in||666===n.status&&e!==c)return D(t,0===t.avail_out?-5:u);if(n.strm=t,i=n.last_flush,n.last_flush=e,n.status===S)if(2===n.wrap)t.adler=0,U(n,31),U(n,139),U(n,8),n.gzhead?(U(n,(n.gzhead.text?1:0)+(n.gzhead.hcrc?2:0)+(n.gzhead.extra?4:0)+(n.gzhead.name?8:0)+(n.gzhead.comment?16:0)),U(n,255&n.gzhead.time),U(n,n.gzhead.time>>8&255),U(n,n.gzhead.time>>16&255),U(n,n.gzhead.time>>24&255),U(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),U(n,255&n.gzhead.os),n.gzhead.extra&&n.gzhead.extra.length&&(U(n,255&n.gzhead.extra.length),U(n,n.gzhead.extra.length>>8&255)),n.gzhead.hcrc&&(t.adler=a(t.adler,n.pending_buf,n.pending,0)),n.gzindex=0,n.status=69):(U(n,0),U(n,0),U(n,0),U(n,0),U(n,0),U(n,9===n.level?2:2<=n.strategy||n.level<2?4:0),U(n,3),n.status=A);else{var p=g+(n.w_bits-8<<4)<<8;p|=(2<=n.strategy||n.level<2?0:n.level<6?1:6===n.level?2:3)<<6,0!==n.strstart&&(p|=32),p+=31-p%31,n.status=A,L(n,p),0!==n.strstart&&(L(n,t.adler>>>16),L(n,65535&t.adler)),t.adler=1}if(69===n.status)if(n.gzhead.extra){for(o=n.pending;n.gzindex<(65535&n.gzhead.extra.length)&&(n.pending!==n.pending_buf_size||(n.gzhead.hcrc&&n.pending>o&&(t.adler=a(t.adler,n.pending_buf,n.pending-o,o)),B(t),o=n.pending,n.pending!==n.pending_buf_size));)U(n,255&n.gzhead.extra[n.gzindex]),n.gzindex++;n.gzhead.hcrc&&n.pending>o&&(t.adler=a(t.adler,n.pending_buf,n.pending-o,o)),n.gzindex===n.gzhead.extra.length&&(n.gzindex=0,n.status=73)}else n.status=73;if(73===n.status)if(n.gzhead.name){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=a(t.adler,n.pending_buf,n.pending-o,o)),B(t),o=n.pending,n.pending===n.pending_buf_size)){l=1;break}l=n.gzindex<n.gzhead.name.length?255&n.gzhead.name.charCodeAt(n.gzindex++):0,U(n,l)}while(0!==l);n.gzhead.hcrc&&n.pending>o&&(t.adler=a(t.adler,n.pending_buf,n.pending-o,o)),0===l&&(n.gzindex=0,n.status=91)}else n.status=91;if(91===n.status)if(n.gzhead.comment){o=n.pending;do{if(n.pending===n.pending_buf_size&&(n.gzhead.hcrc&&n.pending>o&&(t.adler=a(t.adler,n.pending_buf,n.pending-o,o)),B(t),o=n.pending,n.pending===n.pending_buf_size)){l=1;break}l=n.gzindex<n.gzhead.comment.length?255&n.gzhead.comment.charCodeAt(n.gzindex++):0,U(n,l)}while(0!==l);n.gzhead.hcrc&&n.pending>o&&(t.adler=a(t.adler,n.pending_buf,n.pending-o,o)),0===l&&(n.status=103)}else n.status=103;if(103===n.status&&(n.gzhead.hcrc?(n.pending+2>n.pending_buf_size&&B(t),n.pending+2<=n.pending_buf_size&&(U(n,255&t.adler),U(n,t.adler>>8&255),t.adler=0,n.status=A)):n.status=A),0!==n.pending){if(B(t),0===t.avail_out)return n.last_flush=-1,d}else if(0===t.avail_in&&z(e)<=z(i)&&e!==c)return D(t,-5);if(666===n.status&&0!==t.avail_in)return D(t,-5);if(0!==t.avail_in||0!==n.lookahead||e!==h&&666!==n.status){var f=2===n.strategy?function(t,e){for(var i;;){if(0===t.lookahead&&(F(t),0===t.lookahead)){if(e===h)return O;break}if(t.match_length=0,i=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++,i&&(N(t,!1),0===t.strm.avail_out))return O}return t.insert=0,e===c?(N(t,!0),0===t.strm.avail_out?I:k):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?O:P}(n,e):3===n.strategy?function(t,e){for(var i,s,n,o,a=t.window;;){if(t.lookahead<=E){if(F(t),t.lookahead<=E&&e===h)return O;if(0===t.lookahead)break}if(t.match_length=0,t.lookahead>=T&&0<t.strstart&&(s=a[n=t.strstart-1])===a[++n]&&s===a[++n]&&s===a[++n]){o=t.strstart+E;do{}while(s===a[++n]&&s===a[++n]&&s===a[++n]&&s===a[++n]&&s===a[++n]&&s===a[++n]&&s===a[++n]&&s===a[++n]&&n<o);t.match_length=E-(o-n),t.match_length>t.lookahead&&(t.match_length=t.lookahead)}if(t.match_length>=T?(i=r._tr_tally(t,1,t.match_length-T),t.lookahead-=t.match_length,t.strstart+=t.match_length,t.match_length=0):(i=r._tr_tally(t,0,t.window[t.strstart]),t.lookahead--,t.strstart++),i&&(N(t,!1),0===t.strm.avail_out))return O}return t.insert=0,e===c?(N(t,!0),0===t.strm.avail_out?I:k):t.last_lit&&(N(t,!1),0===t.strm.avail_out)?O:P}(n,e):s[n.level].func(n,e);if(f!==I&&f!==k||(n.status=666),f===O||f===I)return 0===t.avail_out&&(n.last_flush=-1),d;if(f===P&&(1===e?r._tr_align(n):5!==e&&(r._tr_stored_block(n,0,0,!1),3===e&&(M(n.head),0===n.lookahead&&(n.strstart=0,n.block_start=0,n.insert=0))),B(t),0===t.avail_out))return n.last_flush=-1,d}return e!==c?d:n.wrap<=0?1:(2===n.wrap?(U(n,255&t.adler),U(n,t.adler>>8&255),U(n,t.adler>>16&255),U(n,t.adler>>24&255),U(n,255&t.total_in),U(n,t.total_in>>8&255),U(n,t.total_in>>16&255),U(n,t.total_in>>24&255)):(L(n,t.adler>>>16),L(n,65535&t.adler)),B(t),0<n.wrap&&(n.wrap=-n.wrap),0!==n.pending?d:1)},i.deflateEnd=function(t){var e;return t&&t.state?(e=t.state.status)!==S&&69!==e&&73!==e&&91!==e&&103!==e&&e!==A&&666!==e?D(t,u):(t.state=null,e===A?D(t,-3):d):u},i.deflateSetDictionary=function(t,e){var i,s,r,a,l,h,c,p,f=e.length;if(!t||!t.state)return u;if(2===(a=(i=t.state).wrap)||1===a&&i.status!==S||i.lookahead)return u;for(1===a&&(t.adler=o(t.adler,e,f,0)),i.wrap=0,f>=i.w_size&&(0===a&&(M(i.head),i.strstart=0,i.block_start=0,i.insert=0),p=new n.Buf8(i.w_size),n.arraySet(p,e,f-i.w_size,i.w_size,0),e=p,f=i.w_size),l=t.avail_in,h=t.next_in,c=t.input,t.avail_in=f,t.next_in=0,t.input=e,F(i);i.lookahead>=T;){for(s=i.strstart,r=i.lookahead-(T-1);i.ins_h=(i.ins_h<<i.hash_shift^i.window[s+T-1])&i.hash_mask,i.prev[s&i.w_mask]=i.head[i.ins_h],i.head[i.ins_h]=s,s++,--r;);i.strstart=s,i.lookahead=T-1,F(i)}return i.strstart+=i.lookahead,i.block_start=i.strstart,i.insert=i.lookahead,i.lookahead=0,i.match_length=i.prev_length=T-1,i.match_available=0,t.next_in=h,t.input=c,t.avail_in=l,i.wrap=a,d},i.deflateInfo="pako deflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./messages":51,"./trees":52}],47:[function(t,e,i){e.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},{}],48:[function(t,e,i){e.exports=function(t,e){var i,s,n,r,o,a,l,h,c,d,u,p,f,m,g,_,y,w,v,b,x,T,E,C,S;i=t.state,s=t.next_in,C=t.input,n=s+(t.avail_in-5),r=t.next_out,S=t.output,o=r-(e-t.avail_out),a=r+(t.avail_out-257),l=i.dmax,h=i.wsize,c=i.whave,d=i.wnext,u=i.window,p=i.hold,f=i.bits,m=i.lencode,g=i.distcode,_=(1<<i.lenbits)-1,y=(1<<i.distbits)-1;t:do{f<15&&(p+=C[s++]<<f,f+=8,p+=C[s++]<<f,f+=8),w=m[p&_];e:for(;;){if(p>>>=v=w>>>24,f-=v,0==(v=w>>>16&255))S[r++]=65535&w;else{if(!(16&v)){if(!(64&v)){w=m[(65535&w)+(p&(1<<v)-1)];continue e}if(32&v){i.mode=12;break t}t.msg="invalid literal/length code",i.mode=30;break t}b=65535&w,(v&=15)&&(f<v&&(p+=C[s++]<<f,f+=8),b+=p&(1<<v)-1,p>>>=v,f-=v),f<15&&(p+=C[s++]<<f,f+=8,p+=C[s++]<<f,f+=8),w=g[p&y];i:for(;;){if(p>>>=v=w>>>24,f-=v,!(16&(v=w>>>16&255))){if(!(64&v)){w=g[(65535&w)+(p&(1<<v)-1)];continue i}t.msg="invalid distance code",i.mode=30;break t}if(x=65535&w,f<(v&=15)&&(p+=C[s++]<<f,(f+=8)<v&&(p+=C[s++]<<f,f+=8)),l<(x+=p&(1<<v)-1)){t.msg="invalid distance too far back",i.mode=30;break t}if(p>>>=v,f-=v,(v=r-o)<x){if(c<(v=x-v)&&i.sane){t.msg="invalid distance too far back",i.mode=30;break t}if(E=u,(T=0)===d){if(T+=h-v,v<b){for(b-=v;S[r++]=u[T++],--v;);T=r-x,E=S}}else if(d<v){if(T+=h+d-v,(v-=d)<b){for(b-=v;S[r++]=u[T++],--v;);if(T=0,d<b){for(b-=v=d;S[r++]=u[T++],--v;);T=r-x,E=S}}}else if(T+=d-v,v<b){for(b-=v;S[r++]=u[T++],--v;);T=r-x,E=S}for(;2<b;)S[r++]=E[T++],S[r++]=E[T++],S[r++]=E[T++],b-=3;b&&(S[r++]=E[T++],1<b&&(S[r++]=E[T++]))}else{for(T=r-x;S[r++]=S[T++],S[r++]=S[T++],S[r++]=S[T++],2<(b-=3););b&&(S[r++]=S[T++],1<b&&(S[r++]=S[T++]))}break}}break}}while(s<n&&r<a);s-=b=f>>3,p&=(1<<(f-=b<<3))-1,t.next_in=s,t.next_out=r,t.avail_in=s<n?n-s+5:5-(s-n),t.avail_out=r<a?a-r+257:257-(r-a),i.hold=p,i.bits=f}},{}],49:[function(t,e,i){var s=t("../utils/common"),n=t("./adler32"),r=t("./crc32"),o=t("./inffast"),a=t("./inftrees"),l=1,h=2,c=0,d=-2,u=1,p=852,f=592;function m(t){return(t>>>24&255)+(t>>>8&65280)+((65280&t)<<8)+((255&t)<<24)}function g(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new s.Buf16(320),this.work=new s.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function _(t){var e;return t&&t.state?(e=t.state,t.total_in=t.total_out=e.total=0,t.msg="",e.wrap&&(t.adler=1&e.wrap),e.mode=u,e.last=0,e.havedict=0,e.dmax=32768,e.head=null,e.hold=0,e.bits=0,e.lencode=e.lendyn=new s.Buf32(p),e.distcode=e.distdyn=new s.Buf32(f),e.sane=1,e.back=-1,c):d}function y(t){var e;return t&&t.state?((e=t.state).wsize=0,e.whave=0,e.wnext=0,_(t)):d}function w(t,e){var i,s;return t&&t.state?(s=t.state,e<0?(i=0,e=-e):(i=1+(e>>4),e<48&&(e&=15)),e&&(e<8||15<e)?d:(null!==s.window&&s.wbits!==e&&(s.window=null),s.wrap=i,s.wbits=e,y(t))):d}function v(t,e){var i,s;return t?(s=new g,(t.state=s).window=null,(i=w(t,e))!==c&&(t.state=null),i):d}var b,x,T=!0;function E(t){if(T){var e;for(b=new s.Buf32(512),x=new s.Buf32(32),e=0;e<144;)t.lens[e++]=8;for(;e<256;)t.lens[e++]=9;for(;e<280;)t.lens[e++]=7;for(;e<288;)t.lens[e++]=8;for(a(l,t.lens,0,288,b,0,t.work,{bits:9}),e=0;e<32;)t.lens[e++]=5;a(h,t.lens,0,32,x,0,t.work,{bits:5}),T=!1}t.lencode=b,t.lenbits=9,t.distcode=x,t.distbits=5}function C(t,e,i,n){var r,o=t.state;return null===o.window&&(o.wsize=1<<o.wbits,o.wnext=0,o.whave=0,o.window=new s.Buf8(o.wsize)),n>=o.wsize?(s.arraySet(o.window,e,i-o.wsize,o.wsize,0),o.wnext=0,o.whave=o.wsize):(n<(r=o.wsize-o.wnext)&&(r=n),s.arraySet(o.window,e,i-n,r,o.wnext),(n-=r)?(s.arraySet(o.window,e,i-n,n,0),o.wnext=n,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=w,i.inflateResetKeep=_,i.inflateInit=function(t){return v(t,15)},i.inflateInit2=v,i.inflate=function(t,e){var i,p,f,g,_,y,w,v,b,x,T,S,A,O,P,I,k,D,z,M,B,N,U,L,R=0,F=new s.Buf8(4),V=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];if(!t||!t.state||!t.output||!t.input&&0!==t.avail_in)return d;12===(i=t.state).mode&&(i.mode=13),_=t.next_out,f=t.output,w=t.avail_out,g=t.next_in,p=t.input,y=t.avail_in,v=i.hold,b=i.bits,x=y,T=w,N=c;t:for(;;)switch(i.mode){case u:if(0===i.wrap){i.mode=13;break}for(;b<16;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(2&i.wrap&&35615===v){F[i.check=0]=255&v,F[1]=v>>>8&255,i.check=r(i.check,F,2,0),b=v=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&v)<<8)+(v>>8))%31){t.msg="incorrect header check",i.mode=30;break}if(8!=(15&v)){t.msg="unknown compression method",i.mode=30;break}if(b-=4,B=8+(15&(v>>>=4)),0===i.wbits)i.wbits=B;else if(B>i.wbits){t.msg="invalid window size",i.mode=30;break}i.dmax=1<<B,t.adler=i.check=1,i.mode=512&v?10:12,b=v=0;break;case 2:for(;b<16;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(i.flags=v,8!=(255&i.flags)){t.msg="unknown compression method",i.mode=30;break}if(57344&i.flags){t.msg="unknown header flags set",i.mode=30;break}i.head&&(i.head.text=v>>8&1),512&i.flags&&(F[0]=255&v,F[1]=v>>>8&255,i.check=r(i.check,F,2,0)),b=v=0,i.mode=3;case 3:for(;b<32;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}i.head&&(i.head.time=v),512&i.flags&&(F[0]=255&v,F[1]=v>>>8&255,F[2]=v>>>16&255,F[3]=v>>>24&255,i.check=r(i.check,F,4,0)),b=v=0,i.mode=4;case 4:for(;b<16;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}i.head&&(i.head.xflags=255&v,i.head.os=v>>8),512&i.flags&&(F[0]=255&v,F[1]=v>>>8&255,i.check=r(i.check,F,2,0)),b=v=0,i.mode=5;case 5:if(1024&i.flags){for(;b<16;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}i.length=v,i.head&&(i.head.extra_len=v),512&i.flags&&(F[0]=255&v,F[1]=v>>>8&255,i.check=r(i.check,F,2,0)),b=v=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(y<(S=i.length)&&(S=y),S&&(i.head&&(B=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),s.arraySet(i.head.extra,p,g,S,B)),512&i.flags&&(i.check=r(i.check,p,S,g)),y-=S,g+=S,i.length-=S),i.length))break t;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===y)break t;for(S=0;B=p[g+S++],i.head&&B&&i.length<65536&&(i.head.name+=String.fromCharCode(B)),B&&S<y;);if(512&i.flags&&(i.check=r(i.check,p,S,g)),y-=S,g+=S,B)break t}else i.head&&(i.head.name=null);i.length=0,i.mode=8;case 8:if(4096&i.flags){if(0===y)break t;for(S=0;B=p[g+S++],i.head&&B&&i.length<65536&&(i.head.comment+=String.fromCharCode(B)),B&&S<y;);if(512&i.flags&&(i.check=r(i.check,p,S,g)),y-=S,g+=S,B)break t}else i.head&&(i.head.comment=null);i.mode=9;case 9:if(512&i.flags){for(;b<16;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(v!==(65535&i.check)){t.msg="header crc mismatch",i.mode=30;break}b=v=0}i.head&&(i.head.hcrc=i.flags>>9&1,i.head.done=!0),t.adler=i.check=0,i.mode=12;break;case 10:for(;b<32;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}t.adler=i.check=m(v),b=v=0,i.mode=11;case 11:if(0===i.havedict)return t.next_out=_,t.avail_out=w,t.next_in=g,t.avail_in=y,i.hold=v,i.bits=b,2;t.adler=i.check=1,i.mode=12;case 12:if(5===e||6===e)break t;case 13:if(i.last){v>>>=7&b,b-=7&b,i.mode=27;break}for(;b<3;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}switch(i.last=1&v,b-=1,3&(v>>>=1)){case 0:i.mode=14;break;case 1:if(E(i),i.mode=20,6!==e)break;v>>>=2,b-=2;break t;case 2:i.mode=17;break;case 3:t.msg="invalid block type",i.mode=30}v>>>=2,b-=2;break;case 14:for(v>>>=7&b,b-=7&b;b<32;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if((65535&v)!=(v>>>16^65535)){t.msg="invalid stored block lengths",i.mode=30;break}if(i.length=65535&v,b=v=0,i.mode=15,6===e)break t;case 15:i.mode=16;case 16:if(S=i.length){if(y<S&&(S=y),w<S&&(S=w),0===S)break t;s.arraySet(f,p,g,S,_),y-=S,g+=S,w-=S,_+=S,i.length-=S;break}i.mode=12;break;case 17:for(;b<14;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(i.nlen=257+(31&v),v>>>=5,b-=5,i.ndist=1+(31&v),v>>>=5,b-=5,i.ncode=4+(15&v),v>>>=4,b-=4,286<i.nlen||30<i.ndist){t.msg="too many length or distance symbols",i.mode=30;break}i.have=0,i.mode=18;case 18:for(;i.have<i.ncode;){for(;b<3;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}i.lens[V[i.have++]]=7&v,v>>>=3,b-=3}for(;i.have<19;)i.lens[V[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,U={bits:i.lenbits},N=a(0,i.lens,0,19,i.lencode,0,i.work,U),i.lenbits=U.bits,N){t.msg="invalid code lengths set",i.mode=30;break}i.have=0,i.mode=19;case 19:for(;i.have<i.nlen+i.ndist;){for(;I=(R=i.lencode[v&(1<<i.lenbits)-1])>>>16&255,k=65535&R,!((P=R>>>24)<=b);){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(k<16)v>>>=P,b-=P,i.lens[i.have++]=k;else{if(16===k){for(L=P+2;b<L;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(v>>>=P,b-=P,0===i.have){t.msg="invalid bit length repeat",i.mode=30;break}B=i.lens[i.have-1],S=3+(3&v),v>>>=2,b-=2}else if(17===k){for(L=P+3;b<L;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}b-=P,B=0,S=3+(7&(v>>>=P)),v>>>=3,b-=3}else{for(L=P+7;b<L;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}b-=P,B=0,S=11+(127&(v>>>=P)),v>>>=7,b-=7}if(i.have+S>i.nlen+i.ndist){t.msg="invalid bit length repeat",i.mode=30;break}for(;S--;)i.lens[i.have++]=B}}if(30===i.mode)break;if(0===i.lens[256]){t.msg="invalid code -- missing end-of-block",i.mode=30;break}if(i.lenbits=9,U={bits:i.lenbits},N=a(l,i.lens,0,i.nlen,i.lencode,0,i.work,U),i.lenbits=U.bits,N){t.msg="invalid literal/lengths set",i.mode=30;break}if(i.distbits=6,i.distcode=i.distdyn,U={bits:i.distbits},N=a(h,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,U),i.distbits=U.bits,N){t.msg="invalid distances set",i.mode=30;break}if(i.mode=20,6===e)break t;case 20:i.mode=21;case 21:if(6<=y&&258<=w){t.next_out=_,t.avail_out=w,t.next_in=g,t.avail_in=y,i.hold=v,i.bits=b,o(t,T),_=t.next_out,f=t.output,w=t.avail_out,g=t.next_in,p=t.input,y=t.avail_in,v=i.hold,b=i.bits,12===i.mode&&(i.back=-1);break}for(i.back=0;I=(R=i.lencode[v&(1<<i.lenbits)-1])>>>16&255,k=65535&R,!((P=R>>>24)<=b);){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(I&&!(240&I)){for(D=P,z=I,M=k;I=(R=i.lencode[M+((v&(1<<D+z)-1)>>D)])>>>16&255,k=65535&R,!(D+(P=R>>>24)<=b);){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}v>>>=D,b-=D,i.back+=D}if(v>>>=P,b-=P,i.back+=P,i.length=k,0===I){i.mode=26;break}if(32&I){i.back=-1,i.mode=12;break}if(64&I){t.msg="invalid literal/length code",i.mode=30;break}i.extra=15&I,i.mode=22;case 22:if(i.extra){for(L=i.extra;b<L;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}i.length+=v&(1<<i.extra)-1,v>>>=i.extra,b-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;I=(R=i.distcode[v&(1<<i.distbits)-1])>>>16&255,k=65535&R,!((P=R>>>24)<=b);){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(!(240&I)){for(D=P,z=I,M=k;I=(R=i.distcode[M+((v&(1<<D+z)-1)>>D)])>>>16&255,k=65535&R,!(D+(P=R>>>24)<=b);){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}v>>>=D,b-=D,i.back+=D}if(v>>>=P,b-=P,i.back+=P,64&I){t.msg="invalid distance code",i.mode=30;break}i.offset=k,i.extra=15&I,i.mode=24;case 24:if(i.extra){for(L=i.extra;b<L;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}i.offset+=v&(1<<i.extra)-1,v>>>=i.extra,b-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){t.msg="invalid distance too far back",i.mode=30;break}i.mode=25;case 25:if(0===w)break t;if(S=T-w,i.offset>S){if((S=i.offset-S)>i.whave&&i.sane){t.msg="invalid distance too far back",i.mode=30;break}A=S>i.wnext?(S-=i.wnext,i.wsize-S):i.wnext-S,S>i.length&&(S=i.length),O=i.window}else O=f,A=_-i.offset,S=i.length;for(w<S&&(S=w),w-=S,i.length-=S;f[_++]=O[A++],--S;);0===i.length&&(i.mode=21);break;case 26:if(0===w)break t;f[_++]=i.length,w--,i.mode=21;break;case 27:if(i.wrap){for(;b<32;){if(0===y)break t;y--,v|=p[g++]<<b,b+=8}if(T-=w,t.total_out+=T,i.total+=T,T&&(t.adler=i.check=i.flags?r(i.check,f,T,_-T):n(i.check,f,T,_-T)),T=w,(i.flags?v:m(v))!==i.check){t.msg="incorrect data check",i.mode=30;break}b=v=0}i.mode=28;case 28:if(i.wrap&&i.flags){for(;b<32;){if(0===y)break t;y--,v+=p[g++]<<b,b+=8}if(v!==(4294967295&i.total)){t.msg="incorrect length check",i.mode=30;break}b=v=0}i.mode=29;case 29:N=1;break t;case 30:N=-3;break t;case 31:return-4;default:return d}return t.next_out=_,t.avail_out=w,t.next_in=g,t.avail_in=y,i.hold=v,i.bits=b,(i.wsize||T!==t.avail_out&&i.mode<30&&(i.mode<27||4!==e))&&C(t,t.output,t.next_out,T-t.avail_out)?(i.mode=31,-4):(x-=t.avail_in,T-=t.avail_out,t.total_in+=x,t.total_out+=T,i.total+=T,i.wrap&&T&&(t.adler=i.check=i.flags?r(i.check,f,T,t.next_out-T):n(i.check,f,T,t.next_out-T)),t.data_type=i.bits+(i.last?64:0)+(12===i.mode?128:0)+(20===i.mode||15===i.mode?256:0),(0==x&&0===T||4===e)&&N===c&&(N=-5),N)},i.inflateEnd=function(t){if(!t||!t.state)return d;var e=t.state;return e.window&&(e.window=null),t.state=null,c},i.inflateGetHeader=function(t,e){var i;return t&&t.state&&2&(i=t.state).wrap?((i.head=e).done=!1,c):d},i.inflateSetDictionary=function(t,e){var i,s=e.length;return t&&t.state?0!==(i=t.state).wrap&&11!==i.mode?d:11===i.mode&&n(1,e,s,0)!==i.check?-3:C(t,e,s,s)?(i.mode=31,-4):(i.havedict=1,c):d},i.inflateInfo="pako inflate (from Nodeca project)"},{"../utils/common":41,"./adler32":43,"./crc32":45,"./inffast":48,"./inftrees":50}],50:[function(t,e,i){var s=t("../utils/common"),n=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],r=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],o=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];e.exports=function(t,e,i,l,h,c,d,u){var p,f,m,g,_,y,w,v,b,x=u.bits,T=0,E=0,C=0,S=0,A=0,O=0,P=0,I=0,k=0,D=0,z=null,M=0,B=new s.Buf16(16),N=new s.Buf16(16),U=null,L=0;for(T=0;T<=15;T++)B[T]=0;for(E=0;E<l;E++)B[e[i+E]]++;for(A=x,S=15;1<=S&&0===B[S];S--);if(S<A&&(A=S),0===S)return h[c++]=20971520,h[c++]=20971520,u.bits=1,0;for(C=1;C<S&&0===B[C];C++);for(A<C&&(A=C),T=I=1;T<=15;T++)if(I<<=1,(I-=B[T])<0)return-1;if(0<I&&(0===t||1!==S))return-1;for(N[1]=0,T=1;T<15;T++)N[T+1]=N[T]+B[T];for(E=0;E<l;E++)0!==e[i+E]&&(d[N[e[i+E]]++]=E);if(y=0===t?(z=U=d,19):1===t?(z=n,M-=257,U=r,L-=257,256):(z=o,U=a,-1),T=C,_=c,P=E=D=0,m=-1,g=(k=1<<(O=A))-1,1===t&&852<k||2===t&&592<k)return 1;for(;;){for(w=T-P,b=d[E]<y?(v=0,d[E]):d[E]>y?(v=U[L+d[E]],z[M+d[E]]):(v=96,0),p=1<<T-P,C=f=1<<O;h[_+(D>>P)+(f-=p)]=w<<24|v<<16|b,0!==f;);for(p=1<<T-1;D&p;)p>>=1;if(0!==p?(D&=p-1,D+=p):D=0,E++,0==--B[T]){if(T===S)break;T=e[i+d[E]]}if(A<T&&(D&g)!==m){for(0===P&&(P=A),_+=C,I=1<<(O=T-P);O+P<S&&!((I-=B[O+P])<=0);)O++,I<<=1;if(k+=1<<O,1===t&&852<k||2===t&&592<k)return 1;h[m=D&g]=A<<24|O<<16|_-c}}return 0!==D&&(h[_+D]=T-P<<24|64<<16),u.bits=A,0}},{"../utils/common":41}],51:[function(t,e,i){e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},{}],52:[function(t,e,i){var s=t("../utils/common"),n=0,r=1;function o(t){for(var e=t.length;0<=--e;)t[e]=0}var a=0,l=29,h=256,c=h+1+l,d=30,u=19,p=2*c+1,f=15,m=16,g=7,_=256,y=16,w=17,v=18,b=[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],T=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],E=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],C=new Array(2*(c+2));o(C);var S=new Array(2*d);o(S);var A=new Array(512);o(A);var O=new Array(256);o(O);var P=new Array(l);o(P);var I,k,D,z=new Array(d);function M(t,e,i,s,n){this.static_tree=t,this.extra_bits=e,this.extra_base=i,this.elems=s,this.max_length=n,this.has_stree=t&&t.length}function B(t,e){this.dyn_tree=t,this.max_code=0,this.stat_desc=e}function N(t){return t<256?A[t]:A[256+(t>>>7)]}function U(t,e){t.pending_buf[t.pending++]=255&e,t.pending_buf[t.pending++]=e>>>8&255}function L(t,e,i){t.bi_valid>m-i?(t.bi_buf|=e<<t.bi_valid&65535,U(t,t.bi_buf),t.bi_buf=e>>m-t.bi_valid,t.bi_valid+=i-m):(t.bi_buf|=e<<t.bi_valid&65535,t.bi_valid+=i)}function R(t,e,i){L(t,i[2*e],i[2*e+1])}function F(t,e){for(var i=0;i|=1&t,t>>>=1,i<<=1,0<--e;);return i>>>1}function V(t,e,i){var s,n,r=new Array(f+1),o=0;for(s=1;s<=f;s++)r[s]=o=o+i[s-1]<<1;for(n=0;n<=e;n++){var a=t[2*n+1];0!==a&&(t[2*n]=F(r[a]++,a))}}function j(t){var e;for(e=0;e<c;e++)t.dyn_ltree[2*e]=0;for(e=0;e<d;e++)t.dyn_dtree[2*e]=0;for(e=0;e<u;e++)t.bl_tree[2*e]=0;t.dyn_ltree[2*_]=1,t.opt_len=t.static_len=0,t.last_lit=t.matches=0}function Z(t){8<t.bi_valid?U(t,t.bi_buf):0<t.bi_valid&&(t.pending_buf[t.pending++]=t.bi_buf),t.bi_buf=0,t.bi_valid=0}function H(t,e,i,s){var n=2*e,r=2*i;return t[n]<t[r]||t[n]===t[r]&&s[e]<=s[i]}function $(t,e,i){for(var s=t.heap[i],n=i<<1;n<=t.heap_len&&(n<t.heap_len&&H(e,t.heap[n+1],t.heap[n],t.depth)&&n++,!H(e,s,t.heap[n],t.depth));)t.heap[i]=t.heap[n],i=n,n<<=1;t.heap[i]=s}function Y(t,e,i){var s,n,r,o,a=0;if(0!==t.last_lit)for(;s=t.pending_buf[t.d_buf+2*a]<<8|t.pending_buf[t.d_buf+2*a+1],n=t.pending_buf[t.l_buf+a],a++,0===s?R(t,n,e):(R(t,(r=O[n])+h+1,e),0!==(o=b[r])&&L(t,n-=P[r],o),R(t,r=N(--s),i),0!==(o=x[r])&&L(t,s-=z[r],o)),a<t.last_lit;);R(t,_,e)}function W(t,e){var i,s,n,r=e.dyn_tree,o=e.stat_desc.static_tree,a=e.stat_desc.has_stree,l=e.stat_desc.elems,h=-1;for(t.heap_len=0,t.heap_max=p,i=0;i<l;i++)0!==r[2*i]?(t.heap[++t.heap_len]=h=i,t.depth[i]=0):r[2*i+1]=0;for(;t.heap_len<2;)r[2*(n=t.heap[++t.heap_len]=h<2?++h:0)]=1,t.depth[n]=0,t.opt_len--,a&&(t.static_len-=o[2*n+1]);for(e.max_code=h,i=t.heap_len>>1;1<=i;i--)$(t,r,i);for(n=l;i=t.heap[1],t.heap[1]=t.heap[t.heap_len--],$(t,r,1),s=t.heap[1],t.heap[--t.heap_max]=i,t.heap[--t.heap_max]=s,r[2*n]=r[2*i]+r[2*s],t.depth[n]=(t.depth[i]>=t.depth[s]?t.depth[i]:t.depth[s])+1,r[2*i+1]=r[2*s+1]=n,t.heap[1]=n++,$(t,r,1),2<=t.heap_len;);t.heap[--t.heap_max]=t.heap[1],function(t,e){var i,s,n,r,o,a,l=e.dyn_tree,h=e.max_code,c=e.stat_desc.static_tree,d=e.stat_desc.has_stree,u=e.stat_desc.extra_bits,m=e.stat_desc.extra_base,g=e.stat_desc.max_length,_=0;for(r=0;r<=f;r++)t.bl_count[r]=0;for(l[2*t.heap[t.heap_max]+1]=0,i=t.heap_max+1;i<p;i++)g<(r=l[2*l[2*(s=t.heap[i])+1]+1]+1)&&(r=g,_++),l[2*s+1]=r,h<s||(t.bl_count[r]++,o=0,m<=s&&(o=u[s-m]),a=l[2*s],t.opt_len+=a*(r+o),d&&(t.static_len+=a*(c[2*s+1]+o)));if(0!==_){do{for(r=g-1;0===t.bl_count[r];)r--;t.bl_count[r]--,t.bl_count[r+1]+=2,t.bl_count[g]--,_-=2}while(0<_);for(r=g;0!==r;r--)for(s=t.bl_count[r];0!==s;)h<(n=t.heap[--i])||(l[2*n+1]!==r&&(t.opt_len+=(r-l[2*n+1])*l[2*n],l[2*n+1]=r),s--)}}(t,e),V(r,h,t.bl_count)}function X(t,e,i){var s,n,r=-1,o=e[1],a=0,l=7,h=4;for(0===o&&(l=138,h=3),e[2*(i+1)+1]=65535,s=0;s<=i;s++)n=o,o=e[2*(s+1)+1],++a<l&&n===o||(a<h?t.bl_tree[2*n]+=a:0!==n?(n!==r&&t.bl_tree[2*n]++,t.bl_tree[2*y]++):a<=10?t.bl_tree[2*w]++:t.bl_tree[2*v]++,r=n,h=(a=0)===o?(l=138,3):n===o?(l=6,3):(l=7,4))}function q(t,e,i){var s,n,r=-1,o=e[1],a=0,l=7,h=4;for(0===o&&(l=138,h=3),s=0;s<=i;s++)if(n=o,o=e[2*(s+1)+1],!(++a<l&&n===o)){if(a<h)for(;R(t,n,t.bl_tree),0!=--a;);else 0!==n?(n!==r&&(R(t,n,t.bl_tree),a--),R(t,y,t.bl_tree),L(t,a-3,2)):a<=10?(R(t,w,t.bl_tree),L(t,a-3,3)):(R(t,v,t.bl_tree),L(t,a-11,7));r=n,h=(a=0)===o?(l=138,3):n===o?(l=6,3):(l=7,4)}}o(z);var G=!1;function Q(t,e,i,n){var r,o,l;L(t,(a<<1)+(n?1:0),3),o=e,l=i,Z(r=t),U(r,l),U(r,~l),s.arraySet(r.pending_buf,r.window,o,l,r.pending),r.pending+=l}i._tr_init=function(t){G||(function(){var t,e,i,s,n,r=new Array(f+1);for(s=i=0;s<l-1;s++)for(P[s]=i,t=0;t<1<<b[s];t++)O[i++]=s;for(O[i-1]=s,s=n=0;s<16;s++)for(z[s]=n,t=0;t<1<<x[s];t++)A[n++]=s;for(n>>=7;s<d;s++)for(z[s]=n<<7,t=0;t<1<<x[s]-7;t++)A[256+n++]=s;for(e=0;e<=f;e++)r[e]=0;for(t=0;t<=143;)C[2*t+1]=8,t++,r[8]++;for(;t<=255;)C[2*t+1]=9,t++,r[9]++;for(;t<=279;)C[2*t+1]=7,t++,r[7]++;for(;t<=287;)C[2*t+1]=8,t++,r[8]++;for(V(C,c+1,r),t=0;t<d;t++)S[2*t+1]=5,S[2*t]=F(t,5);I=new M(C,b,h+1,c,f),k=new M(S,x,0,d,f),D=new M(new Array(0),T,0,u,g)}(),G=!0),t.l_desc=new B(t.dyn_ltree,I),t.d_desc=new B(t.dyn_dtree,k),t.bl_desc=new B(t.bl_tree,D),t.bi_buf=0,t.bi_valid=0,j(t)},i._tr_stored_block=Q,i._tr_flush_block=function(t,e,i,s){var o,a,l=0;0<t.level?(2===t.strm.data_type&&(t.strm.data_type=function(t){var e,i=4093624447;for(e=0;e<=31;e++,i>>>=1)if(1&i&&0!==t.dyn_ltree[2*e])return n;if(0!==t.dyn_ltree[18]||0!==t.dyn_ltree[20]||0!==t.dyn_ltree[26])return r;for(e=32;e<h;e++)if(0!==t.dyn_ltree[2*e])return r;return n}(t)),W(t,t.l_desc),W(t,t.d_desc),l=function(t){var e;for(X(t,t.dyn_ltree,t.l_desc.max_code),X(t,t.dyn_dtree,t.d_desc.max_code),W(t,t.bl_desc),e=u-1;3<=e&&0===t.bl_tree[2*E[e]+1];e--);return t.opt_len+=3*(e+1)+5+5+4,e}(t),o=t.opt_len+3+7>>>3,(a=t.static_len+3+7>>>3)<=o&&(o=a)):o=a=i+5,i+4<=o&&-1!==e?Q(t,e,i,s):4===t.strategy||a===o?(L(t,2+(s?1:0),3),Y(t,C,S)):(L(t,4+(s?1:0),3),function(t,e,i,s){var n;for(L(t,e-257,5),L(t,i-1,5),L(t,s-4,4),n=0;n<s;n++)L(t,t.bl_tree[2*E[n]+1],3);q(t,t.dyn_ltree,e-1),q(t,t.dyn_dtree,i-1)}(t,t.l_desc.max_code+1,t.d_desc.max_code+1,l+1),Y(t,t.dyn_ltree,t.dyn_dtree)),j(t),s&&Z(t)},i._tr_tally=function(t,e,i){return t.pending_buf[t.d_buf+2*t.last_lit]=e>>>8&255,t.pending_buf[t.d_buf+2*t.last_lit+1]=255&e,t.pending_buf[t.l_buf+t.last_lit]=255&i,t.last_lit++,0===e?t.dyn_ltree[2*i]++:(t.matches++,e--,t.dyn_ltree[2*(O[i]+h+1)]++,t.dyn_dtree[2*N(e)]++),t.last_lit===t.lit_bufsize-1},i._tr_align=function(t){var e;L(t,2,3),R(t,_,C),16===(e=t).bi_valid?(U(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):8<=e.bi_valid&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}},{"../utils/common":41}],53:[function(t,e,i){e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},{}],54:[function(t,e,i){(function(t){!function(t,e){if(!t.setImmediate){var i,s,n,r,o=1,a={},l=!1,h=t.document,c=Object.getPrototypeOf&&Object.getPrototypeOf(t);c=c&&c.setTimeout?c:t,i="[object process]"==={}.toString.call(t.process)?function(t){process.nextTick(function(){u(t)})}:function(){if(t.postMessage&&!t.importScripts){var e=!0,i=t.onmessage;return t.onmessage=function(){e=!1},t.postMessage("","*"),t.onmessage=i,e}}()?(r="setImmediate$"+Math.random()+"$",t.addEventListener?t.addEventListener("message",p,!1):t.attachEvent("onmessage",p),function(e){t.postMessage(r+e,"*")}):t.MessageChannel?((n=new MessageChannel).port1.onmessage=function(t){u(t.data)},function(t){n.port2.postMessage(t)}):h&&"onreadystatechange"in h.createElement("script")?(s=h.documentElement,function(t){var e=h.createElement("script");e.onreadystatechange=function(){u(t),e.onreadystatechange=null,s.removeChild(e),e=null},s.appendChild(e)}):function(t){setTimeout(u,0,t)},c.setImmediate=function(t){"function"!=typeof t&&(t=new Function(""+t));for(var e=new Array(arguments.length-1),s=0;s<e.length;s++)e[s]=arguments[s+1];var n={callback:t,args:e};return a[o]=n,i(o),o++},c.clearImmediate=d}function d(t){delete a[t]}function u(t){if(l)setTimeout(u,0,t);else{var i=a[t];if(i){l=!0;try{!function(t){var i=t.callback,s=t.args;switch(s.length){case 0:i();break;case 1:i(s[0]);break;case 2:i(s[0],s[1]);break;case 3:i(s[0],s[1],s[2]);break;default:i.apply(e,s)}}(i)}finally{d(t),l=!1}}}}function p(e){e.source===t&&"string"==typeof e.data&&0===e.data.indexOf(r)&&u(+e.data.slice(r.length))}}("undefined"==typeof self?void 0===t?this:t:self)}).call(this,void 0!==Q?Q:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10));class Fr{constructor(t,i){e(this,"date",new Date),e(this,"author"),e(this,"guid",G.create()),e(this,"viewpoint"),e(this,"modifiedAuthor"),e(this,"modifiedDate"),e(this,"topic"),e(this,"_components"),e(this,"_comment",""),this._components=t,this._comment=i;const s=this._components.get(Yr);this.author=s.config.author}set comment(t){var e;const i=this._components.get(Yr);this._comment=t,this.modifiedDate=new Date,this.modifiedAuthor=i.config.author,null==(e=this.topic)||e.comments.set(this.guid,this)}get comment(){return this._comment}toJSON(){var t,e;const i={guid:this.guid,date:this.date.toISOString(),author:this.author,comment:this.comment,topic_guid:null==(t=this.topic)?void 0:t.guid,viewpoint_guid:this.viewpoint,modified_date:null==(e=this.modifiedDate)?void 0:e.toISOString(),modified_author:this.modifiedAuthor};for(const[t,e]of Object.entries(i))void 0===e&&delete i[t];return i}}const Vr=class t{constructor(i){e(this,"guid",G.create()),e(this,"title",t.default.title),e(this,"creationDate",new Date),e(this,"creationAuthor",""),e(this,"viewpoints",new r),e(this,"relatedTopics",new r),e(this,"comments",new s),e(this,"documentReferences",new r),e(this,"customData",{}),e(this,"description"),e(this,"serverAssignedId"),e(this,"dueDate"),e(this,"modifiedAuthor"),e(this,"modifiedDate"),e(this,"index"),e(this,"_type",t.default.type),e(this,"_status",t.default.status),e(this,"_priority",t.default.priority),e(this,"_stage",t.default.stage),e(this,"_assignedTo",t.default.assignedTo),e(this,"_labels",t.default.labels??new Set),e(this,"_components"),this._components=i;const n=i.get(Yr);this.creationAuthor=n.config.author,this.relatedTopics.guard=t=>t!==this.guid}set type(t){const e=this._components.get(Yr),{strict:i,types:s}=e.config;(!i||s.has(t))&&(this._type=t)}get type(){return this._type}set status(t){const e=this._components.get(Yr),{strict:i,statuses:s}=e.config;(!i||s.has(t))&&(this._status=t)}get status(){return this._status}set priority(t){const e=this._components.get(Yr);if(t){const{strict:i,priorities:s}=e.config;if(!(!i||s.has(t)))return;this._priority=t}else this._priority=t}get priority(){return this._priority}set stage(t){const e=this._components.get(Yr);if(t){const{strict:i,stages:s}=e.config;if(!(!i||s.has(t)))return;this._stage=t}else this._stage=t}get stage(){return this._stage}set assignedTo(t){const e=this._components.get(Yr);if(t){const{strict:i,users:s}=e.config;if(!(!i||s.has(t)))return;this._assignedTo=t}else this._assignedTo=t}get assignedTo(){return this._assignedTo}set labels(t){const e=this._components.get(Yr),{strict:i,labels:s}=e.config;if(i){const e=new Set;for(const n of t){(!i||s.has(n))&&e.add(n)}this._labels=e}else this._labels=t}get labels(){return this._labels}get _managerVersion(){return this._components.get(Yr).config.version}set(t){const e=t,i=this;for(const s in t){if("guid"===s)continue;const t=e[s];s in this&&(i[s]=t)}return this._components.get(Yr).list.set(this.guid,this),this}createComment(t,e){const i=new Fr(this._components,t);return i.viewpoint=e,i.topic=this,this.comments.set(i.guid,i),i}createLabelTags(){const t=[...this.labels];if(this._components.get(Yr).config.exportCustomDataAsLabels)for(const e in this.customData){const i=this.customData[e];"string"==typeof i&&t.push(i)}return t}createCommentTags(){return[...this.comments.values()].map(t=>{var e;return{$Guid:t.guid,Date:t.date.toISOString(),Author:t.author,Comment:t.comment,ModifiedAuthor:t.modifiedAuthor,ModifiedDate:null==(e=t.modifiedDate)?void 0:e.toISOString(),Viewpoint:t.viewpoint?{$Guid:t.viewpoint}:void 0}})}createViewpointTags(){const t=this._components.get(Mo);return[...this.viewpoints].map(e=>t.list.get(e)).filter(t=>t).map(e=>{const i={$Guid:e.guid,Viewpoint:`${e.title??e.guid}.bcfv`};if(t.snapshots.get(e.snapshot)){const s=t.getSnapshotExtension(e.snapshot);i.Snapshot=`${e.snapshot}.${s}`}return i})}createRelatedTopicTags(){return[...this.relatedTopics].map(t=>({$Guid:t}))}createDocumentReferencesTag(t=this._managerVersion){const e=[];if("3"!==t&&"2.1"!==t)return e;const i=this._components.get(Yr);for(const s of this.documentReferences){const n=i.documents.get(s);if(!n)continue;let r={$Guid:G.create(),Description:n.description};"2.1"===t&&(r={...r,$isExternal:"external"===n.type||void 0,ReferencedDocument:"external"===n.type?n.url:`../${n.fileName}`}),"3"===t&&(r={...r,DocumentGuid:"internal"===n.type?s:void 0,Url:"external"===n.type?n.url:void 0}),Object.keys(r).length>0&&e.push(r)}return e}toJSON(){var t,e;const i={guid:this.guid,server_assigned_id:this.serverAssignedId,topic_type:this.type,topic_status:this.status,title:this.title,priority:this.priority,index:this.index,labels:[...this.labels],creation_date:this.creationDate.toISOString(),creation_author:this.creationAuthor,modified_date:null==(t=this.modifiedDate)?void 0:t.toISOString(),modified_author:this.modifiedAuthor,assigned_to:this.assignedTo,stage:this.stage,description:this.description,due_date:null==(e=this.dueDate)?void 0:e.toISOString(),comments:[...this.comments].map(([t,e])=>e.toJSON()),relatedTopics:[...this.relatedTopics].map(t=>({related_topic_guid:t}))},s=this._components.get(Mo);for(const t of this.viewpoints){const e=s.list.get(t);e&&(i.viewpoints||(i.viewpoints=[]),i.viewpoints.push(e.toJSON()))}const n=this._components.get(Yr);for(const t of this.documentReferences){const e=n.documents.get(t);e&&(i.document_references||(i.document_references=[]),"external"===e.type?i.document_references.push({guid:G.create(),description:e.description,url:e.url}):i.document_references.push({guid:G.create(),description:e.description,document_guid:t}))}for(const[t,e]of Object.entries(i))(void 0===e||Array.isArray(e)&&0===e.length)&&delete i[t];return i}serialize(){var t,e;const i=this._managerVersion,s={$Guid:this.guid,$TopicType:this.type,$TopicStatus:this.status,$ServerAssignedId:this.serverAssignedId,Title:this.title,CreationAuthor:this.creationAuthor,CreationDate:this.creationDate.toISOString(),Priority:this.priority,Index:"2.1"===i?this.index:void 0,ModifiedDate:null==(t=this.modifiedDate)?void 0:t.toISOString(),ModifiedAuthor:this.modifiedAuthor,DueDate:null==(e=this.dueDate)?void 0:e.toISOString(),AssignedTo:this.assignedTo,Description:this.description,Stage:this.stage,DocumentReferences:"3"===i?{DocumentReference:this.createDocumentReferencesTag(i)}:void 0,RelatedTopics:"3"===i?{RelatedTopic:this.createRelatedTopicTags()}:void 0,RelatedTopic:"2.1"===i?this.createRelatedTopicTags():void 0,Labels:"3"===i?{Label:this.createLabelTags()}:void 0,Viewpoints:"3"===i?{ViewPoint:this.createViewpointTags()}:void 0,Comments:"3"===i?{Comment:this.createCommentTags()}:void 0};"2.1"===i&&(s.Labels=this.createLabelTags(),s.DocumentReference=this.createDocumentReferencesTag(i));const n={Markup:{Topic:s}};return"2.1"===i&&(n.Markup.Viewpoints=this.createViewpointTags(),n.Markup.Comment=this.createCommentTags()),`<?xml version="1.0" encoding="UTF-8"?>\n ${_e.builder.build(n)}`}};e(Vr,"default",{title:"BCF Topic",type:"Issue",status:"Active"});let jr=Vr;const Zr=(t,e)=>{if(""===e.trim())return;const i=Yr.xmlParser.parse(e).Extensions;if(!i)return;const{Priorities:s,TopicStatuses:n,TopicTypes:r,Users:o}=i;if(s&&s.Priority){const e=Array.isArray(s.Priority)?s.Priority:[s.Priority];for(const i of e)t.config.priorities.add(i)}if(n&&n.TopicStatus){const e=Array.isArray(n.TopicStatus)?n.TopicStatus:[n.TopicStatus];for(const i of e)t.config.statuses.add(i)}if(r&&r.TopicType){const e=Array.isArray(r.TopicType)?r.TopicType:[r.TopicType];for(const i of e)t.config.types.add(i)}if(o&&o.User){const e=Array.isArray(o.User)?o.User:[o.User];for(const i of e)t.config.users.add(i)}};class Hr extends Te{constructor(){super(...arguments),e(this,"_config",{version:{type:"Select",options:new Set(["2.1","3"]),multiple:!1,value:""},author:{type:"Text",value:""},types:{type:"TextSet",value:new Set},statuses:{type:"TextSet",value:new Set},priorities:{type:"TextSet",value:new Set},labels:{type:"TextSet",value:new Set},stages:{type:"TextSet",value:new Set},users:{type:"TextSet",value:new Set},includeSelectionTag:{type:"Boolean",value:!1},updateExtensionsOnImport:{type:"Boolean",value:!1},strict:{type:"Boolean",value:!1},includeAllExtensionsOnExport:{type:"Boolean",value:!1},fallbackVersionOnImport:{type:"Select",multiple:!1,options:new Set(["2.1","3"]),value:""},ignoreIncompleteTopicsOnImport:{type:"Boolean",value:!1},exportCustomDataAsLabels:{type:"Boolean",value:!1}})}get version(){return this._config.version.value}set version(t){this._config.version.value=t}get author(){return this._config.author.value}set author(t){this._config.author.value=t}get types(){return this._config.types.value}set types(t){this._config.types.value=t}get statuses(){return this._config.statuses.value}set statuses(t){this._config.statuses.value=t}get priorities(){return this._config.priorities.value}set priorities(t){this._config.priorities.value=t}get labels(){return this._config.labels.value}set labels(t){this._config.labels.value=t}get stages(){return this._config.stages.value}set stages(t){this._config.stages.value=t}get users(){return this._config.users.value}set users(t){this._config.users.value=t}get includeSelectionTag(){return this._config.includeSelectionTag.value}set includeSelectionTag(t){this._config.includeSelectionTag.value=t}get updateExtensionsOnImport(){return this._config.updateExtensionsOnImport.value}set updateExtensionsOnImport(t){this._config.updateExtensionsOnImport.value=t}get strict(){return this._config.strict.value}set strict(t){this._config.strict.value=t}get includeAllExtensionsOnExport(){return this._config.includeAllExtensionsOnExport.value}set includeAllExtensionsOnExport(t){this._config.includeAllExtensionsOnExport.value=t}get fallbackVersionOnImport(){return this._config.fallbackVersionOnImport.value}set fallbackVersionOnImport(t){this._config.fallbackVersionOnImport.value=t}get ignoreIncompleteTopicsOnImport(){return this._config.ignoreIncompleteTopicsOnImport.value}set ignoreIncompleteTopicsOnImport(t){this._config.ignoreIncompleteTopicsOnImport.value=t}get exportCustomDataAsLabels(){return this._config.exportCustomDataAsLabels.value}set exportCustomDataAsLabels(t){this._config.exportCustomDataAsLabels.value=t}}const $r=class t extends V{constructor(){super(...arguments),e(this,"enabled",!1),e(this,"_defaultConfig",{author:"jhon.doe@example.com",version:"2.1",types:new Set(["Clash","Failure","Fault","Inquiry","Issue","Remark","Request"]),statuses:new Set(["Active","In Progress","Done","In Review","Closed"]),priorities:new Set(["On hold","Minor","Normal","Major","Critical"]),labels:new Set,stages:new Set,users:new Set,includeSelectionTag:!1,updateExtensionsOnImport:!0,strict:!1,includeAllExtensionsOnExport:!0,fallbackVersionOnImport:"2.1",ignoreIncompleteTopicsOnImport:!1,exportCustomDataAsLabels:!1}),e(this,"config",new Hr(this,this.components,"BCF Topics",t.uuid)),e(this,"list",new s),e(this,"documents",new s),e(this,"onSetup",new L),e(this,"isSetup",!1),e(this,"onBCFImported",new L),e(this,"onDisposed",new L)}setup(t){if(this.isSetup)return;const e={...this._defaultConfig,...t};this.config.version=e.version,this.config.author=e.author,this.config.types=e.types,this.config.statuses=e.statuses,this.config.priorities=e.priorities,this.config.labels=e.labels,this.config.stages=e.stages,this.config.users=e.users,this.config.includeSelectionTag=e.includeSelectionTag,this.config.updateExtensionsOnImport=e.updateExtensionsOnImport,this.config.strict=e.strict,this.config.includeAllExtensionsOnExport=e.includeAllExtensionsOnExport,this.config.fallbackVersionOnImport=e.fallbackVersionOnImport||"",this.config.ignoreIncompleteTopicsOnImport=e.ignoreIncompleteTopicsOnImport,this.isSetup=!0,this.enabled=!0,this.onSetup.trigger()}create(t){const e=new jr(this.components);return t?(e.guid=t.guid??e.guid,e.set(t)):this.list.set(e.guid,e),e}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}get usedTypes(){const t=[...this.list].map(([t,e])=>e.type);return new Set(t)}get usedStatuses(){const t=[...this.list].map(([t,e])=>e.status);return new Set(t)}get usedPriorities(){const t=[...this.list].map(([t,e])=>e.priority).filter(t=>t);return new Set(t)}get usedStages(){const t=[...this.list].map(([t,e])=>e.stage).filter(t=>t);return new Set(t)}get usedUsers(){const t=[];for(const[e,i]of this.list){t.push(i.creationAuthor),i.assignedTo&&t.push(i.assignedTo),i.modifiedAuthor&&t.push(i.modifiedAuthor);for(const[e,s]of i.comments)t.push(s.author),s.modifiedAuthor&&t.push(s.modifiedAuthor)}return new Set(t)}get usedLabels(){const t=[];for(const[e,i]of this.list)t.push(...i.labels);return new Set(t)}updateExtensions(){for(const[t,e]of this.list){for(const t of e.labels)this.config.labels.add(t);this.config.types.add(e.type),e.priority&&this.config.priorities.add(e.priority),e.stage&&this.config.stages.add(e.stage),this.config.statuses.add(e.status),this.config.users.add(e.creationAuthor),e.assignedTo&&this.config.users.add(e.assignedTo),e.modifiedAuthor&&this.config.users.add(e.modifiedAuthor);for(const[t,i]of e.comments)this.config.users.add(i.author),i.modifiedAuthor&&this.config.users.add(i.modifiedAuthor)}}updateViewpointReferences(){const t=this.components.get(Mo);for(const[e,i]of this.list)for(const e of i.viewpoints){t.list.has(e)||i.viewpoints.delete(e)}}async export(t=this.list.values()){const e=new Rr;e.file("bcf.version",`<?xml version="1.0" encoding="UTF-8"?>\n <Version VersionId="${this.config.version}" xsi:noNamespaceSchemaLocation="https://raw.githubusercontent.com/buildingSMART/BCF-XML/release_3_0/Schemas/version.xsd"\n xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">\n </Version>`);for(const[t,i]of this.documents.entries())"external"!==i.type&&e.file("2.1"===this.config.version?i.fileName:`documents/${t}`,i.data);if("3"===this.config.version){const t=[];for(const[e,i]of this.documents.entries()){const{type:s,description:n}=i;"external"!==s&&t.push(`<Document Guid="${e}">\n <Filename>${i.fileName}</Filename>\n ${n?`<Description>${n}</Description>`:""}\n </Document>`)}t.length>0&&e.file("documents.xml",`<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\n <DocumentInfo xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="documents.xsd">\n <Documents>\n ${t.join("\n")}\n </Documents>\n </DocumentInfo>`)}e.file("bcf.extensions",this.serializeExtensions());const i=this.components.get(Mo);for(const s of t){const t=e.folder(s.guid);t.file("markup.bcf",s.serialize());for(const e of s.viewpoints){const s=i.list.get(e);if(!s)continue;const n=s.title??s.guid;t.file(`${n}.bcfv`,await s.serialize());const r=i.snapshots.get(s.snapshot);if(!r)continue;const o=r?s.snapshot:s.guid,a=i.getSnapshotExtension(s.snapshot);t.file(`${o}.${a}`,r,{binary:!0})}}return await e.generateAsync({type:"blob"})}serializeExtensions(){const t=[...this.config.types].map(t=>`<TopicType>${t}</TopicType>`).join("\n"),e=[...this.config.statuses].map(t=>`<TopicStatus>${t}</TopicStatus>`).join("\n"),i=[...this.config.priorities].map(t=>`<Priority>${t}</Priority>`).join("\n"),s=[...this.config.labels].map(t=>`<TopicLabel>${t}</TopicLabel>`).join("\n"),n=[...this.config.stages].map(t=>`<Stage>${t}</Stage>`).join("\n"),r=[...this.config.users].map(t=>`<User>${t}</User>`).join("\n");return`\n <?xml version="1.0" encoding="UTF-8"?>\n <Extensions xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="your-schema-location.xsd">\n ${0!==t.length?`<TopicTypes>\n${t}\n</TopicTypes>`:""}\n ${0!==e.length?`<TopicStatuses>\n${e}\n</TopicStatuses>`:""}\n ${0!==i.length?`<Priorities>\n${i}\n</Priorities>`:""}\n ${0!==s.length?`<TopicLabels>\n${s}\n</TopicLabels>`:""}\n ${0!==n.length?`<Stages>\n${n}\n</Stages>`:""}\n ${0!==r.length?`<Users>\n${r}\n</Users>`:""}\n </Extensions>\n `}processMarkupComment(t){const{Guid:e,Date:i,Author:s,Comment:n,Viewpoint:r}=t;if(!(e&&i&&s&&(Fr||r)))return null;const o=new Fr(this.components,n??"");return o.guid=e,o.date=new Date(i),o.author=s,o.viewpoint=null==r?void 0:r.Guid,o.modifiedAuthor=t.ModifiedAuthor,o.modifiedDate=t.ModifiedDate?new Date(t.ModifiedDate):void 0,o}getMarkupComments(t,e){var i;let s;if("2.1"===e&&(s=t.Comment),"3"===e&&(s=null==(i=t.Topic.Comments)?void 0:i.Comment),!s)return[];s=Array.isArray(s)?s:[s];const n=s.map(t=>this.processMarkupComment(t)).filter(t=>t);return Array.isArray(n)?n:[n]}getMarkupLabels(t,e){var i;let s;if("2.1"===e&&(s=t.Topic.Labels),"3"===e&&(s=null==(i=t.Topic.Labels)?void 0:i.Label),!s)return[];return Array.isArray(s)?s:[s]}getMarkupViewpoints(t,e){var i;let s;return"2.1"===e&&(s=t.Viewpoints),"3"===e&&(s=null==(i=t.Topic.Viewpoints)?void 0:i.ViewPoint),s?(s=Array.isArray(s)?s:[s],s):[]}getMarkupRelatedTopics(t,e){var i;let s;if("2.1"===e&&(s=t.Topic.RelatedTopic),"3"===e&&(s=null==(i=t.Topic.RelatedTopics)?void 0:i.RelatedTopic),!s)return[];return(Array.isArray(s)?s:[s]).map(t=>t.Guid)}getMarkupDocumentReferences(t,e){var i;let s;if("2.1"===e&&(s=t.Topic.DocumentReference),"3"===e&&(s=null==(i=t.Topic.DocumentReferences)?void 0:i.DocumentReference),!s)return[];return Array.isArray(s)?s:[s]}async load(e){var i,s,n;const{fallbackVersionOnImport:r,ignoreIncompleteTopicsOnImport:a,updateExtensionsOnImport:l}=this.config,h=new Rr;await h.loadAsync(e);const c=Object.values(h.files);let d=r;const u=c.find(t=>t.name.endsWith(".version"));if(u){const e=await u.async("string"),i=t.xmlParser.parse(e).Version.VersionId;d=String(i)}if(!d||"2.1"!==d&&"3"!==d)throw new Error(`BCFTopics: ${d} is not supported.`);const p=c.find(t=>t.name.endsWith(".extensions"));if(l&&p){const t=await p.async("string");Zr(this,t)}const f=[],m=this.components.get(Mo),g=c.filter(t=>t.name.endsWith(".bcfv"));for(const e of g){const s=await e.async("string"),n=t.xmlParser.parse(s).VisualizationInfo;if(!n){console.warn("Missing VisualizationInfo in Viewpoint");continue}const r={},{Guid:a,ClippingPlanes:l,Components:h,OrthogonalCamera:c,PerspectiveCamera:u}=n;if(a&&(r.guid=a),h){const t={selection:[],coloring:[],visibility:{default_visibility:!1,exceptions:[],view_setup_hints:{spaces_visible:!1,space_boundaries_visible:!1,openings_visible:!1}}};r.components=t;const{Selection:e,Visibility:s}=h;if(e&&e.Component){const i=Array.isArray(e.Component)?e.Component:[e.Component];t.selection=i.map(t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null).filter(t=>null!==t)}if(s&&"DefaultVisibility"in s&&(t.visibility.default_visibility=s.DefaultVisibility),s&&s.Exceptions&&"Component"in s.Exceptions){const{Component:e}=s.Exceptions,i=Array.isArray(e)?e:[e];t.visibility.exceptions=i.map(t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null).filter(t=>null!==t)}let n;"2.1"===d&&(n=h.ViewSetupHints),"3"===d&&(n=null==(i=h.Visibility)?void 0:i.ViewSetupHints),n&&("OpeningsVisible"in n&&(t.visibility.view_setup_hints.openings_visible=n.OpeningsVisible),"SpacesVisible"in n&&(t.visibility.view_setup_hints.spaces_visible=n.SpacesVisible),"SpaceBoundariesVisible"in n&&(t.visibility.view_setup_hints.space_boundaries_visible=n.SpaceBoundariesVisible));const{Coloring:o}=h;if(o&&o.Color){const e=Array.isArray(o.Color)?o.Color:[o.Color];for(const i of e){const{Color:e,Component:s}=i;if(6!==e.length&&8!==e.length)continue;const n=6===e.length?e:e.slice(2),r=(Array.isArray(s)?s:[s]).map(t=>t.IfcGuid?{ifc_guid:t.IfcGuid}:null).filter(t=>null!==t);t.coloring.push({color:n,components:r})}}}if(c||u){const t=n.PerspectiveCamera??n.OrthogonalCamera,{CameraViewPoint:e,CameraDirection:i}=t,s=new o.Vector3(Number(e.X),Number(e.Z),Number(-e.Y)),a=new o.Vector3(Number(i.X),Number(i.Z),Number(-i.Y)),l={camera_view_point:{x:s.x,y:s.y,z:s.z},camera_direction:{x:a.x,y:a.y,z:a.z},aspect_ratio:"AspectRatio"in t?t.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in t&&(r.orthogonal_camera={...l,view_to_world_scale:t.ViewToWorldScale}),"FieldOfView"in t&&(r.perspective_camera={...l,field_of_view:t.FieldOfView})}if(l){const t=(Array.isArray(l.ClippingPlane)?l.ClippingPlane:[l.ClippingPlane]).map(({Location:t,Direction:e})=>({location:{x:t.x,y:t.y,z:t.z},direction:{x:e.x,y:e.y,z:e.z}}));r.clipping_planes=t}const p=new ko(this.components,r);f.push(p)}const _={},y=[],w=c.filter(t=>t.name.endsWith(".bcf"));for(const e of w){const i=await e.async("string"),r=t.xmlParser.parse(i).Markup,o=r.Topic,{Guid:l,TopicType:h,TopicStatus:u,Title:p,CreationDate:f,CreationAuthor:g}=o;if(a&&!(l&&h&&u&&p&&f&&g))continue;const w=new jr(this.components);w.guid=l??w.guid;const v=this.getMarkupRelatedTopics(r,d);_[w.guid]=new Set(v),w.type=h??w.type,w.status=u??w.status,w.title=p??w.title,w.creationDate=f?new Date(f):w.creationDate,w.creationAuthor=g??w.creationAuthor,w.serverAssignedId=o.ServerAssignedId,w.priority=o.Priority,w.index=o.Index,w.modifiedDate=o.ModifiedDate?new Date(o.ModifiedDate):void 0,w.modifiedAuthor=o.ModifiedAuthor,w.dueDate=o.DueDate?new Date(o.DueDate):void 0,w.assignedTo=o.AssignedTo,w.description=o.Description,w.stage=o.Stage;const b=this.getMarkupLabels(r,d);for(const t of b)w.labels.add(t);const x=this.getMarkupComments(r,d);for(const t of x)w.comments.set(t.guid,t);const T=this.getMarkupViewpoints(r,d);for(const t of T){if(!t||!t.Guid)continue;const e=m.list.get(t.Guid);if(!e)continue;w.viewpoints.add(e.guid);const i=`${w.guid}/${t.Snapshot}`,s=c.find(({name:t})=>t===i);if(s){const t=await s.async("arraybuffer"),i=new Uint8Array(t);m.snapshots.set(e.guid,i),e.snapshot=e.guid??null}}const E=this.getMarkupDocumentReferences(r,d),C=c.find(t=>"documents.xml"===t.name);let S=[];const A=await(null==C?void 0:C.async("string"));if(A){const t=null==(n=null==(s=_e.parser.parse(A).DocumentInfo)?void 0:s.Documents)?void 0:n.Document;S=Array.isArray(t)?t:[t]}for(const t of E){const{Description:e,DocumentGuid:i,Url:s,isExternal:n,ReferencedDocument:r}=t;if(i&&S.length>0){const t=S.find(({Guid:t})=>t===i),e=c.find(t=>t.name.endsWith(i)),s=await(null==e?void 0:e.async("uint8array"));if(!t||!s)continue;const{Description:n,Filename:r}=t;this.documents.set(i,{type:"internal",fileName:r,description:n,data:s}),w.documentReferences.add(i)}if(s){const t=this.documents.add({type:"external",url:s,description:e});w.documentReferences.add(t)}if(r){let t=null;if(n)t=this.documents.add({type:"external",url:r,description:e});else{const i=r.split("/"),s=i[i.length-1],n=c.find(t=>t.name.endsWith(s)),o=await(null==n?void 0:n.async("uint8array"));if(!o)continue;t=this.documents.add({type:"internal",fileName:s,data:o,description:e})}w.documentReferences.add(t)}}this.list.set(w.guid,w),y.push(w)}for(const t in _){const e=this.list.get(t);if(!e)continue;const i=_[t];for(const t of i)e.relatedTopics.add(t)}return this.onBCFImported.trigger(y),{viewpoints:f,topics:y}}};e($r,"uuid","de977976-e4f6-4e4f-a01a-204727839802"),e($r,"xmlParser",new ge.XMLParser({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 Yr=$r;const Wr=new T,Xr=new l,qr=new l,Gr=new x,Qr={X:new l(1,0,0),Y:new l(0,1,0),Z:new l(0,0,1)},Kr={type:"change"},Jr={type:"mouseDown",mode:null},to={type:"mouseUp",mode:null},eo={type:"objectChange"};class io extends b{constructor(t,e=null){super(void 0,e);const i=new Eo(this);this._root=i;const s=new Co;this._gizmo=s,i.add(s);const n=new So;this._plane=n,i.add(n);const r=this;function o(t,e){let i=e;Object.defineProperty(r,t,{get:function(){return void 0!==i?i:e},set:function(e){i!==e&&(i=e,n[t]=e,s[t]=e,r.dispatchEvent({type:t+"-changed",value:e}),r.dispatchEvent(Kr))}}),r[t]=e,n[t]=e,s[t]=e}o("camera",t),o("object",void 0),o("enabled",!0),o("axis",null),o("mode","translate"),o("translationSnap",null),o("rotationSnap",null),o("scaleSnap",null),o("space","world"),o("size",1),o("dragging",!1),o("showX",!0),o("showY",!0),o("showZ",!0),o("minX",-1/0),o("maxX",1/0),o("minY",-1/0),o("maxY",1/0),o("minZ",-1/0),o("maxZ",1/0);const a=new l,h=new l,c=new x,d=new x,u=new l,p=new x,f=new l,m=new l,g=new l,_=new l;o("worldPosition",a),o("worldPositionStart",h),o("worldQuaternion",c),o("worldQuaternionStart",d),o("cameraPosition",u),o("cameraQuaternion",p),o("pointStart",f),o("pointEnd",m),o("rotationAxis",g),o("rotationAngle",0),o("eye",_),this._offset=new l,this._startNorm=new l,this._endNorm=new l,this._cameraScale=new l,this._parentPosition=new l,this._parentQuaternion=new x,this._parentQuaternionInv=new x,this._parentScale=new l,this._worldScaleStart=new l,this._worldQuaternionInv=new x,this._worldScale=new l,this._positionStart=new l,this._quaternionStart=new x,this._scaleStart=new l,this._getPointer=so.bind(this),this._onPointerDown=ro.bind(this),this._onPointerHover=no.bind(this),this._onPointerMove=oo.bind(this),this._onPointerUp=ao.bind(this),null!==e&&this.connect(e)}connect(t){super.connect(t),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(t){if(void 0===this.object||!0===this.dragging)return;null!==t&&Wr.setFromCamera(t,this.camera);const e=lo(this._gizmo.picker[this.mode],Wr);this.axis=e?e.object.name:null}pointerDown(t){if(void 0!==this.object&&!0!==this.dragging&&(null==t||0===t.button)&&null!==this.axis){null!==t&&Wr.setFromCamera(t,this.camera);const e=lo(this._plane,Wr,!0);e&&(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(e.point).sub(this.worldPositionStart)),this.dragging=!0,Jr.mode=this.mode,this.dispatchEvent(Jr)}}pointerMove(t){const e=this.axis,i=this.mode,s=this.object;let n=this.space;if("scale"===i?n="local":"E"!==e&&"XYZE"!==e&&"XYZ"!==e||(n="world"),void 0===s||null===e||!1===this.dragging||null!==t&&-1!==t.button)return;null!==t&&Wr.setFromCamera(t,this.camera);const r=lo(this._plane,Wr,!0);if(r){if(this.pointEnd.copy(r.point).sub(this.worldPositionStart),"translate"===i)this._offset.copy(this.pointEnd).sub(this.pointStart),"local"===n&&"XYZ"!==e&&this._offset.applyQuaternion(this._worldQuaternionInv),-1===e.indexOf("X")&&(this._offset.x=0),-1===e.indexOf("Y")&&(this._offset.y=0),-1===e.indexOf("Z")&&(this._offset.z=0),"local"===n&&"XYZ"!==e?this._offset.applyQuaternion(this._quaternionStart).divide(this._parentScale):this._offset.applyQuaternion(this._parentQuaternionInv).divide(this._parentScale),s.position.copy(this._offset).add(this._positionStart),this.translationSnap&&("local"===n&&(s.position.applyQuaternion(Gr.copy(this._quaternionStart).invert()),-1!==e.search("X")&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),-1!==e.search("Y")&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),-1!==e.search("Z")&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.position.applyQuaternion(this._quaternionStart)),"world"===n&&(s.parent&&s.position.add(Xr.setFromMatrixPosition(s.parent.matrixWorld)),-1!==e.search("X")&&(s.position.x=Math.round(s.position.x/this.translationSnap)*this.translationSnap),-1!==e.search("Y")&&(s.position.y=Math.round(s.position.y/this.translationSnap)*this.translationSnap),-1!==e.search("Z")&&(s.position.z=Math.round(s.position.z/this.translationSnap)*this.translationSnap),s.parent&&s.position.sub(Xr.setFromMatrixPosition(s.parent.matrixWorld)))),s.position.x=Math.max(this.minX,Math.min(this.maxX,s.position.x)),s.position.y=Math.max(this.minY,Math.min(this.maxY,s.position.y)),s.position.z=Math.max(this.minZ,Math.min(this.maxZ,s.position.z));else if("scale"===i){if(-1!==e.search("XYZ")){let t=this.pointEnd.length()/this.pointStart.length();this.pointEnd.dot(this.pointStart)<0&&(t*=-1),qr.set(t,t,t)}else Xr.copy(this.pointStart),qr.copy(this.pointEnd),Xr.applyQuaternion(this._worldQuaternionInv),qr.applyQuaternion(this._worldQuaternionInv),qr.divide(Xr),-1===e.search("X")&&(qr.x=1),-1===e.search("Y")&&(qr.y=1),-1===e.search("Z")&&(qr.z=1);s.scale.copy(this._scaleStart).multiply(qr),this.scaleSnap&&(-1!==e.search("X")&&(s.scale.x=Math.round(s.scale.x/this.scaleSnap)*this.scaleSnap||this.scaleSnap),-1!==e.search("Y")&&(s.scale.y=Math.round(s.scale.y/this.scaleSnap)*this.scaleSnap||this.scaleSnap),-1!==e.search("Z")&&(s.scale.z=Math.round(s.scale.z/this.scaleSnap)*this.scaleSnap||this.scaleSnap))}else if("rotate"===i){this._offset.copy(this.pointEnd).sub(this.pointStart);const t=20/this.worldPosition.distanceTo(Xr.setFromMatrixPosition(this.camera.matrixWorld));let i=!1;"XYZE"===e?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(Xr.copy(this.rotationAxis).cross(this.eye))*t):"X"!==e&&"Y"!==e&&"Z"!==e||(this.rotationAxis.copy(Qr[e]),Xr.copy(Qr[e]),"local"===n&&Xr.applyQuaternion(this.worldQuaternion),Xr.cross(this.eye),0===Xr.length()?i=!0:this.rotationAngle=this._offset.dot(Xr.normalize())*t),("E"===e||i)&&(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"===n&&"E"!==e&&"XYZE"!==e?(s.quaternion.copy(this._quaternionStart),s.quaternion.multiply(Gr.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),s.quaternion.copy(Gr.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),s.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(Kr),this.dispatchEvent(eo)}}pointerUp(t){null!==t&&0!==t.button||(this.dragging&&null!==this.axis&&(to.mode=this.mode,this.dispatchEvent(to)),this.dragging=!1,this.axis=null)}dispose(){this.disconnect(),this._root.dispose()}attach(t){return this.object=t,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(Kr),this.dispatchEvent(eo),this.pointStart.copy(this.pointEnd))}getRaycaster(){return Wr}getMode(){return this.mode}setMode(t){this.mode=t}setTranslationSnap(t){this.translationSnap=t}setRotationSnap(t){this.rotationSnap=t}setScaleSnap(t){this.scaleSnap=t}setSize(t){this.size=t}setSpace(t){this.space=t}}function so(t){if(this.domElement.ownerDocument.pointerLockElement)return{x:0,y:0,button:t.button};{const e=this.domElement.getBoundingClientRect();return{x:(t.clientX-e.left)/e.width*2-1,y:-(t.clientY-e.top)/e.height*2+1,button:t.button}}}function no(t){if(this.enabled)switch(t.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(t))}}function ro(t){this.enabled&&(document.pointerLockElement||this.domElement.setPointerCapture(t.pointerId),this.domElement.addEventListener("pointermove",this._onPointerMove),this.pointerHover(this._getPointer(t)),this.pointerDown(this._getPointer(t)))}function oo(t){this.enabled&&this.pointerMove(this._getPointer(t))}function ao(t){this.enabled&&(this.domElement.releasePointerCapture(t.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(t)))}function lo(t,e,i){const s=e.intersectObject(t,!0);for(let t=0;t<s.length;t++)if(s[t].object.visible||i)return s[t];return!1}const ho=new B,co=new l(0,1,0),uo=new l(0,0,0),po=new f,fo=new x,mo=new x,go=new l,_o=new f,yo=new l(1,0,0),wo=new l(0,1,0),vo=new l(0,0,1),bo=new l,xo=new l,To=new l;class Eo extends E{constructor(t){super(),this.isTransformControlsRoot=!0,this.controls=t,this.visible=!1}updateMatrixWorld(t){const e=this.controls;void 0!==e.object&&(e.object.updateMatrixWorld(),null===e.object.parent?console.error("TransformControls: The attached 3D object must be a part of the scene graph."):e.object.parent.matrixWorld.decompose(e._parentPosition,e._parentQuaternion,e._parentScale),e.object.matrixWorld.decompose(e.worldPosition,e.worldQuaternion,e._worldScale),e._parentQuaternionInv.copy(e._parentQuaternion).invert(),e._worldQuaternionInv.copy(e.worldQuaternion).invert()),e.camera.updateMatrixWorld(),e.camera.matrixWorld.decompose(e.cameraPosition,e.cameraQuaternion,e._cameraScale),e.camera.isOrthographicCamera?e.camera.getWorldDirection(e.eye).negate():e.eye.copy(e.cameraPosition).sub(e.worldPosition).normalize(),super.updateMatrixWorld(t)}dispose(){this.traverse(function(t){t.geometry&&t.geometry.dispose(),t.material&&t.material.dispose()})}}class Co extends E{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const t=new C({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),e=new S({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),i=t.clone();i.opacity=.15;const s=e.clone();s.opacity=.5;const n=t.clone();n.color.setHex(16711680);const r=t.clone();r.color.setHex(65280);const o=t.clone();o.color.setHex(255);const a=t.clone();a.color.setHex(16711680),a.opacity=.5;const l=t.clone();l.color.setHex(65280),l.opacity=.5;const h=t.clone();h.color.setHex(255),h.opacity=.5;const c=t.clone();c.opacity=.25;const d=t.clone();d.color.setHex(16776960),d.opacity=.25;t.clone().color.setHex(16776960);const u=t.clone();u.color.setHex(7895160);const p=new A(0,.04,.1,12);p.translate(0,.05,0);const f=new O(.08,.08,.08);f.translate(0,.04,0);const m=new P;m.setAttribute("position",new I([0,0,0,1,0,0],3));const g=new A(.0075,.0075,.5,3);function _(t,e){const i=new z(t,.0075,3,64,e*Math.PI*2);return i.rotateY(Math.PI/2),i.rotateX(Math.PI/2),i}g.translate(0,.25,0);const y={X:[[new v(p,n),[.5,0,0],[0,0,-Math.PI/2]],[new v(p,n),[-.5,0,0],[0,0,Math.PI/2]],[new v(g,n),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new v(p,r),[0,.5,0]],[new v(p,r),[0,-.5,0],[Math.PI,0,0]],[new v(g,r)]],Z:[[new v(p,o),[0,0,.5],[Math.PI/2,0,0]],[new v(p,o),[0,0,-.5],[-Math.PI/2,0,0]],[new v(g,o),null,[Math.PI/2,0,0]]],XYZ:[[new v(new k(.1,0),c.clone()),[0,0,0]]],XY:[[new v(new O(.15,.15,.01),h.clone()),[.15,.15,0]]],YZ:[[new v(new O(.15,.15,.01),a.clone()),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new v(new O(.15,.15,.01),l.clone()),[.15,0,.15],[-Math.PI/2,0,0]]]},w={X:[[new v(new A(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new v(new A(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new v(new A(.2,0,.6,4),i),[0,.3,0]],[new v(new A(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new v(new A(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new v(new A(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new v(new k(.2,0),i)]],XY:[[new v(new O(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new v(new O(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new v(new O(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]]},b={START:[[new v(new k(.01,2),s),null,null,null,"helper"]],END:[[new v(new k(.01,2),s),null,null,null,"helper"]],DELTA:[[new D(function(){const t=new P;return t.setAttribute("position",new I([0,0,0,1,1,1],3)),t}(),s),null,null,null,"helper"]],X:[[new D(m,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new D(m,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new D(m,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},x={XYZE:[[new v(_(.5,1),u),null,[0,Math.PI/2,0]]],X:[[new v(_(.5,.5),n)]],Y:[[new v(_(.5,.5),r),null,[0,0,-Math.PI/2]]],Z:[[new v(_(.5,.5),o),null,[0,Math.PI/2,0]]],E:[[new v(_(.75,1),d),null,[0,Math.PI/2,0]]]},T={AXIS:[[new D(m,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]]},B={XYZE:[[new v(new M(.25,10,8),i)]],X:[[new v(new z(.5,.1,4,24),i),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new v(new z(.5,.1,4,24),i),[0,0,0],[Math.PI/2,0,0]]],Z:[[new v(new z(.5,.1,4,24),i),[0,0,0],[0,0,-Math.PI/2]]],E:[[new v(new z(.75,.1,2,24),i)]]},N={X:[[new v(f,n),[.5,0,0],[0,0,-Math.PI/2]],[new v(g,n),[0,0,0],[0,0,-Math.PI/2]],[new v(f,n),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new v(f,r),[0,.5,0]],[new v(g,r)],[new v(f,r),[0,-.5,0],[0,0,Math.PI]]],Z:[[new v(f,o),[0,0,.5],[Math.PI/2,0,0]],[new v(g,o),[0,0,0],[Math.PI/2,0,0]],[new v(f,o),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new v(new O(.15,.15,.01),h),[.15,.15,0]]],YZ:[[new v(new O(.15,.15,.01),a),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new v(new O(.15,.15,.01),l),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new v(new O(.1,.1,.1),c.clone())]]},U={X:[[new v(new A(.2,0,.6,4),i),[.3,0,0],[0,0,-Math.PI/2]],[new v(new A(.2,0,.6,4),i),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new v(new A(.2,0,.6,4),i),[0,.3,0]],[new v(new A(.2,0,.6,4),i),[0,-.3,0],[0,0,Math.PI]]],Z:[[new v(new A(.2,0,.6,4),i),[0,0,.3],[Math.PI/2,0,0]],[new v(new A(.2,0,.6,4),i),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new v(new O(.2,.2,.01),i),[.15,.15,0]]],YZ:[[new v(new O(.2,.2,.01),i),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new v(new O(.2,.2,.01),i),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new v(new O(.2,.2,.2),i),[0,0,0]]]},L={X:[[new D(m,s.clone()),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new D(m,s.clone()),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new D(m,s.clone()),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function R(t){const e=new E;for(const i in t)for(let s=t[i].length;s--;){const n=t[i][s][0].clone(),r=t[i][s][1],o=t[i][s][2],a=t[i][s][3],l=t[i][s][4];n.name=i,n.tag=l,r&&n.position.set(r[0],r[1],r[2]),o&&n.rotation.set(o[0],o[1],o[2]),a&&n.scale.set(a[0],a[1],a[2]),n.updateMatrix();const h=n.geometry.clone();h.applyMatrix4(n.matrix),n.geometry=h,n.renderOrder=1/0,n.position.set(0,0,0),n.rotation.set(0,0,0),n.scale.set(1,1,1),e.add(n)}return e}this.gizmo={},this.picker={},this.helper={},this.add(this.gizmo.translate=R(y)),this.add(this.gizmo.rotate=R(x)),this.add(this.gizmo.scale=R(N)),this.add(this.picker.translate=R(w)),this.add(this.picker.rotate=R(B)),this.add(this.picker.scale=R(U)),this.add(this.helper.translate=R(b)),this.add(this.helper.rotate=R(T)),this.add(this.helper.scale=R(L)),this.picker.translate.visible=!1,this.picker.rotate.visible=!1,this.picker.scale.visible=!1}updateMatrixWorld(t){const e="local"===("scale"===this.mode?"local":this.space)?this.worldQuaternion:mo;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 i=[];i=i.concat(this.picker[this.mode].children),i=i.concat(this.gizmo[this.mode].children),i=i.concat(this.helper[this.mode].children);for(let t=0;t<i.length;t++){const s=i[t];let n;if(s.visible=!0,s.rotation.set(0,0,0),s.position.copy(this.worldPosition),n=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),s.scale.set(1,1,1).multiplyScalar(n*this.size/4),"helper"!==s.tag){if(s.quaternion.copy(e),"translate"===this.mode||"scale"===this.mode){const t=.99,i=.2;"X"===s.name&&Math.abs(co.copy(yo).applyQuaternion(e).dot(this.eye))>t&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),"Y"===s.name&&Math.abs(co.copy(wo).applyQuaternion(e).dot(this.eye))>t&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),"Z"===s.name&&Math.abs(co.copy(vo).applyQuaternion(e).dot(this.eye))>t&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),"XY"===s.name&&Math.abs(co.copy(vo).applyQuaternion(e).dot(this.eye))<i&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),"YZ"===s.name&&Math.abs(co.copy(yo).applyQuaternion(e).dot(this.eye))<i&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1),"XZ"===s.name&&Math.abs(co.copy(wo).applyQuaternion(e).dot(this.eye))<i&&(s.scale.set(1e-10,1e-10,1e-10),s.visible=!1)}else"rotate"===this.mode&&(fo.copy(e),co.copy(this.eye).applyQuaternion(Gr.copy(e).invert()),-1!==s.name.search("E")&&s.quaternion.setFromRotationMatrix(po.lookAt(this.eye,uo,wo)),"X"===s.name&&(Gr.setFromAxisAngle(yo,Math.atan2(-co.y,co.z)),Gr.multiplyQuaternions(fo,Gr),s.quaternion.copy(Gr)),"Y"===s.name&&(Gr.setFromAxisAngle(wo,Math.atan2(co.x,co.z)),Gr.multiplyQuaternions(fo,Gr),s.quaternion.copy(Gr)),"Z"===s.name&&(Gr.setFromAxisAngle(vo,Math.atan2(co.y,co.x)),Gr.multiplyQuaternions(fo,Gr),s.quaternion.copy(Gr)));s.visible=s.visible&&(-1===s.name.indexOf("X")||this.showX),s.visible=s.visible&&(-1===s.name.indexOf("Y")||this.showY),s.visible=s.visible&&(-1===s.name.indexOf("Z")||this.showZ),s.visible=s.visible&&(-1===s.name.indexOf("E")||this.showX&&this.showY&&this.showZ),s.material._color=s.material._color||s.material.color.clone(),s.material._opacity=s.material._opacity||s.material.opacity,s.material.color.copy(s.material._color),s.material.opacity=s.material._opacity,this.enabled&&this.axis&&(s.name===this.axis||this.axis.split("").some(function(t){return s.name===t}))&&(s.material.color.setHex(16776960),s.material.opacity=1)}else s.visible=!1,"AXIS"===s.name?(s.visible=!!this.axis,"X"===this.axis&&(Gr.setFromEuler(ho.set(0,0,0)),s.quaternion.copy(e).multiply(Gr),Math.abs(co.copy(yo).applyQuaternion(e).dot(this.eye))>.9&&(s.visible=!1)),"Y"===this.axis&&(Gr.setFromEuler(ho.set(0,0,Math.PI/2)),s.quaternion.copy(e).multiply(Gr),Math.abs(co.copy(wo).applyQuaternion(e).dot(this.eye))>.9&&(s.visible=!1)),"Z"===this.axis&&(Gr.setFromEuler(ho.set(0,Math.PI/2,0)),s.quaternion.copy(e).multiply(Gr),Math.abs(co.copy(vo).applyQuaternion(e).dot(this.eye))>.9&&(s.visible=!1)),"XYZE"===this.axis&&(Gr.setFromEuler(ho.set(0,Math.PI/2,0)),co.copy(this.rotationAxis),s.quaternion.setFromRotationMatrix(po.lookAt(uo,co,wo)),s.quaternion.multiply(Gr),s.visible=this.dragging),"E"===this.axis&&(s.visible=!1)):"START"===s.name?(s.position.copy(this.worldPositionStart),s.visible=this.dragging):"END"===s.name?(s.position.copy(this.worldPosition),s.visible=this.dragging):"DELTA"===s.name?(s.position.copy(this.worldPositionStart),s.quaternion.copy(this.worldQuaternionStart),Xr.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),Xr.applyQuaternion(this.worldQuaternionStart.clone().invert()),s.scale.copy(Xr),s.visible=this.dragging):(s.quaternion.copy(e),this.dragging?s.position.copy(this.worldPositionStart):s.position.copy(this.worldPosition),this.axis&&(s.visible=-1!==this.axis.search(s.name)))}super.updateMatrixWorld(t)}}class So extends v{constructor(){super(new N(1e5,1e5,2,2),new C({visible:!1,wireframe:!0,side:_,transparent:!0,opacity:.1,toneMapped:!1})),this.isTransformControlsPlane=!0,this.type="TransformControlsPlane"}updateMatrixWorld(t){let e=this.space;switch(this.position.copy(this.worldPosition),"scale"===this.mode&&(e="local"),bo.copy(yo).applyQuaternion("local"===e?this.worldQuaternion:mo),xo.copy(wo).applyQuaternion("local"===e?this.worldQuaternion:mo),To.copy(vo).applyQuaternion("local"===e?this.worldQuaternion:mo),co.copy(xo),this.mode){case"translate":case"scale":switch(this.axis){case"X":co.copy(this.eye).cross(bo),go.copy(bo).cross(co);break;case"Y":co.copy(this.eye).cross(xo),go.copy(xo).cross(co);break;case"Z":co.copy(this.eye).cross(To),go.copy(To).cross(co);break;case"XY":go.copy(To);break;case"YZ":go.copy(bo);break;case"XZ":co.copy(To),go.copy(xo);break;case"XYZ":case"E":go.set(0,0,0)}break;default:go.set(0,0,0)}0===go.length()?this.quaternion.copy(this.cameraQuaternion):(_o.lookAt(Xr.set(0,0,0),go,co),this.quaternion.setFromRotationMatrix(_o)),super.updateMatrixWorld(t)}}class Ao{constructor(t,i,s,n,r,a=5,l=!0){if(e(this,"onDraggingStarted",new L),e(this,"onDraggingEnded",new L),e(this,"onDisposed",new L),e(this,"normal"),e(this,"origin"),e(this,"three",new o.Plane),e(this,"components"),e(this,"world"),e(this,"type","default"),e(this,"_title","Clipping Plane"),e(this,"_helper"),e(this,"_visible",!0),e(this,"_enabled",!0),e(this,"_controlsActive",!1),e(this,"_arrowBoundBox",new o.Mesh),e(this,"_planeMesh"),e(this,"_controls"),e(this,"_hiddenMaterial",new o.MeshBasicMaterial({visible:!1})),e(this,"_visibilityBeforeDisabled",!0),e(this,"notifyManager",()=>{const t=this.components.get(Io),e=t.list.getKey(this);e&&t.list.set(e,this)}),e(this,"update",()=>{this._enabled&&this.three.setFromNormalAndCoplanarPoint(this.normal,this._helper.position)}),e(this,"changeDrag",t=>{this._visible=!t.value,this.preventCameraMovement(),this.notifyDraggingChanged(t)}),this.components=t,this.world=i,!i.renderer)throw new Error("The given world must have a renderer!");this.normal=n,this.origin=s,i.renderer.setPlane(!0,this.three),this._planeMesh=Ao.newPlaneMesh(a,r),this._helper=this.newHelper(),this._controls=this.newTransformControls(),this.three.setFromNormalAndCoplanarPoint(n,s),l&&this.toggleControls(!0)}set title(t){this._title=t,this.notifyManager()}get title(){return this._title}get enabled(){return this._enabled}set enabled(t){if(!this.world.isDisposing){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");this._enabled=t,t?this.visible=this._visibilityBeforeDisabled:(this._visibilityBeforeDisabled=this.visible,this.visible=!1),this.world.renderer.setPlane(t,this.three),this.notifyManager()}}get visible(){return this._visible}set visible(t){this._visible=t,this._controls.getHelper().visible=t,this._helper.visible=t,this.toggleControls(t),this.notifyManager()}get meshes(){return[this._planeMesh,this._arrowBoundBox]}get planeMaterial(){return this._planeMesh.material}set planeMaterial(t){this._planeMesh.material=t}get size(){return this._planeMesh.scale.x}set size(t){this._planeMesh.scale.set(t,t,t)}get helper(){return this._helper}get controls(){return this._controls}setFromNormalAndCoplanarPoint(t,e){this.reset(),this.normal.equals(t)||(this.normal.copy(t),this._helper.lookAt(t)),this.origin.copy(e),this._helper.position.copy(e),this._helper.updateMatrix(),this.update()}dispose(){this._enabled=!1,this.onDraggingStarted.reset(),this.onDraggingEnded.reset(),this._helper.removeFromParent(),this.world.renderer&&this.world.renderer.setPlane(!1,this.three),this._arrowBoundBox.removeFromParent(),this._arrowBoundBox.geometry.dispose(),this._planeMesh.geometry.dispose(),this._controls.getHelper().removeFromParent(),this._controls.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}reset(){const t=new o.Vector3(1,0,0),e=new o.Vector3;this.normal.equals(t)||(this.normal.copy(t),this._helper.lookAt(t)),this.origin.copy(e),this._helper.position.copy(e),this._helper.updateMatrix()}toggleControls(t){if(t){if(this._controlsActive)return;this._controls.addEventListener("change",this.update),this._controls.addEventListener("dragging-changed",this.changeDrag)}else this._controls.removeEventListener("change",this.update),this._controls.removeEventListener("dragging-changed",this.changeDrag);this._controlsActive=t}newTransformControls(){if(!this.world.renderer)throw new Error("No renderer found for clipping plane!");const t=this.world.camera.three,e=this.world.renderer.three.domElement,i=new io(t,e);return this.initializeControls(i),this.world.scene.three.add(i.getHelper()),i}initializeControls(t){t.attach(this._helper),t.showX=!1,t.showY=!1,t.setSpace("local"),this.createArrowBoundingBox(),t.getHelper().children[0].children[0].add(this._arrowBoundBox)}createArrowBoundingBox(){this._arrowBoundBox.geometry=new o.CylinderGeometry(.18,.18,1.2),this._arrowBoundBox.material=this._hiddenMaterial,this._arrowBoundBox.rotateX(Math.PI/2),this._arrowBoundBox.updateMatrix(),this._arrowBoundBox.geometry.applyMatrix4(this._arrowBoundBox.matrix)}notifyDraggingChanged(t){t.value?this.onDraggingStarted.trigger():this.onDraggingEnded.trigger()}preventCameraMovement(){this.world.camera.enabled=this._visible}newHelper(){const t=new o.Object3D;return t.lookAt(this.normal),t.position.copy(this.origin),this._planeMesh.position.z+=.01,t.add(this._planeMesh),this.world.scene.three.add(t),t}static newPlaneMesh(t,e){const i=new o.PlaneGeometry(1),s=new o.Mesh(i,e);return s.scale.set(t,t,t),s}}class Oo extends Te{constructor(){super(...arguments),e(this,"_config",{enabled:{value:!0,type:"Boolean"},visible:{value:!0,type:"Boolean"},color:{value:new o.Color,type:"Color"},opacity:{type:"Number",interpolable:!0,value:1,min:0,max:1},size:{type:"Number",interpolable:!0,value:2,min:0,max:100}})}get enabled(){return this._config.enabled.value}set enabled(t){this._config.enabled.value=t,this._component.enabled=t}get visible(){return this._config.visible.value}set visible(t){this._config.visible.value=t,this._component.visible=t}get color(){return this._config.color.value}set color(t){this._config.color.value=t,this._component.material.color.copy(t)}get opacity(){return this._config.opacity.value}set opacity(t){this._config.opacity.value=t,this._component.material.opacity=t}get size(){return this._config.size.value}set size(t){this._config.size.value=t,this._component.size=t}}const Po=class t extends V{constructor(s){super(s),e(this,"onSetup",new L),e(this,"onBeforeDrag",new L),e(this,"onAfterDrag",new L),e(this,"onBeforeCreate",new L),e(this,"onBeforeCancel",new L),e(this,"onAfterCancel",new L),e(this,"onBeforeDelete",new L),e(this,"onAfterCreate",new L),e(this,"onAfterDelete",new L),e(this,"onDisposed",new L),e(this,"isSetup",!1),e(this,"orthogonalY",!1),e(this,"toleranceOrthogonalY",.7),e(this,"Type",Ao),e(this,"list",new i.DataMap),e(this,"config",new Oo(this,this.components,"Clipper",t.uuid)),e(this,"_defaultConfig",{color:new o.Color(12255487),opacity:.2,size:2}),e(this,"_material",new o.MeshBasicMaterial({color:12255487,side:o.DoubleSide,transparent:!0,opacity:.2})),e(this,"_size",5),e(this,"_enabled",!1),e(this,"_visible",!0),e(this,"onStateChanged",new L),e(this,"_onStartDragging",()=>{this.onBeforeDrag.trigger()}),e(this,"_onEndDragging",()=>{this.onAfterDrag.trigger()}),this.components.add(t.uuid,this),this.setEvents()}get enabled(){return this._enabled}set enabled(t){this._enabled=t,this.onStateChanged.trigger(["enabled"])}get visible(){return this._visible}set visible(t){this._visible=t;for(const[e,i]of this.list)i.visible=t;this.onStateChanged.trigger(["visibility"])}get material(){return this._material}set material(t){this._material=t;for(const[e,i]of this.list)i.planeMaterial=t;this.onStateChanged.trigger(["material"])}get size(){return this._size}set size(t){this._size=t;for(const[e,i]of this.list)i.size=t;this.onStateChanged.trigger(["size"])}setEvents(){this.list.onBeforeDelete.add(({value:t})=>{if(!t.world.renderer)throw new Error("Renderer not found for this plane's world!");t.world.renderer.setPlane(!1,t.three),t.dispose(),this.updateMaterialsAndPlanes(),this.onAfterDelete.trigger(t)})}dispose(){this._enabled=!1;this.components.get(Ce).list.delete(this.config.uuid),this.list.clear(),this._material.dispose(),this.onBeforeCreate.reset(),this.onBeforeCancel.reset(),this.onBeforeDelete.reset(),this.onBeforeDrag.reset(),this.onAfterCreate.reset(),this.onAfterCancel.reset(),this.onAfterDelete.reset(),this.onAfterDrag.reset(),this.onDisposed.trigger(t.uuid),this.onDisposed.reset()}async create(t){const e=this.components.get(Ye).get(t),i=await e.castRay();return i?this.createPlaneFromIntersection(t,i):null}createFromNormalAndCoplanarPoint(t,e,i){const s=this.newPlane(t,i,e);return this.updateMaterialsAndPlanes(),s}async delete(t,e){if(!e){const i=await this.pickPlane(t);if(!i)return;e=this.list.getKey(i)}e&&this.list.delete(e)}deleteAll(t){for(const[e,i]of this.list)t&&!t.has(i.type)||this.list.delete(e)}setup(t){const e={...this._defaultConfig,...t};this.config.color=e.color,this.config.opacity=e.opacity,this.config.size=e.size,this.isSetup=!0,this.onSetup.trigger()}async pickPlane(t){const e=this.components.get(Ye).get(t),i=this.getAllPlaneMeshes(),s=await e.castRay({items:i});if(s){const t=s.object;return[...this.list.values()].find(e=>e.meshes.includes(t))}}getAllPlaneMeshes(){const t=[];for(const[e,i]of this.list)t.push(...i.meshes);return t}createPlaneFromIntersection(t,e){var i;if(!t.renderer)throw new Error("The given world must have a renderer!");const s=e.point.distanceTo(new o.Vector3(0,0,0)),n=e.normal||(null==(i=e.face)?void 0:i.normal);if(!s||!n)return null;const r=this.getWorldNormal(e,n),a=this.newPlane(t,e.point,r.negate()),l=this.list.get(a);return l.visible=this._visible,l.size=this._size,t.renderer.setPlane(!0,l.three),this.updateMaterialsAndPlanes(),l}getWorldNormal(t,e){const i=t.object;let s=t.object.matrixWorld.clone();if(i instanceof o.InstancedMesh&&void 0!==t.instanceId){const e=new o.Matrix4;i.getMatrixAt(t.instanceId,e),s=e.multiply(s)}const n=(new o.Matrix3).getNormalMatrix(s),r=e.clone().applyMatrix3(n).normalize();return this.normalizePlaneDirectionY(r),r}normalizePlaneDirectionY(t){this.orthogonalY&&(t.y>this.toleranceOrthogonalY&&(t.x=0,t.y=1,t.z=0),t.y<-this.toleranceOrthogonalY&&(t.x=0,t.y=-1,t.z=0))}newPlane(t,e,i){const s=new this.Type(this.components,t,e,i,this._material);s.onDraggingStarted.add(this._onStartDragging),s.onDraggingEnded.add(this._onEndDragging);const n=G.create();return this.list.set(n,s),this.onAfterCreate.trigger(s),n}updateMaterialsAndPlanes(){const t=this.components.get(Ki);for(const[e,i]of t.list){if(!i.renderer)continue;i.renderer.updateClippingPlanes();const{clippingPlanes:t}=i.renderer;for(const e of i.meshes)if(e.material)if(Array.isArray(e.material))for(const i of e.material)i.clippingPlanes=t;else e.material.clippingPlanes=t}}};e(Po,"uuid","66290bc5-18c4-4cd1-9379-2e17a0617611");let Io=Po;class ko{constructor(t,s){e(this,"title"),e(this,"guid",G.create()),e(this,"clippingPlanes",new i.DataSet),e(this,"camera",{aspect_ratio:1,field_of_view:60,camera_direction:{x:0,y:0,z:0},camera_view_point:{x:0,y:0,z:0},camera_up_vector:{x:0,y:1,z:0}}),e(this,"customData",{}),e(this,"exceptionComponents",new i.DataSet),e(this,"selectionComponents",new i.DataSet),e(this,"componentColors",new i.DataMap),e(this,"spacesVisible",!1),e(this,"spaceBoundariesVisible",!1),e(this,"openingsVisible",!1),e(this,"defaultVisibility",!0),e(this,"snapshot",this.guid),e(this,"_components"),e(this,"_world",null),e(this,"notifyUpdate",()=>{this._components.get(Mo).list.set(this.guid,this)}),this._components=t,s&&(this.guid=s.guid??this.guid,this.set(s)),this.setEvents()}async getSelectionMap(){const t=this._components.get(Oe);return await t.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const t=this._components.get(Oe);return await t.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const t=this._components.get(Oe),{camera_view_point:e}=this.camera,{x:i,y:s,z:n}=e,r=new o.Vector3(i,s,n);return t.applyBaseCoordinateSystem(r,new o.Matrix4),r}set position(t){const e=t.clone(),i=this._components.get(Oe);t.clone().applyMatrix4(i.baseCoordinationMatrix.clone().invert()),this.camera.camera_view_point={x:e.x,y:e.y,z:e.z}}get direction(){const{camera_direction:t}=this.camera,{x:e,y:i,z:s}=t;return new o.Vector3(e,i,s)}set world(t){this._world=t}get world(){return this._world}get _managerVersion(){return this._components.get(Yr).config.version}get topics(){return[...this._components.get(Yr).list.values()].filter(t=>t.viewpoints.has(this.guid))}setEvents(){this.selectionComponents.onUpdated.add(this.notifyUpdate),this.exceptionComponents.onUpdated.add(this.notifyUpdate),this.clippingPlanes.onUpdated.add(this.notifyUpdate),this.componentColors.onItemSet.add(this.notifyUpdate),this.componentColors.onItemDeleted.add(this.notifyUpdate),this.componentColors.onItemUpdated.add(this.notifyUpdate),this.componentColors.onCleared.add(this.notifyUpdate)}set(t){this.title=t.title;const{components:e,perspective_camera:i,orthogonal_camera:s,clipping_planes:n}=t;if(e){const{selection:t,visibility:i,coloring:s}=e;if(t){this.selectionComponents.clear();for(const{ifc_guid:e}of t)e&&this.selectionComponents.add(e)}if(i){const{default_visibility:t,exceptions:e,view_setup_hints:s}=i;if(void 0!==t&&(this.defaultVisibility=t),e){this.exceptionComponents.clear();for(const{ifc_guid:t}of e)t&&this.exceptionComponents.add(t)}if(s){const{spaces_visible:t,space_boundaries_visible:e,openings_visible:i}=s;void 0!==t&&(this.spacesVisible=t),void 0!==e&&(this.spaceBoundariesVisible=e),void 0!==i&&(this.openingsVisible=i)}}if(s){this.componentColors.clear();for(const t of s){const{color:e,components:i}=t,s=i.map(t=>t.ifc_guid).filter(t=>null!==t);this.componentColors.set(e,s)}}}if((i||s)&&(this.camera=i??s),n&&this.world){const t=this._components.get(Io);for(const e of n){const{location:i,direction:s}=e,n=new o.Vector3(i.x,i.z,-i.y),r=new o.Vector3(s.x,s.z,-s.y),a=t.createFromNormalAndCoplanarPoint(this.world,r,n);this.clippingPlanes.add(a),t.list.get(a).enabled=!1,t.list.get(a).visible=!1}}this.notifyUpdate()}async go(t){if(!this.world)return;const{camera:e}=this.world;if(!(e instanceof Nr))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:s,applyVisibility:n,clippingsVisibility:r}={transition:!0,applyClippings:!0,applyVisibility:!0,clippingsVisibility:!0,...t};e.projection.set(this.projection);const a=new o.Vector3(this.camera.camera_view_point.x,this.camera.camera_view_point.y,this.camera.camera_view_point.z),l=new o.Vector3(this.camera.camera_direction.x,this.camera.camera_direction.y,this.camera.camera_direction.z);if(a.equals(new o.Vector3)&&l.equals(new o.Vector3))return;const h=this.position,c=this.direction,d={x:h.x+80*c.x,y:h.y+80*c.y,z:h.z+80*c.z},u=[];s&&this.setClippingState(!0),n&&u.push(this.applyVisibility()),this.setClippingVisibility(r),u.push(e.controls.setLookAt(h.x,h.y,h.z,d.x,d.y,d.z,i)),await Promise.all(u)}async updateCamera(t=!0){return new Promise(e=>{if(!this.world)return void e(!1);const{camera:i,renderer:s}=this.world;if(!s)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 n=new o.Vector3;i.controls.getPosition(n);const r=i.three,a=new o.Vector3(0,0,-1).applyEuler(r.rotation),{width:l,height:h}=s.getSize();let c=l/h;Number.isNaN(c)&&(c=1);const d=this._components.get(Oe);n.applyMatrix4(d.baseCoordinationMatrix.clone().invert());const u={aspect_ratio:c,camera_view_point:{x:n.x,y:n.y,z:n.z},camera_direction:{x:a.x,y:a.y,z:a.z},camera_up_vector:{x:0,y:1,z:0}};if(r instanceof o.PerspectiveCamera?this.camera={...u,field_of_view:r.fov}:r instanceof o.OrthographicCamera&&(this.camera={...u,view_to_world_scale:r.top-r.bottom}),t){const t=this._components.get(Mo),n=s.three.domElement;s.three.render(this.world.scene.three,i.three),n.toBlob(async i=>{if(i){const e=await i.arrayBuffer(),s=new Uint8Array(e);t.snapshots.set(this.guid,s)}this.notifyUpdate(),e(!0)})}else this.notifyUpdate(),e(!0)})}takeSnapshot(){return new Promise(t=>{if(!this.world)return void t(!1);const{camera:e,renderer:i}=this.world;if(!i)throw new Error("Viewpoint: the world needs to have a renderer!");const s=this._components.get(Mo),n=i.three.domElement;i.three.render(this.world.scene.three,e.three),n.toBlob(async e=>{if(e){const t=await e.arrayBuffer(),i=new Uint8Array(t);s.snapshots.set(this.guid,i)}this.notifyUpdate(),t(!0)})})}updateClippingPlanes(){this.clippingPlanes.clear();const t=this._components.get(Io);for(const[e,i]of t.list)i.enabled&&this.clippingPlanes.add(e)}async applyVisibility(){const t=this._components.get(ze);t.set(this.defaultVisibility);const e=await this.getExceptionMap();t.set(!this.defaultVisibility,e);const i=await this.getSelectionMap();t.set(!0,i)}async setColorizationState(t){const e=this._components.get(Oe),s=[];if(t)for(const[t,n]of this.componentColors){const r=`#${t}`,a=await e.guidsToModelIdMap(n);for(const[t,n]of Object.entries(a)){const a=e.list.get(t);a&&s.push(a.highlight([...n],{customId:r,color:new o.Color(r),renderedFaces:i.RenderedFaces.ONE,opacity:1,transparent:!1}))}}else for(const[t,i]of this.componentColors){const t=await e.guidsToModelIdMap(i);for(const[i,n]of Object.entries(t)){const t=e.list.get(i);t&&s.push(t.resetHighlight([...n]))}}s.push(e.core.update(!0)),await Promise.all(s)}setClippingState(t){const e=this._components.get(Io);for(const[i,s]of e.list)s.enabled=t&&this.clippingPlanes.has(i)}setClippingVisibility(t){const e=this._components.get(Io);for(const i of this.clippingPlanes){const s=e.list.get(i);s&&(s.visible=t)}}async createComponentTags(t){var e;const i=this._components.get(Oe);let s="";if(this._components.get(Yr).config.includeSelectionTag){const n="selection"===t?await this.getSelectionMap():await this.getExceptionMap();for(const t in n){const r=i.list.get(t);if(!r)continue;const o=n[t];for(const t of o){const i=r.getItem(t),n=await i.getGuid();if(!n)continue;const o=null==(e=await i.getAttributes())?void 0:e.getValue("Tag");let a=null;o&&(a=`AuthoringToolId="${o}"`),s+=`\n<Component IfcGuid="${n}" ${a??""} />`}}}else s=[...this.selectionComponents].map(t=>`<Component IfcGuid="${t}" />`).join("\n");return s}createColorTags(){let t="";for(const[e,i]of this.componentColors.entries()){t+=`<Color Color="${e}">\n${i.map(t=>`\n<Component IfcGuid="${t}" />`).join("\n")}\n</Color>`}return 0!==t.length?`<Coloring>\n${t}\n</Coloring>`:"<Coloring />"}toJSON(){const t=this._components.get(Io),e={guid:this.guid,components:{selection:[...this.selectionComponents].map(t=>({ifc_guid:t,authoring_tool_id:null})),coloring:[...this.componentColors].map(([t,e])=>({color:t,components:e.map(t=>({ifc_guid:t,authoring_tool_id:null}))})),visibility:{default_visibility:this.defaultVisibility,exceptions:[...this.exceptionComponents].map(t=>({ifc_guid:t,authoring_tool_id:null})),view_setup_hints:{spaces_visible:this.spacesVisible,space_boundaries_visible:this.spaceBoundariesVisible,openings_visible:this.openingsVisible}}},clipping_planes:[...this.clippingPlanes].map(e=>{const i=t.list.get(e);if(!i)return null;const s=i._controls.worldPosition??i.origin,{normal:n}=i;return{location:{x:s.x,y:-s.z,z:s.y},direction:{x:n.x,y:-n.z,z:n.y}}}).filter(t=>null!==t)};"field_of_view"in this.camera?e.perspective_camera=this.camera:e.orthogonal_camera=this.camera;const i=this._components.get(Mo),s=i.snapshots.get(this.snapshot);if(s){const t=s.toString(),n=btoa(t),r=i.getSnapshotExtension(this.snapshot);e.snapshot={snapshot_type:r,snapshot_data:n}}return e}async serialize(t=this._managerVersion){const e=this._components.get(Oe),i=this.position;i.applyMatrix4(e.baseCoordinationMatrix.clone().invert());const s=this.direction;s.normalize();const n=(new o.Matrix4).makeRotationX(Math.PI/2),r=s.clone().applyMatrix4(n);r.normalize();const a=`<CameraViewPoint>\n <X>${i.x}</X>\n <Y>${-i.z}</Y>\n <Z>${i.y}</Z>\n </CameraViewPoint>`,l=`<CameraDirection>\n <X>${s.x}</X>\n <Y>${-s.z}</Y>\n <Z>${s.y}</Z>\n </CameraDirection>`,h=`<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 d="";"view_to_world_scale"in this.camera?d=`<OrthogonalCamera>\n ${a}\n ${l}\n ${h}\n ${c}\n <ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>\n </OrthogonalCamera>`:"field_of_view"in this.camera&&(d=`<PerspectiveCamera>\n ${a}\n ${l}\n ${h}\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"===t?u:""}\n ${0!==p.length?`<Selection>${p}</Selection>`:""}\n <Visibility DefaultVisibility="${this.defaultVisibility}">\n ${"3"===t?u:""}\n ${0!==f.length?`<Exceptions>${f}</Exceptions>`:""}\n </Visibility>\n ${m}\n </Components>\n ${d}\n </VisualizationInfo>`}}class Do extends Te{constructor(){super(...arguments),e(this,"_config",{overwriteColors:{value:!1,type:"Boolean"}})}get overwriteColors(){return this._config.overwriteColors.value}set overwriteColors(t){this._config.overwriteColors.value=t}}const zo=class t extends V{constructor(i){super(i),e(this,"enabled",!0),e(this,"world",null),e(this,"list",new s),e(this,"snapshots",new s),e(this,"isSetup",!1),e(this,"onSetup",new L),e(this,"config",new Do(this,this.components,"Viewpoints",t.uuid)),e(this,"onDisposed",new L),i.add(t.uuid,this)}create(t){const e=new ko(this.components,t);return e.world=this.world,t||this.list.set(e.guid,e),e}getSnapshotExtension(t){let e="jpeg";const i=this.snapshots.get(t);if(!i)return e;const s=i.subarray(0,4);let n="";for(let t=0;t<s.length;t++)n+=s[t].toString(16);return n.startsWith("89504e47")&&(e="png"),n.startsWith("ffd8ffe")&&(e="jpeg"),e}setup(){}dispose(){this.list.dispose(),this.onDisposed.trigger(),this.onDisposed.reset()}};e(zo,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");let Mo=zo;class Bo{constructor(t,i){e(this,"_components"),e(this,"_cameraOffset",10),e(this,"_planeHelper"),e(this,"_farPlaneHelper"),e(this,"_cameraHelper"),e(this,"onStateChanged",new L),e(this,"onUpdated",new L),e(this,"onDisposed",new L),e(this,"camera"),e(this,"plane",new o.Plane),e(this,"farPlane",new o.Plane),e(this,"id",G.create()),e(this,"_open",!1),e(this,"_range",Uo.defaultRange),e(this,"_world",null),e(this,"_helpersVisible",!1),e(this,"_planesEnabled",!1),this._components=t,this.camera=new Nr(this._components);const{threeOrtho:s}=this.camera;if((null==i?void 0:i.id)&&(this.id=i.id),(null==i?void 0:i.normal)&&(null==i?void 0:i.point)){const{normal:t,point:e}=i;this.plane.setFromNormalAndCoplanarPoint(t,e)}this._cameraHelper=new o.CameraHelper(s),this._planeHelper=new o.PlaneHelper(this.plane,50),this._farPlaneHelper=new o.PlaneHelper(this.farPlane,50),this.farPlaneHelperColor=new o.Color("blue"),this.update()}get _planeNormalOpposite(){return this.plane.normal.clone().negate()}get _planePosition(){return this.plane.normal.clone().multiplyScalar(-this.plane.constant)}get _cameraPosition(){return this._planePosition.addScaledVector(this._planeNormalOpposite,this._cameraOffset)}set open(t){this._open=t,this.onStateChanged.trigger(["open"])}get open(){return this._open}set planeHelperColor(t){!Array.isArray(this._planeHelper.material)&&"color"in this._planeHelper.material&&this._planeHelper.material.color instanceof o.Color&&(this._planeHelper.material.color=t)}set farPlaneHelperColor(t){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof o.Color&&(this._farPlaneHelper.material.color=t)}set range(t){this._range=t,this.update()}get range(){return this._range}set distance(t){this.plane.constant=t,this.update()}get distance(){return this.plane.constant}set world(t){this._world=t,this.camera.currentWorld=t,t&&(this.camera.projection.set("Orthographic"),this.camera.set("Plan"),this.camera.controls.dollySpeed=6,this.camera.controls.restThreshold=.005,this.update())}get world(){return this._world}set helpersVisible(t){if(!t)return this._helpersVisible=t,this._planeHelper.removeFromParent(),this._farPlaneHelper.removeFromParent(),void this._cameraHelper.removeFromParent();this.world&&(this._helpersVisible=t,this.world.scene.three.add(this._planeHelper,this._farPlaneHelper))}get helpersVisible(){return this._helpersVisible}set planesEnabled(t){const{world:e}=this;if(!e)return;const{renderer:i}=e;i&&(i.setPlane(t,this.plane),i.setPlane(t,this.farPlane),this._planesEnabled=t)}get planesEnabled(){return this._planesEnabled}dispose(){this.helpersVisible=!1;const t=this._components.get(Y);t.destroy(this._planeHelper),t.destroy(this._farPlaneHelper),t.destroy(this._cameraHelper),this.camera.dispose(),this.onDisposed.trigger()}update(){if(this.world){const t=this._cameraPosition,e=this._planePosition;this.camera.controls.setLookAt(t.x,t.y,t.z,e.x,e.y,e.z,!1)}this.farPlane.normal.copy(this._planeNormalOpposite),this.farPlane.constant=this.range-this.plane.constant,this.onUpdated.trigger()}flip(){this.plane.normal.negate(),this.update()}}const No=class t extends V{constructor(i){super(i),e(this,"list",new s),e(this,"enabled",!0),e(this,"world",null),e(this,"_fragmentsUpdateEvent",()=>{this.components.get(Oe).core.update(!0)}),i.add(t.uuid,this),this.setupEvents()}get hasOpenViews(){return[...this.list.values()].some(t=>t.open)}setupEvents(){this.list.onBeforeDelete.add(({key:t,value:e})=>{e.open&&this.close(t),e.dispose()})}create(t,e,i){const s=new Bo(this.components,{id:null==i?void 0:i.id,normal:t,point:e});return s.world=(null==i?void 0:i.world)??this.world,this.list.set(s.id,s),s}createFromPlane(t,e){const i=new Bo(this.components,{id:null==e?void 0:e.id});return i.plane.copy(t),i.update(),i.world=(null==e?void 0:e.world)??this.world,this.list.set(i.id,i),i}async createFromIfcStoreys(t){const e=[],i=this.components.get(Oe),s=void 0===(null==t?void 0:t.offset)?.25:t.offset;for(const[n,r]of i.list){if(t&&t.modelIds&&!t.modelIds.some(t=>t.test(n)))continue;const i=Object.values(await r.getItemsOfCategories([/BUILDINGSTOREY/])).flat();if(0===i.length)continue;const a=await r.getItemsData(i),[,l]=await r.getCoordinates(),h=new o.Vector3(0,-1,0);for(const i of a){if(!("value"in i.Name)||!("value"in i.Elevation))continue;const{value:n}=i.Name;if((null==t?void 0:t.storeyNames)&&!t.storeyNames.some(t=>t.test(n)))continue;const r=i.Elevation.value+l+s,a=new o.Plane(h,r),c=this.createFromPlane(a,{id:n,world:null==t?void 0:t.world});e.push(c)}}return e}createElevations(t){const e=[],i=this.components.get(Oe),s=void 0!==(null==t?void 0:t.combine)&&t.combine,n=(null==t?void 0:t.namingCallback)??(t=>({front:""+(s?"Front":`${t}: Front`),back:""+(s?"Back":`${t}: Back`),left:""+(s?"Left":`${t}: Left`),right:""+(s?"Right":`${t}: Right`)}));let r=[];for(const[e,s]of i.list)t&&t.modelIds&&!t.modelIds.some(t=>t.test(e))||r.push({id:e,box:s.box});if(s){const t=this.components.get(Be);t.list.clear(),t.list.add(...r.map(t=>t.box));r=[{id:"combined",box:t.get()}]}for(const{id:i,box:s}of r){const{min:r,max:a}=s,l=Math.abs(a.x-r.x),h=Math.abs(a.z-r.z),c=new o.Vector3;s.getCenter(c);const d=new o.Plane(new o.Vector3(0,0,-1),a.z),u=new o.Plane(new o.Vector3(0,0,1),-r.z),p=new o.Plane(new o.Vector3(-1,0,0),a.x),f=new o.Plane(new o.Vector3(1,0,0),-r.x),{front:m,back:g,left:_,right:y}=n(i),w=this.createFromPlane(d,{id:m,world:null==t?void 0:t.world});w.range=h;const v=this.createFromPlane(u,{id:g,world:null==t?void 0:t.world});v.range=h;const b=this.createFromPlane(p,{id:_,world:null==t?void 0:t.world});b.range=l;const x=this.createFromPlane(f,{id:y,world:null==t?void 0:t.world});x.range=l,e.push(w,v,b,x)}return e}open(t){const e=this.list.get(t);if(!e)throw new Error(`Views: the view with id ${t} doesn't exist.`);if(e.open)return;const{world:i}=e;if(!i)throw new Error(`Views: no world found for view with id ${t}.`);const{renderer:s}=i;if(!s)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);for(const[,t]of this.list)t.world===i&&this.close(t.id);s.setPlane(!0,e.plane),s.setPlane(!0,e.farPlane),e.camera.controls.addEventListener("rest",this._fragmentsUpdateEvent),i.camera=e.camera,e.open=!0}close(t){let e;if(e=t?this.list.get(t):[...this.list.values()].find(t=>t.open),t&&!e)throw new Error(`Views: the view with id ${t} doesn't exist.`);if(!e)return;if(!e.open)return;const{world:i}=e;if(!i)throw new Error(`Views: no world found for view with id ${t}.`);const{renderer:s}=i;if(!s)throw new Error(`Views: no renderer found for world with id ${i.uuid}.`);s.setPlane(!1,e.plane),s.setPlane(!1,e.farPlane),e.camera.controls.removeEventListener("rest",this._fragmentsUpdateEvent),i.useDefaultCamera(),e.open=!1}};e(No,"uuid","fb22f1f5-6598-4664-a11d-de8963ae420f"),e(No,"defaultRange",15);let Uo=No;async function Lo(t,e,i,s,n,r,o){const a=t.fenceSync(t.SYNC_GPU_COMMANDS_COMPLETE,0);t.flush(),await function(t,e,i,s){return new Promise((n,r)=>{!function o(){const a=t.clientWaitSync(e,i,0);a!==t.WAIT_FAILED?a!==t.TIMEOUT_EXPIRED?n():setTimeout(o,s):r()}()})}(t,a,0,10),t.deleteSync(a),t.bindBuffer(e,i),t.getBufferSubData(e,s,n,r,o),t.bindBuffer(e,null)}class Ro{constructor(t,i){if(e(this,"onDisposed",new L),e(this,"onDistanceComputed",new L),e(this,"excludedObjects",new Set),e(this,"enabled",!0),e(this,"renderDebugFrame",!1),e(this,"components"),e(this,"scene",new o.Scene),e(this,"camera",new o.OrthographicCamera(-1,1,1,-1,0,1)),e(this,"depthMaterial"),e(this,"world"),e(this,"worker"),e(this,"_width",512),e(this,"_height",512),e(this,"_postQuad"),e(this,"tempRT"),e(this,"resultRT"),e(this,"bufferSize"),e(this,"_buffer"),e(this,"_isWorkerBusy",!1),e(this,"compute",async()=>{if(!this.enabled||this.world.isDisposing)return;if(this._isWorkerBusy)return;this._isWorkerBusy=!0,this.world.camera.three.updateMatrix();const t=this.world.renderer.three;t.setRenderTarget(this.tempRT);const e="visibilityBeforeDistanceCheck";for(const t of this.excludedObjects)t.userData[e]=t.visible,t.visible=!1;t.render(this.world.scene.three,this.world.camera.three);for(const t of this.excludedObjects)void 0!==t.userData[e]&&(t.visible=t.userData[e]);this.depthMaterial.uniforms.tDiffuse.value=this.tempRT.texture,this.depthMaterial.uniforms.tDepth.value=this.tempRT.depthTexture,t.setRenderTarget(this.resultRT),t.render(this.scene,this.camera);const i=t.getContext();try{await async function(t,e,i,s,n,r,o,a){const l=t.createBuffer();return t.bindBuffer(t.PIXEL_PACK_BUFFER,l),t.bufferData(t.PIXEL_PACK_BUFFER,a.byteLength,t.STREAM_READ),t.readPixels(e,i,s,n,r,o,0),t.bindBuffer(t.PIXEL_PACK_BUFFER,null),await Lo(t,t.PIXEL_PACK_BUFFER,l,0,a),t.deleteBuffer(l),a}(i,0,0,this._width,this._height,i.RGBA,i.UNSIGNED_BYTE,this._buffer)}catch(e){return t.setRenderTarget(null),void(this._isWorkerBusy=!1)}t.setRenderTarget(null),this.renderDebugFrame&&t.render(this.scene,this.camera),this.worker.postMessage({buffer:this._buffer})}),e(this,"handleWorkerMessage",t=>{if(!this.enabled||this.world.isDisposing)return;const e=t.data.colors;let i=Number.MAX_VALUE;for(const t of e)0!==t&&t<i&&(i=t);const s=this.world.camera.three||o.OrthographicCamera,n=-1*(i/255-1)*(s.far-s.near),r=Math.min(n,s.far);this.onDistanceComputed.trigger(r),this._isWorkerBusy=!1}),!i.renderer)throw new Error("The given world must have a renderer!");this.components=t,this.world=i;const s=i.camera.three;this.tempRT=new o.WebGLRenderTarget(this._width,this._height),this.bufferSize=this._width*this._height*4,this._buffer=new Uint8Array(this.bufferSize),this.tempRT.texture.minFilter=o.NearestFilter,this.tempRT.texture.magFilter=o.NearestFilter,this.tempRT.stencilBuffer=!1,this.tempRT.samples=0,this.tempRT.depthTexture=new o.DepthTexture(this._width,this._height),this.tempRT.depthTexture.format=o.DepthFormat,this.tempRT.depthTexture.type=o.UnsignedShortType,this.resultRT=new o.WebGLRenderTarget(this._width,this._height),this.depthMaterial=new o.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n ",fragmentShader:"\n#include <packing>\n\nvarying vec2 vUv;\nuniform sampler2D tDiffuse;\nuniform sampler2D tDepth;\nuniform float cameraNear;\nuniform float cameraFar;\n\n\nfloat readDepth( sampler2D depthSampler, vec2 coord ) {\n float fragCoordZ = texture2D( depthSampler, coord ).x;\n float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );\n return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );\n}\n\nvoid main() {\n //vec3 diffuse = texture2D( tDiffuse, vUv ).rgb;\n float depth = readDepth( tDepth, vUv );\n\n gl_FragColor.rgb = 1.0 - vec3( depth );\n gl_FragColor.a = 1.0;\n}\n ",uniforms:{cameraNear:{value:s.near},cameraFar:{value:s.far},tDiffuse:{value:null},tDepth:{value:null}}});const n=new o.PlaneGeometry(2,2);this._postQuad=new o.Mesh(n,this.depthMaterial),this.scene.add(this._postQuad);const r=new Blob(['\n addEventListener("message", (event) => {\n const { buffer } = event.data;\n const colors = new Set();\n for (let i = 0; i < buffer.length; i += 4) {\n const r = buffer[i];\n colors.add(r);\n }\n postMessage({ colors });\n });\n '],{type:"application/javascript"});this.worker=new Worker(URL.createObjectURL(r)),this.worker.addEventListener("message",this.handleWorkerMessage)}dispose(){this.enabled=!1,this.onDistanceComputed.reset(),this.worker.terminate(),this.tempRT.dispose(),this.resultRT.dispose();const t=[...this.scene.children];this.excludedObjects.clear();for(const e of t)e.removeFromParent();this._postQuad.geometry.dispose(),this._postQuad.removeFromParent(),this._buffer=null,this.onDisposed.reset()}}class Fo extends Qe{constructor(){super(...arguments),e(this,"_distanceRenderer"),e(this,"autoBias",!0),e(this,"_defaultShadowConfig",{cascade:1,resolution:512}),e(this,"_lightsWithShadow",new Map),e(this,"_isComputingShadows",!1),e(this,"_shadowsEnabled",!0),e(this,"_bias",0),e(this,"recomputeShadows",t=>{if(!this._shadowsEnabled)return;this.autoBias&&(this.bias=-.005);if(t*=1.5,!this.currentWorld)throw new Error("A world needs to be assigned to the scene before computing shadows!");if(!this._lightsWithShadow.size)throw new Error("No shadows found!");const e=this.currentWorld.camera.three;if(!(e instanceof o.PerspectiveCamera||e instanceof o.OrthographicCamera))throw new Error("Invalid camera type!");const i=new o.Vector3;e.getWorldDirection(i);let s=t;const n=new o.Vector3;n.copy(this.config.directionalLight.position),n.normalize();for(const[t,r]of this._lightsWithShadow){const a=this.directionalLights.get(r);if(!a)throw new Error("Light not found.");const l=new o.Vector3;l.copy(i);const h=t===this._lightsWithShadow.size-1,c=h?s/2:2*s/3;l.multiplyScalar(c),l.add(e.position);const d=s-c,u=new o.Vector3;u.copy(n),u.multiplyScalar(d),a.target.position.copy(l),a.position.copy(l),a.position.add(u),a.shadow.camera.right=d,a.shadow.camera.left=-d,a.shadow.camera.top=d,a.shadow.camera.bottom=-d,a.shadow.camera.far=2*d,a.shadow.camera.updateProjectionMatrix(),a.shadow.camera.updateMatrix(),h||(s/=3)}this._isComputingShadows=!1})}get bias(){return this._bias}set bias(t){this._bias=t;for(const[,e]of this._lightsWithShadow){const i=this.directionalLights.get(e);i&&(i.shadow.bias=t)}}get shadowsEnabled(){return this._shadowsEnabled}set shadowsEnabled(t){this._shadowsEnabled=t;for(const[,e]of this.directionalLights)e.castShadow=t}get distanceRenderer(){if(!this._distanceRenderer)throw new Error("You must set up this component before accessing the distance renderer!");return this._distanceRenderer}setup(t){super.setup(t);const e={...this._defaultConfig,...this._defaultShadowConfig,...t};if(e.cascade<=0)throw new Error("Config.shadows.cascade must be a natural number greater than 0!");if(e.cascade>1)throw new Error("Multiple shadows not supported yet!");if(!this.currentWorld)throw new Error("A world needs to be assigned to the scene before setting it up!");for(const[,t]of this.directionalLights)t.target.removeFromParent(),t.removeFromParent(),t.dispose();this.directionalLights.clear(),this._distanceRenderer||(this._distanceRenderer=new Ro(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let t=0;t<e.cascade;t++){const i=new o.DirectionalLight;i.intensity=this.config.directionalLight.intensity,i.color=this.config.directionalLight.color,i.position.copy(this.config.directionalLight.position),i.shadow.mapSize.width=e.resolution,i.shadow.mapSize.height=e.resolution,this.three.add(i,i.target),this.directionalLights.set(i.uuid,i),this._lightsWithShadow.set(t,i.uuid),i.castShadow=!0,i.shadow.bias=this._bias}}dispose(){super.dispose(),this._distanceRenderer&&this._distanceRenderer.dispose(),this._lightsWithShadow.clear()}async updateShadows(){!this._isComputingShadows&&this._shadowsEnabled&&(this._isComputingShadows=!0,await this.distanceRenderer.compute())}}class Vo{constructor(t){e(this,"cardinality","required"),e(this,"instructions"),e(this,"evalRequirement",(t,e,i,s)=>{const n={parameter:i,currentValue:t,requiredValue:e,pass:!1};s&&this.addCheckResult(n,s);let r=!1;if("simple"===e.type&&(r=t===e.parameter),"enumeration"===e.type&&(r=e.parameter.includes(t)),"pattern"===e.type){r=new RegExp(e.parameter).test(String(t))}if("length"===e.type){const{min:i,length:s,max:n}=e.parameter;void 0!==s&&(r=String(t).length===s),void 0!==i&&(r=String(t).length>=i),void 0!==n&&(r=String(t).length<=n)}if("bounds"===e.type&&"number"==typeof t){const{min:i,minInclusive:s,max:n,maxInclusive:o}=e.parameter;let a=!0,l=!0;void 0!==i&&(a=s?t>=i:t>i),void 0!==n&&(l=o?t<=n:t<n),r=a&&l}return"prohibited"===this.cardinality&&(r=!r),"optional"===this.cardinality&&(r=!0),n.pass=r,n.pass}),this._components=t}addCheckResult(t,e){const i=e.findIndex(({parameter:e})=>e===t.parameter);-1!==i?e[i]=t:e.push(t)}getItemChecks(t,e,s,n){if(!("value"in s._localId)||"number"!=typeof s._localId.value)return null;let r=t.get(e);r||(r=new i.DataMap,t.set(e,r));let o=r.get(s._localId.value);if(o&&n&&!o.pass)return null;if(!o){const t=[];o={guid:Array.isArray(s._guid)?void 0:s._guid.value,pass:!1,checks:t},Object.defineProperty(o,"pass",{get:()=>t.every(({pass:t})=>t)}),r.set(s._localId.value,o)}const a=[],l={facetType:this.facetType,cardinality:this.cardinality,checks:a,pass:!1};return Object.defineProperty(l,"pass",{get:()=>a.every(({pass:t})=>t)}),o.checks.push(l),l.checks}}const jo=(t,e)=>{let i="";if(!e)return i;if("simple"===e.type&&(i=`<simpleValue>${e.parameter}</simpleValue>`),"enumeration"===e.type){i=`<xs:restriction base="xs:string">\n ${e.parameter.map(t=>`<xs:enumeration value="${t}" />`).join("\n")}\n </xs:restriction>`}if("pattern"===e.type){i=`<xs:restriction base="xs:string">\n <xs:pattern value="${e.parameter}" />\n </xs:restriction>`}if("bounds"===e.type){const{min:t,minInclusive:s,max:n,maxInclusive:r}=e.parameter;let o="";void 0!==t&&(o=`<xs:min${s?"Inclusive":"Exclusive"} value="${t}">`);let a="";void 0!==n&&(a=`<xs:max${r?"Inclusive":"Exclusive"} value="${n}">`),i=`<xs:restriction base="xs:double">\n ${o}\n ${a}\n </xs:restriction>`}if("length"===e.type){const{length:t,min:s,max:n}=e.parameter;let r="";void 0!==t&&void 0===s&&void 0===n&&(r=`<xs:length value="${t}" />`);let o="";void 0!==s&&void 0===t&&(o=`<xs:minLength value="${s}" />`);let a="";void 0!==n&&void 0===t&&(a=`<xs:maxLength value="${n}" />`),i=`<xs:restriction base="xs:string">\n ${r}\n ${o}\n ${a}\n </xs:restriction>`}return`<${t[0].toLowerCase()+t.slice(1)}>\n ${i}\n </${t[0].toLowerCase()+t.slice(1)}>`};class Zo extends Vo{constructor(t,i){super(t),e(this,"facetType","Attribute"),e(this,"name"),e(this,"value"),this.name=i}serialize(t){const e=jo("Name",this.name),i=jo("Value",this.value);let s="";return"requirement"===t&&(s+=`cardinality="${this.cardinality}"`,s+=this.instructions?`instructions="${this.instructions}"`:""),`<attribute ${s}>\n ${e}\n ${i}\n</attribute>`}async getEntities(){}async test(t,e,i={skipIfFails:!0}){const s=this._components.get(Oe);for(const[n,r]of Object.entries(t)){const t=s.list.get(n);if(!t)continue;const o=await t.getItemsData([...r]);for(const t of o){const s=this.getItemChecks(e,n,t,i.skipIfFails);if(!s)continue;const r=Object.keys(t).filter(e=>{const i=this.evalRequirement(e,this.name,"Name");if(!i)return!1;const s=t[e];return!!Array.isArray(s)||(null===s||null===s.value?"optional"===this.cardinality||"prohibited"===this.cardinality:(!Array.isArray(s.value)||0!==s.value.length)&&(("string"!=typeof s.value||""!==s.value.trim())&&i))}),o=r.length>0;if(s.push({parameter:"Name",currentValue:o?r[0]:null,requiredValue:this.name,pass:"prohibited"===this.cardinality?!o:o}),this.value)if(r[0]){const e=t[r[0]];if(Array.isArray(e))s.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality});else{Array.isArray(e.value)?s.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality}):this.evalRequirement(e.value,this.value,"Value",s)}}else s.push({parameter:"Value",currentValue:null,requiredValue:this.value,pass:"prohibited"===this.cardinality})}}}}class Ho extends Vo{constructor(t,i){super(t),e(this,"facetType","Classification"),e(this,"system"),e(this,"value"),e(this,"uri"),this.system=i}serialize(t){const e=jo("System",this.system),i=jo("Value",this.value);let s="";return"requirement"===t&&(s+=`cardinality="${this.cardinality}"`,s+=this.uri?`uri=${this.uri}`:"",s+=this.instructions?`instructions="${this.instructions}"`:""),`<classification ${s}>\n ${e}\n ${i}\n</classification>`}async getEntities(t,e){}async test(t,e){}}class $o extends Vo{constructor(t,i){super(t),e(this,"facetType","Entity"),e(this,"name"),e(this,"predefinedType"),this.name=i}serialize(t){const e=jo("Name",this.name),i=jo("Name",this.predefinedType);let s="";return"requirement"===t&&(s+=`cardinality="${this.cardinality}"`,s+=this.instructions?`instructions="${this.instructions}"`:""),`<entity ${s}>\n ${e}\n ${i}\n</entity>`}async getEntities(t,e){const i=this._components.get(Oe),s=new Map;for(const[e,n]of i.list){if(!t.find(t=>t.test(e)))continue;const i=await n.getCategories();for(const t of i){if(!await this.evalName(t))continue;let i=s.get(e);i||(i=[],s.set(e,i)),i.push(t)}}const n={};if(await Promise.all(Array.from(s.entries()).map(async([t,e])=>{const s=i.list.get(t);if(!s)return;const r=e.map(t=>new RegExp(`^${t}$`)),o=await s.getItemsOfCategories(r),a=Object.values(o).flat();n[t]=new Set(a)})),this.predefinedType)for(const[t,s]of Object.entries(n)){const n=i.list.get(t);if(!n)continue;const r=await n.getItemsData([...s]);for(const i of r){if(!("value"in i._localId))continue;await this.evalPredefinedType(t,i)&&we.append(e,t,i._localId.value)}}else we.add(e,n)}async test(t,e,i){const s=this._components.get(Oe);for(const[n,r]of Object.entries(t)){const t=s.list.get(n);if(!t)continue;const o=await t.getItemsData([...r]);for(const t of o){if(!("value"in t._category))continue;const s=this.getItemChecks(e,n,t,i.skipIfFails);s&&(await this.evalName(t._category.value,s),await this.evalPredefinedType(n,t,s))}}}async evalName(t,e){return this.evalRequirement(t,this.name,"Name",e)}async evalPredefinedType(t,e,i){if(!this.predefinedType)return null;if(!("value"in e.PredefinedType))return null;const s="string"==typeof this.predefinedType.parameter&&"USERDEFINED"===this.predefinedType.parameter;let n=e.PredefinedType.value;if("USERDEFINED"===n&&!s){const t=Object.keys(e).find(t=>/^((?!Predefined).)*Type$/.test(t));if(t){const i=e[t];"value"in i&&(n=i.value)}else n="USERDEFINED"}if(!n){const i=this._components.get(Oe).list.get(t);if(i&&"value"in e._localId){const[t]=await i.getItemsData([e._localId.value],{relations:{IsTypedBy:{attributes:!0,relations:!1}}});if(Array.isArray(t.IsTypedBy)){const e=t.IsTypedBy[0];if(e&&"value"in e.PredefinedType&&(n=e.PredefinedType.value,"USERDEFINED"===n&&!s)){const t=Object.keys(e).find(t=>/^((?!Predefined).)*Type$/.test(t));if(t){const i=e[t];"value"in i&&(n=i.value)}else n="USERDEFINED"}}}}return this.evalRequirement(n,this.predefinedType,"PredefinedType",i)}}class Yo extends Vo{constructor(t,i,s){super(t),e(this,"facetType","Property"),e(this,"propertySet"),e(this,"baseName"),e(this,"value"),e(this,"dataType"),e(this,"uri"),e(this,"_unsupportedTypes",["IFCCOMPLEXPROPERTY","IFCPHYSICALCOMPLEXQUANTITY"]),this.propertySet=i,this.baseName=s}serialize(t){const e=jo("PropertySet",this.propertySet),i=jo("BaseName",this.baseName),s=jo("Value",this.value),n=this.dataType?`dataType=${this.dataType}`:"";let r="";return"requirement"===t&&(r+=`cardinality="${this.cardinality}"`,r+=this.uri?`uri=${this.uri}`:"",r+=this.instructions?`instructions="${this.instructions}"`:""),`<property ${n} ${r}>\n ${e}\n ${i}\n ${s}\n</property>`}async getEntities(t,e){const i=this._components.get(Oe);for(const[s,n]of i.list){if(!t.find(t=>t.test(s)))continue;const i=await n.getItemsOfCategories([/PROPERTYSET/,/ELEMENTQUANTITY/]),r=Object.values(i).flat();if(0===r.length)continue;const o=await n.getItemsData(r,{relations:{HasProperties:{attributes:!0,relations:!1},DefinesOcurrence:{attributes:!0,relations:!1}}});for(const t of o){if(!("value"in t._localId&&"value"in t._category&&"value"in t.Name&&Array.isArray(t.DefinesOcurrence)))continue;if(!this.evalRequirement(t.Name.value,this.propertySet,"PropertySet"))continue;let i;if("IFCPROPERTYSET"===t._category.value&&(i="HasProperties"),"IFCELEMENTQUANTITY"===t._category.value&&(i="Quantities"),!i)continue;const n=t[i];if(Array.isArray(n))for(const i of n){const n=Object.keys(i),r=n.find(t=>/Name/.test(t));if(!r||!("value"in i[r]))continue;const o=i[r];if(!("value"in o))continue;if(!this.evalRequirement(o.value,this.baseName,"BaseName"))continue;if(this.value){const t=n.find(t=>/Value/.test(t));if(!t)continue;const e=i[t];if(!("value"in e))continue;if(!this.evalRequirement(e.value,this.value,"Value"))continue}const a=t.DefinesOcurrence.map(t=>"value"in t._localId&&"number"==typeof t._localId.value?t._localId.value:null).filter(t=>null!==t);we.append(e,s,...a)}}}}async test(t,e,i={skipIfFails:!0}){const s=this._components.get(Oe);for(const[n,r]of Object.entries(t)){const t=s.list.get(n);if(!t)continue;const o=await t.getItemsData([...r],{relations:{IsDefinedBy:{attributes:!0,relations:!0},IsTypedBy:{attributes:!0,relations:!1},HasPropertySets:{attributes:!0,relations:!0},DefinesOcurrence:{attributes:!1,relations:!1}}});for(const t of o){const s=this.getItemChecks(e,n,t,i.skipIfFails);if(!s)continue;const r=(await this.getPsets(t)).filter(t=>{if(!("value"in t.Name))return!1;return!!this.evalRequirement(t.Name.value,this.propertySet,"PropertySet")&&(s.push({currentValue:t.Name.value,parameter:"PropertySet",pass:!0,requiredValue:this.propertySet}),!0)});if(0!==r.length)for(const t of r){const e=this.getPropertyListName(t);if(!e)continue;const i=t[e];if(!Array.isArray(i)){s.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName});continue}const n=i.filter(t=>{if(!("value"in t._category)||!("value"in t.Name))return!1;if(this._unsupportedTypes.includes(t._category.value))return!1;return!!this.evalRequirement(t.Name.value,this.baseName,"BaseName")&&(s.push({currentValue:t.Name.value,parameter:"BaseName",pass:!0,requiredValue:this.baseName}),!0)});if(0!==n.length)for(const t of n)this.evalValue(t,s),this.evalDataType(t,s),this.evalURI();else s.push({currentValue:null,parameter:"BaseName",pass:!1,requiredValue:this.baseName})}else s.push({currentValue:null,parameter:"PropertySet",pass:!1,requiredValue:this.propertySet})}}}getPropertyListName(t){let e;return"value"in t._category?("IFCPROPERTYSET"===t._category.value&&(e="HasProperties"),"IFCELEMENTQUANTITY"===t._category.value&&(e="Quantities"),e):e}getValueKey(t){return Object.keys(t).find(t=>/Value/.test(t)||/Values/.test(t))}getTypePsets(t){if(!Array.isArray(t.IsTypedBy))return[];const[e]=t.IsTypedBy;return e&&Array.isArray(e.HasPropertySets)?e.HasPropertySets:[]}async getPsets(t){const e=this.getTypePsets(t);if(!Array.isArray(t.IsDefinedBy))return e;const i=[];for(const s of t.IsDefinedBy){if(!("value"in s.Name))continue;const t=s.Name.value,n=this.getPropertyListName(s);if(!t||!n)continue;const r=e.find(e=>"value"in e.Name&&e.Name.value===t);if(r&&Array.isArray(r.HasProperties)&&Array.isArray(s.HasProperties))for(const t of r.HasProperties){if(!("value"in t.Name))continue;const e=t.Name.value;s.HasProperties.find(t=>"value"in t.Name&&t.Name.value===e)||s.HasProperties.push(t)}i.push(s)}return i}evalValue(t,e){const i=this.getValueKey(t),s=t[i];if(!("value"in s))return!1;if(this.value){if(!i)return null==e||e.push({parameter:"Value",currentValue:null,pass:!1,requiredValue:this.value}),!1;const t=structuredClone(this.value);"IFCLABEL"===s.type&&"simple"===t.type&&(t.parameter=String(t.parameter));return this.evalRequirement(s.value,t,"Value",e)}return!i||("string"!=typeof s.value||""!==s.value.trim()||(null==e||e.push({parameter:"Value",currentValue:"",pass:!1,requiredValue:this.value}),!1))}evalDataType(t,e){if(!this.dataType)return!0;const i=this.getValueKey(t);if(!i||!("value"in t[i]))return null==e||e.push({parameter:"DataType",currentValue:null,pass:!1,requiredValue:this.dataType}),!1;const s=t[i];return this.evalRequirement(s.type??null,{type:"simple",parameter:this.dataType},"DataType",e)}evalURI(){return!0}}class Wo extends Vo{constructor(){super(...arguments),e(this,"_ifcMaterialEntities",[/^IFCMATERIALLAYERSETUSAGE$/,/^IFCMATERIALCONSTITUENTSET$/,/^IFCMATERIAL$/,/^IFCMATERIALLIST$/]),e(this,"facetType","Material"),e(this,"value"),e(this,"uri")}serialize(t){if(!this.value||!this.uri)return"<material />";const e=jo("Value",this.value);let i="";return"requirement"===t&&(i+=`cardinality="${this.cardinality}"`,i+=this.uri?`uri=${this.uri}`:"",i+=this.instructions?`instructions="${this.instructions}"`:""),`<material ${i}>\n ${e}\n</material>`}async getEntities(t,e){const i=this._components.get(Oe);for(const[s,n]of i.list){if(!t.find(t=>t.test(s)))continue;const i=await n.getItemsOfCategories(this._ifcMaterialEntities),r=Object.values(i).flat();if(0===r.length)continue;const o=await n.getItemsData(r,{relations:{AssociatedTo:{attributes:!0,relations:!1},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const t of o){if(!("value"in t._localId&&"value"in t._category&&Array.isArray(t.AssociatedTo)))continue;if(!this.hasValidMaterial(t))continue;const i=t.AssociatedTo.map(t=>"value"in t._localId&&t._localId.value?t._localId.value:null).filter(t=>null!==t);we.append(e,s,...i)}}}async test(t,e,i={skipIfFails:!0}){const s=this._components.get(Oe);for(const[n,r]of Object.entries(t)){const t=s.list.get(n);if(!t)continue;const o=await t.getItemsData([[...r][0]],{relations:{AssociatedTo:{attributes:!1,relations:!1},HasAssociations:{attributes:!0,relations:!0},MaterialConstituents:{attributes:!0,relations:!0},ForLayerSet:{attributes:!0,relations:!0},MaterialLayers:{attributes:!0,relations:!0},Materials:{attributes:!0,relations:!1}}});for(const t of o){const s=this.getItemChecks(e,n,t,i.skipIfFails);if(s)if(Array.isArray(t.HasAssociations))for(const e of t.HasAssociations){if(!this._ifcMaterialEntities.some(t=>"value"in e._category&&t.test(e._category.value)))continue;if(this.hasValidMaterial(e,s))break}else s.push({parameter:null,currentValue:null,requiredValue:this.value,pass:!1})}}}hasValidMaterial(t,e){let i=!1;if("value"in t._category&&"IFCMATERIAL"===t._category.value){this.evalValue(t,e)&&(i=!0)}else for(const[s,n]of Object.entries(t))if(["ForLayerSet","MaterialLayers","Material","MaterialConstituents","Materials"].includes(s)&&Array.isArray(n))for(const t of n){if("value"in t._category&&"IFCMATERIAL"===t._category.value){if(this.evalValue(t,e)){i=!0;break}}else{if(this.hasValidMaterial(t)){i=!0;break}}}return i}evalValue(t,e){if(!this.value)return null==e||e.push({parameter:null,currentValue:t.Name&&"value"in t.Name?t.Name.value:null,pass:!0}),!0;if(!("value"in t._category)||"IFCMATERIAL"!==t._category.value)return null;let i=!1;return t.Name&&"value"in t.Name&&(i=this.evalRequirement(t.Name.value,this.value,"Value",e)),i||(t.Category&&"value"in t.Category&&(i=this.evalRequirement(t.Category.value,this.value,"Value",e)),i)}}class Xo extends Vo{constructor(t,i){super(t),e(this,"facetType","PartOf"),e(this,"_entityFacet"),e(this,"_entity"),e(this,"relation"),e(this,"cardinality","required"),this._entity=i,this._entityFacet=new $o(t,i.name),this._entityFacet.predefinedType=i.predefinedType}set entity(t){this._entity=t;const{name:e,predefinedType:i}=t;this._entityFacet=new $o(this._components,e),this._entityFacet.predefinedType=i}get entity(){return this._entity}serialize(){return""}async getEntities(t,e){}async test(t){}}class qo{constructor(t,s,n){e(this,"name"),e(this,"ifcVersion",new Set),e(this,"identifier",G.create()),e(this,"description"),e(this,"instructions"),e(this,"requirementsDescription"),e(this,"applicability",new i.DataSet),e(this,"requirements",new i.DataSet),e(this,"components"),this.components=t,this.name=s;for(const t of n)this.ifcVersion.add(t)}set(t){const e=t,i=this;for(const s in t){if("identifier"===s)continue;const t=e[s];s in this&&(i[s]=t)}return this.components.get(na).list.set(this.identifier,this),this}async test(t,e={skipIfFails:!0}){const s=new i.DataMap;if(0===this.requirements.size)return s;const n={},r=[];for(const e of this.applicability)r.push(e.getEntities(t,n));await Promise.all(r);const o=[];for(const t of this.requirements)o.push(t.test(n,s,e));return await Promise.all(o),s}serialize(){const t=`name="${this.name}"`,e=this.identifier?`identifier="${this.identifier}"`:"",i=this.description?`description="${this.description}"`:"",s=this.instructions?`instructions="${this.instructions}"`:"";return`<specification ifcVersion="${[...this.ifcVersion].join(" ")}" ${t} ${e} ${i} ${s}>\n <applicability minOccurs="1" maxOccurs="unbounded">\n ${[...this.applicability].map(t=>t.serialize("applicability")).join("\n")}\n </applicability>\n <requirements>\n ${[...this.requirements].map(t=>t.serialize("requirement")).join("\n")}\n </requirements>\n </specification>`}}const Go=t=>{if(!t)return;const e={};if("simpleValue"in t&&(e.type="simple",e.parameter=t.simpleValue),"restriction"in t){const i=t.restriction,s=Object.keys(i);if("pattern"in i&&(e.type="pattern",e.parameter=i.pattern.value),"enumeration"in i){e.type="enumeration";const t=i.enumeration.map(({value:t})=>i.base.includes("string")?String(t):i.base.includes("integer")||i.base.includes("double")?Number(t):t);e.parameter=t}if(s.some(t=>["minInclusive","minExclusive","maxInclusive","maxExclusive"].includes(t))){e.type="bounds";const t={},n=s.find(t=>t.includes("min")),r=s.find(t=>t.includes("max"));n&&(t.minInclusive="minInclusive"===n,t.min=i[n].value),r&&(t.maxInclusive="maxInclusive"===r,t.max=i[r].value),e.parameter=t}if(s.some(t=>["minLength","length","maxLength"].includes(t))){e.type="length";const t={};void 0!==i.length&&(t.length=i.length.value),void 0!==i.minLength&&(t.min=i.minLength.value),void 0!==i.maxLength&&(t.max=i.maxLength.value),e.parameter=t}}return void 0!==e.parameter?e:void 0},Qo=(t,e)=>{const i=[];for(const s of e){const e=s.name,n=Go(e);if(!n)continue;const r=new $o(t,n);s.cardinality&&(r.cardinality=s.cardinality),r.predefinedType=Go(s.predefinedType),r.instructions=s.instructions,i.push(r)}return i},Ko=(t,e)=>{const i=[];for(const s of e){const e=s.name,n=Go(e);if(!n)continue;const r=new Zo(t,n);s.cardinality&&(r.cardinality=s.cardinality),r.value=Go(s.value),r.instructions=s.instructions,i.push(r)}return i},Jo=(t,e)=>{const i=[];for(const s of e){const e=new Wo(t);s.cardinality&&(e.cardinality=s.cardinality);const n=Go(s.value);"enumeration"===(null==n?void 0:n.type)&&Array.isArray(n.parameter)&&(n.parameter=n.parameter.map(String)),e.value=n,e.uri=s.uri,e.instructions=s.instructions,i.push(e)}return i},ta=(t,e)=>{const i=[];for(const s of e){const e=s.propertySet,n=s.baseName,r=Go(e),o=Go(n);if(!o||!r)continue;const a=new Yo(t,r,o);s.cardinality&&(a.cardinality=s.cardinality);const l=Go(s.value);a.value=l,a.dataType=s.dataType,a.uri=s.uri,a.instructions=s.instructions,i.push(a)}return i},ea=(t,e)=>{const i=[];for(const s of e){const e=s.system,n=Go(e);if(!n)continue;const r=new Ho(t,n);s.cardinality&&(r.cardinality=s.cardinality);const o=Go(s.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=s.uri,r.instructions=s.instructions,i.push(r)}return i},ia=(t,e)=>{const i=[];for(const s of e){const e=Go(s.entity.name);if(!e)continue;const n=Go(s.entity.predefinedType),r=new Xo(t,{name:e,predefinedType:n});r.relation=s.relation,s.cardinality&&(r.cardinality=s.cardinality),r.instructions=s.instructions,i.push(r)}return i},sa=class t extends V{constructor(i){super(i),e(this,"enabled",!0),e(this,"IDSInfo"),e(this,"list",new s),i.add(t.uuid,this)}getModelIdMap(t){const e={},i={};for(const[s,n]of t){const t=[...n].filter(([,t])=>t.pass).map(([t])=>t);we.append(e,s,...t);const r=[...n].filter(([,t])=>!t.pass).map(([t])=>t);we.append(i,s,...r)}return{pass:e,fail:i}}create(t,e,i){const s=new qo(this.components,t,e);return i&&(s.identifier=i),this.list.set(s.identifier,s),s}load(e){const i=[],s=t.xmlParser.parse(e).ids,{specifications:n,info:r}=s;if(this.IDSInfo={...r},n&&n.specification){const t=Array.isArray(n.specification)?n.specification:[n.specification];for(const e of t){const{name:t,ifcVersion:s,description:n,instructions:r,identifier:o}=e;if(!t||!s)continue;const a=[],l=[],{applicability:h,requirements:c}=e;if(h){const{maxOccurs:t,...e}=h,i=Array.isArray(e)?e:[e];for(const t of i)for(const e in t){const i=Array.isArray(t[e])?t[e]:[t[e]];if("entity"===e){const t=Qo(this.components,i);a.push(...t)}if("attribute"===e){const t=Ko(this.components,i);a.push(...t)}if("material"===e){const t=Jo(this.components,i);a.push(...t)}if("classification"===e){const t=ea(this.components,i);a.push(...t)}if("property"===e){const t=ta(this.components,i);a.push(...t)}if("partOf"===e){const t=ia(this.components,i);a.push(...t)}}}let d;if(c){const{maxOccurs:t,...e}=c;d=c.description;const i=Array.isArray(e)?e:[e];for(const t of i)for(const e in t){const i=Array.isArray(t[e])?t[e]:[t[e]];if("entity"===e){const t=Qo(this.components,i);l.push(...t)}if("attribute"===e){const t=Ko(this.components,i);l.push(...t)}if("material"===e){const t=Jo(this.components,i);l.push(...t)}if("classification"===e){const t=ea(this.components,i);l.push(...t)}if("property"===e){const t=ta(this.components,i);l.push(...t)}if("partOf"===e){const t=ia(this.components,i);l.push(...t)}}}const u=this.create(t,s.split(/\s+/),o);u.description=n,u.instructions=r,u.requirementsDescription=d,u.applicability.add(...a),u.requirements.add(...l),i.push(u)}}return i}export(t,e=this.list.values()){const i=e??this.list;return`<ids xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://standards.buildingsmart.org/IDS http://standards.buildingsmart.org/IDS/1.0/ids.xsd" xmlns:ids="http://standards.buildingsmart.org/IDS">\n \x3c!-- Made with That Open Engine ${kr.release} (https://github.com/thatopen/engine_components) --\x3e\n <info>\n <title>${t.title}</title>\n ${t.copyright?`<copyright>${t.copyright}</copyright>`:""}\n ${t.version?`<version>${t.version}</version>`:""}\n ${t.description?`<description>${t.description}</description>`:""}\n ${t.author?`<author>${t.author}</author>`:""}\n ${t.date?`<date>${t.date.toISOString().split("T")[0]}</date>`:""}\n ${t.purpose?`<purpose>${t.purpose}</purpose>`:""}\n ${t.milestone?`<milestone>${t.milestone}</milestone>`:""}\n </info>\n <specifications>\n ${[...i].map(t=>t.serialize()).join("\n")}\n </specifications>\n</ids>`}};e(sa,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c"),e(sa,"xmlParser",new ge.XMLParser({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 na=sa;const ra=class t extends V{constructor(i){super(i),e(this,"enabled",!0),i.add(t.uuid,this)}static distanceFromPointToLine(t,e,i,s=!1){const n=new o.Line3,r=new o.Vector3;return n.set(e,i),n.closestPointToPoint(t,s,r),r.distanceTo(t)}round(t){const e=1e3;t.x=Math.trunc(t.x*e)/e,t.y=Math.trunc(t.y*e)/e,t.z=Math.trunc(t.z*e)/e}async getVolumeFromFragments(t){return console.warn("getVolumeFromFragments is deprecated. Use getItemsVolume instead."),this.getItemsVolume(t)}async getItemsVolume(t){let e=0;const i=this.components.get(Oe);for(const[s,n]of Object.entries(t)){const t=i.list.get(s);t&&(e+=await t.getItemsVolume([...n]))}return e}static convertUnits(t,e,i,s=2){const n={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(!n[e]||!n[i])throw new Error("Invalid units provided for conversion.");if(!Number.isInteger(s)||s<0||s>5)throw new Error("Precision must be an integer between 0 and 5.");const r=t*(n[e]/n[i]),o=10**s;return Math.round(r*o)/o}};e(ra,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");let oa=ra;export{R as AsyncEvent,Yr as BCFTopics,Hr as BCFTopicsConfigManager,F as Base,Z as BaseCamera,H as BaseRenderer,W as BaseScene,j as BaseWorldItem,Be as BoundingBoxer,Fe as Classifier,Io as Clipper,Fr as Comment,V as Component,kr as Components,Ce as ConfigManager,Te as Configurator,be as ControlsUtils,ve as DataMap,X as DataSet,Y as Disposer,L as Event,xe as EventManager,Ve as FastModelPicker,Ze as FastModelPickers,Ne as FinderQuery,Dr as FirstPersonMode,Oe as FragmentsManager,is as Grids,ze as Hider,Zo as IDSAttribute,Ho as IDSClassification,$o as IDSEntity,Vo as IDSFacet,Wo as IDSMaterial,Xo as IDSPartOf,Yo as IDSProperty,qo as IDSSpecification,na as IDSSpecifications,Pe as IfcFragmentSettings,ke as IfcLoader,Le as ItemsFinder,oa as MeasurementUtils,we as ModelIdMapUtils,Se as Mouse,zr as OrbitMode,Nr as OrthoPerspectiveCamera,Mr as PlanMode,Br as ProjectionManager,Ye as Raycasters,Ke as RendererMode,Fo as ShadowedScene,Gi as SimpleCamera,ts as SimpleGrid,Ji as SimpleGridConfigManager,Ao as SimplePlane,He as SimpleRaycaster,Je as SimpleRenderer,Qe as SimpleScene,Ge as SimpleSceneConfigManager,We as SimpleWorld,jr as Topic,G as UUID,ye as VertexPicker,Bo as View,ko as Viewpoint,Mo as Viewpoints,Uo as Views,Ki as Worlds,_e as XML,Zr as extensionsImporter};
27
+ */const Rz=Nz(Cz.exports=function e(t,s,i){function r(o,a){if(!s[o]){if(!t[o]){if(!a&&Ez)return Ez(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=Ez,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)),b=p.comment,x=n.transformTo("string",u(b)),_=n.transformTo("string",a.utf8encode(b)),w=y.length!==p.name.length,v=_.length!==b.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(x),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(x.length,2)+"\0\0\0\0"+i(I,4)+i(r,4)+g+T+x}}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 b=new u(e,y,a);this.files[e]=b}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 b={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=b},{"./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!==Az?Az:"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,b=286,x=30,_=19,w=2*b+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 z(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function V(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=V(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=V(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*x+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*b+1),D(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new r.Buf16(2*b+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,z(r,p),0!==r.strstart&&(z(r,e.adler>>>16),z(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)):(z(r,e.adler>>>16),z(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,b,x,_,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,b=(1<<s.distbits)-1;e:do{m<15&&(p+=M[i++]<<m,m+=8,p+=M[i++]<<m,m+=8),x=f[p&y];t:for(;;){if(p>>>=_=x>>>24,m-=_,0==(_=x>>>16&255))A[n++]=65535&x;else{if(!(16&_)){if(!(64&_)){x=f[(65535&x)+(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&x,(_&=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),x=g[p&b];s:for(;;){if(p>>>=_=x>>>24,m-=_,!(16&(_=x>>>16&255))){if(!(64&_)){x=g[(65535&x)+(p&(1<<_)-1)];continue s}e.msg="invalid distance code",s.mode=30;break e}if(v=65535&x,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 b(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,y(e)):c}function x(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,b(e))):c}function _(e,t){var s,i;return e?(i=new g,(e.state=i).window=null,(s=x(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=b,s.inflateReset2=x,s.inflateResetKeep=y,s.inflateInit=function(e){return _(e,15)},s.inflateInit2=_,s.inflate=function(e,t){var s,p,m,g,y,b,x,_,w,v,T,A,N,E,C,R,P,B,I,D,L,F,O,z,V=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,x=e.avail_out,g=e.next_in,p=e.input,b=e.avail_in,_=s.hold,w=s.bits,v=b,T=x,F=u;e:for(;;)switch(s.mode){case d:if(0===s.wrap){s.mode=13;break}for(;w<16;){if(0===b)break e;b--,_+=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===b)break e;b--,_+=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===b)break e;b--,_+=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===b)break e;b--,_+=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===b)break e;b--,_+=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&&(b<(A=s.length)&&(A=b),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)),b-=A,g+=A,s.length-=A),s.length))break e;s.length=0,s.mode=7;case 7:if(2048&s.flags){if(0===b)break e;for(A=0;L=p[g+A++],s.head&&L&&s.length<65536&&(s.head.name+=String.fromCharCode(L)),L&&A<b;);if(512&s.flags&&(s.check=n(s.check,p,A,g)),b-=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===b)break e;for(A=0;L=p[g+A++],s.head&&L&&s.length<65536&&(s.head.comment+=String.fromCharCode(L)),L&&A<b;);if(512&s.flags&&(s.check=n(s.check,p,A,g)),b-=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===b)break e;b--,_+=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===b)break e;b--,_+=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=x,e.next_in=g,e.avail_in=b,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===b)break e;b--,_+=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===b)break e;b--,_+=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(b<A&&(A=b),x<A&&(A=x),0===A)break e;i.arraySet(m,p,g,A,y),b-=A,g+=A,x-=A,y+=A,s.length-=A;break}s.mode=12;break;case 17:for(;w<14;){if(0===b)break e;b--,_+=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===b)break e;b--,_+=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=(V=s.lencode[_&(1<<s.lenbits)-1])>>>16&255,P=65535&V,!((C=V>>>24)<=w);){if(0===b)break e;b--,_+=p[g++]<<w,w+=8}if(P<16)_>>>=C,w-=C,s.lens[s.have++]=P;else{if(16===P){for(z=C+2;w<z;){if(0===b)break e;b--,_+=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(z=C+3;w<z;){if(0===b)break e;b--,_+=p[g++]<<w,w+=8}w-=C,L=0,A=3+(7&(_>>>=C)),_>>>=3,w-=3}else{for(z=C+7;w<z;){if(0===b)break e;b--,_+=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<=b&&258<=x){e.next_out=y,e.avail_out=x,e.next_in=g,e.avail_in=b,s.hold=_,s.bits=w,o(e,T),y=e.next_out,m=e.output,x=e.avail_out,g=e.next_in,p=e.input,b=e.avail_in,_=s.hold,w=s.bits,12===s.mode&&(s.back=-1);break}for(s.back=0;R=(V=s.lencode[_&(1<<s.lenbits)-1])>>>16&255,P=65535&V,!((C=V>>>24)<=w);){if(0===b)break e;b--,_+=p[g++]<<w,w+=8}if(R&&!(240&R)){for(B=C,I=R,D=P;R=(V=s.lencode[D+((_&(1<<B+I)-1)>>B)])>>>16&255,P=65535&V,!(B+(C=V>>>24)<=w);){if(0===b)break e;b--,_+=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(z=s.extra;w<z;){if(0===b)break e;b--,_+=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=(V=s.distcode[_&(1<<s.distbits)-1])>>>16&255,P=65535&V,!((C=V>>>24)<=w);){if(0===b)break e;b--,_+=p[g++]<<w,w+=8}if(!(240&R)){for(B=C,I=R,D=P;R=(V=s.distcode[D+((_&(1<<B+I)-1)>>B)])>>>16&255,P=65535&V,!(B+(C=V>>>24)<=w);){if(0===b)break e;b--,_+=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(z=s.extra;w<z;){if(0===b)break e;b--,_+=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===x)break e;if(A=T-x,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(x<A&&(A=x),x-=A,s.length-=A;m[y++]=E[N++],--A;);0===s.length&&(s.mode=21);break;case 26:if(0===x)break e;m[y++]=s.length,x--,s.mode=21;break;case 27:if(s.wrap){for(;w<32;){if(0===b)break e;b--,_|=p[g++]<<w,w+=8}if(T-=x,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=x,(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===b)break e;b--,_+=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=x,e.next_in=g,e.avail_in=b,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,b,x,_,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,z=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(b=0===e?(I=O=c,19):1===e?(I=r,D-=257,O=n,z-=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(x=T-C,w=c[S]<b?(_=0,c[S]):c[S]>b?(_=O[z+c[S]],I[D+c[S]]):(_=96,0),p=1<<T-C,M=m=1<<E;h[y+(B>>C)+(m-=p)]=x<<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,b=16,x=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 z(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 V(e,t,s){z(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?V(e,r,t):(V(e,(n=E[r])+h+1,t),0!==(o=w[n])&&z(e,r-=C[n],o),V(e,n=F(--i),s),0!==(o=v[n])&&z(e,i-=I[n],o)),a<e.last_lit;);V(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*b]++):a<=10?e.bl_tree[2*x]++: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(;V(e,r,e.bl_tree),0!=--a;);else 0!==r?(r!==n&&(V(e,r,e.bl_tree),a--),V(e,b,e.bl_tree),z(e,a-3,2)):a<=10?(V(e,x,e.bl_tree),z(e,a-3,3)):(V(e,_,e.bl_tree),z(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;z(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?(z(e,2+(i?1:0),3),H(e,M,A)):(z(e,4+(i?1:0),3),function(e,t,s,i){var r;for(z(e,t-257,5),z(e,s-1,5),z(e,i-4,4),r=0;r<i;r++)z(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;z(e,2,3),V(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!==Az?Az:"undefined"!=typeof self?self:"undefined"!=typeof window?window:{})},{}]},{},[10])(10));class Pz{constructor(e,s){t(this,"date",new Date),t(this,"author"),t(this,"guid",ce.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(Oz);this.author=i.config.author}set comment(e){var t;const s=this._components.get(Oz);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 Bz=class e{constructor(s){t(this,"guid",ce.create()),t(this,"title",e.default.title),t(this,"creationDate",new Date),t(this,"creationAuthor",""),t(this,"viewpoints",new n),t(this,"relatedTopics",new n),t(this,"comments",new i),t(this,"documentReferences",new n),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=s;const r=s.get(Oz);this.creationAuthor=r.config.author,this.relatedTopics.guard=e=>e!==this.guid}set type(e){const t=this._components.get(Oz),{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(Oz),{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(Oz);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(Oz);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(Oz);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(Oz),{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(Oz).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(Oz).list.set(this.guid,this),this}createComment(e,t){const s=new Pz(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(Oz).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(SV);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(Oz);for(const i of this.documentReferences){const r=s.documents.get(i);if(!r)continue;let n={$Guid:ce.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(SV);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(Oz);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:ce.create(),description:t.description,url:t.url}):s.document_references.push({guid:ce.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 ${At.builder.build(r)}`}};t(Bz,"default",{title:"BCF Topic",type:"Issue",status:"Active"});let Iz=Bz;const Dz=(e,t)=>{if(""===t.trim())return;const s=Oz.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 Lz extends Bt{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 Fz=class e extends se{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 Lz(this,this.components,"BCF Topics",e.uuid)),t(this,"list",new i),t(this,"documents",new i),t(this,"onSetup",new J),t(this,"isSetup",!1),t(this,"onBCFImported",new J),t(this,"onDisposed",new J)}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 Iz(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(SV);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 Rz;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(SV);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&&(Pz||n)))return null;const o=new Pz(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:a,updateExtensionsOnImport:l}=this.config,h=new Rz;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(l&&p){const e=await p.async("string");Dz(this,e)}const m=[],f=this.components.get(SV),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:a,ClippingPlanes:l,Components:h,OrthogonalCamera:u,PerspectiveCamera:d}=r;if(a&&(n.guid=a),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 o.Vector3(Number(t.X),Number(t.Z),Number(-t.Y)),a=new o.Vector3(Number(s.X),Number(s.Z),Number(-s.Y)),l={camera_view_point:{x:i.x,y:i.y,z:i.z},camera_direction:{x:a.x,y:a.y,z:a.z},aspect_ratio:"AspectRatio"in e?e.AspectRatio:1,camera_up_vector:{x:0,y:0,z:0}};"ViewToWorldScale"in e&&(n.orthogonal_camera={...l,view_to_world_scale:e.ViewToWorldScale}),"FieldOfView"in e&&(n.perspective_camera={...l,field_of_view:e.FieldOfView})}if(l){const e=(Array.isArray(l.ClippingPlane)?l.ClippingPlane:[l.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 wV(this.components,n);m.push(p)}const y={},b=[],x=u.filter(e=>e.name.endsWith(".bcf"));for(const t of x){const s=await t.async("string"),n=e.xmlParser.parse(s).Markup,o=n.Topic,{Guid:l,TopicType:h,TopicStatus:d,Title:p,CreationDate:m,CreationAuthor:g}=o;if(a&&!(l&&h&&d&&p&&m&&g))continue;const x=new Iz(this.components);x.guid=l??x.guid;const _=this.getMarkupRelatedTopics(n,c);y[x.guid]=new Set(_),x.type=h??x.type,x.status=d??x.status,x.title=p??x.title,x.creationDate=m?new Date(m):x.creationDate,x.creationAuthor=g??x.creationAuthor,x.serverAssignedId=o.ServerAssignedId,x.priority=o.Priority,x.index=o.Index,x.modifiedDate=o.ModifiedDate?new Date(o.ModifiedDate):void 0,x.modifiedAuthor=o.ModifiedAuthor,x.dueDate=o.DueDate?new Date(o.DueDate):void 0,x.assignedTo=o.AssignedTo,x.description=o.Description,x.stage=o.Stage;const w=this.getMarkupLabels(n,c);for(const e of w)x.labels.add(e);const v=this.getMarkupComments(n,c);for(const e of v)x.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;x.viewpoints.add(t.guid);const s=`${x.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=At.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}),x.documentReferences.add(s)}if(i){const e=this.documents.add({type:"external",url:i,description:t});x.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})}x.documentReferences.add(e)}}this.list.set(x.guid,x),b.push(x)}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(b),{viewpoints:m,topics:b}}};t(Fz,"uuid","de977976-e4f6-4e4f-a01a-204727839802"),t(Fz,"xmlParser",new mt({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 Oz=Fz;const zz=new V,Vz=new u,kz=new u,Uz=new z,Gz={X:new u(1,0,0),Y:new u(0,1,0),Z:new u(0,0,1)},jz={type:"change"},$z={type:"mouseDown",mode:null},Wz={type:"mouseUp",mode:null},Hz={type:"objectChange"};class qz extends O{constructor(e,t=null){super(void 0,t);const s=new mV(this);this._root=s;const i=new fV;this._gizmo=i,s.add(i);const r=new gV;this._plane=r,s.add(r);const n=this;function o(e,t){let s=t;Object.defineProperty(n,e,{get:function(){return void 0!==s?s:t},set:function(t){s!==t&&(s=t,r[e]=t,i[e]=t,n.dispatchEvent({type:e+"-changed",value:t}),n.dispatchEvent(jz))}}),n[e]=t,r[e]=t,i[e]=t}o("camera",e),o("object",void 0),o("enabled",!0),o("axis",null),o("mode","translate"),o("translationSnap",null),o("rotationSnap",null),o("scaleSnap",null),o("space","world"),o("size",1),o("dragging",!1),o("showX",!0),o("showY",!0),o("showZ",!0),o("minX",-1/0),o("maxX",1/0),o("minY",-1/0),o("maxY",1/0),o("minZ",-1/0),o("maxZ",1/0);const a=new u,l=new u,h=new z,c=new z,d=new u,p=new z,m=new u,f=new u,g=new u,y=new u;o("worldPosition",a),o("worldPositionStart",l),o("worldQuaternion",h),o("worldQuaternionStart",c),o("cameraPosition",d),o("cameraQuaternion",p),o("pointStart",m),o("pointEnd",f),o("rotationAxis",g),o("rotationAngle",0),o("eye",y),this._offset=new u,this._startNorm=new u,this._endNorm=new u,this._cameraScale=new u,this._parentPosition=new u,this._parentQuaternion=new z,this._parentQuaternionInv=new z,this._parentScale=new u,this._worldScaleStart=new u,this._worldQuaternionInv=new z,this._worldScale=new u,this._positionStart=new u,this._quaternionStart=new z,this._scaleStart=new u,this._getPointer=Xz.bind(this),this._onPointerDown=Zz.bind(this),this._onPointerHover=Yz.bind(this),this._onPointerMove=Qz.bind(this),this._onPointerUp=Kz.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&&zz.setFromCamera(e,this.camera);const t=Jz(this._gizmo.picker[this.mode],zz);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&&zz.setFromCamera(e,this.camera);const t=Jz(this._plane,zz,!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,$z.mode=this.mode,this.dispatchEvent($z)}}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&&zz.setFromCamera(e,this.camera);const n=Jz(this._plane,zz,!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(Uz.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(Vz.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(Vz.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),kz.set(e,e,e)}else Vz.copy(this.pointStart),kz.copy(this.pointEnd),Vz.applyQuaternion(this._worldQuaternionInv),kz.applyQuaternion(this._worldQuaternionInv),kz.divide(Vz),-1===t.search("X")&&(kz.x=1),-1===t.search("Y")&&(kz.y=1),-1===t.search("Z")&&(kz.z=1);i.scale.copy(this._scaleStart).multiply(kz),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(Vz.setFromMatrixPosition(this.camera.matrixWorld));let s=!1;"XYZE"===t?(this.rotationAxis.copy(this._offset).cross(this.eye).normalize(),this.rotationAngle=this._offset.dot(Vz.copy(this.rotationAxis).cross(this.eye))*e):"X"!==t&&"Y"!==t&&"Z"!==t||(this.rotationAxis.copy(Gz[t]),Vz.copy(Gz[t]),"local"===r&&Vz.applyQuaternion(this.worldQuaternion),Vz.cross(this.eye),0===Vz.length()?s=!0:this.rotationAngle=this._offset.dot(Vz.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(Uz.setFromAxisAngle(this.rotationAxis,this.rotationAngle)).normalize()):(this.rotationAxis.applyQuaternion(this._parentQuaternionInv),i.quaternion.copy(Uz.setFromAxisAngle(this.rotationAxis,this.rotationAngle)),i.quaternion.multiply(this._quaternionStart).normalize())}this.dispatchEvent(jz),this.dispatchEvent(Hz)}}pointerUp(e){null!==e&&0!==e.button||(this.dragging&&null!==this.axis&&(Wz.mode=this.mode,this.dispatchEvent(Wz)),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(jz),this.dispatchEvent(Hz),this.pointStart.copy(this.pointEnd))}getRaycaster(){return zz}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 Xz(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 Yz(e){if(this.enabled)switch(e.pointerType){case"mouse":case"pen":this.pointerHover(this._getPointer(e))}}function Zz(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 Qz(e){this.enabled&&this.pointerMove(this._getPointer(e))}function Kz(e){this.enabled&&(this.domElement.releasePointerCapture(e.pointerId),this.domElement.removeEventListener("pointermove",this._onPointerMove),this.pointerUp(this._getPointer(e)))}function Jz(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 eV=new Y,tV=new u(0,1,0),sV=new u(0,0,0),iV=new l,rV=new z,nV=new z,oV=new u,aV=new l,lV=new u(1,0,0),hV=new u(0,1,0),uV=new u(0,0,1),cV=new u,dV=new u,pV=new u;class mV extends k{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 fV extends k{constructor(){super(),this.isTransformControlsGizmo=!0,this.type="TransformControlsGizmo";const e=new U({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),t=new G({depthTest:!1,depthWrite:!1,fog:!1,toneMapped:!1,transparent:!0}),s=e.clone();s.opacity=.15;const i=t.clone();i.opacity=.5;const r=e.clone();r.color.setHex(16711680);const n=e.clone();n.color.setHex(65280);const o=e.clone();o.color.setHex(255);const a=e.clone();a.color.setHex(16711680),a.opacity=.5;const l=e.clone();l.color.setHex(65280),l.opacity=.5;const h=e.clone();h.color.setHex(255),h.opacity=.5;const u=e.clone();u.opacity=.25;const c=e.clone();c.color.setHex(16776960),c.opacity=.25;const d=e.clone();d.color.setHex(16776960);const p=e.clone();p.color.setHex(7895160),this.materialLib={xAxis:r,yAxis:n,zAxis:o,active:d,xAxisTransparent:a,yAxisTransparent:l,zAxisTransparent:h,activeTransparent:c};const m=new j(0,.04,.1,12);m.translate(0,.05,0);const f=new $(.08,.08,.08);f.translate(0,.04,0);const g=new F;g.setAttribute("position",new W([0,0,0,1,0,0],3));const y=new j(.0075,.0075,.5,3);function b(e,t){const s=new q(e,.0075,3,64,t*Math.PI*2);return s.rotateY(Math.PI/2),s.rotateX(Math.PI/2),s}y.translate(0,.25,0);const x={X:[[new _(m,r),[.5,0,0],[0,0,-Math.PI/2]],[new _(m,r),[-.5,0,0],[0,0,Math.PI/2]],[new _(y,r),[0,0,0],[0,0,-Math.PI/2]]],Y:[[new _(m,n),[0,.5,0]],[new _(m,n),[0,-.5,0],[Math.PI,0,0]],[new _(y,n)]],Z:[[new _(m,o),[0,0,.5],[Math.PI/2,0,0]],[new _(m,o),[0,0,-.5],[-Math.PI/2,0,0]],[new _(y,o),null,[Math.PI/2,0,0]]],XYZ:[[new _(new H(.1,0),u),[0,0,0]]],XY:[[new _(new $(.15,.15,.01),h),[.15,.15,0]]],YZ:[[new _(new $(.15,.15,.01),a),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new _(new $(.15,.15,.01),l),[.15,0,.15],[-Math.PI/2,0,0]]]},w={X:[[new _(new j(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new _(new j(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new _(new j(.2,0,.6,4),s),[0,.3,0]],[new _(new j(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new _(new j(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new _(new j(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XYZ:[[new _(new H(.2,0),s)]],XY:[[new _(new $(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new _(new $(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new _(new $(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]]},v={START:[[new _(new H(.01,2),i),null,null,null,"helper"]],END:[[new _(new H(.01,2),i),null,null,null,"helper"]],DELTA:[[new T(function(){const e=new F;return e.setAttribute("position",new W([0,0,0,1,1,1],3)),e}(),i),null,null,null,"helper"]],X:[[new T(g,i),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new T(g,i),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new T(g,i),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]},S={XYZE:[[new _(b(.5,1),p),null,[0,Math.PI/2,0]]],X:[[new _(b(.5,.5),r)]],Y:[[new _(b(.5,.5),n),null,[0,0,-Math.PI/2]]],Z:[[new _(b(.5,.5),o),null,[0,Math.PI/2,0]]],E:[[new _(b(.75,1),c),null,[0,Math.PI/2,0]]]},M={AXIS:[[new T(g,i),[-1e3,0,0],null,[1e6,1,1],"helper"]]},A={XYZE:[[new _(new X(.25,10,8),s)]],X:[[new _(new q(.5,.1,4,24),s),[0,0,0],[0,-Math.PI/2,-Math.PI/2]]],Y:[[new _(new q(.5,.1,4,24),s),[0,0,0],[Math.PI/2,0,0]]],Z:[[new _(new q(.5,.1,4,24),s),[0,0,0],[0,0,-Math.PI/2]]],E:[[new _(new q(.75,.1,2,24),s)]]},N={X:[[new _(f,r),[.5,0,0],[0,0,-Math.PI/2]],[new _(y,r),[0,0,0],[0,0,-Math.PI/2]],[new _(f,r),[-.5,0,0],[0,0,Math.PI/2]]],Y:[[new _(f,n),[0,.5,0]],[new _(y,n)],[new _(f,n),[0,-.5,0],[0,0,Math.PI]]],Z:[[new _(f,o),[0,0,.5],[Math.PI/2,0,0]],[new _(y,o),[0,0,0],[Math.PI/2,0,0]],[new _(f,o),[0,0,-.5],[-Math.PI/2,0,0]]],XY:[[new _(new $(.15,.15,.01),h),[.15,.15,0]]],YZ:[[new _(new $(.15,.15,.01),a),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new _(new $(.15,.15,.01),l),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new _(new $(.1,.1,.1),u)]]},E={X:[[new _(new j(.2,0,.6,4),s),[.3,0,0],[0,0,-Math.PI/2]],[new _(new j(.2,0,.6,4),s),[-.3,0,0],[0,0,Math.PI/2]]],Y:[[new _(new j(.2,0,.6,4),s),[0,.3,0]],[new _(new j(.2,0,.6,4),s),[0,-.3,0],[0,0,Math.PI]]],Z:[[new _(new j(.2,0,.6,4),s),[0,0,.3],[Math.PI/2,0,0]],[new _(new j(.2,0,.6,4),s),[0,0,-.3],[-Math.PI/2,0,0]]],XY:[[new _(new $(.2,.2,.01),s),[.15,.15,0]]],YZ:[[new _(new $(.2,.2,.01),s),[0,.15,.15],[0,Math.PI/2,0]]],XZ:[[new _(new $(.2,.2,.01),s),[.15,0,.15],[-Math.PI/2,0,0]]],XYZ:[[new _(new $(.2,.2,.2),s),[0,0,0]]]},C={X:[[new T(g,i),[-1e3,0,0],null,[1e6,1,1],"helper"]],Y:[[new T(g,i),[0,-1e3,0],[0,0,Math.PI/2],[1e6,1,1],"helper"]],Z:[[new T(g,i),[0,0,-1e3],[0,-Math.PI/2,0],[1e6,1,1],"helper"]]};function R(e){const t=new k;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=R(x)),this.add(this.gizmo.rotate=R(S)),this.add(this.gizmo.scale=R(N)),this.add(this.picker.translate=R(w)),this.add(this.picker.rotate=R(A)),this.add(this.picker.scale=R(E)),this.add(this.helper.translate=R(v)),this.add(this.helper.rotate=R(M)),this.add(this.helper.scale=R(C)),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:nV;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(tV.copy(lV).applyQuaternion(t).dot(this.eye))>e&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"Y"===i.name&&Math.abs(tV.copy(hV).applyQuaternion(t).dot(this.eye))>e&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"Z"===i.name&&Math.abs(tV.copy(uV).applyQuaternion(t).dot(this.eye))>e&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"XY"===i.name&&Math.abs(tV.copy(uV).applyQuaternion(t).dot(this.eye))<s&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"YZ"===i.name&&Math.abs(tV.copy(lV).applyQuaternion(t).dot(this.eye))<s&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1),"XZ"===i.name&&Math.abs(tV.copy(hV).applyQuaternion(t).dot(this.eye))<s&&(i.scale.set(1e-10,1e-10,1e-10),i.visible=!1)}else"rotate"===this.mode&&(rV.copy(t),tV.copy(this.eye).applyQuaternion(Uz.copy(t).invert()),-1!==i.name.search("E")&&i.quaternion.setFromRotationMatrix(iV.lookAt(this.eye,sV,hV)),"X"===i.name&&(Uz.setFromAxisAngle(lV,Math.atan2(-tV.y,tV.z)),Uz.multiplyQuaternions(rV,Uz),i.quaternion.copy(Uz)),"Y"===i.name&&(Uz.setFromAxisAngle(hV,Math.atan2(tV.x,tV.z)),Uz.multiplyQuaternions(rV,Uz),i.quaternion.copy(Uz)),"Z"===i.name&&(Uz.setFromAxisAngle(uV,Math.atan2(tV.y,tV.x)),Uz.multiplyQuaternions(rV,Uz),i.quaternion.copy(Uz)));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&&(Uz.setFromEuler(eV.set(0,0,0)),i.quaternion.copy(t).multiply(Uz),Math.abs(tV.copy(lV).applyQuaternion(t).dot(this.eye))>.9&&(i.visible=!1)),"Y"===this.axis&&(Uz.setFromEuler(eV.set(0,0,Math.PI/2)),i.quaternion.copy(t).multiply(Uz),Math.abs(tV.copy(hV).applyQuaternion(t).dot(this.eye))>.9&&(i.visible=!1)),"Z"===this.axis&&(Uz.setFromEuler(eV.set(0,Math.PI/2,0)),i.quaternion.copy(t).multiply(Uz),Math.abs(tV.copy(uV).applyQuaternion(t).dot(this.eye))>.9&&(i.visible=!1)),"XYZE"===this.axis&&(Uz.setFromEuler(eV.set(0,Math.PI/2,0)),tV.copy(this.rotationAxis),i.quaternion.setFromRotationMatrix(iV.lookAt(sV,tV,hV)),i.quaternion.multiply(Uz),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),Vz.set(1e-10,1e-10,1e-10).add(this.worldPositionStart).sub(this.worldPosition).multiplyScalar(-1),Vz.applyQuaternion(this.worldQuaternionStart.clone().invert()),i.scale.copy(Vz),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 gV extends _{constructor(){super(new Z(1e5,1e5,2,2),new U({visible:!1,wireframe:!0,side:g,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"),cV.copy(lV).applyQuaternion("local"===t?this.worldQuaternion:nV),dV.copy(hV).applyQuaternion("local"===t?this.worldQuaternion:nV),pV.copy(uV).applyQuaternion("local"===t?this.worldQuaternion:nV),tV.copy(dV),this.mode){case"translate":case"scale":switch(this.axis){case"X":tV.copy(this.eye).cross(cV),oV.copy(cV).cross(tV);break;case"Y":tV.copy(this.eye).cross(dV),oV.copy(dV).cross(tV);break;case"Z":tV.copy(this.eye).cross(pV),oV.copy(pV).cross(tV);break;case"XY":oV.copy(pV);break;case"YZ":oV.copy(cV);break;case"XZ":tV.copy(pV),oV.copy(dV);break;case"XYZ":case"E":oV.set(0,0,0)}break;default:oV.set(0,0,0)}0===oV.length()?this.quaternion.copy(this.cameraQuaternion):(aV.lookAt(Vz.set(0,0,0),oV,tV),this.quaternion.setFromRotationMatrix(aV)),super.updateMatrixWorld(e)}}class yV{constructor(e,s,i,r,n,a=5,l=!0){var h;if(t(this,"onDraggingStarted",new J),t(this,"onDraggingEnded",new J),t(this,"onDisposed",new J),t(this,"normal"),t(this,"origin"),t(this,"three",new o.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 o.Mesh),t(this,"_planeMesh"),t(this,"_controls"),t(this,"_hiddenMaterial",new o.MeshBasicMaterial({visible:!1})),t(this,"_sizeMultiplier",5),t(this,"_autoScale",!0),t(this,"_visibilityBeforeDisabled",!0),t(this,"notifyManager",()=>{const e=this.components.get(_V),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 o.PerspectiveCamera))return;const s=new o.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=a,s.renderer.setPlane(!0,this.three),this._planeMesh=yV.newPlaneMesh(a,n),this._helper=this.newHelper(),this._controls=this.newTransformControls(),this.three.setFromNormalAndCoplanarPoint(r,i),l&&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 o.Vector3(1,0,0),t=new o.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 qz(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 o.CylinderGeometry(.18,.18,1.2),this._arrowBoundBox.material=this._hiddenMaterial,this._arrowBoundBox.rotateX(Math.PI/2),this._arrowBoundBox.updateMatrix(),this._arrowBoundBox.geometry.applyMatrix4(this._arrowBoundBox.matrix)}notifyDraggingChanged(e){e.value?this.onDraggingStarted.trigger():this.onDraggingEnded.trigger()}preventCameraMovement(){this.world.camera.enabled=this._visible}newHelper(){const e=new o.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 o.PlaneGeometry(1),i=new o.Mesh(s,t);return i.scale.set(e,e,e),i}}class bV extends Bt{constructor(){super(...arguments),t(this,"_config",{enabled:{value:!0,type:"Boolean"},visible:{value:!0,type:"Boolean"},color:{value:new o.Color,type:"Color"},opacity:{type:"Number",interpolable:!0,value:1,min:0,max:1},size:{type:"Number",interpolable:!0,value:2,min:0,max:100}})}get enabled(){return this._config.enabled.value}set enabled(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 xV=class e extends se{constructor(i){super(i),t(this,"onSetup",new J),t(this,"onBeforeDrag",new J),t(this,"onAfterDrag",new J),t(this,"onBeforeCreate",new J),t(this,"onBeforeCancel",new J),t(this,"onAfterCancel",new J),t(this,"onBeforeDelete",new J),t(this,"onAfterCreate",new J),t(this,"onAfterDelete",new J),t(this,"onDisposed",new J),t(this,"isSetup",!1),t(this,"orthogonalY",!1),t(this,"toleranceOrthogonalY",.7),t(this,"autoScalePlanes",!0),t(this,"Type",yV),t(this,"list",new s.DataMap),t(this,"config",new bV(this,this.components,"Clipper",e.uuid)),t(this,"_defaultConfig",{color:new o.Color(12255487),opacity:.2,size:2}),t(this,"_material",new o.MeshBasicMaterial({color:12255487,side:o.DoubleSide,transparent:!0,opacity:.2})),t(this,"_size",5),t(this,"_enabled",!1),t(this,"_visible",!0),t(this,"onStateChanged",new J),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(Dt).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(rz).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(rz).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 o.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),a=this.newPlane(e,t.point,n.negate()),l=this.list.get(a);return l.visible=this._visible,l.size=this._size,e.renderer.setPlane(!0,l.three),this.updateMaterialsAndPlanes(),l}getWorldNormal(e,t){const s=e.object;let i=e.object.matrixWorld.clone();if(s instanceof o.InstancedMesh&&void 0!==e.instanceId){const t=new o.Matrix4;s.getMatrixAt(e.instanceId,t),i=t.multiply(i)}const r=(new o.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=ce.create();return this.list.set(r,i),this.onAfterCreate.trigger(i),r}updateMaterialsAndPlanes(){const e=this.components.get(mz);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(xV,"uuid","66290bc5-18c4-4cd1-9379-2e17a0617611");let _V=xV;class wV{constructor(e,i){t(this,"title"),t(this,"guid",ce.create()),t(this,"clippingPlanes",new s.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 s.DataSet),t(this,"selectionComponents",new s.DataSet),t(this,"componentColors",new s.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(SV).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(Lr);return await e.guidsToModelIdMap([...this.selectionComponents])}async getExceptionMap(){const e=this._components.get(Lr);return await e.guidsToModelIdMap([...this.exceptionComponents])}get projection(){return"field_of_view"in this.camera?"Perspective":"Orthographic"}get position(){const e=this._components.get(Lr),{camera_view_point:t}=this.camera,{x:s,y:i,z:r}=t,n=new o.Vector3(s,i,r);return e.applyBaseCoordinateSystem(n,new o.Matrix4),n}set position(e){const t=e.clone(),s=this._components.get(Lr);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 o.Vector3(t,s,i)}set world(e){this._world=e}get world(){return this._world}get _managerVersion(){return this._components.get(Oz).config.version}get topics(){return[...this._components.get(Oz).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(_V);for(const t of r){const{location:s,direction:i}=t,r=new o.Vector3(s.x,s.z,-s.y),n=new o.Vector3(i.x,i.z,-i.y),a=e.createFromNormalAndCoplanarPoint(this.world,n,r);this.clippingPlanes.add(a),e.list.get(a).enabled=!1,e.list.get(a).visible=!1}}this.notifyUpdate()}async go(e){if(!this.world)return;const{camera:t}=this.world;if(!(t instanceof Mz))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 a=new o.Vector3(this.camera.camera_view_point.x,this.camera.camera_view_point.y,this.camera.camera_view_point.z),l=new o.Vector3(this.camera.camera_direction.x,this.camera.camera_direction.y,this.camera.camera_direction.z);if(a.equals(new o.Vector3)&&l.equals(new o.Vector3))return;const 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 o.Vector3;s.controls.getPosition(r);const n=s.three,a=new o.Vector3(0,0,-1).applyEuler(n.rotation),{width:l,height:h}=i.getSize();let u=l/h;Number.isNaN(u)&&(u=1);const c=this._components.get(Lr);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:a.x,y:a.y,z:a.z},camera_up_vector:{x:0,y:1,z:0}};if(n instanceof o.PerspectiveCamera?this.camera={...d,field_of_view:n.fov}:n instanceof o.OrthographicCamera&&(this.camera={...d,view_to_world_scale:n.top-n.bottom}),e){const e=this._components.get(SV),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(SV),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(_V);for(const[t,s]of e.list)s.enabled&&this.clippingPlanes.add(t)}async applyVisibility(){const e=this._components.get(WO);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(Lr),i=[];if(e)for(const[e,r]of this.componentColors){const n=`#${e}`,a=await t.guidsToModelIdMap(r);for(const[e,r]of Object.entries(a)){const a=t.list.get(e);a&&i.push(a.highlight([...r],{customId:n,color:new o.Color(n),renderedFaces:s.RenderedFaces.ONE,opacity:1,transparent:!1}))}}else for(const[e,s]of this.componentColors){const e=await t.guidsToModelIdMap(s);for(const[s,r]of Object.entries(e)){const e=t.list.get(s);e&&i.push(e.resetHighlight([...r]))}}i.push(t.core.update(!0)),await Promise.all(i)}setClippingState(e){const t=this._components.get(_V);for(const[s,i]of t.list)i.enabled=e&&this.clippingPlanes.has(s)}setClippingVisibility(e){const t=this._components.get(_V);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(Lr);let i="";if(this._components.get(Oz).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(_V),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(SV),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(Lr),s=this.position;s.applyMatrix4(t.baseCoordinationMatrix.clone().invert());const i=this.direction;i.normalize();const r=(new o.Matrix4).makeRotationX(Math.PI/2),n=i.clone().applyMatrix4(r);n.normalize();const a=`<CameraViewPoint>\n <X>${s.x}</X>\n <Y>${-s.z}</Y>\n <Z>${s.y}</Z>\n </CameraViewPoint>`,l=`<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 ${a}\n ${l}\n ${h}\n ${u}\n <ViewToWorldScale>${this.camera.view_to_world_scale}</ViewToWorldScale>\n </OrthogonalCamera>`:"field_of_view"in this.camera&&(c=`<PerspectiveCamera>\n ${a}\n ${l}\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 vV extends Bt{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 TV=class e extends se{constructor(s){super(s),t(this,"enabled",!0),t(this,"world",null),t(this,"list",new i),t(this,"snapshots",new i),t(this,"isSetup",!1),t(this,"onSetup",new J),t(this,"config",new vV(this,this.components,"Viewpoints",e.uuid)),t(this,"onDisposed",new J),s.add(e.uuid,this)}create(e){const t=new wV(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(TV,"uuid","ee867824-a796-408d-8aa0-4e5962a83c66");let SV=TV;class MV{constructor(e,s){t(this,"_components"),t(this,"_cameraOffset",10),t(this,"_planeHelper"),t(this,"_farPlaneHelper"),t(this,"_cameraHelper"),t(this,"onStateChanged",new J),t(this,"onUpdated",new J),t(this,"onDisposed",new J),t(this,"camera"),t(this,"plane",new o.Plane),t(this,"farPlane",new o.Plane),t(this,"id",ce.create()),t(this,"_open",!1),t(this,"_range",NV.defaultRange),t(this,"_world",null),t(this,"_helpersVisible",!1),t(this,"_planesEnabled",!1),this._components=e,this.camera=new Mz(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 o.CameraHelper(i),this._planeHelper=new o.PlaneHelper(this.plane,50),this._farPlaneHelper=new o.PlaneHelper(this.farPlane,50),this.farPlaneHelperColor=new o.Color("blue"),this.update()}get _planeNormalOpposite(){return this.plane.normal.clone().negate()}get _planePosition(){return this.plane.normal.clone().multiplyScalar(-this.plane.constant)}get _cameraPosition(){return this._planePosition.addScaledVector(this._planeNormalOpposite,this._cameraOffset)}set open(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 o.Color&&(this._planeHelper.material.color=e)}set farPlaneHelperColor(e){!Array.isArray(this._farPlaneHelper.material)&&"color"in this._farPlaneHelper.material&&this._farPlaneHelper.material.color instanceof o.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(ae);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 AV=class e extends se{constructor(s){super(s),t(this,"list",new i),t(this,"enabled",!0),t(this,"world",null),t(this,"_fragmentsUpdateEvent",()=>{this.components.get(Lr).core.update(!0)}),s.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 MV(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 MV(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(Lr),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 a=await n.getItemsData(s),[,l]=await n.getCoordinates(),h=new o.Vector3(0,-1,0);for(const s of a){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+l+i,a=new o.Plane(h,n),u=this.createFromPlane(a,{id:r,world:null==e?void 0:e.world});t.push(u)}}return t}createElevations(e){const t=[],s=this.components.get(Lr),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(qO);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:a}=i,l=Math.abs(a.x-n.x),h=Math.abs(a.z-n.z),u=new o.Vector3;i.getCenter(u);const c=new o.Plane(new o.Vector3(0,0,-1),a.z),d=new o.Plane(new o.Vector3(0,0,1),-n.z),p=new o.Plane(new o.Vector3(-1,0,0),a.x),m=new o.Plane(new o.Vector3(1,0,0),-n.x),{front:f,back:g,left:y,right:b}=r(s),x=this.createFromPlane(c,{id:f,world:null==e?void 0:e.world});x.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=l;const v=this.createFromPlane(m,{id:b,world:null==e?void 0:e.world});v.range=l,t.push(x,_,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(AV,"uuid","fb22f1f5-6598-4664-a11d-de8963ae420f"),t(AV,"defaultRange",15);let NV=AV;async function EV(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 CV{constructor(e,s){if(t(this,"onDisposed",new J),t(this,"onDistanceComputed",new J),t(this,"excludedObjects",new Set),t(this,"enabled",!0),t(this,"renderDebugFrame",!1),t(this,"components"),t(this,"scene",new o.Scene),t(this,"camera",new o.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 EV(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||o.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 o.WebGLRenderTarget(this._width,this._height),this.bufferSize=this._width*this._height*4,this._buffer=new Uint8Array(this.bufferSize),this.tempRT.texture.minFilter=o.NearestFilter,this.tempRT.texture.magFilter=o.NearestFilter,this.tempRT.stencilBuffer=!1,this.tempRT.samples=0,this.tempRT.depthTexture=new o.DepthTexture(this._width,this._height),this.tempRT.depthTexture.format=o.DepthFormat,this.tempRT.depthTexture.type=o.UnsignedShortType,this.resultRT=new o.WebGLRenderTarget(this._width,this._height),this.depthMaterial=new o.ShaderMaterial({vertexShader:"\nvarying vec2 vUv;\n\nvoid main() {\n vUv = uv;\n gl_Position = projectionMatrix * modelViewMatrix * vec4(position, 1.0);\n}\n ",fragmentShader:"\n#include <packing>\n\nvarying vec2 vUv;\nuniform sampler2D tDiffuse;\nuniform sampler2D tDepth;\nuniform float cameraNear;\nuniform float cameraFar;\n\n\nfloat readDepth( sampler2D depthSampler, vec2 coord ) {\n float fragCoordZ = texture2D( depthSampler, coord ).x;\n float viewZ = perspectiveDepthToViewZ( fragCoordZ, cameraNear, cameraFar );\n return viewZToOrthographicDepth( viewZ, cameraNear, cameraFar );\n}\n\nvoid main() {\n //vec3 diffuse = texture2D( tDiffuse, vUv ).rgb;\n float depth = readDepth( tDepth, vUv );\n\n gl_FragColor.rgb = 1.0 - vec3( depth );\n gl_FragColor.a = 1.0;\n}\n ",uniforms:{cameraNear:{value:i.near},cameraFar:{value:i.far},tDiffuse:{value:null},tDepth:{value:null}}});const r=new o.PlaneGeometry(2,2);this._postQuad=new o.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 RV extends hz{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 o.PerspectiveCamera||t instanceof o.OrthographicCamera))throw new Error("Invalid camera type!");const s=new o.Vector3;t.getWorldDirection(s);let i=e;const r=new o.Vector3;r.copy(this.config.directionalLight.position),r.normalize();for(const[e,n]of this._lightsWithShadow){const a=this.directionalLights.get(n);if(!a)throw new Error("Light not found.");const l=new o.Vector3;l.copy(s);const h=e===this._lightsWithShadow.size-1,u=h?i/2:2*i/3;l.multiplyScalar(u),l.add(t.position);const c=i-u,d=new o.Vector3;d.copy(r),d.multiplyScalar(c),a.target.position.copy(l),a.position.copy(l),a.position.add(d),a.shadow.camera.right=c,a.shadow.camera.left=-c,a.shadow.camera.top=c,a.shadow.camera.bottom=-c,a.shadow.camera.far=2*c,a.shadow.camera.updateProjectionMatrix(),a.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 CV(this.components,this.currentWorld),this._distanceRenderer.onDistanceComputed.add(this.recomputeShadows)),this._lightsWithShadow.clear();for(let e=0;e<t.cascade;e++){const s=new o.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())}}class PV{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,i,r){if(!("value"in i._localId)||"number"!=typeof i._localId.value)return null;let n=e.get(t);n||(n=new s.DataMap,e.set(t,n));let o=n.get(i._localId.value);if(o&&r&&!o.pass)return null;if(!o){const e=[];o={guid:Array.isArray(i._guid)?void 0:i._guid.value,pass:!1,checks:e},Object.defineProperty(o,"pass",{get:()=>e.every(({pass:e})=>e)}),n.set(i._localId.value,o)}const a=[],l={facetType:this.facetType,cardinality:this.cardinality,checks:a,pass:!1};return Object.defineProperty(l,"pass",{get:()=>a.every(({pass:e})=>e)}),o.checks.push(l),l.checks}}const BV=(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 IV extends PV{constructor(e,s){super(e),t(this,"facetType","Attribute"),t(this,"name"),t(this,"value"),this.name=s}serialize(e){const t=BV("Name",this.name),s=BV("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(Lr);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 DV extends PV{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=BV("System",this.system),s=BV("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 LV extends PV{constructor(e,s){super(e),t(this,"facetType","Entity"),t(this,"name"),t(this,"predefinedType"),this.name=s}serialize(e){const t=BV("Name",this.name),s=BV("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(Lr),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)&&Et.append(t,e,s._localId.value)}}else Et.add(t,r)}async test(e,t,s){const i=this._components.get(Lr);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(Lr).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 FV extends PV{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=BV("PropertySet",this.propertySet),s=BV("BaseName",this.baseName),i=BV("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(Lr);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);Et.append(t,i,...a)}}}}async test(e,t,s={skipIfFails:!0}){const i=this._components.get(Lr);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 OV extends PV{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=BV("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(Lr);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);Et.append(t,i,...s)}}}async test(e,t,s={skipIfFails:!0}){const i=this._components.get(Lr);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 zV extends PV{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 LV(e,s.name),this._entityFacet.predefinedType=s.predefinedType}set entity(e){this._entity=e;const{name:t,predefinedType:s}=e;this._entityFacet=new LV(this._components,t),this._entityFacet.predefinedType=s}get entity(){return this._entity}serialize(){return""}async getEntities(e,t){}async test(e){}}class VV{constructor(e,i,r){t(this,"name"),t(this,"ifcVersion",new Set),t(this,"identifier",ce.create()),t(this,"description"),t(this,"instructions"),t(this,"requirementsDescription"),t(this,"applicability",new s.DataSet),t(this,"requirements",new s.DataSet),t(this,"components"),this.components=e,this.name=i;for(const e of r)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(XV).list.set(this.identifier,this),this}async test(e,t={skipIfFails:!0}){const i=new s.DataMap;if(0===this.requirements.size)return i;const r={},n=[];for(const t of this.applicability)n.push(t.getEntities(e,r));await Promise.all(n);const o=[];for(const e of this.requirements)o.push(e.test(r,i,t));return await Promise.all(o),i}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 kV=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},UV=(e,t)=>{const s=[];for(const i of t){const t=i.name,r=kV(t);if(!r)continue;const n=new LV(e,r);i.cardinality&&(n.cardinality=i.cardinality),n.predefinedType=kV(i.predefinedType),n.instructions=i.instructions,s.push(n)}return s},GV=(e,t)=>{const s=[];for(const i of t){const t=i.name,r=kV(t);if(!r)continue;const n=new IV(e,r);i.cardinality&&(n.cardinality=i.cardinality),n.value=kV(i.value),n.instructions=i.instructions,s.push(n)}return s},jV=(e,t)=>{const s=[];for(const i of t){const t=new OV(e);i.cardinality&&(t.cardinality=i.cardinality);const r=kV(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},$V=(e,t)=>{const s=[];for(const i of t){const t=i.propertySet,r=i.baseName,n=kV(t),o=kV(r);if(!o||!n)continue;const a=new FV(e,n,o);i.cardinality&&(a.cardinality=i.cardinality);const l=kV(i.value);a.value=l,a.dataType=i.dataType,a.uri=i.uri,a.instructions=i.instructions,s.push(a)}return s},WV=(e,t)=>{const s=[];for(const i of t){const t=i.system,r=kV(t);if(!r)continue;const n=new DV(e,r);i.cardinality&&(n.cardinality=i.cardinality);const o=kV(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},HV=(e,t)=>{const s=[];for(const i of t){const t=kV(i.entity.name);if(!t)continue;const r=kV(i.entity.predefinedType),n=new zV(e,{name:t,predefinedType:r});n.relation=i.relation,i.cardinality&&(n.cardinality=i.cardinality),n.instructions=i.instructions,s.push(n)}return s},qV=class e extends se{constructor(s){super(s),t(this,"enabled",!0),t(this,"IDSInfo"),t(this,"list",new i),s.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);Et.append(t,i,...e);const n=[...r].filter(([,e])=>!e.pass).map(([e])=>e);Et.append(s,i,...n)}return{pass:t,fail:s}}create(e,t,s){const i=new VV(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=UV(this.components,s);a.push(...e)}if("attribute"===t){const e=GV(this.components,s);a.push(...e)}if("material"===t){const e=jV(this.components,s);a.push(...e)}if("classification"===t){const e=WV(this.components,s);a.push(...e)}if("property"===t){const e=$V(this.components,s);a.push(...e)}if("partOf"===t){const e=HV(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=UV(this.components,s);l.push(...e)}if("attribute"===t){const e=GV(this.components,s);l.push(...e)}if("material"===t){const e=jV(this.components,s);l.push(...e)}if("classification"===t){const e=WV(this.components,s);l.push(...e)}if("property"===t){const e=$V(this.components,s);l.push(...e)}if("partOf"===t){const e=HV(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 ${_z.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(qV,"uuid","9f0b9f78-9b2e-481a-b766-2fbfd01f342c"),t(qV,"xmlParser",new mt({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 XV=qV;const YV=class e extends se{constructor(s){super(s),t(this,"enabled",!0),s.add(e.uuid,this)}static distanceFromPointToLine(e,t,s,i=!1){const r=new o.Line3,n=new o.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(Lr);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(YV,"uuid","267ca032-672f-4cb0-afa9-d24e904f39d6");let ZV=YV;const QV=(e,t,s)=>{const i=new o.Vector3(-t.z,0,t.x),r=new o.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]},KV=(e,t,s)=>{const i=new o.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,a=e.x-t.x*s-i.x*s*.4,l=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,a,e.y,l,r,e.y,n,a,e.y,l]},JV=(e,t,s)=>{const i=new o.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,a=e.x-t.x*s-i.x*s*.4,l=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,a,e.y,l]},ek=()=>[],tk=(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},sk=(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},ik=(e,t,s)=>{const i=new o.Vector3(-t.z,0,t.x),r=.4*s,n=e.clone().addScaledVector(t,r).addScaledVector(i,r),a=e.clone().addScaledVector(t,r).addScaledVector(i,-r),l=e.clone().addScaledVector(t,-r).addScaledVector(i,-r),h=e.clone().addScaledVector(t,-r).addScaledVector(i,r);return[n.x,n.y,n.z,a.x,a.y,a.z,l.x,l.y,l.z,n.x,n.y,n.z,l.x,l.y,l.z,h.x,h.y,h.z]},rk=(e,t,s)=>{const i=new o.Vector3(-t.z,0,t.x),r=e.clone().addScaledVector(t,-s),n=r.clone().addScaledVector(i,.4*s),a=r.clone().addScaledVector(i,.4*-s);return[e.x,e.y,e.z,n.x,n.y,n.z,a.x,a.y,a.z]};class nk extends s.DataMap{getBySystem(e){const t=new Map;for(const[s,i]of this)i.system===e&&t.set(s,i.data);return t}}class ok extends s.DataMap{constructor(e){super(),t(this,"_container"),this._container=e,this.deleteGuard=e=>"0"!==e,this.set("0",{name:"0",visible:!0,material:new o.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 o.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 ak=class e extends o.Group{constructor(s){super(),t(this,"_viewport"),t(this,"_border"),t(this,"_handles",[]),t(this,"_raycaster",new o.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 o.LineBasicMaterial({color:e._BORDER_COLOR,depthTest:!1});const i=new o.BufferGeometry;i.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._border=new o.LineSegments(i,this._borderMat),this._border.renderOrder=999,this._border.frustumCulled=!1,this._border.userData.isDimension=!0,this.add(this._border),this._normalMat=new o.MeshBasicMaterial({color:e._BORDER_COLOR}),this._hoverMat=new o.MeshBasicMaterial({color:e._BORDER_HOVER_COLOR});const r=new o.SphereGeometry(.05,8,6);for(const t of e._HANDLE_DEFS){const e=new o.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 o.Vector3(0,1,0).transformDirection(this.matrixWorld),s=(new o.Vector3).setFromMatrixPosition(this.matrixWorld),i=(new o.Plane).setFromNormalAndCoplanarPoint(t,s),r=new o.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(ak,"_BORDER_COLOR",22015),t(ak,"_BORDER_HOVER_COLOR",16746496),t(ak,"_LINE_THRESHOLD",.06),t(ak,"_HANDLE_DEFS",[{constraints:["left","top"]},{constraints:["right","top"]},{constraints:["right","bottom"]},{constraints:["left","bottom"]},{constraints:["top"]},{constraints:["right"]},{constraints:["bottom"]},{constraints:["left"]}]);let lk=ak;class hk{constructor(e){t(this,"uuid",o.MathUtils.generateUUID()),t(this,"name"),t(this,"camera"),t(this,"onDisposed",new J),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 o.OrthographicCamera(this._left,this._right,this._top,this._bottom,.1,30),this.camera.up.set(0,0,-1),this.camera.position.set(0,10,0),this.camera.lookAt(0,0,0),this.camera.layers.set(1)}get left(){return this._left}set left(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 lk(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 o.Vector3(this._left,0,-this._top),t=new o.Vector3(this._right,0,-this._bottom);return new o.Box3(e,t)}get size(){const e=new o.Vector3;return this.bbox.getSize(e),new o.Vector2(1e3*e.x,1e3*e.z)}get localXAxis(){return new o.Vector3(1,0,0)}get localYAxis(){return new o.Vector3(0,0,-1)}get normal(){return new o.Vector3(0,1,0)}setContainer(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 o.Line3(t[0],t[1])}const a=this.getPlaneIntersections(e);return 0===a.length?null:r?new o.Line3(s,a[0]):new o.Line3(a[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 o.Plane(new o.Vector3(1,0,0),-e.min.x),new o.Plane(new o.Vector3(-1,0,0),e.max.x),new o.Plane(new o.Vector3(0,0,1),-e.min.z),new o.Plane(new o.Vector3(0,0,-1),e.max.z)]}getPlaneIntersections(e){const t=[];for(const s of this.bboxPlanes){const i=new o.Vector3;s.intersectLine(e,i)&&this.bbox.containsPoint(i)&&t.push(i)}return t}}class uk extends s.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 hk(e);return this._container.add(t.camera),t.setContainer(this._container),this.set(t.uuid,t),t}}const ck=class e extends o.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 o.Object3D),t(this,"widthHandle",new o.Object3D),t(this,"heightHandle",new o.Object3D),this._drawing=s,this._frameMat=new o.LineBasicMaterial({color:e._FRAME_COLOR,depthTest:!1}),this._depthMat=new o.LineBasicMaterial({color:e._DEPTH_COLOR,depthTest:!1,transparent:!0,opacity:.4}),this._planeMat=new o.MeshBasicMaterial({color:e._FRAME_COLOR,transparent:!0,opacity:.07,side:o.DoubleSide,depthTest:!1});const i=()=>{const e=new o.BufferGeometry;return e.setAttribute("position",new o.BufferAttribute(new Float32Array(12),3)),e.setIndex([0,1,2,0,2,3]),e};this._topPlane=new o.Mesh(i(),this._planeMat),this._topPlane.renderOrder=998,this._topPlane.frustumCulled=!1,this._topPlane.userData.isDimension=!0,this._bottomPlane=new o.Mesh(i(),this._planeMat),this._bottomPlane.renderOrder=998,this._bottomPlane.frustumCulled=!1,this._bottomPlane.userData.isDimension=!0;const r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._topFrame=new o.LineSegments(r,this._frameMat),this._topFrame.renderOrder=999,this._topFrame.frustumCulled=!1,this._topFrame.userData.isDimension=!0;const n=new o.BufferGeometry;n.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._pillars=new o.LineSegments(n,this._depthMat),this._pillars.renderOrder=999,this._pillars.frustumCulled=!1,this._pillars.userData.isDimension=!0;const a=new o.BufferGeometry;a.setAttribute("position",new o.BufferAttribute(new Float32Array(24),3)),this._bottomFrame=new o.LineSegments(a,this._depthMat),this._bottomFrame.renderOrder=999,this._bottomFrame.frustumCulled=!1,this._bottomFrame.userData.isDimension=!0,this.add(this._topPlane,this._bottomPlane),this.add(this._topFrame,this._pillars,this._bottomFrame),this.add(this.farHandle,this.widthHandle,this.heightHandle),this.farHandle.rotation.x=Math.PI,this.update()}update(){const 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(ck,"_FRAME_COLOR",22015),t(ck,"_DEPTH_COLOR",22015);let dk=ck;function pk(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 o.Vector3).subVectors(e[1],e[0]),i=(new o.Vector3).subVectors(e[2],e[0]);if((new o.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 o.Vector3).subVectors(t,e),r=(new o.Vector3).subVectors(s,e),n=i.clone().normalize(),a=(new o.Vector3).crossVectors(i,r).normalize(),l=(new o.Vector3).crossVectors(n,a).normalize();return(new o.Matrix4).makeBasis(n,a,l)},r=i(e[0],e[1],e[2]),n=i(t[0],t[1],t[2]).clone().multiply(r.clone().invert()),a=e[0].distanceTo(e[1]);if(a<1e-10)throw new Error("The first two drawing points are coincident — cannot compute scale.");const l=t[0].distanceTo(t[1])/a,h=e[0].clone().multiplyScalar(l).applyMatrix4(n),u=(new o.Vector3).subVectors(t[0],h),c=(new o.Quaternion).setFromRotationMatrix(n),d=new o.Matrix4;return d.compose(u,c,new o.Vector3(l,l,l)),d}class mk{constructor(e){t(this,"uuid",o.MathUtils.generateUUID()),t(this,"_raycaster",new o.Raycaster),t(this,"_components"),t(this,"world",null),t(this,"three",new o.Group),t(this,"annotations",new nk),t(this,"layers",new ok(this.three)),t(this,"activeLayer","0"),t(this,"far",10),t(this,"viewports",new uk(this.three)),t(this,"onDisposed",new J),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 o.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 a=null;if(r.object instanceof o.LineSegments&&void 0!==r.index){const e=r.object.geometry.attributes.position,t=r.index,s=new o.Vector3(e.getX(t),e.getY(t),e.getZ(t)),i=new o.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),a=new o.Line3(s,i)}return{point:n,object:r.object,viewport:t,line:a}}alignTo(e,t){pk(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 o.Matrix4).copy(t.three.matrixWorld).invert().multiply(e.matrixWorld),i=e.geometry.attributes.position,r=i.count,n=new Float32Array(3*r),a=new o.Vector3;for(let e=0;e<r;e++)a.fromBufferAttribute(i,e).applyMatrix4(s),n[3*e]=a.x,n[3*e+1]=0,n[3*e+2]=a.z;const l=new o.BufferGeometry;return l.setAttribute("position",new o.BufferAttribute(n,3)),new o.LineSegments(l)}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 o.LineDashedMaterial&&e.computeLineDistances(),e.geometry.computeBoundsTree({strategy:0,indirect:!0,type:Mr}),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(kO),i=s.projectionDirection.clone(),r=s.nearPlane,n=s.farPlane;try{this.three.updateWorldMatrix(!0,!1);const i=new o.Vector3(0,-1,0).transformDirection(this.three.matrixWorld).normalize();s.projectionDirection.copy(i);const r=(new o.Matrix4).makeRotationFromQuaternion((new o.Quaternion).setFromUnitVectors(i,new o.Vector3(0,-1,0))),n=(new o.Vector3).setFromMatrixPosition(this.three.matrixWorld).applyMatrix4(r).y;s.farPlane=n,s.nearPlane=n-this.far;const a=await s.get(e,this.world,{onProgress:t.onProgress}),l=e=>mk.toDrawingSpace(new o.LineSegments(e),this);this.addProjectionLines(l(a.visible),t.layers.visible),this.addProjectionLines(l(a.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(ae).destroy(this.three),this.onDisposed.trigger(),this.onDisposed.reset()}}const fk={m:{factor:1,suffix:"m"},cm:{factor:100,suffix:"cm"},mm:{factor:1e3,suffix:"mm"},ft:{factor:3.28084,suffix:"ft"},in:{factor:39.3701,suffix:"in"}};class gk{constructor(e){t(this,"styles",new s.DataMap),t(this,"activeStyle","default"),t(this,"onCommit",new J),t(this,"onUpdate",new J),t(this,"onDelete",new J),t(this,"onDisposed",new J),t(this,"_knownDrawings",new Set),t(this,"_previewMaterial",new o.LineBasicMaterial({color:16737894,depthTest:!1})),t(this,"_previewObject",null),t(this,"_previewDrawing",null),t(this,"_materialCache",new s.DataMap),t(this,"_meshMaterialCache",new s.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(tU),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 s.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:o.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 o.Raycaster;s.ray.copy(e),s.params.Line={threshold:t},s.params.LineSegments={threshold:t};const i=o.Line.prototype.raycast;let r=null,n=1/0;for(const e of this._knownDrawings)for(const[t,a]of e.annotations){if(a.system!==this)continue;const e=a.three;e.updateWorldMatrix(!0,!0),e.traverse(a=>{if(a===e)return;const l=[];if(a instanceof o.LineSegments&&a.userData.isDimension)i.call(a,s,l),l.length>0&&l[0].distance<n&&(n=l[0].distance,r=t);else if(a instanceof o.Mesh){const e=(new o.Box3).setFromObject(a),i=new o.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 o.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 o.MeshBasicMaterial({color:this._resolveStyle(e).color,side:o.DoubleSide});return this._meshMaterialCache.set(e,s),s}_disposeGroup(e){if(e.removeFromParent(),this._ownsChildGeometry)e.traverse(e=>{e.geometry instanceof o.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 o.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 yk(e,t){const s=e[0],i=e[e.length-1],r=(new o.Vector3).subVectors(i,s);if(r.lengthSq()<1e-10)return 0;r.normalize();const n=new o.Vector3(-r.z,0,r.x);return t.clone().sub(s).dot(n)}function bk(e,t){const s=[];for(let i=0;i<e.length-1;i++)s.push({uuid:o.MathUtils.generateUUID(),pointA:e[i].clone(),pointB:e[i+1].clone(),offset:t,style:""});return s}function xk(e,t){switch(e.kind){case"awaitingFirstPoint":if("CLICK"===t.type){if(!t.line)return e;const s=(new o.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 o.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 o.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),a=[...e.points,n];return{...e,points:a,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=yk(e.points,t.point);return{kind:"committed",dimensions:bk(e.points,s)}}return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e;case"committed":return"ESCAPE"===t.type?{kind:"awaitingFirstPoint"}:e}var s,i}function _k(e){const{pointA:t,pointB:s,offset:i}=e,r=(new o.Vector3).subVectors(s,t),n=new o.Vector3(-r.z,0,r.x).normalize(),a=t.clone().addScaledVector(n,i),l=s.clone().addScaledVector(n,i),h=(new o.Vector3).subVectors(l,a).normalize();return[{tip:a,dir:h},{tip:l,dir:h.clone().negate()}]}function wk(e,t){const{pointA:s,pointB:i,offset:r}=e,n=(new o.Vector3).subVectors(i,s),a=new o.Vector3(-n.z,0,n.x).normalize(),l=r>=0?1:-1,h=Math.abs(r),u=s.clone().addScaledVector(a,t.extensionGap*l),c=s.clone().addScaledVector(a,(h+t.extensionOvershoot)*l),d=i.clone().addScaledVector(a,t.extensionGap*l),p=i.clone().addScaledVector(a,(h+t.extensionOvershoot)*l),m=s.clone().addScaledVector(a,r),f=i.clone().addScaledVector(a,r),g=(new o.Vector3).subVectors(f,m).normalize(),y=t.lineTick(m,g,t.tickSize),b=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,...b]}function vk(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=yk(t,s),n=[];for(let e=0;e<t.length-1;e++)n.push(...wk({pointA:t[e],pointB:t[e+1],offset:r},i));return n}class Tk extends gk{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingFirstPoint"}),t(this,"onMachineStateChanged",new J),this.styles.set("default",{lineTick:QV,tickSize:.4,extensionGap:.05,extensionOvershoot:.2,color:0,textOffset:.4,fontSize:.45})}pickHandle(e,t,s=.1){const i=(new o.Matrix4).copy(e.three.matrixWorld).invert(),r=t.origin.clone().applyMatrix4(i),n=t.direction.clone().transformDirection(i).normalize(),a=new o.Ray(r,n),l=new o.Plane(new o.Vector3(0,1,0),0),h=a.intersectPlane(l,new o.Vector3);if(!h)return null;let u=null,c=s;for(const[t,s]of e.annotations.getBySystem(this)){const e=(new o.Vector3).subVectors(s.pointB,s.pointA),i=new o.Vector3(-e.z,0,e.x).normalize(),r=(new o.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=xk(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 o.Group,i=wk(e,t),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3));const n=new o.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 _k(e)){const n=t.meshTick(i,r,t.tickSize),a=new o.BufferGeometry;a.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const l=new o.Mesh(a,this._getMeshMaterial(e.style));l.layers.set(1),l.userData.isMeshTick=!0,s.add(l)}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=vk(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 o.BufferGeometry;e.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3)),this._previewObject=new o.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 Sk=Math.PI/180;function Mk(e,t,s,i){const r=function(e,t,s){const i=(new o.Vector3).subVectors(e,t).normalize(),r=(new o.Vector3).subVectors(s,t).normalize();return(new o.Vector3).addVectors(i,r).normalize()}(e,t,s);return(new o.Vector3).subVectors(i,t).setY(0).dot(r)}function Ak(e,t,s,i){return Mk(e,t,s,i)<0}function Nk(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 o.Vector3).subVectors(e.line1.end,e.line1.start).normalize(),i=(new o.Vector3).subVectors(t.line.end,t.line.start).normalize();if(Math.abs(s.dot(i))>Math.cos(Sk))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 o.Vector3).subVectors(s,e),a=(n.x*i.z-n.z*i.x)/r;return new o.Vector3(e.x+t.x*a,0,e.z+t.z*a)}(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=Ak(e.pointA,e.vertex,e.pointB,t.point);return{...e,cursor:t.point.clone(),flipped:s}}if("CLICK"===t.type){const s=Ak(e.pointA,e.vertex,e.pointB,t.point),i=Math.max(.05,Math.abs(Mk(e.pointA,e.vertex,e.pointB,t.point)));return{kind:"committed",dimension:{uuid:o.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 Ek(e){const t=(new o.Vector3).subVectors(e.pointA,e.vertex).normalize(),s=(new o.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 o.Vector3(e.vertex.x+Math.cos(i)*e.arcRadius,0,e.vertex.z+Math.sin(i)*e.arcRadius),a=i+r,l=new o.Vector3(e.vertex.x+Math.cos(a)*e.arcRadius,0,e.vertex.z+Math.sin(a)*e.arcRadius),h=Math.sign(r);return[{tip:n,dir:new o.Vector3(-Math.sin(i)*h,0,Math.cos(i)*h)},{tip:l,dir:new o.Vector3(Math.sin(a)*h,0,-Math.cos(a)*h)}]}function Ck(e){const t=(new o.Vector3).subVectors(e.pointA,e.vertex).normalize(),s=(new o.Vector3).subVectors(e.pointB,e.vertex).normalize(),i=Math.acos(o.MathUtils.clamp(t.dot(s),-1,1));return e.flipped?2*Math.PI-i:i}function Rk(e){const t=(new o.Vector3).subVectors(e.pointA,e.vertex).normalize(),s=(new o.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 Pk(e,t,s,i,r,n=!1){const a=Math.atan2(t.z,t.x);let l=Math.atan2(s.z,s.x)-a;for(;l>Math.PI;)l-=2*Math.PI;for(;l<-Math.PI;)l+=2*Math.PI;n&&(l-=2*Math.sign(l)*Math.PI);const h=[];for(let t=0;t<8;t++){const s=a+l*(t/8),r=a+l*((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 o.Vector3(e.x+Math.cos(a)*i,0,e.z+Math.sin(a)*i),c=new o.Vector3(e.x+Math.cos(a+l)*i,0,e.z+Math.sin(a+l)*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(l),f=new o.Vector3(-Math.sin(a)*m,0,Math.cos(a)*m),g=a+l,y=new o.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 Bk(e,t){const s=(new o.Vector3).subVectors(e.pointA,e.vertex).normalize(),i=(new o.Vector3).subVectors(e.pointB,e.vertex).normalize();return Pk(e.vertex,s,i,e.arcRadius,t,e.flipped??!1)}function Ik(e,t,s,i,r,n=!1){if(!i)return[];const a=Math.max(.05,(new o.Vector3).subVectors(i,t).setY(0).length());return Pk(t,(new o.Vector3).subVectors(e,t).normalize(),(new o.Vector3).subVectors(s,t).normalize(),a,r,n)}class Dk extends gk{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingFirstLine"}),t(this,"onMachineStateChanged",new J),t(this,"_secondLinePreviewObject",null),this.styles.set("default",{lineTick:QV,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=Nk(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 o.Group,i=Bk(e,t),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3));const n=new o.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 Ek(e)){const n=t.meshTick(i,r,t.tickSize),a=new o.BufferGeometry;a.setAttribute("position",new o.BufferAttribute(new Float32Array(n),3));const l=new o.Mesh(a,this._getMeshMaterial(e.style));l.layers.set(1),l.userData.isMeshTick=!0,s.add(l)}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=Ik(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 o.BufferGeometry;e.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3)),this._previewObject=new o.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 o.Vector3).subVectors(s.line1.end,s.line1.start).normalize();if(!t)return void this._clearSecondLinePreview();const r=(new o.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,a=s.z-e.z,l=(n*i.z-a*i.x)/r;return new o.Vector3(e.x+l*t.x,0,e.z+l*t.z)}(s.line1.start,i,t.start,r);if(!n)return void this._clearSecondLinePreview();const a=e.clone(),l=(new o.Vector3).subVectors(a,n).setY(0);if(l.length()<.01)return void this._clearSecondLinePreview();const h=(new o.Vector3).subVectors(s.pointA,n).normalize(),u=l.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),a.distanceTo(n))),f=new o.Vector3(n.x+Math.cos(p)*m,0,n.z+Math.sin(p)*m),g=this._resolveStyle(this.activeStyle),y=Ik(s.pointA,n,a,f,g);if(0===y.length)return void this._clearSecondLinePreview();const b=y.length/3;if(!this._secondLinePreviewObject||this._secondLinePreviewObject.geometry.attributes.position.count!==b){this._clearSecondLinePreview();const e=new o.BufferGeometry;e.setAttribute("position",new o.BufferAttribute(new Float32Array(y),3)),this._secondLinePreviewObject=new o.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 Lk(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),a=Math.round(n/(Math.PI/4))*(Math.PI/4);return new o.Vector3(e.x+Math.cos(a)*r,0,e.z+Math.sin(a)*r)}function Fk(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:Lk(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",arrowTip:e.arrowTip,elbow:e.elbow,extensionEnd:Lk(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:o.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 Ok(e,t,s,i){return"curved"===i.leaderShape?function(e,t,s,i){const r=new o.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 o.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 o.Vector3).subVectors(e,t);s.lengthSq()>1e-10&&r.push(...i.lineTick(e,s.normalize(),i.tickSize))}return r}(e,t,s,i)}function zk(e,t){return Ok(e.arrowTip,e.elbow,e.extensionEnd,t)}function Vk(e,t,s,i,r){return i?Ok(t,"placingElbow"===e?i:s,i,r):[]}class kk extends gk{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingArrowTip"}),t(this,"onMachineStateChanged",new J),t(this,"_previewMeshMaterial",new o.MeshBasicMaterial({color:16737894,side:o.DoubleSide,depthTest:!1})),t(this,"_previewMeshObject",null),this.styles.set("default",{tickSize:.4,color:0,textOffset:.1,fontSize:.45,lineTick:JV})}pickHandle(e,t,s=.1){const i=(new o.Matrix4).copy(e.three.matrixWorld).invert(),r=t.origin.clone().applyMatrix4(i),n=t.direction.clone().transformDirection(i).normalize(),a=new o.Ray(r,n),l=new o.Plane(new o.Vector3(0,1,0),0),h=a.intersectPlane(l,new o.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=Fk(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 o.Group,i=zk(e,t),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3));const n=new o.LineSegments(r,this._getMaterial(e.style));if(n.layers.set(1),n.userData.isDimension=!0,s.add(n),t.meshTick){const i=(new o.Vector3).subVectors(e.arrowTip,e.elbow);if(i.lengthSq()>1e-10){i.normalize();const r=t.meshTick(e.arrowTip,i,t.tickSize),n=new o.BufferGeometry;n.setAttribute("position",new o.BufferAttribute(new Float32Array(r),3));const a=new o.Mesh(n,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isMeshArrow=!0,s.add(a)}}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?Vk("placingElbow",e.arrowTip,null,e.cursor,t):Vk("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 o.BufferGeometry;e.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3)),this._previewObject=new o.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 o.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 o.BufferGeometry;e.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3)),this._previewMeshObject=new o.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 Uk extends gk{constructor(e){super(e),t(this,"enabled",!0),t(this,"_ownsChildGeometry",!1),t(this,"definitions",new s.DataMap),this.styles.set("default",{color:0,textOffset:0,fontSize:0})}pickHandle(e,t,s){return null}pick(e,t=.05){const s=new o.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 o.LineSegments))return;const a=[];n.raycast(s,a),a.length>0&&a[0].distance<r&&(r=a[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 o.Group;if(s.lines){const t=new o.LineSegments(s.lines,this._getMaterial(e.style));t.layers.set(1),t.userData.isDimension=!0,i.add(t)}if(s.mesh){const t=new o.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 Gk(e,t){const{position:s,direction:i}=e,{length:r}=t,n=new o.Vector3(s.x+i.x*r,0,s.z+i.z*r),a=new o.Vector3(i.x,0,i.z),l=t.lineTick(n,a,t.tickSize),h=[s.x,0,s.z,n.x,0,n.z];return new Float32Array([...h,...l])}function jk(e,t){return new o.Vector3(e.position.x+e.direction.x*t,0,e.position.z+e.direction.z*t)}function $k(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 Wk extends gk{constructor(e){super(e),t(this,"enabled",!0),this.styles.set("default",{lineTick:ek,meshTick:rk,tickSize:.4,length:3,color:0,textOffset:.1,fontSize:.45,format:"percentage"})}pickHandle(e,t,s){return null}_buildGroup(e,t){const s=new o.Group,i=Gk(e,t),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(i,3));const n=new o.LineSegments(r,this._getMaterial(e.style));if(n.layers.set(1),n.userData.isDimension=!0,s.add(n),t.meshTick){const i=jk(e,t.length),r=t.meshTick(i,e.direction,t.tickSize),n=new o.BufferGeometry;n.setAttribute("position",new o.BufferAttribute(new Float32Array(r),3));const a=new o.Mesh(n,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isDimension=!0,s.add(a)}return s}}function Hk(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),a=Math.round(n/(Math.PI/4))*(Math.PI/4);return new o.Vector3(e.x+Math.cos(a)*r,0,e.z+Math.sin(a)*r)}function qk(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:Hk(e.elbow,t.point)}:"CLICK"===t.type?{kind:"enteringText",center:e.center,halfW:e.halfW,halfH:e.halfH,elbow:e.elbow,extensionEnd:Hk(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:o.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 Xk(e,t){const s=[];s.push(...t.enclosure.buildGeometry(e.center,e.halfW,e.halfH));const i=(new o.Vector3).subVectors(e.elbow,e.center),r=i.lengthSq()>1e-10?i.clone().normalize():new o.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 o.Vector3).subVectors(e.extensionEnd,e.elbow);i.lengthSq()>1e-10&&s.push(...t.lineTick(e.extensionEnd,i.normalize(),t.tickSize))}return s}function Yk(e,t,s,i,r,n,a){const l="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(l<1e-10||h<1e-10)return[];const u=[];if(u.push(...a.enclosure.buildGeometry(t,l,h)),"awaitingRadius"===e)return u;const c="awaitingElbow"===e?n:r;if(!c)return u;const d=(new o.Vector3).subVectors(c,t),p=d.lengthSq()>1e-10?d.clone().normalize():new o.Vector3(1,0,0),m=a.enclosure.getAttachmentPoint(t,l,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 Zk={buildGeometry(e,t,s){const i=.25*Math.min(t,s),r=new o.Vector3(e.x-t,0,e.z-s),n=new o.Vector3(e.x+t,0,e.z-s),a=new o.Vector3(e.x+t,0,e.z+s),l=new o.Vector3(e.x-t,0,e.z+s),h=[[r,n,new o.Vector3(0,0,-1)],[n,a,new o.Vector3(1,0,0)],[a,l,new o.Vector3(0,0,1)],[l,r,new o.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))),a=r/n,l=a/2,h=(new o.Vector3).subVectors(t,e).normalize();for(let t=0;t<n;t++){const i=e.clone().addScaledVector(h,(t+.5)*a),r=e.clone().addScaledVector(h,t*a),n=(new o.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*l*Math.sin(t),a=i.z+n.z*Math.cos(t)+s.z*l*Math.sin(t),h=new o.Vector3(r,0,a);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,a=Math.min(r,n);return new o.Vector3(e.x+i.x*a,0,e.z+i.z*a)}},Qk={buildGeometry(e,t,s){const i=new o.Vector3(e.x-t,0,e.z-s),r=new o.Vector3(e.x+t,0,e.z-s),n=new o.Vector3(e.x+t,0,e.z+s),a=new o.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,a.x,0,a.z,a.x,0,a.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,a=Math.min(r,n);return new o.Vector3(e.x+i.x*a,0,e.z+i.z*a)}},Kk={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,a=Math.sqrt(r*r+n*n),l=a>1e-10?1/a:t;return new o.Vector3(e.x+i.x*l,0,e.z+i.z*l)}};class Jk extends gk{constructor(e){super(e),t(this,"enabled",!0),t(this,"machineState",{kind:"awaitingCenter"}),t(this,"onMachineStateChanged",new J),this.styles.set("default",{enclosure:Zk,lineTick:JV,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=qk(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 o.Group,i=Xk(e,t),r=new o.BufferGeometry;r.setAttribute("position",new o.BufferAttribute(new Float32Array(i),3));const n=new o.LineSegments(r,this._getMaterial(e.style));if(n.layers.set(1),n.userData.isDimension=!0,s.add(n),t.meshTick){const i=(new o.Vector3).subVectors(e.extensionEnd,e.elbow);if(i.lengthSq()>1e-10){i.normalize();const r=t.meshTick(e.extensionEnd,i,t.tickSize),n=new o.BufferGeometry;n.setAttribute("position",new o.BufferAttribute(new Float32Array(r),3));const a=new o.Mesh(n,this._getMeshMaterial(e.style));a.layers.set(1),a.userData.isMeshArrow=!0,s.add(a)}}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 Yk("awaitingRadius",e.center,0,0,null,e.cursor,t);case"awaitingElbow":return Yk("awaitingElbow",e.center,e.halfW,e.halfH,null,e.cursor,t);case"awaitingExtension":return Yk("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 o.BufferGeometry;e.setAttribute("position",new o.BufferAttribute(new Float32Array(s),3)),this._previewObject=new o.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 eU=class e extends se{constructor(i){super(i),t(this,"enabled",!0),t(this,"list",new s.DataMap),t(this,"systems",new s.DataMap),t(this,"onDisposed",new J),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 mk(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 Mz&&(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(eU,"uuid","5c7d3b9a-4e8f-4a2b-9c1d-0e3f2a5b7c8d");let tU=eU;const sU=[[16711680,1],[16776960,2],[65280,3],[65535,4],[255,5],[16711935,6],[16777215,7],[0,7]];function iU(e){const t=e>>16&255,s=e>>8&255,i=255&e;let r=7,n=1/0;for(const[e,o]of sU){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 rU{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 nU{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 rU,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(tU).systems.get(Uk),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=iU(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 o.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,iU(r),r)})}_writeLinearAnnotations(e,t){var s;const i=this._components.get(tU).systems.get(Tk);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),a=iU(n.color),l=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(l))?void 0:s.visible))continue;const h=wk(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,l,a,n.color),n.meshTick)for(const{tip:t,dir:s}of _k(r))this._writeMeshTriangles(e,n.meshTick(t,s,n.tickSize),l,a,n.color);const u=(new o.Vector3).subVectors(r.pointB,r.pointA),c=new o.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,l,a,this._textAngle(u.x,u.z),1,2,n.color)}}_writeAngleAnnotations(e,t){var s;const i=this._components.get(tU).systems.get(Dk);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),a=iU(n.color),l=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(l))?void 0:s.visible))continue;const h=Bk(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,l,a,n.color),n.meshTick)for(const{tip:t,dir:s}of Ek(r))this._writeMeshTriangles(e,n.meshTick(t,s,n.tickSize),l,a,n.color);const u=Rk(r),c=r.arcRadius+n.textOffset,d=r.vertex.x+Math.cos(u)*c,p=r.vertex.z+Math.sin(u)*c,m=o.MathUtils.radToDeg(Ck(r));this._writeText(e,`${m.toFixed(this.precision)}°`,d,p,n.fontSize,l,a,0,1,0,n.color)}}_writeLeaderAnnotations(e,t){var s;const i=this._components.get(tU).systems.get(kk);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),a=iU(n.color),l=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(l))?void 0:s.visible))continue;const h=zk(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,l,a,n.color),n.meshTick){const t=(new o.Vector3).subVectors(r.arrowTip,r.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,n.meshTick(r.arrowTip,t.normalize(),n.tickSize),l,a,n.color)}const u=(new o.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,l,a,0,c,2,n.color)}}_writeSlopeAnnotations(e,t){var s;const i=this._components.get(tU).systems.get(Wk);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),a=iU(n.color),l=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(l))?void 0:s.visible))continue;const h=Gk(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,l,a,n.color),n.meshTick){const t=jk(r,n.length);this._writeMeshTriangles(e,n.meshTick(t,r.direction,n.tickSize),l,a,n.color)}const u=new o.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 o.Vector3(-r.direction.z,0,r.direction.x),n.textOffset+n.fontSize);this._writeText(e,$k(r.slope,n.format),c.x,c.z,n.fontSize,l,a,this._textAngle(r.direction.x,r.direction.z),1,0,n.color)}}_writeCalloutAnnotations(e,t){var s;const i=this._components.get(tU).systems.get(Jk);if(i)for(const[,r]of t.annotations.getBySystem(i)){const n=i.styles.get(r.style)??i.styles.get("default"),a=iU(n.color),l=this._annotationLayers.get(r.uuid)??"0";if(!1===(null==(s=t.layers.get(l))?void 0:s.visible))continue;const h=Xk(r,n);if(!this._fullyInViewport(this._bboxFromPositions(h)))continue;if(this._writePairsAsLines(e,h,l,a,n.color),n.meshTick){const t=(new o.Vector3).subVectors(r.extensionEnd,r.elbow);t.lengthSq()>1e-10&&this._writeMeshTriangles(e,n.meshTick(r.extensionEnd,t.normalize(),n.tickSize),l,a,n.color)}const u=(new o.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,l,a,0,c,2,n.color)}}_writeBlockInsertions(e,t){const s=this._components.get(tU).systems.get(Uk);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=iU(t.color),n=-o.MathUtils.radToDeg(i.rotation),a=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,a).n(42,a).n(43,a).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 a=this._clipSegment(new o.Vector3(n.getX(t),0,n.getZ(t)),new o.Vector3(n.getX(t+1),0,n.getZ(t+1)));a&&this._writeLine(e,a.start.x,a.start.z,a.end.x,a.end.z,s,i,r)}}_writePairsAsLines(e,t,s,i=7,r){for(let n=0;n+5<t.length;n+=6){const a=this._clipSegment(new o.Vector3(t[n],0,t[n+2]),new o.Vector3(t[n+3],0,t[n+5]));a&&this._writeLine(e,a.start.x,a.start.z,a.end.x,a.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 o.Line3(e,t)):new o.Line3(e,t)}_inViewport(e,t){return!this._viewport||this._viewport.bbox.containsPoint(new o.Vector3(e,0,t))}_bboxFromPositions(e){const t=new o.Box3;for(let s=0;s+2<e.length;s+=3)t.expandByPoint(new o.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),o.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(tU).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:iU,textAngle:(e,t)=>this._textAngle(e,t)}}}const oU=class e extends se{constructor(s){super(s),t(this,"enabled",!0),t(this,"exporter",new nU(this.components)),s.add(e.uuid,this)}};t(oU,"uuid","e9a2c3d4-5f67-4b89-a012-1c3d5e7f9b2a");let aU=oU;export{Dk as AngleAnnotations,gk as AnnotationSystem,KV as ArrowTick,ee as AsyncEvent,Oz as BCFTopics,Lz as BCFTopicsConfigManager,te as Base,re as BaseCamera,ne as BaseRenderer,le as BaseScene,ie as BaseWorldItem,Uk as BlockAnnotations,qO as BoundingBoxer,Jk as CalloutAnnotations,Kk as CircleEnclosure,KO as Classifier,_V as Clipper,Zk as CloudEnclosure,Pz as Comment,se as Component,_z as Components,Dt as ConfigManager,Bt as Configurator,Rt as ControlsUtils,Ct as DataMap,he as DataSet,QV as DiagonalTick,ae as Disposer,tk as DotTick,nk as DrawingAnnotations,ok as DrawingLayers,gk as DrawingSystem,hk as DrawingViewport,lk as DrawingViewportHelper,uk as DrawingViewports,nU as DxfExporter,aU as DxfManager,kO as EdgeProjector,J as Event,Pt as EventManager,JO as FastModelPicker,tz as FastModelPickers,rk as FilledArrowTick,sk as FilledCircleTick,ik as FilledSquareTick,XO as FinderQuery,wz as FirstPersonMode,Lr as FragmentsManager,bz as Grids,WO as Hider,IV as IDSAttribute,DV as IDSClassification,LV as IDSEntity,PV as IDSFacet,OV as IDSMaterial,zV as IDSPartOf,FV as IDSProperty,VV as IDSSpecification,XV as IDSSpecifications,UO as IfcFragmentSettings,jO as IfcLoader,ZO as ItemsFinder,kk as LeaderAnnotations,Tk as LinearAnnotations,ZV as MeasurementUtils,Et as ModelIdMapUtils,Lt as Mouse,ek as NoTick,JV as OpenArrowTick,vz as OrbitMode,Mz as OrthoPerspectiveCamera,Tz as PlanMode,Sz as ProjectionManager,rz as Raycasters,Qk as RectEnclosure,uz as RendererMode,RV as ShadowedScene,dz as SimpleCamera,gz as SimpleGrid,fz as SimpleGridConfigManager,yV as SimplePlane,sz as SimpleRaycaster,cz as SimpleRenderer,hz as SimpleScene,lz as SimpleSceneConfigManager,nz as SimpleWorld,Wk as SlopeAnnotations,mk as TechnicalDrawing,dk as TechnicalDrawingHelper,tU as TechnicalDrawings,Iz as Topic,ce as UUID,fk as Units,Nt as VertexPicker,MV as View,wV as Viewpoint,SV as Viewpoints,NV as Views,mz as Worlds,At as XML,Nk as angleDimensionMachine,Bk as buildAnglePositions,Ik as buildAnglePreviewPositions,Xk as buildCalloutPositions,Yk as buildCalloutPreviewPositions,wk as buildDimensionPositions,bk as buildDimensions,zk as buildLeaderPositions,Vk as buildLeaderPreviewPositions,vk as buildPreviewPositions,Gk as buildSlopePositions,qk as calloutAnnotationMachine,pk as computeAlignmentMatrix,Ck as computeAngle,Rk as computeBisectorAngle,yk as computeOffset,Dz as extensionsImporter,$k as formatSlope,Ek as getAngleTickEndpoints,_k as getDimensionTickEndpoints,jk as getSlopeTip,Fk as leaderAnnotationMachine,xk as linearDimensionMachine};